From 4e8aaf4b393ce59d7053de987906a0f8a4aed476 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:41:20 -0800 Subject: [PATCH 01/13] D3D12.X: the PC desc of a translated VS / PS pipeline in its own function prep_graphics: what translated_graphics_pso did between its checks and the driver call (the translated shaders, XCL's ABI root signature with their static samplers, the rect list GS, PC formats and topology), returned with the DXIL it points at. No change in behaviour; a later change makes the same desc outside the title (xcl pipelines). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 67 +++++++++++++++++++------------ 1 file changed, 42 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ac7ab4c4d..ddfad69f7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3949,32 +3949,19 @@ unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: m.insert(key, std::sync::Arc::new(bytes)); } -unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { - with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) -} - -unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { +/// The PC desc of a pipeline with a console VS (and PS) and no GS / HS / DS: the translated +/// shaders, XCL's ABI root signature, PC formats and topology (`translated_graphics_pso`, apart +/// from making the pipeline). +struct GraphicsPrep { + desc: D3D12_GRAPHICS_PIPELINE_STATE_DESC, + rs: *mut c_void, + rect_gs: Option>, + /// the VS / PS DXIL `desc` points at + _dxil: (Vec, Option>), +} + +unsafe fn prep_graphics(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs: &[u8]) -> Option { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; - if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { - return None; - } - let d = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); - let vs = shader_bytes(&d.VS)?; - if !is_console(vs) { - return None; - } - if shader_bytes(&d.HS).is_some() || shader_bytes(&d.DS).is_some() { - note_translation_error("PSO with HS/DS – not supported yet".into()); - 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)); - } - // made when first used (`pso_async::lazy`): not even translated now - if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { - return None; - } // a GPU that can run 32-lane waves may run a wave64 VS / PS in waves of 32 (the driver // picks; RDNA2 does for pixel shaders): the lanes 32..63 it reads come from `upper_lanes` // (split_wave64) @@ -4019,6 +4006,36 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.GS = bytecode(gs); } pc_topology_type(&mut copy); + Some(GraphicsPrep { desc: copy, rs, rect_gs, _dxil: (vs_dxil, ps_dxil) }) +} + +unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) +} + +unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + use crate::gpu::recomp::pso::is_console; + if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return None; + } + let d = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + let vs = shader_bytes(&d.VS)?; + if !is_console(vs) { + return None; + } + if shader_bytes(&d.HS).is_some() || shader_bytes(&d.DS).is_some() { + note_translation_error("PSO with HS/DS – not supported yet".into()); + 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)); + } + // made when first used (`pso_async::lazy`): not even translated now + if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { + return None; + } + let GraphicsPrep { desc: mut copy, rs, rect_gs, _dxil } = prep_graphics(this, d, vs)?; 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(); From e62643edc429f85ac0525ea10816fe7920293eba Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:43:12 -0800 Subject: [PATCH 02/13] D3D12.X: a journal of the pipelines a title queues (\cache\pipelines.bin) Every pipeline with console shaders that goes to pso_async (its DXIL not in the cache yet, or made lazily: a retail title queues ~58 000 in its first minute) is appended to a journal: its desc field by field (no pointers, no padding: the same pipeline always hashes the same), its input layout and its shaders by hash, each shader once, with the run's memory windows. A pipeline's first build is marked as used. Entries of earlier runs are not written again (found from the frames' headers, the shaders stay on disk); a torn last frame is cut off. One title process writes it at a time (others get none). The reader (replay) gives the desc back with everything it points to owned and no pointer from the file. Another process can compile the title's pipelines from it; XCL_PSO_JOURNAL=0 turns it off. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/pso_journal.rs | 436 +++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 7 + 3 files changed, 444 insertions(+) create mode 100644 crates/xcl/src/hle/d3d12x/pso_journal.rs diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f3f035798..87c6ca901 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -25,6 +25,7 @@ pub mod list_x; pub mod null; pub mod present; pub mod pso_async; +pub mod pso_journal; pub mod real; mod shader_cache_session; pub mod sparse; diff --git a/crates/xcl/src/hle/d3d12x/pso_journal.rs b/crates/xcl/src/hle/d3d12x/pso_journal.rs new file mode 100644 index 000000000..788dbf87c --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pso_journal.rs @@ -0,0 +1,436 @@ +//! The pipelines a title asked for, on disk (`\cache\pipelines.bin`), so another process +//! can compile them: `xcl pipelines` reads the journal – during the run (`--watch`) or before +//! the next one – and fills the DXIL cache and the driver's with what the title will ask for. +//! Written for every pipeline with console shaders that goes to `pso_async` (its DXIL was not +//! in the cache, or it is made lazily); a pipeline's first build is marked as used, which the +//! tool compiles first. `XCL_PSO_JOURNAL=0`: off. +//! +//! Append-only frames, little-endian: tag u8, memory windows u8, 0 u16, payload length u32, +//! hash u64, payload. Tags: `S` a shader (its bytes; hash = fnv64 of them), `G` a graphics +//! pipeline, `C` a compute one, `U` (no payload) pipeline `hash` was built. A pipeline's +//! payload names its shaders by hash; each shader is written once, before the first pipeline +//! that uses it. Duplicates of earlier runs are not written again. + +use std::collections::HashSet; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use windows::Win32::Graphics::Direct3D12::*; + +pub const MAGIC: &[u8; 8] = b"XCLPJ001"; +pub const HEAD: usize = 16; + +pub fn path_in(data_dir: &Path) -> PathBuf { + data_dir.join("cache").join("pipelines.bin") +} + +struct Journal { + file: std::fs::File, + seen: HashSet<(u8, u64)>, +} + +static J: Mutex>> = Mutex::new(None); + +fn enabled() -> bool { + std::env::var("XCL_PSO_JOURNAL").map_or(true, |v| v != "0") +} + +fn open() -> Option { + use std::io::{Read, Seek, SeekFrom}; + use std::os::windows::fs::OpenOptionsExt; + if !enabled() { + return None; + } + let path = path_in(&crate::state::data_dir()); + let _ = std::fs::create_dir_all(path.parent()?); + // the only writer: another title process gets no journal (`xcl pipelines` only reads) + const FILE_SHARE_READ: u32 = 1; + let mut file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .share_mode(FILE_SHARE_READ) + .open(&path) + .map_err(|e| crate::xlog_warn!("pipeline journal {}: {e} – none in this run", path.display())) + .ok()?; + let mut seen = HashSet::new(); + let len = file.metadata().map_or(0, |m| m.len()); + let mut magic = [0u8; 8]; + if file.read_exact(&mut magic).is_ok() && &magic == MAGIC { + // the frames' headers only (the shaders' bytes stay on disk); a torn last frame (a + // run killed mid-write) is cut off + let mut at = MAGIC.len() as u64; + let mut head = [0u8; HEAD]; + while file.read_exact(&mut head).is_ok() { + let end = at + HEAD as u64 + u32::from_le_bytes(head[4..8].try_into().unwrap()) as u64; + if end > len { + break; + } + seen.insert((head[0], u64::from_le_bytes(head[8..16].try_into().unwrap()))); + at = end; + if file.seek(SeekFrom::Start(at)).is_err() { + break; + } + } + if at < len { + let _ = file.set_len(at); + } + } else { + let _ = file.set_len(0); + let _ = file.seek(SeekFrom::Start(0)); + let _ = file.write_all(MAGIC); + } + file.seek(SeekFrom::End(0)).ok()?; + crate::xlog_info!("pipeline journal: {} ({} entries from earlier runs) – `xcl pipelines` compiles them outside the title", path.display(), seen.len()); + Some(Journal { file, seen }) +} + +fn with(f: impl FnOnce(&mut Journal)) { + let mut g = J.lock().unwrap(); + if let Some(j) = g.get_or_insert_with(open).as_mut() { + f(j); + } +} + +fn frame(tag: u8, windows: u8, hash: u64, payload: &[u8]) -> Vec { + let mut v = Vec::with_capacity(HEAD + payload.len()); + v.extend_from_slice(&[tag, windows, 0, 0]); + v.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + v.extend_from_slice(&hash.to_le_bytes()); + v.extend_from_slice(payload); + v +} + +/// One frame of the journal. +pub struct Frame<'a> { + pub tag: u8, + pub windows: u8, + pub hash: u64, + pub payload: &'a [u8], +} + +/// Call `f` on each whole frame of `bytes` (a journal from its start); the end of the last whole one. +pub fn for_each_frame<'a>(bytes: &'a [u8], f: impl FnMut(Frame<'a>)) -> usize { + for_each_frame_from(bytes, MAGIC.len(), f) +} + +/// `for_each_frame` from offset `at` (the end of an earlier call: a journal being written). +pub fn for_each_frame_from<'a>(bytes: &'a [u8], mut at: usize, mut f: impl FnMut(Frame<'a>)) -> usize { + while at + HEAD <= bytes.len() { + let n = u32::from_le_bytes(bytes[at + 4..at + 8].try_into().unwrap()) as usize; + if at + HEAD + n > bytes.len() { + break; + } + f(Frame { tag: bytes[at], windows: bytes[at + 1], hash: u64::from_le_bytes(bytes[at + 8..at + 16].try_into().unwrap()), payload: &bytes[at + HEAD..at + HEAD + n] }); + at += HEAD + n; + } + at.min(bytes.len()) +} + +/// Copy each field named into `out` at its offset in `T`: a desc's bytes without its pointers +/// and padding (both stay 0), so the same pipeline always gives the same bytes and hash. +macro_rules! fields { + ($out:expr, $d:expr, $T:ty, $($($f:ident).+),+ $(,)?) => {{ + $(put_at(&mut $out, std::mem::offset_of!($T, $($f).+), &$d.$($f).+);)+ + }}; +} + +fn put_at(out: &mut [u8], off: usize, v: &V) { + let b = unsafe { std::slice::from_raw_parts(v as *const V as *const u8, std::mem::size_of::()) }; + out[off..off + b.len()].copy_from_slice(b); +} + +fn graphics_bytes(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Vec { + type G = D3D12_GRAPHICS_PIPELINE_STATE_DESC; + type R = D3D12_RENDER_TARGET_BLEND_DESC; + let mut out = vec![0u8; std::mem::size_of::()]; + fields!(out, d, G, BlendState.AlphaToCoverageEnable, BlendState.IndependentBlendEnable, SampleMask); + let rt0 = std::mem::offset_of!(G, BlendState.RenderTarget); + for (i, r) in d.BlendState.RenderTarget.iter().enumerate() { + let mut one = vec![0u8; std::mem::size_of::()]; + fields!(one, r, R, BlendEnable, LogicOpEnable, SrcBlend, DestBlend, BlendOp, SrcBlendAlpha, DestBlendAlpha, BlendOpAlpha, LogicOp, RenderTargetWriteMask); + let at = rt0 + i * one.len(); + out[at..at + one.len()].copy_from_slice(&one); + } + fields!( + out, d, G, + RasterizerState.FillMode, RasterizerState.CullMode, RasterizerState.FrontCounterClockwise, RasterizerState.DepthBias, + RasterizerState.DepthBiasClamp, RasterizerState.SlopeScaledDepthBias, RasterizerState.DepthClipEnable, + RasterizerState.MultisampleEnable, RasterizerState.AntialiasedLineEnable, RasterizerState.ForcedSampleCount, + RasterizerState.ConservativeRaster, + DepthStencilState.DepthEnable, DepthStencilState.DepthWriteMask, DepthStencilState.DepthFunc, DepthStencilState.StencilEnable, + DepthStencilState.StencilReadMask, DepthStencilState.StencilWriteMask, + DepthStencilState.FrontFace.StencilFailOp, DepthStencilState.FrontFace.StencilDepthFailOp, + DepthStencilState.FrontFace.StencilPassOp, DepthStencilState.FrontFace.StencilFunc, + DepthStencilState.BackFace.StencilFailOp, DepthStencilState.BackFace.StencilDepthFailOp, + DepthStencilState.BackFace.StencilPassOp, DepthStencilState.BackFace.StencilFunc, + InputLayout.NumElements, IBStripCutValue, PrimitiveTopologyType, NumRenderTargets, RTVFormats, DSVFormat, + SampleDesc.Count, SampleDesc.Quality, NodeMask, Flags, + ); + out +} + +fn compute_bytes(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> Vec { + type C = D3D12_COMPUTE_PIPELINE_STATE_DESC; + let mut out = vec![0u8; std::mem::size_of::()]; + fields!(out, d, C, NodeMask, Flags); + out +} + +unsafe fn bytes_of<'a>(b: &D3D12_SHADER_BYTECODE) -> Option<&'a [u8]> { + (!b.pShaderBytecode.is_null() && b.BytecodeLength != 0).then(|| std::slice::from_raw_parts(b.pShaderBytecode as *const u8, b.BytecodeLength)) +} + +fn put_shader(j: &mut Journal, out: &mut Vec, sh: Option<&[u8]>) -> std::io::Result<()> { + let h = sh.map_or(0, crate::gpu::shader::fnv64); + if let Some(sh) = sh { + if j.seen.insert((b'S', h)) { + j.file.write_all(&frame(b'S', 0, h, sh))?; + } + } + out.extend_from_slice(&h.to_le_bytes()); + Ok(()) +} + +fn finish(j: &mut Journal, tag: u8, mut payload: Vec) -> std::io::Result { + // the memory windows are part of what the pipeline is (its HLSL differs with them) + let windows = crate::gpu::recomp::pso::mem_windows() as u8; + payload.push(windows); + let hash = crate::gpu::shader::fnv64(&payload); + payload.pop(); + if j.seen.insert((tag, hash)) { + j.file.write_all(&frame(tag, windows, hash, &payload))?; + } + Ok(hash) +} + +/// Note a graphics pipeline; its hash for `used`, 0 = not written. +pub unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> u64 { + let mut hash = 0; + with(|j| hash = graphics_in(j, d).unwrap_or(0)); + hash +} + +unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> std::io::Result { + let mut p = Vec::new(); + for b in [&d.VS, &d.PS, &d.DS, &d.HS, &d.GS] { + put_shader(j, &mut p, bytes_of(b))?; + } + let desc = graphics_bytes(d); + p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); + p.extend_from_slice(&desc); + let elems = if d.InputLayout.NumElements > 0 && !d.InputLayout.pInputElementDescs.is_null() { + std::slice::from_raw_parts(d.InputLayout.pInputElementDescs, d.InputLayout.NumElements as usize) + } else { + &[] + }; + p.extend_from_slice(&(elems.len() as u32).to_le_bytes()); + for e in elems { + let name = std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char).to_bytes(); + p.extend_from_slice(&(name.len() as u32).to_le_bytes()); + p.extend_from_slice(name); + for w in [e.SemanticIndex, e.Format.0 as u32, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0 as u32, e.InstanceDataStepRate] { + p.extend_from_slice(&w.to_le_bytes()); + } + } + finish(j, b'G', p) +} + +/// Note a compute pipeline; its hash for `used`, 0 = not written. +pub unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> u64 { + let mut hash = 0; + with(|j| { + let r = (|| { + let mut p = Vec::new(); + put_shader(j, &mut p, bytes_of(&d.CS))?; + let desc = compute_bytes(d); + p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); + p.extend_from_slice(&desc); + finish(j, b'C', p) + })(); + hash = r.unwrap_or(0); + }); + hash +} + +/// Pipeline `hash` was built (the title used it): `xcl pipelines` makes these first. +pub fn used(hash: u64) { + if hash == 0 { + return; + } + with(|j| { + if j.seen.insert((b'U', hash)) { + let _ = j.file.write_all(&frame(b'U', 0, hash, &[])); + } + }); +} + +/// A journal's pipeline, read back with everything it points to owned. +pub enum Replay { + Graphics(Box, Vec>, Vec, Vec), + Compute(Box, Vec>), +} + +unsafe impl Send for Replay {} + +fn read_desc(p: &[u8], at: &mut usize) -> Option> { + let n = u32::from_le_bytes(p.get(*at..*at + 4)?.try_into().ok()?) as usize; + *at += 4; + let bytes = p.get(*at..*at + n)?; + *at += n; + if n != std::mem::size_of::() { + return None; + } + unsafe { + let mut b: Box> = Box::new(std::mem::MaybeUninit::zeroed()); + std::ptr::copy_nonoverlapping(bytes.as_ptr(), b.as_mut_ptr() as *mut u8, n); + Some(Box::from_raw(Box::into_raw(b) as *mut T)) + } +} + +fn u32_at(p: &[u8], at: &mut usize) -> Option { + let v = u32::from_le_bytes(p.get(*at..*at + 4)?.try_into().ok()?); + *at += 4; + Some(v) +} + +/// The pipeline of frame `f` (`G` / `C`), its shaders from `shader` by hash. None: malformed, +/// or a shader not in the journal. +pub fn replay(f: &Frame, shader: impl Fn(u64) -> Option>) -> Option { + let p = f.payload; + let mut at = 0usize; + let sh = |at: &mut usize| -> Option>> { + let h = u64::from_le_bytes(p.get(*at..*at + 8)?.try_into().ok()?); + *at += 8; + if h == 0 { + return Some(None); + } + Some(Some(shader(h)?)) + }; + let code = |b: &Vec| D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as *const _, BytecodeLength: b.len() }; + match f.tag { + b'C' => { + let cs = sh(&mut at)??; + let mut d: Box = read_desc(p, &mut at)?; + // (no pointer from the file reaches the driver) + d.pRootSignature = std::mem::ManuallyDrop::new(None); + d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + d.CS = code(&cs); + Some(Replay::Compute(d, vec![cs])) + } + b'G' => { + let mut blobs = Vec::new(); + let mut slots = [None; 5]; + for s in slots.iter_mut() { + if let Some(b) = sh(&mut at)? { + blobs.push(b); + *s = Some(blobs.len() - 1); + } + } + let mut d: Box = read_desc(p, &mut at)?; + // (no pointer from the file reaches the driver) + d.pRootSignature = std::mem::ManuallyDrop::new(None); + d.StreamOutput = unsafe { std::mem::zeroed() }; + d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + for b in [&mut d.VS, &mut d.PS, &mut d.DS, &mut d.HS, &mut d.GS] { + *b = D3D12_SHADER_BYTECODE::default(); + } + for (s, b) in slots.iter().zip([&mut d.VS, &mut d.PS, &mut d.DS, &mut d.HS, &mut d.GS]) { + if let Some(i) = s { + *b = code(&blobs[*i]); + } + } + let n = u32_at(p, &mut at)? as usize; + let mut names = Vec::with_capacity(n); + let mut raw = Vec::with_capacity(n); + for _ in 0..n { + let len = u32_at(p, &mut at)? as usize; + names.push(std::ffi::CString::new(p.get(at..at + len)?).ok()?); + at += len; + let mut w = [0u32; 6]; + for x in w.iter_mut() { + *x = u32_at(p, &mut at)?; + } + raw.push(w); + } + let elems: Vec = names + .iter() + .zip(&raw) + .map(|(name, w)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: windows::core::PCSTR(name.as_ptr() as *const u8), + SemanticIndex: w[0], + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(w[1] as i32), + InputSlot: w[2], + AlignedByteOffset: w[3], + InputSlotClass: D3D12_INPUT_CLASSIFICATION(w[4] as i32), + InstanceDataStepRate: w[5], + }) + .collect(); + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: if elems.is_empty() { std::ptr::null() } else { elems.as_ptr() }, NumElements: elems.len() as u32 }; + Some(Replay::Graphics(d, blobs, elems, names)) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn graphics_round_trip() { + let vs = vec![1u8, 2, 3, 4]; + let ps = vec![9u8; 40]; + let name = std::ffi::CString::new("TEXCOORD").unwrap(); + let elems = [D3D12_INPUT_ELEMENT_DESC { SemanticName: windows::core::PCSTR(name.as_ptr() as *const u8), SemanticIndex: 3, InputSlot: 1, AlignedByteOffset: 12, ..Default::default() }]; + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + d.VS = D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as *const _, BytecodeLength: vs.len() }; + d.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as *const _, BytecodeLength: ps.len() }; + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elems.as_ptr(), NumElements: 1 }; + d.NumRenderTargets = 2; + d.SampleMask = 0xffff_ffff; + let mut j = Journal { file: tempfile(), seen: HashSet::new() }; + let h1 = unsafe { graphics_in(&mut j, &d).unwrap() }; + let h2 = unsafe { graphics_in(&mut j, &d).unwrap() }; + assert_eq!(h1, h2, "the same desc made again: the same hash"); + // garbage in the padding after a render target's write mask (a desc built on the stack) + let mut d3: D3D12_GRAPHICS_PIPELINE_STATE_DESC = unsafe { std::ptr::read(&d) }; + let pad = std::mem::offset_of!(D3D12_GRAPHICS_PIPELINE_STATE_DESC, BlendState.RenderTarget) + + std::mem::offset_of!(D3D12_RENDER_TARGET_BLEND_DESC, RenderTargetWriteMask) + + 1; + unsafe { *(&mut d3 as *mut D3D12_GRAPHICS_PIPELINE_STATE_DESC as *mut u8).add(pad) = 0xAA }; + assert_eq!(unsafe { graphics_in(&mut j, &d3).unwrap() }, h1, "padding is not part of the pipeline"); + std::mem::forget(d3); + let mut bytes = MAGIC.to_vec(); + use std::io::{Read, Seek}; + j.file.seek(std::io::SeekFrom::Start(0)).unwrap(); + j.file.read_to_end(&mut bytes).unwrap(); + let mut frames = Vec::new(); + for_each_frame(&bytes, |f| frames.push((f.tag, f.hash, f.payload.to_vec()))); + assert_eq!(frames.iter().filter(|f| f.0 == b'S').count(), 2); + assert_eq!(frames.iter().filter(|f| f.0 == b'G').count(), 1, "written once"); + let g = frames.iter().find(|f| f.0 == b'G').unwrap(); + let shader = |h| frames.iter().find(|f| f.0 == b'S' && f.1 == h).map(|f| f.2.clone()); + let Some(Replay::Graphics(r, blobs, _elems, _names)) = replay(&Frame { tag: b'G', windows: 0, hash: g.1, payload: &g.2 }, shader) else { panic!("no replay") }; + assert_eq!(blobs, vec![vs.clone(), ps.clone()]); + unsafe { + assert_eq!(bytes_of(&r.VS).unwrap(), &vs[..]); + assert_eq!(bytes_of(&r.PS).unwrap(), &ps[..]); + assert!(bytes_of(&r.GS).is_none()); + assert_eq!((r.NumRenderTargets, r.SampleMask, r.InputLayout.NumElements), (2, 0xffff_ffff, 1)); + let e = &*r.InputLayout.pInputElementDescs; + assert_eq!((e.SemanticName.to_string().unwrap().as_str(), e.SemanticIndex, e.InputSlot, e.AlignedByteOffset), ("TEXCOORD", 3, 1, 12)); + } + // a torn tail is not a frame + let whole = for_each_frame(&bytes, |_| {}); + assert_eq!(for_each_frame(&bytes[..bytes.len() - 3], |_| {}) < whole, true); + } + + fn tempfile() -> std::fs::File { + let p = std::env::temp_dir().join(format!("xcl_pso_journal_{}.bin", std::process::id())); + let f = std::fs::OpenOptions::new().create(true).truncate(true).read(true).write(true).open(&p).unwrap(); + let _ = std::fs::remove_file(&p); + f + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ddfad69f7..77e8e9424 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4309,9 +4309,16 @@ unsafe fn go_background( } let dev = Dev(this as usize, f as usize); let key = owned.shaders_key(); + // for `xcl pipelines`, which compiles them in its own process (`pso_journal`) + let journal = match &owned { + OwnedDesc::Graphics(d, ..) => super::pso_journal::graphics(d), + OwnedDesc::Compute(d, _) => super::pso_journal::compute(d), + OwnedDesc::Stream(..) => 0, + }; let job: super::pso_async::Job = Box::new(move || { let mut out: *mut c_void = std::ptr::null_mut(); if unsafe { build(dev, &owned, &mut out) } && !out.is_null() { + super::pso_journal::used(journal); out as usize } else { 0 From bc5bdc73bdf7dd8b6156e869e8845041af2d19f7 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:19:57 -0800 Subject: [PATCH 03/13] D3D12.X: a journal write error cuts its frame back and ends the journal for the run A frame is now noted as written only once all of it is on disk; a failed write (a full disk) is cut back to where it started, so later frames stay readable, and the journal is off for the rest of the run. An input layout count read from the file is checked against the bytes there before anything is allocated for it. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/pso_journal.rs | 70 ++++++++++++++---------- 1 file changed, 40 insertions(+), 30 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_journal.rs b/crates/xcl/src/hle/d3d12x/pso_journal.rs index 788dbf87c..835044011 100644 --- a/crates/xcl/src/hle/d3d12x/pso_journal.rs +++ b/crates/xcl/src/hle/d3d12x/pso_journal.rs @@ -12,7 +12,7 @@ //! that uses it. Duplicates of earlier runs are not written again. use std::collections::HashSet; -use std::io::Write; +use std::io::{Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::sync::Mutex; use windows::Win32::Graphics::Direct3D12::*; @@ -86,10 +86,17 @@ fn open() -> Option { Some(Journal { file, seen }) } -fn with(f: impl FnOnce(&mut Journal)) { +/// Runs `f` on the journal; a write error turns it off for the rest of the run (0). +fn with(f: impl FnOnce(&mut Journal) -> std::io::Result) -> u64 { let mut g = J.lock().unwrap(); - if let Some(j) = g.get_or_insert_with(open).as_mut() { - f(j); + let Some(j) = g.get_or_insert_with(open).as_mut() else { return 0 }; + match f(j) { + Ok(h) => h, + Err(e) => { + crate::xlog_warn!("pipeline journal: {e}: off for this run"); + *g = Some(None); + 0 + } } } @@ -182,12 +189,25 @@ unsafe fn bytes_of<'a>(b: &D3D12_SHADER_BYTECODE) -> Option<&'a [u8]> { (!b.pShaderBytecode.is_null() && b.BytecodeLength != 0).then(|| std::slice::from_raw_parts(b.pShaderBytecode as *const u8, b.BytecodeLength)) } +/// Writes a frame once: all of it, or (an error) none of it, so later frames stay readable. +fn put(j: &mut Journal, tag: u8, windows: u8, hash: u64, payload: &[u8]) -> std::io::Result<()> { + if j.seen.contains(&(tag, hash)) { + return Ok(()); + } + let at = j.file.stream_position()?; + if let Err(e) = j.file.write_all(&frame(tag, windows, hash, payload)) { + let _ = j.file.set_len(at); + let _ = j.file.seek(SeekFrom::Start(at)); + return Err(e); + } + j.seen.insert((tag, hash)); + Ok(()) +} + fn put_shader(j: &mut Journal, out: &mut Vec, sh: Option<&[u8]>) -> std::io::Result<()> { let h = sh.map_or(0, crate::gpu::shader::fnv64); if let Some(sh) = sh { - if j.seen.insert((b'S', h)) { - j.file.write_all(&frame(b'S', 0, h, sh))?; - } + put(j, b'S', 0, h, sh)?; } out.extend_from_slice(&h.to_le_bytes()); Ok(()) @@ -199,17 +219,13 @@ fn finish(j: &mut Journal, tag: u8, mut payload: Vec) -> std::io::Result u64 { - let mut hash = 0; - with(|j| hash = graphics_in(j, d).unwrap_or(0)); - hash + with(|j| graphics_in(j, d)) } unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> std::io::Result { @@ -239,19 +255,14 @@ unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) - /// Note a compute pipeline; its hash for `used`, 0 = not written. pub unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> u64 { - let mut hash = 0; with(|j| { - let r = (|| { - let mut p = Vec::new(); - put_shader(j, &mut p, bytes_of(&d.CS))?; - let desc = compute_bytes(d); - p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); - p.extend_from_slice(&desc); - finish(j, b'C', p) - })(); - hash = r.unwrap_or(0); - }); - hash + let mut p = Vec::new(); + put_shader(j, &mut p, bytes_of(&d.CS))?; + let desc = compute_bytes(d); + p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); + p.extend_from_slice(&desc); + finish(j, b'C', p) + }) } /// Pipeline `hash` was built (the title used it): `xcl pipelines` makes these first. @@ -259,11 +270,7 @@ pub fn used(hash: u64) { if hash == 0 { return; } - with(|j| { - if j.seen.insert((b'U', hash)) { - let _ = j.file.write_all(&frame(b'U', 0, hash, &[])); - } - }); + with(|j| put(j, b'U', 0, hash, &[]).map(|_| 0)); } /// A journal's pipeline, read back with everything it points to owned. @@ -342,6 +349,9 @@ pub fn replay(f: &Frame, shader: impl Fn(u64) -> Option>) -> Option (p.len() - at) / 28 { + return None; // each element: a name length and six words at least + } let mut names = Vec::with_capacity(n); let mut raw = Vec::with_capacity(n); for _ in 0..n { From 0cc1dee0cef78fb8bb35e9240d41d64b411b3c12 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:23:07 -0800 Subject: [PATCH 04/13] D3D12.X: the journal keeps a run's heap-window flag Since #680 `pso::mem_windows` carries HEAP_WINDOWS (0x100) when the title's shaders take the memory windows from the descriptor heap (XCL_HEAP_WINDOWS=1). The frame's windows byte cut it off, so a heap-window run's pipelines read as the switch form's. The count stays in the low 7 bits and the flag goes in the top bit (`windows_byte`, `mem_windows_of`). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013hQzywPUY9kSTPQPh31CWh --- crates/xcl/src/hle/d3d12x/pso_journal.rs | 27 +++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_journal.rs b/crates/xcl/src/hle/d3d12x/pso_journal.rs index 835044011..06dc27fba 100644 --- a/crates/xcl/src/hle/d3d12x/pso_journal.rs +++ b/crates/xcl/src/hle/d3d12x/pso_journal.rs @@ -5,7 +5,7 @@ //! in the cache, or it is made lazily); a pipeline's first build is marked as used, which the //! tool compiles first. `XCL_PSO_JOURNAL=0`: off. //! -//! Append-only frames, little-endian: tag u8, memory windows u8, 0 u16, payload length u32, +//! Append-only frames, little-endian: tag u8, memory windows u8 (`windows_byte`), 0 u16, payload length u32, //! hash u64, payload. Tags: `S` a shader (its bytes; hash = fnv64 of them), `G` a graphics //! pipeline, `C` a compute one, `U` (no payload) pipeline `hash` was built. A pipeline's //! payload names its shaders by hash; each shader is written once, before the first pipeline @@ -213,9 +213,21 @@ fn put_shader(j: &mut Journal, out: &mut Vec, sh: Option<&[u8]>) -> std::io: Ok(()) } +/// `pso::mem_windows` in a frame's byte: the count in the low 7 bits, `HEAP_WINDOWS` in the top +/// bit (the shaders take the windows from the descriptor heap: other HLSL than the switch form). +pub fn windows_byte(mem_windows: u32) -> u8 { + (mem_windows & 0x7F) as u8 | if mem_windows & crate::gpu::recomp::HEAP_WINDOWS != 0 { 0x80 } else { 0 } +} + +/// A frame's memory windows as `pso::mem_windows` had them (`windows_byte`). +pub fn mem_windows_of(byte: u8) -> u32 { + (byte & 0x7F) as u32 | if byte & 0x80 != 0 { crate::gpu::recomp::HEAP_WINDOWS } else { 0 } +} + fn finish(j: &mut Journal, tag: u8, mut payload: Vec) -> std::io::Result { - // the memory windows are part of what the pipeline is (its HLSL differs with them) - let windows = crate::gpu::recomp::pso::mem_windows() as u8; + // the memory windows are part of what the pipeline is (its HLSL differs with them, and with + // heap windows) + let windows = windows_byte(crate::gpu::recomp::pso::mem_windows()); payload.push(windows); let hash = crate::gpu::shader::fnv64(&payload); payload.pop(); @@ -388,6 +400,15 @@ pub fn replay(f: &Frame, shader: impl Fn(u64) -> Option>) -> Option Date: Mon, 23 Nov 2026 19:46:49 -0800 Subject: [PATCH 05/13] Shaders: xcl pipelines compiles a run's queued pipelines outside the title `xcl pipelines [--watch]` reads the journal a run wrote and makes each pipeline on its own D3D12 device as the title would (prep_graphics for VS / PS, the compute path with XCL's ABI root signature), on the GPU the title's xcl.toml names. The DXIL cache, the driver's cache and driver_cache (compute blobs) then hold what the title asks for: before its next run, or during this one with --watch (following the journal; the pipelines the title used first). Translation and DXC run on half the cores at below-normal priority, the driver's compiles a few at once (XCL_PIPELINE_THREADS). What was made is kept in pipelines.done for this binary; a failure is tried again by the next run. GS / HS / DS and mesh pipelines are left to the title. The memory windows of the run come from the journal (pso::set_mem_windows: prep_graphics translates through console_to_dxil_for like the title), and shader::readable no longer creates the UMA (uma::existing): a process without a title reserved 12 GiB of windows and a 512 MB coherent window for a pointer check. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- crates/xcl/src/gpu/recomp/pso.rs | 25 +- crates/xcl/src/gpu/shader.rs | 2 +- crates/xcl/src/gpu/uma.rs | 6 + crates/xcl/src/hle/d3d12x/real.rs | 58 ++++- crates/xcl/src/launcher.rs | 2 +- crates/xcl/src/lib.rs | 1 + crates/xcl/src/main.rs | 5 + crates/xcl/src/pipelines.rs | 411 ++++++++++++++++++++++++++++++ 9 files changed, 505 insertions(+), 8 deletions(-) create mode 100644 crates/xcl/src/pipelines.rs diff --git a/README.md b/README.md index 722483312..9c395bad3 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ XCL works only on unpacked game files you already own. It does not download, dec | Feature | State | What it does | Verified by | |---|---|---|---| | **Video** | ✅ | the game's Bink 2 console DLL decodes its movies (720p / 1080p) on the CPU; the game's own YUV → RGB display shaders (`PS_Bink…` in its pack) translate like any other. Bink's GPU-assisted mode needs no Bink-specific support: its compute shaders ship with the game and go through the recompiler too (no game seen using it yet) | a game movie decodes frame by frame, picture checked | -| **Tools** | ✅ | `xcl inspect`, `xcl run`, `xcl disasm` (RDNA2, console shader containers), `xcl shaders` (pack statistics, recompile / compile runs), `xcl rpf` | – | +| **Tools** | ✅ | `xcl inspect`, `xcl run`, `xcl disasm` (RDNA2, console shader containers), `xcl shaders` (pack statistics, recompile / compile runs), `xcl rpf`, `xcl pipelines` (compiles a run's pipelines outside the game) | – | ## Controls @@ -116,6 +116,7 @@ xcl disasm [--hex] # RDNA2 disassembler (console contain xcl shaders D:\data\shaders.rpf --top 50 # pack statistics; --recomp / --compile N xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines # build compute pipelines and save driver blobs for the next run xcl rpf D:\data\shaders.rpf --extract NAME --out folder +xcl pipelines D:\Games\SomeTitle [--watch] # compile the pipelines a run queued (\cache\pipelines.bin) ``` - **Without a command line** (xcl.exe opened from Explorer) XCL shows a small menu: *Choose a diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index c63f8be85..f7a26a45d 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -76,14 +76,33 @@ pub fn fspx(blob: &[u8]) -> Option> { /// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when /// shaders take them from the descriptor heap (`heap_windows`). pub fn mem_windows() -> u32 { - let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); - if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) { - n | super::HEAP_WINDOWS + let n = match MEM_WINDOWS_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { + 0 => { + let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); + if n > 1 && heap_windows() { + n | super::HEAP_WINDOWS + } else { + n + } + } + n => n, + }; + if SWITCH_FORM.with(|s| s.get()) { + n & !super::HEAP_WINDOWS } else { n } } +static MEM_WINDOWS_OVERRIDE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// `mem_windows` as a title's run had it, with its `HEAP_WINDOWS` (`xcl pipelines` replays a +/// run's pipelines without the title's unified memory: the HLSL, and so the cache keys, must be +/// that run's). 0: unset. +pub fn set_mem_windows(n: u32) { + MEM_WINDOWS_OVERRIDE.store(n, std::sync::atomic::Ordering::Relaxed); +} + thread_local! { /// this thread translates in the switch form (`in_switch_form`) static SWITCH_FORM: std::cell::Cell = const { std::cell::Cell::new(false) }; diff --git a/crates/xcl/src/gpu/shader.rs b/crates/xcl/src/gpu/shader.rs index 2eb90fb85..48f9a3e62 100644 --- a/crates/xcl/src/gpu/shader.rs +++ b/crates/xcl/src/gpu/shader.rs @@ -212,7 +212,7 @@ pub fn readable(p: usize, len: usize) -> bool { Some(e) => e, None => return false, }; - if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, len)) { + if crate::gpu::uma::existing().is_some_and(|u| u.in_committed_window(p, len)) { return true; } if resident_and_readable(p, end) { diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 82eac9e53..dd4da201f 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -730,6 +730,12 @@ impl Uma { } } +/// The UMA if something made it already (`get` makes it: a process without a title, such as +/// `xcl pipelines`, must not reserve its windows for a check). +pub fn existing() -> Option<&'static Uma> { + GLOBAL.get()?.as_ref() +} + /// The title's graphics memory (created on first use; `XCL_UMA_MB`, default 2048). pub fn get() -> Option<&'static Uma> { GLOBAL diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 77e8e9424..370340e16 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3950,8 +3950,9 @@ unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: } /// The PC desc of a pipeline with a console VS (and PS) and no GS / HS / DS: the translated -/// shaders, XCL's ABI root signature, PC formats and topology (`translated_graphics_pso`, apart -/// from making the pipeline). +/// shaders, XCL's ABI root signature, PC formats and topology. `translated_graphics_pso`, and +/// `warm` (`xcl pipelines` makes a run's pipelines in its own process: the same desc, so the +/// same DXIL and driver cache entries). struct GraphicsPrep { desc: D3D12_GRAPHICS_PIPELINE_STATE_DESC, rs: *mut c_void, @@ -4347,6 +4348,59 @@ unsafe fn build_stream(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { matches!(translated_mesh_stream(dev.0 as *mut c_void, d.ptr(), &iid, out), Some(hr) if hr >= 0) } +/// `xcl pipelines`: a journal's pipeline made on `dev` (a plain device of this process) as +/// `translated_graphics_pso` / `translated_compute_pso` make it, which fills the DXIL cache +/// and the driver's, and released. `driver` is held around the driver's compile only (few of +/// those at once; translation and DXC run freely). Err: what kept it from being made. +pub(crate) unsafe fn warm(dev: &ID3D12Device, r: &super::pso_journal::Replay, driver: impl FnOnce() -> G) -> Result<(), String> { + use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; + use windows::core::Interface; + let this = dev.as_raw(); + let made: windows::core::Result = match r { + super::pso_journal::Replay::Graphics(d, ..) => { + let vs = shader_bytes(&d.VS).filter(|v| is_console(v)).ok_or("no console VS")?; + if shader_bytes(&d.HS).is_some() || shader_bytes(&d.DS).is_some() || shader_bytes(&d.GS).is_some() { + return Err("GS / HS / DS pipeline – left to the title".into()); + } + let GraphicsPrep { desc: mut copy, rect_gs, _dxil, .. } = prep_graphics(this, d, vs).ok_or("not translated")?; + let _slot = driver(); + let mut made = None; + let hr = retry_without_rect_gs(&mut copy, rect_gs.is_some(), |c| match dev.CreateGraphicsPipelineState::(c) { + Ok(p) => { + made = Some(p); + S_OK + } + Err(e) => e.code().0, + }); + made.ok_or_else(|| windows::core::Error::from_hresult(windows::core::HRESULT(hr))) + } + super::pso_journal::Replay::Compute(d, _) => { + let cs = shader_bytes(&d.CS).filter(|c| is_console(c)).ok_or("no console CS")?; + let compiled = console_to_dxil_for(cs, Stage::Compute, 0, wave32_only(this))?; + let rs = abi_rs_for(this, &compiled.samplers).ok_or("no root signature")?; + let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(&**d); + copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); + copy.CS = bytecode(&compiled.dxil); + copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + // the driver's result goes where `translated_compute_pso` looks for it (`driver_cache`) + let disk = driver_cache::path(&compiled.dxil, copy.Flags.0); + if disk.as_deref().is_some_and(std::path::Path::is_file) { + return Ok(()); + } + let _slot = driver(); + let started = std::time::Instant::now(); + let made = dev.CreateComputePipelineState::(©); + if let (Ok(p), Some(path)) = (&made, &disk) { + if let Ok(b) = p.GetCachedBlob() { + driver_cache::keep(path, std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()), started.elapsed()); + } + } + made + } + }; + made.map(drop).map_err(|e| format!("the driver refused it: {e}")) +} + pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { graphics_pso(this, desc, riid, ppv, false) } diff --git a/crates/xcl/src/launcher.rs b/crates/xcl/src/launcher.rs index 60aeb8f47..624909e92 100644 --- a/crates/xcl/src/launcher.rs +++ b/crates/xcl/src/launcher.rs @@ -234,7 +234,7 @@ fn config_root(exe: &Path) -> Option { None } -fn resolve_location(target: &Path) -> Result<(PathBuf, Option, String), String> { +pub(crate) fn resolve_location(target: &Path) -> Result<(PathBuf, Option, String), String> { let target = std::fs::canonicalize(target).map_err(|e| format!("{}: {e}", target.display()))?; let target = PathBuf::from(target.to_string_lossy().trim_start_matches("\\\\?\\")); let (root, exe) = if target.is_dir() { diff --git a/crates/xcl/src/lib.rs b/crates/xcl/src/lib.rs index 6f828ca68..75f8f9f4c 100644 --- a/crates/xcl/src/lib.rs +++ b/crates/xcl/src/lib.rs @@ -21,6 +21,7 @@ pub mod launcher; pub mod loader; pub mod modules; pub mod pe; +pub mod pipelines; pub mod preflight; pub mod report; pub mod resolver; diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 83ed10292..3a9b498c4 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. + xcl pipelines [--watch] [--threads N] [--limit N] + Compiles the pipelines a run asked for (\\cache\\pipelines.bin) in this process, + not the game's: DXIL and driver caches are ready for the next run, or – with --watch, + started next to `xcl run` – while the game plays (the ones it used first). 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. @@ -65,6 +69,7 @@ fn main() { } Some("disasm") if args.len() >= 2 => xcl::disasm::run(&PathBuf::from(&args[1]), &args[2..]), Some("shaders") if args.len() >= 2 => xcl::shaders::run(&PathBuf::from(&args[1]), &args[2..]), + Some("pipelines") if args.len() >= 2 => xcl::pipelines::run(&PathBuf::from(&args[1]), &args[2..]), Some("rpf") if args.len() >= 2 => xcl::rpf::run(&PathBuf::from(&args[1]), &args[2..]), Some("--version") | Some("-V") => { println!("xcl {}", env!("CARGO_PKG_VERSION")); diff --git a/crates/xcl/src/pipelines.rs b/crates/xcl/src/pipelines.rs new file mode 100644 index 000000000..8fb56a9b1 --- /dev/null +++ b/crates/xcl/src/pipelines.rs @@ -0,0 +1,411 @@ +//! `xcl pipelines`: compiles a title's pipelines in its own process, from the journal a run +//! writes (`hle::d3d12x::pso_journal`): the DXIL cache and the GPU driver's cache get what the +//! title asks for, so its pipelines are ready when it binds them – before the next run, or +//! during this one (`--watch` follows the journal as the title writes it, at below-normal +//! priority). Pipelines the title used come first. What is done is kept next to the journal +//! (`pipelines.done`, for this XCL binary), so a stopped run goes on where it was. +//! It must be the same xcl.exe as the title's: the translations' cache key holds the binary's +//! hash, and the driver keeps its cache per program. + +use crate::hle::d3d12x::pso_journal::{self, Replay}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::io::{Read, Seek, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; + +const HELP: &str = "\ +xcl pipelines [--watch] [--threads N] [--limit N] + Compiles the pipelines a run of the title asked for (\\cache\\pipelines.bin) outside + the title: the DXIL cache and the driver's cache. --watch: also while the title runs, + following what it adds (stop with Ctrl+C). --threads: pipelines at once (default: half the + cores, at below-normal priority; XCL_PIPELINE_THREADS caps the driver compiles, default 4, 2 with --watch)."; + +/// The journal of `target`: the file itself, a data folder with one, or a game folder. +fn journal_of(target: &Path) -> Result { + if target.is_file() && target.extension().is_some_and(|e| e.eq_ignore_ascii_case("bin")) { + return Ok(target.to_path_buf()); + } + let own = pso_journal::path_in(target); + if own.is_file() { + return Ok(own); + } + let (_, _, title) = crate::launcher::resolve_location(target)?; + let j = pso_journal::path_in(&crate::launcher::data_root().join(&title)); + if j.is_file() { + Ok(j) + } else { + Err(format!("no pipeline journal at {} – run the title once with this XCL (`xcl run`) to write it", j.display())) + } +} + +/// This binary (size and time written): what `pipelines.done` is valid for. +fn binary_key() -> u64 { + let m = std::env::current_exe().and_then(std::fs::metadata); + m.map_or(0, |m| { + let t = m.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_nanos() as u64); + crate::gpu::shader::fnv64(&[m.len().to_le_bytes(), t.to_le_bytes()].concat()) + }) +} + +#[derive(Default)] +struct Queue { + /// pipelines the title built, then the others (journal order) + used: VecDeque, + rest: VecDeque, + /// done, or taken by a worker + taken: HashSet, + shaders: HashMap>>, + pipes: HashMap>)>, + was_used: HashSet, + /// the memory windows of the run (`run` sets them: `pso::set_mem_windows`); other runs' are left out + windows: u8, + other_windows: usize, + /// the journal: bytes read, and where its whole frames end + buf: Vec, + parsed: usize, + closed: bool, +} + +impl Queue { + /// Read what was added to the journal; the new work. + fn ingest(&mut self, file: &mut std::fs::File) -> usize { + // a journal made again (shorter than what was read): from its start + if file.metadata().is_ok_and(|m| m.len() < self.buf.len() as u64) { + self.buf.clear(); + self.parsed = 0; + } + let start = self.buf.len(); + let _ = file.seek(std::io::SeekFrom::Start(start as u64)); + let _ = file.read_to_end(&mut self.buf); + if self.buf.len() == start && self.parsed != 0 { + return 0; + } + if self.parsed == 0 { + if !self.buf.starts_with(pso_journal::MAGIC) { + return 0; + } + self.parsed = pso_journal::MAGIC.len(); + } + let mut new = 0; + let mut frames = Vec::new(); + self.parsed = pso_journal::for_each_frame_from(&self.buf, self.parsed, |f| frames.push((f.tag, f.windows, f.hash, f.payload.to_vec()))); + for (tag, windows, hash, payload) in frames { + match tag { + b'S' => { + self.shaders.insert(hash, Arc::new(payload)); + } + b'G' | b'C' => { + if self.windows == 0 { + self.windows = windows.max(1); + } + if windows.max(1) != self.windows { + self.other_windows += 1; + continue; + } + self.pipes.insert(hash, (tag, Arc::new(payload))); + if !self.taken.contains(&hash) { + if self.was_used.contains(&hash) { + self.used.push_back(hash); + } else { + self.rest.push_back(hash); + } + new += 1; + } + } + b'U' => { + if self.was_used.insert(hash) && self.pipes.contains_key(&hash) && !self.taken.contains(&hash) { + self.used.push_back(hash); + } + } + _ => {} + } + } + new + } + + fn next(&mut self) -> Option<(u64, Option)> { + while let Some(h) = self.used.pop_front().or_else(|| self.rest.pop_front()) { + if !self.taken.insert(h) { + continue; + } + let (tag, payload) = self.pipes.get(&h)?.clone(); + let frame = pso_journal::Frame { tag, windows: self.windows, hash: h, payload: &payload }; + return Some((h, pso_journal::replay(&frame, |s| self.shaders.get(&s).map(|b| b.to_vec())))); + } + None + } + + fn left(&self) -> usize { + self.used.len() + self.rest.len() + } +} + +pub fn run(target: &Path, args: &[String]) -> i32 { + if args.iter().any(|a| a == "--help" || a == "-h") { + println!("{HELP}"); + return 0; + } + let opt = |k: &str| args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).and_then(|v| v.parse::().ok()); + let watch = args.iter().any(|a| a == "--watch"); + let limit = opt("--limit").unwrap_or(usize::MAX); + let journal = match journal_of(target) { + Ok(j) => j, + Err(e) => { + eprintln!("xcl pipelines: {e}"); + return 2; + } + }; + let dev = match device(&adapter_setting(&journal)) { + Ok(d) => d, + Err(e) => { + eprintln!("xcl pipelines: no GPU device: {e}"); + return 2; + } + }; + // a background job: the title's threads and the user's programs first, and about half the + // cores (DXC's pool too, unless XCL_DXC_THREADS says otherwise) – the PC stays usable + unsafe { + use windows::Win32::System::Threading::{GetCurrentProcess, SetPriorityClass, BELOW_NORMAL_PRIORITY_CLASS}; + let _ = SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); + } + let half = std::thread::available_parallelism().map_or(2, |n| n.get() / 2).max(1); + if std::env::var_os("XCL_DXC_THREADS").is_none() { + std::env::set_var("XCL_DXC_THREADS", half.to_string()); + } + // a running title keeps its commit (`wait_for_memory`'s 6 GB); without one, 2 + crate::gpu::recomp::dxc::set_memory_reserve(if watch { 6 } else { 2 }); + let gpu_most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(if watch { 2 } else { 4usize }).max(1); + let threads = opt("--threads").unwrap_or(half).max(1); + + let mut file = match std::fs::File::open(&journal) { + Ok(f) => f, + Err(e) => { + eprintln!("xcl pipelines: {}: {e}", journal.display()); + return 2; + } + }; + let q = Arc::new((Mutex::new(Queue::default()), Condvar::new())); + // what an earlier run of this binary finished + let done_path = journal.with_extension("done"); + let key = binary_key(); + let mut done_file = { + let old = std::fs::read(&done_path).unwrap_or_default(); + let mut g = q.0.lock().unwrap(); + if old.len() >= 8 && old[..8] == key.to_le_bytes() { + g.taken.extend(old[8..].chunks_exact(8).map(|c| u64::from_le_bytes(c.try_into().unwrap()))); + } + let fresh = g.taken.is_empty(); + let mut f = match std::fs::OpenOptions::new().create(true).append(true).open(&done_path) { + Ok(f) => f, + Err(e) => { + eprintln!("xcl pipelines: {}: {e}", done_path.display()); + return 2; + } + }; + if fresh { + let _ = f.set_len(0); + let _ = f.write_all(&key.to_le_bytes()); + } + f + }; + let (already, first) = { + let mut g = q.0.lock().unwrap(); + let first = g.ingest(&mut file); + // the HLSL (and so the cache keys) of the run's memory windows + crate::gpu::recomp::pso::set_mem_windows(g.windows as u32); + (g.taken.len(), first) + }; + { + let g = q.0.lock().unwrap(); + println!( + "{}: {first} pipelines to make ({} the title used), {already} done before, {} shaders; {} memory windows; {threads} threads, {gpu_most} driver compiles at once{}", + journal.display(), + g.used.len(), + g.shaders.len(), + g.windows, + if watch { "; following the journal (Ctrl+C stops)" } else { "" } + ); + } + + let t0 = std::time::Instant::now(); + let (made, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + let reasons: Mutex> = Mutex::new(HashMap::new()); + let done_tx = Mutex::new(&mut done_file); + let gpu = (Mutex::new(0usize), Condvar::new()); + let started = AtomicUsize::new(0); + std::thread::scope(|s| { + if watch { + let q = q.clone(); + s.spawn(move || loop { + std::thread::sleep(std::time::Duration::from_secs(2)); + let mut g = q.0.lock().unwrap(); + if g.closed { + return; + } + let new = g.ingest(&mut file); + // (a journal that was empty when the tool started) + crate::gpu::recomp::pso::set_mem_windows(g.windows as u32); + if new > 0 || !g.used.is_empty() { + q.1.notify_all(); + } + }); + } + for k in 0..threads { + let (q, dev, made, failed, skipped, reasons, done_tx, gpu, started) = (&q, &dev, &made, &failed, &skipped, &reasons, &done_tx, &gpu, &started); + let _ = std::thread::Builder::new().name(format!("xcl-warm-{k}")).stack_size(64 << 20).spawn_scoped(s, move || loop { + let item = { + let mut g = q.0.lock().unwrap(); + loop { + if started.load(Ordering::Relaxed) >= limit { + g.closed = true; + q.1.notify_all(); + return; + } + if let Some(it) = g.next() { + started.fetch_add(1, Ordering::Relaxed); + break it; + } + if !watch || g.closed { + return; + } + g = q.1.wait(g).unwrap(); + } + }; + let (hash, replay) = item; + let r = match &replay { + None => Err("not readable from the journal".to_string()), + // the driver's compiles, few at once (the biggest take ~1.5 GB each) + Some(r) => unsafe { crate::hle::d3d12x::real::warm(dev, r, || DriverSlot::take(gpu, gpu_most)) }, + }; + // done: made, or left to the title; a failure is tried again by the next run + let done = match r { + Ok(()) => { + made.fetch_add(1, Ordering::Relaxed); + true + } + Err(e) if e.contains("left to the title") => { + skipped.fetch_add(1, Ordering::Relaxed); + true + } + Err(e) => { + let reason: String = e.lines().find(|l| l.contains("error")).unwrap_or(e.lines().next().unwrap_or("")).chars().take(160).collect(); + *reasons.lock().unwrap().entry(reason).or_default() += 1; + failed.fetch_add(1, Ordering::Relaxed); + false + } + }; + if done { + let _ = done_tx.lock().unwrap().write_all(&hash.to_le_bytes()); + } + let n = made.load(Ordering::Relaxed) + failed.load(Ordering::Relaxed) + skipped.load(Ordering::Relaxed); + if n % 100 == 0 { + let left = q.0.lock().unwrap().left(); + let rate = n as f64 / t0.elapsed().as_secs_f64().max(0.001); + eprintln!(" {n} done, {left} left ({rate:.1}/s, ~{:.0} min to go)", left as f64 / rate.max(0.001) / 60.0); + } + }); + } + }); + let g = q.0.lock().unwrap(); + println!( + "made {}, failed {}, left to the title (GS / HS / DS) {}, time {:.1} s", + made.into_inner(), + failed.into_inner(), + skipped.into_inner(), + t0.elapsed().as_secs_f64() + ); + if g.other_windows > 0 { + println!(" {} pipelines from a run with other memory windows left out", g.other_windows); + } + let mut r: Vec<_> = reasons.into_inner().unwrap().into_iter().collect(); + r.sort_by(|a, b| b.1.cmp(&a.1)); + for (why, n) in r.iter().take(10) { + println!(" {n}× {why}"); + } + 0 +} + +/// A driver compile's turn (`XCL_PIPELINE_THREADS` at once), given back when dropped. +struct DriverSlot<'a>(&'a (Mutex, Condvar)); + +impl<'a> DriverSlot<'a> { + fn take(gpu: &'a (Mutex, Condvar), most: usize) -> DriverSlot<'a> { + let mut n = gpu.0.lock().unwrap(); + while *n >= most { + n = gpu.1.wait(n).unwrap(); + } + *n += 1; + DriverSlot(gpu) + } +} + +impl Drop for DriverSlot<'_> { + fn drop(&mut self) { + *self.0 .0.lock().unwrap() -= 1; + self.0 .1.notify_one(); + } +} + +/// The GPU the title's runs use: its `xcl.toml`'s `d3d12_adapter` (or `XCL_ADAPTER`), as +/// `real::init` picks it – the driver's cache and the wave width are the adapter's. +fn adapter_setting(journal: &Path) -> String { + let toml = journal.parent().and_then(Path::parent).map(|d| d.join("xcl.toml")); + match toml.filter(|t| t.is_file()).map(|t| crate::config::Config::load_or_create(&t)) { + Some(Ok(c)) => c.d3d12_adapter, + _ => "auto".into(), + } +} + +fn device(adapter: &str) -> Result { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?; + let sel = crate::gpu::adapter::Selector::from_env_or(adapter); + let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn frame(tag: u8, hash: u64, payload: &[u8]) -> Vec { + let mut v = vec![tag, 4, 0, 0]; + v.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + v.extend_from_slice(&hash.to_le_bytes()); + v.extend_from_slice(payload); + v + } + + #[test] + fn used_pipelines_first_done_ones_skipped_journal_followed() { + let path = std::env::temp_dir().join(format!("xcl_pipelines_queue_{}.bin", std::process::id())); + let mut j = pso_journal::MAGIC.to_vec(); + for h in [1u64, 2, 3] { + j.extend(frame(b'C', h, &[0; 8])); + } + j.extend(frame(b'U', 3, &[])); + // half a frame: written later + let tail = frame(b'U', 2, &[]); + j.extend(&tail[..5]); + std::fs::write(&path, &j).unwrap(); + let mut f = std::fs::File::open(&path).unwrap(); + let mut q = Queue::default(); + q.taken.insert(1); + assert_eq!(q.ingest(&mut f), 2, "pipeline 1 was done before"); + assert_eq!(q.windows, 4); + assert_eq!(q.next().map(|(h, _)| h), Some(3), "the used one first"); + // the rest of the torn frame arrives: 2 is used now + let mut w = std::fs::OpenOptions::new().append(true).open(&path).unwrap(); + w.write_all(&tail[5..]).unwrap(); + drop(w); + assert_eq!(q.ingest(&mut f), 0); + assert_eq!(q.next().map(|(h, _)| h), Some(2)); + assert!(q.next().is_none(), "each pipeline once"); + drop(f); + let _ = std::fs::remove_file(&path); + } +} From 202838169ffb4e760d14038dcae43a7ffa247b85 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:13:03 -0800 Subject: [PATCH 06/13] Shaders: xcl pipelines replaces another binary's pipelines.done The progress file was opened for appending, and on Windows an append handle cannot be truncated: the set_len(0) for a new binary failed unseen and its key was appended after the old records. It is now opened for writing; a file of another binary starts over and a torn last record is cut off, and an open error ends the run (2). Reported by @anes66 on #759. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/pipelines.rs | 70 ++++++++++++++++++++++++++++--------- 1 file changed, 53 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/pipelines.rs b/crates/xcl/src/pipelines.rs index 8fb56a9b1..63ec5e61b 100644 --- a/crates/xcl/src/pipelines.rs +++ b/crates/xcl/src/pipelines.rs @@ -189,25 +189,15 @@ pub fn run(target: &Path, args: &[String]) -> i32 { // what an earlier run of this binary finished let done_path = journal.with_extension("done"); let key = binary_key(); - let mut done_file = { - let old = std::fs::read(&done_path).unwrap_or_default(); - let mut g = q.0.lock().unwrap(); - if old.len() >= 8 && old[..8] == key.to_le_bytes() { - g.taken.extend(old[8..].chunks_exact(8).map(|c| u64::from_le_bytes(c.try_into().unwrap()))); + let mut done_file = match open_done(&done_path, key) { + Ok((f, done)) => { + q.0.lock().unwrap().taken.extend(done); + f } - let fresh = g.taken.is_empty(); - let mut f = match std::fs::OpenOptions::new().create(true).append(true).open(&done_path) { - Ok(f) => f, - Err(e) => { - eprintln!("xcl pipelines: {}: {e}", done_path.display()); - return 2; - } - }; - if fresh { - let _ = f.set_len(0); - let _ = f.write_all(&key.to_le_bytes()); + Err(e) => { + eprintln!("xcl pipelines: {}: {e}", done_path.display()); + return 2; } - f }; let (already, first) = { let mut g = q.0.lock().unwrap(); @@ -368,10 +358,56 @@ fn device(adapter: &str) -> Result std::io::Result<(std::fs::File, Vec)> { + let mut f = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(path)?; + let mut old = Vec::new(); + f.read_to_end(&mut old)?; + let done: Vec = if old.len() >= 8 && old[..8] == key.to_le_bytes() { + old[8..].chunks_exact(8).map(|c| u64::from_le_bytes(c.try_into().unwrap())).collect() + } else { + Vec::new() + }; + if done.is_empty() { + f.set_len(0)?; + f.seek(std::io::SeekFrom::Start(0))?; + f.write_all(&key.to_le_bytes())?; + } else { + let end = 8 + 8 * done.len() as u64; + f.set_len(end)?; + f.seek(std::io::SeekFrom::Start(end))?; + } + Ok((f, done)) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn done_file_of_another_binary_is_replaced_and_a_torn_record_cut() { + let path = std::env::temp_dir().join(format!("xcl-done-test-{}.done", std::process::id())); + let _ = std::fs::remove_file(&path); + let (mut f, done) = open_done(&path, 1).unwrap(); + assert!(done.is_empty()); + f.write_all(&7u64.to_le_bytes()).unwrap(); + f.write_all(&[9, 9, 9]).unwrap(); // a record cut short + drop(f); + let (mut f, done) = open_done(&path, 1).unwrap(); + assert_eq!(done, [7]); + f.write_all(&8u64.to_le_bytes()).unwrap(); + drop(f); + assert_eq!(std::fs::read(&path).unwrap().len(), 24, "the torn record was cut, 8 follows 7"); + let (mut f, done) = open_done(&path, 2).unwrap(); + assert!(done.is_empty(), "another binary's progress is not reused"); + f.write_all(&5u64.to_le_bytes()).unwrap(); + drop(f); + let bytes = std::fs::read(&path).unwrap(); + let _ = std::fs::remove_file(&path); + assert_eq!(bytes, [2u64.to_le_bytes(), 5u64.to_le_bytes()].concat(), "the old file was replaced, not appended to"); + } + fn frame(tag: u8, hash: u64, payload: &[u8]) -> Vec { let mut v = vec![tag, 4, 0, 0]; v.extend_from_slice(&(payload.len() as u32).to_le_bytes()); From c8e43aad8cf758d15c6448c9281f1c9bb240bf9e Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:20:40 -0800 Subject: [PATCH 07/13] Shaders: xcl pipelines reads a rewritten torn frame again, takes the newest run's windows and runs once per journal - --watch: the bytes after the last whole frame are read again on each poll, so a torn frame the next run cut off and wrote over no longer misaligns every frame after it. - The memory windows to build are the last run's, not the first's: a journal kept across a change of uma_mb built the stale run's set. - pipelines.done is opened without write sharing, so a second tool on the same journal is refused instead of interleaving its records. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/pipelines.rs | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/pipelines.rs b/crates/xcl/src/pipelines.rs index 63ec5e61b..e59821cf8 100644 --- a/crates/xcl/src/pipelines.rs +++ b/crates/xcl/src/pipelines.rs @@ -70,6 +70,8 @@ struct Queue { impl Queue { /// Read what was added to the journal; the new work. fn ingest(&mut self, file: &mut std::fs::File) -> usize { + // a torn last frame may be cut and written over by the next run: read it again + self.buf.truncate(self.parsed); // a journal made again (shorter than what was read): from its start if file.metadata().is_ok_and(|m| m.len() < self.buf.len() as u64) { self.buf.clear(); @@ -90,15 +92,16 @@ impl Queue { let mut new = 0; let mut frames = Vec::new(); self.parsed = pso_journal::for_each_frame_from(&self.buf, self.parsed, |f| frames.push((f.tag, f.windows, f.hash, f.payload.to_vec()))); + if self.windows == 0 { + // the last run's (a run writes all its pipelines again when its windows differ) + self.windows = frames.iter().rev().find(|f| matches!(f.0, b'G' | b'C')).map_or(0, |f| f.1.max(1)); + } for (tag, windows, hash, payload) in frames { match tag { b'S' => { self.shaders.insert(hash, Arc::new(payload)); } b'G' | b'C' => { - if self.windows == 0 { - self.windows = windows.max(1); - } if windows.max(1) != self.windows { self.other_windows += 1; continue; @@ -361,7 +364,9 @@ fn device(adapter: &str) -> Result std::io::Result<(std::fs::File, Vec)> { - let mut f = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(path)?; + use std::os::windows::fs::OpenOptionsExt; + // FILE_SHARE_READ: a second `xcl pipelines` on this journal is refused, not interleaved + let mut f = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).share_mode(1).open(path)?; let mut old = Vec::new(); f.read_to_end(&mut old)?; let done: Vec = if old.len() >= 8 && old[..8] == key.to_le_bytes() { @@ -385,6 +390,27 @@ fn open_done(path: &Path, key: u64) -> std::io::Result<(std::fs::File, Vec) mod tests { use super::*; + #[test] + fn a_torn_frame_written_over_is_read_again() { + let path = std::env::temp_dir().join(format!("xcl_pipelines_torn_{}.bin", std::process::id())); + let mut j = pso_journal::MAGIC.to_vec(); + j.extend(frame(b'C', 1, &[0; 8])); + let good = j.len(); + j.extend(&frame(b'C', 2, &[0; 8])[..9]); // a run killed mid-frame + std::fs::write(&path, &j).unwrap(); + let mut f = std::fs::File::open(&path).unwrap(); + let mut q = Queue::default(); + assert_eq!(q.ingest(&mut f), 1); + // the next run cuts the torn frame and writes on from there + j.truncate(good); + j.extend(frame(b'C', 3, &[0; 8])); + j.extend(frame(b'C', 4, &[0; 8])); + std::fs::write(&path, &j).unwrap(); + assert_eq!(q.ingest(&mut f), 2, "3 and 4, read from where the torn frame began"); + drop(f); + let _ = std::fs::remove_file(&path); + } + #[test] fn done_file_of_another_binary_is_replaced_and_a_torn_record_cut() { let path = std::env::temp_dir().join(format!("xcl-done-test-{}.done", std::process::id())); From 4083f622e9d36ffa044f86ed9640f08aa8b30811 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:17:00 -0800 Subject: [PATCH 08/13] Shaders: xcl pipelines makes big compute pipelines one at a time and goes past one it crashed on - A big compute pipeline (256 KB of DXIL and more) now takes the title's BIG_COMPILES turn and waits for 3 GB of free commit, as the title's own background compiles do. The tool's threads (xcl-warm-*) missed that rule and ran up to four of these at once, 1.5 to 3 GB each in the driver. - The pipelines being made are noted in pipelines.trying, which a run that ends by itself removes. A run that died (a crash in the driver or DXC on one pipeline, reported under Wine on #759) leaves it behind, and the next run leaves those pipelines to the title instead of ending the same way. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 3 +++ crates/xcl/src/pipelines.rs | 27 ++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 370340e16..4632ea328 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4387,6 +4387,9 @@ pub(crate) unsafe fn warm(dev: &ID3D12Device, r: &super::pso_journal::Replay, if disk.as_deref().is_some_and(std::path::Path::is_file) { return Ok(()); } + // a big one as the title's background makes it: one at a time, within the commit left + // (no title thread waits for the tool's pipelines) + let _big = (compiled.dxil.len() >= BIG_DRIVER_COMPILE).then(|| big_compile_turn(&BIG_COMPILES, big_compile_commit_free, || false)); let _slot = driver(); let started = std::time::Instant::now(); let made = dev.CreateComputePipelineState::(©); diff --git a/crates/xcl/src/pipelines.rs b/crates/xcl/src/pipelines.rs index e59821cf8..8240b136d 100644 --- a/crates/xcl/src/pipelines.rs +++ b/crates/xcl/src/pipelines.rs @@ -202,6 +202,27 @@ pub fn run(target: &Path, args: &[String]) -> i32 { return 2; } }; + // what a run that ended without its summary (a crash in the driver or DXC) was making: left + // to the title, so the same pipeline does not end every run + let trying_path = journal.with_extension("trying"); + let crashed: Vec = { + let t = std::fs::read(&trying_path).unwrap_or_default(); + let mut g = q.0.lock().unwrap(); + t.chunks_exact(8).map(|c| u64::from_le_bytes(c.try_into().unwrap())).filter(|h| g.taken.insert(*h)).collect() + }; + for h in &crashed { + let _ = done_file.write_all(&h.to_le_bytes()); + } + if !crashed.is_empty() { + eprintln!("xcl pipelines: the last run ended while making {} pipelines: left to the title", crashed.len()); + } + let trying = match std::fs::File::create(&trying_path) { + Ok(f) => Mutex::new(f), + Err(e) => { + eprintln!("xcl pipelines: {}: {e}", trying_path.display()); + return 2; + } + }; let (already, first) = { let mut g = q.0.lock().unwrap(); let first = g.ingest(&mut file); @@ -245,7 +266,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 { }); } for k in 0..threads { - let (q, dev, made, failed, skipped, reasons, done_tx, gpu, started) = (&q, &dev, &made, &failed, &skipped, &reasons, &done_tx, &gpu, &started); + let (q, dev, made, failed, skipped, reasons, done_tx, gpu, started, trying) = (&q, &dev, &made, &failed, &skipped, &reasons, &done_tx, &gpu, &started, &trying); let _ = std::thread::Builder::new().name(format!("xcl-warm-{k}")).stack_size(64 << 20).spawn_scoped(s, move || loop { let item = { let mut g = q.0.lock().unwrap(); @@ -266,6 +287,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 { } }; let (hash, replay) = item; + let _ = trying.lock().unwrap().write_all(&hash.to_le_bytes()); let r = match &replay { None => Err("not readable from the journal".to_string()), // the driver's compiles, few at once (the biggest take ~1.5 GB each) @@ -300,6 +322,9 @@ pub fn run(target: &Path, args: &[String]) -> i32 { }); } }); + // ended by itself: nothing was cut short + drop(trying); + let _ = std::fs::remove_file(&trying_path); let g = q.0.lock().unwrap(); println!( "made {}, failed {}, left to the title (GS / HS / DS) {}, time {:.1} s", From b06e58c94c8a6efde180f8e1de05bb9fc4f2b7f0 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:20:16 -0800 Subject: [PATCH 09/13] Shaders: xcl pipelines keeps 6 GB of commit free for the PC, also without --watch Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/pipelines.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/pipelines.rs b/crates/xcl/src/pipelines.rs index 8240b136d..eb18a4ca7 100644 --- a/crates/xcl/src/pipelines.rs +++ b/crates/xcl/src/pipelines.rs @@ -176,8 +176,9 @@ pub fn run(target: &Path, args: &[String]) -> i32 { if std::env::var_os("XCL_DXC_THREADS").is_none() { std::env::set_var("XCL_DXC_THREADS", half.to_string()); } - // a running title keeps its commit (`wait_for_memory`'s 6 GB); without one, 2 - crate::gpu::recomp::dxc::set_memory_reserve(if watch { 6 } else { 2 }); + // `wait_for_memory` keeps 6 GB of commit free, as next to a running title: the tool runs in + // the background of a PC in use, and a title's last pipelines take GBs each in DXC + crate::gpu::recomp::dxc::set_memory_reserve(6); let gpu_most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(if watch { 2 } else { 4usize }).max(1); let threads = opt("--threads").unwrap_or(half).max(1); From d20dc0fbc7e8808a44811ad01c43a635e163adbf Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:45:06 -0800 Subject: [PATCH 10/13] Shaders: xcl pipelines keys done by driver, keeps only in-flight work in .trying From the test reports on the tool: - `pipelines.done` was keyed by the xcl binary only: after a driver update the pipelines the driver dropped still counted as done. The key now holds the adapter's vendor and device ID and its driver version. - `.trying` held every pipeline a run started until a clean exit, so after Ctrl+C (the end of --watch) the next run left the failed ones to the title. It now holds the pipelines being made at the moment. - The workers' stacks: 64 MB overflowed under Wine in the driver's compile of a title's biggest compute programs. They reserve 512 MB. - Progress every 10 s, with the pipelines being made; the biggest compute programs take 30 s or more each in the driver, and the line said nothing for minutes. Reported-by: claudetools-gh, JoaoPauluu, milas6669, S1m0ne1997 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/pipelines.rs | 96 ++++++++++++++++++++++++++++++------- 1 file changed, 79 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/pipelines.rs b/crates/xcl/src/pipelines.rs index eb18a4ca7..b7b3b1bee 100644 --- a/crates/xcl/src/pipelines.rs +++ b/crates/xcl/src/pipelines.rs @@ -39,15 +39,40 @@ fn journal_of(target: &Path) -> Result { } } -/// This binary (size and time written): what `pipelines.done` is valid for. -fn binary_key() -> u64 { +/// This binary (size and time written) on this GPU and driver (`gpu`): what `pipelines.done` is +/// valid for. A driver update drops the driver's cached pipelines, so they are made again. +fn binary_key(gpu: u64) -> u64 { let m = std::env::current_exe().and_then(std::fs::metadata); m.map_or(0, |m| { let t = m.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_nanos() as u64); - crate::gpu::shader::fnv64(&[m.len().to_le_bytes(), t.to_le_bytes()].concat()) + crate::gpu::shader::fnv64(&[m.len().to_le_bytes(), t.to_le_bytes(), gpu.to_le_bytes()].concat()) }) } +/// A worker's stack: the driver's compile of a title's biggest compute programs (up to ~1.2 MB of +/// DXIL) runs on it, and a translation layer's (vkd3d-proton under Wine) went past 64 MB. +/// Address space only: pages are committed as used. +const WARM_STACK: usize = 512 << 20; + +/// `pipelines.trying`: the pipelines in the making now, written whole at each change, so a run cut +/// short (a crash, or Ctrl+C) leaves the next run exactly those. +struct Trying { + file: std::fs::File, + now: Vec, +} + +impl Trying { + fn set(&mut self, hash: u64, on: bool) { + if on { + self.now.push(hash); + } else { + self.now.retain(|&h| h != hash); + } + let bytes: Vec = self.now.iter().flat_map(|h| h.to_le_bytes()).collect(); + let _ = self.file.set_len(0).and_then(|_| self.file.rewind()).and_then(|_| self.file.write_all(&bytes)); + } +} + #[derive(Default)] struct Queue { /// pipelines the title built, then the others (journal order) @@ -159,7 +184,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 { return 2; } }; - let dev = match device(&adapter_setting(&journal)) { + let (dev, gpu_key) = match device(&adapter_setting(&journal)) { Ok(d) => d, Err(e) => { eprintln!("xcl pipelines: no GPU device: {e}"); @@ -192,7 +217,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 { let q = Arc::new((Mutex::new(Queue::default()), Condvar::new())); // what an earlier run of this binary finished let done_path = journal.with_extension("done"); - let key = binary_key(); + let key = binary_key(gpu_key); let mut done_file = match open_done(&done_path, key) { Ok((f, done)) => { q.0.lock().unwrap().taken.extend(done); @@ -218,7 +243,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 { eprintln!("xcl pipelines: the last run ended while making {} pipelines: left to the title", crashed.len()); } let trying = match std::fs::File::create(&trying_path) { - Ok(f) => Mutex::new(f), + Ok(f) => Mutex::new(Trying { file: f, now: Vec::new() }), Err(e) => { eprintln!("xcl pipelines: {}: {e}", trying_path.display()); return 2; @@ -266,9 +291,10 @@ pub fn run(target: &Path, args: &[String]) -> i32 { } }); } + let mut workers = Vec::new(); for k in 0..threads { let (q, dev, made, failed, skipped, reasons, done_tx, gpu, started, trying) = (&q, &dev, &made, &failed, &skipped, &reasons, &done_tx, &gpu, &started, &trying); - let _ = std::thread::Builder::new().name(format!("xcl-warm-{k}")).stack_size(64 << 20).spawn_scoped(s, move || loop { + let w = std::thread::Builder::new().name(format!("xcl-warm-{k}")).stack_size(WARM_STACK).spawn_scoped(s, move || loop { let item = { let mut g = q.0.lock().unwrap(); loop { @@ -288,7 +314,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 { } }; let (hash, replay) = item; - let _ = trying.lock().unwrap().write_all(&hash.to_le_bytes()); + trying.lock().unwrap().set(hash, true); let r = match &replay { None => Err("not readable from the journal".to_string()), // the driver's compiles, few at once (the biggest take ~1.5 GB each) @@ -314,13 +340,26 @@ pub fn run(target: &Path, args: &[String]) -> i32 { if done { let _ = done_tx.lock().unwrap().write_all(&hash.to_le_bytes()); } - let n = made.load(Ordering::Relaxed) + failed.load(Ordering::Relaxed) + skipped.load(Ordering::Relaxed); - if n % 100 == 0 { - let left = q.0.lock().unwrap().left(); - let rate = n as f64 / t0.elapsed().as_secs_f64().max(0.001); - eprintln!(" {n} done, {left} left ({rate:.1}/s, ~{:.0} min to go)", left as f64 / rate.max(0.001) / 60.0); - } + trying.lock().unwrap().set(hash, false); }); + workers.extend(w); + } + // progress every 10 s, also while the driver takes long over the biggest programs + let (mut last, mut said) = (0, false); + while !workers.iter().all(|w| w.is_finished()) { + std::thread::sleep(std::time::Duration::from_millis(500)); + if t0.elapsed().as_secs() < last + 10 { + continue; + } + last = t0.elapsed().as_secs(); + let n = made.load(Ordering::Relaxed) + failed.load(Ordering::Relaxed) + skipped.load(Ordering::Relaxed); + let (left, busy) = (q.0.lock().unwrap().left(), trying.lock().unwrap().now.len()); + let rate = n as f64 / t0.elapsed().as_secs_f64().max(0.001); + eprintln!(" {n} done, {busy} being made, {left} left ({rate:.1}/s)"); + if rate < 1.0 && busy > 0 && !said { + said = true; + eprintln!(" (the biggest compute programs take 30 s or more each in the driver; stopping is safe, a re-run goes on from here)"); + } } }); // ended by itself: nothing was cut short @@ -376,14 +415,17 @@ fn adapter_setting(journal: &Path) -> String { } } -fn device(adapter: &str) -> Result { +/// The device, and its adapter's vendor, device and driver version (for `binary_key`). +fn device(adapter: &str) -> Result<(windows::Win32::Graphics::Direct3D12::ID3D12Device, u64), String> { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; use windows::Win32::Graphics::Dxgi::*; unsafe { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?; let sel = crate::gpu::adapter::Selector::from_env_or(adapter); - let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; - crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string()) + let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + let umd = adapter.CheckInterfaceSupport(&::IID).unwrap_or(0); + let key = crate::gpu::shader::fnv64(&[(desc.VendorId as u64) << 32 | desc.DeviceId as u64, umd as u64].map(u64::to_le_bytes).concat()); + Ok((crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?, key)) } } @@ -437,6 +479,26 @@ mod tests { let _ = std::fs::remove_file(&path); } + #[test] + fn trying_holds_only_the_pipelines_being_made() { + let path = std::env::temp_dir().join(format!("xcl-trying-test-{}.trying", std::process::id())); + let mut t = Trying { file: std::fs::File::create(&path).unwrap(), now: Vec::new() }; + t.set(1, true); + t.set(2, true); + t.set(3, true); + t.set(1, false); // made + t.set(3, false); // failed: tried again by the next run, not left to the title + drop(t); + assert_eq!(std::fs::read(&path).unwrap(), 2u64.to_le_bytes()); + let _ = std::fs::remove_file(&path); + } + + #[test] + fn another_gpu_or_driver_starts_the_done_file_over() { + assert_eq!(binary_key(5), binary_key(5)); + assert_ne!(binary_key(5), binary_key(6)); + } + #[test] fn done_file_of_another_binary_is_replaced_and_a_torn_record_cut() { let path = std::env::temp_dir().join(format!("xcl-done-test-{}.done", std::process::id())); From d9cea044eed639c5323c79da93fe0a121ba6c903 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:23:31 -0800 Subject: [PATCH 11/13] Shaders: xcl pipelines replays a run's heap windows and their switch-form fallback The tool sets the run's `mem_windows` with its HEAP_WINDOWS flag from the journal (`mem_windows_of`), so a heap-window run's pipelines get the same HLSL and cache keys as in the title. A pipeline the driver refuses with E_OUTOFMEMORY in that form is made again in the switch form through `with_switch_fallback`, as the title makes it since #680. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013hQzywPUY9kSTPQPh31CWh --- crates/xcl/src/hle/d3d12x/real.rs | 24 +++++++++++++++++++++--- crates/xcl/src/pipelines.rs | 9 +++++---- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4632ea328..9c7aaff38 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4351,8 +4351,20 @@ unsafe fn build_stream(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { /// `xcl pipelines`: a journal's pipeline made on `dev` (a plain device of this process) as /// `translated_graphics_pso` / `translated_compute_pso` make it, which fills the DXIL cache /// and the driver's, and released. `driver` is held around the driver's compile only (few of -/// those at once; translation and DXC run freely). Err: what kept it from being made. -pub(crate) unsafe fn warm(dev: &ID3D12Device, r: &super::pso_journal::Replay, driver: impl FnOnce() -> G) -> Result<(), String> { +/// those at once; translation and DXC run freely). Err: what kept it from being made. One the +/// driver refuses with heap windows is made again in the switch form, as the title does. +pub(crate) unsafe fn warm(dev: &ID3D12Device, r: &super::pso_journal::Replay, driver: impl Fn() -> G) -> Result<(), String> { + with_switch_fallback(|| warm_once(dev, r, &driver)) +} + +/// A driver refusal of `warm_once` noted as the title's `driver_pso` notes it. +fn note_heap_window_oom(hr: HRESULT) { + if hr == E_OUTOFMEMORY && crate::gpu::recomp::pso::mem_windows() & crate::gpu::recomp::HEAP_WINDOWS != 0 { + HEAP_WINDOW_OOM.with(|o| o.set(true)); + } +} + +unsafe fn warm_once(dev: &ID3D12Device, r: &super::pso_journal::Replay, driver: &impl Fn() -> G) -> Result<(), String> { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; use windows::core::Interface; let this = dev.as_raw(); @@ -4370,7 +4382,10 @@ pub(crate) unsafe fn warm(dev: &ID3D12Device, r: &super::pso_journal::Replay, made = Some(p); S_OK } - Err(e) => e.code().0, + Err(e) => { + note_heap_window_oom(e.code().0); + e.code().0 + } }); made.ok_or_else(|| windows::core::Error::from_hresult(windows::core::HRESULT(hr))) } @@ -4393,6 +4408,9 @@ pub(crate) unsafe fn warm(dev: &ID3D12Device, r: &super::pso_journal::Replay, let _slot = driver(); let started = std::time::Instant::now(); let made = dev.CreateComputePipelineState::(©); + if let Err(e) = &made { + note_heap_window_oom(e.code().0); + } if let (Ok(p), Some(path)) = (&made, &disk) { if let Ok(b) = p.GetCachedBlob() { driver_cache::keep(path, std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()), started.elapsed()); diff --git a/crates/xcl/src/pipelines.rs b/crates/xcl/src/pipelines.rs index b7b3b1bee..bb3c4ccd2 100644 --- a/crates/xcl/src/pipelines.rs +++ b/crates/xcl/src/pipelines.rs @@ -253,17 +253,18 @@ pub fn run(target: &Path, args: &[String]) -> i32 { let mut g = q.0.lock().unwrap(); let first = g.ingest(&mut file); // the HLSL (and so the cache keys) of the run's memory windows - crate::gpu::recomp::pso::set_mem_windows(g.windows as u32); + crate::gpu::recomp::pso::set_mem_windows(pso_journal::mem_windows_of(g.windows)); (g.taken.len(), first) }; { let g = q.0.lock().unwrap(); println!( - "{}: {first} pipelines to make ({} the title used), {already} done before, {} shaders; {} memory windows; {threads} threads, {gpu_most} driver compiles at once{}", + "{}: {first} pipelines to make ({} the title used), {already} done before, {} shaders; {} memory windows{}; {threads} threads, {gpu_most} driver compiles at once{}", journal.display(), g.used.len(), g.shaders.len(), - g.windows, + g.windows & 0x7F, + if g.windows & 0x80 != 0 { " (from the descriptor heap)" } else { "" }, if watch { "; following the journal (Ctrl+C stops)" } else { "" } ); } @@ -285,7 +286,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 { } let new = g.ingest(&mut file); // (a journal that was empty when the tool started) - crate::gpu::recomp::pso::set_mem_windows(g.windows as u32); + crate::gpu::recomp::pso::set_mem_windows(pso_journal::mem_windows_of(g.windows)); if new > 0 || !g.used.is_empty() { q.1.notify_all(); } From bbf56a8f5bec0a71e5d25e5d5e59e9674cf1c9e1 Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:27:42 -0800 Subject: [PATCH 12/13] Shaders: xcl pipelines retries what Ctrl+C cut short Ctrl+C is how --watch ends, and it left `.trying` behind as a crash does: the next run wrote the pipelines being made at that moment to `pipelines.done` as left to the title, most often the biggest compute programs, the ones most worth making ahead. A console control handler now removes `.trying` before the default handler ends the process, so the next run makes them again; a crash in the driver or DXC still leaves it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013hQzywPUY9kSTPQPh31CWh --- crates/xcl/src/pipelines.rs | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/pipelines.rs b/crates/xcl/src/pipelines.rs index bb3c4ccd2..2f61b2577 100644 --- a/crates/xcl/src/pipelines.rs +++ b/crates/xcl/src/pipelines.rs @@ -54,6 +54,21 @@ fn binary_key(gpu: u64) -> u64 { /// Address space only: pages are committed as used. const WARM_STACK: usize = 512 << 20; +/// This run's `pipelines.trying`, removed on Ctrl+C, Ctrl+Break or closing the console +/// (`on_console_close`). +static TRYING_PATH: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// The pipelines being made when the user stops the tool (Ctrl+C is how `--watch` ends) were cut +/// short, not crashed on: without `.trying` the next run makes them again. FALSE: the default +/// handler then ends the process. (std opens files with FILE_SHARE_DELETE, so the open handle +/// does not keep it.) +unsafe extern "system" fn on_console_close(_kind: u32) -> i32 { + if let Some(p) = TRYING_PATH.get() { + let _ = std::fs::remove_file(p); + } + 0 +} + /// `pipelines.trying`: the pipelines in the making now, written whole at each change, so a run cut /// short (a crash, or Ctrl+C) leaves the next run exactly those. struct Trying { @@ -228,8 +243,8 @@ pub fn run(target: &Path, args: &[String]) -> i32 { return 2; } }; - // what a run that ended without its summary (a crash in the driver or DXC) was making: left - // to the title, so the same pipeline does not end every run + // what a run that crashed (in the driver or DXC) was making: left to the title, so the same + // pipeline does not end every run (a run the user stopped removes the file) let trying_path = journal.with_extension("trying"); let crashed: Vec = { let t = std::fs::read(&trying_path).unwrap_or_default(); @@ -243,7 +258,11 @@ pub fn run(target: &Path, args: &[String]) -> i32 { eprintln!("xcl pipelines: the last run ended while making {} pipelines: left to the title", crashed.len()); } let trying = match std::fs::File::create(&trying_path) { - Ok(f) => Mutex::new(Trying { file: f, now: Vec::new() }), + Ok(f) => { + let _ = TRYING_PATH.set(trying_path.clone()); + unsafe { windows_sys::Win32::System::Console::SetConsoleCtrlHandler(Some(on_console_close), 1) }; + Mutex::new(Trying { file: f, now: Vec::new() }) + } Err(e) => { eprintln!("xcl pipelines: {}: {e}", trying_path.display()); return 2; From c02d05921a5dae84d2607af4c61dc063d09ecdfb Mon Sep 17 00:00:00 2001 From: ramen-bully <248799758+ramen-bully@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:48:13 -0800 Subject: [PATCH 13/13] D3D12.X: the pipeline journal opens off the title's threads, and locks only to append The first pipeline the title noted read the frame headers of every earlier run (about 63 000 for a 123 MB journal) with the journal's lock held, and each later one hashed its shaders and desc under the same lock, so the title's pipeline threads waited on one another. An entry is now built and hashed with no lock held, and the lock covers its append only. The journal is opened on a thread of its own; what is noted meanwhile waits in memory, each frame once (up to 256 MB, past which the journal is off for the run), and is written in order once it is open. `XCL_PSO_JOURNAL` is read once, and a journal turned off stops entries being built at all. A panic on another thread while it held the lock no longer ends the journal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013hQzywPUY9kSTPQPh31CWh --- crates/xcl/src/hle/d3d12x/pso_journal.rs | 196 +++++++++++++++++++---- 1 file changed, 163 insertions(+), 33 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_journal.rs b/crates/xcl/src/hle/d3d12x/pso_journal.rs index 06dc27fba..651814c42 100644 --- a/crates/xcl/src/hle/d3d12x/pso_journal.rs +++ b/crates/xcl/src/hle/d3d12x/pso_journal.rs @@ -10,11 +10,16 @@ //! pipeline, `C` a compute one, `U` (no payload) pipeline `hash` was built. A pipeline's //! payload names its shaders by hash; each shader is written once, before the first pipeline //! that uses it. Duplicates of earlier runs are not written again. +//! +//! On the title's pipeline threads an entry is built and hashed with no lock held; the lock +//! covers its append only. The journal is opened (the frame headers of earlier runs read) on a +//! thread of its own, and what is noted meanwhile waits in memory (`State::Opening`). use std::collections::HashSet; use std::io::{Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; -use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, MutexGuard}; use windows::Win32::Graphics::Direct3D12::*; pub const MAGIC: &[u8; 8] = b"XCLPJ001"; @@ -29,10 +34,39 @@ struct Journal { seen: HashSet<(u8, u64)>, } -static J: Mutex>> = Mutex::new(None); +/// A frame to append: tag, windows byte, hash, payload. +type Out<'a> = (u8, u8, u64, &'a [u8]); + +enum State { + Closed, + /// being opened (`open_in_background`): the frames noted meanwhile, owned, each once, and + /// their bytes + Opening(Vec<(u8, u8, u64, Vec)>, HashSet<(u8, u64)>, usize), + Open(Journal), + Off, +} + +static J: Mutex = Mutex::new(State::Closed); +/// set with `State::Off`, so that the title's threads stop building entries +static OFF: AtomicBool = AtomicBool::new(false); +/// what may wait in memory while the journal is opened +const OPENING_MAX: usize = 256 << 20; fn enabled() -> bool { - std::env::var("XCL_PSO_JOURNAL").map_or(true, |v| v != "0") + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PSO_JOURNAL").map_or(true, |v| v != "0")) && !OFF.load(Ordering::Relaxed) +} + +/// A panic on another thread while it held the lock does not end the journal (each change of +/// the state is one assignment, so it stays whole). +fn lock() -> MutexGuard<'static, State> { + J.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn turn_off(g: &mut State, why: impl std::fmt::Display) { + crate::xlog_warn!("pipeline journal: {why}: off for this run"); + *g = State::Off; + OFF.store(true, Ordering::Relaxed); } fn open() -> Option { @@ -86,17 +120,60 @@ fn open() -> Option { Some(Journal { file, seen }) } -/// Runs `f` on the journal; a write error turns it off for the rest of the run (0). -fn with(f: impl FnOnce(&mut Journal) -> std::io::Result) -> u64 { - let mut g = J.lock().unwrap(); - let Some(j) = g.get_or_insert_with(open).as_mut() else { return 0 }; - match f(j) { - Ok(h) => h, - Err(e) => { - crate::xlog_warn!("pipeline journal: {e}: off for this run"); - *g = Some(None); - 0 +/// Appends `frames` in order (shaders before the pipeline that names them); a write error turns +/// the journal off for the rest of the run. The first call starts the opening. +fn write(frames: &[Out]) { + if note(&mut lock(), frames) && std::thread::Builder::new().name("xcl-pso-journal".into()).spawn(open_in_background).is_err() { + turn_off(&mut lock(), "no thread to open it"); + } +} + +/// `write` on the state; true: the caller starts the opening. +fn note(g: &mut State, frames: &[Out]) -> bool { + match g { + State::Off => false, + State::Open(j) => { + if let Err(e) = frames.iter().try_for_each(|&(t, w, h, p)| put(j, t, w, h, p)) { + turn_off(g, e); + } + false } + State::Opening(q, kept, bytes) => { + for &(t, w, h, p) in frames { + if kept.insert((t, h)) { + *bytes += p.len(); + q.push((t, w, h, p.to_vec())); + } + } + if *bytes > OPENING_MAX { + turn_off(g, "too much noted while it was opened"); + } + false + } + State::Closed => { + *g = State::Opening(Vec::new(), HashSet::new(), 0); + note(g, frames); + true + } + } +} + +/// Opens the journal with no lock held (the title's threads go on noting), then writes what +/// they noted meanwhile. +fn open_in_background() { + let j = open(); + opened(&mut lock(), j); +} + +fn opened(g: &mut State, j: Option) { + let State::Opening(q, ..) = std::mem::replace(g, State::Off) else { return }; + let Some(mut j) = j else { + OFF.store(true, Ordering::Relaxed); + return; + }; + match q.iter().try_for_each(|(t, w, h, p)| put(&mut j, *t, *w, *h, p)) { + Ok(()) => *g = State::Open(j), + Err(e) => turn_off(g, e), } } @@ -204,13 +281,30 @@ fn put(j: &mut Journal, tag: u8, windows: u8, hash: u64, payload: &[u8]) -> std: Ok(()) } -fn put_shader(j: &mut Journal, out: &mut Vec, sh: Option<&[u8]>) -> std::io::Result<()> { +/// A pipeline's frames, built and hashed with no lock held: its shaders', then its own. +struct Entry<'a> { + shaders: Vec>, + tag: u8, + windows: u8, + hash: u64, + payload: Vec, +} + +impl Entry<'_> { + fn frames(&self) -> Vec> { + let mut f = self.shaders.clone(); + f.push((self.tag, self.windows, self.hash, &self.payload)); + f + } +} + +/// A shader's hash into the pipeline's payload, and its frame (none for an empty slot). +fn add_shader<'a>(shaders: &mut Vec>, out: &mut Vec, sh: Option<&'a [u8]>) { let h = sh.map_or(0, crate::gpu::shader::fnv64); if let Some(sh) = sh { - put(j, b'S', 0, h, sh)?; + shaders.push((b'S', 0, h, sh)); } out.extend_from_slice(&h.to_le_bytes()); - Ok(()) } /// `pso::mem_windows` in a frame's byte: the count in the low 7 bits, `HEAP_WINDOWS` in the top @@ -224,26 +318,34 @@ pub fn mem_windows_of(byte: u8) -> u32 { (byte & 0x7F) as u32 | if byte & 0x80 != 0 { crate::gpu::recomp::HEAP_WINDOWS } else { 0 } } -fn finish(j: &mut Journal, tag: u8, mut payload: Vec) -> std::io::Result { +fn entry(shaders: Vec, tag: u8, mut payload: Vec) -> Entry { // the memory windows are part of what the pipeline is (its HLSL differs with them, and with // heap windows) let windows = windows_byte(crate::gpu::recomp::pso::mem_windows()); payload.push(windows); let hash = crate::gpu::shader::fnv64(&payload); payload.pop(); - put(j, tag, windows, hash, &payload)?; - Ok(hash) + Entry { shaders, tag, windows, hash, payload } +} + +/// Writes the entry; its hash. +fn note_entry(e: Entry) -> u64 { + write(&e.frames()); + e.hash } /// Note a graphics pipeline; its hash for `used`, 0 = not written. pub unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> u64 { - with(|j| graphics_in(j, d)) + if !enabled() { + return 0; + } + note_entry(graphics_entry(d)) } -unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> std::io::Result { - let mut p = Vec::new(); +unsafe fn graphics_entry(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Entry<'_> { + let (mut shaders, mut p) = (Vec::new(), Vec::new()); for b in [&d.VS, &d.PS, &d.DS, &d.HS, &d.GS] { - put_shader(j, &mut p, bytes_of(b))?; + add_shader(&mut shaders, &mut p, bytes_of(b)); } let desc = graphics_bytes(d); p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); @@ -262,19 +364,20 @@ unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) - p.extend_from_slice(&w.to_le_bytes()); } } - finish(j, b'G', p) + entry(shaders, b'G', p) } /// Note a compute pipeline; its hash for `used`, 0 = not written. pub unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> u64 { - with(|j| { - let mut p = Vec::new(); - put_shader(j, &mut p, bytes_of(&d.CS))?; - let desc = compute_bytes(d); - p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); - p.extend_from_slice(&desc); - finish(j, b'C', p) - }) + if !enabled() { + return 0; + } + let (mut shaders, mut p) = (Vec::new(), Vec::new()); + add_shader(&mut shaders, &mut p, bytes_of(&d.CS)); + let desc = compute_bytes(d); + p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); + p.extend_from_slice(&desc); + note_entry(entry(shaders, b'C', p)) } /// Pipeline `hash` was built (the title used it): `xcl pipelines` makes these first. @@ -282,7 +385,7 @@ pub fn used(hash: u64) { if hash == 0 { return; } - with(|j| put(j, b'U', 0, hash, &[]).map(|_| 0)); + write(&[(b'U', 0, hash, &[])]); } /// A journal's pipeline, read back with everything it points to owned. @@ -458,6 +561,33 @@ mod tests { assert_eq!(for_each_frame(&bytes[..bytes.len() - 3], |_| {}) < whole, true); } + /// The entry written straight to `j` (no global state); its hash. + unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> std::io::Result { + let e = graphics_entry(d); + e.frames().iter().try_for_each(|&(t, w, h, p)| put(j, t, w, h, p))?; + Ok(e.hash) + } + + #[test] + fn what_is_noted_while_the_journal_opens_is_written_after_in_order() { + let (vs, ps) = (vec![1u8; 8], vec![2u8; 8]); + let mut g = State::Closed; + assert!(note(&mut g, &[(b'S', 0, 11, &vs[..]), (b'G', 0, 21, &[7])]), "the first note starts the opening"); + assert!(!note(&mut g, &[(b'S', 0, 11, &vs[..]), (b'S', 0, 12, &ps[..]), (b'G', 0, 22, &[8])]), "only once"); + assert!(!note(&mut g, &[(b'U', 0, 21, &[])])); + let State::Opening(q, _, bytes) = &g else { panic!("not opening") }; + assert_eq!((q.len(), *bytes), (5, 18), "a shader noted twice is kept once"); + opened(&mut g, Some(Journal { file: tempfile(), seen: HashSet::new() })); + let State::Open(j) = &mut g else { panic!("not open") }; + let mut bytes = MAGIC.to_vec(); + use std::io::{Read, Seek}; + j.file.seek(std::io::SeekFrom::Start(0)).unwrap(); + j.file.read_to_end(&mut bytes).unwrap(); + let mut order = Vec::new(); + for_each_frame(&bytes, |f| order.push((f.tag, f.hash))); + assert_eq!(order, [(b'S', 11), (b'G', 21), (b'S', 12), (b'G', 22), (b'U', 21)]); + } + fn tempfile() -> std::fs::File { let p = std::env::temp_dir().join(format!("xcl_pso_journal_{}.bin", std::process::id())); let f = std::fs::OpenOptions::new().create(true).truncate(true).read(true).write(true).open(&p).unwrap();