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/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 63d62a7df4..0cc307991e 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -419,7 +419,17 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { /// The keys of the pipelines earlier runs used (`used-pipelines.txt` beside the DXIL cache): /// what `xcl shaders --precompile --used-only` builds. pub fn earlier_used_keys() -> std::collections::HashSet { - used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt")).unwrap_or_default()) + used::parse(&used::read_used_bounded(&crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"), used::MAX_USED_FILE_BYTES)) +} + +/// Flush and join the `used-pipelines.txt` journal worker on normal shutdown. +pub fn shutdown_used() { + used::shutdown(); +} + +/// Best-effort bounded flush of pending `used-pipelines.txt` keys on process termination. +pub fn flush_used_bounded(timeout: std::time::Duration) { + used::flush_bounded(timeout); } /// The pipelines a title used, by a hash of their shaders, kept between runs @@ -432,13 +442,360 @@ pub fn earlier_used_keys() -> std::collections::HashSet { /// instead of waiting for its pipeline, ~2 170 dispatches were skipped in those frames without /// this and 94 – 150 with it. mod used { - use std::collections::HashSet; - use std::io::Write; - use std::sync::{Mutex, OnceLock, RwLock}; + use std::io::{Read, Write}; + use std::path::{Path, PathBuf}; + use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, RwLock, TryLockError}; + use std::{collections::HashSet, fmt::Write as _, thread::JoinHandle, time::{Duration, Instant}}; + + /// Coalesce first-use bursts into a single disk write off the bind lock. + const COALESCE_WINDOW: Duration = Duration::from_millis(25); + /// Flush immediately once a burst reaches this many unique keys. + const BATCH_IMMEDIATE: usize = 64; + /// Cap initial reads of `used-pipelines.txt` so an oversized/corrupt file cannot stall startup. + pub(super) const MAX_USED_FILE_BYTES: u64 = 16 * 1024 * 1024; + + /// Read at most `max_bytes` from `path`; if truncated, drop any trailing partial line so a + /// mid-line cut never parses a corrupt partial hex key. + pub(super) fn read_used_bounded(path: &Path, max_bytes: u64) -> String { + let Ok(file) = std::fs::File::open(path) else { return String::new() }; + let mut bytes = Vec::new(); + if file.take(max_bytes.saturating_add(1)).read_to_end(&mut bytes).is_err() { + return String::new(); + } + if bytes.len() as u64 > max_bytes { + bytes.truncate(max_bytes as usize); + if let Some(pos) = bytes.iter().rposition(|&b| b == b'\n') { + bytes.truncate(pos + 1); + } else { + bytes.clear(); + } + } + String::from_utf8_lossy(&bytes).into_owned() + } + + fn lock_until<'a, T>(m: &'a Mutex, deadline: Instant) -> Option> { + loop { + match m.try_lock() { + Ok(g) => return Some(g), + Err(TryLockError::Poisoned(e)) => return Some(e.into_inner()), + Err(TryLockError::WouldBlock) => { + let rem = deadline.checked_duration_since(Instant::now())?; + if rem.is_zero() { + return None; + } + std::thread::sleep(rem.min(Duration::from_millis(1))); + } + } + } + } + + enum Sink { + LazyFile(PathBuf, Option), + #[cfg(test)] + Writer(Box), + } + + impl Sink { + fn write_batch(&mut self, bytes: &[u8]) { + match self { + Self::LazyFile(path, file) => { + if file.is_none() { + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty() && !d.exists()) { + let _ = std::fs::create_dir_all(dir); + } + *file = std::fs::OpenOptions::new().create(true).append(true).open(&*path).ok(); + } + if file.as_mut().is_some_and(|f| f.write_all(bytes).is_err() || f.flush().is_err()) { *file = None; } + } + #[cfg(test)] + Self::Writer(w) => if w.write_all(bytes).is_ok() { let _ = w.flush(); }, + } + } + } + + fn format_keys(batch: &[u64], buf: &mut String) { + buf.clear(); + buf.reserve(batch.len() * 17); + for &key in batch { let _ = writeln!(buf, "{key:016x}"); } + } + + fn append_to_path(path: &Path, bytes: &[u8]) -> bool { + if bytes.is_empty() { + return true; + } + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty() && !d.exists()) { + let _ = std::fs::create_dir_all(dir); + } + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .and_then(|mut f| { + f.write_all(bytes)?; + f.flush() + }) + .is_ok() + } + + #[derive(Default)] + struct JournalState { + seen: HashSet, + pending: Vec, + /// Keys currently owned by `writer_loop` while `sink.write_batch` is executing. + in_flight: Vec, + in_flight_seq: u64, + in_flight_fallback_written: bool, + fallback_path: Option, + enqueued_seq: u64, + completed_seq: u64, + flush_now: bool, + closed: bool, + writer_stopped: bool, + } + + struct JournalShared { + state: Mutex, + wake_cv: Condvar, + flushed_cv: Condvar, + } + + struct StopGuard<'a>(&'a JournalShared); + impl Drop for StopGuard<'_> { + fn drop(&mut self) { + self.0.state.lock().unwrap_or_else(|e| e.into_inner()).writer_stopped = true; + self.0.flushed_cv.notify_all(); + } + } + + pub(super) struct Journal { + shared: Arc, + writer: Mutex>>, + } + + impl Journal { + fn new_shared(state: JournalState) -> Arc { + Arc::new(JournalShared { state: Mutex::new(state), wake_cv: Condvar::new(), flushed_cv: Condvar::new() }) + } + fn in_memory(seen: HashSet) -> Self { + Self { shared: Self::new_shared(JournalState { seen, writer_stopped: true, ..Default::default() }), writer: Mutex::new(None) } + } + fn with_sink_and_fallback(seen: HashSet, sink: Sink, fallback_path: Option, coalesce: Duration) -> Self { + let shared = Self::new_shared(JournalState { seen, fallback_path, ..Default::default() }); + let bg = Arc::clone(&shared); + let writer = std::thread::Builder::new().name("xcl-pso-used".into()).spawn(move || writer_loop(&bg, sink, coalesce)).ok(); + if writer.is_none() { + shared.state.lock().unwrap_or_else(|e| e.into_inner()).writer_stopped = true; + shared.flushed_cv.notify_all(); + } + Self { shared, writer: Mutex::new(writer) } + } + fn with_sink(seen: HashSet, sink: Sink, coalesce: Duration) -> Self { + let fallback_path = match &sink { + Sink::LazyFile(p, _) => Some(p.clone()), + #[cfg(test)] + Sink::Writer(_) => None, + }; + Self::with_sink_and_fallback(seen, sink, fallback_path, coalesce) + } + #[cfg(test)] + pub(super) fn with_writer(w: Box, c: Duration) -> Self { Self::with_sink(HashSet::new(), Sink::Writer(w), c) } + #[cfg(test)] + pub(super) fn with_writer_and_fallback(w: Box, fallback: PathBuf, c: Duration) -> Self { + Self::with_sink_and_fallback(HashSet::new(), Sink::Writer(w), Some(fallback), c) + } + #[cfg(test)] + pub(super) fn with_file(p: PathBuf, c: Duration) -> Self { Self::with_sink(HashSet::new(), Sink::LazyFile(p, None), c) } + #[cfg(test)] + pub(super) fn without_writer(p: PathBuf) -> Self { + Self { shared: Self::new_shared(JournalState { fallback_path: Some(p), writer_stopped: true, ..Default::default() }), writer: Mutex::new(None) } + } + #[cfg(test)] + pub(super) fn hold_state_lock_for_test(&self, entered: std::sync::mpsc::Sender<()>, release: std::sync::mpsc::Receiver<()>) -> JoinHandle<()> { + let shared = Arc::clone(&self.shared); + std::thread::spawn(move || { + let _g = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + let _ = entered.send(()); + let _ = release.recv_timeout(Duration::from_secs(5)); + }) + } + + pub(super) fn note(&self, key: u64) { + if key == 0 { return; } + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if !g.seen.insert(key) || g.closed || (g.writer_stopped && g.fallback_path.is_none()) { return; } + g.pending.push(key); + g.enqueued_seq += 1; + if matches!(g.pending.len(), 1 | BATCH_IMMEDIATE) { self.shared.wake_cv.notify_one(); } + } + + #[cfg(test)] + pub(super) fn noted(&self, key: u64) -> bool { self.shared.state.lock().unwrap_or_else(|e| e.into_inner()).seen.contains(&key) } + + #[allow(dead_code)] + pub(super) fn flush(&self) { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + let target = g.enqueued_seq; + if g.completed_seq >= target || g.writer_stopped { return; } + g.flush_now = true; + self.shared.wake_cv.notify_one(); + while g.completed_seq < target && !g.writer_stopped { + g = self.shared.flushed_cv.wait(g).unwrap_or_else(|e| e.into_inner()); + } + } + + pub(super) fn flush_bounded(&self, timeout: Duration) { + let deadline = Instant::now() + timeout; + let (path, batch, taken_pending, took_in_flight, in_flight_seq, drained_seq) = { + let Some(mut g) = lock_until(&self.shared.state, deadline) else { return }; + let target = g.enqueued_seq; + let has_unwritten_in_flight = !g.in_flight.is_empty() && !g.in_flight_fallback_written; + if g.completed_seq >= target || (g.writer_stopped && g.pending.is_empty() && !has_unwritten_in_flight) { + return; + } + if !g.writer_stopped { + g.flush_now = true; + self.shared.wake_cv.notify_one(); + while g.completed_seq < target && !g.writer_stopped { + let Some(rem) = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break }; + let (guard, res) = self.shared.flushed_cv.wait_timeout(g, rem).unwrap_or_else(|e| e.into_inner()); + g = guard; + if res.timed_out() { break; } + } + if g.completed_seq >= target { return; } + } + // Worker timed out (e.g. blocked on the Windows loader lock during ExitProcess) or + // stopped/failed to spawn: only drain when a file fallback exists so a non-file + // sink never loses pending keys or falsely advances `completed_seq`. + let Some(path) = g.fallback_path.clone() else { return }; + let mut took_in_flight = false; + let mut in_flight_seq = 0u64; + let mut batch = Vec::new(); + if !g.in_flight.is_empty() && !g.in_flight_fallback_written { + batch.extend_from_slice(&g.in_flight); + g.in_flight_fallback_written = true; + in_flight_seq = g.in_flight_seq; + took_in_flight = true; + } + let taken_pending = std::mem::take(&mut g.pending); + batch.extend_from_slice(&taken_pending); + if batch.is_empty() { return; } + let drained_seq = g.enqueued_seq; + (path, batch, taken_pending, took_in_flight, in_flight_seq, drained_seq) + }; + let mut buf = String::new(); + format_keys(&batch, &mut buf); + let wrote = append_to_path(&path, buf.as_bytes()); + if let Some(mut g) = lock_until(&self.shared.state, Instant::now() + Duration::from_millis(25)) { + if wrote { + g.completed_seq = g.completed_seq.max(drained_seq); + self.shared.flushed_cv.notify_all(); + } else { + if took_in_flight && g.in_flight_seq == in_flight_seq { + g.in_flight_fallback_written = false; + } + if !taken_pending.is_empty() && !g.closed { + let mut restored = taken_pending; + restored.extend_from_slice(&g.pending); + g.pending = restored; + if !g.writer_stopped { + self.shared.wake_cv.notify_one(); + } + } + } + } + } + + pub(super) fn shutdown(&self) { + { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + g.closed = true; + g.flush_now = true; + self.shared.wake_cv.notify_one(); + } + if let Some(h) = self.writer.lock().unwrap_or_else(|e| e.into_inner()).take() { + if h.thread().id() != std::thread::current().id() { let _ = h.join(); } + } else { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + while !g.writer_stopped { g = self.shared.flushed_cv.wait(g).unwrap_or_else(|e| e.into_inner()); } + } + let (fallback, batch, drained_seq) = { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + let mut batch = Vec::new(); + if !g.in_flight.is_empty() && !g.in_flight_fallback_written { + batch.extend(std::mem::take(&mut g.in_flight)); + g.in_flight_seq = 0; + g.in_flight_fallback_written = true; + } + batch.extend(std::mem::take(&mut g.pending)); + if batch.is_empty() { return; } + (g.fallback_path.clone(), batch, g.enqueued_seq) + }; + if let Some(path) = fallback { + let mut buf = String::new(); + format_keys(&batch, &mut buf); + if append_to_path(&path, buf.as_bytes()) { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + g.completed_seq = g.completed_seq.max(drained_seq); + self.shared.flushed_cv.notify_all(); + } + } + } + } + + impl Drop for Journal { + fn drop(&mut self) { + self.shutdown(); + } + } + + fn writer_loop(shared: &JournalShared, mut sink: Sink, coalesce: Duration) { + let _stop = StopGuard(shared); + let mut buf = String::new(); + loop { + let (batch, batch_seq) = { + let mut g = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + while g.pending.is_empty() && !g.closed { + if std::mem::take(&mut g.flush_now) { shared.flushed_cv.notify_all(); } + g = shared.wake_cv.wait(g).unwrap_or_else(|e| e.into_inner()); + } + if g.pending.is_empty() && g.closed { break; } + if !coalesce.is_zero() { + let deadline = Instant::now() + coalesce; + while g.pending.len() < BATCH_IMMEDIATE && !g.flush_now && !g.closed { + let Some(rem) = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break }; + let (guard, res) = shared.wake_cv.wait_timeout(g, rem).unwrap_or_else(|e| e.into_inner()); + g = guard; + if res.timed_out() { break; } + } + } + if g.pending.is_empty() { + if std::mem::take(&mut g.flush_now) { shared.flushed_cv.notify_all(); } + continue; + } + g.flush_now = false; + let batch = std::mem::take(&mut g.pending); + let batch_seq = g.enqueued_seq; + g.in_flight = batch.clone(); + g.in_flight_seq = batch_seq; + g.in_flight_fallback_written = false; + (batch, batch_seq) + }; + format_keys(&batch, &mut buf); + sink.write_batch(buf.as_bytes()); + { + let mut g = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + g.in_flight.clear(); + g.in_flight_seq = 0; + g.in_flight_fallback_written = false; + g.completed_seq = g.completed_seq.max(batch_seq); + } + shared.flushed_cv.notify_all(); + } + } struct Used { earlier: RwLock>, - now: Mutex<(HashSet, Option)>, + now: Journal, } /// The keys in a `used-pipelines.txt` (lines that are not a hexadecimal key are passed over). @@ -446,29 +803,55 @@ mod used { text.lines().filter_map(|l| u64::from_str_radix(l.trim(), 16).ok()).filter(|&k| k != 0).collect() } + static U: OnceLock = OnceLock::new(); + + extern "C" { + fn atexit(f: extern "C" fn()) -> std::ffi::c_int; + } + + extern "C" fn on_process_exit() { + shutdown(); + } + + fn init_from_path(path: PathBuf, coalesce: Duration) -> Used { + let earlier = parse(&read_used_bounded(&path, MAX_USED_FILE_BYTES)); + 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()); + } + let now = Journal::with_sink(earlier.clone(), Sink::LazyFile(path, None), coalesce); + unsafe { atexit(on_process_exit); } + Used { earlier: RwLock::new(earlier), now } + } + 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(HashSet::new()), now: Mutex::new((HashSet::new(), None)) }; - } - let path = crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"); - let earlier = parse(&std::fs::read_to_string(&path).unwrap_or_default()); - 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); + #[cfg(test)] + if let Some(p) = std::env::var_os("XCL_TEST_USED_STATIC_PATH") { + return init_from_path(PathBuf::from(p), Duration::from_secs(60)); + } + return Used { earlier: RwLock::new(HashSet::new()), now: Journal::in_memory(HashSet::new()) }; } - let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok(); - Used { now: Mutex::new((earlier.clone(), file)), earlier: RwLock::new(earlier) } + init_from_path(crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"), COALESCE_WINDOW) }) } + pub fn shutdown() { + if let Some(u) = U.get() { + u.now.shutdown(); + } + } + + pub fn flush_bounded(timeout: Duration) { + if let Some(u) = U.get() { + u.now.flush_bounded(timeout); + } + } + /// An earlier run used a pipeline of these shaders. pub fn known(key: u64) -> bool { - key != 0 && get().earlier.read().unwrap().contains(&key) + key != 0 && get().earlier.read().unwrap_or_else(|e| e.into_inner()).contains(&key) } /// A pipeline of these shaders is used now: kept for the next run. @@ -476,23 +859,18 @@ 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); } /// (tests) This run used a pipeline of these shaders. #[cfg(test)] pub fn noted(key: u64) -> bool { - get().now.lock().unwrap().0.contains(&key) + key != 0 && get().now.noted(key) } #[cfg(test)] pub fn earlier_run_used(key: u64) { - get().earlier.write().unwrap().insert(key); + get().earlier.write().unwrap_or_else(|e| e.into_inner()).insert(key); } } @@ -787,6 +1165,382 @@ mod used_tests { assert!(keys.contains(&0xff) && keys.contains(&0x1a2b)); } + #[test] + fn used_note_does_not_block_on_slow_writer() { + use std::{io::Write, time::Duration}; + struct Blocking(Option>, mpsc::Receiver<()>, Arc>>); + impl Write for Blocking { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if let Some(tx) = self.0.take() { let _ = tx.send(()); let _ = self.1.recv(); } + self.2.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { Ok(()) } + } + let ((entered_tx, entered_rx), (release_tx, release_rx)) = (mpsc::channel(), mpsc::channel()); + let out = Arc::new(Mutex::new(Vec::new())); + let j = used::Journal::with_writer(Box::new(Blocking(Some(entered_tx), release_rx, out.clone())), Duration::ZERO); + j.note(0x1111); + entered_rx.recv_timeout(Duration::from_secs(5)).expect("writer entered write_all"); + j.note(0x2222); + j.note(0x3333); + assert!(j.noted(0x1111) && j.noted(0x2222) && j.noted(0x3333), "note/noted must not block on writer I/O"); + release_tx.send(()).unwrap(); + j.flush(); + assert_eq!(used::parse(std::str::from_utf8(&out.lock().unwrap()).unwrap()), [0x1111, 0x2222, 0x3333].into()); + } + + #[test] + fn used_burst_coalesces_writes_and_deduplicates_keys() { + use std::{io::Write, time::Duration}; + struct Counting(Arc)>>); + impl Write for Counting { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let mut g = self.0.lock().unwrap(); + g.0 += 1; + g.1.extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { Ok(()) } + } + let rec = Arc::new(Mutex::new((0usize, Vec::new()))); + let j = used::Journal::with_writer(Box::new(Counting(rec.clone())), Duration::from_millis(500)); + for k in (0u64..=40).chain(0u64..=40) { j.note(k); } + j.flush(); + let (writes, bytes) = { let g = rec.lock().unwrap(); (g.0, g.1.clone()) }; + let text = String::from_utf8(bytes).unwrap(); + assert!((1..40).contains(&writes), "expected coalesced writes (< 40), got {writes}"); + assert_eq!(text.lines().count(), 40); + assert_eq!(used::parse(&text), (1u64..=40).collect()); + } + + #[test] + fn used_flush_drop_lazy_file_and_io_error_are_graceful() { + use std::{io::Write, time::Duration}; + let dir = std::env::temp_dir().join(format!("xcl-used-journal-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("nested").join("used-pipelines.txt"); + let j = used::Journal::with_file(path.clone(), Duration::from_secs(5)); + assert!(!dir.exists() && !path.exists(), "dir/file must open lazily on first batch write"); + j.note(0xAA01); + j.note(0xAA02); + j.flush(); + assert_eq!(used::parse(&std::fs::read_to_string(&path).unwrap()), [0xAA01, 0xAA02].into()); + j.note(0xAA03); + drop(j); + assert_eq!(used::parse(&std::fs::read_to_string(&path).unwrap()), [0xAA01, 0xAA02, 0xAA03].into()); + let _ = std::fs::remove_dir_all(&dir); + + struct Failing(Arc); + impl Write for Failing { + fn write(&mut self, _: &[u8]) -> std::io::Result { + self.0.fetch_add(1, Ordering::Relaxed); + Err(std::io::Error::other("disk full")) + } + fn flush(&mut self) -> std::io::Result<()> { Err(std::io::Error::other("disk full")) } + } + let attempts = Arc::new(AtomicUsize::new(0)); + let j = used::Journal::with_writer(Box::new(Failing(attempts.clone())), Duration::ZERO); + j.note(0xBAD1); + j.note(0xBAD2); + j.flush(); + j.note(0xBAD3); + j.flush(); + assert!(attempts.load(Ordering::Acquire) >= 1 && j.noted(0xBAD1) && j.noted(0xBAD2) && j.noted(0xBAD3)); + } + + #[test] + fn used_static_once_lock_flushes_on_process_exit() { + use std::time::{Duration, Instant}; + if let Some(path) = std::env::var_os("XCL_TEST_USED_STATIC_PATH") { + let mode = std::env::var("XCL_TEST_USED_EXIT_MODE").unwrap_or_default(); + match mode.as_str() { + "normal" => { + used::note(0xE001); + used::note(0xE002); + return; + } + "exit" => { + // On Windows, `std::process::exit` calls `ExitProcess` directly (bypassing CRT + // `atexit`), matching a title calling `ExitProcess`; `eh::install_crash_handler` + // routes `NtTerminateProcess` through `flush_used_bounded` before threads end. + crate::eh::install_crash_handler(); + used::note(0xE003); + std::process::exit(0); + } + "explicit" => { + used::note(0xE004); + shutdown_used(); + let text = std::fs::read_to_string(&path).expect("shutdown_used must flush before exit"); + assert_eq!(used::parse(&text), [0xE004].into()); + shutdown_used(); + flush_used_bounded(Duration::from_millis(50)); + return; + } + "bounded" => { + used::note(0xE005); + flush_used_bounded(Duration::from_secs(5)); + let text = std::fs::read_to_string(&path).expect("flush_used_bounded must flush before termination"); + assert_eq!(used::parse(&text), [0xE005].into()); + return; + } + other => panic!("unexpected mode {other}"), + } + } + let exe = std::env::current_exe().unwrap(); + let dir = std::env::temp_dir().join(format!("xcl-used-exit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for (mode, expected) in [ + ("normal", &[0xE001u64, 0xE002][..]), + ("exit", &[0xE003u64][..]), + ("explicit", &[0xE004u64][..]), + ("bounded", &[0xE005u64][..]), + ] { + let path = dir.join(mode).join("used-pipelines.txt"); + let start = Instant::now(); + let status = std::process::Command::new(&exe) + .args(["--exact", "hle::d3d12x::pso_async::used_tests::used_static_once_lock_flushes_on_process_exit", "--nocapture"]) + .env("XCL_TEST_USED_STATIC_PATH", &path) + .env("XCL_TEST_USED_EXIT_MODE", mode) + .status() + .unwrap(); + assert!(status.success(), "child ({mode}) failed: {status}"); + assert!(start.elapsed() < Duration::from_secs(10), "child ({mode}) waited for coalesce timer"); + let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("child ({mode}) lost keys on exit: {e}")); + assert_eq!(used::parse(&text), expected.iter().copied().collect(), "child ({mode}) keys mismatch"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn used_flush_bounded_timeout_and_spawn_failure_fallback_are_sound() { + use std::{io::Write, time::Duration}; + // 1. Slow writer finishing batch 1 after `flush_bounded` already drained batch 2 must not + // regress `completed_seq` below `enqueued_seq` (which would hang a later `flush()`). + struct BlockingOnce(Option>, mpsc::Receiver<()>, Option>, Arc>>); + impl Write for BlockingOnce { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if let Some(tx) = self.0.take() { + let _ = tx.send(()); + let _ = self.1.recv_timeout(Duration::from_secs(5)); + } + self.3.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + if let Some(tx) = self.2.take() { let _ = tx.send(()); } + Ok(()) + } + } + let ((entered_tx, entered_rx), (release_tx, release_rx), (wrote_tx, wrote_rx)) = (mpsc::channel(), mpsc::channel(), mpsc::channel()); + let out = Arc::new(Mutex::new(Vec::new())); + let j = Arc::new(used::Journal::with_writer(Box::new(BlockingOnce(Some(entered_tx), release_rx, Some(wrote_tx), out.clone())), Duration::ZERO)); + j.note(0xC001); + entered_rx.recv_timeout(Duration::from_secs(5)).expect("writer entered batch 1"); + j.note(0xC002); + j.flush_bounded(Duration::from_millis(20)); + release_tx.send(()).unwrap(); + wrote_rx.recv_timeout(Duration::from_secs(5)).expect("writer finished batch 1"); + std::thread::sleep(Duration::from_millis(25)); + let (done_tx, done_rx) = mpsc::channel(); + let j2 = Arc::clone(&j); + let flusher = std::thread::spawn(move || { j2.flush(); let _ = done_tx.send(()); }); + done_rx.recv_timeout(Duration::from_secs(5)).expect("flush() must not hang when completed_seq stays monotonic"); + flusher.join().unwrap(); + drop(j); + assert!(used::parse(std::str::from_utf8(&out.lock().unwrap()).unwrap()).contains(&0xC001)); + + // 2. When writer spawn fails (`writer_stopped == true` with `fallback_path`), `note()` + // still queues keys so `flush_bounded()` and `shutdown()` persist them directly. + let dir = std::env::temp_dir().join(format!("xcl-used-nospawn-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let p_bounded = dir.join("bounded").join("used-pipelines.txt"); + let j_b = used::Journal::without_writer(p_bounded.clone()); + j_b.note(0xF001); + j_b.note(0xF002); + j_b.flush_bounded(Duration::from_millis(20)); + assert_eq!(used::parse(&std::fs::read_to_string(&p_bounded).unwrap()), [0xF001, 0xF002].into()); + + let p_shutdown = dir.join("shutdown").join("used-pipelines.txt"); + let j_s = used::Journal::without_writer(p_shutdown.clone()); + j_s.note(0xF003); + j_s.shutdown(); + assert_eq!(used::parse(&std::fs::read_to_string(&p_shutdown).unwrap()), [0xF003].into()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn used_flush_bounded_respects_timeout_when_state_lock_is_held() { + use std::time::{Duration, Instant}; + let dir = std::env::temp_dir().join(format!("xcl-used-lock-bound-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("used-pipelines.txt"); + let j = used::Journal::with_file(path.clone(), Duration::from_secs(5)); + j.note(0xAA11); + + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let holder = j.hold_state_lock_for_test(entered_tx, release_rx); + entered_rx.recv_timeout(Duration::from_secs(5)).expect("holder acquired state lock"); + + let start = Instant::now(); + j.flush_bounded(Duration::from_millis(30)); + let elapsed = start.elapsed(); + assert!(elapsed < Duration::from_millis(250), "flush_bounded blocked past timeout while state lock was held ({elapsed:?})"); + + release_tx.send(()).unwrap(); + holder.join().unwrap(); + j.flush(); + assert_eq!(used::parse(&std::fs::read_to_string(&path).unwrap()), [0xAA11].into()); + drop(j); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn used_flush_bounded_persists_writer_in_flight_batch_and_preserves_non_fallback_pending() { + use std::{io::Write, time::Duration}; + struct BlockingOnce { + entered: Option>, + release: mpsc::Receiver<()>, + wrote: Option>, + out: Arc>>, + } + impl Write for BlockingOnce { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if let Some(tx) = self.entered.take() { + let _ = tx.send(()); + let _ = self.release.recv_timeout(Duration::from_secs(5)); + } + self.out.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + if let Some(tx) = self.wrote.take() { let _ = tx.send(()); } + Ok(()) + } + } + + let dir = std::env::temp_dir().join(format!("xcl-used-inflight-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + + // 1a. File-backed blocking sink: writer owns `0xB001` in-flight with `pending` empty. + let p_single = dir.join("single").join("used-pipelines.txt"); + let ((e_tx, e_rx), (r_tx, r_rx), (w_tx, w_rx)) = (mpsc::channel(), mpsc::channel(), mpsc::channel()); + let out_a = Arc::new(Mutex::new(Vec::new())); + let j_a = used::Journal::with_writer_and_fallback( + Box::new(BlockingOnce { entered: Some(e_tx), release: r_rx, wrote: Some(w_tx), out: Arc::clone(&out_a) }), + p_single.clone(), + Duration::ZERO, + ); + j_a.note(0xB001); + e_rx.recv_timeout(Duration::from_secs(5)).expect("writer took 0xB001 in-flight"); + j_a.flush_bounded(Duration::from_millis(20)); + assert_eq!( + used::parse(&std::fs::read_to_string(&p_single).expect("in-flight batch must persist on timeout")), + [0xB001].into(), + ); + r_tx.send(()).unwrap(); + w_rx.recv_timeout(Duration::from_secs(5)).expect("writer finished 0xB001"); + j_a.flush(); + drop(j_a); + + // 1b. File-backed blocking sink: writer owns `0xB001` in-flight AND `0xB002` is queued in `pending`. + let p_both = dir.join("both").join("used-pipelines.txt"); + let ((e_tx, e_rx), (r_tx, r_rx), (w_tx, w_rx)) = (mpsc::channel(), mpsc::channel(), mpsc::channel()); + let out_b = Arc::new(Mutex::new(Vec::new())); + let j_b = Arc::new(used::Journal::with_writer_and_fallback( + Box::new(BlockingOnce { entered: Some(e_tx), release: r_rx, wrote: Some(w_tx), out: Arc::clone(&out_b) }), + p_both.clone(), + Duration::ZERO, + )); + j_b.note(0xB001); + e_rx.recv_timeout(Duration::from_secs(5)).expect("writer took 0xB001 in-flight"); + j_b.note(0xB002); + j_b.flush_bounded(Duration::from_millis(20)); + assert_eq!( + used::parse(&std::fs::read_to_string(&p_both).expect("both in-flight and pending must persist")), + [0xB001, 0xB002].into(), + ); + r_tx.send(()).unwrap(); + w_rx.recv_timeout(Duration::from_secs(5)).expect("writer finished 0xB001"); + let (done_tx, done_rx) = mpsc::channel(); + let j_b2 = Arc::clone(&j_b); + let flusher = std::thread::spawn(move || { j_b2.flush(); let _ = done_tx.send(()); }); + done_rx.recv_timeout(Duration::from_secs(5)).expect("subsequent flush() must return promptly"); + flusher.join().unwrap(); + drop(j_b); + + // 2. Non-fallback `Sink::Writer`: timed-out `flush_bounded` must leave both `in_flight` and + // `pending` intact so the writer persists both keys once unblocked. + let ((e_tx, e_rx), (r_tx, r_rx), (w_tx, w_rx)) = (mpsc::channel(), mpsc::channel(), mpsc::channel()); + let out_nf = Arc::new(Mutex::new(Vec::new())); + let j_nf = used::Journal::with_writer( + Box::new(BlockingOnce { entered: Some(e_tx), release: r_rx, wrote: Some(w_tx), out: Arc::clone(&out_nf) }), + Duration::ZERO, + ); + j_nf.note(0xC001); + e_rx.recv_timeout(Duration::from_secs(5)).expect("writer took 0xC001 in-flight"); + j_nf.note(0xC002); + j_nf.flush_bounded(Duration::from_millis(20)); + r_tx.send(()).unwrap(); + w_rx.recv_timeout(Duration::from_secs(5)).expect("writer finished 0xC001"); + j_nf.flush(); + assert_eq!( + used::parse(std::str::from_utf8(&out_nf.lock().unwrap()).unwrap()), + [0xC001, 0xC002].into(), + "non-fallback flush_bounded must not drop pending 0xC002 or prematurely advance completed_seq", + ); + drop(j_nf); + + // 3. Panicking writer with `fallback_path`: `shutdown()` persists the panicked in-flight batch. + struct PanicOnce(Option>); + impl Write for PanicOnce { + fn write(&mut self, _: &[u8]) -> std::io::Result { + if let Some(tx) = self.0.take() { let _ = tx.send(()); } + panic!("simulated mid-batch writer panic"); + } + fn flush(&mut self) -> std::io::Result<()> { Ok(()) } + } + let p_panic = dir.join("panic").join("used-pipelines.txt"); + let (p_tx, p_rx) = mpsc::channel(); + let j_p = used::Journal::with_writer_and_fallback(Box::new(PanicOnce(Some(p_tx))), p_panic.clone(), Duration::ZERO); + j_p.note(0xD001); + p_rx.recv_timeout(Duration::from_secs(5)).expect("writer entered panicking write"); + j_p.shutdown(); + assert_eq!( + used::parse(&std::fs::read_to_string(&p_panic).expect("shutdown must drain panicked in-flight batch")), + [0xD001].into(), + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn used_bounded_read_caps_oversized_file_on_line_boundary() { + let dir = std::env::temp_dir().join(format!("xcl-used-read-bound-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // Cutting mid-way through line 2 ("5555666677778888\n") must drop the partial line so the + // truncated hex prefix ("55556666") is never parsed as a bogus key. + let p = dir.join("used-pipelines.txt"); + let content = "1111222233334444\n5555666677778888\n9999aaaabbbbcccc\n"; + std::fs::write(&p, content).unwrap(); + let capped = used::read_used_bounded(&p, 25); + assert_eq!(capped, "1111222233334444\n"); + assert_eq!(used::parse(&capped), [0x1111_2222_3333_4444].into()); + + // Cutting inside the very first line (no newline before cap) yields empty string. + assert!(used::read_used_bounded(&p, 8).is_empty()); + + // Exact-size file without trailing newline is not treated as truncated. + let p_exact = dir.join("exact.txt"); + std::fs::write(&p_exact, "1111222233334444").unwrap(); + let full = used::read_used_bounded(&p_exact, 16); + assert_eq!(used::parse(&full), [0x1111_2222_3333_4444].into()); + + let _ = std::fs::remove_dir_all(&dir); + } + /// A lazy pipeline of shaders an earlier run used is built without a bind; another one is /// built only at its first use, and that use is kept for the next run. #[test] diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 1f5d3f4970..5d85db63e9 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -144,6 +144,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::flush_used_bounded(std::time::Duration::from_millis(500)); crate::hle::d3d12x::real::end_title(0); }); } @@ -162,5 +163,6 @@ 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 }