Skip to content
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,12 @@ Memory sync between the title's memory and the copies on the card:
them in every run) and can open the guards there:
`VICTORY_PAGE_WRITES=guards` (off by default; `1`, `slots`, `all` do more).
- Failed page-destination reads are retried (`VICTORY_DSTORAGE_RETRIES=0` = as before).
- A page-destination read that starts before the title wrote its page
numbers reads them again for up to 250 ms before those retries. Since
reads into physical pages wait for the title's Submit, only a full queue's
start that early. Measured before reads waited for it: up to 302 requests
of a burst at the opening's loading failed so (their models or textures
kept whatever their pages held); none with this (RTX 5090).

Card memory (the test card is full from the first frame of the world: 85 to
99 % of its budget for a whole run, about 26,000 texture copies let go and
Expand Down
4 changes: 2 additions & 2 deletions crates/victory-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2574,7 +2574,7 @@ impl State {
let draws: u32 = census.1.values().sum();
if draws > 0 {
let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect();
rects.sort_unstable_by(|a, b| b.1.cmp(&a.1));
rects.sort_unstable_by_key(|r| std::cmp::Reverse(r.1));
let scissors: Vec<String> = rects
.iter()
.take(5)
Expand Down Expand Up @@ -3321,7 +3321,7 @@ impl State {
// the record drawn before it.
if (6..=8).contains(&why_not) {
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 256 == 0 {
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed).is_multiple_of(256) {
let (last_copy, last_offset) = self.last_indirect;
tracing::info!(
"a window miss (one in 256): cause {why_not}, kind {kind}, stride {stride}, buffer {} offset {offset:#x} ({} left); the command before it on the list: buffer {last_copy} offset \
Expand Down
4 changes: 2 additions & 2 deletions crates/victory-gpu/src/fpsbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ pub(crate) fn draw(host: &crate::host::Host, list: &ID3D12GraphicsCommandList, b
made.clear();
}
let key = (tenths, format.0, scale);
if !made.contains_key(&key) {
if let std::collections::hash_map::Entry::Vacant(slot) = made.entry(key) {
let (w, h, lit) = bitmap(&text(tenths), scale);
let pitch = (w as usize * bytes).next_multiple_of(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT as usize);
let Some((buffer, data)) = host.shared_buffer((pitch * h as usize) as u64) else {
Expand All @@ -185,7 +185,7 @@ pub(crate) fn draw(host: &crate::host::Host, list: &ID3D12GraphicsCommandList, b
pixel(format, lit[y * w as usize + x], &mut out[at..at + bytes]);
}
}
made.insert(key, Made { buffer, width: w, height: h, pitch: pitch as u32 });
slot.insert(Made { buffer, width: w, height: h, pitch: pitch as u32 });
}
let Some(m) = made.get(&key) else {
return;
Expand Down
5 changes: 3 additions & 2 deletions crates/victory-gpu/src/indirect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2450,7 +2450,8 @@ void work() {
heap_pairs: [[Option<ID3D12DescriptorHeap>; 2]; 2],
tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2],
targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2],
depth_written: D3D12_CPU_DESCRIPTOR_HANDLE,
/// Kept with the bench: the view the depth clears go through.
_depth_written: D3D12_CPU_DESCRIPTOR_HANDLE,
depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE,
stamps: ID3D12QueryHeap,
back: ID3D12Resource,
Expand Down Expand Up @@ -2758,7 +2759,7 @@ void work() {
heap_pairs,
tables,
targets,
depth_written,
_depth_written: depth_written,
depth_tested,
stamps,
back,
Expand Down
9 changes: 5 additions & 4 deletions crates/victory-gpu/src/pipeline/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -506,10 +506,11 @@ fn open(device: &ID3D12Device1, blob: Blob) -> Option<Library> {
// RenderDoc's device refused the card's library, an empty one was
// saved over 366 MB of built pipelines, and the next run drew black
// until they were built again).
if rejected && let Some(dir) = DIR.get() {
if let Err(e) = std::fs::rename(dir.join(LIBRARY_FILE), dir.join(REJECTED_FILE)) {
tracing::warn!(error = %e, "the rejected host pipeline library could not be kept under its other name");
}
if rejected
&& let Some(dir) = DIR.get()
&& let Err(e) = std::fs::rename(dir.join(LIBRARY_FILE), dir.join(REJECTED_FILE))
{
tracing::warn!(error = %e, "the rejected host pipeline library could not be kept under its other name");
}
let library = make(&[]).ok()?;
Some(Library {
Expand Down
2 changes: 1 addition & 1 deletion crates/victory-gpu/src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,7 @@ fn send_joined(joined: &mut Joined) {
let sent = JOINED[1].fetch_add(1, Ordering::Relaxed) + 1;
JOINED[2].fetch_add(order.len() as u64, Ordering::Relaxed);
JOINED[3].fetch_add(joined.signals.len() as u64, Ordering::Relaxed);
if sent % 2048 == 0 {
if sent.is_multiple_of(2048) {
let n: Vec<u64> = JOINED.iter().map(|n| n.swap(0, Ordering::Relaxed)).collect();
tracing::info!(
"parts joined (VICTORY_JOIN_PARTS=1): {} parts went to the host in {} submissions ({:.1} parts, {:.1} lists each), {} signals delivered behind them, {} waits passed for a write of a part not sent yet",
Expand Down
1 change: 1 addition & 0 deletions crates/victory-gpu/src/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2553,6 +2553,7 @@ static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64

/// See [`PLACED_TWINS`].
#[cfg(windows)]
#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
pub(crate) fn placed_filler_twins() -> u64 {
PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed)
}
Expand Down
4 changes: 2 additions & 2 deletions crates/victory-gpu/src/shadow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3141,7 +3141,7 @@ impl Shadow {
}
OWN_WRITES[1].fetch_add(bytes.len() as u64, Ordering::Relaxed);
let n = OWN_WRITES[0].fetch_add(1, Ordering::Relaxed) + 1;
if n % 16384 == 0 {
if n.is_multiple_of(16384) {
tracing::info!(
"what shaders wrote, stored through views of our own (VICTORY_BACK_OWN_VIEW=1), since the start: {n} stretches {} MB, {} pages noted current for the copy that wrote them (not copied in again), {} stretches written the old way; with VICTORY_BACK_OWN_CHECK=1: {} stores the title's address did not show, {} pages noted current whose CPU side differs from title memory, {} of those with the guard clean",
OWN_WRITES[1].load(Ordering::Relaxed) >> 20,
Expand Down Expand Up @@ -3667,7 +3667,7 @@ impl Shadow {
COPY_CHANGED[1].fetch_add(sent as u64, Ordering::Relaxed);
COPY_CHANGED[2].fetch_add(stretches.len() as u64, Ordering::Relaxed);
let calls = COPY_CHANGED[3].fetch_add(1, Ordering::Relaxed) + 1;
if calls % 65536 == 0 {
if calls.is_multiple_of(65536) {
tracing::info!(
"copies in the card's memory, refreshed by what differs (VICTORY_COPY_CHANGED=1), since the start: {calls} refreshes read {} MB of title memory the title had written to; {} MB of it differed from the copy and went on to the card, in {} stretches",
COPY_CHANGED[0].load(Ordering::Relaxed) >> 20,
Expand Down
4 changes: 2 additions & 2 deletions crates/victory-gpu/src/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
fn failed_asking(start: usize, end: usize) {
use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 2048 != 0 {
if !N.fetch_add(1, std::sync::atomic::Ordering::Relaxed).is_multiple_of(2048) {
return;
}
// SAFETY: plain data filled in by the query.
Expand Down Expand Up @@ -876,7 +876,7 @@ fn protect_here(g: &mut Guards, from: usize, to: usize) {
#[cfg(feature = "diagnostics")]
{
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 1024 == 0 {
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed).is_multiple_of(1024) {
tracing::info!("a block of title memory could not be made read-only (one in 1024): {:#x}: {error}", block * BLOCK);
}
}
Expand Down
127 changes: 106 additions & 21 deletions crates/victory-hle/src/modules/dstorage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,7 @@ impl Lanes {
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),
destination_waits = DESTINATION_WAITS.swap(0, 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,
Expand Down Expand Up @@ -1139,48 +1140,85 @@ fn into_destination(
return filled;
}
let offset = (request.page_offset & 0xffff) as usize;
// SAFETY: the title passes a page number per 64 KiB of destination,
// which holds at least `len` bytes from `offset`.
let pages = unsafe {
std::slice::from_raw_parts(
request.destination.cast::<usize>(),
(offset + len).div_ceil(PAGE),
)
let count = (offset + len).div_ceil(PAGE);
// The page numbers as the title has them now: it may still be writing
// them (read each time, not kept).
let read_pages = || -> Vec<usize> {
(0..count)
// SAFETY: the title passes a page number per 64 KiB of
// destination, which holds at least `len` bytes from `offset`.
.map(|i| unsafe { std::ptr::read_volatile(request.destination.cast::<usize>().add(i)) })
.collect()
};
let mut pages = read_pages();
// 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) {
if let Some(mut window) = super::xmem::page_window(&pages, offset, len) {
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);
super::xmem::pages_written(&pages, offset, len);
return filled;
}
let mut data = vec![0; len];
let n = fill(&mut data)?;
// A page number not known yet: the title fills the array after it
// enqueued the request, right before its Submit. A queue that submits
// itself half full leaves such a read for that Submit
// (`Lanes::submit_as`), so a worker comes to one first only where a
// full queue's held reads start before it (`queue`). (Before reads were
// held, 302 requests of a burst at the opening's loading went unwritten
// in one run, 44 and 9 in others; one number was known 17 us later.)
// The numbers are read again for a while.
let waiting = std::time::Instant::now();
let mut waited = 0u32;
while !super::xmem::pages_known(&pages, offset, n) && waiting.elapsed() < std::time::Duration::from_millis(250) {
waited += 1;
if waited < 16 {
std::thread::yield_now();
} else {
std::thread::sleep(std::time::Duration::from_millis(1));
}
pages = read_pages();
}
if waited > 0 {
DESTINATION_WAITS.fetch_add(1, Ordering::Relaxed);
if super::xmem::pages_known(&pages, offset, n) {
static SEEN: std::sync::Once = std::sync::Once::new();
SEEN.call_once(|| {
tracing::info!(
tries = waited,
us = waiting.elapsed().as_micros() as u64,
"dstorage: a destination's page numbers were known only after the request was taken (read again until they were)"
);
});
}
}
// 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.
// that tried again (run 165) lost none of 13. The page numbers are read
// again before each try.
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.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 written = super::xmem::write_physical(&pages, offset, &data[..n]);
let mut tries = 0u32;
while !written && tries < retries {
std::thread::sleep(std::time::Duration::from_millis((2u64 << tries.min(6)).min(128)));
tries += 1;
written = super::xmem::write_physical(pages, offset, &data[..n]);
pages = read_pages();
written = super::xmem::write_physical(&pages, offset, &data[..n]);
}
if written {
if tries > 0 {
Expand All @@ -1195,17 +1233,11 @@ fn into_destination(
);
}
// As above, after the write that succeeded.
super::xmem::pages_written(pages, offset, n);
super::xmem::pages_written(&pages, offset, n);
Ok(())
} else {
let known = super::xmem::pages_known(&pages, offset, n);
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
Expand All @@ -1214,12 +1246,21 @@ fn into_destination(
offset,
len,
pages = pages.len(),
"dstorage: a destination's physical pages could not be written (unknown page or a host failure); its request fails"
first = format_args!("{:#x}", pages.first().copied().unwrap_or(0)),
why = if known { "the host could not map them" } else { "a page number is unknown" },
tries,
given_up,
on_a_retry = RETRIED[0].load(Ordering::Relaxed),
"dstorage: a destination's physical pages could not be written; its request fails (VICTORY_DSTORAGE_RETRIES)"
);
Err(E_INVALIDARG)
}
}

/// Requests whose destination page numbers were read again because one was
/// not known when a worker took the request.
static DESTINATION_WAITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Queues that submitted themselves, half full (diagnostics).
static AUTO_SUBMITS: AtomicU32 = AtomicU32::new(0);

Expand Down Expand Up @@ -1824,6 +1865,50 @@ mod tests {
assert!(first.iter().all(|&b| b == 0), "the old page was written");
}

#[test]
fn a_page_number_written_after_its_read_started_is_read_again() {
use crate::modules::xmem;
let (mut given, mut pages) = (1usize, [0usize; 1]);
assert_eq!(
xmem::XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()),
1
);
let mapped = xmem::XMemVirtualAlloc(
std::ptr::null_mut(),
PAGE,
0x2000 | 0x2040_0000, // reserve, 64 KiB pages
0,
0x04,
);
assert!(!mapped.is_null());
assert_eq!(xmem::XMemMapPhysicalPages(mapped, 1, pages.as_ptr()), mapped);
// The title's page list: no number in it yet when the read starts,
// as where a full queue's held reads go before the title's Submit.
let mut numbers = [0usize];
let list = numbers.as_mut_ptr();
let plain = pattern(4096);
let (queue, array) = (new_queue(1), status_array(1));
let r = request(
PAGE_DESTINATION | MEMORY_SOURCE,
list.cast(),
plain.len(),
plain.as_ptr().cast(),
0,
plain.len(),
);
enqueue(queue, &r);
enqueue_status(queue, array, 0);
void(queue, 0x30);
// Time for a worker to take the read and find no page.
std::thread::sleep(Duration::from_millis(20));
// SAFETY: the list outlives the request, which reads it while it runs.
unsafe { std::ptr::write_volatile(list, pages[0]) };
assert_eq!(wait(array, 0), S_OK);
// SAFETY: the page is mapped read-write.
let seen = unsafe { std::slice::from_raw_parts(mapped.cast::<u8>(), plain.len()) };
assert_eq!(seen, plain);
}

#[test]
fn zlib_into_pages_in_place_and_across_allocations() {
use crate::modules::xmem;
Expand Down