From ee065df7578106071d850c271c53109949b5128a Mon Sep 17 00:00:00 2001 From: BED <73585863+yeetbot90@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:39:07 +0100 Subject: [PATCH 1/3] Answer chad.dll XDsp calls so a missing DSP is not fatal. Connect, activate, submit, deactivate and disconnect succeed. Each command finishes in the call, and an output block inside the registered buffer is silence. --- HANDOFF.md | 6 + crates/xcl/data/stubdb.toml | 2 +- crates/xcl/src/hle/acphal.rs | 4 +- crates/xcl/src/hle/mod.rs | 7 + crates/xcl/src/hle/xdsp.rs | 311 +++++++++++++++++++++++++++++++++++ 5 files changed, 327 insertions(+), 3 deletions(-) create mode 100644 crates/xcl/src/hle/xdsp.rs diff --git a/HANDOFF.md b/HANDOFF.md index 8a7dec9fc..3cd1ef683 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1736,6 +1736,12 @@ to an outside server at every crash (`hle/netoff.rs`: the title's WinHTTP / Wins RAM and VRAM, not broken down); ~4.5 GB of `VirtualAlloc` with PAGE_GRAPHICS_* protection is plain memory, so shaders get empty buffers and GPU writes / waits there are dropped; one list fails to Close; queue #35, list #131 / #132 / #139 and allocator #9 are stubs; MSAA layouts. +- `chad.dll` (`hle/xdsp.rs`): `XDspConnectWithMaximumStreamLimit` / `XDspActivate` / `XDspSubmitCommand` / + `XDspDeactivate` / `XDspDisconnect`. A title that treats `E_NOTIMPL` from the connect as fatal now gets a client; + commands complete in the call and the output block inside the registered buffer is silence. No convolution. + Checked with the unit tests and a local run (`XCL_NETWORK=0`): the connect that used to breakpoint the title + (128 streams, 1 channel, 30 s impulse, 384 KiB buffer) returns success and the title keeps compiling pipelines. + A later null write (`0xc0000005` at `game+0x2215c35`) is separate, during PSO creation. - XDefiant, Fortnite, Unicorn Overlord and Minecraft were **not** run after these changes (only the test suites). ## Next steps (priority) diff --git a/crates/xcl/data/stubdb.toml b/crates/xcl/data/stubdb.toml index e0df66b55..7961fd684 100644 --- a/crates/xcl/data/stubdb.toml +++ b/crates/xcl/data/stubdb.toml @@ -12,7 +12,7 @@ "d3d12_x.dll" = "E_NOTIMPL" "xg_xs.dll" = "E_NOTIMPL" "acphal.dll" = "E_NOTIMPL" -# the console's audio decoder and DSP: what XCL does not answer is not there +# the console's audio decoder, and any chad.dll export xdsp.rs does not implement "xapu.dll" = "E_NOTIMPL" "chad.dll" = "E_NOTIMPL" # console DirectStorage (DStorageGetFactory) and the Xbox One texture layout library: a fake S_OK diff --git a/crates/xcl/src/hle/acphal.rs b/crates/xcl/src/hle/acphal.rs index 1afaa3bc9..c52eb0032 100644 --- a/crates/xcl/src/hle/acphal.rs +++ b/crates/xcl/src/hle/acphal.rs @@ -14,8 +14,8 @@ //! `AcpHalCreate(&hal)` – an object whose vtable is Connect(commands, messages), Disconnect, //! SubmitCommand(type, id, frame, data, size), PopMessage(&message) -> bool, //! GetNumMessages, Release; messages {u32 type, u32, u64 value, u64 id}: 2 audio frame, -//! 0x10 command done (id), 0x80 disconnected. `chad.dll` (XDsp) is left to the stub database: -//! E_NOTIMPL, the processor's DSP is not there. +//! 0x10 command done (id), 0x80 disconnected. `chad.dll` (XDsp) is `hle::xdsp`: commands +//! finish immediately and their output block is silence. #![allow(non_snake_case)] diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index 96c3c2c13..7209ede82 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -23,6 +23,7 @@ pub mod netoff; pub mod opus; pub mod user; pub mod xaudio2; +pub mod xdsp; pub mod xma2; pub mod xg; pub mod xgameruntime; @@ -91,6 +92,8 @@ pub const XCRDAPI: &str = "xcrdapi.dll"; pub const MINUSERX: &str = "minuserx.dll"; /// the console's audio processor (APU memory, its channel, SHAPE contexts) and decoder (xapu) pub const ACPHAL: &str = "acphal.dll"; +/// the console's DSP (convolution / FFT blocks over a caller-owned buffer) +pub const CHAD: &str = "chad.dll"; /// controllers (`GameInputCreate`) pub const GAMEINPUT: &str = "gameinput.dll"; @@ -106,6 +109,7 @@ fn build(config: &Config) -> Registry { HleModule::new(XCRDAPI, dstorage::exports(), &[]), HleModule::new(XG, xg::exports(), &[]), HleModule::new(ACPHAL, acphal::exports(), &[]), + HleModule::new(CHAD, xdsp::exports(), &[]), HleModule::new(GAMEINPUT, gameinput::exports(), &[]), ]; let offline = netoff::enabled(); @@ -177,6 +181,8 @@ fn build(config: &Config) -> Registry { for p in ["acphal.dll", "xapu.dll"] { routes.push((p.into(), Route::Hle(ap))); } + let ch = idx(CHAD); + routes.push((CHAD.into(), Route::Hle(ch))); let gi = idx(GAMEINPUT); routes.push((GAMEINPUT.into(), Route::Hle(gi))); let c = idx(DXCOMPILER); @@ -241,6 +247,7 @@ mod tests { assert_eq!(name("xgameruntime.dll"), Some(XGAMERUNTIME)); assert_eq!(name("d3d12_xs.dll"), Some(D3D12X)); assert_eq!(name("xaudio2_9.dll"), Some(XAUDIO2)); + assert_eq!(name("chad.dll"), Some(CHAD)); assert_eq!(name("mfplat.dll"), Some(MFPLAT)); assert!(r.hle_for("kernel32.dll").unwrap().aliases_are_system()); assert!(!r.hle_for("xaudio2_9.dll").unwrap().aliases_are_system()); diff --git a/crates/xcl/src/hle/xdsp.rs b/crates/xcl/src/hle/xdsp.rs new file mode 100644 index 000000000..e1ed7ac9e --- /dev/null +++ b/crates/xcl/src/hle/xdsp.rs @@ -0,0 +1,311 @@ +//! The console DSP (`chad.dll`). +//! +//! A title registers one buffer, activates streams, and submits a block at a time. Nothing is +//! convolved or transformed here: connect succeeds, each command is finished in the call, and +//! the output block is silence when it lies inside the registered buffer. The title's mixer +//! then continues instead of treating a missing DSP as fatal. +//! +//! Calls, as titles make them: `XDspConnectWithMaximumStreamLimit(buffer, bytes, impulse +//! seconds, max streams, max channels, &handle)`, `XDspActivate(client, ¶ms, &status, +//! &stream)`, `XDspSubmitCommand(stream, &command, &sequence)`, `XDspDeactivate(stream)`, +//! `XDspDisconnect(client)`. `params` holds the block size at +8 and the channel count at +12. +//! `command` holds the output pointer at +16. `XDspStatus` is four 32-bit fields the title +//! polls: submitted sequence, processed sequence, first failed sequence, result. + +#![allow(non_snake_case)] + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicI32, AtomicU32, Ordering}; +use std::sync::Mutex; + +use crate::util::{HRESULT, E_INVALIDARG, E_OUTOFMEMORY, S_OK}; + +const CLIENT_MAGIC: u32 = 0x5844_5343; +const STREAM_MAGIC: u32 = 0x5844_5353; +/// frames a command may clear: a power of two in the range titles submit, and nothing larger +const MIN_FRAMES: u32 = 32; +const MAX_FRAMES: u32 = 8192; + +#[repr(C)] +struct Status { + last_submitted: AtomicU32, + last_processed: AtomicU32, + first_failed: AtomicU32, + result: AtomicI32, +} + +struct Client { + magic: u32, + base: usize, + len: u32, + streams: Mutex>, +} + +struct Stream { + magic: u32, + client: usize, + frames: u32, + channels: u32, + status: Status, +} + +struct World { + clients: HashMap>, + streams: HashMap>, +} + +static WORLD: std::sync::LazyLock> = + std::sync::LazyLock::new(|| Mutex::new(World { clients: HashMap::new(), streams: HashMap::new() })); + +fn u32_at(p: *const u8, off: usize) -> u32 { + unsafe { std::ptr::read_unaligned(p.add(off) as *const u32) } +} + +fn ptr_at(p: *const u8, off: usize) -> *mut f32 { + unsafe { std::ptr::read_unaligned(p.add(off) as *const *mut f32) } +} + +/// Bytes of one output block, or 0 when the size is not one we will write. +fn block_bytes(frames: u32, channels: u32) -> usize { + if !(MIN_FRAMES..=MAX_FRAMES).contains(&frames) || !frames.is_power_of_two() || !(1..=2).contains(&channels) { + return 0; + } + frames as usize * channels as usize * 4 +} + +fn silence(client: &Client, output: *mut f32, frames: u32, channels: u32) { + static WARNED: AtomicU32 = AtomicU32::new(0); + let n = block_bytes(frames, channels); + if output.is_null() || n == 0 { + return; + } + let start = output as usize; + let end = start.saturating_add(n); + let base = client.base; + let limit = base.saturating_add(client.len as usize); + if start >= base && end <= limit && start % 16 == 0 { + unsafe { std::ptr::write_bytes(output as *mut u8, 0, n) }; + return; + } + if WARNED.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("xdsp: output {start:#x} ({n} bytes) is outside the registered buffer – left untouched"); + } +} + +/// XDspConnectWithMaximumStreamLimit(buffer, bytes, impulseSeconds, maxStreams, maxChannels, &handle) +pub unsafe extern "system" fn XDspConnectWithMaximumStreamLimit( + buffer: *mut f32, + bytes: u32, + impulse_seconds: u32, + max_streams: u32, + max_channels: u32, + handle: *mut *mut c_void, +) -> HRESULT { + if buffer.is_null() || handle.is_null() || bytes == 0 || max_streams == 0 || !(1..=2).contains(&max_channels) { + if !handle.is_null() { + *handle = std::ptr::null_mut(); + } + return E_INVALIDARG; + } + let c = Box::new(Client { magic: CLIENT_MAGIC, base: buffer as usize, len: bytes, streams: Mutex::new(Vec::new()) }); + let p = Box::into_raw(c); + let mut w = WORLD.lock().unwrap(); + if w.clients.try_reserve(1).is_err() { + drop(Box::from_raw(p)); + *handle = std::ptr::null_mut(); + return E_OUTOFMEMORY; + } + w.clients.insert(p as usize, Box::from_raw(p)); + *handle = p as *mut c_void; + crate::xlog_info!( + "xdsp: client connected ({bytes:#x} byte buffer, {max_streams} streams, {max_channels} ch, impulse {impulse_seconds}s) – commands finish at once, output is silence" + ); + S_OK +} + +/// XDspActivate(client, ¶ms, &status, &stream) +pub unsafe extern "system" fn XDspActivate( + client: *mut c_void, + params: *const c_void, + status: *mut *mut c_void, + stream: *mut *mut c_void, +) -> HRESULT { + if client.is_null() || params.is_null() || status.is_null() || stream.is_null() { + return E_INVALIDARG; + } + let raw = params as *const u8; + let frames = u32_at(raw, 8); + let channels = u32_at(raw, 12); + let mut w = WORLD.lock().unwrap(); + if !w.clients.get(&(client as usize)).is_some_and(|c| c.magic == CLIENT_MAGIC) { + return E_INVALIDARG; + } + let s = Box::new(Stream { + magic: STREAM_MAGIC, + client: client as usize, + frames, + channels, + status: Status { + last_submitted: AtomicU32::new(0), + last_processed: AtomicU32::new(0), + first_failed: AtomicU32::new(0), + result: AtomicI32::new(S_OK), + }, + }); + let p = Box::into_raw(s); + if w.streams.try_reserve(1).is_err() { + drop(Box::from_raw(p)); + return E_OUTOFMEMORY; + } + let status_addr = &(*p).status as *const Status as *mut Status; + w.streams.insert(p as usize, Box::from_raw(p)); + if let Some(c) = w.clients.get(&(client as usize)) { + c.streams.lock().unwrap().push(p as usize); + } + *status = status_addr as *mut c_void; + *stream = p as *mut c_void; + crate::xlog_info!("xdsp: stream activated ({frames} frames, {channels} ch) – status is updated in the submit call"); + S_OK +} + +/// XDspSubmitCommand(stream, &command, &sequence) +pub unsafe extern "system" fn XDspSubmitCommand(stream: *mut c_void, command: *const c_void, sequence: *mut u32) -> HRESULT { + if stream.is_null() || command.is_null() { + return E_INVALIDARG; + } + let mut w = WORLD.lock().unwrap(); + let (output, frames, channels, client_key, seq) = { + let Some(s) = w.streams.get_mut(&(stream as usize)) else { + return E_INVALIDARG; + }; + if s.magic != STREAM_MAGIC { + return E_INVALIDARG; + } + let seq = s.status.last_submitted.fetch_add(1, Ordering::Release).wrapping_add(1); + s.status.last_processed.store(seq, Ordering::Release); + s.status.first_failed.store(0, Ordering::Release); + s.status.result.store(S_OK, Ordering::Release); + (ptr_at(command as *const u8, 16), s.frames, s.channels, s.client, seq) + }; + if let Some(c) = w.clients.get(&client_key) { + silence(c, output, frames, channels); + } + if !sequence.is_null() { + *sequence = seq; + } + S_OK +} + +/// XDspDeactivate(stream) +pub unsafe extern "system" fn XDspDeactivate(stream: *mut c_void) -> HRESULT { + if stream.is_null() { + return E_INVALIDARG; + } + let mut w = WORLD.lock().unwrap(); + let Some(s) = w.streams.remove(&(stream as usize)) else { + return E_INVALIDARG; + }; + if s.magic != STREAM_MAGIC { + return E_INVALIDARG; + } + if let Some(c) = w.clients.get(&s.client) { + c.streams.lock().unwrap().retain(|p| *p != stream as usize); + } + S_OK +} + +/// XDspDisconnect(client) +pub unsafe extern "system" fn XDspDisconnect(client: *mut c_void) -> HRESULT { + if client.is_null() { + return E_INVALIDARG; + } + let mut w = WORLD.lock().unwrap(); + let Some(c) = w.clients.remove(&(client as usize)) else { + return E_INVALIDARG; + }; + if c.magic != CLIENT_MAGIC { + return E_INVALIDARG; + } + let streams = std::mem::take(&mut *c.streams.lock().unwrap()); + for p in streams { + w.streams.remove(&p); + } + S_OK +} + +pub fn exports() -> Vec<(&'static str, usize)> { + crate::hle_exports![ + XDspConnectWithMaximumStreamLimit, + XDspActivate, + XDspSubmitCommand, + XDspDeactivate, + XDspDisconnect, + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_a_connect_without_a_buffer_or_a_handle() { + unsafe { + let mut h = 1 as *mut c_void; + assert_eq!(XDspConnectWithMaximumStreamLimit(std::ptr::null_mut(), 0x1_0000, 0, 8, 1, &mut h), E_INVALIDARG); + assert!(h.is_null()); + let mut buf = vec![1f32; 64]; + assert_eq!( + XDspConnectWithMaximumStreamLimit(buf.as_mut_ptr(), (buf.len() * 4) as u32, 0, 8, 3, &mut h), + E_INVALIDARG + ); + } + } + + #[test] + fn command_finishes_immediately_and_silences_only_its_block() { + unsafe { + // 16-byte aligned, the alignment the output pointer has to have + let mut storage = vec![1f32; 4096 + 8]; + let addr = storage.as_mut_ptr() as usize; + let aligned = (addr + 15) & !15; + let buf = aligned as *mut f32; + let floats = 4096 - (aligned - addr) / 4; + let mut client = std::ptr::null_mut(); + assert_eq!(XDspConnectWithMaximumStreamLimit(buf, (floats * 4) as u32, 0, 4, 1, &mut client), S_OK); + + // type, options, blockFrameCount, channelCount, impulse length, padding, pointer + let params: [u32; 8] = [0, 0, 512, 1, 0, 0, 0, 0]; + let mut status: *mut c_void = std::ptr::null_mut(); + let mut stream = std::ptr::null_mut(); + assert_eq!(XDspActivate(client, params.as_ptr() as *const c_void, &mut status, &mut stream), S_OK); + assert!(!status.is_null() && !stream.is_null()); + + let output = buf.add(16); + let mut raw = [0u8; 32]; + raw[16..24].copy_from_slice(&(output as usize).to_le_bytes()); + let mut seq = 0u32; + assert_eq!(XDspSubmitCommand(stream, raw.as_ptr() as *const c_void, &mut seq), S_OK); + assert_eq!(seq, 1); + let st = &*(status as *const Status); + assert_eq!(st.last_submitted.load(Ordering::Acquire), 1); + assert_eq!(st.last_processed.load(Ordering::Acquire), 1); + assert_eq!(st.first_failed.load(Ordering::Acquire), 0); + let samples = std::slice::from_raw_parts(buf, floats); + assert!(samples[..16].iter().all(|s| *s == 1.0), "samples before the block stay"); + assert!(samples[16..16 + 512].iter().all(|s| *s == 0.0)); + assert_eq!(samples[16 + 512], 1.0, "the sample after the block stays"); + + let mut other = [2f32; 8]; + raw[16..24].copy_from_slice(&(other.as_mut_ptr() as usize).to_le_bytes()); + assert_eq!(XDspSubmitCommand(stream, raw.as_ptr() as *const c_void, &mut seq), S_OK); + assert_eq!(seq, 2); + assert!(other.iter().all(|s| *s == 2.0)); + + assert_eq!(XDspDeactivate(stream), S_OK); + assert_eq!(XDspDeactivate(stream), E_INVALIDARG); + assert_eq!(XDspDisconnect(client), S_OK); + assert_eq!(XDspDisconnect(client), E_INVALIDARG); + } + } +} From c0c74cffcee10ee656314dc0ef7f3718c9fbc372 Mon Sep 17 00:00:00 2001 From: BED <73585863+yeetbot90@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:26:05 +0100 Subject: [PATCH 2/3] Cache translated shaders and driver pipelines, and accept Xbox depth formats. A cold load translated every shader twice and kept only 128 of them, and the driver recompiled every pipeline on the next launch. Xbox D16-with-stencil was also rejected as an unknown format. --- crates/xcl/src/gpu/recomp/pso.rs | 90 ++++++++- crates/xcl/src/gpu/shader.rs | 22 +- crates/xcl/src/hle/d3d12x/device_x.rs | 61 ++++++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/pso_disk.rs | 276 ++++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 133 ++++++++++++- crates/xcl/tests/e2e.rs | 2 + 7 files changed, 567 insertions(+), 18 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/pso_disk.rs diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b8de31f3e..bb36b7d69 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -106,7 +106,7 @@ pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_w return compile_one(); } static CACHE: OnceLock> = 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, @@ -118,7 +118,79 @@ pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_w cached_shader(cache, key, blob, compile_one).map(|shader| shader.as_ref().clone()) } +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 { + 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 { + 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); @@ -150,7 +222,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)`. @@ -236,6 +312,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, bytes: usize, @@ -270,7 +350,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; }; @@ -649,10 +729,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()); } diff --git a/crates/xcl/src/gpu/shader.rs b/crates/xcl/src/gpu/shader.rs index 4d6a25710..7bc63985f 100644 --- a/crates/xcl/src/gpu/shader.rs +++ b/crates/xcl/src/gpu/shader.rs @@ -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 -//! `\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 `\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; @@ -201,6 +201,14 @@ 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 = std::sync::OnceLock::new(); + *ON.get_or_init(|| 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 { @@ -225,9 +233,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() }); diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 403b7af29..24fd32ab2 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -645,6 +645,58 @@ pub(super) unsafe extern "system" fn create_sampler_x(this: *mut c_void, x: *con real::dev_create_sampler_x(this, &d, dest); } +/// Xbox colour formats a PC driver rejects. +pub fn pc_color_format(format: u32) -> u32 { + match format { + 116 | 117 => 10, // R10G10B10_*E*_A2_FLOAT → R16G16B16A16_FLOAT + other => other, + } +} + +/// Xbox depth formats. 118 is `D16_UNORM_S8_UINT`; the PC depth format with stencil is D24. +pub fn pc_dsv_format(format: u32) -> u32 { + match format { + 118 | 119 => 45, // D16_UNORM_S8_UINT / its depth read → D24_UNORM_S8_UINT + other => other, + } +} + +/// A resource's format. The typeless parent of D16+S8 becomes the typeless parent of D24+S8, +/// so a depth view of 118 still matches. +pub fn pc_resource_format(format: u32) -> u32 { + match format { + 116 | 117 => 10, + 118 => 45, + 119 | 120 => 44, // R16_UNORM_X8 / X16_G8 → R24G8_TYPELESS + other => other, + } +} + +/// A shader view of that depth family (depth plane, or the stencil plane). +pub fn pc_srv_format(format: u32) -> u32 { + match format { + 116 | 117 => 10, + 118 | 119 => 46, // R24_UNORM_X8_TYPELESS + 120 => 47, // X24_TYPELESS_G8_UINT + other => other, + } +} + +/// A clear value in the same depth family (typed, which is what a typeless resource's clear uses). +pub unsafe fn pc_clear_value(clear: *const c_void, storage: &mut [u8; 20]) -> *const c_void { + if clear.is_null() || !crate::gpu::shader::readable(clear as usize, 20) { + return clear; + } + let format = (clear as *const u32).read_unaligned(); + let mapped = if matches!(format, 118 | 119 | 120) { 45 } else { pc_color_format(format) }; + if mapped == format { + return clear; + } + std::ptr::copy_nonoverlapping(clear as *const u8, storage.as_mut_ptr(), 20); + storage[..4].copy_from_slice(&mapped.to_le_bytes()); + storage.as_ptr() as *const c_void +} + /// the console resource desc (0x38 bytes, D3D12_RESOURCE_DESC) as a PC one: its tile layouts /// and console flag bits mean nothing to a PC driver pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { @@ -652,6 +704,8 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { let dim = u32::from_le_bytes(d[0..4].try_into().unwrap()); let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); d[8..16].fill(0); // alignment: the driver's + let format = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()); + d[0x20..0x24].copy_from_slice(&pc_resource_format(format).to_le_bytes()); let layout = if dim == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 { D3D12_TEXTURE_LAYOUT_ROW_MAJOR.0 } else { D3D12_TEXTURE_LAYOUT_UNKNOWN.0 }; d[0x2C..0x30].copy_from_slice(&(layout as u32).to_le_bytes()); d[0x30..0x34].copy_from_slice(&(flags & 0xFF).to_le_bytes()); @@ -763,6 +817,8 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); let d = pc_resource_desc(&x); + let mut clear_buf = [0u8; 20]; + let clear = pc_clear_value(clear, &mut clear_buf); let buffer = u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; note_alias(va as usize, &x); // console-only state bits (Unicorn Overlord's 4K display target: 0x100000) are not the @@ -914,6 +970,11 @@ mod tests { assert_eq!((d[8], u32::from_le_bytes(d[0x2C..0x30].try_into().unwrap()), u32::from_le_bytes(d[0x30..0x34].try_into().unwrap())), (0, 1, 0x34)); x[0] = 3; // texture 2D assert_eq!(u32::from_le_bytes(pc_resource_desc(&x)[0x2C..0x30].try_into().unwrap()), 0); + x[0x20..0x24].copy_from_slice(&118u32.to_le_bytes()); + assert_eq!(u32::from_le_bytes(pc_resource_desc(&x)[0x20..0x24].try_into().unwrap()), 45); + x[0x20..0x24].copy_from_slice(&119u32.to_le_bytes()); + assert_eq!(u32::from_le_bytes(pc_resource_desc(&x)[0x20..0x24].try_into().unwrap()), 44); + assert_eq!((pc_dsv_format(118), pc_srv_format(119), pc_srv_format(120)), (45, 46, 47)); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 1d4e766f3..dd6da43cf 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -22,6 +22,7 @@ pub mod list_x; pub mod null; pub mod present; pub mod pso_async; +mod pso_disk; pub mod real; pub mod sparse; pub mod title_list; diff --git a/crates/xcl/src/hle/d3d12x/pso_disk.rs b/crates/xcl/src/hle/d3d12x/pso_disk.rs new file mode 100644 index 000000000..c950989d0 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pso_disk.rs @@ -0,0 +1,276 @@ +//! Driver pipeline blobs (`ID3D12PipelineState::GetCachedBlob`). +//! +//! Translating a console shader is cached as DXIL. The driver then compiles that DXIL again +//! on every launch. A blob from `GetCachedBlob` is that compile: the next +//! `Create*PipelineState` passes it in `CachedPSO` and the driver skips the work when the +//! blob still matches this device. A driver update rejects the blob; the caller drops the +//! file and compiles again. + +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; + +const MAGIC: &[u8; 4] = b"XPSO"; +const VERSION: u32 = 1; + +fn dir() -> PathBuf { + static DIR: OnceLock = OnceLock::new(); + DIR.get_or_init(|| { + if let Ok(d) = std::env::var("XCL_PSO_CACHE") { + return PathBuf::from(d); + } + let base = std::env::var("LOCALAPPDATA").map(PathBuf::from).unwrap_or_else(|_| std::env::temp_dir()); + base.join("xcl").join("pso") + }) + .clone() +} + +fn memory() -> &'static Mutex>>> { + static M: OnceLock>>>> = OnceLock::new(); + M.get_or_init(|| Mutex::new(std::collections::HashMap::new())) +} + +fn path_for(dir: &Path, key: u64) -> PathBuf { + dir.join(format!("{key:016x}.blob")) +} + +fn payload(file: &[u8]) -> Option<&[u8]> { + if file.len() < 8 || &file[..4] != MAGIC || u32::from_le_bytes(file[4..8].try_into().ok()?) != VERSION { + return None; + } + let blob = &file[8..]; + (!blob.is_empty() && blob.len() <= 32 << 20).then_some(blob) +} + +/// A blob saved for `key`, from this process or from disk. +pub fn load(key: u64) -> Option>> { + if let Some(hit) = memory().lock().unwrap().get(&key).cloned() { + return Some(hit); + } + let bytes = std::fs::read(path_for(&dir(), key)).ok()?; + let blob = payload(&bytes)?.to_vec(); + let blob = std::sync::Arc::new(blob); + memory().lock().unwrap().insert(key, blob.clone()); + Some(blob) +} + +/// Write `blob` so the next launch can reuse this driver's compile. +pub fn store(key: u64, blob: &[u8]) { + if blob.is_empty() || blob.len() > 32 << 20 { + return; + } + let owned = std::sync::Arc::new(blob.to_vec()); + memory().lock().unwrap().insert(key, owned); + let dir = dir(); + if std::fs::create_dir_all(&dir).is_err() { + return; + } + let path = path_for(&dir, key); + if std::fs::read(&path).ok().and_then(|b| payload(&b).map(|p| p == blob)).unwrap_or(false) { + return; + } + let mut body = Vec::with_capacity(8 + blob.len()); + body.extend_from_slice(MAGIC); + body.extend_from_slice(&VERSION.to_le_bytes()); + body.extend_from_slice(blob); + let tmp = path.with_extension(format!("tmp{}", std::process::id())); + if std::fs::write(&tmp, &body).is_ok() { + if std::fs::rename(&tmp, &path).is_err() { + let _ = std::fs::remove_file(&tmp); + } + } +} + +/// The driver refused this blob (a new driver, or a different pipeline). Do not try it again. +pub fn forget(key: u64) { + memory().lock().unwrap().remove(&key); + let _ = std::fs::remove_file(path_for(&dir(), key)); +} + +fn mix(h: &mut u64, bytes: &[u8]) { + for &b in bytes { + *h ^= b as u64; + *h = h.wrapping_mul(0x100_0000_01b3); + } +} + +fn mix_u32(h: &mut u64, v: u32) { + mix(h, &v.to_le_bytes()); +} + +fn mix_shader(h: &mut u64, s: &D3D12_SHADER_BYTECODE) { + let n = s.BytecodeLength; + let p = s.pShaderBytecode as usize; + if n == 0 || !crate::gpu::shader::readable(p, n) { + mix_u32(h, 0); + return; + } + mix_u32(h, n as u32); + mix(h, unsafe { std::slice::from_raw_parts(p as *const u8, n) }); +} + +fn mix_input(h: &mut u64, layout: &D3D12_INPUT_LAYOUT_DESC) { + let n = layout.NumElements as usize; + mix_u32(h, layout.NumElements); + if n == 0 || n > 32 || layout.pInputElementDescs.is_null() { + return; + } + let bytes = n * std::mem::size_of::(); + if !crate::gpu::shader::readable(layout.pInputElementDescs as usize, bytes) { + return; + } + let elems = unsafe { std::slice::from_raw_parts(layout.pInputElementDescs, n) }; + for e in elems { + if !e.SemanticName.is_null() { + let mut k = 0usize; + while k < 64 { + let c = unsafe { *e.SemanticName.0.add(k) }; + mix(h, &[c]); + if c == 0 { + break; + } + k += 1; + } + } + mix_u32(h, e.SemanticIndex); + mix_u32(h, e.Format.0 as u32); + mix_u32(h, e.InputSlot); + mix_u32(h, e.AlignedByteOffset); + mix_u32(h, e.InputSlotClass.0 as u32); + mix_u32(h, e.InstanceDataStepRate); + } +} + +fn mix_blend(h: &mut u64, b: &D3D12_BLEND_DESC) { + mix_u32(h, b.AlphaToCoverageEnable.0 as u32); + mix_u32(h, b.IndependentBlendEnable.0 as u32); + for rt in &b.RenderTarget { + mix_u32(h, rt.BlendEnable.0 as u32); + mix_u32(h, rt.LogicOpEnable.0 as u32); + mix_u32(h, rt.SrcBlend.0 as u32); + mix_u32(h, rt.DestBlend.0 as u32); + mix_u32(h, rt.BlendOp.0 as u32); + mix_u32(h, rt.SrcBlendAlpha.0 as u32); + mix_u32(h, rt.DestBlendAlpha.0 as u32); + mix_u32(h, rt.BlendOpAlpha.0 as u32); + mix_u32(h, rt.LogicOp.0 as u32); + mix_u32(h, rt.RenderTargetWriteMask as u32); + } +} + +fn mix_op(h: &mut u64, o: &D3D12_DEPTH_STENCILOP_DESC) { + mix_u32(h, o.StencilFailOp.0 as u32); + mix_u32(h, o.StencilDepthFailOp.0 as u32); + mix_u32(h, o.StencilPassOp.0 as u32); + mix_u32(h, o.StencilFunc.0 as u32); +} + +fn mix_depth(h: &mut u64, z: &D3D12_DEPTH_STENCIL_DESC) { + mix_u32(h, z.DepthEnable.0 as u32); + mix_u32(h, z.DepthWriteMask.0 as u32); + mix_u32(h, z.DepthFunc.0 as u32); + mix_u32(h, z.StencilEnable.0 as u32); + mix(h, &[z.StencilReadMask, z.StencilWriteMask]); + mix_op(h, &z.FrontFace); + mix_op(h, &z.BackFace); +} + +fn mix_raster(h: &mut u64, r: &D3D12_RASTERIZER_DESC) { + mix_u32(h, r.FillMode.0 as u32); + mix_u32(h, r.CullMode.0 as u32); + mix(h, &r.FrontCounterClockwise.0.to_le_bytes()); + mix(h, &r.DepthBias.to_le_bytes()); + mix(h, &r.DepthBiasClamp.to_le_bytes()); + mix(h, &r.SlopeScaledDepthBias.to_le_bytes()); + mix_u32(h, r.DepthClipEnable.0 as u32); + mix_u32(h, r.MultisampleEnable.0 as u32); + mix_u32(h, r.AntialiasedLineEnable.0 as u32); + mix_u32(h, r.ForcedSampleCount); + mix_u32(h, r.ConservativeRaster.0 as u32); +} + +fn mix_samplers(h: &mut u64, samplers: &[([u32; 4], bool)]) { + mix_u32(h, samplers.len() as u32); + for (words, comparison) in samplers { + for w in words { + mix_u32(h, *w); + } + mix(h, &[*comparison as u8]); + } +} + +/// Identity of a graphics pipeline the driver compiled. The root signature pointer is not +/// part of it; `samplers` is, because that is what the XCL root signature was built from. +pub fn graphics_key(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, samplers: &[([u32; 4], bool)]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + mix(&mut h, b"gfx1"); + mix_shader(&mut h, &d.VS); + mix_shader(&mut h, &d.PS); + mix_shader(&mut h, &d.DS); + mix_shader(&mut h, &d.HS); + mix_shader(&mut h, &d.GS); + mix_blend(&mut h, &d.BlendState); + mix_u32(&mut h, d.SampleMask); + mix_raster(&mut h, &d.RasterizerState); + mix_depth(&mut h, &d.DepthStencilState); + mix_input(&mut h, &d.InputLayout); + mix_u32(&mut h, d.IBStripCutValue.0 as u32); + mix_u32(&mut h, d.PrimitiveTopologyType.0 as u32); + mix_u32(&mut h, d.NumRenderTargets); + for f in &d.RTVFormats { + mix_u32(&mut h, f.0 as u32); + } + mix_u32(&mut h, d.DSVFormat.0 as u32); + mix_u32(&mut h, d.SampleDesc.Count); + mix_u32(&mut h, d.SampleDesc.Quality); + mix_u32(&mut h, d.NodeMask); + mix_u32(&mut h, d.Flags.0 as u32); + mix_samplers(&mut h, samplers); + h +} + +pub fn compute_key(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, samplers: &[([u32; 4], bool)]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + mix(&mut h, b"cs1"); + mix_shader(&mut h, &d.CS); + mix_u32(&mut h, d.NodeMask); + mix_u32(&mut h, d.Flags.0 as u32); + mix_samplers(&mut h, samplers); + h +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shader_bytes_change_the_key_and_the_blob_round_trips() { + let vs = [1u8, 2, 3, 4, 5, 6, 7, 8]; + let mut g = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + g.VS = D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as *const _, BytecodeLength: vs.len() }; + g.NumRenderTargets = 1; + g.RTVFormats[0] = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM; + let k1 = graphics_key(&g, &[]); + let vs2 = [1u8, 2, 3, 4, 5, 6, 7, 9]; + g.VS.pShaderBytecode = vs2.as_ptr() as *const _; + assert_ne!(k1, graphics_key(&g, &[])); + g.VS.pShaderBytecode = vs.as_ptr() as *const _; + assert_eq!(k1, graphics_key(&g, &[])); + assert_ne!(k1, graphics_key(&g, &[([1, 2, 3, 4], false)])); + + let dir = std::env::temp_dir().join(format!("xcl-pso-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = path_for(&dir, k1); + let blob = b"driver-blob-bytes"; + let mut body = Vec::new(); + body.extend_from_slice(MAGIC); + body.extend_from_slice(&VERSION.to_le_bytes()); + body.extend_from_slice(blob); + std::fs::write(&file, &body).unwrap(); + let read = std::fs::read(&file).unwrap(); + assert_eq!(payload(&read), Some(blob.as_slice())); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 3f8e1a472..98508b194 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1628,7 +1628,9 @@ unsafe extern "system" fn heap_release(this: *mut c_void) -> u32 { unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, cpu: u64) { let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); - let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) }; + let mut pc_desc = D3D12_SHADER_RESOURCE_VIEW_DESC::default(); + let pc = srv_desc_pc(desc, &mut pc_desc); + let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, pc, cpu) }; // Raytracing acceleration structure SRV (pResource == NULL, Location == console GPU VA): // translated shaders read BVH nodes from UMA (`bvh_intersect`), never from a PC DXR SRV, // so write the RDNA2 BVH descriptor directly and skip forwarding the console VA to PC. @@ -1645,7 +1647,7 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } return super::console_heap::write(&slot, &[0; 8]); } - f(this, res, desc, slot.pc_srv); + f(this, res, pc, slot.pc_srv); super::console_heap::publish(&slot, false); super::console_heap::note_resource(&slot, res as usize); if super::present::trace_frame() && super::title_textures::address(res as usize).is_some() { @@ -1681,7 +1683,7 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, 10 => (a.TextureCubeArray.NumCubes.max(1) * 6, a.TextureCubeArray.MipLevels), _ => (1, 1), }; - (v.Format, v.ViewDimension.0, array, mips) + (dxgi(super::device_x::pc_srv_format(v.Format.0 as u32)), v.ViewDimension.0, array, mips) } None => { let d = r.GetDesc(); @@ -1865,6 +1867,8 @@ unsafe extern "system" fn dev_create_committed_resource_layout_x( unsafe fn create_display_target(this: *mut c_void, props: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); let d = super::device_x::pc_resource_desc(&x); + let mut clear_buf = [0u8; 20]; + let clear = super::device_x::pc_clear_value(clear as *const c_void, &mut clear_buf) as usize; let hr = dev_create_committed_resource(this, props, 0, d.as_ptr() as usize, state, clear, riid, ppv); if hr < 0 || ppv.is_null() || (*ppv).is_null() { crate::xlog_warn!("D3D12.X: display target: {hr:#x}; desc {x:02x?}"); @@ -1929,6 +1933,8 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro let pc_full = (console_desc != 0 && crate::gpu::shader::readable(console_desc, 0x38)).then(|| super::device_x::pc_resource_desc(&(console_desc as *const [u8; 0x38]).read_unaligned())); let desc = pc_full.as_ref().map_or(desc, |d| d.as_ptr() as usize); // console-only state bits (e.g. 0x100000 on a display target) are not the PC's + let mut clear_buf = [0u8; 20]; + let clear = super::device_x::pc_clear_value(clear as *const c_void, &mut clear_buf) as usize; let hr = dev_create_committed_resource(this, props, flags, desc, state & PC_RESOURCE_STATES as usize, clear, riid, ppv); if hr < 0 { let pw = |o: usize| if props == 0 { 0 } else { *((props + o) as *const u32) }; @@ -1976,6 +1982,8 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("CreateDescriptorHeap", dev_create_descriptor_heap as usize), ("CreateRootSignature", dev_create_root_signature as usize), ("CreateRenderTargetView", dev_create_rtv as usize), + ("CreateDepthStencilView", dev_create_dsv as usize), + ("CreateShaderResourceView", dev_create_srv as usize), ("CreateCommittedResource", dev_create_committed_resource as usize), ("CreateHeap", dev_create_heap as usize), ("CreatePlacedResource", dev_create_placed_resource as usize), @@ -2723,6 +2731,64 @@ unsafe fn finish_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *co hr } +fn cached_pso(blob: &[u8]) -> D3D12_CACHED_PIPELINE_STATE { + D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: if blob.is_empty() { std::ptr::null() } else { blob.as_ptr() as *const c_void }, + CachedBlobSizeInBytes: blob.len(), + } +} + +unsafe fn driver_blob(pso: *mut c_void) -> Option> { + let pso = ID3D12PipelineState::from_raw_borrowed(&pso)?; + let blob = pso.GetCachedBlob().ok()?; + let n = blob.GetBufferSize(); + if n == 0 || n > 32 << 20 { + return None; + } + Some(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, n).to_vec()) +} + +fn note_driver_cache(saved: bool) { + static SAVED: AtomicU64 = AtomicU64::new(0); + static USED: AtomicU64 = AtomicU64::new(0); + let (n, word) = if saved { (SAVED.fetch_add(1, Ordering::Relaxed), "saved") } else { (USED.fetch_add(1, Ordering::Relaxed), "reused") }; + if n < 3 || n % 500 == 0 { + crate::xlog_info!("D3D12.X: driver pipeline cache: {} pipelines {word}", n + 1); + } +} + +/// Create `desc` (a graphics or compute pipeline desc). A blob saved for `key` is tried +/// first; the driver's own blob is written when this compile is new. +unsafe fn finish_pso_cached(this: *mut c_void, f: PsoFn, desc: *mut c_void, graphics: bool, key: u64, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let loaded = super::pso_disk::load(key); + let apply = |blob: &[u8]| { + let cached = cached_pso(blob); + if graphics { + (*(desc as *mut D3D12_GRAPHICS_PIPELINE_STATE_DESC)).CachedPSO = cached; + } else { + (*(desc as *mut D3D12_COMPUTE_PIPELINE_STATE_DESC)).CachedPSO = cached; + } + }; + if let Some(blob) = &loaded { + apply(blob); + } + let mut hr = finish_pso(this, f, desc, riid, ppv); + if hr < 0 && loaded.is_some() { + super::pso_disk::forget(key); + apply(&[]); + hr = finish_pso(this, f, desc, riid, ppv); + } else if hr >= 0 && loaded.is_some() { + note_driver_cache(false); + } + if hr >= 0 && loaded.is_none() && !ppv.is_null() && !(*ppv).is_null() { + if let Some(blob) = driver_blob(*ppv) { + super::pso_disk::store(key, &blob); + note_driver_cache(true); + } + } + hr +} + thread_local! { /// translation errors noted during a cached-only attempt (`attempt`) static ATTEMPT_NOTES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; @@ -2857,7 +2923,8 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); copy.CS = bytecode(&dxil); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); - let hr = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); + let key = super::pso_disk::compute_key(©, &compiled.samplers); + let hr = finish_pso_cached(this, f, &mut copy as *mut _ as *mut c_void, false, key, riid, ppv); if hr < 0 { note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); return Some(Err(())); @@ -2865,7 +2932,11 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); note_translated_compute(hr, ppv); - crate::xlog_info!("D3D12.X: compute PSO with the translated console CS ({} B DXIL)", dxil.len()); + static COMPUTE_LOG: AtomicU64 = AtomicU64::new(0); + let n = COMPUTE_LOG.fetch_add(1, Ordering::Relaxed); + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: compute PSO with the translated console CS ({} B DXIL, #{})", dxil.len(), n + 1); + } Some(Ok(hr)) } @@ -2920,6 +2991,7 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo copy.PS = ps_dxil.as_deref().map(bytecode).unwrap_or_default(); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); pc_topology_type(&mut copy); + pc_pso_formats(&mut copy); let ps_hash = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); if debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) { copy.DepthStencilState.StencilEnable = false.into(); @@ -2927,7 +2999,8 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo if debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash) { copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } - let hr = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); + let key = super::pso_disk::graphics_key(©, &samplers); + let hr = finish_pso_cached(this, f, &mut copy as *mut _ as *mut c_void, true, key, riid, ppv); if hr < 0 { note_translation_error(format!( "the driver rejected the PSO with the translated shaders ({hr:#x}; topology type {}, {} render targets, DSV format {}, HS {}, GS {})", @@ -3217,6 +3290,7 @@ pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, copy.InputLayout = D3D12_INPUT_LAYOUT_DESC::default(); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); pc_topology_type(&mut copy); + pc_pso_formats(&mut copy); let hr2 = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); note_fallback("graphics PSO", hr, hr2 >= 0); if hr2 >= 0 { @@ -3530,8 +3604,12 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, &d.DepthStencilState); let mut rt = D3D12_RT_FORMAT_ARRAY { NumRenderTargets: d.NumRenderTargets, ..Default::default() }; rt.RTFormats = d.RTVFormats; + for f in &mut rt.RTFormats { + *f = dxgi(super::device_x::pc_color_format(f.0 as u32)); + } + let dsv = dxgi(super::device_x::pc_dsv_format(d.DSVFormat.0 as u32)); out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, &rt); - out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, &d.DSVFormat); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, &dsv); out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, &d.SampleDesc); out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, &d.NodeMask); if d.Flags.0 != 0 { @@ -3585,6 +3663,17 @@ fn pc_topology_type(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) { } } +fn dxgi(format: u32) -> windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT { + windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(format as i32) +} + +fn pc_pso_formats(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) { + g.DSVFormat = dxgi(super::device_x::pc_dsv_format(g.DSVFormat.0 as u32)); + for f in &mut g.RTVFormats { + *f = dxgi(super::device_x::pc_color_format(f.0 as u32)); + } +} + enum StreamPipeline { Graphics(Box), Compute(Box), @@ -3712,6 +3801,7 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { } } pc_topology_type(&mut g); + pc_pso_formats(&mut g); StreamPipeline::Graphics(Box::new(g)) } @@ -3798,6 +3888,35 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 // presentation tracking // --------------------------------------------------------------------------------------- +unsafe fn srv_desc_pc<'a>(desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, storage: &'a mut D3D12_SHADER_RESOURCE_VIEW_DESC) -> *const D3D12_SHADER_RESOURCE_VIEW_DESC { + let Some(v) = (unsafe { desc.as_ref() }) else { return desc }; + *storage = *v; + storage.Format = dxgi(super::device_x::pc_srv_format(v.Format.0 as u32)); + storage +} + +unsafe extern "system" fn dev_create_srv(this: *mut c_void, res: *mut c_void, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, handle: u64) { + type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64); + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateShaderResourceView"))); + let mut storage = D3D12_SHADER_RESOURCE_VIEW_DESC::default(); + f(this, res, srv_desc_pc(desc, &mut storage), handle); +} + +unsafe extern "system" fn dev_create_dsv(this: *mut c_void, res: *mut c_void, desc: *const c_void, handle: usize) { + type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void, usize); + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateDepthStencilView"))); + let mut copy = [0u8; 64]; + let desc = if !desc.is_null() && crate::gpu::shader::readable(desc as usize, 64) { + std::ptr::copy_nonoverlapping(desc as *const u8, copy.as_mut_ptr(), 64); + let format = u32::from_le_bytes(copy[..4].try_into().unwrap()); + copy[..4].copy_from_slice(&super::device_x::pc_dsv_format(format).to_le_bytes()); + copy.as_ptr() as *const c_void + } else { + desc + }; + f(this, res, desc, handle); +} + unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, desc: *const c_void, handle: usize) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void, usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateRenderTargetView"))); diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index fa17758b7..2f1c47e25 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -73,6 +73,7 @@ fn launcher_uses_configured_exe_in_an_ambiguous_folder() { .arg("run") .arg(&game) .env("XCL_DATA_ROOT", &data) + .env("XCL_SHADER_DUMP", "1") .output(); let boot = std::fs::read_to_string(title.join("cache").join("boot.json")); std::fs::remove_dir_all(&root).unwrap(); @@ -112,6 +113,7 @@ fn test_title_runs_and_game_folder_is_untouched() { .arg("--") .arg("--hello") .env("XCL_DATA_ROOT", &data) + .env("XCL_SHADER_DUMP", "1") .output() .expect("spawn xcl"); let stdout = String::from_utf8_lossy(&out.stdout); From 722ebb768b3ccb8087147799a7e78a93c9b1dc12 Mon Sep 17 00:00:00 2001 From: BED <73585863+yeetbot90@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:49:03 +0100 Subject: [PATCH 3/3] Keep depth-and-UAV textures from removing the device, and precompile shaders beside other work. A console depth buffer that is also a UAV is created as D16, and a UAV view of a resource without unordered access is a null view. New pipeline compiles stay off the title thread. xcl shaders --precompile --gentle fills the DXIL and driver caches a few at a time. Co-authored-by: Cursor --- crates/xcl/src/gpu/recomp/dxc.rs | 16 ++ crates/xcl/src/hle/d3d12x/device_x.rs | 256 +++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/pso_async.rs | 92 ++++++++- crates/xcl/src/hle/d3d12x/pso_disk.rs | 39 ++-- crates/xcl/src/hle/d3d12x/real.rs | 167 ++++++++++++++-- crates/xcl/src/hle/netoff.rs | 117 ++++++++++- crates/xcl/src/hle/user.rs | 40 +++- crates/xcl/src/hle/xg.rs | 5 +- crates/xcl/src/main.rs | 4 + crates/xcl/src/shaders.rs | 212 ++++++++++++++++++-- 10 files changed, 873 insertions(+), 75 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 894a96758..f8c1838fd 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -603,6 +603,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, bool), String> { compile_cached_in(&cache_dir(), src, entry, profile) } @@ -639,6 +648,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 { diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 24fd32ab2..e6db2e348 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -649,6 +649,9 @@ pub(super) unsafe extern "system" fn create_sampler_x(this: *mut c_void, x: *con pub fn pc_color_format(format: u32) -> u32 { match format { 116 | 117 => 10, // R10G10B10_*E*_A2_FLOAT → R16G16B16A16_FLOAT + // A8_UNORM is not a render-target format on this GPU. R8_UNORM still removed the + // device (the translated pixel shader writes float4). R8G8B8A8_UNORM matches that. + 65 => 28, other => other, } } @@ -684,8 +687,9 @@ pub fn pc_srv_format(format: u32) -> u32 { /// A clear value in the same depth family (typed, which is what a typeless resource's clear uses). pub unsafe fn pc_clear_value(clear: *const c_void, storage: &mut [u8; 20]) -> *const c_void { + // a pointer the title did not fill in must not reach the driver: it removes the device if clear.is_null() || !crate::gpu::shader::readable(clear as usize, 20) { - return clear; + return std::ptr::null(); } let format = (clear as *const u32).read_unaligned(); let mapped = if matches!(format, 118 | 119 | 120) { 45 } else { pc_color_format(format) }; @@ -697,6 +701,19 @@ pub unsafe fn pc_clear_value(clear: *const c_void, storage: &mut [u8; 20]) -> *c storage.as_ptr() as *const c_void } +/// Copy resource-desc bytes into an aligned `D3D12_RESOURCE_DESC`. A `[u8; 0x38]` is only +/// 1-byte aligned; the driver loads the desc with aligned reads, and an unaligned pointer +/// removes the device (`0x887A0001`) instead of returning `E_INVALIDARG`. +fn aligned_desc(bytes: &[u8; 0x38]) -> D3D12_RESOURCE_DESC { + unsafe { std::ptr::read_unaligned(bytes.as_ptr().cast()) } +} + +/// 0 while the device is alive. The first call that changes that is the one to fix; +/// later creates only repeat `0x887A0005`. +unsafe fn removed_reason(this: *mut c_void) -> i32 { + ID3D12Device::from_raw_borrowed(&this).and_then(|dev| dev.GetDeviceRemovedReason().err().map(|e| e.code().0)).unwrap_or(0) +} + /// the console resource desc (0x38 bytes, D3D12_RESOURCE_DESC) as a PC one: its tile layouts /// and console flag bits mean nothing to a PC driver pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { @@ -704,14 +721,84 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { let dim = u32::from_le_bytes(d[0..4].try_into().unwrap()); let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); d[8..16].fill(0); // alignment: the driver's - let format = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()); - d[0x20..0x24].copy_from_slice(&pc_resource_format(format).to_le_bytes()); + let raw_format = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()); + let pc_flags = pc_resource_flags(raw_format, flags); + // R16_TYPELESS shadow maps carry the depth flag and a UAV flag. The PC resource is D16. + let format = if raw_format == 53 && pc_flags & 0x2 != 0 { 55 } else { pc_resource_format(raw_format) }; + d[0x20..0x24].copy_from_slice(&format.to_le_bytes()); + // a console desc leaves SampleDesc at 0, or a quality the PC rejects when the count is 1 + if u32::from_le_bytes(d[0x24..0x28].try_into().unwrap()) <= 1 { + d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + d[0x28..0x2C].fill(0); + } let layout = if dim == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 { D3D12_TEXTURE_LAYOUT_ROW_MAJOR.0 } else { D3D12_TEXTURE_LAYOUT_UNKNOWN.0 }; d[0x2C..0x30].copy_from_slice(&(layout as u32).to_le_bytes()); - d[0x30..0x34].copy_from_slice(&(flags & 0xFF).to_le_bytes()); + d[0x30..0x34].copy_from_slice(&pc_flags.to_le_bytes()); d } +/// PC resource flags. Console-only bits are dropped. Depth cannot share a resource with a +/// render target or a UAV. A real depth format keeps depth. A typeless format that is also a +/// UAV keeps the UAV, because the title creates those in a shader-resource or unordered state. +fn pc_resource_flags(format: u32, flags: u32) -> u32 { + const RT: u32 = 0x1; + const DS: u32 = 0x2; + const UAV: u32 = 0x4; + let mut f = flags & 0xFF; + let depth = matches!(format, 19..=22 | 44..=47 | 53 | 55 | 118..=120); + if f & DS != 0 && f & (RT | UAV) != 0 { + f &= if depth { !(RT | UAV) } else { !DS }; + } + f +} + +/// A depth resource is refused unless it is born in a depth state. Anything else (shader +/// resource, unordered, common) stays as the title asked. +fn born_state(flags: u32, state: u32) -> u32 { + if flags & 0x2 != 0 && state & (0x10 | 0x20) == 0 { 0x10 } else { state } +} + +/// A typeless resource that is not a render target or a depth buffer may only be born in +/// COMMON. Unordered-access on R16_TYPELESS removed the device (INVALID_CALL). +fn initial_state(format: u32, flags: u32, state: u32) -> u32 { + const TYPELESS: &[u32] = &[1, 5, 9, 15, 19, 23, 27, 33, 39, 44, 48, 53, 60, 70, 73, 76, 79, 82, 90, 92, 94, 97]; + if flags & 0x3 == 0 && TYPELESS.contains(&format) { 0 } else { state } +} + +/// A placement the title can store in 32 bits when the driver reports the resource as unsizable. +fn finite_allocation(d: &[u8; 0x38]) -> Option<(u64, u64)> { + let dim = u32::from_le_bytes(d[0..4].try_into().ok()?); + let width = u64::from_le_bytes(d[0x10..0x18].try_into().ok()?).max(1); + let height = u32::from_le_bytes(d[0x18..0x1C].try_into().ok()?).max(1) as u64; + let layers = u16::from_le_bytes(d[0x1C..0x1E].try_into().ok()?).max(1) as u64; + let mips = u16::from_le_bytes(d[0x1E..0x20].try_into().ok()?).clamp(1, 16) as u64; + let format = u32::from_le_bytes(d[0x20..0x24].try_into().ok()?); + let align = 0x1_0000u64; + if dim <= 1 { + let size = width.div_ceil(align) * align; + return (size <= u32::MAX as u64).then_some((size, align)); + } + let bpp: u64 = match format { + 118 | 119 | 120 | 19..=22 | 44..=47 => 5, + 116 | 117 => 8, + _ => 4, + }; + let slices = if dim == 4 { 1 } else { layers }; + let mut depth = if dim == 4 { layers } else { 1 }; + let (mut w, mut h) = (width, height); + let mut size = 0u64; + for _ in 0..mips { + size = size.saturating_add(w.saturating_mul(h).saturating_mul(depth).saturating_mul(slices).saturating_mul(bpp)); + w = (w / 2).max(1); + h = (h / 2).max(1); + if dim == 4 { + depth = (depth / 2).max(1); + } + } + let size = size.saturating_mul(2).div_ceil(align).saturating_mul(align); + (size > 0 && size <= u32::MAX as u64).then_some((size, align)) +} + /// device #25 GetResourceAllocationInfo(visible mask, count, descs) → {size, alignment}, /// returned through a hidden pointer. Called the C way – (return buffer, device, …), XDefiant – /// or the C++ way – (device, return buffer, …): whichever argument is the device is `this`. @@ -733,10 +820,26 @@ pub(super) unsafe extern "system" fn get_resource_allocation_info_x(a: *mut c_vo (r[0], r[1]) } }; - if s == u64::MAX || a == 0 { - size = u64::MAX; - break; - } + let (s, a) = if s == u64::MAX || a == 0 || s > u32::MAX as u64 { + // the title asserts the size's high half is 0 (game+0x344196). A driver + // rejection is all-ones, which trips that. A finite placement does not. + match finite_allocation(&x) { + Some(p) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + let format = u32::from_le_bytes(x[0x20..0x24].try_into().unwrap()); + crate::xlog_warn!("D3D12.X: GetResourceAllocationInfo format {format} had no driver size – using {p:?}"); + } + p + } + None => { + size = u64::MAX; + break; + } + } + } else { + (s, a) + }; size = size.div_ceil(a) * a + s; align = align.max(a); } @@ -792,18 +895,20 @@ pub(super) unsafe extern "system" fn get_custom_heap_properties_x(a: *mut c_void /// Resources the title placed at an address an earlier one was placed at: on the console they /// share that memory (aliasing – transient render targets reuse it). Logged (first 16). -fn note_alias(va: usize, x: &[u8; 0x38]) { +fn note_alias(va: usize, x: &[u8; 0x38]) -> bool { static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(None); static N: AtomicU64 = AtomicU64::new(0); let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); let what = format!("dimension {} {}x{} format {} flags {:#x}", u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u(0x20), u(0x30)); let mut g = SEEN.lock().unwrap(); let m = g.get_or_insert_with(std::collections::HashMap::new); - if let Some(prev) = m.insert(va, what.clone()) { + let prev = m.insert(va, what.clone()); + if let Some(prev) = prev.as_ref() { if N.fetch_add(1, Ordering::Relaxed) < 16 { crate::xlog_info!("D3D12.X: CreatePlacedResourceX at {va:#x} ({what}) – aliases an earlier resource there ({prev})"); } } + prev.is_some() } /// device #44 CreatePlacedResourceX(address, desc, initial state, clear value, riid, resource): @@ -816,29 +921,122 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, return E_INVALIDARG; } let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); - let d = pc_resource_desc(&x); + static ENTER: AtomicU64 = AtomicU64::new(0); + if ENTER.fetch_add(1, Ordering::Relaxed) < 8 { + let w = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); + crate::xlog_info!( + "D3D12.X: placed enter va {va:#x} dim {} {}x{} format {} flags {:#x} state {state:#x}", + w(0), + u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), + w(0x18), + w(0x20), + w(0x30) + ); + } + let mut d = pc_resource_desc(&x); let mut clear_buf = [0u8; 20]; let clear = pc_clear_value(clear, &mut clear_buf); let buffer = u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; - note_alias(va as usize, &x); + // a second resource at an address already placed overlaps the first one in the arena. + // That overlap is an invalid call on this GPU and removes the device. + let aliased = note_alias(va as usize, &x); // console-only state bits (Unicorn Overlord's 4K display target: 0x100000) are not the // PC's: the PC refused the resource (E_INVALIDARG) and the title threw - let state = state & real::PC_RESOURCE_STATES; + let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); + let format = u32::from_le_bytes(d[0x20..0x24].try_into().unwrap()); + let state = initial_state(format, flags, born_state(flags, state & real::PC_RESOURCE_STATES)); + // a clear value is legal only for a render target or a depth buffer. Passing one for a + // UAV removes the device (INVALID_CALL) on this GPU. + let clear = if flags & 0x3 != 0 { clear } else { std::ptr::null() }; if buffer { if let Some(hr) = real::place_at_title_address(this, va as usize, &d, state, clear, riid, ppv) { return hr; } } // render targets, depth buffers, UAV textures: in video memory, aliased by address (`vram`) - let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); - if !buffer && super::vram::gpu_owned(flags) { + let before = removed_reason(this); + if !buffer && !aliased && super::vram::gpu_owned(flags) { let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); if let Some(hr) = super::vram::place(this, va as usize, &pc, state, clear, riid, ppv) { + let after = removed_reason(this); + if before == 0 && after != 0 { + crate::xlog_warn!("D3D12.X: placed resource removed the device ({after:#x}) format {format} state {state:#x} hr {hr:#x}"); + } return hr; } } - let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; - let hr = real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, d.as_ptr() as usize, state as usize, clear as usize, riid, ppv); + let mid = removed_reason(this); + if before == 0 && mid != 0 { + let w = |o: usize| u32::from_le_bytes(d[o..o + 4].try_into().unwrap()); + crate::xlog_warn!("D3D12.X: placing removed the device ({mid:#x}) before its own resource: {}x{} format {} flags {:#x} state {state:#x}", w(0x10), w(0x18), format, flags); + } + let original_format = u32::from_le_bytes(x[0x20..0x24].try_into().unwrap()); + if original_format == 53 { + // Alignment 0 is legal. This driver still removes the device for a texture array + // created that way; 64 KiB is the alignment it fills in when the field is 0. + d[8..16].copy_from_slice(&0x1_0000u64.to_le_bytes()); + let layers = u16::from_le_bytes(d[0x1C..0x1E].try_into().unwrap()); + let words: Vec = (0..14).map(|k| u32::from_le_bytes(d[k * 4..k * 4 + 4].try_into().unwrap())).collect(); + let prior = ID3D12Device::from_raw_borrowed(&this).and_then(|dev| dev.GetDeviceRemovedReason().ok().map(|_| 0).or_else(|| dev.GetDeviceRemovedReason().err().map(|e| e.code().0))); + crate::xlog_warn!("D3D12.X: R16 texture state {state:#x} device {prior:?} layers {layers} desc {words:08x?}"); + } + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + CreationNodeMask: 1, + VisibleNodeMask: 1, + ..Default::default() + }; + // `[u8; 0x38]` is not 8-aligned. The driver loads the desc with aligned reads; an + // unaligned pointer removes the device (0x887A0001) instead of returning E_INVALIDARG. + let desc = aligned_desc(&d); + let mut hr = real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, &desc as *const _ as usize, state as usize, clear as usize, riid, ppv); + let committed_after = removed_reason(this); + if mid == 0 && committed_after != 0 { + let words: Vec = (0..14).map(|k| u32::from_le_bytes(d[k * 4..k * 4 + 4].try_into().unwrap())).collect(); + crate::xlog_warn!("D3D12.X: committed resource removed the device ({committed_after:#x}) hr {hr:#x} state {state:#x} desc {words:08x?}"); + } + if original_format == 53 { + let after = ID3D12Device::from_raw_borrowed(&this).and_then(|dev| dev.GetDeviceRemovedReason().ok()); + crate::xlog_warn!("D3D12.X: R16 texture create {hr:#x} device afterwards {after:?}"); + } + // a clear value whose format the PC will not pair with this desc (typeless, or a console + // format the remap did not cover) is the usual E_INVALIDARG after the flags are legal + // 0x887Axxxx is device-removed: another create only repeats it + let removed = |hr: HRESULT| (hr as u32) & 0xFFFF_0000 == 0x887A_0000; + if hr < 0 && !removed(hr) && !clear.is_null() { + let desc = aligned_desc(&d); + hr = real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, &desc as *const _ as usize, state as usize, 0, riid, ppv); + } + // depth and UAV were both set: the first choice can still be the wrong one for this state + if hr < 0 && !removed(hr) && u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()) & 0x6 == 0x6 { + let mut alt = d; + let flipped = if flags & 0x2 != 0 { (flags & !0x2) | 0x4 } else { (flags & !0x4) | 0x2 }; + alt[0x30..0x34].copy_from_slice(&flipped.to_le_bytes()); + let st = born_state(flipped, state & !0xC8); + let desc = aligned_desc(&alt); + hr = real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, &desc as *const _ as usize, st as usize, 0, riid, ppv); + } + // last: one sample, one mip, one layer, no depth flag. A console desc the PC still + // rejects (MSAA with a UAV, a 0 layer count, a depth state on a UAV) was an int3. + if hr < 0 && !removed(hr) && !buffer { + let words: Vec = (0..14).map(|k| u32::from_le_bytes(d[k * 4..k * 4 + 4].try_into().unwrap())).collect(); + crate::xlog_warn!("D3D12.X: CreatePlacedResourceX refused ({hr:#x}) state {state:#x} desc {words:08x?}"); + let mut plain = d; + let h = u32::from_le_bytes(plain[0x18..0x1C].try_into().unwrap()).max(1); + plain[0x18..0x1C].copy_from_slice(&h.to_le_bytes()); + plain[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + plain[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + plain[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + plain[0x28..0x2C].fill(0); + plain[0x30..0x34].copy_from_slice(&4u32.to_le_bytes()); + let desc = aligned_desc(&plain); + hr = real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, &desc as *const _ as usize, 0, 0, riid, ppv); + if hr < 0 { + plain[0x30..0x34].fill(0); + let desc = aligned_desc(&plain); + hr = real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, &desc as *const _ as usize, 0, 0, riid, ppv); + } + } if hr >= 0 && !buffer && !(*ppv).is_null() { static M: AtomicU64 = AtomicU64::new(0); match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { @@ -945,6 +1143,11 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi let needs_root = list.iter().any(|a| (5..=8).contains(&a[0])); pc[8..16].copy_from_slice(&(if list.is_empty() { 0 } else { list.as_ptr() as u64 }).to_le_bytes()); let hr = real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv); + static N: AtomicU64 = AtomicU64::new(0); + if hr < 0 && N.fetch_add(1, Ordering::Relaxed) < 6 { + let kinds: Vec = list.iter().map(|a| a[0]).collect(); + crate::xlog_warn!("D3D12.X: CreateCommandSignature {hr:#x} args {kinds:?} root {root:#x}"); + } if hr >= 0 && !ppv.is_null() && needs_root { super::bind::note_root_changing_signature(*ppv as usize); } @@ -968,13 +1171,30 @@ mod tests { x[0x30..0x34].copy_from_slice(&0x1234u32.to_le_bytes()); let d = pc_resource_desc(&x); assert_eq!((d[8], u32::from_le_bytes(d[0x2C..0x30].try_into().unwrap()), u32::from_le_bytes(d[0x30..0x34].try_into().unwrap())), (0, 1, 0x34)); + x[0x20..0x24].copy_from_slice(&53u32.to_le_bytes()); + x[0x30..0x34].copy_from_slice(&0x8030_0006u32.to_le_bytes()); + let made = pc_resource_desc(&x); + // depth and UAV together: R16_TYPELESS becomes a D16 depth buffer + assert_eq!(u32::from_le_bytes(made[0x30..0x34].try_into().unwrap()), 2); + assert_eq!(u32::from_le_bytes(made[0x20..0x24].try_into().unwrap()), 55); + assert_eq!(born_state(0x2, 0xC0), 0x10); + assert_eq!(born_state(0x4, 0xC0), 0xC0); + assert_eq!(initial_state(53, 0x4, 0x8), 0); x[0] = 3; // texture 2D assert_eq!(u32::from_le_bytes(pc_resource_desc(&x)[0x2C..0x30].try_into().unwrap()), 0); x[0x20..0x24].copy_from_slice(&118u32.to_le_bytes()); - assert_eq!(u32::from_le_bytes(pc_resource_desc(&x)[0x20..0x24].try_into().unwrap()), 45); + let mapped = pc_resource_desc(&x); + assert_eq!(u32::from_le_bytes(mapped[0x20..0x24].try_into().unwrap()), 45); + assert_eq!(u32::from_le_bytes(mapped[0x24..0x28].try_into().unwrap()), 1); + x[0x10..0x18].copy_from_slice(&256u64.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&256u32.to_le_bytes()); + x[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + let (size, align) = finite_allocation(&x).unwrap(); + assert!(size > 0 && size <= u32::MAX as u64 && align == 0x10000); x[0x20..0x24].copy_from_slice(&119u32.to_le_bytes()); assert_eq!(u32::from_le_bytes(pc_resource_desc(&x)[0x20..0x24].try_into().unwrap()), 44); assert_eq!((pc_dsv_format(118), pc_srv_format(119), pc_srv_format(120)), (45, 46, 47)); + assert_eq!(pc_color_format(65), 28); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index a8cc75d57..ae77b190b 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1,10 +1,10 @@ -//! Non-blocking pipeline creation. Translating a console shader takes milliseconds; compiling -//! the HLSL with DXC takes 0.2 s to seconds, and a title creates thousands of pipelines while -//! it loads. When a pipeline's DXIL is not in the disk cache yet, the title gets a stand-in -//! pipeline (shaders that draw nothing) at once and the real one is built on a worker; binding -//! (`SetPipelineState`, console list replay, the two-pass lookups) uses the real one as soon -//! as it is there. A graphics pipeline draws nothing until then; a compute pipeline is waited -//! for at its first bind (a skipped dispatch would corrupt what it computes). +//! Non-blocking pipeline creation. A title creates thousands of pipelines while it loads. +//! Translating a console shader is milliseconds from the cache and a long DXC compile when it +//! is not; the driver's compile of that DXIL is the slow part either way. The title gets a +//! stand-in pipeline (shaders that draw nothing) at once and the real one is built on a +//! worker; binding (`SetPipelineState`, console list replay, the two-pass lookups) uses the +//! real one as soon as it is there. A graphics pipeline draws nothing until then; a compute +//! pipeline is waited for at its first bind (a skipped dispatch would corrupt what it computes). //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::HashMap; @@ -84,7 +84,7 @@ pub fn submit(standin: usize, compute: bool, job: Job) { PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { - crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); + crate::xlog_info!("D3D12.X: pipeline creation returns at once; shader and driver compiles run in the background"); }); let _ = queue().lock().unwrap().send((p, job)); } @@ -143,6 +143,82 @@ pub fn is_pending(pso: usize) -> bool { entry(pso).is_some_and(|p| !*p.done.lock().unwrap()) } +/// How many uncached driver compiles may run at once. Each one fans out across the GPU +/// driver's own compiler, so a few of them already fill the machine; more of them fight +/// over the same cores and the load takes longer. `XCL_PSO_COMPILES` overrides it. +fn driver_compile_limit() -> usize { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| { + let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); + std::env::var("XCL_PSO_COMPILES").ok().and_then(|v| v.parse().ok()).unwrap_or((cores / 4).clamp(2, 4)) + }) +} + +struct DriverGate { + /// compiles in the driver, and whether a resource create wants the driver to itself + running: Mutex<(usize, bool)>, + cv: Condvar, +} + +fn driver_gate() -> &'static DriverGate { + static G: OnceLock = OnceLock::new(); + G.get_or_init(|| DriverGate { running: Mutex::new((0, false)), cv: Condvar::new() }) +} + +/// Hold the driver until the in-flight pipeline compiles finish, and keep new ones from +/// starting. A resource create overlapping a pipeline compile removes the device on this GPU. +pub struct DriverQuiet; + +impl Drop for DriverQuiet { + fn drop(&mut self) { + let g = driver_gate(); + let mut n = g.running.lock().unwrap(); + n.1 = false; + g.cv.notify_all(); + } +} + +pub fn quiet_driver() -> DriverQuiet { + let g = driver_gate(); + let mut n = g.running.lock().unwrap(); + n.1 = true; + if n.0 > 0 { + crate::xlog_info!("D3D12.X: waiting for {} pipeline compile(s) before creating a resource", n.0); + } + while n.0 > 0 { + n = g.cv.wait(n).unwrap(); + } + DriverQuiet +} + +/// Held across one driver compile of a pipeline the cache did not have. +pub struct DriverGuard; + +impl Drop for DriverGuard { + fn drop(&mut self) { + let g = driver_gate(); + let mut n = g.running.lock().unwrap(); + n.0 = n.0.saturating_sub(1); + g.cv.notify_all(); + } +} + +/// Block until fewer than `driver_compile_limit` uncached driver compiles are running. +pub fn uncached_compile() -> DriverGuard { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + crate::xlog_info!("D3D12.X: up to {} new pipelines compile in the driver at once", driver_compile_limit()); + }); + let g = driver_gate(); + let limit = driver_compile_limit(); + let mut n = g.running.lock().unwrap(); + while n.1 || n.0 >= limit { + n = g.cv.wait(n).unwrap(); + } + n.0 += 1; + DriverGuard +} + /// (built in the background, failed, still building) pub fn counts() -> (usize, usize, usize) { let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); diff --git a/crates/xcl/src/hle/d3d12x/pso_disk.rs b/crates/xcl/src/hle/d3d12x/pso_disk.rs index c950989d0..7d1d2ea36 100644 --- a/crates/xcl/src/hle/d3d12x/pso_disk.rs +++ b/crates/xcl/src/hle/d3d12x/pso_disk.rs @@ -55,13 +55,7 @@ pub fn load(key: u64) -> Option>> { Some(blob) } -/// Write `blob` so the next launch can reuse this driver's compile. -pub fn store(key: u64, blob: &[u8]) { - if blob.is_empty() || blob.len() > 32 << 20 { - return; - } - let owned = std::sync::Arc::new(blob.to_vec()); - memory().lock().unwrap().insert(key, owned); +fn write_file(key: u64, blob: &[u8]) { let dir = dir(); if std::fs::create_dir_all(&dir).is_err() { return; @@ -75,10 +69,33 @@ pub fn store(key: u64, blob: &[u8]) { body.extend_from_slice(&VERSION.to_le_bytes()); body.extend_from_slice(blob); let tmp = path.with_extension(format!("tmp{}", std::process::id())); - if std::fs::write(&tmp, &body).is_ok() { - if std::fs::rename(&tmp, &path).is_err() { - let _ = std::fs::remove_file(&tmp); - } + if std::fs::write(&tmp, &body).is_ok() && std::fs::rename(&tmp, &path).is_err() { + let _ = std::fs::remove_file(&tmp); + } +} + +fn writer() -> &'static std::sync::mpsc::SyncSender<(u64, std::sync::Arc>)> { + static W: OnceLock>)>> = OnceLock::new(); + W.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::sync_channel::<(u64, std::sync::Arc>)>(64); + let _ = std::thread::Builder::new().name("xcl-pso-cache".into()).spawn(move || { + while let Ok((key, blob)) = rx.recv() { + write_file(key, &blob); + } + }); + tx + }) +} + +/// Remember `blob` now and write it on a side thread, so a driver compile is not stuck on disk. +pub fn store(key: u64, blob: &[u8]) { + if blob.is_empty() || blob.len() > 32 << 20 { + return; + } + let owned = std::sync::Arc::new(blob.to_vec()); + memory().lock().unwrap().insert(key, owned.clone()); + if let Err(std::sync::mpsc::TrySendError::Full((_, blob))) = writer().try_send((key, owned)) { + write_file(key, &blob); } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 98508b194..2bf1a3846 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1779,6 +1779,28 @@ fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) { super::present::note_use(res as usize, super::present::USE_UAV); + // A depth buffer the console also marks as a UAV has no UAV flag on the PC. A view of + // that resource removes the device; a null view does not. Typed formats are not rewritten. + let null_view; + let (res, counter, desc) = match ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()) { + Some(rd) if rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 => { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "D3D12.X: UAV of a resource without unordered access ({}x{}, format {}, flags {:#x}) – a null view", + rd.Width, rd.Height, rd.Format.0, rd.Flags.0 + ); + } + let mut d = desc.as_ref().copied().unwrap_or(D3D12_UNORDERED_ACCESS_VIEW_DESC { + ViewDimension: D3D12_UAV_DIMENSION(resource_dim_to_view(&rd)), + ..Default::default() + }); + d.Format = dxgi(42); + null_view = d; + (std::ptr::null_mut(), std::ptr::null_mut(), &null_view as *const D3D12_UNORDERED_ACCESS_VIEW_DESC) + } + _ => (res, counter, desc), + }; let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 19)); if super::present::trace_frame() { let d = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()); @@ -2757,8 +2779,19 @@ fn note_driver_cache(saved: bool) { } } +static PSO_DEVICE_REMOVED: AtomicBool = AtomicBool::new(false); + +fn device_is_removed(_this: *mut c_void) -> bool { + PSO_DEVICE_REMOVED.load(Ordering::Acquire) +} + +fn note_device_removed() { + PSO_DEVICE_REMOVED.store(true, Ordering::Release); +} + /// Create `desc` (a graphics or compute pipeline desc). A blob saved for `key` is tried -/// first; the driver's own blob is written when this compile is new. +/// first; the driver's own blob is written when this compile is new. A cache hit does not +/// take a driver-compile slot. A miss does, so only a few new pipelines compile at once. unsafe fn finish_pso_cached(this: *mut c_void, f: PsoFn, desc: *mut c_void, graphics: bool, key: u64, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let loaded = super::pso_disk::load(key); let apply = |blob: &[u8]| { @@ -2771,16 +2804,54 @@ unsafe fn finish_pso_cached(this: *mut c_void, f: PsoFn, desc: *mut c_void, grap }; if let Some(blob) = &loaded { apply(blob); - } - let mut hr = finish_pso(this, f, desc, riid, ppv); - if hr < 0 && loaded.is_some() { + let hr = finish_pso(this, f, desc, riid, ppv); + if hr >= 0 { + note_driver_cache(false); + return hr; + } + if (hr as u32) & 0xFFFF_0000 == 0x887A_0000 { + note_device_removed(); + return hr; + } super::pso_disk::forget(key); apply(&[]); - hr = finish_pso(this, f, desc, riid, ppv); - } else if hr >= 0 && loaded.is_some() { - note_driver_cache(false); } - if hr >= 0 && loaded.is_none() && !ppv.is_null() && !(*ppv).is_null() { + if device_is_removed(this) { + return 0x887A_0005u32 as HRESULT; + } + // A cache miss reaches the GPU compiler. Two of those compiles remove the device from + // inside the call (0x887A0001): one graphics pipeline, and the first new compute shader. + // Cached pipelines still load above. The title already holds a stand-in for a miss. + if key == 0x94a63ac3f96c98ac || !graphics { + static ONCE: AtomicBool = AtomicBool::new(false); + if !graphics { + if !ONCE.swap(true, Ordering::Relaxed) { + crate::xlog_warn!("D3D12.X: new compute pipelines stay stand-ins; compiling them removes the device"); + } + } else { + crate::xlog_warn!("D3D12.X: pipeline {key:016x} is not compiled: it removes the device"); + } + return E_INVALIDARG; + } + let _guard = super::pso_async::uncached_compile(); + if graphics { + let g = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + let n = (g.NumRenderTargets as usize).min(8); + crate::xlog_info!( + "D3D12.X: driver compile {key:016x} RTs {} {:?} DSV {} samples {}", + g.NumRenderTargets, + &g.RTVFormats[..n].iter().map(|f| f.0).collect::>(), + g.DSVFormat.0, + g.SampleDesc.Count + ); + } else { + crate::xlog_info!("D3D12.X: driver compile {key:016x} compute"); + } + let hr = finish_pso(this, f, desc, riid, ppv); + if (hr as u32) & 0xFFFF_0000 == 0x887A_0000 { + note_device_removed(); + } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { if let Some(blob) = driver_blob(*ppv) { super::pso_disk::store(key, &blob); note_driver_cache(true); @@ -2909,6 +2980,12 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi if !is_console(cs) { return None; } + // Driver compile of a pipeline is the slow part, cached DXIL or not. The title gets a + // stand-in; a worker does this same call without `cached_only`. + if crate::gpu::recomp::dxc::in_cached_only() { + crate::gpu::recomp::dxc::defer_to_worker(); + return None; + } let compiled = match console_to_dxil_for(cs, Stage::Compute, 0, wave32_only(this)) { Ok(b) => b, Err(e) => { @@ -2954,6 +3031,12 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo note_translation_error("PSO with HS/DS – not supported yet".into()); return None; } + // Driver compile of a pipeline is the slow part, cached DXIL or not. The title gets a + // stand-in; a worker does this same call without `cached_only`. + if crate::gpu::recomp::dxc::in_cached_only() { + crate::gpu::recomp::dxc::defer_to_worker(); + return None; + } if let Some(gs) = shader_bytes(&d.GS).filter(|g| is_console(g)) { let _ = f; return Some(translated_gs_pso(this, d, vs, gs, riid, ppv)); @@ -3003,10 +3086,12 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo let hr = finish_pso_cached(this, f, &mut copy as *mut _ as *mut c_void, true, key, riid, ppv); if hr < 0 { note_translation_error(format!( - "the driver rejected the PSO with the translated shaders ({hr:#x}; topology type {}, {} render targets, DSV format {}, HS {}, GS {})", + "the driver rejected the PSO with the translated shaders ({hr:#x}; topology type {}, {} render targets {:?}, DSV format {}, samples {}, HS {}, GS {})", copy.PrimitiveTopologyType.0, copy.NumRenderTargets, + ©.RTVFormats[..(copy.NumRenderTargets as usize).min(8)].iter().map(|f| f.0).collect::>(), copy.DSVFormat.0, + copy.SampleDesc.Count, !copy.HS.pShaderBytecode.is_null(), !copy.GS.pShaderBytecode.is_null() )); @@ -3194,6 +3279,9 @@ unsafe fn standin_graphics(this: *mut c_void, f: PsoFn, desc: *const c_void, rii copy.StreamOutput = std::mem::zeroed(); copy.InputLayout = D3D12_INPUT_LAYOUT_DESC::default(); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + // the title's formats (A8, Xbox depth) are not the PC's; a stand-in built with them + // removes the device before the real pipeline is compiled + pc_pso_formats(&mut copy); finish_pso(this, f, © as *const _ as *const c_void, riid, ppv) } @@ -3513,6 +3601,10 @@ unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: * note_translation_error("mesh pipeline with AS – not supported yet".into()); return Some(E_INVALIDARG); } + if crate::gpu::recomp::dxc::in_cached_only() { + crate::gpu::recomp::dxc::defer_to_worker(); + return None; + } let ps = subs.iter().find(|s| s.0 == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32).and_then(|s| payload_shader(s.1)); let (tp, (ps, ps_samplers)) = match (console_mesh(ms, ps, wave32_only(this)), two_pass_ps(ps, wave32_only(this))) { (Ok(tp), Ok(ps)) => (tp, ps), @@ -3668,9 +3760,56 @@ fn dxgi(format: u32) -> windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT { } fn pc_pso_formats(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) { - g.DSVFormat = dxgi(super::device_x::pc_dsv_format(g.DSVFormat.0 as u32)); - for f in &mut g.RTVFormats { - *f = dxgi(super::device_x::pc_color_format(f.0 as u32)); + // A typeless format, or an Xbox-only one, in a pipeline is an invalid call. On this GPU + // that removes the device (0x887A0001) instead of returning E_INVALIDARG, and every later + // create fails the same way. Only illegal formats change, so a pipeline the driver already + // accepted keeps its cache key. + g.DSVFormat = dxgi(typed_dsv(super::device_x::pc_dsv_format(g.DSVFormat.0 as u32))); + let n = (g.NumRenderTargets as usize).min(g.RTVFormats.len()); + for f in &mut g.RTVFormats[..n] { + *f = dxgi(typed_rtv(super::device_x::pc_color_format(f.0 as u32))); + } + if g.SampleDesc.Count == 0 { + g.SampleDesc.Count = 1; + g.SampleDesc.Quality = 0; + } +} + +/// A render-target format the PC accepts. Typeless and the Xbox depth family are not. +fn typed_rtv(format: u32) -> u32 { + match format { + 1 => 2, // R32G32B32A32 + 5 => 6, // R32G32B32 + 9 => 10, // R16G16B16A16 + 15 => 16, // R32G32 + 23 => 24, // R10G10B10A2 + 27 => 28, // R8G8B8A8 + 33 => 35, // R16G16 + 39 => 40, // R32 + 44 | 118 | 119 | 120 => 28, + 48 => 49, // R8G8 + 53 => 54, // R16 + 60 => 61, // R8 + 70 => 71, // BC1 + 73 => 74, // BC2 + 76 => 77, // BC3 + 79 => 80, // BC4 + 82 => 83, // BC5 + 95 => 96, // BC6H + 98 => 99, // BC7 + other => other, + } +} + +/// A depth format the PC accepts. Anything else is no depth view, which the driver allows. +fn typed_dsv(format: u32) -> u32 { + match format { + 0 => 0, + 19 | 20 => 20, // D32_FLOAT_S8X24 + 39 | 41 => 41, // D32_FLOAT + 44 | 45 | 118 | 119 => 45, // D24_UNORM_S8 + 53 | 55 => 55, // D16_UNORM + other => other, } } @@ -3909,6 +4048,10 @@ unsafe extern "system" fn dev_create_dsv(this: *mut c_void, res: *mut c_void, de let desc = if !desc.is_null() && crate::gpu::shader::readable(desc as usize, 64) { std::ptr::copy_nonoverlapping(desc as *const u8, copy.as_mut_ptr(), 64); let format = u32::from_le_bytes(copy[..4].try_into().unwrap()); + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!("D3D12.X: DSV format {format} of {res:p}"); + } copy[..4].copy_from_slice(&super::device_x::pc_dsv_format(format).to_le_bytes()); copy.as_ptr() as *const c_void } else { diff --git a/crates/xcl/src/hle/netoff.rs b/crates/xcl/src/hle/netoff.rs index f8ffba0d8..a7ee537ed 100644 --- a/crates/xcl/src/hle/netoff.rs +++ b/crates/xcl/src/hle/netoff.rs @@ -22,9 +22,22 @@ extern "system" { fn real_connect(s: usize, name: *const u8, len: i32) -> i32; #[link_name = "sendto"] fn real_sendto(s: usize, buf: *const u8, len: i32, flags: i32, to: *const u8, tolen: i32) -> i32; + #[link_name = "getaddrinfo"] + fn real_getaddrinfo(node: *const u8, service: *const u8, hints: *const c_void, out: *mut *mut c_void) -> i32; + #[link_name = "GetAddrInfoW"] + fn real_getaddrinfo_w(node: *const u16, service: *const u16, hints: *const c_void, out: *mut *mut c_void) -> i32; + #[link_name = "GetAddrInfoExW"] + fn real_getaddrinfo_ex(n: *const u16, s: *const u16, ns: u32, id: *const c_void, hints: *const c_void, out: *mut *mut c_void, t: *const c_void, ov: *mut c_void, cb: *const c_void, h: *mut c_void) -> i32; + #[link_name = "freeaddrinfo"] + fn real_freeaddrinfo(p: *mut c_void); fn WSASetLastError(e: i32); + fn WSAStartup(version: u16, data: *mut u8) -> i32; } +/// Numeric loopback. Resolving this does not ask DNS. +const LOOPBACK: &[u8] = b"127.0.0.1\0"; +const LOOPBACK_W: &[u16] = &[b'1' as u16, b'2' as u16, b'7' as u16, b'.' as u16, b'0' as u16, b'.' as u16, b'0' as u16, b'.' as u16, b'1' as u16, 0]; + pub fn enabled() -> bool { std::env::var("XCL_NETWORK").is_ok_and(|v| v.trim() == "0") } @@ -39,7 +52,7 @@ fn table() -> Vec<(&'static str, usize, u16)> { ("WSAConnect", wsa_connect as *const () as usize, 0), ("WSASendTo", wsa_send_to as *const () as usize, 0), ("getaddrinfo", getaddrinfo as *const () as usize, 0), - ("GetAddrInfoW", getaddrinfo as *const () as usize, 0), + ("GetAddrInfoW", getaddrinfo_w as *const () as usize, 0), ("GetAddrInfoExW", getaddrinfo_ex as *const () as usize, 0), ] } @@ -52,13 +65,17 @@ pub fn ordinals() -> Vec<(u16, &'static str)> { table().into_iter().filter(|t| t.2 != 0).map(|(n, _, o)| (o, n)).collect() } -fn note(what: &str) { +fn note_msg(msg: &str) { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 16 { - crate::xlog_info!("XCL_NETWORK=0: {what} fails (no network)"); + crate::xlog_info!("XCL_NETWORK=0: {msg}"); } } +fn note(what: &str) { + note_msg(&format!("{what} fails (no network)")); +} + /// 127.0.0.0/8 or ::1 (sockaddr_in / sockaddr_in6) unsafe fn loopback(name: *const u8, len: i32) -> bool { if name.is_null() || len < 8 { @@ -115,21 +132,95 @@ unsafe extern "system" fn gethostbyname(_name: *const u8) -> *mut c_void { std::ptr::null_mut() } -unsafe extern "system" fn getaddrinfo(_node: *const c_void, _service: *const c_void, _hints: *const c_void, out: *mut *mut c_void) -> i32 { - note("getaddrinfo"); +unsafe fn ansi_bytes<'a>(node: *const u8) -> &'a [u8] { + if node.is_null() { + return b""; + } + let mut n = 0; + while n < 255 && *node.add(n) != 0 { + n += 1; + } + std::slice::from_raw_parts(node, n) +} + +fn local_ansi(node: *const u8) -> bool { + let s = unsafe { ansi_bytes(node) }; + node.is_null() || s.is_empty() || s.eq_ignore_ascii_case(b"localhost") || s == b"127.0.0.1" || s == b"::1" +} + +unsafe fn wide_bytes<'a>(node: *const u16) -> &'a [u16] { + if node.is_null() { + return &[]; + } + let mut n = 0; + while n < 255 && *node.add(n) != 0 { + n += 1; + } + std::slice::from_raw_parts(node, n) +} + +fn wide_is(s: &[u16], ascii: &[u8]) -> bool { + s.len() == ascii.len() && s.iter().zip(ascii).all(|(c, a)| *c < 128 && (*c as u8).eq_ignore_ascii_case(a)) +} + +fn local_wide(node: *const u16) -> bool { + let s = unsafe { wide_bytes(node) }; + node.is_null() || s.is_empty() || wide_is(s, b"localhost") || wide_is(s, b"127.0.0.1") || wide_is(s, b"::1") +} + +/// A name that is not local, answered as loopback. The real resolver does this without DNS, +/// so a title that retries a failed lookup does not sit there. `connect` still refuses it +/// unless the title is talking to itself. +unsafe fn loopback_ansi(service: *const u8, hints: *const c_void, out: *mut *mut c_void) -> i32 { + let hr = real_getaddrinfo(LOOPBACK.as_ptr(), service, hints, out); + if hr == 0 { + return 0; + } + let hr6 = real_getaddrinfo(b"::1\0".as_ptr(), service, hints, out); + if hr6 == 0 { + return 0; + } if !out.is_null() { *out = std::ptr::null_mut(); } - WSAHOST_NOT_FOUND + hr } -#[allow(clippy::too_many_arguments)] -unsafe extern "system" fn getaddrinfo_ex(_n: *const u16, _s: *const u16, _ns: u32, _id: *const c_void, _hints: *const c_void, out: *mut *mut c_void, _t: *const c_void, _ov: *mut c_void, _cb: *const c_void, _h: *mut c_void) -> i32 { - note("GetAddrInfoExW"); +unsafe extern "system" fn getaddrinfo(node: *const u8, service: *const u8, hints: *const c_void, out: *mut *mut c_void) -> i32 { + if local_ansi(node) { + return real_getaddrinfo(node, service, hints, out); + } + note_msg("getaddrinfo answers 127.0.0.1"); + loopback_ansi(service, hints, out) +} + +unsafe extern "system" fn getaddrinfo_w(node: *const u16, service: *const u16, hints: *const c_void, out: *mut *mut c_void) -> i32 { + if local_wide(node) { + return real_getaddrinfo_w(node, service, hints, out); + } + note_msg("GetAddrInfoW answers 127.0.0.1"); + let hr = real_getaddrinfo_w(LOOPBACK_W.as_ptr(), service, hints, out); + if hr == 0 { + return 0; + } + const LOOPBACK6_W: &[u16] = &[b':' as u16, b':' as u16, b'1' as u16, 0]; + let hr6 = real_getaddrinfo_w(LOOPBACK6_W.as_ptr(), service, hints, out); + if hr6 == 0 { + return 0; + } if !out.is_null() { *out = std::ptr::null_mut(); } - WSAHOST_NOT_FOUND + hr +} + +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn getaddrinfo_ex(n: *const u16, s: *const u16, ns: u32, id: *const c_void, hints: *const c_void, out: *mut *mut c_void, t: *const c_void, ov: *mut c_void, cb: *const c_void, h: *mut c_void) -> i32 { + let name = if local_wide(n) { n } else { LOOPBACK_W.as_ptr() }; + if name != n { + note_msg("GetAddrInfoExW answers 127.0.0.1"); + } + real_getaddrinfo_ex(name, s, ns, id, hints, out, t, ov, cb, h) } #[cfg(test)] @@ -150,6 +241,12 @@ mod tests { assert!(!loopback(v6.as_ptr(), 28)); assert_eq!(connect(usize::MAX, v4([8, 8, 8, 8]).as_ptr(), 16), -1); assert_eq!(send_request(std::ptr::null_mut(), std::ptr::null(), 0, std::ptr::null(), 0, 0, 0), 0); + let mut wsa = [0u8; 512]; + assert_eq!(WSAStartup(0x0202, wsa.as_mut_ptr()), 0); + let mut out = std::ptr::null_mut(); + assert_eq!(getaddrinfo(b"example.invalid\0".as_ptr(), std::ptr::null(), std::ptr::null(), &mut out), 0); + assert!(!out.is_null()); + real_freeaddrinfo(out); } } } diff --git a/crates/xcl/src/hle/user.rs b/crates/xcl/src/hle/user.rs index 3f4738825..191ec6e48 100644 --- a/crates/xcl/src/hle/user.rs +++ b/crates/xcl/src/hle/user.rs @@ -67,6 +67,15 @@ unsafe fn name(p: *const u8, keep: &mut Vec>) -> *const u16 { keep.last().unwrap().as_ptr() } +#[link(name = "kernel32")] +extern "system" { + fn GetLastError() -> u32; +} + +/// Atoms this process registered, so a second RegisterClassExA of the same name still returns +/// the atom. Windows answers the second call with 0, and the title stops on that. +static CLASS_ATOMS: std::sync::Mutex, u16)>> = std::sync::Mutex::new(Vec::new()); + pub unsafe extern "system" fn RegisterClassExA(c: *const WndClassEx) -> u16 { if c.is_null() { return 0; @@ -87,7 +96,28 @@ pub unsafe extern "system" fn RegisterClassExA(c: *const WndClassEx) -> u16 class_name: name(c.class_name, &mut keep), icon_small: c.icon_small, }; - RegisterClassExW(&w) + let class_key = ((c.class_name as usize) >= 0x1_0000).then(|| keep.last().cloned().unwrap_or_default()).unwrap_or_default(); + if !class_key.is_empty() { + if let Some(atom) = CLASS_ATOMS.lock().unwrap().iter().find(|(n, _)| n == &class_key).map(|(_, a)| *a) { + return atom; + } + } + let atom = RegisterClassExW(&w); + if atom != 0 { + if !class_key.is_empty() { + CLASS_ATOMS.lock().unwrap().push((class_key, atom)); + } + return atom; + } + let err = GetLastError(); + // ERROR_CLASS_ALREADY_EXISTS: the class is registered, the title only tests the atom is non-zero + if err == 1410 { + crate::xlog_info!("user: RegisterClassExA: class already registered"); + return 1; + } + let shown = if class_key.is_empty() { String::new() } else { String::from_utf16_lossy(&class_key) }; + crate::xlog_warn!("user: RegisterClassExA failed ({err}) for '{shown}'"); + 0 } #[allow(clippy::too_many_arguments)] @@ -140,8 +170,14 @@ unsafe fn console_window(ex_style: u32, class: *const u16, title: *const u16, st } let style = style & !WS_FRAME | WS_POPUP; let ex_style = ex_style & !WS_EX_FRAME & !WS_EX_APPWINDOW | WS_EX_TOOLWINDOW; - let hwnd = CreateWindowExW(ex_style, class, title, style, 0, 0, CONSOLE_W, CONSOLE_H, parent, menu, instance, param); + let mut hwnd = CreateWindowExW(ex_style, class, title, style, 0, 0, CONSOLE_W, CONSOLE_H, parent, menu, instance, param); + if hwnd.is_null() { + let err = GetLastError(); + crate::xlog_warn!("user: CreateWindowEx failed ({err:#x}) style {style:#x} parent {parent:p}; retrying without a parent"); + hwnd = CreateWindowExW(ex_style, class, title, style, 0, 0, CONSOLE_W, CONSOLE_H, std::ptr::null_mut(), std::ptr::null_mut(), instance, param); + } if hwnd.is_null() { + crate::xlog_warn!("user: CreateWindowEx retry failed ({:#x})", GetLastError()); return hwnd; } let cloak: i32 = 1; diff --git a/crates/xcl/src/hle/xg.rs b/crates/xcl/src/hle/xg.rs index 234f96492..09a798fe8 100644 --- a/crates/xcl/src/hle/xg.rs +++ b/crates/xcl/src/hle/xg.rs @@ -155,8 +155,9 @@ impl Texture { if width == 0 || width > 16384 || height == 0 || height > 16384 || array == 0 { return Err(E_INVALIDARG); } - // depth + stencil formats: a 4-byte depth plane and a 1-byte stencil plane - let planar = matches!(format, 19..=22 | 44..=47); + // depth + stencil formats: a 4-byte depth plane and a 1-byte stencil plane. + // 118–120 are the Xbox D16+stencil family; the PC resource is D24+stencil, same planes. + let planar = matches!(format, 19..=22 | 44..=47 | 118..=120); let (e, side) = if planar { (2, 1) } else { element(format).ok_or(E_INVALIDARG)? }; let mode = match layout { 1 => 0, diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 83ed10292..149633299 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -34,6 +34,10 @@ Usage: for the recompiler). RPF9 packages are scanned for shader records. --recomp: translates every RDNA2 program → HLSL and shows what is missing; --compile N: additionally compiles N complete translations with DXC. + --precompile: translate every program into the DXIL cache (resumable). + --precompile --gentle: the same, plus each compute pipeline, a few at a time + (below-normal priority, four compile threads, two driver compiles). + --pause MS inserts a pause after a compile (default 0). Cached programs are skipped. xcl rpf [--top N] [--find NAME] [--extract NAME --out DIR] Lists or extracts readable inline records. Archives larger than 1 GB use a bounded-memory header probe; --probe requests it explicitly and --full overrides it. diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index ef4153908..7a7e2c4dc 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -713,7 +713,13 @@ pub fn run(path: &Path, args: &[String]) -> i32 { } }; if args.iter().any(|a| a == "--precompile") { - return precompile(&input, opt("--limit").unwrap_or(usize::MAX), opt("--windows").unwrap_or(4) as u32, opt("--split").map(|v| v != 0), t0); + let gentle = args.iter().any(|a| a == "--gentle"); + // a handful of DXC workers, before the pool reads the thread count + if gentle && std::env::var_os("XCL_DXC_THREADS").is_none() { + std::env::set_var("XCL_DXC_THREADS", "4"); + } + let pause = opt("--pause").unwrap_or(0); + return precompile(&input, opt("--limit").unwrap_or(usize::MAX), opt("--windows").unwrap_or(4) as u32, opt("--split").map(|v| v != 0), gentle, pause, t0); } let agg = analyze(&input, recomp_on, compile, iface_on); drop(input); @@ -731,23 +737,34 @@ pub fn run(path: &Path, args: &[String]) -> i32 { /// no split form, so a title asked for other HLSL and compiled everything again. Still /// 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. -fn precompile(input: &Input, limit: usize, windows: u32, split: Option, t0: std::time::Instant) -> i32 { +/// `--gentle` compiles with four threads at below-normal priority and builds two compute +/// pipelines at a time on its own device, so the driver cache fills without taking the machine. +fn precompile(input: &Input, limit: usize, windows: u32, split: Option, gentle: bool, pause_ms: usize, t0: std::time::Instant) -> i32 { let n = input.len().min(limit); let next = AtomicUsize::new(0); let (done, compiled, cached, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); let errors: Mutex> = Mutex::new(Vec::new()); // the compiles run on the DXC pool; these threads translate and keep it fed - let threads = recomp::dxc::compile_threads() + 2; + let threads = if gentle { 4 } else { recomp::dxc::compile_threads() + 2 }; let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w)); + if gentle { + bake_priority(); + } + let pipes = if gentle { Pipelines::new(2).map_err(|e| eprintln!("xcl shaders: pipelines stay for the game ({e})")).ok() } else { None }; println!( - "precompiling {n} shaders into {} ({} compile threads; {windows} memory windows{})", + "precompiling {n} shaders into {} ({} compile threads; {windows} memory windows{}{})", recomp::dxc::cache_dir().display(), - recomp::dxc::compile_threads(), - if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } + if gentle { 4 } else { recomp::dxc::compile_threads() }, + if split { ", split wave64 for a GPU with 32-lane waves" } else { "" }, + if gentle { ", two pipelines at a time" } else { "" } ); std::thread::scope(|s| { for _ in 0..threads { - s.spawn(|| loop { + s.spawn(|| { + if gentle { + bake_priority(); + } + loop { let i = next.fetch_add(1, Ordering::Relaxed); if i >= n { break; @@ -755,6 +772,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, t0 let (name, blob) = input.get(i); let Some(blob) = blob else { continue }; let Some(sh) = xbox::parse(&blob) else { continue }; + let mut busy = false; for f in &sh.fssm { let Some(mode) = recomp::interface(&blob, &sh, f) else { continue }; let jobs: Vec<(&str, Option)> = match &mode { @@ -778,23 +796,49 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, t0 } for (profile, src) in &jobs { match recomp::dxc::compile_cached(src.as_deref().unwrap_or(&t.hlsl), "main", profile) { - Ok((_, true)) => cached.fetch_add(1, Ordering::Relaxed), - Ok(_) => compiled.fetch_add(1, Ordering::Relaxed), + Ok((dxil, hit)) => { + if hit { + cached.fetch_add(1, Ordering::Relaxed); + } else { + compiled.fetch_add(1, Ordering::Relaxed); + busy = true; + } + if *profile == "cs_6_6" { + if let Some(p) = &pipes { + if !pipeline_baked(&dxil) && p.alive() && !dxil.is_empty() { + busy = true; + p.make_dxil(&dxil); + let _ = std::fs::write(pipeline_mark(&dxil), b""); + } + } + } + } Err(e) => { let mut g = errors.lock().unwrap(); if g.len() < 10 { g.push(format!("{name}: {}", e.lines().find(|l| l.contains("error")).unwrap_or(""))); } - failed.fetch_add(1, Ordering::Relaxed) + failed.fetch_add(1, Ordering::Relaxed); } }; } } } let d = done.fetch_add(1, Ordering::Relaxed) + 1; - if d % 200 == 0 { - eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); + if gentle && pause_ms > 0 && busy { + std::thread::sleep(std::time::Duration::from_millis(pause_ms as u64)); + } + if (gentle && d % 25 == 0) || (!gentle && d % 200 == 0) { + let pipes_n = pipes.as_ref().map(|p| p.counts()).unwrap_or((0, 0)); + eprintln!( + " {d}/{n} shaders, {} new, {} cached, {} pipelines ({:.0} s)", + compiled.load(Ordering::Relaxed), + cached.load(Ordering::Relaxed), + pipes_n.0, + t0.elapsed().as_secs_f64() + ); } + } }); } }); @@ -812,6 +856,150 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, t0 0 } +fn pipeline_mark(dxil: &[u8]) -> std::path::PathBuf { + let mut h: u64 = 0xcbf29ce484222325; + for b in dxil { + h ^= *b as u64; + h = h.wrapping_mul(0x100000001b3); + } + recomp::dxc::cache_dir().join(format!("baked-{h:016x}")) +} + +fn pipeline_baked(dxil: &[u8]) -> bool { + dxil.is_empty() || pipeline_mark(dxil).is_file() +} + +fn bake_priority() { + use windows::Win32::System::Threading::{GetCurrentProcess, GetCurrentThread, SetPriorityClass, SetThreadPriority, BELOW_NORMAL_PRIORITY_CLASS, THREAD_PRIORITY_BELOW_NORMAL}; + unsafe { + let _ = SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); + let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + } +} + +/// Compute pipelines on a device that is not the game's, `most` of them at once. The driver +/// keeps each one in its own cache. A removed device stops further pipelines; shaders still compile. +struct Pipelines { + dev: windows::Win32::Graphics::Direct3D12::ID3D12Device, + signatures: Mutex, windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, + made: AtomicUsize, + refused: AtomicUsize, + inflight: AtomicUsize, + most: usize, + dead: std::sync::atomic::AtomicBool, +} + +unsafe impl Sync for Pipelines {} + +impl Pipelines { + fn new(most: usize) -> Result { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::CreateDXGIFactory2; + use windows::Win32::Graphics::Dxgi::DXGI_CREATE_FACTORY_FLAGS; + unsafe { + let factory = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?; + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + 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())?; + Ok(Pipelines { + dev, + signatures: Mutex::new(Default::default()), + made: AtomicUsize::new(0), + refused: AtomicUsize::new(0), + inflight: AtomicUsize::new(0), + most: most.max(1), + dead: std::sync::atomic::AtomicBool::new(false), + }) + } + } + + fn alive(&self) -> bool { + !self.dead.load(Ordering::Relaxed) + } + + fn counts(&self) -> (usize, usize) { + (self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)) + } + + fn make(&self, c: &recomp::pso::Compiled) { + if !self.alive() { + return; + } + let key: Vec = c.samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect(); + let rs = { + let mut g = self.signatures.lock().unwrap(); + match g.get(&key) { + Some(rs) => rs.clone(), + None => match recomp::pso::abi_root_signature_with(&self.dev, true, &c.samplers) { + Ok(rs) => { + g.insert(key, rs.clone()); + rs + } + Err(_) => { + self.refused.fetch_add(1, Ordering::Relaxed); + return; + } + }, + } + }; + self.finish(rs, &c.dxil); + } + + fn make_dxil(&self, dxil: &[u8]) { + if !self.alive() || dxil.is_empty() { + return; + } + let key = Vec::new(); + let rs = { + let mut g = self.signatures.lock().unwrap(); + if let Some(rs) = g.get(&key) { + rs.clone() + } else { + match recomp::pso::abi_root_signature(&self.dev, true) { + Ok(rs) => { + g.insert(key, rs.clone()); + rs + } + Err(_) => { + self.refused.fetch_add(1, Ordering::Relaxed); + return; + } + } + } + }; + self.finish(rs, dxil); + } + + fn finish(&self, rs: windows::Win32::Graphics::Direct3D12::ID3D12RootSignature, dxil: &[u8]) { + use windows::Win32::Graphics::Direct3D12::*; + while self.inflight.load(Ordering::Relaxed) >= self.most { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + self.inflight.fetch_add(1, Ordering::Relaxed); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs)), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, + ..Default::default() + }; + let r: windows::core::Result = unsafe { self.dev.CreateComputePipelineState(&desc) }; + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + self.inflight.fetch_sub(1, Ordering::Relaxed); + match r { + Ok(_) => { + self.made.fetch_add(1, Ordering::Relaxed); + } + Err(e) => { + self.refused.fetch_add(1, Ordering::Relaxed); + let code = e.code().0 as u32; + if code & 0xFFFF0000 == 0x887A0000 { + self.dead.store(true, Ordering::Relaxed); + eprintln!("xcl shaders: pipeline compile removed the device ({code:#x}); shaders continue, pipelines stop"); + } + } + } + } +} + /// Compile the kept HLSL samples with DXC on all cores: (ok, failures with the first error line). fn compile_samples(samples: &[(String, String, &'static str)]) -> (usize, Vec) { let next = AtomicUsize::new(0);