diff --git a/crates/leonida-gpu/src/lib.rs b/crates/leonida-gpu/src/lib.rs index e09a219dc..e126be7a5 100644 --- a/crates/leonida-gpu/src/lib.rs +++ b/crates/leonida-gpu/src/lib.rs @@ -97,6 +97,6 @@ pub fn probe_translation_host() -> bool { pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; #[cfg(windows)] pub use watch::{ - title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_written, - writing as kernel_will_write, + Remapping, title_memory_reading, title_memory_remapped, title_memory_remapping, + title_memory_written, writing as kernel_will_write, }; diff --git a/crates/leonida-gpu/src/texture.rs b/crates/leonida-gpu/src/texture.rs index 51d364d78..8f5b4c735 100644 --- a/crates/leonida-gpu/src/texture.rs +++ b/crates/leonida-gpu/src/texture.rs @@ -1071,20 +1071,20 @@ impl Staging { } // From here on the texture's memory may be read in place. Held until // that read is done: the runtime changes what title memory shows - // only with this taken alone, so what `committed` finds mapped - // stays mapped (see `crate::watch::title_memory_reading`; without - // it a page went between the asking and the read in runs 71 and - // 74). + // only with its mapping locked, so what `committed` finds mapped + // stays mapped until we finish reading the texture. + let range = start..start + size; let _mapped = if no_wait() { // 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::texture_memory_reading(range, true) else { return self.refresh_unlocked(last, size); }; mapped } else { - waited(2, crate::watch::title_memory_reading) + waited(2, || crate::watch::texture_memory_reading(range, false)) + .expect("a blocking mapping read always acquires its locks") }; if !committed(self.memory, size) { // Partly mapped: a streamed texture with only some mips' pages diff --git a/crates/leonida-gpu/src/watch.rs b/crates/leonida-gpu/src/watch.rs index d4f4e4216..aff18675b 100644 --- a/crates/leonida-gpu/src/watch.rs +++ b/crates/leonida-gpu/src/watch.rs @@ -24,7 +24,8 @@ //! system call writing into a guarded block fails (none is known to). use std::collections::{BTreeMap, BTreeSet}; -use std::sync::Mutex; +use std::ops::Range; +use std::sync::{Mutex, OnceLock, RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockError}; /// The unit tracked and copied: 64 KiB, the console's page (the kernel's /// 4 KiB pages fold into it). Finer units made the checks of the world's @@ -1058,33 +1059,76 @@ pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) { /// had asked whether the texture was all mapped and been told yes. Asking /// cannot help; not changing the mapping while such a read is under way /// does. -static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(()); +static MAPPING: RwLock<()> = RwLock::new(()); + +// Texture staging only reads its own range. One lock covers a 2 MiB block; +// blocks that share a lock may still wait for each other. Every caller takes +// locks in table order, including ranges that wrap or cover the whole table. +const MAPPING_BLOCK: usize = 2 << 20; +const MAPPING_LOCK_COUNT: usize = 128; +static MAPPING_LOCKS: [RwLock<()>; MAPPING_LOCK_COUNT] = + [const { RwLock::new(()) }; MAPPING_LOCK_COUNT]; + +/// `LEONIDA_TEXTURE_RANGE_LOCK=1` lets a texture refresh read in place +/// during a remap of unrelated memory. Off until tested in the title. +fn texture_range_lock() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_RANGE_LOCK").is_some_and(|v| v == "1")) +} + +fn mapping_locks(range: Range) -> impl Iterator> { + let first = range.start / MAPPING_BLOCK; + let count = if range.is_empty() { + 0 + } else { + ((range.end - 1) / MAPPING_BLOCK - first + 1).min(MAPPING_LOCK_COUNT) + }; + let start = first % MAPPING_LOCK_COUNT; + let end = start + count; + MAPPING_LOCKS[..end.saturating_sub(MAPPING_LOCK_COUNT)] + .iter() + .chain(&MAPPING_LOCKS[start..end.min(MAPPING_LOCK_COUNT)]) +} /// What the runtime holds while it changes what title memory shows /// ([`title_memory_remapping`]). -pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>, std::time::Instant); +pub struct Remapping { + _range_locks: Vec>, + _mapping: RwLockWriteGuard<'static, ()>, + asked: std::time::Instant, +} impl Drop for Remapping { fn drop(&mut self) { // From asking for the lock until it is let go (the frame log). - crate::framelog::add(crate::framelog::T::RemapUs, self.1.elapsed().as_micros() as u64); + crate::framelog::add(crate::framelog::T::RemapUs, self.asked.elapsed().as_micros() as u64); } } -/// The runtime is about to map, unmap or move physical pages of title -/// memory: until what it returns is dropped, no read of title memory in -/// 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 { +/// Protects all addresses that can become unmapped, including any portions of +/// the old views that the runtime will temporarily unmap and then restore. +/// Held from before unmapping until the replacement mappings are ready. +pub fn title_memory_remapping(range: Range) -> Remapping { + lock_remapping(range, texture_range_lock()) +} + +fn lock_remapping(range: Range, ranged: bool) -> Remapping { let asked = std::time::Instant::now(); - let held = MAPPING.write().unwrap_or_else(|e| e.into_inner()); + // Readers that may follow aliases keep using the global lock. + let mapping = MAPPING.write().unwrap_or_else(|e| e.into_inner()); + let mut range_locks = Vec::new(); + if ranged { + range_locks.extend( + mapping_locks(range).map(|lock| lock.write().unwrap_or_else(|e| e.into_inner())), + ); + } crate::framelog::add(crate::framelog::T::Remaps, 1); crate::framelog::add(crate::framelog::T::RemapWaitUs, asked.elapsed().as_micros() as u64); - Remapping(held, asked) + Remapping { _range_locks: range_locks, _mapping: mapping, asked } } /// 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)] RwLockReadGuard<'static, ()>); /// For reading title memory in place: until what it returns is dropped, /// the runtime changes no mapping, so memory found mapped stays mapped. @@ -1098,13 +1142,50 @@ pub fn title_memory_reading() -> Reading { /// 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, + try_read_mapping(&MAPPING).map(Reading) +} + +fn try_read_mapping(lock: &'static RwLock<()>) -> Option> { + match lock.try_read() { + Ok(guard) => Some(guard), + Err(TryLockError::Poisoned(e)) => Some(e.into_inner()), + Err(TryLockError::WouldBlock) => None, } } +pub(crate) enum TextureReading { + Global { _guard: Reading }, + Range { _guards: Vec> }, +} + +pub(crate) fn texture_memory_reading( + range: Range, + try_only: bool, +) -> Option { + if texture_range_lock() { + lock_texture_range(range, try_only).map(|guards| TextureReading::Range { _guards: guards }) + } else if try_only { + title_memory_reading_now().map(|guard| TextureReading::Global { _guard: guard }) + } else { + Some(TextureReading::Global { _guard: title_memory_reading() }) + } +} + +fn lock_texture_range( + range: Range, + try_only: bool, +) -> Option>> { + mapping_locks(range) + .map(|lock| { + if try_only { + try_read_mapping(lock) + } else { + Some(lock.read().unwrap_or_else(|e| e.into_inner())) + } + }) + .collect() +} + /// The runtime mapped or unmapped title memory `[at, at + len)`: what it /// shows is new and read-write, so it is no longer guarded (nor known /// unmapped). @@ -1702,11 +1783,36 @@ mod tests { #[cfg(test)] mod mapping_tests { - use super::{title_memory_reading, title_memory_remapping}; + use super::{ + MAPPING_BLOCK, MAPPING_LOCK_COUNT, lock_remapping, lock_texture_range, mapping_locks, + title_memory_reading, title_memory_reading_now, title_memory_remapping, + }; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, mpsc}; use std::time::Duration; + #[test] + fn a_disjoint_texture_read_can_start_during_a_remap() { + let boundary = MAPPING_BLOCK; + let changing = lock_remapping(boundary - 16..boundary + 16, true); + assert!(lock_texture_range(2 * boundary..2 * boundary + 16, true).is_some()); + assert!(lock_texture_range(boundary - 32..boundary, true).is_none()); + assert!(lock_texture_range(boundary..boundary + 32, true).is_none()); + assert!(title_memory_reading_now().is_none()); + drop(changing); + assert!(lock_texture_range(boundary - 16..boundary + 16, true).is_some()); + } + + #[test] + fn a_wide_or_wrapping_range_locks_each_block_in_table_order() { + let wrap = MAPPING_BLOCK * MAPPING_LOCK_COUNT; + let wrapped: Vec<_> = mapping_locks(wrap - 1..wrap + 1).map(std::ptr::from_ref).collect(); + let all: Vec<_> = mapping_locks(0..wrap).map(std::ptr::from_ref).collect(); + assert_eq!(wrapped, [all[0], all[MAPPING_LOCK_COUNT - 1]]); + assert!(mapping_locks(wrap..wrap).next().is_none()); + assert!(mapping_locks(MAPPING_BLOCK..usize::MAX).map(std::ptr::from_ref).eq(all)); + } + /// A change of mapping waits for a read in place that is under way, and /// a read in place waits for a change of mapping. #[test] @@ -1719,7 +1825,7 @@ mod mapping_tests { let changed = changed.clone(); std::thread::spawn(move || { began.send(()).unwrap(); - let _changing = title_memory_remapping(); + let _changing = title_memory_remapping(0..MAPPING_BLOCK); changed.store(true, Ordering::SeqCst); }) }; @@ -1731,7 +1837,7 @@ mod mapping_tests { assert!(changed.load(Ordering::SeqCst)); // A change holds; the read does not begin until it is done. let read = Arc::new(AtomicBool::new(false)); - let changing = title_memory_remapping(); + let changing = title_memory_remapping(0..MAPPING_BLOCK); let (began, wait) = mpsc::channel(); let reader = { let read = read.clone(); diff --git a/crates/leonida-hle/src/modules/xmem.rs b/crates/leonida-hle/src/modules/xmem.rs index 7292a7674..2bdfd5d52 100644 --- a/crates/leonida-hle/src/modules/xmem.rs +++ b/crates/leonida-hle/src/modules/xmem.rs @@ -10,6 +10,7 @@ use std::alloc::{Layout, alloc, dealloc}; use std::collections::{BTreeMap, HashMap}; use std::ffi::c_void; +use std::ops::Range; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; @@ -670,12 +671,9 @@ pub extern "system" fn XMemMapPhysicalPages( ) -> *mut c_void { let base = address as usize; let mut physical = physical(); - // Until the pages are mapped again: `unmap` takes whole views away and - // maps what stays of them again, and a mapped view is a reservation - // until it is committed. A read of title memory in place must not fall - // into that gap (`leonida_gpu::title_memory_remapping`). - let _changing = leonida_gpu::title_memory_remapping(); - unmap(&mut physical, base, n * PAGE); + // Keep the old views and their replacements protected until the new + // pages are committed, when an in-place reader can see them again. + let _changing = unmap(&mut physical, base, n * PAGE); if pages.is_null() { return address; } @@ -742,9 +740,7 @@ pub extern "system" fn XMemMapPhysicalPagesScatter( pub fn map_alias(to: u64, from: u64, len: u64) -> bool { let (to, from, len) = (to as usize, from as usize, len as usize); let mut physical = physical(); - // As in `XMemMapPhysicalPages`: no read in place meets the gap. - let _changing = leonida_gpu::title_memory_remapping(); - unmap(&mut physical, to, len); + let _changing = unmap(&mut physical, to, len); for k in (0..len).step_by(PAGE) { if from == 0 { break; @@ -866,28 +862,35 @@ fn commit_limit_message( message } -/// Returns `[base, base + len)` to placeholders; views reaching past it -/// are mapped again outside it. -fn unmap(physical: &mut Physical, base: usize, len: usize) { - // No bytes: no view to return. The search below would still find the - // view holding `base` and cut it in two there, and its range of views - // starting inside would run backwards (which `BTreeMap` panics on). - if len == 0 { - return; +/// Finds the views an unmap will remove and the full span they and the +/// replacement mappings can touch. The fringes of a split view need the +/// same protection as the requested pages because Windows unmaps it whole. +fn remapping_views(physical: &Physical, range: Range) -> (Range, Vec) { + if range.is_empty() { + return (range, Vec::new()); } - let end = base + len; - // Views do not overlap: the one holding `base`, then those starting - // inside (the GPU's page mappings make one view per page). + let (base, end) = (range.start, range.end); let first = physical .views .range(..=base) .next_back() - .filter(|(at, (size, _))| *at + size > base) - .map(|(at, _)| *at); - let hit: Vec = first - .into_iter() - .chain(physical.views.range(base + 1..end).map(|(at, _)| *at)) - .collect(); + .filter(|(at, (size, _))| *at + size > base); + let mut affected = range; + let mut hit = Vec::new(); + for (&at, (size, _)) in first.into_iter().chain(physical.views.range(base + 1..end)) { + affected.start = affected.start.min(at); + affected.end = affected.end.max(at + size); + hit.push(at); + } + (affected, hit) +} + +/// Returns `[base, base + len)` to placeholders and remaps the old views' +/// fringes. The caller keeps the guard until its replacement views are ready. +fn unmap(physical: &mut Physical, base: usize, len: usize) -> leonida_gpu::Remapping { + let end = base + len; + let (affected, hit) = remapping_views(physical, base..end); + let changing = leonida_gpu::title_memory_remapping(affected); for at in hit { let Some((size, slice)) = physical.views.remove(&at) else { continue; @@ -920,6 +923,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { map(physical, end, at + size - end, Slice { index, ..slice }); } } + changing } /// The oldest layout we know; newer titles pass other flag values (Minecraft @@ -1191,6 +1195,10 @@ mod tests { assert_eq!(unsafe { at(b, 1).cast::().add(1).read() }, 9); // Unmapping the middle page keeps its neighbours. + let base = a as usize; + let (affected, hit) = remapping_views(&physical(), base + PAGE..base + 2 * PAGE); + assert_eq!(affected, base..base + 3 * PAGE); + assert_eq!(hit, [base]); assert_eq!( XMemMapPhysicalPages(at(a, 1), 1, std::ptr::null()), at(a, 1) diff --git a/docs/fork-notes.md b/docs/fork-notes.md index 0c836f1ec..d8e13909b 100644 --- a/docs/fork-notes.md +++ b/docs/fork-notes.md @@ -417,6 +417,45 @@ cargo test -p leonida-gpu --lib --release --locked ` cargo test -p leonida-gpu --lib --release --locked ` bench_single_record_clamp -- --ignored --nocapture --test-threads=1 ``` +**Texture refreshes wait for unrelated remaps (P-4).** In an opening +scene run on `0a1a17b`, base profile, Ryzen 9 7900X and RTX 4070 Ti SUPER +(621.40), the median measured frame window was 1,706 ms. One window +spent 1,038 ms per frame waiting for the mapping lock across texture +refresh threads. A refresh needs its own mapped bytes to stay put, while +the current lock also makes it wait for changes elsewhere in the title's +address space. A remap can temporarily unmap a whole view to replace one +page, so any narrower lock has to cover the full span of that view. +`LEONIDA_TEXTURE_RANGE_LOCK=1` enables range protection for texture +refreshes. It keeps overlapping views locked through the remap and its +notifications. Reads of unrelated ranges can continue, unless they share +a lock in the fixed table. The switch is off by default. + +Series X opening-scene runs on `e8aa615` and the range-lock patch used the +same start state and copies of the same warmed shader and pipeline caches. +The hardware and driver were as above. Each run took 330 seconds and added +its listed switch to `base`. FPS and frame times are the median of the +script's windows after 170 seconds. Waits and deferred refreshes are +medians for windows with at least 500 draws per frame in that interval. + +| Switch added to `base` | FPS | Frame (ms) | Mapping wait (ms/frame) | Deferred refreshes/frame | +|---|---:|---:|---:|---:| +| None | 0.2 | 4034.3 | 2995.4 | 0 | +| `LEONIDA_TEXTURE_NO_WAIT=1` | 2.2 | 449.4 | 0 | 16.2 | +| `LEONIDA_TEXTURE_RANGE_LOCK=1` | 3.2 | 307.8 | 3.8 | 0 | + +The existing switch used kernel reads during contention and retried some +refreshes on later frames. Range locking kept the normal texture refresh +path. All three runs reached the opening scene and ended without a title +crash or device loss. The runs reached different points in the cutscene, +so these numbers cover the sampled windows of each run. Three early +range-lock samples had near-black centers while hundreds of pipelines +were pending. Shorter repeats in reverse order used a more complete +common pipeline cache and sampled from 100 to 190 seconds. The range +lock had visible output in all eight early samples. The existing switch +had one near-black sample. Median FPS in these shorter runs was 1.1 with +range locking and 4.0 with the existing switch. Equivalent gameplay +views are still needed to compare picture quality and frame rate. The +cost of the page remaps themselves remains part of P-4. **The passes over copies in the card's memory hash a piece with 64 threads.** The compare after a submission and the rehash after ranges go