diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f3f035798..87c6ca901 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -25,6 +25,7 @@ pub mod list_x; pub mod null; pub mod present; pub mod pso_async; +pub mod pso_journal; pub mod real; mod shader_cache_session; pub mod sparse; diff --git a/crates/xcl/src/hle/d3d12x/pso_journal.rs b/crates/xcl/src/hle/d3d12x/pso_journal.rs new file mode 100644 index 000000000..651814c42 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pso_journal.rs @@ -0,0 +1,597 @@ +//! The pipelines a title asked for, on disk (`\cache\pipelines.bin`), so another process +//! can compile them: `xcl pipelines` reads the journal – during the run (`--watch`) or before +//! the next one – and fills the DXIL cache and the driver's with what the title will ask for. +//! Written for every pipeline with console shaders that goes to `pso_async` (its DXIL was not +//! in the cache, or it is made lazily); a pipeline's first build is marked as used, which the +//! tool compiles first. `XCL_PSO_JOURNAL=0`: off. +//! +//! Append-only frames, little-endian: tag u8, memory windows u8 (`windows_byte`), 0 u16, payload length u32, +//! hash u64, payload. Tags: `S` a shader (its bytes; hash = fnv64 of them), `G` a graphics +//! pipeline, `C` a compute one, `U` (no payload) pipeline `hash` was built. A pipeline's +//! payload names its shaders by hash; each shader is written once, before the first pipeline +//! that uses it. Duplicates of earlier runs are not written again. +//! +//! On the title's pipeline threads an entry is built and hashed with no lock held; the lock +//! covers its append only. The journal is opened (the frame headers of earlier runs read) on a +//! thread of its own, and what is noted meanwhile waits in memory (`State::Opening`). + +use std::collections::HashSet; +use std::io::{Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, MutexGuard}; +use windows::Win32::Graphics::Direct3D12::*; + +pub const MAGIC: &[u8; 8] = b"XCLPJ001"; +pub const HEAD: usize = 16; + +pub fn path_in(data_dir: &Path) -> PathBuf { + data_dir.join("cache").join("pipelines.bin") +} + +struct Journal { + file: std::fs::File, + seen: HashSet<(u8, u64)>, +} + +/// A frame to append: tag, windows byte, hash, payload. +type Out<'a> = (u8, u8, u64, &'a [u8]); + +enum State { + Closed, + /// being opened (`open_in_background`): the frames noted meanwhile, owned, each once, and + /// their bytes + Opening(Vec<(u8, u8, u64, Vec)>, HashSet<(u8, u64)>, usize), + Open(Journal), + Off, +} + +static J: Mutex = Mutex::new(State::Closed); +/// set with `State::Off`, so that the title's threads stop building entries +static OFF: AtomicBool = AtomicBool::new(false); +/// what may wait in memory while the journal is opened +const OPENING_MAX: usize = 256 << 20; + +fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PSO_JOURNAL").map_or(true, |v| v != "0")) && !OFF.load(Ordering::Relaxed) +} + +/// A panic on another thread while it held the lock does not end the journal (each change of +/// the state is one assignment, so it stays whole). +fn lock() -> MutexGuard<'static, State> { + J.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn turn_off(g: &mut State, why: impl std::fmt::Display) { + crate::xlog_warn!("pipeline journal: {why}: off for this run"); + *g = State::Off; + OFF.store(true, Ordering::Relaxed); +} + +fn open() -> Option { + use std::io::{Read, Seek, SeekFrom}; + use std::os::windows::fs::OpenOptionsExt; + if !enabled() { + return None; + } + let path = path_in(&crate::state::data_dir()); + let _ = std::fs::create_dir_all(path.parent()?); + // the only writer: another title process gets no journal (`xcl pipelines` only reads) + const FILE_SHARE_READ: u32 = 1; + let mut file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .share_mode(FILE_SHARE_READ) + .open(&path) + .map_err(|e| crate::xlog_warn!("pipeline journal {}: {e} – none in this run", path.display())) + .ok()?; + let mut seen = HashSet::new(); + let len = file.metadata().map_or(0, |m| m.len()); + let mut magic = [0u8; 8]; + if file.read_exact(&mut magic).is_ok() && &magic == MAGIC { + // the frames' headers only (the shaders' bytes stay on disk); a torn last frame (a + // run killed mid-write) is cut off + let mut at = MAGIC.len() as u64; + let mut head = [0u8; HEAD]; + while file.read_exact(&mut head).is_ok() { + let end = at + HEAD as u64 + u32::from_le_bytes(head[4..8].try_into().unwrap()) as u64; + if end > len { + break; + } + seen.insert((head[0], u64::from_le_bytes(head[8..16].try_into().unwrap()))); + at = end; + if file.seek(SeekFrom::Start(at)).is_err() { + break; + } + } + if at < len { + let _ = file.set_len(at); + } + } else { + let _ = file.set_len(0); + let _ = file.seek(SeekFrom::Start(0)); + let _ = file.write_all(MAGIC); + } + file.seek(SeekFrom::End(0)).ok()?; + crate::xlog_info!("pipeline journal: {} ({} entries from earlier runs) – `xcl pipelines` compiles them outside the title", path.display(), seen.len()); + Some(Journal { file, seen }) +} + +/// Appends `frames` in order (shaders before the pipeline that names them); a write error turns +/// the journal off for the rest of the run. The first call starts the opening. +fn write(frames: &[Out]) { + if note(&mut lock(), frames) && std::thread::Builder::new().name("xcl-pso-journal".into()).spawn(open_in_background).is_err() { + turn_off(&mut lock(), "no thread to open it"); + } +} + +/// `write` on the state; true: the caller starts the opening. +fn note(g: &mut State, frames: &[Out]) -> bool { + match g { + State::Off => false, + State::Open(j) => { + if let Err(e) = frames.iter().try_for_each(|&(t, w, h, p)| put(j, t, w, h, p)) { + turn_off(g, e); + } + false + } + State::Opening(q, kept, bytes) => { + for &(t, w, h, p) in frames { + if kept.insert((t, h)) { + *bytes += p.len(); + q.push((t, w, h, p.to_vec())); + } + } + if *bytes > OPENING_MAX { + turn_off(g, "too much noted while it was opened"); + } + false + } + State::Closed => { + *g = State::Opening(Vec::new(), HashSet::new(), 0); + note(g, frames); + true + } + } +} + +/// Opens the journal with no lock held (the title's threads go on noting), then writes what +/// they noted meanwhile. +fn open_in_background() { + let j = open(); + opened(&mut lock(), j); +} + +fn opened(g: &mut State, j: Option) { + let State::Opening(q, ..) = std::mem::replace(g, State::Off) else { return }; + let Some(mut j) = j else { + OFF.store(true, Ordering::Relaxed); + return; + }; + match q.iter().try_for_each(|(t, w, h, p)| put(&mut j, *t, *w, *h, p)) { + Ok(()) => *g = State::Open(j), + Err(e) => turn_off(g, e), + } +} + +fn frame(tag: u8, windows: u8, hash: u64, payload: &[u8]) -> Vec { + let mut v = Vec::with_capacity(HEAD + payload.len()); + v.extend_from_slice(&[tag, windows, 0, 0]); + v.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + v.extend_from_slice(&hash.to_le_bytes()); + v.extend_from_slice(payload); + v +} + +/// One frame of the journal. +pub struct Frame<'a> { + pub tag: u8, + pub windows: u8, + pub hash: u64, + pub payload: &'a [u8], +} + +/// Call `f` on each whole frame of `bytes` (a journal from its start); the end of the last whole one. +pub fn for_each_frame<'a>(bytes: &'a [u8], f: impl FnMut(Frame<'a>)) -> usize { + for_each_frame_from(bytes, MAGIC.len(), f) +} + +/// `for_each_frame` from offset `at` (the end of an earlier call: a journal being written). +pub fn for_each_frame_from<'a>(bytes: &'a [u8], mut at: usize, mut f: impl FnMut(Frame<'a>)) -> usize { + while at + HEAD <= bytes.len() { + let n = u32::from_le_bytes(bytes[at + 4..at + 8].try_into().unwrap()) as usize; + if at + HEAD + n > bytes.len() { + break; + } + f(Frame { tag: bytes[at], windows: bytes[at + 1], hash: u64::from_le_bytes(bytes[at + 8..at + 16].try_into().unwrap()), payload: &bytes[at + HEAD..at + HEAD + n] }); + at += HEAD + n; + } + at.min(bytes.len()) +} + +/// Copy each field named into `out` at its offset in `T`: a desc's bytes without its pointers +/// and padding (both stay 0), so the same pipeline always gives the same bytes and hash. +macro_rules! fields { + ($out:expr, $d:expr, $T:ty, $($($f:ident).+),+ $(,)?) => {{ + $(put_at(&mut $out, std::mem::offset_of!($T, $($f).+), &$d.$($f).+);)+ + }}; +} + +fn put_at(out: &mut [u8], off: usize, v: &V) { + let b = unsafe { std::slice::from_raw_parts(v as *const V as *const u8, std::mem::size_of::()) }; + out[off..off + b.len()].copy_from_slice(b); +} + +fn graphics_bytes(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Vec { + type G = D3D12_GRAPHICS_PIPELINE_STATE_DESC; + type R = D3D12_RENDER_TARGET_BLEND_DESC; + let mut out = vec![0u8; std::mem::size_of::()]; + fields!(out, d, G, BlendState.AlphaToCoverageEnable, BlendState.IndependentBlendEnable, SampleMask); + let rt0 = std::mem::offset_of!(G, BlendState.RenderTarget); + for (i, r) in d.BlendState.RenderTarget.iter().enumerate() { + let mut one = vec![0u8; std::mem::size_of::()]; + fields!(one, r, R, BlendEnable, LogicOpEnable, SrcBlend, DestBlend, BlendOp, SrcBlendAlpha, DestBlendAlpha, BlendOpAlpha, LogicOp, RenderTargetWriteMask); + let at = rt0 + i * one.len(); + out[at..at + one.len()].copy_from_slice(&one); + } + fields!( + out, d, G, + RasterizerState.FillMode, RasterizerState.CullMode, RasterizerState.FrontCounterClockwise, RasterizerState.DepthBias, + RasterizerState.DepthBiasClamp, RasterizerState.SlopeScaledDepthBias, RasterizerState.DepthClipEnable, + RasterizerState.MultisampleEnable, RasterizerState.AntialiasedLineEnable, RasterizerState.ForcedSampleCount, + RasterizerState.ConservativeRaster, + DepthStencilState.DepthEnable, DepthStencilState.DepthWriteMask, DepthStencilState.DepthFunc, DepthStencilState.StencilEnable, + DepthStencilState.StencilReadMask, DepthStencilState.StencilWriteMask, + DepthStencilState.FrontFace.StencilFailOp, DepthStencilState.FrontFace.StencilDepthFailOp, + DepthStencilState.FrontFace.StencilPassOp, DepthStencilState.FrontFace.StencilFunc, + DepthStencilState.BackFace.StencilFailOp, DepthStencilState.BackFace.StencilDepthFailOp, + DepthStencilState.BackFace.StencilPassOp, DepthStencilState.BackFace.StencilFunc, + InputLayout.NumElements, IBStripCutValue, PrimitiveTopologyType, NumRenderTargets, RTVFormats, DSVFormat, + SampleDesc.Count, SampleDesc.Quality, NodeMask, Flags, + ); + out +} + +fn compute_bytes(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> Vec { + type C = D3D12_COMPUTE_PIPELINE_STATE_DESC; + let mut out = vec![0u8; std::mem::size_of::()]; + fields!(out, d, C, NodeMask, Flags); + out +} + +unsafe fn bytes_of<'a>(b: &D3D12_SHADER_BYTECODE) -> Option<&'a [u8]> { + (!b.pShaderBytecode.is_null() && b.BytecodeLength != 0).then(|| std::slice::from_raw_parts(b.pShaderBytecode as *const u8, b.BytecodeLength)) +} + +/// Writes a frame once: all of it, or (an error) none of it, so later frames stay readable. +fn put(j: &mut Journal, tag: u8, windows: u8, hash: u64, payload: &[u8]) -> std::io::Result<()> { + if j.seen.contains(&(tag, hash)) { + return Ok(()); + } + let at = j.file.stream_position()?; + if let Err(e) = j.file.write_all(&frame(tag, windows, hash, payload)) { + let _ = j.file.set_len(at); + let _ = j.file.seek(SeekFrom::Start(at)); + return Err(e); + } + j.seen.insert((tag, hash)); + Ok(()) +} + +/// A pipeline's frames, built and hashed with no lock held: its shaders', then its own. +struct Entry<'a> { + shaders: Vec>, + tag: u8, + windows: u8, + hash: u64, + payload: Vec, +} + +impl Entry<'_> { + fn frames(&self) -> Vec> { + let mut f = self.shaders.clone(); + f.push((self.tag, self.windows, self.hash, &self.payload)); + f + } +} + +/// A shader's hash into the pipeline's payload, and its frame (none for an empty slot). +fn add_shader<'a>(shaders: &mut Vec>, out: &mut Vec, sh: Option<&'a [u8]>) { + let h = sh.map_or(0, crate::gpu::shader::fnv64); + if let Some(sh) = sh { + shaders.push((b'S', 0, h, sh)); + } + out.extend_from_slice(&h.to_le_bytes()); +} + +/// `pso::mem_windows` in a frame's byte: the count in the low 7 bits, `HEAP_WINDOWS` in the top +/// bit (the shaders take the windows from the descriptor heap: other HLSL than the switch form). +pub fn windows_byte(mem_windows: u32) -> u8 { + (mem_windows & 0x7F) as u8 | if mem_windows & crate::gpu::recomp::HEAP_WINDOWS != 0 { 0x80 } else { 0 } +} + +/// A frame's memory windows as `pso::mem_windows` had them (`windows_byte`). +pub fn mem_windows_of(byte: u8) -> u32 { + (byte & 0x7F) as u32 | if byte & 0x80 != 0 { crate::gpu::recomp::HEAP_WINDOWS } else { 0 } +} + +fn entry(shaders: Vec, tag: u8, mut payload: Vec) -> Entry { + // the memory windows are part of what the pipeline is (its HLSL differs with them, and with + // heap windows) + let windows = windows_byte(crate::gpu::recomp::pso::mem_windows()); + payload.push(windows); + let hash = crate::gpu::shader::fnv64(&payload); + payload.pop(); + Entry { shaders, tag, windows, hash, payload } +} + +/// Writes the entry; its hash. +fn note_entry(e: Entry) -> u64 { + write(&e.frames()); + e.hash +} + +/// Note a graphics pipeline; its hash for `used`, 0 = not written. +pub unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> u64 { + if !enabled() { + return 0; + } + note_entry(graphics_entry(d)) +} + +unsafe fn graphics_entry(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Entry<'_> { + let (mut shaders, mut p) = (Vec::new(), Vec::new()); + for b in [&d.VS, &d.PS, &d.DS, &d.HS, &d.GS] { + add_shader(&mut shaders, &mut p, bytes_of(b)); + } + let desc = graphics_bytes(d); + p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); + p.extend_from_slice(&desc); + let elems = if d.InputLayout.NumElements > 0 && !d.InputLayout.pInputElementDescs.is_null() { + std::slice::from_raw_parts(d.InputLayout.pInputElementDescs, d.InputLayout.NumElements as usize) + } else { + &[] + }; + p.extend_from_slice(&(elems.len() as u32).to_le_bytes()); + for e in elems { + let name = std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char).to_bytes(); + p.extend_from_slice(&(name.len() as u32).to_le_bytes()); + p.extend_from_slice(name); + for w in [e.SemanticIndex, e.Format.0 as u32, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0 as u32, e.InstanceDataStepRate] { + p.extend_from_slice(&w.to_le_bytes()); + } + } + entry(shaders, b'G', p) +} + +/// Note a compute pipeline; its hash for `used`, 0 = not written. +pub unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> u64 { + if !enabled() { + return 0; + } + let (mut shaders, mut p) = (Vec::new(), Vec::new()); + add_shader(&mut shaders, &mut p, bytes_of(&d.CS)); + let desc = compute_bytes(d); + p.extend_from_slice(&(desc.len() as u32).to_le_bytes()); + p.extend_from_slice(&desc); + note_entry(entry(shaders, b'C', p)) +} + +/// Pipeline `hash` was built (the title used it): `xcl pipelines` makes these first. +pub fn used(hash: u64) { + if hash == 0 { + return; + } + write(&[(b'U', 0, hash, &[])]); +} + +/// A journal's pipeline, read back with everything it points to owned. +pub enum Replay { + Graphics(Box, Vec>, Vec, Vec), + Compute(Box, Vec>), +} + +unsafe impl Send for Replay {} + +fn read_desc(p: &[u8], at: &mut usize) -> Option> { + let n = u32::from_le_bytes(p.get(*at..*at + 4)?.try_into().ok()?) as usize; + *at += 4; + let bytes = p.get(*at..*at + n)?; + *at += n; + if n != std::mem::size_of::() { + return None; + } + unsafe { + let mut b: Box> = Box::new(std::mem::MaybeUninit::zeroed()); + std::ptr::copy_nonoverlapping(bytes.as_ptr(), b.as_mut_ptr() as *mut u8, n); + Some(Box::from_raw(Box::into_raw(b) as *mut T)) + } +} + +fn u32_at(p: &[u8], at: &mut usize) -> Option { + let v = u32::from_le_bytes(p.get(*at..*at + 4)?.try_into().ok()?); + *at += 4; + Some(v) +} + +/// The pipeline of frame `f` (`G` / `C`), its shaders from `shader` by hash. None: malformed, +/// or a shader not in the journal. +pub fn replay(f: &Frame, shader: impl Fn(u64) -> Option>) -> Option { + let p = f.payload; + let mut at = 0usize; + let sh = |at: &mut usize| -> Option>> { + let h = u64::from_le_bytes(p.get(*at..*at + 8)?.try_into().ok()?); + *at += 8; + if h == 0 { + return Some(None); + } + Some(Some(shader(h)?)) + }; + let code = |b: &Vec| D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as *const _, BytecodeLength: b.len() }; + match f.tag { + b'C' => { + let cs = sh(&mut at)??; + let mut d: Box = read_desc(p, &mut at)?; + // (no pointer from the file reaches the driver) + d.pRootSignature = std::mem::ManuallyDrop::new(None); + d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + d.CS = code(&cs); + Some(Replay::Compute(d, vec![cs])) + } + b'G' => { + let mut blobs = Vec::new(); + let mut slots = [None; 5]; + for s in slots.iter_mut() { + if let Some(b) = sh(&mut at)? { + blobs.push(b); + *s = Some(blobs.len() - 1); + } + } + let mut d: Box = read_desc(p, &mut at)?; + // (no pointer from the file reaches the driver) + d.pRootSignature = std::mem::ManuallyDrop::new(None); + d.StreamOutput = unsafe { std::mem::zeroed() }; + d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + for b in [&mut d.VS, &mut d.PS, &mut d.DS, &mut d.HS, &mut d.GS] { + *b = D3D12_SHADER_BYTECODE::default(); + } + for (s, b) in slots.iter().zip([&mut d.VS, &mut d.PS, &mut d.DS, &mut d.HS, &mut d.GS]) { + if let Some(i) = s { + *b = code(&blobs[*i]); + } + } + let n = u32_at(p, &mut at)? as usize; + if n > (p.len() - at) / 28 { + return None; // each element: a name length and six words at least + } + let mut names = Vec::with_capacity(n); + let mut raw = Vec::with_capacity(n); + for _ in 0..n { + let len = u32_at(p, &mut at)? as usize; + names.push(std::ffi::CString::new(p.get(at..at + len)?).ok()?); + at += len; + let mut w = [0u32; 6]; + for x in w.iter_mut() { + *x = u32_at(p, &mut at)?; + } + raw.push(w); + } + let elems: Vec = names + .iter() + .zip(&raw) + .map(|(name, w)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: windows::core::PCSTR(name.as_ptr() as *const u8), + SemanticIndex: w[0], + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(w[1] as i32), + InputSlot: w[2], + AlignedByteOffset: w[3], + InputSlotClass: D3D12_INPUT_CLASSIFICATION(w[4] as i32), + InstanceDataStepRate: w[5], + }) + .collect(); + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: if elems.is_empty() { std::ptr::null() } else { elems.as_ptr() }, NumElements: elems.len() as u32 }; + Some(Replay::Graphics(d, blobs, elems, names)) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_heap_windows_flag_is_kept() { + let heap = crate::gpu::recomp::HEAP_WINDOWS; + for w in [1, 4, 4 | heap, 16 | heap] { + assert_eq!(mem_windows_of(windows_byte(w)), w); + } + assert_ne!(windows_byte(4), windows_byte(4 | heap)); + } + + #[test] + fn graphics_round_trip() { + let vs = vec![1u8, 2, 3, 4]; + let ps = vec![9u8; 40]; + let name = std::ffi::CString::new("TEXCOORD").unwrap(); + let elems = [D3D12_INPUT_ELEMENT_DESC { SemanticName: windows::core::PCSTR(name.as_ptr() as *const u8), SemanticIndex: 3, InputSlot: 1, AlignedByteOffset: 12, ..Default::default() }]; + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + d.VS = D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as *const _, BytecodeLength: vs.len() }; + d.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as *const _, BytecodeLength: ps.len() }; + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elems.as_ptr(), NumElements: 1 }; + d.NumRenderTargets = 2; + d.SampleMask = 0xffff_ffff; + let mut j = Journal { file: tempfile(), seen: HashSet::new() }; + let h1 = unsafe { graphics_in(&mut j, &d).unwrap() }; + let h2 = unsafe { graphics_in(&mut j, &d).unwrap() }; + assert_eq!(h1, h2, "the same desc made again: the same hash"); + // garbage in the padding after a render target's write mask (a desc built on the stack) + let mut d3: D3D12_GRAPHICS_PIPELINE_STATE_DESC = unsafe { std::ptr::read(&d) }; + let pad = std::mem::offset_of!(D3D12_GRAPHICS_PIPELINE_STATE_DESC, BlendState.RenderTarget) + + std::mem::offset_of!(D3D12_RENDER_TARGET_BLEND_DESC, RenderTargetWriteMask) + + 1; + unsafe { *(&mut d3 as *mut D3D12_GRAPHICS_PIPELINE_STATE_DESC as *mut u8).add(pad) = 0xAA }; + assert_eq!(unsafe { graphics_in(&mut j, &d3).unwrap() }, h1, "padding is not part of the pipeline"); + std::mem::forget(d3); + let mut bytes = MAGIC.to_vec(); + use std::io::{Read, Seek}; + j.file.seek(std::io::SeekFrom::Start(0)).unwrap(); + j.file.read_to_end(&mut bytes).unwrap(); + let mut frames = Vec::new(); + for_each_frame(&bytes, |f| frames.push((f.tag, f.hash, f.payload.to_vec()))); + assert_eq!(frames.iter().filter(|f| f.0 == b'S').count(), 2); + assert_eq!(frames.iter().filter(|f| f.0 == b'G').count(), 1, "written once"); + let g = frames.iter().find(|f| f.0 == b'G').unwrap(); + let shader = |h| frames.iter().find(|f| f.0 == b'S' && f.1 == h).map(|f| f.2.clone()); + let Some(Replay::Graphics(r, blobs, _elems, _names)) = replay(&Frame { tag: b'G', windows: 0, hash: g.1, payload: &g.2 }, shader) else { panic!("no replay") }; + assert_eq!(blobs, vec![vs.clone(), ps.clone()]); + unsafe { + assert_eq!(bytes_of(&r.VS).unwrap(), &vs[..]); + assert_eq!(bytes_of(&r.PS).unwrap(), &ps[..]); + assert!(bytes_of(&r.GS).is_none()); + assert_eq!((r.NumRenderTargets, r.SampleMask, r.InputLayout.NumElements), (2, 0xffff_ffff, 1)); + let e = &*r.InputLayout.pInputElementDescs; + assert_eq!((e.SemanticName.to_string().unwrap().as_str(), e.SemanticIndex, e.InputSlot, e.AlignedByteOffset), ("TEXCOORD", 3, 1, 12)); + } + // a torn tail is not a frame + let whole = for_each_frame(&bytes, |_| {}); + assert_eq!(for_each_frame(&bytes[..bytes.len() - 3], |_| {}) < whole, true); + } + + /// The entry written straight to `j` (no global state); its hash. + unsafe fn graphics_in(j: &mut Journal, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> std::io::Result { + let e = graphics_entry(d); + e.frames().iter().try_for_each(|&(t, w, h, p)| put(j, t, w, h, p))?; + Ok(e.hash) + } + + #[test] + fn what_is_noted_while_the_journal_opens_is_written_after_in_order() { + let (vs, ps) = (vec![1u8; 8], vec![2u8; 8]); + let mut g = State::Closed; + assert!(note(&mut g, &[(b'S', 0, 11, &vs[..]), (b'G', 0, 21, &[7])]), "the first note starts the opening"); + assert!(!note(&mut g, &[(b'S', 0, 11, &vs[..]), (b'S', 0, 12, &ps[..]), (b'G', 0, 22, &[8])]), "only once"); + assert!(!note(&mut g, &[(b'U', 0, 21, &[])])); + let State::Opening(q, _, bytes) = &g else { panic!("not opening") }; + assert_eq!((q.len(), *bytes), (5, 18), "a shader noted twice is kept once"); + opened(&mut g, Some(Journal { file: tempfile(), seen: HashSet::new() })); + let State::Open(j) = &mut g else { panic!("not open") }; + let mut bytes = MAGIC.to_vec(); + use std::io::{Read, Seek}; + j.file.seek(std::io::SeekFrom::Start(0)).unwrap(); + j.file.read_to_end(&mut bytes).unwrap(); + let mut order = Vec::new(); + for_each_frame(&bytes, |f| order.push((f.tag, f.hash))); + assert_eq!(order, [(b'S', 11), (b'G', 21), (b'S', 12), (b'G', 22), (b'U', 21)]); + } + + fn tempfile() -> std::fs::File { + let p = std::env::temp_dir().join(format!("xcl_pso_journal_{}.bin", std::process::id())); + let f = std::fs::OpenOptions::new().create(true).truncate(true).read(true).write(true).open(&p).unwrap(); + let _ = std::fs::remove_file(&p); + f + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ac7ab4c4d..77e8e9424 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3949,32 +3949,19 @@ unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: m.insert(key, std::sync::Arc::new(bytes)); } -unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { - with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) -} - -unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { +/// The PC desc of a pipeline with a console VS (and PS) and no GS / HS / DS: the translated +/// shaders, XCL's ABI root signature, PC formats and topology (`translated_graphics_pso`, apart +/// from making the pipeline). +struct GraphicsPrep { + desc: D3D12_GRAPHICS_PIPELINE_STATE_DESC, + rs: *mut c_void, + rect_gs: Option>, + /// the VS / PS DXIL `desc` points at + _dxil: (Vec, Option>), +} + +unsafe fn prep_graphics(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs: &[u8]) -> Option { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; - if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { - return None; - } - let d = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); - let vs = shader_bytes(&d.VS)?; - if !is_console(vs) { - return None; - } - if shader_bytes(&d.HS).is_some() || shader_bytes(&d.DS).is_some() { - note_translation_error("PSO with HS/DS – not supported yet".into()); - return None; - } - if let Some(gs) = shader_bytes(&d.GS).filter(|g| is_console(g)) { - let _ = f; - return Some(translated_gs_pso(this, d, vs, gs, riid, ppv)); - } - // made when first used (`pso_async::lazy`): not even translated now - if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { - return None; - } // a GPU that can run 32-lane waves may run a wave64 VS / PS in waves of 32 (the driver // picks; RDNA2 does for pixel shaders): the lanes 32..63 it reads come from `upper_lanes` // (split_wave64) @@ -4019,6 +4006,36 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.GS = bytecode(gs); } pc_topology_type(&mut copy); + Some(GraphicsPrep { desc: copy, rs, rect_gs, _dxil: (vs_dxil, ps_dxil) }) +} + +unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) +} + +unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { + use crate::gpu::recomp::pso::is_console; + if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return None; + } + let d = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + let vs = shader_bytes(&d.VS)?; + if !is_console(vs) { + return None; + } + if shader_bytes(&d.HS).is_some() || shader_bytes(&d.DS).is_some() { + note_translation_error("PSO with HS/DS – not supported yet".into()); + return None; + } + if let Some(gs) = shader_bytes(&d.GS).filter(|g| is_console(g)) { + let _ = f; + return Some(translated_gs_pso(this, d, vs, gs, riid, ppv)); + } + // made when first used (`pso_async::lazy`): not even translated now + if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { + return None; + } + let GraphicsPrep { desc: mut copy, rs, rect_gs, _dxil } = prep_graphics(this, d, vs)?; let ps_hash = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); if debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) { copy.DepthStencilState.StencilEnable = false.into(); @@ -4292,9 +4309,16 @@ unsafe fn go_background( } let dev = Dev(this as usize, f as usize); let key = owned.shaders_key(); + // for `xcl pipelines`, which compiles them in its own process (`pso_journal`) + let journal = match &owned { + OwnedDesc::Graphics(d, ..) => super::pso_journal::graphics(d), + OwnedDesc::Compute(d, _) => super::pso_journal::compute(d), + OwnedDesc::Stream(..) => 0, + }; let job: super::pso_async::Job = Box::new(move || { let mut out: *mut c_void = std::ptr::null_mut(); if unsafe { build(dev, &owned, &mut out) } && !out.is_null() { + super::pso_journal::used(journal); out as usize } else { 0