Merge e1702e2 (landing on threads, card steps 2) into local/copies

What is landed beside the guards is an entry of the journal, after the
bytes are in: the blocks stay guarded, clean and known by their bits.
VICTORY_LAND_WINDOW goes, VICTORY_LAND_BESIDE does its work; the runtime
tells of a section it lets go, and our view of it goes too. A test of
landings, title writes and light refreshes at once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-24 22:32:14 -06:00
commit ee188c1df0
10 files changed
+2776 -351

No files matched your search

+518 -86
View File
@@ -1638,7 +1638,8 @@ static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atom
/// settles: about 630 pieces and 40 MB a frame (run 104), each compared
/// with the copy's CPU side byte by byte and put into title memory through
/// the kernel. A piece is its own bytes of its copy and of title memory,
/// so eight threads take an eighth of them each.
/// so eight threads take an eighth of them each. (Not with [`relay`], whose
/// landings do not come here: `crate::land` has threads of its own.)
fn wide_merge() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1"))
@@ -1677,10 +1678,9 @@ enum Step {
/// A copy into title memory (destination, source, bytes): the title's
/// buffer copies, which later refreshes must see.
Copy(usize, usize, usize),
/// A copy of title memory into the list's own upload memory; if a
/// descriptor slot shows that memory and nothing else does (a constant
/// buffer of a table made for the draw), the title heap and the slot.
Fill(usize, usize, usize, Option<(usize, u32)>),
/// A copy of title memory into the list's own upload memory, and how
/// the card could bring the bytes instead.
Fill(usize, usize, usize, Option<card_steps::FillTo>),
/// Brings a range (address, bytes) of a buffer's host copy up to date:
/// once per submission, whichever lists ask, until a `Copy` or `Run`
/// intervenes.
@@ -1970,13 +1970,16 @@ fn landable(line: &[Option<u64>], completed: u64) -> usize {
/// For one plan of copies in the card's memory, with [`relay`]: `flags`
/// holds, for every piece of every range of the plan, the copy, the
/// piece's number in the copy and whether the compare flagged it there (or
/// did not run). The pieces to fetch, under whichever range: all of them
/// flagged under any. Two ranges of a plan may hold parts of the same
/// did not run). The pieces to fetch, under whichever range, in order: all
/// of them flagged under any. Two ranges of a plan may hold parts of the same
/// 64 KiB piece; the compare hashes the whole piece for each and stores
/// the hash, so the second of them may find it stored already and not
/// flag it.
fn flagged_pieces(flags: &[(usize, u32, bool)]) -> std::collections::HashSet<(usize, u32)> {
flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect()
fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> {
let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect();
pieces.sort_unstable();
pieces.dedup();
pieces
}
#[cfg(test)]
@@ -2291,13 +2294,23 @@ fn refused(why: &'static str) {
*BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why);
}
/// The wait that comes next is for these ranges ([`stale_under_flights`]).
#[cfg(feature = "diagnostics")]
fn blame_stale(stale: &[(std::sync::Arc<crate::shadow::Shadow>, usize, usize)]) {
if let Some((shadow, from, _)) = stale.first() {
let (start, len) = shadow.span();
let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize);
BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from));
}
}
/// The wait for what [`blame`] last named, or a wait of another reason than
/// title memory read, took `us`.
#[cfg(feature = "diagnostics")]
fn blamed(why: usize, us: u64) {
let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, ""));
let (key, at) = match (why, named) {
(WHY_READ, Some(named)) => named,
(WHY_READ | WHY_STALE, Some(named)) => named,
(WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0),
_ => {
let kind = match why {
@@ -2342,7 +2355,11 @@ fn log_blame(frames: f64) {
us as f64 / 1e3 / frames,
n as f64 / frames,
passes.join(", "),
if why.is_empty() { "" } else { "; not done on the card: " },
match (why.is_empty(), kind) {
(true, _) => "",
(_, "title memory changed under shader writes") => "; not put in under them: ",
_ => "; not done on the card: ",
},
);
}
}
@@ -2416,7 +2433,7 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op
/// may write and that the title wrote since it was last copied. The
/// refresh leaves ranges shaders are writing alone (`Shadow::update`), so
/// the title's bytes there would reach the card a submission late.
fn stale_under_flights(runs: &[&HostList]) -> bool {
fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> {
use std::sync::Arc;
// Per copy, the span of what is refreshed (a flush brings that much
// up to date at most).
@@ -2437,11 +2454,15 @@ fn stale_under_flights(runs: &[&HostList]) -> bool {
// The title's bytes are put in beside the flights' writes; a
// settle is still due where that could not be done. At most this
// many changed runs go up to copies in the card's memory, each a
// copy of its own there.
let mut runs_left = 512;
return spans.iter().any(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
// copy of its own there. With [`card_steps`] the pages of the
// title's ring of constants come here too, which were waited for
// before: hundreds of short runs each, at about 1.5 us a run.
let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 };
spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left));
return spans;
}
spans.iter().any(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from))
spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from));
spans
}
/// A fence signal on a queue ([`late`]): goes behind the flights in the
@@ -2660,6 +2681,8 @@ struct RelayFetch {
sent: u64,
/// Buffer, mapping, bytes.
buffer: Option<(ID3D12Resource, usize, u64)>,
/// What earlier fetches brought of flights not landed yet.
had: crate::land::Had,
}
/// The thread that lands flights ([`relay`]): as soon as the card has run
@@ -2738,8 +2761,16 @@ fn relay_worker() {
/// in the PC's memory goes into title memory. As [`hand_back`], each byte
/// once, the pieces that differ found on several threads; but the merge is
/// `Shadow::relay_merge`, which does not write the copy, and the ranges
/// are not done with here (each flight's are, afterwards).
fn relay_hand_back(back: &[Declared]) {
/// are not done with here (each flight's are, afterwards). In two steps:
/// what is to be looked through and what of it differs ([`RelayBack::look`],
/// which needs nothing that the fetch from the card's memory brings), and
/// the merge.
struct RelayBack {
work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
found: Option<Vec<Vec<(usize, usize)>>>,
}
fn relay_hand_back(back: &[Declared]) -> RelayBack {
let mut work: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
for (shadow, declared) in back {
if shadow.carded() {
@@ -2752,27 +2783,71 @@ fn relay_hand_back(back: &[Declared]) {
}
work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to)));
}
if work.is_empty() {
return;
}
#[cfg(feature = "diagnostics")]
let scanning = std::time::Instant::now();
// Looked through without a lock: a piece that changes meanwhile (a
// later flight writing, the title's bytes going in) is found now or by
// that flight's landing, and the merge looks again under the lock.
let found = crate::shadow::find_all(&work);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
let (mut now, mut title) = (Vec::new(), Vec::new());
for ((shadow, from, to), found) in work.iter().zip(found) {
let mut written = 0;
for (at, n) in found {
written += shadow.relay_merge(at, n, &mut now, &mut title);
RelayBack { work, found: None }
}
impl RelayBack {
/// Looks the ranges through, once; its time counts as `stat`.
fn look(&mut self, stat: usize) {
if self.work.is_empty() || self.found.is_some() {
return;
}
COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
let scanning = std::time::Instant::now();
// Looked through without a lock: a piece that changes meanwhile (a
// later flight writing, the title's bytes going in) is found now or
// by that flight's landing, and the merge looks again under the
// lock.
self.found = Some(crate::shadow::find_all(&self.work));
crate::land::spent(stat, scanning);
#[cfg(feature = "diagnostics")]
crate::copystat::compared(*from, to - from, written);
let _ = (from, to);
crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64);
}
/// What differs goes into title memory.
fn merge(mut self) {
use crate::land;
self.look(land::stat::SCAN);
let Some(found) = self.found else {
return;
};
let merging = std::time::Instant::now();
let mut written: Vec<u64> = Vec::new();
if land::on() {
// Pieces in the same block of title memory in one job, in order.
let pieces: Vec<(usize, usize, usize)> =
found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect();
let start = |i: usize| self.work[i].0.span().0 as usize;
let mut order: Vec<usize> = (0..pieces.len()).collect();
order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK);
let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect();
let jobs = land::jobs(&cut);
let put: Vec<std::sync::atomic::AtomicU64> = self.work.iter().map(|_| Default::default()).collect();
land::each(jobs.len(), &|j| {
let working = std::time::Instant::now();
let mut notes = land::Notes::default();
for &p in &order[jobs[j].clone()] {
let (i, at, n) = pieces[p];
put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed);
}
notes.flush();
land::spent(land::stat::BACK_ALL, working);
});
land::count(land::stat::JOBS, jobs.len() as u64);
written.extend(put.iter().map(|p| p.load(Ordering::Relaxed)));
} else {
let (mut now, mut title) = (Vec::new(), Vec::new());
for ((shadow, ..), found) in self.work.iter().zip(found) {
let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64;
written.push(found.into_iter().map(merge).sum());
}
}
land::spent(land::stat::BACK, merging);
for ((_, from, to), written) in self.work.iter().zip(written) {
COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
crate::copystat::compared(*from, to - from, written as usize);
let _ = (from, to);
}
}
}
@@ -2841,6 +2916,7 @@ fn late_line(frames: f64) {
r[4] / 1000.0,
);
}
crate::land::log(frames);
card_steps::log(frames);
#[cfg(feature = "diagnostics")]
log_blame(frames);
@@ -3641,6 +3717,7 @@ impl Host {
event,
sent: 0,
buffer: None,
had: crate::land::Had::default(),
})
}
}
@@ -3654,21 +3731,28 @@ impl Host {
/// fetched under all ([`flagged_pieces`]); the fetch runs behind
/// whatever was sent meanwhile, so it may bring a later flight's
/// bytes, which that flight's landing then finds merged already; and
/// nothing is sent back up.
fn relay_card_back(&self, plans: &[&CardPlan], fetch: &mut Option<RelayFetch>) {
/// nothing is sent back up. `plans` come with the value signalled behind
/// their flight. `meanwhile` is called while the fetch is on its way, if
/// there is one.
fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option<RelayFetch>, meanwhile: &mut dyn FnMut()) {
use crate::land;
let gathering = std::time::Instant::now();
let differs = {
let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner());
work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize))
};
let mut pieces: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize, u64)> = Vec::new();
let mut total = 0u64;
if 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) };
let mut seen = std::collections::HashSet::new();
for plan in plans {
for &(plan, behind) in plans {
let flags: Vec<(usize, u32, bool)> = plan
.ranges
.iter()
@@ -3683,11 +3767,20 @@ impl Host {
for r in &plan.ranges {
let copy = std::sync::Arc::as_ptr(&r.shadow) as usize;
for p in 0..r.span.pieces {
if !fetched.contains(&(copy, r.span.first + p)) {
if fetched.binary_search(&(copy, r.span.first + p)).is_err() {
continue;
}
let (lo, hi) = r.shadow.card_piece(&r.span, p);
if lo < hi && seen.insert((copy, lo, hi)) {
if lo < hi && !seen.contains(&(copy, lo, hi)) {
let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo);
if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) {
land::count(land::stat::HAD, 1);
land::count(land::stat::HAD_BYTES, (hi - lo) as u64);
if land::skip_on() {
continue;
}
}
seen.insert((copy, lo, hi));
pieces.push((r.shadow.clone(), lo, hi, total));
total += (hi - lo) as u64;
}
@@ -3696,12 +3789,29 @@ impl Host {
}
}
}
if land::on() {
// In the order they are landed, each byte of a copy once.
let keys: Vec<land::Piece> =
pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect();
total = 0;
pieces = land::ordered(&keys)
.into_iter()
.map(|(i, title, len)| {
let shadow = &pieces[i].0;
let lo = title - shadow.span().0 as usize;
let at = total;
total += len as u64;
(shadow.clone(), lo, lo + len, at)
})
.collect();
}
land::spent(land::stat::GATHER, gathering);
if fetch.is_none() {
*fetch = self.make_relay_fetch();
}
// The sends these flights ran behind, all a fetch on the copy queue
// is known to have run behind.
let behind = plans.iter().map(|p| p.sent_as).max().unwrap_or(0);
let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
if pieces.is_empty() {
// Nothing to fetch: every send so far is older than the next
// fetch, if that goes to the queue the sends went to.
@@ -3726,6 +3836,12 @@ impl Host {
let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
let copy_queue = f.queue.clone();
let waiting = std::time::Instant::now();
// The flights the fetch runs behind: those in the line by now have
// been given to the queue. On the copy queue, those landed here.
let ahead = match copy_queue {
Some(_) => 0,
None => line().target,
};
// SAFETY: the list's last run was waited for by this thread; live
// buffers (the copies are held by the plans); the fence and the
// event are this thread's.
@@ -3741,6 +3857,7 @@ impl Host {
if let Some(queue) = &copy_queue {
queue.ExecuteCommandLists(&lists);
queue.Signal(&fence, sent)?;
meanwhile();
fence.SetEventOnCompletion(sent, event)?;
WaitForSingleObject(event, INFINITE);
return Ok(behind);
@@ -3753,6 +3870,7 @@ impl Host {
drop(order);
self.card_sent();
self.queue.Signal(&fence, sent)?;
meanwhile();
fence.SetEventOnCompletion(sent, event)?;
WaitForSingleObject(event, INFINITE);
Ok(after)
@@ -3771,17 +3889,48 @@ impl Host {
CARD_STATS[5].fetch_add(1, Ordering::Relaxed);
CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
}
let mut title = Vec::new();
let merging = std::time::Instant::now();
let mut written = 0;
for (shadow, lo, hi, at) in &pieces {
// SAFETY: the mapping of the fetched bytes, `total` of them;
// the copy into it has run.
let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
shadow.walls_merged(gpu.len(), merged);
written += merged;
if land::on() {
let titles: Vec<(usize, usize)> =
pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect();
let jobs = land::jobs(&titles);
let put = std::sync::atomic::AtomicU64::new(0);
land::each(jobs.len(), &|j| {
let working = std::time::Instant::now();
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)> =
run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect();
// SAFETY: the mapping of the fetched bytes, `total` of
// them; the copy into it has run, and the next waits
// for this call.
put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed);
}
notes.flush();
land::spent(land::stat::CARD_ALL, working);
});
land::count(land::stat::JOBS, jobs.len() as u64);
written = put.into_inner();
} else {
let mut title = Vec::new();
for (shadow, lo, hi, at) in &pieces {
// SAFETY: the mapping of the fetched bytes, `total` of them;
// the copy into it has run.
let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
shadow.walls_merged(gpu.len(), merged);
written += merged as u64;
}
}
land::spent(land::stat::CARD, merging);
COPY_BACK[1].fetch_add(written, Ordering::Relaxed);
if let Some(f) = fetch.as_mut() {
f.had.fetched(
ahead,
pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)),
);
}
COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
// Sends up to `after` are of no use to any later merge.
crate::shadow::relay_fetched(after);
}
@@ -3816,24 +3965,25 @@ impl Host {
last_notes(&runs)
));
}
let plans: Vec<&CardPlan> = flights.iter().filter_map(|f| f.card.as_ref()).collect();
self.relay_card_back(&plans, fetch);
let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect();
// (Each byte once: the ranges are joined.)
let mut back: Vec<Declared> = Vec::new();
for flight in &flights {
for (shadow, ranges) in &flight.back {
for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) {
match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) {
Some((_, all)) => {
for range in ranges {
if !all.contains(range) {
all.push(*range);
}
}
}
Some((_, all)) => all.extend_from_slice(ranges),
None => back.push((shadow.clone(), ranges.clone())),
}
}
}
relay_hand_back(&back);
let mut hand_back = relay_hand_back(&back);
self.relay_card_back(&plans, fetch, &mut || {
if crate::land::on() {
hand_back.look(crate::land::stat::SCAN_BESIDE);
}
});
hand_back.merge();
let finishing = std::time::Instant::now();
// Only now, and flight by flight: a range another flight
// in the air declared too stays closed to refreshes.
for flight in &flights {
@@ -3841,6 +3991,7 @@ impl Host {
shadow.copy_back_done(ranges);
}
}
crate::land::spent(crate::land::stat::DONE, finishing);
COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
RELAY_STATS[0].fetch_add(1, Ordering::Relaxed);
RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed);
@@ -3849,8 +4000,9 @@ impl Host {
// In the order given: what tells the title the card is done.
let mut last = 0;
let mut landed = Vec::new();
let mut telling = std::time::Instant::now();
for item in items {
match item {
telling = match item {
Late::Run(flight) => {
last = flight.number;
for &i in &flight.order {
@@ -3863,16 +4015,24 @@ impl Host {
own.landed();
}
landed.push((flight.lists, flight.order));
crate::land::spent(crate::land::stat::READ_BACKS, telling)
}
Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value),
}
Late::Write(at, what, bytes) => {
what.write(at as *mut u8, bytes);
crate::land::spent(crate::land::stat::TOLD, telling)
}
Late::Signal(fence, value) => {
crate::fence::set(fence as crate::object::This, value);
crate::land::spent(crate::land::stat::TOLD, telling)
}
};
}
if last > 0 {
FINISHED.store(last, Ordering::Release);
bury(last);
}
self.log_messages();
crate::land::spent(crate::land::stat::REST, telling);
RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
{
let mut line = line();
@@ -4295,6 +4455,40 @@ impl Host {
working(was_working);
}
/// For a submission of `runs` that refreshes the ranges `stale` of host
/// copies, which flights may be writing and the title wrote too
/// ([`stale_under_flights`]): the flights land first. `ranges` are
/// those of the submission's one asking, which is made again.
///
/// With [`card_steps`] only the flights that declared them: a range of
/// a copy nobody declared any more is refreshed like any other. What
/// they landed is title memory written, so everything is asked and
/// looked at again; what is left after three times waits as before.
fn settle_stale(
&self,
submitted: &mut u64,
runs: &[&HostList],
mut stale: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
ranges: &[(usize, usize)],
) {
if relay_exact() && card_steps::stage() > 0 {
for _ in 0..3 {
#[cfg(feature = "diagnostics")]
blame_stale(&stale);
relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to)));
crate::watch::ask_once(ranges);
stale = stale_under_flights(runs);
if stale.is_empty() {
return;
}
}
}
#[cfg(feature = "diagnostics")]
blame_stale(&stale);
self.settle(submitted, WHY_STALE);
crate::watch::ask_once(ranges);
}
/// [`Host::execute`], or with `late` the first half of
/// [`Host::execute_late`]: the lists are prepared and sent, and what is
/// to be done once they have run comes back with the submission lock
@@ -4400,13 +4594,13 @@ 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 && stale_under_flights(runs) {
let stale = if behind { stale_under_flights(runs) } else { Vec::new() };
if !stale.is_empty() {
let settling = std::time::Instant::now();
self.settle(&mut submitted, WHY_STALE);
self.settle_stale(&mut submitted, runs, stale, &ranges);
settled += settling.elapsed();
crate::watch::ask_once(&ranges);
}
} else if behind && stale_under_flights(runs) {
} else if behind && !stale_under_flights(runs).is_empty() {
let settling = std::time::Instant::now();
self.settle(&mut submitted, WHY_STALE);
settled += settling.elapsed();
@@ -5369,7 +5563,14 @@ impl HostList {
pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) {
self.deferred()
.copies
.push(Step::Fill(dst as usize, src as usize, len, Some(slot)));
.push(Step::Fill(dst as usize, src as usize, len, Some(card_steps::FillTo::Slot(slot.0, slot.1))));
}
/// As [`HostList::defer_fill`], for the beginning of a buffer
/// [`HostList::upload`] made.
pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) {
let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone()));
self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to));
}
/// Brings `[address, address + len)` of a buffer's host copy up to date
@@ -5421,7 +5622,8 @@ impl HostList {
///
/// shortcut: one buffer per copy; pool them once uploads are frequent.
pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
let (buffer, data) = host.upload_buffer(size)?;
// With [`card_steps`] the card may be the one that fills it.
let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? };
name(&buffer, || format!("list upload {size:#x}"));
self.deferred().hold_upload(buffer.clone(), size);
Some((buffer, data))
@@ -5880,8 +6082,7 @@ fn split_line(frames: f64) {
);
tracing::info!(
"asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB; 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 ({:.0} pieces \
put past the guards, VICTORY_LAND_WINDOW); {:.1} ms \
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],
@@ -5891,7 +6092,6 @@ fn split_line(frames: f64) {
a[4],
a[5],
a[6],
a[9],
a[7] / 1e6,
a[8] / 1e6,
s[0],
@@ -7468,6 +7668,234 @@ mod refresh_tests {
}
}
/// A copy in the card's memory, with the card's side and the sends to it
/// played by the test.
struct Carded {
shadow: Arc<Shadow>,
data: usize,
start: usize,
len: usize,
/// The last send, the last send every fetch to come is behind, and
/// the card's bytes: the queue's order is the order it is locked in.
card: std::sync::Mutex<(u64, u64, Vec<u8>)>,
/// Whether a flight that writes it has not landed.
flying: std::sync::atomic::AtomicBool,
/// The dword of each eight its shaders write.
class: usize,
}
impl Carded {
fn new(start: usize, len: usize, class: usize) -> Carded {
let data = memory(len);
Carded {
shadow: Shadow::unbacked(start as u64, data, len as u64, true),
data: data as usize,
start,
len,
card: std::sync::Mutex::new((0, 0, vec![0; len])),
flying: std::sync::atomic::AtomicBool::new(false),
class,
}
}
/// What changed on the CPU's side goes up.
fn send(&self) {
let mut card = self.card.lock().unwrap();
card.0 += 1;
let (number, merged) = (card.0, card.1);
for (a, b) in self.shadow.send_up(number, merged) {
// SAFETY: the copy's bytes; nothing writes those that are to
// go up.
unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) };
}
}
}
/// Everything at once: the title writes its memory on two threads, the
/// submitting thread puts its bytes in under shader writes
/// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in
/// the card's memory, one not), sends up what changed and declares what
/// the next flight's shaders write, and what flights wrote is landed
/// meanwhile (`crate::land`, beside the guards). When all of it stands
/// still and the copies are refreshed once more, each of them, and the
/// card's side of those that have one, hold what title memory holds, and
/// title memory what was written last.
///
/// (It fails in the first rounds if `landed_beside` notes nothing, or
/// only takes the block out of the guards' clean ones and leaves its bit,
/// or if a fault leaves the bit; in some thousand rounds,
/// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.)
#[test]
fn landings_title_writes_and_light_refreshes_at_once() {
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 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)];
let plain = {
let (start, len) = (region + 700, LEN - 9000);
let data = memory(len);
(Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize)
};
let stop = AtomicBool::new(false);
// Also when an assertion fails on one of the threads.
struct Stop<'a>(&'a AtomicBool);
impl Drop for Stop<'_> {
fn drop(&mut self) {
self.0.store(true, Ordering::Relaxed);
}
}
// Held shared by who writes title memory, alone while it is looked at.
let still = std::sync::RwLock::new(());
let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>();
std::thread::scope(|s| {
for t in 0..2usize {
let (stop, still) = (&stop, &still);
s.spawn(move || {
let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111);
let mut value = 0u32;
while !stop.load(Ordering::Relaxed) {
{
let _moving = still.read().unwrap();
for _ in 0..3 {
value += 1;
// Of each eight dwords, one a thread.
let at = random.below(LEN / 32) * 32 + 4 * (1 + t);
dword(at).store(value, Ordering::Relaxed);
}
}
std::thread::sleep(std::time::Duration::from_micros(20));
}
});
}
// Lands flights.
{
let (carded, stop) = (&carded, &stop);
s.spawn(move || {
let _stop = Stop(stop);
while let Ok((which, ranges, value)) = flights.recv() {
let c = &carded[which];
// Fetched: the card's bytes, behind every send so far.
let (after, now) = {
let card = c.card.lock().unwrap();
(card.0, card.2.clone())
};
// By piece: 64 KiB of title memory.
let mut pieces = Vec::new();
for &(from, to) in &ranges {
let mut at = from;
while at < to {
let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to);
pieces.push((at, next, now.as_ptr() as usize + at));
at = next;
}
}
let parts: Vec<_> = pieces.chunks(3).collect();
crate::land::each(parts.len(), &|i| {
let mut notes = crate::land::Notes::default();
// SAFETY: the bytes of `now`; each piece once.
unsafe { c.shadow.land_card(parts[i], after, &mut notes) };
notes.flush();
});
for &(from, to) in &ranges {
for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
// (The next fetch may have brought more.)
assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed");
}
}
let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect();
c.shadow.copy_back_done(&done);
c.card.lock().unwrap().1 = after;
c.flying.store(false, Ordering::Release);
}
});
}
let _stop = Stop(&stop);
let mut random = Random(0xABCD_EF01_2345_6789);
let check = |round: usize, random: &mut Random, quiet: bool| {
for c in &carded {
if c.shadow.writes_pending() {
let mut runs = usize::MAX;
assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}");
}
}
let mut ranges = Vec::new();
for (shadow, start, len) in
carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)])
{
// All of it, or a part; often the same part.
let (from, n) = match random.below(3) {
_ if quiet => (0, len),
0 => (0, len),
1 => (len / 3 / 4 * 4, len / 2 / 4 * 4),
_ => {
let from = random.below(len / 4) * 4;
(from, (4 + random.below((len - from) / 4) * 4).min(len - from))
}
};
ranges.push((shadow.clone(), start + from, n));
}
submission(&ranges, 1 + random.below(3));
carded.iter().for_each(Carded::send);
};
let mut value = 1u32;
for round in 0..rounds {
check(round, &mut random, false);
// The flight of this submission: its shaders' writes.
for (which, c) in carded.iter().enumerate() {
if c.flying.swap(true, Ordering::Acquire) {
continue;
}
value += 1;
let mut ranges: Vec<(usize, usize)> = Vec::new();
let first = random.below(6) * PAGE / 2;
for k in 0..2 {
let from = first + k * 9 * PAGE + 4 * random.below(9000);
let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len);
if from < to {
ranges.push((from, to));
}
}
for &(from, to) in &ranges {
c.shadow.writing(c.start + from, to - from);
}
{
let mut card = c.card.lock().unwrap();
for &(from, to) in &ranges {
for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) {
card.2[at..at + 4].copy_from_slice(&value.to_le_bytes());
}
}
}
fly.send((which, ranges, value)).unwrap();
}
if round % 20 != 19 {
continue;
}
// Still: no flight in the air, no title write.
let _still = still.write().unwrap();
while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) {
assert!(!stop.load(Ordering::Relaxed), "the landing thread failed");
std::thread::yield_now();
}
check(round, &mut random, true);
// SAFETY: the test's own memory, written by nobody now.
let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) };
let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y);
for c in &carded {
let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len));
assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class);
let card = c.card.lock().unwrap();
assert_eq!(first(&card.2, there), None, "round {round}: a card copy's card side (class {})", c.class);
}
assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy");
}
drop(fly);
});
}
/// 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]
@@ -7575,6 +8003,9 @@ mod refresh_tests {
small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000));
}
let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG);
// The same memory, as another copy: what is landed is landed through
// it, and the refreshes are of the first.
let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true);
let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]);
let (mut sum, mut landing) = (0.0, 0.0);
const FRAMES: usize = 12;
@@ -7593,18 +8024,19 @@ mod refresh_tests {
unsafe { (at as *mut u64).write_volatile(frame as u64) };
}
let first = random.below(BIG / PAGE - 60);
let lands = lands.clone();
let land = std::thread::spawn(move || {
let mut took = 0.0;
for piece in first..first + 55 {
let mut was = vec![0; PAGE];
assert!(super::read_into((big + piece * PAGE) as *const u8, &mut was));
let mut now = was.clone();
now[8..PAGE - 8].fill(frame as u8 ^ i as u8);
let started = std::time::Instant::now();
Shadow::put(big + piece * PAGE, &was, &now);
took += started.elapsed().as_secs_f64() * 1e3;
let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE];
let started = std::time::Instant::now();
for pieces in (first..first + 55).collect::<Vec<_>>().chunks(4) {
let pieces: Vec<_> =
pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect();
let mut notes = crate::land::Notes::default();
// SAFETY: the bytes of `now`; nothing else lands here.
unsafe { lands.land_card(&pieces, 0, &mut notes) };
notes.flush();
}
took
started.elapsed().as_secs_f64() * 1e3
});
let ranges: Vec<(Arc<Shadow>, usize, usize)> = if i == 0 {
small.iter().cloned().chain([heap.clone()]).collect()
+433 -133
View File
@@ -9,17 +9,21 @@ use crate::shadow::Shadow;
/// The stage (`VICTORY_CARD_STEPS`; off by default): `1` constant buffers
/// of descriptor tables (`Step::Fill` with a slot of its own), `2` the
/// title's buffer copies (`Step::Copy`) too. Only with the relay's second
/// stage (`relay_exact`).
/// title's buffer copies (`Step::Copy`) too, with the steps of the same
/// submission that depend on them. Only with the relay's second stage
/// (`relay_exact`).
///
/// Why: a root view has no size, so a pass that writes through one into the
/// title's 174 MB heap is declared to write all that is left of it, and
/// some pass of every flight does. The title's ring of constants lies in
/// the same heap. One constant buffer of 480 bytes and one copy of 20 KiB a
/// frame, at a new place of the ring each time, waited for nearly
/// everything in the air: 25-30 ms of a 105 ms frame, the submitting thread
/// standing (run record-1; with `VICTORY_FILL_TITLE=1` in run relaycopy-1
/// the copy alone took over the wait).
/// Why: eleven dispatches a frame (the skinning passes, in two early
/// submissions) write through a view of the title's whole 174 MB heap, at
/// places they read out of job records in buffers: no bound of what they
/// write is known before they ran (frame capture replay2: 17af15c4015cb4b6,
/// 55679a0547649d0b, 89d08e561897d4e5, fdd56d97a806bcca and three more,
/// all through one view at offset 5920 of the title's bindless table). The
/// title's ring of constants lies in the same heap. One constant buffer of
/// 480 bytes and one copy of 20 KiB a frame, at a new place of the ring
/// each time, waited for these passes to land: 25-30 ms of a 105 ms frame,
/// the submitting thread standing (run record-1; with `VICTORY_FILL_TITLE=1`
/// in run relaycopy-1 the copy alone took over the wait).
///
/// What is done: a list of ours goes to the card in front of the
/// submission's lists, in the same call. It copies the bytes read from the
@@ -41,8 +45,10 @@ use crate::shadow::Shadow;
/// like any other list's (also under flights' declared writes:
/// `stale_under_flights`, which settles if it cannot). Nothing of this
/// submission writes these bytes earlier than our list: the steps are done
/// in front of all its lists in either case, and [`plan`] refuses when
/// another step of the submission writes what is read. Every draw that
/// in front of all its lists in either case, and among themselves in the
/// order they stand in wherever one depends on another: [`plan`] takes
/// every copy and fill of the submission that writes what a taken one
/// reads or writes, or reads what a taken one writes. Every draw that
/// reads a buffer view of the heap relies on the same refresh and the same
/// order; what is new is only that a constant buffer and a copy do too.
/// Where a page is not mapped the host copy may hold other bytes than the
@@ -54,9 +60,10 @@ use crate::shadow::Shadow;
/// memory before the title is told anything of this flight (its
/// bottom-of-pipe writes and fences come after, in order); CPU steps of
/// later submissions that read it find it declared and wait, or are done
/// here. Refused: another step of the submission reads or writes the
/// destination on the CPU, or a refresh brings another host copy of it up
/// to date ([`plan`], [`elsewhere`]). While such a copy is in the air a
/// here. Refused: a step of the submission that cannot be taken (a texture,
/// vertices expanded, a fill of memory of another kind) reads the
/// destination behind the copy, or a refresh brings another host copy of it
/// up to date ([`plan`], [`elsewhere`]). While such a copy is in the air a
/// submission that refreshes another host copy of its destination, or
/// reads it in a step that is not checked otherwise, waits for it
/// ([`copied_read`]); with the copy done on the CPU it was there at once.
@@ -77,8 +84,22 @@ pub(super) fn stage() -> u32 {
}
/// The bytes of our buffer between reading and writing: what one submission
/// may do this way.
const BETWEEN: u64 = 1 << 20;
/// may do this way (each place read once, however many fills take it).
const BETWEEN: u64 = 4 << 20;
/// The most steps of a submission done this way.
const MOST: usize = 4096;
/// How a fill's bytes get where its list reads them, if the card brings
/// them.
#[derive(Clone)]
pub(super) enum FillTo {
/// A descriptor slot that shows the fill's memory, and nothing else does
/// (title heap, slot): it is made to show our buffer instead.
Slot(usize, u32),
/// A buffer the card can write, filled from its beginning.
Buffer(ID3D12Resource),
}
/// Title memory something in the air writes: the host copy it goes through
/// (`None`: none, the bytes reach title memory when the flight lands), from,
@@ -167,7 +188,8 @@ pub(super) fn copied_read(copies: &[Writer], runs: &[&HostList]) -> bool {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Does {
Copy { dst: usize, src: usize, len: usize, asked: bool },
Fill { src: usize, len: usize, asked: bool, slot: Option<(usize, u32)> },
/// `to`: its memory can be given the bytes on the card.
Fill { src: usize, len: usize, asked: bool, to: bool },
/// Another read on the CPU (a texture, vertices expanded).
Read { from: usize, to: usize, asked: bool },
/// A refresh of a host copy (named by its address).
@@ -180,51 +202,125 @@ fn meet(a: (usize, usize), b: (usize, usize)) -> bool {
a.0 < b.1 && b.0 < a.1
}
/// The steps of `does` (by place) to be done on the card: all that are
/// asked for, or why not. Our list does them all in front of the
/// submission's, every read before every write, so that is right only if no
/// step, asked for or not, writes what one of them reads or writes, and no
/// CPU step reads what one of them writes.
fn plan(does: &[Does], stage: u32) -> Result<Vec<usize>, &'static str> {
let mut asked = Vec::new();
/// The bytes `d` reads and writes as a copy or a fill (empty ranges for
/// what it does not).
fn reads_writes(d: &Does) -> Option<((usize, usize), (usize, usize))> {
match *d {
Does::Copy { dst, src, len, .. } => Some(((src, src + len), (dst, dst + len))),
Does::Fill { src, len, .. } => Some(((src, src + len), (0, 0))),
_ => None,
}
}
fn touched(ranges: &[(usize, usize)], r: (usize, usize)) -> bool {
touches(ranges, r.0, r.1)
}
/// The steps of `does` (by place) to be done on the card, in order, each
/// with its level; or why not. All that are asked for, and every copy and
/// fill that is in the way of one that is done there: it writes what that
/// one reads or writes, or reads what it writes, whichever comes first. So
/// what is left on the CPU writes none of their bytes, and reads of them
/// only what a taken copy has not been told to write yet: bytes a step
/// ahead of it reads, in title memory as it is.
///
/// Steps of a level are done together, every read before every write; a
/// step that writes what an earlier one reads or writes, or reads what it
/// writes, is of a higher level. Our list does them level by level.
fn plan(does: &[Does], stage: u32) -> Result<Vec<(usize, u32)>, &'static str> {
let takes = |d: &Does| match *d {
Does::Copy { .. } if stage < 2 => Err("a buffer copy (VICTORY_CARD_STEPS=2 does it on the card)"),
Does::Fill { to: false, .. } => Err("a fill of memory the card cannot be given the bytes of"),
_ => Ok(()),
};
let mut taken = vec![false; does.len()];
let (mut read, mut written) = (Vec::new(), Vec::new());
let mut more = Vec::new();
for (i, d) in does.iter().enumerate() {
match *d {
Does::Run => return Err("a step of ours runs"),
Does::Read { asked: true, .. } => return Err("a texture reads it"),
Does::Fill { asked: true, slot: None, .. } => return Err("a fill without a descriptor slot of its own"),
Does::Copy { asked: true, .. } if stage < 2 => return Err("a buffer copy (VICTORY_CARD_STEPS=2 does it on the card)"),
Does::Copy { asked: true, .. } | Does::Fill { asked: true, .. } => asked.push(i),
Does::Copy { asked: true, .. } | Does::Fill { asked: true, .. } => more.push(i),
_ => {}
}
}
for &i in &asked {
let (src, dst) = match does[i] {
Does::Copy { dst, src, len, .. } => ((src, src + len), Some((dst, dst + len))),
Does::Fill { src, len, .. } => ((src, src + len), None),
_ => continue,
};
for (k, d) in does.iter().enumerate() {
let (read, written) = match *d {
Does::Copy { dst, src, len, .. } => (Some((src, src + len)), Some((dst, dst + len))),
Does::Fill { src, len, .. } => (Some((src, src + len)), None),
Does::Read { from, to, .. } => (Some((from, to)), None),
Does::Refresh { .. } | Does::Run => (None, None),
};
if written.is_some_and(|w| meet(w, src)) {
return Err("a copy of the submission writes what it reads");
while !more.is_empty() {
for i in std::mem::take(&mut more) {
takes(&does[i])?;
taken[i] = true;
if let Some((r, w)) = reads_writes(&does[i]) {
if w.0 < w.1 && meet(r, w) {
return Err("a copy onto itself");
}
join_ranges(&mut read, [r]);
join_ranges(&mut written, [w]);
}
let Some(dst) = dst else {
}
if taken.iter().filter(|t| **t).count() > MOST {
return Err("too many steps depend on it");
}
for (i, d) in does.iter().enumerate() {
// A fill that cannot be taken is looked at below.
if taken[i] || matches!(d, Does::Fill { to: false, .. }) {
continue;
};
if k != i && written.is_some_and(|w| meet(w, dst)) {
return Err("another copy of the submission writes what it writes");
}
if read.is_some_and(|r| meet(r, dst)) {
return Err("a step of the submission reads what it writes");
if let Some((r, w)) = reads_writes(d)
&& (touched(&written, r) || touched(&written, w) || touched(&read, w))
{
more.push(i);
}
}
}
Ok(asked)
let order: Vec<usize> = (0..does.len()).filter(|&i| taken[i]).collect();
// What stays on the CPU and reads what an earlier taken copy writes
// would read it too early.
let mut behind: Vec<(usize, usize)> = Vec::new();
for (i, d) in does.iter().enumerate() {
if taken[i] {
if let Some((_, w)) = reads_writes(d) {
join_ranges(&mut behind, [w]);
}
continue;
}
match *d {
Does::Read { from, to, .. } if touched(&behind, (from, to)) => {
return Err("a texture or expanded vertices read what it writes");
}
Does::Fill { src, len, .. } if touched(&behind, (src, src + len)) => {
return Err("a fill of memory the card cannot be given the bytes of reads what it writes");
}
_ => {}
}
}
let mut out: Vec<(usize, u32)> = Vec::with_capacity(order.len());
// The copies among them, which alone put others behind them or have to
// stand behind others.
let mut copies: Vec<usize> = Vec::new();
for &i in &order {
let Some((r, w)) = reads_writes(&does[i]) else {
continue;
};
let writes = w.0 < w.1;
let mut level = 0;
// Behind what writes what this reads or writes, and, if this
// writes, behind what reads it.
let ahead: Box<dyn Iterator<Item = usize>> =
if writes { Box::new(0..out.len()) } else { Box::new(copies.iter().copied()) };
for k in ahead {
let (j, at): (usize, u32) = out[k];
let Some((jr, jw)) = reads_writes(&does[j]) else {
continue;
};
if at >= level && (meet(jw, r) || meet(jw, w) || meet(jr, w)) {
level = at + 1;
}
}
if writes {
copies.push(out.len());
}
out.push((i, level));
}
Ok(out)
}
/// Whether a refresh of `does` brings a host copy other than `shadow` up to
@@ -272,6 +368,7 @@ struct Op {
len: usize,
/// Its place in the buffer between.
at: u64,
level: u32,
to: To,
}
@@ -280,14 +377,18 @@ enum To {
Copy(Arc<Shadow>, usize),
/// A descriptor slot (title heap, slot).
Slot(usize, u32),
/// A buffer's beginning.
Buffer(ID3D12Resource),
}
/// Records what [`stage`] describes into `list` (open): `reads` are copied
/// into `between` (source, offset in it, offset in `between`, bytes), then
/// `writes` out of it (destination, offset in it, offset in `between`,
/// bytes). `between` is left readable as constants, the others in the
/// common state, as the submission's lists expect them.
/// Records a level of what [`stage`] describes into `list` (open): `reads`
/// are copied into `between` (source, offset in it, offset in `between`,
/// bytes), then `writes` out of it (destination, offset in it, offset in
/// `between`, bytes). `between` is left readable as constants (and must be
/// so, unless this is the `first` level), the others in the common state,
/// as the submission's lists expect them.
fn record(
first: bool,
list: &ID3D12GraphicsCommandList,
between: &ID3D12Resource,
reads: &[(&ID3D12Resource, u64, u64, u64)],
@@ -305,23 +406,28 @@ fn record(
}
}
let both = |b: &ID3D12Resource| dests.iter().any(|d| d.as_raw() == b.as_raw());
let mut barriers = vec![transition(between, dest, source | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER)];
let constants = source | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
let mut barriers = vec![transition(between, dest, constants)];
barriers.extend(sources.iter().map(|b| transition(b, source, if both(b) { dest } else { common })));
let done: Vec<D3D12_RESOURCE_BARRIER> = dests.iter().map(|b| transition(b, dest, common)).collect();
// SAFETY: an open list; live buffers, and the callers' ranges lie in
// them. The buffers start in the common state (the list is the first of
// its call) and are promoted by their first use.
unsafe {
// What earlier lists' shaders wrote, first.
list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
pResource: std::mem::ManuallyDrop::new(None),
}),
},
}]);
if first {
// What earlier lists' shaders wrote, first.
list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
pResource: std::mem::ManuallyDrop::new(None),
}),
},
}]);
} else {
list.ResourceBarrier(&[transition(between, constants, dest)]);
}
for &(buffer, offset, at, len) in reads {
list.CopyBufferRegion(between, at, buffer, offset, len);
}
@@ -426,6 +532,8 @@ impl Host {
fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result<Option<Taken>, &'static str> {
let mut does = Vec::new();
// Where the fills' bytes go.
let mut fills = std::collections::HashMap::new();
// Which step each is. One list's lock at a time: a submission may
// name a list twice.
let mut steps = Vec::new();
@@ -438,11 +546,16 @@ impl Host {
len,
asked: copy_blocked(written, dst, src, len).is_some(),
},
&Step::Fill(_, src, len, slot) => Does::Fill {
src,
len,
asked: read_blocked(written, src, len),
slot,
Step::Fill(_, src, len, to) => Does::Fill {
src: *src,
len: *len,
asked: read_blocked(written, *src, *len),
to: {
if let Some(to) = to {
fills.insert(does.len(), to.clone());
}
to.is_some()
},
},
Step::Texture(staging) => {
let (at, len) = staging.memory();
@@ -468,7 +581,7 @@ impl Host {
if chosen.is_empty() {
return Ok(None);
}
let writers = {
let mut writers = {
let line = line();
let mut all = writers(&line.line);
all.extend(line.landing.iter().map(|w| Writer {
@@ -478,24 +591,39 @@ impl Host {
all
};
let mut ops: Vec<Op> = Vec::with_capacity(chosen.len());
let mut at = 0u64;
for &i in &chosen {
let (src, len) = match does[i] {
Does::Copy { src, len, .. } | Does::Fill { src, len, .. } => (src, len),
_ => continue,
// The places read (host copy, address, bytes, level): where in the
// buffer between their bytes are.
let mut places = std::collections::HashMap::new();
let mut end = 0u64;
for &(i, level) in &chosen {
let Some(((src, _), (dst, _))) = reads_writes(&does[i]) else {
continue;
};
let (Does::Copy { len, .. } | Does::Fill { len, .. }) = does[i] else {
continue;
};
if len == 0 {
return Err("nothing to read");
}
if at + len as u64 > BETWEEN {
return Err("too much at once");
}
let from = holder(&writers, src, src + len)?;
if !mapped(src, src + len) {
return Err("not all of what it reads is mapped");
}
let place = (Arc::as_ptr(&from) as usize, src, len, level);
let at = match places.get(&place) {
Some(&at) => at,
None => {
if end + len as u64 > BETWEEN {
return Err("too much at once");
}
if !mapped(src, src + len) {
return Err("not all of what it reads is mapped");
}
let at = end;
end = (end + len as u64).next_multiple_of(256);
places.insert(place, at);
at
}
};
let to = match does[i] {
Does::Copy { dst, .. } => {
Does::Copy { .. } => {
let to = holder(&writers, dst, dst + len)?;
if elsewhere(&does, Arc::as_ptr(&to) as usize, dst, dst + len) {
return Err("another host copy of what it writes is read");
@@ -503,35 +631,42 @@ impl Host {
if !mapped(dst, dst + len) {
return Err("not all of what it writes is mapped");
}
// What the steps behind it read of it is in that host
// copy, or nowhere.
writers.push(Writer {
shadow: Some(to.clone()),
from: dst,
to: dst + len,
copy: true,
});
To::Copy(to, dst)
}
Does::Fill { slot: Some((heap, index)), .. } => To::Slot(heap, index),
_ => continue,
_ => match fills.get(&i) {
Some(FillTo::Slot(heap, index)) => To::Slot(*heap, *index),
Some(FillTo::Buffer(buffer)) => To::Buffer(buffer.clone()),
None => continue,
},
};
ops.push(Op {
from: (from, src),
len,
at,
level,
to,
});
at = (at + len as u64).next_multiple_of(256);
}
let Some(own) = self.own_list() else {
return Err("no host list or buffer for it");
};
let mut reads = Vec::new();
let mut writes = Vec::new();
let mut copied = Vec::new();
// First every refresh, then the write: the bytes compared with are
// First every refresh, then the writes: the bytes compared with are
// the title's.
for op in &ops {
op.from.0.refresh(&own.list, op.from.1 as u64, op.len as u64);
reads.push((&op.from.0.buffer, op.from.0.offset(op.from.1 as u64), op.at, op.len as u64));
if let To::Copy(to, dst) = &op.to {
to.refresh(&own.list, *dst as u64, op.len as u64);
writes.push((&to.buffer, to.offset(*dst as u64), op.at, op.len as u64));
}
}
let mut copied = Vec::new();
for op in &ops {
if let To::Copy(to, dst) = &op.to {
to.gpu_writes(&own.list, *dst as u64, op.len as u64);
@@ -539,8 +674,26 @@ impl Host {
}
}
#[cfg(feature = "diagnostics")]
own.list.note_op(|| format!("{} copies of title memory done on the card, {at} bytes (VICTORY_CARD_STEPS)", ops.len()));
record(&own.list.list, &own.between, &reads, &writes);
own.list.note_op(|| format!("{} copies of title memory done on the card, {end} bytes (VICTORY_CARD_STEPS)", ops.len()));
let levels = ops.iter().map(|op| op.level).max().unwrap_or(0);
for level in 0..=levels {
let mut reads = Vec::new();
let mut writes = Vec::new();
for op in ops.iter().filter(|op| op.level == level) {
let len = op.len as u64;
let read = (&op.from.0.buffer, op.from.0.offset(op.from.1 as u64), op.at, len);
// (Each place once.)
if places.remove(&(Arc::as_ptr(&op.from.0) as usize, op.from.1, op.len, level)).is_some() {
reads.push(read);
}
match &op.to {
To::Copy(to, dst) => writes.push((&to.buffer, to.offset(*dst as u64), op.at, len)),
To::Buffer(buffer) => writes.push((buffer, 0, op.at, len)),
To::Slot(..) => {}
}
}
record(level == 0, &own.list.list, &own.between, &reads, &writes);
}
own.list.close();
// SAFETY: a live buffer.
let gpu = unsafe { own.between.GetGPUVirtualAddress() };
@@ -552,6 +705,9 @@ impl Host {
// (A heap that is gone: nothing can read the slot.)
crate::descriptor::constant_slot(*heap, *index, gpu + op.at, op.len as u32);
}
To::Buffer(_) => {
DONE[0].fetch_add(1, Ordering::Relaxed);
}
To::Copy(..) => {
DONE[1].fetch_add(1, Ordering::Relaxed);
}
@@ -561,7 +717,7 @@ impl Host {
}
Ok(Some(Taken {
own,
steps: chosen.iter().map(|&i| steps[i]).collect(),
steps: chosen.iter().map(|&(i, _)| steps[i]).collect(),
copied,
}))
}
@@ -592,7 +748,7 @@ static NOTED: Mutex<Option<Noted>> = Mutex::new(None);
fn noted(op: &Op) {
let (to, dst) = match &op.to {
To::Copy(to, dst) => (to.span(), *dst),
To::Slot(..) => ((0, 0), 0),
To::Slot(..) | To::Buffer(_) => ((0, 0), 0),
};
let mut noted = NOTED.lock().unwrap_or_else(|e| e.into_inner());
let e = noted.get_or_insert_with(Default::default).entry((op.len, op.from.0.span(), to)).or_default();
@@ -646,11 +802,20 @@ mod tests {
}
fn fill(src: usize, len: usize, asked: bool) -> Does {
Does::Fill { src, len, asked, slot: Some((1, 2)) }
Does::Fill { src, len, asked, to: true }
}
fn stuck(src: usize, len: usize) -> Does {
Does::Fill { src, len, asked: false, to: false }
}
/// What is done on the card, as (place, level), in stage 2.
fn planned(does: &[Does]) -> Vec<(usize, u32)> {
plan(does, 2).unwrap()
}
/// Only what is asked for is taken, all of it, and a step that stands
/// in none of their ways changes nothing.
/// in none of their ways stays where it is.
#[test]
fn steps_apart_from_one_another_are_taken() {
let does = [
@@ -660,44 +825,150 @@ mod tests {
copy(3000, 6000, 100, true),
fill(1000, 64, false),
Does::Read { from: 3100, to: 4000, asked: false },
stuck(3100, 5),
];
assert_eq!(plan(&does, 2), Ok(vec![1, 3]));
assert_eq!(planned(&does), [(1, 0), (3, 0)]);
// Two fills of the same bytes.
assert_eq!(plan(&[fill(0, 64, true), fill(32, 64, true)], 1), Ok(vec![0, 1]));
assert_eq!(plan(&[fill(0, 64, true), fill(32, 64, true)], 1), Ok(vec![(0, 0), (1, 0)]));
assert_eq!(plan(&[fill(0, 64, false)], 1), Ok(vec![]));
// Ends that touch are apart.
let does = [
copy(1000, 5000, 100, true),
copy(900, 9000, 100, false),
copy(1100, 9000, 5, false),
copy(4900, 9000, 100, false),
];
assert_eq!(planned(&does), [(0, 0)]);
}
/// Everything that could make the card's order another than the CPU's
/// refuses the lot, wherever in the submission it stands.
/// What depends on a taken step, or it on it, is taken too, on the level
/// the order of the steps asks for.
#[test]
fn steps_in_one_anothers_way_are_refused() {
fn steps_that_depend_on_one_another_are_taken_in_order() {
let taken = copy(1000, 5000, 100, true);
let refused = |other: Does| {
assert!(plan(&[taken, other], 2).is_err(), "{other:?} after");
assert!(plan(&[other, taken], 2).is_err(), "{other:?} before");
// Reads what it writes, behind and ahead of it.
assert_eq!(planned(&[taken, fill(1099, 64, false)]), [(0, 0), (1, 1)]);
assert_eq!(planned(&[fill(1099, 64, false), taken]), [(0, 0), (1, 1)]);
assert_eq!(planned(&[taken, copy(7000, 1050, 10, false)]), [(0, 0), (1, 1)]);
// Writes what it reads, and what it writes.
assert_eq!(planned(&[copy(5099, 9000, 1, false), taken]), [(0, 0), (1, 1)]);
assert_eq!(planned(&[taken, copy(5099, 9000, 1, false)]), [(0, 0), (1, 1)]);
assert_eq!(planned(&[taken, copy(999, 9000, 2, false)]), [(0, 0), (1, 1)]);
// The same list twice.
assert_eq!(planned(&[taken, taken]), [(0, 0), (1, 1)]);
// A chain, with steps apart from it in between, and two fills of one
// copy on one level.
let does = [
copy(8000, 7000, 50, false),
taken,
copy(2000, 1010, 20, false),
fill(90_000, 10, false),
fill(2000, 20, false),
fill(2010, 20, true),
copy(1000, 2005, 5, false),
fill(1000, 100, false),
];
assert_eq!(planned(&does), [(1, 0), (2, 1), (4, 2), (5, 2), (6, 2), (7, 3)]);
// A fill is in nobody's way.
assert_eq!(planned(&[taken, fill(5000, 100, false)]), [(0, 0)]);
// A copy ahead that a taken one only shares its source with.
assert_eq!(planned(&[copy(7000, 5000, 10, false), taken]), [(1, 0)]);
}
/// Whatever the steps, done level by level (in a level every read
/// before every write) they read and leave what they read and leave one
/// after the other, the CPU's steps ahead of all of them.
#[test]
fn levels_do_what_the_order_does() {
let mut seed = 12345u32;
let mut random = move |n: u32| {
seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12345);
(seed >> 16) % n
};
for asked in [false, true] {
// Writes what it reads.
refused(copy(5099, 9000, 1, asked));
// Writes what it writes.
refused(copy(999, 9000, 2, asked));
// Reads what it writes.
refused(copy(7000, 1050, 10, asked));
refused(fill(1099, 64, asked));
refused(Does::Read { from: 900, to: 1001, asked });
let (mut done, mut refused) = (0, 0);
for _ in 0..4000 {
let does: Vec<Does> = (0..2 + random(9))
.map(|_| {
let (at, other, len) = (random(60) as usize, random(60) as usize, 1 + random(8) as usize);
let asked = random(4) == 0;
match random(8) {
0..4 => copy(at, other, len, asked),
4..6 => fill(at, len, asked),
6 => stuck(at, len),
_ => Does::Read { from: at, to: at + len, asked: false },
}
})
.collect();
let Ok(chosen) = plan(&does, 2) else {
refused += 1;
continue;
};
done += 1;
let start: Vec<u32> = (0..80).collect();
// One after the other: what each reads, and what is left.
let mut memory = start.clone();
let mut wanted = Vec::new();
for d in &does {
let (from, to) = match *d {
Does::Read { from, to, .. } => (from, to),
_ => reads_writes(d).unwrap().0,
};
wanted.push(memory[from..to].to_vec());
if let Does::Copy { dst, src, len, .. } = *d {
memory.copy_within(src..src + len, dst);
}
}
// The CPU's, then the card's.
let mut cpu = start.clone();
let taken = |i: usize| chosen.iter().any(|c| c.0 == i);
for (i, d) in does.iter().enumerate().filter(|&(i, _)| !taken(i)) {
let (from, to) = match *d {
Does::Read { from, to, .. } => (from, to),
_ => reads_writes(d).unwrap().0,
};
assert_eq!(cpu[from..to], wanted[i][..], "step {i} of {does:?}");
if let Does::Copy { dst, src, len, .. } = *d {
cpu.copy_within(src..src + len, dst);
}
}
let mut card = cpu.clone();
for level in 0..=chosen.iter().map(|c| c.1).max().unwrap_or(0) {
let of: Vec<usize> = chosen.iter().filter(|c| c.1 == level).map(|c| c.0).collect();
let before = card.clone();
for i in of {
let ((from, to), (dst, _)) = reads_writes(&does[i]).unwrap();
assert_eq!(before[from..to], wanted[i][..], "step {i} of {does:?}: {chosen:?}");
if matches!(does[i], Does::Copy { .. }) {
card[dst..dst + to - from].copy_from_slice(&before[from..to]);
}
}
}
assert_eq!(card, memory, "{does:?}: {chosen:?}");
}
refused(Does::Run);
// A texture that itself waits for flights; a fill with no slot.
refused(Does::Read { from: 1, to: 2, asked: true });
refused(Does::Fill { src: 1, len: 1, asked: true, slot: None });
// Into itself, and the same list twice.
assert!(done > 500 && refused > 100, "{done} {refused}");
}
/// What cannot be done on the card refuses the lot, where it stands in
/// the way.
#[test]
fn steps_in_the_way_are_refused() {
let taken = copy(1000, 5000, 100, true);
assert!(plan(&[taken, Does::Run], 2).is_err());
// A texture that itself waits for flights; a fill that cannot be
// taken but waits.
assert!(plan(&[taken, Does::Read { from: 1, to: 2, asked: true }], 2).is_err());
assert!(plan(&[Does::Fill { src: 1, len: 1, asked: true, to: false }], 2).is_err());
// Reads on the CPU of what it writes: behind it, not ahead of it.
for read in [Does::Read { from: 900, to: 1001, asked: false }, stuck(1050, 3)] {
assert!(plan(&[taken, read], 2).is_err(), "{read:?} behind");
assert_eq!(planned(&[read, taken]), [(1, 0)], "{read:?} ahead");
}
// Also of what is taken along.
assert!(plan(&[taken, copy(3000, 1000, 10, false), stuck(3005, 1)], 2).is_err());
// Into itself, and copies without stage 2.
assert!(plan(&[copy(1000, 1050, 100, true)], 2).is_err());
assert!(plan(&[taken, taken], 2).is_err());
// A fill of what a copy writes, and copies without stage 2.
assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 2).is_err());
assert!(plan(&[taken], 1).is_err());
// Ends that touch are apart.
assert!(plan(&[taken, copy(900, 9000, 100, false), copy(1100, 9000, 5, false), copy(4900, 9000, 100, false)], 2).is_ok());
assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 1).is_err());
}
#[test]
@@ -735,11 +1006,14 @@ mod tests {
let own = host.own_list().unwrap();
// Within `a` (there and back), from `a` to `b`, and a read alone.
record(
true,
&own.list.list,
&own.between,
&[(&a, 33, 0, 100), (&a, 2000, 256, 100), (&a, 5001, 512, 7), (&a, 9, 1024, 4)],
&[(&a, 2000, 0, 100), (&a, 33, 256, 100), (&b, 77, 512, 7)],
);
// A level behind it, of what it wrote.
record(false, &own.list.list, &own.between, &[(&b, 77, 2048, 7)], &[(&b, 1077, 2048, 7)]);
own.list.close();
// A list behind it that uses the buffers in other ways.
let next = host.new_list().unwrap();
@@ -756,6 +1030,7 @@ mod tests {
assert_eq!(a_bytes[2000..2100], was[33..133]);
assert_eq!(a_bytes[33..133], was[2000..2100]);
assert_eq!(b_bytes[77..84], was[5001..5008]);
assert_eq!(b_bytes[1077..1084], was[5001..5008]);
assert_eq!(b_bytes[4096..4196], was[2000..2100]);
// SAFETY: a mapping of 64 KiB.
assert_eq!(unsafe { std::slice::from_raw_parts(out_data, 4) }, &was[9..13]);
@@ -780,7 +1055,10 @@ mod tests {
fn a_copy_behind_a_flight_reads_what_the_flight_wrote() {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
const LEN: usize = 4 << 20;
const WRITE_WATCH: u32 = 0x20_0000;
// Without it (`TEST_UNWATCHED=1`) the title's bytes cannot be put in
// under a flight's writes: the flights that declared them are waited
// for.
let write_watch = if std::env::var_os("TEST_UNWATCHED").is_some() { 0 } else { 0x20_0000 };
let Some(host) = host() else {
return;
};
@@ -789,7 +1067,7 @@ mod tests {
// second, and back.
let (title, start) = {
// SAFETY: memory of our own, never freed.
let base = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE) }.cast::<u8>();
let base = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | write_watch, PAGE_READWRITE) }.cast::<u8>();
assert!(!base.is_null());
// SAFETY: `LEN` bytes just committed.
(unsafe { std::slice::from_raw_parts_mut(base, LEN) }, base as usize)
@@ -831,10 +1109,21 @@ mod tests {
for (i, b) in title[5300..5400].iter_mut().enumerate() {
*b = seed(1300 + i) ^ 0x5c;
}
// Thousands of runs of bytes of its own.
for b in title[1_700_000..1_708_000].iter_mut().step_by(2) {
*b = 1 + round as u8;
}
// Into the second buffer, and within the first.
let b = host.new_list().unwrap();
b.defer_copy((start + HALF + 100) as *mut u8, (start + 4001) as *const u8, 1500);
b.defer_copy((start + 900_001) as *mut u8, (start + 4400) as *const u8, 777);
b.defer_copy((start + HALF + 10_000) as *mut u8, (start + 1_700_000) as *const u8, 8000);
// What depends on them: a copy of the first copy, upload memory
// filled from that, and the first one's bytes copied over.
b.defer_copy((start + 1_500_000) as *mut u8, (start + HALF + 600) as *const u8, 700);
let (staging, staged) = b.upload(host, 4096).unwrap();
b.defer_fill_buffer(&staging, staged, (start + 1_500_100) as *const u8, 500);
b.defer_copy((start + HALF + 300) as *mut u8, (start + 8000) as *const u8, 64);
b.close();
host.execute_own(&b);
// What the first wrote, read by the next submission.
@@ -852,17 +1141,28 @@ mod tests {
})
.collect();
assert!(title[4000..6000] == wanted[..], "what the flight wrote, round {round}");
assert!(title[HALF + 100..HALF + 1600] == wanted[1..1501], "the copy to the other buffer, round {round}");
// (The copy over the first one's bytes came last.)
let mut over = wanted[1..1501].to_vec();
over[200..264].fill(0);
assert!(title[HALF + 100..HALF + 1600] == over[..], "the copy to the other buffer, round {round}");
assert!(title[1_500_000..1_500_700] == wanted[501..1201], "the copy behind a copy, round {round}");
// SAFETY: the mapping, which the flight wrote and has landed.
let staged = unsafe { std::slice::from_raw_parts(staged, 500) };
assert!(staged == &wanted[601..1101], "the fill behind it, round {round}");
assert!(title[900_001..900_778] == wanted[400..1177], "the copy within the buffer, round {round}");
assert!(title[1_200_000..1_201_500] == wanted[1..1501], "the copy of the copy, round {round}");
assert!(title[1_200_000..1_201_500] == over[..], "the copy of the copy, round {round}");
assert!(title[HALF..HALF + 100].iter().all(|&x| x == 0));
assert!(title[HALF + 1600..].iter().all(|&x| x == 0));
assert!(title[HALF + 1600..HALF + 10_000].iter().all(|&x| x == 0));
assert!(title[HALF + 18_000..].iter().all(|&x| x == 0));
let runs = &title[HALF + 10_000..HALF + 18_000];
assert!(runs.chunks(2).all(|b| b == [1 + round as u8, 0]), "the runs, round {round}");
a.keep(&upload);
lists.extend([a, b, c]);
}
assert_eq!(host.log_messages(), None);
let done = DONE[1].load(Ordering::Relaxed) - before;
eprintln!("{done} of 24 copies were done on the card, {} submissions waited", DONE[3].load(Ordering::Relaxed));
assert!(done >= 12, "only {done} copies were done on the card");
eprintln!("{done} of 48 copies were done on the card, {} submissions waited", DONE[3].load(Ordering::Relaxed));
eprintln!("settles for title memory under shader writes: {}", LATE_STATS[WHY_STALE].load(Ordering::Relaxed));
assert!(done >= 20, "only {done} copies were done on the card");
}
}
+48 -26
View File
@@ -269,9 +269,12 @@ struct Views {
views: BTreeMap<usize, (usize, usize, u64)>,
/// Sections by handle: bytes, and whether made committed.
sections: Vec<(usize, u64, bool)>,
/// Our own view of a whole section, by its handle (0: the host gave
/// none), made when first asked for ([`beside`]) and kept.
whole: Vec<(usize, usize)>,
}
static VIEWS: Mutex<Views> = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new() });
static VIEWS: Mutex<Views> = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new(), whole: Vec::new() });
fn views() -> std::sync::MutexGuard<'static, Views> {
VIEWS.lock().unwrap_or_else(|e| e.into_inner())
@@ -280,41 +283,30 @@ fn views() -> std::sync::MutexGuard<'static, Views> {
/// The runtime made a section of `bytes` for physical pages; `committed`
/// if with `SEC_COMMIT` (only such a section can be opened as a heap).
pub fn title_memory_section(section: usize, bytes: u64, committed: bool) {
title_memory_section_gone(section);
let mut v = views();
v.sections.retain(|s| s.0 != section);
// A handle's number given out again: the view was of the section that
// had it before (it stays mapped: someone may be writing through it).
v.whole.retain(|w| w.0 != section);
v.sections.push((section, bytes, committed));
}
/// Views of ours of whole sections, by the section's handle: where.
static WINDOWS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new());
/// The runtime lets go of a section, and of its handle: no view of it is
/// mapped any more.
/// The runtime lets go of a section, and of its handle: no view the title
/// sees is of it any more, and [`beside`]'s view goes.
pub fn title_memory_section_gone(section: usize) {
let window = WINDOWS.lock().unwrap_or_else(|e| e.into_inner()).remove(&section);
if let Some(base) = window.filter(|&base| base != 0) {
// SAFETY: a view of ours. Who writes through it holds off the
// runtime's unmapping of the view it found the section by
// (`crate::watch::land_through`), which came before this.
let whole = {
let mut v = views();
let at = v.whole.iter().position(|w| w.0 == section);
at.map(|i| v.whole.swap_remove(i).1)
};
if let Some(base) = whole.filter(|&base| base != 0) {
// SAFETY: a view of ours. Who writes through it found the section
// in a view the title saw and holds off its unmapping
// (`crate::watch::title_memory_reading`), which came before this.
unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: base as *mut c_void }) };
}
}
/// Where a view of ours of all of `section` is, made when first asked for;
/// `None` if the host gives none. The caller holds off remapping
/// (`crate::title_memory_reading`) and found the section in a view the
/// runtime told us of, so the section lives.
pub(crate) fn window(section: usize) -> Option<usize> {
let bytes = views().sections.iter().find(|s| s.0 == section)?.1;
let mut windows = WINDOWS.lock().unwrap_or_else(|e| e.into_inner());
let base = *windows.entry(section).or_insert_with(|| {
// SAFETY: a live section of that many bytes.
unsafe { mem::MapViewOfFile(section as *mut c_void, mem::FILE_MAP_WRITE, 0, 0, bytes as usize) }.Value as usize
});
(base != 0).then_some(base)
}
/// The runtime mapped `[at, at + len)` as a view of `section` from
/// `offset` on. Call after [`crate::title_memory_remapped`] of the range.
pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) {
@@ -373,6 +365,36 @@ pub(crate) fn cover(at: usize, len: usize) -> Cover {
cover_in(&views().views, at, len)
}
/// Another address of the title memory `[at, at + len)`, if it is a view of
/// the title's pages, all of it one run of a section: in a view of ours of
/// the whole section, which is never guarded (`crate::watch`) nor changed.
///
/// The section's pages are reserved and the runtime commits each before it
/// shows it, which holds for every view of the section. The caller holds
/// `crate::watch::title_memory_reading`: until it lets go the title sees
/// the same pages at `at`.
pub(crate) fn beside(at: usize, len: usize) -> Option<usize> {
let mut v = views();
let Cover::Run(section, offset) = cover_in(&v.views, at, len) else {
return None;
};
let base = match v.whole.iter().find(|w| w.0 == section) {
Some(w) => w.1,
None => {
let &(_, bytes, _) = v.sections.iter().find(|s| s.0 == section)?;
// SAFETY: the whole of a section the runtime made; a view the
// title sees is of it, so its handle is open.
let base = unsafe { mem::MapViewOfFile(section as _, mem::FILE_MAP_WRITE, 0, 0, bytes as usize) }.Value as usize;
if base == 0 {
tracing::warn!(error = %std::io::Error::last_os_error(), "no view of the title's pages beside its own");
}
v.whole.push((section, base));
base
}
};
(base != 0).then(|| base + offset as usize)
}
/// Whether `[at, at + len)` is private memory, all committed and
/// read-write: what [`From::Part`] takes. One question to Windows (it
/// walks the page tables to the end of the pages that share the first
+556
View File
@@ -0,0 +1,556 @@
//! What shaders wrote goes into title memory on a few threads
//! (`VICTORY_LAND`, on by default; `=0` merges piece by piece on the thread
//! that lands flights, as before).
//!
//! The relay's thread (`crate::host::relay`) was 58-60 ms of a 104 ms frame
//! landing (run record-1): some 1,500 pieces of 64 KiB, 98 MB, fetched from
//! copies in the card's memory, and each of them searched from both ends,
//! cleared room for, read from title memory, copied, merged and compared
//! again while it was put, one after the other; a lock and a protection
//! call to open the guard of each, and the kernel's fault on the first
//! write to each 4 KiB page of memory just made writable again.
//!
//! Here a piece is merged in one pass ([`crate::safecopy::merge`]): what
//! the card holds is compared with what it held 32 bytes at a time, title
//! memory is read only where they differ, just before the dwords that
//! change are stored. The pieces of a landing are cut into jobs for a few
//! threads kept for it ([`Pool`]).
//!
//! What stays in order: pieces in the same 64 KiB of title memory are in
//! one job, in the order they were given (two copies may hold the same
//! title memory); a landing's copies in the card's memory come before its
//! other copies; a landing is done, whole, before the title is told
//! anything and before the next one starts (`Host::relay_land`).
//!
//! With `VICTORY_LAND_BESIDE` (on by default) title memory that is a view of
//! the title's physical pages is written through a view of our own of the
//! same pages ([`crate::inplace::beside`]). The guards (`crate::watch`) are
//! read-only title views: they stay as they are, no protection changes, and
//! [`crate::watch::landed_beside`] notes the blocks written afterwards, so
//! that the next refresh takes them as before.
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Condvar, Mutex, MutexGuard, OnceLock};
/// The unit pieces are cut in (of title memory), and the guards' blocks.
pub(crate) const BLOCK: usize = 64 << 10;
/// The unit title memory is there or not in.
const PAGE: usize = 4096;
/// About this many bytes to a job.
const JOB: usize = 256 << 10;
/// See the file.
pub(crate) fn on() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| {
std::env::var_os("VICTORY_LAND").is_none_or(|v| v != "0") && crate::safecopy::on() && crate::shadow::exact_back()
})
}
/// How many threads land, the relay's own counted (`VICTORY_LAND_THREADS`).
fn threads() -> usize {
static THREADS: OnceLock<usize> = OnceLock::new();
*THREADS.get_or_init(|| {
let asked = std::env::var("VICTORY_LAND_THREADS").ok().and_then(|v| v.trim().parse().ok());
asked.unwrap_or_else(|| std::thread::available_parallelism().map_or(2, |n| n.get() / 4).clamp(1, 4)).clamp(1, 16)
})
}
/// Whether views of the title's pages are written through one of ours.
fn beside_on() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LAND_BESIDE").is_none_or(|v| v != "0"))
}
/// Whether pieces an earlier fetch holds as they are now are left out
/// ([`Had`]; `VICTORY_LAND_SKIP=1`, off by default: counted either way).
pub(crate) fn skip_on() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LAND_SKIP").is_some_and(|v| v == "1"))
}
/// Since the last frame-rate line; microseconds first.
pub(crate) mod stat {
/// Which pieces to fetch; their list recorded and sent.
pub(crate) const GATHER: usize = 0;
/// Looking for what shaders wrote to copies in the PC's memory, the part
/// done while the fetch was on its way.
pub(crate) const SCAN_BESIDE: usize = 1;
/// The same, with nothing else to wait for.
pub(crate) const SCAN: usize = 2;
/// Merging what was fetched: until the last job is done, and the jobs'
/// time on all threads.
pub(crate) const CARD: usize = 3;
pub(crate) const CARD_ALL: usize = 4;
/// Merging what the scan found.
pub(crate) const BACK: usize = 5;
pub(crate) const BACK_ALL: usize = 6;
/// In the jobs: waiting for the lock against the title's bytes going in.
pub(crate) const LOCK: usize = 7;
/// In the jobs: guards opened before a write, or noted after one.
pub(crate) const NOTES: usize = 8;
/// The flights' ranges done with; reading back, resets; what the title
/// is told; the rest (the line's account).
pub(crate) const DONE: usize = 9;
pub(crate) const READ_BACKS: usize = 10;
pub(crate) const TOLD: usize = 11;
pub(crate) const REST: usize = 12;
/// Counts: pieces merged, those with a new byte, their 4 KiB pages,
/// those with a new byte, blocks of 32 bytes with a new byte, dwords put.
pub(crate) const PIECES: usize = 13;
pub(crate) const NEW_PIECES: usize = 14;
pub(crate) const PAGES: usize = 15;
pub(crate) const NEW_PAGES: usize = 16;
pub(crate) const NEW_BLOCKS: usize = 17;
pub(crate) const DWORDS: usize = 18;
/// Pieces put through a view of ours, through the title's; pages where
/// title memory was not there.
pub(crate) const BESIDE: usize = 19;
pub(crate) const DIRECT: usize = 20;
pub(crate) const MISSING: usize = 21;
/// Bytes asked for twice in a landing (fetched once); pieces and bytes
/// an earlier fetch held already.
pub(crate) const TWICE: usize = 22;
pub(crate) const HAD: usize = 23;
pub(crate) const HAD_BYTES: usize = 24;
/// Jobs.
pub(crate) const JOBS: usize = 25;
pub(crate) const COUNT: usize = 26;
}
static STATS: [AtomicU64; stat::COUNT] = [const { AtomicU64::new(0) }; stat::COUNT];
pub(crate) fn count(which: usize, n: u64) {
STATS[which].fetch_add(n, Ordering::Relaxed);
}
/// Adds the microseconds since `from` to `which`; now.
pub(crate) fn spent(which: usize, from: std::time::Instant) -> std::time::Instant {
let now = std::time::Instant::now();
count(which, (now - from).as_micros() as u64);
now
}
/// For the frame-rate line: where landing went, per frame.
pub(crate) fn log(frames: f64) {
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;
}
let ms = |i: usize| s[i] / 1000.0;
let mb = |v: f64| v / (1 << 20) as f64;
tracing::info!(
"landing per frame (VICTORY_LAND={}, {} threads): which pieces to fetch {:.2} ms, then the fetches (the relay's line); \
looking through copies in the PC's memory {:.2} ms beside them and {:.2} ms more; merging what was fetched {:.2} ms \
({:.2} ms on all threads, {:.0} jobs), merging the others {:.2} ms ({:.2} on all threads); of the threads' time \
{:.2} ms waiting for the title's bytes going in, {:.2} ms opening or noting guards; then ranges done with {:.2} ms, \
read-backs and lists {:.2}, the title told {:.2}, the rest {:.2}",
u8::from(on()),
threads(),
ms(stat::GATHER),
ms(stat::SCAN_BESIDE),
ms(stat::SCAN),
ms(stat::CARD),
ms(stat::CARD_ALL),
s[stat::JOBS],
ms(stat::BACK),
ms(stat::BACK_ALL),
ms(stat::LOCK),
ms(stat::NOTES),
ms(stat::DONE),
ms(stat::READ_BACKS),
ms(stat::TOLD),
ms(stat::REST),
);
tracing::info!(
"landed per frame: {:.0} pieces, {:.0} with a new byte; of their {:.0} pages of 4 KiB {:.0} with a new byte ({:.1} MB), \
{:.1} MB in blocks of 32 bytes with one, {:.2} MB put as dwords; {:.0} pieces through a view of ours \
(VICTORY_LAND_BESIDE={}), {:.0} through the title's; {:.0} pages not there; asked for twice in a landing {:.1} MB; \
held already by an earlier fetch {:.0} pieces {:.1} MB (VICTORY_LAND_SKIP={})",
s[stat::PIECES],
s[stat::NEW_PIECES],
s[stat::PAGES],
s[stat::NEW_PAGES],
mb(s[stat::NEW_PAGES] * PAGE as f64),
mb(s[stat::NEW_BLOCKS] * 32.0),
mb(s[stat::DWORDS] * 4.0),
s[stat::BESIDE],
u8::from(beside_on()),
s[stat::DIRECT],
s[stat::MISSING],
mb(s[stat::TWICE]),
s[stat::HAD],
mb(s[stat::HAD_BYTES]),
u8::from(skip_on()),
);
}
/// Threads kept for landing, and the work they are at.
struct Pool {
state: Mutex<State>,
more: Condvar,
idle: Condvar,
/// One batch at a time.
turn: Mutex<()>,
threads: usize,
}
struct State {
/// What to do with each number below `count`.
work: Option<Work>,
next: usize,
count: usize,
/// Helpers inside a call.
running: usize,
panicked: bool,
}
#[derive(Clone, Copy)]
struct Work(*const (dyn Fn(usize) + Sync));
// SAFETY: the closure may be called from any thread (`Sync`), and
// `Pool::each` keeps it alive until no helper is inside a call.
unsafe impl Send for Work {}
impl Pool {
fn state(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
fn new(threads: usize) -> &'static Pool {
let pool: &'static Pool = Box::leak(Box::new(Pool {
state: Mutex::new(State { work: None, next: 0, count: 0, running: 0, panicked: false }),
more: Condvar::new(),
idle: Condvar::new(),
turn: Mutex::new(()),
threads,
}));
for i in 1..threads {
// (A helper that is not there is only missed.)
let _ = std::thread::Builder::new().name(format!("victory-land-{i}")).spawn(move || pool.help());
}
pool
}
fn help(&self) {
let mut state = self.state();
loop {
let Some((work, i)) = take(&mut state) else {
state = self.more.wait(state).unwrap_or_else(|e| e.into_inner());
continue;
};
state.running += 1;
drop(state);
// SAFETY: counted in `running`, so `each` has not returned.
let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { (*work.0)(i) }));
state = self.state();
state.running -= 1;
state.panicked |= ran.is_err();
if state.running == 0 {
self.idle.notify_all();
}
}
}
/// Calls `f` with every number below `count`, on the pool's threads and
/// this one, and returns when every call has.
fn each(&self, count: usize, f: &(dyn Fn(usize) + Sync)) {
if count < 2 || self.threads < 2 {
(0..count).for_each(f);
return;
}
let _turn = self.turn.lock().unwrap_or_else(|e| e.into_inner());
// SAFETY: the lifetime is left out only until this call returns, and
// it does not before no helper is inside `f` and none can enter.
let work = Work(unsafe { std::mem::transmute::<*const (dyn Fn(usize) + Sync + '_), *const (dyn Fn(usize) + Sync + 'static)>(f) });
let mut state = self.state();
(state.work, state.next, state.count, state.panicked) = (Some(work), 0, count, false);
drop(state);
if count > self.threads {
self.more.notify_all();
} else {
(1..count).for_each(|_| self.more.notify_one());
}
let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
loop {
let Some((_, i)) = take(&mut self.state()) else { break };
f(i);
}
}));
let mut state = self.state();
// (After a panic here: nothing more is begun.)
state.work = None;
while state.running > 0 {
state = self.idle.wait(state).unwrap_or_else(|e| e.into_inner());
}
let panicked = state.panicked;
drop(state);
if let Err(panic) = ran {
std::panic::resume_unwind(panic);
}
assert!(!panicked, "a job of landing panicked");
}
}
/// The next number of the batch, if there is one.
fn take(state: &mut State) -> Option<(Work, usize)> {
let work = state.work?;
if state.next >= state.count {
return None;
}
state.next += 1;
Some((work, state.next - 1))
}
/// [`Pool::each`] on the threads kept for landing.
pub(crate) fn each(count: usize, f: &(dyn Fn(usize) + Sync)) {
static POOL: OnceLock<&'static Pool> = OnceLock::new();
POOL.get_or_init(|| Pool::new(threads())).each(count, f);
}
/// A piece to land: the copy's number, the title address, its bytes.
pub(crate) type Piece = (u64, usize, usize);
/// `pieces` in the order they are landed: by the 64 KiB block of title
/// memory they lie in, those in one block in the order given (each is
/// within one block). Where one copy alone has pieces in a block, those
/// that overlap or touch are one piece: a landing's flights declare parts
/// of the same memory, and what overlapped came down and was merged twice.
/// Each with the number of the piece given that it begins with.
pub(crate) fn ordered(pieces: &[Piece]) -> Vec<(usize, usize, usize)> {
let mut order: Vec<usize> = (0..pieces.len()).collect();
order.sort_by_key(|&i| pieces[i].1 / BLOCK);
let mut out: Vec<(usize, usize, usize)> = Vec::with_capacity(order.len());
for group in order.chunk_by(|&a, &b| pieces[a].1 / BLOCK == pieces[b].1 / BLOCK) {
let alone = group.len() > 1 && group.iter().all(|&i| pieces[i].0 == pieces[group[0]].0);
if !alone {
out.extend(group.iter().map(|&i| (i, pieces[i].1, pieces[i].2)));
continue;
}
let mut sorted = group.to_vec();
sorted.sort_by_key(|&i| pieces[i].1);
let begun = out.len();
for i in sorted {
let (_, at, len) = pieces[i];
match out[begun..].last_mut() {
Some(last) if at <= last.1 + last.2 => {
let end = (last.1 + last.2).max(at + len);
count(stat::TWICE, (last.2 + len - (end - last.1)) as u64);
last.2 = end - last.1;
}
_ => out.push((i, at, len)),
}
}
}
out
}
/// Pieces (title address, bytes; in [`ordered`]'s order) as jobs: runs of
/// about [`JOB`] bytes that end where a block ends.
pub(crate) fn jobs(pieces: &[(usize, usize)]) -> Vec<std::ops::Range<usize>> {
let mut out: Vec<std::ops::Range<usize>> = Vec::new();
let (mut from, mut bytes) = (0, 0);
for (i, &(at, len)) in pieces.iter().enumerate() {
let new_block = i == 0 || pieces[i - 1].0 / BLOCK != at / BLOCK;
if bytes >= JOB && new_block {
out.push(from..i);
(from, bytes) = (i, 0);
}
bytes += len;
}
if from < pieces.len() {
out.push(from..pieces.len());
}
out
}
/// What earlier fetches brought, for as long as a flight they ran behind
/// has not landed: per fetch, the value the host's fence had been given
/// behind the last flight sent before it, and by copy (its number) and
/// piece the offsets it brought.
///
/// A fetch on the drawing queue runs behind everything sent before it, so
/// it brings what those flights' shaders wrote too, and the merge of it put
/// that into title memory. Their own landings flag the same pieces and
/// fetched them again, to find every byte merged. A piece that a fetch held
/// whole, behind the flight that flags it, has nothing more of that flight.
/// (Bytes left out of that merge, the title's that went up behind the
/// fetch, went up behind that flight too, and stand over what it wrote.)
#[derive(Default)]
pub(crate) struct Had(Vec<(u64, std::collections::HashMap<(u64, usize), (usize, usize)>)>);
impl Had {
/// Flights from the one behind which `fence` is signalled on are landed
/// next: what is of no use to them is dropped.
pub(crate) fn landing(&mut self, fence: u64) {
self.0.retain(|had| had.0 >= fence);
}
/// A fetch that ran behind every flight up to `fence` brought (copy,
/// title address, bytes) `pieces`. They are merged before the next ask.
pub(crate) fn fetched(&mut self, fence: u64, pieces: impl Iterator<Item = Piece>) {
let mut all = std::collections::HashMap::new();
for (copy, at, len) in pieces {
// (Two parts of a block that do not touch: the longer one.)
let had = all.entry((copy, at / BLOCK)).or_insert((at, at + len));
if len > had.1 - had.0 {
*had = (at, at + len);
}
}
self.0.push((fence, all));
}
/// Whether a fetch behind the flight of `fence` brought all of the
/// piece.
pub(crate) fn holds(&self, fence: u64, (copy, at, len): Piece) -> bool {
self.0.iter().any(|(behind, all)| {
*behind >= fence && all.get(&(copy, at / BLOCK)).is_some_and(|had| had.0 <= at && at + len <= had.1)
})
}
}
/// What a job wrote beside the guards, to be noted ([`Notes::flush`]).
#[derive(Default)]
pub(crate) struct Notes {
/// Pages of 4 KiB, by number.
pages: Vec<usize>,
/// Per piece, from the first such page to the last: address, bytes.
spans: Vec<(usize, usize)>,
}
impl Notes {
/// At the end of a job: what it wrote beside the guards is noted.
pub(crate) fn flush(&mut self) {
if self.pages.is_empty() {
return;
}
let noting = std::time::Instant::now();
crate::watch::landed_beside(&self.pages, &self.spans);
self.pages.clear();
self.spans.clear();
spent(stat::NOTES, noting);
}
}
/// Lands one piece: `parts` (offsets from and to) of the bytes at `now`,
/// which the card wrote, go into title memory from `title` on and into
/// `held` ([`crate::safecopy::merge`] says how, and what `take` is). The
/// piece lies in one 64 KiB block of title memory. Returns the bytes put.
///
/// # Safety
/// `now` and `held` are ours from 0 to the last part's end, and nothing but
/// the card writes `now` there, nothing but this call `held`.
pub(crate) unsafe fn piece(
title: usize,
now: *const u8,
held: *mut u8,
parts: &[(usize, usize)],
take: bool,
notes: &mut Notes,
) -> u64 {
// SAFETY: the caller's.
unsafe { piece_at(title, now, held, parts, take, notes, beside_on()) }
}
/// [`piece`], and whether a view of ours is looked for.
///
/// # Safety
/// [`piece`]'s.
unsafe fn piece_at(
title: usize,
now: *const u8,
held: *mut u8,
parts: &[(usize, usize)],
take: bool,
notes: &mut Notes,
beside: bool,
) -> u64 {
let Some(end) = parts.last().map(|p| p.1) else {
return 0;
};
// From here until the piece is put the runtime changes no mapping: our
// view's address stays where the title sees `title`. Not waited for: if
// a change is under way, the title's own address does.
let reading = beside.then(crate::watch::title_memory_reading_now).flatten();
let beside = reading.as_ref().and_then(|_| crate::inplace::beside(title, end));
count(stat::PIECES, 1);
count(if beside.is_some() { stat::BESIDE } else { stat::DIRECT }, 1);
// The pages that differ, before any is written: none, and the guard
// stays; else it is opened once for the piece.
let mut differing = [true; BLOCK / PAGE + 1];
let base = title / PAGE;
if beside.is_none() {
drop(reading);
differing.fill(false);
for_pages(title, parts, |from, n| {
// SAFETY: the caller's.
if unsafe { crate::safecopy::differ(now.add(from), held.add(from), n) } {
differing[(title + from) / PAGE - base] = true;
}
});
let Some(first) = differing.iter().position(|&d| d) else {
for_pages(title, parts, |_, _| count(stat::PAGES, 1));
return 0;
};
let last = differing.iter().rposition(|&d| d).unwrap_or(first);
let (from, to) = (((base + first) * PAGE).max(title), ((base + last + 1) * PAGE).min(title + end));
let opening = std::time::Instant::now();
crate::watch::landing(from, to - from);
spent(stat::NOTES, opening);
}
let into = beside.unwrap_or(title);
let (mut pages, mut new_pages, mut blocks, mut dwords, mut missing) = (0, 0u64, 0, 0, 0);
let mut span: Option<(usize, usize)> = None;
for_pages(title, parts, |from, n| {
pages += 1;
if !differing[(title + from) / PAGE - base] {
return;
}
// SAFETY: the caller's; title memory, by an address that shows it
// (`beside`) or the title's own.
let done = unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) };
blocks += done.new;
dwords += done.dwords;
missing += u64::from(!done.there);
if done.new > 0 {
new_pages += 1;
if beside.is_some() {
let page = (title + from) / PAGE;
// (Two parts in one page.)
if notes.pages.last() != Some(&page) {
notes.pages.push(page);
}
let s = span.get_or_insert((title + from, title + from + n));
s.1 = title + from + n;
}
}
});
if let Some((from, to)) = span {
notes.spans.push((from, to - from));
}
count(stat::NEW_PIECES, u64::from(new_pages > 0));
count(stat::PAGES, pages);
count(stat::NEW_PAGES, new_pages);
count(stat::NEW_BLOCKS, blocks);
count(stat::DWORDS, dwords);
count(stat::MISSING, missing);
crate::shadow::PUT[0].fetch_add(u64::from(dwords > 0), Ordering::Relaxed);
crate::shadow::PUT[2].fetch_add(dwords * 4, Ordering::Relaxed);
dwords * 4
}
/// `parts` of a piece that begins at `title`, cut where 4 KiB pages of title
/// memory end: offset and bytes.
fn for_pages(title: usize, parts: &[(usize, usize)], mut f: impl FnMut(usize, usize)) {
for &(from, to) in parts {
let mut at = from;
while at < to {
let n = (PAGE - (title + at) % PAGE).min(to - at);
f(at, n);
at += n;
}
}
}
#[cfg(test)]
mod tests;
+433
View File
@@ -0,0 +1,433 @@
use super::*;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize};
use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, PAGE_READWRITE};
struct Random(u64);
impl Random {
fn next(&mut self) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 >> 8) as usize
}
}
/// View memory as the runtime makes the title's: a view of a section, noted
/// as it notes it. Kept: the journal of what was written (`crate::watch`)
/// knows its addresses, which must not become another test's fresh memory.
struct Title {
at: usize,
len: usize,
}
impl Title {
fn new(len: usize) -> Title {
// SAFETY: a pagefile section of our own and a view of it.
unsafe {
let section =
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
assert!(!section.is_null());
let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
assert_ne!(at, 0);
crate::inplace::title_memory_section(section as usize, len as u64, true);
crate::title_memory_remapped(at, len);
crate::inplace::title_memory_view(at, len, section as usize, 0);
Title { at, len }
}
}
fn bytes(&self) -> &[u8] {
// SAFETY: the view.
unsafe { std::slice::from_raw_parts(self.at as *const u8, self.len) }
}
}
/// Every number once, whatever the count and the threads, batch after batch
/// and from several callers.
#[test]
fn the_pool_calls_every_number_once() {
for threads in [1usize, 2, 4, 7] {
let pool = Pool::new(threads);
std::thread::scope(|s| {
for _ in 0..3 {
s.spawn(|| {
for round in 0..300usize {
let count = round * 7 % 50;
let calls: Vec<AtomicUsize> = (0..count).map(|_| AtomicUsize::new(0)).collect();
pool.each(count, &|i| {
calls[i].fetch_add(1, Ordering::Relaxed);
});
assert!(calls.iter().all(|c| c.load(Ordering::Relaxed) == 1));
}
});
}
});
}
}
/// A job that panics is told to the caller, and the pool goes on.
#[test]
fn a_panicking_job_reaches_the_caller() {
let pool = Pool::new(3);
for bad in 0..8usize {
let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
pool.each(8, &|i| assert_ne!(i, bad, "(expected)"));
}));
assert!(ran.is_err());
let n = AtomicUsize::new(0);
pool.each(20, &|i| {
n.fetch_add(i, Ordering::Relaxed);
});
assert_eq!(n.into_inner(), 190);
}
}
/// The order pieces are landed in holds every byte of every piece, under its
/// copy, and no other; blocks come in order, pieces of several copies in one
/// block stay in the order given, and jobs never cut a block.
#[test]
fn ordered_pieces_hold_the_same_bytes() {
let mut random = Random(99);
for _ in 0..400 {
let count = random.next() % 40;
let pieces: Vec<Piece> = (0..count)
.map(|_| {
let block = random.next() % 12 * BLOCK;
let from = random.next() % BLOCK / 4 * 4;
let to = (from + 4 + random.next() % BLOCK / 4 * 4).min(BLOCK);
(random.next() as u64 % 3, block + from, to - from)
})
.collect();
let out = ordered(&pieces);
let bytes = |copy: u64, at: usize, all: &[Piece]| all.iter().any(|p| p.0 == copy && p.1 <= at && at < p.1 + p.2);
let landed: Vec<Piece> = out.iter().map(|&(i, at, len)| (pieces[i].0, at, len)).collect();
for copy in 0..3 {
for at in (0..12 * BLOCK).step_by(1024 * 4) {
assert_eq!(bytes(copy, at, &pieces), bytes(copy, at, &landed), "{pieces:?}");
}
}
assert!(out.iter().all(|&(_, at, len)| len > 0 && at / BLOCK == (at + len - 1) / BLOCK));
assert!(out.windows(2).all(|w| w[0].1 / BLOCK <= w[1].1 / BLOCK));
for block in 0..12 {
let given: Vec<Piece> = pieces.iter().copied().filter(|p| p.1 / BLOCK == block).collect();
let here: Vec<Piece> = landed.iter().copied().filter(|p| p.1 / BLOCK == block).collect();
if given.iter().any(|p| p.0 != given[0].0) {
assert_eq!(here, given);
} else {
assert!(here.windows(2).all(|w| w[0].1 + w[0].2 < w[1].1), "apart, in order");
}
}
let cut: Vec<(usize, usize)> = out.iter().map(|&(_, at, len)| (at, len)).collect();
let jobs = jobs(&cut);
assert_eq!(jobs.iter().cloned().flatten().collect::<Vec<_>>(), (0..cut.len()).collect::<Vec<_>>());
for w in jobs.windows(2) {
assert_ne!(cut[w[0].end - 1].0 / BLOCK, cut[w[1].start].0 / BLOCK);
}
}
}
/// A piece is left out only if a fetch behind its own flight, or behind a
/// later one, brought all of it, and is forgotten when that flight is done.
#[test]
fn only_what_a_fetch_behind_the_flight_brought_is_left_out() {
let mut had = Had::default();
had.fetched(7, [(1, BLOCK, BLOCK), (2, 0x100, 0x200)].into_iter());
assert!(had.holds(6, (1, BLOCK, BLOCK)) && had.holds(7, (1, BLOCK + 64, 128)));
assert!(!had.holds(8, (1, BLOCK, BLOCK)), "the fetch ran ahead of flight 8");
assert!(!had.holds(7, (3, BLOCK, BLOCK)) && !had.holds(7, (1, 0, 64)));
assert!(had.holds(7, (2, 0x100, 0x200)) && !had.holds(7, (2, 0x100, 0x204)) && !had.holds(7, (2, 0xfc, 8)));
had.landing(7);
assert!(had.holds(7, (1, BLOCK, BLOCK)));
had.landing(8);
assert!(had.0.is_empty());
}
/// A piece landed through either address holds what the merge of one thread
/// and one pass ([`crate::safecopy::merge`]) is to leave, with parts left
/// out, wherever it begins and ends.
#[test]
fn a_piece_lands_what_the_card_wrote_in_its_parts() {
assert!(crate::safecopy::on());
let title = Title::new(2 * BLOCK);
let mut random = Random(5);
for round in 0..300usize {
let from = (random.next() % 5000) & !3;
let len = (random.next() % BLOCK).min(BLOCK - from).max(1);
let base: Vec<u8> = (0..len).map(|_| random.next() as u8).collect();
let (mut now, mut held) = (base.clone(), base.clone());
for _ in 0..random.next() % 60 {
let at = random.next() % len;
let n = (random.next() % 300).min(len - at);
for b in &mut now[at..at + n] {
*b = random.next() as u8;
}
}
let mut there = base.clone();
for _ in 0..random.next() % 60 {
there[random.next() % len] ^= 0x11;
}
// Left out: some ranges, anywhere.
let mut parts = vec![(0, len)];
for _ in 0..round % 4 {
let a = random.next() % len;
let b = (a + random.next() % 200).min(len);
parts = parts
.into_iter()
.flat_map(|(x, y)| [(x, y.min(a)), (x.max(b), y)])
.filter(|(x, y)| x < y)
.collect();
}
// SAFETY: inside the view; `kernel_will_write`'s rule for our own
// writes: the guard goes first.
unsafe {
crate::watch::writing(title.at, 2 * BLOCK);
std::ptr::copy_nonoverlapping(there.as_ptr(), (title.at + from) as *mut u8, len);
}
// Guarded, as after a refresh, in two rounds of three.
if round % 3 != 0 {
assert!(crate::watch::writes(title.at, title.at + 2 * BLOCK, true).is_some());
assert_eq!(crate::watch::writes(title.at, title.at + 2 * BLOCK, true).map(|w| w.1.len() > 2), Some(false));
}
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) };
notes.flush();
let mut expect_held = base.clone();
let mut expect = there.clone();
for &(a, b) in &parts {
for i in a..b {
if now[i] != base[i] {
expect[i] = now[i];
expect_held[i] = now[i];
}
}
}
assert!(held == expect_held, "round {round}");
assert!(title.bytes()[from..from + len] == expect[..], "round {round}");
// Told: a refresh from now on takes the block again.
let (_, written) = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view");
let told = written.iter().any(|&(page, at)| page == title.at / BLOCK && at > asked);
assert!(told || put == 0, "round {round}: {put} bytes, {written:?} after {asked}");
}
}
/// Landings on several threads beside title threads that write the same
/// blocks (other dwords) and a thread that refreshes a copy, guarding what
/// it takes: no write of the title's is lost or undone, all the card wrote
/// arrives, and once everything stands still the next refresh takes the
/// last of it (no note is lost).
#[test]
fn landings_beside_the_title_and_its_refreshes_lose_nothing() {
assert!(crate::safecopy::on());
const BLOCKS: usize = 24;
const LEN: usize = BLOCKS * BLOCK;
let title = Title::new(LEN);
let at = title.at;
// SAFETY: committed, aligned, touched as atomics or by the landing's
// stores of whole dwords.
let dword = |i: usize| unsafe { &*((at + i * 4) as *const AtomicU32) };
let stop = AtomicBool::new(false);
// The copy: its bytes, and per block the asking that last took it.
let copy: Mutex<(Vec<u8>, Vec<u64>)> = Mutex::new((vec![0; LEN], vec![0; BLOCKS]));
let refresh = || {
let mut copy = copy.lock().unwrap_or_else(|e| e.into_inner());
let (now, written) = crate::watch::writes(at, at + LEN, true).expect("a view");
let (bytes, taken) = &mut *copy;
for block in 0..BLOCKS {
let write = written.iter().find(|w| w.0 == at / BLOCK + block).map_or(0, |w| w.1);
if taken[block] == 0 || write > taken[block] {
taken[block] = now;
let part = &mut bytes[block * BLOCK..(block + 1) * BLOCK];
// SAFETY: inside the view; whoever writes it meanwhile is
// noted, and the block taken again.
assert!(unsafe { crate::safecopy::copy(part.as_mut_ptr(), (at + block * BLOCK) as *const u8, BLOCK) });
}
}
};
let mut held = vec![0u8; LEN];
std::thread::scope(|s| {
let writers: Vec<_> = (0..3usize)
.map(|w| {
let stop = &stop;
s.spawn(move || {
let mut value = 1u32;
while !stop.load(Ordering::Relaxed) {
// Its own dwords, in every other block (in the rest
// only landings change anything).
for i in (w..LEN / 4).step_by(4 * 97).filter(|i| i * 4 / BLOCK % 2 == 0) {
assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone");
}
value += 1;
}
value - 1
})
})
.collect();
s.spawn(|| {
while !stop.load(Ordering::Relaxed) {
refresh();
}
});
let mut random = Random(77);
for round in 1..250u32 {
// The card's dwords: every fourth, from the third on, in some
// pages of some blocks.
let mut now = held.clone();
for _ in 0..60 {
let page = random.next() % (LEN / PAGE);
for i in (page * 1024 + 3..(page + 1) * 1024).step_by(4) {
now[i * 4..i * 4 + 4].copy_from_slice(&(round * 4096 + i as u32).to_le_bytes());
}
}
let pieces: Vec<Piece> = (0..BLOCKS).map(|b| (1, at + b * BLOCK, BLOCK)).collect();
let order = ordered(&pieces);
let cut: Vec<(usize, usize)> = order.iter().map(|&(_, at, len)| (at, len)).collect();
let jobs = jobs(&cut);
let into = held.as_mut_ptr() as usize;
each(jobs.len(), &|j| {
let mut notes = Notes::default();
for &(address, len) in &cut[jobs[j].clone()] {
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);
}
}
notes.flush();
});
assert!(held == now, "round {round}");
for i in (3..LEN / 4).step_by(4 * 61) {
let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().expect("four"));
assert_eq!(dword(i).load(Ordering::Relaxed), expect, "round {round} dword {i}");
}
}
stop.store(true, Ordering::Relaxed);
for (w, writer) in writers.into_iter().enumerate() {
let last = writer.join().expect("nothing undone");
for i in (w..LEN / 4).step_by(4 * 97).filter(|i| i * 4 / BLOCK % 2 == 0) {
assert_eq!(dword(i).load(Ordering::Relaxed), last);
}
}
});
refresh();
let copy = copy.into_inner().unwrap_or_else(|e| e.into_inner());
assert!(copy.0 == title.bytes(), "a write was not told to the copy");
}
/// What a frame's landing costs (ignored: a measurement): 1,536 pieces of
/// 64 KiB, 96 MB, of a 174 MB heap of view memory in 15 landings, each block
/// guarded by a refresh before it; three quarters of the pages of a piece
/// with new bytes, every dword of them. As before, and here on one thread
/// and more, through the title's address and through a view of ours.
#[test]
#[ignore]
fn what_landing_costs() {
assert!(crate::safecopy::on());
const HEAP: usize = 2784 * BLOCK;
const COUNT: usize = 1536;
let title = Title::new(HEAP);
let mut held = vec![0u8; HEAP];
let mut card = vec![0u8; COUNT * BLOCK];
let busy = AtomicBool::new(true);
// The pieces: runs of eight blocks, scattered.
let pieces: Vec<usize> = (0..COUNT).map(|i| (i / 8 * 1021 % (HEAP / BLOCK / 8)) * 8 + i % 8).collect();
std::thread::scope(|s| {
// Other threads of the process at work (what a protection change
// has to reach).
for _ in 0..6 {
s.spawn(|| {
let mut v = vec![0u64; 1 << 14];
while busy.load(Ordering::Relaxed) {
for (i, x) in v.iter_mut().enumerate() {
*x = x.wrapping_mul(31).wrapping_add(i as u64);
}
}
});
}
let mut round = 0u32;
// `guarded`: 2 as a refresh leaves them, 1 opened again before (that
// is timed beside), 0 not at all, as they were after the last.
let mut frame = |label: &str, dense: bool, guarded: u8, land: &dyn Fn(&[(usize, usize, usize)])| {
let mut best = f64::MAX;
let (mut guards, mut opening) = (f64::MAX, f64::MAX);
for _ in 0..5 {
round += 1;
for (k, &block) in pieces.iter().enumerate() {
for page in 0..16 {
if page % 4 == 3 {
continue;
}
let from = k * BLOCK + page * PAGE;
let step = if dense { 4 } else { 64 };
// (The rest as held.)
let old = block * BLOCK + page * PAGE;
card[from..from + PAGE].copy_from_slice(&held[old..old + PAGE]);
for b in card[from..from + PAGE].chunks_exact_mut(step) {
b[..4].copy_from_slice(&round.wrapping_mul(0x0101_0101).to_le_bytes());
}
}
let (a, b) = (k * BLOCK + 12 * PAGE, block * BLOCK + 12 * PAGE);
for page in [3usize, 7, 11, 15] {
let (a, b) = (a - 12 * PAGE + page * PAGE, b - 12 * PAGE + page * PAGE);
card[a..a + PAGE].copy_from_slice(&held[b..b + PAGE]);
}
}
let t = std::time::Instant::now();
if guarded > 0 {
assert!(crate::watch::writes(title.at, title.at + HEAP, true).is_some());
}
guards = guards.min(t.elapsed().as_secs_f64() * 1e3);
let t = std::time::Instant::now();
if guarded == 1 {
pieces.iter().for_each(|block| crate::watch::landing(title.at + block * BLOCK, BLOCK));
}
opening = opening.min(t.elapsed().as_secs_f64() * 1e3);
let all: Vec<(usize, usize, usize)> = pieces
.iter()
.enumerate()
.map(|(k, &block)| {
(title.at + block * BLOCK, card.as_ptr() as usize + k * BLOCK, held.as_mut_ptr() as usize + block * BLOCK)
})
.collect();
let t = std::time::Instant::now();
for landing in all.chunks(COUNT / 15 + 1) {
land(landing);
}
best = best.min(t.elapsed().as_secs_f64() * 1e3);
}
println!("{label}: {best:.1} ms a frame to land; the guards before it {guards:.1} ms, opening them {opening:.1} ms");
};
for dense in [true, false] {
println!("{}", if dense { "every dword of three pages in four new" } else { "every sixteenth dword of them new" });
let before: &dyn Fn(&[(usize, usize, usize)]) = &|landing| {
let mut scratch: Vec<u8> = Vec::new();
for &(at, now, held) in landing {
crate::shadow::land_as_before(at, now, held, BLOCK, &mut scratch);
}
};
frame("as before", dense, 2, before);
frame("as before, guards opened ahead", dense, 1, before);
frame("as before, nothing guarded", dense, 0, before);
for threads in [1usize, 2, 3, 4, 5, 6, 8] {
let pool = Pool::new(threads);
for beside in [false, true] {
frame(&format!("{threads} threads, beside {beside}"), dense, 2, &|landing| {
let cut: Vec<(usize, usize)> = landing.iter().map(|p| (p.0, BLOCK)).collect();
let jobs = jobs(&cut);
pool.each(jobs.len(), &|j| {
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) };
}
notes.flush();
});
});
}
}
}
busy.store(false, Ordering::Relaxed);
});
}
+2
View File
@@ -33,6 +33,8 @@ mod host;
mod indirect;
#[cfg(windows)]
mod inplace;
#[cfg(windows)]
mod land;
pub mod list;
pub mod object;
pub mod pipeline;
+1 -1
View File
@@ -971,7 +971,7 @@ extern "system" fn copy_texture_region(
};
// The list owns this mapped D3D12 upload buffer. Wine can report
// its address as MEM_FREE, so use the host-upload path.
list.defer_fill(staging, data, bytes as usize);
list.defer_fill_buffer(&buffer, staging, data, bytes as usize);
from.resource = buffer.as_raw().cast_const().cast();
from.footprint.offset = 0;
#[cfg(feature = "diagnostics")]
+363 -1
View File
@@ -115,6 +115,65 @@ std::arch::global_asm!(
"vzeroupper",
"xor eax, eax",
"ret",
".globl victory_safe_merge",
".globl victory_safe_merge_at",
".globl victory_safe_merge_after",
".globl victory_safe_merge_failed",
// rcx title memory, rdx what the card holds, r8 what it held when last
// looked at, r9 blocks of 32 bytes, fifth where the two counts go. Where
// a byte of the second differs from the third, it goes into title memory
// (as whole dwords, and only dwords that then differ from what is there)
// and into the third; each block of title memory is read just before it
// is written. rax: the blocks left when a page of title memory could not
// be read or written (0: all done). The counts: blocks in which the
// second and third differed, dwords stored in title memory.
"victory_safe_merge:",
"xor r10d, r10d",
"xor r11d, r11d",
"test r9, r9",
"jz 6f",
"vpcmpeqd ymm5, ymm5, ymm5",
"2:",
"vmovdqu ymm0, ymmword ptr [rdx]",
"vpcmpeqb ymm1, ymm0, ymmword ptr [r8]",
"vpmovmskb eax, ymm1",
"cmp eax, -1",
"je 5f",
"victory_safe_merge_at:",
"vmovdqu ymm2, ymmword ptr [rcx]",
"vpblendvb ymm3, ymm0, ymm2, ymm1",
"vpcmpeqd ymm4, ymm3, ymm2",
"vmovmskps eax, ymm4",
"xor eax, 255",
"jz 4f",
"cmp eax, 255",
"je 3f",
"vpxor ymm4, ymm4, ymm5",
"vpmaskmovd ymmword ptr [rcx], ymm4, ymm3",
"jmp 7f",
"3:",
"vmovdqu ymmword ptr [rcx], ymm3",
"victory_safe_merge_after:",
"7:",
"popcnt eax, eax",
"add r11, rax",
"4:",
"inc r10",
"vmovdqu ymmword ptr [r8], ymm0",
"5:",
"add rcx, 32",
"add rdx, 32",
"add r8, 32",
"dec r9",
"jnz 2b",
"6:",
"victory_safe_merge_failed:",
"vzeroupper",
"mov rax, qword ptr [rsp + 40]",
"mov qword ptr [rax], r10",
"mov qword ptr [rax + 8], r11",
"mov rax, r9",
"ret",
);
unsafe extern "system" {
@@ -130,6 +189,10 @@ unsafe extern "system" {
fn victory_safe_update_at();
fn victory_safe_update_after();
fn victory_safe_update_failed();
fn victory_safe_merge(title: *mut u8, now: *const u8, held: *mut u8, blocks: usize, counts: *mut [u64; 2]) -> usize;
fn victory_safe_merge_at();
fn victory_safe_merge_after();
fn victory_safe_merge_failed();
}
/// What [`update`] found.
@@ -179,6 +242,134 @@ pub(crate) unsafe fn update(dst: *mut u8, src: *const u8, len: usize) -> Updated
if from >= to { Updated::Same } else { Updated::Changed(from, to) }
}
/// What [`merge`] did.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Merged {
/// Blocks of 32 bytes in which the card's bytes were new.
pub(crate) new: u64,
/// Dwords stored in title memory.
pub(crate) dwords: u64,
/// Whether title memory could be read and written wherever it had to be.
pub(crate) there: bool,
}
/// What shaders wrote goes into title memory: every byte of `now` that
/// differs from the one in `held` goes to `title` and into `held`, every
/// other byte of both stays as it is. Title memory is read 32 bytes at a
/// time, each just before what changes of them is stored, and only the
/// dwords that change are stored (at ends that are no dword's, bytes): the
/// title's own threads may be writing those beside them.
///
/// Where title memory cannot be read or written, the rest of `held` takes
/// `now` if `take` says so (the caller has the card's bytes nowhere else),
/// else it stays.
///
/// # Safety
/// `now` and `held` are `len` bytes of ours, not overlapping, that nothing
/// else writes (but for `now` the card: it is read once); `title` is as
/// [`copy`]'s. The stretch lies in one page of 4 KiB of title memory. [`on`]
/// must have been asked.
pub(crate) unsafe fn merge(title: *mut u8, now: *const u8, held: *mut u8, len: usize, take: bool) -> Merged {
let mut out = Merged { there: true, ..Merged::default() };
let mut at = 0;
while at < len {
let address = title.addr() + at;
let left = len - at;
if !address.is_multiple_of(4) || left < 4 {
// A dword only partly in the stretch: its bytes one by one.
// SAFETY: inside the stretch.
unsafe {
let byte = now.add(at).read_volatile();
let mut there = 0u8;
if byte != held.add(at).read() {
out.new += 1;
let mut ok = copy(&mut there, title.add(at), 1);
if ok && there != byte {
ok = copy(title.add(at), &byte, 1);
out.dwords += u64::from(ok);
}
out.there &= ok;
if ok || take {
held.add(at).write(byte);
}
}
}
at += 1;
continue;
}
let into = address % 32;
let mut counts = [0u64; 2];
if into != 0 || left < 32 {
// Part of a block: in a block of its own, equal beside the part.
let n = (32 - into).min(left) & !3;
let (mut new, mut old) = ([0u8; 32], [0u8; 32]);
// SAFETY: inside the stretch; the block of title memory around
// it lies in the same page, and nothing of it outside the part
// is stored (the two arrays are equal there).
unsafe {
std::ptr::copy_nonoverlapping(now.add(at), new.as_mut_ptr().add(into), n);
std::ptr::copy_nonoverlapping(held.add(at), old.as_mut_ptr().add(into), n);
let stuck = victory_safe_merge(title.wrapping_add(at).wrapping_sub(into), new.as_ptr(), old.as_mut_ptr(), 1, &mut counts);
out.there &= stuck == 0;
let from = if stuck != 0 && take { new.as_ptr() } else { old.as_ptr() };
std::ptr::copy_nonoverlapping(from.add(into), held.add(at), n);
}
at += n;
} else {
let blocks = left / 32;
// SAFETY: whole blocks of the stretch.
let stuck = unsafe { victory_safe_merge(title.add(at), now.add(at), held.add(at), blocks, &mut counts) };
if stuck != 0 {
out.there = false;
if take {
let from = at + (blocks - stuck) * 32;
// SAFETY: the blocks that were not done.
unsafe { std::ptr::copy_nonoverlapping(now.add(from), held.add(from), stuck * 32) };
}
}
at += blocks * 32;
}
out.new += counts[0];
out.dwords += counts[1];
}
out
}
/// Whether the `len` bytes at `a` and `b` differ.
///
/// # Safety
/// Both are `len` bytes that can be read; the card may be writing them.
pub(crate) unsafe fn differ(a: *const u8, b: *const u8, len: usize) -> bool {
use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_or_si256, _mm256_setzero_si256, _mm256_testz_si256, _mm256_xor_si256};
/// # Safety
/// [`differ`]'s; the processor has AVX2 (as the code above assumes).
#[target_feature(enable = "avx2")]
unsafe fn blocks(a: *const u8, b: *const u8, n: usize) -> bool {
let mut at = 0;
while at < n {
let mut any = _mm256_setzero_si256();
for k in at..n.min(at + 4) {
// SAFETY: block `k`, inside both.
let (x, y) = unsafe {
(_mm256_loadu_si256(a.add(k * 32).cast::<__m256i>()), _mm256_loadu_si256(b.add(k * 32).cast::<__m256i>()))
};
any = _mm256_or_si256(any, _mm256_xor_si256(x, y));
}
if _mm256_testz_si256(any, any) == 0 {
return true;
}
at += 4;
}
false
}
// SAFETY: the caller's.
if unsafe { blocks(a, b, len / 32) } {
return true;
}
// SAFETY: the bytes behind the blocks.
(len / 32 * 32..len).any(|i| unsafe { a.add(i).read_volatile() != b.add(i).read_volatile() })
}
/// Puts `now` at `dst` where it differs from `was`, whole dwords (as `dst`
/// is aligned) and not a byte beside them: other threads may be writing
/// those. At the ends, single bytes of a dword only partly in the stretch.
@@ -255,7 +446,11 @@ pub(crate) fn failing_exit(at: usize) -> Option<usize> {
return Some(victory_safe_put_failed as *const () as usize);
}
let (from, to) = (victory_safe_update_at as *const () as usize, victory_safe_update_after as *const () as usize);
(from..to).contains(&at).then_some(victory_safe_update_failed as *const () as usize)
if (from..to).contains(&at) {
return Some(victory_safe_update_failed as *const () as usize);
}
let (from, to) = (victory_safe_merge_at as *const () as usize, victory_safe_merge_after as *const () as usize);
(from..to).contains(&at).then_some(victory_safe_merge_failed as *const () as usize)
}
#[cfg(test)]
@@ -407,6 +602,173 @@ mod tests {
}
}
/// [`merge`] against what it is to do, byte by byte, for every kind of
/// start, end and change: the bytes the card changed arrive in title
/// memory and in what it held, no dword without one is stored.
#[test]
fn a_merge_puts_what_the_card_changed_and_nothing_else() {
assert!(on());
let pages = Pages::new(1 << 12);
let mut seed = 1u32;
let mut random = move || {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
seed
};
for round in 0..4000u32 {
let at = random() as usize % 100;
let len = random() as usize % 300;
let (from, to) = (at, (at + len).min(400));
let n = to - from;
let base: Vec<u8> = (0..512).map(|_| random() as u8).collect();
let was: Vec<u8> = base[from..to].to_vec();
let mut held = was.clone();
let mut now = was.clone();
let mut title = base.clone();
// The card's writes: dwords and single bytes; the title's: some
// in the same dwords, some the same values.
for _ in 0..random() % 12 {
if n > 0 {
let i = random() as usize % n;
now[i] = random() as u8;
}
let i = random() as usize % 512;
title[i] = if (from..to).contains(&i) && round % 3 == 0 { now[i - from] } else { random() as u8 };
}
if round % 7 == 0 {
now.iter_mut().for_each(|b| *b = b.wrapping_add(1));
}
// SAFETY: inside the allocation and the vectors.
let done = unsafe {
std::ptr::copy_nonoverlapping(title.as_ptr(), pages.0, 512);
merge(pages.0.add(from), now.as_ptr(), held.as_mut_ptr(), n, round % 2 == 0)
};
assert!(done.there);
// SAFETY: inside the allocation.
let there = unsafe { std::slice::from_raw_parts(pages.0, 512) };
for i in 0..512 {
let wrote = (from..to).contains(&i) && now[i - from] != was[i - from];
let expect = if wrote { now[i - from] } else { title[i] };
assert_eq!(there[i], expect, "round {round} byte {i} of {from}..{to}");
}
assert_eq!(held, now, "round {round}");
assert_eq!(done.new == 0, was == now);
// Found merged already.
// SAFETY: as above.
let again = unsafe { merge(pages.0.add(from), now.as_ptr(), held.as_mut_ptr(), n, false) };
assert_eq!(again, Merged { new: 0, dwords: 0, there: true });
}
}
/// Title memory that is not there: what the card wrote stays to be
/// looked at again, or is taken, as asked; a page that only cannot be
/// written counts the same.
#[test]
fn a_merge_into_missing_memory_fails() {
assert!(on());
let pages = Pages::new(1 << 13);
let mut old = 0;
for (missing, take) in [(true, false), (true, true), (false, false), (false, true)] {
for (at, len) in [(0usize, 4096usize), (4, 64), (7, 1), (40, 100)] {
let was = vec![1u8; len];
let mut now = was.clone();
now[len - 1] = 9;
let mut held = was.clone();
// SAFETY: our allocation.
let done = unsafe {
if missing {
VirtualFree(pages.0.cast(), 4096, MEM_DECOMMIT);
} else {
VirtualProtect(pages.0.cast(), 4096, PAGE_READONLY, &mut old);
}
let done = merge(pages.0.add(at), now.as_ptr(), held.as_mut_ptr(), len, take);
VirtualAlloc(pages.0.cast(), 4096, MEM_COMMIT, PAGE_READWRITE);
VirtualProtect(pages.0.cast(), 4096, PAGE_READWRITE, &mut old);
done
};
assert!(!done.there);
assert_eq!(held, if take { now.clone() } else { was.clone() }, "{missing} {take} {at} {len}");
// Nothing to put: nothing fails.
let mut held = now.clone();
// SAFETY: as above; the addresses are no one's.
let done = unsafe { merge(std::ptr::without_provenance_mut(0x1000 + at), now.as_ptr(), held.as_mut_ptr(), len, take) };
assert!(done.there && done.new == 0);
}
}
}
/// [`merge`] beside threads that write other dwords of the same memory:
/// none of their writes is lost or undone.
#[test]
fn merges_undo_no_write_of_other_threads() {
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
assert!(on());
let pages = Pages::new(1 << 12);
let base = pages.0 as usize;
// SAFETY: committed, aligned memory, only touched as atomics or by
// the merge's stores of whole dwords.
let dword = |i: usize| unsafe { &*((base + i * 4) as *const AtomicU32) };
let stop = AtomicBool::new(false);
std::thread::scope(|s| {
let writers: Vec<_> = (0..2usize)
.map(|w| {
let stop = &stop;
s.spawn(move || {
let mut value = 1u32;
while !stop.load(Ordering::Relaxed) {
for i in (w..1024).step_by(4) {
// This thread's own dword: nobody else's value.
assert_eq!(dword(i).load(Ordering::Relaxed), value - 1, "dword {i}");
dword(i).store(value, Ordering::Relaxed);
}
value += 1;
}
})
})
.collect();
// The card's dwords: every fourth, from the third on.
let mut held = vec![0u8; 4096];
for round in 1..3000u32 {
let mut now = held.clone();
for i in (2..1024).step_by(4) {
if i * 7 % 5 != round as usize % 5 {
now[i * 4..i * 4 + 4].copy_from_slice(&(round + i as u32).to_le_bytes());
}
}
// SAFETY: the allocation, whole.
let done = unsafe { merge(base as *mut u8, now.as_ptr(), held.as_mut_ptr(), 4096, false) };
assert!(done.there);
for i in (2..1024).step_by(4) {
let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().unwrap());
assert_eq!(dword(i).load(Ordering::Relaxed), expect);
}
for i in (3..1024).step_by(4) {
assert_eq!(dword(i).load(Ordering::Relaxed), 0);
}
}
stop.store(true, Ordering::Relaxed);
for w in writers {
w.join().expect("no write was undone");
}
});
}
#[test]
fn differences_are_seen_wherever_they_are() {
for len in [0usize, 1, 31, 32, 33, 127, 128, 129, 200] {
let a = vec![7u8; len];
// SAFETY: the vectors' bytes.
assert!(!unsafe { differ(a.as_ptr(), a.clone().as_ptr(), len) });
for at in 0..len {
let mut b = a.clone();
b[at] = 8;
// SAFETY: as above.
assert!(unsafe { differ(a.as_ptr(), b.as_ptr(), len) }, "{len} {at}");
}
}
}
/// What the copies cost (ignored: a measurement): 64 KiB pieces of
/// scattered memory into a buffer the card reads, by the kernel and here.
#[test]
+349 -30
View File
@@ -17,7 +17,7 @@
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, RwLock};
use windows::Win32::Graphics::Direct3D12::ID3D12Resource;
@@ -54,6 +54,11 @@ pub(crate) struct Shadow {
/// GPU wrote differs. Room for the whole copy; only those ranges' bytes
/// are set (and read).
before: Mutex<Option<Vec<u8>>>,
/// Held shared while pieces of the copy are landed (`crate::land`), each
/// its own bytes of it on several threads, and alone while title bytes
/// go in under shader writes ([`Shadow::merge_under_writes`]), which
/// takes `before`'s lock too. Taken ahead of that one.
merging: RwLock<()>,
/// With snapshots kept ([`keeps`]): which 64 KiB pieces of the snapshot
/// hold the copy's bytes as they are now, and whether the snapshot is
/// counted in [`KEPT_BYTES`].
@@ -565,40 +570,34 @@ pub(crate) fn relay_fetched(number: u64) {
/// writing: the next refresh would have put title bytes over what the
/// second flight's shaders were writing.
#[derive(Default)]
struct Flights(Vec<((usize, usize), u32, u64)>);
struct Flights(std::collections::HashMap<(usize, usize), (u32, u64)>);
impl Flights {
/// Submission `number` declares `range`: counted once for it, however
/// often it declares it.
fn declare(&mut self, range: (usize, usize), number: u64) {
match self.0.iter_mut().find(|f| f.0 == range) {
Some(f) => {
if f.2 != number {
f.1 += 1;
f.2 = number;
}
}
None => self.0.push((range, 1, number)),
let f = self.0.entry(range).or_insert((0, number));
if f.0 == 0 || f.1 != number {
*f = (f.0 + 1, number);
}
}
/// One submission that declared `ranges` (each once) is copied back:
/// the ranges no other submission still holds.
/// the ranges no other submission still holds, in order.
fn done(&mut self, ranges: &[(usize, usize)]) -> Vec<(usize, usize)> {
let mut free = Vec::new();
for range in ranges {
match self.0.iter().position(|f| f.0 == *range) {
Some(at) => {
self.0[at].1 = self.0[at].1.saturating_sub(1);
if self.0[at].1 == 0 {
self.0.swap_remove(at);
free.push(*range);
}
match self.0.get_mut(range) {
Some(f) if f.0 > 1 => f.0 -= 1,
Some(_) => {
self.0.remove(range);
free.push(*range);
}
// Not counted (declared before anything counted): free.
None => free.push(*range),
}
}
free.sort_unstable();
free
}
}
@@ -1410,6 +1409,25 @@ mod wide_tests {
/// compared, changed runs put in, and their bytes.
static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
/// Why [`Shadow::merge_under_writes`] last left the caller to wait.
static STALE_WHY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn note_stale(why: usize) {
STALE_WHY.store(why, Ordering::Relaxed);
}
/// [`STALE_WHY`] in words (diagnostics).
#[cfg(feature = "diagnostics")]
pub(crate) fn stale_why() -> &'static str {
const WHY: [&str; 4] = [
"the memory is not watched",
"the journal does not say what was written",
"more changed runs than a submission sends up",
"no snapshot",
];
WHY[STALE_WHY.load(Ordering::Relaxed).min(3)]
}
/// [`MERGED`], taken.
pub(crate) fn merged_stats() -> [u64; 3] {
[0, 1, 2].map(|i| MERGED[i].swap(0, Ordering::Relaxed))
@@ -1495,7 +1513,7 @@ pub(crate) fn send_stats() -> [u64; 3] {
/// Whether what shaders wrote goes into title memory run by run
/// ([`put_changed`]; on by default, `VICTORY_EXACT_BACK=0` writes the whole
/// stretch from the first changed byte to the last, as before).
fn exact_back() -> bool {
pub(crate) fn exact_back() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_EXACT_BACK").is_none_or(|v| v != "0"))
}
@@ -1535,16 +1553,6 @@ fn dword_runs(at: usize, title: &[u8], merged: &[u8], gap: usize) -> Vec<(usize,
/// shortcut: a piece with very many runs has them joined over small gaps,
/// where the old race is left.
fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize {
// Past the guard, if it is one (`VICTORY_LAND_WINDOW`).
if exact_back()
&& crate::safecopy::on()
// SAFETY: the same title memory through a view of ours.
&& crate::watch::land_through(at, title.len(), |to| unsafe { crate::safecopy::put_changed(to, title, merged) })
{
PUT[0].fetch_add(1, Ordering::Relaxed);
PUT[2].fetch_add(merged.len() as u64, Ordering::Relaxed);
return merged.len();
}
crate::watch::landing(at, title.len());
if !exact_back() {
crate::host::write_mapped(at as *mut u8, merged.as_ptr(), merged.len());
@@ -1583,6 +1591,27 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize {
written
}
/// For `crate::land`'s measurement: a piece as [`Shadow::card_merge_relay`]
/// lands it without `VICTORY_LAND`: `n` bytes at `now`, `held` what the CPU's
/// side held, both the caller's alone.
#[cfg(test)]
pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, title: &mut Vec<u8>) {
// SAFETY: the caller's.
let (gpu, held) = unsafe { (std::slice::from_raw_parts(now as *const u8, n), std::slice::from_raw_parts_mut(held as *mut u8, n)) };
let Some(first) = first_difference(gpu, held) else {
return;
};
let last = last_difference(gpu, held).unwrap_or(first);
let n = last + 1 - first;
title.clear();
title.resize(n, 0);
assert!(crate::host::read_into((start + first) as *const u8, title));
let was = title.clone();
if merge_piece(&gpu[first..=last], &mut held[first..=last], title) {
put_changed(start + first, &was, title);
}
}
#[cfg(test)]
mod merge_tests {
use super::{changed_runs, dword_runs};
@@ -2002,6 +2031,7 @@ impl Shadow {
pending: Mutex::default(),
flights: Mutex::default(),
before: Mutex::default(),
merging: RwLock::default(),
kept: Mutex::default(),
used: AtomicU64::new(crate::host::moment()),
asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)],
@@ -2401,7 +2431,7 @@ impl Shadow {
let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
if relay() {
let free = self.flights.lock().unwrap_or_else(|e| e.into_inner()).done(ranges);
pending.retain(|r| !free.contains(r));
pending.retain(|r| free.binary_search(r).is_err());
} else {
pending.retain(|r| !ranges.contains(r));
}
@@ -2465,6 +2495,12 @@ impl Shadow {
!self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
}
/// Whether one of those submissions may be writing in title memory
/// `[from, to)`.
pub(crate) fn writes_pending_in(&self, from: usize, to: usize) -> bool {
self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from)
}
/// Whether [`Shadow::update`] of `[address, address + len)` would leave
/// title bytes behind: a range shaders may be writing holds a page the
/// title wrote since the copy last took it. The answer comes from the
@@ -2540,6 +2576,7 @@ impl Shadow {
return false;
}
if self.watched.load(Ordering::Relaxed) == NOT_WATCHED {
note_stale(0);
return true;
}
let base = start / PAGE;
@@ -2552,6 +2589,7 @@ impl Shadow {
// those were all of run 99's cases: the flights were settled
// 4-5 times a frame for "0 pages looked at".
let Some((now, written)) = crate::watch::writes(a, e, true) else {
note_stale(1);
return true;
};
let stale: Vec<usize> = {
@@ -2577,6 +2615,7 @@ impl Shadow {
// reference under the same lock, and a page read before
// such a merge and compared after it would take the card's
// bytes for the title's.
let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
// A page that is not there is left as it is, and looked at
// again next time.
@@ -2591,6 +2630,7 @@ impl Shadow {
let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
let runs = changed_runs(title, held);
if runs.len() > *runs_left {
note_stale(2);
return true;
}
*runs_left -= runs.len();
@@ -2602,6 +2642,7 @@ impl Shadow {
}
} else {
let Some(snapshot) = before.as_mut() else {
note_stale(3);
return true;
};
// SAFETY: the snapshot's allocation holds the copy's
@@ -2619,6 +2660,7 @@ impl Shadow {
}
}
drop(before);
drop(_merging);
// Taken, if the range holds all of the page that is in the
// copy; else the rest of it is the refresh's, which notes
// only whole pages, and the page is looked at again.
@@ -3187,12 +3229,289 @@ impl Shadow {
put_changed(at, title, merged);
}
/// What is to go up to the card, noted as sent with `number`, as
/// [`card_dirty`] does; notes of sends up to `merged` go.
pub(crate) fn send_up(&self, number: u64, merged: u64) -> Vec<(usize, usize)> {
let card = self.card.as_ref().unwrap();
let mut dirty = card.dirty.lock().unwrap();
let ranges = std::mem::take(&mut *dirty);
let mut sent = card.sent.lock().unwrap();
sent.retain(|s| s.2 > merged);
sent.extend(ranges.iter().map(|&(a, b)| (a, b, number)));
ranges
}
/// What is to go up to the card, taken.
pub(crate) fn take_dirty(&self) -> Vec<(usize, usize)> {
std::mem::take(&mut *self.card.as_ref().unwrap().dirty.lock().unwrap())
}
}
impl Shadow {
/// [`Shadow::card_merge_relay`] of several pieces, each within one
/// 64 KiB block of title memory: from and to (offsets in the copy), and
/// where the fetched bytes are. On any thread: several may land pieces
/// of one copy, no two the same bytes. Returns the bytes put into title
/// memory.
///
/// What is left out is as there, asked once for all of them: the notes
/// of bytes that went up (or are to go up) behind the fetch only move
/// from `dirty` to `sent`, with a later number, and grow only by
/// [`Shadow::merge_under_writes`], which the lock held here keeps out.
///
/// # Safety
/// The third of each piece is the address of its bytes, which stay as
/// they are during the call.
pub(crate) unsafe fn land_card(&self, pieces: &[(usize, usize, usize)], fetched_after: u64, notes: &mut crate::land::Notes) -> u64 {
let Some(card) = &self.card else {
return 0;
};
let waiting = std::time::Instant::now();
let _merging = self.merging.read().unwrap_or_else(|e| e.into_inner());
crate::land::spent(crate::land::stat::LOCK, waiting);
let (from, to) = pieces.iter().fold((usize::MAX, 0), |(a, b), p| (a.min(p.0), b.max(p.1)));
let skip: Vec<(usize, usize)> = {
let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner());
dirty
.iter()
.copied()
.chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1)))
.filter(|&(a, b)| a < to && b > from)
.collect()
};
let mut put = 0;
for &(lo, hi, now) in pieces {
if lo >= hi || hi > self.len as usize {
continue;
}
let near: Vec<(usize, usize)> = skip.iter().copied().filter(|&(a, b)| a < hi && b > lo).collect();
let parts: Vec<(usize, usize)> = outside(lo, hi, near).into_iter().map(|(a, b)| (a - lo, b - lo)).collect();
// SAFETY: inside the mapping (checked above), in a range
// declared and not done with, which no refresh writes; the
// title's bytes are kept out by the lock; the caller's.
// 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) };
self.walls_merged(hi - lo, merged as usize);
put += merged;
}
put
}
/// [`Shadow::relay_merge`] of a piece `[at, at + n)` (within one 64 KiB
/// block of title memory) of a copy in the PC's memory; on any thread,
/// as [`Shadow::land_card`]. The copy is read once and never written.
/// Returns the bytes put into title memory.
pub(crate) fn land_back(&self, at: usize, n: usize, notes: &mut crate::land::Notes) -> u64 {
if self.card.is_some() || n == 0 || at + n > self.len as usize {
return 0;
}
let waiting = std::time::Instant::now();
let _merging = self.merging.read().unwrap_or_else(|e| e.into_inner());
crate::land::spent(crate::land::stat::LOCK, waiting);
// The snapshot's memory stays where it is until the range is done
// with (`copy_back_done`), which comes after this.
let Some(held) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut().map(Vec::as_mut_ptr) else {
return 0;
};
// SAFETY: inside the copy's mapping (checked above), which only the
// card writes there, and inside the snapshot's allocation, which
// holds the copy's length (`writing`): these offsets are in a range
// declared and not done with, whose bytes it holds, and the lock
// 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) }
}
}
#[cfg(test)]
mod land_tests {
use super::{Card, PIECE, Shadow};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
/// A copy in the card's memory of title memory at `title` (its card side
/// is never looked at here), all bytes 0 on the CPU's side.
fn copy_of(title: usize, len: usize) -> Option<Shadow> {
let (buffer, data) = crate::host::host()?.shared_buffer(len as u64)?;
// SAFETY: the mapping, `len` bytes.
unsafe { std::ptr::write_bytes(data, 0, len) };
let mut shadow = Shadow::new(buffer.clone(), data, 0, title as u64, len as u64);
shadow.card = Some(Card {
staging: buffer,
before: Mutex::default(),
dirty: Mutex::default(),
sent: Mutex::default(),
size: len as u64,
});
Some(shadow)
}
/// Memory that stays (`crate::watch` knows its addresses): private, or a
/// view noted as the runtime notes the title's.
fn memory(len: usize, view: bool) -> usize {
use windows_sys::Win32::System::Memory as mem;
// SAFETY: plain allocations of our own.
unsafe {
if !view {
return mem::VirtualAlloc(std::ptr::null(), len, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as usize;
}
let section = mem::CreateFileMappingW(-1isize as _, std::ptr::null(), mem::PAGE_READWRITE, 0, len as u32, std::ptr::null());
let at = mem::MapViewOfFile(section, mem::FILE_MAP_WRITE, 0, 0, len).Value as usize;
crate::inplace::title_memory_section(section as usize, len as u64, true);
crate::title_memory_remapped(at, len);
crate::inplace::title_memory_view(at, len, section as usize, 0);
at
}
}
fn random(seed: &mut u64) -> usize {
*seed ^= *seed << 13;
*seed ^= *seed >> 7;
*seed ^= *seed << 17;
(*seed >> 8) as usize
}
/// [`Shadow::land_card`] leaves title memory and the CPU's side as
/// [`Shadow::card_merge_relay`] does, with title bytes that went up
/// behind the fetch, or have not gone up, left out.
#[test]
fn pieces_land_as_the_merge_one_by_one_lands_them() {
assert!(crate::safecopy::on());
const LEN: usize = 3 * PIECE;
let mut seed = 0x1234_5678_9abcu64;
for view in [false, true] {
let (a, b) = (memory(LEN, view), memory(LEN, view));
let (Some(one), Some(many)) = (copy_of(a, LEN), copy_of(b, LEN)) else {
return; // no host GPU
};
// SAFETY: the two memories and the two mappings.
let bytes = |at: usize| unsafe { std::slice::from_raw_parts_mut(at as *mut u8, LEN) };
for round in 0..40u32 {
let base: Vec<u8> = (0..LEN).map(|_| random(&mut seed) as u8).collect();
let (mut held, mut title, mut now) = (base.clone(), base.clone(), base);
let (mut dirty, mut sent) = (Vec::new(), Vec::new());
for k in 0..120 {
let at = random(&mut seed) % LEN / 4 * 4;
let n = (random(&mut seed) % 900 / 4 * 4).min(LEN - at);
match k % 4 {
0 | 1 => now[at..at + n].fill(random(&mut seed) as u8),
2 => title[at..at + n].fill(random(&mut seed) as u8),
// Title bytes put into the CPU's side meanwhile.
_ => {
let byte = random(&mut seed) as u8;
held[at..at + n].fill(byte);
title[at..at + n].fill(byte);
if k % 8 == 3 {
dirty.push((at, at + n));
} else {
sent.push((at, at + n, u64::from(round % 3) + (k as u64 / 16)));
}
}
}
}
let after = 4u64;
for (shadow, at) in [(&one, a), (&many, b)] {
crate::watch::writing(at, LEN);
bytes(at).copy_from_slice(&title);
bytes(shadow.data as usize).copy_from_slice(&held);
let card = shadow.card.as_ref().expect("made with one");
*card.dirty.lock().unwrap() = dirty.clone();
*card.sent.lock().unwrap() = sent.clone();
}
let pieces: Vec<(usize, usize)> = (0..3).map(|p| (p * PIECE + 16, (p + 1) * PIECE - 4)).collect();
let mut scratch = Vec::new();
for &(lo, hi) in &pieces {
one.card_merge_relay(lo, &now[lo..hi], after, &mut scratch);
}
let addressed: Vec<(usize, usize, usize)> =
pieces.iter().map(|&(lo, hi)| (lo, hi, now.as_ptr() as usize + lo)).collect();
let mut notes = crate::land::Notes::default();
// SAFETY: the fetched bytes are `now`'s.
unsafe { many.land_card(&addressed, after, &mut notes) };
notes.flush();
assert!(bytes(a) == bytes(b), "title memory, round {round}");
assert!(bytes(one.data as usize) == bytes(many.data as usize), "the CPU's side, round {round}");
}
}
}
/// Landings of one copy on several threads, the title writing dwords of
/// the same blocks, and the title's bytes put into the CPU's side under
/// the shaders' writes ([`Shadow::merge_under_writes`]), all at once. The
/// card has never received the title's bytes: what is fetched holds older
/// ones there, which must not be taken for shaders' writes.
#[test]
fn landings_and_title_bytes_going_in_keep_each_others_bytes() {
assert!(crate::safecopy::on());
const BLOCKS: usize = 16;
const LEN: usize = BLOCKS * PIECE;
let title = memory(LEN, true);
let Some(shadow) = copy_of(title, LEN) else {
return; // no host GPU
};
shadow.pending.lock().unwrap().push((title, title + LEN));
// SAFETY: committed, aligned; touched as atomics or by the landing's
// stores of whole dwords.
let dword = |i: usize| unsafe { &*((title + i * 4) as *const AtomicU32) };
let stop = AtomicBool::new(false);
std::thread::scope(|s| {
let writer = s.spawn(|| {
let mut value = 1u32;
while !stop.load(Ordering::Relaxed) {
for i in (1..LEN / 4).step_by(4 * 331) {
assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone");
}
value += 1;
std::thread::sleep(std::time::Duration::from_micros(200));
}
value - 1
});
s.spawn(|| {
while !stop.load(Ordering::Relaxed) {
let mut runs = usize::MAX;
assert!(!shadow.merge_under_writes(title, LEN, &mut runs));
// Sent up, as the preparing of a submission would: noted
// with a number behind the fetches'.
let card = shadow.card.as_ref().expect("made with one");
let mut dirty = card.dirty.lock().unwrap();
let mut sent = card.sent.lock().unwrap();
let moved: Vec<_> = std::mem::take(&mut *dirty).into_iter().map(|(a, b)| (a, b, 9)).collect();
sent.extend(moved);
sent.sort_unstable();
sent.dedup();
}
});
let mut now = vec![0u8; LEN];
for round in 1..200u32 {
for block in (0..BLOCKS).filter(|b| (*b as u32 * 5 + round) % 3 != 0) {
for i in (block * PIECE / 4 + 3..(block + 1) * PIECE / 4).step_by(4) {
now[i * 4..i * 4 + 4].copy_from_slice(&(round << 20 | i as u32).to_le_bytes());
}
}
let at = now.as_ptr() as usize;
crate::land::each(BLOCKS, &|b| {
let mut notes = crate::land::Notes::default();
let (lo, hi) = (b * PIECE, (b + 1) * PIECE);
// SAFETY: the fetched bytes are `now`'s; each block once.
unsafe { shadow.land_card(&[(lo, hi, at + lo)], 8, &mut notes) };
notes.flush();
});
for i in (3..LEN / 4).step_by(4 * 53) {
let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().expect("four"));
assert_eq!(dword(i).load(Ordering::Relaxed), expect, "round {round} dword {i}");
}
}
stop.store(true, Ordering::Relaxed);
let last = writer.join().expect("nothing undone");
assert!((1..LEN / 4).step_by(4 * 331).all(|i| dword(i).load(Ordering::Relaxed) == last));
});
}
}
struct Entry {
end: u64,
shadow: Option<Arc<Shadow>>,
+73 -74
View File
@@ -589,10 +589,9 @@ 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); pieces put into title
/// memory past the guards ([`land_through`]).
/// nanoseconds of changing protections (all threads).
#[cfg(feature = "diagnostics")]
static ASKS: [std::sync::atomic::AtomicU64; 10] = [const { std::sync::atomic::AtomicU64::new(0) }; 10];
static ASKS: [std::sync::atomic::AtomicU64; 9] = [const { std::sync::atomic::AtomicU64::new(0) }; 9];
#[cfg(feature = "diagnostics")]
fn tally(what: usize, n: u64) {
@@ -601,7 +600,7 @@ fn tally(what: usize, n: u64) {
/// [`ASKS`], taken.
#[cfg(feature = "diagnostics")]
pub(crate) fn asks() -> [u64; 10] {
pub(crate) fn asks() -> [u64; 9] {
std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
}
@@ -637,82 +636,82 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> {
/// The 4 KiB pages of title memory that what shaders wrote was put into,
/// and the frame it last was.
static LANDED: Mutex<Option<std::collections::HashMap<usize, u64>>> = Mutex::new(None);
static LANDED: Mutex<Option<std::collections::HashMap<usize, u64, std::hash::BuildHasherDefault<PageHash>>>> = Mutex::new(None);
/// A page's number, spread: some 20,000 a frame are noted in [`LANDED`].
#[derive(Default)]
struct PageHash(u64);
impl std::hash::Hasher for PageHash {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for &byte in bytes {
self.write_u64(u64::from(byte));
}
}
fn write_u64(&mut self, n: u64) {
self.0 = (self.0 ^ n).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(26).wrapping_mul(0x9e37_79b9_7f4a_7c15);
}
fn write_usize(&mut self, n: usize) {
self.write_u64(n as u64);
}
}
/// What shaders wrote is about to go into title memory at `[at, at + len)`.
pub(crate) fn landing(at: usize, len: usize) {
note_landed(at, len);
{
let frame = crate::frame::current();
let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
let landed = landed.get_or_insert_with(Default::default);
for page in at / 4096..=(at + len.max(1) - 1) / 4096 {
landed.insert(page, frame);
}
}
writing(at, len);
}
fn note_landed(at: usize, len: usize) {
let frame = crate::frame::current();
let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
let landed = landed.get_or_insert_with(Default::default);
for page in at / 4096..=(at + len.max(1) - 1) / 4096 {
landed.insert(page, frame);
}
}
/// Whether what shaders wrote goes into guarded title memory past the guard
/// (`VICTORY_LAND_WINDOW=1`; off by default, not yet run in the game).
/// What shaders wrote went into title memory through another view of the
/// same pages (`crate::inplace::beside`): `pages` (of 4 KiB, by number)
/// hold some of it, all of them in `spans` (address, bytes).
///
/// Each piece put into title memory took the guard off its block, and the
/// next refresh of a copy of it put it on again, two changes of protection
/// under the guards' one lock, 10 microseconds each with the title's threads
/// running: some 1,600 pieces a frame, in the relay's landing and in the
/// submitting thread's refreshes. The title's own writes take some 260.
fn land_window() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LAND_WINDOW").is_some_and(|v| v == "1") && light())
}
/// With [`land_window`], if `[at, at + len)` is guarded view memory: `put`
/// writes what shaders wrote there, at the address it is given, through a
/// view of ours of the same section. Whether it did (`put` says whether it
/// could); if not the caller goes the other way ([`landing`]), `put` begun
/// or not.
///
/// Why it is the same: the runtime tells of every view it maps, and forgets
/// those it unmaps, under the lock held here for reading, so while it is
/// held the pages the title sees at `at` are the pages written. The block
/// stays read-only for the title, whose own writes are seen as before. Ours
/// is noted in the journal, after the bytes are in: an asking before that
/// may or may not copy them, and has a number under the note's, so the next
/// one copies the page (again).
pub(crate) fn land_through(at: usize, len: usize, put: impl FnOnce(*mut u8) -> bool) -> bool {
land_window() && land_past(at, len, put)
}
fn land_past(at: usize, len: usize, put: impl FnOnce(*mut u8) -> bool) -> bool {
if len == 0 || !published(at, at + len) {
return false;
/// Nothing faulted and no guard was opened. A guarded block stays read-only,
/// clean, and known by its bit ([`PUBLISHED`]), all of which say that the
/// title wrote nothing there: our write is an entry of the journal, which
/// every answer about the block comes from, the quick ones and the guards'
/// alike (a block whose guard is off they report anyway). So neither the
/// guards' lock nor a protection is touched here, or by the next refresh.
/// Noted after the bytes are in, never before: a copy that read the block
/// 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)]) {
{
let frame = crate::frame::current();
let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
let landed = landed.get_or_insert_with(Default::default);
for &page in pages {
landed.insert(page, frame);
}
}
let Some(_mapped) = title_memory_reading_now() else {
return false;
};
let crate::inplace::Cover::Run(section, offset) = crate::inplace::cover(at, len) else {
return false;
};
let Some(base) = crate::inplace::window(section) else {
return false;
};
if !put((base + offset as usize) as *mut u8) {
return false;
}
note_landed(at, len);
{
let mut j = journal_mut();
let now = next_asking();
for page in at / PAGE..(at + len).div_ceil(PAGE) {
j.written.insert(page, now);
let mut last = usize::MAX;
for &page in pages {
let block = page * KERNEL_PAGE / PAGE;
if block != last {
j.written.insert(block, now);
last = block;
}
}
}
#[cfg(feature = "diagnostics")]
tally(9, 1);
// As `writing` says.
crate::descriptor::host::remapped(at, len);
true
for &(at, len) in spans {
// A placed texture there changes with no descriptor written.
crate::descriptor::host::remapped(at, len);
}
}
/// Whether shaders' writes went into a page of `[at, at + len)` in the last
@@ -727,7 +726,8 @@ pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool {
/// Whether every block of `[at, at + len)` is view memory written since a
/// host copy last took it: guarded then, and the guard is off. (Written by
/// the title, or by us putting a flight's shader writes into it.) Not for
/// the title, or by us putting a flight's shader writes into it, if not
/// beside the guard, [`landed_beside`].) Not for
/// blocks no copy ever took, which were never guarded: the caller's range
/// lies in a copy a flight was given, which took all of it.
pub(crate) fn written_since_taken(at: usize, len: usize) -> bool {
@@ -736,7 +736,7 @@ pub(crate) fn written_since_taken(at: usize, len: usize) -> bool {
}
let g = guards();
(at / BLOCK..=(at + len - 1) / BLOCK)
.all(|b| !g.protected.contains(&b) && !g.clean.contains(&b) && !g.absent.contains(&b))
.all(|b| !g.clean.contains(&b) && !g.absent.contains(&b))
}
/// For view memory: the pages of `[start, end)`'s blocks written since
@@ -1589,12 +1589,11 @@ mod many_askers_tests {
// or past the guard.
let word = at + page * PAGE + t * 8;
// SAFETY (both): as above.
let put = next(3) == 0
&& super::land_past(word, 8, |to| {
unsafe { to.cast::<u64>().write_volatile(2) };
true
});
if put {
let reading = (next(3) == 0).then(super::title_memory_reading_now).flatten();
let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8));
if let Some(to) = beside {
unsafe { (to as *mut u64).write_volatile(2) };
super::landed_beside(&[word / 4096], &[(word, 8)]);
past.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
assert_eq!(unsafe { (word as *const u64).read_volatile() }, 2, "put elsewhere");
} else {