diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index eec75f8c..e435750d 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -1366,21 +1366,27 @@ thread_local! { /// Read far more often than written: every slot a draw reads through a /// table is looked up here, on several recording threads at once in the /// world. Readers share it; only a view not seen before (a new table entry) -/// and a released resource take it alone. -static VIEWS: std::sync::OnceLock> = std::sync::OnceLock::new(); +/// and a released resource take it alone. With `VICTORY_VIEWS_SHARDED` (on +/// unless `0`) a reader takes a lock of its thread's own +/// (`crate::listcpu::ReadMostly`). +static VIEWS: std::sync::OnceLock> = std::sync::OnceLock::new(); static VIEW_SHAPES: std::sync::OnceLock> = std::sync::OnceLock::new(); #[inline] -fn views_lock() -> &'static std::sync::RwLock { +fn views_lock() -> &'static crate::listcpu::ReadMostly { VIEWS.get_or_init(|| { - std::sync::RwLock::new(Views { - list: Vec::new(), - index: FastMap::default(), - by_resource: FastMap::default(), - free: Vec::new(), - ownerless: std::collections::VecDeque::new(), - }) + crate::listcpu::ReadMostly::new( + Views { + list: Vec::new(), + index: FastMap::default(), + by_resource: FastMap::default(), + free: Vec::new(), + ownerless: std::collections::VecDeque::new(), + }, + crate::listcpu::views_sharded, + 0, + ) }) } @@ -1706,32 +1712,26 @@ fn words_for(view: View) -> [u32; 2] { views_write().entry(view) } -fn views_read() -> std::sync::RwLockReadGuard<'static, Views> { +fn views_read() -> crate::listcpu::ReadGuard<'static, Views> { let lock = views_lock(); - match lock.try_read() { - Ok(views) => views, - Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), - Err(std::sync::TryLockError::WouldBlock) => { - let started = std::time::Instant::now(); - let views = lock.read().unwrap_or_else(|e| e.into_inner()); - waited(1, started); - views - } + if let Some(views) = lock.try_read() { + return views; } + let started = std::time::Instant::now(); + let views = lock.read(); + waited(1, started); + views } -fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { +fn views_write() -> crate::listcpu::WriteGuard<'static, Views> { let lock = views_lock(); - match lock.try_write() { - Ok(views) => views, - Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), - Err(std::sync::TryLockError::WouldBlock) => { - let started = std::time::Instant::now(); - let views = lock.write().unwrap_or_else(|e| e.into_inner()); - waited(1, started); - views - } + if let Some(views) = lock.try_write() { + return views; } + let started = std::time::Instant::now(); + let views = lock.write(); + waited(1, started); + views } fn shapes_read() -> std::sync::RwLockReadGuard<'static, ViewShapes> { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index df4f86c4..d8063215 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -68,6 +68,7 @@ mod port; #[cfg(windows)] mod land; pub mod list; +mod listcpu; pub mod object; pub mod pipeline; #[cfg(windows)] diff --git a/crates/victory-gpu/src/listcpu.rs b/crates/victory-gpu/src/listcpu.rs new file mode 100644 index 00000000..2fd00b04 --- /dev/null +++ b/crates/victory-gpu/src/listcpu.rs @@ -0,0 +1,383 @@ +//! Cuts of the processor time the threads that translate the title's list +//! calls spend on lookups whose answer comes back the same, draw after draw. +//! In a busy crowded area the eight list threads used 281 ms of processor a +//! frame, much of it in short lookups behind locks every one of them takes: +//! the texture made for a view of placed memory (a mutex over the whole table +//! of them), what a descriptor's record names (a lock over every view of the +//! run), the host copy of the memory a buffer view names (another over every +//! title buffer, and one over the windows outside them). Taking a lock shared +//! by all threads writes its cache line, which goes from processor to +//! processor with every read even when nobody writes the table. +//! +//! Each cut has a switch of its own, on unless `0`; diagnostics builds can +//! turn it while the title runs (`VICTORY_AB`). What a cut answers is what +//! the lookup it stands for answers: tests below and in the modules hold that. +//! +//! Measured inside runs +//! (`VICTORY_AB`, 10 s phases in a mixed order in a busy area, drift fitted): +//! the list threads' processor time 16 ms a frame less with the three on 32 +//! logical processors (of 255), 14 less held to 12 (of 209). + +/// A switch that is on unless its variable is `0` (or `VICTORY_AB` names it: +/// on and off while the title runs). +macro_rules! asked { + ($name:literal) => {{ + static ASKED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let asked = ASKED.get_or_init(|| { + #[cfg(all(windows, feature = "diagnostics"))] + if let Some(bit) = crate::ab::bit($name) { + return Err(bit); + } + Ok(std::env::var_os($name).is_none_or(|v| v != "0")) + }); + match *asked { + Ok(on) => on, + #[cfg(all(windows, feature = "diagnostics"))] + Err(bit) => crate::ab::on(bit), + #[cfg(not(all(windows, feature = "diagnostics")))] + Err(_) => true, + } + }}; +} + +/// `VICTORY_PLACED_SEEN` (on unless `0`): a thread remembers the textures it +/// was given for views of placed memory (`crate::resource`'s `texture_at`: an +/// address and a resource description) and takes a remembered one without +/// the table of them, which every list thread locked for every such view a +/// draw read (and walked: a B-tree of 64-byte keys). A texture made for a +/// place and a description is kept for the run (the table is only ever added +/// to), so a remembered answer stays the table's. +pub(crate) fn placed_seen() -> bool { + asked!("VICTORY_PLACED_SEEN") +} + +/// `VICTORY_VIEWS_SHARDED` (on unless `0`): the table of every view the title +/// wrote (`crate::descriptor`'s `VIEWS`), which every list thread reads for +/// every slot a draw reads, is read under a lock of the reading thread's own +/// ([`ReadMostly`]) instead of one lock all of them share. +pub(crate) fn views_sharded() -> bool { + asked!("VICTORY_VIEWS_SHARDED") +} + +/// `VICTORY_SHADOW_SHARDED` (on unless `0`): the tables of the host copies of +/// title memory (`crate::shadow`'s `BUFFERS`, the title's buffers, and +/// `LOOSE`, the windows of memory outside them), which every list thread +/// reads for every buffer a draw names, are read as [`views_sharded`] reads +/// the views'. +pub(crate) fn shadow_sharded() -> bool { + asked!("VICTORY_SHADOW_SHARDED") +} + +/// Locks a reader may take ([`ReadMostly`]): one of [`SHARDS`] by its +/// thread, or (the switch off) the whole's, the last. +const SHARDS: usize = 16; +const WHOLE: usize = SHARDS; + +/// [`ReadMostly`]s there may be ([`ReadMostly::new`]'s `id`): 0 the views, +/// 1 and 2 the host copies of title memory, 3 a test's. +const READ_MOSTLY: usize = 4; + +/// A lock on a cache line of its own (and its neighbour's: the processor +/// fetches lines in pairs). +#[repr(align(128))] +struct Padded(std::sync::RwLock<()>); + +/// Which of [`SHARDS`] this thread reads under. +fn shard() -> usize { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + thread_local! { + static MINE: usize = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % SHARDS; + } + MINE.with(|m| *m) +} + +thread_local! { + /// By [`ReadMostly`] (its `id`): how many of its read guards this thread + /// holds, and the lock the first of them took, which the others take + /// too. + static HELD: [std::cell::Cell<(u32, usize)>; READ_MOSTLY] = + const { [const { std::cell::Cell::new((0, 0)) }; READ_MOSTLY] }; +} + +/// Something read far more often than written, by many threads at once. +/// A reader takes the whole's lock, or with `sharded` (its switch, which +/// may turn while the title runs) the lock of its own thread among +/// [`SHARDS`], each on lines of its own: readers on different processors +/// then write no line another reads. A writer takes every lock in order, so +/// that it is alone whichever lock the readers took. A thread that reads +/// again while it reads takes the lock it took first (a writer waiting +/// between two different ones would wait for it forever). Readers and +/// writers exclude each other exactly as with one `RwLock`. +pub(crate) struct ReadMostly { + locks: [Padded; SHARDS + 1], + data: std::cell::UnsafeCell, + sharded: fn() -> bool, + id: usize, +} + +// SAFETY: the data is reached only through the guards, a reader's under a +// lock every writer takes for writing, a writer's under all of them. +unsafe impl Send for ReadMostly {} +// SAFETY: as above; readers on several threads share `&T`. +unsafe impl Sync for ReadMostly {} + +impl ReadMostly { + /// `id`: a number of its own below [`READ_MOSTLY`]. + pub(crate) const fn new(data: T, sharded: fn() -> bool, id: usize) -> Self { + assert!(id < READ_MOSTLY); + Self { + locks: [const { Padded(std::sync::RwLock::new(())) }; SHARDS + 1], + data: std::cell::UnsafeCell::new(data), + sharded, + id, + } + } + + /// The lock this thread reads under now, and how many read guards of + /// this one it holds already. + fn reader(&self) -> (u32, usize) { + let id = self.id; + // (A thread past its locals reads under the whole's lock.) + HELD.try_with(|held| { + let (depth, first) = held[id].get(); + let at = if depth > 0 { + first + } else if (self.sharded)() { + shard() + } else { + WHOLE + }; + (depth, at) + }) + .unwrap_or((0, WHOLE)) + } + + /// Shared access (a lock that excludes writers only). + pub(crate) fn read(&self) -> ReadGuard<'_, T> { + let (depth, at) = self.reader(); + let held = self.locks[at].0.read().unwrap_or_else(|e| e.into_inner()); + let _ = HELD.try_with(|h| h[self.id].set((depth + 1, at))); + // SAFETY: a read lock is held that every writer takes for writing. + ReadGuard { _held: held, id: self.id, data: unsafe { &*self.data.get() } } + } + + /// [`Self::read`] if no writer holds or waits for the lock it would take. + pub(crate) fn try_read(&self) -> Option> { + let (depth, at) = self.reader(); + let held = match self.locks[at].0.try_read() { + Ok(held) => held, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => return None, + }; + let _ = HELD.try_with(|h| h[self.id].set((depth + 1, at))); + // SAFETY: as in `read`. + Some(ReadGuard { _held: held, id: self.id, data: unsafe { &*self.data.get() } }) + } + + /// Sole access. + pub(crate) fn write(&self) -> WriteGuard<'_, T> { + let locks = std::array::from_fn(|i| self.locks[i].0.write().unwrap_or_else(|e| e.into_inner())); + // SAFETY: every lock a reader may take is held for writing. + WriteGuard { _locks: locks, data: unsafe { &mut *self.data.get() } } + } + + /// [`Self::write`] if no reader or writer holds any of the locks now. + pub(crate) fn try_write(&self) -> Option> { + let mut held = Vec::with_capacity(SHARDS + 1); + for lock in &self.locks { + match lock.0.try_write() { + Ok(guard) => held.push(guard), + Err(std::sync::TryLockError::Poisoned(e)) => held.push(e.into_inner()), + // (Those taken are let go as `held` drops.) + Err(std::sync::TryLockError::WouldBlock) => return None, + } + } + let locks: [std::sync::RwLockWriteGuard<'_, ()>; SHARDS + 1] = held.try_into().ok()?; + // SAFETY: as in `write`. + Some(WriteGuard { _locks: locks, data: unsafe { &mut *self.data.get() } }) + } +} + +/// [`ReadMostly::read`]'s guard. +pub(crate) struct ReadGuard<'a, T> { + _held: std::sync::RwLockReadGuard<'a, ()>, + id: usize, + data: &'a T, +} + +impl Drop for ReadGuard<'_, T> { + fn drop(&mut self) { + let id = self.id; + // (While the thread ends its locals may go after this table.) + let _ = HELD.try_with(|held| { + let (depth, first) = held[id].get(); + held[id].set((depth.saturating_sub(1), first)); + }); + } +} + +impl std::ops::Deref for ReadGuard<'_, T> { + type Target = T; + fn deref(&self) -> &T { + self.data + } +} + +/// [`ReadMostly::write`]'s guard. +pub(crate) struct WriteGuard<'a, T> { + _locks: [std::sync::RwLockWriteGuard<'a, ()>; SHARDS + 1], + data: &'a mut T, +} + +impl std::ops::Deref for WriteGuard<'_, T> { + type Target = T; + fn deref(&self) -> &T { + self.data + } +} + +impl std::ops::DerefMut for WriteGuard<'_, T> { + fn deref_mut(&mut self) -> &mut T { + self.data + } +} + +/// A small table a thread keeps of answers by key: one place a key (by its +/// hash), the last answer put there wins. `N` is a power of two. +pub(crate) struct Remembered { + places: Vec>, +} + +impl Remembered { + pub(crate) const fn new() -> Self { + Self { places: Vec::new() } + } + + /// The answer kept for `key` (whose hash is `hash`), if any. + #[inline] + pub(crate) fn get(&self, hash: u64, key: &K) -> Option { + match self.places.get(Self::at(hash))? { + Some((k, v)) if k == key => Some(*v), + _ => None, + } + } + + /// Keeps `value` for `key`. + pub(crate) fn put(&mut self, hash: u64, key: K, value: V) { + if self.places.is_empty() { + self.places.resize_with(N, || None); + } + let at = Self::at(hash); + self.places[at] = Some((key, value)); + } + + #[inline] + fn at(hash: u64) -> usize { + (hash.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 40) as usize & (N - 1) + } +} + +/// A hash of words, for [`Remembered`]: two multiplications a word. +#[inline] +pub(crate) fn hash_words(seed: u64, words: &[u32]) -> u64 { + let mut h = seed ^ 0x243F_6A88_85A3_08D3; + for &w in words { + h = (h ^ u64::from(w)).wrapping_mul(0x0000_0100_0000_01B3).rotate_left(23); + } + h +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::Ordering::Relaxed; + + #[test] + fn a_remembered_answer_is_the_one_put_for_that_key() { + let mut r: Remembered<(u64, [u32; 14]), usize, 64> = Remembered::new(); + let key = (0x10_0000, [3; 14]); + let h = hash_words(key.0, &key.1); + assert_eq!(r.get(h, &key), None); + r.put(h, key, 7); + assert_eq!(r.get(h, &key), Some(7)); + // Another key that lands on the same place is not given its answer. + let other = (0x20_0000, [3; 14]); + assert_eq!(r.get(h, &other), None); + // Keys that differ in one word never share an answer. + for i in 0..14 { + let mut k = key; + k.1[i] ^= 1; + assert_eq!(r.get(hash_words(k.0, &k.1), &k), None); + } + } + + /// Writers keep two words equal; readers, some under the whole's lock and + /// some under their own while the switch turns on and off, never see + /// them differ, and every write lands; `try_write` and `try_read` give + /// way to a holder and take the lock once it is free. + #[test] + fn readers_never_see_a_write_half_done_whichever_lock_they_take() { + use std::sync::atomic::AtomicBool; + static SHARDED: AtomicBool = AtomicBool::new(false); + fn sharded() -> bool { + SHARDED.load(Relaxed) + } + static PAIR: ReadMostly<(u64, u64)> = ReadMostly::new((0, 0), sharded, 3); + const WRITES: u64 = 20_000; + let stop = std::sync::Arc::new(AtomicBool::new(false)); + std::thread::scope(|s| { + let turner = stop.clone(); + s.spawn(move || { + while !turner.load(Relaxed) { + SHARDED.fetch_xor(true, Relaxed); + std::thread::yield_now(); + } + }); + let mut readers = Vec::new(); + for _ in 0..6 { + let stop = stop.clone(); + readers.push(s.spawn(move || { + let mut looks = 0u64; + while !stop.load(Relaxed) { + let pair = PAIR.read(); + assert_eq!(pair.0, pair.1, "a write seen half done"); + // Read again while reading: the same lock, no wait. + let again = PAIR.read(); + assert_eq!(again.0, pair.0); + looks += 1; + } + looks + })); + } + let writers: Vec<_> = (0..2) + .map(|_| { + s.spawn(|| { + for _ in 0..WRITES { + let mut pair = PAIR.write(); + pair.0 += 1; + std::hint::spin_loop(); + pair.1 += 1; + } + }) + }) + .collect(); + for w in writers { + w.join().unwrap(); + } + stop.store(true, Relaxed); + for r in readers { + assert!(r.join().unwrap() > 0); + } + }); + let pair = PAIR.read(); + assert_eq!(*pair, (2 * WRITES, 2 * WRITES)); + assert!(PAIR.try_write().is_none(), "a reader holds it"); + drop(pair); + let mut pair = PAIR.try_write().expect("nobody holds it"); + pair.0 += 1; + pair.1 += 1; + assert!(std::thread::scope(|s| s.spawn(|| PAIR.try_read().is_none()).join().unwrap()), "a writer holds it"); + drop(pair); + assert_eq!(*PAIR.try_read().expect("nobody holds it"), (2 * WRITES + 1, 2 * WRITES + 1)); + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index c2b5d563..78d26bf0 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -4121,7 +4121,8 @@ pub(crate) extern "system" fn create_at_address( /// address, made the first time a draw reads one. /// The resource is kept for the run (views and lists name its address); /// its host texture is let go when nothing names it any more -/// ([`let_go_idle`]) and made again on the next use. +/// ([`let_go_idle`]) and made again on the next use. Entries are only ever +/// added: `VICTORY_PLACED_SEEN` ([`texture_at`]) lets threads remember them. #[cfg(windows)] static PLACED_TEXTURES: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); @@ -4224,9 +4225,39 @@ pub(crate) fn texture_held(resource: This) -> Option<(u32, crate::texture::Diges } /// The resource for a texture placed at `address` with the resource -/// description `desc` (as words), made on first use. +/// description `desc` (as words), made on first use. With +/// `VICTORY_PLACED_SEEN` (on unless `0`, `crate::listcpu::placed_seen`) a +/// thread takes what it was given before for the same place and description +/// without the table: what the table holds for them is kept for the run. #[cfg(windows)] pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { + if crate::listcpu::placed_seen() { texture_at_seen(address, desc) } else { texture_at_table(address, desc) } +} + +/// [`texture_at`] with `VICTORY_PLACED_SEEN`. +#[cfg(windows)] +fn texture_at_seen(address: u64, desc: &[u32; 14]) -> Option { + let hash = crate::listcpu::hash_words(address, desc); + let key = (address, *desc); + if let Some(r) = PLACED_SEEN.with(|seen| seen.borrow().get(hash, &key)) { + return Some(r as This); + } + let r = texture_at_table(address, desc)?; + PLACED_SEEN.with(|seen| seen.borrow_mut().put(hash, key, r as usize)); + Some(r) +} + +#[cfg(windows)] +thread_local! { + /// What [`texture_at`] gave this thread lately, by place and description + /// as asked (`VICTORY_PLACED_SEEN`). + static PLACED_SEEN: std::cell::RefCell> = + const { std::cell::RefCell::new(crate::listcpu::Remembered::new()) }; +} + +/// [`texture_at`] by the table of placed textures ([`PLACED_TEXTURES`]). +#[cfg(windows)] +fn texture_at_table(address: u64, desc: &[u32; 14]) -> Option { // Words 1 and 13 of the description are the filler of its layout // (after the dimension, and at the end): the title leaves there what // its stack held, and two views of one texture that differed only in @@ -6033,6 +6064,49 @@ float4 lit() : SV_Target { return 1.0; } assert!(more.serial != copy.serial && more.grown.load(std::sync::atomic::Ordering::Relaxed)); } + /// `VICTORY_PLACED_SEEN`: what a thread remembers of the placed textures + /// is what the table gives, for the same place and description asked + /// again, with other filler words, at other places, from another thread, + /// and after many others crowded its table. + #[cfg(windows)] + #[test] + fn a_remembered_placed_texture_is_the_tables() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + if crate::host::host().is_none() { + return; + } + // 64x64 RGBA8, one level (2D), and a buffer (never a texture). + let texture = [3u32, 0, 0, 0, 64, 0, 64, 0x1_0001, 28, 1, 0, 0, 0, 0]; + let buffer = [BUFFER, 0, 0, 0, 0x1000, 0, 1, 0x10001, 0, 1, 0, 0, 0, 0]; + let bytes = placed_bytes(&texture).unwrap(); + const PLACES: usize = 40; + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), bytes as usize * PLACES, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) } as u64; + assert_ne!(at, 0); + let asks: Vec<(u64, [u32; 14])> = (0..PLACES as u64) + .flat_map(|n| { + let mut filler = texture; + (filler[1], filler[13]) = (0x55 + n as u32, 0xaa); + [(at + n * bytes, texture), (at + n * bytes, filler), (at + n * bytes, buffer)] + }) + .collect(); + let table: Vec> = asks.iter().map(|(a, d)| texture_at_table(*a, d).map(|r| r as usize)).collect(); + for round in 0..3 { + for ((a, d), want) in asks.iter().zip(&table) { + assert_eq!(texture_at_seen(*a, d).map(|r| r as usize), *want, "round {round} at {a:#x}"); + } + } + // Crowded out: a thousand other places later, the same answers. + for n in 0..1024u64 { + let _ = texture_at_seen(0x7_0000_0000 + n * 0x1000, &buffer); + } + let again: Vec> = asks.iter().map(|(a, d)| texture_at_seen(*a, d).map(|r| r as usize)).collect(); + assert_eq!(again, table); + // Another thread, its own table, the same answers. + let other = std::thread::spawn(move || asks.iter().map(|(a, d)| texture_at_seen(*a, d).map(|r| r as usize)).collect::>()); + assert_eq!(other.join().unwrap(), table); + } + #[test] fn a_block_of_textures_wants_room_for_itself_and_for_what_is_to_come() { const MB: u64 = 1 << 20; diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 2323f6d7..b58c179b 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -935,7 +935,7 @@ pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc, Arc usize { static NEXT: AtomicU64 = AtomicU64::new(0); let mut all: Vec> = buffers_read().values().filter_map(|e| e.shadow.clone()).collect(); - all.extend(LOOSE.write().unwrap_or_else(|e| e.into_inner()).values().cloned()); + all.extend(LOOSE.write().values().cloned()); all.retain(|s| s.place.is_none() && s.watched.load(Ordering::Relaxed) == 1); all.sort_by_key(|s| s.id); let next = NEXT.load(Ordering::Relaxed); @@ -4155,7 +4155,7 @@ static LET_GO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; #[cfg(feature = "diagnostics")] pub(crate) fn windows() -> [u64; 3] { let asked: u64 = { - let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); + let loose = LOOSE.write(); loose .values() .map(|s| { @@ -4179,7 +4179,7 @@ pub(crate) fn windows() -> [u64; 3] { #[cfg(feature = "diagnostics")] pub(crate) fn window_use() -> [u64; 8] { let mut out = [0u64; 8]; - let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); + let loose = LOOSE.write(); for s in loose.values() { let pages = s.copied.iter().filter(|at| at.load(Ordering::Relaxed) != 0).count() as u64; out[0] += (pages * PAGE as u64).min(s.len); @@ -4223,7 +4223,7 @@ pub(crate) fn let_go_idle() { let gone: Vec> = { // Held from the look to the removal: `loose` hands a copy out // under the same lock, so none is handed out in between. - let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner()); + let mut map = LOOSE.write(); if map.is_empty() { return; } @@ -4260,7 +4260,7 @@ pub(crate) fn let_go_idle() { #[cfg(feature = "diagnostics")] pub(crate) fn memory() -> [u64; 6] { let (windows, window_bytes) = { - let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); + let loose = LOOSE.write(); // Each copy once: a window may stand under several keys. let mut seen = std::collections::HashSet::new(); let bytes: u64 = loose @@ -6541,11 +6541,14 @@ struct Entry { /// Title buffers by (start address, resource), with their copy once made. /// /// Read by every view a draw names, on all recording threads at once, and -/// written when a buffer comes, goes or gets its copy: readers share it. -static BUFFERS: std::sync::RwLock> = std::sync::RwLock::new(BTreeMap::new()); - -fn buffers() -> std::sync::RwLockWriteGuard<'static, BTreeMap<(u64, usize), Entry>> { - let map = BUFFERS.write().unwrap_or_else(|e| e.into_inner()); +/// written when a buffer comes, goes or gets its copy: readers share it +/// (with `VICTORY_SHADOW_SHARDED`, on unless `0`, each under a lock of its +/// thread's own, `crate::listcpu::ReadMostly`). +static BUFFERS: crate::listcpu::ReadMostly> = + crate::listcpu::ReadMostly::new(BTreeMap::new(), crate::listcpu::shadow_sharded, 1); + +fn buffers() -> crate::listcpu::WriteGuard<'static, BTreeMap<(u64, usize), Entry>> { + let map = BUFFERS.write(); // What threads remember of it ([`FOUND`]) is of before. BUFFERS_CHANGED.fetch_add(1, Ordering::SeqCst); map @@ -6604,8 +6607,8 @@ fn remember(address: u64, len: u64, changed: u64, shadow: &Arc) { }); } -fn buffers_read() -> std::sync::RwLockReadGuard<'static, BTreeMap<(u64, usize), Entry>> { - BUFFERS.read().unwrap_or_else(|e| e.into_inner()) +fn buffers_read() -> crate::listcpu::ReadGuard<'static, BTreeMap<(u64, usize), Entry>> { + BUFFERS.read() } /// A title buffer exists at `start` (`len` bytes). @@ -6655,7 +6658,7 @@ pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 { let end = at.saturating_add(len); let mut gone: Vec> = Vec::new(); { - let mut map = LOOSE.write().unwrap_or_else(|e| e.into_inner()); + let mut map = LOOSE.write(); let keys: Vec<(u64, u64)> = map .range((at.saturating_sub(WINDOW), 0)..(end, 0)) .filter(|(key, shadow)| shadow.place.is_some() && key.0 + key.1 > at) @@ -6685,7 +6688,7 @@ pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 { /// bytes, true). pub(crate) fn spans() -> Vec<(u64, u64, bool)> { let mut spans: Vec<(u64, u64, bool)> = buffers_read().iter().map(|(key, entry)| (key.0, entry.end - key.0, false)).collect(); - let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); + let loose = LOOSE.write(); spans.extend(loose.keys().map(|&(start, len)| (start, len, true))); spans } @@ -6974,7 +6977,7 @@ fn fine() -> bool { /// which is copied once for each. #[cfg(feature = "diagnostics")] pub(crate) fn window_cover() -> u64 { - let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); + let loose = LOOSE.write(); cover(loose.keys().copied()) } @@ -7102,8 +7105,10 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option> { Some(shadow) } -/// Copies of title memory outside buffers, by (start, length). -static LOOSE: std::sync::RwLock>> = std::sync::RwLock::new(BTreeMap::new()); +/// Copies of title memory outside buffers, by (start, length) (read as +/// [`BUFFERS`] is). +static LOOSE: crate::listcpu::ReadMostly>> = + crate::listcpu::ReadMostly::new(BTreeMap::new(), crate::listcpu::shadow_sharded, 2); fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option> { let (cell, _) = window_of(address, end, WINDOW); @@ -7127,13 +7132,13 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option String { .values() .filter_map(|e| e.shadow.as_deref().map(|s| (s.gpu, s.start, s.len))) .collect(); - all.extend( - LOOSE - .read() - .unwrap_or_else(|e| e.into_inner()) - .values() - .map(|s| (s.gpu, s.start, s.len)), - ); + all.extend(LOOSE.read().values().map(|s| (s.gpu, s.start, s.len))); let below = all.iter().filter(|c| c.0 <= va).max(); let above = all.iter().filter(|c| c.0 > va).min(); let mut text = match below {