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

+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(),