diff --git a/README.md b/README.md index 973a027e86..14f4c8eae7 100644 --- a/README.md +++ b/README.md @@ -240,19 +240,30 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper.
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 are created during play the first - time; the ones a run used are recorded with their state (`used-graphics-pipelines.bin` beside - the shader cache, at most `XCL_GFX_RECORDS_MB`, default 64) and built before the title starts - on the next launch, with their driver blobs kept, so the title makes them from those in - milliseconds. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. 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 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 ab9486a98e..4820770a8d 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -948,7 +948,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 fdc25f40ef..82f2f036b9 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -201,6 +201,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}; @@ -268,7 +270,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/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index cb4b872354..8221bf7ad3 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -4,16 +4,19 @@ //! 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` beside the DXIL cache: +//! `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) -//! key = `real::shaders_key` of the set (as `used-pipelines.txt` has it); in a shader entry +//! | 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 the VS, PS, DS, HS, GS (0: none) +//! 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) @@ -34,14 +37,22 @@ use std::path::{Path, PathBuf}; use windows::Win32::Graphics::Direct3D12::*; const MAGIC: &[u8; 8] = b"XCLGFXP\0"; -/// The layout of an entry: a change makes every file of the older one read as none. +/// 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 -/// The records of this cache (beside the DXIL cache, as `used-pipelines.txt`). +/// 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") } @@ -84,6 +95,12 @@ impl Reader<'_> { 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; @@ -100,25 +117,25 @@ impl Reader<'_> { /// 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)) { +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); + f(&mut v, u32::MAX); $x = v as i32; }}; } macro_rules! byte { ($x:expr) => {{ let mut v = $x as u32; - f(&mut v); + f(&mut v, u8::MAX.into()); $x = v as u8; }}; } macro_rules! float { ($x:expr) => {{ let mut v = $x.to_bits(); - f(&mut v); + f(&mut v, u32::MAX); $x = f32::from_bits(v); }}; } @@ -137,7 +154,7 @@ fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32) int!(rt.LogicOp.0); byte!(rt.RenderTargetWriteMask); } - f(&mut d.SampleMask); + f(&mut d.SampleMask, u32::MAX); let r = &mut d.RasterizerState; int!(r.FillMode.0); int!(r.CullMode.0); @@ -148,7 +165,7 @@ fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32) int!(r.DepthClipEnable.0); int!(r.MultisampleEnable.0); int!(r.AntialiasedLineEnable.0); - f(&mut r.ForcedSampleCount); + f(&mut r.ForcedSampleCount, u32::MAX); int!(r.ConservativeRaster.0); let z = &mut d.DepthStencilState; int!(z.DepthEnable.0); @@ -165,14 +182,14 @@ fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32) } int!(d.IBStripCutValue.0); int!(d.PrimitiveTopologyType.0); - f(&mut d.NumRenderTargets); + f(&mut d.NumRenderTargets, 8); for format in &mut d.RTVFormats { int!(format.0); } int!(d.DSVFormat.0); - f(&mut d.SampleDesc.Count); - f(&mut d.SampleDesc.Quality); - f(&mut d.NodeMask); + f(&mut d.SampleDesc.Count, u32::MAX); + f(&mut d.SampleDesc.Quality, u32::MAX); + f(&mut d.NodeMask, u32::MAX); int!(d.Flags.0); } @@ -187,7 +204,7 @@ pub(crate) unsafe fn encode(key: u64, shaders: [u64; 5], d: &D3D12_GRAPHICS_PIPE } // (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)); + 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); @@ -202,6 +219,83 @@ pub(crate) unsafe fn encode(key: u64, shaders: [u64; 5], d: &D3D12_GRAPHICS_PIPE 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()); @@ -214,6 +308,7 @@ pub(crate) fn shader_entry(key: u64, bytes: &[u8]) -> Vec { /// 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, @@ -241,11 +336,58 @@ impl Record { } } +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()?; @@ -254,7 +396,10 @@ pub(crate) fn decode(payload: &[u8]) -> Option { if tag == SHADER { return Some(Entry::Shader(key, r.0.to_vec())); } - if tag != PIPELINE { + 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]; @@ -263,7 +408,7 @@ pub(crate) fn decode(payload: &[u8]) -> Option { } let mut desc: Box = Box::new(unsafe { std::mem::zeroed() }); let mut short = false; - state(&mut desc, &mut |v| match r.u32var() { + state(&mut desc, &mut |v, _| match r.u32var() { Some(x) => *v = x, None => short = true, }); @@ -298,7 +443,7 @@ pub(crate) fn decode(payload: &[u8]) -> Option { InstanceDataStepRate: f[5], }) .collect(); - Some(Entry::Pipeline(Record { key, shaders, desc, inputs, _names: names })) + Some(Entry::Pipeline(Record { key, shaders, depth_bounds: tag == DEPTH_BOUNDS_PIPELINE, desc, inputs, _names: names })) } fn header() -> [u8; HEADER] { @@ -337,6 +482,77 @@ pub(crate) fn read(path: &Path) -> Vec> { 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 { @@ -423,7 +639,7 @@ pub(crate) fn note(payload: Vec) { 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()); + crate::xlog_warn!("D3D12.X: {}: {e} – the graphics pipelines of this run are not prepared before the next", path.display()); return; } }; @@ -438,7 +654,7 @@ pub(crate) fn note(payload: Vec) { } Ok(_) => {} Err(e) => { - crate::xlog_warn!("D3D12.X: {}: {e} – no more graphics pipelines are recorded in this run", path.display()); + crate::xlog_warn!("D3D12.X: {}: {e} – no more graphics pipelines are recorded in this run", path.display()); return; } } @@ -538,6 +754,20 @@ mod tests { } } + #[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] @@ -578,7 +808,147 @@ mod tests { 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(&[3, 0, 0, 0, 0, 0, 0, 0, 0]).is_none(), "another kind of entry"); + 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 diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index 5d468c52d6..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,26 +42,22 @@ 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()) { + 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(()); } - // `XCL_PREPARE=0`: the title starts at once and builds what it uses as it goes (it stands - // still for those builds): for a look at a change without the wait - if std::env::var("XCL_PREPARE").is_ok_and(|v| v.trim() == "0") { - crate::xlog_info!("Shader preparation left out (XCL_PREPARE=0): the title builds what it uses as it goes"); - return Ok(()); - } - let only = Some(crate::hle::d3d12x::pso_async::earlier_used_shaders()) - .filter(|used| !used.is_empty() && !std::env::var("XCL_PREPARE_ALL").is_ok_and(|v| v.trim() == "1")); - if let Some(used) = &only { - crate::xlog_info!("Shader preparation: only the {} shaders earlier runs used (XCL_PREPARE_ALL=1: every record)", used.len()); - } - let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), only, ..Default::default() }); + 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 }; @@ -73,12 +70,13 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { 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 graphics { "graphics pipelines" } else { "records" }, - if graphics { format!("built by {workers} workers") } else if workers != 0 { format!("checked for pipelines by {workers} workers") } else { "translated".to_string() }, + 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() ); } @@ -155,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); @@ -169,28 +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 workers = s.progress.workers.load(Ordering::Relaxed); let graphics = workers != 0 && s.progress.graphics.load(Ordering::Relaxed); - let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else if graphics { "Building graphics pipelines" } else if workers != 0 { "Building pipelines" } else { "Preparing shaders" }; + 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 if graphics { format!("{done} of {total} graphics pipelines built by {workers} worker processes") } + 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 = if workers != 0 { format!("Large pipelines compile in the driver: {quiet} s since the last record") } else { 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); @@ -251,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/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4fc883bf4e..7d81274c71 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5804,6 +5804,23 @@ pub(super) 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 { @@ -6225,9 +6242,13 @@ unsafe fn graphics_pso_through_cache( |label, has_cached, f| driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some((record, has_cached)), f), create, ); + if build.reused { + if let Some(blob) = cached.as_ref() { crate::shaders::warm_replay::accepted(disk, blob); } + } if build.cache_eligible { if let (Some(b), Some(p)) = (blob_of(), disk) { driver_cache::keep_at(p, &b, build.in_driver, keep_min); + crate::shaders::warm_replay::accepted(Some(p), &b); } } else if build.reused && from_disk { driver_cache::note(true, None); @@ -6236,10 +6257,10 @@ unsafe fn graphics_pso_through_cache( } 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; @@ -6317,7 +6338,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); // (no file without the adapter's identity: it could be another adapter's) let driver = driver_identity(this); let disk = driver.and_then(|id| driver_cache::graphics_path(driver_cache::graphics_file_hash(gkey, id, crate::gpu::recomp::pso::mem_windows()), bytes)); @@ -6332,7 +6353,12 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const &mut copy, rect_gs.is_some(), ps_hash, - |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) }, || keep_graphics_blob(gkey, *ppv, bytes), ); GRAPHICS_STAGES.with(|s| s.set(None)); @@ -6453,6 +6479,10 @@ pub(crate) fn shader_key_of_hash(hash: u64) -> u64 { } 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); @@ -6498,8 +6528,11 @@ impl OwnedDesc { } /// A graphics pipeline's entry for the next run's preparation (`gfx_records`), of the set - /// `key` whose shaders' keys are `parts`; None for any other. + /// `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(); @@ -6816,11 +6849,12 @@ pub(crate) fn prepare_device(device: ID3D12Device) -> usize { /// (`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) -> bool { +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 made = matches!(translated_graphics_pso(this, f, desc as *const _ as *const c_void, &pc_iid(Kind::PipelineState), &mut out), Some(hr) if hr >= 0) && !out.is_null(); + 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 } @@ -7066,6 +7100,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(); @@ -7107,6 +7175,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(); @@ -7208,6 +7406,8 @@ fn driver_identity(device: *mut c_void) -> Option { }) } +pub(crate) fn preparation_driver_identity(dev: &ID3D12Device) -> Option { driver_identity(dev.as_raw()) } + struct TwoPassBlob { key: (u64, usize, i32), disk: Option, @@ -7251,6 +7451,7 @@ unsafe fn build_two_pass_pso( let cached = mem.or_else(|| disk.and_then(driver_cache::load).map(std::sync::Arc::new)); if let Some(blob) = cached { if let Ok((hr, pso, _)) = attempt(Some(&blob)) { + crate::shaders::warm_replay::accepted(disk, &blob); if from_disk { driver_cache::note(true, None); store_compute_blob(cache.key, blob); @@ -7279,6 +7480,7 @@ unsafe fn build_two_pass_pso( if let Some(blob) = (disk.is_some() || keep_ram).then(|| read_pso_cached_blob(pso.as_raw())).flatten() { if let Some(path) = disk { driver_cache::keep_at(path, &blob, took, min); + crate::shaders::warm_replay::accepted(Some(path), &blob); } if keep_ram { store_compute_blob(cache.key, std::sync::Arc::new(blob)); @@ -7478,6 +7680,29 @@ mod mesh_slot_tests { s } + #[test] + fn recorded_mesh_preserves_bounds_and_only_accepts_empty_extra_stages() { + let ms = sample(13, &[fssm(&CODE, &[(8, 13)])]); + let mut stream = sub(25, &bytecode(&ms)); + for kind in [1, 2, 3, 4, 5, 12] { stream.extend(sub(kind, &[0; 16])); } + let mut depth = [0u8; 56]; + depth[52..].copy_from_slice(&1u32.to_le_bytes()); + stream.extend(sub(21, &depth)); + let encoded = unsafe { super::record_mesh_stream(&stream) }.unwrap(); + let Some(super::super::gfx_records::Entry::MeshPipeline(record)) = super::super::gfx_records::decode(&encoded) else { + panic!("expected a mesh pipeline") + }; + assert_eq!(record.layout, [25, 1, 2, 3, 4, 5, 12, 21]); + assert!(record.depth_bounds); + let mut active = sub(25, &bytecode(&ms)); + active.extend(sub(3, &bytecode(&ms))); + assert!(unsafe { super::record_mesh_stream(&active) }.is_none()); + let mut layout = sub(25, &bytecode(&ms)); + let mut input = [0u8; 16]; input[8] = 1; + layout.extend(sub(12, &input)); + assert!(unsafe { super::record_mesh_stream(&layout) }.is_none()); + } + /// The stand-in for a console MS alone in the AS slot is a mesh pipeline: the subobject is /// retyped to MS with the dummy MS (as `translated_mesh_stream` reads the title's stream), /// the PS is the dummy PS. Left an empty AS and a PS, the stream had neither an MS nor a VS 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 6ca0572281..37e6a41c53 100644 --- a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs +++ b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs @@ -206,6 +206,11 @@ pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gp } } 1..=6 | 24 | 25 => { + if matches!(ty, 1..=5) && payload.iter().all(|&byte| byte == 0) { + h.u32(ty); + h.u64(0); + continue; + } let code = payload_shader(payload)?; shader_bytes = shader_bytes.checked_add(code.len())?; h.u32(ty); @@ -256,6 +261,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/main.rs b/crates/xcl/src/main.rs index 20223c18c7..5ab1aa123c 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 67fb3e0dcb..9917c105ea 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). @@ -813,6 +853,7 @@ struct ShadersOptions { measure_pso: Option, repeat: usize, precompile: bool, + prepare_corpus: bool, limit: usize, only: Option, pipelines: bool, @@ -850,6 +891,7 @@ fn parse_args(args: &[String]) -> Result { measure_pso: None, repeat: 1, precompile: false, + prepare_corpus: false, limit: usize::MAX, only: None, pipelines: false, @@ -889,6 +931,7 @@ 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, @@ -920,6 +963,21 @@ pub fn run(path: &Path, args: &[String]) -> i32 { return 2; } }; + if opts.prepare_corpus { + if opts.windows.is_some() || 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: as many as a run has (`XCL_UMA_WINDOWS`), from the // descriptor heap with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`), as `--precompile` let runtime_windows = { @@ -933,7 +991,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 { move || if heap { windows | recomp::HEAP_WINDOWS } else { windows } }; if opts.graphics_records { - return graphics_worker(path, runtime_windows()); + return graphics_worker(path, runtime_windows(), opts.threads); } let top = opts.top; let json = opts.json; @@ -996,7 +1054,11 @@ pub fn run(path: &Path, args: &[String]) -> i32 { let used = opts.used_only.then(crate::hle::d3d12x::pso_async::earlier_used_keys); // 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, used.as_ref(), 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, used.as_ref(), t0, None, coverage.as_ref()) { Ok(()) => 0, Err(e) => { eprintln!("xcl shaders: {e}"); 2 } }; @@ -1223,6 +1285,8 @@ 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, @@ -1451,6 +1515,8 @@ 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), @@ -1504,9 +1570,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) { @@ -1522,9 +1612,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}")); } } } @@ -1544,6 +1634,14 @@ impl Pipelines { driver_cache::path_for(dxil, desc.Flags.0, chained) }); 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 @@ -1552,7 +1650,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(); @@ -1571,12 +1669,14 @@ impl Pipelines { 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; + return Err("Another process is preparing this compute pipeline".into()); } }, _ => None, @@ -1600,20 +1700,26 @@ 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)); } + } } } } @@ -1623,13 +1729,14 @@ impl Pipelines { *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())) } } @@ -1650,10 +1757,35 @@ pub(crate) struct LaunchPreparation { pub workers: AtomicUsize, /// The workers build graphics pipelines (`graphics_in_workers`): `done` and `total` count those. pub graphics: std::sync::atomic::AtomicBool, - /// The shaders earlier runs used (`pso_async::earlier_used_shaders`), when there are any: - /// only their records are translated before the title starts, and it translates another - /// when it first uses it. `XCL_PREPARE_ALL=1`: every record, as without the list. - pub only: Option>, + /// 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 @@ -1675,6 +1807,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())? { @@ -1695,25 +1837,96 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS; } 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()); } // 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, std::time::Instant::now(), Some(progress))?; + precompile(input, usize::MAX, windows, None, None, false, None, std::time::Instant::now(), Some(progress), coverage.as_ref())?; if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - pipelines_in_workers(&pack, windows, workers, n, progress)?; + 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, std::time::Instant::now(), Some(progress))?; + precompile(input, usize::MAX, windows, None, None, true, None, std::time::Instant::now(), Some(progress), coverage.as_ref())?; } if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - // `XCL_PREPARE_GRAPHICS=0`: the title builds the graphics pipelines it uses as it goes - if std::env::var("XCL_PREPARE_GRAPHICS").is_ok_and(|v| v.trim() == "0") { - crate::xlog_info!("Shader preparation: graphics pipelines left out (XCL_PREPARE_GRAPHICS=0)"); - return Ok(()); + 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)) } - graphics_in_workers(&inputs, windows, workers, progress) } /// `XCL_PREPARE_WORKERS`: the processes that build a pack's compute pipelines before a title @@ -1799,23 +2012,23 @@ mod claim_tests { } /// The compute pipelines of `pack` built by `workers` processes of this program, each on its own -/// slice of the records (`XCL_PRECOMPILE_SLICE`): only the ones an earlier run of the title used -/// when that list exists (the title builds another when it first uses it). Their records count -/// into `progress`. A worker that fails is noted and the title starts all the same: it builds -/// what is missing itself. -fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation) -> Result<(), String> { +/// 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 used_only = !crate::hle::d3d12x::pso_async::earlier_used_keys().is_empty(); + 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{}", if used_only { ", those an earlier run used" } else { "" }); + 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 used_only { c.arg("--used-only"); } + 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(()) } @@ -1826,7 +2039,7 @@ 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"] { c.env_remove(gone); } + 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"); } @@ -1883,7 +2096,7 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut std::thread::sleep(std::time::Duration::from_millis(100)); } }); - let mut failed = 0; + let mut failed = workers - children.len(); for (i, child) in children.iter_mut() { match child.wait() { Ok(st) if st.success() => {} @@ -1903,23 +2116,56 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut /// 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 failure is noted and the title -/// starts all the same: it builds what is missing itself. -fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation) -> Result<(), String> { - use crate::hle::d3d12x::gfx_records::{self, Entry}; +/// 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 payloads = gfx_records::read(&gfx_records::path()); - let records: Vec<(Vec, gfx_records::Record)> = payloads.into_iter().filter_map(|p| match gfx_records::decode(&p) { Some(Entry::Pipeline(r)) => Some((p, r)), _ => None }).collect(); + 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(()); } - let shaders = shaders_by_key(inputs, records.iter().flat_map(|(_, r)| r.shaders).filter(|&k| k != 0).collect(), progress); + 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); - if missing != 0 { - crate::xlog_info!("Shader preparation: {missing} of {} graphics pipelines left out (their shaders are not in the title's shader files)", records.len()); + 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) @@ -1932,7 +2178,7 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: 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.shaders.into_iter().filter(|&s| s != 0)); + 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()))?; @@ -1953,6 +2199,10 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: 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] @@ -1960,6 +2210,33 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: Ok(()) } +/// 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> { @@ -1982,14 +2259,37 @@ fn shaders_by_key(inputs: &[Input], wanted: HashSet, progress: &LaunchPrepa 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: &std::collections::HashMap>) -> (Vec, usize) { +fn buildable<'a>(records: impl Iterator, shaders: &HashMap>) -> (Vec, usize) { let (mut ok, mut missing) = (Vec::new(), 0); - for (i, r) in records.enumerate() { - let blobs: Option>> = r.shaders.iter().filter(|&&k| k != 0).map(|k| shaders.get(k).cloned()).collect(); + 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(b) if crate::hle::d3d12x::real::shaders_key(&b) == r.key => ok.push(i), + Some(blobs) if crate::hle::d3d12x::real::shader_set_key(blobs.iter().copied()) == key => ok.push(i), _ => missing += 1, } } @@ -2005,52 +2305,106 @@ fn graphics_summary(line: &str) -> Option<[usize; 4]> { 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 (`real::prepare_graphics`), with the +/// 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) -> i32 { - use crate::hle::d3d12x::gfx_records::{self, Entry}; +fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { + use crate::hle::d3d12x::real; end_with_parent(); - // (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 mut shaders = std::collections::HashMap::new(); let mut records = Vec::new(); - for p in gfx_records::read(job) { - match gfx_records::decode(&p) { - Some(Entry::Pipeline(r)) => records.push(r), - Some(Entry::Shader(k, b)) => { shaders.insert(k, b); } - None => {} + 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 device = match Pipelines::for_adapter("auto") { - Ok(p) => crate::hle::d3d12x::real::prepare_device(p.dev), + 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 n = records.len(); - let threads = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse::().ok()).unwrap_or(1).clamp(1, 8); - let (next, done, made, failed) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + 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(r) = records.get(i) else { break }; - let code = r.shaders.map(|k| shaders.get(&k).map(Vec::as_slice)); - let desc = r.desc(code); + 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 ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { crate::hle::d3d12x::real::prepare_graphics(device, &desc) })).unwrap_or(false); - if ok { made.fetch_add(1, Ordering::Relaxed); } else { failed.fetch_add(1, Ordering::Relaxed); } - let d = done.fetch_add(1, Ordering::Relaxed) + 1; - eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); + 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); + } }); } }); - let (hits, _, stored) = crate::hle::d3d12x::real::driver_cache_stats(); - eprintln!("graphics pipelines: {} made, {} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner(), failed.into_inner()); - 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 @@ -2072,12 +2426,20 @@ fn end_with_parent() { }); } -fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { +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, used: Option<&std::collections::HashSet>, 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 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) @@ -2088,10 +2450,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on 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: Option<(usize, usize)> = std::env::var("XCL_PRECOMPILE_SLICE").ok().and_then(|v| { - let (i, n) = v.split_once('/')?; - Some((i.trim().parse().ok()?, n.trim().parse::().ok().filter(|n| *n > 0)?)) - }); + 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 }; @@ -2111,6 +2470,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() || used.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(), @@ -2135,6 +2509,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if let Some(p) = startup { p.done.fetch_add(1, Ordering::Relaxed); } 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); } @@ -2152,14 +2530,22 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on record_done(); continue; } - if startup.and_then(|p| p.only.as_ref()).is_some_and(|used| !used.contains(&crate::hle::d3d12x::real::shader_key(&blob))) { - unused.fetch_add(1, Ordering::Relaxed); - record_done(); - continue; - } // 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) => {} + } + } if used.is_some_and(|u| !used_compute(&blob, u)) { unused.fetch_add(1, Ordering::Relaxed); record_done(); @@ -2168,9 +2554,16 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { - p.make(&c); - if startup.is_some() && 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 { + p.make(&c); } } compiled.fetch_add(1, Ordering::Relaxed) @@ -2186,6 +2579,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 { @@ -2220,9 +2614,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 { @@ -2234,12 +2633,17 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } } } + if let Some(proof) = &pack_proof { proof.record(i, stage_outputs); } record_done(); }); } }); 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(), @@ -2253,6 +2657,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } if let Some(p) = pipelines { 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); @@ -2266,8 +2674,8 @@ 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()); } + 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)); @@ -2278,6 +2686,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(()) } @@ -2646,25 +3055,97 @@ mod tests { /// 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, Entry}; + use crate::hle::d3d12x::gfx_records::{decode, encode, encode_mesh}; use crate::hle::d3d12x::real::{shader_key, shaders_key}; - let (vs, ps) = (b"vertex".to_vec(), b"pixel".to_vec()); - let record = |key: u64, shaders: [u64; 5]| { - let d = windows::Win32::Graphics::Direct3D12::D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); - match decode(&unsafe { encode(key, shaders, &d) }) { - Some(Entry::Pipeline(r)) => r, - _ => unreachable!(), - } + 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 = std::collections::HashMap::from([(shader_key(&vs), vs.clone()), (shader_key(&ps), ps.clone())]); - assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1], 2)); + 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 @@ -2693,6 +3174,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 4f238248a9..c82c9bb38a 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("