Merge How much of a texture is mapped is read from the runtime's own record

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-24 23:51:02 -06:00
commit 0703d16748
5 files changed
+533 -89

No files matched your search

+263 -5
View File
@@ -149,7 +149,8 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out
tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened");
// SAFETY: a handle we just opened and nobody else owns.
let file = unsafe { std::fs::File::from_raw_handle(handle) };
let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file });
let files = Files::new(file, Io::chosen());
let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { files });
WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept));
put(out, file)
}
@@ -263,7 +264,184 @@ static FACTORY_VTABLE: Methods<16> = Methods([
// Files.
struct File {
file: std::fs::File,
files: Files,
}
/// How files are read (`VICTORY_DSTORAGE_IO`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Io {
/// `one`: all workers through the one handle, as before. The host does
/// the reads of a handle one after the other.
One,
/// `handles`: a handle for each worker.
Handles,
/// `overlapped`: one handle, whose reads the host does side by side.
Overlapped,
/// `direct`: a handle for each worker, past the host's file cache.
Direct,
}
impl Io {
fn chosen() -> Io {
static CHOSEN: OnceLock<Io> = OnceLock::new();
*CHOSEN.get_or_init(|| {
let io = match std::env::var("VICTORY_DSTORAGE_IO").as_deref().map(str::trim) {
Ok("one") => Io::One,
Ok("handles") => Io::Handles,
Ok("overlapped") => Io::Overlapped,
Ok("direct") => Io::Direct,
_ => Io::DEFAULT,
};
tracing::info!(?io, "dstorage: how files are read (VICTORY_DSTORAGE_IO)");
io
})
}
const DEFAULT: Io = Io::Handles;
}
/// A file as the workers read it: the handle the title opened, and those
/// made from it when a worker first reads.
struct Files {
first: std::fs::File,
others: Box<[OnceLock<Option<std::fs::File>>]>,
io: Io,
}
impl Files {
fn new(first: std::fs::File, io: Io) -> Files {
let workers = std::thread::available_parallelism().map_or(4, |n| n.get());
let others = match io {
Io::One => 0,
Io::Overlapped => 1,
Io::Handles | Io::Direct => workers,
};
Files { first, others: (0..others).map(|_| OnceLock::new()).collect(), io }
}
#[cfg(test)]
fn open_for_test(path: &str, io: Io) -> Files {
Files::new(std::fs::File::open(path).unwrap(), io)
}
/// Reads at `offset`; as [`FileExt::seek_read`].
fn read_at(&self, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
use windows_sys::Win32::Storage::FileSystem::{FILE_FLAG_NO_BUFFERING, FILE_FLAG_OVERLAPPED};
let flags = match self.io {
Io::One | Io::Handles => 0,
Io::Overlapped => FILE_FLAG_OVERLAPPED,
Io::Direct => FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING,
};
let other = match self.others.len() {
0 => None,
n => self.others[this_thread() % n].get_or_init(|| reopen(&self.first, flags)).as_ref(),
};
match (other, self.io) {
(Some(file), Io::Overlapped) => read_overlapped(file, out, offset),
(Some(file), Io::Direct) => read_direct(file, out, offset),
(file, _) => file.unwrap_or(&self.first).seek_read(out, offset),
}
}
}
/// A number for this thread: 0 for the first that asks, and so on.
fn this_thread() -> usize {
static NEXT: AtomicU32 = AtomicU32::new(0);
thread_local! {
static NUMBER: usize = NEXT.fetch_add(1, Ordering::Relaxed) as usize;
}
NUMBER.with(|n| *n)
}
/// Another handle to `file`, for reading; `None` if the host gives none
/// (then the first one is used).
fn reopen(file: &std::fs::File, flags: u32) -> Option<std::fs::File> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::{GENERIC_READ, INVALID_HANDLE_VALUE};
use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, ReOpenFile};
// SAFETY: a file we hold open.
let handle = unsafe { ReOpenFile(file.as_raw_handle(), GENERIC_READ, FILE_SHARE_READ, flags) };
if handle == INVALID_HANDLE_VALUE {
tracing::warn!(error = %std::io::Error::last_os_error(), flags, "dstorage: a file could not be opened again");
return None;
}
// SAFETY: a handle just opened, ours alone.
Some(unsafe { std::fs::File::from_raw_handle(handle) })
}
/// A read through a handle opened for overlapped reads, waited for.
fn read_overlapped(file: &std::fs::File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::{CloseHandle, ERROR_HANDLE_EOF, ERROR_IO_PENDING, HANDLE};
use windows_sys::Win32::Storage::FileSystem::ReadFile;
use windows_sys::Win32::System::IO::{GetOverlappedResult, OVERLAPPED};
use windows_sys::Win32::System::Threading::CreateEventW;
/// Set when this thread's read is done.
struct Event(HANDLE);
impl Drop for Event {
fn drop(&mut self) {
// SAFETY: our own event.
unsafe { CloseHandle(self.0) };
}
}
thread_local! {
static DONE: Event =
// SAFETY: a plain manual-reset event.
Event(unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) });
}
DONE.with(|done| {
if done.0.is_null() {
return Err(std::io::Error::last_os_error());
}
let mut overlapped = OVERLAPPED { hEvent: done.0, ..Default::default() };
overlapped.Anonymous.Anonymous.Offset = offset as u32;
overlapped.Anonymous.Anonymous.OffsetHigh = (offset >> 32) as u32;
let len = out.len().min(1 << 30) as u32;
let mut n = 0;
// SAFETY: `out` and `overlapped` stay until the read is done, which
// is waited for.
let mut read = unsafe {
ReadFile(file.as_raw_handle(), out.as_mut_ptr(), len, std::ptr::null_mut(), &mut overlapped)
} != 0;
let mut error = std::io::Error::last_os_error();
if read || error.raw_os_error() == Some(ERROR_IO_PENDING as i32) {
// SAFETY: as above.
read = unsafe { GetOverlappedResult(file.as_raw_handle(), &overlapped, &mut n, 1) } != 0;
error = std::io::Error::last_os_error();
}
match error.raw_os_error() {
_ if read => Ok(n as usize),
Some(code) if code == ERROR_HANDLE_EOF as i32 => Ok(0),
_ => Err(error),
}
})
}
/// A read past the file cache: of the whole sectors around the bytes, into
/// a buffer of this thread's, unless `out` takes them as they are.
fn read_direct(file: &std::fs::File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
/// Every disk's sectors are at most this; offsets, sizes and addresses
/// are multiples of it.
const SECTOR: usize = 4096;
/// Read at a time.
const MOST: usize = 1 << 20;
let sector = SECTOR as u64;
if offset % sector == 0 && out.len() % SECTOR == 0 && out.as_ptr() as usize % SECTOR == 0 {
return read_overlapped(file, out, offset);
}
thread_local! {
static BUFFER: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(vec![0; MOST + SECTOR]);
}
BUFFER.with_borrow_mut(|buffer| {
let skip = buffer.as_ptr().align_offset(SECTOR);
let before = (offset % sector) as usize;
let len = (before + out.len()).next_multiple_of(SECTOR).min(MOST);
let aligned = &mut buffer[skip..skip + len];
let read = read_overlapped(file, aligned, offset - before as u64)?;
let n = read.saturating_sub(before).min(out.len());
out[..n].copy_from_slice(&aligned[before..before + n]);
Ok(n)
})
}
static FILE_VTABLE: Methods<8> = Methods([
@@ -1248,16 +1426,16 @@ fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> {
return Ok(());
}
// SAFETY: a file object we created; the title keeps it open.
let file = &unsafe { &*request.source.cast::<Instance<File>>() }
let files = &unsafe { &*request.source.cast::<Instance<File>>() }
.state
.file;
.files;
let started = std::time::Instant::now();
let (mut done, mut tries) = (0, 0);
let result = loop {
if done == out.len() {
break Ok(());
}
let error = match file.seek_read(&mut out[done..], request.offset + done as u64) {
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;
@@ -1822,6 +2000,86 @@ mod tests {
assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, plain.len()) }, plain);
}
/// What ways of reading a file give, at `VICTORY_BENCH_FILE` (a file of
/// the title's, only read): 24 threads, requests of 48 KiB at random,
/// first from places nobody read lately, then the same once more.
/// `VICTORY_BENCH_FILE=... cargo test --release -p victory-hle --lib
/// read_bench -- --ignored --nocapture`
#[test]
#[ignore = "a benchmark"]
fn read_bench() {
const THREADS: usize = 24;
const SIZE: usize = 48 << 10;
const READS: usize = 12_000;
let path = std::env::var("VICTORY_BENCH_FILE").expect("VICTORY_BENCH_FILE");
let len = std::fs::metadata(&path).unwrap().len();
let mut seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u64 | 1;
let mut random = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
for round in 0..2 {
for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct] {
let file = Files::open_for_test(&path, mode);
let at: Vec<u64> = (0..READS).map(|_| random() % (len - SIZE as u64) & !15).collect();
for pass in ["cold", "again"] {
let next = std::sync::atomic::AtomicUsize::new(0);
let busy = AtomicU64::new(0);
let start = Instant::now();
std::thread::scope(|s| {
for _ in 0..THREADS {
s.spawn(|| {
let mut out = vec![0u8; SIZE];
while let Some(&at) = at.get(next.fetch_add(1, Ordering::Relaxed)) {
let began = Instant::now();
let mut done = 0;
while done < SIZE {
done += file.read_at(&mut out[done..], at + done as u64).unwrap();
}
busy.fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed);
}
});
}
});
let took = start.elapsed().as_secs_f64();
println!(
"{round} {mode:?} {pass}: {:.0} MB/s, {:.2} ms a read",
(READS * SIZE) as f64 / took / 1e6,
busy.load(Ordering::Relaxed) as f64 / READS as f64 / 1e3
);
}
}
}
}
/// Every way of reading a file gives its bytes, also past its end.
#[test]
fn every_way_of_reading_gives_the_same_bytes() {
let plain = pattern(300_001);
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] {
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];
let mut done = 0;
while done < len {
let n = file.read_at(&mut out[done..], (at + done) as u64).unwrap();
assert_ne!(n, 0, "{mode:?} {at} {len}");
done += n;
}
assert!(out == plain[at..at + len], "{mode:?} {at} {len}");
}
let mut out = [0u8; 16];
assert_eq!(file.read_at(&mut out, 299_999).unwrap(), 2, "{mode:?}");
assert_eq!(file.read_at(&mut out, 300_001).unwrap(), 0, "{mode:?}");
assert_eq!(file.read_at(&mut out, 400_000).unwrap(), 0, "{mode:?}");
}
}
/// Lanes without workers: what `start` picks, and when statuses land.
fn lanes(staging: u64) -> Lanes {
Lanes {