Merge commit 'c651346' into local/upcopies

This commit is contained in:
local committed 2026-11-24 23:51:11 -06:00
commit 4f6bd62362
3 files changed
+127 -208

No files matched your search

+48 -13
View File
@@ -6290,7 +6290,7 @@ fn split_line(frames: f64) {
let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect();
let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect();
let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / (1 << 20) as f64 / frames).collect();
let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect();
tracing::info!(
"preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \
writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
@@ -6317,8 +6317,8 @@ fn split_line(frames: f64) {
"asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
waiting for the guards, {:.1} ms changing protections; pages taken again for the card: {:.1} MB compared, {:.1} MB of them \
as they were, {:.1} MB to go up (VICTORY_SEND_CHANGED)",
waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \
as they were, {:.1} MB to go up in {:.0} runs (VICTORY_SEND_CHANGED)",
a[0],
a[1] / 1024.0,
a[11] / 1e6,
@@ -6332,9 +6332,10 @@ fn split_line(frames: f64) {
a[6],
a[7] / 1e6,
a[8] / 1e6,
s[0],
s[1],
s[2],
s[0] / 1048576.0,
s[1] / 1048576.0,
s[2] / 1048576.0,
s[3],
);
tracing::info!(
"the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures",
@@ -8045,6 +8046,10 @@ mod refresh_tests {
/// card's side of those that have one, hold what title memory holds, and
/// title memory what was written last.
///
/// Into the first copy shaders write besides through a view nobody
/// declared, words the title does not write: nothing that goes up ever
/// puts an older value over those.
///
/// (It fails in the first rounds if `landed_beside` notes nothing, or
/// only takes the block out of the guards' clean ones and leaves its bit,
/// or if a fault leaves the bit; in some thousand rounds,
@@ -8063,6 +8068,9 @@ mod refresh_tests {
let data = memory(len);
(Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
};
// What was last written so, by offset.
let mut undeclared = std::collections::HashMap::new();
let exact = std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0");
let stop = AtomicBool::new(false);
// Also when an assertion fails on one of the threads.
struct Stop<'a>(&'a AtomicBool);
@@ -8167,6 +8175,16 @@ mod refresh_tests {
let mut value = 1u32;
for round in 0..rounds {
check(round, &mut random, false);
if exact {
let c = &carded[0];
let mut card = c.card.lock().unwrap();
for _ in 0..40 {
value += 1;
let at = random.below(LEN / 32) * 32 + 4 * 6;
card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
undeclared.insert(at, value);
}
}
// The flight of this submission: its shaders' writes.
for (which, c) in carded.iter().enumerate() {
if c.flying.swap(true, Ordering::Acquire) {
@@ -8212,7 +8230,17 @@ mod refresh_tests {
let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
let card = c.card.lock().unwrap();
assert_eq!(first(&card.2, there), None, "round {round}: a card copy's card side (class {})", c.class);
let mut side = card.2.clone();
if c.class == carded[0].class {
// (They may have been landed meanwhile, by a flight
// that declared their range, and may not.)
for (&at, &value) in &undeclared {
let on_card = u32::from_le_bytes(side[at..at + 4].try_into().unwrap());
assert_eq!(on_card, value, "round {round}: an older value at {at:#x}");
side[at..at + 4].copy_from_slice(&there[at..at + 4]);
}
}
assert_eq!(first(&side, there), None, "round {round}: a card copy's card side (class {})", c.class);
}
assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
}
@@ -8296,8 +8324,9 @@ mod refresh_tests {
}
}
/// A part of a copy in the card's memory taken again goes up only if it
/// differs (with `VICTORY_SEND_CHANGED=1`), whole when never taken.
/// Of a copy in the card's memory only the dwords title memory changed go
/// up, and none beside them, not even between two in 64 bytes; a page
/// never taken goes up whole.
#[test]
fn only_what_differs_goes_up() {
let region = title(4 * PAGE, true);
@@ -8316,18 +8345,24 @@ mod refresh_tests {
copy.update(region, 4 * PAGE);
let again = copy.take_dirty();
// SAFETY: as above.
unsafe { ((region + 2 * PAGE + 128) as *mut u8).write_volatile(9) };
unsafe {
((region + 2 * PAGE + 129) as *mut u8).write_volatile(9);
((region + 2 * PAGE + 136) as *mut u32).write_volatile(9);
((region + 2 * PAGE + 140) as *mut u32).write_volatile(9);
// The value that was there.
((region + 2 * PAGE + 132) as *mut u32).write_volatile(0);
}
copy.update(region, 4 * PAGE);
let written = copy.take_dirty();
if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") {
if std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0") {
assert_eq!(again, []);
assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 192)]);
assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 132), (2 * PAGE + 136, 2 * PAGE + 144)]);
} else {
assert_eq!(again, [(PAGE, 2 * PAGE)]);
assert_eq!(written, [(2 * PAGE, 3 * PAGE)]);
}
// SAFETY: as above.
assert_eq!(unsafe { data.add(2 * PAGE + 128).read() }, 9);
assert_eq!(unsafe { data.add(2 * PAGE + 129).read() }, 9);
}
/// The refreshes of a frame as run record-1 had them: 30 submissions, the
-141
View File
@@ -75,46 +75,6 @@ std::arch::global_asm!(
"vzeroupper",
"xor eax, eax",
"ret",
".globl victory_safe_update",
".globl victory_safe_update_at",
".globl victory_safe_update_after",
".globl victory_safe_update_failed",
// rcx destination, rdx source, r8 bytes (whole 64s, not none), r9 where
// the offset of the first 64 bytes that differed goes (-1: none did) and
// behind it the offset of the end of the last: stores the 64s that
// differ. eax: whether all could be read.
"victory_safe_update:",
"xor r10d, r10d",
"mov r11, -1",
"xor eax, eax",
"2:",
"victory_safe_update_at:",
"vmovdqu ymm0, ymmword ptr [rdx + r10]",
"vmovdqu ymm1, ymmword ptr [rdx + r10 + 32]",
"victory_safe_update_after:",
"vpxor ymm2, ymm0, ymmword ptr [rcx + r10]",
"vpxor ymm3, ymm1, ymmword ptr [rcx + r10 + 32]",
"vpor ymm2, ymm2, ymm3",
"vptest ymm2, ymm2",
"jz 3f",
"vmovdqu ymmword ptr [rcx + r10], ymm0",
"vmovdqu ymmword ptr [rcx + r10 + 32], ymm1",
"cmp r11, -1",
"cmove r11, r10",
"lea rax, [r10 + 64]",
"3:",
"add r10, 64",
"cmp r10, r8",
"jb 2b",
"mov qword ptr [r9], r11",
"mov qword ptr [r9 + 8], rax",
"vzeroupper",
"mov eax, 1",
"ret",
"victory_safe_update_failed:",
"vzeroupper",
"xor eax, eax",
"ret",
".globl victory_safe_merge",
".globl victory_safe_merge_at",
".globl victory_safe_merge_after",
@@ -185,63 +145,12 @@ unsafe extern "system" {
fn victory_safe_put_at();
fn victory_safe_put_after();
fn victory_safe_put_failed();
fn victory_safe_update(dst: *mut u8, src: *const u8, len: usize, changed: *mut [usize; 2]) -> u32;
fn victory_safe_update_at();
fn victory_safe_update_after();
fn victory_safe_update_failed();
fn victory_safe_merge(title: *mut u8, now: *const u8, held: *mut u8, blocks: usize, counts: *mut [u64; 2]) -> usize;
fn victory_safe_merge_at();
fn victory_safe_merge_after();
fn victory_safe_merge_failed();
}
/// What [`update`] found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Updated {
/// Every byte was the same already; nothing was stored.
Same,
/// The bytes that changed lie in these offsets.
Changed(usize, usize),
/// Not all of the source could be read; some may have been copied.
Failed,
}
/// Makes `dst` hold what `src` holds, storing only what differs. The source
/// may change meanwhile: what is compared is what is stored, read once.
///
/// # Safety
/// As [`copy`]'s, and the destination is memory of ours that nothing else
/// writes.
pub(crate) unsafe fn update(dst: *mut u8, src: *const u8, len: usize) -> Updated {
let whole = len / 64 * 64;
let (mut from, mut to) = (usize::MAX, 0);
if whole > 0 {
let mut changed = [usize::MAX, 0];
// SAFETY: the source's faults leave through the failing exit; the
// rest is the caller's.
if unsafe { victory_safe_update(dst, src, whole, &mut changed) } == 0 {
return Updated::Failed;
}
[from, to] = changed;
}
if whole < len {
let mut rest = [0u8; 64];
let rest = &mut rest[..len - whole];
// SAFETY: as above; `rest` is ours.
unsafe {
if !copy(rest.as_mut_ptr(), src.add(whole), rest.len()) {
return Updated::Failed;
}
let held = std::slice::from_raw_parts_mut(dst.add(whole), rest.len());
if held != rest {
held.copy_from_slice(rest);
(from, to) = (from.min(whole), len);
}
}
}
if from >= to { Updated::Same } else { Updated::Changed(from, to) }
}
/// What [`merge`] did.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Merged {
@@ -445,10 +354,6 @@ pub(crate) fn failing_exit(at: usize) -> Option<usize> {
if (from..to).contains(&at) {
return Some(victory_safe_put_failed as *const () as usize);
}
let (from, to) = (victory_safe_update_at as *const () as usize, victory_safe_update_after as *const () as usize);
if (from..to).contains(&at) {
return Some(victory_safe_update_failed as *const () as usize);
}
let (from, to) = (victory_safe_merge_at as *const () as usize, victory_safe_merge_after as *const () as usize);
(from..to).contains(&at).then_some(victory_safe_merge_failed as *const () as usize)
}
@@ -504,52 +409,6 @@ mod tests {
}
}
/// An update makes the two the same, says where they differed (to 64
/// bytes), stores nothing where they did not, and fails at a page that
/// is not there.
#[test]
fn updates_store_what_differs() {
assert!(on());
let (src, dst) = (Pages::new(1 << 14), Pages::new(1 << 14));
for len in [0usize, 1, 63, 64, 65, 200, 4096, 5000] {
for (da, sa) in [(0usize, 0usize), (3, 0), (0, 5)] {
for changed in [vec![], vec![0usize], vec![len / 2], vec![len.saturating_sub(1)], vec![1, len / 3, len / 2]] {
src.fill();
// SAFETY: inside the two allocations.
unsafe {
std::ptr::write_bytes(dst.0, 0xEE, dst.1);
std::ptr::copy_nonoverlapping(src.0.add(sa), dst.0.add(da), len);
let at: std::collections::BTreeSet<usize> = changed.iter().copied().filter(|&i| i < len).collect();
for &i in &at {
*src.0.add(sa + i) ^= 0x40;
}
let found = update(dst.0.add(da), src.0.add(sa), len);
match (at.iter().min(), at.iter().max()) {
(Some(&first), Some(&last)) => {
let Updated::Changed(from, to) = found else {
panic!("{len} {at:?}: {found:?}")
};
assert_eq!(from, first / 64 * 64);
assert_eq!(to, ((last / 64 + 1) * 64).min(len));
}
_ => assert_eq!(found, Updated::Same),
}
let (to, from) = (std::slice::from_raw_parts(dst.0, dst.1), std::slice::from_raw_parts(src.0, src.1));
assert_eq!(to[da..da + len], from[sa..sa + len]);
assert!(to[..da].iter().chain(&to[da + len..]).all(|&x| x == 0xEE));
}
}
}
}
// SAFETY: our allocation.
unsafe {
VirtualFree(src.0.add(4096).cast(), 4096, MEM_DECOMMIT);
assert_eq!(update(dst.0, src.0, 8192), Updated::Failed);
assert_eq!(update(dst.0, src.0.add(4096), 10), Updated::Failed);
assert_ne!(update(dst.0, src.0, 4096), Updated::Failed);
}
}
/// The dwords that changed are stored, and no byte of any other, at
/// every alignment and length; a page that is not there fails.
#[test]
+79 -54
View File
@@ -1576,30 +1576,34 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> {
runs
}
/// Whether pages of a copy in the card's memory that a refresh takes again
/// go up to the card only where they are not what the CPU's side holds
/// already (`VICTORY_SEND_CHANGED=1`; off by default).
/// Whether a refresh of a copy in the card's memory takes, and sends up,
/// the dwords that title memory changed and no others
/// (`VICTORY_SEND_CHANGED=0`: the 64 KiB pages written since it last took
/// them, whole, as before).
///
/// A refresh copies the 64 KiB pages that were written since it last took
/// them, and all of each went up and was hashed there again. Most of them
/// the title did not write: the relay put what shaders wrote into title
/// memory, and the card and the CPU's side hold those bytes already
/// ([`Shadow::card_merge_relay`]). Run record-1: 1,500 pieces (98 MB) a
/// frame fetched from the card, 103 MB in 328 ranges sent up, 322 hash
/// passes, while the title's own writes took some 260 guards off.
/// A page that counts as written is mostly not the title's doing, or not all
/// of it: a word the title wrote, and around it what shaders wrote and the
/// title never touched; or only what the relay put into title memory, which
/// the card and the CPU's side hold already ([`Shadow::card_merge_relay`]).
/// Sent up whole, such a page goes over whatever the card holds there that
/// did not come back yet, or never will (a write through a view nobody
/// declared): what stood on the card, newer, was gone.
///
/// What it rests on: the card's side holds what the CPU's side holds, but
/// for ranges shaders may be writing (no refresh touches them) and what is
/// still to go up. A page's first taking always goes up whole, so does one
/// that could not be read; after that every byte that changes on the CPU's
/// side goes up (the bytes compared are the bytes stored).
/// What it rests on: the CPU's side is what the card's side was last known
/// to hold, for every range no shader may be writing (no refresh touches
/// the others). So a dword goes up only if title memory holds another value
/// of it than the CPU's side, which then holds it too; title memory is read
/// once, what is compared is what is stored and sent. Dwords, not bytes:
/// no shader writes less, and the title's bytes beside a changed one in its
/// dword are those the CPU's side holds.
///
/// Why it is not on by default: a shader that writes a copy through a view
/// nobody declared (`crate::draw`, buffers picked by index) breaks that
/// rule. Taken again, its page went up over what it wrote; with the switch
/// its bytes stay, as they would on the console, until the title changes the
/// same 64 bytes: clearing them to the zeros they held before is then no
/// change.
/// A page never taken goes up whole as long as no shader's write was ever
/// declared for the copy. After that it is compared as any other: the CPU's
/// side and the card's began as zeros, both.
///
/// What it cannot know: that the title wrote a value over the same value.
/// Where a shader wrote in between, through a view nobody declared, the
/// shader's stays.
fn send_changed() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| {
@@ -1607,19 +1611,19 @@ fn send_changed() -> bool {
if crate::copystat::mode() != 0 {
return false;
}
std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") && crate::safecopy::on()
std::env::var_os("VICTORY_SEND_CHANGED").is_none_or(|v| v != "0")
})
}
/// Since the last frame-rate line, of pages taken again into copies in the
/// Since the last frame-rate line, of pages taken into copies in the
/// card's memory ([`send_changed`]): bytes compared, those of pages that
/// held the same, and bytes to go up.
static SEND: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
/// held the same, bytes to go up, and the runs they are.
static SEND: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
/// [`SEND`], taken.
#[cfg(feature = "diagnostics")]
pub(crate) fn send_stats() -> [u64; 3] {
[0, 1, 2].map(|i| SEND[i].swap(0, Ordering::Relaxed))
pub(crate) fn send_stats() -> [u64; 4] {
[0, 1, 2, 3].map(|i| SEND[i].swap(0, Ordering::Relaxed))
}
/// Whether what shaders wrote goes into title memory run by run
@@ -3066,34 +3070,47 @@ impl Shadow {
/// Copies title memory `[from, to)` (inside the buffer) into the copy;
/// `known`: the copy held it before ([`send_changed`]).
fn take(&self, from: usize, to: usize, known: bool) -> usize {
if !known || self.card.is_none() || !send_changed() {
return self.copy(from, to);
thread_local! {
/// A page of title memory, as read.
static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
}
let Some(card) = self.card.as_ref().filter(|_| send_changed()) else {
return self.copy(from, to);
};
let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none();
let start = self.start as usize;
let mut at = from;
while at < to {
let n = (PAGE - at % PAGE).min(to - at);
// SAFETY: inside the mapping of the copy's CPU side, which
// nothing else writes there: no shader's range holds it.
let found = unsafe { crate::safecopy::update(self.data.add(at - start), at as *const u8, n) };
SEND[0].fetch_add(n as u64, Ordering::Relaxed);
match found {
crate::safecopy::Updated::Same => {
TITLE.with_borrow_mut(|title| {
title.resize(PAGE, 0);
let mut at = from;
while at < to {
let n = (PAGE - at % PAGE).min(to - at);
let title = &mut title[..n];
// (Pages that are not there read as zeros.)
crate::host::copy_mapped(title.as_mut_ptr(), at as *const u8, n, false);
// SAFETY: inside the mapping of the copy's CPU side, which
// nothing else reads or writes there (the card copies from
// it): no shader's range holds it, and the parts of a
// refresh lie apart.
let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) };
let was = crate::host::upcheck::on().then(|| held.to_vec());
let runs = if whole { vec![(0, n)] } else { dword_runs(at, held, title, 0) };
for &(a, len) in &runs {
held[a..a + len].copy_from_slice(&title[a..a + len]);
self.changed(at - start + a, at - start + a + len);
}
self.card_changed_runs(runs.iter().map(|&(a, len)| (at - start + a, at - start + a + len)));
if let Some(was) = was {
crate::host::upcheck::note(self.id, at - start, &was, held);
}
SEND[0].fetch_add(n as u64, Ordering::Relaxed);
if runs.is_empty() {
SEND[1].fetch_add(n as u64, Ordering::Relaxed);
}
crate::safecopy::Updated::Changed(a, b) => {
SEND[2].fetch_add((b - a) as u64, Ordering::Relaxed);
self.changed(at - start + a, at - start + b);
self.card_changed(at - start + a, at - start + b);
}
// A page is not there: as before, around it, and all of it
// goes up.
crate::safecopy::Updated::Failed => {
self.copy(at, at + n);
}
SEND[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed);
SEND[3].fetch_add(runs.len() as u64, Ordering::Relaxed);
at += n;
}
at += n;
}
});
to - from
}
@@ -3128,16 +3145,24 @@ impl Shadow {
/// The CPU side's bytes at offsets `[from, to)` changed: they go to the
/// card's side before the next submission.
fn card_changed(&self, from: usize, to: usize) {
self.card_changed_runs(std::iter::once((from, to)));
}
/// [`Shadow::card_changed`] of each of `runs`.
fn card_changed_runs(&self, runs: impl Iterator<Item = (usize, usize)>) {
let Some(card) = &self.card else {
return;
};
if from >= to {
let mut runs = runs.filter(|r| r.0 < r.1).peekable();
if runs.peek().is_none() {
return;
}
let mut dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
match dirty.last_mut() {
Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)),
_ => dirty.push((from, to)),
for (from, to) in runs {
match dirty.last_mut() {
Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)),
_ => dirty.push((from, to)),
}
}
// (Under the lock: what takes the list sees it or finds it set.)
card.touched.store(true, Ordering::Release);