gpu: port lock-free submit-thread watch/shadow/batch/card_steps/send optimizations

This commit is contained in:
theme613 committed 2026-11-28 13:54:54 +08:00
1 parent 84b4509fa3
commit 6f34121d31
5 files changed
+325 -143

No files matched your search

+13 -1
View File
@@ -8847,6 +8847,9 @@ impl Batch {
let Step::Refresh(shadow, address, len) = step else {
continue;
};
if shadow.in_place() {
continue;
}
let (from, to) = (*address, *address + *len);
let key = std::sync::Arc::as_ptr(shadow) as usize;
let at = if last.0 == key && key != 0 {
@@ -8876,6 +8879,9 @@ impl Batch {
}
fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
if shadow.in_place() {
return;
}
let end = address + len;
let key = std::sync::Arc::as_ptr(shadow) as usize;
if self.ahead.get(&key).is_some_and(|&(from, to)| from <= address && end <= to) {
@@ -8962,6 +8968,9 @@ impl Batch {
for step in &list.deferred().copies {
match step {
Step::Refresh(shadow, at, len) => {
if shadow.in_place() {
continue;
}
self.touches.push(Touch::Refresh(std::sync::Arc::as_ptr(shadow) as usize, *at, *at + *len));
}
Step::GpuWrite(shadow, ..) => self.touches.push(Touch::Write(std::sync::Arc::as_ptr(shadow) as usize)),
@@ -9038,6 +9047,9 @@ impl Batch {
for (i, step) in list.deferred().copies.iter().enumerate() {
touches.push(match step {
Step::Refresh(shadow, at, len) => {
if shadow.in_place() {
continue;
}
let key = std::sync::Arc::as_ptr(shadow) as usize;
copies.entry(key).or_insert_with(|| shadow.clone());
Touch::Refresh(key, *at, *at + *len)
@@ -9144,7 +9156,7 @@ impl Batch {
}
// One write-watch asking for the copies that lie close together,
// not one per copy.
let ahead = self.refreshes.len() > 1;
let ahead = self.refreshes.len() > 1 && !crate::watch::kept_active();
if ahead {
let started = std::time::Instant::now();
let ranges: Vec<(usize, usize)> = self
+37 -16
View File
@@ -370,45 +370,66 @@ fn plan(does: &[Does], stage: u32, by_order: bool, behind: &mut Option<(usize, u
let mut taken = vec![false; does.len()];
let (mut read, mut written) = (Vec::new(), Vec::new());
let mut more = Vec::new();
let (mut has_copy, mut has_placed) = (false, false);
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::Copy { asked: true, .. } | Does::Fill { asked: true, .. } => more.push(i),
Does::Copy { asked, .. } => {
has_copy = true;
if asked {
more.push(i);
}
}
Does::Fill { asked: true, .. } => more.push(i),
Does::Placed { .. } => has_placed = true,
_ => {}
}
}
let mut taken_count = 0usize;
while !more.is_empty() {
// (Joined once for the round: one by one the 2,800 fills of a frame
// sorted the ranges each time, 16 ms of the submitting thread.)
let (mut reads, mut writes) = (Vec::new(), Vec::new());
for i in std::mem::take(&mut more) {
takes(&does[i])?;
taken[i] = true;
if !taken[i] {
taken[i] = true;
taken_count += 1;
}
if let Some((r, w)) = reads_writes(&does[i]) {
if w.0 < w.1 && meet(r, w) {
return Err("a copy onto itself");
}
reads.push(r);
writes.push(w);
if has_copy || has_placed {
reads.push(r);
}
if w.0 < w.1 {
writes.push(w);
}
}
}
join_ranges(&mut read, reads);
if writes.iter().any(|w| w.0 < w.1) {
if !reads.is_empty() {
join_ranges(&mut read, reads);
}
if !writes.is_empty() {
join_ranges(&mut written, writes);
}
if taken.iter().filter(|t| **t).count() > MOST {
if taken_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 let Some((r, w)) = reads_writes(d)
&& (touched(&written, r) || touched(&written, w) || touched(&read, w))
{
more.push(i);
if !written.is_empty() || (has_copy && !read.is_empty()) {
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 let Some((r, w)) = reads_writes(d)
&& (touched(&written, r)
|| (w.0 < w.1 && (touched(&written, w) || touched(&read, w))))
{
more.push(i);
}
}
}
}
+49 -28
View File
@@ -219,7 +219,7 @@ pub(super) struct Own {
}
/// Runs whose pairs are one piece of work.
const RUNS_AT_A_TIME: usize = 4096;
const RUNS_AT_A_TIME: usize = 512;
/// Takes what `dirty` sends up out of the CPU sides.
pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)]) -> Option<Own> {
@@ -227,42 +227,58 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, us
pass(host)?;
// Runs of whole words of the copy: only those are pairs. (A byte beside
// them in a word may be the card's.)
let short = |&(a, b): &(usize, usize)| short(a, b - a);
let is_short = |&(a, b): &(usize, usize)| short(a, b - a);
let mut at = 0u64;
let mut copies = Vec::with_capacity(dirty.len());
for (_, ranges) in dirty {
let mut word_chunks: Vec<(usize, &[(usize, usize)], u64)> = Vec::new();
let mut run_bytes = 0u64;
let mut run_count = 0u64;
let mut total_words = 0u64;
for (shadow, ranges) in dirty {
let mut runs = Vec::new();
for &(a, b) in ranges.iter().filter(|r| !short(r)) {
runs.push((a, at, b - a));
at += ((b - a) as u64).next_multiple_of(16);
let mut words = 0usize;
let from = shadow.card_data() as usize;
let chunk_start = word_chunks.len();
for chunk in ranges.chunks(RUNS_AT_A_TIME) {
let mut chunk_words = 0usize;
for &(a, b) in chunk {
let len = b - a;
if short(a, len) {
chunk_words += len / 4;
} else {
runs.push((a, at, len));
at += (len as u64).next_multiple_of(16);
run_bytes += len as u64;
run_count += 1;
}
}
if chunk_words > 0 {
word_chunks.push((from, chunk, words as u64));
words += chunk_words;
}
}
let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum();
copies.push(Copy { runs, pairs: (at, words as u32) });
let pairs_at = at;
for entry in &mut word_chunks[chunk_start..] {
entry.2 = pairs_at + entry.2 * 8;
}
copies.push(Copy { runs, pairs: (pairs_at, words as u32) });
total_words += words as u64;
at += (words as u64 * 8).next_multiple_of(16);
}
if at == 0 {
return None;
}
let memory = memory(host, at)?;
let mut moves: Vec<(usize, usize, usize)> = Vec::new();
let mut work: Vec<(usize, &[(usize, usize)], usize)> = Vec::new();
for ((shadow, ranges), copy) in dirty.iter().zip(&copies) {
let mut moves: Vec<(usize, usize, usize)> = Vec::with_capacity(run_count as usize);
for ((shadow, _), copy) in dirty.iter().zip(&copies) {
let from = shadow.card_data() as usize;
moves.extend(copy.runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n)));
// (80,000 runs of some words a frame: in pieces of work.)
let mut to = memory.data + copy.pairs.0 as usize;
for ranges in ranges.chunks(RUNS_AT_A_TIME) {
let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum();
if words > 0 {
work.push((from, ranges, to));
to += words * 8;
}
}
}
let mem_data = memory.data;
let one = |i: usize| {
let (from, ranges, to) = work[i];
let mut to = to as *mut [u32; 2];
for &(a, b) in ranges.iter().filter(|r| short(r)) {
let (from, ranges, rel_to) = word_chunks[i];
let mut to = (mem_data + rel_to as usize) as *mut [u32; 2];
for &(a, b) in ranges.iter().filter(|r| is_short(r)) {
for offset in (a..b).step_by(4) {
// SAFETY: inside the copy's mapping (its CPU side, which
// the thread that asked, and waits, alone writes in these
@@ -276,15 +292,20 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, us
}
}
};
crate::land::each_under(work.len(), &one);
STATS[0].fetch_add(moves.iter().map(|m| m.2 as u64).sum(), Ordering::Relaxed);
STATS[1].fetch_add(moves.len() as u64, Ordering::Relaxed);
STATS[2].fetch_add(copies.iter().map(|c| u64::from(c.pairs.1)).sum(), Ordering::Relaxed);
crate::land::each_under(work_len(&word_chunks), &one);
STATS[0].fetch_add(run_bytes, Ordering::Relaxed);
STATS[1].fetch_add(run_count, Ordering::Relaxed);
STATS[2].fetch_add(total_words, Ordering::Relaxed);
crate::shadow::copy_all(moves);
STATS[3].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed);
Some(Own { memory, copies })
}
#[inline]
fn work_len<T>(chunks: &[T]) -> usize {
chunks.len()
}
impl Own {
/// Records the sends into `list`; the copies that `looked` says are in
/// `COPY_DEST`, the others in the common state. Those with a "before" are
@@ -315,7 +336,7 @@ impl Own {
}
state = Some(write);
}
let hashed = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
let hashed = shadow.has_card_before();
if let Some(was) = state
&& hashed
&& (!copy.runs.is_empty() || copy.pairs.1 > 0)
+115 -71
View File
@@ -41,18 +41,17 @@ pub(crate) struct Shadow {
start: u64,
len: u64,
/// Per page of title memory from `start`'s on: the write-watch asking
/// after which it was last copied (0: never).
copied: Mutex<Vec<u64>>,
/// Two ranges of title memory taken whole, the last one and the longest,
/// and the asking after which each was ([`Shadow::copy_stale`]). A page
/// a range holds in part cannot say so in `copied`. Locked inside
/// `copied`'s lock.
ranged: Mutex<[(usize, usize, u64); 2]>,
/// after which it was last copied (0: never), paired under the same lock
/// with the two ranges taken whole (last and longest, with their asking).
copied: Mutex<(Vec<u64>, [(usize, usize, u64); 2])>,
/// Whether the memory is write-watched: unknown, yes, no.
watched: AtomicU8,
/// Ranges shaders of a submission not yet copied back may be writing:
/// title memory there is older than the copy.
pending: Mutex<Vec<(usize, usize)>>,
/// Lock-free mirror of `pending.len()` so refreshes and filters skip
/// locking `pending` when no shader writes are in flight for this copy.
pending_len: AtomicUsize,
/// With [`relay`]: how many submissions not yet copied back declared
/// each range of `pending` ([`Flights`]). Locked inside `pending`'s
/// lock.
@@ -118,7 +117,9 @@ struct Card {
/// started, in the card's memory too: made when shader writes are
/// first declared for the copy, and compared with the card's side, on
/// the card, after each submission that declares some.
before: Mutex<Option<ID3D12Resource>>,
before: std::sync::OnceLock<ID3D12Resource>,
/// Serializes one-time creation of `before`.
before_init: Mutex<()>,
/// Offsets of the copy whose bytes changed on the CPU's side and have
/// not gone to the card's side yet.
dirty: Mutex<Vec<(usize, usize)>>,
@@ -320,8 +321,8 @@ pub(crate) fn card_room_kept() -> u64 {
card_limits().1.min(SEEN).saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed))
}
/// The copies in the card's memory.
static CARDED: Mutex<Vec<std::sync::Weak<Shadow>>> = Mutex::new(Vec::new());
/// The copies in the card's memory, with their title address range `(start, end)`.
static CARDED: Mutex<Vec<(std::sync::Weak<Shadow>, usize, usize)>> = Mutex::new(Vec::new());
/// The copies in the card's memory whose `touched` was set since
/// [`card_dirty`] last took them (a copy may be on it twice). Before, each
@@ -339,9 +340,13 @@ fn carded(shadow: &Arc<Shadow>) {
};
let _ = card.me.set(Arc::downgrade(shadow));
let mut carded = CARDED.lock().unwrap_or_else(|e| e.into_inner());
carded.push(Arc::downgrade(shadow));
carded.push((
Arc::downgrade(shadow),
shadow.start as usize,
(shadow.start + shadow.len) as usize,
));
if carded.len() >= 2 * KEPT.load(Ordering::Relaxed).max(1024) {
carded.retain(|weak| weak.strong_count() > 0);
carded.retain(|(weak, _, _)| weak.strong_count() > 0);
KEPT.store(carded.len(), Ordering::Relaxed);
}
}
@@ -364,7 +369,7 @@ pub(crate) fn card_stats() -> [u64; 10] {
for (i, stat) in CARD_STATS.iter().enumerate() {
out[i] = stat.swap(0, Ordering::Relaxed);
}
out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64;
out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|(w, _, _)| w.strong_count() > 0).count() as u64;
out[8] = CARD_BYTES[0].load(Ordering::Relaxed)
+ WINDOW_CARD_BYTES.load(Ordering::Relaxed)
+ WINDOW_MAPPED_BYTES.load(Ordering::Relaxed);
@@ -733,7 +738,7 @@ pub(crate) fn stale_pages(most: usize, say: &mut dyn FnMut(&Shadow, usize, usize
continue;
};
let written: std::collections::HashMap<usize, u64> = written.into_iter().collect();
let copied = shadow.copied.lock().unwrap_or_else(|e| e.into_inner()).clone();
let copied = shadow.copied.lock().unwrap_or_else(|e| e.into_inner()).0.clone();
for (i, &at) in copied.iter().enumerate() {
let page = start / PAGE + i;
if at == 0 || written.get(&page).is_some_and(|&w| w > at) {
@@ -784,12 +789,24 @@ pub(crate) fn copy_all(copies: Vec<(usize, usize, usize)>) {
/// CPU side held the same before or not. Left out is what shaders in the air
/// may be writing (such a copy waits for them, or is done on the card).
pub(crate) fn send_copied(dst: usize, len: usize) {
for shadow in carded_copies() {
let dst_end = dst.saturating_add(len);
let hits: Vec<Arc<Shadow>> = CARDED
.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
.filter(|&&(_, start, end)| dst < end && start < dst_end)
.filter_map(|(w, _, _)| w.upgrade())
.collect();
for shadow in hits {
let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize);
let (from, to) = (dst.max(start), (dst + len).min(end));
let (from, to) = (dst.max(start), dst_end.min(end));
if from >= to {
continue;
}
if shadow.pending_len.load(Ordering::Acquire) == 0 {
shadow.copy(from, to);
continue;
}
let busy: Vec<(usize, usize)> =
shadow.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().copied().filter(|&(a, b)| a < to && b > from).collect();
for (a, b) in outside(from, to, busy) {
@@ -800,7 +817,7 @@ pub(crate) fn send_copied(dst: usize, len: usize) {
/// The copies in the card's memory (diagnostics: `crate::host::upcheck`).
pub(crate) fn carded_copies() -> Vec<Arc<Shadow>> {
CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter_map(std::sync::Weak::upgrade).collect()
CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter_map(|(w, _, _)| w.upgrade()).collect()
}
/// Ranges in order, those that overlap or touch as one.
@@ -2937,7 +2954,7 @@ impl Drop for Shadow {
} else {
CARD_BYTES[0].fetch_sub(card.size, Ordering::Relaxed);
}
if card.before.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() {
if card.before.get().is_some() {
CARD_BYTES[1].fetch_sub(card_hash_bytes(card.size), Ordering::Relaxed);
}
}
@@ -3211,7 +3228,7 @@ pub(crate) fn window_use() -> [u64; 8] {
let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner());
for s in loose.values() {
let copied = s.copied.lock().unwrap_or_else(|e| e.into_inner());
let pages = copied.iter().filter(|&&at| at != 0).count() as u64;
let pages = copied.0.iter().filter(|&&at| at != 0).count() as u64;
out[0] += (pages * PAGE as u64).min(s.len);
if crate::host::references(&s.buffer) > 1 {
out[1] += 1;
@@ -3409,10 +3426,10 @@ impl Shadow {
gpu,
start,
len,
copied: Mutex::new(vec![0; pages as usize]),
ranged: Mutex::default(),
copied: Mutex::new((vec![0; pages as usize], Default::default())),
watched: AtomicU8::new(0),
pending: Mutex::default(),
pending_len: AtomicUsize::new(0),
flights: Mutex::default(),
before: Mutex::default(),
merging: RwLock::default(),
@@ -3525,6 +3542,7 @@ impl Shadow {
// lists).
if self.card.is_some() {
pending.push(range);
self.pending_len.store(pending.len(), Ordering::Release);
return;
}
// The parts no declared range holds yet: their bytes are taken now,
@@ -3549,6 +3567,7 @@ impl Shadow {
parts = rest;
}
pending.push(range);
self.pending_len.store(pending.len(), Ordering::Release);
let taken: usize = parts.iter().map(|&(from, to)| to.saturating_sub(from)).sum();
BACK_CLASS[usize::from(!self.window)].fetch_add(taken as u64, Ordering::Relaxed);
let total = self.len as usize;
@@ -3838,6 +3857,7 @@ impl Shadow {
} else {
pending.retain(|r| !ranges.contains(r));
}
self.pending_len.store(pending.len(), Ordering::Release);
if !pending.is_empty() || self.card.is_some() {
return;
}
@@ -3894,13 +3914,17 @@ impl Shadow {
/// Whether shaders of a submission not yet copied back may be writing
/// the copy.
#[inline]
pub(crate) fn writes_pending(&self) -> bool {
!self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
self.pending_len.load(Ordering::Acquire) != 0
}
/// 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 {
if self.pending_len.load(Ordering::Acquire) == 0 {
return false;
}
self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from)
}
@@ -3918,7 +3942,7 @@ impl Shadow {
pub(crate) fn stale_under_writes(&self, address: usize, len: usize) -> bool {
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
let (from, to) = (address.max(start), (address + len).min(end));
if from >= to {
if from >= to || self.pending_len.load(Ordering::Acquire) == 0 {
return false;
}
let busy: Vec<(usize, usize)> = self
@@ -3938,7 +3962,7 @@ impl Shadow {
let base = start / PAGE;
let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) {
Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(),
Some((_, written)) => !stale_pages_in(base, &copied.0, a, e, &written).is_empty(),
None => true,
})
}
@@ -3962,7 +3986,7 @@ impl Shadow {
pub(crate) fn merge_under_writes(&self, address: usize, len: usize, runs_left: &mut usize) -> bool {
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
let (from, to) = (address.max(start), (address + len).min(end));
if from >= to {
if from >= to || self.pending_len.load(Ordering::Acquire) == 0 {
return false;
}
let busy: Vec<(usize, usize)> = self
@@ -3999,7 +4023,7 @@ impl Shadow {
};
let stale: Vec<usize> = {
let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
stale_pages_in(base, &copied, a, e, &written)
stale_pages_in(base, &copied.0, a, e, &written)
};
if stale.is_empty() {
continue;
@@ -4074,7 +4098,7 @@ impl Shadow {
{
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
for page in taken {
if let Some(at) = copied.get_mut(page - base) {
if let Some(at) = copied.0.get_mut(page - base) {
*at = now;
}
}
@@ -4158,30 +4182,32 @@ impl Shadow {
if from >= to {
return 0;
}
let mut busy: Vec<(usize, usize)> = self
.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
.copied()
.filter(|&(a, e)| a < to && e > from)
.collect();
if !busy.is_empty() {
// Around ranges shaders are writing: the gaps, each as below
// (in the world most submissions have such ranges; copying the
// gaps whole cost ~1 s per frame).
busy.sort_unstable();
let (mut at, mut bytes) = (from, 0);
for (a, e) in busy {
if a > at {
bytes += self.update_free(at, a);
if self.pending_len.load(Ordering::Acquire) != 0 {
let mut busy: Vec<(usize, usize)> = self
.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
.copied()
.filter(|&(a, e)| a < to && e > from)
.collect();
if !busy.is_empty() {
// Around ranges shaders are writing: the gaps, each as below
// (in the world most submissions have such ranges; copying the
// gaps whole cost ~1 s per frame).
busy.sort_unstable();
let (mut at, mut bytes) = (from, 0);
for (a, e) in busy {
if a > at {
bytes += self.update_free(at, a);
}
at = at.max(e);
}
at = at.max(e);
if at < to {
bytes += self.update_free(at, to);
}
return bytes;
}
if at < to {
bytes += self.update_free(at, to);
}
return bytes;
}
self.update_free(from, to)
}
@@ -4202,11 +4228,14 @@ impl Shadow {
return false;
}
// Around ranges shaders are writing the refresh asks gap by gap.
if self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) {
if self.pending_len.load(Ordering::Acquire) != 0
&& self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from)
{
return false;
}
let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
let same = crate::watch::nothing_new(from, to, start / PAGE, &copied, self.ranged(from, to));
let ranged = Self::ranged_in(&copied.1, from, to);
let same = crate::watch::nothing_new(from, to, start / PAGE, &copied.0, ranged);
#[cfg(feature = "diagnostics")]
if same {
use crate::copystat::{C, add};
@@ -4217,9 +4246,9 @@ impl Shadow {
}
/// The latest asking after which a range that holds `[from, to)` was
/// taken whole (0: none is known). The caller holds `copied`'s lock.
fn ranged(&self, from: usize, to: usize) -> u64 {
let ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner());
/// taken whole (0: none is known).
#[inline]
fn ranged_in(ranged: &[(usize, usize, u64); 2], from: usize, to: usize) -> u64 {
ranged.iter().filter(|r| r.0 <= from && to <= r.1).map(|r| r.2).max().unwrap_or(0)
}
@@ -4322,7 +4351,7 @@ impl Shadow {
// of the heap's buffer views alone two ends for each of 4,400
// copies, every frame. A range that was taken whole, and not written
// since, is as it was.
let ranged = if crate::watch::light() { self.ranged(from, to) } else { 0 };
let ranged = if crate::watch::light() { Self::ranged_in(&copied.1, from, to) } else { 0 };
let (mut runs, mut run) = (Vec::new(), None::<(usize, bool)>);
// Pages taken before and written since: in the order of their runs.
let mut again_at: Vec<(usize, u64)> = Vec::new();
@@ -4335,7 +4364,7 @@ impl Shadow {
}
_ => 0,
};
let at = &mut copied[page - base];
let at = &mut copied.0[page - base];
let taken = (*at).max(ranged);
if taken == 0 || write > taken {
// A page only partly in the range is copied in part: it
@@ -4368,7 +4397,7 @@ impl Shadow {
let bytes = self.take_all(runs);
if crate::watch::light() {
// All of the range is in the copy as of this asking.
let mut ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner());
let ranged = &mut copied.1;
ranged[0] = (from, to, now);
if to - from >= ranged[1].1 - ranged[1].0 {
ranged[1] = (from, to, now);
@@ -4501,7 +4530,7 @@ impl Shadow {
}
return self.copy(from, to);
};
let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none();
let whole = !known && card.before.get().is_none();
let start = self.start as usize;
TITLE.with_borrow_mut(|title| {
title.resize(PAGE, 0);
@@ -4659,11 +4688,17 @@ impl Shadow {
self.card.as_ref().map_or_else(Vec::new, |c| c.dirty.lock().unwrap_or_else(|e| e.into_inner()).clone())
}
/// Whether this copy is in the card's memory and has a "before" hash buffer.
#[inline]
pub(crate) fn has_card_before(&self) -> bool {
self.card.as_ref().is_some_and(|card| card.before.get().is_some())
}
/// Of a copy in the card's memory: the CPU's side (PC memory), the
/// card side's bytes from before if made yet, and their size.
pub(crate) fn card_sides(&self) -> Option<(&ID3D12Resource, Option<ID3D12Resource>, u64)> {
let card = self.card.as_ref()?;
let before = card.before.lock().unwrap_or_else(|e| e.into_inner()).clone();
let before = card.before.get().cloned();
Some((&card.staging, before, card.size))
}
@@ -4676,15 +4711,19 @@ impl Shadow {
let Some(card) = &self.card else {
return false;
};
let mut before = card.before.lock().unwrap_or_else(|e| e.into_inner());
if before.is_some() {
if card.before.get().is_some() {
return false;
}
*before = make(card.size);
if before.is_some() {
CARD_BYTES[1].fetch_add(card_hash_bytes(card.size), Ordering::Relaxed);
let _init = card.before_init.lock().unwrap_or_else(|e| e.into_inner());
if card.before.get().is_some() {
return false;
}
before.is_some()
let Some(made) = make(card.size) else {
return false;
};
let _ = card.before.set(made);
CARD_BYTES[1].fetch_add(card_hash_bytes(card.size), Ordering::Relaxed);
true
}
/// The declared range `[address, end)` as the compare on the card
@@ -4897,7 +4936,8 @@ impl Shadow {
if card {
shadow.card = Some(Card {
staging: none(),
before: Mutex::default(),
before: std::sync::OnceLock::new(),
before_init: Mutex::default(),
dirty: Mutex::default(),
sent: Mutex::default(),
touched: Default::default(),
@@ -5028,7 +5068,7 @@ impl Shadow {
return false;
};
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
let Some(at) = copied.get_mut(page) else {
let Some(at) = copied.0.get_mut(page) else {
return false;
};
let held = *at != 0 && *at >= before && crate::watch::block_published(block);
@@ -5054,7 +5094,8 @@ mod land_tests {
let mut shadow = Shadow::new(buffer.clone(), data, 0, title as u64, len as u64);
shadow.card = Some(Card {
staging: buffer,
before: Mutex::default(),
before: std::sync::OnceLock::new(),
before_init: Mutex::default(),
dirty: Mutex::default(),
sent: Mutex::default(),
touched: Default::default(),
@@ -5499,7 +5540,8 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> {
);
let card = Card {
staging: buffer,
before: Mutex::default(),
before: std::sync::OnceLock::new(),
before_init: Mutex::default(),
dirty: Mutex::default(),
sent: Mutex::default(),
touched: Default::default(),
@@ -5728,7 +5770,8 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> {
shadow.changes_only.store(true, Ordering::Relaxed);
shadow.card = Some(Card {
staging,
before: Mutex::default(),
before: std::sync::OnceLock::new(),
before_init: Mutex::default(),
dirty: Mutex::default(),
sent: Mutex::default(),
touched: Default::default(),
@@ -5818,7 +5861,8 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Sha
crate::host::name(&on_card, || format!("title memory {start:#x}+{len:#x} on the card"));
let card = Card {
staging: buffer,
before: Mutex::default(),
before: std::sync::OnceLock::new(),
before_init: Mutex::default(),
dirty: Mutex::default(),
sent: Mutex::default(),
touched: Default::default(),
+111 -27
View File
@@ -319,22 +319,52 @@ const AHEAD_GAP: usize = (8 << 20) / PAGE;
/// The most one asking covers (its answer needs 8 bytes per 4 KiB page).
const AHEAD_MAX: usize = (1 << 30) / PAGE;
/// Fast atomic mirror of `JOURNAL.kept`: true while a submission's `ask_once`
/// covers its ranges so per-flush `ask_ahead`/`ask_ahead_done` skip locking
/// `JOURNAL` and building range vectors.
static AHEAD_KEPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Whether the submission's one-shot asking (`ask_once`) already covers
/// write-watch queries, so per-flush `ask_ahead` calls are no-ops.
#[inline]
pub(crate) fn kept_active() -> bool {
AHEAD_KEPT.load(std::sync::atomic::Ordering::Acquire)
}
fn sort_merge_ahead(ranges: &mut Vec<(usize, usize)>) {
if ranges.len() <= 1 {
return;
}
ranges.sort_unstable();
let mut write = 0usize;
for read in 1..ranges.len() {
let (a, b) = ranges[read];
if a <= ranges[write].1 {
ranges[write].1 = ranges[write].1.max(b);
} else {
write += 1;
ranges[write] = (a, b);
}
}
ranges.truncate(write + 1);
}
#[inline]
fn ahead_contains(ahead: &[(usize, usize)], first: usize, last: usize) -> bool {
let idx = ahead.partition_point(|&(a, _)| a <= first);
idx > 0 && ahead[idx - 1].1 >= last
}
/// Asks the kernel about many ranges `(start, end)` at once, before the
/// [`writes`] of each: ranges close together are one asking, and `writes`
/// then answers from the journal until [`ask_ahead_done`]. The world's
/// Whether the submission's one-shot asking (`ask_once`) already covers
/// write-watch queries, so per-flush `ask_ahead` calls are no-ops.
pub(crate) fn kept_active() -> bool {
journal().kept
}
/// submissions refresh thousands of host copies (6,664 askings a frame,
/// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are
/// left to `writes`.
pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) {
// The submission's one asking stands ([`ask_once`]): check before
// allocating, filtering, or sorting thousands of ranges.
if journal().kept {
if kept_active() {
return;
}
let mut pieces: Vec<(usize, usize)> = ranges
@@ -365,6 +395,7 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) {
ask_run(&pieces[i..k], &mut asked, &mut written);
i = k;
}
sort_merge_ahead(&mut asked);
note_hot(&written);
let mut j = journal_mut();
j.ahead_asked = next_asking();
@@ -513,6 +544,9 @@ fn ask_early(every: std::time::Duration) {
/// The submission's refreshes are done: `writes` asks the kernel again.
pub(crate) fn ask_ahead_done() {
if kept_active() {
return;
}
let mut j = journal_mut();
if !j.kept {
j.ahead.clear();
@@ -569,18 +603,24 @@ fn ask_rest(ranges: &[(usize, usize)]) {
// askings a frame with the switch on, as without it). They are asked
// here, once; what is not write-watched stays with `writes`.
let mut written = Vec::new();
let mut extra = Vec::new();
for &(start, end) in ranges {
if start >= end || published(start, end) {
continue;
}
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
if !ahead.iter().any(|&(a, b)| a <= first && last <= b)
if !ahead_contains(&ahead, first, last)
&& !extra.iter().any(|&(a, b)| a <= first && last <= b)
&& let Some(pages) = kernel_written(first, last)
{
written.extend(pages);
ahead.push((first, last));
extra.push((first, last));
}
}
if !extra.is_empty() {
ahead.extend(extra);
sort_merge_ahead(&mut ahead);
}
note_hot(&written);
let mut j = journal_mut();
// A number of its own, and the one this asking stands under: between
@@ -592,13 +632,19 @@ fn ask_rest(ranges: &[(usize, usize)]) {
for (page, parts) in written {
j.note(page, parts, now);
}
j.kept = !ahead.is_empty();
let kept = !ahead.is_empty();
j.kept = kept;
j.ahead = ahead;
AHEAD_KEPT.store(kept, std::sync::atomic::Ordering::Release);
}
/// The submission's one asking stands no longer: its refreshes are done,
/// or title memory was written in a way the journal was not told.
pub(crate) fn ask_once_end() {
if !kept_active() {
return;
}
AHEAD_KEPT.store(false, std::sync::atomic::Ordering::Release);
let mut j = journal_mut();
if j.kept {
j.kept = false;
@@ -666,9 +712,7 @@ fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written:
pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> {
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
let j = journal();
j.ahead
.iter()
.any(|&(a, b)| a <= first && last <= b)
ahead_contains(&j.ahead, first, last)
.then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect()))
}
@@ -687,7 +731,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
let of = |j: &Journal| -> Vec<(usize, u64)> { j.written.range(first..last).map(|(&p, &w)| (p, w)).collect() };
// Asked ahead with the submission's other ranges: the journal has it.
let ahead = |j: &Journal| j.ahead.iter().any(|&(a, b)| a <= first && last <= b).then(|| (j.ahead_asked, of(j)));
let ahead = |j: &Journal| ahead_contains(&j.ahead, first, last).then(|| (j.ahead_asked, of(j)));
if let Some(known) = ahead(&journal()) {
return Some(known);
}
@@ -771,7 +815,7 @@ pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64],
crate::faultbook::note(crate::faultbook::What::Known, first, last, 1);
}
let j = journal();
if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) {
if !known && !ahead_contains(&j.ahead, first, last) {
return false;
}
let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else {
@@ -1472,7 +1516,7 @@ pub(crate) fn asks() -> [u64; 13] {
}
/// The guards' lock, the wait for it counted.
fn guards_timed() -> std::sync::MutexGuard<'static, Guards> {
fn guards_timed() -> std::sync::RwLockWriteGuard<'static, Guards> {
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
let g = guards();
@@ -1481,6 +1525,16 @@ fn guards_timed() -> std::sync::MutexGuard<'static, Guards> {
g
}
/// The guards' shared read lock, the wait for it counted.
fn guards_read_timed() -> std::sync::RwLockReadGuard<'static, Guards> {
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
let g = guards_read();
#[cfg(feature = "diagnostics")]
tally(7, started.elapsed().as_nanos() as u64);
g
}
/// A set of blocks, a bit each: a fault, or a look at a range of thousands of
/// blocks, is a few words of it and no walk through a tree of every guarded
/// block there is.
@@ -1746,7 +1800,7 @@ impl Guards {
}
}
static GUARDS: Mutex<Guards> = Mutex::new(Guards {
static GUARDS: std::sync::RwLock<Guards> = std::sync::RwLock::new(Guards {
protected: Blocks::new(),
clean: Blocks::new(),
absent: Blocks::new(),
@@ -1760,17 +1814,29 @@ static GUARDS: Mutex<Guards> = Mutex::new(Guards {
/// The guards' lock, with what faults opened without it settled first
/// ([`settle`]).
fn guards() -> std::sync::MutexGuard<'static, Guards> {
let mut g = match GUARDS.try_lock() {
fn guards() -> std::sync::RwLockWriteGuard<'static, Guards> {
let mut g = match GUARDS.try_write() {
Ok(g) => g,
// (Held by this, whoever panicked with it: not to be asked for again.)
Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
Err(std::sync::TryLockError::WouldBlock) => waited(3, || GUARDS.lock().unwrap_or_else(|e| e.into_inner())),
Err(std::sync::TryLockError::WouldBlock) => waited(3, || GUARDS.write().unwrap_or_else(|e| e.into_inner())),
};
settle(&mut g);
g
}
/// Shared read lock on the guards, settling any unlocked faults first.
fn guards_read() -> std::sync::RwLockReadGuard<'static, Guards> {
if TO_SETTLE.load(std::sync::atomic::Ordering::SeqCst) != 0 {
drop(guards());
}
match GUARDS.try_read() {
Ok(g) => g,
Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
Err(std::sync::TryLockError::WouldBlock) => waited(3, || GUARDS.read().unwrap_or_else(|e| e.into_inner())),
}
}
/// The 4 KiB pages of title memory that what shaders wrote was put into,
/// and the frame it last was: in pieces made when first needed and never let
/// go. Some 20,000 pages a frame are noted by the relay and the landing
@@ -1964,7 +2030,7 @@ pub(crate) fn written_since_taken(at: usize, len: usize) -> bool {
if len == 0 {
return false;
}
let g = guards();
let g = guards_read();
(at / BLOCK..=(at + len - 1) / BLOCK)
.all(|b| !g.clean.contains(b) && !g.absent.contains(b) && !g.protected.contains(b))
}
@@ -1984,7 +2050,7 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1"))
&& (PROTECTED.any(first, first + 1) || {
let g = guards_timed();
let g = guards_read_timed();
g.protected.contains(first) || g.absent.contains(first)
});
if !known && !is_view(start, end) {
@@ -1996,8 +2062,23 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
// other thread asks about it: `ASKING`); what the runtime tells meanwhile
// takes the block out of the set, and it is looked at as any other.
let unsure: Vec<usize> = {
let g = guards_timed();
if g.clean.range(first..last).count() == last - first && !BESIDE.any(first, last) && !unsettled(first, last) {
let g = guards_read_timed();
// Fast path under shared read lock: every block in `first..last` is
// either clean (guarded, not BESIDE) or a known placeholder hole
// (`absent & held`), and none is OPENING/TOLD, so no VirtualQuery or
// write lock is needed.
let mut all_clean_or_held = true;
for word in first / 64..last.div_ceil(64) {
let mask = in_word(word * 64, first, last);
let ok = ((g.clean.word(word) & !BESIDE.word(word)) | (g.absent.word(word) & g.held.word(word)))
& !OPENING.word(word)
& !TOLD.word(word);
if (!ok & mask) != 0 {
all_clean_or_held = false;
break;
}
}
if all_clean_or_held {
// Nothing written, mapped or new since the range was last taken.
#[cfg(feature = "diagnostics")]
tally(3, 1);
@@ -2544,12 +2625,15 @@ pub fn title_memory_written(at: usize, len: usize, pages: bool) {
}
}
{
let mut g = guards();
let guarded = g.protected.range(at / BLOCK..end.div_ceil(BLOCK)).count() as u64;
let guarded = {
let g = guards_read();
g.protected.range(at / BLOCK..end.div_ceil(BLOCK)).count() as u64
};
if pages {
WRITTEN[2].fetch_add(guarded, Relaxed);
}
if mode & 1 != 0 && guarded != 0 {
let mut g = guards();
open(&mut g, at, end);
}
}
@@ -2911,7 +2995,7 @@ fn allocation_end(at: usize, inside: usize) -> usize {
/// Tells what keeps track of what title memory shows; the guards, with no
/// block of the range known unmapped.
fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, Guards> {
fn title_memory_changed(at: usize, len: usize) -> std::sync::RwLockWriteGuard<'static, Guards> {
// A placed texture there arrives, goes or changes with no descriptor
// written.
crate::descriptor::host::remapped(at, len);