Merge branch 'local/next' into local/copies

This commit is contained in:
local committed 2026-11-24 23:24:47 -06:00
commit 0b3af7939c
15 files changed
+2212 -35

No files matched your search

+12 -1
View File
@@ -1164,6 +1164,9 @@ impl State {
for stage in &p.stages {
let t = stage.translated();
STORES.set(t.stores);
if t.stores && crate::picked::on() && crate::picked::picks(&stage.shader, &t.picks) {
crate::picked::runs_in(list);
}
let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute);
STORES.set(true);
if made.iter().any(|m| m.1 == u32::MAX) {
@@ -1578,7 +1581,8 @@ impl State {
.entry(std::ptr::from_ref(host) as usize)
.or_insert_with(|| (0, HeapRanges(Vec::new())));
let changed = host.buffer_changes();
let slots = if *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()) {
let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread());
let slots = if all {
ranges.0.clear();
host.buffer_slots()
} else if heap_spread() {
@@ -1596,6 +1600,7 @@ impl State {
// it is named below.
static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none();
let mut unordered = Vec::new();
for (n, &index) in slots.iter().enumerate() {
ranges.set(index, None);
let Some(handle) = heap.handle(index) else {
@@ -1628,8 +1633,14 @@ impl State {
if host.shows(index, &shadow.buffer) == Some(false) {
HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed);
}
if crate::picked::on() && view_kind(&view) == Some(ResourceType::Uav) {
unordered.push((shadow.clone(), address, address + len));
}
ranges.set(index, Some((shadow, address, address + len)));
}
if crate::picked::on() {
crate::picked::shown(unordered, all);
}
#[cfg(feature = "diagnostics")]
let looked = std::time::Instant::now();
// Per host copy, the span its picked views cover.
+6
View File
@@ -84,6 +84,12 @@ pub(crate) fn current() -> u64 {
FRAME.load(Ordering::Relaxed)
}
/// For tests of what is done once a frame.
#[cfg(test)]
pub(crate) fn test_advance() {
FRAME.fetch_add(1, Ordering::Relaxed);
}
/// Per event kind (origin, vblank, flip and later kinds): the last tick a
/// wait for it ended on.
static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
+150 -22
View File
@@ -1515,7 +1515,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.
@@ -1536,7 +1536,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.
///
@@ -1586,7 +1586,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);
@@ -1596,6 +1598,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.
@@ -1662,6 +1670,22 @@ struct CardRange {
at: u32,
/// Whether the card compares it; else every piece is fetched.
compared: bool,
/// Looked at by `crate::picked`, and not declared: what is found changed
/// there was written through a view nobody declared. Not landed.
picked: bool,
}
impl CardPlan {
/// `crate::picked` is told where what it looked at changed, by the
/// compare's results.
fn picked_found(&self, differs: &[u32]) {
for r in self.ranges.iter().filter(|r| r.picked) {
let changed = (0..r.span.pieces).find(|p| differs.get((r.at + p) as usize).is_some_and(|&d| torn::flagged(d)));
if let Some(p) = changed {
crate::picked::found(&r.shadow, r.shadow.card_piece(&r.span, p).0);
}
}
}
}
/// What a submission does for copies in the card's memory.
@@ -1678,6 +1702,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.
@@ -2695,6 +2721,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,
/// What earlier fetches brought of flights not landed yet.
had: crate::land::Had,
}
@@ -2929,9 +2957,19 @@ 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],
);
}
}
crate::land::log(frames);
card_steps::log(frames);
crate::picked::log(frames);
#[cfg(feature = "diagnostics")]
log_blame(frames);
if late_exact() {
@@ -2945,6 +2983,8 @@ fn late_line(frames: f64) {
}
mod card_steps;
mod torn;
pub(crate) mod upcheck;
#[cfg(test)]
mod late_tests {
@@ -3451,7 +3491,9 @@ impl Host {
/// `flown`: the submission is sent ahead with [`relay`]. Its compare
/// then stores the hashes it makes (see [`flagged_pieces`] and
/// `relay`).
fn card_before(&self, runs: &[&HostList], flown: bool) -> Option<CardPlan> {
/// `picked`: ranges that may be written too, and ranges to look at
/// (`crate::picked`).
fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
use std::sync::Arc;
if !crate::shadow::cards() {
return None;
@@ -3475,6 +3517,10 @@ impl Host {
}
}
}
let declared = crate::picked::with(declared, &picked.written);
// (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();
// With the relay: the order of the queue is held from here until
// what is taken is on the queue, and the taking is numbered.
let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
@@ -3486,7 +3532,7 @@ impl Host {
None => 0,
};
let mut dirty = crate::shadow::card_dirty(sent_as);
if declared.is_empty() && dirty.is_empty() {
if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
return None;
}
let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
@@ -3494,7 +3540,7 @@ impl Host {
// A copy whose shader writes are declared for the first time gets
// its bytes from before, whole.
let mut whole: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
for (shadow, _) in &declared {
for shadow in declared.iter().map(|d| &d.0).chain(looked.iter().map(|l| &l.0)) {
if shadow.card_make_before(|size| {
let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?;
name(&before, || "title buffer on the card, hashes of its pieces".into());
@@ -3507,6 +3553,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"));
@@ -3519,6 +3566,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.
@@ -3588,6 +3638,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.
@@ -3614,12 +3665,30 @@ impl Host {
span,
at,
compared,
picked: false,
});
if compared {
at += span.pieces;
}
}
}
for (shadow, from, len) in looked {
let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
if let Some(span) = shadow.card_span(*from, from + len)
&& twin
&& u64::from(at + span.pieces) * 4 <= work.differs.2
{
plan.ranges.push(CardRange {
shadow: shadow.clone(),
declared: (*from, from + len),
span,
at,
compared: true,
picked: true,
});
at += span.pieces;
}
}
work.taken = at;
if plan.ranges.iter().any(|r| r.compared) {
let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else {
@@ -3652,7 +3721,9 @@ impl Host {
};
list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress());
list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
card_pass(list, &r.span, size as u32, r.at, if flown { 2 } else { 1 });
// (What is only looked at keeps its hashes: what
// changed there is the next declared range's to land.)
card_pass(list, &r.span, size as u32, r.at, if flown && !r.picked { 2 } else { 1 });
CARD_PASSES[2].fetch_add(1, Ordering::Relaxed);
}
list.Close()?;
@@ -3685,6 +3756,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;
@@ -3736,6 +3810,7 @@ impl Host {
event,
sent: 0,
buffer: None,
suspects: torn::Suspects::default(),
had: crate::land::Had::default(),
})
}
@@ -3765,26 +3840,34 @@ impl Host {
if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) {
fetch.had.landing(first);
}
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) };
// 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 = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) });
if let Some(differs) = differs {
// Pieces caught while a later flight was at them (`torn`).
let suspects = fetch.as_ref().map(|f| &f.suspects);
let mut seen = std::collections::HashSet::new();
for &(plan, behind) in plans {
plan.picked_found(differs);
let flags: Vec<(usize, u32, bool)> = plan
.ranges
.iter()
.filter(|r| !r.picked)
.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)
let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d));
let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged));
(std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted)
})
})
.collect();
let fetched = flagged_pieces(&flags);
for r in &plan.ranges {
for r in plan.ranges.iter().filter(|r| !r.picked) {
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 {
if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
continue;
@@ -3799,6 +3882,9 @@ impl Host {
continue;
}
}
if upcheck::on() {
upcheck::fetched(r.shadow.id(), lo);
}
seen.insert((copy, lo, hi));
pieces.push((r.shadow.clone(), lo, hi, total));
total += (hi - lo) as u64;
@@ -3828,6 +3914,13 @@ impl Host {
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: the pieces come down whole, to be hashed.
let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some()))
.then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces));
if let Some(check) = &check {
total = check.total;
}
// 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.0.sent_as).max().unwrap_or(0);
@@ -3868,7 +3961,7 @@ impl Host {
(|| -> windows::core::Result<u64> {
allocator.Reset()?;
list.Reset(&allocator, None)?;
for (shadow, lo, hi, at) in &pieces {
for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) {
list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64);
}
list.Close()?;
@@ -3917,6 +4010,12 @@ impl Host {
let put = std::sync::atomic::AtomicU64::new(0);
land::each(jobs.len(), &|j| {
let working = std::time::Instant::now();
if let Some(check) = &check {
for i in jobs[j].clone() {
// SAFETY: as below.
unsafe { check.look(i, data) };
}
}
let mut notes = land::Notes::default();
for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) {
let addressed: Vec<(usize, usize, usize)> =
@@ -3933,7 +4032,11 @@ impl Host {
written = put.into_inner();
} else {
let mut title = Vec::new();
for (shadow, lo, hi, at) in &pieces {
for (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() {
if let Some(check) = &check {
// SAFETY: as below.
unsafe { check.look(i, data) };
}
// 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) };
@@ -3945,6 +4048,9 @@ impl Host {
land::spent(land::stat::CARD, merging);
COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
if let Some(f) = fetch.as_mut() {
if let Some(check) = &check {
check.done(&mut f.suspects);
}
f.had.fetched(
ahead,
pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
@@ -4116,9 +4222,10 @@ impl Host {
// where the bytes come down.
let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new();
let mut total = 0u64;
for (i, r) in plan.ranges.iter().enumerate() {
plan.picked_found(differs);
for (i, r) in plan.ranges.iter().enumerate().filter(|(_, r)| !r.picked) {
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);
@@ -4558,12 +4665,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);
}
@@ -4615,6 +4728,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);
}
let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
if !stale.is_empty() {
let settling = std::time::Instant::now();
@@ -4661,7 +4777,13 @@ impl Host {
self.settle(&mut submitted, WHY_MOST);
settled += settling.elapsed();
}
let card = self.card_before(runs, flown);
// What shaders may write through views they pick: last, so that no
// refresh of this submission leaves it alone.
let picked = crate::picked::declare(runs);
for (shadow, at, len) in &picked.written {
shadow.writing(*at, *len);
}
let card = self.card_before(runs, &picked, flown);
if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
lists.push(Some(check));
}
@@ -4681,7 +4803,7 @@ impl Host {
}
#[cfg(feature = "diagnostics")]
split.part(5);
let back = declared_writes(runs);
let back = crate::picked::with(declared_writes(runs), &picked.written);
let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
submitting(0, 0);
@@ -4801,7 +4923,7 @@ impl Host {
if let Some(card) = &card {
self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
}
let back = declared_writes(runs);
let back = crate::picked::with(declared_writes(runs), &picked.written);
hand_back(&back);
if let Some(card) = card {
self.card_done(card);
@@ -5926,6 +6048,12 @@ impl HostList {
self.deferred().textures.insert(key)
}
/// Whether `key` was asked about ([`HostList::first_use`]) since the
/// reset.
pub(crate) fn used(&self, key: usize) -> bool {
self.deferred().textures.contains(&key)
}
/// Runs `work` when the list is submitted, in order with its copies.
/// `work` may write title memory (refreshes after it copy again).
pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
+329
View File
@@ -0,0 +1,329 @@
//! 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, on the thread that merges them (`crate::land`).
use std::collections::{HashMap, HashSet};
use std::sync::atomic::AtomicU8;
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 for 96 MB beside the merge, spread over the threads that land).
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.is_empty() && 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);
}
}
}
/// What is landed: its copy, its offsets from and to, and where it comes
/// down.
pub(super) type Landed = (std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64);
/// The pieces of a landing's fetch, whole, and what is known of them.
pub(super) struct Check {
/// What is copied down: whole pieces, as the compare hashes them.
pub(super) copies: Vec<Landed>,
/// The bytes of them.
pub(super) total: u64,
/// Of each: the piece, and the hash the last flight that may have
/// written it ended with.
of: Vec<(Piece, Option<u32>)>,
/// Of what is landed, the piece (in `copies`) it is of.
within: Vec<usize>,
/// Of each piece: 0 not looked at yet, 1 as that flight ended with, 2
/// not so.
found: Vec<AtomicU8>,
}
impl Check {
/// For `landed`, parts of pieces that `plans` may have written, whose
/// compares' results are in `differs`: the parts are given their places
/// in the pieces that come down.
pub(super) fn new<'a>(plans: impl Iterator<Item = &'a CardPlan>, differs: &[u32], landed: &mut [Landed]) -> Check {
let mut index: HashMap<Piece, usize> = HashMap::new();
let (mut copies, mut of, mut within, mut total) = (Vec::new(), Vec::new(), Vec::new(), 0u64);
for (shadow, lo, _, at) in landed {
let number = shadow.card_piece_of(*lo);
let piece = (shadow.id(), number);
let i = *index.entry(piece).or_insert_with(|| {
let (from, to) = shadow.card_hashed(number);
copies.push((shadow.clone(), from, to, total));
of.push((piece, None));
total += (to - from) as u64;
copies.len() - 1
});
*at = copies[i].3 + (*lo - copies[i].1) as u64;
within.push(i);
}
// (The last flight's stands.)
for r in plans.flat_map(|plan| &plan.ranges).filter(|r| r.compared && !r.picked) {
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)
{
of[i].1 = Some(folded(d));
}
}
}
let found = of.iter().map(|_| AtomicU8::new(0)).collect();
Check { copies, total, of, within, found }
}
/// Looks at the piece that part `i` of what is landed is of, if none of
/// its parts was looked at: on the thread that lands it, just before, so
/// that its bytes are near.
///
/// # Safety
/// What was fetched is at `data`, and stays as it is during the call.
pub(super) unsafe fn look(&self, i: usize, data: usize) {
let i = self.within[i];
if self.found[i].load(Ordering::Relaxed) != 0 {
return;
}
let Some(hash) = self.of[i].1 else {
return;
};
let (_, from, to, at) = &self.copies[i];
// SAFETY: the caller's.
let bytes = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, to - from) };
self.found[i].store(if self::hash(bytes) == hash { 1 } else { 2 }, Ordering::Relaxed);
}
/// All is landed: what was found is kept for later flights.
pub(super) fn done(&self, suspects: &mut Suspects) {
for ((piece, _), found) in self.of.iter().zip(&self.found) {
match found.load(Ordering::Relaxed) {
// Not compared on the card: fetched by every flight.
0 => {}
found => suspects.fetched(*piece, found == 1),
}
}
}
}
/// 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})");
}
}
}
+866
View File
@@ -0,0 +1,866 @@
//! 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(&copy) 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] = &noted[..] 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));
}
/// A shader that writes through views it picks: its buffer is found when
/// it comes to it in turn, and what it writes from then on is landed.
#[test]
#[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 VICTORY_PICKED_WRITES=1 VICTORY_PICKED_MB=1 and a process of its own"]
fn writes_through_picked_views_come_back() {
let Some(host) = host() else {
return;
};
assert!(crate::picked::on(), "set VICTORY_PICKED_WRITES=1");
let (title, start, shadow) = title(0x6666, true);
crate::picked::shown(vec![(shadow.clone(), start as u64, (start + LEN) as u64)], true);
let at = (37 << 16) + 512;
let mut lists = Vec::new();
let mut back = Vec::new();
for round in 0..12u8 {
// Turns go by frames.
crate::frame::test_advance();
title[(37 << 16) + 9000] = round + 1;
let list = host.new_list().unwrap();
shadow.refresh(&list, start as u64, LEN as u64);
crate::picked::runs_in(&list);
write(host, &list, &shadow, at, &[0x40 + round; 64]);
list.close();
host.execute_own(&list);
settle_now(WHY_SYNC);
back.push(title[at..at + 64] == [0x40 + round; 64]);
// The title's own write beside it is on the card, and the
// shader's stays, once its buffer is known.
let next = host.new_list().unwrap();
shadow.refresh(&next, start as u64, LEN as u64);
next.close();
host.execute_own(&next);
settle_now(WHY_SYNC);
if *back.last().unwrap() {
let holds = card(host, &shadow);
assert_eq!((holds[(37 << 16) + 9000], holds[at]), (round + 1, 0x40 + round));
assert_eq!(look(host), Some(0));
}
lists.extend([list, next]);
}
eprintln!("came back, by round: {back:?}");
let first = back.iter().position(|b| *b).expect("it is found");
assert!(first <= 6 && back[first..].iter().all(|b| *b), "{back:?}");
}
/// 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"
);
}
}
}
}
+11 -1
View File
@@ -858,7 +858,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.
+2
View File
@@ -39,6 +39,8 @@ pub mod list;
pub mod object;
pub mod pipeline;
#[cfg(windows)]
mod picked;
#[cfg(windows)]
mod pool;
#[cfg(windows)]
mod primitive;
+372
View File
@@ -0,0 +1,372 @@
//! Buffers shaders write through views they pick from the heap by an index
//! they compute (`VICTORY_PICKED_WRITES=1`; off by default).
//!
//! 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
//! comes back to title memory (`Shadow::gpu_writes`). A view picked by an
//! index out of a buffer, per lane, names any of the heap's. What was
//! written through one stayed on the card: title memory, and the title's own
//! copies and textures made from it, never saw it, and a refresh of its 64
//! KiB put title memory's older bytes over it. (Captures replay1 and
//! replay2: `[compute 82a2ad6d07417d36]` writes 4.6 MB a frame of a 24 MB
//! buffer so.) To declare all such a shader could write would be 987 MB of
//! 573 buffers for every list that runs one.
//!
//! Two things make it small. The compare on the card says what changed since
//! the last time it looked, whoever wrote it and whenever: looking now and
//! then misses no buffer, it only finds it later. And a buffer that was
//! written so once is written so again. So with a submission that has a
//! shader that stores through a picked view ([`stores_picked`])
//!
//! - the buffers found written that way ([`found`]) are declared: compared
//! and landed with the submission, as any declared write;
//! - of the others that the heap shows unordered views of the next [`slice`]
//! in turn, once a frame, is compared, and nothing else: at 32 MB all of
//! them in some 30 frames. Where something changed that nobody declared,
//! the buffer is one of the first kind from then on.
//!
//! What is found late is not landed late: the title may have other things in
//! that memory by then. It goes to title memory with the next declared write
//! to its 64 KiB. So what is written once, into a buffer not found yet, stays
//! on the card as before.
//!
//! The declarations are the submission's, made when its refreshes are done
//! (`Host::submit`): no refresh of it finds a range closed on their account.
//!
//! Only copies in the card's memory: for those in the PC's, a declared range
//! is a snapshot and a compare on the CPU. (They hold 55 MB of the 987.)
//!
//! What it costs: the hashing of the slice and of the buffers found, and
//! what changed of the latter coming back. What else changes: a step on the
//! CPU that reads a buffer found waits for the flight, as it should always
//! have done.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed};
use std::sync::{Arc, Mutex, OnceLock, Weak};
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"))
}
/// Bytes looked at in turn per frame (`VICTORY_PICKED_MB`).
fn slice() -> u64 {
static SLICE: OnceLock<u64> = OnceLock::new();
*SLICE.get_or_init(|| {
let mb = std::env::var("VICTORY_PICKED_MB").ok().and_then(|v| v.trim().parse::<u64>().ok());
mb.unwrap_or(32) << 20
})
}
/// A list's key for [`HostList::first_use`]: it runs such a shader (no title
/// resource is there).
const KEY: usize = usize::MAX - 0x7a;
/// `list` runs a shader that stores through a picked view.
pub(crate) fn runs_in(list: &HostList) {
list.first_use(KEY);
}
/// [`crate::pipeline::Translated::picks`]: not asked yet, asked, the answers.
const UNKNOWN: u8 = 0;
const ASKED: u8 = 1;
const NO: u8 = 2;
const YES: u8 = 3;
/// Whether `shader`, which stores to buffers, does so through a view it
/// picks. Tracing its descriptors takes some 50 ms, so a thread of ours does
/// it when the shader is first bound, and it is "no" until then: what it
/// writes is found some frames later in any case. (Of the 25,904 programs of
/// the title 2,923 store and have the view heap among their parameters; 37
/// compute programs store through views they pick.)
pub(crate) fn picks(shader: &Arc<crate::pipeline::Shader>, known: &AtomicU8) -> bool {
match known.load(Relaxed) {
YES => true,
UNKNOWN => {
if known.compare_exchange(UNKNOWN, ASKED, Relaxed, Relaxed).is_ok() {
ask(shader.clone());
}
false
}
_ => false,
}
}
fn ask(shader: Arc<crate::pipeline::Shader>) {
use std::sync::mpsc::{Sender, channel};
static ASKS: OnceLock<Mutex<Sender<Arc<crate::pipeline::Shader>>>> = OnceLock::new();
let asks = ASKS.get_or_init(|| {
let (send, asks) = channel::<Arc<crate::pipeline::Shader>>();
let _ = std::thread::Builder::new().name("victory-picked".into()).spawn(move || {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL};
// SAFETY: this thread's own.
unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL) };
for shader in asks {
let yes = shader.programs().is_none_or(|all| all.iter().any(stores_picked));
if yes {
tracing::info!(hash = %shader.hash, "a shader stores through views it picks from the heap (VICTORY_PICKED_WRITES=1)");
}
if let Some(t) = shader.translated() {
t.picks.store(if yes { YES } else { NO }, Relaxed);
}
}
});
Mutex::new(send)
});
let _ = asks.lock().unwrap_or_else(|e| e.into_inner()).send(shader);
}
/// Whether the code of `program` stores to a buffer through a descriptor
/// that its tables do not name: loaded from the view heap, or from a table at
/// an offset it computes (programs with the view heap among their parameters). Yes where that cannot be told.
fn stores_picked(program: &victory_shader::NativeProgram) -> bool {
use victory_shader::HwStage;
use victory_shader::gfx10::Fields;
use victory_shader::native::RootType;
use victory_shader::resource::{Role, Source};
// (The programs that are translated.)
if !matches!(program.stage, HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms) {
return false;
}
let heap = |param: usize| program.layout.get(param).is_some_and(|p| p.root == RootType::ResourceHeap);
if !(0..program.layout.len()).any(heap) {
return false;
}
let Ok(p) = victory_shader::spill::build(program) else {
return true;
};
// The structure is what takes time, and only per-lane descriptors need
// it.
let plain = victory_shader::resource::track(&p, &program.layout, program.stage, None);
let res = plain.or_else(|_| {
let st = victory_shader::structure::structure(&p);
victory_shader::resource::track(&p, &program.layout, program.stage, st.as_ref().ok())
});
let Ok(res) = res else {
return true;
};
res.descriptors.iter().filter(|d| d.role == Role::Resource).any(|d| {
let inst = &p.blocks[d.site.0].insts[d.site.1];
let stores = matches!(inst.fields, Fields::Buffer { .. }) && (inst.name().contains("store") || inst.name().contains("atomic"));
stores
&& d.source.leaves().into_iter().any(|s| match s {
Source::Loaded { load, .. } | Source::Fetched { load, .. } => res
.scalar
.iter()
.find(|(site, _)| site == load)
.is_some_and(|(_, a)| heap(a.param) || a.dynamic.is_some()),
_ => false,
})
})
}
/// A buffer the heap shows unordered views of: title addresses, from the
/// first to the last.
struct Shown {
copy: Weak<Shadow>,
from: u64,
to: u64,
}
#[derive(Default)]
struct State {
shown: BTreeMap<u64, Shown>,
/// The copies (by number) found written through picked views.
found: BTreeSet<u64>,
/// Where the next slice begins: copy, offset from its first address.
next: (u64, u64),
/// The frame of the last slice.
frame: u64,
}
static STATE: Mutex<Option<State>> = Mutex::new(None);
impl State {
/// The ranges of the next `most` bytes in turn, at most all once.
fn turn(&mut self, most: u64) -> Vec<(u64, u64, u64)> {
let mut out: Vec<(u64, u64, u64)> = Vec::new();
let mut left = most;
// (The one it begins in may come twice: its end first.)
for _ in 0..=self.shown.len() {
let (copy, offset) = self.next;
let Some((&id, s)) = self.shown.range(copy..).next().or_else(|| self.shown.iter().next()) else {
break;
};
let offset = if id == copy { offset } else { 0 };
let len = s.to - s.from;
let n = len.saturating_sub(offset).min(left);
if n > 0 && !self.found.contains(&id) {
if out.iter().any(|r| r.0 == id) {
break;
}
out.push((id, s.from + offset, n));
left -= n;
if offset + n < len {
self.next = (id, offset + n);
break;
}
}
self.next = (id + 1, 0);
if left == 0 {
break;
}
}
out
}
}
/// The pass over the heap's buffer views (`crate::draw`): the unordered ones
/// it looked at (copy, from, to); `all` if those are all there are.
pub(crate) fn shown(views: Vec<(Arc<Shadow>, u64, u64)>, all: bool) {
let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
let state = state.get_or_insert_with(State::default);
if all {
state.shown.clear();
}
for (copy, from, to) in views.into_iter().filter(|v| v.0.carded() && v.1 < v.2) {
let e = state.shown.entry(copy.id()).or_insert_with(|| Shown {
copy: Arc::downgrade(&copy),
from,
to,
});
(e.from, e.to) = (e.from.min(from), e.to.max(to));
}
}
/// A range of a copy: title address and bytes.
pub(crate) type Range = (Arc<Shadow>, usize, usize);
/// What is done with a submission.
#[derive(Default)]
pub(crate) struct Ranges {
/// To be declared.
pub(crate) written: Vec<Range>,
/// To be compared only.
pub(crate) looked: Vec<Range>,
}
/// Of a submission that is about to go to the card, its refreshes done: what
/// is to be declared and looked at, if one of its lists runs a shader that
/// stores through a picked view.
pub(crate) fn declare(runs: &[&HostList]) -> Ranges {
if !on() || !runs.iter().any(|list| list.used(KEY)) {
return Ranges::default();
}
let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
let Some(state) = state.as_mut() else {
return Ranges::default();
};
let frame = crate::frame::current();
let written: Vec<(u64, u64, u64)> =
state.found.iter().filter_map(|id| state.shown.get(id).map(|s| (*id, s.from, s.to - s.from))).collect();
let mut looked = Vec::new();
if state.frame != frame {
state.frame = frame;
looked = state.turn(slice());
}
let of = |ranges: Vec<(u64, u64, u64)>, count: usize| -> Vec<Range> {
COUNTS[count].fetch_add(ranges.iter().map(|r| r.2).sum(), Relaxed);
ranges
.into_iter()
.filter_map(|(id, at, len)| Some((state.shown.get(&id)?.copy.upgrade()?, at as usize, len as usize)))
.collect()
};
Ranges { written: of(written, 0), looked: of(looked, 1) }
}
/// The compare found a piece changed (it begins at offset `at` of `copy`)
/// where it only looked: something wrote it through a view nobody declared.
pub(crate) fn found(copy: &Arc<Shadow>, at: usize) {
let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
if state.get_or_insert_with(State::default).found.insert(copy.id()) {
let (start, len) = copy.span();
tracing::info!(
"a buffer is written through views picked from the heap: {start:#x}+{len:#x} (first seen at +{at:#x}; VICTORY_PICKED_WRITES=1): \
declared with every submission that may write it from here on"
);
}
}
/// Since the last frame-rate line: bytes declared, and bytes looked at.
static COUNTS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
/// For the frame-rate line.
pub(crate) fn log(frames: f64) {
if !on() {
return;
}
let [declared, looked] = [0, 1].map(|i| COUNTS[i].swap(0, Relaxed) as f64 / frames / (1 << 20) as f64);
let state = STATE.lock().unwrap_or_else(|e| e.into_inner());
let (shown, found) = state.as_ref().map_or((0, 0), |s| (s.shown.len(), s.found.len()));
tracing::info!(
"views picked from the heap, per frame (VICTORY_PICKED_WRITES=1): {declared:.1} MB declared for them, {looked:.1} MB \
looked at in turn; unordered views of {shown} buffers on the card, {found} of them found written"
);
}
/// Declared writes, per copy, and those of `picked`.
pub(crate) fn with(mut back: Vec<(Arc<Shadow>, Vec<(usize, usize)>)>, picked: &[Range]) -> Vec<(Arc<Shadow>, Vec<(usize, usize)>)> {
for (copy, at, len) in picked {
let range = (*at, *at + *len);
match back.iter_mut().find(|b| Arc::ptr_eq(&b.0, copy)) {
Some((_, ranges)) if ranges.contains(&range) => {}
Some((_, ranges)) => ranges.push(range),
None => back.push((copy.clone(), vec![range])),
}
}
back
}
#[cfg(test)]
mod tests {
use super::*;
fn state(sizes: &[u64]) -> State {
let mut state = State::default();
for (i, &n) in sizes.iter().enumerate() {
let from = (i as u64 + 1) << 32;
state.shown.insert(i as u64 * 3 + 2, Shown { copy: Weak::new(), from, to: from + n });
}
state
}
/// Every byte in turn, none left out, whatever the slice.
#[test]
fn all_buffers_are_looked_at_in_turn() {
let sizes = [100u64, 7, 1000, 1, 350];
let total: u64 = sizes.iter().sum();
for most in [1u64, 10, 99, 350, 1000, 5000] {
let mut s = state(&sizes);
let mut seen = std::collections::BTreeMap::<u64, u64>::new();
// (A turn ends with the list: it may take one more.)
let turns = total.div_ceil(most) + sizes.len() as u64 + 1;
for _ in 0..turns {
let turn = s.turn(most);
assert!(turn.iter().map(|r| r.2).sum::<u64>() <= most);
for (id, at, n) in turn {
let from = s.shown[&id].from;
for b in at - from..at - from + n.min(2000) {
*seen.entry(id << 32 | b).or_default() += 1;
}
}
}
assert_eq!(seen.len() as u64, total, "slices of {most}");
}
}
#[test]
fn what_was_found_has_no_turn() {
let mut s = state(&[64, 64, 64]);
s.found.insert(5);
let turn = s.turn(1000);
assert_eq!(turn.iter().map(|r| r.0).collect::<Vec<_>>(), [2, 8]);
assert!(state(&[]).turn(10).is_empty());
let mut all = state(&[64]);
all.found.insert(2);
assert!(all.turn(10).is_empty());
}
}
+20 -1
View File
@@ -126,6 +126,9 @@ pub(crate) struct Translated {
/// Whether the shader's code can store to buffer memory ([`stores`]);
/// true when its code is not known.
pub(crate) stores: bool,
/// Whether it stores through a view it picks from the heap by an index,
/// once asked (`crate::picked`).
pub(crate) picks: std::sync::atomic::AtomicU8,
}
#[cfg(windows)]
@@ -172,6 +175,17 @@ impl Shader {
}
}
#[cfg(windows)]
impl Shader {
/// The console programs of the container; `None` if they are not known.
pub(crate) fn programs(&self) -> Option<Vec<victory_shader::NativeProgram>> {
use victory_shader::{Container, FourCC};
let c = Container::parse(&self.container).ok()?;
let part = c.part(FourCC::DXIL).or(c.part(FourCC::ACCC))?;
victory_shader::native_programs(part.data).ok()
}
}
#[cfg(windows)]
fn translate(container: &[u8]) -> Result<Translated, String> {
use victory_shader::{Container, FourCC, HwStage};
@@ -194,7 +208,12 @@ fn translate(container: &[u8]) -> Result<Translated, String> {
})
.map(|p| p.used)
.unwrap_or_default();
Ok(Translated { host, used, stores })
Ok(Translated {
host,
used,
stores,
picks: Default::default(),
})
}
/// The compute pipelines of the console's ray-tracing structure builder
+1
View File
@@ -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(())
}
}
+83 -2
View File
@@ -382,6 +382,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();
@@ -449,9 +454,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]
@@ -507,6 +519,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)]);
@@ -971,6 +1002,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.
@@ -2989,7 +3030,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);
@@ -3018,6 +3068,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)> {
@@ -3065,6 +3133,19 @@ impl Shadow {
card_piece_of(self.start as usize, self.len as usize, span, i)
}
/// The piece that holds offset `at`.
pub(crate) fn card_piece_of(&self, at: usize) -> u32 {
self.pieces(at, at + 1).start as u32
}
/// 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: