diff --git a/README.md b/README.md index c086a8e64e..6324896115 100644 --- a/README.md +++ b/README.md @@ -262,18 +262,30 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
Switches, caches, logs and the files XCL writes -- When a game folder contains a `shaders.rpf` shader pack or loose `.dxbc` files under - `shaders/`, XCL shows shader preparation in the game window before executing title code. - The same window then presents the game. The percentage counts - processed records. The timer counts seconds since one finished (or preparation started); - five seconds without progress counts as a stall, and the window shows when the last one ended. - XCL prepares supported shader stages and compute pipelines, including - split pieces and their whole fallback. Graphics pipelines that need state supplied by the - title are created during play. Later launches reuse matching cache entries. - Closing the window cancels the launch. A compiler or driver failure stops it and reports - the cause. Null-renderer runs skip shader preparation. With presentation disabled, the gate runs without a window. - `XCL_PREPARE=0` leaves the preparation out: the game starts at once and builds the shaders it - uses as it goes (it stands still while they build). +- XCL uses the game window to show preparation progress before executing title code. It prepares + supported shader packs, supported loose shaders under `shaders/`, recorded graphics history and + staged pipeline recipes. Closing the window cancels launch. A failed staged recipe stops launch. + With presentation disabled, preparation runs without a window. A staged corpus still gates + launch when the null renderer is selected. For an unstaged title set `XCL_PREPARE=0` + to skip startup preparation, or `XCL_PREPARE_GRAPHICS=0` to skip optional graphics history. + Native recipes validated on this adapter and driver reuse their verified blobs across + rebuilds. Changes to translation, pipeline layout, settings or cache files trigger validation. +- To prepare known graphics, two-pass mesh and compute recipes offline, use a local + [archive layout profile](scripts/pso_corpus/archive-profile.md) with the following commands. + The staging command accepts several journals and deduplicates their recipes. + + ```powershell + python scripts/pso_corpus/pso_archive.py profile.json archive.bin pipelines.bin + python scripts/pso_corpus/stage.py --title pipelines.bin + xcl shaders --prepare-corpus --threads 8 + ``` + + The offline command accepts up to 32 workers. Normal launch also prepares the staged corpus. + When a shader pack or local history overlaps the corpus, XCL prepares each exact match once. + Use the same adapter and memory-window + configuration for offline preparation and play so the driver can reuse the results. + Graphics state combinations absent from the supplied recipes and local history can still + require a first-use compile during play. - For compute shaders that XCL can split, the runtime first tries the saved driver blob for the whole shader. A usable blob lets the GPU run it in one dispatch. If the blob is missing or the driver rejects it, XCL builds the split pieces. diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index 22b136da8e..c2d191e8f6 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -50,6 +50,41 @@ fn direct_sources(dir: &Path, out: &mut Vec) { mod source_hash; use source_hash::{add, add_source}; +// Bump when the native builder (including the D3D12.X glue in real.rs) changes the +// mapping from a journal recipe to driver descriptors or blob acceptance. Shader +// translator/toolchain, driver, adapter, settings and per-file stamps are keyed separately. +const NATIVE_PREPARATION_ABI: &[u8] = b"xcl-native-preparation-v1"; +const PREPARATION_LAYOUT_SOURCES: &[&str] = &[ + "src/gpu/recomp/pso.rs", // root signatures, translation glue, split pipeline layout + "src/hle/d3d12x/real/two_pass_identity.rs", // driver-blob identities for both mesh passes + "src/hle/d3d12x/gfx_records.rs", // normalized recipe fields and reconstruction +]; + +fn preparation_source_id(root: &Path) -> u64 { + let mut id = 0xcbf2_9ce4_8422_2325u64; + add(&mut id, NATIVE_PREPARATION_ABI); + for &relative in PREPARATION_LAYOUT_SOURCES { + println!("cargo:rerun-if-changed={relative}"); + add(&mut id, relative.as_bytes()); + add(&mut id, &[0]); + add_source(&mut id, &std::fs::read(root.join(relative)).expect("read pipeline layout input")); + add(&mut id, &[0]); + } + for name in ["TARGET", "PROFILE", "CARGO_ENCODED_RUSTFLAGS", "OPT_LEVEL", "DEBUG"] { + add(&mut id, name.as_bytes()); + add(&mut id, std::env::var(name).unwrap_or_default().as_bytes()); + add(&mut id, &[0]); + } + let rustc = std::process::Command::new(std::env::var_os("RUSTC").expect("rustc")) + .arg("-vV").output().expect("read compiler identity"); + assert!(rustc.status.success()); + add_source(&mut id, &rustc.stdout); + let mut features: Vec<_> = std::env::vars().filter(|(name,_)| name.starts_with("CARGO_FEATURE_")).collect(); + features.sort(); + for (name, value) in features { add(&mut id, name.as_bytes()); add(&mut id, value.as_bytes()); add(&mut id, &[0]); } + id +} + fn main() { // xcl.exe without high-entropy ASLR: the title's memory then lies under 2^40, which a // retail title's BVH builder requires of its GPU addresses (#585, PR #631) @@ -59,6 +94,7 @@ fn main() { _ => {} } let root = Path::new(env!("CARGO_MANIFEST_DIR")); + println!("cargo:rustc-env=XCL_NATIVE_PREPARATION_ID={:016x}", preparation_source_id(root)); let mut h = 0xcbf2_9ce4_8422_2325u64; add(&mut h, b"xcl-translator-source-v1\0"); add(&mut h, TRANSLATION_GLUE_REVISION.as_bytes()); diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 379bd8518f..ba07463d81 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -691,7 +691,7 @@ fn cache_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &st h } -fn cache_key(src: &str, entry: &str, profile: &str) -> u64 { +pub(crate) fn cache_key(src: &str, entry: &str, profile: &str) -> u64 { cache_key_for_toolchain(src, entry, profile, toolchain_identity()) } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 5d000775ef..6335faa475 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -80,8 +80,29 @@ 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 title = TITLE_WINDOWS.load(std::sync::atomic::Ordering::Relaxed); + if title != 0 { + return windows_for(title & !super::HEAP_WINDOWS, title & super::HEAP_WINDOWS != 0 && !SWITCH_FORM.with(|s| s.get())); + } 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()) { + windows_for(n, heap_windows() && !SWITCH_FORM.with(|s| s.get())) +} + +/// The title's windows (`mem_windows` with `HEAP_WINDOWS`) for a process without its memory: a +/// shader preparation worker builds the title's pipelines with them (0: none given). +static TITLE_WINDOWS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// `mem_windows` is `windows` from here on (a preparation worker: `uma::leave_out`). +pub fn set_title_windows(windows: u32) { + TITLE_WINDOWS.store(windows, std::sync::atomic::Ordering::Relaxed); +} + +/// `n` windows as shaders take them: from the descriptor heap (`heap`), or in the switch form +/// over the root UAVs – of which there are `MAX_WINDOWS`, so never more there (the HLSL path +/// refused a wider switch, and DXIL quietly made it 4: a 16-window run whose heap views could +/// not be made, or a pipeline the driver refused with them, lost every shader on HLSL). +fn windows_for(n: u32, heap: bool) -> u32 { + if n > 1 && heap { n | super::HEAP_WINDOWS } else { n @@ -178,6 +199,8 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa /// each at every start. Keyed by two hashes and the length of the bytes, the stage and the /// translation parameters; translator sources and the DXC toolchain identify compatible builds. /// `XCL_TRANSLATED_CACHE=0` turns it off. +pub(crate) fn translation_cache_identity() -> u64 { translated::identity() } + mod translated { use super::{Compiled, Stage}; use std::path::{Path, PathBuf}; @@ -245,7 +268,7 @@ mod translated { /// Translation semantics and the DXC DLLs, independent of link metadata and build profile. /// Zero means the disk cache is disabled. - fn identity() -> u64 { + pub(super) fn identity() -> u64 { static I: OnceLock = OnceLock::new(); *I.get_or_init(|| { if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") { diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 8341c61ed3..17872bd68d 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -788,6 +788,13 @@ impl Arena { static GLOBAL: OnceLock> = OnceLock::new(); +/// A process that holds no title memory (a shader preparation worker): `get` is None from here +/// on, and nothing is reserved or committed for it (a run's region commits its coherent window). +/// Before any `get`. +pub fn leave_out() { + let _ = GLOBAL.set(None); +} + /// The title's graphics memory XCL places in the coherent window (`note_coherent_need`) is /// known only once it asks for it, and the window is committed when it is made: its size is /// what the title asked for in its last run (`/cache/uma_coherent.txt`) and XCL's own diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs new file mode 100644 index 0000000000..8221bf7ad3 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -0,0 +1,1044 @@ +//! The graphics pipelines a title used, as it described them, kept for the shader preparation of +//! its next run (`shaders::prepare_for_launch`): it builds them before the title starts, the way +//! the title does (`real::prepare_graphics`), so the title finds their translations and the +//! driver's blobs on disk. `used-pipelines.txt` holds only the keys of the shader sets and the +//! driver cache only blobs named after the translated DXIL: neither is enough to make one again. +//! +//! `used-graphics-pipelines.bin` in the title's cache (older runs used the shared DXIL cache): +//! +//! ```text +//! file = "XCLGFXP\0", version u32, entry* +//! entry = length u32, check u32 (the low half of fnv64 of the payload), payload +//! payload = 1 key u64 shaders [u64; 5] state input* a pipeline +//! | 2 key u64 bytes a shader (preparation job files only) +//! | 3 key u64 shaders [u64; 2] layout state a mesh pipeline stream +//! | 4 key u64 shaders [u64; 5] state input* a pipeline with depth bounds enabled +//! key = `real::shaders_key` of the set, in mesh then PS order for mesh; in a shader entry, +//! `real::shader_key` of it +//! shaders = `real::shader_key` of VS, PS, DS, HS, GS, or mesh, PS (0: none) +//! layout = subobject count (u8), then subobject types in stream order (u8 each) +//! state = every field of the description but its pointers, in `state`'s order (varints) +//! input = count, then each element's semantic name (length, bytes), index, format, slot, +//! offset, class, step rate (varints) +//! ``` +//! +//! Integers little-endian, varints LEB128. A pipeline entry holds no shader code: the preparation +//! takes the shaders from the title's shader files by key, as it does those of `used-shaders.txt` +//! (~200 bytes a pipeline). A file of another version is read as none and started again; an entry +//! cut short or damaged ends the file there (the writer cuts it off before it appends). The title +//! side: a pipeline's description is noted at its first use in a run (`note`, from +//! `pso_async::on_first_use`), each once, written by a thread of its own, the file at most +//! `XCL_GFX_RECORDS_MB` (64). + +use std::collections::HashSet; +use std::ffi::CString; +use std::io::{Seek, Write}; +use std::path::{Path, PathBuf}; +use windows::Win32::Graphics::Direct3D12::*; + +const MAGIC: &[u8; 8] = b"XCLGFXP\0"; +/// The file format and existing entry layouts. Optional new tags keep earlier entries readable. +const VERSION: u32 = 1; +const HEADER: usize = 12; +const PIPELINE: u8 = 1; +const SHADER: u8 = 2; +const MESH_PIPELINE: u8 = 3; +const DEPTH_BOUNDS_PIPELINE: u8 = 4; +const MAX_MESH_LAYOUT: usize = 19; // includes four inactive shader slots and an empty input layout + +/// New records belong to the active title. A shared translation cache can serve unrelated titles. +pub(crate) fn path() -> PathBuf { + if let Some(boot) = crate::state::boot() { return boot.cache_dir().join("used-graphics-pipelines.bin"); } + shared_history_path() +} + +pub(crate) fn shared_history_path() -> PathBuf { + crate::gpu::recomp::dxc::cache_dir().join("used-graphics-pipelines.bin") +} + +/// `XCL_GFX_RECORDS_MB`: the most the records may take on disk (64 MB: ~300 000 pipelines). +fn cap_bytes() -> u64 { + cap_of(std::env::var("XCL_GFX_RECORDS_MB").ok().as_deref()) +} + +fn cap_of(v: Option<&str>) -> u64 { + v.and_then(|v| v.trim().parse::().ok()).unwrap_or(64) << 20 +} + +fn put_var(out: &mut Vec, mut v: u64) { + loop { + let b = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + out.push(b); + return; + } + out.push(b | 0x80); + } +} + +struct Reader<'a>(&'a [u8]); + +impl Reader<'_> { + fn var(&mut self) -> Option { + let mut v = 0u64; + for shift in (0..64).step_by(7) { + let (&b, rest) = self.0.split_first()?; + self.0 = rest; + v |= ((b & 0x7f) as u64) << shift; + if b & 0x80 == 0 { + return Some(v); + } + } + None + } + fn u32var(&mut self) -> Option { + self.var().and_then(|v| u32::try_from(v).ok()) + } + fn bounded_var(&mut self, max: u32) -> Option { + let before = self.0.len(); + let v = self.u32var()?; + let bits = (u32::BITS - v.leading_zeros()).max(1); + (before - self.0.len() == bits.div_ceil(7) as usize && v <= max).then_some(v) + } + fn u64(&mut self) -> Option { + let (b, rest) = self.0.split_at_checked(8)?; + self.0 = rest; + Some(u64::from_le_bytes(b.try_into().ok()?)) + } + fn bytes(&mut self, n: usize) -> Option<&[u8]> { + let (b, rest) = self.0.split_at_checked(n)?; + self.0 = rest; + Some(b) + } +} + +/// Every field of `d` but its pointers (shaders, root signature, input layout, stream output, +/// cached blob), each as a u32 handed to `f`, which may change it: one order for writing and +/// reading. What the title's translated pipeline is made of beside its shaders +/// (`real::graphics_blob_key` hashes the same). +fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32, u32)) { + macro_rules! int { + ($x:expr) => {{ + let mut v = $x as u32; + f(&mut v, u32::MAX); + $x = v as i32; + }}; + } + macro_rules! byte { + ($x:expr) => {{ + let mut v = $x as u32; + f(&mut v, u8::MAX.into()); + $x = v as u8; + }}; + } + macro_rules! float { + ($x:expr) => {{ + let mut v = $x.to_bits(); + f(&mut v, u32::MAX); + $x = f32::from_bits(v); + }}; + } + let b = &mut d.BlendState; + int!(b.AlphaToCoverageEnable.0); + int!(b.IndependentBlendEnable.0); + for rt in &mut b.RenderTarget { + int!(rt.BlendEnable.0); + int!(rt.LogicOpEnable.0); + int!(rt.SrcBlend.0); + int!(rt.DestBlend.0); + int!(rt.BlendOp.0); + int!(rt.SrcBlendAlpha.0); + int!(rt.DestBlendAlpha.0); + int!(rt.BlendOpAlpha.0); + int!(rt.LogicOp.0); + byte!(rt.RenderTargetWriteMask); + } + f(&mut d.SampleMask, u32::MAX); + let r = &mut d.RasterizerState; + int!(r.FillMode.0); + int!(r.CullMode.0); + int!(r.FrontCounterClockwise.0); + int!(r.DepthBias); + float!(r.DepthBiasClamp); + float!(r.SlopeScaledDepthBias); + int!(r.DepthClipEnable.0); + int!(r.MultisampleEnable.0); + int!(r.AntialiasedLineEnable.0); + f(&mut r.ForcedSampleCount, u32::MAX); + int!(r.ConservativeRaster.0); + let z = &mut d.DepthStencilState; + int!(z.DepthEnable.0); + int!(z.DepthWriteMask.0); + int!(z.DepthFunc.0); + int!(z.StencilEnable.0); + byte!(z.StencilReadMask); + byte!(z.StencilWriteMask); + for face in [&mut z.FrontFace, &mut z.BackFace] { + int!(face.StencilFailOp.0); + int!(face.StencilDepthFailOp.0); + int!(face.StencilPassOp.0); + int!(face.StencilFunc.0); + } + int!(d.IBStripCutValue.0); + int!(d.PrimitiveTopologyType.0); + f(&mut d.NumRenderTargets, 8); + for format in &mut d.RTVFormats { + int!(format.0); + } + int!(d.DSVFormat.0); + f(&mut d.SampleDesc.Count, u32::MAX); + f(&mut d.SampleDesc.Quality, u32::MAX); + f(&mut d.NodeMask, u32::MAX); + int!(d.Flags.0); +} + +/// The pipeline entry of `d` (a title's description, its input layout readable), of the shader +/// set `key` whose shaders are `shaders` (`Record::shaders`). +pub(crate) unsafe fn encode(key: u64, shaders: [u64; 5], d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Vec { + let mut out = Vec::with_capacity(256); + out.push(PIPELINE); + out.extend_from_slice(&key.to_le_bytes()); + for s in shaders { + out.extend_from_slice(&s.to_le_bytes()); + } + // (a copy for `state`, which takes the fields by `&mut`; its pointers are not used) + let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(d); + state(&mut copy, &mut |v, _| put_var(&mut out, *v as u64)); + let il = &d.InputLayout; + let elems = if il.NumElements > 0 && !il.pInputElementDescs.is_null() { std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) } else { &[] }; + put_var(&mut out, elems.len() as u64); + for e in elems { + let name = if e.SemanticName.0.is_null() { &[][..] } else { std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char).to_bytes() }; + put_var(&mut out, name.len() as u64); + out.extend_from_slice(name); + for v in [e.SemanticIndex, e.Format.0 as u32, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0 as u32, e.InstanceDataStepRate] { + put_var(&mut out, v as u64); + } + } + out +} + +fn valid_mesh_layout(shaders: [u64; 2], layout: &[u32]) -> bool { + if shaders[0] == 0 || layout.len() > MAX_MESH_LAYOUT { + return false; + } + let mut seen = 0u32; + for &id in layout { + match D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(id as i32) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS => {} + _ => return false, + } + let bit = 1 << id; + if seen & bit != 0 { + return false; + } + seen |= bit; + } + let has = |kind: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE| seen & (1 << kind.0) != 0; + (has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS) != has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS)) + && (shaders[1] == 0 || has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS)) + && !(has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL) && has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1)) +} + +/// A mesh stream entry with shader keys in mesh, PS order and subobjects in their original order. +pub(crate) fn encode_mesh(key: u64, shaders: [u64; 2], layout: &[u32], d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, depth_bounds: bool) -> Option> { + if key == 0 || !valid_mesh_layout(shaders, layout) || d.NumRenderTargets > 8 { + return None; + } + let depth1 = layout.contains(&(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1.0 as u32)); + if depth_bounds && !depth1 { return None; } + let mut values = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + BlendState: d.BlendState, + SampleMask: d.SampleMask, + RasterizerState: d.RasterizerState, + DepthStencilState: d.DepthStencilState, + IBStripCutValue: d.IBStripCutValue, + PrimitiveTopologyType: d.PrimitiveTopologyType, + NumRenderTargets: d.NumRenderTargets, + RTVFormats: d.RTVFormats, + DSVFormat: d.DSVFormat, + SampleDesc: d.SampleDesc, + NodeMask: d.NodeMask, + Flags: d.Flags, + ..Default::default() + }; + let mut out = Vec::with_capacity(256); + out.push(MESH_PIPELINE); + out.extend_from_slice(&key.to_le_bytes()); + for shader in shaders { + out.extend_from_slice(&shader.to_le_bytes()); + } + out.push(layout.len() as u8); + out.extend(layout.iter().map(|&id| id as u8)); + state(&mut values, &mut |v, _| put_var(&mut out, (*v).into())); + if depth1 { put_var(&mut out, u64::from(depth_bounds)); } + Some(out) +} + +/// A shader entry (the preparation's job files): `bytes`, of `real::shader_key` `key`. +pub(crate) fn shader_entry(key: u64, bytes: &[u8]) -> Vec { + let mut out = Vec::with_capacity(9 + bytes.len()); + out.push(SHADER); + out.extend_from_slice(&key.to_le_bytes()); + out.extend_from_slice(bytes); + out +} + +/// A pipeline as a title described it, but its shaders and root signature (`desc` puts them in). +pub(crate) struct Record { + pub key: u64, + pub depth_bounds: bool, + /// `real::shader_key` of the VS, PS, DS, HS, GS (0: none) + pub shaders: [u64; 5], + desc: Box, + inputs: Vec, + _names: Vec, +} + +// (only read once made; the names the inputs point at live as long) +unsafe impl Send for Record {} +unsafe impl Sync for Record {} + +impl Record { + /// The description with the shaders `code` (VS, PS, DS, HS, GS), pointing into `self` and + /// `code`, with no root signature (a translated pipeline gets XCL's). + pub(crate) fn desc(&self, code: [Option<&[u8]>; 5]) -> D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // (no root signature in it: nothing is released twice) + let mut d: D3D12_GRAPHICS_PIPELINE_STATE_DESC = unsafe { std::ptr::read(&*self.desc) }; + let bytecode = |c: Option<&[u8]>| c.map_or_else(D3D12_SHADER_BYTECODE::default, |c| D3D12_SHADER_BYTECODE { pShaderBytecode: c.as_ptr().cast(), BytecodeLength: c.len() }); + let [vs, ps, ds, hs, gs] = code; + (d.VS, d.PS, d.DS, d.HS, d.GS) = (bytecode(vs), bytecode(ps), bytecode(ds), bytecode(hs), bytecode(gs)); + if !self.inputs.is_empty() { + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: self.inputs.as_ptr(), NumElements: self.inputs.len() as u32 }; + } + d + } +} + +pub(crate) struct MeshRecord { + pub key: u64, + pub shaders: [u64; 2], + pub layout: Vec, + pub depth_bounds: bool, + desc: Box, +} + +pub(crate) fn depth_stencil1(d: &D3D12_DEPTH_STENCIL_DESC, bounds: bool) -> D3D12_DEPTH_STENCIL_DESC1 { + D3D12_DEPTH_STENCIL_DESC1 { + DepthEnable: d.DepthEnable, DepthWriteMask: d.DepthWriteMask, DepthFunc: d.DepthFunc, + StencilEnable: d.StencilEnable, StencilReadMask: d.StencilReadMask, StencilWriteMask: d.StencilWriteMask, + FrontFace: d.FrontFace, BackFace: d.BackFace, DepthBoundsTestEnable: bounds.into(), + } +} + +// The decoder starts with null pointers and only fills scalar fields. The descriptor is immutable. +unsafe impl Send for MeshRecord {} +unsafe impl Sync for MeshRecord {} + +impl MeshRecord { + pub(crate) fn state(&self) -> &D3D12_GRAPHICS_PIPELINE_STATE_DESC { + &self.desc + } +} + +pub(crate) enum Entry { + Pipeline(Record), + MeshPipeline(MeshRecord), + Shader(u64, Vec), +} + +fn decode_mesh(key: u64, mut r: Reader<'_>) -> Option { + let shaders = [r.u64()?, r.u64()?]; + let n = *r.bytes(1)?.first()? as usize; + if key == 0 || n > MAX_MESH_LAYOUT { + return None; + } + let layout: Vec = r.bytes(n)?.iter().map(|&id| id.into()).collect(); + if !valid_mesh_layout(shaders, &layout) { + return None; + } + let mut desc = Box::::default(); + let mut valid = true; + state(&mut desc, &mut |v, max| match r.bounded_var(max) { + Some(x) => *v = x, + None => valid = false, + }); + let depth_bounds = layout.contains(&(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1.0 as u32)) && r.bounded_var(1)? != 0; + (valid && r.0.is_empty()).then_some(MeshRecord { key, shaders, layout, desc, depth_bounds }) +} + +/// The entry of `payload` (None: not one this version writes). +pub(crate) fn decode(payload: &[u8]) -> Option { + let (&tag, rest) = payload.split_first()?; + let mut r = Reader(rest); + let key = r.u64()?; + if tag == SHADER { + return Some(Entry::Shader(key, r.0.to_vec())); + } + if tag == MESH_PIPELINE { + return decode_mesh(key, r).map(Entry::MeshPipeline); + } + if !matches!(tag, PIPELINE | DEPTH_BOUNDS_PIPELINE) { + return None; + } + let mut shaders = [0u64; 5]; + for s in &mut shaders { + *s = r.u64()?; + } + let mut desc: Box = Box::new(unsafe { std::mem::zeroed() }); + let mut short = false; + state(&mut desc, &mut |v, _| match r.u32var() { + Some(x) => *v = x, + None => short = true, + }); + if short { + return None; + } + let n = r.var()? as usize; + let mut names = Vec::new(); + let mut fields = Vec::new(); + for _ in 0..n.min(64) { + let len = r.var()? as usize; + names.push(CString::new(r.bytes(len)?).ok()?); + let mut f = [0u32; 6]; + for v in &mut f { + *v = r.u32var()?; + } + fields.push(f); + } + if n > 64 || !r.0.is_empty() { + return None; + } + let inputs = names + .iter() + .zip(&fields) + .map(|(name, f)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: windows::core::PCSTR(name.as_ptr().cast()), + SemanticIndex: f[0], + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(f[1] as i32), + InputSlot: f[2], + AlignedByteOffset: f[3], + InputSlotClass: D3D12_INPUT_CLASSIFICATION(f[4] as i32), + InstanceDataStepRate: f[5], + }) + .collect(); + Some(Entry::Pipeline(Record { key, shaders, depth_bounds: tag == DEPTH_BOUNDS_PIPELINE, desc, inputs, _names: names })) +} + +fn header() -> [u8; HEADER] { + let mut h = [0u8; HEADER]; + h[..8].copy_from_slice(MAGIC); + h[8..].copy_from_slice(&VERSION.to_le_bytes()); + h +} + +fn check(payload: &[u8]) -> u32 { + crate::gpu::shader::fnv64(payload) as u32 +} + +/// The payloads of a file's whole entries and where the last of them ends. None: no file of this +/// version (another one, or not one at all). +fn payloads(file: &[u8]) -> Option<(Vec<&[u8]>, usize)> { + if file.len() < HEADER || file[..HEADER] != header() { + return None; + } + let (mut list, mut at) = (Vec::new(), HEADER); + while let Some(head) = file.get(at..at + 8) { + let len = u32::from_le_bytes(head[..4].try_into().unwrap()) as usize; + let Some(payload) = file.get(at + 8..at + 8 + len) else { break }; + if check(payload) != u32::from_le_bytes(head[4..].try_into().unwrap()) { + break; + } + list.push(payload); + at += 8 + len; + } + Some((list, at)) +} + +/// The entries of the file at `path` (none: no file, or one of another version). +pub(crate) fn read(path: &Path) -> Vec> { + let file = std::fs::read(path).unwrap_or_default(); + payloads(&file).map_or_else(Vec::new, |(list, _)| list.into_iter().map(<[u8]>::to_vec).collect()) +} + +/// A completed worker job must contain only whole, supported records. A title history +/// may end inside an append after the previous run stopped. +fn visit_payloads_with_tail(path: &Path, allow_incomplete_tail: bool, mut visit: impl FnMut(&[u8]) -> Result<(), String>) -> Result<(), String> { + use std::io::{BufReader, Read}; + let file = std::fs::File::open(path).map_err(|e| e.to_string())?; + let size = file.metadata().map_err(|e| e.to_string())?.len(); + let mut reader = BufReader::new(file); + let mut magic = [0; HEADER]; + if reader.read_exact(&mut magic).is_err() || magic != header() { + return Err("unrecognized graphics job header".into()); + } + let mut offset = HEADER as u64; + let mut payload = Vec::new(); + while offset < size { + let damaged = || format!("damaged graphics job at byte {offset}"); + let mut frame = [0; 8]; + if size - offset < 8 { + if allow_incomplete_tail { break; } + return Err(damaged()); + } + reader.read_exact(&mut frame).map_err(|_| damaged())?; + let len = u32::from_le_bytes(frame[..4].try_into().unwrap()) as usize; + if len as u64 > size - offset - 8 { + if allow_incomplete_tail { break; } + return Err(damaged()); + } + payload.resize(len, 0); + reader.read_exact(&mut payload).map_err(|_| damaged())?; + if check(&payload) != u32::from_le_bytes(frame[4..].try_into().unwrap()) { return Err(damaged()); } + visit(&payload)?; + offset += 8 + len as u64; + } + Ok(()) +} + +pub(crate) fn visit_payloads(path: &Path, visit: impl FnMut(&[u8]) -> Result<(), String>) -> Result<(), String> { + visit_payloads_with_tail(path, false, visit) +} + +pub(crate) fn shader_payload(payload: &[u8]) -> Option<(u64, &[u8])> { + let (&tag, rest) = payload.split_first()?; + if tag != SHADER { return None; } + let mut r = Reader(rest); + Some((r.u64()?, r.0)) +} + +fn read_complete(path: &Path, allow_incomplete_tail: bool, mut take: impl FnMut(&[u8], Entry) -> T) -> Result, String> { + let mut entries = Vec::new(); + visit_payloads_with_tail(path, allow_incomplete_tail, |bytes| { + // A newer recorder can add a tag without changing the frame format. + if allow_incomplete_tail && bytes.first().is_some_and(|tag| !matches!(*tag, PIPELINE | SHADER | MESH_PIPELINE | DEPTH_BOUNDS_PIPELINE)) { + return Ok(()); + } + let entry = decode(bytes).ok_or_else(|| format!("invalid graphics job entry {}", entries.len() + 1))?; + entries.push(take(bytes, entry)); + Ok(()) + })?; + Ok(entries) +} + +pub(crate) fn read_history_payloads(path: &Path) -> Result>, String> { + read_complete(path, true, |bytes, _| bytes.to_vec()) +} + +pub(crate) fn read_job(path: &Path) -> Result, String> { + read_complete(path, false, |bytes, entry| { + let recipe = if matches!(entry, Entry::Shader(_, _)) { 0 } else { crate::gpu::shader::fnv64(bytes) }; + (recipe, entry) + }) +} + +/// What became of an entry handed to `Writer::add`. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Added { + New, + /// in the file already + Known, + /// not written: the file is at its cap + Full, +} + +/// Appends entries to a file of records, each once, up to `cap` bytes. +pub(crate) struct Writer { + file: std::fs::File, + len: u64, + cap: u64, + seen: HashSet, + full: bool, +} + +impl Writer { + /// The file at `path` for appending: its whole entries are kept (a cut-short tail is cut off), + /// one of another version is started again. + pub(crate) fn open(path: &Path, cap: u64) -> std::io::Result { + let old = std::fs::read(path).unwrap_or_default(); + let (seen, end) = match payloads(&old) { + Some((list, end)) => (list.iter().map(|p| crate::gpu::shader::fnv64(p)).collect(), end), + None => (HashSet::new(), 0), + }; + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + let mut file = std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(path)?; + let len = if end == 0 { + file.set_len(0)?; + file.write_all(&header())?; + HEADER as u64 + } else { + file.set_len(end as u64)?; + end as u64 + }; + file.seek(std::io::SeekFrom::Start(len))?; + Ok(Writer { file, len, cap, seen, full: false }) + } + + /// Entries in the file. + pub(crate) fn count(&self) -> usize { + self.seen.len() + } + + pub(crate) fn add(&mut self, payload: &[u8]) -> std::io::Result { + let id = crate::gpu::shader::fnv64(payload); + if self.seen.contains(&id) { + return Ok(Added::Known); + } + let n = 8 + payload.len() as u64; + if self.full || self.len + n > self.cap { + self.full = true; + return Ok(Added::Full); + } + let mut entry = Vec::with_capacity(n as usize); + entry.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + entry.extend_from_slice(&check(payload).to_le_bytes()); + entry.extend_from_slice(payload); + self.file.write_all(&entry)?; + self.len += n; + self.seen.insert(id); + Ok(Added::New) + } +} + +/// A graphics pipeline's first use in this run: its entry (`encode`) goes to the file on a thread +/// of its own, not the title's. +pub(crate) fn note(payload: Vec) { + use std::sync::{mpsc, Mutex, OnceLock}; + // (a test does not write the user's file) + if cfg!(test) { + return; + } + static TX: OnceLock>>> = OnceLock::new(); + let tx = TX.get_or_init(|| { + let (tx, rx) = mpsc::channel::>(); + let _ = std::thread::Builder::new().name("xcl-gfx-records".into()).spawn(move || { + let (path, cap) = (path(), cap_bytes()); + let mut w = match Writer::open(&path, cap) { + Ok(w) => w, + Err(e) => { + crate::xlog_warn!("D3D12.X: {}: {e} – the graphics pipelines of this run are not prepared before the next", path.display()); + return; + } + }; + crate::xlog_info!("D3D12.X: graphics pipelines are recorded at their first use for the next run's preparation ({} from earlier runs)", w.count()); + for payload in rx.iter() { + match w.add(&payload) { + Ok(Added::Full) => { + crate::xlog_warn!("D3D12.X: the graphics pipeline records are at their cap of {} MB (XCL_GFX_RECORDS_MB): pipelines first used from here on are not prepared before the next run", cap >> 20); + // (the rest are dropped unread) + for _ in rx.iter() {} + return; + } + Ok(_) => {} + Err(e) => { + crate::xlog_warn!("D3D12.X: {}: {e} – no more graphics pipelines are recorded in this run", path.display()); + return; + } + } + } + }); + Mutex::new(tx) + }); + let _ = tx.lock().unwrap().send(payload); +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + + struct Directory(PathBuf); + impl Drop for Directory { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn directory(name: &str) -> Directory { + let dir = std::env::temp_dir().join(format!("xcl-gfx-records-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Directory(dir) + } + + /// A description with every field set to a value of its own (none its default), written out + /// field by field here: a field `state` leaves out does not come back. + fn described() -> D3D12_GRAPHICS_PIPELINE_STATE_DESC { + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let mut n = 0x10; + let mut next = || { + n += 3; + n + }; + let b = &mut d.BlendState; + b.AlphaToCoverageEnable.0 = 1; + b.IndependentBlendEnable.0 = 1; + for rt in &mut b.RenderTarget { + rt.BlendEnable.0 = 1; + rt.LogicOpEnable.0 = 1; + rt.SrcBlend.0 = next(); + rt.DestBlend.0 = next(); + rt.BlendOp.0 = next(); + rt.SrcBlendAlpha.0 = next(); + rt.DestBlendAlpha.0 = next(); + rt.BlendOpAlpha.0 = next(); + rt.LogicOp.0 = next(); + rt.RenderTargetWriteMask = next() as u8; + } + d.SampleMask = 0xfedc_ba98; + let r = &mut d.RasterizerState; + r.FillMode.0 = next(); + r.CullMode.0 = next(); + r.FrontCounterClockwise.0 = 1; + r.DepthBias = -1234; + r.DepthBiasClamp = -0.25; + r.SlopeScaledDepthBias = 3.5; + r.DepthClipEnable.0 = 1; + r.MultisampleEnable.0 = 1; + r.AntialiasedLineEnable.0 = 1; + r.ForcedSampleCount = 8; + r.ConservativeRaster.0 = 1; + let z = &mut d.DepthStencilState; + z.DepthEnable.0 = 1; + z.DepthWriteMask.0 = 1; + z.DepthFunc.0 = next(); + z.StencilEnable.0 = 1; + z.StencilReadMask = 0x3c; + z.StencilWriteMask = 0xc3; + for face in [&mut z.FrontFace, &mut z.BackFace] { + face.StencilFailOp.0 = next(); + face.StencilDepthFailOp.0 = next(); + face.StencilPassOp.0 = next(); + face.StencilFunc.0 = next(); + } + d.IBStripCutValue.0 = 2; + d.PrimitiveTopologyType.0 = 3; + d.NumRenderTargets = 7; + for f in &mut d.RTVFormats { + *f = DXGI_FORMAT(next()); + } + d.DSVFormat = DXGI_FORMAT(next()); + d.SampleDesc.Count = 4; + d.SampleDesc.Quality = 9; + d.NodeMask = 0x5; + d.Flags.0 = 1; + d + } + + fn pipeline(payload: &[u8]) -> Record { + match decode(payload) { + Some(Entry::Pipeline(r)) => r, + _ => panic!("not a pipeline entry"), + } + } + + #[test] + fn classic_depth_bounds_record_keeps_version_one_state() { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let mut bytes = unsafe { encode(7, [9, 0, 0, 0, 0], &desc) }; + assert!(!pipeline(&bytes).depth_bounds); + bytes[0] = DEPTH_BOUNDS_PIPELINE; + let record = pipeline(&bytes); + assert!(record.depth_bounds); + assert_eq!(record.shaders, [9, 0, 0, 0, 0]); + assert_eq!(record.key, 7); + bytes.pop(); + assert!(decode(&bytes).is_none()); + } + + /// A description comes back with every field (as the key of its translated pipeline's driver + /// blob sees them), its input layout and its shaders' keys. + #[test] + fn a_description_comes_back_as_it_was_written() { + let names = [CString::new("POSITION").unwrap(), CString::new("TEXCOORD").unwrap()]; + let elems = [ + D3D12_INPUT_ELEMENT_DESC { SemanticName: windows::core::PCSTR(names[0].as_ptr().cast()), SemanticIndex: 0, Format: DXGI_FORMAT(6), InputSlot: 0, AlignedByteOffset: 0, InputSlotClass: D3D12_INPUT_CLASSIFICATION(0), InstanceDataStepRate: 0 }, + D3D12_INPUT_ELEMENT_DESC { SemanticName: windows::core::PCSTR(names[1].as_ptr().cast()), SemanticIndex: 3, Format: DXGI_FORMAT(16), InputSlot: 2, AlignedByteOffset: u32::MAX, InputSlotClass: D3D12_INPUT_CLASSIFICATION(1), InstanceDataStepRate: 7 }, + ]; + let mut d = described(); + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elems.as_ptr(), NumElements: 2 }; + let shaders = [11, 22, 0, 0, 55]; + let payload = unsafe { encode(0xabcd_ef01, shaders, &d) }; + assert!(payload.len() < 400, "{} bytes", payload.len()); + let r = pipeline(&payload); + assert_eq!((r.key, r.shaders), (0xabcd_ef01, shaders)); + let (vs, ps, gs) = (b"vs".as_slice(), b"pixel".as_slice(), b"g".as_slice()); + let back = r.desc([Some(vs), Some(ps), None, None, Some(gs)]); + let key = |d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC| unsafe { super::super::real::graphics_blob_key(d, b"dxil", None, None, &[]) }; + assert_eq!(key(&back), key(&d), "the state and the input layout"); + assert_ne!(key(&back), key(&described()), "(the input layout is in the key)"); + assert_eq!(unsafe { encode(0xabcd_ef01, shaders, &back) }, payload); + assert_eq!((back.VS.BytecodeLength, back.PS.BytecodeLength, back.DS.BytecodeLength, back.GS.BytecodeLength), (2, 5, 0, 1)); + assert!(back.pRootSignature.is_none()); + // a description without an input layout + let plain = unsafe { encode(1, [1, 0, 0, 0, 0], &described()) }; + let back = pipeline(&plain).desc([None; 5]); + assert_eq!((back.InputLayout.NumElements, back.InputLayout.pInputElementDescs.is_null()), (0, true)); + assert_eq!(key(&back), key(&described())); + } + + #[test] + fn a_shader_entry_and_a_damaged_payload() { + match decode(&shader_entry(0x77, b"code")) { + Some(Entry::Shader(k, b)) => assert_eq!((k, b.as_slice()), (0x77, b"code".as_slice())), + _ => panic!("not a shader entry"), + } + let payload = unsafe { encode(9, [9, 0, 0, 0, 0], &described()) }; + assert!(decode(&payload[..payload.len() - 1]).is_none(), "cut short"); + assert!(decode(&[payload.as_slice(), &[0]].concat()).is_none(), "a byte too many"); + assert!(decode(&[u8::MAX, 0, 0, 0, 0, 0, 0, 0, 0]).is_none(), "another kind of entry"); + } + + #[test] + fn a_mesh_entry_preserves_moved_shader_slot_order_and_state() { + let layout = [ + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, + ].map(|kind| kind.0 as u32); + let shaders = [0x13, 0x27]; + let mut desc = described(); + let ps = b"pixel"; + desc.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len() }; + let payload = encode_mesh(0x1234, shaders, &layout, &desc, false).unwrap(); + let Some(Entry::MeshPipeline(record)) = decode(&payload) else { panic!("expected a mesh entry") }; + assert_eq!((record.key, record.shaders), (0x1234, shaders)); + assert_eq!(record.layout, layout); + assert_eq!(record.state().RasterizerState.DepthBias, desc.RasterizerState.DepthBias); + assert_eq!(record.state().RTVFormats, desc.RTVFormats); + assert!(record.state().PS.pShaderBytecode.is_null()); + assert_eq!(encode_mesh(record.key, record.shaders, &record.layout, record.state(), record.depth_bounds).unwrap(), payload); + } + + #[test] + fn mesh_entries_require_supported_unique_layout_and_exact_payload() { + let ms = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32; + let moved = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0 as u32; + let ps = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32; + let input = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0 as u32; + let d = described(); + let stream_output = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT.0 as u32; + for layout in [vec![], vec![ms, moved], vec![ms, ms], vec![ms, ps, ps], vec![ms, stream_output], vec![ms, 11, 21]] { + assert!(encode_mesh(1, [1, 0], &layout, &d, false).is_none(), "unsupported layout {layout:?}"); + } + assert!(encode_mesh(1, [1, 2], &[ms], &d, false).is_none()); + assert!(encode_mesh(1, [0, 0], &[ms], &d, false).is_none()); + let payload = encode_mesh(1, [1, 0], &[ms], &d, false).unwrap(); + assert!(decode(&payload[..payload.len() - 1]).is_none()); + assert!(decode(&[payload.as_slice(), &[0]].concat()).is_none()); + + let count_at = 1 + 3 * std::mem::size_of::(); + let mut invalid = payload.clone(); + invalid[count_at] = MAX_MESH_LAYOUT as u8 + 1; + assert!(decode(&invalid).is_none()); + invalid[count_at] = 1; + invalid[count_at + 1] = input as u8; + assert!(decode(&invalid).is_none()); + let state_at = count_at + 2; + let overlong = [&payload[..state_at], &[0x81, 0], &payload[state_at + 1..]].concat(); + assert!(decode(&overlong).is_none()); + } + + #[test] + fn mesh_bounds_and_empty_subobjects_survive_the_worker_job() { + let layout = [0, 25, 2, 3, 4, 5, 8, 9, 10, 21, 17, 12, 14, 15, 16]; + let desc = described(); + for bounds in [false, true] { + let job = encode_mesh(1, [1, 0], &layout, &desc, bounds).unwrap(); + let Some(Entry::MeshPipeline(record)) = decode(&job) else { panic!("mesh record missing") }; + assert_eq!(record.layout, layout); + assert_eq!(record.depth_bounds, bounds); + assert_eq!(record.shaders, [1, 0]); + let state = depth_stencil1(&record.state().DepthStencilState, record.depth_bounds); + assert_eq!(state.BackFace, desc.DepthStencilState.BackFace); + assert_eq!(state.DepthBoundsTestEnable.as_bool(), bounds); + assert!(decode(&job[..job.len() - 1]).is_none()); + let mut bad = job; *bad.last_mut().unwrap() = 2; + assert!(decode(&bad).is_none()); + } + assert!(encode_mesh(1, [1, 0], &[25, 11], &desc, true).is_none()); + } + + #[test] + fn complete_jobs_reject_damaged_or_unknown_entries() { + let dir = directory("complete-job"); + let path = dir.0.join("job.bin"); + assert!(read_job(&path).is_err()); + { + let mut writer = Writer::open(&path, u64::MAX).unwrap(); + writer.add(&shader_entry(5, b"shader")).unwrap(); + } + assert_eq!(read_job(&path).unwrap().len(), 1); + let original = std::fs::read(&path).unwrap(); + std::fs::write(&path, [&original[..], &[1, 2]].concat()).unwrap(); + assert!(read_job(&path).is_err()); + assert_eq!(read(&path).len(), 1); + std::fs::write(&path, original).unwrap(); + Writer::open(&path, u64::MAX).unwrap().add(&[0xff]).unwrap(); + assert!(read_job(&path).is_err()); + } + + #[test] + fn history_reader_keeps_verified_entries_after_an_incomplete_final_append() { + let dir = directory("history-tail"); + let path = dir.0.join("history.bin"); + let first = shader_entry(5, b"shader"); + let mut writer = Writer::open(&path, u64::MAX).unwrap(); + writer.add(&first).unwrap(); + drop(writer); + let original = std::fs::read(&path).unwrap(); + let mut writer = Writer::open(&path, u64::MAX).unwrap(); + writer.add(&shader_entry(6, b"next")).unwrap(); + drop(writer); + let complete = std::fs::read(&path).unwrap(); + let second = &complete[original.len()..]; + for tail in [&second[..3], &second[..second.len() - 2]] { + std::fs::write(&path, [original.as_slice(), tail].concat()).unwrap(); + assert_eq!(read_history_payloads(&path).unwrap(), vec![first.clone()]); + assert!(read_job(&path).is_err(), "worker jobs still require whole frames"); + } + let mut corrupt = original; + corrupt[HEADER + 8] ^= 1; + std::fs::write(&path, corrupt).unwrap(); + assert!(read_history_payloads(&path).is_err(), "a complete but corrupt frame is not a torn append"); + std::fs::write(&path, &complete).unwrap(); + Writer::open(&path, u64::MAX).unwrap().add(&[0xff]).unwrap(); + assert_eq!(read_history_payloads(&path).unwrap(), vec![first, shader_entry(6, b"next")]); + assert!(read_job(&path).is_err(), "an unsupported worker entry remains an error"); + } + + #[test] + fn legacy_pipeline_and_mesh_entries_share_version_one_history() { + let dir = directory("mesh-version-one"); + let path = dir.0.join("records.bin"); + let legacy = unsafe { encode(3, [3, 0, 0, 0, 0], &described()) }; + let shader = shader_entry(5, b"mesh"); + let mesh = encode_mesh(5, [5, 0], &[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32], &described(), false).unwrap(); + let mut writer = Writer::open(&path, 1 << 20).unwrap(); + writer.add(&legacy).unwrap(); + writer.add(&mesh).unwrap(); + writer.add(&shader).unwrap(); + drop(writer); + assert_eq!(&std::fs::read(&path).unwrap()[8..HEADER], &1u32.to_le_bytes()); + assert_eq!(read(&path), vec![legacy.clone(), mesh.clone(), shader.clone()]); + assert_eq!(pipeline(&legacy).key, 3); + assert!(matches!(decode(&mesh), Some(Entry::MeshPipeline(_)))); + assert!(matches!(decode(&shader), Some(Entry::Shader(5, _)))); + } + + /// Written, read back in order, each entry once; a file cut short in its last entry keeps the + /// ones before it and the writer goes on after them. + #[test] + fn entries_are_written_once_and_read_back() { + let dir = directory("round"); + let p = dir.0.join("cache").join("records.bin"); + let a = unsafe { encode(1, [1, 0, 0, 0, 0], &described()) }; + let b = shader_entry(2, b"shader"); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + assert_eq!(w.add(&a).unwrap(), Added::New); + assert_eq!(w.add(&b).unwrap(), Added::New); + assert_eq!(w.add(&a).unwrap(), Added::Known); + drop(w); + assert_eq!(read(&p), vec![a.clone(), b.clone()]); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + assert_eq!((w.count(), w.add(&b).unwrap()), (2, Added::Known), "known from the file"); + drop(w); + // a run cut short in its third entry + let whole = std::fs::read(&p).unwrap(); + std::fs::write(&p, [whole.as_slice(), &[40, 0, 0, 0, 1, 2]].concat()).unwrap(); + assert_eq!(read(&p), vec![a.clone(), b.clone()]); + let c = shader_entry(3, b"another"); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + assert_eq!(w.add(&c).unwrap(), Added::New); + drop(w); + assert_eq!(read(&p), vec![a.clone(), b.clone(), c.clone()]); + // a damaged entry ends the file there + let mut bytes = std::fs::read(&p).unwrap(); + let last = bytes.len() - 1; + bytes[last] ^= 0xff; + std::fs::write(&p, &bytes).unwrap(); + assert_eq!(read(&p), vec![a, b]); + } + + /// A file of another version (or no file of records at all) is read as none, and the writer + /// starts it again. + #[test] + fn a_file_of_another_version_is_passed_over() { + let dir = directory("version"); + let p = dir.0.join("records.bin"); + let a = shader_entry(5, b"five"); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + w.add(&a).unwrap(); + drop(w); + let mut bytes = std::fs::read(&p).unwrap(); + bytes[8..12].copy_from_slice(&(VERSION + 1).to_le_bytes()); + std::fs::write(&p, &bytes).unwrap(); + assert!(read(&p).is_empty()); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + assert_eq!((w.count(), w.add(&a).unwrap()), (0, Added::New)); + drop(w); + assert_eq!(read(&p), vec![a.clone()]); + assert_eq!(&std::fs::read(&p).unwrap()[8..12], &VERSION.to_le_bytes()); + std::fs::write(&p, b"not records").unwrap(); + assert!(read(&p).is_empty()); + assert!(read(&dir.0.join("none.bin")).is_empty()); + } + + /// An entry that would take the file past its cap is not written, nor any after it. + #[test] + fn the_file_stops_at_its_cap() { + assert_eq!(cap_of(None), 64 << 20); + assert_eq!(cap_of(Some(" 2 ")), 2 << 20); + assert_eq!(cap_of(Some("lots")), 64 << 20); + let dir = directory("cap"); + let p = dir.0.join("records.bin"); + let (a, b, small) = (shader_entry(1, &[1; 40]), shader_entry(2, &[2; 40]), shader_entry(3, &[])); + // (room for `small` after `a`, not for `b`) + let cap = (HEADER + 8 + a.len() + 8 + small.len()) as u64; + let mut w = Writer::open(&p, cap).unwrap(); + assert_eq!(w.add(&a).unwrap(), Added::New); + assert_eq!(w.add(&b).unwrap(), Added::Full); + assert_eq!(w.add(&small).unwrap(), Added::Full, "nothing after the cap was hit"); + assert_eq!(w.add(&a).unwrap(), Added::Known); + drop(w); + assert_eq!(read(&p), vec![a]); + assert!(std::fs::metadata(&p).unwrap().len() <= cap); + } + + #[test] + fn varints_round_trip() { + for v in [0u64, 1, 0x7f, 0x80, 0x3fff, 0x4000, u32::MAX as u64, u64::MAX] { + let mut out = Vec::new(); + put_var(&mut out, v); + let mut r = Reader(&out); + assert_eq!(r.var(), Some(v)); + assert!(r.0.is_empty()); + } + assert_eq!(Reader(&[0x80]).var(), None, "cut short"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index b7c2e38c14..c5fbb963a8 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -19,6 +19,7 @@ mod cpu_writes; pub mod dred; mod fence_x; pub mod frame; +pub(crate) mod gfx_records; pub mod guard; mod late_release; pub mod layout; diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index ba9f22257d..725f5c593e 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -25,7 +25,8 @@ struct Screen { impl Screen { fn release(&mut self) -> bool { - self.ready = !self.progress.cancel.load(Ordering::Relaxed); + self.ready = !self.progress.cancel.load(Ordering::Relaxed) && + (!self.progress.corpus.load(Ordering::Acquire) || self.progress.check_corpus_complete().is_ok()); self.ready } } @@ -41,25 +42,44 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { std::env::remove_var("XCL_PREPARATION_PARENT"); std::env::remove_var("XCL_PREPARATION_MENU"); let root = &boot.game_root; - if boot.config.graphics.eq_ignore_ascii_case("null") || - (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir()) { - return Ok(()); - } - if left_out(std::env::var("XCL_PREPARE").ok().as_deref()) { - crate::xlog_info!("Shader preparation left out (XCL_PREPARE=0): the title builds what it uses as it goes"); + let corpus = root.join(".xcl/pso-corpus").try_exists().map_err(|e| e.to_string())?; + if !corpus && std::env::var("XCL_PREPARE").is_ok_and(|v| v.trim() == "0") { return Ok(()); } + let history = crate::hle::d3d12x::gfx_records::path().try_exists().map_err(|e| e.to_string())?; + if !corpus && !history && (boot.config.graphics.eq_ignore_ascii_case("null") || + (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir())) { return Ok(()); } let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), ..Default::default() }); let hwnd = if super::enabled() { *SCREEN.lock().unwrap() = Some(Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }); ACTIVE.store(true, Ordering::Release); - let hwnd = super::ensure_window().ok_or("Could not create the presentation window for shader preparation")?; + let Some(hwnd) = super::ensure_window() else { + ACTIVE.store(false, Ordering::Release); + *SCREEN.lock().unwrap() = None; + return Err("Could not create the presentation window for pipeline preparation".into()); + }; crate::xlog_info!("Shader preparation window {:#x}", hwnd.0 as usize); Some(hwnd) } else { None }; let result = std::thread::scope(|scope| { let worker = scope.spawn(|| prepare_for_launch(root, &progress)); + // (a line every 5 s: a log that stands still for long reads as a frozen process) + let (began, mut said) = (Instant::now(), Instant::now()); while !worker.is_finished() { + if said.elapsed() >= Duration::from_secs(5) { + said = Instant::now(); + let workers = progress.workers.load(Ordering::Relaxed); + let graphics = progress.graphics.load(Ordering::Relaxed); + let corpus = progress.corpus.load(Ordering::Acquire); + crate::xlog_info!( + "Shader preparation: {} of {} {} {} after {} s", + progress.done.load(Ordering::Relaxed), + progress.total.load(Ordering::Relaxed), + if corpus { "pipeline recipes" } else if graphics { "graphics pipelines" } else { "records" }, + if corpus { "confirmed by the graphics driver".into() } else if graphics { format!("processed by {workers} workers") } else if workers != 0 { format!("checked for pipelines by {workers} workers") } else { "processed".into() }, + began.elapsed().as_secs() + ); + } if let Some(parent) = &parent { if unsafe { WaitForSingleObject(parent.as_raw_handle(), 80) } == WAIT_OBJECT_0 { // The launcher was stopped during preparation. Do not leave an orphan compile or start the title. @@ -133,6 +153,38 @@ unsafe fn text(dc: HDC, rect: RECT, value: &str, size: i32, weight: i32, color: DeleteObject(font); } +/// A projected wireframe whose illuminated columns follow confirmed progress. +unsafe fn draw_surface(dc: HDC, rect: RECT, pct: usize) { + use windows_sys::Win32::Foundation::POINT; + const COLS: i32 = 24; + const ROWS: i32 = 8; + let vertex = |col: i32, row: i32| { + let u = col as f64 / COLS as f64; + let v = row as f64 / ROWS as f64; + let hill = |x: f64, z: f64, height: f64| height * (-20.0*(u-x).powi(2) - 6.0*(v-z).powi(2)).exp(); + let elevation = hill(0.35, 0.41, 0.53) + hill(0.68, 0.55, 0.34); + POINT { x: rect.left + ((rect.right-rect.left) as f64*(0.80*u + 0.19*(1.0-v))) as i32, + y: rect.top + ((rect.bottom-rect.top) as f64*(0.42 + 0.55*v - elevation)) as i32 } + }; + let shadow = CreatePen(PS_SOLID, 1, 0x4d4734); + let lit = CreatePen(PS_SOLID, 1, 0x97cc86); + let base = CreateSolidBrush(0x28251b); + let old_pen = SelectObject(dc, shadow); + let old_brush = SelectObject(dc, base); + for row in 0..ROWS { + for col in 0..COLS { + let points = [vertex(col,row),vertex(col+1,row),vertex(col+1,row+1),vertex(col,row+1)]; + SelectObject(dc, if 100*(col+1) as usize <= COLS as usize*pct { lit } else { shadow }); + Polygon(dc, points.as_ptr(), points.len() as i32); + MoveToEx(dc, points[0].x, points[0].y, std::ptr::null_mut()); + LineTo(dc, points[2].x, points[2].y); + } + } + SelectObject(dc, old_brush); + SelectObject(dc, old_pen); + DeleteObject(base); DeleteObject(shadow); DeleteObject(lit); +} + unsafe fn paint(hwnd: HWND, s: &mut Screen) { let mut ps: PAINTSTRUCT = std::mem::zeroed(); let dest = BeginPaint(hwnd.0, &mut ps); @@ -147,23 +199,37 @@ unsafe fn paint(hwnd: HWND, s: &mut Screen) { let scale = |px: i32| (px * GetDeviceCaps(dc, LOGPIXELSY as i32).max(96)) / 96; let width = scale(560).min((rc.right - scale(40)).max(1)); let x = (rc.right - width) / 2; - let y = ((rc.bottom - scale(150)) / 2).max(0); + let art = if rc.bottom >= scale(300) && width >= scale(300) { scale(132) } else { 0 }; + let top = ((rc.bottom - scale(150) - art) / 2).max(0); + let y = top + art; let row = |top, bottom| RECT { left: x, right: x+width, top: y+scale(top), bottom: y+scale(bottom) }; let done = s.progress.done.load(Ordering::Relaxed); let total = s.progress.total.load(Ordering::Relaxed); let pct = percent(done, total, s.ready); + if art != 0 { + draw_surface(dc, RECT { left: x, right: x+width, top, bottom: y-scale(14) }, pct); + } let (quiet, last) = s.clock.sample(done, s.start.elapsed()); - let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else { "Preparing shaders" }; + let workers = s.progress.workers.load(Ordering::Relaxed); + let graphics = workers != 0 && s.progress.graphics.load(Ordering::Relaxed); + let corpus = s.progress.corpus.load(Ordering::Acquire); + let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else if s.ready { "Ready to launch" } + else if corpus { "Preparing pipeline cache" } else if graphics { "Building graphics pipelines" } else if workers != 0 { "Building pipelines" } else { "Preparing shaders" }; let mut title = row(0,48); title.right -= scale(84); text(dc, title, heading, scale(31), 600, 0xf7f5f1, DT_LEFT); text(dc, row(0,48), &format!("{pct}%"), scale(27), 600, 0xdfd09a, DT_RIGHT); - let bar = row(65,72); + let bar = row(62,72); fill(dc, bar, 0x4b4038); fill(dc, RECT {right: x+(width as i64 * pct as i64/100) as i32, ..bar}, 0xbdb458); - let count = if total == 0 { "Reading shader records…".into() } else { format!("{done} of {total} records processed") }; + let count = if corpus { format!("{done} of {total} pipeline recipes confirmed by the driver") } + else if total == 0 { "Reading shader records…".into() } + else if graphics { format!("{done} of {total} graphics pipelines processed by {workers} worker processes") } + else if workers != 0 { format!("{done} of {total} records checked by {workers} worker processes") } + else { format!("{done} of {total} records processed") }; text(dc, row(87,112), &count, scale(17), 400, 0xe1dcd7, DT_LEFT); - let mut times = format!("No shader progress for {quiet} s"); + let elapsed = s.start.elapsed().as_secs(); + let mut times = format!("Elapsed {}:{:02} · {quiet} s since last progress", elapsed / 60, elapsed % 60); if let Some(ago) = last { times.push_str(&format!(" · Last stall ended {ago} s ago")); } text(dc, row(117,145), ×, scale(14), 400, 0xb4aaa4, DT_LEFT); BitBlt(dest, 0, 0, rc.right, rc.bottom, dc, 0, 0, SRCCOPY); @@ -198,23 +264,10 @@ fn percent(done: usize, total: usize, ready: bool) -> usize { if ready { 100 } else { done.saturating_mul(100).checked_div(total).unwrap_or(0).min(99) } } -/// `XCL_PREPARE=0` (`value`): the title starts at once and builds what it uses as it goes, -/// standing still for those builds, as before the preparation (the switch nvidia-dev has). -fn left_out(value: Option<&str>) -> bool { - value.is_some_and(|v| v.trim() == "0") -} - #[cfg(test)] mod tests { use super::*; - /// Only `XCL_PREPARE=0` leaves the preparation out; unset or any other value prepares. - #[test] - fn only_xcl_prepare_0_leaves_the_preparation_out() { - assert!(left_out(Some("0")) && left_out(Some(" 0 "))); - assert!(!left_out(None) && !left_out(Some("1")) && !left_out(Some("")) && !left_out(Some("no"))); - } - #[test] fn clock_advances_during_a_stall_and_remembers_recovery() { let mut clock = StallClock::default(); @@ -237,6 +290,25 @@ mod tests { assert!(!screen.ready); } + #[test] + fn corpus_handoff_requires_every_native_completion() { + let progress = Arc::new(LaunchPreparation::default()); + let mut screen = Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }; + assert!(progress.check_corpus_complete().is_err()); + progress.begin_corpus(0); + assert!(!screen.release()); + progress.begin_corpus(3); + progress.complete_corpus(2).unwrap(); + progress.complete_corpus(1).unwrap(); + assert_eq!(progress.done.load(Ordering::Acquire), 2); + assert!(progress.complete_corpus(4).is_err()); + assert!(!screen.release()); + progress.complete_corpus(3).unwrap(); + assert!(screen.release()); + progress.cancel.store(true, Ordering::Release); + assert!(!screen.release()); + } + #[test] fn only_a_successful_join_releases_the_last_percent() { assert_eq!(percent(0, 0, false), 0); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 63d62a7df4..59f2e81cc2 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -34,6 +34,8 @@ struct Pending { /// its dispatches may be left out while it is built (`image_only`): binds do not wait for it spared: std::sync::atomic::AtomicBool, demand: Mutex, + /// what its first use tells besides `used::note` (`on_first_use`) + on_use: Mutex>, } /// Whether one of the title's threads waits for the pipeline, and the preload worker building it. @@ -112,6 +114,10 @@ impl Pending { fn note_use(&self) { if self.key != 0 && !self.used.swap(true, Ordering::Relaxed) { used::note(self.key); + let on_use = self.on_use.lock().unwrap().take(); + if let Some(f) = on_use { + f(); + } } } } @@ -400,6 +406,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { late: Default::default(), spared: Default::default(), demand: Default::default(), + on_use: Default::default(), }); PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); static ONCE: std::sync::Once = std::sync::Once::new(); @@ -416,6 +423,30 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { } } +/// Run on the thread of a lazy pipeline's first use, once (it is to hand work to another). +pub type OnUse = Box; + +/// What the first use of lazy pipeline `standin` tells besides `used::note`: a graphics one's +/// description for the next run's preparation (`gfx_records::note`). Told before the title has +/// the stand-in. +pub(super) fn on_first_use(standin: usize, f: OnUse) { + if let Some(p) = entry(standin) { + *p.on_use.lock().unwrap() = Some(f); + } +} + +/// The shaders of a pipeline's set, told when the set's key is made (`real::OwnedDesc`). +pub(crate) fn shaders_of(key: u64, shaders: Vec) { + used::parts(key, shaders); +} + +/// The shaders of the pipelines earlier runs used, each by its own key (`used-shaders.txt` +/// beside the DXIL cache): what a title's shader preparation translates. Empty before a run +/// with this list has used a pipeline. +pub fn earlier_used_shaders() -> std::collections::HashSet { + used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join("used-shaders.txt")).unwrap_or_default()) +} + /// The keys of the pipelines earlier runs used (`used-pipelines.txt` beside the DXIL cache): /// what `xcl shaders --precompile --used-only` builds. pub fn earlier_used_keys() -> std::collections::HashSet { @@ -439,6 +470,10 @@ mod used { struct Used { earlier: RwLock>, now: Mutex<(HashSet, Option)>, + /// the shaders of each set made in this run, by the set's key; the shaders of the sets + /// used so far and `used-shaders.txt`, where they are kept for the next run + parts: Mutex>>, + shaders: Mutex<(HashSet, Option)>, } /// The keys in a `used-pipelines.txt` (lines that are not a hexadecimal key are passed over). @@ -451,7 +486,7 @@ mod used { U.get_or_init(|| { // (a test neither reads nor writes the user's file) if cfg!(test) { - return Used { earlier: RwLock::new(HashSet::new()), now: Mutex::new((HashSet::new(), None)) }; + return Used { earlier: RwLock::new(HashSet::new()), now: Mutex::new((HashSet::new(), None)), parts: Default::default(), shaders: Mutex::new((HashSet::new(), None)) }; } let path = crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"); let earlier = parse(&std::fs::read_to_string(&path).unwrap_or_default()); @@ -462,7 +497,10 @@ mod used { let _ = std::fs::create_dir_all(dir); } let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok(); - Used { now: Mutex::new((earlier.clone(), file)), earlier: RwLock::new(earlier) } + let shaders_path = path.with_file_name("used-shaders.txt"); + let shaders = parse(&std::fs::read_to_string(&shaders_path).unwrap_or_default()); + let shaders_file = std::fs::OpenOptions::new().create(true).append(true).open(&shaders_path).ok(); + Used { now: Mutex::new((earlier.clone(), file)), earlier: RwLock::new(earlier), parts: Default::default(), shaders: Mutex::new((shaders, shaders_file)) } }) } @@ -476,12 +514,38 @@ mod used { if key == 0 { return; } - let mut g = get().now.lock().unwrap(); - if g.0.insert(key) { - if let Some(f) = g.1.as_mut() { - let _ = writeln!(f, "{key:016x}"); + { + let mut g = get().now.lock().unwrap(); + if g.0.insert(key) { + if let Some(f) = g.1.as_mut() { + let _ = writeln!(f, "{key:016x}"); + } } } + // its shaders, each once (also those of a set an earlier run used: the list of + // shaders is younger than the list of sets) + let parts = get().parts.lock().unwrap().get(&key).cloned().unwrap_or_default(); + let mut g = get().shaders.lock().unwrap(); + for part in parts { + if g.0.insert(part) { + if let Some(f) = g.1.as_mut() { + let _ = writeln!(f, "{part:016x}"); + } + } + } + } + + /// The shaders of the set `key`, each by its own key (`real::shader_key`). + pub fn parts(key: u64, shaders: Vec) { + if key != 0 { + get().parts.lock().unwrap().entry(key).or_insert(shaders); + } + } + + /// (tests) This run used the shader `key`. + #[cfg(test)] + pub fn shader_noted(key: u64) -> bool { + get().shaders.lock().unwrap().0.contains(&key) } /// (tests) This run used a pipeline of these shaders. @@ -560,6 +624,20 @@ fn preload() -> Option<&'static Preload> { mod used_tests { use super::*; + /// The shaders of a set are kept when a pipeline of the set is used, each once, and not + /// before: a set that is only made keeps nothing. + #[test] + fn the_shaders_of_a_used_set_are_kept_for_the_next_run() { + let (set, other) = (0x5e70_0000_0000_0001u64, 0x5e70_0000_0000_0003u64); + let (vs, ps, cs) = (0x5e70_0000_0000_0011u64, 0x5e70_0000_0000_0013u64, 0x5e70_0000_0000_0015u64); + shaders_of(set, vec![vs, ps]); + shaders_of(other, vec![cs]); + assert!(!used::shader_noted(vs) && !used::shader_noted(ps), "made, not used yet"); + used::note(set); + assert!(used::shader_noted(vs) && used::shader_noted(ps), "the shaders of the used set"); + assert!(!used::shader_noted(cs), "the other set was not used"); + } + /// A PC call that has kept one of the title's threads for long holds the title, a short one /// does not, and the hold ends with the call. #[test] @@ -810,6 +888,25 @@ mod used_tests { released(unknown); } + /// What a pipeline's first use tells (a graphics one's description: `gfx_records`) is told + /// once, at that use, not when it is made or built. + #[test] + fn a_first_use_is_told_once() { + let (standin, key) = (0x7E57_7011usize, 0x5EED_0011u64); + let told = Arc::new(AtomicUsize::new(0)); + submit_lazy(standin, true, Box::new(|| 0x4331), key); + let t = told.clone(); + on_first_use(standin, Box::new(move || { t.fetch_add(1, Ordering::SeqCst); })); + assert_eq!(told.load(Ordering::SeqCst), 0, "not at its making"); + assert_eq!(resolve_wait(standin), 0x4331); + assert_eq!(told.load(Ordering::SeqCst), 1); + assert_eq!(resolve(standin), 0x4331); + assert_eq!(resolve_wait(standin), 0x4331); + assert_eq!(told.load(Ordering::SeqCst), 1, "once"); + on_first_use(0x7E57_7012, Box::new(|| unreachable!("no such pipeline"))); + released(standin); + } + static WORKER_SATURATION_LOCK: Mutex<()> = Mutex::new(()); /// A queued normal worker job whose stand-in was released before a worker starts it is diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 19eedfe6ac..c1c0aceb99 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4545,7 +4545,7 @@ pub(crate) mod driver_cache { format!("gfx-{hash:016x}-{bytes:x}.pso") } - fn enabled() -> bool { + pub(crate) fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE").map_or(true, |v| v.trim() != "0")) } @@ -4895,7 +4895,7 @@ fn remember_graphics_blob(key: (u64, usize), blob: std::sync::Arc>) { /// Deterministic FNV-1a digest of every field in a translated PC graphics PSO (shaders, static /// samplers, blend/rasterizer/depth-stencil state, input layout, render target / depth formats, /// sample desc, topology, flags) for in-memory and on-disk driver blob caching. -unsafe fn graphics_blob_key( +pub(super) unsafe fn graphics_blob_key( copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs_dxil: &[u8], ps_dxil: Option<&[u8]>, @@ -5014,6 +5014,23 @@ unsafe fn graphics_blob_key( mod graphics_blob_tests { use super::*; + #[test] + fn classic_depth_bounds_record_preserves_native_state_and_cache_identity() { + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + d.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_GREATER; + d.DepthStencilState.StencilReadMask = 0x5a; + let stream = depth_bounds_stream(&d); + let fields = stream_subobjects(&stream.0).unwrap(); + let (_, bytes) = fields.iter().find(|(ty, _)| *ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1.0 as u32).unwrap(); + let state = unsafe { std::ptr::read_unaligned(bytes.as_ptr().cast::()) }; + assert!(state.DepthBoundsTestEnable.as_bool()); + assert_eq!(state.DepthFunc, d.DepthStencilState.DepthFunc); + assert_eq!(state.StencilReadMask, 0x5a); + let key = (123, 456); + assert_eq!(depth_bounds_key(key, false), key); + assert_ne!(depth_bounds_key(key, true), key); + } + #[test] fn graphics_blob_key_tracks_shaders_samplers_and_state() { unsafe { @@ -5222,10 +5239,10 @@ fn create_graphics_pso_cached( } 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)) + with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv, false)) } -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 { +unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, depth_bounds: bool) -> 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; @@ -5299,7 +5316,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + rect_gs.as_ref().map_or(0, Vec::len); - let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers); + let gkey = depth_bounds_key(graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers), depth_bounds); let mut cached = graphics_blob(gkey); let disk = driver_cache::graphics_path(gkey.0, gkey.1); let from_disk = cached.is_none(); @@ -5319,13 +5336,24 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } }, |label, has_cached, f| driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some((ps_hash, has_cached)), f), - |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv), + |c| if depth_bounds { + let stream = depth_bounds_stream(c); + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: stream.0.len(), pPipelineStateSubobjectStream: stream.0.as_ptr() as _ }; + let create: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); + finish_pso(this, create, &desc as *const _ as _, riid, ppv) + } else { finish_pso(this, f, c as *const _ as *const c_void, riid, ppv) }, ); let hr = build.hr; + if build.reused { + if let Some(blob) = cached.as_ref() { + crate::shaders::warm_replay::accepted(disk.as_deref(), blob); + } + } if build.cache_eligible { keep_graphics_blob(gkey, *ppv, bytes); if let (Some(p), Some(b)) = (disk.as_deref(), graphics_blob(gkey)) { driver_cache::keep(p, &b, build.in_driver); + crate::shaders::warm_replay::accepted(Some(p), &b); } } else if build.reused && from_disk { driver_cache::note(true, None); @@ -5423,7 +5451,16 @@ unsafe impl Send for OwnedDesc {} /// A hash of a pipeline's shaders in their order (never 0): what `pso_async` knows a used /// pipeline by in the next run. +/// `shaders_key` of the one shader `blob`. +pub(crate) fn shader_key(blob: &[u8]) -> u64 { + ((0xcbf2_9ce4_8422_2325u64 ^ crate::gpu::shader::fnv64(blob)).wrapping_mul(0x0000_0100_0000_01b3)) | 1 +} + pub(crate) fn shaders_key(blobs: &[Vec]) -> u64 { + shader_set_key(blobs.iter().map(Vec::as_slice)) +} + +pub(crate) fn shader_set_key<'a>(blobs: impl IntoIterator) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; for b in blobs { h = (h ^ crate::gpu::shader::fnv64(b)).wrapping_mul(0x0000_0100_0000_01b3); @@ -5433,6 +5470,13 @@ pub(crate) fn shaders_key(blobs: &[Vec]) -> u64 { #[cfg(test)] mod shaders_key_tests { + #[test] + fn the_key_of_one_shader_is_the_key_of_a_set_of_it() { + let a = vec![1u8, 2, 3]; + assert_eq!(super::shader_key(&a), super::shaders_key(&[a.clone()])); + assert_ne!(super::shader_key(&a), super::shader_key(&[4u8, 5])); + } + #[test] fn a_key_follows_the_shaders_and_their_order_and_is_never_zero() { let (a, b) = (vec![1u8, 2, 3], vec![4u8, 5]); @@ -5446,12 +5490,37 @@ mod shaders_key_tests { } impl OwnedDesc { - fn shaders_key(&self) -> u64 { - shaders_key(match self { + /// The key of its shaders, and each shader's (`shader_key`, in its own order). + fn shaders_key(&self) -> (u64, Vec) { + let blobs = match self { OwnedDesc::Compute(_, b) => b, OwnedDesc::Graphics(_, b, ..) => b, OwnedDesc::Stream(_, _, b) => b, - }) + }; + let key = shaders_key(blobs); + // each shader by itself too: what a title's shader preparation translates before the + // next run (`pso_async::earlier_used_shaders`) + let parts: Vec = blobs.iter().map(|b| shader_key(b)).collect(); + super::pso_async::shaders_of(key, parts.clone()); + (key, parts) + } + + /// A graphics pipeline's entry for the next run's preparation (`gfx_records`), of the set + /// `key` whose shaders' keys are `parts`, or an eligible mesh stream's entry. + unsafe fn record(&self, key: u64, parts: &[u64]) -> Option> { + if let OwnedDesc::Stream(_, stream, _) = self { + return record_mesh_stream(stream); + } + let OwnedDesc::Graphics(d, ..) = self else { return None }; + // (`own_graphics` copied the stages it has, in this order) + let mut parts = parts.iter(); + let mut shaders = [0u64; 5]; + for (s, b) in shaders.iter_mut().zip([&d.VS, &d.PS, &d.DS, &d.HS, &d.GS]) { + if !b.pShaderBytecode.is_null() && b.BytecodeLength != 0 { + *s = *parts.next()?; + } + } + Some(super::gfx_records::encode(key, shaders, d)) } fn ptr(&self) -> *const c_void { @@ -5676,7 +5745,9 @@ unsafe fn go_background( return None; } let dev = Dev(this as usize, f as usize); - let key = owned.shaders_key(); + let (key, parts) = owned.shaders_key(); + // (a graphics pipeline used in this run is built before the next starts: `gfx_records`) + let described = if super::pso_async::lazy() { owned.record(key, &parts) } else { None }; // a big compute program that writes nothing but images: binds can go on without it let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); let job: super::pso_async::Job = Box::new(move || { @@ -5689,6 +5760,9 @@ unsafe fn go_background( }); if super::pso_async::lazy() { super::pso_async::submit_lazy(*ppv as usize, compute, job, key); + if let Some(entry) = described { + super::pso_async::on_first_use(*ppv as usize, Box::new(move || super::gfx_records::note(entry))); + } } else { super::pso_async::submit(*ppv as usize, compute, job); } @@ -5706,6 +5780,34 @@ unsafe fn build_graphics(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out), Some(hr) if hr >= 0) } +/// This process is a shader preparation worker (`prepare_device`): it keeps the driver's blob of +/// every graphics pipeline it builds on disk, whatever its size and time, and none in memory. +static PREPARING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// A shader preparation worker's device (`shaders::graphics_worker`), made on the title's adapter: +/// adopted as the title's is, so `prepare_graphics` takes the title's path. Raw, kept for the +/// process. +pub(crate) fn prepare_device(device: ID3D12Device) -> usize { + PREPARING.store(true, Ordering::Relaxed); + let raw = device.into_raw(); + unsafe { adopt(raw, Kind::Device) }; + raw as usize +} + +/// A title's graphics pipeline `desc` (`gfx_records::Record::desc`) built on `device` +/// (`prepare_device`) as the title's background build makes it (`build_graphics`): the +/// translation, DXC and driver blob caches on disk get what the title will ask for. The pipeline +/// is released; false: not made (noted in the log as the title's would be). +pub(crate) unsafe fn prepare_graphics(device: usize, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, depth_bounds: bool) -> bool { + let this = device as *mut c_void; + let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState"))); + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = with_switch_fallback(|| translated_graphics_pso_once(this, f, desc as *const _ as _, &pc_iid(Kind::PipelineState), &mut out, depth_bounds)); + let made = matches!(hr, Some(hr) if hr >= 0) && !out.is_null(); + super::pso_async::release(out as usize); + made +} + unsafe fn build_compute(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); matches!(translated_compute_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out), Some(Ok(hr)) if hr >= 0) @@ -5920,6 +6022,40 @@ impl StreamOut { } } +fn depth_bounds_key(mut key: (u64, usize), enabled: bool) -> (u64, usize) { + if enabled { + for &byte in b"DB01" { key.0 = (key.0 ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3); } + } + key +} + +/// The richer depth-stencil descriptor can only be passed through a pipeline stream. +fn depth_bounds_stream(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> StreamOut { + let mut out = StreamOut::default(); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &d.pRootSignature); + for (stage, code) in [(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &d.VS), + (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, &d.PS), (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS, &d.DS), + (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS, &d.HS), (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, &d.GS)] { + if code.BytecodeLength != 0 { out.put(stage, code); } + } + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, &super::gfx_records::depth_stencil1(&d.DepthStencilState, true)); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &d.BlendState); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, &d.RasterizerState); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &d.SampleMask); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, &d.SampleDesc); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + &D3D12_RT_FORMAT_ARRAY { NumRenderTargets: d.NumRenderTargets, RTFormats: d.RTVFormats }); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, &d.DSVFormat); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, &d.PrimitiveTopologyType); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, &d.IBStripCutValue); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, &d.InputLayout); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT, &d.StreamOutput); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, &d.NodeMask); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, &d.Flags); + if d.CachedPSO.CachedBlobSizeInBytes != 0 { out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, &d.CachedPSO); } + out +} + /// The subobjects of a stream: (type, payload). fn stream_subobjects(buf: &[u8]) -> Option> { let mut out = Vec::new(); @@ -5961,6 +6097,136 @@ unsafe fn payload_shader<'a>(p: &[u8]) -> Option<&'a [u8]> { shader_bytes(&b) } +/// Keep the source states the mesh translator will use again during preparation. +unsafe fn record_mesh_stream(stream: &[u8]) -> Option> { + let subs = stream_subobjects(stream)?; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let mut layout = Vec::with_capacity(subs.len()); + let (mut ms, mut amplification, mut ps) = (None, None, None); + let mut depth_bounds = false; + let (mut seen, mut size) = (0u32, 0usize); + + fn value(payload: &[u8]) -> Option { + (payload.len() == std::mem::size_of::()).then(|| unsafe { std::ptr::read_unaligned(payload.as_ptr().cast()) }) + } + + for (ty, payload) in subs { + let (_, align) = super::null::subobject_payload(ty)?; + size += (align + payload.len() + 7) & !7; + let bit = 1u32 << ty; + if seen & bit != 0 { + return None; + } + seen |= bit; + match ty { + 0 => {} // The translator supplies its own root signature. + 19 => continue, // The title's cache blob is never an input to translation. + 24 | 25 if payload.iter().all(|&b| b == 0) => continue, + 1..=5 if payload.iter().all(|&b| b == 0) => {} + 2 => ps = Some(payload_shader(payload)?), + 24 => amplification = Some(payload_shader(payload)?), + 25 => ms = Some(payload_shader(payload)?), + 8 => desc.BlendState = value(payload)?, + 9 => desc.SampleMask = value(payload)?, + 10 => desc.RasterizerState = value(payload)?, + 11 => desc.DepthStencilState = value(payload)?, + 12 if value::(payload).is_some_and(|d| d.NumElements == 0 && d.pInputElementDescs.is_null()) => {} + 21 => { + let d = value::(payload)?; + depth_bounds = d.DepthBoundsTestEnable.as_bool(); + desc.DepthStencilState = D3D12_DEPTH_STENCIL_DESC { + DepthEnable: d.DepthEnable, DepthWriteMask: d.DepthWriteMask, DepthFunc: d.DepthFunc, + StencilEnable: d.StencilEnable, StencilReadMask: d.StencilReadMask, StencilWriteMask: d.StencilWriteMask, + FrontFace: d.FrontFace, BackFace: d.BackFace, + }; + } + 13 => desc.IBStripCutValue = value(payload)?, + 14 => desc.PrimitiveTopologyType = value(payload)?, + 15 => { + let rt: D3D12_RT_FORMAT_ARRAY = value(payload)?; + if rt.NumRenderTargets > 8 { + return None; + } + desc.NumRenderTargets = rt.NumRenderTargets; + desc.RTVFormats = rt.RTFormats; + } + 16 => desc.DSVFormat = value(payload)?, + 17 => desc.SampleDesc = value(payload)?, + 18 => desc.NodeMask = value(payload)?, + 20 => desc.Flags = value(payload)?, + _ => return None, + } + layout.push(ty); + } + if size != stream.len() || (ms.is_some() && amplification.is_some()) { + return None; + } + let ms = ms.or(amplification)?; + if !crate::gpu::xbox::parse(ms).is_some_and(|shader| shader.stage == "MS") { + return None; + } + let shaders = [shader_key(ms), ps.map_or(0, shader_key)]; + let key = shader_set_key(std::iter::once(ms).chain(ps)); + super::gfx_records::encode_mesh(key, shaders, &layout, &desc, depth_bounds) +} + +/// Build both recorded mesh passes on the adopted device from `prepare_device`. +/// +/// # Safety +/// `device` must be the live adopted device returned from `prepare_device`. +pub(crate) unsafe fn replay_mesh_record( + device: usize, + record: &super::gfx_records::MeshRecord, + shaders: [Option<&[u8]>; 2], +) -> Result<(), String> { + let [Some(ms), ps] = shaders else { return Err("mesh shader missing from the job".into()) }; + if record.shaders != [shader_key(ms), ps.map_or(0, shader_key)] || + record.key != shader_set_key(std::iter::once(ms).chain(ps)) + { + return Err("mesh shaders do not match the recorded keys".into()); + } + + let d = record.state(); + let mut stream = StreamOut::default(); + for &ty in &record.layout { + let subobject = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(ty as i32); + match ty { + 0 => stream.put(subobject, &std::ptr::null::()), + 2 => match ps { + Some(bytes) => stream.shader(subobject, bytes), + None => stream.put(subobject, &D3D12_SHADER_BYTECODE::default()), + }, + 1 | 3..=5 => stream.put(subobject, &D3D12_SHADER_BYTECODE::default()), + 24 | 25 => stream.shader(subobject, ms), + 8 => stream.put(subobject, &d.BlendState), + 9 => stream.put(subobject, &d.SampleMask), + 10 => stream.put(subobject, &d.RasterizerState), + 11 => stream.put(subobject, &d.DepthStencilState), + 12 => stream.put(subobject, &D3D12_INPUT_LAYOUT_DESC::default()), + 21 => stream.put(subobject, &super::gfx_records::depth_stencil1(&d.DepthStencilState, record.depth_bounds)), + 13 => stream.put(subobject, &d.IBStripCutValue), + 14 => stream.put(subobject, &d.PrimitiveTopologyType), + 15 => stream.put(subobject, &D3D12_RT_FORMAT_ARRAY { RTFormats: d.RTVFormats, NumRenderTargets: d.NumRenderTargets }), + 16 => stream.put(subobject, &d.DSVFormat), + 17 => stream.put(subobject, &d.SampleDesc), + 18 => stream.put(subobject, &d.NodeMask), + 20 => stream.put(subobject, &d.Flags), + _ => return Err(format!("unsupported mesh subobject {ty}")), + } + } + let desc = [stream.0.len(), stream.0.as_ptr() as usize]; + let mut out = std::ptr::null_mut(); + let hr = unsafe { + translated_mesh_stream(device as *mut c_void, desc.as_ptr().cast(), &pc_iid(Kind::PipelineState), &mut out) + }; + super::pso_async::release(out as usize); + match hr { + Some(hr) if hr >= 0 && !out.is_null() => Ok(()), + Some(hr) => Err(format!("mesh pipeline replay failed ({hr:#x})")), + None => Err("mesh pipeline record could not be translated".into()), + } +} + /// The passthrough mesh shader emits triangles for both translated MS and GS pipelines. fn two_pass_mesh_stream(rs: *mut c_void, ms: &[u8], ps: Option<&[u8]>) -> StreamOut { let mut out = StreamOut::default(); @@ -6062,6 +6328,10 @@ fn two_pass_driver_id(device: *mut c_void) -> Option { }) } +pub(crate) fn preparation_driver_identity(dev: &ID3D12Device) -> Option { + two_pass_driver_id(dev.as_raw()) +} + /// Create the mesh pipeline (RS and shaders already in the stream) and its compute pass. #[allow(clippy::too_many_arguments)] unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, ps_samplers: &[crate::gpu::recomp::pso::StaticSampler], kind: &'static str, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { @@ -6132,6 +6402,9 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: }; if let Some(key) = gkey { if greused { + if let Some(blob) = gcached.as_ref() { + crate::shaders::warm_replay::accepted(gdisk.as_deref(), blob); + } if let Some(blob) = gcached.filter(|_| gfrom_disk) { remember_graphics_blob(key, blob); driver_cache::note(true, None); @@ -6143,6 +6416,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: if let Some(blob) = blob { if let Some(path) = gdisk.as_deref().filter(|_| slow) { driver_cache::keep(path, &blob, gin_driver); + crate::shaders::warm_replay::accepted(Some(path), &blob); } remember_graphics_blob(key, blob); } @@ -6187,10 +6461,16 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: cin_driver += took; } let creused = hc >= 0 && ccached.is_some() && cdesc.CachedPSO.CachedBlobSizeInBytes != 0; + if creused { + if let Some(blob) = ccached.as_ref() { + crate::shaders::warm_replay::accepted(cdisk.as_deref(), blob); + } + } if hc >= 0 && !creused && !compute.is_null() { keep_compute_blob(ckey, compute, tp.cs.len()); if let (Some(p), Some(b)) = (cdisk.as_deref(), compute_blob(ckey)) { driver_cache::keep(p, &b, cin_driver); + crate::shaders::warm_replay::accepted(Some(p), &b); } } else if creused && cfrom_disk { driver_cache::note(true, None); @@ -7549,6 +7829,12 @@ pub fn log_device_removed() { return; } crate::xlog_error!("D3D12 device removed: {:#x} {}", e.code().0 as u32, e.message()); + // (to rule the system's memory in or out: a removal with no fault of the GPU's had 30 GB of + // commit left) + let (commit, limit) = crate::host::system_commit(); + if limit != 0 { + crate::xlog_error!("system commit at the removal: {} of {} MB ({} MB left)", commit >> 20, limit >> 20, limit.saturating_sub(commit) >> 20); + } unsafe { let Ok(dred) = dev.cast::() else { return }; if let Ok(pf) = dred.GetPageFaultAllocationOutput() { diff --git a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs index c1e7efddc3..187c9885fa 100644 --- a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs +++ b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs @@ -222,7 +222,14 @@ pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gp } 1..=6 | 24 | 25 => { let state = read_state::(payload)?; - if state.BytecodeLength == 0 && ty != 25 { + if state.BytecodeLength == 0 { + if ty == 25 { + return None; + } + if matches!(ty, 1..=5) && payload.iter().all(|&byte| byte == 0) { + h.u32(ty); + h.u64(0); + } continue; } let code = payload_shader(payload)?; @@ -275,6 +282,25 @@ mod tests { use super::super::StreamOut; use std::ffi::c_void; + #[test] + fn inactive_shader_stages_keep_a_two_pass_driver_cache_key() { + let ms = [1u8, 2, 3, 4]; + let key = |stages: &[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE]| { + let mut stream = StreamOut::default(); + stream.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, &ms); + for &stage in stages { stream.put(stage, &D3D12_SHADER_BYTECODE::default()); } + unsafe { two_pass_stream_key(&stream.0, &[], 7, 1) } + }; + let ds = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS; + let hs = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS; + let gs = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS; + let tagged = key(&[ds, hs, gs]).unwrap(); + assert_eq!(tagged.1, ms.len()); + assert_eq!(Some(tagged), key(&[gs, ds, hs])); + assert_ne!(Some(tagged), key(&[])); + assert_eq!(key(&[ds, ds]), None); + } + #[test] fn canonical_stream_key_distinguishes_state_samplers_and_driver() { let ms = [1u8, 2, 3, 4]; diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 1f5d3f4970..a73f8c8a85 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -8,6 +8,50 @@ use crate::config::Boot; pub static HOST_MODE: AtomicBool = AtomicBool::new(false); +/// The system's commit charge and its limit in bytes (RAM plus page files): what all programs' +/// memory, and all video memory, is counted against. (0, 0): not known. +pub fn system_commit() -> (u64, u64) { + use windows_sys::Win32::System::ProcessStatus::{K32GetPerformanceInfo, PERFORMANCE_INFORMATION}; + unsafe { + let mut p: PERFORMANCE_INFORMATION = std::mem::zeroed(); + p.cb = std::mem::size_of_val(&p) as u32; + if K32GetPerformanceInfo(&mut p, p.cb) == 0 { + return (0, 0); + } + (p.CommitTotal as u64 * p.PageSize as u64, p.CommitLimit as u64 * p.PageSize as u64) + } +} + +/// Whether commit left over (`limit - commit`) is logged as low: under `LOW_COMMIT` the first +/// time, then each time it is half of what was logged last. +fn low_commit_logged(left: u64, last: u64) -> bool { + left < LOW_COMMIT && (last == 0 || left <= last / 2) +} + +/// Commit left under which the log warns: a retail title's world took the last 6 GB in seconds. +const LOW_COMMIT: u64 = 8 << 30; + +/// The system is running out of commit: said in the log (once, then at each halving). When it +/// runs out, allocations fail for every program. (Measured on a retail title's world, whose +/// process held 45 GB beside 71 GB of other programs under a 147 GB limit: the process's own +/// memory counts against the commit, its 24 GB of video memory do not.) +fn warn_low_commit(commit: u64, limit: u64, private: u64, video: u64) { + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let left = limit.saturating_sub(commit); + let last = LAST.load(Ordering::Relaxed); + if !low_commit_logged(left, last) { + return; + } + LAST.store(left.max(1), Ordering::Relaxed); + crate::xlog_warn!( + "memory: the system is running out of commit: {} MB left of {} MB (RAM + page file). This process holds {} MB (and {} MB of video memory, which do not count), other programs the rest. When it runs out allocations fail for every program: close other programs or give Windows a larger page file", + left >> 20, + limit >> 20, + private >> 20, + video >> 20 + ); +} + pub fn host_main(boot_path: &Path) -> i32 { let boot: Boot = match std::fs::read_to_string(boot_path).map_err(|e| e.to_string()).and_then(|s| serde_json::from_str(&s).map_err(|e| e.to_string())) { Ok(b) => b, @@ -77,8 +121,16 @@ pub fn host_main(boot_path: &Path) -> i32 { let (pools, pools_mapped) = crate::hle::d3d12x::sparse::pool_bytes(); let (pages, page_pools) = crate::hle::d3d12x::vram::page_bytes(); let mb = |b: u64| b >> 20; + // the system's commit: this process's memory counts against it with every other + // program's (video memory does not), and where it ends allocations fail + let (commit, commit_limit) = system_commit(); + let mut commit_text = String::new(); + if commit_limit != 0 { + commit_text = format!("; system commit {} of {} MB", mb(commit), mb(commit_limit)); + warn_low_commit(commit, commit_limit, private as u64, local); + } crate::xlog_info!( - "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped)", + "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped){commit_text}", mb(private as u64), mb(local), mb(non_local), @@ -164,3 +216,24 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::log::flush(); code as i32 } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn low_commit_is_logged_under_the_mark_and_at_each_halving() { + assert!(!low_commit_logged(LOW_COMMIT, 0), "at the mark: not yet"); + assert!(low_commit_logged(LOW_COMMIT - 1, 0)); + assert!(!low_commit_logged(5 << 30, 7 << 30), "less, but not half of what was logged last"); + assert!(low_commit_logged(3 << 30, 7 << 30)); + assert!(low_commit_logged(0, 1), "none left"); + assert!(!low_commit_logged(9 << 30, 1 << 30), "back above the mark"); + } + + #[test] + fn the_system_commit_is_known_and_under_its_limit() { + let (commit, limit) = system_commit(); + assert!(commit > 0 && commit <= limit, "{commit} of {limit}"); + } +} diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index e40b3e18ad..6fe7571fef 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -35,6 +35,7 @@ Usage: --recomp: translates every RDNA2 program → HLSL and shows what is missing; --compile N: additionally compiles N complete translations with DXC. --precompile [--only STAGE]: caches compiled shaders before a run (e.g. --only cs). + --prepare-corpus: builds every staged native pipeline recipe for a title folder. --pipelines also builds compute pipelines and caches them for the next run. --used-only skips compute shaders whose pipelines were not used in earlier runs. --export-hlsl DIR [--count N] [--min-kb N] [--record-hash HEX]: writes deterministic diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index b41799ec84..c9cdeed753 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -12,6 +12,46 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use crate::gpu::{dxbc, pack, rdna2, recomp, shader, xbox}; +use crate::hle::d3d12x::gfx_records; +pub(crate) mod pso_corpus; +mod warm_blobs; +mod warm_pack; +pub(crate) mod warm_replay; + +pub(crate) fn warm_settings_key() -> u64 { warm_settings(std::env::vars_os()) } + +// Driver and cache directory are keyed separately. Worker PIDs, title paths, scheduling +// and observation settings do not affect the recipe the driver validates. +fn warm_settings(vars: impl IntoIterator) -> u64 { + let mut settings = Vec::new(); + for (name, value) in vars { + let name = name.to_string_lossy().to_ascii_uppercase(); + if !name.starts_with("XCL_") { continue; } + if matches!(name.as_str(), + "XCL_HOST" | "XCL_DATA_ROOT" | "XCL_ADAPTER" | "XCL_DXIL_CACHE" | "XCL_UMA_MB" | + "XCL_PRECOMPILE_PARENT" | "XCL_PREPARATION_PARENT" | "XCL_PREPARATION_MENU" | + "XCL_PRECOMPILE_SLICE" | "XCL_PRECOMPILE_COVERAGE_MAP" | "XCL_PRECOMPILE_COVERAGE_DIR" | + "XCL_DXC_THREADS" | "XCL_PIPELINE_THREADS" | "XCL_PREPARE_WORKERS" | "XCL_PREPARE" | + "XCL_PREPARE_GRAPHICS" | "XCL_PREPARE_ALL_LIVE" | "XCL_RUN_SECONDS" | "XCL_PRESS_AT" | + "XCL_PRESS_AFTER_POLL" | "XCL_ACTIVITY" | "XCL_SKIP_BINK" | "XCL_FRAME_DUMP" | + "XCL_FRAME_DUMP_FULL" | "XCL_GPU_CULPRIT" | "XCL_DSTORAGE_LATE_PAGE_MS" | "XCL_DISPATCH_TILE_AXIS") { + continue; + } + settings.push((name, value)); + } + settings.sort(); + warm_blobs::digest(&settings) +} + +#[cfg(test)] +#[test] +fn warm_settings_ignore_worker_identity_but_keep_backend_changes() { + let key = |entries: &[(&str, &str)]| warm_settings(entries.iter().map(|(k, v)| ((*k).into(), (*v).into()))); + let offline = key(&[("XCL_DIRECT_DXIL", "1")]); + let worker = key(&[("XCL_PRECOMPILE_PARENT", "812"), ("XCL_DXC_THREADS", "2"), ("xcl_direct_dxil", "1")]); + assert_eq!(offline, worker); + assert_ne!(offline, key(&[("xcl_direct_dxil", "all")])); +} /// `--iface`: how console programs connect to their DXBC signatures (hypothesis checks for /// the VS/PS interface of the recompiler). @@ -811,11 +851,14 @@ struct ShadersOptions { measure_pso: Option, repeat: usize, precompile: bool, + prepare_corpus: bool, limit: usize, only: Option, pipelines: bool, used_only: bool, records: Option, + /// `--graphics-records`: the path is a job file of `graphics_in_workers` (`graphics_worker`) + graphics_records: bool, direct: bool, sample: usize, seed: u64, @@ -847,11 +890,13 @@ fn parse_args(args: &[String]) -> Result { measure_pso: None, repeat: 1, precompile: false, + prepare_corpus: false, limit: usize::MAX, only: None, pipelines: false, used_only: false, records: None, + graphics_records: false, direct: false, sample: 200, seed: 1, @@ -886,11 +931,13 @@ fn parse_args(args: &[String]) -> Result { "--measure-pso" => opts.measure_pso = Some(p.parse_hex_u64("--measure-pso")?), "--repeat" => opts.repeat = p.parse_usize("--repeat")?, "--precompile" => opts.precompile = true, + "--prepare-corpus" => opts.prepare_corpus = true, "--limit" => opts.limit = p.parse_usize("--limit")?, "--only" => opts.only = Some(p.value("--only")?.to_ascii_lowercase()), "--pipelines" => opts.pipelines = true, "--used-only" | "--used" => opts.used_only = true, "--records" => opts.records = Some(PathBuf::from(p.value("--records")?)), + "--graphics-records" => opts.graphics_records = true, "--direct" => opts.direct = true, "--sample" => opts.sample = p.parse_usize("--sample")?, "--seed" => opts.seed = p.parse_u64("--seed")?, @@ -948,12 +995,30 @@ pub fn run(path: &Path, args: &[String]) -> i32 { return 2; } }; + if opts.prepare_corpus { + if opts.split.is_some() || opts.limit != usize::MAX || opts.only.is_some() || opts.used_only { + eprintln!("xcl shaders: --prepare-corpus requires all staged recipes and their recorded memory configuration"); + return 2; + } + let progress = LaunchPreparation { adapter: "auto".into(), ..Default::default() }; + let result = pso_corpus::discover(path) + .and_then(|c| c.ok_or_else(|| "No pipeline corpus found in this title folder".to_string())) + .and_then(|c| c.prepare_with_threads(&progress, opts.threads)) + .and_then(|_| progress.check_corpus_complete()); + return match result { + Ok(()) => { println!("Prepared all {} discovered pipeline recipes", progress.done.load(Ordering::Acquire)); 0 } + Err(e) => { eprintln!("xcl shaders: {e}"); 2 } + }; + } // the runtime's memory windows: from the descriptor heap with `XCL_HEAP_WINDOWS=1` // (`pso::mem_windows`), as `--precompile` let runtime_windows = || { let windows = opts.windows; if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows } }; + if opts.graphics_records { + return graphics_worker(path, runtime_windows(), opts.threads); + } let top = opts.top; let json = opts.json; let compile = opts.compile; @@ -1026,7 +1091,11 @@ pub fn run(path: &Path, args: &[String]) -> i32 { } // the runtime's key: heap windows with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`) let windows = runtime_windows(); - return match precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, selected.as_ref(), opts.threads, t0, None) { + let coverage = match ComputeCoverage::worker() { + Ok(coverage) => coverage, + Err(e) => { eprintln!("xcl shaders: {e}"); return 2; } + }; + return match precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, selected.as_ref(), opts.threads, t0, None, coverage.as_ref()) { Ok(()) => 0, Err(e) => { eprintln!("xcl shaders: {e}"); 2 } }; @@ -1253,9 +1322,13 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl struct Pipelines { dev: windows::Win32::Graphics::Direct3D12::ID3D12Device, signatures: Mutex), windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, + warm_blobs: Option, + verified: AtomicUsize, made: AtomicUsize, refused: AtomicUsize, reused: AtomicUsize, + /// pipelines another process of the same preparation was building (`Claim`): left to it + elsewhere: AtomicUsize, split_programs: AtomicUsize, split_pieces: AtomicUsize, /// programs over `max_dxil` with no blob yet, and their DXIL bytes @@ -1505,9 +1578,12 @@ impl Pipelines { Ok(Pipelines { dev, signatures: Mutex::new(Default::default()), + warm_blobs: None, + verified: AtomicUsize::new(0), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), + elsewhere: AtomicUsize::new(0), split_programs: AtomicUsize::new(0), split_pieces: AtomicUsize::new(0), capped: AtomicUsize::new(0), @@ -1557,9 +1633,33 @@ impl Pipelines { self.make_one(&c.dxil, &c.samplers, false, path_override); } + fn prepare_compute(&self, blob: &[u8], windows: u32) -> Result<(), String> { + let split = recomp::pso::wave32_only_for_device(&self.dev); + let program = recomp::pso::console_to_dxil_in(blob, recomp::pso::Stage::Compute, 0, split, windows)?; + self.prepare_compiled_compute(&program) + } + + fn prepare_compiled_compute(&self, program: &recomp::pso::Compiled) -> Result<(), String> { + let make = |dxil: &[u8], chained| { + self.make_required(dxil, &program.samplers, chained, None, true) + }; + make(&program.dxil, false)?; + if let Some(chain) = program.dispatch_chain.as_deref().filter(|c| c.pieces.len() >= 2) { + for piece in &chain.pieces { make(piece, true)?; } + make(&program.dxil, true)?; + } + Ok(()) + } + fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option) { + let _ = self.make_required(dxil, samplers, chained, path_override, false); + } + + fn make_required(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, + path_override: Option, required: bool) -> Result<(), String> { use windows::Win32::Graphics::Direct3D12::*; let key: (bool, Vec) = (chained, samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect()); + let layout = self.warm_blobs.as_ref().map(|_| warm_blobs::digest(&key)); let rs = { let mut g = self.signatures.lock().unwrap(); match g.get(&key) { @@ -1575,9 +1675,9 @@ impl Pipelines { g.insert(key, rs.clone()); rs } - Err(_) => { + Err(e) => { self.refused.fetch_add(1, Ordering::Relaxed); - return; + return Err(format!("Creating compute root signature: {e}")); } } } @@ -1596,7 +1696,15 @@ impl Pipelines { } driver_cache::path_for(dxil, desc.Flags.0, chained) }); - let cached = path.as_deref().and_then(driver_cache::load); + let mut cached = path.as_deref().and_then(driver_cache::load); + let receipt = self.warm_blobs.as_ref().zip(layout).zip(path.as_deref()); + if let (Some(((book, layout), path)), Some(blob)) = (receipt, cached.as_ref()) { + if book.contains(&warm_blobs::stamp(path, layout, blob)) { + self.verified.fetch_add(1, Ordering::Relaxed); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return Ok(()); + } + } let over_cap = self.max_dxil != 0 && dxil.len() > self.max_dxil; // over the cap and no blob from an earlier run: the driver's compile of this one takes // tens of minutes and gigabytes; the pass finishes without it, and the runtime builds it @@ -1605,7 +1713,7 @@ impl Pipelines { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - return; + return Err(format!("Compute DXIL exceeds the native pipeline size limit ({} bytes)", dxil.len())); } { let mut n = self.running.0.lock().unwrap(); @@ -1614,6 +1722,28 @@ impl Pipelines { } *n += 1; } + // (another process may have written the blob while this one waited for its turn) + if cached.is_none() { + cached = path.as_deref().and_then(driver_cache::load); + } + // not in the cache: the one process that claims the pipeline builds it. Records with the + // same program are in several workers' slices, and the driver's compile of one took + // twice as long in each of four workers that built it at once. + let claim = match (&cached, path.as_deref()) { + (None, Some(path)) => match Claim::take(path) { + Some(c) => Some(c), + // A mandatory job needs a native result even if another process owns the cache write. + None if required => None, + None => { + *self.running.0.lock().unwrap() -= 1; + self.running.1.notify_one(); + self.elsewhere.fetch_add(1, Ordering::Relaxed); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return Err("Another process is preparing this compute pipeline".into()); + } + }, + _ => None, + }; let from_cache = cached.as_ref().and_then(|bytes| { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: bytes.as_ptr().cast(), CachedBlobSizeInBytes: bytes.len() }; // a driver that cannot use the blob may compile from the DXIL itself and still @@ -1633,35 +1763,43 @@ impl Pipelines { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - return; + return Err(format!("The cached compute pipeline was rejected and {} bytes of DXIL exceed the limit", dxil.len())); } let r = if let Some(pso) = from_cache { + if let (Some(((book, layout), path)), Some(blob)) = (receipt, cached.as_ref()) { + book.record(warm_blobs::stamp(path, layout, blob)); + } self.reused.fetch_add(1, Ordering::Relaxed); Ok(pso) } else { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let pso = unsafe { self.dev.CreateComputePipelineState::(&desc) }; - if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { + if let (Some(path), Ok(pso)) = (path.as_deref().filter(|_| claim.is_some() || cached.is_some()), &pso) { if let Ok(blob) = unsafe { pso.GetCachedBlob() } { let bytes = unsafe { blob.GetBufferPointer() }.cast::(); let len = unsafe { blob.GetBufferSize() }; if !bytes.is_null() && len != 0 { - driver_cache::write(path, unsafe { std::slice::from_raw_parts(bytes, len) }); + let bytes = unsafe { std::slice::from_raw_parts(bytes, len) }; + if driver_cache::write(path, bytes) { + if let Some(((book, layout), _)) = receipt { book.record(warm_blobs::stamp(path, layout, bytes)); } + } } } } pso }; + drop(claim); *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - let done = match r { + let done = match &r { Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1, Err(_) => self.refused.fetch_add(1, Ordering::Relaxed) + 1, }; if done % 25 == 0 { eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); } + r.map(drop).map_err(|e| format!("Creating native compute pipeline ({} bytes of DXIL): {e}", dxil.len())) } } @@ -1751,6 +1889,40 @@ pub(crate) struct LaunchPreparation { pub done: AtomicUsize, pub total: AtomicUsize, pub cancel: std::sync::atomic::AtomicBool, + /// The worker processes building compute pipelines (0: none; `done` and `total` then count + /// the records translated here, with them the records the workers have passed). + pub workers: AtomicUsize, + /// The workers build graphics pipelines (`graphics_in_workers`): `done` and `total` count those. + pub graphics: std::sync::atomic::AtomicBool, + /// While replaying the discovered corpus, only verified native successes advance `done`. + pub corpus: std::sync::atomic::AtomicBool, +} + +impl LaunchPreparation { + pub(crate) fn begin_corpus(&self, total: usize) { + self.done.store(0, Ordering::Relaxed); + self.total.store(total, Ordering::Relaxed); + self.corpus.store(true, Ordering::Release); + } + + pub(crate) fn complete_corpus(&self, count: usize) -> Result<(), String> { + if self.cancel.load(Ordering::Relaxed) { return Err("Pipeline preparation cancelled".into()); } + if !self.corpus.load(Ordering::Acquire) || count > self.total.load(Ordering::Relaxed) { + return Err("Native completion count exceeds the discovered corpus".into()); + } + self.done.fetch_max(count, Ordering::Release); + Ok(()) + } + + pub(crate) fn check_corpus_complete(&self) -> Result<(), String> { + if self.cancel.load(Ordering::Relaxed) { return Err("Pipeline preparation cancelled".into()); } + let done = self.done.load(Ordering::Acquire); + let total = self.total.load(Ordering::Relaxed); + if !self.corpus.load(Ordering::Acquire) || total == 0 || done != total { + return Err(format!("Native pipeline preparation incomplete: {done} of {total} recipes confirmed")); + } + Ok(()) + } } /// Unpacked shader containers in the title's shaders directory. Do not follow directory @@ -1772,6 +1944,16 @@ fn loose_inputs(dir: &Path, files: &mut Vec) -> std::io::Result<()> { } pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> Result<(), String> { + let corpus = pso_corpus::discover(root)?; + prepare_title_inputs(root, progress, corpus.as_ref())?; + if let Some(corpus) = corpus { + corpus.prepare(progress)?; + progress.check_corpus_complete()?; + } + Ok(()) +} + +fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation, corpus: Option<&pso_corpus::Corpus>) -> Result<(), String> { let mut inputs = Vec::new(); let pack = root.join("shaders.rpf"); if pack.try_exists().map_err(|e| e.to_string())? { @@ -1790,21 +1972,614 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R progress.total.store(inputs.iter().map(Input::len).sum(), Ordering::Relaxed); let mut windows = crate::gpu::uma::configured_runtime_windows() as u32; if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS; } - for input in inputs { + let workers = prepare_workers(); + for input in &inputs { + let coverage = corpus.filter(|c| c.compute_directory().is_some()) + .map(|corpus| ComputeCoverage::Published(corpus, Mutex::default(), AtomicUsize::new(0))); if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - precompile(&input, usize::MAX, windows, None, None, true, None, None, std::time::Instant::now(), Some(progress))?; + // a pack: its stages here, its compute pipelines in worker processes (the driver builds + // about two pipelines at a time for one process, whatever the processors) + if workers > 1 && matches!(input, Input::Pack { .. }) { + let n = input.len(); + precompile(input, usize::MAX, windows, None, None, false, None, None, std::time::Instant::now(), Some(progress), coverage.as_ref())?; + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + if coverage.as_ref().is_some_and(ComputeCoverage::all_staged) { continue; } + pipelines_in_workers(&pack, windows, workers, n, progress, coverage.as_ref())?; + continue; + } + precompile(input, usize::MAX, windows, None, None, true, None, None, std::time::Instant::now(), Some(progress), coverage.as_ref())?; } + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + if std::env::var("XCL_PREPARE_GRAPHICS").is_ok_and(|v| v.trim() == "0") { return Ok(()); } + graphics_in_workers(&inputs, windows, workers, progress, corpus.and_then(|c| c.graphics_path())) +} + +/// Only records verified byte-for-byte against the discovered corpus may leave their native +/// preparation to that pass. A worker also checks the index, key and bytes of its own pack. +enum ComputeCoverage<'a> { + Published(&'a pso_corpus::Corpus, Mutex>, AtomicUsize), + Slice(PathBuf, BTreeMap), +} + +const COVERAGE_MAP: &str = "XCL_PRECOMPILE_COVERAGE_MAP"; +const COVERAGE_DIR: &str = "XCL_PRECOMPILE_COVERAGE_DIR"; + +struct CoverageFile(PathBuf); +impl Drop for CoverageFile { + fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } +} + +impl ComputeCoverage<'_> { + fn all_staged(&self) -> bool { + matches!(self, Self::Published(_, _, remaining) if remaining.load(Ordering::Relaxed) == 0) + } + + fn covers(&self, index: usize, blob: &[u8]) -> Result { + let key = shader::fnv64(blob); + let path = match self { + Self::Published(corpus, _, remaining) => match corpus.compute_path(key) { + Some(path) => path.to_path_buf(), + None => { remaining.fetch_add(1, Ordering::Relaxed); return Ok(false); } + }, + Self::Slice(dir, keys) if keys.get(&index) == Some(&key) => dir.join(format!("{key:016x}.dxbc")), + Self::Slice(..) => return Ok(false), + }; + let staged = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?; + if blob != staged { + if shader::fnv64(&staged) != key { return Err(format!("Staged compute shader {key:016x} changed")); } + if let Self::Published(_, _, remaining) = self { remaining.fetch_add(1, Ordering::Relaxed); } + return Ok(false); + } + if let Self::Published(_, selected, _) = self { selected.lock().unwrap().insert(index, key); } + Ok(true) + } + + fn slice_file(&self) -> Result, String> { + use std::io::Write; + let Self::Published(corpus, selected, _) = self else { return Ok(None) }; + let Some(dir) = corpus.compute_directory() else { return Ok(None) }; + let selected = selected.lock().unwrap(); + if selected.is_empty() { return Ok(None); } + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos(); + let path = std::env::temp_dir().join(format!("xcl-compute-coverage-{}-{nonce}.bin", std::process::id())); + let mut file = std::fs::File::create_new(&path).map_err(|e| e.to_string())?; + let cleanup = CoverageFile(path); + let mut bytes = Vec::with_capacity(selected.len()*16); + for (&i, &key) in selected.iter() { bytes.extend_from_slice(&(i as u64).to_le_bytes()); bytes.extend_from_slice(&key.to_le_bytes()); } + file.write_all(&bytes).map_err(|e| e.to_string())?; + Ok(Some((cleanup, dir))) + } + + fn worker() -> Result, String> { + if std::env::var_os("XCL_PRECOMPILE_PARENT").is_none() { return Ok(None); } + let Some(path) = std::env::var_os(COVERAGE_MAP) else { return Ok(None) }; + let dir = std::env::var_os(COVERAGE_DIR).ok_or("Missing staged compute directory for worker")?; + Self::read_slice(Path::new(&path), PathBuf::from(dir)).map(Some) + } + + fn read_slice(path: &Path, dir: PathBuf) -> Result { + let bytes = std::fs::read(path).map_err(|e| e.to_string())?; + if bytes.len() % 16 != 0 { return Err("Incomplete compute worker coverage map".into()); } + let keys = bytes.chunks_exact(16).map(|b| (u64::from_le_bytes(b[..8].try_into().unwrap()) as usize, + u64::from_le_bytes(b[8..].try_into().unwrap()))).collect(); + Ok(Self::Slice(dir, keys)) + } +} + +/// `XCL_PREPARE_WORKERS`: the processes that build a pack's compute pipelines before a title +/// starts (1: in this process, as before). Unset: the logical processors less four, and no +/// more than 3 GB of the commit the system has left for each. +fn prepare_workers() -> usize { + if let Some(n) = std::env::var("XCL_PREPARE_WORKERS").ok().and_then(|v| v.parse::().ok()) { + return n.clamp(1, 32); + } + let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); + let (used, limit) = crate::host::system_commit(); + workers_for(cores, limit.saturating_sub(used)) +} + +/// The workers for `cores` logical processors (threads, not cores) and `free_mb` of commit left. +fn workers_for(cores: usize, free_mb: u64) -> usize { + cores.saturating_sub(4).min(32).min((free_mb / 3072) as usize).max(1) +} + +/// The record count of a builder's progress line (` 400/26503 (12 s)`). +fn progress_count(line: &str) -> Option { + let (d, rest) = line.trim().split_once('/')?; + let (n, rest) = rest.split_once(' ')?; + n.parse::().ok()?; + if !rest.starts_with('(') { return None; } + d.parse().ok() +} + +/// A pipeline one process builds: a file beside the driver blob it will write (`.claim`), +/// made when the build starts and gone when it ends. A second process that finds it leaves the +/// pipeline to the first. One left behind by a process that died is taken over after `STALE`. +struct Claim(PathBuf); + +impl Claim { + const STALE: std::time::Duration = std::time::Duration::from_secs(30 * 60); + + /// None: another process has it. + fn take(blob: &std::path::Path) -> Option { + let mut name = blob.as_os_str().to_owned(); + name.push(".claim"); + let path = PathBuf::from(name); + let make = || std::fs::OpenOptions::new().write(true).create_new(true).open(&path); + match make() { + Ok(_) => Some(Claim(path)), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + let old = std::fs::metadata(&path).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > Self::STALE); + (old && std::fs::remove_file(&path).is_ok() && make().is_ok()).then(|| Claim(path)) + } + // (the folder cannot be written: nothing is shared through it either) + Err(_) => Some(Claim(PathBuf::new())), + } + } +} + +impl Drop for Claim { + fn drop(&mut self) { + if !self.0.as_os_str().is_empty() { + let _ = std::fs::remove_file(&self.0); + } + } +} + +#[cfg(test)] +mod claim_tests { + use super::Claim; + + /// The first process to ask builds a pipeline, a second one leaves it, and it is free again + /// when the first is done. + #[test] + fn a_pipeline_is_claimed_by_one_builder_at_a_time() { + let dir = std::env::temp_dir().join(format!("xcl-claim-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let blob = dir.join("0123.pso"); + let first = Claim::take(&blob).expect("free"); + assert!(dir.join("0123.pso.claim").exists()); + assert!(Claim::take(&blob).is_none(), "claimed"); + assert!(Claim::take(&dir.join("4567.pso")).is_some(), "another pipeline is free"); + drop(first); + assert!(!dir.join("0123.pso.claim").exists()); + assert!(Claim::take(&blob).is_some(), "free again"); + let _ = std::fs::remove_dir_all(&dir); + } +} + +/// The compute pipelines of `pack` built by `workers` processes of this program, each on its own +/// slice of the records (`XCL_PRECOMPILE_SLICE`). A failed worker prevents guest entry. +fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation, + coverage: Option<&ComputeCoverage>) -> Result<(), String> { + let me = std::env::current_exe().map_err(|e| e.to_string())?; + let map = coverage.map(|c| c.slice_file()).transpose()?.flatten(); + let t0 = std::time::Instant::now(); + crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes"); + let (cancelled, failed, _) = in_workers(workers, records, progress, |i| { + let mut c = worker_command(&me); + if let Some((file, dir)) = &map { c.env(COVERAGE_MAP, &file.0).env(COVERAGE_DIR, dir); } + c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); + if std::env::var_os("XCL_ADAPTER").is_none() && !progress.adapter.is_empty() { c.env("XCL_ADAPTER", &progress.adapter); } + c.env("XCL_PRECOMPILE_SLICE", format!("{i}/{workers}")); + c + }); + if cancelled { return Err("Shader preparation cancelled".into()); } + if failed != 0 { return Err(format!("{failed} of {workers} compute pipeline workers failed")); } + crate::xlog_info!("Shader preparation: compute pipelines done in {:.0} s ({failed} of {workers} workers failed)", t0.elapsed().as_secs_f64()); + Ok(()) +} + +/// A preparation worker: this program, not a host and not a launcher's child, a builder that +/// ends when this process does. +fn worker_command(me: &Path) -> std::process::Command { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let mut c = std::process::Command::new(me); + for gone in ["XCL_HOST", "XCL_PREPARATION_PARENT", "XCL_PREPARATION_MENU", "XCL_RUN_SECONDS", COVERAGE_MAP, COVERAGE_DIR] { c.env_remove(gone); } + c.env("XCL_PRECOMPILE_PARENT", std::process::id().to_string()); + if std::env::var_os("XCL_DXC_THREADS").is_none() { c.env("XCL_DXC_THREADS", "2"); } + if std::env::var_os("XCL_PIPELINE_THREADS").is_none() { c.env("XCL_PIPELINE_THREADS", "1"); } + c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped()).creation_flags(CREATE_NO_WINDOW); + c +} + +/// `workers` worker processes (`command(i)`), their progress lines (`progress_count`, each of its +/// own part) the count of `records` in all on the screen while they run: whether preparation was +/// cancelled (they are ended then), how many failed, and the summary line each wrote last +/// (`graphics_summary`). +fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut command: impl FnMut(usize) -> std::process::Command) -> (bool, usize, Vec) { + use std::io::BufRead; + // the workers' pass has its own count on the screen: the records they have passed + let (done_before, total_before) = (progress.done.load(Ordering::Relaxed), progress.total.load(Ordering::Relaxed)); + progress.done.store(0, Ordering::Relaxed); + progress.total.store(records, Ordering::Relaxed); + progress.workers.store(workers, Ordering::Relaxed); + let counts: Vec = (0..workers).map(|_| AtomicUsize::new(0)).collect(); + let summaries: Vec> = (0..workers).map(|_| Mutex::new(String::new())).collect(); + let mut children = Vec::new(); + for i in 0..workers { + match command(i).spawn() { + Ok(child) => children.push((i, child)), + Err(e) => crate::xlog_warn!("Shader preparation: worker {i} did not start: {e}"), + } + } + let cancelled = std::thread::scope(|s| { + for (i, child) in children.iter_mut() { + let Some(err) = child.stderr.take() else { continue }; + let (count, summary) = (&counts[*i], &summaries[*i]); + s.spawn(move || { + // (a builder ends its progress lines with a line feed; others pass by) + let mut r = std::io::BufReader::new(err); + let mut buf = Vec::new(); + while r.read_until(b'\n', &mut buf).is_ok_and(|n| n > 0) { + for part in String::from_utf8_lossy(&buf).split(['\r', '\n']) { + if let Some(d) = progress_count(part) { count.store(d, Ordering::Relaxed); } + if graphics_summary(part).is_some() { *summary.lock().unwrap() = part.to_string(); } + } + buf.clear(); + } + }); + } + loop { + // (a worker counts the records of its own slice) + let d: usize = counts.iter().map(|c| c.load(Ordering::Relaxed)).sum(); + progress.done.store(d.min(records), Ordering::Relaxed); + if progress.cancel.load(Ordering::Relaxed) { + for (_, child) in children.iter_mut() { let _ = child.kill(); } + return true; + } + if children.iter_mut().all(|(_, child)| !matches!(child.try_wait(), Ok(None))) { return false; } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + }); + let mut failed = workers - children.len(); + for (i, child) in children.iter_mut() { + match child.wait() { + Ok(st) if st.success() => {} + Ok(st) => { failed += 1; crate::xlog_warn!("Shader preparation: worker {i} ended with {st}"); } + Err(e) => { failed += 1; crate::xlog_warn!("Shader preparation: worker {i}: {e}"); } + } + } + progress.workers.store(0, Ordering::Relaxed); + progress.total.store(total_before, Ordering::Relaxed); + progress.done.store(done_before, Ordering::Relaxed); + (cancelled, failed, summaries.into_iter().map(|s| s.into_inner().unwrap()).collect()) +} + +/// The graphics pipelines earlier runs used (`gfx_records`), built before the title starts by +/// `workers` processes of this program (`graphics_worker`) the way the title builds them, so the +/// title finds their translations and driver blobs on disk and builds each in milliseconds. In +/// worker processes as the compute pipelines: the driver builds about two pipelines at a time for +/// one process, and a driver that ends a worker ends no title. Their shaders come from the title's +/// shader files (`inputs`) by key, as those of `used-shaders.txt`; each worker gets a file of its +/// part (`gfx_records`' format, with the shaders it needs). A worker must confirm every recipe. +fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation, staged_graphics: Option<&Path>) -> Result<(), String> { + let t0 = std::time::Instant::now(); + let path = gfx_records::path(); + let local = if path.try_exists().map_err(|e| e.to_string())? { gfx_records::read_history_payloads(&path)? } else { Vec::new() }; + let mut records = Vec::new(); + let mut embedded = std::collections::HashMap::new(); + for payload in local { + match gfx_records::decode(&payload).ok_or("Unrecognized graphics history entry")? { + gfx_records::Entry::Shader(key, code) => { + if crate::hle::d3d12x::real::shader_key(&code) != key { + return Err(format!("Graphics history shader {key:016x} failed its identity check")); + } + embedded.insert(key, code); + } + entry => if let Some(record) = GraphicsHistoryRecord::from_entry(entry) { records.push((payload, record)); }, + } + } + let mut local_count = records.len(); + let legacy = gfx_records::shared_history_path(); + if !inputs.is_empty() && legacy != path { + let scoped: HashSet<_> = records.iter().map(|(bytes, _)| bytes.as_slice()).collect(); + let candidates: Vec<_> = gfx_records::read(&legacy).into_iter().filter(|bytes| !scoped.contains(bytes.as_slice())) + .filter_map(|payload| Some((GraphicsHistoryRecord::from_entry(gfx_records::decode(&payload)?)?, payload))).collect(); + records.extend(candidates.into_iter().map(|(record, payload)| (payload, record))); + } + if records.is_empty() { + crate::xlog_info!("Shader preparation: no graphics pipelines of an earlier run to build"); + return Ok(()); + } + if let Some(staged) = staged_graphics { + let before = records.len(); + local_count = merge_staged_history(staged, &mut records, local_count, &mut embedded)?; + if before != records.len() { + crate::xlog_info!("Shader preparation: the mandatory staged job covers {} exact graphics history recipes", before - records.len()); + } + if records.is_empty() { return Ok(()); } + } + let wanted: HashSet<_> = records.iter().flat_map(|(_, record)| record.identity().1.iter().copied()) + .filter(|&key| key != 0 && !embedded.contains_key(&key)).collect(); + let mut shaders = if wanted.is_empty() { HashMap::new() } else { shaders_by_key(inputs, wanted, progress) }; + shaders.extend(embedded); + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + let (buildable, missing) = buildable(records.iter().map(|(_, r)| r), &shaders); + let local_missing = local_count - buildable.iter().take_while(|&&i| i < local_count).count(); + if local_missing != 0 { + crate::xlog_info!("Shader preparation: deferring {local_missing} of {local_count} recorded title graphics recipes until their shader sources are available"); + } + let shared_missing = missing - local_missing; + if shared_missing != 0 { crate::xlog_info!("Shader preparation: {shared_missing} shared graphics recipes have no matching shaders in this title"); } + if buildable.is_empty() { return Ok(()); } + let workers = workers.clamp(1, buildable.len()); + // each worker's part, with the shaders it needs (removed when they are done) + let mut jobs = Vec::new(); + for i in 0..workers { + let path = std::env::temp_dir().join(format!("xcl-prepare-{}-{i}.bin", std::process::id())); + let _ = std::fs::remove_file(&path); + let mut w = gfx_records::Writer::open(&path, u64::MAX).map_err(|e| format!("{}: {e}", path.display()))?; + let part: Vec = buildable.iter().copied().skip(i).step_by(workers).collect(); + let mut keys = HashSet::new(); + for &k in &part { + w.add(&records[k].0).map_err(|e| format!("{}: {e}", path.display()))?; + keys.extend(records[k].1.identity().1.iter().copied().filter(|&key| key != 0)); + } + for key in keys { + w.add(&gfx_records::shader_entry(key, &shaders[&key])).map_err(|e| format!("{}: {e}", path.display()))?; + } + jobs.push((path, part.len())); + } + let me = std::env::current_exe().map_err(|e| e.to_string())?; + crate::xlog_info!("Shader preparation: the {} graphics pipelines earlier runs used, in {workers} worker processes", buildable.len()); + progress.graphics.store(true, Ordering::Relaxed); + let (cancelled, failed, summaries) = in_workers(workers, buildable.len(), progress, |i| { + let mut c = worker_command(&me); + c.arg("shaders").arg(&jobs[i].0).args(["--graphics-records", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); + // (the title's adapter: its blobs are the ones it takes) + if std::env::var_os("XCL_ADAPTER").is_none() && !progress.adapter.is_empty() { c.env("XCL_ADAPTER", &progress.adapter); } + c + }); + progress.graphics.store(false, Ordering::Relaxed); + for (path, _) in &jobs { let _ = std::fs::remove_file(path); } + if cancelled { return Err("Shader preparation cancelled".into()); } + let sum = summaries.iter().filter_map(|s| graphics_summary(s)).fold([0usize; 4], |a, b| std::array::from_fn(|k| a[k] + b[k])); + if failed != 0 || sum[1] != 0 || sum[0] != buildable.len() { + return Err(format!("Graphics preparation incomplete: {} of {} confirmed, {} refused, {failed} workers failed", + sum[0], buildable.len(), sum[1])); + } + crate::xlog_info!( + "Shader preparation: graphics pipelines done in {:.0} s: {} made, {} failed; driver blobs: {} from disk, {} kept ({failed} of {workers} workers failed)", + t0.elapsed().as_secs_f64(), sum[0], sum[1], sum[2], sum[3] + ); Ok(()) } -fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, selected: Option<&std::collections::HashSet>, pipeline_threads: Option, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { +/// Only identical serialized descriptors can be left for the subsequent mandatory staged job. +fn merge_staged_history( + staged: &Path, records: &mut Vec<(Vec, GraphicsHistoryRecord)>, local_count: usize, + embedded: &mut HashMap>, +) -> Result { + let mut covered: HashMap<&[u8], bool> = records.iter().map(|(p, _)| (p.as_slice(), false)).collect(); + let wanted: HashSet = records.iter().flat_map(|(_, r)| r.identity().1.iter().copied()).filter(|k| *k != 0).collect(); + gfx_records::visit_payloads(staged, |payload| { + if let Some((key, code)) = gfx_records::shader_payload(payload) { + if wanted.contains(&key) { + if crate::hle::d3d12x::real::shader_key(code) != key || embedded.get(&key).is_some_and(|prior| prior.as_slice() != code) { + return Err(format!("Staged graphics shader {key:016x} failed its identity check")); + } + embedded.entry(key).or_insert_with(|| code.to_vec()); + } + } else if let Some(present) = covered.get_mut(payload) { + *present = true; + } + Ok(()) + })?; + let keep: Vec = records.iter().map(|(p, _)| !covered[p.as_slice()]).collect(); + let remaining_local = keep[..local_count].iter().filter(|&&k| k).count(); + let mut keep = keep.into_iter(); + records.retain(|_| keep.next().unwrap()); + Ok(remaining_local) +} + +/// The bytes of the shaders `wanted` (`real::shader_key`) in the title's shader files, looked +/// for on every processor. +fn shaders_by_key(inputs: &[Input], wanted: HashSet, progress: &LaunchPreparation) -> std::collections::HashMap> { + let found = Mutex::new(std::collections::HashMap::new()); + let threads = std::thread::available_parallelism().map_or(4, |n| n.get()); + for input in inputs { + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= input.len() || progress.cancel.load(Ordering::Relaxed) { break; } + let Some(blob) = input.get(i).1 else { continue }; + let key = crate::hle::d3d12x::real::shader_key(&blob); + if wanted.contains(&key) { found.lock().unwrap().insert(key, blob); } + }); + } + }); + } + found.into_inner().unwrap() +} + +enum GraphicsHistoryRecord { + Legacy(gfx_records::Record), + Mesh(gfx_records::MeshRecord), +} + +impl GraphicsHistoryRecord { + fn from_entry(entry: gfx_records::Entry) -> Option { + match entry { + gfx_records::Entry::Pipeline(record) => Some(Self::Legacy(record)), + gfx_records::Entry::MeshPipeline(record) => Some(Self::Mesh(record)), + gfx_records::Entry::Shader(..) => None, + } + } + + fn identity(&self) -> (u64, &[u64]) { + match self { + Self::Legacy(record) => (record.key, &record.shaders), + Self::Mesh(record) => (record.key, &record.shaders), + } + } +} + +/// The records (by their index) whose shaders are all in `shaders` and make their set's key, and +/// how many are not. +fn buildable<'a>(records: impl Iterator, shaders: &HashMap>) -> (Vec, usize) { + let (mut ok, mut missing) = (Vec::new(), 0); + for (i, record) in records.enumerate() { + let (key, keys) = record.identity(); + let blobs: Option> = keys.iter().filter(|&&k| k != 0).map(|k| shaders.get(k).map(Vec::as_slice)).collect(); + match blobs { + Some(blobs) if crate::hle::d3d12x::real::shader_set_key(blobs.iter().copied()) == key => ok.push(i), + _ => missing += 1, + } + } + (ok, missing) +} + +/// The counts of a graphics worker's last line (`graphics pipelines: 5 made, 1 failed; driver +/// blobs: 2 from disk, 3 kept`): made, failed, blobs from disk, blobs kept. +fn graphics_summary(line: &str) -> Option<[usize; 4]> { + let rest = line.trim().strip_prefix("graphics pipelines: ")?; + let mut n = rest.split(|c: char| !c.is_ascii_digit()).filter(|s| !s.is_empty()).map(|s| s.parse::()); + let out = [n.next()?.ok()?, n.next()?.ok()?, n.next()?.ok()?, n.next()?.ok()?]; + n.next().is_none().then_some(out) +} + +fn corpus_threads(requested: Option, default: usize) -> usize { + requested.or_else(|| std::env::var("XCL_PIPELINE_THREADS").ok()?.parse().ok()).unwrap_or(default).clamp(1, 32) +} + +/// `xcl shaders --graphics-records` (a worker of `graphics_in_workers`): the graphics +/// pipelines of a job file built as the title builds them, with the +/// title's memory windows (`windows`) and on its adapter (`XCL_ADAPTER`), `XCL_PIPELINE_THREADS` +/// at a time. A progress line a pipeline, then the summary `graphics_summary` reads. +fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { + use crate::hle::d3d12x::real; + end_with_parent(); + let mut shaders = std::collections::HashMap::new(); + let mut records = Vec::new(); + let entries = match gfx_records::read_job(job) { + Ok(entries) => entries, + Err(e) => { eprintln!("xcl shaders: {}: {e}", job.display()); return 2; } + }; + let mut recipe_keys = Vec::new(); + for (key, entry) in entries { + match entry { + gfx_records::Entry::Shader(key, code) => { + if real::shader_key(&code) != key || shaders.get(&key).is_some_and(|prior| prior != &code) { + eprintln!("xcl shaders: invalid or conflicting shader {key:016x} in {}", job.display()); + return 2; + } + shaders.insert(key, code); + } + entry => if let Some(record) = GraphicsHistoryRecord::from_entry(entry) { records.push(record); recipe_keys.push(key); }, + } + } + let n = records.len(); + let (ready, missing) = buildable(records.iter(), &shaders); + if missing != 0 { eprintln!("xcl shaders: {missing} graphics records have missing or mismatched shaders"); } + if ready.is_empty() { + eprintln!("graphics pipelines: 0 made, {missing} failed; driver blobs: 0 from disk, 0 kept"); + return if missing == 0 { 0 } else { 2 }; + } + // (no title memory here: its windows are given) + crate::gpu::uma::leave_out(); + recomp::pso::set_title_windows(windows); + recomp::dxc::set_memory_reserve(2); + let (device, book) = match Pipelines::for_adapter("auto") { + Ok(p) => { + let cache = recomp::dxc::cache_dir(); + let book = warm_replay::native_key(&p.dev).and_then(|key| { + let known = warm_replay::driver_files(&cache.join("driver")).unwrap_or_default(); + warm_replay::Index::open(&cache, &known, warm_blobs::digest(&(key, &recipe_keys)), windows) + }); + (real::prepare_device(p.dev), book) + }, + Err(e) => { eprintln!("xcl shaders: no pipeline device: {e}"); return 2; } + }; + let threads = corpus_threads(requested, 1).min(ready.len()); + let verified = AtomicUsize::new(0); + let (next, made, failed) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(missing)); + let t0 = std::time::Instant::now(); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(&index) = ready.get(i) else { break }; + let r = &records[index]; + let code = |key| shaders.get(&key).map(Vec::as_slice); + // (a pipeline that panics fails; the others are built) + let key = recipe_keys[index]; + let run = || std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match r { + GraphicsHistoryRecord::Legacy(record) => { + let desc = record.desc(record.shaders.map(code)); + unsafe { real::prepare_graphics(device, &desc, record.depth_bounds) } + } + GraphicsHistoryRecord::Mesh(record) => { + unsafe { real::replay_mesh_record(device, record, record.shaders.map(code)).is_ok() } + } + })).unwrap_or(false); + let ok = if let Some(book) = &book { + if book.can_defer(key) { + verified.fetch_add(1, Ordering::Relaxed); + true + } else { + let (ok, files) = warm_replay::capture(run); + if ok { book.add(key, files, matches!(r, GraphicsHistoryRecord::Mesh(_))); } + ok + } + } else { run() }; + if ok { + let d = made.fetch_add(1, Ordering::Relaxed) + 1; + eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); + } else { + failed.fetch_add(1, Ordering::Relaxed); + eprintln!("xcl shaders: failed graphics record {} (shader set {:016x})", index + 1, r.identity().0); + } + }); + } + }); + if let Some(book) = book { book.save(); } + eprintln!("previously verified native graphics recipes: {}", verified.into_inner()); + let (hits, _, stored) = real::driver_cache_stats(); + let failed = failed.into_inner(); + eprintln!("graphics pipelines: {} made, {failed} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner()); + if failed == 0 { 0 } else { 2 } +} + +/// `XCL_PRECOMPILE_PARENT=pid` (set for a title's preparation workers): this process ends when +/// that one does, so no builder is left on the GPU behind a title that was ended. +fn end_with_parent() { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{OpenProcess, WaitForSingleObject, INFINITE, PROCESS_SYNCHRONIZE}; + let Some(pid) = std::env::var("XCL_PRECOMPILE_PARENT").ok().and_then(|v| v.parse::().ok()) else { return }; + let h = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) }; + if h.is_null() { + // (gone already) + std::process::exit(3); + } + let h = h as usize; + std::thread::spawn(move || unsafe { + WaitForSingleObject(h as _, INFINITE); + CloseHandle(h as _); + std::process::exit(3); + }); +} + +fn precompile_slice(startup_owner: bool, value: Option<&str>) -> Option<(usize, usize)> { + if startup_owner { return None; } + let (i, n) = value?.split_once('/')?; + Some((i.trim().parse().ok()?, n.trim().parse::().ok().filter(|n| *n > 0)?)) +} + +fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, selected: Option<&std::collections::HashSet>, pipeline_threads: Option, t0: std::time::Instant, startup: Option<&LaunchPreparation>, coverage: Option<&ComputeCoverage>) -> Result<(), String> { + if startup.is_none() { end_with_parent(); } + let mandatory = startup.is_some() || std::env::var_os("XCL_PRECOMPILE_PARENT").is_some(); let pipelines = if pipelines { let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter.as_str())) .map_err(|e| format!("No pipeline device: {e}"))?; if let Some(threads) = pipeline_threads { p.most = threads.max(1); } - if startup.is_some() && std::env::var_os("XCL_PIPELINE_MAX_KB").is_none() { + if mandatory { p.warm_blobs = warm_blobs::Verified::for_device(&p.dev); } + if mandatory && std::env::var_os("XCL_PIPELINE_MAX_KB").is_none() { p.max_dxil = 0; } Some(p) @@ -1813,6 +2588,12 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on }; let pipelines = pipelines.as_ref(); let n = input.len().min(limit); + // `XCL_PRECOMPILE_SLICE=i/n` (experiment): this process takes only every n-th shader, from the + // i-th, so n processes share the work and each has its own driver compiler + let slice = precompile_slice(startup.is_some(), std::env::var("XCL_PRECOMPILE_SLICE").ok().as_deref()); + // a progress line every 200 records; every record for a title waiting on this builder + // (`pipelines_in_workers` shows the count) + let every = if std::env::var_os("XCL_PRECOMPILE_PARENT").is_some() { 1 } else { 200 }; let next = AtomicUsize::new(0); let (done, compiled, cached, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); let errors: Mutex> = Mutex::new(Vec::new()); @@ -1835,6 +2616,21 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let startup_device = pipelines.filter(|_| startup.is_some()); let graphics_split = split.unwrap_or_else(|| startup_device.map_or_else(recomp::runner::graphics_wave32, |p| recomp::pso::graphics_wave32_for_device(&p.dev))); let split = split.unwrap_or_else(|| startup_device.map_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w), |p| recomp::pso::wave32_only_for_device(&p.dev))); + // A graphics-stage proof skips translation only. Compute records still pass through + // coverage and native preparation, including a changed or newly staged compute job. + let pack_proof = startup.and_then(|owner| { + let Input::Pack { data, .. } = input else { return None }; + if n != input.len() || only.is_some() || selected.is_some() || slice.is_some() { return None; } + let extra_device; + let device = match pipelines { + Some(p) => &p.dev, + None => { + extra_device = Pipelines::for_adapter(&owner.adapter).ok()?; + &extra_device.dev + } + }; + warm_pack::Stages::open(warm_replay::native_key(device)?, data, n, windows, split, graphics_split) + }); println!( "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), @@ -1851,11 +2647,18 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if i >= n { break; } + if slice.is_some_and(|(part, count)| i % count != part) { + continue; + } let record_done = || { let d = done.fetch_add(1, Ordering::Relaxed) + 1; if let Some(p) = startup { p.done.fetch_add(1, Ordering::Relaxed); } - if d % 200 == 0 { eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); } + if d % every == 0 { eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); } }; + if pack_proof.as_ref().is_some_and(|p| p.covered(i)) { + record_done(); + continue; + } let (name, blob) = input.get(i); let Some(blob) = blob else { if startup.is_some() { failed.fetch_add(1, Ordering::Relaxed); } @@ -1884,13 +2687,29 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // a compute program as a title's pipeline translates it (`pso::console_to_dxil_in`): // into the translation cache too, so the title does not translate it again if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) { + if let Some(coverage) = coverage { + match coverage.covers(i, &blob) { + Ok(true) => { record_done(); continue; } + Err(e) => { + failed.fetch_add(1, Ordering::Relaxed); + let mut logs = errors.lock().unwrap(); + if logs.len() < 10 { logs.push(format!("{name}: {e}")); } + record_done(); + continue; + } + Ok(false) => {} + } + } match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { - if startup.is_some() { - p.make(&c); - if c.dispatch_chain.as_ref().is_some_and(|plan| plan.pieces.len() >= 2) { - p.make_one(&c.dxil, &c.samplers, true, None); + if mandatory { + if let Err(e) = p.prepare_compiled_compute(&c) { + failed.fetch_add(1, Ordering::Relaxed); + let mut logs = errors.lock().unwrap(); + if logs.len() < 10 { logs.push(format!("{name}: {e}")); } + record_done(); + continue; } } else { let used = used_earlier.contains(&pipeline_key(&blob)); @@ -1910,6 +2729,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on record_done(); continue; } + let mut stage_outputs = Vec::new(); for f in &sh.fssm { let Some(mode) = recomp::interface(&blob, &sh, f) else { continue }; let jobs: Vec<(&str, Option)> = match &mode { @@ -1944,9 +2764,14 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } }; for (profile, src) in &jobs { - match recomp::dxc::compile_cached(src.as_deref().unwrap_or(&t.hlsl), "main", profile) { - Ok((_, true)) => cached.fetch_add(1, Ordering::Relaxed), - Ok(_) => compiled.fetch_add(1, Ordering::Relaxed), + let src = src.as_deref().unwrap_or(&t.hlsl); + match recomp::dxc::compile_cached(src, "main", profile) { + Ok((bytes, hit)) => { + if pack_proof.is_some() { + stage_outputs.push((recomp::dxc::cache_key(src, "main", profile), bytes.len() as u64)); + } + if hit { &cached } else { &compiled }.fetch_add(1, Ordering::Relaxed) + } Err(e) => { let mut g = errors.lock().unwrap(); if g.len() < 10 { @@ -1958,6 +2783,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } } } + if let Some(proof) = &pack_proof { proof.record(i, stage_outputs); } record_done(); }); } @@ -1973,6 +2799,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } let failed = failed.into_inner(); let skipped_reason = if startup.is_some() { "runtime pairing or unsupported translation" } else { "GS – paired at pipeline creation" }; + if let Some(ComputeCoverage::Published(_, selected, _)) = coverage { + let count = selected.lock().unwrap().len(); + if count != 0 { crate::xlog_info!("Shader preparation: {count} byte-matched compute records will be built by the staged corpus"); } + } println!( "compiled {}, already cached {}, errors {}, skipped ({skipped_reason}) {}, time {:.1} s", compiled.into_inner(), @@ -1986,7 +2816,12 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on make_pipelines(p, pipeline_jobs.into_inner().unwrap()); } println!("pipelines made on the GPU {}, refused {}", p.made.load(Ordering::Relaxed), p.refused.load(Ordering::Relaxed)); + if let Some(book) = &p.warm_blobs { + book.save(); + println!("previously verified native compute pipelines {}", p.verified.load(Ordering::Relaxed)); + } println!("pipelines loaded from the driver cache {}", p.reused.load(Ordering::Relaxed)); + println!("pipelines left to another process that was building them {}", p.elsewhere.load(Ordering::Relaxed)); let split_programs = p.split_programs.load(Ordering::Relaxed); if split_programs != 0 { println!("split compute programs: {} ({} pieces)", split_programs, p.split_pieces.load(Ordering::Relaxed)); @@ -1998,11 +2833,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } let errors = errors.into_inner().unwrap(); for e in &errors { println!(" {e}"); } - if let Some(progress) = startup { - if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - let p = pipelines.expect("startup requested pipelines"); - let refused = p.refused.load(Ordering::Relaxed); - let capped = p.capped.load(Ordering::Relaxed); + if mandatory { + if startup.is_some_and(|p| p.cancel.load(Ordering::Relaxed)) { return Err("Shader preparation cancelled".into()); } + // (no pipelines here when worker processes build them: `pipelines_in_workers`) + let refused = pipelines.map_or(0, |p| p.refused.load(Ordering::Relaxed)); + let capped = pipelines.map_or(0, |p| p.capped.load(Ordering::Relaxed)); if failed + refused + capped > 0 { let cause = errors.first().map(String::as_str).unwrap_or( if capped > 0 { "Raise XCL_PIPELINE_MAX_KB or set it to 0 to prepare larger pipelines." } @@ -2010,6 +2845,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on return Err(format!("Shader preparation stopped: {failed} record failures, {refused} refused pipelines, {capped} over the size cap. {cause}")); } } + if let Some(proof) = pack_proof { proof.save(); } Ok(()) } @@ -2340,6 +3176,137 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim #[cfg(test)] mod tests { + /// The workers of a title's shader preparation: four logical processors are left free, + /// 3 GB of commit for each, and one where there is no room. + #[test] + fn preparation_workers_leave_two_processors_and_follow_the_commit_left() { + assert_eq!(workers_for(32, 100_000), 28); + assert_eq!(workers_for(8, 100_000), 4); + assert_eq!(workers_for(32, 10_000), 3); + assert_eq!(workers_for(2, 100_000), 1); + assert_eq!(workers_for(64, 1_000_000), 32); + assert_eq!(workers_for(32, 0), 1); + } + + /// A builder's progress line gives its record count; its other lines give none. + #[test] + fn a_builders_progress_line_gives_its_count() { + assert_eq!(progress_count(" 400/26503 (12 s)"), Some(400)); + assert_eq!(progress_count("26400/26503 (1339 s)"), Some(26400)); + assert_eq!(progress_count("xcl: [SHADER] direct DXIL fallback stage=CS reason=a/b (c)"), None); + assert_eq!(progress_count(" pipelines: 50 made, 0 refused"), None); + assert_eq!(progress_count("3/4"), None); + } + + /// A graphics worker's summary gives its counts; its progress lines and others give none. + #[test] + fn a_graphics_workers_summary_gives_its_counts() { + assert_eq!(graphics_summary("graphics pipelines: 512 made, 3 failed; driver blobs: 40 from disk, 470 kept"), Some([512, 3, 40, 470])); + assert_eq!(graphics_summary(" graphics pipelines: 0 made, 0 failed; driver blobs: 0 from disk, 0 kept\r"), Some([0; 4])); + assert_eq!(graphics_summary(" 12/512 (3 s)"), None); + assert_eq!(graphics_summary("graphics pipelines: 5 made"), None); + assert_eq!(graphics_summary("graphics pipelines: 1 made, 2 failed; driver blobs: 3 from disk, 4 kept, 5 more"), None); + assert_eq!(progress_count("graphics pipelines: 512 made, 3 failed; driver blobs: 40 from disk, 470 kept"), None); + } + + /// A graphics record is built when every shader it names is found and they make its set's + /// key (the key `used-pipelines.txt` has); one with a shader not in the title's files, or + /// other shaders under its keys, is left out. + #[test] + fn a_graphics_record_is_built_only_with_its_own_shaders() { + use crate::hle::d3d12x::gfx_records::{decode, encode, encode_mesh}; + use crate::hle::d3d12x::real::{shader_key, shaders_key}; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_GRAPHICS_PIPELINE_STATE_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, + }; + let (vs, ps, ms) = (b"vertex".to_vec(), b"pixel".to_vec(), b"mesh".to_vec()); + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let record = |key, shaders| { + GraphicsHistoryRecord::from_entry(decode(&unsafe { encode(key, shaders, &desc) }).unwrap()).unwrap() + }; + let both = [shader_key(&vs), shader_key(&ps), 0, 0, 0]; + let mesh = |key, shaders| { + let layout = [D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32]; + let payload = encode_mesh(key, shaders, &layout, &desc, false).unwrap(); + GraphicsHistoryRecord::from_entry(decode(&payload).unwrap()).unwrap() + }; + let records = [ + record(shaders_key(&[vs.clone(), ps.clone()]), both), + record(shaders_key(&[vs.clone()]), [shader_key(&vs), 0, 0, 0, 0]), + record(shaders_key(&[vs.clone(), b"other".to_vec()]), [shader_key(&vs), shader_key(b"other"), 0, 0, 0]), + record(shaders_key(&[ps.clone(), vs.clone()]), both), + mesh(shaders_key(&[ms.clone(), ps.clone()]), [shader_key(&ms), shader_key(&ps)]), + mesh(shaders_key(&[ps.clone(), ms.clone()]), [shader_key(&ms), shader_key(&ps)]), + ]; + let shaders = HashMap::from([(shader_key(&vs), vs), (shader_key(&ps), ps), (shader_key(&ms), ms)]); + assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1, 4], 3)); + } + + #[test] + fn staged_history_defers_exact_recipes_and_supplies_sources_for_other_variants() { + use crate::hle::d3d12x::real::shader_key; + use windows::Win32::Graphics::Direct3D12::D3D12_GRAPHICS_PIPELINE_STATE_DESC; + let path = std::env::temp_dir().join(format!("xcl-staged-history-{}.bin", std::process::id())); + let _ = std::fs::remove_file(&path); + let code = b"vertex source"; + let key = shader_key(code); + let pipeline = |mask| { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { SampleMask: mask, ..Default::default() }; + let payload = unsafe { gfx_records::encode(key, [key, 0, 0, 0, 0], &desc) }; + let record = GraphicsHistoryRecord::from_entry(gfx_records::decode(&payload).unwrap()).unwrap(); + (payload, record) + }; + let mut records = vec![pipeline(1), pipeline(2), pipeline(1), pipeline(3)]; + { + let mut staged = gfx_records::Writer::open(&path, u64::MAX).unwrap(); + staged.add(&records[0].0).unwrap(); + staged.add(&gfx_records::shader_entry(key, code)).unwrap(); + } + let mut sources = HashMap::new(); + assert_eq!(merge_staged_history(&path, &mut records, 2, &mut sources).unwrap(), 1); + assert_eq!(records.len(), 2); + assert_eq!(records[0].0, pipeline(2).0); + assert_eq!(records[1].0, pipeline(3).0); + assert_eq!(buildable(records.iter().map(|(_, r)| r), &sources), (vec![0, 1], 0)); + { + let mut staged = gfx_records::Writer::open(&path, u64::MAX).unwrap(); + staged.add(&gfx_records::shader_entry(key, b"wrong")).unwrap(); + } + assert!(merge_staged_history(&path, &mut records, 1, &mut sources).unwrap_err().contains("identity check")); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn a_graphics_job_with_a_missing_or_incorrectly_named_shader_fails() { + use crate::hle::d3d12x::gfx_records::{encode_mesh, shader_entry, Writer}; + use crate::hle::d3d12x::real::shader_key; + let path = std::env::temp_dir().join(format!("xcl-graphics-missing-{}.bin", std::process::id())); + let _ = std::fs::remove_file(&path); + let bytes = b"mesh"; + let key = shader_key(bytes); + { + let mut job = Writer::open(&path, u64::MAX).unwrap(); + job.add(&encode_mesh(key, [key, 0], &[25], &Default::default(), false).unwrap()).unwrap(); + } + assert_eq!(graphics_worker(&path, 1, Some(1)), 2); + { + let mut job = Writer::open(&path, u64::MAX).unwrap(); + job.add(&shader_entry(key, b"different mesh")).unwrap(); + } + assert_eq!(graphics_worker(&path, 1, Some(1)), 2); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn explicit_pipeline_worker_counts_can_use_all_thirty_two_slots() { + for count in [1, 2, 8, 16, 32] { + assert_eq!(corpus_threads(Some(count), 1), count); + } + assert_eq!(corpus_threads(Some(0), 1), 1); + assert_eq!(corpus_threads(Some(33), 1), 32); + } + /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the /// key of a pipeline of that one shader, as `real::shaders_key` makes it. #[test] @@ -2366,6 +3333,47 @@ mod tests { sample(5, &[compute]) } + #[test] + fn staged_compute_covers_only_its_exact_sources_in_loose_and_pack_passes() { + let name = format!("xcl-compute-membership-{}-{}", std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()); + let root = std::env::temp_dir().join(name); + let base = root.join(".xcl/pso-corpus"); + let dir = base.join("compute"); + std::fs::create_dir_all(&dir).unwrap(); + let blob = compute_sample(); + let file = dir.join(format!("{:016x}.dxbc", shader::fnv64(&blob))); + std::fs::write(&file, &blob).unwrap(); + std::fs::write(base.join("windows"), "4").unwrap(); + std::fs::write(base.join("complete"), "0 1").unwrap(); + let corpus = pso_corpus::discover(&root).unwrap().unwrap(); + let parent = ComputeCoverage::Published(&corpus, Mutex::default(), AtomicUsize::new(0)); + assert!(parent.covers(3, &blob).unwrap()); + assert!(parent.all_staged(), "no compute slice workers needed"); + assert!(!parent.covers(6, b"different source").unwrap()); + assert!(!parent.all_staged(), "uncovered compute records still need the slice"); + let (map, directory) = parent.slice_file().unwrap().unwrap(); + let child = ComputeCoverage::read_slice(&map.0, directory.to_owned()).unwrap(); + assert!(child.covers(3, &blob).unwrap()); + assert!(!child.covers(7, &blob).unwrap(), "index absent from the checked pack"); + assert!(!child.covers(3, b"changed input").unwrap(), "parent and child pack differ"); + std::fs::write(&file, b"changed after discovery").unwrap(); + assert!(child.covers(3, &blob).is_err(), "corrupt staged data cannot satisfy a recipe"); + std::fs::remove_file(&file).unwrap(); + assert!(parent.covers(3, &blob).is_err(), "missing staged data cannot satisfy a recipe"); + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn launch_owner_ignores_inherited_slices_and_workers_drop_foreign_coverage() { + assert_eq!(precompile_slice(true, Some("1/2")), None); + assert_eq!(precompile_slice(false, Some("1/2")), Some((1, 2))); + let command = worker_command(Path::new("xcl.exe")); + for name in [COVERAGE_MAP, COVERAGE_DIR] { + assert!(command.get_envs().any(|(key, value)| key == name && value.is_none())); + } + } + #[test] fn record_hash_is_strict_hex() { assert_eq!(parse_record_hash("0x0123aB").unwrap(), 0x123AB); diff --git a/crates/xcl/src/shaders/pso_corpus.rs b/crates/xcl/src/shaders/pso_corpus.rs new file mode 100644 index 0000000000..2a1237cbf4 --- /dev/null +++ b/crates/xcl/src/shaders/pso_corpus.rs @@ -0,0 +1,214 @@ +//! A staged set of native graphics and compute recipes, shared by startup and offline preparation. +use super::{graphics_summary, progress_count, recomp, worker_command, LaunchPreparation, Pipelines}; +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{mpsc, Mutex}; +use std::time::Duration; + +pub(crate) struct Corpus { + graphics: Option<(PathBuf, usize)>, + compute: Vec<(u64, PathBuf)>, + windows: u32, +} + +pub(crate) fn discover(root: &Path) -> Result, String> { + let dir = root.join(".xcl").join("pso-corpus"); + if !dir.try_exists().map_err(|e| e.to_string())? { return Ok(None); } + let marker = std::fs::read_to_string(dir.join("complete")).map_err(|e| format!("Incomplete pipeline corpus: {e}"))?; + let expected = marker.split_whitespace().map(str::parse::).collect::, _>>() + .map_err(|_| "Invalid pipeline corpus counts")?; + if expected.len() != 2 { return Err("Expected graphics and compute counts in the corpus marker".into()); } + let encoded = std::fs::read_to_string(dir.join("windows")).map_err(|e| e.to_string())?; + let encoded = encoded.trim().parse::().map_err(|_| "Invalid corpus memory window count")?; + let count = (encoded & 127) as usize; + let heap = encoded & 128 != 0; + if count == 0 || !recomp::valid_window_count(count, heap) || heap && count <= 1 { + return Err(format!("Invalid corpus memory window configuration {encoded}")); + } + let windows = count as u32 | if heap { recomp::HEAP_WINDOWS } else { 0 }; + let path = dir.join("graphics.bin"); + let graphics = if path.try_exists().map_err(|e| e.to_string())? { + if expected[0] == 0 { return Err("Unexpected graphics job in compute-only corpus".into()); } + // The worker validates and decodes the job. Require its independent native-success + // count to match the marker before handoff, without loading the job twice. + Some((path, expected[0])) + } else { None }; + let mut compute = Vec::new(); + let folder = dir.join("compute"); + if folder.try_exists().map_err(|e| e.to_string())? { + for entry in std::fs::read_dir(&folder).map_err(|e| e.to_string())? { + let entry = entry.map_err(|e| e.to_string())?; + let path = entry.path(); + let name = entry.file_name(); + let key = name.to_str().and_then(|s| s.strip_suffix(".dxbc")) + .filter(|s| s.len() == 16).and_then(|s| u64::from_str_radix(s, 16).ok()); + let key = key.ok_or_else(|| format!("Invalid compute entry {}", path.display()))?; + if !entry.file_type().map_err(|e| e.to_string())?.is_file() { + return Err(format!("Expected a compute file at {}", path.display())); + } + compute.push((key, path)); + } + } + compute.sort_unstable(); + if expected != [graphics.as_ref().map_or(0, |(_, n)| *n), compute.len()] { + return Err("Pipeline corpus is missing records. Restage before launching.".into()); + } + if graphics.is_none() && compute.is_empty() { return Err("Published pipeline corpus is empty".into()); } + Ok(Some(Corpus { graphics, compute, windows })) +} + +impl Corpus { + pub(super) fn graphics_path(&self) -> Option<&Path> { + self.graphics.as_ref().map(|(path, _)| path.as_path()) + } + + pub(super) fn compute_path(&self, key: u64) -> Option<&Path> { + let i = self.compute.binary_search_by_key(&key, |(key, _)| *key).ok()?; + Some(self.compute[i].1.as_path()) + } + + pub(super) fn compute_directory(&self) -> Option<&Path> { + self.compute.first().and_then(|(_, path)| path.parent()) + } + + pub(crate) fn prepare(&self, progress: &LaunchPreparation) -> Result<(), String> { + self.prepare_with_threads(progress, None) + } + + pub(super) fn prepare_with_threads(&self, progress: &LaunchPreparation, requested: Option) -> Result<(), String> { + let graphics_count = self.graphics.as_ref().map_or(0, |(_, n)| *n); + let total = graphics_count.checked_add(self.compute.len()).ok_or("Pipeline corpus count overflow")?; + progress.begin_corpus(total); + let count = self.windows & !recomp::HEAP_WINDOWS; + let runtime = crate::gpu::uma::configured_runtime_windows(); + if count as usize != runtime || (self.windows & recomp::HEAP_WINDOWS != 0) != (runtime > 1 && recomp::pso::heap_windows()) { + return Err(format!("Pipeline corpus memory configuration differs from the runtime ({runtime} windows). Restage for the current configuration or select the matching XCL_UMA_WINDOWS and XCL_HEAP_WINDOWS.")); + } + let parallel = super::corpus_threads(requested, super::prepare_workers().min(8)); + if let Some((path, n)) = &self.graphics { + run_graphics(path, *n, count, parallel, progress)?; + } + if self.compute.is_empty() { return progress.check_corpus_complete(); } + let mut pipelines = Pipelines::for_adapter(&progress.adapter)?; + pipelines.warm_blobs = super::warm_blobs::Verified::for_device(&pipelines.dev); + pipelines.max_dxil = 0; + pipelines.most = parallel; + let next = AtomicUsize::new(0); + let completed = Mutex::new(graphics_count); + let error = Mutex::new(None); + std::thread::scope(|scope| { + for _ in 0..parallel.min(self.compute.len()) { + scope.spawn(|| loop { + if progress.cancel.load(Ordering::Acquire) || error.lock().unwrap().is_some() { break; } + let i = next.fetch_add(1, Ordering::Relaxed); + let Some((key,path)) = self.compute.get(i) else { break }; + let result = std::fs::read(path).map_err(|e| e.to_string()).and_then(|code| { + if crate::gpu::shader::fnv64(&code) != *key || !super::is_compute_container(&code) { + return Err("Compute shader identity or stage differs from the staged recipe".into()); + } + pipelines.prepare_compute(&code, self.windows)?; + let mut done = completed.lock().unwrap(); + *done += 1; + progress.complete_corpus(*done) + }); + if let Err(e) = result { + error.lock().unwrap().get_or_insert_with(|| format!("{}: {e}", path.display())); + break; + } + }); + } + }); + if let Some(book) = &pipelines.warm_blobs { + book.save(); + eprintln!("previously verified native compute pipelines: {}", pipelines.verified.load(Ordering::Relaxed)); + } + if let Some(e) = error.into_inner().unwrap() { return Err(e); } + progress.check_corpus_complete() + } +} + +fn run_graphics(path: &Path, count: usize, windows: u32, parallel: usize, progress: &LaunchPreparation) -> Result<(), String> { + let me = std::env::current_exe().map_err(|e| e.to_string())?; + let mut command = worker_command(&me); + if std::env::var("XCL_ADAPTER").unwrap_or_default().trim().is_empty() && !progress.adapter.is_empty() { + command.env("XCL_ADAPTER", &progress.adapter); + } + let mut child = command.arg("shaders").arg(path).arg("--graphics-records") + .arg("--windows").arg(windows.to_string()).env("XCL_PIPELINE_THREADS", parallel.to_string()) + .spawn().map_err(|e| e.to_string())?; + let stderr = child.stderr.take().expect("worker_command pipes stderr"); + let (tx, rx) = mpsc::channel(); + let reader = std::thread::spawn(move || { + for line in BufReader::new(stderr).lines() { + if tx.send(line).is_err() { break; } + } + }); + let mut summary = None; + let mut last = String::new(); + let mut made = 0; + let result = loop { + if progress.cancel.load(Ordering::Acquire) { break Err("Pipeline preparation cancelled".to_string()); } + match rx.recv_timeout(Duration::from_millis(100)) { + Ok(Ok(line)) => { + if let Some(n) = progress_count(&line) { + // Independent workers can print their completion counters out of order. + made = made.max(n); + if let Err(e) = progress.complete_corpus(made) { break Err(e); } + } else { + if let Some(verified) = line.strip_prefix("previously verified native graphics recipes: ") + .and_then(|n| n.parse::().ok()) { + eprintln!("Reused {verified} verified native graphics recipes"); + } + if let Some(values) = graphics_summary(&line) { summary = Some(values); } + if !line.trim().is_empty() { last = line; } + } + } + Ok(Err(e)) => break Err(e.to_string()), + Err(mpsc::RecvTimeoutError::Timeout) => continue, + Err(mpsc::RecvTimeoutError::Disconnected) => break Ok(()), + } + }; + if result.is_err() { let _ = child.kill(); } + drop(rx); + let status = child.wait().map_err(|e| e.to_string())?; + reader.join().map_err(|_| "Could not read graphics worker output")?; + result?; + if !status.success() || !matches!(summary, Some([n, 0, _, _]) if n == count) { + return Err(format!("Graphics preparation incomplete ({status}): {last}")); + } + progress.complete_corpus(count) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn discovery_distinguishes_absent_incomplete_and_ready_compute_corpora() { + let root = std::env::temp_dir().join(format!("xcl-corpus-discovery-{}", std::process::id())); + let dir = root.join(".xcl/pso-corpus"); + struct Cleanup(PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } + } + let _cleanup = Cleanup(root.clone()); + assert!(discover(&root).unwrap().is_none()); + std::fs::create_dir_all(dir.join("compute")).unwrap(); + assert!(discover(&root).is_err()); + std::fs::write(dir.join("complete"), "0 1\n").unwrap(); + std::fs::write(dir.join("windows"), "1\n").unwrap(); + assert!(discover(&root).is_err()); + std::fs::write(dir.join("compute/0000000000000010.dxbc"), []).unwrap(); + let corpus = discover(&root).unwrap().unwrap(); + assert_eq!(corpus.compute[0].0, 16); + assert_eq!(corpus.compute_path(16), Some(dir.join("compute/0000000000000010.dxbc").as_path())); + assert!(corpus.compute_path(17).is_none()); + assert!(corpus.graphics_path().is_none()); + assert_eq!(corpus.windows, 1); + std::fs::write(dir.join("windows"), "255").unwrap(); + assert!(discover(&root).is_err()); + std::fs::write(dir.join("windows"), "0").unwrap(); + assert!(discover(&root).is_err()); + } +} diff --git a/crates/xcl/src/shaders/warm_blobs.rs b/crates/xcl/src/shaders/warm_blobs.rs new file mode 100644 index 0000000000..99acc05292 --- /dev/null +++ b/crates/xcl/src/shaders/warm_blobs.rs @@ -0,0 +1,93 @@ +//! Successful temporary-device validations. Live PSO creation on the render device +//! still supplies the driver blob and retries normally if the driver refuses it. +use std::collections::{hash_map::DefaultHasher, HashSet}; +use std::hash::{Hash, Hasher}; +use std::path::{Path, PathBuf}; +use std::sync::{atomic::{AtomicBool, Ordering}, Mutex}; +use windows::Win32::Graphics::Direct3D12::ID3D12Device; + +pub(super) fn digest(value: &impl Hash) -> u64 { + let mut h = DefaultHasher::new(); + value.hash(&mut h); + h.finish() +} + +pub(super) fn stamp(path: &Path, layout: u64, blob: &[u8]) -> [u64; 3] { + [digest(&path.file_name()), layout, digest(&blob)] +} + +pub(super) struct Verified { + path: PathBuf, + keys: Mutex>, + dirty: AtomicBool, +} + +impl Verified { + pub(super) fn for_device(dev: &ID3D12Device) -> Option { + let key = super::warm_replay::native_key(dev)?; + let slice = std::env::var("XCL_PRECOMPILE_SLICE").unwrap_or_default(); + let key = digest(&(key, slice)); + Some(Self::open(crate::gpu::recomp::dxc::cache_dir().join(format!("verified-compute-v1-{key:016x}.bin")))) + } + + fn open(path: PathBuf) -> Self { + let mut keys = HashSet::new(); + if let Ok(bytes) = std::fs::read(&path) { + if let Some((checksum, body)) = bytes.split_at_checked(8) { + if body.len() % 24 == 0 && checksum == digest(&body).to_le_bytes() { + for row in body.chunks_exact(24) { + keys.insert(std::array::from_fn(|i| u64::from_le_bytes(row[i*8..i*8+8].try_into().unwrap()))); + } + } + } + } + Self { path, keys: Mutex::new(keys), dirty: AtomicBool::new(false) } + } + + pub(super) fn contains(&self, stamp: &[u64; 3]) -> bool { + self.keys.lock().unwrap().contains(stamp) + } + + pub(super) fn record(&self, stamp: [u64; 3]) { + if self.keys.lock().unwrap().insert(stamp) { self.dirty.store(true, Ordering::Relaxed); } + } + + pub(super) fn save(&self) { + if !self.dirty.load(Ordering::Relaxed) { return; } + let keys = self.keys.lock().unwrap(); + let mut data = Vec::with_capacity(8 + 24 * keys.len()); + data.extend_from_slice(&[0; 8]); + for row in keys.iter() { + for v in row { data.extend_from_slice(&v.to_le_bytes()); } + } + let sum = digest(&&data[8..]).to_le_bytes(); + data[..8].copy_from_slice(&sum); + if !crate::hle::d3d12x::real::driver_cache::write(&self.path, &data) { + crate::xlog_warn!("Shader preparation: could not save verified compute blob list"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn warm_receipt_matches_only_the_validated_blob_and_layout() { + let path = std::env::temp_dir().join(format!("xcl-warm-receipt-{}.bin", std::process::id())); + let file = Path::new("123.chain.pso"); + let key = stamp(file, 1, &[3, 4]); + let book = Verified::open(path.clone()); + book.record(key); + book.save(); + let book = Verified::open(path.clone()); + assert!(book.contains(&key)); + assert!(!book.contains(&stamp(file, 2, &[3, 4]))); + assert!(!book.contains(&stamp(file, 1, &[3, 5]))); + assert!(!book.contains(&stamp(Path::new("123.pso"), 1, &[3, 4]))); + let mut contents = std::fs::read(&path).unwrap(); + contents[8] ^= 1; + std::fs::write(&path, contents).unwrap(); + assert!(!Verified::open(path.clone()).contains(&key)); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/xcl/src/shaders/warm_pack.rs b/crates/xcl/src/shaders/warm_pack.rs new file mode 100644 index 0000000000..ad9cddc216 --- /dev/null +++ b/crates/xcl/src/shaders/warm_pack.rs @@ -0,0 +1,101 @@ +//! Skip re-emitting graphics stages when their successful pack pass still has all its DXIL. +use super::{warm_blobs::digest, warm_replay::{read_receipt, write_receipt}}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; +use std::os::windows::fs::MetadataExt; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +type Stamp = [u64; 3]; + +#[derive(Default, Serialize, Deserialize)] +struct Receipt { + indices: BTreeSet, + outputs: BTreeMap, +} + +fn inventory(cache: &Path) -> Option> { + let mut outputs = BTreeMap::new(); + for entry in std::fs::read_dir(cache).ok()? { + let entry = entry.ok()?; + let path = entry.path(); + if path.extension().is_none_or(|ext| ext != "dxil") { continue; } + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { continue }; + if stem.len() != 16 { continue; } + let Ok(key) = u64::from_str_radix(stem, 16) else { continue }; + let m = entry.metadata().ok()?; + if m.is_file() && m.file_attributes() & 0x400 == 0 { + outputs.insert(key, [m.len(), m.creation_time(), m.last_write_time()]); + } + } + Some(outputs) +} + +impl Receipt { + fn valid(&self, count: usize, files: &BTreeMap) -> bool { + !self.indices.is_empty() && !self.outputs.is_empty() && self.indices.last().is_some_and(|i| *i < count) + && self.outputs.iter().all(|(key, stamp)| files.get(key) == Some(stamp)) + } +} + +pub(super) struct Stages { + cache: PathBuf, + path: PathBuf, + prior: Option, + fresh: Mutex)>>, +} + +impl Stages { + pub(super) fn open(native: u64, data: &[u8], count: usize, windows: u32, split: bool, graphics_split: bool) -> Option { + let cache = crate::gpu::recomp::dxc::cache_dir(); + let key = digest(&(native, digest(&data), count, windows, split, graphics_split)); + let path = cache.join(format!("pack-stages-v1-{key:016x}.bin")); + let prior = read_receipt::(&path).filter(|r| inventory(&cache).is_some_and(|files| r.valid(count, &files))); + if let Some(r) = &prior { + crate::xlog_info!("Shader preparation: reusing verified DXIL for {} graphics records in the pack", r.indices.len()); + } + Some(Self { cache, path, prior, fresh: Mutex::default() }) + } + + pub(super) fn covered(&self, i: usize) -> bool { + self.prior.as_ref().is_some_and(|r| r.indices.contains(&i)) + } + + pub(super) fn record(&self, index: usize, outputs: Vec<(u64, u64)>) { + if !outputs.is_empty() { self.fresh.lock().unwrap().push((index, outputs)); } + } + + pub(super) fn save(self) { + let newly = self.fresh.into_inner().unwrap(); + if newly.is_empty() { return; } + let Some(files) = inventory(&self.cache) else { return }; + let mut receipt = self.prior.unwrap_or_default(); + if receipt.outputs.iter().any(|(k, s)| files.get(k) != Some(s)) { return; } + for (index, stages) in newly { + for (key, len) in stages { + let Some(stamp) = files.get(&key).filter(|s| len != 0 && s[0] == len) else { return }; + receipt.outputs.insert(key, *stamp); + } + receipt.indices.insert(index); + } + write_receipt(&self.path, &receipt); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn graphics_pack_proof_requires_every_output_and_valid_indices() { + let receipt = Receipt { indices: BTreeSet::from([0, 3]), outputs: BTreeMap::from([(1, [30, 4, 5]), (9, [60, 7, 8])]) }; + let mut files = receipt.outputs.clone(); + files.insert(11, [40, 2, 3]); + assert!(receipt.valid(4, &files)); + assert!(!receipt.valid(3, &files)); + files.get_mut(&9).unwrap()[2] += 1; + assert!(!receipt.valid(4, &files)); + files.remove(&9); + assert!(!receipt.valid(4, &files)); + } +} diff --git a/crates/xcl/src/shaders/warm_replay.rs b/crates/xcl/src/shaders/warm_replay.rs new file mode 100644 index 0000000000..ccda319b9b --- /dev/null +++ b/crates/xcl/src/shaders/warm_replay.rs @@ -0,0 +1,144 @@ +//! A recipe can be left on disk only after a successful replay identified every +//! native blob it used. The render device still creates the live PSO on first use. +use serde::{Deserialize, Serialize}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::os::windows::fs::MetadataExt; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +/// Interrupted writes or a damaged index fall back to ordinary preparation. +pub(crate) fn read_receipt(path: &Path) -> Option { + let bytes = std::fs::read(path).ok()?; + let (checksum, payload) = bytes.split_at_checked(8)?; + if checksum != crate::gpu::shader::fnv64(payload).to_le_bytes() { return None; } + serde_json::from_slice(payload).ok() +} + +pub(crate) fn write_receipt(path: &Path, receipt: &T) -> bool { + let mut bytes = vec![0; 8]; + if serde_json::to_writer(&mut bytes, receipt).is_err() { return false; } + let checksum = crate::gpu::shader::fnv64(&bytes[8..]).to_le_bytes(); + bytes[..8].copy_from_slice(&checksum); + crate::hle::d3d12x::real::driver_cache::write(path, &bytes) +} + +pub(crate) type Stamp = [u64; 3]; +pub(crate) type Inventory = HashMap; + +fn stamp(m: &std::fs::Metadata) -> Option { + (m.is_file() && m.len() != 0 && m.file_attributes() & 0x400 == 0).then(|| [m.len(), m.creation_time(), m.last_write_time()]) +} + +pub(crate) fn driver_files(dir: &Path) -> Option { + let mut files = Inventory::new(); + for e in std::fs::read_dir(dir).ok()? { + let e = e.ok()?; + let m = e.metadata().ok()?; + if m.file_attributes() & 0x400 != 0 { continue; } + let Some(stamp) = stamp(&m) else { continue }; + if let Ok(name) = e.file_name().into_string() { + if name.ends_with(".pso") { files.insert(name, stamp); } + } + } + Some(files) +} +#[derive(Clone, Serialize, Deserialize)] +pub(super) struct File { name: String, stamp: Stamp } +type Recipes = HashMap>; + +thread_local! { static CAPTURE: RefCell>> = const { RefCell::new(None) }; } + +pub(super) fn capture(f: impl FnOnce() -> bool) -> (bool, Vec) { + CAPTURE.with(|slot| { *slot.borrow_mut() = Some(Vec::new()); }); + let success = f(); + let files = CAPTURE.with(|slot| slot.take().unwrap_or_default()); + (success, files) +} + +/// Record only bytes accepted by the native driver that still occupy this cache file. +pub(crate) fn accepted(path: Option<&Path>, bytes: &[u8]) { + CAPTURE.with(|slot| { + let mut slot = slot.borrow_mut(); + let Some(files) = slot.as_mut() else { return }; + let verified = || { + let path = path?; + let before = stamp(&path.metadata().ok()?)?; + if before[0] != bytes.len() as u64 || std::fs::read(path).ok()?.as_slice() != bytes { return None; } + if stamp(&path.metadata().ok()?)? != before { return None; } + Some(File { name: path.file_name()?.to_str()?.to_owned(), stamp: before }) + }; + if let Some(file) = verified() { files.push(file); } + }); +} + +pub(super) struct Index { + path: PathBuf, + entries: Recipes, + new: Mutex, +} + +impl Index { + pub(super) fn open(dir: &Path, known: &Inventory, key: u64, windows: u32) -> Option { + let path = dir.join(format!("warm-recipes-v2-{key:016x}-{windows:02x}.bin")); + let mut entries: Recipes = read_receipt(&path).unwrap_or_default(); + entries.retain(|_, files| !files.is_empty() && files.iter().all(|f| known.get(&f.name) == Some(&f.stamp))); + Some(Self { path, entries, new: Default::default() }) + } + pub(super) fn can_defer(&self, hash: u64) -> bool { self.entries.contains_key(&hash) } + pub(super) fn add(&self, hash: u64, files: Vec, mesh: bool) { + let complete = if mesh { + files.len() == 2 && files.iter().any(|f| f.name.starts_with("tp-ms-")) + && files.iter().any(|f| f.name.starts_with("tp-cs-")) + } else { + files.len() == 1 && files[0].name.starts_with("gfx-") + }; + if complete { self.new.lock().unwrap().insert(hash, files); } + } + pub(super) fn save(mut self) { + let new = self.new.into_inner().unwrap(); + if new.is_empty() { return; } + self.entries.extend(new); + if !write_receipt(&self.path, &self.entries) { + crate::xlog_warn!("PSO preparation: could not save the verified recipe index"); + } + } +} + +pub(super) fn native_key(dev: &windows::Win32::Graphics::Direct3D12::ID3D12Device) -> Option { + let gpu = crate::hle::d3d12x::real::preparation_driver_identity(dev)?; + let translation = crate::gpu::recomp::pso::translation_cache_identity(); + if translation == 0 || !crate::hle::d3d12x::real::driver_cache::enabled() { return None; } + let cache = std::path::absolute(crate::gpu::recomp::dxc::cache_dir()).ok()?; + Some(super::warm_blobs::digest(&(env!("XCL_NATIVE_PREPARATION_ID"), gpu, translation, cache, super::warm_settings_key()))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verified_mesh_needs_both_unchanged_driver_files() { + let dir = std::env::temp_dir().join(format!("xcl-warm-mesh-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let graphics = dir.join("tp-ms-test.pso"); + let compute = dir.join("tp-cs-test.pso"); + std::fs::write(&graphics, b"graphics").unwrap(); + std::fs::write(&compute, b"compute").unwrap(); + let open = || Index::open(&dir, &driver_files(&dir).unwrap(), 1, 4).unwrap(); + let capture_passes = |compute_bytes: &[u8]| capture(|| { + accepted(Some(&graphics), b"graphics"); + accepted(Some(&compute), compute_bytes); + true + }).1; + let book = open(); + book.add(1, capture_passes(b"wrong"), true); + book.add(2, capture_passes(b"compute"), true); + book.save(); + assert!(!open().can_defer(1)); + assert!(open().can_defer(2)); + std::fs::remove_file(&compute).unwrap(); + assert!(!open().can_defer(2)); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index 8e7109f622..b0a00f5c96 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -48,6 +48,37 @@ fn copy_dir(src: &Path, dst: &Path) { } } +#[test] +fn incomplete_discovered_corpus_blocks_headless_title_entry() { + let xcl = Path::new(env!("CARGO_BIN_EXE_xcl")); + let root = temp_dir("incomplete-corpus"); + let game = root.join("game"); + let data = root.join("data"); + copy_dir(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data/testgame"), &game); + std::fs::copy(xcl.parent().unwrap().join("xcl_testtitle.exe"), game.join("xcl_testtitle.exe")).unwrap(); + std::fs::create_dir_all(game.join(".xcl/pso-corpus")).unwrap(); + let settings = data.join("XCL.TestTitle"); + std::fs::create_dir_all(&settings).unwrap(); + std::fs::write(settings.join("xcl.toml"), "graphics='null'\npresent='off'\n").unwrap(); + let launch = |prepare| Command::new(xcl).arg("run").arg(&game).env("XCL_DATA_ROOT", &data) + .env("XCL_PREPARE", prepare).output().unwrap(); + let out = launch("0"); + assert!(!out.status.success(), "An incomplete corpus released the guest"); + let log = std::fs::read_to_string(settings.join("logs/xcl.log")).unwrap(); + assert!(log.contains("Incomplete pipeline corpus"), "{log}"); + assert!(!log.contains("game entry point returned"), "{log}"); + std::fs::remove_dir(game.join(".xcl/pso-corpus")).unwrap(); + std::fs::create_dir_all(settings.join("cache")).unwrap(); + std::fs::write(settings.join("cache/used-graphics-pipelines.bin"), b"bad history").unwrap(); + let _ = launch("0"); + let log = std::fs::read_to_string(settings.join("logs/xcl.log")).unwrap(); + assert!(!log.contains("unrecognized graphics job header"), "Disabled optional preparation read local history"); + assert!(!launch("1").status.success()); + let log = std::fs::read_to_string(settings.join("logs/xcl.log")).unwrap(); + assert!(log.contains("unrecognized graphics job header"), "{log}"); + assert!(!log.contains("game entry point returned"), "{log}"); +} + struct TempDir(PathBuf); impl std::ops::Deref for TempDir { diff --git a/scripts/pso_corpus/archive-profile.md b/scripts/pso_corpus/archive-profile.md new file mode 100644 index 0000000000..921bc483f0 --- /dev/null +++ b/scripts/pso_corpus/archive-profile.md @@ -0,0 +1,21 @@ +# Preparing a pipeline journal from an archive + +Run `python pso_archive.py profile.json archive.bin pipelines.bin` with Python 3.10 or newer. Use `--records tables.bin` when a locally extracted archive member contains the tables and the shader data remains in the original archive. The command reports the number of distinct sources and recipes. It replaces the destination after every record resolves and the journal has been written. + +A profile describes the local archive layout and how its selectors map to XCL wire records. The profile author must establish these mappings for the archive revision. Include optional `archive_sha256` to check the source archive. When the tables occupy compressed blocks, list their archive ranges in order under optional `record_chunks`, using the same range format as `sources`. Table offsets then address the concatenated decoded blocks. An absent selector raises an error. Use an explicitly empty variant list for an intentionally excluded record type. + +| Version 1 field | Meaning | +|---|---| +| `sources` | Named shader byte ranges with `offset` and `size`. For `encoding` equal to `deflate` (raw) or `zlib`, supply the exact compressed stream length and `raw_size`. | +| `stage_maps` | Named dictionaries mapping a decimal selector string to a named source, or `null` for an absent optional shader stage. | +| `states` | Named dictionaries mapping decimal selector strings to hex-encoded state fragments in XCL wire order. | +| `tables` | A list of fixed-stride tables with `offset`, `count`, `stride`, and named `fields` given as `[byte_offset, width]` within a record. Integers use 1, 2, 4 or 8 little-endian bytes. | +| `variants` | A table's list of wire templates. Optionally use `variant_field` to select between lists keyed by decimal field value. Each variant supplies `kind` (C, G or M), the XCL journal `windows` byte, and an ordered `parts` list. | + +A part is one of `{"hex":"..."}` for a literal, `{"field":["field name","state dictionary"]}` for a selected fragment, or `{"stage":["field name","stage dictionary"]}` for a shader identity computed from the selected local source. Templates must follow XCL's journal wire format, including any required zeroed fields and attachment layouts. The synthetic compute profile in `test_pso_archive.py` shows these parts in descriptor order. + +The generated XCLPJ001 journal carries each required shader source once, followed by unique recipes. The tool enumerates the record tables and variants in the supplied profile. Coverage of gameplay paths depends on what that profile models. + +If the archive contains its own dictionaries, define optional `shader_directories` and `state_directories` instead of listing entries by hand. Both take named directories with `offset`, `count`, `stride`, and an optional integer `id` field (defaults to the row ordinal). Offsets refer to the record file or decoded record chunks. A shader directory requires integer fields `location` and `size`, with optional `data_base`, `encoding` and integer `raw_size` field. Shader locations resolve against the original archive. A state directory requires `fragment: [offset, byte_length]` within the row. The named directory becomes a stage or state dictionary for the existing template operations. Conflicting entries raise an error. + +Run `python -m unittest -v test_pso_archive test_pso_directory` in the script directory. diff --git a/scripts/pso_corpus/pso_archive.py b/scripts/pso_corpus/pso_archive.py new file mode 100644 index 0000000000..23c4b0a785 --- /dev/null +++ b/scripts/pso_corpus/pso_archive.py @@ -0,0 +1,181 @@ +"""Expand archive selector tables into a self-contained XCL pipeline journal.""" + +import argparse +from contextlib import contextmanager +import hashlib +import json +import os +from pathlib import Path +import shutil +import struct +import tempfile +import zlib + +from pso_directory import read_directories + +FRAME = struct.Struct(" len(record): + raise ValueError(f"invalid little-endian selector field {spec}") + return str(int.from_bytes(record[offset:offset + size], "little")) + + +def expand(profile, archive, records, shader_frames, recipe_frames): + if profile["version"] != 1: + raise ValueError("unknown profile version") + read_directories(profile, records) + sources = {} + for table in profile["tables"]: + stride = table["stride"] + if not 0 < stride <= LIMIT or table["count"] < 0 or table["offset"] < 0: + raise ValueError("invalid record table") + for index in range(table["count"]): + record = read_at(records, table["offset"] + stride * index, stride) + ids = {name: field(record, spec) for name, spec in table["fields"].items()} + variants = table["variants"] + if "variant_field" in table: + variants = variants[ids[table["variant_field"]]] + for variant in variants: + pieces = [] + stage_ids = [] + for part in variant["parts"]: + if len(part) != 1: + raise ValueError("wire fragment requires exactly one operation") + op, arg = next(iter(part.items())) + if op == "hex": + value = bytes.fromhex(arg) + elif op == "field": + name, state_map = arg + value = bytes.fromhex(profile["states"][state_map][ids[name]]) + elif op == "stage": + name, stage_map = arg + source = profile["stage_maps"][stage_map][ids[name]] + if source is None: + value = bytes(8) + else: + entry = profile["sources"][source] + region = (entry["offset"], entry["size"], entry.get("encoding", "raw"), entry.get("raw_size")) + if region not in sources: + blob = source_bytes(archive, entry) + key = f"{fnv64(blob):016x}" + shader_frames.add(key, "S", 0, blob) + sources[region] = key + key = sources[region] + value = struct.pack(" len(record): + raise ValueError("invalid directory integer field") + return int.from_bytes(record[offset:offset + width], "little") + + +def directory_entries(stream, directory): + offset, count, stride = (directory[k] for k in ("offset", "count", "stride")) + if offset < 0 or count < 0 or not 0 < stride <= 64 << 20: + raise ValueError("invalid directory range") + stream.seek(offset) + for row in range(count): + record = stream.read(stride) + if len(record) != stride: + raise ValueError(f"truncated directory at row {row}") + key = integer(record, directory["id"]) if "id" in directory else row + yield str(key), record + + +def add_entry(mapping, key, value): + if key in mapping and mapping[key] != value: + raise ValueError(f"ambiguous directory entry {key}") + mapping[key] = value + + +def read_directories(profile, records): + """Populate the maps for the ordinary profile expander from the record file.""" + for name, directory in profile.get("shader_directories", {}).items(): + stages = profile.setdefault("stage_maps", {}).setdefault(name, {}) + sources = profile.setdefault("sources", {}) + for key, record in directory_entries(records, directory): + offset = directory.get("data_base", 0) + integer(record, directory["location"]) + size = integer(record, directory["size"]) + source = f"{name}:{key}" + entry = {"offset": offset, "size": size, "encoding": directory.get("encoding", "raw")} + if "raw_size" in directory: + entry["raw_size"] = integer(record, directory["raw_size"]) + add_entry(sources, source, entry) + add_entry(stages, key, source) + for name, directory in profile.get("state_directories", {}).items(): + states = profile.setdefault("states", {}).setdefault(name, {}) + start, size = directory["fragment"] + if start < 0 or size <= 0 or start + size > directory["stride"]: + raise ValueError("invalid directory state fragment") + for key, record in directory_entries(records, directory): + add_entry(states, key, record[start:start + size].hex()) diff --git a/scripts/pso_corpus/stage.py b/scripts/pso_corpus/stage.py new file mode 100644 index 0000000000..6e2723f486 --- /dev/null +++ b/scripts/pso_corpus/stage.py @@ -0,0 +1,268 @@ +"""Stage local XCLPJ001 journals for offline pipeline preparation. + +python scripts/pso_corpus/stage.py --title FOLDER JOURNAL [JOURNAL ...] +Use the same window configuration for all journals. The resulting .xcl/pso-corpus +contains local shader bytes. An existing different corpus is preserved. Compute +node masks 0 and 1 select the first node on the supported single-node adapter. +""" +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +import shutil +import struct +import tempfile + +OFFSET, PRIME, MASK = 0xcbf29ce484222325, 0x100000001b3, (1 << 64) - 1 +HEADER = struct.Struct("= 128: + result.append(128 | (value & 127)) + value >>= 7 + result.append(value) + return result + + +class Reader: + def __init__(self, data): + self.data = memoryview(data) + self.pos = 0 + + def take(self, size): + end = self.pos + size + require(end <= len(self.data), "short descriptor") + part = self.data[self.pos:end] + self.pos = end + return part + + def ints(self, fmt): + return struct.unpack(fmt, self.take(struct.calcsize(fmt))) + + def u32(self): + return self.ints("