From 1db4826c82b1ee0dff6466f97d2a40d6c8c1b860 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 27 Nov 2026 22:58:29 +0800 Subject: [PATCH 1/3] gpu: opt in to epoch-validated texture reads Disabled by default, preserving the original refresh path and bytes. Previous Series X measurement: 2.25 to 2.58 fps, median lock wait 974 to 438 ms. --- crates/victory-gpu/src/texture.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 301b0455f..b4e09ab49 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -1513,6 +1513,30 @@ impl Staging { // stays mapped (see `crate::watch::title_memory_reading`; without // it a page went between the asking and the read in runs 71 and // 74). + static LOCKLESS: std::sync::LazyLock = std::sync::LazyLock::new(|| { + std::env::var_os("VICTORY_REFRESH_LOCKLESS").is_some_and(|v| v == "1") + }); + if *LOCKLESS { + let epoch = crate::watch::changes(); + if epoch.is_multiple_of(2) && with_read(size, |bytes| { + if !crate::host::read_into(self.memory, bytes) || epoch != crate::watch::changes() { + return false; + } + let hash = digest(bytes); + if last.hash != Some(hash) { + // Streamed mip selection still needs the mapping guard. + if self.on_demand { + return false; + } + last.hash = Some(hash); + found_blind(last); + self.detile(bytes); + } + true + }) { + return size; + } + } let _mapped = if no_wait() && !exact { // Not waited for: while the runtime remaps title memory the // texture is read through the kernel instead, whole or not at From 9ce55c014a2c8dd50b8b13e9e0e9f7f9d13cdf4e Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 27 Nov 2026 22:59:56 +0800 Subject: [PATCH 2/3] gpu: share a mapping read across up to eight due textures Disabled by default, keeping single-texture refreshes unchanged. Release the guard at the end of each scheduled group, before write boundaries or contended staging locks. Previous Series X run: 3.22 to 4.06 fps, median lock wait 9.5 to 0.0 ms. --- crates/victory-gpu/src/host.rs | 21 ++++++-- crates/victory-gpu/src/texture.rs | 88 +++++++++++++++++++++---------- crates/victory-gpu/src/watch.rs | 6 +++ 3 files changed, 83 insertions(+), 32 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 66710676f..8a5a966a4 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -8974,10 +8974,16 @@ impl Batch { crate::watch::ask_ahead(&ranges); } FLUSHES[3].fetch_add(spans.len() as u64, Ordering::Relaxed); - crate::shadow::wide_each(spans.len() + due.len(), move |i| { + let group = crate::texture::refresh_group_size(); + let groups = due.len().div_ceil(group); + crate::shadow::wide_each(spans.len() + groups, move |i| { // The textures first: they are the longer pieces. - let Some(i) = i.checked_sub(due.len()) else { - due[i].refresh(); + let Some(i) = i.checked_sub(groups) else { + if group == 1 { + due[i].refresh(); + } else { + crate::texture::refresh_group(&due[i * group..((i + 1) * group).min(due.len())]); + } return; }; let (shadow, from, to) = &spans[i]; @@ -9079,7 +9085,14 @@ impl Batch { let started = std::time::Instant::now(); let before = PREPARING[2].load(Ordering::Relaxed); let due = std::mem::take(&mut self.due); - crate::shadow::wide_each(due.len(), move |i| due[i].refresh()); + let group = crate::texture::refresh_group_size(); + if group == 1 { + crate::shadow::wide_each(due.len(), move |i| due[i].refresh()); + } else { + crate::shadow::wide_each(due.len().div_ceil(group), move |i| { + crate::texture::refresh_group(&due[i * group..((i + 1) * group).min(due.len())]); + }); + } let summed = PREPARING[2].load(Ordering::Relaxed).saturating_sub(before); PREPARING[2].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed); } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index b4e09ab49..03a0a2c57 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -17,6 +17,21 @@ pub(crate) mod ahead; +/// Bound the number of refreshes between opportunities for a remapping writer. +pub(crate) fn refresh_group_size() -> usize { + static SIZE: std::sync::LazyLock = std::sync::LazyLock::new(|| { + if std::env::var_os("VICTORY_REFRESH_BATCH").is_some_and(|v| v == "1") { 8 } else { 1 } + }); + if *SIZE > 1 && crate::watch::refresh_may_materialize() { 1 } else { *SIZE } +} + +pub(crate) fn refresh_group<'a>(textures: impl IntoIterator>) { + let mut mapping = None; + for texture in textures { + texture.refresh_in(&mut mapping); + } +} + use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -1408,10 +1423,14 @@ impl Staging { /// Detiles the texture memory into the staging buffer if it changed /// since the last time (and is mapped at all). pub(crate) fn refresh(&self) { + self.refresh_in(&mut None); + } + + fn refresh_in(&self, mapping: &mut Option) { use std::sync::atomic::Ordering::Relaxed; let started = std::time::Instant::now(); let _texture = crate::timeline::span("a texture's refresh"); - let read = self.refresh_now(); + let read = self.refresh_now(mapping); let preparing = &crate::host::PREPARING; preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed); preparing[3].fetch_add(read as u64, Relaxed); @@ -1432,17 +1451,28 @@ impl Staging { } /// Returns the bytes of title memory read. - fn refresh_now(&self) -> usize { + fn refresh_now(&self, mapping: &mut Option) -> usize { let whole = std::time::Instant::now(); - let read = self.refresh_timed(); + let read = self.refresh_timed(mapping); REFRESH_WAITS[3].fetch_add(whole.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed); read } - fn refresh_timed(&self) -> usize { + fn refresh_timed(&self, mapping: &mut Option) -> usize { let size = self.read; let start = self.memory as usize; - let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); + let mut last = waited(0, || { + if mapping.is_some() { + match self.last.try_lock() { + Ok(last) => return last, + Err(std::sync::TryLockError::Poisoned(e)) => return e.into_inner(), + // Other refreshes take last before MAPPING. Release our + // previous read before waiting behind one of them. + Err(std::sync::TryLockError::WouldBlock) => *mapping = None, + } + } + self.last.lock().unwrap_or_else(|e| e.into_inner()) + }); let last = &mut *last; let exact = self.exact.swap(false, std::sync::atomic::Ordering::Relaxed); let alone = self.once.load(std::sync::atomic::Ordering::Relaxed); @@ -1537,30 +1567,32 @@ impl Staging { return size; } } - let _mapped = if no_wait() && !exact { - // Not waited for: while the runtime remaps title memory the - // texture is read through the kernel instead, whole or not at - // all (`no_wait`). - let Some(mapped) = crate::watch::title_memory_reading_now() else { - return self.refresh_unlocked(last, size); - }; - mapped - } else if exact && exact_unlocked() { - match crate::watch::title_memory_reading_now() { - Some(mapped) => mapped, - None => match self.refresh_exact_unlocked(last, size) { - Some(read) => { - if read { - found_blind(last); + if mapping.is_none() { + *mapping = Some(if no_wait() && !exact { + // Not waited for: while the runtime remaps title memory the + // texture is read through the kernel instead, whole or not at + // all (`no_wait`). + let Some(mapped) = crate::watch::title_memory_reading_now() else { + return self.refresh_unlocked(last, size); + }; + mapped + } else if exact && exact_unlocked() { + match crate::watch::title_memory_reading_now() { + Some(mapped) => mapped, + None => match self.refresh_exact_unlocked(last, size) { + Some(read) => { + if read { + found_blind(last); + } + return size; } - return size; - } - None => waited(2, crate::watch::title_memory_reading), - }, - } - } else { - waited(2, crate::watch::title_memory_reading) - }; + None => waited(2, crate::watch::title_memory_reading), + }, + } + } else { + waited(2, crate::watch::title_memory_reading) + }); + } if !committed(self.memory, size) { // Partly mapped: a streamed texture with only some mips' pages // there, the usual state while it streams in. Read through the diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 1e63f3431..ea22f3444 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -2999,6 +2999,12 @@ pub struct SoftViews { static SOFT_VIEWS: std::sync::OnceLock = std::sync::OnceLock::new(); +/// The next texture's write-watch or copy may call into the runtime to +/// materialize a view. That takes the mapping write lock. +pub(crate) fn refresh_may_materialize() -> bool { + LAZY_VIEWS.get().is_some() || SOFT_VIEWS.get().is_some() +} + /// The runtime keeps views in its books alone ([`SoftViews`]). pub fn use_soft_views(hooks: SoftViews) { let _ = SOFT_VIEWS.set(hooks); From 960816d25ecb9e74607016e6dd9abd99cbe2e78c Mon Sep 17 00:00:00 2001 From: superboynick Date: Sat, 28 Nov 2026 01:45:06 +0800 Subject: [PATCH 3/3] gpu: opt in to address-range stripes on the mapping lock Disabled by default; one stripe is the existing global lock, byte for byte. Stripes are 2 MiB address ranges. A mapping call takes only the stripes its range covers, a refresh only the stripes it touches, always in ascending order, and a range that grows releases and reacquires. FIFO ordering keeps a reader from being starved. A writer that arrives while readers hold unrelated stripes no longer blocks, which is the point: the title makes 1,200-1,300 mapping calls a frame during streaming, each taking the lock exclusively for any address. Series X, the 36-item play set, paired windows matched on scene progress, draw counts and mapping rate (draws within 4.66%): | | 1 stripe | 4 stripes | 8 stripes | |---|---:|---:|---:| | steady windows (12 pairs), fps | 5.23 | 5.14 | 5.14 | | steady, submit lock wait median | 0 ms | 0 ms | 0 ms | | streaming load windows (16 pairs), fps | 2.00 | 3.87 | 3.29 | | streaming, frame | 499.12 ms | 258.31 ms | 303.71 ms | | streaming, list | 310.91 ms | 93.57 ms | 74.58 ms | | streaming, submit lock wait median | 202.03 ms | 22.94 ms | 7.55 ms | So this is a load-time change, not a steady-state one: with the refresh batching below landed, the steady-state wait is already zero and the frame is GPU-bound. Four stripes is the better trade than eight - eight lowers the wait further but costs more elsewhere in the load frames. All three counts pass a 4,325,376-byte paging remap comparison and a concurrency test in which a writer on unrelated stripes completes while another writer waits on readers; if the old view grows while waiting, the writer releases and retakes. Builds on the two commits above, which touch the same refresh path. --- crates/victory-gpu/src/draw.rs | 2 +- crates/victory-gpu/src/land.rs | 2 +- crates/victory-gpu/src/lib.rs | 1 + crates/victory-gpu/src/texback.rs | 12 +- crates/victory-gpu/src/texture.rs | 12 +- crates/victory-gpu/src/watch.rs | 160 +++++++++++++++++++++-- crates/victory-gpu/src/watch/mapping.rs | 166 ++++++++++++++++++++++++ crates/victory-hle/src/modules/xmem.rs | 57 ++++++-- 8 files changed, 382 insertions(+), 30 deletions(-) create mode 100644 crates/victory-gpu/src/watch/mapping.rs diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e3a7be8bf..400e3203e 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -4988,7 +4988,7 @@ impl State { // the world streams a change is under way most of the time, // and this is the thread that submits. let mut read = vec![0u8; n * 3 * stride]; - let held = (!crate::host::read_into(from as *const u8, &mut read)).then(crate::watch::title_memory_reading); + let held = (!crate::host::read_into(from as *const u8, &mut read)).then(|| crate::watch::reading_range(from, n * 3 * stride)); // SAFETY: the vertices lie in a title buffer (checked when // recorded) and the scratch memory is the list's. let (src, dst) = unsafe { diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index eb6200d16..64d17f527 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -590,7 +590,7 @@ unsafe fn piece_at( // view's address stays where the title sees `title`. Not waited for: if // a change is under way, what the record of the views says now does // ([`anytime`]), or the title's own address. - let reading = beside.then(crate::watch::title_memory_reading_now).flatten(); + let reading = beside.then(|| crate::watch::reading_range_now(title, end)).flatten(); let beside = if reading.is_some() || beside && anytime() { crate::inplace::beside(title, end) } else { None }; count(stat::PIECES, 1); count(if beside.is_some() { stat::BESIDE } else { stat::DIRECT }, 1); diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index b60d28f55..45d556cd8 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -137,6 +137,7 @@ pub use inplace::{title_memory_freeing, title_memory_section, title_memory_secti pub use shadow::title_memory_write_combined; #[cfg(windows)] pub use watch::{ + MappingRanges, mapping_stripes, mapping_views, SoftViews, kernel_writing, soft_view_guards, title_memory_allocated, title_memory_freed, title_memory_made_real, title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_splitting, title_memory_unmapping, title_memory_written, use_lazy_views, use_soft_views, writing as kernel_will_write, diff --git a/crates/victory-gpu/src/texback.rs b/crates/victory-gpu/src/texback.rs index cf7b0e326..0f99d90ca 100644 --- a/crates/victory-gpu/src/texback.rs +++ b/crates/victory-gpu/src/texback.rs @@ -114,9 +114,15 @@ impl Target { pub(crate) fn new(resource: This) -> Option { // Keep the host copy independently of the title's resource lifetime. let copy = crate::resource::host_copy(resource)?; - let _mapping = crate::watch::title_memory_reading(); + let _mapping = if crate::watch::mapping_stripes() == 1 { + crate::watch::title_memory_reading() + } else { + let (_, at, size) = crate::resource::title_texture(resource)?; + crate::watch::reading_range(at, size) + }; let (layout, at, size) = crate::resource::title_texture(resource)?; let end = at.checked_add(size).filter(|&end| at != 0 && end > at)?; + if !_mapping.covers(at, size) { return None; } let ticket = track(resource as usize, at, end); Some(Self { copy, layout, ticket }) } @@ -201,7 +207,8 @@ pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option pub(crate) fn land(back: &Back) { static COPIED: AtomicU64 = AtomicU64::new(0); static STALE: AtomicU64 = AtomicU64::new(0); - let _mapping = crate::watch::title_memory_reading(); + let (at, end) = back.range(); + let _mapping = crate::watch::reading_range(at, end - at); let _ticket_guard = TICKETS.lock().unwrap_or_else(|e| e.into_inner()); if !back.ticket.valid.load(Ordering::Acquire) { let skipped = STALE.fetch_add(1, Ordering::Relaxed) + 1; @@ -210,7 +217,6 @@ pub(crate) fn land(back: &Back) { } return; } - let (at, end) = back.range(); let size = end - at; let mut tiled = vec![0u8; size]; // Keep title bytes the subresources do not cover. diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 03a0a2c57..2fd599792 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -1164,7 +1164,7 @@ fn fill_plane( bytes: usize, pitch: usize, ) { - let _pin = crate::watch::title_memory_reading(); + let _pin = crate::watch::reading_range(at, len); // SAFETY: the list owns this full upload allocation until its GPU work completes. let out = unsafe { std::slice::from_raw_parts_mut(dst as *mut u8, bytes) }; let mip = &layout.mips[0]; @@ -1461,6 +1461,8 @@ impl Staging { fn refresh_timed(&self, mapping: &mut Option) -> usize { let size = self.read; let start = self.memory as usize; + // Never extend a held set of stripes. Reuse the batch guard only for a subset. + if mapping.as_ref().is_some_and(|held| !held.covers(start, size)) { *mapping = None; } let mut last = waited(0, || { if mapping.is_some() { match self.last.try_lock() { @@ -1572,12 +1574,12 @@ impl Staging { // Not waited for: while the runtime remaps title memory the // texture is read through the kernel instead, whole or not at // all (`no_wait`). - let Some(mapped) = crate::watch::title_memory_reading_now() else { + let Some(mapped) = crate::watch::reading_range_now(start, size) else { return self.refresh_unlocked(last, size); }; mapped } else if exact && exact_unlocked() { - match crate::watch::title_memory_reading_now() { + match crate::watch::reading_range_now(start, size) { Some(mapped) => mapped, None => match self.refresh_exact_unlocked(last, size) { Some(read) => { @@ -1586,11 +1588,11 @@ impl Staging { } return size; } - None => waited(2, crate::watch::title_memory_reading), + None => waited(2, || crate::watch::reading_range(start, size)), }, } } else { - waited(2, crate::watch::title_memory_reading) + waited(2, || crate::watch::reading_range(start, size)) }); } if !committed(self.memory, size) { diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index ea22f3444..3da489880 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -2622,7 +2622,13 @@ static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(()); /// What the runtime holds while it changes what title memory shows /// ([`title_memory_remapping`]). -pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>); +#[allow(dead_code)] +pub struct Remapping { + legacy: Option>, + stripes: Vec, +} +mod mapping; +pub use mapping::{MappingRanges, mapping_stripes}; impl Drop for Remapping { fn drop(&mut self) { @@ -2769,6 +2775,54 @@ pub(crate) fn lost(what: &'static str, at: usize, len: usize) { /// place is under way and none begins ([`title_memory_reading`]). Taken /// around the whole change, the unmapping and the mapping again. pub fn title_memory_remapping() -> Remapping { + prepare_remapping(); + let (legacy, stripes) = if mapping_stripes() == 1 { + (Some(MAPPING.write().unwrap_or_else(|e| e.into_inner())), Vec::new()) + } else { + (None, mapping::take(MappingRanges::all(), true, false).unwrap()) + }; + begin_remapping(legacy, stripes) +} + +/// Field order matters. In striped mode finish the global change epoch before +/// releasing the view table. In legacy mode release the table first, as before. +pub struct MappingViews { + _striped: Option, + views: T, + _legacy: Option, +} +impl std::ops::Deref for MappingViews { + type Target = T; + fn deref(&self) -> &T { &self.views } +} +impl std::ops::DerefMut for MappingViews { + fn deref_mut(&mut self) -> &mut T { &mut self.views } +} + +/// All callers supply the same exclusive view table. Its lifetime, not a +/// separate writer gate, serializes changes to the view map and change epoch. +pub fn mapping_views(table: impl Fn() -> T, needed: impl Fn(&T) -> MappingRanges) -> MappingViews { + if mapping_stripes() == 1 { + let guard = title_memory_remapping(); + return MappingViews { _striped: None, views: table(), _legacy: Some(guard) }; + } + prepare_remapping(); + let mut footprint = needed(&table()).nonempty(); + loop { + let pins = mapping::take(footprint, true, false).unwrap(); + let views = table(); + let current = needed(&views).nonempty(); + if footprint.contains(current) { + return MappingViews { _striped: Some(begin_remapping(None, pins)), views, _legacy: None }; + } + drop(views); + drop(pins); + // At least one new bit on each retry. A racing split cannot livelock. + footprint.include(current); + } +} + +fn prepare_remapping() { // For the title's own threads ([`came_back`]). install(); let met = MET.load(std::sync::atomic::Ordering::Relaxed); @@ -2779,32 +2833,63 @@ pub fn title_memory_remapping() -> Remapping { tracing::info!(met, "accesses of title threads that waited for a change of mapping"); } } - let changing = MAPPING.write().unwrap_or_else(|e| e.into_inner()); +} + +fn begin_remapping(legacy: Option>, stripes: Vec) -> Remapping { CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst); CHANGING.set((true, false)); - Remapping(changing) + Remapping { legacy, stripes } } /// What a read of title memory in place holds ([`title_memory_reading`]). -pub struct Reading(#[allow(dead_code)] std::sync::RwLockReadGuard<'static, ()>); +pub struct Reading { + #[allow(dead_code)] + legacy: Option>, + #[allow(dead_code)] + stripes: Vec, + ranges: MappingRanges, +} + +impl Reading { + pub(crate) fn covers(&self, at: usize, len: usize) -> bool { + self.legacy.is_some() || self.ranges.contains(MappingRanges::of(at, len)) + } +} /// For reading title memory in place: until what it returns is dropped, /// the runtime changes no mapping, so memory found mapped stays mapped. /// Not to be taken twice by one thread, nor held across anything that /// maps title memory. pub fn title_memory_reading() -> Reading { - Reading(MAPPING.read().unwrap_or_else(|e| e.into_inner())) + read_mapping(MappingRanges::all(), false).unwrap() +} + +pub(crate) fn reading_range(at: usize, len: usize) -> Reading { + read_mapping(MappingRanges::of(at, len), false).unwrap() +} + +pub(crate) fn reading_range_now(at: usize, len: usize) -> Option { + read_mapping(MappingRanges::of(at, len), true) } -/// [`title_memory_reading`] if it can be had at once: `None` while the -/// runtime changes a mapping (or waits to), for a caller that has another -/// way to read and would rather not wait. pub fn title_memory_reading_now() -> Option { - match MAPPING.try_read() { - Ok(guard) => Some(Reading(guard)), - Err(std::sync::TryLockError::Poisoned(e)) => Some(Reading(e.into_inner())), - Err(std::sync::TryLockError::WouldBlock) => None, + read_mapping(MappingRanges::all(), true) +} + +fn read_mapping(ranges: MappingRanges, now: bool) -> Option { + if mapping_stripes() != 1 { + return Some(Reading { stripes: mapping::take(ranges, false, now)?, legacy: None, ranges }); } + let guard = if now { + match MAPPING.try_read() { + Ok(g) => g, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => return None, + } + } else { + MAPPING.read().unwrap_or_else(|e| e.into_inner()) + }; + Some(Reading { legacy: Some(guard), stripes: Vec::new(), ranges }) } /// The runtime mapped title memory `[at, at + len)`: what it shows is new, @@ -5288,3 +5373,54 @@ mod many_askers_tests { assert!(!BITS.swap_on(70) && BITS.swap_on(70) && BITS.all(70, 71)); } } + +#[cfg(test)] +mod mapping_views_tests { + use super::*; + use std::sync::{Mutex, mpsc}; + use std::time::Duration; + + #[test] + fn waiting_writer_rechecks_whole_view_without_blocking_an_unrelated_writer() { + if mapping_stripes() < 4 { return; } + let chunk = 2 << 20; + let table = Mutex::new(false); + let (first_release, first_wait) = mpsc::channel(); + let (second_release, second_wait) = mpsc::channel(); + let (ready, pinned) = mpsc::channel(); + let (observed, observation) = mpsc::channel(); + let (admitted, admission) = mpsc::channel(); + std::thread::scope(|workers| { + for (address, release) in [(0, first_wait), (chunk, second_wait)] { + let ready = ready.clone(); + workers.spawn(move || { + let _pin = reading_range(address, 1); + ready.send(()).unwrap(); + release.recv_timeout(Duration::from_secs(5)).unwrap(); + }); + } + for _ in 0..2 { pinned.recv_timeout(Duration::from_secs(2)).unwrap(); } + workers.spawn(|| { + let checks = std::cell::Cell::new(0); + let _guard = mapping_views(|| table.lock().unwrap(), |wide| { + checks.set(checks.get() + 1); + observed.send(checks.get()).unwrap(); + MappingRanges::of(0, if **wide {chunk + 1} else {1}) + }); + admitted.send(()).unwrap(); + }); + observation.recv_timeout(Duration::from_secs(2)).unwrap(); + // A disjoint writer changes the table between discovery and acquisition. + { + let mut other = mapping_views(|| table.lock().unwrap(), |_| MappingRanges::of(2 * chunk, 1)); + **other = true; + } + first_release.send(()).unwrap(); + assert_eq!(observation.recv_timeout(Duration::from_secs(2)).unwrap(), 2); + assert!(admission.try_recv().is_err()); + second_release.send(()).unwrap(); + admission.recv_timeout(Duration::from_secs(2)).unwrap(); + assert_eq!(observation.recv().unwrap(), 3); + }); + } +} diff --git a/crates/victory-gpu/src/watch/mapping.rs b/crates/victory-gpu/src/watch/mapping.rs new file mode 100644 index 000000000..7a95b0b25 --- /dev/null +++ b/crates/victory-gpu/src/watch/mapping.rs @@ -0,0 +1,166 @@ +//! A ticket admits readers together and writers one at a time in arrival order. +use std::sync::{Condvar, LazyLock, Mutex}; + +const MAX: usize = 64; +const CHUNK: usize = 2 << 20; + +pub fn mapping_stripes() -> usize { + static N: LazyLock = LazyLock::new(|| { + std::env::var("VICTORY_MAPPING_STRIPES") + .ok() + .and_then(|v| v.parse().ok()) + .filter(|v| (1..=MAX).contains(v)) + .unwrap_or(1) + }); + *N +} + +#[derive(Clone, Copy, Default)] +pub struct MappingRanges(u64); +impl MappingRanges { + pub fn add(&mut self, at: usize, len: usize) { + if len == 0 { + return; + } + let first = at / CHUNK; + let last = at.saturating_add(len - 1) / CHUNK; + let n = mapping_stripes(); + for k in 0..(last - first + 1).min(n) { + self.0 |= 1 << ((first + k) % n); + } + } + pub(super) fn of(at: usize, len: usize) -> Self { + let mut ranges = Self::default(); + ranges.add(at, len); + ranges + } + pub(super) fn all() -> Self { + Self(u64::MAX >> (64 - mapping_stripes())) + } + // An empty operation still advances the global epoch. Reserve one stripe + // so an all-address writer cannot enter its epoch concurrently. + pub(super) fn nonempty(self) -> Self { + Self(self.0.max(1)) + } + pub(super) fn include(&mut self, other: Self) { + self.0 |= other.0; + } + pub(super) fn contains(self, other: Self) -> bool { + self.0 & other.0 == other.0 + } +} + +#[derive(Default)] +struct State { + next: u64, + serving: u64, + readers: usize, + writing: bool, +} + +#[derive(Default)] +struct Stripe { + state: Mutex, + changed: Condvar, +} + +static LOCKS: LazyLock<[Stripe; MAX]> = + LazyLock::new(|| std::array::from_fn(|_| Stripe::default())); + +pub(super) struct Permit { + stripe: &'static Stripe, + write: bool, +} +impl Drop for Permit { + fn drop(&mut self) { + let mut s = self.stripe.state.lock().unwrap_or_else(|e| e.into_inner()); + if self.write { + s.writing = false; + } else { + s.readers -= 1; + } + self.stripe.changed.notify_all(); + } +} +impl Stripe { + fn enter(&'static self, write: bool, now: bool) -> Option { + let mut s = if now { + match self.state.try_lock() { + Ok(s) => s, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => return None, + } + } else { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + }; + if now && (s.next != s.serving || s.writing || write && s.readers != 0) { + return None; + } + let ticket = s.next; + s.next = s.next.wrapping_add(1); + while ticket != s.serving || s.writing || write && s.readers != 0 { + s = self.changed.wait(s).unwrap_or_else(|e| e.into_inner()); + } + if write { + s.writing = true; + } else { + s.readers += 1; + } + s.serving = s.serving.wrapping_add(1); + self.changed.notify_all(); + Some(Permit { + stripe: self, + write, + }) + } +} + +pub(super) fn take(ranges: MappingRanges, write: bool, now: bool) -> Option> { + let mut bits = ranges.0; + let mut held = Vec::with_capacity(bits.count_ones() as usize); + while bits != 0 { + let index = bits.trailing_zeros() as usize; + held.push(LOCKS[index].enter(write, now)?); + bits &= bits - 1; + } + Some(held) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn overlapping_readers_yield_to_a_queued_writer() { + use std::sync::mpsc; + let stripe: &'static Stripe = Box::leak(Box::new(Stripe::default())); + let read = stripe.enter(false, false).unwrap(); + let (ready, started) = mpsc::sync_channel(0); + std::thread::scope(|scope| { + scope.spawn(move || { + ready.send(()).unwrap(); + let _guard = stripe.enter(true, false).unwrap(); + }); + started.recv().unwrap(); + while stripe.state.lock().unwrap().next < 2 { + std::thread::yield_now(); + } + assert!(stripe.enter(false, true).is_none()); + drop(read); + }); + } + + #[test] + fn crossing_a_chunk_locks_both_endpoints() { + let n = mapping_stripes(); + let cross = MappingRanges::of(CHUNK - 1, 2); + let held = take(cross, true, false).unwrap(); + assert!(take(MappingRanges::of(0, 1), false, true).is_none()); + assert!(take(MappingRanges::of(CHUNK, 1), false, true).is_none()); + if n >= 3 { + assert!(take(MappingRanges::of(2 * CHUNK, 1), false, true).is_some()); + } + drop(held); + assert!(take(cross, false, true).is_some()); + } +} diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 6c4f0f6c6..4fbdcfb86 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -1293,6 +1293,23 @@ fn arrange(base: usize, pages: &[usize]) { } } +/// A partial unmap removes whole old views. Only the two endpoints can +/// have bytes outside the requested range. The caller holds the view table. +fn changing_ranges(views: &Physical, ranges: impl IntoIterator) -> victory_gpu::MappingRanges { + let mut out = victory_gpu::MappingRanges::default(); + for (at, len) in ranges { + if len == 0 { continue; } + out.add(at, len); + for endpoint in [at, at.saturating_add(len - 1)] { + if let Some((&base, (size, _))) = views.views.range(..=endpoint).next_back() + && endpoint - base < *size { + out.add(base, *size); + } + } + } + out +} + /// Maps `n` pages at `address`, in place of what is mapped there; null /// `pages` unmaps. Returns `address`, or null if a page or the host fails. pub extern "system" fn XMemMapPhysicalPages( @@ -1325,8 +1342,7 @@ fn map_pages(address: *mut c_void, n: usize, pages: *const usize, lazy: bool) -> // into that gap (`victory_gpu::title_memory_remapping`). Taken before // the views, as everywhere: a reader that holds it may fault into a // lazy view and need the views to make it real ([`materialize`]). - let _changing = victory_gpu::title_memory_remapping(); - let mut physical = physical(); + let mut physical = victory_gpu::mapping_views(physical, |views| changing_ranges(views, [(base, n.saturating_mul(PAGE))])); if let Some(costed) = &mut costed { costed.waited = costed.started.elapsed().as_nanos() as u64; } @@ -1426,8 +1442,7 @@ fn alias_as(to: u64, from: u64, len: u64, runs_in_one: bool, lazy: bool) -> bool let _busy = Busy::begin(); // As in `XMemMapPhysicalPages`: no read in place meets the gap (taken // before the views, as there). - let _changing = victory_gpu::title_memory_remapping(); - let mut physical = physical(); + let mut physical = victory_gpu::mapping_views(physical, |views| changing_ranges(views, [(to, len)])); unmap(&mut physical, to, len); if from == 0 { return true; @@ -1597,8 +1612,12 @@ pub fn map_aliases(ranges: &[(u64, u64, u64)]) -> bool { let mut at = 0; while at < pages.len() { let _busy = Busy::begin(); - let _changing = victory_gpu::title_memory_remapping(); - let mut physical = physical(); + let mut physical = victory_gpu::mapping_views(physical, |views| { + let mut seen = std::collections::HashSet::new(); + let group = pages[at..].iter().take(GROUP) + .take_while(|&&(to, from)| !from.is_some_and(|v| seen.contains(&v)) && seen.insert(to)); + changing_ranges(views, group.map(|&(to, _)| (to, PAGE))) + }); let mut ops: Vec = Vec::new(); let mut touched = std::collections::HashSet::new(); for &(to, from) in &pages[at..] { @@ -1627,8 +1646,11 @@ fn scatter(wanted: &[(usize, usize)]) -> bool { let _busy = Busy::begin(); let mut costed = Costed::begin(None); let mut ops: Vec = Vec::new(); - let _changing = victory_gpu::title_memory_remapping(); - let mut physical = physical(); + let mut physical = victory_gpu::mapping_views(physical, |views| { + let mut seen = std::collections::HashSet::new(); + let group = wanted[at..].iter().take(GROUP).take_while(|&&(to, _)| seen.insert(to)); + changing_ranges(views, group.map(|&(to, _)| (to, PAGE))) + }); if let Some(costed) = &mut costed { costed.waited = costed.started.elapsed().as_nanos() as u64; } @@ -3390,6 +3412,24 @@ mod tests { assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); } + #[test] + fn mapping_stripes_partial_remap_preserves_every_byte() { + let n = (4 << 20) / PAGE + 2; + let pages = allocate(n); + let len = n * PAGE; + let a = XMemVirtualAlloc(std::ptr::null_mut(), len, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!a.is_null()); + assert_eq!(XMemMapPhysicalPages(a, n, pages.as_ptr()), a); + let bytes: Vec = (0..len).map(|i| ((i / PAGE) ^ (i >> 8) ^ i) as u8).collect(); + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), a.cast::(), len) }; + let middle = n / 2; + let at = a.wrapping_byte_add(middle * PAGE); + assert_eq!(XMemMapPhysicalPages(at, 1, pages[middle..].as_ptr()), at); + assert_eq!(unsafe { std::slice::from_raw_parts(a.cast::(), len) }, &bytes[..]); + assert_eq!(XMemMapPhysicalPages(a, n, std::ptr::null()), a); + assert_eq!(XMemFreePhysicalPages(n, pages.as_ptr()), 1); + } + /// A thread that reads a mapped page in place, as the GPU side reads a /// texture, never meets the moment in which the runtime has taken the /// page's view away to map it again: mapping the same pages at the same @@ -3397,6 +3437,7 @@ mod tests { /// reader faults on a page "reserved, never committed" (the crashes of /// runs 71 and 74). #[test] + fn a_read_in_place_never_meets_the_gap_of_a_remapping() { use std::sync::atomic::{AtomicBool, Ordering}; let mut pages = [0usize; 3];