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 46e237b2c..f6817042f 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/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..651814c42 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pso_journal.rs @@ -0,0 +1,597 @@ +//! 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 (`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 +//! 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::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, MutexGuard}; +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)>, +} + +/// 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 { + 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 { + 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 }) +} + +/// 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), + } +} + +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)) +} + +/// 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(()) +} + +/// 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 { + shaders.push((b'S', 0, h, sh)); + } + out.extend_from_slice(&h.to_le_bytes()); +} + +/// `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 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(); + 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 { + if !enabled() { + return 0; + } + note_entry(graphics_entry(d)) +} + +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] { + 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()); + 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()); + } + } + 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 { + 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. +pub fn used(hash: u64) { + if hash == 0 { + return; + } + write(&[(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; + if n > (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 { + 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 the_heap_windows_flag_is_kept() { + let heap = crate::gpu::recomp::HEAP_WINDOWS; + for w in [1, 4, 4 | heap, 16 | heap] { + assert_eq!(mem_windows_of(windows_byte(w)), w); + } + assert_ne!(windows_byte(4), windows_byte(4 | heap)); + } + + #[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); + } + + /// 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(); + 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 ac7ab4c4d..9c7aaff38 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3949,32 +3949,20 @@ 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`, 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, + 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 +4007,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(); @@ -4292,9 +4310,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 @@ -4323,6 +4348,80 @@ 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. 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(); + 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) => { + note_heap_window_oom(e.code().0); + 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(()); + } + // 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::(©); + 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()); + } + } + 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 bb6c3e921..79f4b298b 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -37,6 +37,10 @@ Usage: --direct [--sample N] [--seed S] [--validate] [--compare]: direct DXIL translator coverage over a seeded sample (default 200 programs, 0 = all); also --timeout, --max-bytes, --threads, --json, --hash H, --dump DIR. + 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. @@ -68,6 +72,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..2f61b2577 --- /dev/null +++ b/crates/xcl/src/pipelines.rs @@ -0,0 +1,581 @@ +//! `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) 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(), 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; + +/// 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 { + 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) + 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 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(); + 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()))); + 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 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, gpu_key) = 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()); + } + // `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); + + 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(gpu_key); + let mut done_file = match open_done(&done_path, key) { + Ok((f, done)) => { + q.0.lock().unwrap().taken.extend(done); + f + } + Err(e) => { + eprintln!("xcl pipelines: {}: {e}", done_path.display()); + return 2; + } + }; + // 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(); + 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) => { + 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; + } + }; + 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(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{}", + journal.display(), + g.used.len(), + g.shaders.len(), + g.windows & 0x7F, + if g.windows & 0x80 != 0 { " (from the descriptor heap)" } else { "" }, + 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(pso_journal::mem_windows_of(g.windows)); + if new > 0 || !g.used.is_empty() { + q.1.notify_all(); + } + }); + } + 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 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 { + 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; + 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) + 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()); + } + 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 + 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", + 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(), + } +} + +/// 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, 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)) + } +} + +/// Opens `pipelines.done` for `key` (this binary): the hashes it holds, and the file positioned +/// after them. A file of another binary starts over; a torn last record is cut off. +fn open_done(path: &Path, key: u64) -> std::io::Result<(std::fs::File, Vec)> { + 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() { + 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 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 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())); + 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()); + 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); + } +}