diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 2d431e5a47..06277d4a41 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -136,6 +136,7 @@ unsafe extern "system" fn hk_nt_terminate_process(h: isize, status: i32) -> i32 crate::xlog_info!("process ends (thread {tid}); on the stack: {stack}"); } crate::log::flush(); + crate::hle::d3d12x::pso_async::flush_used_bounded(std::time::Duration::from_millis(100)); } let orig: unsafe extern "system" fn(isize, i32) -> i32 = std::mem::transmute(ORIG_NT_TERMINATE.load(Ordering::Acquire)); orig(h, status) diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 18436a51c0..c94a152dcf 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -36,6 +36,7 @@ mod standin; pub mod title_list; pub mod title_textures; mod uma_driver; +mod used_journal; pub mod vram; use std::ffi::c_void; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index f8dbfab36f..7be538bd2a 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -793,6 +793,17 @@ pub fn earlier_used_keys() -> std::collections::HashSet { used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt")).unwrap_or_default()) } +/// Ask the used-pipeline writer to finish without ever joining it unboundedly. +pub fn shutdown_used() { + used::shutdown(std::time::Duration::from_millis(500)); +} + +/// Best effort at process termination: only the one writer touches the append handle, and a +/// loader-lock-blocked writer cannot hold termination longer than `timeout`. +pub fn flush_used_bounded(timeout: std::time::Duration) { + used::shutdown(timeout); +} + /// The pipelines a title used, by a hash of their shaders, kept between runs /// (`used-pipelines.txt` beside the DXIL cache, a key a line). /// @@ -806,16 +817,21 @@ mod used { use std::collections::{HashMap, HashSet}; use std::io::Write; use std::sync::{Mutex, OnceLock, RwLock}; + use std::time::Duration; + + use super::super::used_journal::Journal; struct Used { earlier: RwLock>, - now: Mutex<(HashSet, Option)>, + now: Journal, /// the shaders of each set made in this run, by the set's key; the shaders of the sets /// used so far and `used-shaders.txt`, where they are kept for the next run parts: Mutex>>, shaders: Mutex<(HashSet, Option)>, } + static U: OnceLock = OnceLock::new(); + /// The keys in a `used-pipelines.txt` (lines that are not a hexadecimal key are passed over). pub fn parse(text: &str) -> HashSet { parse_ranked(text).into_keys().collect() @@ -832,13 +848,12 @@ mod used { } fn get() -> &'static Used { - static U: OnceLock = OnceLock::new(); U.get_or_init(|| { // (a test neither reads nor writes the user's file) if cfg!(test) { return Used { earlier: RwLock::new(HashMap::new()), - now: Mutex::new((HashSet::new(), None)), + now: Journal::memory(HashSet::new()), parts: Default::default(), shaders: Mutex::new((HashSet::new(), None)), }; @@ -848,15 +863,12 @@ mod used { if !earlier.is_empty() { crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); } - if let Some(dir) = path.parent() { - let _ = std::fs::create_dir_all(dir); - } - let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok(); + let now = Journal::file(path.clone(), earlier.keys().copied().collect()); let shaders_path = path.with_file_name("used-shaders.txt"); let shaders = parse(&std::fs::read_to_string(&shaders_path).unwrap_or_default()); let shaders_file = std::fs::OpenOptions::new().create(true).append(true).open(&shaders_path).ok(); Used { - now: Mutex::new((earlier.keys().copied().collect(), file)), + now, earlier: RwLock::new(earlier), parts: Default::default(), shaders: Mutex::new((shaders, shaders_file)), @@ -864,6 +876,12 @@ mod used { }) } + pub fn shutdown(timeout: Duration) { + if let Some(used) = U.get() { + let _ = used.now.shutdown_bounded(timeout); + } + } + /// First-use rank when an earlier run used a pipeline of these shaders. pub fn rank(key: u64) -> Option { (key != 0).then(|| get().earlier.read().unwrap().get(&key).copied()).flatten() @@ -874,14 +892,7 @@ mod used { if key == 0 { return; } - { - let mut g = get().now.lock().unwrap(); - if g.0.insert(key) { - if let Some(f) = g.1.as_mut() { - let _ = writeln!(f, "{key:016x}"); - } - } - } + get().now.note(key); // its shaders, each once (also those of a set an earlier run used: the list of // shaders is younger than the list of sets) let parts = get().parts.lock().unwrap().get(&key).cloned().unwrap_or_default(); @@ -911,7 +922,7 @@ mod used { /// (tests) This run used a pipeline of these shaders. #[cfg(test)] pub fn noted(key: u64) -> bool { - get().now.lock().unwrap().0.contains(&key) + get().now.contains(key) } #[cfg(test)] diff --git a/crates/xcl/src/hle/d3d12x/used_journal.rs b/crates/xcl/src/hle/d3d12x/used_journal.rs new file mode 100644 index 0000000000..1c058df440 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/used_journal.rs @@ -0,0 +1,349 @@ +//! Ordered background append journal for `used-pipelines.txt`. + +use std::collections::HashSet; +use std::fmt::Write as _; +use std::io::Write; +use std::path::PathBuf; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +const COALESCE: Duration = Duration::from_millis(25); +const FULL_BATCH: usize = 64; + +trait Sink: Send { + fn append(&mut self, bytes: &[u8]) -> bool; +} + +struct FileSink { + path: PathBuf, + file: Option, +} + +impl Sink for FileSink { + fn append(&mut self, bytes: &[u8]) -> bool { + if self.file.is_none() { + if let Some(dir) = self.path.parent() { + let _ = std::fs::create_dir_all(dir); + } + self.file = std::fs::OpenOptions::new().create(true).append(true).open(&self.path).ok(); + } + let ok = self.file.as_mut().is_some_and(|file| file.write_all(bytes).is_ok()); + if !ok { + self.file = None; + } + ok + } +} + +#[derive(Clone)] +struct Batch { + end_seq: u64, + keys: Arc<[u64]>, +} + +struct State { + seen: HashSet, + pending: Vec<(u64, u64)>, + in_flight: Option, + next_seq: u64, + completed_seq: u64, + flush_now: bool, + closed: bool, + stopped: bool, +} + +struct Shared { + state: Mutex, + wake: Condvar, + completed: Condvar, +} + +/// A single writer owns the append handle. Producers only touch `Shared::state`; the batch being +/// written stays there until it succeeds, so a later producer can never hide or overtake it. +pub(super) struct Journal { + shared: Arc, +} + +impl Journal { + pub(super) fn file(path: PathBuf, seen: HashSet) -> Self { + Self::with_sink(seen, Box::new(FileSink { path, file: None }), COALESCE) + } + + pub(super) fn memory(seen: HashSet) -> Self { + let shared = Arc::new(Shared { + state: Mutex::new(State { + seen, + pending: Vec::new(), + in_flight: None, + next_seq: 0, + completed_seq: 0, + flush_now: false, + closed: false, + stopped: true, + }), + wake: Condvar::new(), + completed: Condvar::new(), + }); + Self { shared } + } + + fn with_sink(seen: HashSet, sink: Box, coalesce: Duration) -> Self { + let shared = Arc::new(Shared { + state: Mutex::new(State { + seen, + pending: Vec::new(), + in_flight: None, + next_seq: 0, + completed_seq: 0, + flush_now: false, + closed: false, + stopped: false, + }), + wake: Condvar::new(), + completed: Condvar::new(), + }); + let worker = shared.clone(); + if std::thread::Builder::new().name("xcl-pso-used".into()).spawn(move || writer(worker, sink, coalesce)).is_err() { + shared.state.lock().unwrap().stopped = true; + } + Self { shared } + } + + pub(super) fn note(&self, key: u64) { + if key == 0 { + return; + } + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.closed || !state.seen.insert(key) { + return; + } + // An in-memory/test journal, or a worker that could not start, still deduplicates. + if state.stopped { + return; + } + state.next_seq += 1; + let seq = state.next_seq; + state.pending.push((seq, key)); + if state.pending.len() == 1 || state.pending.len() == FULL_BATCH { + self.shared.wake.notify_one(); + } + } + + #[cfg(test)] + pub(super) fn contains(&self, key: u64) -> bool { self.shared.state.lock().unwrap_or_else(|e| e.into_inner()).seen.contains(&key) } + + #[cfg(test)] + fn flush_bounded(&self, timeout: Duration) -> bool { self.wait_bounded(timeout, false) } + + pub(super) fn shutdown_bounded(&self, timeout: Duration) -> bool { self.wait_bounded(timeout, true) } + + fn wait_bounded(&self, timeout: Duration, close: bool) -> bool { + let deadline = Instant::now() + timeout; + let mut state = loop { + match self.shared.state.try_lock() { + Ok(state) => break state, + Err(std::sync::TryLockError::Poisoned(e)) => break e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + if Instant::now() >= deadline { + return false; + } + std::thread::yield_now(); + } + } + }; + if close { + state.closed = true; + } + let target = state.next_seq; + state.flush_now = true; + self.shared.wake.notify_one(); + while (state.completed_seq < target || close && !state.stopped) && !state.stopped { + let Some(left) = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break }; + let (next, waited) = self.shared.completed.wait_timeout(state, left).unwrap_or_else(|e| e.into_inner()); + state = next; + if waited.timed_out() { + break; + } + } + state.completed_seq >= target && (!close || state.stopped) + } +} + +impl Drop for Journal { + fn drop(&mut self) { + let _ = self.shutdown_bounded(Duration::from_millis(100)); + } +} + +struct Stopped(Arc); + +impl Drop for Stopped { + fn drop(&mut self) { + let mut state = self.0.state.lock().unwrap_or_else(|e| e.into_inner()); + state.stopped = true; + self.0.completed.notify_all(); + } +} + +fn writer(shared: Arc, mut sink: Box, coalesce: Duration) { + let stopped = Stopped(shared.clone()); + let mut bytes = String::new(); + let mut retrying = false; + loop { + let batch = { + let mut state = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + while state.in_flight.is_none() && state.pending.is_empty() && !state.closed { + state = shared.wake.wait(state).unwrap_or_else(|e| e.into_inner()); + } + if state.in_flight.is_none() && !state.pending.is_empty() && !coalesce.is_zero() && !state.flush_now && !state.closed { + let until = Instant::now() + coalesce; + while state.pending.len() < FULL_BATCH && !state.flush_now && !state.closed { + let Some(left) = until.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break }; + let (next, waited) = shared.wake.wait_timeout(state, left).unwrap_or_else(|e| e.into_inner()); + state = next; + if waited.timed_out() { + break; + } + } + } + state.flush_now = false; + if state.in_flight.is_none() && !state.pending.is_empty() { + let pending = std::mem::take(&mut state.pending); + let end_seq = pending.last().unwrap().0; + state.in_flight = Some(Batch { end_seq, keys: pending.into_iter().map(|(_, key)| key).collect() }); + } + let Some(batch) = state.in_flight.clone() else { + if state.closed { break } else { continue }; + }; + batch + }; + + bytes.clear(); + if retrying { + // `write_all` may have appended an arbitrary prefix before reporting failure. End + // that fragment so replay cannot concatenate it with the first key into a lost line. + bytes.push('\n'); + } + bytes.reserve(batch.keys.len() * 17); + for key in batch.keys.iter() { + let _ = writeln!(bytes, "{key:016x}"); + } + let written = sink.append(bytes.as_bytes()); + retrying = !written; + let mut state = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if written { + if state.in_flight.as_ref().is_some_and(|current| current.end_seq == batch.end_seq) { + state.in_flight = None; + state.completed_seq = state.completed_seq.max(batch.end_seq); + shared.completed.notify_all(); + } + } else { + let (next, _) = shared.wake.wait_timeout(state, coalesce.max(Duration::from_millis(1))).unwrap_or_else(|e| e.into_inner()); + drop(next); + } + } + drop(sink); + drop(stopped); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + + struct Blocking { + first: bool, + entered: mpsc::Sender<()>, + release: mpsc::Receiver<()>, + output: Arc>>, + } + + impl Sink for Blocking { + fn append(&mut self, bytes: &[u8]) -> bool { + if self.first { + self.first = false; + self.entered.send(()).unwrap(); + self.release.recv().unwrap(); + } + self.output.lock().unwrap().extend_from_slice(bytes); + true + } + } + + #[test] + fn flush_waits_for_the_shared_in_flight_batch_and_later_producers() { + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let output = Arc::new(Mutex::new(Vec::new())); + let journal = Arc::new(Journal::with_sink( + HashSet::new(), + Box::new(Blocking { first: true, entered: entered_tx, release: release_rx, output: output.clone() }), + Duration::ZERO, + )); + journal.note(1); + entered_rx.recv_timeout(Duration::from_secs(2)).expect("writer did not take the first batch"); + journal.note(2); + let waiter = journal.clone(); + let (flushed_tx, flushed_rx) = mpsc::channel(); + std::thread::spawn(move || flushed_tx.send(waiter.flush_bounded(Duration::from_secs(2))).unwrap()); + assert!(matches!(flushed_rx.recv_timeout(Duration::from_millis(20)), Err(mpsc::RecvTimeoutError::Timeout))); + release_tx.send(()).unwrap(); + assert!(flushed_rx.recv_timeout(Duration::from_secs(2)).unwrap()); + assert_eq!(String::from_utf8(output.lock().unwrap().clone()).unwrap(), "0000000000000001\n0000000000000002\n"); + assert!(journal.shutdown_bounded(Duration::from_secs(2))); + } + + struct FailOnce { + failed: bool, + output: Arc>>, + } + + impl Sink for FailOnce { + fn append(&mut self, bytes: &[u8]) -> bool { + if !self.failed { + self.failed = true; + self.output.lock().unwrap().extend_from_slice(&bytes[..8.min(bytes.len())]); + return false; + } + self.output.lock().unwrap().extend_from_slice(bytes); + true + } + } + + #[test] + fn failed_batch_is_retried_before_later_keys() { + let output = Arc::new(Mutex::new(Vec::new())); + let journal = Journal::with_sink( + HashSet::new(), + Box::new(FailOnce { failed: false, output: output.clone() }), + Duration::from_millis(1), + ); + journal.note(3); + journal.note(4); + assert!(journal.flush_bounded(Duration::from_secs(2))); + journal.note(5); + assert!(journal.flush_bounded(Duration::from_secs(2))); + let text = String::from_utf8(output.lock().unwrap().clone()).unwrap(); + let keys: Vec = text.lines().filter_map(|line| u64::from_str_radix(line, 16).ok()).filter(|&key| key != 0).collect(); + assert_eq!(keys, [3, 4, 5]); + assert!(journal.shutdown_bounded(Duration::from_secs(2))); + } + + #[test] + fn shutdown_is_bounded_when_the_only_writer_is_blocked() { + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let journal = Journal::with_sink( + HashSet::new(), + Box::new(Blocking { first: true, entered: entered_tx, release: release_rx, output: Arc::new(Mutex::new(Vec::new())) }), + Duration::ZERO, + ); + journal.note(6); + entered_rx.recv_timeout(Duration::from_secs(2)).expect("writer did not block"); + let start = Instant::now(); + assert!(!journal.shutdown_bounded(Duration::from_millis(20))); + assert!(start.elapsed() < Duration::from_millis(500), "bounded shutdown waited {:?}", start.elapsed()); + release_tx.send(()).unwrap(); + assert!(journal.shutdown_bounded(Duration::from_secs(2))); + } +} diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index def09b4e06..e729487803 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -200,6 +200,7 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title ({shown} frames shown, {presented} PresentX calls)"); crate::report::write_final(None); crate::log::flush(); + crate::hle::d3d12x::pso_async::shutdown_used(); crate::hle::d3d12x::real::end_title(0); }); } @@ -218,6 +219,7 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::xlog_info!("game entry point returned code {code}"); crate::report::write_final(None); crate::log::flush(); + crate::hle::d3d12x::pso_async::shutdown_used(); code as i32 }