Merge local/next (e6f492d) into local/tests

Blocks the kernel writes, or the runtime is unmapping, are no known holes
and not published; foreign blocks are never held; freed memory forgets its
known holes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-24 23:47:04 -06:00
commit 4833ae6ea2
20 files changed
+3521 -181

No files matched your search

+13 -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.
@@ -1678,6 +1689,7 @@ impl State {
}
#[cfg(feature = "diagnostics")]
let refreshed = std::time::Instant::now();
crate::watch::look_at_holes();
self.heap_textures(list, heap, host);
#[cfg(feature = "diagnostics")]
for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked, refreshed.elapsed()]) {
+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];
+334 -51
View File
@@ -1531,7 +1531,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.
@@ -1552,7 +1552,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.
///
@@ -1602,7 +1602,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);
@@ -1612,6 +1614,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.
@@ -1678,6 +1686,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.
@@ -1694,6 +1718,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.
@@ -2461,14 +2487,21 @@ fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow:
// Per copy, the span of what is refreshed (a flush brings that much
// up to date at most).
let mut spans: Vec<(Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
// Where each copy is in it, if shaders may be writing it (none begins to
// while this runs): a frame has 20,000 refreshes of some 4,500 copies.
let mut places: ByCopy<Option<usize>> = ByCopy::default();
for list in runs {
for step in &list.deferred().copies {
if let Step::Refresh(shadow, address, len) = step
&& shadow.writes_pending()
{
match spans.iter_mut().find(|s| Arc::ptr_eq(&s.0, shadow)) {
Some(s) => (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len)),
None => spans.push((shadow.clone(), *address, *address + *len)),
if let Step::Refresh(shadow, address, len) = step {
let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| {
shadow.writes_pending().then(|| {
spans.push((shadow.clone(), *address, *address + *len));
spans.len() - 1
})
});
if let Some(i) = *place {
let s = &mut spans[i];
(s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len));
}
}
}
@@ -2704,6 +2737,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,
}
@@ -2938,9 +2973,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() {
@@ -2954,6 +2999,8 @@ fn late_line(frames: f64) {
}
mod card_steps;
mod torn;
pub(crate) mod upcheck;
#[cfg(test)]
mod late_tests {
@@ -3052,18 +3099,22 @@ fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool {
/// One list's lock at a time: a submission may name a list twice.
fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
let mut back: Vec<Declared> = Vec::new();
// Where each copy is in it, and the ranges seen: dispatches declare the
// same ranges thousands of times a frame.
let mut places: ByCopy<usize> = ByCopy::default();
let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default();
for list in runs {
for step in &list.deferred().copies {
if let Step::GpuWrite(shadow, address, len) = step {
let range = (*address, *address + *len);
match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
Some((_, ranges)) => {
if !ranges.contains(&range) {
ranges.push(range);
}
}
None => back.push((shadow.clone(), vec![range])),
let key = std::sync::Arc::as_ptr(shadow) as usize;
if !seen.insert((key, *address, *len)) {
continue;
}
let i = *places.entry(key).or_insert_with(|| {
back.push((shadow.clone(), Vec::new()));
back.len() - 1
});
back[i].1.push((*address, *address + *len));
}
}
}
@@ -3456,7 +3507,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;
@@ -3480,6 +3533,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()));
@@ -3491,7 +3548,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());
@@ -3499,7 +3556,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());
@@ -3512,6 +3569,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"));
@@ -3524,6 +3582,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.
@@ -3593,6 +3654,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.
@@ -3619,12 +3681,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 {
@@ -3657,7 +3737,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()?;
@@ -3690,6 +3772,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;
@@ -3741,6 +3826,7 @@ impl Host {
event,
sent: 0,
buffer: None,
suspects: torn::Suspects::default(),
had: crate::land::Had::default(),
})
}
@@ -3770,26 +3856,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;
@@ -3804,6 +3898,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;
@@ -3833,6 +3930,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);
@@ -3873,7 +3977,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()?;
@@ -3922,6 +4026,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)> =
@@ -3938,7 +4048,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) };
@@ -3950,6 +4064,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)),
@@ -4121,9 +4238,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);
@@ -4563,12 +4681,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);
}
@@ -4601,7 +4725,7 @@ impl Host {
for list in runs {
for step in &list.deferred().copies {
if let Step::Refresh(shadow, address, len) = step
&& !shadow.unwatched()
&& shadow.asked_ahead()
{
let span = spans
.entry(std::sync::Arc::as_ptr(shadow) as usize)
@@ -4611,6 +4735,8 @@ impl Host {
}
}
let ranges: Vec<(usize, usize)> = spans.into_values().collect();
#[cfg(feature = "diagnostics")]
SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
crate::watch::ask_once(&ranges);
#[cfg(feature = "diagnostics")]
split.part(0);
@@ -4618,6 +4744,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();
@@ -4664,7 +4793,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));
}
@@ -4684,7 +4819,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);
@@ -4804,7 +4939,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);
@@ -5929,6 +6064,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) {
@@ -6039,7 +6180,10 @@ impl HostList {
}
Step::Texture(staging) => {
if batch.texture_due(staging) {
staging.refresh();
batch.due.push(staging.clone());
if !wide_textures() {
batch.refresh_textures();
}
}
continue;
}
@@ -6089,9 +6233,11 @@ impl std::hash::Hasher for AddressHash {
/// in under flights' writes; the lists' steps, the refreshes among them; the
/// snapshots; what goes to copies in the card's memory; the lists sent; and
/// of the steps: the refreshes, and the copies and fills (those with the
/// refreshes a copy of title memory flushes).
/// refreshes a copy of title memory flushes). Of the asking, which ranges it
/// is of. Of the refreshes, those before ranges are given to shaders, one
/// copy at a time: nanoseconds, and how many.
#[cfg(feature = "diagnostics")]
static SPLIT: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
static SPLIT: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11];
/// Since the last frame-rate line: flushes of refreshes, their refreshes,
/// those known to copy nothing, and those done on several threads.
@@ -6108,6 +6254,11 @@ impl Split {
Split(std::cell::Cell::new(std::time::Instant::now()))
}
/// Nanoseconds since the last part.
fn so_far(&self) -> u64 {
self.0.get().elapsed().as_nanos() as u64
}
/// What came since the last part was part `i`.
fn part(&self, i: usize) {
let now = std::time::Instant::now();
@@ -6124,11 +6275,12 @@ fn split_line(frames: f64) {
let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect();
let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / (1 << 20) as f64 / frames).collect();
tracing::info!(
"preparing per frame, the submitting thread: {:.1} ms asking the write watch, {:.1} putting the title's bytes under flights' \
"preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \
writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \
several threads; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \
several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \
card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})",
ms[0],
ms[8],
ms[1],
ms[2],
ms[6],
@@ -6136,6 +6288,8 @@ fn split_line(frames: f64) {
f[1],
f[2],
f[3],
ms[9],
ms[10] * 1e6,
ms[7],
ms[3],
ms[4],
@@ -6143,12 +6297,17 @@ fn split_line(frames: f64) {
if crate::watch::light() { "on" } else { "off" },
);
tracing::info!(
"asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB; view ranges: {:.0} answered by their \
"asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \
written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \
bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \
waiting for the guards, {:.1} ms changing protections; pages taken again for the card: {:.1} MB compared, {:.1} MB of them \
as they were, {:.1} MB to go up (VICTORY_SEND_CHANGED)",
a[0],
a[1] / 1024.0,
a[11] / 1e6,
a[12],
a[10],
a[9],
a[2],
a[3],
a[4],
@@ -6230,8 +6389,29 @@ struct Batch {
/// for every refresh of a submission was tens of millions of
/// comparisons a frame.
index: ByCopy<usize>,
/// Staging buffers (by address) refreshed since the last title write.
/// Staging buffers (by address) refreshed since the last title write,
/// or due to be.
textures: std::collections::HashSet<usize>,
/// Those due ([`Batch::refresh_textures`]).
due: Vec<std::sync::Arc<crate::texture::Staging>>,
}
/// Whether a submission's textures are brought up to date on several
/// threads (`VICTORY_WIDE_TEXTURES=0`: one after the other, where the lists
/// name them, as before).
///
/// They are read, hashed and, if they changed, detiled into their staging
/// buffers: 5 ms a frame of the submitting thread, for some 16 MB. Each has
/// its own buffer, notes and lock, and is refreshed by the title's own
/// threads as it is. They are done before the next step that writes title
/// memory, as the copies' refreshes are, and before the lists go to the
/// card. What is new: the note of a list that its upload takes what the
/// buffer then holds (`texture.rs`, `dirty`) may come ahead of the refresh
/// an earlier list of the submission asked for, not behind it. The texture
/// is then uploaded by a later list too, once more than needed.
fn wide_textures() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_TEXTURES").is_none_or(|v| v != "0") && wide_refresh())
}
impl Batch {
@@ -6267,7 +6447,12 @@ impl Batch {
Self::update(&shadow, from, to);
}
#[cfg(feature = "diagnostics")]
SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
{
let ns = started.elapsed().as_nanos() as u64;
SPLIT[6].fetch_add(ns, Ordering::Relaxed);
SPLIT[9].fetch_add(ns, Ordering::Relaxed);
SPLIT[10].fetch_add(1, Ordering::Relaxed);
}
}
/// Brings `[from, to)` of a copy up to date, timed.
@@ -6294,7 +6479,23 @@ impl Batch {
self.textures.clear();
}
/// The textures due are brought up to date.
fn refresh_textures(&mut self) {
if self.due.len() < 2 || !wide_textures() {
self.due.drain(..).for_each(|staging| staging.refresh());
return;
}
// The time counted is the time it took, not the threads' sum.
let started = std::time::Instant::now();
let before = PREPARING[2].load(Ordering::Relaxed);
let due = std::mem::take(&mut self.due);
crate::shadow::wide_each(due.len(), move |i| due[i].refresh());
let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before);
PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed);
}
fn flush(&mut self) {
self.refresh_textures();
self.index.clear();
if self.refreshes.is_empty() {
return;
@@ -6334,7 +6535,7 @@ impl Batch {
let ranges: Vec<(usize, usize)> = self
.refreshes
.iter()
.filter(|r| !r.0.unwatched())
.filter(|r| r.0.asked_ahead())
.map(|r| (r.1, r.2))
.collect();
crate::watch::ask_ahead(&ranges);
@@ -7661,6 +7862,50 @@ mod refresh_tests {
at
}
/// Title memory of `blocks` pages in a placeholder, one view to a page,
/// and every fourth page not there: as a title that streams has it.
fn with_holes(blocks: usize) -> usize {
use windows_sys::Win32::System::Memory::{
MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS,
VirtualAlloc2, VirtualFree,
};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
// SAFETY: a placeholder and a section of our own.
unsafe {
let at = VirtualAlloc2(
GetCurrentProcess(),
std::ptr::null(),
blocks * PAGE,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS,
std::ptr::null_mut(),
0,
) as usize;
assert_ne!(at, 0);
let len = blocks * PAGE;
let section =
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, (len >> 32) as u32, len as u32, std::ptr::null());
for block in (0..blocks).filter(|b| b % 4 != 3) {
let to = at + block * PAGE;
VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
let view = MapViewOfFile3(
section,
GetCurrentProcess(),
to as *const _,
(block * PAGE) as u64,
PAGE,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
std::ptr::null_mut(),
0,
);
assert_eq!(view.Value as usize, to);
crate::title_memory_remapped(to, PAGE);
}
at
}
}
fn memory(len: usize) -> *mut u8 {
// SAFETY: a plain allocation.
unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() }
@@ -7821,7 +8066,7 @@ mod refresh_tests {
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
assert!(crate::safecopy::on());
const LEN: usize = 24 * PAGE;
let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(400);
let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(120);
let region = title(LEN, true);
let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) };
let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)];
@@ -7987,6 +8232,37 @@ mod refresh_tests {
});
}
/// The title's bytes put in under shader writes, for a copy of 174 MB
/// whose shader writes were declared as 40 ranges that overlap, with 12
/// pages written since. Run with `--ignored --nocapture`, and with
/// `VICTORY_LIGHT_REFRESH=0` for the way it was.
#[test]
#[ignore]
fn bytes_under_overlapping_ranges() {
const BIG: usize = 174 << 20;
let big = title(BIG, true);
// SAFETY (both): the test's own memory.
unsafe { std::ptr::write_bytes(big as *mut u8, 1, BIG) };
let copy = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
copy.update(big, BIG);
copy.take_dirty();
for i in 0..40 {
copy.writing(big + i * 5920, BIG - i * 5920);
}
let mut best = f64::MAX;
for round in 0..30 {
for i in 0..12 {
unsafe { ((big + (i * 211 + round) % 2700 * PAGE + 64) as *mut u8).write_volatile(round as u8) };
}
let started = std::time::Instant::now();
let mut runs = usize::MAX;
assert!(!copy.merge_under_writes(big, BIG, &mut runs));
best = best.min(started.elapsed().as_secs_f64() * 1e3);
copy.take_dirty();
}
println!("VICTORY_LIGHT_REFRESH {}: best {best:.3} ms", crate::watch::light());
}
/// A range nothing wrote is known to be as it was, at its ends too, and
/// is so no more once something wrote it.
#[test]
@@ -8078,12 +8354,17 @@ mod refresh_tests {
const EACH: usize = 224 << 10;
const BIG: usize = 174 << 20;
let watched = title(3000 * EACH, false);
let views = title(1400 * EACH, true);
// `VICTORY_BENCH_HOLES=0`: views without holes.
let holes = std::env::var_os("VICTORY_BENCH_HOLES").is_none_or(|v| v != "0");
let views = if holes { with_holes(1400 * EACH / PAGE) } else { title(1400 * EACH, true) };
let there = |at: usize| !holes || (at - views) / PAGE % 4 != 3;
let big = title(BIG, true);
// SAFETY: the test's own memory.
unsafe {
std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH);
std::ptr::write_bytes(views as *mut u8, 1, 1400 * EACH);
for at in (views..views + 1400 * EACH).step_by(PAGE).filter(|&at| there(at)) {
std::ptr::write_bytes(at as *mut u8, 1, PAGE);
}
std::ptr::write_bytes(big as *mut u8, 1, BIG);
}
let mut small = Vec::new();
@@ -8106,8 +8387,10 @@ mod refresh_tests {
// The title's writes, and the relay's beside the submission.
for _ in 0..9 {
let at = views + random.below(1400 * EACH / 8) * 8;
// SAFETY: the test's own memory.
unsafe { (at as *mut u64).write_volatile(frame as u64) };
if there(at) {
// SAFETY: the test's own memory.
unsafe { (at as *mut u64).write_volatile(frame as u64) };
}
}
for _ in 0..60 {
let at = watched + random.below(3000 * EACH / 8) * 8;
+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.
+64 -2
View File
@@ -133,6 +133,16 @@ pub(crate) fn spent(which: usize, from: std::time::Instant) -> std::time::Instan
/// For the frame-rate line: where landing went, per frame.
pub(crate) fn log(frames: f64) {
let t: Vec<f64> = TAKEN.iter().map(|t| t.swap(0, Ordering::Relaxed) as f64 / frames).collect();
if t[0] > 0.0 {
tracing::info!(
"blocks landed in beside the guards per frame: {:.0}, {:.0} of them held by the copy they were landed through, which takes \
them no more (VICTORY_LAND_TAKEN={})",
t[0],
t[1],
u8::from(taken()),
);
}
let s: Vec<f64> = STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
if s[stat::PIECES] == 0.0 && s[stat::REST] == 0.0 {
return;
@@ -416,8 +426,39 @@ pub(crate) struct Notes {
pages: Vec<usize>,
/// Per piece, from the first such page to the last: address, bytes.
spans: Vec<(usize, usize)>,
/// Per piece put beside the guards, all of it: its 64 KiB block and the
/// copy it was landed through (which the job holds until the flush).
landed: Vec<(usize, *const crate::shadow::Shadow)>,
}
// SAFETY: the pointers are used by the job that has the notes, in `flush`.
unsafe impl Send for Notes {}
/// Whether a copy a landing went through is noted as up to date with it
/// (`VICTORY_LAND_TAKEN=0`: it is not, and the next refresh copies the 64
/// KiB again and sends them up to the card, as before).
///
/// What a landing puts into title memory the copy holds already: the card
/// wrote it there, and a copy in the card's memory was given it on the CPU's
/// side by the same merge. But the block counted as written, for that copy
/// as for every other one, so the next refresh copied the whole block, sent
/// it up and had the card hash it again: some 900 blocks a frame landed
/// beside the guards, of the 103 MB a frame that went up (run record-1).
///
/// Why it may be left out ([`crate::shadow::Shadow::landed`]): the copy held
/// title memory's bytes of the block before the landing, if it had taken it
/// after the block's last noted write and no write was to be noted (the
/// block's bit, `crate::watch::block_published`), and the landing put the
/// same bytes into both. Only where one copy alone landed in the block.
fn taken() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LAND_TAKEN").is_none_or(|v| v != "0"))
}
/// Since the last frame-rate line: blocks landed in beside the guards, and
/// those of them the copy was noted as up to date with.
static TAKEN: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
impl Notes {
/// At the end of a job: what it wrote beside the guards is noted.
pub(crate) fn flush(&mut self) {
@@ -425,9 +466,24 @@ impl Notes {
return;
}
let noting = std::time::Instant::now();
crate::watch::landed_beside(&self.pages, &self.spans);
let (now, blocks) = crate::watch::landed_beside(&self.pages, &self.spans);
TAKEN[0].fetch_add(blocks.len() as u64, Ordering::Relaxed);
if taken() {
for (block, before) in blocks {
let mut through = self.landed.iter().filter(|l| l.0 == block).map(|l| l.1);
let Some(copy) = through.next() else {
continue;
};
if !copy.is_null() && through.all(|other| other == copy) {
// SAFETY: the job holds its copies until this is done.
let copy = unsafe { &*copy };
TAKEN[1].fetch_add(u64::from(copy.landed(block, before, now)), Ordering::Relaxed);
}
}
}
self.pages.clear();
self.spans.clear();
self.landed.clear();
spent(stat::NOTES, noting);
}
}
@@ -447,9 +503,10 @@ pub(crate) unsafe fn piece(
parts: &[(usize, usize)],
take: bool,
notes: &mut Notes,
copy: *const crate::shadow::Shadow,
) -> u64 {
// SAFETY: the caller's.
unsafe { piece_at(title, now, held, parts, take, notes, beside_on()) }
unsafe { piece_at(title, now, held, parts, take, notes, beside_on(), copy) }
}
/// [`piece`], and whether a view of ours is looked for.
@@ -464,6 +521,7 @@ unsafe fn piece_at(
take: bool,
notes: &mut Notes,
beside: bool,
copy: *const crate::shadow::Shadow,
) -> u64 {
let Some(end) = parts.last().map(|p| p.1) else {
return 0;
@@ -547,6 +605,10 @@ unsafe fn piece_at(
});
if let Some((from, to)) = span {
notes.spans.push((from, to - from));
// Not through a copy that is not to be noted, if that is asked: the
// block then has two.
let through = if missing == 0 { copy } else { std::ptr::null() };
notes.landed.push((title / BLOCK, through));
}
count(stat::NEW_PIECES, u64::from(new_pages > 0));
count(stat::PAGES, pages);
+5 -5
View File
@@ -192,7 +192,7 @@ fn a_piece_lands_what_the_card_wrote_in_its_parts() {
let asked = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view").0;
let mut notes = Notes::default();
// SAFETY: vectors of `len` bytes.
let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes) };
let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes, std::ptr::null()) };
notes.flush();
let mut expect_held = base.clone();
let mut expect = there.clone();
@@ -227,7 +227,7 @@ fn a_piece_waits_for_a_change_of_mapping() {
for take in [true, false] {
let mut held = [0u8; 100];
// SAFETY: arrays of 100 bytes.
let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], take, &mut Notes::default()) };
let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], take, &mut Notes::default(), std::ptr::null()) };
assert_eq!((put, held), (0, [if take { 9 } else { 0 }; 100]));
}
let (began, wait) = std::sync::mpsc::channel();
@@ -241,7 +241,7 @@ fn a_piece_waits_for_a_change_of_mapping() {
wait.recv().unwrap();
let mut held = [0u8; 100];
// SAFETY: as above.
let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], true, &mut Notes::default()) };
let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], true, &mut Notes::default(), std::ptr::null()) };
change.join().unwrap();
assert_eq!((put, held), (100, now));
// SAFETY: committed by now.
@@ -329,7 +329,7 @@ fn landings_beside_the_title_and_its_refreshes_lose_nothing() {
let offset = address - at;
// SAFETY: each job its own pieces of the two vectors.
unsafe {
piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes);
piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes, std::ptr::null());
}
}
notes.flush();
@@ -457,7 +457,7 @@ fn what_landing_costs() {
let mut notes = Notes::default();
for &(at, now, held) in &landing[jobs[j].clone()] {
// SAFETY: each its own bytes.
unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside) };
unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside, std::ptr::null()) };
}
notes.flush();
});
+4 -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;
@@ -70,6 +72,6 @@ pub use host::on_failure;
pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view};
#[cfg(windows)]
pub use watch::{
kernel_writing, title_memory_freed, title_memory_reading, title_memory_remapped, title_memory_remapping,
title_memory_unmapping, writing as kernel_will_write,
kernel_writing, title_memory_allocated, title_memory_freed, title_memory_reading, title_memory_remapped,
title_memory_remapping, title_memory_unmapping, writing as kernel_will_write,
};
+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(())
}
}
+129 -6
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)]);
@@ -908,6 +939,8 @@ fn give_back(v: Vec<u8>) {
}
const NOT_WATCHED: u8 = 2;
/// Watched, not by the kernel but by the guards, when last asked about.
const GUARDED: u8 = 3;
/// Where `a` and `b` (of one length) first differ, compared eight bytes at
/// a time.
@@ -969,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.
@@ -2011,6 +2054,14 @@ impl Shadow {
self.watched.load(Ordering::Relaxed) == NOT_WATCHED
}
/// Whether a submission asks the kernel about the copy's ranges ahead:
/// not of memory that is not watched, nor of view memory, which the
/// kernel would refuse (and with it the ranges asked about together).
pub(crate) fn asked_ahead(&self) -> bool {
let watched = self.watched.load(Ordering::Relaxed);
watched != NOT_WATCHED && (watched != GUARDED || !crate::watch::light())
}
/// The copy's own number (see the field).
pub(crate) fn id(&self) -> u64 {
self.id
@@ -2614,6 +2665,11 @@ impl Shadow {
note_stale(0);
return true;
}
// The declared ranges overlap (views of the title's whole heap from
// dozens of offsets): as one range each page is asked about and
// compared once. Every byte of it is in a declared range, and of a
// copy in the PC's memory in the snapshot.
let busy = if crate::watch::light() { joined(busy) } else { busy };
let base = start / PAGE;
let mut title = vec![0u8; PAGE];
for (a, e) in busy {
@@ -2763,7 +2819,7 @@ impl Shadow {
if from >= to {
return true;
}
if self.watched.load(Ordering::Relaxed) != 1 {
if !matches!(self.watched.load(Ordering::Relaxed), 1 | GUARDED) {
return false;
}
// Around ranges shaders are writing the refresh asks gap by gap.
@@ -2793,7 +2849,8 @@ impl Shadow {
fn update_free(&self, from: usize, to: usize) -> usize {
if self.watched.load(Ordering::Relaxed) != NOT_WATCHED {
if let Some((now, written)) = crate::watch::writes(from, to, true) {
self.watched.store(1, Ordering::Relaxed);
let guarded = crate::watch::guarded(from, to);
self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed);
let copied = self.copy_stale(from, to, now, &written);
self.refresh_check(from, to);
#[cfg(feature = "diagnostics")]
@@ -3008,7 +3065,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);
@@ -3037,6 +3103,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)> {
@@ -3084,6 +3168,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:
@@ -3328,7 +3425,7 @@ impl Shadow {
// Where title memory is not mapped the CPU's side keeps what
// the card wrote, as before.
let merged =
unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes) };
unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes, self) };
self.walls_merged(hi - lo, merged as usize);
put += merged;
}
@@ -3358,7 +3455,33 @@ impl Shadow {
// keeps out what else writes them. Title memory that is not there
// is looked at again when the next flight that declared the range
// lands.
unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes) }
unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes, self) }
}
/// What shaders wrote in 64 KiB block `block` (of title memory) of this
/// copy was put into title memory beside the guard, which was noted as a
/// write with number `now`, `before` the number of the block's last write
/// before. If the copy held title memory's bytes of the block ahead of
/// that it holds them still, and is noted to ([`crate::land`] says why);
/// whether it was.
///
/// That it did: it took the whole block after that write, and no other
/// came that is not noted yet. Looked at after the note, whatever comes
/// later has a number above it: a write of the title's takes the block's
/// bit, until an asking has noted it.
pub(crate) fn landed(&self, block: usize, before: u64, now: u64) -> bool {
let Some(page) = block.checked_sub(self.start as usize / PAGE) else {
return false;
};
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
let Some(at) = copied.get_mut(page) else {
return false;
};
let held = *at != 0 && *at >= before && crate::watch::block_published(block);
if held {
*at = (*at).max(now);
}
held
}
}
+525 -53
View File
@@ -140,11 +140,17 @@ fn kernel_written(first: usize, last: usize) -> Option<Vec<usize>> {
&mut granularity,
)
} != 0;
#[cfg(feature = "diagnostics")]
{
tally(10, u64::from(failed));
tally(11, started.elapsed().as_nanos() as u64);
}
if failed {
return None;
}
#[cfg(feature = "diagnostics")]
{
tally(12, count as u64);
use crate::copystat::{C, add};
add(C::Watches, 1);
add(C::WatchUs, started.elapsed().as_micros() as u64);
@@ -541,6 +547,27 @@ impl Bits {
}
}
/// Whether a bit of `[first, last)` is set.
fn any(&self, first: usize, last: usize) -> bool {
let mut block = first;
while block < last {
let word = block / 64;
let until = ((word + 1) * 64).min(last);
let mask = (u64::MAX >> (64 - (until - block))) << (block % 64);
match self.piece(word) {
Some(piece) => {
if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::SeqCst) & mask != 0 {
return true;
}
block = until;
}
// None of the piece's.
None => block = (word / Bits::WORDS + 1) * Bits::WORDS * 64,
}
}
false
}
/// Whether the bits of all of `[first, last)` are set (not so of none).
fn all(&self, first: usize, last: usize) -> bool {
let mut block = first;
@@ -574,18 +601,146 @@ impl Bits {
/// at the journal after that finds every earlier write in it. A write that
/// comes while the bit is looked at is no different from one that comes just
/// after an asking: the next asking finds the block open.
///
/// So too for the blocks of placeholders that were copied as zeros
/// (`Guards::held`): nothing can be there before the runtime maps it, and
/// it tells of that ([`title_memory_remapped`]) before the title is.
static PUBLISHED: Bits = Bits::new();
/// The blocks read-only by our hand, or about to be: set under the guards'
/// lock ahead of the protection, cleared under it when the block is open
/// again. Who finds none set has no guard to open and need not wait for the
/// lock ([`writing`]): some 700 pieces a frame are landed in memory that is
/// no view.
static PROTECTED: Bits = Bits::new();
/// An asking made blocks of `pages` clean and noted them in the journal.
fn publish(pages: &[usize]) {
let g = guards();
for page in pages {
if g.clean.contains(page) {
if g.clean.contains(page) || g.held.contains(page) {
PUBLISHED.set(*page);
}
}
}
/// Whether placeholders are known for what they are (`VICTORY_KNOWN_HOLES=0`:
/// every hole is looked at at every asking, as before).
///
/// Most ranges asked about have holes, reservations the title maps its pages
/// into as it streams (231,000 regions, 1,125 of a frame's 1,530 asked view
/// ranges, run next1-1). Such a range was never known whole: each asking put
/// a question to Windows for each of its holes, under the guards' lock, and
/// 111 ms a frame of all threads' time went into waiting for that lock.
fn known_holes() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_KNOWN_HOLES").is_none_or(|v| v != "0") && light())
}
/// Whether `block` lies in a placeholder: a reservation in which pages come
/// to be only by mapping a view (or an allocation) in its place, which an
/// ordinary commit cannot do.
fn placeholder(block: usize) -> bool {
/// `MEMORY_REGION_INFORMATION` (ntddk).
#[repr(C)]
#[derive(Default)]
struct Region {
allocation_base: usize,
allocation_protect: u32,
region_type: u32,
region_size: usize,
commit_size: usize,
partition_id: usize,
node_preference: usize,
}
#[link(name = "ntdll", kind = "raw-dylib")]
unsafe extern "system" {
fn NtQueryVirtualMemory(
process: *mut std::ffi::c_void,
at: *const std::ffi::c_void,
class: u32,
out: *mut std::ffi::c_void,
len: usize,
returned: *mut usize,
) -> i32;
}
// (Class 3 answers with the kind of memory in that word, not the flags.)
const MEMORY_REGION_INFORMATION_EX: u32 = 7;
const PLACEHOLDER_RESERVATION: u32 = 1 << 8;
let mut region = Region::default();
// SAFETY: the answer's room and its size.
let status = unsafe {
NtQueryVirtualMemory(
windows_sys::Win32::System::Threading::GetCurrentProcess(),
(block * BLOCK) as *const _,
MEMORY_REGION_INFORMATION_EX,
(&raw mut region).cast(),
size_of::<Region>(),
std::ptr::null_mut(),
)
};
status >= 0 && region.region_type & PLACEHOLDER_RESERVATION != 0
}
/// The runtime gave the title memory at `[at, at + len)`, allocated or
/// committed: what was known of holes there is asked again.
pub fn title_memory_allocated(at: usize, len: usize) {
if len == 0 || !known_holes() {
return;
}
let mut g = guards();
let blocks: Vec<usize> = g.held.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect();
for block in blocks {
g.held.remove(&block);
PUBLISHED.clear(block);
}
}
/// Once a frame: a hundredth of the known holes are looked at, in case one
/// was filled with nobody telling ([`title_memory_allocated`],
/// [`title_memory_remapped`]), which no title we know does.
pub(crate) fn look_at_holes() {
const PARTS: usize = 100;
if !known_holes() {
return;
}
static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let blocks: Vec<usize> = {
let g = guards();
let from = FROM.load(std::sync::atomic::Ordering::Relaxed);
let part: Vec<usize> = g.held.range(from..).take(g.held.len() / PARTS + 1).copied().collect();
FROM.store(part.last().map_or(0, |b| b + 1), std::sync::atomic::Ordering::Relaxed);
part
};
let mut until = 0;
for block in blocks {
if block >= until {
until = uncommitted_end(block);
}
if block >= until {
// (Or unmapped memory was mapped since the part was taken: told
// already, and forgotten.)
let mut g = guards();
if g.held.remove(&block) {
PUBLISHED.clear(block);
static SAID: std::sync::Once = std::sync::Once::new();
SAID.call_once(|| {
tracing::warn!(
address = format_args!("{:#x}", block * BLOCK),
"a placeholder of the title's was filled with nobody telling (VICTORY_KNOWN_HOLES=0 asks every time)"
);
});
}
}
}
}
/// Whether a block of `[start, end)` is view memory read-only by our hand:
/// the kernel keeps no written pages of it and would refuse an asking.
pub(crate) fn guarded(start: usize, end: usize) -> bool {
PROTECTED.any(start / BLOCK, end.div_ceil(BLOCK))
}
/// Whether nothing of `[start, end)` can have been written since an asking
/// noted it in the journal ([`PUBLISHED`]).
fn published(start: usize, end: usize) -> bool {
@@ -596,9 +751,11 @@ fn published(start: usize, end: usize) -> bool {
/// askings and the KiB they walked; view ranges answered by their bits, by
/// the guards whole clean, and block by block; blocks made read-only; blocks
/// opened by ourselves; nanoseconds waiting for the guards' lock and
/// nanoseconds of changing protections (all threads).
/// nanoseconds of changing protections (all threads); questions to Windows
/// about holes; kernel askings refused; nanoseconds in kernel askings; the
/// 4 KiB pages they found written.
#[cfg(feature = "diagnostics")]
static ASKS: [std::sync::atomic::AtomicU64; 9] = [const { std::sync::atomic::AtomicU64::new(0) }; 9];
static ASKS: [std::sync::atomic::AtomicU64; 13] = [const { std::sync::atomic::AtomicU64::new(0) }; 13];
#[cfg(feature = "diagnostics")]
fn tally(what: usize, n: u64) {
@@ -607,7 +764,7 @@ fn tally(what: usize, n: u64) {
/// [`ASKS`], taken.
#[cfg(feature = "diagnostics")]
pub(crate) fn asks() -> [u64; 9] {
pub(crate) fn asks() -> [u64; 13] {
std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
}
@@ -629,6 +786,8 @@ struct Guards {
/// Blocks already copied as zeros. While they remain wholly uncommitted,
/// the copy can skip hundreds of MB of failing kernel reads per world frame.
absent: BTreeSet<usize>,
/// Of those, the ones in placeholders ([`known_holes`]).
held: BTreeSet<usize>,
/// Blocks that were absent and turned out to be other memory than views
/// when something was there again: never guarded, copied every time.
foreign: BTreeSet<usize>,
@@ -650,6 +809,7 @@ static GUARDS: Mutex<Guards> = Mutex::new(Guards {
protected: BTreeSet::new(),
clean: BTreeSet::new(),
absent: BTreeSet::new(),
held: BTreeSet::new(),
foreign: BTreeSet::new(),
kernel: Vec::new(),
changing: Vec::new(),
@@ -712,7 +872,12 @@ pub(crate) fn landing(at: usize, len: usize) {
/// before they were did so with the number of an asking made before that,
/// which is under the one given here, and takes it again; noted before, a
/// copy could read the older bytes with a number above the note's.
pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) {
///
/// Returns the note's number, and for each 64 KiB block noted the number of
/// the block's last write before (0: none is known).
pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64, Vec<(usize, u64)>) {
let mut before = Vec::with_capacity(spans.len());
let noted;
{
let frame = crate::frame::current();
let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
@@ -724,11 +889,12 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) {
{
let mut j = journal_mut();
let now = next_asking();
noted = now;
let mut last = usize::MAX;
for &page in pages {
let block = page * KERNEL_PAGE / PAGE;
if block != last {
j.written.insert(block, now);
before.push((block, j.written.insert(block, now).unwrap_or(0)));
last = block;
}
}
@@ -737,6 +903,13 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) {
// A placed texture there changes with no descriptor written.
crate::descriptor::host::remapped(at, len);
}
(noted, before)
}
/// Whether every write of the title's to 64 KiB block `block` so far is in
/// the journal ([`PUBLISHED`]).
pub(crate) fn block_published(block: usize) -> bool {
light() && PUBLISHED.all(block, block + 1)
}
/// Whether shaders' writes went into a page of `[at, at + len)` in the last
@@ -776,58 +949,68 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
// of the 68 ms a frame of "guards" (run 58).
// `VICTORY_GUARD_ASK=1` asks every time, as before.
static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && {
let g = guards_timed();
let first = start / BLOCK;
g.protected.contains(&first) || g.absent.contains(&first)
};
let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1"))
&& (PROTECTED.any(first, first + 1) || {
let g = guards_timed();
g.protected.contains(&first) || g.absent.contains(&first)
});
if !known && !is_view(start, end) {
return None;
}
install();
let mut g = guards_timed();
let mut written = Vec::new();
let mut run: Option<usize> = None;
let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
// The range's clean blocks, in order: read off the set in one pass,
// not looked up one block at a time. A frame asks about some 10 GB of
// view memory, 150,000 blocks, nearly all clean: the lookups were most
// of the 60-90 ms a frame of "guards" (run 54). What the loop adds to
// the set meanwhile is the block it stands at or ones before it.
let clean: Vec<usize> = g.clean.range(first..last).copied().collect();
if clean.len() == last - first {
// Nothing written, mapped or new since the range was last taken.
#[cfg(feature = "diagnostics")]
tally(3, 1);
return Some(written);
// The holes that an ordinary commit may have filled, with no word of the
// runtime's. Windows is asked with the lock not held (the range is, no
// other thread asks about it: `ASKING`); what the runtime tells meanwhile
// takes the block out of the set, and it is looked at as any other.
let unsure: Vec<usize> = {
let g = guards_timed();
if g.clean.range(first..last).count() == last - first {
// Nothing written, mapped or new since the range was last taken.
#[cfg(feature = "diagnostics")]
tally(3, 1);
return Some(Vec::new());
}
g.absent.range(first..last).filter(|block| !g.held.contains(block)).copied().collect()
};
let mut came: Vec<(usize, bool)> = Vec::new();
let mut uncommitted_until = first;
for block in unsure {
// One question for the blocks of a region.
if block >= uncommitted_until {
uncommitted_until = uncommitted_end(block);
#[cfg(feature = "diagnostics")]
tally(9, 1);
}
if block >= uncommitted_until {
// The hole may have been given up, and its address be the
// title's heap's, or code's, now: not ours to guard.
came.push((block, is_view(block * BLOCK, (block + 1) * BLOCK)));
}
}
let mut g = guards_timed();
#[cfg(feature = "diagnostics")]
tally(4, 1);
let mut next_clean = 0;
let mut uncommitted_until = first;
for &(block, view) in &came {
if g.absent.remove(&block) && !view {
g.foreign.insert(block);
}
}
let mut written = Vec::new();
let mut run: Option<usize> = None;
// The range's clean blocks, and those known to be holes, in order: read
// off the sets in one pass, not looked up one block at a time. A frame
// asks about some 10 GB of view memory, 150,000 blocks, nearly all
// clean: the lookups were most of the 60-90 ms a frame of "guards"
// (run 54). What the loop adds to the sets meanwhile is the block it
// stands at or ones before it.
let clean: Vec<usize> = g.clean.range(first..last).copied().collect();
let absent: Vec<usize> = g.absent.range(first..last).copied().collect();
let (mut clean, mut absent) = (clean.into_iter().peekable(), absent.into_iter().peekable());
for block in first..=last {
while next_clean < clean.len() && clean[next_clean] < block {
next_clean += 1;
}
let is_clean = next_clean < clean.len() && clean[next_clean] == block;
let mut open = block < last && !is_clean;
if open && g.absent.contains(&block) {
// Ordinary commits need no runtime mapping notification. Reuse
// this asking's query for the following blocks in the same region.
if block >= uncommitted_until {
uncommitted_until = uncommitted_end(block);
}
open = block >= uncommitted_until;
if open {
g.absent.remove(&block);
// The hole may have been given up, and its address be the
// title's heap's, or code's, now: not ours to guard.
if !is_view(block * BLOCK, (block + 1) * BLOCK) {
g.foreign.insert(block);
}
}
}
if open {
let is_clean = clean.next_if_eq(&block).is_some();
let is_absent = absent.next_if_eq(&block).is_some();
if block < last && !is_clean && !is_absent {
written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE);
if g.protected.contains(&block) {
// Written through the runtime, still read-only.
@@ -924,15 +1107,30 @@ fn protect(g: &mut Guards, from: usize, to: usize) {
g.protected.extend(from..to);
g.clean.extend(from..to);
};
// Ahead of the protection (`PROTECTED`).
(from..to).for_each(|block| PROTECTED.set(block));
if set(from, to) {
note(g, from, to);
return;
}
let mut uncommitted_until = from;
for block in from..to {
if set(block, block + 1) {
// (Not one question a block of a region that is not there.)
if block >= uncommitted_until && set(block, block + 1) {
note(g, block, block + 1);
} else if block < uncommitted_end(block) {
continue;
}
PROTECTED.clear(block);
if block >= uncommitted_until {
uncommitted_until = uncommitted_end(block);
#[cfg(feature = "diagnostics")]
tally(9, 1);
}
if block < uncommitted_until {
g.absent.insert(block);
if known_holes() && placeholder(block) {
g.held.insert(block);
}
}
}
}
@@ -980,6 +1178,7 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool {
VirtualProtect((block * BLOCK) as *const _, BLOCK, old, &mut old);
}
}
PROTECTED.clear(block);
}
#[cfg(feature = "diagnostics")]
if !blocks.is_empty() {
@@ -994,7 +1193,8 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool {
/// reads into its own memory.
pub fn writing(at: usize, len: usize) {
// The length is the title's (`fread`'s size times count, saturated).
{
let last = at.saturating_add(len).div_ceil(BLOCK);
if !light() || PROTECTED.any(at / BLOCK, last) {
let mut g = guards_timed();
#[cfg(feature = "diagnostics")]
let held = g.protected.len();
@@ -1022,6 +1222,14 @@ pub fn kernel_writing(at: usize, len: usize) -> KernelWrite {
let mut g = guards_timed();
open(&mut g, at, at.saturating_add(len));
if len != 0 {
// Nothing known of them stands while they are left alone.
let absent: Vec<usize> = g.absent.range(first..last).copied().collect();
for block in absent {
g.absent.remove(&block);
if g.held.remove(&block) {
PUBLISHED.clear(block);
}
}
g.kernel.push((first, last));
}
}
@@ -1265,6 +1473,7 @@ pub fn title_memory_unmapping(at: usize, len: usize) {
g.protected.remove(&block);
g.clean.remove(&block);
PUBLISHED.clear(block);
PROTECTED.clear(block);
}
}
@@ -1290,6 +1499,9 @@ pub fn title_memory_freed(at: usize, len: usize) {
let absent: Vec<usize> = g.absent.range(first..end).copied().collect();
for block in absent {
g.absent.remove(&block);
if g.held.remove(&block) {
PUBLISHED.clear(block);
}
}
let foreign: Vec<usize> = g.foreign.range(first..end).copied().collect();
for block in foreign {
@@ -1335,6 +1547,9 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static,
let absent: Vec<usize> = g.absent.range(range.clone()).copied().collect();
for block in absent {
g.absent.remove(&block);
if g.held.remove(&block) {
PUBLISHED.clear(block);
}
}
let foreign: Vec<usize> = g.foreign.range(range).copied().collect();
for block in foreign {
@@ -1631,6 +1846,46 @@ mod tests {
unsafe { UnmapViewOfFile(view) };
}
/// A hole the kernel is to write is no known hole meanwhile, nor is one
/// the runtime has begun to change; after that it is again.
#[test]
fn what_is_left_alone_is_no_known_hole() {
let p = placeholder(3);
let known = |block: usize| published(p + block * BLOCK, p + (block + 1) * BLOCK);
let ask = || writes(p, p + 3 * BLOCK, true).expect("as a view");
ask();
let holes = known_holes();
assert!((0..3).all(known) == holes);
let writing = kernel_writing(p + BLOCK + 5, 100);
for _ in 0..2 {
assert!(known(0) == holes && !known(1) && known(2) == holes);
let (now, written) = ask();
assert!(written.contains(&(p / PAGE + 1, now)));
assert!(written.iter().all(|w| w.0 == p / PAGE + 1 || w.1 < now));
}
assert!(!guards().held.contains(&(p / BLOCK + 1)));
drop(writing);
ask();
assert!((0..3).all(known) == holes);
{
let _changing = title_memory_remapping();
title_memory_unmapping(p, BLOCK);
ask();
assert!(!known(0) && !guards().held.contains(&(p / BLOCK)));
}
ask();
assert!((0..3).all(known) == holes);
title_memory_freed(p, BLOCK);
assert!(!known(0) && !guards().held.contains(&(p / BLOCK)));
title_memory_unmapping(p, 3 * BLOCK);
// SAFETY: our placeholders.
unsafe {
for block in 0..3 {
VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
}
}
}
/// A refresh during a change of mapping guards nothing the runtime has
/// begun to unmap: no note of it stays behind.
#[test]
@@ -1697,6 +1952,8 @@ mod tests {
private_at(p, PAGE_EXECUTE_READ);
private_at(p + BLOCK, PAGE_READWRITE);
private_at(p + 2 * BLOCK, PAGE_EXECUTE_READWRITE);
// (The runtime's allocations it tells of, or the holes stay known.)
title_memory_allocated(p + BLOCK, 2 * BLOCK);
let as_made = || {
assert_eq!(protection(p), PAGE_EXECUTE_READ);
assert_eq!(protection(p + BLOCK), PAGE_READWRITE);
@@ -1707,6 +1964,8 @@ mod tests {
let written = guard(p, p + 3 * BLOCK).expect("as a view");
assert!(holes.iter().all(|page| written.contains(page)), "copied every time");
as_made();
let g = guards();
assert!(holes.iter().all(|block| !g.held.contains(block) && !g.absent.contains(block)));
}
writing(p, BLOCK);
as_made();
@@ -2249,6 +2508,219 @@ mod many_askers_tests {
// of these writes.)
}
/// A range of a placeholder with views in it is known whole, its holes
/// among it, until something is mapped into one, unmapped from it or
/// allocated there. A hole that is no placeholder's is asked about.
#[test]
fn holes_are_known_until_the_runtime_tells() {
use windows_sys::Win32::System::Threading::GetCurrentProcess;
const BLOCKS: usize = 8;
// SAFETY (all): a placeholder and a section of our own, which stay.
let (at, section) = unsafe {
let at = VirtualAlloc2(
GetCurrentProcess(),
std::ptr::null(),
BLOCKS * PAGE,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS,
std::ptr::null_mut(),
0,
) as usize;
let section =
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (BLOCKS * PAGE) as u32, std::ptr::null());
(at, section)
};
let map = |block: usize| unsafe {
let to = at + block * PAGE;
VirtualFree(to as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
let view = MapViewOfFile3(
section,
GetCurrentProcess(),
to as *const _,
(block * PAGE) as u64,
PAGE,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
std::ptr::null_mut(),
0,
);
assert_eq!(view.Value as usize, to);
super::title_memory_remapped(to, PAGE);
};
map(1);
map(5);
assert!(super::placeholder(at / PAGE) && super::placeholder(at / PAGE + 7) && !super::placeholder(at / PAGE + 5));
let end = at + BLOCKS * PAGE;
let ask = |since: u64| -> (u64, Vec<usize>) {
let (now, written) = writes(at, end, true).expect("a view");
(now, written.into_iter().filter(|w| w.1 > since).map(|w| w.0 - at / PAGE).collect())
};
let (first, all) = ask(0);
assert_eq!(all, (0..BLOCKS).collect::<Vec<_>>());
assert!(super::published(at, end), "with its holes");
// Written; mapped into; unmapped.
unsafe { ((at + 5 * PAGE) as *mut u8).write_volatile(1) };
assert!(!super::published(at, end));
let (second, all) = ask(first);
assert_eq!(all, [5]);
map(2);
assert!(!super::published(at, end));
let (third, all) = ask(second);
assert_eq!(all, [2]);
unsafe { ((at + 2 * PAGE) as *mut u8).write_volatile(1) };
let (fourth, all) = ask(third);
assert_eq!(all, [2]);
super::title_memory_unmapping(at + 5 * PAGE, PAGE);
unsafe {
let view = MEMORY_MAPPED_VIEW_ADDRESS { Value: (at + 5 * PAGE) as *mut _ };
UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER);
}
let (fifth, all) = ask(fourth);
assert_eq!(all, [5]);
assert!(super::published(at, end));
// Told of memory there, though there is none: asked about again.
super::title_memory_allocated(at, PAGE);
assert!(!super::published(at, end));
let (_, all) = ask(fifth);
assert_eq!(all, []);
// A reservation of the ordinary kind is no placeholder.
let plain = unsafe { VirtualAlloc(std::ptr::null(), PAGE, MEM_RESERVE, PAGE_NOACCESS) } as usize;
assert!(!super::placeholder(plain / PAGE));
super::look_at_holes();
assert!(!super::published(at, end), "block 0 stays asked about");
assert!(super::published(at + PAGE, end), "the others are as they were");
super::title_memory_unmapping(at, BLOCKS * PAGE);
}
/// Pages mapped into a placeholder, written and unmapped again, each by a
/// thread of its own as the runtime does it, while others ask about all
/// of it: what was written, and that a page came or went, is told to
/// whoever asks after it, and blocks are known by their bits meanwhile.
#[test]
fn no_mapping_is_lost_between_askers() {
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
const BLOCKS: usize = 12;
// SAFETY (all): a placeholder and a section of our own, which stay.
let (at, section) = unsafe {
let at = VirtualAlloc2(
GetCurrentProcess(),
std::ptr::null(),
BLOCKS * PAGE,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS,
std::ptr::null_mut(),
0,
) as usize;
for block in 0..BLOCKS - 1 {
VirtualFree((at + block * PAGE) as *mut _, PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
}
let section =
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (BLOCKS * PAGE) as u32, std::ptr::null());
(at, section as usize)
};
let end = at + BLOCKS * PAGE;
let (stop, by_bits) = (AtomicBool::new(false), AtomicUsize::new(0));
let number = |written: &[(usize, u64)], block: usize| written.iter().find(|w| w.0 == at / PAGE + block).map_or(0, |w| w.1);
std::thread::scope(|s| {
let mappers: Vec<_> = (0..4usize)
.map(|t| {
let number = &number;
s.spawn(move || {
for round in 0..120 {
let block = t * 3 + round % 3;
let to = at + block * PAGE;
let (before, _) = writes(at, end, true).expect("a view");
unsafe {
let view = MapViewOfFile3(
section as _,
GetCurrentProcess(),
to as *const _,
(block * PAGE) as u64,
PAGE,
MEM_REPLACE_PLACEHOLDER,
PAGE_READWRITE,
std::ptr::null_mut(),
0,
);
assert_eq!(view.Value as usize, to);
super::title_memory_remapped(to, PAGE);
(to as *mut u8).write_volatile(round as u8);
}
let (mapped, written) = writes(at, end, true).expect("a view");
assert!(number(&written, block) > before, "mapped and written: not told");
unsafe { ((to + 9) as *mut u8).write_volatile(round as u8) };
let (again, written) = writes(to, to + PAGE, true).expect("a view");
assert!(number(&written, block) > mapped, "written again: not told");
super::title_memory_unmapping(to, PAGE);
unsafe {
let view = MEMORY_MAPPED_VIEW_ADDRESS { Value: to as *mut _ };
assert_ne!(UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER), 0);
}
let _ = again;
}
})
})
.collect();
for t in 0..3usize {
let (stop, by_bits) = (&stop, &by_bits);
s.spawn(move || {
let mut k = t;
while !stop.load(Ordering::Relaxed) {
k = (k * 5 + 3) % 64;
let (from, to) = (at + k % 6 * PAGE, end - k / 8 % 5 * PAGE);
by_bits.fetch_add(usize::from(super::published(from, to)), Ordering::Relaxed);
assert!(writes(from, to, true).is_some());
}
});
}
let failed = mappers.into_iter().map(|m| m.join()).filter(Result::is_err).count();
stop.store(true, Ordering::Relaxed);
assert_eq!(failed, 0);
});
assert!(by_bits.into_inner() > 0, "the bits answered none");
// All unmapped: known whole, and nothing but holes.
writes(at, end, true).expect("a view");
assert!(super::published(at, end));
super::title_memory_unmapping(at, BLOCKS * PAGE);
}
/// A block's bit goes with everything that makes it the title's to write,
/// or forgets it.
#[test]
fn bits_go_with_the_guard() {
// SAFETY: a view of a section of our own, which stays.
let at = unsafe {
let section =
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (2 * PAGE) as u32, std::ptr::null());
MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * PAGE).Value as usize
};
let end = at + 2 * PAGE;
let takes: [&dyn Fn(); 4] = [
&|| super::title_memory_remapped(at, PAGE),
// SAFETY: the view.
&|| unsafe { ((at + 8) as *mut u8).write_volatile(1) },
&|| super::writing(at, 1),
// (Told again, as of a view mapped there next: it is read-only.)
&|| {
super::title_memory_unmapping(at, PAGE);
assert!(!super::published(at, end), "forgotten");
super::title_memory_remapped(at, PAGE);
let mut old = 0;
// SAFETY: the view.
unsafe { VirtualProtect(at as *const _, PAGE, PAGE_READWRITE, &mut old) };
},
];
for (i, take) in takes.iter().enumerate() {
writes(at, end, true).expect("a view");
assert!(super::published(at, end), "{i}");
take();
assert!(!super::published(at, end), "{i}");
assert!(super::published(at + PAGE, end), "{i}: the other block");
}
super::title_memory_unmapping(at, 2 * PAGE);
}
/// A range's bits are all of its blocks', whatever lies beside them.
#[test]
fn bits_of_ranges() {