Merge Each submission's shaders read the bytes it was prepared with (VICTORY

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-25 00:17:28 -06:00
commit c6604f99cf
5 files changed
+719 -45

No files matched your search

+39 -6
View File
@@ -1720,6 +1720,8 @@ struct CardPlan {
sent_as: u64,
/// With [`upcheck`]: the look at what it sent up.
looks: Option<upcheck::Looks>,
/// With [`send`]: the memory its sends come from.
sends: Option<send::Memory>,
}
/// One piece of submission-time work, in recorded order.
@@ -2973,6 +2975,17 @@ fn late_line(frames: f64) {
r[3] / 1000.0,
r[4] / 1000.0,
);
if send::own() {
let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
tracing::info!(
"bytes of submissions' own sent up per frame (VICTORY_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \
taking them out of the CPU sides",
t[0] / (1 << 20) as f64,
t[1],
t[2],
t[3] / 1000.0,
);
}
let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
if t[0] > 0.0 {
tracing::info!(
@@ -2999,6 +3012,7 @@ fn late_line(frames: f64) {
}
mod card_steps;
mod send;
mod torn;
pub(crate) mod upcheck;
@@ -3533,7 +3547,7 @@ impl Host {
}
}
}
let declared = crate::picked::with(declared, &picked.written);
let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
// (Of a copy with a declared range here, that says it.)
let looked: Vec<&crate::picked::Range> =
picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect();
@@ -3570,6 +3584,8 @@ impl Host {
}
let mut used: Vec<(bool, Prelude)> = Vec::new();
let mut looks = None;
// The bytes as they are now, whatever later submissions put there.
let own = if send::own() { send::take(self, &dirty) } else { None };
if !dirty.is_empty() {
let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
fail(format_args!("no host list to bring host copies in the card's memory up to date"));
@@ -3589,16 +3605,21 @@ impl Host {
// pass: a wait between each copy and its pass had the
// card do them one after the other.
let mut sent = Vec::new();
if let Some(own) = &own {
own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow)));
}
for (shadow, ranges) in &dirty {
let Some((staging, before, _)) = shadow.card_sides() else {
continue;
};
for &(a, b) in ranges {
list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
if own.is_none() {
list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
}
crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
}
crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
if before.is_some() && !ranges.is_empty() {
if own.is_none() && before.is_some() && !ranges.is_empty() {
sent.push(transition(
&shadow.buffer,
D3D12_RESOURCE_STATE_COPY_DEST,
@@ -3630,7 +3651,7 @@ impl Host {
ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
};
// The same pieces in fewer passes (`rehash_runs`).
let runs = if rehash_runs() { crate::shadow::joined_piece_runs(runs) } else { runs };
let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs };
CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
for run in runs {
@@ -3655,6 +3676,7 @@ impl Host {
lists: used,
sent_as,
looks,
sends: own.map(send::Own::memory),
};
// Each byte once, as the copy-back joins the declared ranges. The
// results go behind those of plans still in the air.
@@ -3775,6 +3797,9 @@ impl Host {
if let Some(looks) = plan.looks {
looks.read();
}
if let Some(memory) = plan.sends {
send::give_back(memory);
}
let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
let Some(work) = work.as_mut() else {
return;
@@ -4744,8 +4769,11 @@ impl Host {
// may write too, and this submission refreshes it. The flights
// are settled, and the asking made again: the copy-back wrote
// title memory, which other copies of it must see.
if behind && upcheck::on() {
upcheck::reads(runs);
if upcheck::on() {
upcheck::order(runs);
if behind {
upcheck::reads(runs);
}
}
let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
if !stale.is_empty() {
@@ -6122,6 +6150,11 @@ impl HostList {
copy_mapped(dst as *mut u8, src as *const u8, len, true);
// With the submission's one asking: the journal learns it.
crate::watch::wrote(dst, len);
// What the card holds there may be another value although
// ours did not change.
if send::own() {
crate::shadow::send_copied(dst, len);
}
(started, len)
}
&Step::Fill(dst, src, len, _) => {
+261
View File
@@ -0,0 +1,261 @@
//! What goes up to copies in the card's memory goes up as it was when its
//! submission was prepared (`VICTORY_SEND_OWN`, on by default; `0`: as
//! before).
//!
//! The sends were copies out of the copies' CPU sides, which the card makes
//! when it comes to the submission. By then later submissions are prepared
//! (two frames of them with `VICTORY_RELAY`), and their refreshes have
//! written the same CPU sides: the earlier submission's shaders then read a
//! later one's bytes. For what the title's CPU writes that is as on the
//! console (it does not write what the card still reads). But the title's
//! own buffer copies are commands in its lists, and those are done by us
//! when a submission is prepared: "a value to a buffer, a draw that reads
//! it" in one submission and the same with another value in the next is
//! ordinary, and both draws read the second value.
//!
//! So each submission's bytes are taken out of the CPU sides into memory of
//! the submission's own when they are taken from the dirty lists, and the
//! card copies them from there. Runs of a few words, which a refresh that
//! sends only what changed makes many of, go as pairs of offset and value,
//! stored by one dispatch per copy; the others as a copy each.
use super::*;
use crate::shadow::Shadow;
pub(super) fn own() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_SEND_OWN").is_none_or(|v| v != "0"))
}
/// Runs up to this many bytes go as pairs.
const SHORT: usize = 256;
const SCATTER: &str = r#"
#define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)"
cbuffer Part : register(b0) { uint at; uint count; };
ByteAddressBuffer pairs : register(t0);
RWByteAddressBuffer card : register(u0);
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
if (id.x >= count) return;
uint2 p = pairs.Load2(at + id.x * 8u);
card.Store(p.x, p.y);
}
"#;
struct Pass {
root: ID3D12RootSignature,
pso: ID3D12PipelineState,
}
fn pass(host: &Host) -> Option<&'static Pass> {
static PASS: OnceLock<Option<Pass>> = OnceLock::new();
PASS.get_or_init(|| {
let code = compile(SCATTER, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?;
// SAFETY: the code lives through the calls; the root signature is
// inside it.
unsafe {
let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?;
let pso: ID3D12PipelineState = host
.device
.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE {
pShaderBytecode: code.as_ptr().cast(),
BytecodeLength: code.len(),
},
..Default::default()
})
.ok()?;
name(&pso, || "victory: changed words sent to the card".into());
Some(Pass { root, pso })
}
})
.as_ref()
}
/// Memory a submission's sends come from, mapped.
pub(super) struct Memory {
buffer: ID3D12Resource,
data: usize,
size: u64,
}
// SAFETY: a D3D12 object (free-threaded) and its mapping, with one owner.
unsafe impl Send for Memory {}
/// What submissions that have run gave back.
static SPARE: Mutex<Vec<Memory>> = Mutex::new(Vec::new());
/// At most this much is kept.
const KEPT: u64 = 768 << 20;
fn memory(host: &Host, size: u64) -> Option<Memory> {
{
let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
let fit = spare.iter().enumerate().filter(|(_, m)| m.size >= size).min_by_key(|(_, m)| m.size).map(|(i, _)| i);
if let Some(i) = fit {
return Some(spare.swap_remove(i));
}
}
let size = size.next_multiple_of(8 << 20);
let (buffer, data) = host.upload_buffer(size)?;
name(&buffer, || "bytes a submission sends up".into());
Some(Memory {
buffer,
data: data as usize,
size,
})
}
/// The submission has run.
pub(super) fn give_back(memory: Memory) {
let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
spare.push(memory);
spare.sort_by_key(|m| std::cmp::Reverse(m.size));
while spare.iter().map(|m| m.size).sum::<u64>() > KEPT {
spare.remove(0);
}
}
/// Since the last frame-rate line: bytes copied, runs copied, words stored,
/// microseconds of taking them out of the CPU sides.
pub(super) static STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
/// One copy's sends: ranges copied (offset in the copy, in the memory,
/// bytes), and its pairs (where in the memory, how many).
struct Copy {
runs: Vec<(usize, u64, usize)>,
pairs: (u64, u32),
}
/// Where a submission's bytes are taken to.
pub(super) struct Own {
memory: Memory,
copies: Vec<Copy>,
}
/// Takes what `dirty` sends up out of the CPU sides.
pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)]) -> Option<Own> {
let began = std::time::Instant::now();
pass(host)?;
// Runs of whole words of the copy: only those are pairs. (A byte beside
// them in a word may be the card's.)
let short = |&(a, b): &(usize, usize)| b - a <= SHORT && a % 4 == 0 && b % 4 == 0;
let mut at = 0u64;
let mut copies = Vec::with_capacity(dirty.len());
for (_, ranges) in dirty {
let mut runs = Vec::new();
for &(a, b) in ranges.iter().filter(|r| !short(r)) {
runs.push((a, at, b - a));
at += ((b - a) as u64).next_multiple_of(16);
}
let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum();
copies.push(Copy { runs, pairs: (at, words as u32) });
at += (words as u64 * 8).next_multiple_of(16);
}
if at == 0 {
return None;
}
let memory = memory(host, at)?;
let mut moves: Vec<(usize, usize, usize)> = Vec::new();
for ((shadow, ranges), copy) in dirty.iter().zip(&copies) {
let from = shadow.card_data() as usize;
moves.extend(copy.runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n)));
let mut to = (memory.data + copy.pairs.0 as usize) as *mut [u32; 2];
for &(a, b) in ranges.iter().filter(|r| short(r)) {
for offset in (a..b).step_by(4) {
// SAFETY: inside the copy's mapping (its CPU side, which
// this thread alone writes in these ranges) and inside the
// memory, which has room for every pair.
unsafe {
let word = ((from + offset) as *const u32).read_unaligned();
to.write([offset as u32, word]);
to = to.add(1);
}
}
}
}
STATS[0].fetch_add(moves.iter().map(|m| m.2 as u64).sum(), Ordering::Relaxed);
STATS[1].fetch_add(moves.len() as u64, Ordering::Relaxed);
STATS[2].fetch_add(copies.iter().map(|c| u64::from(c.pairs.1)).sum(), Ordering::Relaxed);
crate::shadow::copy_all(moves);
STATS[3].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed);
Some(Own { memory, copies })
}
impl Own {
/// Records the sends into `list`; the copies that `looked` says are in
/// `COPY_DEST`, the others in the common state. Those with a "before" are
/// left readable by compute shaders.
///
/// # Safety
/// An open list of ours, whose compute state is set anew behind this.
pub(super) unsafe fn record(
&self,
host: &Host,
list: &ID3D12GraphicsCommandList,
dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)],
looked: impl Fn(&Shadow) -> bool,
) {
let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
let write = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
let dest = D3D12_RESOURCE_STATE_COPY_DEST;
let (mut first, mut last) = (Vec::new(), Vec::new());
for ((shadow, _), copy) in dirty.iter().zip(&self.copies) {
for &(a, from, n) in &copy.runs {
// SAFETY: the caller's; live buffers, ranges inside them.
unsafe { list.CopyBufferRegion(&shadow.buffer, a as u64, &self.memory.buffer, from, n as u64) };
}
let mut state = (looked(shadow) || !copy.runs.is_empty()).then_some(dest);
if copy.pairs.1 > 0 {
if let Some(was) = state {
first.push(transition(&shadow.buffer, was, write));
}
state = Some(write);
}
let hashed = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
if let Some(was) = state
&& hashed
&& (!copy.runs.is_empty() || copy.pairs.1 > 0)
{
last.push(transition(&shadow.buffer, was, read));
}
}
// SAFETY: the caller's; live objects.
unsafe {
if !first.is_empty() {
list.ResourceBarrier(&first);
}
if let Some(pass) = pass(host)
&& self.copies.iter().any(|c| c.pairs.1 > 0)
{
list.SetComputeRootSignature(&pass.root);
list.SetPipelineState(&pass.pso);
list.SetComputeRootShaderResourceView(1, self.memory.buffer.GetGPUVirtualAddress());
for ((shadow, _), copy) in dirty.iter().zip(&self.copies).filter(|(_, c)| c.pairs.1 > 0) {
list.SetComputeRootUnorderedAccessView(2, shadow.buffer.GetGPUVirtualAddress());
const MOST: u32 = 64 * D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
let (at, words) = copy.pairs;
let mut done = 0;
while done < words {
let n = (words - done).min(MOST);
let constants = [at as u32 + done * 8, n];
list.SetComputeRoot32BitConstants(0, 2, constants.as_ptr().cast(), 0);
list.Dispatch(n.div_ceil(64), 1, 1);
done += n;
}
}
}
if !last.is_empty() {
list.ResourceBarrier(&last);
}
}
}
/// The memory, to be kept until the submission has run.
pub(super) fn memory(self) -> Memory {
self.memory
}
}
+202 -12
View File
@@ -112,12 +112,21 @@ pub(crate) fn note(copy: u64, at: usize, was: &[u8], new: &[u8]) {
if n == 0 {
return;
}
let at = at + skip;
let (mut was, new) = (was[skip..skip + n].to_vec(), new[skip..skip + n].to_vec());
let mut noted = NOTED.lock().unwrap_or_else(|e| e.into_inner());
noted.entry(copy).or_default().push(Taken {
at: at + skip,
was: was[skip..skip + n].to_vec(),
new: new[skip..skip + n].to_vec(),
});
let noted = noted.entry(copy).or_default();
// What was noted before in this submission has not gone up yet: the card
// knows what stood there before that. And what it took is not what goes
// up where this took it again.
for t in noted.iter_mut() {
let (a, b) = (at.max(t.at), (at + n).min(t.at + t.was.len()));
if a < b {
was[a - at..b - at].copy_from_slice(&t.was[a - t.at..b - t.at]);
t.new[a - t.at..b - t.at].copy_from_slice(&new[a - at..b - at]);
}
}
noted.push(Taken { at, was, new });
}
/// A submission's look at what it sends up, until it has run.
@@ -202,6 +211,11 @@ pub(super) fn record(
}
impl Looks {
/// Whether `shadow` was looked at: it is left in `COPY_DEST`.
pub(super) fn hold(&self, shadow: &Shadow) -> bool {
self.of.iter().any(|(s, _)| s.id() == shadow.id())
}
/// The submission has run: what it found is counted.
pub(super) fn read(self) {
// SAFETY: the mapping holds an answer for each; the card has run.
@@ -354,6 +368,69 @@ pub(super) fn reads(runs: &[&HostList]) {
}
}
/// The title's buffer copies that are out of their place in a submission:
/// by what is wrong, bytes and destination: how often, the last source, and
/// (for shader writes) how much was declared.
type Misplaced = BTreeMap<(&'static str, usize, usize), (u64, usize, usize)>;
static MISPLACED: Mutex<(u64, Misplaced)> = Mutex::new((0, BTreeMap::new()));
/// A submission is about to be prepared: its title buffer copies are done on
/// the CPU then, all of them before the first of its draws runs. Where that
/// is not the order of its lists: what an earlier draw of it reads of the
/// destination, or shaders of it write there, or an earlier copy of it put
/// there for what lies between; and a source that shaders of it write first.
pub(super) fn order(runs: &[&HostList]) {
let (mut read, mut written, mut copied): (Vec<(usize, usize)>, Vec<(usize, usize)>, Vec<(usize, usize)>) =
(Vec::new(), Vec::new(), Vec::new());
let meets = |all: &[(usize, usize)], from: usize, to: usize| all.iter().rev().find(|r| r.0 < to && from < r.1).copied();
let mut misplaced = MISPLACED.lock().unwrap_or_else(|e| e.into_inner());
for list in runs {
for step in &list.deferred().copies {
match step {
Step::Refresh(_, at, len) => read.push((*at, *at + *len)),
Step::GpuWrite(_, at, len) => written.push((*at, *at + *len)),
&Step::Copy(dst, src, len) => {
let mut say = |what: &'static str, range: (usize, usize)| {
let e = misplaced.1.entry((what, len, dst)).or_default();
*e = (e.0 + 1, src, range.1 - range.0);
};
if let Some(r) = meets(&written, src, src + len) {
say("its source is declared written earlier in the submission", r);
}
if let Some(r) = meets(&written, dst, dst + len) {
say("its destination is declared written earlier in the submission", r);
}
if let Some(r) = meets(&copied, dst, dst + len) {
say("its destination is copied to earlier in the submission", r);
} else if let Some(r) = meets(&read, dst, dst + len) {
say("its destination is read earlier in the submission", r);
}
copied.push((dst, dst + len));
}
_ => {}
}
}
}
let now = now_ms();
if now < misplaced.0 + 4000 {
return;
}
misplaced.0 = now;
let mut all: Vec<_> = std::mem::take(&mut misplaced.1).into_iter().collect();
all.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
let mut kinds: BTreeMap<&str, (u64, u64)> = BTreeMap::new();
for ((what, len, _), (n, ..)) in &all {
let e = kinds.entry(what).or_default();
*e = (e.0 + n, e.1 + n * *len as u64);
}
for (what, (n, bytes)) in kinds {
tracing::warn!("up-copy check, copies out of place: {n} ({bytes} bytes): {what}");
}
for ((what, len, dst), (n, src, declared)) in all.into_iter().take(16) {
tracing::warn!("up-copy check, a copy out of place: {n} times {len:#x} bytes from {src:#x} to {dst:#x}: {what} ({declared:#x} bytes there)");
}
}
/// A run of words that differ at rest.
struct Differs {
shadow: std::sync::Arc<Shadow>,
@@ -375,10 +452,42 @@ pub(super) fn at_rest(host: &Host) {
if look(host).is_none() {
tracing::warn!("up-copy check: the look at rest could not be made");
}
look_for_stale();
tracing::info!(ms = began.elapsed().as_millis(), "up-copy check: the look at rest is done");
LAST.store(now_ms(), Ordering::Relaxed);
}
/// At rest: copies of title memory, whatever reads them (meshes too), that
/// are not what title memory holds although nothing told that it changed: a
/// refresh will not bring them up to date.
fn look_for_stale() {
const MOST: usize = 1 << 30;
let mut by: BTreeMap<(u64, u64), (bool, u64, usize, Vec<String>)> = BTreeMap::new();
let compared = crate::shadow::stale_pages(MOST, &mut |shadow, page, words, (at, copy, title)| {
let e = by.entry(shadow.span()).or_insert((shadow.carded(), 0, 0, Vec::new()));
e.1 += words as u64;
e.2 += 1;
if e.3.len() < 4 {
e.3.push(format!("{words} words in the 64 KiB at {page:#x} (the first at {at:#x}: the copy {copy:#x}, title memory {title:#x})"));
}
});
tracing::info!(
"up-copy check at rest: {} MB of copies held for unchanged compared with title memory, {} copies are stale",
compared >> 20,
by.len()
);
let mut by: Vec<_> = by.into_iter().collect();
by.sort_by_key(|(_, e)| std::cmp::Reverse(e.1));
for ((start, len), (carded, words, pages, some)) in by.into_iter().take(16) {
tracing::warn!(
"up-copy check at rest, stale: {start:#x}+{len:#x} ({}): {words} words in {pages} pages are not title memory's, and nothing \
told of it: {}",
if carded { "on the card" } else { "in PC memory" },
some.join("; ")
);
}
}
/// Sends `list` (recorded by `f`) and waits for it.
fn run(host: &Host, f: impl FnOnce(&ID3D12GraphicsCommandList)) -> Option<()> {
let (allocator, list) = host.make_prelude()?;
@@ -567,6 +676,12 @@ mod tests {
/// Title memory of our own (write-watched, or a view of a section, which
/// is guarded), and the card copy of the title buffer it is.
fn title(resource: usize, view: bool) -> (&'static mut [u8], usize, std::sync::Arc<Shadow>) {
let all = title_of(resource, view, LEN);
assert!(all.2.carded(), "the copy is in the card's memory");
all
}
fn title_of(resource: usize, view: bool, len: usize) -> (&'static mut [u8], usize, std::sync::Arc<Shadow>) {
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE, VirtualAlloc,
};
@@ -574,20 +689,19 @@ mod tests {
// SAFETY: memory of our own, never freed.
let base = unsafe {
if view {
let section = CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, LEN as u32, std::ptr::null());
let section = CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
assert!(!section.is_null());
MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, LEN).Value.cast::<u8>()
MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value.cast::<u8>()
} else {
VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE).cast::<u8>()
VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE).cast::<u8>()
}
};
assert!(!base.is_null());
crate::shadow::register(resource, base as u64, LEN as u64);
crate::shadow::register(resource, base as u64, len as u64);
let shadow = crate::shadow::find(base as u64, 64).expect("a copy");
assert!(shadow.carded(), "the copy is in the card's memory");
assert!(super::super::relay_exact() && super::super::relay_copy(), "set VICTORY_RELAY=2 VICTORY_RELAY_COPY=1");
// SAFETY: `LEN` bytes just committed.
(unsafe { std::slice::from_raw_parts_mut(base, LEN) }, base as usize, shadow)
// SAFETY: `len` bytes just committed.
(unsafe { std::slice::from_raw_parts_mut(base, len) }, base as usize, shadow)
}
/// Work for the card that takes some milliseconds.
@@ -765,6 +879,81 @@ mod tests {
assert!(first <= 6 && back[first..].iter().all(|b| *b), "{back:?}");
}
/// The title copies another value to the same bytes in each of three
/// submissions, and each has a draw (a copy here) that reads them. The
/// card is busy meanwhile, so all three are prepared before the first
/// runs: each must read its own.
fn each_reads_its_own(len: usize, resource: usize, carded: bool) {
let Some(host) = host() else {
return;
};
let (title, start, shadow) = title_of(resource, true, len);
assert_eq!(shadow.carded(), carded, "where the copy is");
let slow = Slow::new(host);
let (out, out_data) = host.shared_buffer(1 << 16).unwrap();
let mut lists = Vec::new();
const AT: usize = 8192;
// All there once.
let all = host.new_list().unwrap();
shadow.refresh(&all, start as u64, len as u64);
all.close();
host.execute_own(&all);
settle_now(WHY_SYNC);
lists.push(all);
let mut wrong = Vec::new();
for round in 0..6u8 {
for v in 0..3u8 {
title[65_536 + usize::from(v) * 256..][..256].fill(round * 16 + v + 1);
}
let busy = host.new_list().unwrap();
slow.record(&busy, 40);
busy.close();
host.execute_own(&busy);
lists.push(busy);
for v in 0..3usize {
let list = host.new_list().unwrap();
list.defer_copy((start + AT) as *mut u8, (start + 65_536 + v * 256) as *const u8, 256);
shadow.refresh(&list, (start + AT) as u64, 256);
// SAFETY: an open list; live buffers.
unsafe {
list.list.CopyBufferRegion(&out, (v * 256) as u64, &shadow.buffer, AT as u64, 256);
}
list.close();
host.execute_own(&list);
lists.push(list);
}
settle_now(WHY_SYNC);
// SAFETY: a mapping of 64 KiB; the copies into it have run.
let read = unsafe { std::slice::from_raw_parts(out_data, 768) };
for v in 0..3u8 {
let got = read[usize::from(v) * 256];
if got != round * 16 + v + 1 {
wrong.push((round, v, got - round * 16));
}
}
}
eprintln!("read another submission's value (round, submission, whose + 1): {wrong:?}");
let stale = STALE.lock().unwrap_or_else(|e| e.into_inner());
let found = stale.get(&shadow.span()).map_or(0, |s| s.words);
eprintln!("the check at sends found {found} words");
assert!(wrong.is_empty());
assert_eq!(found, 0);
// With the debug layer (`VICTORY_D3D12_DEBUG=1`, diagnostics).
assert_eq!(host.log_messages(), None);
}
#[test]
#[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
fn each_submission_reads_its_own_copy_on_the_card() {
each_reads_its_own(LEN, 0x7777, true);
}
#[test]
#[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
fn each_submission_reads_its_own_copy_in_pc_memory() {
each_reads_its_own(256 << 10, 0x8888, std::env::var_os("VICTORY_CARD_ALL").is_some_and(|v| v == "1"));
}
/// Declared writes beside the title's own, in the same 64 KiB pieces and
/// dword by dword, flights landing while later ones are in the air: in
/// the end title memory and the card hold what each wrote last. (A byte
@@ -860,6 +1049,7 @@ mod tests {
on_card.is_empty() && in_title.is_empty(),
"round {round}: words {on_card:x?} on the card and {in_title:x?} in title memory are not what was written last"
);
assert_eq!(host.log_messages(), None);
}
}
}
+19 -3
View File
@@ -1,5 +1,5 @@
//! Buffers shaders write through views they pick from the heap by an index
//! they compute (`VICTORY_PICKED_WRITES=1`; off by default).
//! they compute (`VICTORY_PICKED_WRITES`; off by default, [`stage`]).
//!
//! Which views a draw or dispatch writes through is known from its tables
//! and root parameters, and their ranges are declared: what is written there
@@ -49,8 +49,24 @@ use crate::host::HostList;
use crate::shadow::Shadow;
pub(crate) fn on() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_PICKED_WRITES").is_some_and(|v| v == "1"))
stage() > 0
}
/// `VICTORY_PICKED_WRITES`: 0 (off), 1 (what is found is declared, so that
/// no refresh sends title memory over it while a flight may write it, and
/// not landed), 2 (landed too).
fn stage() -> u8 {
static STAGE: OnceLock<u8> = OnceLock::new();
*STAGE.get_or_init(|| match std::env::var("VICTORY_PICKED_WRITES").as_deref() {
Ok("1") => 1,
Ok("2") => 2,
_ => 0,
})
}
/// Whether what is found is landed.
pub(crate) fn lands() -> bool {
stage() > 1
}
/// Bytes looked at in turn per frame (`VICTORY_PICKED_MB`).
+198 -24
View File
@@ -108,7 +108,9 @@ struct Card {
/// side, each with the number of the send that took it
/// ([`card_dirty`]), kept until a fetch sent after it has been merged.
/// Locked inside `dirty`'s lock.
sent: Mutex<Vec<(usize, usize, u64)>>,
sent: Mutex<SentRuns>,
/// Whether something was put into `dirty` since it was last taken.
touched: std::sync::atomic::AtomicBool,
/// The buffers' bytes (the title buffer's, rounded up to 64 KiB).
size: u64,
}
@@ -202,11 +204,14 @@ fn card_limits() -> (u64, u64) {
*LIMITS.get_or_init(|| {
let env_mb = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<u64>().ok());
let vram_budget = crate::host::host().and_then(|h| h.video_memory()).map(|[budget, ..]| budget);
let (min_bytes, max_bytes) = resolve_card_limits(
let (mut min_bytes, max_bytes) = resolve_card_limits(
vram_budget,
env_mb("VICTORY_CARD_BUFFERS_MIN_MB"),
env_mb("VICTORY_CARD_BUFFERS_MB"),
);
if card_all() {
min_bytes = 0;
}
tracing::info!(
vram_budget_mb = vram_budget.map(|b| b >> 20),
card_buffers_min_mb = min_bytes >> 20,
@@ -253,6 +258,36 @@ pub(crate) fn card_hash_bytes(size: u64) -> u64 {
/// [`card_limits`] and below 1 GiB (the compare counts in 32 bits), and the
/// host has what it takes (`Host::card_ready`).
fn card_for(size: u64) -> Option<ID3D12Resource> {
let there = card_room_for(size);
if there.is_some() || !card_all() || size >= 1 << 30 {
return there;
}
// Two sides all the same, the card's in the PC's memory.
let host = host()?;
if !cards() || !host.card_ready() {
return None;
}
let (buffer, _) = host.shared_buffer(size)?;
CARD_BYTES[0].fetch_add(size, Ordering::Relaxed);
Some(buffer)
}
/// Whether every title buffer's copy has two sides, however small
/// (`VICTORY_CARD_ALL=1`; off by default).
///
/// A copy with one side, in the PC's memory, is what the card reads while
/// our refreshes write it: a submission that is prepared changes it under
/// the ones in the air ahead of it. The title's CPU does not write what they
/// still read, but its own buffer copies are done by us at preparing
/// (`crate::host::send` has the order of those right for copies with two
/// sides), and so are the bytes put in beside shaders' writes.
fn card_all() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ALL").is_some_and(|v| v == "1"))
}
/// [`card_for`] in the card's own memory.
fn card_room_for(size: u64) -> Option<ID3D12Resource> {
if !cards() {
return None;
}
@@ -341,6 +376,46 @@ fn window_card_for(size: u64) -> Option<ID3D12Resource> {
buffer
}
/// What went up, by send: its number, and the offsets, in order and joined
/// (a refresh sends thousands of runs of a few words).
#[derive(Default)]
struct SentRuns(Vec<(u64, Vec<(usize, usize)>)>);
impl SentRuns {
fn note(&mut self, number: u64, ranges: Vec<(usize, usize)>) {
if ranges.is_empty() {
return;
}
let ranges = joined(ranges);
match self.0.iter_mut().find(|s| s.0 == number) {
Some((_, all)) => *all = joined([std::mem::take(all), ranges].concat()),
None => self.0.push((number, ranges)),
}
}
/// Sends up to `number` are of no use any more.
fn forget(&mut self, number: u64) {
self.0.retain(|s| s.0 > number);
}
/// Adds to `out` what sends after `number` took of `[from, to)`.
fn near(&self, number: u64, from: usize, to: usize, out: &mut Vec<(usize, usize)>) {
for (_, ranges) in self.0.iter().filter(|s| s.0 > number) {
let first = ranges.partition_point(|r| r.1 <= from);
out.extend(ranges[first..].iter().take_while(|r| r.0 < to).copied());
}
}
#[cfg(test)]
fn of(all: &[(usize, usize, u64)]) -> SentRuns {
let mut sent = SentRuns::default();
for &(a, b, number) in all {
sent.note(number, vec![(a, b)]);
}
sent
}
}
/// The copies in the card's memory whose CPU side changed since they were
/// last asked: each with the changed offsets, in order and joined where
/// they touch. The ranges are taken: the caller copies them to the card's
@@ -363,13 +438,14 @@ pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc<Shadow>, Vec<(usize, usize)>)
let ranges = shadow
.card
.as_ref()
.filter(|c| c.touched.swap(false, Ordering::AcqRel))
.map(|c| {
let mut dirty = c.dirty.lock().unwrap_or_else(|e| e.into_inner());
let ranges = std::mem::take(&mut *dirty);
if relay() {
let mut sent = c.sent.lock().unwrap_or_else(|e| e.into_inner());
sent.retain(|s| s.2 > fetched);
sent.extend(ranges.iter().map(|&(a, b)| (a, b, sent_as)));
sent.forget(fetched);
sent.note(sent_as, ranges.clone());
}
ranges
})
@@ -382,6 +458,98 @@ pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc<Shadow>, Vec<(usize, usize)>)
out
}
/// Diagnostics (`crate::host::upcheck`, nothing in the air): copies whose
/// pages the write watch and the guards hold for unchanged since they were
/// taken, compared with title memory, `most` bytes a call in turn. `say` gets
/// the copy, the title address of a page that is not the same, the words that
/// differ and the first of them (its address, the copy's value, title
/// memory's). Returns the bytes compared.
pub(crate) fn stale_pages(most: usize, say: &mut dyn FnMut(&Shadow, usize, usize, (usize, u32, u32))) -> usize {
static NEXT: AtomicU64 = AtomicU64::new(0);
let mut all: Vec<Arc<Shadow>> = buffers().values().filter_map(|e| e.shadow.clone()).collect();
all.extend(LOOSE.lock().unwrap_or_else(|e| e.into_inner()).values().cloned());
all.retain(|s| s.place.is_none() && s.watched.load(Ordering::Relaxed) == 1);
all.sort_by_key(|s| s.id);
let next = NEXT.load(Ordering::Relaxed);
let turn = all.partition_point(|s| s.id < next);
let mut done = 0;
let mut title = vec![0u8; PAGE];
for shadow in all[turn..].iter().chain(&all[..turn]) {
if done >= most {
NEXT.store(shadow.id, Ordering::Relaxed);
break;
}
let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize);
// (What it finds written stays noted for the next refresh.)
let Some((_, written)) = crate::watch::writes(start, end, true) else {
continue;
};
let written: std::collections::HashMap<usize, u64> = written.into_iter().collect();
let copied = shadow.copied.lock().unwrap_or_else(|e| e.into_inner()).clone();
for (i, &at) in copied.iter().enumerate() {
let page = start / PAGE + i;
if at == 0 || written.get(&page).is_some_and(|&w| w > at) {
continue;
}
let (lo, hi) = ((page * PAGE).max(start), ((page + 1) * PAGE).min(end));
let title = &mut title[..hi - lo];
if !crate::host::read_into(lo as *const u8, title) {
continue;
}
done += hi - lo;
// SAFETY: inside the mapping; nothing is in the air and the
// submission lock is held.
let held = unsafe { std::slice::from_raw_parts(shadow.data.add(lo - start).cast_const(), hi - lo) };
if held == title {
continue;
}
let word = |b: &[u8], k: usize| u32::from_le_bytes([b[k], b[k + 1], b[k + 2], b[k + 3]]);
let differ: Vec<usize> = (0..(hi - lo) & !3).step_by(4).filter(|&k| word(held, k) != word(title, k)).collect();
// Written meanwhile: not stale, and the next refresh sees it.
let again = crate::watch::writes(lo, hi, true).is_none_or(|(_, w)| w.iter().any(|&(p, w)| p == page && w > at));
if let Some(&k) = differ.first()
&& !again
{
say(shadow, lo, differ.len(), (lo + k, word(held, k), word(title, k)));
}
}
}
done
}
/// Copies of memory (from, to, bytes: apart), on several threads if they are
/// many.
pub(crate) fn copy_all(copies: Vec<(usize, usize, usize)>) {
let bytes: usize = copies.iter().map(|c| c.2).sum();
if bytes > 4 << 20 {
wide(copy_jobs(copies));
return;
}
for (src, dst, len) in copies {
// SAFETY: the caller's ranges.
unsafe { std::ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, len) };
}
}
/// A title buffer copy was done on the CPU into `[dst, dst + len)`: all of it
/// goes up to the copies in the card's memory that hold it, whether their
/// CPU side held the same before or not. Left out is what shaders in the air
/// may be writing (such a copy waits for them, or is done on the card).
pub(crate) fn send_copied(dst: usize, len: usize) {
for shadow in carded_copies() {
let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize);
let (from, to) = (dst.max(start), (dst + len).min(end));
if from >= to {
continue;
}
let busy: Vec<(usize, usize)> =
shadow.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().copied().filter(|&(a, b)| a < to && b > from).collect();
for (a, b) in outside(from, to, busy) {
shadow.copy(a, b);
}
}
}
/// The copies in the card's memory (diagnostics: `crate::host::upcheck`).
pub(crate) fn carded_copies() -> Vec<Arc<Shadow>> {
CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter_map(std::sync::Weak::upgrade).collect()
@@ -2729,12 +2897,16 @@ impl Shadow {
return true;
}
*runs_left -= runs.len();
let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec());
for (r, m) in runs {
held[r..r + m].copy_from_slice(&title[r..r + m]);
self.card_changed(at + r, at + r + m);
MERGED[1].fetch_add(1, Ordering::Relaxed);
MERGED[2].fetch_add(m as u64, Ordering::Relaxed);
}
if let Some(was) = was {
crate::host::upcheck::note(self.id, at, &was, held);
}
} else {
let Some(snapshot) = before.as_mut() else {
note_stale(3);
@@ -3126,6 +3298,13 @@ impl Shadow {
_ => dirty.push((from, to)),
}
}
// (Under the lock: what takes the list sees it or finds it set.)
card.touched.store(true, Ordering::Release);
}
/// Of a copy in the card's memory: where its CPU side is.
pub(crate) fn card_data(&self) -> *const u8 {
self.data
}
/// Diagnostics: of a copy in the card's memory, what its CPU side holds
@@ -3333,12 +3512,9 @@ impl Shadow {
let skip: Vec<(usize, usize)> = {
let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner());
dirty
.iter()
.copied()
.chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1)))
.filter(|&(a, b)| a < at + n && b > at)
.collect()
let mut skip: Vec<(usize, usize)> = dirty.iter().copied().filter(|&(a, b)| a < at + n && b > at).collect();
sent.near(fetched_after, at, at + n, &mut skip);
skip
};
title.clear();
title.resize(n, 0);
@@ -3373,6 +3549,7 @@ impl Shadow {
before: Mutex::default(),
dirty: Mutex::default(),
sent: Mutex::default(),
touched: Default::default(),
size: len.next_multiple_of(PIECE as u64),
});
}
@@ -3393,8 +3570,8 @@ impl Shadow {
let mut dirty = card.dirty.lock().unwrap();
let ranges = std::mem::take(&mut *dirty);
let mut sent = card.sent.lock().unwrap();
sent.retain(|s| s.2 > merged);
sent.extend(ranges.iter().map(|&(a, b)| (a, b, number)));
sent.forget(merged);
sent.note(number, ranges.clone());
ranges
}
@@ -3430,12 +3607,9 @@ impl Shadow {
let skip: Vec<(usize, usize)> = {
let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner());
dirty
.iter()
.copied()
.chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1)))
.filter(|&(a, b)| a < to && b > from)
.collect()
let mut skip: Vec<(usize, usize)> = dirty.iter().copied().filter(|&(a, b)| a < to && b > from).collect();
sent.near(fetched_after, from, to, &mut skip);
skip
};
let mut put = 0;
for &(lo, hi, now) in pieces {
@@ -3528,6 +3702,7 @@ mod land_tests {
before: Mutex::default(),
dirty: Mutex::default(),
sent: Mutex::default(),
touched: Default::default(),
size: len as u64,
});
Some(shadow)
@@ -3603,7 +3778,7 @@ mod land_tests {
bytes(shadow.data as usize).copy_from_slice(&held);
let card = shadow.card.as_ref().expect("made with one");
*card.dirty.lock().unwrap() = dirty.clone();
*card.sent.lock().unwrap() = sent.clone();
*card.sent.lock().unwrap() = super::SentRuns::of(&sent);
}
let pieces: Vec<(usize, usize)> = (0..3).map(|p| (p * PIECE + 16, (p + 1) * PIECE - 4)).collect();
let mut scratch = Vec::new();
@@ -3662,10 +3837,7 @@ mod land_tests {
let card = shadow.card.as_ref().expect("made with one");
let mut dirty = card.dirty.lock().unwrap();
let mut sent = card.sent.lock().unwrap();
let moved: Vec<_> = std::mem::take(&mut *dirty).into_iter().map(|(a, b)| (a, b, 9)).collect();
sent.extend(moved);
sent.sort_unstable();
sent.dedup();
sent.note(9, std::mem::take(&mut *dirty));
}
});
let mut now = vec![0u8; LEN];
@@ -3832,7 +4004,7 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> {
// (`crate::inplace::place_for`): the buffer is the title's own
// memory. Not the big ones `cards` puts in the card's memory: those
// are read too often to stay in the PC's.
let big = cards() && size >= card_limits().0;
let big = cards() && (size >= card_limits().0 || card_all());
if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) {
entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false)));
return entry.shadow.clone();
@@ -3854,6 +4026,7 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> {
before: Mutex::default(),
dirty: Mutex::default(),
sent: Mutex::default(),
touched: Default::default(),
size,
};
(on_card, Some(card))
@@ -4070,6 +4243,7 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Sha
before: Mutex::default(),
dirty: Mutex::default(),
sent: Mutex::default(),
touched: Default::default(),
size: len,
};
(on_card, Some(card))