What shaders wrote is landed on a few threads, beside the guards (VICTORY_LAND)

The relay's thread merged some 1,500 pieces of 64 KiB (98 MB) a frame one
after the other: 45 ms in the frame's shape, of them 22 ms copying and
merging, 18 ms the kernel's faults on the first write to each page of memory
just made writable, 5 ms protection calls. Now one AVX2 pass a piece, in jobs
on four threads, through a view of ours of the title's pages that is never
guarded (VICTORY_LAND_BESIDE): 8 ms. The log splits a landing's time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-24 22:14:03 -06:00
1 parent da89c8a5a9
commit 590af7ca39
8 files changed
+1960 -82

No files matched your search

+199 -56
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"))
@@ -1970,13 +1971,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)]
@@ -2660,6 +2664,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 +2744,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 +2766,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 +2899,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 +3700,7 @@ impl Host {
event,
sent: 0,
buffer: None,
had: crate::land::Had::default(),
})
}
}
@@ -3654,21 +3714,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 +3750,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 +3772,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 +3819,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 +3840,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 +3853,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 +3872,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 +3948,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 +3974,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 +3983,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 +3998,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();
+37 -1
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())
@@ -282,6 +285,9 @@ fn views() -> std::sync::MutexGuard<'static, Views> {
pub fn title_memory_section(section: usize, bytes: u64, committed: bool) {
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));
}
@@ -343,6 +349,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;
+363 -1
View File
@@ -75,6 +75,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" {
@@ -86,6 +145,138 @@ unsafe extern "system" {
fn victory_safe_put_at();
fn victory_safe_put_after();
fn victory_safe_put_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 [`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`
@@ -160,7 +351,11 @@ pub(crate) fn failing_exit(at: usize) -> Option<usize> {
return Some(victory_safe_copy_failed as *const () as usize);
}
let (from, to) = (victory_safe_put_at as *const () as usize, victory_safe_put_after as *const () as usize);
(from..to).contains(&at).then_some(victory_safe_put_failed as *const () as usize)
if (from..to).contains(&at) {
return Some(victory_safe_put_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)]
@@ -266,6 +461,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]
+308 -20
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;
@@ -49,6 +49,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`].
@@ -560,40 +565,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
}
}
@@ -1412,7 +1411,7 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> {
/// 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"))
}
@@ -1490,6 +1489,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};
@@ -1880,6 +1900,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)],
@@ -2279,7 +2300,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));
}
@@ -2455,6 +2476,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.
@@ -2497,6 +2519,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.
@@ -2908,6 +2931,271 @@ impl Shadow {
}
}
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>>,
+62 -4
View File
@@ -449,7 +449,28 @@ 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) {
@@ -464,6 +485,42 @@ pub(crate) fn landing(at: usize, len: usize) {
writing(at, len);
}
/// 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).
///
/// Nothing faulted and no guard was opened. A guarded block stays read-only
/// and is noted as written, as [`guard`] notes one "written through the
/// runtime": the next asking reports it, to every copy that has it, and has
/// nothing to protect. Noted after the bytes are in, never before: a copy
/// that takes the block while they go in notes it clean, and this makes it
/// written again; noted before, such a copy would keep the half it read.
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 mut g = guards();
let mut last = usize::MAX;
for &page in pages {
let block = page * KERNEL_PAGE / BLOCK;
if block != last {
g.clean.remove(&block);
last = block;
}
}
}
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
/// `frames` frames.
pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool {
@@ -475,8 +532,9 @@ 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
/// host copy last took it: guarded then, and the guard is off, or noted
/// written behind it. (Written by the title, or by us putting a flight's
/// shader writes into it, [`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 {
@@ -485,7 +543,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