What goes up to card copies: a check, and fetches caught in between put right
VICTORY_FETCH_CHECK=1 (off by default): with VICTORY_RELAY_COPY a piece is fetched beside later submissions, and one of those that clears it and fills it again with the same is not flagged by its compare: title memory and the CPU's side kept what was in between, and the next refresh of the 64 KiB sent it up over the right bytes. The compare now gives the piece's hash with its flag; a fetch that is not that is made again by the next flight that may write the piece. (The test shows 11-12 of 12 wrong without it.) VICTORY_UPCOPY_CHECK=1 (diagnostics): at each send up, the words that the title did not change and the card holds another value of; every few seconds at rest, the words in which a copy's card side is not its CPU side, and whether they were declared as written and fetched. victory replay --upcopies: the same question of a captured frame, and which pieces were written undeclared (replay1 and replay2: compute 82a2ad6d07417d36 through views picked by index, 73-75 pieces a frame). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
65b4c43ec1
commit
017fb0b383
10 files changed
+1688
-54
No files matched your search
@@ -111,6 +111,11 @@ pub(crate) struct Replay {
|
||||
/// Name resources the frame changes that the replay does not put back.
|
||||
#[arg(long)]
|
||||
check_written: bool,
|
||||
/// Run the frame twice and say which words the copies of the CPU's sides
|
||||
/// of card buffers bring that the card holds another value of, and what
|
||||
/// shaders wrote that was not declared as written.
|
||||
#[arg(long)]
|
||||
upcopies: bool,
|
||||
/// Name what the heap slots hold that a command's constants name:
|
||||
/// `<list>:<command>`.
|
||||
#[arg(long)]
|
||||
@@ -182,6 +187,10 @@ pub(crate) fn run(r: Replay) -> Result<()> {
|
||||
let mut player = play::Player::load(&r.folder, &options)?;
|
||||
return player.check_written(&mut |line| println!("{line}"));
|
||||
}
|
||||
if r.upcopies {
|
||||
let mut player = play::Player::load(&r.folder, &options)?;
|
||||
return player.upcopies(&options, &mut |line| println!("{line}"));
|
||||
}
|
||||
let mut watched = Vec::new();
|
||||
for text in &r.watch {
|
||||
let mut n = text
|
||||
|
||||
@@ -1508,7 +1508,7 @@ struct CardWork {
|
||||
fetch: Prelude,
|
||||
root: ID3D12RootSignature,
|
||||
pso: ID3D12PipelineState,
|
||||
/// One dword per piece compared, set where the piece differs: PC
|
||||
/// One dword per piece compared, odd where the piece differs: PC
|
||||
/// memory, mapped (buffer, mapping, bytes).
|
||||
differs: (ID3D12Resource, usize, u64),
|
||||
/// Where the pieces that differ are fetched to: PC memory, mapped.
|
||||
@@ -1529,7 +1529,7 @@ static CARD_WORK: Mutex<Option<CardWork>> = Mutex::new(None);
|
||||
/// The compare of a declared range of a copy in the card's memory with
|
||||
/// its bytes from before, one group per 64 KiB piece (cut at multiples of
|
||||
/// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs`
|
||||
/// gets a dword per piece, 1 where a byte differs. The offsets are widened
|
||||
/// gets a dword per piece, odd where a byte differs. The offsets are widened
|
||||
/// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a
|
||||
/// byte just outside the range costs a fetch that finds nothing.
|
||||
///
|
||||
@@ -1579,7 +1579,9 @@ void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
|
||||
h = h.yzwx ^ (h >> 15);
|
||||
}
|
||||
if (compare != 0u) {
|
||||
differs.Store(out_at + id.x * 4u, any(h != hashes.Load4(piece * 16u)) ? 1u : 0u);
|
||||
// The flag, and above it 31 bits of the hash (`torn`).
|
||||
uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u);
|
||||
differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u));
|
||||
// With the copy-back on its own thread: the next compare of the
|
||||
// piece finds what is written from here on.
|
||||
if (compare == 2u) hashes.Store4(piece * 16u, h);
|
||||
@@ -1589,6 +1591,12 @@ void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) {
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The hash [`CARD_COMPARE`] gives of a piece with its flag.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn piece_hash(bytes: &[u8]) -> u32 {
|
||||
torn::hash(bytes)
|
||||
}
|
||||
|
||||
/// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from
|
||||
/// dword `at` on (`mode` as the shader's `compare`): a group per piece, in
|
||||
/// parts a dispatch can hold.
|
||||
@@ -1670,6 +1678,8 @@ struct CardPlan {
|
||||
/// With [`relay`]: the number of the send to copies in the card's memory
|
||||
/// that the submission ran behind ([`QUEUE_ORDER`]).
|
||||
sent_as: u64,
|
||||
/// With [`upcheck`]: the look at what it sent up.
|
||||
looks: Option<upcheck::Looks>,
|
||||
}
|
||||
|
||||
/// One piece of submission-time work, in recorded order.
|
||||
@@ -2660,6 +2670,8 @@ struct RelayFetch {
|
||||
sent: u64,
|
||||
/// Buffer, mapping, bytes.
|
||||
buffer: Option<(ID3D12Resource, usize, u64)>,
|
||||
/// Pieces caught while a later flight was writing them.
|
||||
suspects: torn::Suspects,
|
||||
}
|
||||
|
||||
/// The thread that lands flights ([`relay`]): as soon as the card has run
|
||||
@@ -2840,6 +2852,15 @@ fn late_line(frames: f64) {
|
||||
r[3] / 1000.0,
|
||||
r[4] / 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!(
|
||||
"fetched pieces checked per frame (VICTORY_FETCH_CHECK): {:.1}, of which {:.2} were not what their flight ended with (caught while a later flight was at them, or title bytes went up meanwhile); {:.2} were found whole when fetched again",
|
||||
t[0],
|
||||
t[1],
|
||||
t[2],
|
||||
);
|
||||
}
|
||||
}
|
||||
card_steps::log(frames);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
@@ -2855,6 +2876,8 @@ fn late_line(frames: f64) {
|
||||
}
|
||||
|
||||
mod card_steps;
|
||||
mod torn;
|
||||
pub(crate) mod upcheck;
|
||||
|
||||
#[cfg(test)]
|
||||
mod late_tests {
|
||||
@@ -3412,6 +3435,7 @@ impl Host {
|
||||
}
|
||||
}
|
||||
let mut used: Vec<(bool, Prelude)> = Vec::new();
|
||||
let mut looks = 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"));
|
||||
@@ -3424,6 +3448,9 @@ impl Host {
|
||||
(|| -> windows::core::Result<()> {
|
||||
allocator.Reset()?;
|
||||
list.Reset(allocator, None)?;
|
||||
if upcheck::on() {
|
||||
looks = upcheck::record(self, list, &dirty);
|
||||
}
|
||||
// Every copy first, then one barrier call, then every
|
||||
// pass: a wait between each copy and its pass had the
|
||||
// card do them one after the other.
|
||||
@@ -3493,6 +3520,7 @@ impl Host {
|
||||
_synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
|
||||
lists: used,
|
||||
sent_as,
|
||||
looks,
|
||||
};
|
||||
// Each byte once, as the copy-back joins the declared ranges. The
|
||||
// results go behind those of plans still in the air.
|
||||
@@ -3590,6 +3618,9 @@ impl Host {
|
||||
/// when nothing of ours is on the card, so the compare's results start
|
||||
/// from the beginning again.
|
||||
fn card_done(&self, plan: CardPlan) {
|
||||
if let Some(looks) = plan.looks {
|
||||
looks.read();
|
||||
}
|
||||
let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(work) = work.as_mut() else {
|
||||
return;
|
||||
@@ -3641,6 +3672,7 @@ impl Host {
|
||||
event,
|
||||
sent: 0,
|
||||
buffer: None,
|
||||
suspects: torn::Suspects::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3660,45 +3692,24 @@ impl Host {
|
||||
let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
|
||||
};
|
||||
let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
|
||||
let mut total = 0u64;
|
||||
if fetch.is_none() {
|
||||
*fetch = self.make_relay_fetch();
|
||||
}
|
||||
// On the copy queue a later flight may be at a piece while it is
|
||||
// fetched (`torn`).
|
||||
let mut suspects = fetch.as_mut().filter(|f| f.queue.is_some() && torn::on()).map(|f| std::mem::take(&mut f.suspects));
|
||||
let mut pieces = Vec::new();
|
||||
if let Some((differs, dwords)) = differs {
|
||||
// SAFETY: the mapping of the results. The compares of these
|
||||
// plans have run, and their dwords are given to no other plan
|
||||
// before these are done with (`card_done`).
|
||||
let differs = unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) };
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for plan in plans {
|
||||
let flags: Vec<(usize, u32, bool)> = plan
|
||||
.ranges
|
||||
.iter()
|
||||
.flat_map(|r| {
|
||||
(0..r.span.pieces).map(move |p| {
|
||||
let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| d != 0);
|
||||
(std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, flagged)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let fetched = flagged_pieces(&flags);
|
||||
for r in &plan.ranges {
|
||||
let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
|
||||
for p in 0..r.span.pieces {
|
||||
if !fetched.contains(&(copy, r.span.first + p)) {
|
||||
continue;
|
||||
}
|
||||
let (lo, hi) = r.shadow.card_piece(&r.span, p);
|
||||
if lo < hi && seen.insert((copy, lo, hi)) {
|
||||
pieces.push((r.shadow.clone(), lo, hi, total));
|
||||
total += (hi - lo) as u64;
|
||||
}
|
||||
}
|
||||
crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
|
||||
}
|
||||
pieces = torn::fetches(plans, differs, suspects.as_ref());
|
||||
for r in plans.iter().flat_map(|plan| &plan.ranges) {
|
||||
crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
if fetch.is_none() {
|
||||
*fetch = self.make_relay_fetch();
|
||||
}
|
||||
let total = pieces.last().map_or(0, |p| p.at + (p.to - p.from) as u64);
|
||||
// The sends these flights ran behind, all a fetch on the copy queue
|
||||
// is known to have run behind.
|
||||
let behind = plans.iter().map(|p| p.sent_as).max().unwrap_or(0);
|
||||
@@ -3710,6 +3721,9 @@ impl Host {
|
||||
false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
|
||||
};
|
||||
crate::shadow::relay_fetched(after);
|
||||
if let (Some(f), Some(suspects)) = (fetch.as_mut(), suspects) {
|
||||
f.suspects = suspects;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(f) = fetch.as_mut() else {
|
||||
@@ -3733,8 +3747,8 @@ impl Host {
|
||||
(|| -> windows::core::Result<u64> {
|
||||
allocator.Reset()?;
|
||||
list.Reset(&allocator, None)?;
|
||||
for (shadow, lo, hi, at) in &pieces {
|
||||
list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
|
||||
for p in &pieces {
|
||||
list.CopyBufferRegion(&buffer, p.at, &p.shadow.buffer, p.from as u64, (p.to - p.from) as u64);
|
||||
}
|
||||
list.Close()?;
|
||||
let lists = [Some(list.cast::<ID3D12CommandList>()?)];
|
||||
@@ -3773,13 +3787,22 @@ impl Host {
|
||||
}
|
||||
let mut title = Vec::new();
|
||||
let mut written = 0;
|
||||
for (shadow, lo, hi, at) in &pieces {
|
||||
for p in &pieces {
|
||||
// SAFETY: the mapping of the fetched bytes, `total` of them;
|
||||
// the copy into it has run.
|
||||
let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
|
||||
let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
|
||||
shadow.walls_merged(gpu.len(), merged);
|
||||
written += merged;
|
||||
let gpu = unsafe { std::slice::from_raw_parts((data + p.at as usize) as *const u8, p.to - p.from) };
|
||||
if let (Some((piece, Some(hash))), Some(suspects)) = (p.check, &mut suspects) {
|
||||
suspects.fetched((p.shadow.id(), piece), torn::hash(gpu) == hash);
|
||||
}
|
||||
for &(lo, hi) in &p.merged {
|
||||
let gpu = &gpu[lo - p.from..hi - p.from];
|
||||
let merged = p.shadow.card_merge_relay(lo, gpu, after, &mut title);
|
||||
p.shadow.walls_merged(gpu.len(), merged);
|
||||
written += merged;
|
||||
}
|
||||
}
|
||||
if let (Some(f), Some(suspects)) = (fetch.as_mut(), suspects) {
|
||||
f.suspects = suspects;
|
||||
}
|
||||
COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
|
||||
// Sends up to `after` are of no use to any later merge.
|
||||
@@ -3939,7 +3962,7 @@ impl Host {
|
||||
let mut total = 0u64;
|
||||
for (i, r) in plan.ranges.iter().enumerate() {
|
||||
for p in 0..r.span.pieces {
|
||||
if r.compared && differs[(r.at + p) as usize] == 0 {
|
||||
if r.compared && !torn::flagged(differs[(r.at + p) as usize]) {
|
||||
continue;
|
||||
}
|
||||
let (lo, hi) = r.shadow.card_piece(&r.span, p);
|
||||
@@ -4345,12 +4368,18 @@ impl Host {
|
||||
// one at every present).
|
||||
static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
if !behind {
|
||||
if upcheck::on() {
|
||||
upcheck::at_rest(self);
|
||||
}
|
||||
sweep();
|
||||
SWEPT.store(now_ms(), Ordering::Relaxed);
|
||||
} else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 {
|
||||
// With the present sent ahead nothing else brings a moment
|
||||
// with nothing in the air: one is made for the sweep.
|
||||
self.settle(&mut submitted, WHY_SYNC);
|
||||
if upcheck::on() {
|
||||
upcheck::at_rest(self);
|
||||
}
|
||||
sweep();
|
||||
SWEPT.store(now_ms(), Ordering::Relaxed);
|
||||
}
|
||||
@@ -4396,6 +4425,9 @@ 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 behind && stale_under_flights(runs) {
|
||||
let settling = std::time::Instant::now();
|
||||
self.settle(&mut submitted, WHY_STALE);
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
//! Pieces of card copies that came down while a later flight was writing
|
||||
//! them (`VICTORY_FETCH_CHECK`, with `VICTORY_RELAY_COPY`).
|
||||
//!
|
||||
//! On the copy queue a fetch runs beside later submissions (`relay_copy`),
|
||||
//! so what comes down of a piece may be what it held in the middle of one:
|
||||
//! a counter cleared and not counted up again, a list half filled. Such
|
||||
//! bytes went into title memory and the copy's CPU side, to be put right by
|
||||
//! that submission's own landing, which fetches what its compare flagged.
|
||||
//! But the compare flags a piece only if it is not, at the submission's end,
|
||||
//! what it was at the end of the one before. A piece cleared and filled
|
||||
//! again with the same is not flagged, is not fetched, and the CPU's side
|
||||
//! keeps the bytes from in between: until they go up with a refresh of
|
||||
//! their 64 KiB, over the right ones.
|
||||
//!
|
||||
//! So the compare gives each piece's hash with its flag, and what came down
|
||||
//! is hashed here too. The same hash: it is what the flight ended with. Not
|
||||
//! the same: the piece is suspect (another flight was at it, or the title's
|
||||
//! bytes went up to it meanwhile), and the next flight that may write it
|
||||
//! fetches it whatever its compare says, until a fetch is found whole.
|
||||
//!
|
||||
//! What it costs: pieces are fetched whole where a flight declared a part
|
||||
//! of one, and 64 KiB of what came down are hashed (some 4 us) just before
|
||||
//! they are merged, which reads them again.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// `VICTORY_FETCH_CHECK=1`; off by default until a run has shown how often a
|
||||
/// piece is caught (the frame-rate line says so) and what the hashes cost
|
||||
/// (3-4 ms of the landing thread's time for 96 MB, beside the merge).
|
||||
pub(super) fn on() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_FETCH_CHECK").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
/// A piece: its copy's number, and the piece.
|
||||
pub(super) type Piece = (u64, u32);
|
||||
|
||||
/// Since the last frame-rate line: pieces fetched and hashed, those found
|
||||
/// suspect, and those fetched because an earlier fetch was.
|
||||
pub(super) static STATS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
|
||||
|
||||
/// The pieces whose last fetch was not what a flight ended with.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Suspects(HashSet<Piece>);
|
||||
|
||||
impl Suspects {
|
||||
/// Whether a flight that may write `piece` fetches it, its compare
|
||||
/// having flagged it or not.
|
||||
pub(super) fn wanted(&self, piece: Piece, flagged: bool) -> bool {
|
||||
flagged || self.0.contains(&piece)
|
||||
}
|
||||
|
||||
/// `piece` was fetched; `same`: it was what the last of the flights
|
||||
/// landed ended with.
|
||||
pub(super) fn fetched(&mut self, piece: Piece, same: bool) {
|
||||
STATS[0].fetch_add(1, Ordering::Relaxed);
|
||||
if same {
|
||||
if self.0.remove(&piece) {
|
||||
STATS[2].fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
} else {
|
||||
self.0.insert(piece);
|
||||
STATS[1].fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A piece to fetch.
|
||||
pub(super) struct Fetch {
|
||||
pub(super) shadow: std::sync::Arc<crate::shadow::Shadow>,
|
||||
/// The offsets fetched, and where they come down.
|
||||
pub(super) from: usize,
|
||||
pub(super) to: usize,
|
||||
pub(super) at: u64,
|
||||
/// The offsets merged: what flights declared of it.
|
||||
pub(super) merged: Vec<(usize, usize)>,
|
||||
/// With the check: the piece, and the hash the last flight that may
|
||||
/// have written it ended with.
|
||||
pub(super) check: Option<(u32, Option<u32>)>,
|
||||
}
|
||||
|
||||
/// What is fetched for `plans`, whose compares' results are in `differs`.
|
||||
/// With `suspects`, pieces are fetched whole, with the hash to compare.
|
||||
pub(super) fn fetches(plans: &[&CardPlan], differs: &[u32], suspects: Option<&Suspects>) -> Vec<Fetch> {
|
||||
let mut out: Vec<Fetch> = Vec::new();
|
||||
let mut total = 0u64;
|
||||
let mut seen = HashSet::new();
|
||||
// With `suspects`: where each piece is in `out`.
|
||||
let mut index: HashMap<Piece, usize> = HashMap::new();
|
||||
for plan in plans {
|
||||
let flags: Vec<(usize, u32, bool)> = plan
|
||||
.ranges
|
||||
.iter()
|
||||
.flat_map(|r| {
|
||||
(0..r.span.pieces).map(move |p| {
|
||||
let piece = r.span.first + p;
|
||||
let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| flagged(d));
|
||||
let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), piece), flagged));
|
||||
(std::sync::Arc::as_ptr(&r.shadow) as usize, piece, wanted)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let fetched = flagged_pieces(&flags);
|
||||
for r in &plan.ranges {
|
||||
let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
|
||||
if upcheck::on() {
|
||||
upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize);
|
||||
}
|
||||
for p in 0..r.span.pieces {
|
||||
let piece = r.span.first + p;
|
||||
if !fetched.contains(&(copy, piece)) {
|
||||
continue;
|
||||
}
|
||||
let (lo, hi) = r.shadow.card_piece(&r.span, p);
|
||||
if lo >= hi || !seen.insert((copy, lo, hi)) {
|
||||
continue;
|
||||
}
|
||||
if upcheck::on() {
|
||||
upcheck::fetched(r.shadow.id(), lo);
|
||||
}
|
||||
if suspects.is_none() {
|
||||
out.push(Fetch {
|
||||
shadow: r.shadow.clone(),
|
||||
from: lo,
|
||||
to: hi,
|
||||
at: total,
|
||||
merged: vec![(lo, hi)],
|
||||
check: None,
|
||||
});
|
||||
total += (hi - lo) as u64;
|
||||
continue;
|
||||
}
|
||||
let i = *index.entry((r.shadow.id(), piece)).or_insert_with(|| {
|
||||
let (from, to) = r.shadow.card_hashed(piece);
|
||||
out.push(Fetch {
|
||||
shadow: r.shadow.clone(),
|
||||
from,
|
||||
to,
|
||||
at: total,
|
||||
merged: Vec::new(),
|
||||
check: Some((piece, None)),
|
||||
});
|
||||
total += (to - from) as u64;
|
||||
out.len() - 1
|
||||
});
|
||||
out[i].merged.push((lo, hi));
|
||||
}
|
||||
}
|
||||
}
|
||||
if suspects.is_some() {
|
||||
// The hash of the last flight that may have written the piece.
|
||||
for plan in plans {
|
||||
for r in plan.ranges.iter().filter(|r| r.compared) {
|
||||
for p in 0..r.span.pieces {
|
||||
if let Some(&i) = index.get(&(r.shadow.id(), r.span.first + p))
|
||||
&& let Some(&d) = differs.get((r.at + p) as usize)
|
||||
&& let Some((_, hash)) = &mut out[i].check
|
||||
{
|
||||
*hash = Some(folded(d));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Of a result of the compare: whether the piece differs.
|
||||
pub(super) fn flagged(result: u32) -> bool {
|
||||
result & 1 != 0
|
||||
}
|
||||
|
||||
/// Of a result of the compare: the piece's hash, 31 bits of it.
|
||||
pub(super) fn folded(result: u32) -> u32 {
|
||||
result >> 1
|
||||
}
|
||||
|
||||
/// The hash the compare on the card ([`CARD_COMPARE`]) makes of a piece
|
||||
/// that holds `bytes` (a multiple of 16 of them), as [`folded`].
|
||||
pub(super) fn hash(bytes: &[u8]) -> u32 {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
if std::is_x86_feature_detected!("avx2") {
|
||||
// SAFETY: the feature is there.
|
||||
return unsafe { hash_avx2(bytes) };
|
||||
}
|
||||
hash_plain(bytes)
|
||||
}
|
||||
|
||||
const MUL: [u32; 4] = [0x0100_0193, 0x9E37_79B1, 0x85EB_CA77, 0xC2B2_AE3D];
|
||||
const SEED: [u32; 4] = [0x9E37_79B9, 0x85EB_CA6B, 0xC2B2_AE35, 0x27D4_EB2F];
|
||||
|
||||
fn step(h: &mut [u32; 4], with: [u32; 4]) {
|
||||
let x: [u32; 4] = std::array::from_fn(|i| (h[i] ^ with[i]).wrapping_mul(MUL[i]));
|
||||
*h = std::array::from_fn(|i| x[(i + 1) % 4] ^ (x[i] >> 15));
|
||||
}
|
||||
|
||||
/// The 64 threads' hashes as one, folded to 31 bits.
|
||||
fn finish(parts: &[[u32; 4]; 64]) -> u32 {
|
||||
let mut h = parts[0];
|
||||
for part in &parts[1..] {
|
||||
step(&mut h, *part);
|
||||
}
|
||||
let f = h[0] ^ h[1].wrapping_mul(3) ^ h[2].wrapping_mul(5) ^ h[3].wrapping_mul(7);
|
||||
f & 0x7FFF_FFFF
|
||||
}
|
||||
|
||||
fn seeds() -> [[u32; 4]; 64] {
|
||||
std::array::from_fn(|thread| SEED.map(|s| s.wrapping_add(thread as u32)))
|
||||
}
|
||||
|
||||
fn tail(parts: &mut [[u32; 4]; 64], bytes: &[u8]) {
|
||||
for (thread, chunk) in bytes.chunks_exact(16).enumerate() {
|
||||
let with = std::array::from_fn(|i| u32::from_le_bytes([chunk[i * 4], chunk[i * 4 + 1], chunk[i * 4 + 2], chunk[i * 4 + 3]]));
|
||||
step(&mut parts[thread], with);
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_plain(bytes: &[u8]) -> u32 {
|
||||
let mut parts = seeds();
|
||||
for row in bytes.chunks(1024) {
|
||||
tail(&mut parts, row);
|
||||
}
|
||||
finish(&parts)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
#[target_feature(enable = "avx2")]
|
||||
fn hash_avx2(bytes: &[u8]) -> u32 {
|
||||
use std::arch::x86_64::*;
|
||||
let mut parts = seeds();
|
||||
let rows = bytes.chunks_exact(1024);
|
||||
let rest = rows.remainder();
|
||||
let mul = _mm256_setr_epi32(
|
||||
MUL[0] as i32, MUL[1] as i32, MUL[2] as i32, MUL[3] as i32, MUL[0] as i32, MUL[1] as i32, MUL[2] as i32, MUL[3] as i32,
|
||||
);
|
||||
let state = parts.as_mut_ptr().cast::<__m256i>();
|
||||
for row in rows {
|
||||
let from = row.as_ptr().cast::<__m256i>();
|
||||
for k in 0..32 {
|
||||
// SAFETY: two threads' hashes of 16 bytes each, and their 32 of
|
||||
// the row's 1,024 bytes.
|
||||
unsafe {
|
||||
let h = _mm256_xor_si256(_mm256_loadu_si256(state.add(k)), _mm256_loadu_si256(from.add(k)));
|
||||
let x = _mm256_mullo_epi32(h, mul);
|
||||
// y, z, w, x of each.
|
||||
let turned = _mm256_shuffle_epi32::<0b00_11_10_01>(x);
|
||||
_mm256_storeu_si256(state.add(k), _mm256_xor_si256(turned, _mm256_srli_epi32::<15>(x)));
|
||||
}
|
||||
}
|
||||
}
|
||||
tail(&mut parts, rest);
|
||||
finish(&parts)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_wide_hash_is_the_plain_one() {
|
||||
let bytes: Vec<u8> = (0..65_536u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect();
|
||||
for n in [0usize, 16, 32, 1008, 1024, 1040, 5000 & !15, 65_536] {
|
||||
assert_eq!(hash(&bytes[..n]), hash_plain(&bytes[..n]), "{n} bytes");
|
||||
}
|
||||
let mut other = bytes.clone();
|
||||
other[40_000] ^= 1;
|
||||
assert_ne!(hash(&bytes), hash(&other));
|
||||
}
|
||||
|
||||
/// A model of one piece. The card runs flights in order; each writes the
|
||||
/// piece several times and its compare flags it if it ends otherwise
|
||||
/// than the flight before. Each landing fetches what is wanted, on a
|
||||
/// queue beside the drawing one: the fetch sees the piece as it is while
|
||||
/// a later flight is at some step. Returns what the CPU's side holds in
|
||||
/// the end, and the fetches.
|
||||
fn landed(flights: &[&[u32]], seen: &[(usize, usize)], check: bool) -> (u32, u32) {
|
||||
let piece: Piece = (1, 0);
|
||||
let mut suspects = Suspects::default();
|
||||
let (mut held, mut ended, mut fetches) = (0, 0, 0);
|
||||
for (f, steps) in flights.iter().enumerate() {
|
||||
let before = ended;
|
||||
ended = *steps.last().expect("a step");
|
||||
let flagged = ended != before;
|
||||
if if check { !suspects.wanted(piece, flagged) } else { !flagged } {
|
||||
continue;
|
||||
}
|
||||
fetches += 1;
|
||||
// While flight `at` is after its step `step`.
|
||||
let (at, step) = seen[f];
|
||||
assert!(at >= f);
|
||||
held = flights[at][step];
|
||||
suspects.fetched(piece, held == ended);
|
||||
}
|
||||
(held, fetches)
|
||||
}
|
||||
|
||||
/// A counter that each flight clears and counts up to the same: the
|
||||
/// first flight's fetch sees it cleared by the second, whose compare
|
||||
/// flags nothing.
|
||||
#[test]
|
||||
fn a_piece_caught_in_between_is_fetched_again() {
|
||||
let count: &[u32] = &[0, 3, 5];
|
||||
// The first is fetched while the second has cleared it.
|
||||
assert_eq!(landed(&[count, count], &[(1, 0), (1, 2)], false), (0, 1), "the CPU's side keeps what was in between");
|
||||
assert_eq!(landed(&[count, count], &[(1, 0), (1, 2)], true), (5, 2));
|
||||
// And again, while the third was at it; the fourth finds it whole.
|
||||
let four = [count; 4];
|
||||
assert_eq!(landed(&four, &[(1, 0), (2, 1), (3, 0), (3, 2)], true), (5, 4));
|
||||
// Fetched whole: no more fetches than without the check.
|
||||
assert_eq!(landed(&four, &[(0, 2), (1, 2), (2, 2), (3, 2)], true), (5, 1));
|
||||
assert_eq!(landed(&four, &[(0, 2), (1, 2), (2, 2), (3, 2)], false), (5, 1));
|
||||
}
|
||||
|
||||
/// What the hash costs (ignored: a measurement): pieces that just came
|
||||
/// down, hashed alone, compared with what the CPU's side holds (as the
|
||||
/// merge begins), and both.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn hash_costs() {
|
||||
let (bytes, held) = (vec![0x5Au8; 96 << 20], vec![0x5Au8; 96 << 20]);
|
||||
let pieces = || bytes.chunks(64 << 10).zip(held.chunks(64 << 10));
|
||||
let compare = |a: &[u8], b: &[u8]| a.chunks(4096).zip(b.chunks(4096)).filter(|(a, b)| a != b).count() as u32;
|
||||
for _ in 0..5 {
|
||||
let mut all = 0u32;
|
||||
let mut time = |f: &dyn Fn(&[u8], &[u8]) -> u32| {
|
||||
let t = std::time::Instant::now();
|
||||
for (a, b) in pieces() {
|
||||
all ^= f(a, b);
|
||||
}
|
||||
t.elapsed().as_secs_f64() * 1e3
|
||||
};
|
||||
let (hashed, compared, both) = (
|
||||
time(&|a, _| hash(a)),
|
||||
time(&compare),
|
||||
time(&|a, b| hash(a) ^ compare(a, b)),
|
||||
);
|
||||
println!("96 MB: hashed {hashed:.2} ms, compared {compared:.2} ms, both {both:.2} ms ({all:#x})");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,821 @@
|
||||
//! Diagnostics (`VICTORY_UPCOPY_CHECK=1`; off by default): whether what goes
|
||||
//! up to a copy in the card's memory is older than what the card holds.
|
||||
//!
|
||||
//! What every send up rests on: outside ranges shaders may be writing, and
|
||||
//! but for what the title wrote since, a copy's CPU side holds what its card
|
||||
//! side holds. Two looks at that, both on the card:
|
||||
//!
|
||||
//! - **at each send**: a refresh tells what the CPU's side held before
|
||||
//! ([`note`]) and what it took. Ahead of the send, in its place on the
|
||||
//! queue, the card's words are compared with the former. A word the title
|
||||
//! did not change (both are equal) and the card holds another value of is
|
||||
//! one the send puts an older value over;
|
||||
//! - **at rest**: every few seconds, when the flights were settled for the
|
||||
//! sweep and nothing is in the air, every copy is compared whole with its
|
||||
//! CPU side. A word that differs is one a later send would undo. The log
|
||||
//! line says which buffers, what stands on the card, on the CPU's side and
|
||||
//! in title memory, and whether the range was declared as written at all
|
||||
//! (if not: a shader writes through a view nobody declared) and fetched
|
||||
//! lately (if so: what came down was not what the card ended with).
|
||||
//!
|
||||
//! The looks cost memory and time (the bytes sent twice more, and each
|
||||
//! copy read over the bus at rest): the check is not for runs that are timed.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use windows::Win32::Foundation::CloseHandle;
|
||||
|
||||
use super::*;
|
||||
use crate::shadow::Shadow;
|
||||
|
||||
pub(crate) fn on() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_UPCOPY_CHECK").is_some_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
/// One dispatch looks at up to a piece: `words` words of the card's buffer
|
||||
/// from `at`, beside `was` (what the CPU's side held when both were known to
|
||||
/// be alike) and `new` (what the title has there now). Where the two are
|
||||
/// equal and the card's word is another one, it is counted, and the first
|
||||
/// found is kept: its offset, the card's value, the CPU's.
|
||||
const SOURCE: &str = r#"
|
||||
#define RS "RootConstants(num32BitConstants=5, b0), SRV(t0), SRV(t1), UAV(u0)"
|
||||
cbuffer Look : register(b0) { uint at; uint words; uint was; uint now; uint found_at; };
|
||||
ByteAddressBuffer card : register(t0);
|
||||
ByteAddressBuffer cpu : register(t1);
|
||||
RWByteAddressBuffer found : register(u0);
|
||||
[RootSignature(RS)]
|
||||
[numthreads(64, 1, 1)]
|
||||
void main(uint3 id : SV_DispatchThreadID) {
|
||||
if (id.x >= words) return;
|
||||
uint k = id.x * 4u, n;
|
||||
uint c = card.Load(at + k), w = cpu.Load(was + k);
|
||||
if (c == w || cpu.Load(now + k) != w) return;
|
||||
found.InterlockedAdd(found_at, 1u, n);
|
||||
if (n == 0u) found.Store3(found_at + 4u, uint3(at + k, c, w));
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Bytes of an answer.
|
||||
const ANSWER: u64 = 16;
|
||||
const PIECE: usize = 64 << 10;
|
||||
|
||||
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(SOURCE, 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()?;
|
||||
Some(Pass { root, pso })
|
||||
}
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// A piece a refresh took: its offset in the copy, what the CPU's side held
|
||||
/// and what it holds now.
|
||||
pub(crate) struct Taken {
|
||||
at: usize,
|
||||
was: Vec<u8>,
|
||||
new: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Refreshes since the last send, per copy (by its number).
|
||||
static NOTED: Mutex<BTreeMap<u64, Vec<Taken>>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
/// At most this much is looked at per submission.
|
||||
const MOST: usize = 128 << 20;
|
||||
|
||||
/// Offsets `[at, at + was.len())` of `copy`'s CPU side held `was` and hold
|
||||
/// `new` from here on. (Whole words: a word only partly in it is left out.)
|
||||
pub(crate) fn note(copy: u64, at: usize, was: &[u8], new: &[u8]) {
|
||||
let skip = at.wrapping_neg() & 3;
|
||||
let n = was.len().min(new.len()).saturating_sub(skip) & !3;
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
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(),
|
||||
});
|
||||
}
|
||||
|
||||
/// A submission's look at what it sends up, until it has run.
|
||||
pub(super) struct Looks {
|
||||
found: (ID3D12Resource, usize),
|
||||
_bytes: ID3D12Resource,
|
||||
/// Per answer: the copy, and the bytes looked at.
|
||||
of: Vec<(std::sync::Arc<Shadow>, usize)>,
|
||||
}
|
||||
|
||||
/// Per copy, since the last line: sends looked at, their bytes, words an
|
||||
/// older value went over, and the first few of them.
|
||||
#[derive(Default)]
|
||||
struct Stale {
|
||||
looked: u64,
|
||||
bytes: u64,
|
||||
sends: u64,
|
||||
words: u64,
|
||||
some: Vec<String>,
|
||||
}
|
||||
|
||||
static STALE: Mutex<BTreeMap<(u64, u64), Stale>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
/// Records the looks at what `dirty` sends up into `list`, ahead of the
|
||||
/// sends.
|
||||
pub(super) fn record(
|
||||
host: &Host,
|
||||
list: &ID3D12GraphicsCommandList,
|
||||
dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)],
|
||||
) -> Option<Looks> {
|
||||
let mut noted = std::mem::take(&mut *NOTED.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
let mut all: Vec<(std::sync::Arc<Shadow>, Taken)> = Vec::new();
|
||||
let mut total = 0;
|
||||
for (shadow, _) in dirty {
|
||||
for taken in noted.remove(&shadow.id()).unwrap_or_default() {
|
||||
total += 2 * taken.was.len();
|
||||
if total <= MOST {
|
||||
all.push((shadow.clone(), taken));
|
||||
}
|
||||
}
|
||||
}
|
||||
if all.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let pass = pass(host)?;
|
||||
let (bytes, to) = host.shared_buffer(total.min(MOST) as u64)?;
|
||||
let size = (all.len() as u64 * ANSWER).next_multiple_of(256);
|
||||
let (found, answers) = host.shared_buffer(size)?;
|
||||
// SAFETY: mappings of the sizes asked for; an open list, whose compute
|
||||
// state is set whole by what follows; live buffers, the ranges in them.
|
||||
unsafe {
|
||||
std::ptr::write_bytes(answers, 0, size as usize);
|
||||
list.SetComputeRootSignature(&pass.root);
|
||||
list.SetPipelineState(&pass.pso);
|
||||
list.SetComputeRootShaderResourceView(2, bytes.GetGPUVirtualAddress());
|
||||
list.SetComputeRootUnorderedAccessView(3, found.GetGPUVirtualAddress());
|
||||
let mut at = 0usize;
|
||||
for (i, (shadow, taken)) in all.iter().enumerate() {
|
||||
let n = taken.was.len();
|
||||
std::ptr::copy_nonoverlapping(taken.was.as_ptr(), to.add(at), n);
|
||||
std::ptr::copy_nonoverlapping(taken.new.as_ptr(), to.add(at + n), n);
|
||||
list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
|
||||
let constants = [taken.at as u32, (n / 4) as u32, at as u32, (at + n) as u32, (i as u64 * ANSWER) as u32];
|
||||
list.SetComputeRoot32BitConstants(0, 5, constants.as_ptr().cast(), 0);
|
||||
list.Dispatch((n / 4).div_ceil(64) as u32, 1, 1);
|
||||
at += 2 * n;
|
||||
}
|
||||
// The sends come after the looks.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let done: Vec<D3D12_RESOURCE_BARRIER> = all
|
||||
.iter()
|
||||
.filter(|(s, _)| seen.insert(std::sync::Arc::as_ptr(s) as usize))
|
||||
.map(|(s, _)| transition(&s.buffer, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST))
|
||||
.collect();
|
||||
list.ResourceBarrier(&done);
|
||||
}
|
||||
Some(Looks {
|
||||
found: (found, answers as usize),
|
||||
_bytes: bytes,
|
||||
of: all.into_iter().map(|(s, t)| (s, t.was.len())).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
impl Looks {
|
||||
/// 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.
|
||||
let answers = unsafe { std::slice::from_raw_parts(self.found.1 as *const [u32; 4], self.of.len()) };
|
||||
let mut stale = STALE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for ((shadow, bytes), &[words, at, card, cpu]) in self.of.iter().zip(answers) {
|
||||
let (start, len) = shadow.span();
|
||||
let e = stale.entry((start, len)).or_default();
|
||||
e.looked += 1;
|
||||
e.bytes += *bytes as u64;
|
||||
if words > 0 {
|
||||
e.sends += 1;
|
||||
e.words += u64::from(words);
|
||||
if e.some.len() < 4 {
|
||||
e.some.push(format!("{words} words from +{at:#x} (card {card:#x}, sent {cpu:#x}; {})", known(shadow.id(), at as usize)));
|
||||
}
|
||||
}
|
||||
}
|
||||
line(&mut stale);
|
||||
}
|
||||
}
|
||||
|
||||
/// Once a second: what was found since.
|
||||
fn line(stale: &mut BTreeMap<(u64, u64), Stale>) {
|
||||
static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let now = now_ms();
|
||||
let said = SAID.load(Ordering::Relaxed);
|
||||
if now < said + 1000 || SAID.compare_exchange(said, now, Ordering::Relaxed, Ordering::Relaxed).is_err() {
|
||||
return;
|
||||
}
|
||||
let all = std::mem::take(stale);
|
||||
let sum = |f: fn(&Stale) -> u64| all.values().map(f).sum::<u64>();
|
||||
tracing::info!(
|
||||
frame = crate::frame::current(),
|
||||
"up-copy check: {} pieces ({} KB) sent up again in {} buffers; {} of them put an older value over {} words the card had written",
|
||||
sum(|s| s.looked),
|
||||
sum(|s| s.bytes) >> 10,
|
||||
all.len(),
|
||||
sum(|s| s.sends),
|
||||
sum(|s| s.words),
|
||||
);
|
||||
let mut worst: Vec<_> = all.into_iter().filter(|(_, s)| s.words > 0).collect();
|
||||
worst.sort_by_key(|(_, s)| std::cmp::Reverse(s.words));
|
||||
for ((start, len), s) in worst.into_iter().take(12) {
|
||||
tracing::warn!(
|
||||
"up-copy check: older values sent up to {start:#x}+{len:#x}: {} words in {} pieces: {}",
|
||||
s.words,
|
||||
s.sends,
|
||||
s.some.join(", ")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Of a copy: the ranges shaders were declared to write (joined), and the
|
||||
/// frame each piece was last fetched in.
|
||||
#[derive(Default)]
|
||||
struct Known {
|
||||
declared: Vec<(usize, usize)>,
|
||||
fetched: HashMap<usize, u64>,
|
||||
}
|
||||
|
||||
static KNOWN: Mutex<BTreeMap<u64, Known>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
/// Offsets `[from, to)` of a copy were declared as written.
|
||||
pub(super) fn declared(copy: u64, from: usize, to: usize) {
|
||||
let mut known = KNOWN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let known = known.entry(copy).or_default();
|
||||
if !known.declared.iter().any(|r| r.0 <= from && to <= r.1) {
|
||||
join_ranges(&mut known.declared, [(from, to)]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A piece from offset `at` on of a copy was fetched.
|
||||
pub(super) fn fetched(copy: u64, at: usize) {
|
||||
let mut known = KNOWN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
known.entry(copy).or_default().fetched.insert(at / PIECE, crate::frame::current());
|
||||
}
|
||||
|
||||
fn known(copy: u64, at: usize) -> String {
|
||||
let all = KNOWN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(known) = all.get(©) else {
|
||||
return "no shader was declared to write the buffer".into();
|
||||
};
|
||||
if !touches(&known.declared, at, at + 4) {
|
||||
return "never declared as written there".into();
|
||||
}
|
||||
// (Fetched pieces begin where title memory's do; the copy may begin
|
||||
// inside one.)
|
||||
let last = [at / PIECE, (at / PIECE).saturating_sub(1)].iter().filter_map(|p| known.fetched.get(p)).max().copied();
|
||||
match last {
|
||||
Some(frame) => format!("declared; last fetched {} frames ago", crate::frame::current().saturating_sub(frame)),
|
||||
None => "declared; never fetched".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads of title memory through one copy while a flight in the air may
|
||||
/// write it through another: (reader, writer) by their spans: how often, and
|
||||
/// the last range they share.
|
||||
type Crossed = BTreeMap<((u64, u64), (u64, u64)), (u64, usize, usize)>;
|
||||
static CROSSED: Mutex<(u64, Crossed)> = Mutex::new((0, BTreeMap::new()));
|
||||
|
||||
/// Flights are in the air and `runs` are about to be prepared: which
|
||||
/// refreshes of theirs read title memory that a flight may be writing through
|
||||
/// another copy of it. Such a refresh takes what was there before the flight
|
||||
/// (nothing waits for it), and no later one knows that it was too early but
|
||||
/// for the landing's own write.
|
||||
pub(super) fn reads(runs: &[&HostList]) {
|
||||
let mut writes: Vec<(std::sync::Arc<Shadow>, usize, usize)> = Vec::new();
|
||||
let mut all = Vec::new();
|
||||
for item in &super::line().line {
|
||||
if let Late::Run(flight) = item {
|
||||
for (shadow, ranges) in &flight.back {
|
||||
writes.extend(ranges.iter().map(|&(a, b)| (shadow.clone(), a, b)));
|
||||
join_ranges(&mut all, ranges.iter().copied());
|
||||
}
|
||||
}
|
||||
}
|
||||
if writes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut crossed = CROSSED.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for list in runs {
|
||||
for step in &list.deferred().copies {
|
||||
let Step::Refresh(shadow, at, len) = step else {
|
||||
continue;
|
||||
};
|
||||
let (from, to) = (*at, *at + *len);
|
||||
if !touches(&all, from, to) {
|
||||
continue;
|
||||
}
|
||||
for (writer, a, b) in &writes {
|
||||
if *a < to && from < *b && !std::sync::Arc::ptr_eq(writer, shadow) {
|
||||
let e = crossed.1.entry((shadow.span(), writer.span())).or_default();
|
||||
*e = (e.0 + 1, (*a).max(from), (*b).min(to));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let now = now_ms();
|
||||
if now < crossed.0 + 4000 {
|
||||
return;
|
||||
}
|
||||
crossed.0 = now;
|
||||
let mut all: Vec<_> = std::mem::take(&mut crossed.1).into_iter().collect();
|
||||
all.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
|
||||
for (((r, rn), (w, wn)), (n, a, b)) in all.into_iter().take(12) {
|
||||
tracing::warn!(
|
||||
"up-copy check: {n} refreshes of {r:#x}+{rn:#x} read title memory that flights in the air may write through {w:#x}+{wn:#x} (the last at {a:#x}..{b:#x})"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A run of words that differ at rest.
|
||||
struct Differs {
|
||||
shadow: std::sync::Arc<Shadow>,
|
||||
at: usize,
|
||||
len: usize,
|
||||
words: u32,
|
||||
}
|
||||
|
||||
/// Nothing is in the air, and nothing is sent meanwhile (the submission
|
||||
/// lock is held): compares every copy in the card's memory with its CPU
|
||||
/// side, every few seconds.
|
||||
pub(super) fn at_rest(host: &Host) {
|
||||
static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let now = now_ms();
|
||||
if now < LAST.load(Ordering::Relaxed) + 4000 {
|
||||
return;
|
||||
}
|
||||
let began = std::time::Instant::now();
|
||||
if look(host).is_none() {
|
||||
tracing::warn!("up-copy check: the look at rest could not be made");
|
||||
}
|
||||
tracing::info!(ms = began.elapsed().as_millis(), "up-copy check: the look at rest is done");
|
||||
LAST.store(now_ms(), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Sends `list` (recorded by `f`) and waits for it.
|
||||
fn run(host: &Host, f: impl FnOnce(&ID3D12GraphicsCommandList)) -> Option<()> {
|
||||
let (allocator, list) = host.make_prelude()?;
|
||||
// SAFETY: objects of our own, waited for before they go.
|
||||
unsafe {
|
||||
allocator.Reset().ok()?;
|
||||
list.Reset(&allocator, None).ok()?;
|
||||
f(&list);
|
||||
list.Close().ok()?;
|
||||
let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
|
||||
let event = CreateEventW(None, false, false, None).ok()?;
|
||||
host.queue.ExecuteCommandLists(&[Some(list.cast().ok()?)]);
|
||||
let done = host.queue.Signal(&fence, 1).and_then(|()| fence.SetEventOnCompletion(1, event));
|
||||
if done.is_ok() {
|
||||
WaitForSingleObject(event, INFINITE);
|
||||
}
|
||||
let _ = CloseHandle(event);
|
||||
done.ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// The words that differ.
|
||||
fn look(host: &Host) -> Option<u64> {
|
||||
let pass = pass(host)?;
|
||||
let copies = crate::shadow::carded_copies();
|
||||
// (copy, offset, bytes)
|
||||
let mut pieces: Vec<(std::sync::Arc<Shadow>, usize, usize)> = Vec::new();
|
||||
for shadow in &copies {
|
||||
// What has not gone up yet differs rightly.
|
||||
let dirty = shadow.card_dirty_now();
|
||||
let len = shadow.span().1 as usize & !3;
|
||||
for at in (0..len).step_by(PIECE) {
|
||||
let n = PIECE.min(len - at);
|
||||
if !dirty.iter().any(|&(a, b)| a < at + n && b > at) {
|
||||
pieces.push((shadow.clone(), at, n));
|
||||
}
|
||||
}
|
||||
}
|
||||
if pieces.is_empty() {
|
||||
return Some(0);
|
||||
}
|
||||
let size = (pieces.len() as u64 * ANSWER).next_multiple_of(256);
|
||||
let (found, answers) = host.shared_buffer(size)?;
|
||||
// SAFETY: a mapping of that size.
|
||||
unsafe { std::ptr::write_bytes(answers, 0, size as usize) };
|
||||
run(host, |list| {
|
||||
// SAFETY: an open list; live buffers (held by `pieces`).
|
||||
unsafe {
|
||||
list.SetComputeRootSignature(&pass.root);
|
||||
list.SetPipelineState(&pass.pso);
|
||||
list.SetComputeRootUnorderedAccessView(3, found.GetGPUVirtualAddress());
|
||||
let mut bound = 0;
|
||||
for (i, (shadow, at, n)) in pieces.iter().enumerate() {
|
||||
let Some((staging, ..)) = shadow.card_sides() else {
|
||||
continue;
|
||||
};
|
||||
if bound != shadow.id() {
|
||||
bound = shadow.id();
|
||||
list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
|
||||
list.SetComputeRootShaderResourceView(2, staging.GetGPUVirtualAddress());
|
||||
}
|
||||
let at = *at as u32;
|
||||
let constants = [at, (*n / 4) as u32, at, at, (i as u64 * ANSWER) as u32];
|
||||
list.SetComputeRoot32BitConstants(0, 5, constants.as_ptr().cast(), 0);
|
||||
list.Dispatch((*n / 4).div_ceil(64) as u32, 1, 1);
|
||||
}
|
||||
}
|
||||
})?;
|
||||
// SAFETY: the mapping holds an answer for each; the card has run.
|
||||
let answers = unsafe { std::slice::from_raw_parts(answers as *const [u32; 4], pieces.len()) };
|
||||
let differs: Vec<Differs> = pieces
|
||||
.iter()
|
||||
.zip(answers)
|
||||
.filter(|(_, a)| a[0] > 0)
|
||||
.map(|((shadow, at, len), a)| Differs {
|
||||
shadow: shadow.clone(),
|
||||
at: *at,
|
||||
len: *len,
|
||||
words: a[0],
|
||||
})
|
||||
.collect();
|
||||
let bytes: u64 = pieces.iter().map(|p| p.2 as u64).sum();
|
||||
let words: u64 = differs.iter().map(|d| u64::from(d.words)).sum();
|
||||
tracing::info!(
|
||||
frame = crate::frame::current(),
|
||||
"up-copy check at rest: {} copies, {} MB; {words} words in {} pieces of them differ from the CPU's side",
|
||||
copies.len(),
|
||||
bytes >> 20,
|
||||
differs.len()
|
||||
);
|
||||
if differs.is_empty() {
|
||||
return Some(0);
|
||||
}
|
||||
// Per copy, what stands where, of a few pieces.
|
||||
const SHOWN: usize = 64;
|
||||
let shown = &differs[..differs.len().min(SHOWN)];
|
||||
let (held, data) = host.shared_buffer((SHOWN * PIECE) as u64)?;
|
||||
run(host, |list| {
|
||||
for (i, d) in shown.iter().enumerate() {
|
||||
// SAFETY: an open list; live buffers, the ranges in them.
|
||||
unsafe { list.CopyBufferRegion(&held, (i * PIECE) as u64, &d.shadow.buffer, d.at as u64, d.len as u64) };
|
||||
}
|
||||
})?;
|
||||
let mut by: BTreeMap<(u64, u64), (u64, usize, Vec<String>)> = BTreeMap::new();
|
||||
for d in &differs {
|
||||
let e = by.entry(d.shadow.span()).or_default();
|
||||
e.0 += u64::from(d.words);
|
||||
e.1 += 1;
|
||||
}
|
||||
for (i, d) in shown.iter().enumerate() {
|
||||
let (start, _) = d.shadow.span();
|
||||
// SAFETY: the mapping; the copy into it has run.
|
||||
let card = unsafe { std::slice::from_raw_parts(data.add(i * PIECE).cast_const(), d.len) };
|
||||
let cpu = d.shadow.card_held(d.at, d.len);
|
||||
let mut title = vec![0u8; d.len];
|
||||
let mapped = read_into((start as usize + d.at) as *const u8, &mut title);
|
||||
// Of the words that differ: title memory holds the CPU side's
|
||||
// value, the card's, another one.
|
||||
let (mut as_cpu, mut as_card, mut other) = (0, 0, 0);
|
||||
let mut first = None;
|
||||
let (mut low, mut high) = (usize::MAX, 0);
|
||||
for at in (0..d.len & !3).step_by(4) {
|
||||
let word = |b: &[u8]| u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]);
|
||||
let (c, h, t) = (word(card), word(&cpu), word(&title));
|
||||
if c == h {
|
||||
continue;
|
||||
}
|
||||
(low, high) = (low.min(at), at);
|
||||
first.get_or_insert((at, c, h, t));
|
||||
if t == h {
|
||||
as_cpu += 1;
|
||||
} else if t == c {
|
||||
as_card += 1;
|
||||
} else {
|
||||
other += 1;
|
||||
}
|
||||
}
|
||||
let Some((at, c, h, t)) = first else {
|
||||
continue;
|
||||
};
|
||||
if let Some(e) = by.get_mut(&d.shadow.span())
|
||||
&& e.2.len() < 6
|
||||
{
|
||||
e.2.push(format!(
|
||||
"{} words in +{:#x}..{:#x} (title memory: {as_cpu} as the CPU's side, {as_card} as the card, {other} neither{}; first: \
|
||||
card {c:#x}, CPU {h:#x}, title {t:#x}; {})",
|
||||
d.words,
|
||||
d.at + low,
|
||||
d.at + high + 4,
|
||||
if mapped { "" } else { ", not all mapped" },
|
||||
known(d.shadow.id(), d.at + at)
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut by: Vec<_> = by.into_iter().collect();
|
||||
by.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
|
||||
for ((start, len), (words, pieces, some)) in by.into_iter().take(16) {
|
||||
tracing::warn!(
|
||||
"up-copy check at rest: {start:#x}+{len:#x}: {words} words in {pieces} pieces are not the CPU side's: {}",
|
||||
some.join("; ")
|
||||
);
|
||||
}
|
||||
Some(words)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn notes_are_cut_to_whole_words() {
|
||||
// Bytes 5..18 of a copy: the words at 8 and 12.
|
||||
let (was, new): (Vec<u8>, Vec<u8>) = ((5..18).collect(), (105..118).collect());
|
||||
note(u64::MAX, 5, &was, &new);
|
||||
let noted = NOTED.lock().unwrap_or_else(|e| e.into_inner()).remove(&u64::MAX).expect("noted");
|
||||
let [t] = ¬ed[..] else { panic!("one piece") };
|
||||
assert_eq!((t.at, &t.was[..], &t.new[..]), (8, &was[3..11], &new[3..11]));
|
||||
}
|
||||
|
||||
/// The tests below want processes of their own with the relay on: each
|
||||
/// `VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 VICTORY_UPCOPY_CHECK=1 cargo
|
||||
/// test -p victory-gpu --lib upcheck -- --ignored --test-threads=1
|
||||
/// <name>`.
|
||||
const LEN: usize = 4 << 20;
|
||||
|
||||
/// 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>) {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE, VirtualAlloc,
|
||||
};
|
||||
const WRITE_WATCH: u32 = 0x20_0000;
|
||||
// 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());
|
||||
assert!(!section.is_null());
|
||||
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>()
|
||||
}
|
||||
};
|
||||
assert!(!base.is_null());
|
||||
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)
|
||||
}
|
||||
|
||||
/// Work for the card that takes some milliseconds.
|
||||
struct Slow(ID3D12Resource, ID3D12Resource);
|
||||
|
||||
impl Slow {
|
||||
fn new(host: &Host) -> Slow {
|
||||
Slow(host.uav_buffer(64 << 20).unwrap(), host.uav_buffer(64 << 20).unwrap())
|
||||
}
|
||||
|
||||
fn record(&self, list: &HostList, times: usize) {
|
||||
// SAFETY: an open list; live buffers.
|
||||
unsafe {
|
||||
for _ in 0..times {
|
||||
list.list.CopyBufferRegion(&self.1, 0, &self.0, 0, 64 << 20);
|
||||
list.list.ResourceBarrier(&[
|
||||
transition(&self.1, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shader's stand-in: `bytes` go to offset `at` of the copy.
|
||||
fn write(host: &Host, list: &HostList, shadow: &Shadow, at: usize, bytes: &[u8]) {
|
||||
let (upload, data) = host.upload_buffer(bytes.len() as u64).unwrap();
|
||||
// SAFETY: the mapping; an open list and live buffers.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len());
|
||||
list.list.CopyBufferRegion(&shadow.buffer, at as u64, &upload, 0, bytes.len() as u64);
|
||||
list.list
|
||||
.ResourceBarrier(&[transition(&shadow.buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]);
|
||||
}
|
||||
list.keep(&upload);
|
||||
}
|
||||
|
||||
/// What the card's side holds, nothing being in the air.
|
||||
fn card(host: &Host, shadow: &Shadow) -> Vec<u8> {
|
||||
let (held, data) = host.shared_buffer(LEN as u64).unwrap();
|
||||
// SAFETY: an open list; live buffers.
|
||||
run(host, |list| unsafe { list.CopyBufferRegion(&held, 0, &shadow.buffer, 0, LEN as u64) }).unwrap();
|
||||
// SAFETY: the mapping; the copy has run.
|
||||
unsafe { std::slice::from_raw_parts(data, LEN) }.to_vec()
|
||||
}
|
||||
|
||||
/// (e) of the list in `Host::relay_card_back`'s fetch: a flight's result
|
||||
/// is fetched while the next flight is at the same bytes, which ends with
|
||||
/// what it found. Without `VICTORY_FETCH_CHECK` title memory keeps what
|
||||
/// was in between, and the next refresh of the 64 KiB sends it up.
|
||||
#[test]
|
||||
#[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
|
||||
fn a_result_caught_in_between_is_put_right() {
|
||||
let Some(host) = host() else {
|
||||
return;
|
||||
};
|
||||
let (title, start, shadow) = title(0x3333, false);
|
||||
let slow = Slow::new(host);
|
||||
let (mut wrong, mut undone) = (0, 0);
|
||||
let mut lists = Vec::new();
|
||||
const ROUNDS: usize = 12;
|
||||
for round in 0..ROUNDS {
|
||||
let result: Vec<u8> = (0..256).map(|i| (round * 17 + i + 1) as u8).collect();
|
||||
let between = vec![0u8; 256];
|
||||
let a = host.new_list().unwrap();
|
||||
shadow.refresh(&a, start as u64, LEN as u64);
|
||||
shadow.gpu_writes(&a, start as u64, LEN as u64);
|
||||
write(host, &a, &shadow, 1024, &result);
|
||||
a.close();
|
||||
let b = host.new_list().unwrap();
|
||||
shadow.gpu_writes(&b, start as u64, LEN as u64);
|
||||
write(host, &b, &shadow, 1024, &between);
|
||||
slow.record(&b, 60);
|
||||
write(host, &b, &shadow, 1024, &result);
|
||||
b.close();
|
||||
host.execute_own(&a);
|
||||
host.execute_own(&b);
|
||||
settle_now(WHY_SYNC);
|
||||
wrong += usize::from(title[1024..1280] != result[..]);
|
||||
// The title writes beside it: the refresh takes the 64 KiB.
|
||||
title[4096] = round as u8 + 1;
|
||||
let c = host.new_list().unwrap();
|
||||
shadow.refresh(&c, start as u64, LEN as u64);
|
||||
c.close();
|
||||
host.execute_own(&c);
|
||||
settle_now(WHY_SYNC);
|
||||
let holds = card(host, &shadow);
|
||||
assert_eq!(holds[4096], round as u8 + 1, "the title's write is on the card");
|
||||
undone += usize::from(holds[1024..1280] != result[..]);
|
||||
lists.extend([a, b, c]);
|
||||
}
|
||||
eprintln!(
|
||||
"{wrong} of {ROUNDS} results wrong in title memory, {undone} undone on the card; pieces checked, suspect, put right: {:?}",
|
||||
super::torn::STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(look(host), Some(0));
|
||||
assert_eq!((wrong, undone), (0, 0), "without VICTORY_FETCH_CHECK=1 most are wrong");
|
||||
}
|
||||
|
||||
/// What nobody declared: a shader writes a piece through a view that was
|
||||
/// not known. The title writes another byte of the piece: it goes up
|
||||
/// whole, with title memory's older bytes, and the check says so.
|
||||
#[test]
|
||||
#[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 VICTORY_UPCOPY_CHECK=1 and a process of its own"]
|
||||
fn the_check_finds_an_undeclared_write_undone() {
|
||||
let Some(host) = host() else {
|
||||
return;
|
||||
};
|
||||
assert!(on(), "set VICTORY_UPCOPY_CHECK=1");
|
||||
let (title, start, shadow) = title(0x4444, false);
|
||||
let a = host.new_list().unwrap();
|
||||
shadow.refresh(&a, start as u64, LEN as u64);
|
||||
shadow.gpu_writes(&a, start as u64, 1 << 16);
|
||||
write(host, &a, &shadow, (5 << 16) + 512, &[0x77; 64]);
|
||||
a.close();
|
||||
host.execute_own(&a);
|
||||
settle_now(WHY_SYNC);
|
||||
assert_eq!(card(host, &shadow)[(5 << 16) + 512], 0x77);
|
||||
assert!(title[(5 << 16) + 512] == 0, "it never comes back");
|
||||
assert_eq!(look(host), Some(16), "the look at rest finds it");
|
||||
title[(5 << 16) + 9000] = 1;
|
||||
let b = host.new_list().unwrap();
|
||||
shadow.refresh(&b, start as u64, LEN as u64);
|
||||
b.close();
|
||||
host.execute_own(&b);
|
||||
settle_now(WHY_SYNC);
|
||||
let undone = card(host, &shadow)[(5 << 16) + 512] == 0;
|
||||
let stale = STALE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let found = stale.get(&shadow.span()).map_or(0, |s| s.words);
|
||||
eprintln!("undone on the card: {undone}; the check found {found} words");
|
||||
assert_eq!((undone, found), (true, 16));
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// is written by flights or by the title, not both at a time.)
|
||||
#[test]
|
||||
#[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
|
||||
fn declared_writes_beside_the_titles_own_stay() {
|
||||
let Some(host) = host() else {
|
||||
return;
|
||||
};
|
||||
for view in [false, true] {
|
||||
beside(host, 0x5555 + usize::from(view), view);
|
||||
}
|
||||
}
|
||||
|
||||
fn beside(host: &Host, resource: usize, view: bool) {
|
||||
let (title, start, shadow) = title(resource, view);
|
||||
let slow = Slow::new(host);
|
||||
// A small generator: the runs are the same each time.
|
||||
let mut seed = 0x1234_5678_9abc_def1u64;
|
||||
let mut next = move |n: usize| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed >> 11) as usize % n
|
||||
};
|
||||
// What memory should hold: pieces 0..8 are used, words of them by
|
||||
// turns the title's (even) and the shaders' (odd).
|
||||
const USED: usize = 8 << 16;
|
||||
let mut model = vec![0u8; USED];
|
||||
let mut lists = Vec::new();
|
||||
for round in 0..800usize {
|
||||
// The title writes some of its words, flights in the air or not.
|
||||
for _ in 0..next(24) {
|
||||
let at = next(USED / 8) * 8;
|
||||
let value = ((round as u32) << 8 | next(256) as u32).to_le_bytes();
|
||||
title[at..at + 4].copy_from_slice(&value);
|
||||
model[at..at + 4].copy_from_slice(&value);
|
||||
}
|
||||
// A submission: reads all or a part, writes a declared part.
|
||||
let list = host.new_list().unwrap();
|
||||
let (from, to) = match next(4) {
|
||||
0 => (0, LEN),
|
||||
1 => {
|
||||
let a = next(8) << 16;
|
||||
(a, a + (1 << 16))
|
||||
}
|
||||
_ => {
|
||||
let a = next(USED - 4096) & !255;
|
||||
(a, a + 256 * (1 + next(16)))
|
||||
}
|
||||
};
|
||||
shadow.refresh(&list, (start + from) as u64, (to - from) as u64);
|
||||
if next(5) > 0 {
|
||||
shadow.gpu_writes(&list, (start + from) as u64, (to - from) as u64);
|
||||
if next(3) == 0 {
|
||||
slow.record(&list, 1 + next(3));
|
||||
}
|
||||
for _ in 0..1 + next(6) {
|
||||
let words = (to.min(USED) - from) / 8;
|
||||
let at = from + next(words) * 8 + 4;
|
||||
// Now and then something in between first.
|
||||
if next(4) == 0 {
|
||||
write(host, &list, &shadow, at, &[0xEE; 4]);
|
||||
slow.record(&list, 1);
|
||||
}
|
||||
let value = if next(3) == 0 { [7, 7, 7, 7] } else { (0x8000_0000 | (round as u32) << 8 | next(256) as u32).to_le_bytes() };
|
||||
write(host, &list, &shadow, at, &value);
|
||||
model[at..at + 4].copy_from_slice(&value);
|
||||
}
|
||||
}
|
||||
list.close();
|
||||
host.execute_own(&list);
|
||||
lists.push(list);
|
||||
if round % 40 == 39 {
|
||||
// Everything refreshed, landed and looked at.
|
||||
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);
|
||||
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);
|
||||
assert_eq!(look(host), Some(0), "round {round}: the card's side is the CPU's side");
|
||||
let holds = card(host, &shadow);
|
||||
let wrong = |held: &[u8]| (0..USED / 4).filter(|w| held[w * 4..w * 4 + 4] != model[w * 4..w * 4 + 4]).collect::<Vec<_>>();
|
||||
let (on_card, in_title) = (wrong(&holds), wrong(title));
|
||||
assert!(
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -773,7 +773,17 @@ void main() {
|
||||
}
|
||||
warp.submit_and_wait();
|
||||
// SAFETY: as above.
|
||||
[0, 1, 2].map(|piece| unsafe { differs_ptr.cast::<u32>().add(piece).read_volatile() })
|
||||
let found = [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::<u32>().add(piece).read_volatile() });
|
||||
if mode == 0 {
|
||||
return found;
|
||||
}
|
||||
// Above the flag, the hash: as `host::torn` makes it of the bytes.
|
||||
for (piece, d) in found.iter().enumerate() {
|
||||
// SAFETY: inside the mapping, which the card has read.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(now_ptr.add(piece * PIECE).cast_const(), PIECE) };
|
||||
assert_eq!(d >> 1, crate::host::piece_hash(bytes), "piece {piece}");
|
||||
}
|
||||
found.map(|d| d & 1)
|
||||
};
|
||||
let at = PIECE + 1234;
|
||||
// SAFETY (each): inside the mapping.
|
||||
|
||||
@@ -31,6 +31,7 @@ use super::wire::{
|
||||
|
||||
pub mod diverge;
|
||||
mod merge;
|
||||
mod upcopies;
|
||||
|
||||
/// The name of the argument clamp's pipeline, by which its passes are
|
||||
/// recognised.
|
||||
|
||||
@@ -12,19 +12,19 @@ const PIECE: usize = 64 << 10;
|
||||
|
||||
/// Where a run's contents come down: for each resource (and subresource) the
|
||||
/// frame writes, its place in read-back memory.
|
||||
struct Reader {
|
||||
pub(super) struct Reader {
|
||||
blocks: Vec<(ID3D12Resource, usize)>,
|
||||
parts: Vec<Part>,
|
||||
pub(super) parts: Vec<Part>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Part {
|
||||
id: u32,
|
||||
pub(super) struct Part {
|
||||
pub(super) id: u32,
|
||||
/// `None` for a buffer.
|
||||
sub: Option<(u32, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)>,
|
||||
block: usize,
|
||||
at: u64,
|
||||
len: u64,
|
||||
pub(super) len: u64,
|
||||
}
|
||||
|
||||
/// One way to run commands `from..to` of a list.
|
||||
@@ -275,7 +275,7 @@ impl Player {
|
||||
}
|
||||
|
||||
/// The states of textures at the frame's start.
|
||||
fn start_states(&self) -> States {
|
||||
pub(super) fn start_states(&self) -> States {
|
||||
let mut states = States::default();
|
||||
for (id, all) in &self.start {
|
||||
let Some(o) = self.objects.get(id) else {
|
||||
@@ -412,7 +412,7 @@ impl Player {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reader(&self, ids: &[u32]) -> Result<Reader> {
|
||||
pub(super) fn reader(&self, ids: &[u32]) -> Result<Reader> {
|
||||
const BLOCK: u64 = 512 << 20;
|
||||
let mut parts = Vec::new();
|
||||
let mut sizes: Vec<u64> = vec![0];
|
||||
@@ -514,7 +514,7 @@ impl Player {
|
||||
}
|
||||
|
||||
/// Hashes of all parts' pieces, as memory is now (in `states`).
|
||||
fn hashes_now(&mut self, reader: &Reader, states: &States) -> Result<Vec<Vec<u64>>> {
|
||||
pub(super) fn hashes_now(&mut self, reader: &Reader, states: &States) -> Result<Vec<Vec<u64>>> {
|
||||
let objects = &self.objects;
|
||||
for block in 0..reader.blocks.len() {
|
||||
let parts: Vec<&Part> = reader.parts.iter().filter(|p| p.block == block).collect();
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
//! The copies of the CPU's sides of card buffers up to them, looked at: do
|
||||
//! they bring words older than what the card holds? And do the frame's
|
||||
//! shaders write card buffers outside what the host layer had declared as
|
||||
//! written (its compare passes cover that)?
|
||||
|
||||
use super::*;
|
||||
|
||||
/// As the host layer cuts buffers.
|
||||
const PIECE: u64 = 64 << 10;
|
||||
|
||||
/// A copy up: submission, source, destination, offset, length.
|
||||
type Up = (usize, u32, u32, u64, u64);
|
||||
|
||||
/// A word a copy brings that the card holds another value of: its offset,
|
||||
/// what the card holds, what was last put there before the card wrote, what
|
||||
/// is brought.
|
||||
type Word = (u64, [u32; 3]);
|
||||
|
||||
impl Player {
|
||||
/// The copies up in a submission's lists.
|
||||
fn ups(&self, submit: usize, lists: &[Vec<Cmd>]) -> Vec<Up> {
|
||||
let mut out = Vec::new();
|
||||
for c in lists.iter().flatten() {
|
||||
if self.merged_copy(c).is_some()
|
||||
&& let Cmd::CopyBuffer {
|
||||
dst,
|
||||
dst_at,
|
||||
src,
|
||||
len,
|
||||
..
|
||||
} = c
|
||||
{
|
||||
out.push((submit, *src, *dst, *dst_at, *len));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where pieces begin in a card buffer, and those the host layer's
|
||||
/// compares look at in a submission.
|
||||
fn declared(&self, lists: &[Vec<Cmd>]) -> HashMap<u32, (u64, HashSet<u64>)> {
|
||||
let compares = self.pipelines_named(COMPARE);
|
||||
let mut out: HashMap<u32, (u64, HashSet<u64>)> = HashMap::new();
|
||||
for cmds in lists {
|
||||
let (mut bound, mut constants, mut of) = (NONE, Vec::new(), NONE);
|
||||
for c in cmds {
|
||||
match c {
|
||||
Cmd::Pipeline { pso } => bound = *pso,
|
||||
Cmd::Constants {
|
||||
graphics: false,
|
||||
param: 0,
|
||||
values,
|
||||
..
|
||||
} => constants = values.clone(),
|
||||
Cmd::RootView {
|
||||
graphics: false,
|
||||
param: 1,
|
||||
va: Va::At { res, .. },
|
||||
..
|
||||
} => of = *res,
|
||||
Cmd::Dispatch { .. }
|
||||
if compares.contains(&bound)
|
||||
&& constants.len() >= 6
|
||||
&& constants[5] != 0 =>
|
||||
{
|
||||
let e = out
|
||||
.entry(of)
|
||||
.or_insert((u64::from(constants[1]), HashSet::new()));
|
||||
e.1.extend((constants[0]..constants[0] + constants[3]).map(u64::from));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Bytes of buffers, as they are now.
|
||||
fn slices(&mut self, all: &[(ID3D12Resource, u64, u64)]) -> Result<Vec<Vec<u8>>> {
|
||||
let total: u64 = all.iter().map(|a| a.2).sum();
|
||||
if total == 0 {
|
||||
return Ok(vec![Vec::new(); all.len()]);
|
||||
}
|
||||
let (back, data) = gpu::buffer(
|
||||
&self.device,
|
||||
D3D12_HEAP_TYPE_READBACK,
|
||||
total,
|
||||
D3D12_RESOURCE_FLAG_NONE,
|
||||
)?;
|
||||
self.worker.run(|list| {
|
||||
let mut at = 0;
|
||||
for (res, from, len) in all {
|
||||
// SAFETY: an open list; live buffers, ranges inside them.
|
||||
unsafe { list.CopyBufferRegion(&back, at, res, *from, *len) };
|
||||
at += len;
|
||||
}
|
||||
})?;
|
||||
let mut at = 0usize;
|
||||
Ok(all
|
||||
.iter()
|
||||
.map(|(_, _, len)| {
|
||||
// SAFETY: the mapping; the copies into it have run.
|
||||
let bytes =
|
||||
unsafe { std::slice::from_raw_parts(data.add(at), *len as usize) }.to_vec();
|
||||
at += *len as usize;
|
||||
bytes
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The heap slots that show a buffer, a few of each kind.
|
||||
fn views_of(&self, id: u32) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut shown = |kind: u8, at: String| {
|
||||
let what = if kind == slot::UAV { "uav" } else { "srv" };
|
||||
if out.iter().filter(|l: &&String| l.starts_with(what)).count() < 6 {
|
||||
out.push(format!("{what} {at}"));
|
||||
}
|
||||
};
|
||||
for h in &self.frame.descriptor_heaps {
|
||||
for (first, n, s) in h.runs.iter().filter(|r| r.2.res == id) {
|
||||
shown(s.kind, format!("heap {} slot {first:#x} ({n})", h.id));
|
||||
}
|
||||
}
|
||||
for (i, s) in self.frame.submits.iter().enumerate() {
|
||||
for (heap, at, s) in s.views.iter().filter(|v| v.2.res == id) {
|
||||
shown(
|
||||
s.kind,
|
||||
format!("heap {heap} slot {at:#x} from submission {i} on"),
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Runs the frame twice, submission by submission, and says what the
|
||||
/// copies up would have put over what the card wrote in both runs alike,
|
||||
/// and what was written undeclared.
|
||||
pub fn upcopies(&mut self, o: &Options, say: &mut dyn FnMut(String)) -> Result<()> {
|
||||
let mut report = Report::default();
|
||||
self.set_merging(true)?;
|
||||
let submits = self.edited(o, &mut report, &[]);
|
||||
let built = self.build(&submits, o)?;
|
||||
let ids: Vec<u32> = self
|
||||
.masters
|
||||
.iter()
|
||||
.map(|m| m.0)
|
||||
.filter(|id| {
|
||||
self.card_writes.contains(id)
|
||||
&& self.frame.resources[self.objects[id].index]
|
||||
.name
|
||||
.ends_with("on the card")
|
||||
})
|
||||
.collect();
|
||||
let reader = self.reader(&ids)?;
|
||||
say(format!(
|
||||
"{} buffers on the card that the frame writes, {} MB",
|
||||
ids.len(),
|
||||
reader.parts.iter().map(|p| p.len).sum::<u64>() >> 20
|
||||
));
|
||||
// What a shader that picks a view to write through by an index could
|
||||
// write.
|
||||
let mut shown: BTreeMap<u32, u64> = BTreeMap::new();
|
||||
for s in self
|
||||
.frame
|
||||
.descriptor_heaps
|
||||
.iter()
|
||||
.flat_map(|h| h.runs.iter().map(|r| &r.2))
|
||||
{
|
||||
if s.kind == slot::UAV
|
||||
&& let Some(o) = self.objects.get(&s.res)
|
||||
{
|
||||
let d = &self.frame.resources[o.index].desc;
|
||||
if d.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
|
||||
*shown.entry(s.res).or_default() = d.width;
|
||||
}
|
||||
}
|
||||
}
|
||||
say(format!(
|
||||
"unordered views of {} buffers in the heaps at the start, {} MB of them",
|
||||
shown.len(),
|
||||
shown.values().sum::<u64>() >> 20
|
||||
));
|
||||
let states = self.start_states();
|
||||
let mut runs: Vec<Vec<(Up, Vec<Word>)>> = Vec::new();
|
||||
for run in 0..2 {
|
||||
self.restore(true)?;
|
||||
self.fresh = false;
|
||||
let mut found: Vec<(Up, Vec<Word>)> = Vec::new();
|
||||
let mut was = if run == 0 {
|
||||
self.hashes_now(&reader, &states)?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
for (i, (delta, lists)) in built.steps.iter().enumerate() {
|
||||
if let Some(d) = delta {
|
||||
// SAFETY: a closed list, waited for.
|
||||
unsafe {
|
||||
self.worker
|
||||
.queue
|
||||
.ExecuteCommandLists(&[Some(d.list.cast()?)])
|
||||
};
|
||||
self.worker.idle()?;
|
||||
}
|
||||
let ups = self.ups(i, &submits[i]);
|
||||
if !ups.is_empty() {
|
||||
let mut asked = Vec::new();
|
||||
for &(_, src, dst, at, len) in &ups {
|
||||
let Some(base) = self.merger.as_ref().and_then(|m| m.bases.get(&dst))
|
||||
else {
|
||||
bail!("a copy up without a base");
|
||||
};
|
||||
asked.push((self.objects[&dst].res.clone(), at, len));
|
||||
asked.push((base.clone(), at, len));
|
||||
asked.push((self.objects[&src].res.clone(), at, len));
|
||||
}
|
||||
let bytes = self.slices(&asked)?;
|
||||
for (k, up) in ups.iter().enumerate() {
|
||||
let (now, base, new) =
|
||||
(&bytes[k * 3], &bytes[k * 3 + 1], &bytes[k * 3 + 2]);
|
||||
let word = |b: &[u8], i: usize| {
|
||||
u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]])
|
||||
};
|
||||
let mut words = Vec::new();
|
||||
for at in (0..now.len() / 4 * 4).step_by(4) {
|
||||
let w = [word(now, at), word(base, at), word(new, at)];
|
||||
if w[0] != w[2] {
|
||||
words.push((up.3 + at as u64, w));
|
||||
}
|
||||
}
|
||||
found.push((*up, words));
|
||||
}
|
||||
}
|
||||
let all: Vec<Option<ID3D12CommandList>> = lists
|
||||
.iter()
|
||||
.map(|l| l.list.cast::<ID3D12CommandList>().map(Some))
|
||||
.collect::<std::result::Result<_, _>>()?;
|
||||
if !all.is_empty() {
|
||||
// SAFETY: closed lists, waited for.
|
||||
unsafe { self.worker.queue.ExecuteCommandLists(&all) };
|
||||
self.worker.idle().context("the card was lost")?;
|
||||
}
|
||||
if run > 0 {
|
||||
continue;
|
||||
}
|
||||
let now = self.hashes_now(&reader, &states)?;
|
||||
let mut declared = self.declared(&submits[i]);
|
||||
for (_, _, dst, at, len) in &ups {
|
||||
let e = declared.entry(*dst).or_default();
|
||||
let skew = e.0;
|
||||
e.1.extend((*at + skew) / PIECE..(*at + len + skew).div_ceil(PIECE));
|
||||
}
|
||||
for (p, (a, b)) in was.iter().zip(&now).enumerate() {
|
||||
let id = reader.parts[p].id;
|
||||
let differ: Vec<usize> = (0..a.len()).filter(|&k| a[k] != b[k]).collect();
|
||||
if differ.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let outside: Vec<u64> = differ
|
||||
.iter()
|
||||
.map(|&k| k as u64)
|
||||
.filter(|&k| match declared.get(&id) {
|
||||
None => true,
|
||||
// (A copy that does not begin on a piece: the
|
||||
// hashes' piece lies over two of the compare's.)
|
||||
Some((skew, pieces)) => {
|
||||
let first = (k * PIECE + skew) / PIECE;
|
||||
let last = ((k + 1) * PIECE + skew - 1) / PIECE;
|
||||
!(first..=last).any(|p| pieces.contains(&p))
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if !outside.is_empty() {
|
||||
say(format!(
|
||||
"submission {i}: {} of {} changed pieces of {} were not declared as written, the first {:#x?}",
|
||||
outside.len(),
|
||||
differ.len(),
|
||||
self.called(id),
|
||||
&outside[..outside.len().min(8)]
|
||||
));
|
||||
for line in self.views_of(id) {
|
||||
say(format!(" {line}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
was = now;
|
||||
}
|
||||
runs.push(found);
|
||||
}
|
||||
let [first, second] = &runs[..] else {
|
||||
bail!("not two runs");
|
||||
};
|
||||
// What the card wrote in both runs alike, and what comes is another
|
||||
// value: the title's, or an old one.
|
||||
let (mut same, mut old, mut differ, mut all, mut titles) = (0u64, 0u64, 0u64, 0u64, 0u64);
|
||||
let mut by: BTreeMap<(u32, u64), (u64, u64, Vec<String>)> = BTreeMap::new();
|
||||
for ((up, a), (_, b)) in first.iter().zip(second) {
|
||||
all += up.4 / 4;
|
||||
let b: HashMap<u64, [u32; 3]> = b.iter().copied().collect();
|
||||
for (at, [now, base, new]) in a {
|
||||
if now == base {
|
||||
titles += 1;
|
||||
continue;
|
||||
}
|
||||
if b.get(at).is_none_or(|other| other[0] != *now) {
|
||||
differ += 1;
|
||||
continue;
|
||||
}
|
||||
same += 1;
|
||||
let back = new == base;
|
||||
old += u64::from(back);
|
||||
let e = by.entry((up.2, at / PIECE)).or_default();
|
||||
e.0 += 1;
|
||||
e.1 += u64::from(back);
|
||||
if e.2.len() < 6 {
|
||||
e.2.push(format!(
|
||||
"submission {} +{at:#x}: card {now:#x}, before {base:#x}, comes {new:#x}",
|
||||
up.0
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
say(format!(
|
||||
"{} copies up of {all} words: {titles} bring something new where the card had not written; where it had and another \
|
||||
value comes: {differ} words differ between the runs, {same} the card wrote alike in both ({old} of them would get \
|
||||
back what stood there before the card wrote)",
|
||||
first.len(),
|
||||
));
|
||||
let mut by: Vec<_> = by.into_iter().collect();
|
||||
by.sort_by_key(|b| std::cmp::Reverse(b.1.0));
|
||||
for ((id, piece), (n, back, some)) in by.into_iter().take(40) {
|
||||
say(format!(
|
||||
" {} piece {piece:#x}: {n} words, {back} back to before",
|
||||
self.called(id)
|
||||
));
|
||||
for line in some {
|
||||
say(format!(" {line}"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -372,6 +372,11 @@ pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc<Shadow>, Vec<(usize, usize)>)
|
||||
out
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
/// Ranges in order, those that overlap or touch as one.
|
||||
fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
|
||||
ranges.sort_unstable();
|
||||
@@ -439,9 +444,16 @@ fn card_piece_of(start: usize, len: usize, span: &CardSpan, i: u32) -> (usize, u
|
||||
(lo.max(span.from as usize), hi.min(span.to as usize))
|
||||
}
|
||||
|
||||
/// The offsets [`Shadow::card_hashed`] gives, for a card's buffer of `size`
|
||||
/// bytes for title memory from `start` on.
|
||||
fn card_hashed_of(start: usize, size: usize, piece: usize) -> (usize, usize) {
|
||||
let (lo, hi) = piece_at(start, size, piece);
|
||||
(lo & !15, hi.next_multiple_of(16))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod card_tests {
|
||||
use super::{CardSpan, PIECE, card_piece_of, card_span_of, joined, joined_piece_runs};
|
||||
use super::{CardSpan, PIECE, card_hashed_of, card_piece_of, card_span_of, joined, joined_piece_runs};
|
||||
|
||||
/// Joined runs hold every piece of the runs given, once, and no other.
|
||||
#[test]
|
||||
@@ -497,6 +509,25 @@ mod card_tests {
|
||||
}
|
||||
|
||||
/// Changed ranges are joined where they overlap or touch, and only there.
|
||||
/// What is fetched of a piece to hash it is what the shader hashes.
|
||||
#[test]
|
||||
fn a_piece_is_hashed_here_as_on_the_card() {
|
||||
for start in [0usize, 0x10_0000, 0xd_5edb_c780, 0x12_3456_7008] {
|
||||
for size in [1usize << 16, 5 << 16, 0x20_0000] {
|
||||
let span = card_span_of(start, 0, size);
|
||||
for i in 0..span.pieces {
|
||||
// As `CARD_COMPARE` has it.
|
||||
let (piece, skew, size) = (span.first + i, span.skew, size as u32);
|
||||
let lo = (piece * 65536).saturating_sub(skew);
|
||||
let hi = ((piece + 1) * 65536 - skew).min(size);
|
||||
let shader = (lo & !15, (hi + 15) & !15);
|
||||
let here = card_hashed_of(start, size as usize, piece as usize);
|
||||
assert_eq!((here.0 as u32, here.1 as u32), shader, "start {start:#x} size {size:#x} piece {piece}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_join_where_they_touch() {
|
||||
assert_eq!(joined(vec![(8, 12), (0, 4), (4, 6), (10, 20), (30, 31)]), [(0, 6), (8, 20), (30, 31)]);
|
||||
@@ -965,6 +996,16 @@ mod difference_tests {
|
||||
/// The unit shader writes are looked for and put back in.
|
||||
const PIECE: usize = 64 << 10;
|
||||
|
||||
/// Calls `f` with `[from, to)` cut at multiples of [`PIECE`].
|
||||
fn for_pieces_of(from: usize, to: usize, mut f: impl FnMut(usize, usize)) {
|
||||
let mut at = from;
|
||||
while at < to {
|
||||
let next = ((at / PIECE + 1) * PIECE).min(to);
|
||||
f(at, next);
|
||||
at = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies `len` bytes, on several threads if they are many: a snapshot of
|
||||
/// the world's big heap is 100-170 MB per submission, 2-4 GB a frame, and
|
||||
/// one thread copies some 8 GB/s.
|
||||
@@ -2680,7 +2721,16 @@ impl Shadow {
|
||||
let (from, to) = (from.max(start), to.min(end));
|
||||
// SAFETY: inside the mapping (`from` and `to` are within the buffer).
|
||||
let at = unsafe { self.data.add(from - start) };
|
||||
crate::host::copy_mapped(at, from as *const u8, to - from, false);
|
||||
if self.card.is_some() && from < to && crate::host::upcheck::on() {
|
||||
for_pieces_of(from - start, to - start, |a, b| {
|
||||
let was = self.card_held(a, b - a);
|
||||
// SAFETY: inside the mapping, as above.
|
||||
crate::host::copy_mapped(unsafe { self.data.add(a) }, (start + a) as *const u8, b - a, false);
|
||||
crate::host::upcheck::note(self.id, a, &was, &self.card_held(a, b - a));
|
||||
});
|
||||
} else {
|
||||
crate::host::copy_mapped(at, from as *const u8, to - from, false);
|
||||
}
|
||||
// After the bytes are in: a snapshot taken meanwhile is not current.
|
||||
self.changed(from - start, to - start);
|
||||
self.card_changed(from - start, to - start);
|
||||
@@ -2709,6 +2759,24 @@ impl Shadow {
|
||||
}
|
||||
}
|
||||
|
||||
/// Diagnostics: of a copy in the card's memory, what its CPU side holds
|
||||
/// at offsets `[at, at + len)` (cut to the copy).
|
||||
pub(crate) fn card_held(&self, at: usize, len: usize) -> Vec<u8> {
|
||||
let to = (at + len).min(self.len as usize);
|
||||
if self.card.is_none() || at >= to {
|
||||
return Vec::new();
|
||||
}
|
||||
// SAFETY: inside the mapping; the caller holds the submission lock,
|
||||
// under which it is written but for what is being landed.
|
||||
unsafe { std::slice::from_raw_parts(self.data.add(at).cast_const(), to - at) }.to_vec()
|
||||
}
|
||||
|
||||
/// Diagnostics: the offsets whose bytes have not gone to the card's side
|
||||
/// yet.
|
||||
pub(crate) fn card_dirty_now(&self) -> Vec<(usize, usize)> {
|
||||
self.card.as_ref().map_or_else(Vec::new, |c| c.dirty.lock().unwrap_or_else(|e| e.into_inner()).clone())
|
||||
}
|
||||
|
||||
/// Of a copy in the card's memory: the CPU's side (PC memory), the
|
||||
/// card side's bytes from before if made yet, and their size.
|
||||
pub(crate) fn card_sides(&self) -> Option<(&ID3D12Resource, Option<ID3D12Resource>, u64)> {
|
||||
@@ -2756,6 +2824,14 @@ impl Shadow {
|
||||
card_piece_of(self.start as usize, self.len as usize, span, i)
|
||||
}
|
||||
|
||||
/// The offsets the compare on the card hashes of a piece: what lies of
|
||||
/// it in the card's buffer (which may be longer than the copy), widened
|
||||
/// to 16 bytes.
|
||||
pub(crate) fn card_hashed(&self, piece: u32) -> (usize, usize) {
|
||||
let size = self.card.as_ref().map_or(self.len, |c| c.size) as usize;
|
||||
card_hashed_of(self.start as usize, size, piece as usize)
|
||||
}
|
||||
|
||||
/// The walls trace (`crate::host::walls_trace`): a piece of `fetched`
|
||||
/// bytes of this copy came back from the card and `written` of them
|
||||
/// went into title memory. Summed per buffer and logged once a frame:
|
||||
|
||||
@@ -93,6 +93,7 @@ report counts them). `--no-merge` runs the copies as recorded.
|
||||
| `--watch <id>:<offset>:<bytes>` | which lists (with `--lists`: commands) change those words |
|
||||
| `--slots <list>:<command>` | the heap slots its constants name |
|
||||
| `--check-written` | that everything the frame changes is put back |
|
||||
| `--upcopies` | runs the frame twice: which words the copies of the CPU's sides of card buffers bring that the card holds another value of (those the card wrote alike in both runs are the ones to look at), and which pieces shaders wrote that were not declared as written. The live check is `VICTORY_UPCOPY_CHECK=1` (`host/upcheck.rs`) |
|
||||
| `--dump <text>` | the DXIL of the pipelines named, in `shaders` |
|
||||
|
||||
The `--diverge` family runs the recorded copies without the merge.
|
||||
|
||||
Reference in new issue
Block a user