From 502ddaefc2f300672e3141277be47c92dea39f1c Mon Sep 17 00:00:00 2001 From: Shawn Date: Sun, 29 Nov 2026 05:00:25 -0500 Subject: [PATCH] Add opt-in native DirectStorage staging for compressed reads --- Cargo.lock | 1 + crates/victory-hle/Cargo.toml | 1 + crates/victory-hle/src/modules/dstorage.rs | 462 ++++++++++++++++-- .../src/modules/dstorage/native_dstorage.rs | 85 ++++ tools/native-dstorage-bridge/.gitignore | 7 + tools/native-dstorage-bridge/README.md | 44 ++ .../SNAPSHOT_DIAGNOSTICS.md | 7 + tools/native-dstorage-bridge/bridge.cpp | 206 ++++++++ .../native-dstorage-bridge/budget_harness.rs | 37 ++ .../native-dstorage-bridge/missing_harness.rs | 8 + tools/native-dstorage-bridge/test_harness.rs | 1 + .../native-dstorage-bridge/timeout_harness.rs | 22 + 12 files changed, 844 insertions(+), 37 deletions(-) create mode 100644 crates/victory-hle/src/modules/dstorage/native_dstorage.rs create mode 100644 tools/native-dstorage-bridge/.gitignore create mode 100644 tools/native-dstorage-bridge/README.md create mode 100644 tools/native-dstorage-bridge/SNAPSHOT_DIAGNOSTICS.md create mode 100644 tools/native-dstorage-bridge/bridge.cpp create mode 100644 tools/native-dstorage-bridge/budget_harness.rs create mode 100644 tools/native-dstorage-bridge/missing_harness.rs create mode 100644 tools/native-dstorage-bridge/test_harness.rs create mode 100644 tools/native-dstorage-bridge/timeout_harness.rs diff --git a/Cargo.lock b/Cargo.lock index 09b77bc83..84668f6b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -701,6 +701,7 @@ dependencies = [ "opus-pure", "tempfile", "tracing", + "tracing-subscriber", "victory-core", "victory-formats", "victory-gpu", diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index b645ab710..069c18b46 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -64,6 +64,7 @@ windows-core = { workspace = true } [dev-dependencies] tempfile.workspace = true +tracing-subscriber.workspace = true # Tests read our command line back as the host does (`CommandLineToArgvW`). [target.'cfg(windows)'.dev-dependencies] diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 7a205125e..0dad37162 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -418,6 +418,8 @@ fn source_path(request: &Request) -> &str { &unsafe { &*request.source.cast::>() }.state.name } +mod native_dstorage; + /// How files are read (`VICTORY_DSTORAGE_IO`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Io { @@ -430,6 +432,8 @@ enum Io { Overlapped, /// `direct`: a handle for each worker, past the host's file cache. Direct, + /// `windows`: experimental PC DirectStorage, with Win32 fallback. + Windows, } impl Io { @@ -441,6 +445,7 @@ impl Io { Ok("handles") => Io::Handles, Ok("overlapped") => Io::Overlapped, Ok("direct") => Io::Direct, + Ok("windows") => Io::Windows, _ => Io::DEFAULT, }; tracing::info!(?io, "dstorage: how files are read (VICTORY_DSTORAGE_IO)"); @@ -457,6 +462,7 @@ struct Files { first: std::fs::File, others: Box<[OnceLock>]>, io: Io, + native: OnceLock>, } impl Files { @@ -465,9 +471,9 @@ impl Files { let others = match io { Io::One => 0, Io::Overlapped => 1, - Io::Handles | Io::Direct => workers, + Io::Handles | Io::Direct | Io::Windows => workers, }; - Files { first, others: (0..others).map(|_| OnceLock::new()).collect(), io } + Files { first, others: (0..others).map(|_| OnceLock::new()).collect(), io, native: OnceLock::new() } } #[cfg(test)] @@ -475,11 +481,93 @@ impl Files { Files::new(std::fs::File::open(path).unwrap(), io) } - /// Reads at `offset`; as [`FileExt::seek_read`]. + /// Only Vec-owned host staging may be passed to the native bridge. + fn read_owned_at(&self, out: &mut Vec, done: usize, offset: u64) -> std::io::Result { + // Match the bridge's per-request staging cap. Route larger reads + // straight to Win32 instead of logging a native allocation failure. + const MAX_NATIVE_REQUEST: usize = 16 * 1024 * 1024; + let remaining = &mut out[done..]; + if self.io == Io::Windows && remaining.len() > MAX_NATIVE_REQUEST { + static ANNOUNCED: AtomicBool = AtomicBool::new(false); + if !ANNOUNCED.swap(true, Ordering::Relaxed) { + tracing::info!(size = remaining.len(), max = MAX_NATIVE_REQUEST, + "dstorage: staging request exceeds native limit; using Win32"); + } + return self.read_at(remaining, offset); + } + let native = if self.io == Io::Windows { + self.native.get_or_init(|| { + let native = native_dstorage::NativeFile::open(&self.first); + if native.is_none() { + static WARNED: AtomicBool = AtomicBool::new(false); + if !WARNED.swap(true, Ordering::Relaxed) { + tracing::warn!("dstorage: native bridge unavailable; using Win32 reads"); + } + } else { + static ANNOUNCED: AtomicBool = AtomicBool::new(false); + if !ANNOUNCED.swap(true, Ordering::Relaxed) { + if let Some((slots, wait_ms, staging_bytes)) = native.as_ref().and_then(|file| file.limits()) { + tracing::info!(slots, wait_ms, staging_bytes, + "dstorage: native bridge initialized for owned compressed-source staging; raw guest reads remain Win32"); + } else { + tracing::info!("dstorage: native bridge initialized; effective limits unavailable from this bridge"); + } + } + } + native + }).as_ref() + } else { None }; + if let Some(native) = native { + NATIVE_READ_ATTEMPTS.fetch_add(1, Ordering::Relaxed); + match native.read(remaining, offset) { + Ok(count) => { + if NATIVE_READ_SUCCESSES.fetch_add(1, Ordering::Relaxed) == 0 { + tracing::info!("dstorage: first native staging read succeeded"); + } + log_native_completion(); + return Ok(count); + } + Err(hr) => { + NATIVE_READ_FALLBACKS.fetch_add(1, Ordering::Relaxed); + match hr as u32 { + // HRESULT_FROM_WIN32(ERROR_BUSY): the native concurrency limit is full. + 0x8007_00aa => { + if NATIVE_READ_BUSY.fetch_add(1, Ordering::Relaxed) == 0 { + tracing::info!("dstorage: native staging busy; using Win32 fallback while slots are full"); + } + } + // HRESULT_FROM_WIN32(ERROR_TIMEOUT): bridge disabled itself and quarantined the request. + 0x8007_05b4 => { + if NATIVE_READ_TIMEOUTS.fetch_add(1, Ordering::Relaxed) == 0 { + tracing::warn!(hr, "dstorage: native staging timed out; disabling native reads and using Win32"); + } + } + // E_ABORT can mean either disabled after timeout or a runtime cancellation. + 0x8000_4004 => { + if NATIVE_READ_ABORTS.fetch_add(1, Ordering::Relaxed) == 0 { + tracing::warn!(hr, "dstorage: native staging aborted or disabled; using Win32 reads"); + } + } + _ => { + if NATIVE_READ_ERRORS.fetch_add(1, Ordering::Relaxed) == 0 { + tracing::warn!(hr, "dstorage: native staging read failed; retrying with Win32 reads"); + } + } + } + } + } + } + if native.is_some() { + log_native_completion(); + } + self.read_at(remaining, offset) + } + + /// Reads guest destinations through the original retryable Win32 path. fn read_at(&self, out: &mut [u8], offset: u64) -> std::io::Result { use windows_sys::Win32::Storage::FileSystem::{FILE_FLAG_NO_BUFFERING, FILE_FLAG_OVERLAPPED}; let flags = match self.io { - Io::One | Io::Handles => 0, + Io::One | Io::Handles | Io::Windows => 0, Io::Overlapped => FILE_FLAG_OVERLAPPED, Io::Direct => FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, }; @@ -1293,12 +1381,35 @@ impl Lanes { if elapsed.as_secs() >= 5 { let waiting: usize = self.lanes.values().map(|l| l.reads.len()).sum(); let reading = READING.swap(0, Ordering::Relaxed) as f64 / 1e9; + let native_attempts = NATIVE_READ_ATTEMPTS.load(Ordering::Relaxed); + if native_attempts != 0 { + static REPORT_TICKS: AtomicU64 = AtomicU64::new(0); + if REPORT_TICKS.fetch_add(1, Ordering::Relaxed) % 12 == 0 { + tracing::info!(native_staging_attempts_total = native_attempts, + native_staging_successes_total = NATIVE_READ_SUCCESSES.load(Ordering::Relaxed), + native_staging_fallbacks_total = NATIVE_READ_FALLBACKS.load(Ordering::Relaxed), + native_staging_busy_total = NATIVE_READ_BUSY.load(Ordering::Relaxed), + native_staging_timeouts_total = NATIVE_READ_TIMEOUTS.load(Ordering::Relaxed), + native_staging_aborts_total = NATIVE_READ_ABORTS.load(Ordering::Relaxed), + native_staging_errors_total = NATIVE_READ_ERRORS.load(Ordering::Relaxed), + guest_win32_reads_total = GUEST_WIN32_READS.load(Ordering::Relaxed), + "dstorage: native bridge counters"); + } + } tracing::debug!( requests = *requests, mb_per_s = format_args!("{:.1}", *bytes as f64 / elapsed.as_secs_f64() / 1e6), busy_workers = format_args!("{:.2}", busy.as_secs_f64() / elapsed.as_secs_f64()), reading_workers = format_args!("{:.2}", reading / elapsed.as_secs_f64()), staging_waits = std::mem::take(&mut self.refused), + native_staging_attempts_total = NATIVE_READ_ATTEMPTS.load(Ordering::Relaxed), + native_staging_successes_total = NATIVE_READ_SUCCESSES.load(Ordering::Relaxed), + native_staging_fallbacks_total = NATIVE_READ_FALLBACKS.load(Ordering::Relaxed), + native_staging_busy_total = NATIVE_READ_BUSY.load(Ordering::Relaxed), + native_staging_timeouts_total = NATIVE_READ_TIMEOUTS.load(Ordering::Relaxed), + native_staging_aborts_total = NATIVE_READ_ABORTS.load(Ordering::Relaxed), + native_staging_errors_total = NATIVE_READ_ERRORS.load(Ordering::Relaxed), + guest_win32_reads_total = GUEST_WIN32_READS.load(Ordering::Relaxed), bcpack_mb = self.bcpack.0 / 1_000_000, bcpack_workers = format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()), waiting, @@ -2256,7 +2367,7 @@ fn read_source(request: &Request) -> Result { return Ok(Held::Borrowed(bytes)); } let mut bytes = Scratch::zeroed(size); - read_into(request, &mut bytes)?; + read_into_owned(request, &mut bytes.bytes)?; Ok(Held::Scratch(bytes)) } @@ -2434,53 +2545,83 @@ impl Drop for Scratch { /// Nanoseconds workers spent reading files, for the debug summary. static READING: AtomicU64 = AtomicU64::new(0); +static NATIVE_READ_ATTEMPTS: AtomicU64 = AtomicU64::new(0); +static NATIVE_READ_COMPLETED: AtomicU64 = AtomicU64::new(0); +static NATIVE_READ_SUCCESSES: AtomicU64 = AtomicU64::new(0); +static NATIVE_READ_FALLBACKS: AtomicU64 = AtomicU64::new(0); +static NATIVE_READ_BUSY: AtomicU64 = AtomicU64::new(0); +static NATIVE_READ_TIMEOUTS: AtomicU64 = AtomicU64::new(0); +static NATIVE_READ_ABORTS: AtomicU64 = AtomicU64::new(0); +static NATIVE_READ_ERRORS: AtomicU64 = AtomicU64::new(0); +static GUEST_WIN32_READS: AtomicU64 = AtomicU64::new(0); + +// Native attempts, rather than storage-job completions, trigger snapshots. +// Counter reads are approximate under concurrency and may include in-flight work. +fn log_native_completion() { + let completed = NATIVE_READ_COMPLETED.fetch_add(1, Ordering::Relaxed) + 1; + if matches!(completed, 1 | 16 | 64 | 256 | 1024 | 4096) || (completed >= 8192 && completed % 8192 == 0) { + tracing::info!(native_completed_total = completed, + native_attempts_total = NATIVE_READ_ATTEMPTS.load(Ordering::Relaxed), + native_successes_total = NATIVE_READ_SUCCESSES.load(Ordering::Relaxed), + native_fallbacks_total = NATIVE_READ_FALLBACKS.load(Ordering::Relaxed), + native_busy_total = NATIVE_READ_BUSY.load(Ordering::Relaxed), + native_timeouts_total = NATIVE_READ_TIMEOUTS.load(Ordering::Relaxed), + native_aborts_total = NATIVE_READ_ABORTS.load(Ordering::Relaxed), + native_errors_total = NATIVE_READ_ERRORS.load(Ordering::Relaxed), + guest_win32_reads_total = GUEST_WIN32_READS.load(Ordering::Relaxed), + "dstorage: native completed-attempt snapshot"); + } +} /// How often a read the host refuses is tried again (about 0.25 s in all). const READ_RETRIES: u32 = 8; -/// Fills `out` (the source size) from the request's file or memory. +/// Only the owned Vec branch is eligible for the native bridge. Guest +/// destinations retain the existing Win32 guarded-memory retry behavior. +enum ReadBuffer<'a> { Guest(&'a mut [u8]), Owned(&'a mut Vec) } +impl ReadBuffer<'_> { + fn slice(&mut self) -> &mut [u8] { + match self { Self::Guest(out) => out, Self::Owned(out) => out.as_mut_slice() } + } +} fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { + read_into_buffer(request, ReadBuffer::Guest(out)) +} +fn read_into_owned(request: &Request, out: &mut Vec) -> Result<(), HRESULT> { + read_into_buffer(request, ReadBuffer::Owned(out)) +} +fn read_into_buffer(request: &Request, mut out: ReadBuffer<'_>) -> Result<(), HRESULT> { if request.options & MEMORY_SOURCE != 0 { - // SAFETY: the title's source holds `out.len()` bytes until completion. - out.copy_from_slice(unsafe { std::slice::from_raw_parts(request.source.cast(), out.len()) }); + let bytes = out.slice(); + // SAFETY: the title's source holds `bytes.len()` bytes until completion. + bytes.copy_from_slice(unsafe { std::slice::from_raw_parts(request.source.cast(), bytes.len()) }); return Ok(()); } // SAFETY: a file object we created; the title keeps it open. - let files = &unsafe { &*request.source.cast::>() } - .state - .files; + let files = &unsafe { &*request.source.cast::>() }.state.files; let started = std::time::Instant::now(); let (mut done, mut tries) = (0, 0); + let len = out.slice().len(); let result = loop { - if done == out.len() { - break Ok(()); - } - let error = match files.read_at(&mut out[done..], request.offset + done as u64) { - Ok(0) => break Err(END_OF_FILE), - Ok(n) => { - done += n; - continue; + if done == len { break Ok(()); } + let read = match &mut out { + ReadBuffer::Guest(bytes) => { + GUEST_WIN32_READS.fetch_add(1, Ordering::Relaxed); + files.read_at(&mut bytes[done..], request.offset + done as u64) } + ReadBuffer::Owned(bytes) => files.read_owned_at(bytes, done, request.offset + done as u64), + }; + let error = match read { + Ok(0) => break Err(END_OF_FILE), + Ok(n) => { done += n; continue; } Err(error) => error, }; - // Title memory the GPU side guards again in the moment between our - // opening it and the kernel's write fails the read (and a busy host - // can refuse one): opened again and tried again, since the title - // never learns of a failed read. - tracing::warn!( - %error, - offset = request.offset, - size = out.len(), - done, - tries, - "dstorage: a read of the file failed" - ); - if tries == READ_RETRIES { - break Err(from_win32(&error)); - } + tracing::warn!(%error, offset = request.offset, size = len, done, tries, + "dstorage: a read of the file failed"); + if tries == READ_RETRIES { break Err(from_win32(&error)); } std::thread::sleep(std::time::Duration::from_millis(1 << tries)); tries += 1; - victory_gpu::kernel_will_write(out.as_ptr() as usize + done, out.len() - done); + victory_gpu::kernel_will_write(out.slice().as_ptr() as usize + done, len - done); }; READING.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); result @@ -3286,7 +3427,7 @@ mod tests { seed }; for round in 0..2 { - for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct] { + for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct, Io::Windows] { let file = Files::open_for_test(&path, mode); let at: Vec = (0..READS).map(|_| (random() % (len - SIZE as u64)) & !15).collect(); for pass in ["cold", "again"] { @@ -3371,7 +3512,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("data.bin"); std::fs::write(&path, &plain).unwrap(); - for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct] { + for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct, Io::Windows] { let file = Files::open_for_test(path.to_str().unwrap(), mode); for (at, len) in [(0, 4096), (1, 100), (4095, 2), (8192, 200_000), (12_345, 250_000), (299_990, 11), (300_000, 1)] { let mut out = vec![0u8; len]; @@ -3390,6 +3531,253 @@ mod tests { } } + /// Exercises the real dispatch with the optional native runtime available. + #[test] + #[ignore = "requires experimental bridge and Microsoft runtime beside test executable"] + fn native_dispatch_reads_and_falls_back_on_end_of_file() { + let data = pattern(300_001); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("native-data.bin"); + std::fs::write(&path, &data).unwrap(); + let file = Files::open_for_test(path.to_str().unwrap(), Io::Windows); + assert!(file.native.get().is_none(), "native must open lazily"); + let mut valid = vec![0u8; 100]; + assert_eq!(file.read_owned_at(&mut valid, 0, 239).unwrap(), valid.len()); + assert!(file.native.get().is_some_and(Option::is_some), "native bridge did not load"); + assert_eq!(&valid[..], &data[239..339]); + let mut eof = vec![0u8; 16]; + assert_eq!(file.read_owned_at(&mut eof, 0, 299_999).unwrap(), 2); + assert_eq!(&eof[..2], &data[299_999..]); + assert_eq!(file.read_owned_at(&mut eof, 0, 300_001).unwrap(), 0); + } + + #[test] + fn oversized_native_staging_request_reads_through_win32() { + let data = pattern(16 * 1024 * 1024 + 1); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("oversized-staging.bin"); + std::fs::write(&path, &data).unwrap(); + let file = Files::open_for_test(path.to_str().unwrap(), Io::Windows); + let mut actual = vec![0; data.len()]; + assert_eq!(file.read_owned_at(&mut actual, 0, 0).unwrap(), data.len()); + assert!(actual == data, "Win32 read changed the bytes"); + assert!(file.native.get().is_none(), "oversized read must not open the native bridge"); + } + + #[test] + #[ignore = "requires experimental bridge and Microsoft runtime beside test executable"] + fn native_dispatch_concurrent_reads_match() { + let data = pattern(1_000_000); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("native-concurrent.bin"); + std::fs::write(&path, &data).unwrap(); + let file = Files::open_for_test(path.to_str().unwrap(), Io::Windows); + assert!(file.native.get().is_none(), "native must open lazily"); + std::thread::scope(|scope| { + for worker in 0..4usize { + let file = &file; + let data = &data; + scope.spawn(move || { + for i in 0..50 { + let at = worker * 50_000 + i * 239; + let mut actual = vec![0; 8193]; + assert_eq!(file.read_owned_at(&mut actual, 0, at as u64).unwrap(), actual.len()); + assert_eq!(&actual[..], &data[at..at + actual.len()]); + } + }); + } + }); + assert!(file.native.get().is_some_and(Option::is_some), "native bridge did not load"); + } + + #[test] + #[ignore = "requires test-only simulated-stall bridge, never use in production"] + fn native_dispatch_falls_back_after_simulated_stall() { + let path = std::env::temp_dir().join(format!("victory-files-timeout-{}", std::process::id())); + let data = pattern(300_001); + std::fs::write(&path, &data).unwrap(); + println!("FILE={}", path.display()); + let file = Files::open_for_test(path.to_str().unwrap(), Io::Windows); + assert!(file.native.get().is_none(), "native must open lazily"); + let mut actual = vec![0u8; 100]; + let start = std::time::Instant::now(); + assert_eq!(file.read_owned_at(&mut actual, 0, 239).unwrap(), 100); + assert!(start.elapsed().as_millis() >= 90 && start.elapsed().as_secs() < 3); + assert!(file.native.get().is_some_and(Option::is_some), "test bridge did not load"); + assert_eq!(&actual[..], &data[239..339]); + let start = std::time::Instant::now(); + assert_eq!(file.read_owned_at(&mut actual, 0, 239).unwrap(), 100); + assert!(start.elapsed().as_millis() < 90, "native must disable after a timeout"); + assert_eq!(&actual[..], &data[239..339]); + let reopened = Files::open_for_test(path.to_str().unwrap(), Io::Windows); + assert!(reopened.native.get().is_none(), "native must open lazily"); + assert_eq!(reopened.read_owned_at(&mut actual, 0, 239).unwrap(), 100); + assert!(reopened.native.get().is_some_and(Option::is_none), "new native opens must stop after a timeout"); + assert_eq!(&actual[..], &data[239..339]); + // The process invoking this test cleans up after exit; the quarantine + // intentionally retains the file while a queued request may be live. + } + + #[test] + #[ignore = "requires bridge and VICTORY_DSTORAGE_IO=windows in a fresh test process"] + fn native_only_reads_owned_compressed_source() { + let plain = pattern(80_000); + let packed = compress_zlib(&plain); + let mut contents = plain.clone(); + contents.extend_from_slice(&packed); + let (_dir, source) = file_with(&contents); + let files = &unsafe { &*source.cast::>() }.state.files; + assert!(files.native.get().is_none(), "raw-only file must not open native bridge"); + let attempts = NATIVE_READ_ATTEMPTS.load(Ordering::Relaxed); + let guest_reads = GUEST_WIN32_READS.load(Ordering::Relaxed); + let mut raw = vec![0u8; 1000]; + let r = request(0, raw.as_mut_ptr().cast(), raw.len(), source, 5000, raw.len()); + assert_eq!(execute(&r), Ok(())); + assert_eq!(&raw[..], &plain[5000..6000]); + assert_eq!(NATIVE_READ_ATTEMPTS.load(Ordering::Relaxed), attempts, + "raw guest destination must never use native memcpy"); + assert!(GUEST_WIN32_READS.load(Ordering::Relaxed) > guest_reads); + assert!(files.native.get().is_none(), "raw guest read must not initialize native bridge"); + let mut inflated = vec![0u8; plain.len()]; + let r = request(ZLIB, inflated.as_mut_ptr().cast(), inflated.len(), source, + plain.len() as u64, packed.len()); + let successes = NATIVE_READ_SUCCESSES.load(Ordering::Relaxed); + assert_eq!(execute(&r), Ok(())); + assert_eq!(inflated, plain); + assert!(files.native.get().is_some_and(Option::is_some), "native bridge not loaded"); + assert!(NATIVE_READ_ATTEMPTS.load(Ordering::Relaxed) > attempts); + assert!(NATIVE_READ_SUCCESSES.load(Ordering::Relaxed) > successes, + "compressed owned source must actually use native reads"); + } + + #[test] + #[ignore = "requires test-only busy-then-fail bridge, never use in production"] + fn native_busy_does_not_hide_later_failures() { + use std::io::Write; + use std::sync::{Arc, Mutex}; + #[derive(Clone)] + struct Sink(Arc>>); + impl Write for Sink { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().write(bytes) + } + fn flush(&mut self) -> std::io::Result<()> { Ok(()) } + } + let captured = Arc::new(Mutex::new(Vec::new())); + let writer = captured.clone(); + let subscriber = tracing_subscriber::fmt().without_time().with_ansi(false) + .with_max_level(tracing::Level::INFO).with_writer(move || Sink(writer.clone())).finish(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("native-errors.bin"); + let data = pattern(4096); + std::fs::write(&path, &data).unwrap(); + let file = Files::open_for_test(path.to_str().unwrap(), Io::Windows); + let before = [NATIVE_READ_BUSY.load(Ordering::Relaxed), NATIVE_READ_ERRORS.load(Ordering::Relaxed), + NATIVE_READ_TIMEOUTS.load(Ordering::Relaxed), NATIVE_READ_ABORTS.load(Ordering::Relaxed), + NATIVE_READ_FALLBACKS.load(Ordering::Relaxed)]; + tracing::subscriber::with_default(subscriber, || { + for _ in 0..4 { + let mut out = vec![0; 100]; + assert_eq!(file.read_owned_at(&mut out, 0, 239).unwrap(), 100); + assert_eq!(&out[..], &data[239..339]); + } + }); + assert!(file.native.get().is_some_and(Option::is_some)); + let after = [NATIVE_READ_BUSY.load(Ordering::Relaxed), NATIVE_READ_ERRORS.load(Ordering::Relaxed), + NATIVE_READ_TIMEOUTS.load(Ordering::Relaxed), NATIVE_READ_ABORTS.load(Ordering::Relaxed), + NATIVE_READ_FALLBACKS.load(Ordering::Relaxed)]; + assert_eq!(after, [before[0]+1, before[1]+1, before[2]+1, before[3]+1, before[4]+4]); + let log = String::from_utf8(captured.lock().unwrap().clone()).unwrap(); + assert!(log.contains("INFO") && log.contains("native staging busy"), "{log}"); + assert!(log.contains("WARN") && log.contains("native staging read failed"), "{log}"); + assert!(log.contains("WARN") && log.contains("native staging timed out"), "{log}"); + assert!(log.contains("WARN") && log.contains("native staging aborted or disabled"), "{log}"); + } + + #[test] + #[ignore = "synthetic cache-hot native-read benchmark; requires native bridge"] + fn native_staging_saturation_benchmark() { + use std::sync::{Arc, Barrier, Mutex}; + let data = pattern(4 * 1024 * 1024); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("native-bench.bin"); + std::fs::write(&path, &data).unwrap(); + let file = Files::open_for_test(path.to_str().unwrap(), Io::Windows); + let barrier = Arc::new(Barrier::new(13)); + let durations = Mutex::new(Vec::with_capacity(1200)); + let started = std::time::Instant::now(); + std::thread::scope(|scope| { + for worker in 0..12usize { + let file = &file; + let data = &data; + let durations = &durations; + let barrier = barrier.clone(); + scope.spawn(move || { + let mut out = vec![0; 65_536]; + barrier.wait(); + for i in 0..100usize { + let at = (worker * 71_113 + i * 47_119) % (data.len() - out.len()); + let start = std::time::Instant::now(); + assert_eq!(file.read_owned_at(&mut out, 0, at as u64).unwrap(), out.len()); + durations.lock().unwrap().push(start.elapsed().as_micros() as u64); + assert_eq!(&out[..], &data[at..at+out.len()]); + } + }); + } + barrier.wait(); + }); + let elapsed_ms = started.elapsed().as_millis(); + let mut samples = durations.into_inner().unwrap(); + samples.sort_unstable(); + assert_eq!(samples.len(), 1200); + assert!(file.native.get().is_some_and(Option::is_some), "native bridge unavailable"); + println!("BENCH elapsed_ms={elapsed_ms} p50_us={} p95_us={} attempts={} success={} busy={} other_errors={}", + samples[600], samples[1140], NATIVE_READ_ATTEMPTS.load(Ordering::Relaxed), + NATIVE_READ_SUCCESSES.load(Ordering::Relaxed), NATIVE_READ_BUSY.load(Ordering::Relaxed), + NATIVE_READ_ERRORS.load(Ordering::Relaxed)); + } + + #[test] + #[ignore = "requires native bridge in a fresh test process"] + fn native_snapshots_and_effective_limits_are_reported() { + use std::io::Write; + use std::sync::{Arc, Mutex}; + #[derive(Clone)] + struct Sink(Arc>>); + impl Write for Sink { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().write(bytes) + } + fn flush(&mut self) -> std::io::Result<()> { Ok(()) } + } + let captured = Arc::new(Mutex::new(Vec::new())); + let writer = captured.clone(); + let subscriber = tracing_subscriber::fmt().without_time().with_ansi(false) + .with_max_level(tracing::Level::INFO).with_writer(move || Sink(writer.clone())).finish(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("native-snapshots.bin"); + let data = pattern(4096); + std::fs::write(&path, &data).unwrap(); + let file = Files::open_for_test(path.to_str().unwrap(), Io::Windows); + tracing::subscriber::with_default(subscriber, || { + for _ in 0..256 { + let mut out = vec![0; 100]; + assert_eq!(file.read_owned_at(&mut out, 0, 239).unwrap(), 100); + assert_eq!(&out[..], &data[239..339]); + } + }); + assert!(file.native.get().is_some_and(Option::is_some)); + let log = String::from_utf8(captured.lock().unwrap().clone()).unwrap(); + for threshold in [1, 16, 64, 256] { + assert!(log.contains(&format!("native_completed_total={threshold}")), "{log}"); + } + if std::env::var("VICTORY_DS_EXPECT_LIMITS").as_deref() == Ok("1") { + assert!(log.contains("slots=12") && log.contains("wait_ms=0") && log.contains("staging_bytes=67108864"), "{log}"); + } else { + assert!(log.contains("effective limits unavailable"), "{log}"); + } + } + /// Lanes without workers: what `start` picks, and when statuses land. fn lanes(staging: u64) -> Lanes { Lanes { diff --git a/crates/victory-hle/src/modules/dstorage/native_dstorage.rs b/crates/victory-hle/src/modules/dstorage/native_dstorage.rs new file mode 100644 index 000000000..d69afe60b --- /dev/null +++ b/crates/victory-hle/src/modules/dstorage/native_dstorage.rs @@ -0,0 +1,85 @@ +//! Optional native PC DirectStorage file-to-memory bridge. Fails closed to Win32. +//! The DLLs are never loaded unless VICTORY_DSTORAGE_IO=windows is selected. +use std::{ffi::{c_char, c_void}, fs::File, os::windows::{ffi::OsStrExt, io::AsRawHandle}, sync::OnceLock}; + +type Open = unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> i32; +type Read = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, u64) -> i32; +type Close = unsafe extern "system" fn(*mut c_void); +type Limits = unsafe extern "system" fn(*mut u32, *mut u32, *mut u64); +struct Api { open: Open, read: Read, close: Close, limits: Option } +#[link(name="kernel32")] +unsafe extern "system" { + fn LoadLibraryExW(path: *const u16, file: *mut c_void, flags: u32) -> *mut c_void; + fn GetProcAddress(module: *mut c_void, name: *const c_char) -> *const c_void; +} +fn api() -> Option<&'static Api> { + static API: OnceLock> = OnceLock::new(); + API.get_or_init(|| { + let path = std::env::current_exe().ok()?.parent()?.join("victory-dstorage-bridge.dll"); + let wide: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); + // Absolute path plus restricted search for its dependencies; module is + // deliberately retained for process lifetime, including thread locals. + let lib = unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), 0x100 | 0x1000) }; + if lib.is_null() { return None; } + let open = unsafe { GetProcAddress(lib, c"victory_ds_open".as_ptr()) }; + let read = unsafe { GetProcAddress(lib, c"victory_ds_read".as_ptr()) }; + let close = unsafe { GetProcAddress(lib, c"victory_ds_close".as_ptr()) }; + if open.is_null() || read.is_null() || close.is_null() { return None; } + let limits = unsafe { GetProcAddress(lib, c"victory_ds_get_limits".as_ptr()) }; + Some(Api { + open: unsafe { std::mem::transmute::<*const c_void, Open>(open) }, + read: unsafe { std::mem::transmute::<*const c_void, Read>(read) }, + close: unsafe { std::mem::transmute::<*const c_void, Close>(close) }, + limits: if limits.is_null() { None } else { Some(unsafe { std::mem::transmute::<*const c_void, Limits>(limits) }) }, + }) + }).as_ref() +} + +pub(super) struct NativeFile { context: *mut c_void, api: &'static Api } +// The bridge owns a reference to the DirectStorage file object. Its per-thread +// queues and status buffers are independent, and a shared borrow keeps this +// context alive until every synchronous read has completed. +unsafe impl Send for NativeFile {} +unsafe impl Sync for NativeFile {} +impl NativeFile { + pub(super) fn open(file: &File) -> Option { + let api=api()?; let mut context=std::ptr::null_mut(); + let result=unsafe { (api.open)(file.as_raw_handle().cast(), &mut context) }; + (result >= 0 && !context.is_null()).then_some(Self { context, api }) + } + pub(super) fn limits(&self) -> Option<(u32, u32, u64)> { + let limits = self.api.limits?; + let (mut slots, mut wait_ms, mut staging_bytes) = (0, 0, 0); + unsafe { limits(&mut slots, &mut wait_ms, &mut staging_bytes) }; + Some((slots, wait_ms, staging_bytes)) + } + pub(super) fn read(&self, output: &mut [u8], offset: u64) -> Result { + let len=u32::try_from(output.len()).map_err(|_| -1)?; + // Pending native writes target bridge-owned staging, never this output. + // The bridge copies into this slice only after successful completion. + let hr=unsafe { (self.api.read)(self.context, output.as_mut_ptr().cast(), len, offset) }; + if hr < 0 { Err(hr) } else { Ok(output.len()) } + } +} +impl Drop for NativeFile { fn drop(&mut self) { unsafe { (self.api.close)(self.context) } } } + +#[cfg(test)] +mod tests { + use super::*; + use std::{io::Write, sync::Arc}; + #[test] + #[ignore = "requires the experimental bridge and Microsoft runtime DLLs beside the test executable"] + fn native_byte_parity_and_eof() { + let path=std::env::temp_dir().join(format!("victory-ds-test-{}", std::process::id())); + let src: Vec=(0..1_000_000u32).map(|x| ((x*17+(x>>9))&255) as u8).collect(); + let mut f=File::create(&path).unwrap(); f.write_all(&src).unwrap(); drop(f); + let f=File::open(&path).unwrap(); eprintln!("opening native"); let native=Arc::new(NativeFile::open(&f).expect("bridge and runtime available")); eprintln!("opened native"); + let mut threads=vec![]; + for n in 0..4 { let native=native.clone(); let src=src.clone(); threads.push(std::thread::spawn(move || { + for i in 0..50 { if i == 0 {eprintln!("worker {n} start");} let offset=n*50000+i*239; let mut b=vec![0;8193]; native.read(&mut b,offset as u64).unwrap(); assert_eq!(b,&src[offset..offset+b.len()]); } + })); } + eprintln!("joining"); for t in threads {t.join().unwrap()}; eprintln!("joined"); + assert!(native.read(&mut [0;16],1_000_001).is_err()); + drop(native); drop(f); std::fs::remove_file(path).unwrap(); + } +} diff --git a/tools/native-dstorage-bridge/.gitignore b/tools/native-dstorage-bridge/.gitignore new file mode 100644 index 000000000..f0add65e3 --- /dev/null +++ b/tools/native-dstorage-bridge/.gitignore @@ -0,0 +1,7 @@ +*.dll +*.exe +*.pdb +*.lib +*.exp +*.obj +*.log diff --git a/tools/native-dstorage-bridge/README.md b/tools/native-dstorage-bridge/README.md new file mode 100644 index 000000000..c2d399f53 --- /dev/null +++ b/tools/native-dstorage-bridge/README.md @@ -0,0 +1,44 @@ +# Windows DirectStorage staging reader + +Select the reader with `VICTORY_DSTORAGE_IO=windows`. The runner uses `handles` when no mode is specified. Native reads are restricted to Rust-owned `Vec` staging for compressed file sources. Native file and runtime initialization is lazy: raw-only files never open or initialize the native bridge. Raw or page-mapped guest destinations always use the original Win32 path and its guarded-memory retry behavior. Existing zlib/BCPack decoding and guest-copy logic remain in place. + +For a future packaged test, put all three x64 DLLs next to the **runner executable**, not merely the launcher: the locally compiled `victory-dstorage-bridge.dll`, plus Microsoft's signed `dstorage.dll` and `dstoragecore.dll` from the official DirectStorage SDK 1.4.0. The bridge finds the original file's final path and checks volume and file ID after reopening. A missing bridge/runtime or completed native error falls back to Win32. The bridge's dependencies in this build are `DSTORAGE.dll` and Windows `KERNEL32.dll`. + +Build with Visual Studio x64 developer tools and DirectStorage SDK 1.4.0: + +``` +cl /std:c++17 /EHsc /LD bridge.cpp /I \native\include /link /LIBPATH:\native\lib\x64 dstorage.lib /OUT:victory-dstorage-bridge.dll +cargo test --offline -j 1 -p victory-hle --lib --no-run +``` + +Selectively run the ignored `native_dispatch_reads_and_falls_back_on_end_of_file`, `native_dispatch_concurrent_reads_match`, and `native_only_reads_owned_compressed_source` tests with the genuine bridge and official runtime beside the test executable. Run `native_dispatch_falls_back_after_simulated_stall` in a separate process and directory containing a bridge compiled **only for the test** with `/DVICTORY_DS_TEST_STALL /DVICTORY_DS_TIMEOUT_MS=100`; never ship that test build. The guest guard test is `a_read_into_memory_guarded_for_a_moment_is_tried_again`. + +The actual crate tests passed in fresh subprocesses with the current bridge: absent DLL fallback, native read and short/beyond-EOF behavior, 200 reads across four threads, native-only-owned-versus-guest routing verified by counters, transient guest page guard retry, and simulated timeout/fallback followed by refusing new native opens. The guest guard test covers a controlled temporary read-only page, not all GPU races. The simulated stall does not prove behavior during a real hardware failure. An earlier upstream revision with the same bridge confirmed native reads in gameplay. A controlled game performance comparison and asset parity remain unverified. + +At normal info level, the runtime logs successful initialization, the first successful native read, and cumulative native attempt/success/fallback and guest-Win32 counts at most approximately once per minute while storage jobs complete. Completion snapshots report native success and fallback counts at specific completed-attempt totals. See [snapshot diagnostics](SNAPSHOT_DIAGNOSTICS.md). Requests larger than 16 MiB go straight to Win32. + +A native request writes to bridge-owned memory, copying to the owned Rust staging Vec only after successful completion. A status wait over five seconds disables new native opens and reads, quarantining the pending queue, file reference and staging until process exit so fallback cannot cause use-after-free. By default at most four native reads are admitted concurrently. `VICTORY_DSTORAGE_NATIVE_SLOTS` optionally accepts 1–16, and `VICTORY_DSTORAGE_NATIVE_WAIT_MS` accepts 0–20; invalid values revert to 4 and 0 respectively. Across all native requests, staging is capped at 64 MiB, with a 16 MiB maximum per request; excess/larger requests fall back to Win32. Queue/runtime overhead and caller-owned buffers are additional. The bridge waits on a queue completion event. It copies staged bytes only after status confirms a successful read. The deadline starts after submission: factory initialization, OpenFile, Submit or a broken runtime can still block. An affected file handle and pending resources remain held until exit. Do not deploy or enable until real-game parity, error handling, performance and shutdown are reviewed. + +The tested SDK package SHA-256 is `0838E7F71B14ACFBD1AC7ECC5E943F6C95E4F4E679E8A67F8FF6E7C102414321`. Microsoft DLL hashes: `dstorage.dll` `7F8D110FFF4AABA15BA50135DAF0584FAA098942DC24F5853ABFC66BD617E19D`; `dstoragecore.dll` `7A5D3C9B5DEE9AC9AC10AF6761F5BB46B498F57C45B87BFA50AAF95210490CD8`. Both have valid Microsoft Authenticode signatures. Original four-slot experimental bridge SHA-256 `3BFE20C2A3DD52C330C40FCAE3AB5A6146A33597A2411A9832C661370D3FD4F9`; tunable bridge SHA-256 `384FB3833ACC89FC0EB001C1DA521A6B7399E377D1B9D2EF538A091A9F6076F8` (local unsigned builds). + +## Saturation versus failures + +`ERROR_BUSY` means the native concurrency slots are full and causes an ordinary Win32 fallback; its first occurrence is informational and does not suppress later error messages. The cumulative counters separate busy, timeout, abort, other errors and all fallbacks. Timeout, abort and other native errors each have an independent first-occurrence warning. E_ABORT can represent either a runtime cancellation or native shutdown after a timeout and is reported as ambiguous rather than assuming the cause. + +The ignored `native_busy_does_not_hide_later_failures` test requires a test-only bridge compiled with `/DVICTORY_DS_TEST_BUSY_THEN_FAILURES`, in a separate directory. Its fake busy, error, timeout and abort sequence verifies matching Win32 fallback bytes, separate counters, and actual INFO/WARN log output in one fresh process. Never ship the injected bridge. + +## Synthetic saturation experiment + +A cache-hot 4 MiB test file, 12 threads, 100 varied 64 KiB reads per thread, three randomized runs per configuration, produced these medians. It is synthetic, does not include guest decompression or game I/O, and is not a frame-rate result. + +| Slots | Wait | Elapsed | p95/read | Native successes | Busy fallbacks | +|---:|---:|---:|---:|---:|---:| +| 4 | 0 ms | 217 ms | 2.12 ms | 400 | 800 | +| 8 | 0 ms | 228 ms | 2.97 ms | 800 | 400 | +| 12 | 0 ms | 219 ms | 2.48 ms | 1200 | 0 | +| 4 | 2 ms | 559 ms | 15.96 ms | 1003 | 197 | +| 8 | 2 ms | 363 ms | 9.97 ms | 1144 | 56 | + +The 12-slot setting reduced busy responses in this synthetic scenario without improving median completion time; retain the 4-slot default and evaluate 12/0 only in a controlled game A/B. The 2 ms wait increased total and tail latency, so it is not recommended from this data. In three forced-stall tests at 16 slots with five 16 MiB requests, peak observed native staging was 64 MiB and at least one request correctly returned busy. Configuration parsing and 21 actual-crate regression runs also passed. Logs: `tunable-benchmark.log`, `tunable-budget.log`, `tunable-regression.log` (local and ignored by Git). Timeout still starts after `Submit`; factory/OpenFile/Submit remain unbounded in a broken runtime. + +An event-driven completion follow-up used the same synthetic 1,200-read workload. At four slots, median elapsed time across three runs per version was 209 ms with polling and 31 ms with events. Each run completed 400 native reads and 800 Win32 fallbacks for busy slots, with zero other errors. diff --git a/tools/native-dstorage-bridge/SNAPSHOT_DIAGNOSTICS.md b/tools/native-dstorage-bridge/SNAPSHOT_DIAGNOSTICS.md new file mode 100644 index 000000000..a86655d33 --- /dev/null +++ b/tools/native-dstorage-bridge/SNAPSHOT_DIAGNOSTICS.md @@ -0,0 +1,7 @@ +# Completion snapshots + +At info level, completed native calls produce cumulative counter snapshots at 1, 16, 64, 256, 1,024, 4,096, and each subsequent multiple of 8,192. The counter advances after the native call returns, before any Win32 fallback completes. Concurrent counter fields are approximate and can include in-flight work. A call that has not returned cannot trigger a snapshot, so this does not diagnose a hang by itself. + +The optional bridge export reports its effective slot count, wait setting, and native staging budget at initialization. Older bridge DLLs continue to load and explicitly report that their effective limits are unavailable. Default settings are unchanged. + +The ignored `native_snapshots_and_effective_limits_are_reported` crate test checks thresholds 1 through 256 with a new DLL and verifies that a legacy DLL still reads correctly with unavailable limits. It and the other focused checks passed in 27 fresh-process regression runs; see the local ignored `snapshot-regression.log`. These are synthetic read tests, not a comparison of game performance or visual parity. diff --git a/tools/native-dstorage-bridge/bridge.cpp b/tools/native-dstorage-bridge/bridge.cpp new file mode 100644 index 000000000..20a632aed --- /dev/null +++ b/tools/native-dstorage-bridge/bridge.cpp @@ -0,0 +1,206 @@ +// Optional native Windows DirectStorage bridge. It only reads into CPU memory. +// The caller owns input handles and buffers until each synchronous call returns. +#include +#include +#include +#include +#include +#include +#include +#include +using Microsoft::WRL::ComPtr; + +struct FileContext { ComPtr file; }; +struct ThreadQueue { + ComPtr queue; + ComPtr status; + HANDLE completion = nullptr; + + ~ThreadQueue() { + if (completion) CloseHandle(completion); + } +}; +static ComPtr factory() { static ComPtr singleton = [](){ ComPtr f; if (FAILED(DStorageGetFactory(IID_PPV_ARGS(&f)))) f.Reset(); return f; }(); return singleton; } +static thread_local std::unique_ptr existing; +static std::atomic native_disabled{false}; +static std::atomic active_reads{0}; +static std::atomic active_bytes{0}; +static constexpr unsigned MAX_REQUEST_BYTES = 16u * 1024u * 1024u; +static constexpr unsigned long long MAX_STAGING_BYTES = 64ull * 1024ull * 1024ull; +#ifdef VICTORY_DS_TEST_OBSERVE +static std::atomic peak_bytes{0}; +static std::atomic peak_slots{0}; +template static void mark_peak(std::atomic& peak, T value) { + auto old = peak.load(std::memory_order_relaxed); + while (old < value && !peak.compare_exchange_weak(old, value, std::memory_order_relaxed)) {} +} +#endif +// Values are process-wide, initialized once. Invalid/out-of-range values use +// the old defaults. The aggregate budget remains fixed for every slot count. +static unsigned env_unsigned(const wchar_t* name, unsigned fallback, unsigned low, unsigned high) { + wchar_t value[24]{}; + const DWORD n = GetEnvironmentVariableW(name, value, 24); + if (!n || n >= 24) return fallback; + unsigned number = 0; + for (DWORD i = 0; i < n; ++i) { + if (value[i] < L'0' || value[i] > L'9') return fallback; + const unsigned digit = unsigned(value[i] - L'0'); + if (number > (high - digit) / 10u) return fallback; + number = number * 10u + digit; + } + return number >= low && number <= high ? number : fallback; +} +static unsigned slot_limit() { static const unsigned value = env_unsigned(L"VICTORY_DSTORAGE_NATIVE_SLOTS", 4, 1, 16); return value; } +static unsigned slot_wait_ms() { static const unsigned value = env_unsigned(L"VICTORY_DSTORAGE_NATIVE_WAIT_MS", 0, 0, 20); return value; } +// Optional runtime diagnostic ABI. Old callers can ignore this export. +extern "C" __declspec(dllexport) void __stdcall victory_ds_get_limits(UINT32* slots, UINT32* wait_ms, UINT64* staging_bytes) noexcept { + if (slots) *slots = slot_limit(); + if (wait_ms) *wait_ms = slot_wait_ms(); + if (staging_bytes) *staging_bytes = MAX_STAGING_BYTES; +} +#ifdef VICTORY_DS_TEST_OBSERVE +extern "C" __declspec(dllexport) unsigned __stdcall victory_ds_test_slot_limit() { return slot_limit(); } +extern "C" __declspec(dllexport) unsigned __stdcall victory_ds_test_wait_ms() { return slot_wait_ms(); } +extern "C" __declspec(dllexport) unsigned __stdcall victory_ds_test_peak_slots() { return peak_slots.load(); } +extern "C" __declspec(dllexport) unsigned long long __stdcall victory_ds_test_peak_bytes() { return peak_bytes.load(); } +#endif +static bool try_acquire(unsigned size) { + unsigned slots = active_reads.load(std::memory_order_relaxed); + do { if (slots >= slot_limit()) return false; } + while (!active_reads.compare_exchange_weak(slots, slots + 1, std::memory_order_acq_rel)); + auto bytes = active_bytes.load(std::memory_order_relaxed); + do { + if (bytes > MAX_STAGING_BYTES - size) { + active_reads.fetch_sub(1, std::memory_order_release); + return false; + } + } while (!active_bytes.compare_exchange_weak(bytes, bytes + size, std::memory_order_acq_rel)); +#ifdef VICTORY_DS_TEST_OBSERVE + mark_peak(peak_bytes, bytes + size); + mark_peak(peak_slots, active_reads.load(std::memory_order_relaxed)); +#endif + return true; +} +struct Slot { + unsigned size; + ~Slot() { + active_bytes.fetch_sub(size, std::memory_order_release); + active_reads.fetch_sub(1, std::memory_order_release); + } +}; +static ThreadQueue* thread_queue() { + if (existing) return existing.get(); + auto f=factory(); if (!f) return nullptr; + auto q=std::make_unique(); + DSTORAGE_QUEUE_DESC desc{}; desc.SourceType=DSTORAGE_REQUEST_SOURCE_FILE; + desc.Capacity=DSTORAGE_MIN_QUEUE_CAPACITY; desc.Priority=DSTORAGE_PRIORITY_NORMAL; + desc.Name="victory-native-read"; + if (FAILED(f->CreateQueue(&desc,IID_PPV_ARGS(&q->queue)))) return nullptr; + if (FAILED(f->CreateStatusArray(1,"victory-native-status",IID_PPV_ARGS(&q->status)))) return nullptr; + q->completion = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!q->completion) return nullptr; + + existing=std::move(q); return existing.get(); +} +static bool same_file(const BY_HANDLE_FILE_INFORMATION& a, const BY_HANDLE_FILE_INFORMATION& b) { + return a.dwVolumeSerialNumber==b.dwVolumeSerialNumber && a.nFileIndexHigh==b.nFileIndexHigh && a.nFileIndexLow==b.nFileIndexLow; +} +// Open by the actual existing handle's final path, and fail closed if it was +// replaced/renamed while reopened. Rust retains the original handle for fallback. +extern "C" __declspec(dllexport) HRESULT __stdcall victory_ds_open(HANDLE handle, void** result) noexcept { + try { + if (!result || !handle || handle==INVALID_HANDLE_VALUE) return E_INVALIDARG; + *result=nullptr; + if (native_disabled.load(std::memory_order_acquire)) return E_ABORT; + BY_HANDLE_FILE_INFORMATION original{}; if(!GetFileInformationByHandle(handle,&original)) return HRESULT_FROM_WIN32(GetLastError()); + auto chars=GetFinalPathNameByHandleW(handle,nullptr,0,FILE_NAME_NORMALIZED); + if(!chars || chars>32767) return E_FAIL; + std::vector path(chars+1); + auto got=GetFinalPathNameByHandleW(handle,path.data(),static_cast(path.size()),FILE_NAME_NORMALIZED); + if(!got || got>=path.size()) return E_FAIL; + auto f=factory(); if(!f) return E_FAIL; + auto ctx=std::make_unique(); + auto hr=f->OpenFile(path.data(),IID_PPV_ARGS(&ctx->file)); if(FAILED(hr)) return hr; + BY_HANDLE_FILE_INFORMATION reopened{}; hr=ctx->file->GetFileInformation(&reopened); + if(FAILED(hr) || !same_file(original,reopened)) return E_FAIL; + *result=ctx.release(); return S_OK; + } catch (...) { return E_OUTOFMEMORY; } +} +// A request writes only to bridge-owned staging, never to the caller. If it +// times out, move the entire queue, file reference, and staging into a leaked +// quarantine allocation: driver access remains valid even after fallback and +// during process shutdown. The OS reclaims this memory when the process ends. +struct Pending { + std::unique_ptr queue; + ComPtr file; + std::vector bytes; +}; +#ifndef VICTORY_DS_TIMEOUT_MS +#define VICTORY_DS_TIMEOUT_MS 5000 +#endif +extern "C" __declspec(dllexport) HRESULT __stdcall victory_ds_read(void* context, void* out, UINT32 size, UINT64 offset) noexcept { + if (!context || (!out && size)) return E_INVALIDARG; + if (!size) return S_OK; +#ifdef VICTORY_DS_TEST_BUSY_THEN_FAILURES + // Test-only deterministic failure sequence; never compile this into a shipped bridge. + static std::atomic injection_step{0}; + switch (injection_step.fetch_add(1, std::memory_order_relaxed)) { + case 0: return HRESULT_FROM_WIN32(ERROR_BUSY); + case 1: return E_FAIL; + case 2: return HRESULT_FROM_WIN32(ERROR_TIMEOUT); + default: return E_ABORT; + } +#endif + if (native_disabled.load(std::memory_order_acquire)) return E_ABORT; + if (size > MAX_REQUEST_BYTES) return E_OUTOFMEMORY; + const ULONGLONG slot_deadline = GetTickCount64() + slot_wait_ms(); + while (!try_acquire(size)) { + if (native_disabled.load(std::memory_order_acquire)) return E_ABORT; + if (GetTickCount64() >= slot_deadline) return HRESULT_FROM_WIN32(ERROR_BUSY); + Sleep(1); + } + Slot slot{size}; + if (native_disabled.load(std::memory_order_acquire)) return E_ABORT; + ThreadQueue* t = nullptr; + std::unique_ptr pending; + try { + t = thread_queue(); + if (!t) return E_FAIL; + pending = std::make_unique(); + pending->bytes.resize(size); + pending->file = static_cast(context)->file; + } catch (...) { return E_OUTOFMEMORY; } + DSTORAGE_REQUEST r{}; r.Options.SourceType=DSTORAGE_REQUEST_SOURCE_FILE; + r.Options.DestinationType=DSTORAGE_REQUEST_DESTINATION_MEMORY; + r.Options.CompressionFormat=DSTORAGE_COMPRESSION_FORMAT_NONE; + r.Source.File.Source=pending->file.Get(); r.Source.File.Offset=offset; r.Source.File.Size=size; + r.Destination.Memory.Buffer=pending->bytes.data(); r.Destination.Memory.Size=size; + t->queue->EnqueueRequest(&r); + t->queue->EnqueueStatus(t->status.Get(), 0); + t->queue->EnqueueSetEvent(t->completion); + t->queue->Submit(); +#if defined(VICTORY_DS_TEST_STALL) + Sleep(VICTORY_DS_TIMEOUT_MS); + const DWORD result = WAIT_TIMEOUT; +#else + const DWORD result = WaitForSingleObject(t->completion, VICTORY_DS_TIMEOUT_MS); +#endif + HRESULT hr = result == WAIT_FAILED ? HRESULT_FROM_WIN32(GetLastError()) + : HRESULT_FROM_WIN32(ERROR_TIMEOUT); + if (result == WAIT_OBJECT_0) { + hr = t->status->GetHResult(0); + if (hr != E_PENDING) { + if (SUCCEEDED(hr)) std::memcpy(out, pending->bytes.data(), size); + return hr; + } + } + // Retain the event as well as the queue and data if native completion was + // not verified. A timeout or failed wait cannot cancel a pending write. + native_disabled.store(true, std::memory_order_release); + pending->queue = std::move(existing); + (void)pending.release(); + return hr; +} +extern "C" __declspec(dllexport) void __stdcall victory_ds_close(void* context) noexcept { + delete static_cast(context); +} diff --git a/tools/native-dstorage-bridge/budget_harness.rs b/tools/native-dstorage-bridge/budget_harness.rs new file mode 100644 index 000000000..028e68712 --- /dev/null +++ b/tools/native-dstorage-bridge/budget_harness.rs @@ -0,0 +1,37 @@ +use std::{ffi::{c_char,c_void},fs::File,sync::{Arc,Barrier}}; +#[path = "../../crates/victory-hle/src/modules/dstorage/native_dstorage.rs"] +mod native_dstorage; +#[link(name="kernel32")] +unsafe extern "system" { + fn GetModuleHandleW(name:*const u16)->*mut c_void; + fn GetProcAddress(module:*mut c_void,name:*const c_char)->*const c_void; +} +unsafe fn function(module:*mut c_void,name:&std::ffi::CStr)->T { + let p=unsafe{GetProcAddress(module,name.as_ptr())};assert!(!p.is_null()); + unsafe{std::mem::transmute_copy(&p)} +} +fn main() { + let path=std::env::temp_dir().join(format!("victory-budget-{}",std::process::id())); + let f=File::create(&path).unwrap();f.set_len(16*1024*1024).unwrap();drop(f); + let f=File::open(&path).unwrap();let native=Arc::new(native_dstorage::NativeFile::open(&f).unwrap()); + let wide:Vec="victory-dstorage-bridge.dll\0".encode_utf16().collect(); + let module=unsafe{GetModuleHandleW(wide.as_ptr())};assert!(!module.is_null()); + let slots:unsafe extern "system" fn()->u32=unsafe{function(module,c"victory_ds_test_slot_limit")}; + let wait:unsafe extern "system" fn()->u32=unsafe{function(module,c"victory_ds_test_wait_ms")}; + let peak:unsafe extern "system" fn()->u64=unsafe{function(module,c"victory_ds_test_peak_bytes")}; + let expected_slots:u32=std::env::args().nth(1).unwrap().parse().unwrap(); + let expected_wait:u32=std::env::args().nth(2).unwrap().parse().unwrap(); + assert_eq!(unsafe{slots()},expected_slots);assert_eq!(unsafe{wait()},expected_wait); + if std::env::args().nth(3).as_deref()==Some("budget") { + let barrier=Arc::new(Barrier::new(6));let mut threads=Vec::new(); + for _ in 0..5 {let n=native.clone();let b=barrier.clone();threads.push(std::thread::spawn(move||{ + let mut out=vec![0u8;16*1024*1024];b.wait();n.read(&mut out,0) + }));} + barrier.wait();let results:Vec<_>=threads.into_iter().map(|t|t.join().unwrap()).collect(); + assert!(results.iter().any(|v|matches!(v,Err(x) if *x as u32==0x800700aa)),"{results:?}"); + let observed=unsafe{peak()};assert!(observed<=64*1024*1024,"{observed}"); + println!("budget cap passed: peak_bytes={observed}, results={results:?}"); + } + println!("config passed slots={} wait_ms={}",unsafe{slots()},unsafe{wait()}); + drop(native);drop(f);println!("FILE={}",path.display()); +} diff --git a/tools/native-dstorage-bridge/missing_harness.rs b/tools/native-dstorage-bridge/missing_harness.rs new file mode 100644 index 000000000..71e64785e --- /dev/null +++ b/tools/native-dstorage-bridge/missing_harness.rs @@ -0,0 +1,8 @@ +use std::fs::File; +#[path = "../../crates/victory-hle/src/modules/dstorage/native_dstorage.rs"] +mod native_dstorage; +fn main() { + let file=File::open(std::env::current_exe().unwrap()).unwrap(); + assert!(native_dstorage::NativeFile::open(&file).is_none(), "bridge unexpectedly present"); + println!("missing bridge: unavailable as expected"); +} diff --git a/tools/native-dstorage-bridge/test_harness.rs b/tools/native-dstorage-bridge/test_harness.rs new file mode 100644 index 000000000..99cbb4e05 --- /dev/null +++ b/tools/native-dstorage-bridge/test_harness.rs @@ -0,0 +1 @@ +#[path = "../../crates/victory-hle/src/modules/dstorage/native_dstorage.rs"] mod native_dstorage; diff --git a/tools/native-dstorage-bridge/timeout_harness.rs b/tools/native-dstorage-bridge/timeout_harness.rs new file mode 100644 index 000000000..c91a23354 --- /dev/null +++ b/tools/native-dstorage-bridge/timeout_harness.rs @@ -0,0 +1,22 @@ +use std::{fs::File, io::Write, os::windows::fs::FileExt, time::Instant}; +#[path = "../../crates/victory-hle/src/modules/dstorage/native_dstorage.rs"] +mod native_dstorage; +fn main() { + let path=std::env::temp_dir().join(format!("victory-ds-fault-{}",std::process::id())); + let data: Vec=(0..1_000_000u32).map(|x| ((x*17+(x>>9))&255) as u8).collect(); + File::create(&path).unwrap().write_all(&data).unwrap(); + let file=File::open(&path).unwrap(); + let native=native_dstorage::NativeFile::open(&file).expect("test bridge loaded"); + let mut out=vec![0xa5;8193]; + let start=Instant::now(); let result=native.read(&mut out,239); + assert!(result.is_err()); assert!(start.elapsed().as_millis()>=90 && start.elapsed().as_millis()<3000); + assert!(out.iter().all(|&b|b==0xa5),"native modified caller buffer on timeout"); + assert_eq!(file.seek_read(&mut out,239).unwrap(),out.len()); + assert_eq!(&out[..],&data[239..239+out.len()]); + let start=Instant::now(); assert!(native.read(&mut out,0).is_err()); assert!(start.elapsed().as_millis()<90); + drop(native); drop(file); + let deletion = std::fs::remove_file(&path).expect_err("quarantine must hold file until process exit"); + assert_eq!(deletion.raw_os_error(), Some(32)); + println!("timeout isolated; fallback bytes match; native disabled; file retained until exit"); + println!("FILE={}", path.display()); +}