A write through one view of a page is seen at its other views; page writes counted; levels on demand (off); warm-up; card memory numbers

Memory sync:
- The guard over every view of a physical page (code by myokex, victory-amd
  c6dc4d8, after pull request #115 by Spexivus, its correction by joroyt and
  a part of VIctory #1122 by tightfall): the title shows one page at several
  addresses and a copy was guarded at one only. 0.8 to 1.0 million writes
  through another view in a five-minute run on the test machine.
  VICTORY_VIEW_GUARD=0 turns it off.
- Kernel reads into title memory are read beside and copied in (Joshua Odom,
  10ea38e).
- Writes of the storage layer into physical pages are counted where the
  title has the pages mapped and can open the guards there
  (VICTORY_PAGE_WRITES, off: counted only). Failed page-destination reads
  are retried.

Card memory:
- Levels on demand, off unless VICTORY_LEVELS_ON_DEMAND=1: a texture the
  title fills takes card memory for the levels the title holds; held levels
  get memory only while the card has room and are asked for again. Its test
  runs on the software adapter; not run on a card yet.
- Refused texture slots are held back so a pass reaches the slots behind
  them; room can be kept for card copies of title buffers (off).

Tools: translate --warm all; the shader cache is keyed on the translator's
source; counters for copy-back races, page writes and the copies the
texture sweep never lets go; a walls trace.

Game runs of these changes on an RTX 4070: five five-minute runs without a
device loss or a failed request. This merged tree was built; its test
suites were run on the tree the changes come from (gpu 129, hle 97).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
fxcelessandClaude Fable 5.2 committed 2026-11-25 00:44:25 -05:00
1 parent 310c6eb6c1
commit 8dd30ab472
25 files changed
+4218 -240

No files matched your search

+13
View File
@@ -36,6 +36,19 @@ fn host_gpu_failed(what: &str) -> ! {
unreachable!("the process has ended")
}
/// The offline warm-up: see `victory_gpu::shader_cache::warm`.
pub fn warm_shader(container: &[u8]) -> Result<bool, String> {
#[cfg(windows)]
{
victory_gpu::shader_cache::warm(container)
}
#[cfg(not(windows))]
{
let _ = container;
Err("no shader cache on this host".into())
}
}
/// Keeps the host's translations of the title's shaders in `dir` (a
/// folder of the cache) across runs, and its compiled pipelines beside it
/// (`pipelines`).
+70 -15
View File
@@ -863,8 +863,25 @@ fn execute(request: &Request) -> Result<(), HRESULT> {
return Err(fail(E_INVALIDARG, "source larger than destination"));
}
let size = request.source_size as usize;
return into_destination(request, size, |out| read_into(request, out).map(|()| size))
.map_err(|hr| fail(hr, "copying"));
// A file read into a title address is the kernel's write, and the
// kernel does not fault into the GPU side's guard: a block guarded
// again between `kernel_will_write` and the read (the guard over all
// the views of a page protects other views from other threads) made
// the read fail with ERROR_INVALID_USER_BUFFER, and the title stops
// at the failed request (runs amd-C and amd-C2, seconds after the
// world's first frame). It is read beside and copied in: our copy
// faults into the guard like the title's own writes.
let bounce = options & (PAGE_DESTINATION | MEMORY_SOURCE) == 0;
return into_destination(request, size, |out| {
if !bounce {
return read_into(request, out).map(|()| size);
}
let mut data = vec![0; size];
read_into(request, &mut data)?;
out.copy_from_slice(&data);
Ok(size)
})
.map_err(|hr| fail(hr, "copying"));
}
let tables = if bc != 0 { Some(bcpack_tables()?) } else { None };
let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?;
@@ -1034,13 +1051,22 @@ fn into_destination(
fill: impl FnOnce(&mut [u8]) -> Result<usize, HRESULT>,
) -> Result<(), HRESULT> {
if request.options & PAGE_DESTINATION == 0 {
// Raw reads land through the kernel, which does not fault into the
// GPU side's guard on title buffers; open them first.
// Opens the guarded blocks and tells the GPU side a placed texture
// there changes. `fill` writes from user mode (a file read is read
// beside first, see `execute`), so a block guarded again meanwhile
// faults into the guard instead of failing the write.
victory_gpu::kernel_will_write(request.destination as usize, len);
// SAFETY: the title's destination holds `destination_size` bytes, at
// least `len`, and nothing else writes it until completion.
let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::<u8>(), len) };
return fill(out).map(drop);
let filled = fill(out).map(drop);
// Said again now that the bytes are there (upstream's c75fdba holds
// the blocks open over the read and marks them once more at its
// end): a copy or a texture pass that took the memory while the
// read was under way took what was there before. Counted; acted on
// only with `VICTORY_PAGE_WRITES=all`.
victory_gpu::title_memory_written(request.destination as usize, len, false);
return filled;
}
let offset = (request.page_offset & 0xffff) as usize;
// SAFETY: the title passes a page number per 64 KiB of destination,
@@ -1054,20 +1080,33 @@ fn into_destination(
// Consecutive pages of one allocation (the usual case): written in
// place through one view.
if let Some(mut window) = super::xmem::page_window(pages, offset, len) {
return fill(window.bytes()).map(drop);
let filled = fill(window.bytes()).map(drop);
drop(window);
// The title maps pages where the card reads them and has them
// filled afterwards: the GPU side's copies of those addresses
// learn of the bytes only from this (upstream c75fdba, fork PR
// #571). After a decode that failed part way too: what it wrote
// is there.
super::xmem::pages_written(pages, offset, len);
return filled;
}
let mut data = vec![0; len];
let n = fill(&mut data)?;
// A page the title has just made, or a view the host refuses for a moment (commit
// or address space short while a load maps many at once), can come right a little
// later: tried again before the request fails (`VICTORY_DSTORAGE_RETRIES`, default 12,
// about 1.5 s in all).
// A page the title has just made, or a view the host refuses for a
// moment, comes right a little later: the write is tried again before
// the request fails (`VICTORY_DSTORAGE_RETRIES`, 12 tries, about 0.9 s
// in all; 0: not tried again, as before). Runs 175-178 lost 12 to 446
// reads a launch here, all in one second of the loading; the one build
// that tried again (run 165) lost none of 13.
static RETRIES: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
let retries = *RETRIES.get_or_init(|| {
std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.parse().ok()).unwrap_or(12)
std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(12)
});
// Since the start: writes that succeeded on a later try, and writes
// given up.
static RETRIED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)];
let mut written = super::xmem::write_physical(pages, offset, &data[..n]);
let mut tries = 0;
let mut tries = 0u32;
while !written && tries < retries {
std::thread::sleep(std::time::Duration::from_millis((2u64 << tries.min(6)).min(128)));
tries += 1;
@@ -1075,12 +1114,28 @@ fn into_destination(
}
if written {
if tries > 0 {
tracing::info!(offset, len, tries, "dstorage: a destination's physical pages written after a retry");
let on_a_retry = RETRIED[0].fetch_add(1, Ordering::Relaxed) + 1;
tracing::info!(
offset,
len,
tries,
on_a_retry,
given_up = RETRIED[1].load(Ordering::Relaxed),
"dstorage: a destination's physical pages written after a retry"
);
}
// As above, after the write that succeeded.
super::xmem::pages_written(pages, offset, n);
Ok(())
} else {
let known = super::xmem::pages_known(pages, offset, len);
tracing::warn!(known, last_error = std::io::Error::last_os_error().raw_os_error(), "dstorage: retries used up");
let given_up = RETRIED[1].fetch_add(1, Ordering::Relaxed) + 1;
tracing::warn!(
known = super::xmem::pages_known(pages, offset, len),
tries,
given_up,
on_a_retry = RETRIED[0].load(Ordering::Relaxed),
"dstorage: retries used up (VICTORY_DSTORAGE_RETRIES)"
);
// Said aloud: the title never reads a request's result
// (it only polls for completion), so a destination left unwritten
// is a model or texture that silently holds whatever its pages
+69 -6
View File
@@ -519,7 +519,10 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi
// fail there instead of faulting into its handler; the title's
// synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned
// destinations and retry a failed `ReadFile` forever. So the destination
// is opened first.
// is opened first. A block guarded again before the kernel writes it (the
// guard over all the views of a page protects other views from other
// threads) fails that `ReadFile`, and the title's retry opens it again;
// `fread` has no such retry and reads beside instead (see there).
pub extern "system" fn ReadFile(
file: *mut c_void,
@@ -534,12 +537,38 @@ pub extern "system" fn ReadFile(
)
}
/// The host CRT reads large requests straight into the caller's buffer.
/// The host CRT reads large requests straight into the caller's buffer
/// through the kernel, whose write fails on a guarded block instead of
/// faulting into the guard. So the bytes are read beside, a chunk at a time
/// (a caller may ask for far more than the file holds), and copied in from
/// user mode, where a guarded block faults into the guard like the title's
/// own writes. Returns the items read, as the CRT does; the bytes of a
/// partial last item are copied too, as the CRT leaves them.
pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize {
victory_gpu::kernel_will_write(buffer as usize, size.saturating_mul(count));
host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)(
buffer, size, count, stream,
)
let read = host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize);
let total = size.saturating_mul(count);
if buffer.is_null() || total == 0 {
// The CRT's own checks and answer (EINVAL, or nothing to read).
return read(buffer, size, count, stream);
}
const CHUNK: usize = 1 << 20;
let mut beside = vec![0u8; total.min(CHUNK)];
let mut done = 0;
while done < total {
let want = (total - done).min(CHUNK);
let n = read(beside.as_mut_ptr(), 1, want, stream);
if n > 0 {
victory_gpu::kernel_will_write(buffer as usize + done, n);
// SAFETY: the caller's buffer holds `size * count` bytes, and
// `done + n` is at most that.
unsafe { std::ptr::copy_nonoverlapping(beside.as_ptr(), buffer.add(done), n) };
done += n;
}
if n < want {
break;
}
}
done / size
}
pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File {
@@ -751,6 +780,40 @@ mod tests {
assert_eq!((&out, n), (b"0123456789", 10));
}
#[test]
fn fread_reads_beside_in_chunks() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("data.bin");
// Over two chunks, and not a whole number of 3-byte items.
let bytes: Vec<u8> = (0..(5 << 19) + 1).map(|i| (i * 7 + i / 251) as u8).collect();
std::fs::write(&path, &bytes).unwrap();
let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32);
let open = || {
let f = _wfopen(w(&path.to_string_lossy()).as_ptr(), w("rb").as_ptr());
assert!(!f.is_null());
f
};
// Asked for far more than the file holds: the whole file, in items.
let f = open();
let mut out = vec![0xaau8; bytes.len() + 64];
let items = fread(out.as_mut_ptr(), 3, out.len() / 3, f);
assert_eq!(items, bytes.len() / 3);
assert_eq!(&out[..bytes.len()], &bytes[..], "the partial last item's bytes too");
assert!(out[bytes.len()..].iter().all(|&b| b == 0xaa), "nothing past what was read");
fclose(f);
// Exact reads continue where the last one stopped.
let f = open();
let mut a = vec![0u8; 1000];
let mut b = vec![0u8; (1 << 20) + 5];
assert_eq!(fread(a.as_mut_ptr(), 1000, 1, f), 1);
assert_eq!(fread(b.as_mut_ptr(), 1, b.len(), f), b.len());
assert_eq!(a, bytes[..1000]);
assert_eq!(b, bytes[1000..1000 + b.len()]);
fclose(f);
}
fn text(v: &[u16]) -> String {
String::from_utf16_lossy(&v[..v.len() - 1])
}
+1 -1
View File
@@ -58,7 +58,7 @@ const KEYBOARD: usize = PADS + 1;
const DEVICES: usize = PADS + 2;
/// Readings kept per device for next/previous lookups.
const HISTORY: usize = 32;
const HISTORY: usize = 256;
const POLL: Duration = Duration::from_millis(8);
/// The keyboard's stand-in gamepad (virtual key, button); README lists it.
+125
View File
@@ -364,12 +364,25 @@ struct Slice {
index: usize,
}
impl Slice {
/// The key in `Physical::shown` of the page `k` pages after this one.
fn key(&self, k: usize) -> (usize, usize) {
(Arc::as_ptr(&self.section) as usize, self.index + k)
}
}
#[derive(Default)]
struct Physical {
next_page: usize,
pages: HashMap<usize, Slice>,
/// Mapped views by address: their length and what they show.
views: BTreeMap<usize, (usize, Slice)>,
/// Where each page shows: by its section and its index there, the
/// address of that page in every view that shows it now ([`shown_at`];
/// as upstream's c75fdba keeps it). The title maps pages where the
/// card reads them and has them filled afterwards by DirectStorage,
/// which writes through views of our own.
shown: HashMap<(usize, usize), Vec<usize>>,
}
static PHYSICAL: LazyLock<Mutex<Physical>> = LazyLock::new(|| {
@@ -596,6 +609,58 @@ pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option<
})
}
/// The title addresses that show bytes `[offset, offset + len)` of `pages`
/// now, byte for byte, as runs (address, bytes) in address order: a write
/// to the pages through a view of our own ([`page_window`],
/// [`write_physical`]) lands there too, and nothing that watches those
/// addresses sees it (the GPU side's guards fault only on a write at the
/// guarded address itself). Empty if no view shows them. Byte for byte,
/// not by whole pages: the title packs several small textures into one
/// page and fills each with a request of its own.
pub(crate) fn shown_at(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> {
let Some(end) = offset.checked_add(len) else {
return Vec::new();
};
let first = offset / PAGE;
let Some(touched) = pages.get(first..end.div_ceil(PAGE)) else {
return Vec::new();
};
let mut pieces: Vec<(usize, usize)> = Vec::new();
{
let physical = physical();
for (i, page) in touched.iter().enumerate() {
let Some(addresses) = physical.pages.get(page).and_then(|slice| physical.shown.get(&slice.key(0))) else {
continue;
};
// The bytes of this page that the write covers.
let lo = if i == 0 { offset % PAGE } else { 0 };
let hi = (end - (first + i) * PAGE).min(PAGE);
pieces.extend(addresses.iter().map(|&at| (at + lo, hi - lo)));
}
}
pieces.sort_unstable();
let mut runs: Vec<(usize, usize)> = Vec::new();
for (at, bytes) in pieces {
match runs.last_mut() {
Some((start, n)) if *start + *n == at => *n += bytes,
_ => runs.push((at, bytes)),
}
}
runs
}
/// Bytes `[offset, offset + len)` of `pages` have been written through a
/// view of our own: the GPU side is told at every title address that
/// shows them (`victory_gpu::title_memory_written`; what it does with it
/// is `VICTORY_PAGE_WRITES`' to say, and it counts either way). Call when
/// the bytes are there, and without the page table's lock ([`shown_at`]
/// takes and leaves it).
pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) {
for (at, bytes) in shown_at(pages, offset, len) {
victory_gpu::title_memory_written(at, bytes, true);
}
}
/// Maps `n` pages at `address`, in place of what is mapped there; null
/// `pages` unmaps. Returns `address`, or null if a page or the host fails.
pub extern "system" fn XMemMapPhysicalPages(
@@ -746,6 +811,9 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
victory_gpu::title_memory_remapped(base, len);
// What the range shows now, for the GPU side's in-place census.
victory_gpu::title_memory_view(base, len, slice.section.0 as usize, (slice.index * PAGE) as u64);
for k in 0..len.div_ceil(PAGE) {
physical.shown.entry(slice.key(k)).or_default().push(base + k * PAGE);
}
physical.views.insert(base, (len, slice));
true
}
@@ -824,6 +892,15 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) {
let Some((size, slice)) = physical.views.remove(&at) else {
continue;
};
for k in 0..size.div_ceil(PAGE) {
let key = slice.key(k);
if let Some(addresses) = physical.shown.get_mut(&key) {
addresses.retain(|&a| a != at + k * PAGE);
if addresses.is_empty() {
physical.shown.remove(&key);
}
}
}
victory_gpu::title_memory_remapped(at, size);
// SAFETY: a view we mapped; it becomes a placeholder again.
unsafe {
@@ -1306,6 +1383,54 @@ mod tests {
assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1);
}
/// Pages say where the title has them mapped, byte for byte (after
/// fork PR #571's test; its runs are whole pages).
#[test]
fn pages_say_where_they_are_mapped() {
let pages = allocate(3);
let reserve = |n: usize| {
let at = XMemVirtualAlloc(std::ptr::null_mut(), n * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE);
assert!(!at.is_null());
at
};
// `b` keeps a page unmapped at either end, so that no run at `b`
// ever touches one at `a`, wherever the host puts the two.
let (a, b) = (reserve(3), reserve(4));
assert!(shown_at(&pages, 0, 3 * PAGE).is_empty(), "mapped nowhere");
// All three at `a`; the last two at `b`, from its second page on.
assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a);
let second = b.wrapping_byte_add(PAGE);
assert_eq!(XMemMapPhysicalPages(second, 2, pages[1..].as_ptr()), second);
let (a, second) = (a as usize, second as usize);
let sorted = |mut runs: Vec<(usize, usize)>| {
runs.sort_unstable();
runs
};
assert_eq!(shown_at(&pages, 0, PAGE), vec![(a, PAGE)]);
// A request for part of a page names those bytes alone.
assert_eq!(shown_at(&pages, 0x4000, 0x3000), vec![(a + 0x4000, 0x3000)]);
// Across two pages, shown at two addresses each: one run at each.
assert_eq!(
shown_at(&pages, PAGE + 1, PAGE),
sorted(vec![(a + PAGE + 1, PAGE), (second + 1, PAGE)])
);
// A page unmapped in the middle of a view: the rest still shows.
let middle = (a + PAGE) as *mut c_void;
assert_eq!(XMemMapPhysicalPages(middle, 1, std::ptr::null()), middle);
assert_eq!(
shown_at(&pages, 0, 3 * PAGE),
sorted(vec![(a, PAGE), (a + 2 * PAGE, PAGE), (second, 2 * PAGE)])
);
// Too few pages for the bytes: nothing (the write fails too).
assert!(shown_at(&pages, 0, 3 * PAGE + 1).is_empty());
for (at, n) in [(a, 3), (second, 2)] {
let at = at as *mut c_void;
assert_eq!(XMemMapPhysicalPages(at, n, std::ptr::null()), at);
}
assert!(shown_at(&pages, 0, 3 * PAGE).is_empty());
assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
}
#[test]
fn page_windows_cover_one_run_in_place() {
let (a, b) = (allocate(3), allocate(1));