From 600130d978364f473da27c553694c895c60a6cf9 Mon Sep 17 00:00:00 2001 From: wike1701 Date: Sat, 28 Nov 2026 02:53:10 +0100 Subject: [PATCH 1/2] perf(gpu): lock-free no-op refreshes, thin-worker refresh coalescing, and AVX2 copy diff --- crates/victory-gpu/src/host.rs | 151 +++++++++++++++++++++----- crates/victory-gpu/src/shadow.rs | 178 ++++++++++++++++++++++++------- crates/victory-gpu/src/watch.rs | 100 ++++++++++++++--- 3 files changed, 347 insertions(+), 82 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 2db060a9d9..61fa4740b3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2863,6 +2863,11 @@ struct Deferred { /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. refreshed: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, + /// Per-shadow coalesced span `(copies_index, from, to)` in the current + /// uninterrupted segment (cleared on title writes and per-shadow on GPU + /// writes): lets `VICTORY_THIN` workers merge overlapping/adjacent + /// refreshes before the submitting thread ever walks `copies`. + refreshed_span: std::collections::HashMap>, /// Ranges declared written by shaders since the list last wrote title /// memory (host copy, address, bytes): declaring them again would /// change nothing. @@ -2915,6 +2920,7 @@ impl Deferred { /// date before them is not any more. fn title_written(&mut self) { self.refreshed.clear(); + self.refreshed_span.clear(); self.gpu_written.clear(); self.filled.clear(); } @@ -7152,6 +7158,7 @@ impl HostList { deferred .copies .splice(at..at, found.into_iter().map(|(shadow, from, to)| Step::Refresh(shadow, from as usize, (to - from) as usize))); + deferred.refreshed_span.clear(); } /// A new host list for one of the title's lists (`crate::list::detach`), @@ -7971,11 +7978,33 @@ impl HostList { len: usize, ) { let mut deferred = self.deferred(); - let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); + let deferred = &mut *deferred; + let ptr = std::sync::Arc::as_ptr(shadow) as usize; + let end = address.saturating_add(len); + if let Some(&mut (idx, ref mut from, ref mut to)) = deferred.refreshed_span.get_mut(&ptr) + && address <= *to + && end >= *from + { + if *from <= address && end <= *to { + return; + } + let new_from = (*from).min(address); + let new_to = (*to).max(end); + if let Some(Step::Refresh(_, a, l)) = deferred.copies.get_mut(idx) { + *a = new_from; + *l = new_to - new_from; + *from = new_from; + *to = new_to; + return; + } + } + let key = (ptr, address, len); if deferred.refreshed.insert(key) { + let idx = deferred.copies.len(); deferred .copies .push(Step::Refresh(shadow.clone(), address, len)); + deferred.refreshed_span.insert(ptr, (idx, address, end)); } } @@ -7991,7 +8020,9 @@ impl HostList { len: usize, ) { let mut deferred = self.deferred(); - let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); + let ptr = std::sync::Arc::as_ptr(shadow) as usize; + deferred.refreshed_span.remove(&ptr); + let key = (ptr, address, len); if deferred.gpu_written.insert(key) || !declare_once() { deferred.copies.push(Step::GpuWrite(shadow.clone(), address, len)); } @@ -9346,28 +9377,56 @@ impl Batch { let many = spans.len() > FEW; if !many { let all = spans.len(); - spans.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + let journal = crate::watch::read_journal(); + spans.retain(|(shadow, from, to)| !shadow.nothing_new_with(&journal, *from, *to - *from)); + drop(journal); FLUSHES[2].fetch_add((all - spans.len()) as u64, Ordering::Relaxed); } - let ahead = spans.len() > 1; + let ahead = spans.len() > 1 && !crate::watch::is_kept(); if ahead { let ranges: Vec<(usize, usize)> = spans.iter().filter(|r| r.0.asked_ahead()).map(|r| (r.1, r.2)).collect(); crate::watch::ask_ahead(&ranges); } FLUSHES[3].fetch_add(spans.len() as u64, Ordering::Relaxed); - // (The textures one to a thread; the copies as `VICTORY_WIDE_CHUNK` says.) - crate::shadow::wide_each_from(spans.len() + due.len(), due.len(), crate::shadow::wide_chunk(), move |i| { - // The textures first: they are the longer pieces. - let Some(i) = i.checked_sub(due.len()) else { - due[i].refresh(); - return; - }; - let (shadow, from, to) = &spans[i]; - if many && shadow.nothing_new(*from, *to - *from) { - FLUSHES[2].fetch_add(1, Ordering::Relaxed); + let due_len = due.len(); + let spans_len = spans.len(); + // Textures first (longer pieces, 1 per worker claim), then buffer + // refreshes in 32-item chunks sharing one `JournalRead` and one + // `FLUSHES[2]` increment per chunk (never holding `JournalRead` across + // `Self::update`). + if due_len > 0 { + crate::shadow::wide_each(due_len, move |i| due[i].refresh()); + } + crate::shadow::wide_chunks(spans_len, 32, move |range| { + if !many { + for i in range { + let (shadow, from, to) = &spans[i]; + Self::update(shadow, *from, *to); + } return; } - Self::update(shadow, *from, *to); + let mut need = [0usize; 32]; + let mut n_need = 0usize; + let mut skipped = 0u64; + { + let journal = crate::watch::read_journal(); + for i in range { + let (shadow, from, to) = &spans[i]; + if shadow.nothing_new_with(&journal, *from, *to - *from) { + skipped += 1; + } else { + need[n_need] = i; + n_need += 1; + } + } + } + if skipped > 0 { + FLUSHES[2].fetch_add(skipped, Ordering::Relaxed); + } + for &i in &need[..n_need] { + let (shadow, from, to) = &spans[i]; + Self::update(shadow, *from, *to); + } }); if ahead { crate::watch::ask_ahead_done(); @@ -9410,9 +9469,21 @@ impl Batch { } let started = std::time::Instant::now(); let before = PREPARING[0].load(Ordering::Relaxed); - crate::shadow::wide_each(due.len(), move |i| { - let (shadow, from, to) = &due[i]; - if !shadow.nothing_new(*from, *to - *from) { + crate::shadow::wide_chunks(due.len(), 32, move |range| { + let mut need = [0usize; 32]; + let mut n_need = 0usize; + { + let journal = crate::watch::read_journal(); + for i in range { + let (shadow, from, to) = &due[i]; + if !shadow.nothing_new_with(&journal, *from, *to - *from) { + need[n_need] = i; + n_need += 1; + } + } + } + for &i in &need[..n_need] { + let (shadow, from, to) = &due[i]; Self::update(shadow, *from, *to); } }); @@ -9490,13 +9561,15 @@ impl Batch { if light && self.refreshes.len() <= FEW { let started = std::time::Instant::now(); let all = self.refreshes.len(); - self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + let journal = crate::watch::read_journal(); + self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new_with(&journal, *from, *to - *from)); + drop(journal); PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed); } // 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::is_kept(); if ahead { let started = std::time::Instant::now(); let ranges: Vec<(usize, usize)> = self @@ -9516,15 +9589,41 @@ impl Batch { let before = PREPARING[0].load(Ordering::Relaxed); FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed); if light { - // A number to a free thread, not a job to each copy. + // Chunked claiming: one `JournalRead` and one `FLUSHES[2]` + // increment per 32-item chunk instead of per item. let refreshes = std::mem::take(&mut self.refreshes); - crate::shadow::wide_each_from(refreshes.len(), 0, crate::shadow::wide_chunk(), move |i| { - let (shadow, from, to) = &refreshes[i]; - if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) { - FLUSHES[2].fetch_add(1, Ordering::Relaxed); + let len = refreshes.len(); + let check = len > FEW; + crate::shadow::wide_chunks(len, 32, move |range| { + if !check { + for i in range { + let (shadow, from, to) = &refreshes[i]; + Self::update(shadow, *from, *to); + } return; } - Self::update(shadow, *from, *to); + let mut need = [0usize; 32]; + let mut n_need = 0usize; + let mut skipped = 0u64; + { + let journal = crate::watch::read_journal(); + for i in range { + let (shadow, from, to) = &refreshes[i]; + if shadow.nothing_new_with(&journal, *from, *to - *from) { + skipped += 1; + } else { + need[n_need] = i; + n_need += 1; + } + } + } + if skipped > 0 { + FLUSHES[2].fetch_add(skipped, Ordering::Relaxed); + } + for &i in &need[..n_need] { + let (shadow, from, to) = &refreshes[i]; + Self::update(shadow, *from, *to); + } }); } else { let jobs: Vec> = self diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 215be62bf4..d10ec0ea9f 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -16,7 +16,7 @@ //! indexed heaps keep what their first use copied. use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, RwLock}; use windows::Win32::Graphics::Direct3D12::ID3D12Resource; @@ -41,13 +41,20 @@ 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>, + /// after which it was last copied (0: never). Fixed-size and atomic so + /// [`Shadow::nothing_new_with`] reads it lock-free; writers serialize on + /// `copy_lock` and store `now` with `Release` only after copying bytes. + copied: Box<[AtomicU64]>, + /// Serializes writers updating `copied` and `ranged` (`copy_stale`, + /// `merge_under_writes`, `landed`). + copy_lock: Mutex<()>, /// 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. + /// `copy_lock`. ranged: Mutex<[(usize, usize, u64); 2]>, + /// Fast-path flag: `true` once `ranged` holds any non-zero range. + ranged_any: AtomicBool, /// Whether the memory is write-watched: unknown, yes, no. watched: AtomicU8, /// Ranges shaders of a submission not yet copied back may be writing: @@ -738,8 +745,8 @@ pub(crate) fn stale_pages(most: usize, say: &mut dyn FnMut(&Shadow, usize, usize continue; }; let written: std::collections::HashMap = written.into_iter().collect(); - let copied = shadow.copied.lock().unwrap_or_else(|e| e.into_inner()).clone(); - for (i, &at) in copied.iter().enumerate() { + for (i, slot) in shadow.copied.iter().enumerate() { + let at = slot.load(Ordering::Acquire); let page = start / PAGE + i; if at == 0 || written.get(&page).is_some_and(|&w| w > at) { continue; @@ -1928,6 +1935,7 @@ pub(crate) fn wide_each(n: usize, work: impl Fn(usize) + Send + Sync + 'static) /// nothing and 9,086 of them told so on the threads (session 2026-11-28 /// 00:45): each took its number from one counter all the threads share, and /// a flush of a few small ones woke as many threads as it had pieces. +#[allow(dead_code)] pub(crate) fn wide_chunk() -> usize { static CHUNK: std::sync::OnceLock = std::sync::OnceLock::new(); *CHUNK.get_or_init(|| { @@ -1944,6 +1952,7 @@ pub(crate) fn wide_chunk() -> usize { /// under `single` go one at a time (the long pieces: each may be a thread's /// whole share), the others `chunk` at a time, and no more threads take part /// than there are such shares. With `chunk` 1 it is [`wide_each`]. +#[allow(dead_code)] pub(crate) fn wide_each_from(n: usize, single: usize, chunk: usize, work: impl Fn(usize) + Send + Sync + 'static) { let (single, chunk) = (single.min(n), chunk.max(1)); if chunk == 1 { @@ -1991,6 +2000,34 @@ fn claim(next: &std::sync::atomic::AtomicUsize, n: usize, single: usize, chunk: } } +/// Calls `work` with disjoint contiguous chunks of `0..n` of size up to +/// `chunk`, claimed per worker with a single atomic increment: reduces +/// cache-line contention on `next` and allows per-chunk amortization of +/// shared read locks and counters. +pub(crate) fn wide_chunks(n: usize, chunk: usize, work: impl Fn(std::ops::Range) + Send + Sync + 'static) { + if n == 0 { + return; + } + let chunk = chunk.max(1); + let next = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let work = Arc::new(work); + let threads = (wide_threads() + 1).min(n.div_ceil(chunk)); + let jobs = (0..threads) + .map(|_| { + let (next, work) = (next.clone(), work.clone()); + Box::new(move || { + loop { + let start = next.fetch_add(chunk, Ordering::Relaxed); + if start >= n { + break; + } + work(start..(start + chunk).min(n)); + } + }) as Job + }) + .collect(); + wide(jobs); +} /// About this many bytes to a piece of work for [`wide`]. const WIDE_JOB: usize = 1 << 20; @@ -3209,13 +3246,13 @@ mod piece_tests { /// merged nor a reason to settle; the refresh leaves such ranges alone, and /// shaders read zeros there (fxceless/victory-fork#206: missing geometry /// with `VICTORY_LATE_WAIT`/`VICTORY_RELAY`). -fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec { +fn stale_pages_in(base: usize, copied: &[AtomicU64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec { (a / PAGE..e.div_ceil(PAGE)) .filter(|&page| page >= base) - .filter(|&page| match copied.get(page - base) { + .filter(|&page| match copied.get(page - base).map(|v| v.load(Ordering::Acquire)) { None => false, Some(0) => true, - Some(&at) => written + Some(at) => written .binary_search_by_key(&page, |&(p, _)| p) .is_ok_and(|i| written[i].1 > at), }) @@ -3332,7 +3369,7 @@ mod stale_tests { #[test] fn pages_never_taken_are_stale_written_or_not() { let base = 0x100; - let copied = [5, 0, 5, 5]; + let copied = [5u64, 0, 5, 5].map(AtomicU64::new); let at = |page: usize| page * PAGE; // Page 0x101 was never taken; page 0x102 was written after it was // taken, page 0x103 before. @@ -3380,8 +3417,7 @@ pub(crate) fn window_use() -> [u64; 8] { let mut out = [0u64; 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 = s.copied.iter().filter(|at| at.load(Ordering::Relaxed) != 0).count() as u64; out[0] += (pages * PAGE as u64).min(s.len); if crate::host::references(&s.buffer) > 1 { out[1] += 1; @@ -3586,8 +3622,10 @@ impl Shadow { gpu, start, len, - copied: Mutex::new(vec![0; pages as usize]), + copied: (0..pages as usize).map(|_| AtomicU64::new(0)).collect::>().into_boxed_slice(), + copy_lock: Mutex::new(()), ranged: Mutex::default(), + ranged_any: AtomicBool::new(false), watched: AtomicU8::new(0), pending: Mutex::default(), has_pending: std::sync::atomic::AtomicBool::new(false), @@ -4118,9 +4156,8 @@ impl Shadow { return true; } 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, &self.copied, a, e, &written).is_empty(), None => true, }) } @@ -4179,10 +4216,7 @@ impl Shadow { note_stale(1); return true; }; - let stale: Vec = { - let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - stale_pages_in(base, &copied, a, e, &written) - }; + let stale: Vec = stale_pages_in(base, &self.copied, a, e, &written); if stale.is_empty() { continue; } @@ -4288,7 +4322,7 @@ impl Shadow { let mut pages_read = 0u64; let mut total_bytes = 0u64; { - let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + let _copy = self.copy_lock.lock().unwrap_or_else(|e| e.into_inner()); for (i, entry) in done.iter().enumerate() { match entry { PageMerge::Unread => continue, @@ -4306,9 +4340,9 @@ impl Shadow { // copy; else the rest of it is the refresh's, which notes // only whole pages, and the page is looked at again. if lo < hi && (stale[i] * PAGE).max(start) >= a && ((stale[i] + 1) * PAGE).min(end) <= e - && let Some(at) = copied.get_mut(stale[i] - base) + && let Some(at) = self.copied.get(stale[i] - base) { - *at = now; + at.store(now, Ordering::Release); } } } @@ -4438,8 +4472,17 @@ impl Shadow { /// Whether [`Shadow::update`] of `[address, address + len)` would copy /// nothing, and knows it without asking anything - /// (`crate::watch::nothing_new`). `false` if it would have to ask. + /// (`crate::watch::JournalRead::nothing_new_atomic`). `false` if it would + /// have to ask. pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool { + let journal = crate::watch::read_journal(); + self.nothing_new_with(&journal, address, len) + } + + /// As [`Shadow::nothing_new`], reusing a caller-held [`crate::watch::JournalRead`] + /// and reading `copied` lock-free to avoid mutex and `RwLock` contention + /// across thousands of no-op refreshes per frame. + pub(crate) fn nothing_new_with(&self, journal: &crate::watch::JournalRead, address: usize, len: usize) -> bool { if self.place.is_some() { return true; } @@ -4457,8 +4500,7 @@ impl Shadow { { 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 same = journal.nothing_new_atomic(from, to, start / PAGE, &self.copied, || self.ranged(from, to)); #[cfg(feature = "diagnostics")] if same { use crate::copystat::{C, add}; @@ -4469,8 +4511,11 @@ 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. + /// taken whole (0: none is known). fn ranged(&self, from: usize, to: usize) -> u64 { + if !self.ranged_any.load(Ordering::Acquire) { + return 0; + } let ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner()); ranged.iter().filter(|r| r.0 <= from && to <= r.1).map(|r| r.2).max().unwrap_or(0) } @@ -4567,7 +4612,7 @@ impl Shadow { /// asking), whole pages within the buffer. fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize { let base = self.start as usize / PAGE; - let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + let _copy = self.copy_lock.lock().unwrap_or_else(|e| e.into_inner()); let mut writes = written.iter().peekable(); // Pages the range holds in part are never noted in `copied`, and // were copied again at every refresh of the range, written or not: @@ -4578,7 +4623,12 @@ impl Shadow { 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(); + // Whole pages whose `copied` generation will be published once their + // bytes are in `self.data` (so lock-free readers never observe `now` + // before `take_all` finishes). + let mut updated_pages: Vec = Vec::new(); let last = (to - 1) / PAGE; + let (start, end) = (self.start as usize, (self.start + self.len) as usize); for page in from / PAGE..=last { let write = match writes.peek() { Some(&&(p, w)) if p == page => { @@ -4587,14 +4637,13 @@ impl Shadow { } _ => 0, }; - let at = &mut copied[page - base]; - let taken = (*at).max(ranged); + let prev = self.copied[page - base].load(Ordering::Relaxed); + let taken = prev.max(ranged); if taken == 0 || write > taken { // A page only partly in the range is copied in part: it // stays stale for the rest. - let (start, end) = (self.start as usize, (self.start + self.len) as usize); if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to { - *at = now; + updated_pages.push(page - base); } // Cut where pages taken before meet pages never taken. let again = taken != 0; @@ -4618,6 +4667,9 @@ impl Shadow { } let runs = by_parts(runs, &again_at, &crate::watch::parts_written(&again_at)); let bytes = self.take_all(runs); + for idx in updated_pages { + self.copied[idx].store(now, Ordering::Release); + } 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()); @@ -4625,6 +4677,7 @@ impl Shadow { if to - from >= ranged[1].1 - ranged[1].0 { ranged[1] = (from, to, now); } + self.ranged_any.store(true, Ordering::Release); } bytes } @@ -4755,6 +4808,7 @@ impl Shadow { }; let whole = !known && card.before.get().is_none(); let start = self.start as usize; + let (mut send_checked, mut send_same, mut send_bytes, mut send_runs) = (0u64, 0u64, 0u64, 0u64); TITLE.with_borrow_mut(|title| { title.resize(PAGE, 0); let mut at = from; @@ -4778,15 +4832,28 @@ impl Shadow { if let Some(was) = was { crate::host::upcheck::note(self.id, at - start, &was, held); } - SEND[0].fetch_add(n as u64, Ordering::Relaxed); + send_checked += n as u64; if runs.is_empty() { - SEND[1].fetch_add(n as u64, Ordering::Relaxed); + send_same += n as u64; + } else { + send_bytes += runs.iter().map(|r| r.1 as u64).sum::(); + send_runs += runs.len() as u64; } - SEND[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed); - SEND[3].fetch_add(runs.len() as u64, Ordering::Relaxed); at += n; } }); + if send_checked > 0 { + SEND[0].fetch_add(send_checked, Ordering::Relaxed); + } + if send_same > 0 { + SEND[1].fetch_add(send_same, Ordering::Relaxed); + } + if send_bytes > 0 { + SEND[2].fetch_add(send_bytes, Ordering::Relaxed); + } + if send_runs > 0 { + SEND[3].fetch_add(send_runs, Ordering::Relaxed); + } to - from } @@ -5301,13 +5368,14 @@ impl Shadow { let Some(page) = block.checked_sub(self.start as usize / PAGE) else { return false; }; - let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - let Some(at) = copied.get_mut(page) else { + let _copy = self.copy_lock.lock().unwrap_or_else(|e| e.into_inner()); + let Some(slot) = self.copied.get(page) else { return false; }; - let held = *at != 0 && *at >= before && crate::watch::block_published(block); + let at = slot.load(Ordering::Relaxed); + let held = at != 0 && at >= before && crate::watch::block_published(block); if held { - *at = (*at).max(now); + slot.store(at.max(now), Ordering::Release); } held } @@ -5497,6 +5565,38 @@ mod land_tests { assert!((1..LEN / 4).step_by(4 * 331).all(|i| dword(i).load(Ordering::Relaxed) == last)); }); } + + #[test] + fn wide_chunks_visits_every_index_once() { + for &(n, chunk) in &[(0usize, 32usize), (1, 32), (5, 32), (32, 32), (64, 32), (1000, 32), (257, 17)] { + let hits: std::sync::Arc> = + std::sync::Arc::new((0..n).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect()); + let hits_work = hits.clone(); + super::wide_chunks(n, chunk, move |range| { + let (lo, hi) = (range.start, range.end); + assert!(lo < hi, "empty chunk ({lo}..{hi}) for n={n}"); + assert!(hi <= n, "out of bounds ({lo}..{hi}) for n={n}"); + assert!(hi - lo <= chunk, "oversized chunk ({lo}..{hi}) > {chunk}"); + for slot in &hits_work[lo..hi] { + slot.fetch_add(1, Ordering::Relaxed); + } + }); + for (i, slot) in hits.iter().enumerate() { + assert_eq!(slot.load(Ordering::Relaxed), 1, "index {i} for n={n}, chunk={chunk}"); + } + } + } + + #[test] + fn journal_read_atomic_matches_watch_nothing_new() { + let journal = crate::watch::read_journal(); + let copied = [u64::MAX]; + let atomic = [std::sync::atomic::AtomicU64::new(u64::MAX)]; + assert_eq!( + journal.nothing_new_atomic(0x1000, 0x2000, 0x1000, &atomic, || u64::MAX), + crate::watch::nothing_new(0x1000, 0x2000, 0x1000, &copied, u64::MAX), + ); + } } struct Entry { diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 416e03d474..4f9359d5f4 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -28,6 +28,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::ops::{Bound, RangeBounds}; +use std::sync::atomic::Ordering; use std::sync::{Condvar, Mutex, RwLock}; /// The unit tracked and copied: 64 KiB, the console's page (the kernel's @@ -406,7 +407,20 @@ const AHEAD_MAX: usize = (1 << 30) / PAGE; /// 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`. +/// Fast-path mirror of `journal().kept`: avoids building/sorting `ask_ahead` +/// ranges and taking an exclusive `journal_mut()` write lock on every flush +/// while a submission's one asking (`VICTORY_ASK_ONCE`) stands. +static JOURNAL_KEPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Whether the submission's one asking (`ask_once`) currently stands. +pub(crate) fn is_kept() -> bool { + JOURNAL_KEPT.load(Ordering::Acquire) +} + pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { + if is_kept() { + return; + } let mut pieces: Vec<(usize, usize)> = ranges .iter() // Not view memory known by its bits: the kernel would refuse the @@ -595,6 +609,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 is_kept() { + return; + } let mut j = journal_mut(); if !j.kept { j.ahead.clear(); @@ -788,17 +805,23 @@ 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; + JOURNAL_KEPT.store(kept, 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 !is_kept() { + return; + } let mut j = journal_mut(); if j.kept { j.kept = false; j.ahead.clear(); + JOURNAL_KEPT.store(false, Ordering::Release); } } @@ -806,6 +829,9 @@ pub(crate) fn ask_once_end() { /// stands (the title's buffer copies, done at submission): its pages count /// as written after that asking, so the refreshes that follow copy them. pub(crate) fn wrote(at: usize, len: usize) { + if !is_kept() || len == 0 { + return; + } let mut j = journal_mut(); if !j.kept || len == 0 { return; @@ -952,29 +978,69 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve Some(answer) } +/// A held read guard on the write-watch journal, allowing callers to check +/// many buffers with [`JournalRead::nothing_new_atomic`] without acquiring +/// `JOURNAL`'s `RwLock` on every single buffer. +/// +/// Callers MUST drop `JournalRead` before calling any function that acquires +/// `journal_mut()` (such as [`writes`]). +pub(crate) struct JournalRead(std::sync::RwLockReadGuard<'static, Journal>); + +/// Acquires a shared read guard on the write-watch journal for batched +/// [`JournalRead::nothing_new_atomic`] checks. +pub(crate) fn read_journal() -> JournalRead { + JournalRead(journal()) +} + +impl JournalRead { + /// Lock-free check of whether nothing of `[start, end)` was written since + /// `copied` (one `AtomicU64` per 64 KiB page from `base` on) was taken. + /// Only invokes `ranged_fn` (which may lock `Shadow.ranged`) when a page in + /// `[first, last)` is partial (`0`) or older than a recorded write, keeping + /// the common whole-page no-op path 100% mutex-free. + pub(crate) fn nothing_new_atomic( + &self, + start: usize, + end: usize, + base: usize, + copied: &[std::sync::atomic::AtomicU64], + ranged_fn: impl FnOnce() -> u64, + ) -> bool { + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let known = published(start, end); + #[cfg(feature = "diagnostics")] + if known { + crate::faultbook::note(crate::faultbook::What::Known, first, last, 1); + } + let j = &*self.0; + if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { + return false; + } + let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else { + return false; + }; + let all_nonzero = taken.iter().all(|at| at.load(Ordering::Acquire) != 0); + if all_nonzero && j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].load(Ordering::Acquire)) { + return true; + } + let ranged = ranged_fn(); + (ranged != 0 || all_nonzero) + && j.written + .range(first..last) + .all(|(&page, &write)| write <= taken[page - first].load(Ordering::Acquire).max(ranged)) + } +} + /// Whether nothing of `[start, end)` was written that a copy with the notes /// `copied` (the asking after which each page from page `base` on was taken) /// and `ranged` (the asking after which a range that holds this one was /// taken whole, or 0) does not hold, as [`writes`] would answer with nothing /// asked: the submission's asking covers the range, or its blocks are known /// by their bits. `false` if something would have to be asked. +#[cfg(test)] pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], ranged: u64) -> bool { - let (first, last) = (start / PAGE, end.div_ceil(PAGE)); - // The bits first, then the journal, as in `writes`. - let known = published(start, end); - #[cfg(feature = "diagnostics")] - if known { - 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) { - return false; - } - let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else { - return false; - }; - (ranged != 0 || taken.iter().all(|&at| at != 0)) - && j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged)) + let atomic: Vec = copied.iter().map(|&v| std::sync::atomic::AtomicU64::new(v)).collect(); + read_journal().nothing_new_atomic(start, end, base, &atomic, || ranged) } impl Tracked { From 7382c3684deefe756a77ef3f4ca8706d0eb6bb36 Mon Sep 17 00:00:00 2001 From: wike1701 Date: Sat, 28 Nov 2026 14:30:12 +0100 Subject: [PATCH 2/2] perf(gpu): drop Deferred::refreshed_span in-place coalescing per 20-min A/B isolation --- crates/victory-gpu/src/host.rs | 35 ++-------------------------------- 1 file changed, 2 insertions(+), 33 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 61fa4740b3..63feab60e1 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2863,11 +2863,6 @@ struct Deferred { /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. refreshed: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, - /// Per-shadow coalesced span `(copies_index, from, to)` in the current - /// uninterrupted segment (cleared on title writes and per-shadow on GPU - /// writes): lets `VICTORY_THIN` workers merge overlapping/adjacent - /// refreshes before the submitting thread ever walks `copies`. - refreshed_span: std::collections::HashMap>, /// Ranges declared written by shaders since the list last wrote title /// memory (host copy, address, bytes): declaring them again would /// change nothing. @@ -2920,7 +2915,6 @@ impl Deferred { /// date before them is not any more. fn title_written(&mut self) { self.refreshed.clear(); - self.refreshed_span.clear(); self.gpu_written.clear(); self.filled.clear(); } @@ -7158,7 +7152,6 @@ impl HostList { deferred .copies .splice(at..at, found.into_iter().map(|(shadow, from, to)| Step::Refresh(shadow, from as usize, (to - from) as usize))); - deferred.refreshed_span.clear(); } /// A new host list for one of the title's lists (`crate::list::detach`), @@ -7978,33 +7971,11 @@ impl HostList { len: usize, ) { let mut deferred = self.deferred(); - let deferred = &mut *deferred; - let ptr = std::sync::Arc::as_ptr(shadow) as usize; - let end = address.saturating_add(len); - if let Some(&mut (idx, ref mut from, ref mut to)) = deferred.refreshed_span.get_mut(&ptr) - && address <= *to - && end >= *from - { - if *from <= address && end <= *to { - return; - } - let new_from = (*from).min(address); - let new_to = (*to).max(end); - if let Some(Step::Refresh(_, a, l)) = deferred.copies.get_mut(idx) { - *a = new_from; - *l = new_to - new_from; - *from = new_from; - *to = new_to; - return; - } - } - let key = (ptr, address, len); + let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); if deferred.refreshed.insert(key) { - let idx = deferred.copies.len(); deferred .copies .push(Step::Refresh(shadow.clone(), address, len)); - deferred.refreshed_span.insert(ptr, (idx, address, end)); } } @@ -8020,9 +7991,7 @@ impl HostList { len: usize, ) { let mut deferred = self.deferred(); - let ptr = std::sync::Arc::as_ptr(shadow) as usize; - deferred.refreshed_span.remove(&ptr); - let key = (ptr, address, len); + let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); if deferred.gpu_written.insert(key) || !declare_once() { deferred.copies.push(Step::GpuWrite(shadow.clone(), address, len)); }