diff --git a/d3d12/apps/leonida/src/warm.rs b/d3d12/apps/leonida/src/warm.rs index e72cda75a7..6d004fe384 100644 --- a/d3d12/apps/leonida/src/warm.rs +++ b/d3d12/apps/leonida/src/warm.rs @@ -49,7 +49,9 @@ pub fn run(jobs: Option, limit: Option, again: bool, used: bool, t let bad = std::fs::read_to_string(&bad_file).unwrap_or_default(); let bad: HashSet<&str> = bad.lines().filter_map(|l| l.split(' ').next()).collect(); let early = std::fs::read_to_string(dir.join("early-pipelines.txt")).unwrap_or_default(); - let early: HashSet<&str> = early.lines().collect(); + // A key, then the run that last drew with it (a list of an older build + // has the key alone). + let early: HashSet<&str> = early.lines().filter_map(|l| l.split(' ').next()).collect(); // Those earlier runs drew with first, the others in no order (by key). let mut all: Vec = (0..keys.len()) .filter(|&n| { diff --git a/d3d12/crates/leonida-gpu/Cargo.toml b/d3d12/crates/leonida-gpu/Cargo.toml index 617a774c2f..25614a09f4 100644 --- a/d3d12/crates/leonida-gpu/Cargo.toml +++ b/d3d12/crates/leonida-gpu/Cargo.toml @@ -38,7 +38,7 @@ mimalloc = ["dep:mimalloc"] workspace = true [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Cryptography", "Win32_Security_WinTrust", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] } +windows-sys = { workspace = true, features = ["Win32_Devices_DeviceAndDriverInstallation", "Win32_Foundation", "Win32_Security", "Win32_Security_Cryptography", "Win32_Security_WinTrust", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D_Fxc", diff --git a/d3d12/crates/leonida-gpu/src/copystat.rs b/d3d12/crates/leonida-gpu/src/copystat.rs index e041177317..c031255f1a 100644 --- a/d3d12/crates/leonida-gpu/src/copystat.rs +++ b/d3d12/crates/leonida-gpu/src/copystat.rs @@ -183,22 +183,102 @@ pub(crate) fn mode() -> u8 { }) } +/// One set's part of a [`Banked`] map, in lines of the processor's memory +/// of its own. +#[repr(align(64))] +struct Part(Mutex>>); + +/// A map of what was copied or compared since the last line, in one part +/// per set of counters: each thread adds to its own set's part ([`bank`]), +/// the line merges them ([`Banked::take`]). One map behind one lock had +/// every host-copy refresh that copied anything ([`range`], on the wide +/// threads, in parallel) and every range compared after a submission +/// ([`compared`], on the land threads) wait for the same process-wide lock, +/// in the build played and measured (`target\diag`, the diagnostics +/// feature). What the line says is the same: the parts' entries are summed. +struct Banked([Part; BANKS]); + +impl Banked { + const fn new() -> Self { + Banked([const { Part(Mutex::new(None)) }; BANKS]) + } + + /// The entry of `key` in this thread's part, made by `new` if there is + /// none, given to `add`. + fn add(&self, key: K, new: impl FnOnce() -> V, add: impl FnOnce(&mut V)) { + let mut part = lock_part(&self.0[bank()].0); + add(part.get_or_insert_with(HashMap::new).entry(key).or_insert_with(new)); + } + + /// Every part's entries, those of one key put together by `merge`; the + /// parts are empty after. + fn take(&self, merge: impl Fn(&mut V, V)) -> HashMap { + let mut all = HashMap::new(); + for part in &self.0 { + let Some(map) = part.0.lock().unwrap_or_else(|e| e.into_inner()).take() else { + continue; + }; + for (key, v) in map { + match all.entry(key) { + std::collections::hash_map::Entry::Occupied(mut e) => merge(e.get_mut(), v), + std::collections::hash_map::Entry::Vacant(e) => { + e.insert(v); + } + } + } + } + all + } +} + +// Waits for a part's lock on this thread, for the test (plain data: no +// destructor, see AGENTS.md). +#[cfg(test)] +thread_local!(static PART_WAITS: std::cell::Cell = const { std::cell::Cell::new(0) }); + +/// A part's lock (another thread of the same set, or the line taking it). +fn lock_part(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + match m.try_lock() { + Ok(part) => part, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + #[cfg(test)] + PART_WAITS.with(|n| n.set(n.get() + 1)); + m.lock().unwrap_or_else(|e| e.into_inner()) + } + } +} + /// Per source range (start, length): copies, bytes, microseconds, memory type. -type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>; -static RANGES: Mutex> = Mutex::new(None); +static RANGES: Banked<(usize, usize), (u64, u64, u64, u32)> = Banked::new(); + +/// [`RANGES`]' entries since the last line, merged. +fn take_ranges() -> HashMap<(usize, usize), (u64, u64, u64, u32)> { + RANGES.take(|e, v| { + e.0 += v.0; + e.1 += v.1; + e.2 += v.2; + }) +} /// Per range copied whole because its memory is not watched (start, /// length): copies and microseconds. -static WHOLE: Mutex>> = Mutex::new(None); +static WHOLE: Banked<(usize, usize), (u64, u64)> = Banked::new(); /// `len` bytes at `src`, memory that is not watched, were copied whole in /// `us`. pub(crate) fn whole(src: usize, len: usize, us: u64) { add(C::WholeUs, us); - let mut map = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); - let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); - e.0 += 1; - e.1 += us; + WHOLE.add((src, len), || (0, 0), |e| { + e.0 += 1; + e.1 += us; + }); +} + +/// Adds the two counts of an entry of [`WHOLE`] or [`COMPARED`]. +fn sum_pair(e: &mut (u64, u64), v: (u64, u64)) { + e.0 += v.0; + e.1 += v.1; } /// The longest wait for the card since the last line: microseconds, and @@ -288,27 +368,24 @@ pub(crate) fn barrier_test() -> u8 { /// Per range compared after a submission (start, length): times, and the /// bytes of it written back to the title. -static COMPARED: Mutex>> = Mutex::new(None); +static COMPARED: Banked<(usize, usize), (u64, u64)> = Banked::new(); /// `len` bytes at `src` were compared after a submission and `written` of /// them put back into title memory. pub(crate) fn compared(src: usize, len: usize, written: usize) { - let mut map = COMPARED.lock().unwrap_or_else(|e| e.into_inner()); - let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); - e.0 += 1; - e.1 += written as u64; + COMPARED.add((src, len), || (0, 0), |e| { + e.0 += 1; + e.1 += written as u64; + }); } /// A copy of `len` bytes from `src` (memory type `kind`) took `us`. pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) { - let mut map = RANGES.lock().unwrap_or_else(|e| e.into_inner()); - let e = map - .get_or_insert_with(HashMap::new) - .entry((src, len)) - .or_insert((0, 0, 0, kind)); - e.0 += 1; - e.1 += len as u64; - e.2 += us; + RANGES.add((src, len), || (0, 0, 0, kind), |e| { + e.0 += 1; + e.1 += len as u64; + e.2 += us; + }); } /// Our own allocations alive now, by size of block (under 4 KiB, to 64 KiB, @@ -440,6 +517,51 @@ unsafe impl std::alloc::GlobalAlloc for Counting { #[global_allocator] static HEAP: Counting = Counting; +#[cfg(test)] +mod banked_tests { + use super::{PART_WAITS, bank, range, take_ranges}; + + /// Eight threads refreshing the same ranges at once each add to their + /// own part, without waiting for each other's lock (with one map for all + /// they waited thousands of times), and the line has every refresh. + #[test] + fn parallel_refreshes_do_not_wait_and_all_count() { + const THREADS: usize = 8; + const CALLS: u64 = 20_000; + const RANGES: usize = 16; + let at = |i: usize| 0x7e57_0000_0000 + i * 0x1_0000; + let start = std::sync::Barrier::new(THREADS); + let seen: Vec<(usize, u64)> = std::thread::scope(|s| { + let threads: Vec<_> = (0..THREADS) + .map(|_| { + s.spawn(|| { + let set = bank(); + start.wait(); + let before = PART_WAITS.with(std::cell::Cell::get); + for i in 0..CALLS { + let r = i as usize % RANGES; + range(at(r), 0x100 + r, 3, 0); + } + (set, PART_WAITS.with(std::cell::Cell::get) - before) + }) + }) + .collect(); + threads.into_iter().map(|t| t.join().unwrap()).collect() + }); + let sets: std::collections::BTreeSet = seen.iter().map(|s| s.0).collect(); + let waits: u64 = seen.iter().map(|s| s.1).sum(); + // (Two of them share a set only if 32 other threads began between them.) + if sets.len() == THREADS { + assert_eq!(waits, 0, "waits for a part's lock"); + } + let ranges = take_ranges(); + let each = THREADS as u64 * CALLS / RANGES as u64; + for r in 0..RANGES { + assert_eq!(ranges.get(&(at(r), 0x100 + r)), Some(&(each, each * (0x100 + r) as u64, 3 * each, 0))); + } + } +} + #[cfg(test)] mod command_tests { /// Commands are summed by pipeline and first word; those without a @@ -741,6 +863,7 @@ fn log_memory() { let made: Vec = crate::host::MADE.iter().map(|m| m.load(Relaxed)).collect(); let windows = crate::shadow::windows(); let stagings = crate::texture::let_go(); + let released = crate::texture::released(); let census = crate::resource::census(); let kinds: Vec = crate::resource::KINDS.iter().map(|k| k.load(Relaxed)).collect(); let card = crate::host::host() @@ -847,19 +970,25 @@ fn log_memory() { mb(targets[9]), ); tracing::info!( - "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \ - {:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \ - asked for in each", + "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging states \ + (buffers {:.0} MB); {} staging buffers let go once copied {:.0} MB, {} made again by a \ + detiling (LEONIDA_STAGING_RELEASE); of the windows alive, {:.0} MB lie between the lowest \ + and highest address asked for in each", windows[0], mb(windows[1]), stagings[0], mb(stagings[1]), + released[0], + mb(released[1]), + released[2], mb(windows[2]), ); tracing::info!( "memory: {:.0} MB private ({:.0} MB of it in memory; the PC has {:.0} MB free and {:.0} MB \ left to commit); host copies of title memory: {} alive {:.0} MB, of them {} windows \ - outside buffers {:.0} MB; snapshot buffers kept: {} reserving {:.0} MB; staging of \ + outside buffers {:.0} MB, {} whose CPU side is title memory itself, {:.0} MB of their own \ + not made ({} given one since the start; LEONIDA_CARD_FROM_TITLE); snapshot buffers kept: {} \ + reserving {:.0} MB; staging of \ textures: {} alive {:.0} MB, {} kept by their texture; host textures: {} alive {:.0} MB, \ {} placed in title memory; made so far: {} upload buffers {:.0} MB, {} shared buffers \ {:.0} MB, {} card buffers {:.0} MB", @@ -871,6 +1000,9 @@ fn log_memory() { mb(copies[1]), copies[2], mb(copies[3]), + copies[6], + mb(copies[7]), + copies[8], copies[4], mb(copies[5]), staged[0], @@ -887,8 +1019,20 @@ fn log_memory() { mb(made[5]), ); tracing::info!( - "memory, placed textures: {} of them were asked for again with other filler words in their description (one resource and host copy each since the filler left the key; LEONIDA_PLACED_FILLER=1 keeps it)", - crate::resource::placed_filler_twins() + "memory, placed textures: {} of them were asked for again with other filler words in their description (one resource and host copy each since the filler left the key; LEONIDA_PLACED_FILLER=1 keeps it); \ + {} released since the start, nothing having named them for a minute and 600 frames with no host copy \ + (LEONIDA_PLACED_EVICT=0 keeps them for the run); the most in the table at a look: {}; host copies let go \ + since the start because their title memory was unmapped: {} ({:.0} MB; LEONIDA_PLACED_UNMAPPED=0 keeps \ + them to the card's idle time); their release {:.2} ms a look of the sweep, the longest {:.1}", + crate::resource::placed_filler_twins(), + crate::resource::PLACED_EVICTED[0].load(Relaxed), + crate::resource::PLACED_EVICTED[1].load(Relaxed), + crate::resource::PLACED_UNMAPPED_GONE[0].load(Relaxed), + mb(crate::resource::PLACED_UNMAPPED_GONE[1].load(Relaxed)), + crate::resource::PLACED_EVICT_US[0].load(Relaxed) as f64 + / 1e3 + / crate::resource::SWEPT_US[0].load(Relaxed).max(1) as f64, + crate::resource::PLACED_EVICT_US[1].load(Relaxed) as f64 / 1e3 ); // What the line above leaves open: what is alive of the buffers "made // so far", what the windows hold and what holds them, and what our own @@ -934,11 +1078,16 @@ fn log_memory() { // what host lists cost, the card's share that is the layer's own or // the title's no more, and which big blocks are ours. let lists: Vec = crate::host::LISTS.iter().map(|l| l.load(Relaxed)).collect(); + let pool = &crate::host::preludes::PRELUDES; + let preludes = pool.counts(); tracing::info!( "memory, more: views named whole in their records since the start: {} constant buffer \ views, {} views of placed memory; of the view table's entries {} are constant buffer \ - views and {} views of placed memory; shapes of placed views kept: {}; host lists: {} \ - made by the host, {} preludes made for them, private bytes grew {:.0} MB while \ + views and {} views of placed memory (of the two, {} let go unseen so far, \ + LEONIDA_VIEW_ADDRESSED_MOST); shapes of placed views kept: {}; host lists: {} \ + made by the host, {} preludes made for them ({} taken made ahead, {} made where \ + they were taken, {} made ahead and not taken yet, LEONIDA_PRELUDE_POOL), private \ + bytes grew {:.0} MB while \ lists were made; twins of depth textures: {:.0} MB; host copies of \ placed textures whose title memory is not mapped any more (estimate): {:.0} MB, of \ them still shown by a descriptor slot {:.0} MB; the pipeline library's mapped file \ @@ -947,9 +1096,13 @@ fn log_memory() { views[7], views[3], views[4], + views[8], views[5], lists[0], lists[1], + preludes[0], + preludes[1], + pool.len(), lists[2] as i64 as f64 / (1 << 20) as f64, mb(census[7]), mb(census[8]), @@ -1297,6 +1450,9 @@ pub(crate) fn log(frames: f64) { if let Some(line) = crate::host::fronts_line() { tracing::info!("{line}"); } + if let Some(line) = crate::host::summary_line() { + tracing::info!("{line}"); + } let [copies, blocks, opened, stores, unknown, full, stayed, copied_same, records] = [0, 1, 2, 3, 4, 5, 6, 7, 8].map(|n| crate::titlewrite::DONE[n].load(std::sync::atomic::Ordering::Relaxed)); tracing::info!( @@ -1342,8 +1498,7 @@ pub(crate) fn log(frames: f64) { c[C::PartsTogether as usize], ); // What is copied whole, largest first: memory nobody tells us about. - let whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()).take(); - let mut whole: Vec<_> = whole.into_iter().flatten().collect(); + let mut whole: Vec<_> = WHOLE.take(sum_pair).into_iter().collect(); whole.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); tracing::info!( " copied whole (memory not watched): {:.1} ms per frame in {} ranges; the largest follow", @@ -1442,8 +1597,7 @@ pub(crate) fn log(frames: f64) { ); // What is compared after submissions, largest first, and how much of // it shaders had written. - let compared = COMPARED.lock().unwrap_or_else(|e| e.into_inner()).take(); - let mut compared: Vec<_> = compared.into_iter().flatten().collect(); + let mut compared: Vec<_> = COMPARED.take(sum_pair).into_iter().collect(); compared.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); tracing::info!(" compared after submissions: {} ranges; the largest follow", compared.len()); for ((src, len), (n, written)) in compared.into_iter().take(8) { @@ -1481,8 +1635,7 @@ pub(crate) fn log(frames: f64) { .collect(); tracing::info!(" list calls by thread: {} threads; {}", recorders.len(), busiest.join(", ")); log_memory(); - let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take(); - let mut ranges: Vec<_> = ranges.into_iter().flatten().collect(); + let mut ranges: Vec<_> = take_ranges().into_iter().collect(); ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes)); for ((src, len), (n, bytes, us, _)) in ranges.into_iter().take(10) { use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; diff --git a/d3d12/crates/leonida-gpu/src/cores.rs b/d3d12/crates/leonida-gpu/src/cores.rs index 486ac560fd..b80bae347d 100644 --- a/d3d12/crates/leonida-gpu/src/cores.rs +++ b/d3d12/crates/leonida-gpu/src/cores.rs @@ -118,15 +118,58 @@ fn helpers_raised() -> bool { crate::toggled!("LEONIDA_HELPER_PRIORITY") } -/// A helper's priority ([`helpers_raised`]). [`Self::keep`] is called before -/// each piece of work; it asks the system only when the switch has changed. +/// Whether the thread that lands flights (`leonida-relay`, `host::relay_worker`) +/// runs above normal, as the threads it waits for do (`LEONIDA_RELAY_PRIORITY=1`; +/// off unless set and not `0`; `LEONIDA_AB` can flip it while the title runs). That thread +/// sets every title fence (`fence::set`) once a flight's bytes are in title +/// memory, and the title's busiest thread spins on such a fence's value +/// (`monitorx`/`mwaitx`, then `Sleep`, on the address `fence::gpu_address` +/// gave it: 72 % of its samples in a 30-second profile in the world), so the +/// time from the card's end of a flight to the fence set is the frame's. +/// It was only kept on the fast cores, which asks nothing of a processor with +/// one kind of cores (this PC's 7600X), and ran at normal among some twenty +/// busy title threads on twelve logical processors. +/// +/// Measured before (two timelines of five frames in the world, 171 of 172 +/// fences set by it; the profile): gaps inside its landings with no wait and +/// no wake in them, 3.8 ms after its copy queue's wait returned, 5.2 ms before +/// a fetch, 2.9 ms right before a fence set; per frame the tails above the +/// medians (0.04-0.06 ms) of its gathers, its fetches' sends and its wake to +/// its first landing came to 3.3 and 0.8 ms; of its 975 samples in 30 s, 894 +/// were waits (663 for the card, 175 for a flight), so the tails are its turn +/// to run, not its work. Above normal only, not higher: the pools of `land` +/// it hands pieces to run above normal themselves ([`helpers_raised`]), and +/// a relay above them could keep them from the cores its merge waits on. +/// Nothing it does, nor its order, changes: every merge, read-back and +/// write behind a flight still comes before the fence is set. +/// +/// Off by default: in the title (2026-11-30, RX 7900 XT, one `LEONIDA_AB` run +/// of 67 phases of 7 s in the world, four switches crossed) raising it made +/// the median frame 1.6 % slower (s.e. 1.9 %), the submitting thread's work +/// 1.4 % (s.e. 1.2 %) and the card's idle time 6.4 % longer (s.e. 6.2 %): +/// nothing gained, and every reading on the side of a loss. +pub(crate) fn relay_raised() -> bool { + crate::asked!("LEONIDA_RELAY_PRIORITY") +} + +/// A thread's priority, above normal while the switch it follows says so +/// ([`helpers_raised`] for the helpers, [`relay_raised`] for the relay). +/// [`Self::keep`] is called before each piece of work; it asks the system +/// only when the switch has changed. pub(crate) struct Priority { applied: Option, + raised: fn() -> bool, } impl Priority { + /// A helper's ([`helpers_raised`]). pub(crate) fn new() -> Self { - let mut priority = Self { applied: None }; + Self::following(helpers_raised) + } + + /// One that follows `raised`, asked for now. + pub(crate) fn following(raised: fn() -> bool) -> Self { + let mut priority = Self { applied: None, raised }; priority.keep(); priority } @@ -135,7 +178,7 @@ impl Priority { use windows_sys::Win32::System::Threading::{ GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_NORMAL, }; - let on = helpers_raised(); + let on = (self.raised)(); if self.applied == Some(on) { return; } @@ -171,4 +214,72 @@ mod tests { .join() .unwrap(); } + + fn own_priority() -> i32 { + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadPriority}; + // SAFETY: our own thread. + unsafe { GetThreadPriority(GetCurrentThread()) } + } + + /// A priority that follows a switch is above normal while it is on and + /// normal while it is off, and is asked of the system again only when the + /// switch changes. + #[test] + fn a_priority_follows_its_switch() { + use std::sync::atomic::{AtomicBool, Ordering}; + use windows_sys::Win32::System::Threading::{THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_NORMAL}; + std::thread::spawn(|| { + let _raised = Priority::following(|| true); + assert_eq!(own_priority(), THREAD_PRIORITY_ABOVE_NORMAL); + }) + .join() + .unwrap(); + std::thread::spawn(|| { + let _normal = Priority::following(|| false); + assert_eq!(own_priority(), THREAD_PRIORITY_NORMAL); + }) + .join() + .unwrap(); + static ON: AtomicBool = AtomicBool::new(true); + std::thread::spawn(|| { + let mut priority = Priority::following(|| ON.load(Ordering::Relaxed)); + assert_eq!((priority.applied, own_priority()), (Some(true), THREAD_PRIORITY_ABOVE_NORMAL)); + ON.store(false, Ordering::Relaxed); + priority.keep(); + assert_eq!((priority.applied, own_priority()), (Some(false), THREAD_PRIORITY_NORMAL)); + // Unchanged: not asked again, so a priority set meanwhile stays. + // SAFETY: our own thread. + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority}; + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); + } + priority.keep(); + assert_eq!((priority.applied, own_priority()), (Some(false), THREAD_PRIORITY_ABOVE_NORMAL)); + // Changed back on, from normal: the system is asked again. + // SAFETY: our own thread. + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority}; + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); + } + ON.store(true, Ordering::Relaxed); + priority.keep(); + assert_eq!((priority.applied, own_priority()), (Some(true), THREAD_PRIORITY_ABOVE_NORMAL)); + }) + .join() + .unwrap(); + } + + /// The thread that lands flights starts at the priority its switch asks + /// for: above normal when [`relay_raised`] (off by default), else normal. + #[test] + fn the_relay_starts_at_the_priority_its_switch_asks() { + use windows_sys::Win32::System::Threading::{THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_NORMAL}; + std::thread::spawn(|| { + let _priority = crate::host::relay_thread_setup(); + let want = if relay_raised() { THREAD_PRIORITY_ABOVE_NORMAL } else { THREAD_PRIORITY_NORMAL }; + assert_eq!(own_priority(), want); + }) + .join() + .unwrap(); + } } diff --git a/d3d12/crates/leonida-gpu/src/descriptor.rs b/d3d12/crates/leonida-gpu/src/descriptor.rs index 1078802037..1b94bd7c24 100644 --- a/d3d12/crates/leonida-gpu/src/descriptor.rs +++ b/d3d12/crates/leonida-gpu/src/descriptor.rs @@ -804,6 +804,47 @@ pub(crate) fn with_view_heap(f: impl FnOnce(&host::HostHeap) -> T) -> Option< Some(f(host)) } +/// The slots of every host view heap that view one of `buffers` (raw +/// interface pointers) view nothing of them any more, or with `now` off are +/// only made again before they are next read ([`host::HostHeap::let_go_of`]): +/// buffers placed over title memory the title gave up or protected +/// (`crate::inplace`). Returns how many. Every slot of every +/// heap is looked at (a lock each: some 300,000 for the title's view heap), +/// so not per draw: for the title's frees and protections of memory in +/// place, on its thread, and once a second while one waits behind a buffer +/// the tables show no more, on the submitting thread +/// (`crate::inplace::tick`). +#[cfg(windows)] +pub(crate) fn let_go_of_buffers(buffers: &[usize], now: bool) -> u32 { + if buffers.is_empty() { + return 0; + } + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + // SAFETY: registered heaps are live (removed when dropped). + .map(|&(_, _, at)| unsafe { &*(at as *const Heap) }) + .filter(|heap| !heap.samplers()) + .filter_map(|heap| heap.host.get()?.as_ref()) + .map(|host| host.let_go_of(buffers, now)) + .sum() +} + +/// For the tests: a shader-visible view heap of `count` slots of the title's, +/// as the title makes one (released with its `Release`, slot 0x10), and its +/// host heap. +#[cfg(all(windows, test))] +pub(crate) fn test_view_heap(count: u32) -> (This, Option<&'static host::HostHeap>) { + // (With a placement of none after it, as the tests' `create` passes it: + // the placement is read whatever is passed.) + #[repr(C)] + struct Extended(HeapDesc, Placement); + let extended = Extended(HeapDesc { kind: VIEWS_KIND, count, flags: SHADER_VISIBLE, nodes: 0 }, Placement { address: 0, size: 0 }); + let mut h: This = std::ptr::null(); + assert_eq!(create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], &mut h), crate::object::S_OK); + (h, heap(h).host()) +} + /// Makes dynamic slot `index` of the host heap behind the title heap at /// `heap`, if that heap still exists, the constant buffer view of `size` /// bytes of `buffer` at `gpu`. @@ -836,6 +877,9 @@ impl Drop for Heap { let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner()); heaps.retain(|&(_, _, h)| h != at); drop(heaps); + if matches!(self.desc.kind, VIEWS_KIND | SAMPLERS) { + VIEW_HEAPS.write().unwrap_or_else(|e| e.into_inner()).retain(|&(h, ..)| h != at); + } #[cfg(windows)] crate::port_descriptors::let_go(self.start); } @@ -1015,7 +1059,29 @@ impl View { /// buffers, however often it moves them; without the padding the title /// leaves unwritten, which made nearly every view a shape of its own: /// [`normal_placed`]). -/// `LEONIDA_VIEW_INLINE=0`: every view is an entry, as before. +/// `LEONIDA_VIEW_INLINE=0`: every view is an entry; as before only with +/// `LEONIDA_VIEW_ADDRESSED_MOST=0` too, else those of the two kinds are +/// bounded as below. +/// +/// What still became an entry of those two kinds (a placed view once the +/// shapes are full, a constant buffer view its record cannot hold) was kept +/// for the run: past the shapes, a title that streams writes one for every +/// view at every address, and none came back. Such entries are now +/// [`Views::addressed`], and past [`addressed_most`] of them one that no +/// view record in a descriptor heap names and nothing looked up for a round +/// is let go as a released resource's are ([`Views::let_go_one`]). +/// +/// "As many as there are sampler states" holds only while the title's +/// sampler states are few: a sampler is an entry for every distinct +/// description, nothing releases it, and its words hold floats a title may +/// change as it plays (a mip bias that follows a dynamic resolution, a +/// least LOD that follows what of a texture is in; a hypothesis for this +/// title, whose sampler count is not measured). Written with a new value +/// each time, they were one entry each for the run +/// (`sampler_entries_stay_bounded_when_a_title_writes_new_ones`: 20,000 for +/// 20,000). They now go round with the entries carrying an address +/// ([`samplers_bound`]), under the same most, and the sampler heaps' records +/// keep theirs as the view heaps' do ([`heap_records`]). struct Views { /// Each entry's view and generation. list: Vec<(View, u32)>, @@ -1026,20 +1092,44 @@ struct Views { /// The shapes of views of placed memory, and where each is. shapes: Vec, shape_index: std::collections::BTreeMap, -} + /// Per entry, beside `list`: [`SEEN`] and [`LIVE`]. Atomic so that + /// readers, who share the lock, can say an entry was seen. + marks: Vec, + /// The entries in use that are views carrying an address (a constant + /// buffer view or a view of placed memory that its record cannot name + /// whole), and samplers if [`Limits::samplers`] (which carry none, but + /// nothing else releases either), in the order [`Views::let_go_one`]'s + /// hand meets them: nothing releases them but it, and it walks only + /// these. An entry let go is given the next such view in its place, so + /// the order holds. + addressed: Vec, + /// Where in `addressed` [`Views::let_go_one`] looks next. + hand: usize, + /// How many `addressed` there are before [`Views::let_go_one`] is asked + /// again, if more than the most: a quarter more than the live descriptor + /// slots named at the last round's start ([`Views::keep_live`]). So a + /// table whose entries the slots hold nearly all grows rather than + /// going round them for every new view. + put_off: usize, +} + +/// Looked up, written, or named by a live descriptor slot +/// ([`Views::keep_live`]) since [`Views::let_go_one`] last passed the entry. +const SEEN: u8 = 2; +/// Named by a live descriptor slot in the look through them that began the +/// round ([`Views::keep_live`], which counts each entry once by it). +const LIVE: u8 = 4; + +/// What the live descriptor slots hold: calls its argument with the two +/// record words (`i`, `generation`) of every view record in them +/// ([`heap_records`]). +type Live<'a> = &'a dyn Fn(&mut dyn FnMut(u32, u32)); /// 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 /// or shape) and a released resource take it alone. -static VIEWS: std::sync::RwLock = std::sync::RwLock::new(Views { - list: Vec::new(), - index: std::collections::BTreeMap::new(), - by_resource: std::collections::BTreeMap::new(), - free: Vec::new(), - shapes: Vec::new(), - shape_index: std::collections::BTreeMap::new(), -}); +static VIEWS: std::sync::RwLock = std::sync::RwLock::new(Views::new()); pub(crate) const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE"); /// A record is the tag and two words, `i` and `generation` (the host keeps @@ -1067,7 +1157,9 @@ type Shape = (bool, [u32; 14], [u32; 14]); /// Whether constant buffer views and views of placed memory are named whole /// in their records ([`Views`]). On by default; `LEONIDA_VIEW_INLINE=0` -/// makes every view a table entry, as before. +/// makes every view a table entry (as before with +/// `LEONIDA_VIEW_ADDRESSED_MOST=0` too: else the constant buffer and placed +/// ones are let go past [`addressed_most`], as any [`Views::addressed`]). fn inline() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("LEONIDA_VIEW_INLINE").is_none_or(|v| v != "0")) @@ -1131,14 +1223,174 @@ fn placed_words(shape: u32, address: u64) -> [u32; 2] { kind_words(PLACED, u64::from(shape) << PLACED_ADDRESS_BITS | address) } +/// How far the [`Views`] grow: the shapes of placed views, and the table +/// entries that carry an address ([`Views::addressed`]; 0: as many as come); +/// whether samplers count among those ([`samplers_bound`]); and what the +/// live descriptor slots hold, which is never let go. +#[derive(Clone, Copy)] +struct Limits<'a> { + shapes: usize, + addressed: usize, + samplers: bool, + live: Live<'a>, +} + +impl Limits<'static> { + /// The run's: as many shapes as records can number, [`addressed_most`] + /// entries, samplers among them unless `LEONIDA_VIEW_SAMPLERS_BOUND=0`, + /// and the slots of the title's view and sampler heaps. + fn run() -> Self { + Limits { shapes: SHAPES, addressed: addressed_most(), samplers: samplers_bound(), live: &heap_records } + } +} + +/// Whether sampler entries go round with those carrying an address +/// ([`Views::addressed`]), under [`addressed_most`]: past it, one that no +/// record in a view or sampler heap names and nothing looked up for a round +/// is let go, its records stale (the host's slot then the point stand-in, +/// `host.rs` `null_sampler`, until the title writes the sampler again). +/// `LEONIDA_VIEW_SAMPLERS_BOUND=0`: kept for the run, as before ([`Views`]). +/// +/// On by default: below the most (1,048,576 entries of both kinds) nothing +/// changes but that the sampler heaps are registered for the look through +/// the slots, which only a round of the hand makes; past it, the table grew +/// without bound before. What it can cost, as for the views carrying an +/// address: a sampler record the title keeps outside every heap for a whole +/// round, unread, and copies back, finds its sampler gone. The sampler heaps, +/// CPU-only ones too, are looked through as the view heaps are +/// (`sampler_heaps_are_looked_through_while_they_are_there`). +fn samplers_bound() -> bool { + crate::toggled!("LEONIDA_VIEW_SAMPLERS_BOUND") +} + +/// How many table entries carrying an address ([`Views::addressed`]) are +/// kept before one no live slot names is let go +/// (`LEONIDA_VIEW_ADDRESSED_MOST=`, 1,048,576 if not given; `0`: +/// none is, they are kept for the run, as before). +/// +/// What becomes such an entry: a view of placed memory once the shapes are +/// full, or at an address past 1 TiB; a constant buffer view its record +/// cannot hold; every one of the two with `LEONIDA_VIEW_INLINE=0`. Nothing +/// releases them, and a title writes them at ever new addresses: the run +/// at main 33db04a70 (before [`normal_placed`] kept the shapes few) had +/// 33.27 million views in the table, 11,985 MB, none of them free, at 79 +/// minutes; the fork [`normal_placed`] is from had 5.6 million (3.3 GB) +/// after its 4,194,304 shapes were full. Measured there, not here. +/// About as many as the title's view heap has slots (a little over a +/// million, `host.rs` `PORTABLE_VIEWS`), some 350 MB of table and index by +/// the memory line's estimate (`kept`: 136 bytes an entry, one and a half +/// times that its share of the index); more while the live slots name more +/// ([`Views::put_off`]). An entry let go is one that no view record in a +/// descriptor heap named when the table last began a round of its entries +/// ([`heap_records`]) and that nothing looked up (a host slot made from it, +/// a draw reading it, the title writing the same view again) since the +/// round before passed it; a record still naming it is stale from then on, +/// as a released resource's are. Only a record the title keeps outside its +/// heaps for a whole round, and copies back, finds its view gone (its slot +/// null). +fn addressed_most() -> usize { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("LEONIDA_VIEW_ADDRESSED_MOST").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1 << 20) + }) +} + +/// Table entries carrying an address (and samplers, [`samplers_bound`]) let +/// go since the start (for the memory line). +static LET_GO: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Every view and sampler heap, shader-visible or CPU-only (the heap, its +/// first slot, its count, the bytes of a slot): where the records are that +/// [`Views::let_go_one`] keeps the entries of ([`heap_records`]). Taken +/// alone where heaps come and go, and shared for a look through them, under +/// [`VIEWS`]; nothing that holds it takes [`VIEWS`]. +#[cfg(windows)] +static VIEW_HEAPS: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); + +/// Calls `each` with the two record words (`i`, `generation`) of every view +/// or sampler record in the heaps ([`VIEW_HEAPS`]): the CPU-only ones too, +/// since a title writes a view into one and copies it into its +/// shader-visible heap later, and a mirror makes nothing of a CPU heap's +/// slots ([`mirror`]). Read through the kernel 64 KiB at a time, a page at a +/// time where that fails: a placed heap's memory is the title's, which it +/// may unmap. Some 32 MB for the title's view heap, once a round of +/// [`Views::let_go_one`], under the table's lock. +#[cfg(windows)] +fn heap_records(each: &mut dyn FnMut(u32, u32)) { + const CHUNK: usize = 1 << 16; + const PAGE: usize = 1 << 12; + let records = |bytes: &[u8], step: usize, each: &mut dyn FnMut(u32, u32)| { + for record in bytes.chunks_exact(step) { + let word = |n: usize| record[4 * n..4 * n + 4].try_into().map_or(0, u32::from_le_bytes); + if word(0) == VIEW_TAG { + each(word(1), word(2)); + } + } + }; + let heaps = VIEW_HEAPS.read().unwrap_or_else(|e| e.into_inner()); + let mut bytes = vec![0u8; CHUNK]; + for &(_, start, count, step) in heaps.iter() { + let step = step as usize; + let end = start + u64::from(count) * step as u64; + let mut at = start; + while at < end { + let len = (end - at).min(CHUNK as u64) as usize; + if crate::host::read_into(at as *const u8, &mut bytes[..len]) { + records(&bytes[..len], step, each); + } else { + for from in (0..len).step_by(PAGE) { + let page = &mut bytes[from..(from + PAGE).min(len)]; + if crate::host::read_into((at + from as u64) as *const u8, page) { + records(page, step, each); + } + } + } + at += len as u64; + } + } +} + +/// No heaps are looked through but on Windows. +#[cfg(not(windows))] +fn heap_records(_: &mut dyn FnMut(u32, u32)) {} + +impl View { + /// Whether the view carries an address and no resource: a table entry of + /// such a view is one of [`Views::addressed`]. + fn addressed(&self) -> bool { + matches!(self, View::Constant(..) | View::Placed(..)) + } + + /// Whether a table entry of the view is one of [`Views::addressed`]: one + /// carrying an address, or a sampler if `samplers` ([`samplers_bound`]). + fn let_go_able(&self, samplers: bool) -> bool { + self.addressed() || samplers && matches!(self, View::Sampler(..) | View::ConsoleSampler(..)) + } +} + impl Views { + const fn new() -> Self { + Views { + list: Vec::new(), + index: std::collections::BTreeMap::new(), + by_resource: std::collections::BTreeMap::new(), + free: Vec::new(), + shapes: Vec::new(), + shape_index: std::collections::BTreeMap::new(), + marks: Vec::new(), + addressed: Vec::new(), + hand: 0, + put_off: 0, + } + } + /// The number of `shape`, a new one if it is not there yet; `None` when - /// the shapes are full (the view is then a table entry). - fn shape(&mut self, shape: Shape) -> Option { + /// there are `most` shapes (the view is then a table entry). + fn shape(&mut self, shape: Shape, most: usize) -> Option { if let Some(&at) = self.shape_index.get(&shape) { return Some(at); } - if self.shapes.len() >= SHAPES { + if self.shapes.len() >= most.min(SHAPES) { return None; } let at = self.shapes.len() as u32; @@ -1159,39 +1411,177 @@ impl Views { Some(View::Placed(unordered, resource, desc)) } + /// Entry `i` was looked up or written again ([`SEEN`]); taken shared. + fn seen(&self, i: u32) { + use std::sync::atomic::Ordering::Relaxed; + if let Some(mark) = self.marks.get(i as usize) + && mark.load(Relaxed) & SEEN == 0 + { + mark.fetch_or(SEEN, Relaxed); + } + } + + /// The view the record words `i` and `generation` name: the one they + /// hold whole, or the view of entry `i` if `generation` is still its own. + fn view_at(&self, i: u32, generation: u32) -> Option { + match generation >> KIND_SHIFT { + 0 => { + let (view, current) = self.list.get(i as usize)?; + (*current == generation).then(|| { + self.seen(i); + view.clone() + }) + } + CONSTANT => Some(constant_of(i, generation)), + PLACED => self.placed_of(i, generation), + _ => None, + } + } + /// The record words of `view` as a table entry, if it has one. fn entry_of(&self, view: &View) -> Option<[u32; 2]> { let &i = self.index.get(view)?; + self.seen(i); Some([i, self.list[i as usize].1]) } /// The record words of `view` as a table entry: its entry (a new or a /// freed one if the view is not there yet) and that entry's generation. - fn entry(&mut self, view: View) -> [u32; 2] { - let i = match self.index.get(&view) { - Some(&i) => i, - None => { - let i = match self.free.pop() { - Some(i) => { - self.list[i as usize].0 = view.clone(); - i - } - None => { - self.list.push((view.clone(), 1)); - self.list.len() as u32 - 1 - } - }; - for r in view.resources().into_iter().filter(|&r| r != 0) { - self.by_resource.entry(r).or_default().push(i); + /// A new entry carrying an address (or a sampler, [`Limits::samplers`]) + /// when there are as many of them as `limits` allow (0: no most) takes + /// the place of one no live slot names and nothing looked up for a round + /// ([`Views::let_go_one`]). + fn entry(&mut self, view: View, limits: Limits) -> [u32; 2] { + use std::sync::atomic::AtomicU8; + if let Some(&i) = self.index.get(&view) { + self.seen(i); + return [i, self.list[i as usize].1]; + } + let addressed = view.let_go_able(limits.samplers); + let most = limits.addressed; + let let_go = (addressed && most != 0 && self.addressed.len() >= most.max(self.put_off)) + .then(|| self.let_go_one(limits.live, limits.samplers)) + .flatten(); + let i = match let_go.or_else(|| self.free.pop()) { + Some(i) => { + self.list[i as usize].0 = view.clone(); + // (Tables a test builds whole may have no marks.) + if let Some(at) = self.marks.get_mut(i as usize) { + *at.get_mut() = SEEN; } - self.index.insert(view, i); - // (A reused entry keeps the generation `forget` gave it.) - view_generation_set(i, self.list[i as usize].1); i } + None => { + self.list.push((view.clone(), 1)); + self.marks.resize_with(self.list.len() - 1, || AtomicU8::new(0)); + self.marks.push(AtomicU8::new(SEEN)); + self.list.len() as u32 - 1 + } }; + // (One let go keeps its place.) + if addressed && let_go.is_none() { + self.addressed.push(i); + } + for r in view.resources().into_iter().filter(|&r| r != 0) { + self.by_resource.entry(r).or_default().push(i); + } + self.index.insert(view, i); [i, self.list[i as usize].1] } + + /// Marks [`SEEN`] the entries the view records in live descriptor slots + /// name at their generation (`live`), as if looked up; how many of + /// [`Views::addressed`] they are (samplers too if `samplers`), each + /// counted once ([`LIVE`]). + fn keep_live(&mut self, live: Live, samplers: bool) -> usize { + use std::sync::atomic::Ordering::Relaxed; + for &i in &self.addressed { + if let Some(mark) = self.marks.get_mut(i as usize) { + *mark.get_mut() &= !LIVE; + } + } + let mut named = 0; + live(&mut |i, generation| { + if let (Some((view, current)), Some(mark)) = (self.list.get(i as usize), self.marks.get(i as usize)) + && *current == generation + && mark.fetch_or(SEEN | LIVE, Relaxed) & LIVE == 0 + && view.let_go_able(samplers) + { + named += 1; + } + }); + named + } + + /// Lets go of an entry of [`Views::addressed`] not [`SEEN`] since the + /// hand last passed it (a clock: every entry a second chance), as + /// [`forget`] lets go of a released resource's: out of the index, its + /// generation one on, so the records still naming it are stale (the host + /// makes their slots null; the title writing the view again gets a new + /// record). Each round of the hand begins with what the live descriptor + /// slots name seen ([`Views::keep_live`]), so no entry a heap slot names + /// is let go, looked up or not, and [`Views::put_off`] set from how many + /// they name. The entry, for the caller's new view (it keeps its place, + /// just behind the hand); `None` if every one is live: at most two rounds + /// of `addressed` and two looks through the slots, since the first round + /// clears every [`SEEN`] it passes and only the look sets them again. + fn let_go_one(&mut self, live: Live, samplers: bool) -> Option { + let n = self.addressed.len(); + for _ in 0..2 * n { + if self.hand >= n { + self.hand = 0; + } + if self.hand == 0 { + let named = self.keep_live(live, samplers); + self.put_off = named + named / 4 + 1; + } + let i = self.addressed[self.hand]; + self.hand += 1; + let Some(mark) = self.marks.get_mut(i as usize) else { + continue; + }; + let mark = mark.get_mut(); + if *mark & SEEN != 0 { + *mark &= !SEEN; + continue; + } + let (view, generation) = &mut self.list[i as usize]; + self.index.remove(view); + // (Below the bits that say a record is no table entry.) + *generation = ((*generation + 1) & GENERATIONS).max(1); + LET_GO.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return Some(i); + } + None + } + + /// The two words that name `view` in a record ([`words_for`], which + /// looks for them shared first): the view itself where its kind allows + /// and `inline`, else its table entry. + fn name(&mut self, view: View, inline: bool, limits: Limits) -> [u32; 2] { + use std::sync::atomic::Ordering::Relaxed; + if inline { + match &view { + View::Constant(address, size) => { + if let Some(words) = constant_words(*address, *size) { + NAMED_WHOLE[0].fetch_add(1, Relaxed); + return words; + } + } + View::Placed(unordered, resource, desc) => { + let (shape, address) = shape_of(*unordered, resource, desc); + if address >> PLACED_ADDRESS_BITS == 0 + && let Some(shape) = self.shape(shape, limits.shapes) + { + NAMED_WHOLE[1].fetch_add(1, Relaxed); + return placed_words(shape, address); + } + } + _ => {} + } + } + self.entry(view, limits) + } } /// The two words that name `view` in a record: the view itself where its @@ -1208,14 +1598,12 @@ fn words_for(view: View) -> [u32; 2] { } View::Placed(unordered, resource, desc) => { let (shape, address) = shape_of(*unordered, resource, desc); - if address >> PLACED_ADDRESS_BITS == 0 { - // Nearly every placed view has a shape seen before. - let known = views_read().shape_index.get(&shape).copied(); - let shape = known.or_else(|| views_write().shape(shape)); - if let Some(shape) = shape { - NAMED_WHOLE[1].fetch_add(1, Relaxed); - return placed_words(shape, address); - } + // Nearly every placed view has a shape seen before. + if address >> PLACED_ADDRESS_BITS == 0 + && let Some(&shape) = views_read().shape_index.get(&shape) + { + NAMED_WHOLE[1].fetch_add(1, Relaxed); + return placed_words(shape, address); } } _ => {} @@ -1225,7 +1613,15 @@ fn words_for(view: View) -> [u32; 2] { if let Some(words) = views_read().entry_of(&view) { return words; } - views_write().entry(view) + let mut views = views_write(); + let words = views.name(view, inline(), Limits::run()); + // The generation of the entry made, reused (it keeps the one `forget` + // gave it) or let go of for this view, for [`view_cached`]; here, not in + // [`Views::entry`], so that the tables tests build alone leave it be. + if words[1] >> KIND_SHIFT == 0 { + view_generation_set(words[0], words[1]); + } + words } fn views_read() -> std::sync::RwLockReadGuard<'static, Views> { @@ -1259,8 +1655,9 @@ const VIEW_GENERATIONS_HELD: usize = 1 << 20; /// The generation of each of the first [`VIEW_GENERATIONS_HELD`] table entries ([`Views::list`]), read without the /// lock by [`view_cached`]. Fixed in size, so it never moves while read. Stored under the write lock wherever an -/// entry's generation is set: [`Views::entry`] when it makes or reuses one, [`forget`] when it gives one a new -/// generation. Kept whether the cache is on or not, so that [`view_cache`] can change by turns. 0: no entry. +/// entry's generation is set: [`words_for`] for the entry [`Views::entry`] makes, reuses or takes from +/// [`Views::let_go_one`], [`forget`] when it gives one a new generation. Kept whether the cache is on or not, so that +/// [`view_cache`] can change by turns. 0: no entry. static VIEW_GENERATIONS: std::sync::LazyLock> = std::sync::LazyLock::new(|| (0..VIEW_GENERATIONS_HELD).map(|_| std::sync::atomic::AtomicU32::new(0)).collect()); @@ -1403,7 +1800,8 @@ fn kind_index(view: &View) -> usize { /// buffer views and views of placed memory (those that did not fit a /// record, or all of them with `LEONIDA_VIEW_INLINE=0`), the shapes of /// placed views kept, and the views named whole in their records since the -/// start: constant buffer views, views of placed memory. +/// start: constant buffer views, views of placed memory; last, the entries +/// carrying an address let go since the start ([`Views::let_go_one`]). /// /// The second element is the same table, by [`kind_index`]: for each of the /// six `View` kinds, how many of its entries are occupied (named in @@ -1440,7 +1838,7 @@ fn kind_index(view: &View) -> usize { /// `host.rs`) — not "every sixth line," which is a different, unrelated /// cadence belonging to [`log_memory_map`](crate::copystat) alone. #[cfg(all(windows, feature = "diagnostics"))] -pub(crate) fn views_kept() -> ([u64; 8], [[u64; 3]; 6]) { +pub(crate) fn views_kept() -> ([u64; 9], [[u64; 3]; 6]) { kept(&views_read()) } @@ -1450,7 +1848,7 @@ pub(crate) fn views_kept() -> ([u64; 8], [[u64; 3]; 6]) { /// state and nothing to race against (see `kind_breakdown_is_exact_for_a_\ /// known_table` below). [`views_kept`] is the only real caller. #[cfg(all(windows, feature = "diagnostics"))] -fn kept(views: &Views) -> ([u64; 8], [[u64; 3]; 6]) { +fn kept(views: &Views) -> ([u64; 9], [[u64; 3]; 6]) { use std::sync::atomic::Ordering::Relaxed; let each = size_of::<(View, u32)>() as u64; let shape = size_of::() as u64; @@ -1482,6 +1880,7 @@ fn kept(views: &Views) -> ([u64; 8], [[u64; 3]; 6]) { views.shapes.len() as u64, NAMED_WHOLE[0].load(Relaxed), NAMED_WHOLE[1].load(Relaxed), + LET_GO.load(Relaxed), ]; (summary, by_kind) } @@ -1537,6 +1936,13 @@ pub(crate) fn texture_made(resource: usize) { .push(resource); } +/// Whether a slot waits for the host copy of texture `resource` +/// ([`wait_for`]): it is made when that copy is, so the texture must stay. +#[cfg(windows)] +pub(crate) fn waits(resource: usize) -> bool { + WAITING.lock().unwrap_or_else(|e| e.into_inner()).contains_key(&resource) +} + /// The slot at `handle` was written with a view of texture `resource`, /// which has no host copy: it waits for one. #[cfg(windows)] @@ -1640,32 +2046,30 @@ pub(crate) fn forget(resource: usize) { } /// The view the record words `i` and `generation` name: the one they hold -/// whole, or the view of entry `i` if `generation` is still its own. +/// whole, or the view of entry `i` if `generation` is still its own +/// ([`Views::view_at`]). With [`view_cache`], an entry the clock may let go +/// ([`View::let_go_able`]) is still looked up under the lock, which marks it +/// [`SEEN`] ([`Views::let_go_one`] lets go of no entry looked up for a round); +/// only the others are kept per thread. fn view_at(i: u32, generation: u32) -> Option { let cache = view_cache(); match generation >> KIND_SHIFT { - 0 => { - if cache && let Some(view) = view_cached(i, generation) { + 0 if cache => { + let samplers = samplers_bound(); + if let Some(view) = view_cached(i, generation).filter(|view| !view.let_go_able(samplers)) { view_cache_counted(true); return Some(view); } - let found = { - let views = views_read(); - let (view, current) = views.list.get(i as usize)?; - (*current == generation).then(|| view.clone()) - }; - if cache { - view_cache_counted(false); - if let Some(view) = &found { - view_remember(i, generation, view); - } + let found = views_read().view_at(i, generation); + view_cache_counted(false); + if let Some(view) = found.as_ref().filter(|view| !view.let_go_able(samplers)) { + view_remember(i, generation, view); } found } CONSTANT => Some(constant_of(i, generation)), PLACED if cache => placed_at(i, generation), - PLACED => views_read().placed_of(i, generation), - _ => None, + _ => views_read().view_at(i, generation), } } @@ -1679,6 +2083,13 @@ pub(crate) fn record_at(handle: u64) -> Option<[u32; 3]> { (words[0] == VIEW_TAG).then_some(words) } +/// Whether record words `words` (as [`record_at`] gives them) are a view's +/// and name one that is alive: what [`view`] would find in a slot that holds +/// them. +pub(crate) fn record_live(words: [u32; 3]) -> bool { + words[0] == VIEW_TAG && view_at(words[1], words[2]).is_some() +} + /// The view recorded at `handle`, if one is (and its resource is alive). pub(crate) fn view(handle: u64) -> Option { if handle == 0 { @@ -1720,7 +2131,7 @@ pub(crate) extern "system" fn create_srv( desc: *const [u32; 10], handle: u64, ) { - record(handle, View::Shader(resource as usize, words(desc))); + record(handle, View::Shader(resource as usize, resource_view_words(false, desc))); } /// Device method. @@ -1731,7 +2142,7 @@ pub(crate) extern "system" fn create_uav( desc: *const [u32; 10], handle: u64, ) { - let view = View::Unordered(resource as usize, counter as usize, words(desc)); + let view = View::Unordered(resource as usize, counter as usize, resource_view_words(true, desc)); record(handle, view); } @@ -1795,6 +2206,36 @@ fn placed_normal() -> bool { fn normal_placed(unordered: bool, mut resource: [u32; 14], mut desc: [u32; 16]) -> ([u32; 14], [u32; 16]) { resource[1] = 0; resource[13] = 0; + normal_view(unordered, &mut desc); + (resource, desc) +} + +/// Whether a view of a resource object is kept without the words of its description that no +/// view reads ([`normal_view`]). On by default; `LEONIDA_VIEW_NORMAL=0` keeps them as the +/// title gave them, as before. +/// +/// A view of a resource is a table entry keyed by its whole description, freed when the +/// resource is released ([`Views`]): a description written again with other words in its +/// padding was another entry and another record (the host made the slot again), and for a +/// resource the title keeps (a target, a pool it streams into) the entries added up for as +/// long as it lived; a view of no resource (a null view) was never freed at all. Hypothesis, +/// not measured here: the title fills these descriptions as it fills those of placed views, +/// which are the same 40 bytes and whose padding it left as its stack held it +/// ([`normal_placed`]). +fn view_normal() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_VIEW_NORMAL").is_none_or(|v| v != "0")) +} + +/// The first ten words of a view description (`D3D12_SHADER_RESOURCE_VIEW_DESC` or +/// `D3D12_UNORDERED_ACCESS_VIEW_DESC`, 40 bytes either) with the words no view reads set to +/// zero: a shader resource view's word 3 (the union that follows starts on 8 bytes) and the +/// union's words past the member of the view's dimension (`D3D12_BUFFER_SRV`, +/// `D3D12_TEX2D_SRV` and the like say how many words each uses; an unknown dimension keeps +/// them all). The host hands these words to the device as they are (`host.rs` `srv_desc`, +/// `uav_desc`), which reads none of the ones set to zero. Words 10 and on (a placed view's +/// address and the console's own fields) are left as they are. +fn normal_view(unordered: bool, desc: &mut [u32]) { // Where the union starts, and the words of it the dimension's member uses. let (start, used) = if unordered { // D3D12_UAV_DIMENSION: buffer, 1D, 1D array, 2D, 2D array, 2D MS, 2D MS array, 3D. @@ -1831,7 +2272,16 @@ fn normal_placed(unordered: bool, mut resource: [u32; 14], mut desc: [u32; 16]) (4, used) }; desc[(start + used).min(10)..10].fill(0); - (resource, desc) +} + +/// A resource view's description as it is kept: without the words no view reads +/// ([`view_normal`]). +fn resource_view_words(unordered: bool, desc: *const [u32; 10]) -> Option<[u32; 10]> { + let mut desc = words(desc)?; + if view_normal() { + normal_view(unordered, &mut desc); + } + Some(desc) } /// Device method. @@ -2003,6 +2453,13 @@ pub(crate) extern "system" fn create_heap( let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner()); heaps.push((start, start + size, at)); } + // (Sampler heaps too: their records keep samplers, `samplers_bound`.) + #[cfg(windows)] + if matches!(desc.kind, VIEWS_KIND | SAMPLERS) { + let at = std::ptr::from_ref::(&heap) as usize; + let step = increment(desc.kind).unwrap_or(32); + VIEW_HEAPS.write().unwrap_or_else(|e| e.into_inner()).push((at, start, desc.count, step)); + } #[cfg(not(windows))] let _ = visible; object::hand_out(DESCRIPTOR_HEAP, heap, iid, &HEAP_IIDS, out) @@ -2475,6 +2932,357 @@ mod tests { assert_eq!(view(at), Some(View::Placed(false, texture(0), odd))); } + /// A raw buffer view of placed memory as a streaming title writes it: `width` bytes at + /// `address`, the padding of both descriptions left as its stack held it (`junk`), kept + /// as [`create_placed_srv`] keeps it ([`normal_placed`]). + fn streamed(width: u32, junk: u32, address: u64) -> View { + let resource = [1, junk, 0, 0, width, 0, 1, 0x1_0001, 0, 1, 0, 1, 0, junk ^ 0x5a5a]; + let mut desc = [0u32; 16]; + desc[..10].copy_from_slice(&[0x27, 1, 0x1688, junk, 0, 0, width / 4, 0, 1, junk.rotate_left(7)]); + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + let (resource, desc) = normal_placed(false, resource, desc); + View::Placed(false, resource, desc) + } + + /// The view table of a title that streams (on a table of its own, with room for 16 shapes + /// and 256 entries carrying an address): its placed views of a few kinds of buffer, at + /// addresses it reuses and with stack padding, add one shape per kind and no entry; buffers + /// of ever new widths fill the shapes and then each is a table entry, which nothing + /// released, one per view written (33.27 million at 79 minutes at main 33db04a70). Kept to + /// the most now: the slots the title still shows, looked up every frame, keep their + /// views; a record of a view let go is stale, never another view; the view written + /// again is named again; views of resources and samplers are never let go. + #[test] + fn entries_carrying_an_address_stay_bounded_when_a_title_streams_past_the_shapes() { + const SHAPES_HERE: usize = 16; + const MOST: usize = 256; + const SLOTS: usize = 64; + let limits = Limits { shapes: SHAPES_HERE, addressed: MOST, samplers: false, live: &|_| {} }; + let mut views = Views::new(); + let pool = |n: usize| 0x7_7700_0000u64 + (n % 32) as u64 * 0x1_0000; + // Never looked up again: a sampler and a view of a resource. + let sampler = views.name(View::Sampler([0x5a; 13]), true, limits); + let resource = views.name(View::Shader(0x5eed_0000, None), true, limits); + // Eight kinds of buffer, a thousand views each, padding as the stack left it. + let mut slots = vec![([0u32; 2], View::Constant(0, 0)); SLOTS]; + for n in 0..8_000usize { + let junk = (n as u32).wrapping_mul(0x9e37_79b9) | 1; + let view = streamed(0x100 << (n % 8), junk, pool(n)); + slots[n % SLOTS] = (views.name(view.clone(), true, limits), view); + } + assert_eq!((views.shapes.len(), views.addressed.len()), (8, 0), "a shape per kind, no entry"); + // Then a buffer of a new width each time. + let first = slots[0].0; + let first_view = views.view_at(first[0], first[1]); + let mut first_entry = [0u32; 2]; + for n in 0..100_000usize { + let view = streamed(0x10_0000 + 16 * n as u32, 7, pool(n)); + let words = views.name(view.clone(), true, limits); + assert_eq!(views.view_at(words[0], words[1]).as_ref(), Some(&view)); + if n == SHAPES_HERE - 8 { + first_entry = words; + } + slots[n % SLOTS] = (words, view); + // A frame: the host reads every slot the title shows. + if n % SLOTS == SLOTS - 1 { + for (words, view) in &slots { + assert_eq!(views.view_at(words[0], words[1]).as_ref(), Some(view), "a slot still shown"); + } + } + } + assert_eq!(views.shapes.len(), SHAPES_HERE); + assert!( + views.list.len() <= MOST + 2 && views.addressed.len() <= MOST, + "{} entries for 100,000 views written, {} carrying an address", + views.list.len(), + views.addressed.len() + ); + assert_eq!(views.view_at(first[0], first[1]), first_view, "a placed view named whole stays"); + // The first of the new widths that was an entry was let go: its record is stale, and + // the view written again gets another. + let old = streamed(0x10_0000 + 16 * (SHAPES_HERE as u32 - 8), 7, pool(SHAPES_HERE - 8)); + assert!(!views.index.contains_key(&old), "let go"); + assert_eq!(views.view_at(first_entry[0], first_entry[1]), None, "stale, not another view"); + let again = views.name(old.clone(), true, limits); + assert_ne!(again, first_entry); + assert_eq!(views.view_at(again[0], again[1]), Some(old)); + assert_eq!(views.view_at(sampler[0], sampler[1]), Some(View::Sampler([0x5a; 13]))); + assert_eq!(views.view_at(resource[0], resource[1]), Some(View::Shader(0x5eed_0000, None))); + } + + /// `LEONIDA_VIEW_ADDRESSED_MOST=0`: entries carrying an address are kept for the run, as + /// before. + #[test] + fn entries_carrying_an_address_are_kept_without_a_most() { + let limits = Limits { shapes: 4, addressed: 0, samplers: false, live: &|_| {} }; + let mut views = Views::new(); + for n in 0..5_000u32 { + views.name(streamed(0x10_0000 + 16 * n, 7, 0x7_7800_0000), true, limits); + } + assert_eq!((views.shapes.len(), views.list.len(), views.addressed.len()), (4, 4_996, 4_996)); + } + + /// Views the title writes into a heap's slots and leaves there, which nothing looks up (a + /// CPU-only heap, which no mirror reads; a shader-visible slot no draw reads for a while), + /// stay through a hundred rounds of the hand while views written once stream past: the + /// slots name them ([`Views::keep_live`]), and the first look up of each, when the title + /// copies them into the heap the shaders see, gives the view, not a null slot. Before, only + /// a look up kept an entry, and those eight were let go in the first round past the most. + /// A view let go and written again is named again; the slot written with another view no + /// longer keeps the old one; one look through the slots a round, not one a view. + #[test] + fn entries_a_live_slot_names_are_never_let_go() { + const MOST: usize = 64; + let slots = std::cell::RefCell::new(Vec::<[u32; 2]>::new()); + let looks = std::cell::Cell::new(0usize); + let live = |each: &mut dyn FnMut(u32, u32)| { + looks.set(looks.get() + 1); + for &[i, generation] in slots.borrow().iter() { + each(i, generation); + } + }; + let limits = Limits { shapes: 4, addressed: MOST, samplers: false, live: &live }; + let mut views = Views::new(); + for n in 0..4 { + views.name(streamed(0x100 << n, 7, 0x7_7900_0000), true, limits); + } + let kept: Vec = (0..8).map(|n| streamed(0x20_0000 + 16 * n, 7, 0x7_7a00_0000)).collect(); + for view in &kept { + let words = views.name(view.clone(), true, limits); + slots.borrow_mut().push(words); + } + let streams = |n: usize| streamed(0x40_0000 + 16 * n as u32, 7, 0x7_7b00_0000 + (n % 32) as u64 * 0x1_0000); + for n in 0..100 * MOST { + views.name(streams(n), true, limits); + } + assert!(views.addressed.len() <= MOST, "{} entries carrying an address", views.addressed.len()); + assert!(!views.index.contains_key(&streams(0)), "a view no slot names was let go"); + for (words, view) in slots.borrow().iter().zip(&kept) { + assert_eq!(views.view_at(words[0], words[1]).as_ref(), Some(view), "a slot's view, first looked up now"); + } + // A look a round, and a round lets go of about half the 56 entries no slot names (one + // written since the hand passed its place is seen once more): some 230 for 6,400. + assert!(looks.get() <= 100 * MOST / 16, "{} looks through the slots for {} views", looks.get(), 100 * MOST); + let again = views.name(streams(0), true, limits); + assert_eq!(views.view_at(again[0], again[1]), Some(streams(0)), "named again"); + // The first slot written with another view: the old entry goes within two rounds. + let old = slots.borrow()[0]; + slots.borrow_mut()[0] = views.name(streams(1 << 20), true, limits); + for n in 0..2 * MOST { + views.name(streams(200 * MOST + n), true, limits); + } + assert_eq!(views.view_at(old[0], old[1]), None, "let go once no slot names it"); + assert!(views.index.contains_key(&streams(1 << 20))); + } + + /// Slots that name more views than the most keep them all: the table grows to a quarter + /// more than they name ([`Views::put_off`]) and lets go of the rest, and does not look + /// through the slots for every new view while it cannot let any go. + #[test] + fn entries_live_slots_need_past_the_most_are_kept() { + const MOST: usize = 64; + const NAMED: usize = 100; + let slots = std::cell::RefCell::new(Vec::<[u32; 2]>::new()); + let looks = std::cell::Cell::new(0usize); + let live = |each: &mut dyn FnMut(u32, u32)| { + looks.set(looks.get() + 1); + for &[i, generation] in slots.borrow().iter() { + // (Each in two slots: counted once.) + each(i, generation); + each(i, generation); + } + }; + let limits = Limits { shapes: 0, addressed: MOST, samplers: false, live: &live }; + let mut views = Views::new(); + let named = |n: usize| View::Constant(1 << 50 | (n as u64) << 8, 256); + for n in 0..NAMED { + let words = views.name(named(n), true, limits); + slots.borrow_mut().push(words); + } + for n in 0..1_000 { + views.name(View::Constant(1 << 51 | (n as u64) << 8, 256), true, limits); + } + for (n, words) in slots.borrow().iter().enumerate() { + assert_eq!(views.view_at(words[0], words[1]), Some(named(n))); + } + assert!(views.addressed.len() <= NAMED + NAMED / 4 + 1, "{} entries", views.addressed.len()); + assert!(looks.get() <= 1_000 / 8, "{} looks through the slots for 1,000 views", looks.get()); + } + + /// The live slots are those of every view heap, CPU-only ones too, while the heap is there. + #[cfg(windows)] + #[test] + fn view_heaps_are_looked_through_while_they_are_there() { + let desc = HeapDesc { kind: VIEWS_KIND, count: 4, flags: 0, nodes: 1 }; + let mut h: This = std::ptr::null(); + assert_eq!(create(desc, Placement { address: 0, size: 0 }, &mut h), S_OK); + let words = [VIEW_TAG, 0x1234_5678, 0x0abc_def0]; + // SAFETY: slot 2 of the heap just made. + unsafe { ((heap(h).start + 2 * 32) as *mut [u32; 3]).write_unaligned(words) }; + let named = || { + let mut found = false; + heap_records(&mut |i, generation| found |= [i, generation] == [words[1], words[2]]); + found + }; + assert!(named(), "a CPU-only heap's record"); + release(h); + assert!(!named(), "not after the heap is gone"); + } + + /// The live slots are those of every sampler heap too, CPU-only ones included, at their + /// own 16 bytes a slot, while the heap is there ([`samplers_bound`]). Before, only view + /// heaps were looked through, and a sampler heap's record kept nothing. + #[cfg(windows)] + #[test] + fn sampler_heaps_are_looked_through_while_they_are_there() { + let desc = HeapDesc { kind: SAMPLERS, count: 4, flags: 0, nodes: 1 }; + let mut h: This = std::ptr::null(); + assert_eq!(create(desc, Placement { address: 0, size: 0 }, &mut h), S_OK); + let words = [VIEW_TAG, 0x2345_6789, 0x0bcd_ef01]; + // SAFETY: slot 3 of the heap just made, its last. + unsafe { ((heap(h).start + 3 * 16) as *mut [u32; 3]).write_unaligned(words) }; + let named = || { + let mut found = false; + heap_records(&mut |i, generation| found |= [i, generation] == [words[1], words[2]]); + found + }; + assert!(named(), "a CPU-only sampler heap's record"); + release(h); + assert!(!named(), "not after the heap is gone"); + } + + /// A title that streams can write samplers with values that change as it plays (a mip bias + /// that follows a dynamic resolution, a least LOD that follows what of a texture is in): + /// each a sampler of its own, and nothing released one, so the table grew by one entry for + /// every one written (20,000 here, with `LEONIDA_VIEW_SAMPLERS_BOUND=0` at the end). Now + /// they go round with the entries carrying an address, under the same most: those in the + /// slots the title shows, looked up every frame, and those in a heap's slots nothing looks + /// up ([`Views::keep_live`]) keep their samplers; a record of one let go is stale, never + /// another sampler, and the sampler written again is named again; a view of a resource is + /// never let go. + #[test] + fn sampler_entries_stay_bounded_when_a_title_writes_new_ones() { + const MOST: usize = 64; + const SHOWN: usize = 16; + const WRITTEN: usize = 20_000; + // A CPU-only heap's records: the samplers the title keeps and copies when it needs them. + let slots = std::cell::RefCell::new(Vec::<[u32; 2]>::new()); + let live = |each: &mut dyn FnMut(u32, u32)| { + for &[i, generation] in slots.borrow().iter() { + each(i, generation); + } + }; + let limits = Limits { shapes: 4, addressed: MOST, samplers: true, live: &live }; + // An anisotropic sampler with mip bias -n/4096; a console one with word 9 n (which of + // its words a title changes is not known here: any makes another sampler). + let biased = |n: usize| { + let mut desc = [0x55, 1, 1, 1, 0, 16, 0, 0, 0, 0, 0, 0, f32::MAX.to_bits()]; + desc[4] = (-(n as f32) / 4096.0).to_bits(); + View::Sampler(desc) + }; + let console = |n: usize| { + let mut desc = [0u32; 27]; + (desc[0], desc[9]) = (0x15, n as u32); + View::ConsoleSampler(desc) + }; + let written = |n: usize| if n.is_multiple_of(2) { biased(n) } else { console(n) }; + let mut views = Views::new(); + let kept: Vec = (0..8).map(|n| written(1 << 20 | n)).collect(); + for view in &kept { + let words = views.name(view.clone(), true, limits); + slots.borrow_mut().push(words); + } + let resource = views.name(View::Shader(0x5a3_0000, None), true, limits); + let mut shown = vec![([0u32; 2], written(0)); SHOWN]; + let mut first = [0u32; 2]; + for n in 0..WRITTEN { + let view = written(n); + let words = views.name(view.clone(), true, limits); + assert_eq!(views.view_at(words[0], words[1]).as_ref(), Some(&view)); + if n == 0 { + first = words; + } + shown[n % SHOWN] = (words, view); + // A frame: the host reads every slot the title shows. + if n % SHOWN == SHOWN - 1 { + for (words, view) in &shown { + assert_eq!(views.view_at(words[0], words[1]).as_ref(), Some(view), "a slot still shown"); + } + } + } + let samplers = views.index.keys().filter(|v| matches!(v, View::Sampler(..) | View::ConsoleSampler(..))).count(); + assert!( + samplers <= MOST && views.list.len() <= MOST + 1, + "{samplers} sampler entries for {WRITTEN} written, {} entries in all", + views.list.len() + ); + for (words, view) in slots.borrow().iter().zip(&kept) { + assert_eq!(views.view_at(words[0], words[1]).as_ref(), Some(view), "a heap's sampler, first looked up now"); + } + assert_eq!(views.view_at(resource[0], resource[1]), Some(View::Shader(0x5a3_0000, None))); + assert_eq!(views.view_at(first[0], first[1]), None, "stale, not another sampler"); + let again = views.name(written(0), true, limits); + assert_eq!(views.view_at(again[0], again[1]), Some(written(0)), "named again"); + // `LEONIDA_VIEW_SAMPLERS_BOUND=0`: one entry each, kept for the run, as before. + let limits = Limits { samplers: false, ..limits }; + let mut views = Views::new(); + for n in 0..WRITTEN { + views.name(written(n), true, limits); + } + assert_eq!((views.list.len(), views.addressed.len()), (WRITTEN, 0)); + } + + /// The views of a resource the title keeps, written again and again with the padding of + /// their descriptions as a stack leaves it (word 3 of a shader resource view's, the + /// union's words past the member of the view's dimension), are one entry and one record + /// each, as are null views; a word the view's kind uses still tells views apart + /// ([`normal_view`]). Before, each such write was an entry freed only when the resource + /// was, and a null view's never. + #[test] + fn resource_views_that_differ_in_padding_alone_are_one_entry() { + if !view_normal() { + return; + } + let null = std::ptr::null(); + let slots = [0u64; 4]; + let at = slots.as_ptr() as u64; + // SAFETY: the handle is a slot of 32 bytes above. + let words = |handle: u64| unsafe { *(handle as *const [u32; 3]) }; + const KEPT: usize = 0x5e1f_0000; + // R8G8B8A8_UNORM (28) is no format another test uses with this resource; 0x7e57 is + // the format of the null views below, which no other test uses. + let live = |view: &View| match view { + View::Shader(r, _) | View::Unordered(r, _, _) if *r == KEPT => true, + View::Shader(0, Some(d)) => d[0] == 0x7e57, + _ => false, + }; + let entries = || VIEWS.read().unwrap().index.keys().filter(|v| live(v)).count(); + let mut seen = Vec::new(); + for n in 0..1_000u32 { + let junk = n.wrapping_mul(0x9e37_79b9) | 1; + // A 2D texture's shader resource view uses four words of its union (4 to 7). + let sampled = [28, 4, 0x1688, junk, 0, 1, 0, 0, junk.rotate_left(3), junk.rotate_left(9)]; + create_srv(null, KEPT as This, &sampled, at); + seen.push(words(at)); + // An unordered buffer view uses seven (2 to 8). + create_uav(null, KEPT as This, null, &[28, 1, 0, 0, 64, 4, 0, 0, 0, junk], at); + // A null 2D texture view. + create_srv(null, null, &[0x7e57, 4, 0x1688, junk, 0, 1, 0, 0, junk, junk], at); + } + seen.sort_unstable(); + seen.dedup(); + assert_eq!(seen.len(), 1, "one record for the view, whatever the padding"); + assert_eq!(entries(), 3, "one entry each for 3,000 views written"); + create_uav(null, KEPT as This, null, &[28, 1, 0, 0, 64, 4, 0, 0, 0, 0x55], at); + assert_eq!(view(at), Some(View::Unordered(KEPT, 0, Some([28, 1, 0, 0, 64, 4, 0, 0, 0, 0])))); + create_srv(null, KEPT as This, &[28, 4, 0x1688, 0x55, 0, 1, 0, 0, 0x66, 0x77], at); + assert_eq!(view(at), Some(View::Shader(KEPT, Some([28, 4, 0x1688, 0, 0, 1, 0, 0, 0, 0])))); + // A field of the union still tells views apart: the most detailed mip. + create_srv(null, KEPT as This, &[28, 4, 0x1688, 0, 1, 1, 0, 0, 0, 0], at); + assert_eq!(entries(), 4); + forget(KEPT); + } + /// A released resource's views go stale; the same view of a new /// resource at the same address is a new record. #[test] @@ -2620,7 +3428,7 @@ mod tests { by_resource: Default::default(), free, shapes: Vec::new(), - shape_index: Default::default(), + ..Views::new() }; let (summary, by_kind) = kept(&views); let each = size_of::<(View, u32)>() as u64; @@ -2674,7 +3482,7 @@ mod tests { by_resource: Default::default(), free: Vec::new(), shapes: Vec::new(), - shape_index: Default::default(), + ..Views::new() }; let (_, before_kind) = kept(&before); for (k, name) in [ diff --git a/d3d12/crates/leonida-gpu/src/descriptor/host.rs b/d3d12/crates/leonida-gpu/src/descriptor/host.rs index 79efb896f9..0aa8e6b83a 100644 --- a/d3d12/crates/leonida-gpu/src/descriptor/host.rs +++ b/d3d12/crates/leonida-gpu/src/descriptor/host.rs @@ -32,6 +32,10 @@ impl Slots { } } + fn has(&self, slot: u32) -> bool { + self.0.get(slot as usize / 64).is_some_and(|bits| bits.load(std::sync::atomic::Ordering::Acquire) & 1 << (slot % 64) != 0) + } + /// Whether it was there. fn remove(&self, slot: u32) -> bool { use std::sync::atomic::Ordering::{AcqRel, Acquire}; @@ -146,6 +150,13 @@ impl DynamicBits { (at < self.len).then(|| self.words[at / 64] >> (at % 64) & 1 != 0) } + /// Whether dynamic slot `at` (counted from the first dynamic one) is + /// taken; one past the end is. + fn taken(&self, at: u32) -> bool { + let at = at as usize; + at >= self.len || self.words[at / 64] >> (at % 64) & 1 != 0 + } + /// Of `[at, end)`, the bits that lie in `at`'s word: the word, their /// mask, how many they are. fn piece(at: usize, end: usize) -> (usize, u64, usize) { @@ -340,9 +351,14 @@ pub(crate) struct HostHeap { /// are due: such a texture is uploaded when a draw reads it through a /// table; one a shader picks by a computed index is brought up to date /// from here ([`HostHeap::texture_slots_due`]). + /// Taken only through [`HostHeap::queue`], which first takes out the + /// slots left in `tabled_inbox`. textures: Mutex, /// What `textures` holds, read without its lock ([`QueueMarks`]). marks: std::sync::Arc, + /// Slots draws read through tables while `textures` was locked, to + /// leave it under the lock's next holder ([`TabledInbox`]). + tabled_inbox: TabledInbox, /// Per title slot, the frame (plus one; 0: never) in which a draw last /// read it through a table, or made a table it lies in (with /// [`TABLED_READ`] set if the draw read it). The draw that @@ -368,11 +384,27 @@ pub(crate) struct HostHeap { spanned: Slots, } -/// The spans of every view heap made ([`HostHeap::placed`]), for the +/// The spans of every view heap standing ([`HostHeap::placed`]), for the /// texture code, which has no heap at hand ([`next_start`], /// [`first_viewed`]). static PLACED_SPANS: Mutex>>> = Mutex::new(Vec::new()); +/// A heap that goes (the title released its descriptor heap) leaves the +/// tables kept of every heap: [`PLACED_SPANS`] and [`GPU_RANGES`] had an +/// entry per heap ever made. Every [`next_start`] and [`first_viewed`] +/// walked the dead spans too, and device-removed reports ([`near_heaps`]) +/// named ranges of heaps gone, whose GPU addresses newer heaps may have. +impl Drop for HostHeap { + fn drop(&mut self) { + let id = self.lease_id; + GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).retain(|r| r.0 != id); + if !self.sampler { + let placed = std::sync::Arc::as_ptr(&self.placed); + PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner()).retain(|w| w.as_ptr() != placed); + } + } +} + /// Where the next texture placed inside `[start, end)` starts, past the /// first bytes of the one at `start` ([`HEAD`]): what is there of the /// texture at `start` ends there, whatever its full size. `None`: no view @@ -1155,22 +1187,27 @@ pub(crate) static SPANS_QUICK: [std::sync::atomic::AtomicU64; 2] = /// does not wait for its lock: every view the title wrote took that lock /// for one heap, and the passes over the textures picked by index hold it /// while they go through their slots (4 of the 16 ms a frame the -/// submitting thread waited for one in a run of another port). Off by -/// default (`LEONIDA_SPANS_QUICK=1`; `LEONIDA_AB` can name it): here the lock -/// was not waited for, and in four runs by turns the submitting thread worked -/// 0.12 to 0.30 ms a frame more with it (runs d41, d43; `docs/findings.md`). +/// submitting thread waited for one in a run of another port). On by +/// default (`LEONIDA_SPANS_QUICK=0`: every write takes the lock, as before; +/// `LEONIDA_AB` can name it). It was off while only the submitting thread +/// was weighed: that thread did not wait for the lock, and in four runs by +/// turns worked 0.12 to 0.30 ms a frame more with it (runs d41, d43; +/// `docs/findings.md`). The recording threads do wait: in timelines of +/// three scenes they waited 23 to 72 ms a frame for the locks of the host +/// heaps, 0.9 to 1.9 ms of it in slot writes, while not one of some 17,000 +/// slot writes a frame went past this lock. /// Ported from Belobug's VIctory-Belobug-AMD (a284ca7, via readmet3xt /// 96dfd9bb8) and trustno1's pull request #1937 (danielibabet), GPL-3.0. fn spans_quick() -> bool { - crate::asked!("LEONIDA_SPANS_QUICK") + crate::toggled!("LEONIDA_SPANS_QUICK") } /// One more slot write past the lock (`quick`) or under it, counted in /// [`SPANS_QUICK`] by each thread in batches: tens of thousands a frame, on /// many threads at once, and a shared counter's cache line is waited for as -/// the lock was. +/// the lock was. (One by one in tests, which read the counts at once.) fn spans_counted(quick: bool) { - const BATCH: u32 = 256; + const BATCH: u32 = if cfg!(test) { 1 } else { 256 }; thread_local! { static COUNTED: std::cell::Cell<[u32; 2]> = const { std::cell::Cell::new([0; 2]) }; } @@ -1228,7 +1265,7 @@ pub(crate) fn remapped(at: usize, len: usize) { /// more memory than changed). Clearing the list here instead (as before) let /// a texture uploaded already keep old bytes after its memory changed: the /// intro's video frames went back during the streaming bursts. -fn compact(ranges: &mut Vec<(u64, u64)>, most: usize) { +pub(crate) fn compact(ranges: &mut Vec<(u64, u64)>, most: usize) { join(ranges); while ranges.len() > most / 2 && ranges.len() > 1 { let wide: Vec<(u64, u64)> = ranges.chunks(2).map(|pair| (pair[0].0, pair[pair.len() - 1].1)).collect(); @@ -1332,9 +1369,14 @@ fn fair_due() -> bool { /// every slot record they make in the queue, and most of those notes change /// nothing: in a run of another port other threads waited 33-44 s for the /// lock in 150 s. Ported from readmet3xt-lab's b377071 (VIctory lineage, -/// GPL-3.0). Off by default (`LEONIDA_QUEUE_MARKS=1`; `LEONIDA_AB` can name -/// it): here no one waited for that lock, and by turns the submitting thread -/// worked +0.27 and +0.06 ms a frame with the marks (runs d41). +/// GPL-3.0). On by default (`LEONIDA_QUEUE_MARKS=0`: every note takes the +/// lock, as before; `LEONIDA_AB` can name it). It was off while only the +/// submitting thread was weighed: that thread did not wait for the lock, +/// and by turns worked +0.27 and +0.06 ms a frame with the marks (runs +/// d41). The recording threads do wait: in timelines of three scenes they +/// waited 3.3 to 18.9 ms a frame for it in table reads +/// ([`HostHeap::texture_slot_tabled`]) and 2.9 to 6.6 ms in slot records, +/// with not one note spared. #[derive(Default)] pub(crate) struct QueueMarks(Box<[std::sync::atomic::AtomicU64]>); @@ -1358,10 +1400,10 @@ impl QueueMarks { } } -/// Whether the queue's marks ([`QueueMarks`]) spare its lock -/// (`LEONIDA_QUEUE_MARKS=1`; off by default). The marks are kept either way. +/// Whether the queue's marks ([`QueueMarks`]) spare its lock (on unless +/// `LEONIDA_QUEUE_MARKS=0`). The marks are kept either way. fn queue_marks() -> bool { - crate::asked!("LEONIDA_QUEUE_MARKS") + crate::toggled!("LEONIDA_QUEUE_MARKS") } /// Since the start, the notes that left the queue's lock alone as they @@ -1371,9 +1413,10 @@ fn queue_marks() -> bool { pub(crate) static QUEUE_SPARED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; -/// One more note at place `site` of [`QUEUE_SPARED`]. +/// One more note at place `site` of [`QUEUE_SPARED`] (one by one in +/// tests, which read the counts at once). fn queue_spared(site: usize) { - const BATCH: u32 = 64; + const BATCH: u32 = if cfg!(test) { 1 } else { 64 }; thread_local! { static SPARED: std::cell::Cell<[u32; 3]> = const { std::cell::Cell::new([0; 3]) }; } @@ -1388,6 +1431,74 @@ fn queue_spared(site: usize) { }); } +/// Title slots draws read through tables whose way out of the queue of +/// textures picked by index found the queue's lock held +/// ([`HostHeap::tabled_in`]): the slot is left here and the draw goes on, +/// and whoever takes the lock next takes the slots here out of the queue +/// before anything else ([`HostHeap::queue`]). So no one sees the queue +/// without them: the result is that of a draw that waited for the lock and +/// took its slot out right after the thread that held it, which it may +/// always have done. Taking a slot out twice changes nothing, and one taken +/// out late is at worst uploaded once more by the pass, never left behind. +/// +/// The recording threads take a slot out at its first table read in a +/// frame, and the heaps' records thread, the passes and the title's +/// threads take the queue's lock as well: in timelines of three +/// scenes the recording threads waited 3.3 to 18.9 ms a frame for it in +/// table reads alone, and 23 to 72 ms a frame for the locks of the host +/// heaps in all. `LEONIDA_TABLED_INBOX=0`: a table read waits for the lock, +/// as before; `LEONIDA_AB` can name it. +#[derive(Default)] +struct TabledInbox { + slots: Mutex>, + /// How many `slots` holds, set under its lock and read without it. + pending: std::sync::atomic::AtomicUsize, +} + +/// Slots past which a table read waits for the queue's lock after all +/// ([`TabledInbox`]): the lock's holders take the slots out at every +/// turn, so only a queue held for long gets this far. +const TABLED_INBOX_MAX: usize = 1 << 16; + +impl TabledInbox { + /// Slot `index` waits here to leave the queue; `false`: full, so it + /// does not. + fn push(&self, index: u32) -> bool { + let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner()); + if slots.len() >= TABLED_INBOX_MAX { + return false; + } + slots.push(index); + self.pending.store(slots.len(), std::sync::atomic::Ordering::Release); + true + } + + /// Whether any slot waits here. + fn pending(&self) -> bool { + self.pending.load(std::sync::atomic::Ordering::Acquire) != 0 + } + + /// Under the queue's lock: every slot waiting here leaves `queue`; how + /// many were in it. + fn take_out_of(&self, queue: &mut TextureQueue) -> u64 { + let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner()); + let out = slots.drain(..).map(|index| u64::from(queue.take_out(index))).sum(); + self.pending.store(0, std::sync::atomic::Ordering::Release); + out + } +} + +/// Whether a table read that finds the queue's lock held leaves its slot +/// to the lock's next holder ([`TabledInbox`]; on unless +/// `LEONIDA_TABLED_INBOX=0`). +fn tabled_inbox() -> bool { + crate::toggled!("LEONIDA_TABLED_INBOX") +} + +/// Since the start: table reads that found the queue's lock held and left +/// their slot to its next holder ([`TabledInbox`]). +pub(crate) static TABLED_INBOX: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// The queue of title slots whose texture view waits to be brought up to /// date for shaders that pick textures by index: which are due, and in /// which order (no host heap needed, so it is tested without one). @@ -2067,16 +2178,17 @@ pub(crate) fn slot_story(slot: u32) -> String { .unwrap_or_default() } -/// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for -/// device-removed reports: a shader indexing a heap past its end faults. -static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); +/// Host heaps' GPU ranges (the heap's `lease_id`, start, bytes, bytes per +/// slot, sampler), for device-removed reports: a shader indexing a heap +/// past its end faults. +static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); /// For device-removed reports: where host GPU address `va` lies against /// the host descriptor heaps. pub(crate) fn near_heaps(va: u64) -> String { let ranges = GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()); let mut text = String::new(); - for &(start, bytes, step, sampler) in ranges.iter() { + for &(_, start, bytes, step, sampler) in ranges.iter() { let kind = if sampler { "sampler" } else { "view" }; let place = if va < start { format!("{:#x} below", start - va) @@ -2349,7 +2461,12 @@ impl HostHeap { tracing::debug!(count, sampler, "host descriptor heap"); // SAFETY: a live shader-visible heap. let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; + let lease_id = { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + }; GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( + lease_id, gpu, u64::from(size) * u64::from(step), u64::from(step), @@ -2394,10 +2511,7 @@ impl HostHeap { kept: (0..count + extra).map(|_| Mutex::new(None)).collect(), next: Mutex::new((0, DynamicBits::new(extra as usize))), free: std::sync::atomic::AtomicU32::new(extra), - lease_id: { - static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); - NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) - }, + lease_id, remap_cursor: Mutex::new(REMAPPED.lock().unwrap_or_else(|e| e.into_inner()).latest), too_long: std::sync::atomic::AtomicU32::new(u32::MAX), strides, @@ -2405,6 +2519,7 @@ impl HostHeap { changed: Slots::new(count as usize), textures: Mutex::new(TextureQueue::with_marks(marks.clone())), marks, + tabled_inbox: TabledInbox::default(), tabled: (0..if sampler { 0 } else { count }) .map(|_| std::sync::atomic::AtomicU32::new(0)) .collect(), @@ -2656,14 +2771,14 @@ impl HostHeap { /// ([`TextureQueue::due`]), and the queue's counts /// ([`TextureQueue::census`]). pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 5]) { - let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let textures = self.queue(); (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame)) } /// A number that changes when a slot is written or made due anew, and /// whether memory was noted since a pass last took the notes. pub(crate) fn texture_news(&self) -> (u64, bool) { - let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes; + let writes = self.queue().writes; let noted = |ranges: &Mutex>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty(); let cursor = if crate::toggled!("LEONIDA_REMAP_HISTORY") { *self.remap_cursor.lock().unwrap_or_else(|e| e.into_inner()) @@ -2679,7 +2794,7 @@ impl HostHeap { /// look): for the card accounting line /// (`crate::resource::card_accounting`). pub(crate) fn texture_slots_all_due(&self, frame: u64) -> Vec<(u32, bool)> { - let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let textures = self.queue(); textures .slots .iter() @@ -2693,7 +2808,7 @@ impl HostHeap { /// that many bytes of its memory there, not all), or not until the /// slot is written again. pub(crate) fn texture_slot_done(&self, index: u32, write: u64, again: Option<(u64, u64)>) { - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); match again { Some((frame, mapped)) => textures.partly(index, write, frame, mapped), None => textures.done(index, write), @@ -2712,26 +2827,26 @@ impl HostHeap { looks: u8, uploaded: u64, ) { - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); textures.recheck(index, write, due, at, print, looks, uploaded); } /// See [`TextureQueue::checked`]. pub(crate) fn texture_slot_checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { - self.textures.lock().unwrap_or_else(|e| e.into_inner()).checked(index) + self.queue().checked(index) } /// Nothing to upload at title slot `index` now (its memory is not /// mapped, or no more of it than before): looked at again after 1, 2, /// 4, ... frames, at most `most`. pub(crate) fn texture_slot_later(&self, index: u32, write: u64, frame: u64, most: u64) { - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); textures.later(index, write, frame, most); } /// See [`TextureQueue::hold`]. pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) { - self.textures.lock().unwrap_or_else(|e| e.into_inner()).hold(index, write, due); + self.queue().hold(index, write, due); } /// Slot `index`, refused a new host texture for lack of room on the card, @@ -2775,13 +2890,13 @@ impl HostHeap { /// See [`TextureQueue::room`]. pub(crate) fn texture_slots_room(&self, frame: u64) -> usize { - self.textures.lock().unwrap_or_else(|e| e.into_inner()).room(frame) + self.queue().room(frame) } /// Bytes of title slot `index`'s memory that were mapped when it was /// last uploaded in part (0: not uploaded, or whole). pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 { - self.textures.lock().unwrap_or_else(|e| e.into_inner()).mapped(index) + self.queue().mapped(index) } /// Takes the ranges of title memory the runtime mapped, unmapped or @@ -2831,7 +2946,7 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); for &slot in &slots { textures.changed(slot, frame, frame + 1); } @@ -2857,7 +2972,7 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); for &slot in &slots { textures.changed(slot, frame, frame + 1); } @@ -2917,7 +3032,7 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); for &slot in &slots { textures.changed(slot, frame, frame); @@ -2938,7 +3053,7 @@ impl HostHeap { slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); let held = slots.len(); - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); // Uploaded before: out of the queue, or in it after an upload (in // part, or whole and being looked at again). slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); @@ -3028,7 +3143,7 @@ impl HostHeap { slots.sort_unstable(); slots.dedup(); slots.retain(|&slot| !self.tabled_lately(slot, frame)); - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); for &slot in &slots { textures.changed(slot, frame, frame + 1); } @@ -3560,22 +3675,87 @@ impl HostHeap { queue_spared(1); return; } - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); - if textures.take_out(index) { - TABLED_WRITES[1].fetch_add(1, Relaxed); + self.tabled_out_of_queue(index, tabled_inbox()); + } + } + } + + /// Title slot `index`, read through a table, leaves the queue of + /// textures picked by index. `inbox`: if the queue's lock is held, the + /// slot is left to its next holder ([`TabledInbox`]) instead of waiting + /// for it. + fn tabled_out_of_queue(&self, index: u32, inbox: bool) { + let mut textures = if inbox { + match self.textures.try_lock() { + Ok(textures) => self.with_tabled_out(textures), + Err(std::sync::TryLockError::Poisoned(e)) => self.with_tabled_out(e.into_inner()), + Err(std::sync::TryLockError::WouldBlock) => { + if self.tabled_inbox.push(index) { + TABLED_INBOX.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return; + } + self.queue() } } + } else { + self.queue() + }; + if textures.take_out(index) { + TABLED_WRITES[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + + /// The queue of textures picked by index, under its lock, with the + /// slots draws read through tables while it was held taken out first + /// ([`TabledInbox`]): every reader and writer of the queue takes it + /// here. + fn queue(&self) -> std::sync::MutexGuard<'_, TextureQueue> { + self.with_tabled_out(self.textures.lock().unwrap_or_else(|e| e.into_inner())) + } + + /// `textures`, the queue just locked, with the slots waiting in + /// [`HostHeap::tabled_inbox`] taken out of it. + fn with_tabled_out<'a>( + &self, + mut textures: std::sync::MutexGuard<'a, TextureQueue>, + ) -> std::sync::MutexGuard<'a, TextureQueue> { + if self.tabled_inbox.pending() { + let out = self.tabled_inbox.take_out_of(&mut textures); + TABLED_WRITES[1].fetch_add(out, std::sync::atomic::Ordering::Relaxed); } + textures } /// Whether the queue of textures holds title slot `index`, by its marks /// ([`QueueMarks`]), without its lock; `None`: ask the queue (the marks - /// are not used, or do not reach the slot). + /// are not used, or do not reach the slot, or the slot may wait to + /// leave it in [`HostHeap::tabled_inbox`], which the queue's lock + /// takes out first). fn queued(&self, index: u32) -> Option { + self.queued_around(index, || {}) + } + + /// [`HostHeap::queued`], running `between` after it looks at the inbox + /// and before it reads the mark (where tests take the inbox out). + /// + /// The inbox first: a take-out clears the slot's mark and only then + /// says no slot waits (Release, under the queue's lock). Read the other + /// way round, a take-out between the two reads would leave a mark that + /// says held with an inbox that says none waits, and a make that + /// expects the slot held would skip the lock and leave it out of the + /// queue. Read this way, a reader that finds no slot waiting by that + /// take-out (Acquire) finds the mark it cleared, or a later write's. + fn queued_around(&self, index: u32, between: impl FnOnce()) -> Option { if !queue_marks() { return None; } - self.marks.get(index).map(|write| write != 0) + let waiting = self.tabled_inbox.pending(); + between(); + let write = self.marks.get(index)?; + if write != 0 && waiting { + return None; + } + Some(write != 0) } /// Whether title slot `index` was a table's within the last @@ -3620,7 +3800,7 @@ impl HostHeap { queue_spared(0); return; } - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); if keeps { let due = if lately && !seen { TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -3640,6 +3820,16 @@ impl HostHeap { self.tabled_in(index, false, crate::frame::current()); } + /// [`HostHeap::slot_tabled`] in frame `frame`, for a test that keeps a + /// frame of its own: the tests beside it begin frames of the process + /// (`crate::frame::test_advance`, the frame waits' test), and a slot + /// taken in a frame begun after the one the test passes on is no + /// table's at that frame ([`HostHeap::copied_tabled`]). + #[cfg(test)] + pub(crate) fn slot_tabled_in(&self, index: u32, frame: u64) { + self.tabled_in(index, false, frame); + } + /// The title slots that hold buffer views. pub(crate) fn buffer_slots(&self) -> Vec { self.buffers.all(|_| true) @@ -3664,6 +3854,20 @@ impl HostHeap { self.spanned.0.get(index as usize / 64).is_none_or(|bits| bits.load(std::sync::atomic::Ordering::Acquire) & bit != 0) } + /// Slots taken out of [`HostHeap::buffer_changes`] and not looked at + /// are written still: the next pass takes them again. + pub(crate) fn buffer_changed_again(&self, slots: &[u32]) { + for &slot in slots { + self.changed.put(slot); + } + } + + /// The record (view index and generation, as [`HostHeap::mirror`] keys + /// it) slot `index` was last made from; 0 if it is made from none. + pub(crate) fn made_key(&self, index: u32) -> Option { + self.made.get(index) + } + /// Records what title slot `index` now holds for shaders that pick /// buffers from the heap: its element stride in the table, and whether /// it is a buffer view at all. @@ -3752,7 +3956,7 @@ impl HostHeap { if queued.is_empty() { queue_spared(2); } else { - let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let mut textures = self.queue(); for slot in queued { textures.remove(slot); } @@ -3864,12 +4068,13 @@ impl HostHeap { pub(crate) fn make_at(&self, index: u32, view: &View) { let kept = make_twinned_info(view, self.at(index), self.twin(index)).0; let bias = take_twin_bias(); - if kept.is_none() { + let is_made = kept.is_some(); + self.write_stride(index, if is_made { with_twin_bias(view_stride_word(view), bias) } else { 0 }); + if !is_made { null_for(view, self.at(index)); } self.put(index); - self.twin_made(index, kept.is_some() && twinned(view)); - self.write_stride(index, if kept.is_some() { with_twin_bias(view_stride_word(view), bias) } else { 0 }); + self.twin_made(index, is_made && twinned(view)); self.keep(index, kept.flatten()); } @@ -3909,11 +4114,13 @@ impl HostHeap { flush_listed(); let (s0, s1) = (views.slot(at), views.slot(at + 1)); let (kept, cast_serial) = make_twinned_info(&view, s0, Some(s1)); + let bias = take_twin_bias(); let Some(kept) = kept else { null_for(&view, s0); if let Some(existing) = views.made.get_mut(&words) { existing.kept = None; existing.twin = false; + existing.stride_word = 0; existing.listed.ready = (0, 0, false); } views.cast_serials.insert(words, u64::MAX); @@ -3921,6 +4128,7 @@ impl HostHeap { }; if let Some(existing) = views.made.get_mut(&words) { existing.kept = kept; + existing.stride_word = with_twin_bias(view_stride_word(&view), bias); existing.listed.ready = (0, 0, false); match cast_serial { Some(cs) => { @@ -3959,9 +4167,9 @@ impl HostHeap { let made = &views.made[&words]; self.copy_listed(index, views.slot(made.at)); if made.twin && twins { + self.write_stride(index, made.stride_word); self.copy_listed(self.raw + index, views.slot(made.at + 1)); self.twins[index as usize].store(true, std::sync::atomic::Ordering::Relaxed); - self.write_stride(index, made.stride_word); } else { self.clear_twin(index); self.write_stride(index, with_twin_bias(made.stride_word, 0)); @@ -4138,6 +4346,94 @@ impl HostHeap { self.kept.get(index as usize)?.lock().unwrap_or_else(|e| e.into_inner()).clone() } + /// Whether slot `index` views one of `buffers` (raw interface pointers). + pub(crate) fn keeps_one_of(&self, index: u32, buffers: &[usize]) -> bool { + use windows::core::Interface; + self.kept.get(index as usize).is_some_and(|slot| { + slot.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|r| buffers.contains(&(r.as_raw() as usize))) + }) + } + + /// The slots that view one of `buffers` (raw interface pointers of + /// buffers placed over title memory the title freed, decommitted or + /// protected: `crate::inplace`) view nothing of them any more, so that + /// the heap under them can go: a slot keeps what it views until the + /// title writes it again ([`HostHeap::kept`]), which it need not do for + /// memory it gave up, and the title's release then waited for good. + /// Returns how many. + /// + /// - A title slot is made unmade: the next draw that reads it through a + /// table, or the pass over the buffer views shaders pick by index + /// (told it changed), makes it again from the record, from a copy or + /// the memory opened anew (`crate::shadow::in_place_let_go` took the + /// old buffer out of the tables). With `now` it also becomes the null + /// view of its record's kind and lets go of the buffer: read before + /// it is made again, it reads zeros. That is for memory the title + /// freed or decommitted, which it was done with on the GPU too (the + /// console would read memory given up). Without `now` (a protection: + /// the GPU may still read the memory, as the console's would) the + /// slot goes on showing the buffer, still the title's memory while + /// its heap stands: submissions sent before read what they would + /// have, and a draw or pass after makes the slot again before it + /// reads it. `crate::inplace` asks again with `now` once the + /// submissions sent before have run. + /// - A dynamic slot no list holds (given back, `next`) becomes a null + /// view under the lock lists take slots with: nothing reads it. + /// - A dynamic slot a list holds is left: the list keeps the buffer + /// itself until it is reset (`HostList::keep`), and may still run. + /// `crate::inplace` asks again while a release waits. + /// + /// The old buffer is retired as any a slot let go of: running + /// submissions may read it through the slot. + pub(crate) fn let_go_of(&self, buffers: &[usize], now: bool) -> u32 { + if self.sampler || buffers.is_empty() { + return 0; + } + let found: Vec = (0..self.kept.len() as u32).filter(|&index| self.keeps_one_of(index, buffers)).collect(); + let mut n = 0; + for index in found { + if index < self.count { + let _held = self.made.lock(index); + if !self.keeps_one_of(index, buffers) { + continue; + } + let shown = self.made.get(index).unwrap_or(0); + // Unmade already, and to be left showing the buffer. + if !now && shown == 0 { + continue; + } + self.quick_is(index, 0); + self.made.set(index, 0); + if now { + match view_at(shown as u32, (shown >> 32) as u32) { + Some(view) => null_for(&view, self.at(index)), + None => null_view(self.at(index)), + } + self.put(index); + self.clear_twin(index); + self.keep(index, None); + } + if self.buffers.has(index) && !IN_BUFFER_PASS.get() { + self.changed.put(index); + } + n += 1; + } else { + let guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); + if guard.1.taken(index - self.count) || !self.keeps_one_of(index, buffers) { + continue; + } + null_buffer_view(self.at(index)); + self.put(index); + self.clear_twin(index); + self.write_stride(index, 0); + self.keep(index, None); + drop(guard); + n += 1; + } + } + n + } + /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes /// of `buffer` from byte `offset` (a multiple of 16): a root SRV with a /// size, whose reads past it return zeros instead of reaching whatever @@ -4357,6 +4653,12 @@ impl HostHeap { self.put(index); host.device.CreateShaderResourceView(buffer, Some(&raw), twin); } + let mark = if leonida_shader::emit::constant_marks() { + leonida_shader::emit::SLOT_STRIDE_CONSTANT + } else { + 0 + }; + self.write_stride(index, mark); self.twin_made(index, true); self.keep_ref(index, Some(buffer)); true @@ -4672,18 +4974,18 @@ impl HostHeap { make_twinned_info(&view, self.at(index), self.twin(index)) }; let bias = take_twin_bias(); - if kept.is_none() && !self.sampler { - null_for(&view, self.at(index)); - } - if kept.is_some() || !self.sampler { - self.put(index); - } - self.twin_made(index, kept.is_some() && twinned(&view)); let is_made = kept.is_some(); if is_made && bias != 0 { - // (`note_buffer` wrote the word without it.) + // (`note_buffer` wrote the word without it: write before publishing `put`/`twin_made`.) self.write_stride(index, with_twin_bias(view_stride_word(&view), bias)); } + if !is_made && !self.sampler { + null_for(&view, self.at(index)); + } + if is_made || !self.sampler { + self.put(index); + } + self.twin_made(index, is_made && twinned(&view)); self.keep(index, kept.flatten()); self.note_cast_serial(index, cast_serial.filter(|&cs| is_made || cs != 0)); self.quick_is(index, if later || cast_serial.is_some() { 0 } else { key }); @@ -4764,7 +5066,7 @@ impl HostHeap { /// `index` at `frame`, in a few words (diagnostics). #[cfg(feature = "diagnostics")] pub(crate) fn texture_slot_state(&self, index: u32, frame: u64) -> String { - let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let textures = self.queue(); match textures.slots.get(&index) { None => "not queued".into(), Some(w) => format!( @@ -5219,14 +5521,14 @@ fn with_twin_bias(word: u32, bias: u32) -> u32 { /// For a raw twin at `twin` showing from `start` (GPU address) `bytes`, /// `by` bytes before its view ([`twin_window`]): moved to the view -/// ([`move_raw`]) where it can be, else kept with a bias ([`twin_bias`]), -/// else made null. +/// ([`move_raw`]) where it can be, else kept with a dword-aligned bias +/// ([`twin_bias`]), else made null. fn settle_twin(twin: D3D12_CPU_DESCRIPTOR_HANDLE, start: u64, bytes: u32, by: u32) { use std::sync::atomic::Ordering::Relaxed; if by == 0 || (staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, bytes, by)) { return; } - if twin_bias() && by < 16 && by < bytes { + if twin_bias() && by < 16 && by.is_multiple_of(4) && by < bytes { TWINS[3].fetch_add(1, Relaxed); TWIN_BIAS.with(|b| b.set(by)); } else { @@ -5287,11 +5589,11 @@ fn twin_window(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bo if end <= start { return None; } - let dwords = u32::try_from((end - from) / 4).ok()?; + let bytes = u32::try_from(end - from).ok()?; if from != start { TWINS[1].fetch_add(1, Relaxed); } - Some((from / 4, dwords, (start - from) as u32)) + Some((from / 4, bytes / 4, (start - from) as u32)) } fn buffer_srv( @@ -7148,6 +7450,32 @@ void BY_FLOATS_OR_NOT(uint3 id : SV_DispatchThreadID) { assert_eq!(constant_bytes(u32::MAX), 64 << 10); } + /// A host heap that goes leaves the tables kept of every heap made: its + /// GPU range (device-removed reports, [`near_heaps`]) and its placed + /// spans ([`next_start`], [`first_viewed`], which walk them all). Both + /// kept an entry per heap ever made, and the reports named ranges of + /// heaps gone whose addresses newer heaps may have. + #[test] + fn a_heap_that_goes_leaves_the_tables_of_every_heap() { + if host().is_none() { + return; // no host GPU + } + let (Some(views), Some(samplers)) = (HostHeap::new(false, 4), HostHeap::new(true, 4)) else { + return; + }; + let ids = [views.lease_id, samplers.lease_id]; + let spans = std::sync::Arc::downgrade(&views.placed); + let ranges = || { + let ranges = GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()); + ids.iter().filter(|&&id| ranges.iter().any(|r| r.0 == id)).count() + }; + let placed = || PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.ptr_eq(&spans)).count(); + assert_eq!((ranges(), placed()), (2, 1), "(heaps' ranges, view heap's spans) while they stand"); + drop(views); + drop(samplers); + assert_eq!((ranges(), placed()), (0, 0), "(heaps' ranges, view heap's spans) left once they went"); + } + /// A null 3D UAV made on the real device leaves it alive. #[test] fn null_3d_uav_is_accepted_by_the_device() { @@ -7901,6 +8229,143 @@ void BY_FLOATS_OR_NOT(uint3 id : SV_DispatchThreadID) { assert_eq!(marks(&heap), held(&[])); } + /// A table read of a slot the queue holds, while another thread holds + /// the queue's lock, leaves the slot to the lock's next holder and goes + /// on; whoever takes the lock next finds the slot out. The old way + /// (`LEONIDA_TABLED_INBOX=0`) waits for the lock. + #[test] + fn table_reads_leave_their_slot_to_the_queues_next_holder() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + if !tabled_inbox() || !tabled_out() { + return; // switched off in this environment + } + let frame = 200; + let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + heap.queue_texture(3, true, false, frame); + heap.queue_texture(4, true, false, frame); + assert_eq!(slots(frame), [4, 3]); + let (sent, got) = std::sync::mpsc::channel(); + std::thread::scope(|scope| { + let held = heap.textures.lock().unwrap_or_else(|e| e.into_inner()); + let read = scope.spawn(|| { + heap.tabled_in(3, true, frame); + sent.send(()).unwrap(); + }); + let back = got.recv_timeout(std::time::Duration::from_secs(2)); + drop(held); + read.join().unwrap(); + assert!(back.is_ok(), "the table read waited for the queue's lock"); + }); + assert!(heap.tabled_inbox.pending()); + // The marks still say held, but no longer answer for it. + assert_eq!(heap.queued(3), None); + assert_eq!(slots(u64::MAX), [4]); + assert!(!heap.tabled_inbox.pending()); + assert_eq!(heap.queued(3), queue_marks().then_some(false)); + // Waiting for the lock, as before. + let (sent, got) = std::sync::mpsc::channel(); + std::thread::scope(|scope| { + let held = heap.textures.lock().unwrap_or_else(|e| e.into_inner()); + let read = scope.spawn(|| { + heap.tabled_out_of_queue(4, false); + sent.send(()).unwrap(); + }); + assert!(got.recv_timeout(std::time::Duration::from_millis(50)).is_err()); + drop(held); + read.join().unwrap(); + assert!(got.recv().is_ok()); + }); + assert!(!heap.tabled_inbox.pending()); + assert_eq!(slots(u64::MAX), []); + } + + /// A slot left to the queue's next holder leaves the queue before that + /// holder does anything else: a write that comes after it queues the + /// slot again, and so does the make of a slot no longer held, whose + /// mark still says it is. + #[test] + fn slots_left_to_the_queue_leave_it_before_the_next_change() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let frame = 300; + let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + heap.queue_texture(2, true, false, frame); + heap.queue_texture(5, true, false, frame); + assert_eq!(slots(frame), [5, 2]); + // Read through a table while the lock was held, then written. + assert!(heap.tabled_inbox.push(2)); + heap.queue_texture(2, true, false, frame); + assert_eq!(slots(frame), [2, 5]); + // Read through a table while the lock was held, then made by a + // draw (or the pass) that did not read it: queued as made. + assert!(heap.tabled_inbox.push(5)); + heap.queue_texture(5, true, true, frame + 1); + assert_eq!(slots(frame + 1), [5, 2]); + assert!(!heap.tabled_inbox.pending()); + } + + /// A take-out of the inbox between a marks reader's two reads leaves + /// it no answer that says held: the slot has just left the queue, so a + /// make that expects it held must take the lock and queue it again. + #[test] + fn marks_read_across_a_take_out_never_say_held() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + if !queue_marks() { + return; // the marks answer for nothing here + } + let frame = 500; + heap.queue_texture(4, true, false, frame); + assert_eq!(heap.queued(4), Some(true)); + assert!(heap.tabled_inbox.push(4)); + let read = heap.queued_around(4, || drop(heap.queue())); + assert!(!heap.tabled_inbox.pending()); + assert_eq!(heap.queued(4), Some(false)); + assert_ne!(read, Some(true), "a mark read across a take-out said held"); + // So the make that expects it held queues it again. + heap.queue_texture(4, true, true, frame + 1); + assert_eq!(heap.queued(4), Some(true)); + } + + /// By default the marks spare the queue's lock: a table read of a slot + /// the queue does not hold neither takes the lock nor leaves the slot + /// to its next holder. So does a write of another view into a slot + /// that holds no placed texture view, past the lock of `placed`. + #[test] + fn notes_that_change_nothing_leave_the_locks_alone_by_default() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let set = |name: &str| std::env::var_os(name).is_some(); + if set("LEONIDA_QUEUE_MARKS") || set("LEONIDA_SPANS_QUICK") || set("LEONIDA_AB") { + return; // not the default here + } + let frame = 400; + let spared = || QUEUE_SPARED[1].load(std::sync::atomic::Ordering::Relaxed); + let quick = || SPANS_QUICK[0].load(std::sync::atomic::Ordering::Relaxed); + let before = (spared(), quick()); + std::thread::scope(|scope| { + let _held = heap.textures.lock().unwrap_or_else(|e| e.into_inner()); + scope + .spawn(|| { + for at in frame..frame + 4 { + heap.tabled_in(6, true, at); + } + }) + .join() + .unwrap(); + }); + assert!(spared() >= before.0 + 4); + assert!(!heap.tabled_inbox.pending()); + assert!(heap.note_buffer(7, None, false).is_empty()); + assert!(quick() > before.1); + assert!(queue_marks() && spans_quick()); + } + /// The queue's marks say which slots it holds, by the write of each /// entry: set by writes and memory made due, kept by looks, uploads in /// part and makes of a slot it holds, cleared when the slot leaves. diff --git a/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs b/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs index 675dc31f15..24da6bf47a 100644 --- a/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs +++ b/d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs @@ -282,3 +282,175 @@ fn dump_buffer_view_descriptor_bytes() { ); } } + +/// Sub-dword unaligned typed buffer views (`by % 4 != 0`, such as `R16_UINT` at an odd element or +/// `R8_UINT` off 4 bytes) must not keep a misaligned raw twin or record an unaligned bias in +/// `strides[slot]`; dword-aligned views (`by` in `[4, 8, 12]`) keep their biased twins; and +/// `constant_raw_at` clears any prior bias when recycling a dynamic slot. +#[test] +fn sub_dword_views_null_twins_and_recycled_raw_cbv_clears_bias() { + if !twin_bias() { + return; + } + const SIZE: u64 = 4096; + let Some(host) = host() else { return }; + let mut heap = HostHeap::new(false, 4).expect("a host view heap"); + if heap.raw == 0 { + // Portable hosts (1,000,000-descriptor cap) still have room inside this test's small heap + // to exercise the exact twin-slot and stride-word machinery. + heap.raw = 64; + heap.twins = (0..32) + .map(|_| std::sync::atomic::AtomicBool::new(false)) + .collect(); + } + let first = heap.dynamic(8).expect("dynamic descriptor slots"); + assert!((first + 8) <= heap.twins.len() as u32); + + let title = Box::new([0u32; SIZE as usize / 4]); + let address = title.as_ptr() as u64; + struct Registration(u64); + impl Drop for Registration { + fn drop(&mut self) { + crate::shadow::unregister(self.0 as usize, self.0); + } + } + crate::shadow::register(address as usize, address, SIZE); + let _registered = Registration(address); + let source = crate::shadow::find(address, SIZE).expect("the registered buffer's host copy"); + let (target, result) = host.shared_buffer(SIZE).expect("a mapped write target"); + let values: [u32; 16] = std::array::from_fn(|i| 0x4567_8000 + i as u32); + // SAFETY: live mapped buffer of SIZE bytes. + unsafe { + let mut data = std::ptr::null_mut(); + source.buffer.Map(0, None, Some(&mut data)).expect("map source"); + data.cast::<[u32; 16]>().write(values); + source.buffer.Unmap(0, None); + } + + let word = |h: &HostHeap, slot: u32| { + let (_, _, data) = h.strides.as_ref().expect("stride table mapping"); + // SAFETY: slot is within `SLOT_STRIDES_COUNT`. + unsafe { (*data as *const u32).add(slot as usize).read_volatile() } + }; + + let code = crate::host::compile(TRANSFER, s!("main"), s!("cs_5_1")).expect("transfer shader"); + // SAFETY: shader blob contains matching root signature. + let (root, pipeline): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + let root = host.device.CreateRootSignature(0, &code).expect("root signature"); + let pipeline = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }) + .expect("compute pipeline"); + (root, pipeline) + }; + let strides_gpu = heap.strides_gpu().expect("strides GPU address"); + let cpu = ListViews::new().expect("CPU descriptor staging"); + let uav_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + FirstElement: 0, + NumElements: 16, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: private CPU slot and live target buffer. + unsafe { + host.device.CreateUnorderedAccessView(&target, None::<&ID3D12Resource>, Some(&uav_desc), cpu.slot(0)); + } + let out_uav_slot = first + 7; + heap.copy_from(out_uav_slot, cpu.slot(0)); + + let read_twin = |h: &HostHeap, slot: u32| -> [u32; 2] { + let list = host.new_list().expect("command list"); + // SAFETY: live heap, pipeline, and mapped result buffer. + unsafe { + result.cast::<[u32; 4]>().write([0xfeed_face; 4]); + list.list.SetDescriptorHeaps(&[Some(h.heap.clone())]); + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pipeline); + list.list.SetComputeRootDescriptorTable(0, h.gpu_handle(h.raw + slot)); + list.list.SetComputeRootDescriptorTable(1, h.gpu_handle(out_uav_slot)); + let constants = [0u32, 0u32, slot]; + list.list.SetComputeRoot32BitConstants(2, 3, constants.as_ptr().cast(), 0); + list.list.SetComputeRootShaderResourceView(3, strides_gpu); + list.list.Dispatch(1, 1, 1); + list.close(); + host.execute(&[&list]); + result.cast::<[u32; 2]>().read_volatile() + } + }; + + let resource = [1, 0, 0, 0, SIZE as u32, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0]; + let mut recording = 1000u64; + let make_via_listed = |recording: &mut u64, view: View| { + let mut rec = [0u32; 8]; + crate::descriptor::record(rec.as_mut_ptr() as u64, view); + *recording += 1; + assert!(heap.make_listed(*recording, [rec[0], rec[1], rec[2]], first).is_some()); + flush_listed(); + }; + // 1. Sub-dword unaligned R16_UINT (format 57, 2 bytes) at odd FirstElement (9 -> byte 18, by = 2; + // 11 -> byte 22, by = 6; 13 -> byte 26, by = 10; 15 -> byte 30, by = 14) and R8_UINT (format 62, + // 1 byte) at FirstElement 17 (by = 1) and 19 (by = 3), both SRV and UAV. + for (format, elem_idx, by) in [(57u32, 9u32, 2u32), (57, 11, 6), (57, 13, 10), (57, 15, 14), (62, 17, 1), (62, 19, 3)] { + for unordered in [false, true] { + let mut desc = [0u32; 16]; + if unordered { + desc[..10].copy_from_slice(&[format, 1, elem_idx, 0, 8, 0, 0, 0, 0, 0]); + } else { + desc[..10].copy_from_slice(&[format, 1, 5768, 0, elem_idx, 0, 8, 0, 0, 0]); + } + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + make_via_listed(&mut recording, View::Placed(unordered, resource, desc)); + let bias_bits = (word(&heap, first) & leonida_shader::emit::VIEW_BIAS_MASK) + >> leonida_shader::emit::VIEW_BIAS_SHIFT; + assert_eq!( + bias_bits, 0, + "non-dword-aligned view (format {format}, by={by}, uav={unordered}) must not record an unaligned bias" + ); + if !unordered { + assert_eq!( + read_twin(&heap, first), + [0, 0], + "non-dword-aligned SRV twin (by={by}) must be null, not reading misaligned pre-view bytes" + ); + } + } + } + + // 2. Dword-aligned unaligned R32_UINT (format 42, 4 bytes) at FirstElement = 6 (byte 24, by = 8) + // keeps its biased twin and reads [values[6], values[7]], then `constant_raw_at` on the same + // slot clears the bias bits to 0. + let mut aligned8 = [0u32; 16]; + aligned8[..10].copy_from_slice(&[42, 1, 5768, 0, 6, 0, 2, 0, 0, 0]); + (aligned8[10], aligned8[11]) = (address as u32, (address >> 32) as u32); + make_via_listed(&mut recording, View::Placed(false, resource, aligned8)); + let bias_bits = (word(&heap, first) & leonida_shader::emit::VIEW_BIAS_MASK) + >> leonida_shader::emit::VIEW_BIAS_SHIFT; + assert_eq!(bias_bits, 8, "8-byte-offset R32_UINT view must record bias=8"); + assert_eq!(read_twin(&heap, first), [values[6], values[7]]); + + // Recycle `first` with `constant_raw_at` on a 256-byte-aligned address inside `source.buffer`. + let gpu_base = source.gpu(address); + assert!( + heap.constant_raw_at(first, &source.buffer, gpu_base + 256, 256), + "constant_raw_at should succeed on 16-byte-aligned GPU address" + ); + let recycled_bias = (word(&heap, first) & leonida_shader::emit::VIEW_BIAS_MASK) + >> leonida_shader::emit::VIEW_BIAS_SHIFT; + assert_eq!( + recycled_bias, 0, + "constant_raw_at must clear stale twin bias when recycling a dynamic slot" + ); +} diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index 6fac25f06e..cc0a491986 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -28,6 +28,8 @@ use crate::host::HostList; use crate::object::This; use crate::pipeline::host::HostPipeline; +mod sigtable; + /// Whether a shader view description reads a texture's depth plane (the /// ambient resolve's stand-in binds one such view and no other). fn is_depth_srv(desc: &[u32; 10]) -> bool { @@ -543,6 +545,34 @@ const BAKE_AHEAD: [u64; 2] = [12, 2]; /// until something is new, the next bakes of the frame need no pass. static BAKE_SERVED: AtomicU64 = AtomicU64::new(0); +/// How many decoration bake draws are at work under [`BAKE_UPLOAD`] (a +/// [`BakeBusy`] each, from the moment they hold it to the end of their work +/// there): what a holder does there is not seen elsewhere until it is done. +/// It takes this heap's flips pending in lists before it shows them (so +/// `needs_gpu_settle_for_bake` stops counting them), and runs its pass with +/// whatever milliseconds were left when it began; a draw that passed the +/// lock then ([`bake_can_skip`]) could reach the card before those slots +/// are shown and bake their stand-ins. Raised before the flips are taken +/// and read after them ([`bake_may_pass`]), so a draw that finds them gone +/// finds this raised. +static BAKE_BUSY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// [`BAKE_BUSY`] raised while this lives. +struct BakeBusy; + +impl BakeBusy { + fn raise() -> Self { + BAKE_BUSY.fetch_add(1, Ordering::SeqCst); + BakeBusy + } +} + +impl Drop for BakeBusy { + fn drop(&mut self) { + BAKE_BUSY.fetch_sub(1, Ordering::SeqCst); + } +} + /// Free-threaded wrapper around a reusable upload-only [`HostList`] protected /// by [`BAKE_UPLOAD`]. D3D12 command allocators, lists, and retained COM /// resources are free-threaded when externally synchronized. @@ -598,6 +628,116 @@ fn bake_flown(slot: &mut Option, number: u64) { } } +/// Whether a decoration bake draw does what needs no lock before taking +/// [`BAKE_UPLOAD`] (`LEONIDA_BAKE_QUICK=0`: everything under it, as before): +/// the wait for uploads on their way and the settle of what is in the air +/// ([`State::settle_for_bake`]), and then, when [`bake_can_skip`] finds no +/// pass, settle or promotion left to do, the draw goes on without the lock +/// at all. Before, every list thread with a bake draw queued behind the one +/// holding the lock while that one waited for the card (a settle, an upload +/// pass run synchronously), even when its own draw needed nothing: in a scene +/// with bakes a mesh dispatch took milliseconds where elsewhere it takes a +/// fraction of one, most of it in that wait. Settles on several threads at +/// once are safe ([`crate::host::settle_for_fence`] is global, the flips +/// take locks of their own); under the lock the flush runs whole as before, +/// and finds little left. While another thread is at work under the lock +/// (its pass, flips it took from lists and has not shown yet) [`BAKE_BUSY`] +/// is raised, so no draw passes then, milliseconds left or not. +fn bake_quick() -> bool { + crate::toggled!("LEONIDA_BAKE_QUICK") +} + +/// Whether a bake draw that takes the lock now would find nothing to do +/// there ([`bake_quick`]): no pass (not the frame's first, the pass exact, +/// and either no milliseconds left or nothing new since the last pass served +/// all there was, `served == writes + 1` with nothing noted), no upload on its +/// way, no settle the heap needs (a flip of the heap pending in a list among +/// it), and no other bake at work under the lock (`busy`, [`BAKE_BUSY`]). +/// It is then as if it had taken the lock a moment before, and it does not. +#[allow(clippy::too_many_arguments)] +fn bake_can_skip( + first: bool, + exact: bool, + left_ms: u64, + served: u64, + writes: u64, + noted: bool, + in_flight: bool, + settle_needed: bool, + busy: bool, +) -> bool { + !first + && exact + && !in_flight + && !settle_needed + && !busy + && (left_ms == 0 || (!noted && served == writes + 1)) +} + +/// [`bake_can_skip`] of a bake draw on `host` now, read in this order: the +/// pass's mark, news, uploads on their way, the settle the heap needs (with +/// its flips pending in lists), and last [`BAKE_BUSY`], which a holder +/// raises before it takes those flips. +fn bake_may_pass(first: bool, exact: bool, left_ms: u64, host: &crate::descriptor::host::HostHeap) -> bool { + let served = BAKE_SERVED.load(Ordering::Acquire); + let (writes, noted) = host.texture_news(); + let in_flight = crate::texture::ahead::in_flight(); + let settle_needed = host.needs_gpu_settle_for_bake(); + let busy = BAKE_BUSY.load(Ordering::SeqCst) != 0; + bake_can_skip(first, exact, left_ms, served, writes, noted, in_flight, settle_needed, busy) +} + +/// The order of a bake draw's work around `lock` ([`bake_quick`]): with +/// `quick`, `pre` runs first without the lock and `skip` with what it found; +/// `true` from `skip` means it served the draw itself and the lock is not +/// taken. Otherwise `locked` runs under the lock, with `pre`'s finding +/// (`P::default()` without `quick`, where neither `pre` nor `skip` runs and +/// the lock is taken first, as before). Whether the lock was passed. +fn bake_gate( + quick: bool, + lock: &std::sync::Mutex, + pre: impl FnOnce() -> P, + skip: impl FnOnce(&P) -> bool, + locked: impl FnOnce(&mut L, P), +) -> bool { + let found = if quick { + let found = pre(); + if skip(&found) { + return true; + } + found + } else { + P::default() + }; + let mut held = lock.lock().unwrap_or_else(|e| e.into_inner()); + locked(&mut held, found); + false +} + +/// Counts what the flush before a decoration bake found to do +/// ([`State::flush_for_bake`], or [`State::settle_for_bake`] alone when the +/// bake passes the lock, [`bake_quick`]) and says so now and then. +fn bake_rescued(drained: usize, settled: bool, flipped: usize, promoted: usize) { + static RESCUED: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + if drained > 0 || settled || flipped > 0 || promoted > 0 { + let n = RESCUED[0].fetch_add(1, Ordering::Relaxed) + 1; + let all_drained = RESCUED[1].fetch_add(drained as u64, Ordering::Relaxed) + drained as u64; + let all_flipped = RESCUED[2].fetch_add(flipped as u64, Ordering::Relaxed) + flipped as u64; + let all_promoted = RESCUED[3].fetch_add(promoted as u64, Ordering::Relaxed) + promoted as u64; + if n.is_power_of_two() { + tracing::info!( + frame = crate::frame::current(), + flushes = n, + drained_ahead = all_drained, + flipped = all_flipped, + promoted_from_lists = all_promoted, + settled, + "flushed deferred texture stand-ins before decoration bake" + ); + } + } +} + /// Pending descriptor publications for a synchronous bake upload pass: slots /// stay on `neutral()` (or their previous compatible view) until the dedicated /// upload list has finished executing on the host GPU. @@ -1487,6 +1627,98 @@ fn sweep_spans() -> bool { crate::toggled!("LEONIDA_SWEEP_SPANS") } +/// Whether the parts whose spans are to be made again ([`sweep_spans`]) are +/// made in one walk over the slots when [`ONE_WALK_FROM`] or more of them +/// are, [`ONE_WALK_BLOCK`] slots at a time with each such part's slots of a +/// block looked at while the block is in the core's cache +/// (`LEONIDA_SPANS_ONE_WALK=0`: a walk over every sixteenth slot of all of +/// them for each such part, as before). +/// +/// A slot's range is 24 bytes, so a part's slots lie 384 bytes apart and a +/// part's walk reads a line of memory for each slot it looks at; with +/// sixteen parts stale the slots were walked sixteen times over, each walk +/// at a stride that stalls on every load unless the slots are still in a +/// cache. In a sampling profile of the title's world (2 ms, 30 s) the +/// thread that records the list ahead of each frame spent 1,103 of its +/// 2,717 samples between the present and the first submission in these +/// spans, 729 of them on the one load of that walk that finds a slot +/// showing nothing (some 2.4 ms a frame at 50 ms frames), while the +/// submitting thread waited for that list 5 to 7 ms a frame. Measured with +/// `spans_of_a_pass` (an optimized build, a Ryzen 7 5800X, the median of +/// 60, either way the spans joined from the parts after it): with 72,000 +/// of 1,152,000 slots showing something and 8 or 16 parts stale, 1.42 and +/// 1.98 ms in one walk where the walks of each part took 1.91 and 3.26 ms +/// with the slots out of the caches (0.67 and 1.24 ms where they took 0.73 +/// and 1.78 in them); with every one of 72,000 slots showing something, +/// where each part's spans hold all of the copies and the parts' tables +/// are taken in turn block by block, 1.64 ms where they took 1.46. The +/// spans are the same either way: each is a copy's lowest start and +/// highest end, whatever the order its ranges are joined in +/// (`heap_range_tests`). A single stale part keeps its own walk, which +/// reads only that part's slots. (It is seldom the pass's own: the pass +/// forgets its part, which clears its bit, before setting its slots again, +/// and slots set into a forgotten part join its spans in place; a part alone +/// stale is mostly one the title wrote to.) The frame line counts the parts +/// made again and the walks a pass, and how many of the slots show +/// something: the one walk was slower only with every slot showing +/// something, so a run where that line shows the slots mostly showing +/// something is the one to compare `LEONIDA_SPANS_ONE_WALK=0` on. +pub(crate) fn spans_one_walk() -> bool { + #[cfg(test)] + if let Some(on) = SPANS_ONE_WALK_IN_TEST.get() { + return on; + } + crate::toggled!("LEONIDA_SPANS_ONE_WALK") +} + +/// How many stale parts make [`spans_one_walk`]'s one walk over the slots +/// worth it: one part's walk reads a sixth of the slots' memory and the one +/// walk all of it, but block by block, and from two parts on it was as +/// quick or quicker in `spans_of_a_pass` (2 parts of 1,152,000 slots out of +/// the caches: 0.72 ms, 0.83 ms a walk for each). +const ONE_WALK_FROM: u32 = 2; + +/// The slots [`spans_one_walk`]'s walk takes at a time, each stale part's +/// among them looked at while they are in the core's own cache: 96 KiB of +/// ranges. A multiple of [`PARTS`], so a block's every sixteenth slot from +/// its `p`th is of part `p`. +const ONE_WALK_BLOCK: usize = 4096; +const _: () = assert!(ONE_WALK_BLOCK.is_multiple_of(PARTS)); + +#[cfg(test)] +thread_local! { + /// [`spans_one_walk`], for the spans this thread asks for. + static SPANS_ONE_WALK_IN_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// Walks over a [`SweepRanges`]'s slots this thread made for spans. + static SPAN_WALKS_IN_TEST: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Since the last frame line: the passes that asked for their spans, the +/// parts whose spans those made again from their slots, the walks over the +/// slots that took, and the slots those passes had and how many of them +/// showed something (diagnostics; [`spans_one_walk`]). +#[cfg(feature = "diagnostics")] +pub(crate) static SPAN_WALKS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +/// Counts a walk over the slots for spans (`SPAN_WALKS`). +fn span_walk() { + #[cfg(test)] + SPAN_WALKS_IN_TEST.set(SPAN_WALKS_IN_TEST.get() + 1); + #[cfg(feature = "diagnostics")] + SPAN_WALKS[2].fetch_add(1, Ordering::Relaxed); +} + +/// Counts a pass's slots and those of them that show something +/// (`SPAN_WALKS`). +#[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))] +fn span_slots(slots: usize, views: u32) { + #[cfg(feature = "diagnostics")] + { + SPAN_WALKS[3].fetch_add(slots as u64, Ordering::Relaxed); + SPAN_WALKS[4].fetch_add(u64::from(views), Ordering::Relaxed); + } +} + /// The parts of a round. const PARTS: usize = HEAP_ROUND as usize; @@ -1610,25 +1842,55 @@ impl SweepRanges { /// slots show something. fn spans(&mut self) -> (crate::host::ByCopy>, u32) { let mut all: crate::host::ByCopy> = Default::default(); + #[cfg(feature = "diagnostics")] + SPAN_WALKS[0].fetch_add(1, Ordering::Relaxed); if !sweep_spans() { // From every slot, as before. (The parts set meanwhile are // stale, so their spans are made again once the switch is on.) + span_walk(); let mut views = 0; for range in self.ranges.ranges() { views += 1; join_span(&mut all, range); } + span_slots(self.ranges.0.len(), views); return (all, views); } - for p in (0..PARTS).filter(|p| self.stale >> p & 1 != 0) { - let part = &mut self.spans[p]; - part.clear(); - let mut views = 0; - for (slot, (copy, from, to)) in self.ranges.part_slots(p as u32, PARTS as u32) { - views += 1; - join_part(part, slot, copy_key(copy), *from, *to); + let stale = self.stale; + #[cfg(feature = "diagnostics")] + SPAN_WALKS[1].fetch_add(u64::from(stale.count_ones()), Ordering::Relaxed); + if stale.count_ones() >= ONE_WALK_FROM && spans_one_walk() { + // Every stale part in one walk ([`spans_one_walk`]). + for p in (0..PARTS).filter(|p| stale >> p & 1 != 0) { + self.spans[p].clear(); + self.views[p] = 0; + } + span_walk(); + for (b, block) in self.ranges.0.chunks(ONE_WALK_BLOCK).enumerate() { + let first = b * ONE_WALK_BLOCK; + for p in (0..PARTS).filter(|p| stale >> p & 1 != 0) { + let (part, mut views) = (&mut self.spans[p], 0); + for (i, range) in block.iter().enumerate().skip(p).step_by(PARTS) { + if let Some((copy, from, to)) = range { + views += 1; + join_part(part, (first + i) as u32, copy_key(copy), *from, *to); + } + } + self.views[p] += views; + } + } + } else { + for p in (0..PARTS).filter(|p| stale >> p & 1 != 0) { + let part = &mut self.spans[p]; + part.clear(); + span_walk(); + let mut views = 0; + for (slot, (copy, from, to)) in self.ranges.part_slots(p as u32, PARTS as u32) { + views += 1; + join_part(part, slot, copy_key(copy), *from, *to); + } + self.views[p] = views; } - self.views[p] = views; } self.stale = 0; // (As many as the part with the most, at least.) @@ -1650,7 +1912,9 @@ impl SweepRanges { } } } - (all, self.views.iter().sum()) + let views = self.views.iter().sum(); + span_slots(self.ranges.0.len(), views); + (all, views) } } @@ -1803,6 +2067,10 @@ pub(crate) struct BufferSweep { ranges: SweepState, // Last refresh frame and covered interval for throttled, unwatched copies. unwatched: std::collections::HashMap, + /// What looks ahead of the next pass found ([`heap_prelook`]). + ahead: Ahead, + /// Slots the last pass, or look ahead of one, looked at. + looked: usize, } impl HeapRanges { @@ -1958,6 +2226,117 @@ mod heap_range_tests { assert!(copies.iter().all(|copy| Arc::strong_count(copy) == 1)); } + /// A seeded linear congruential generator: a number below `below`. + fn lcg(seed: &mut u64, below: usize) -> usize { + *seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (*seed >> 33) as usize % below + } + + /// `kept`'s spans asked for with [`super::spans_one_walk`] as `one`, + /// held to those joined from every slot that shows something, part by + /// part as well; the walks over the slots they took. + fn spans_checked(kept: &mut SweepRanges, one: bool, what: &str) -> u32 { + use std::collections::BTreeMap; + super::SPANS_ONE_WALK_IN_TEST.set(Some(one)); + super::SPAN_WALKS_IN_TEST.set(0); + let (spans, views) = kept.spans(); + let walks = super::SPAN_WALKS_IN_TEST.get(); + super::SPANS_ONE_WALK_IN_TEST.set(None); + assert_eq!(kept.stale, 0, "{what}"); + let mut every: crate::host::ByCopy> = Default::default(); + let mut parts = [0u32; PARTS]; + for (slot, range) in kept.ranges.0.iter().enumerate() { + if let Some(range) = range { + parts[slot % PARTS] += 1; + super::join_span(&mut every, range); + } + } + let table = |spans: &crate::host::ByCopy>| -> BTreeMap { + spans + .iter() + .map(|(&key, (copy, from, to))| { + assert_eq!(key, super::copy_key(copy), "{what}"); + (key, (*from, *to)) + }) + .collect() + }; + assert_eq!(table(&spans), table(&every), "{what}"); + assert_eq!(views, parts.iter().sum::(), "{what}"); + assert_eq!(kept.views, parts, "{what}"); + walks + } + + /// With 1, 2, 8 and all 16 parts stale, among 72,000 slots showing + /// ranges of 4,400 copies, the spans made in one walk over the slots and + /// those made part by part ([`super::spans_one_walk`] on and off) are + /// both those of every slot, and so are the parts' counts of views. + #[test] + fn spans_made_in_one_walk_are_those_of_every_slot() { + use std::sync::Arc; + const SLOTS: usize = 72_000; + let copies: Vec> = (0..4400).map(Arc::new).collect(); + for one in [true, false] { + let mut seed = 0x2545_F491_4F6C_DD1Du64; + let mut kept = SweepRanges::::default(); + let range = |seed: &mut u64| { + let from = lcg(seed, 1 << 20) as u64; + Some((copies[lcg(seed, copies.len())].clone(), from, from + 1 + lcg(seed, 4096) as u64)) + }; + for slot in 0..SLOTS as u32 { + // Most slots show nothing, as in the title's heap. + let shows = lcg(&mut seed, 3) == 0; + kept.set(slot, if shows { range(&mut seed) } else { None }); + } + spans_checked(&mut kept, one, "filled"); + for stale in [1, 2, 8, 16] { + let mut parts: Vec = (0..PARTS).collect(); + for _ in 0..PARTS - stale { + parts.swap_remove(lcg(&mut seed, parts.len())); + } + for &p in &parts { + // A slot of the part that shows something shows + // another copy's range or nothing (the part's spans + // are made again), and others of it anything. + let shown = (p..SLOTS).step_by(PARTS).find(|&slot| kept.ranges.0[slot].is_some()).unwrap(); + kept.set(shown as u32, None); + if lcg(&mut seed, 2) == 0 { + kept.set(shown as u32, range(&mut seed)); + } + for _ in 0..lcg(&mut seed, 20) { + let slot = p + PARTS * lcg(&mut seed, SLOTS / PARTS); + kept.set(slot as u32, if lcg(&mut seed, 4) == 0 { None } else { range(&mut seed) }); + } + } + assert_eq!(kept.stale.count_ones() as usize, stale); + spans_checked(&mut kept, one, &format!("one walk {one}, {stale} parts stale")); + } + } + } + + /// With every part stale the spans are made in one walk over the slots, + /// not sixteen ([`super::spans_one_walk`]); with one part stale, or the + /// switch off, in a walk for each stale part. + #[test] + fn stale_parts_are_made_again_in_one_walk() { + use std::sync::Arc; + let copies: Vec> = (0..40).map(Arc::new).collect(); + let mut kept = SweepRanges::::default(); + for slot in 0..1000u32 { + kept.set(slot, Some((copies[slot as usize % copies.len()].clone(), u64::from(slot), u64::from(slot) + 8))); + } + spans_checked(&mut kept, true, "filled"); + for (stale, one, walks) in [(16, true, 1), (16, false, 16), (1, true, 1), (1, false, 1), (2, true, 1), (2, false, 2)] { + // A slot of each of the first `stale` parts shows nothing now. + for p in 0..stale { + kept.set(p + 32, None); + kept.set(p + 32, Some((copies[0].clone(), 0, 1))); + } + assert_eq!(kept.stale.count_ones(), stale); + let made = spans_checked(&mut kept, one, &format!("{stale} parts stale, one walk {one}")); + assert_eq!(made, walks, "{stale} parts stale, one walk {one}"); + } + } + /// The spans of 4,400 copies from the ranges of 72,000 slots, as a pass /// makes them, by slot and from the table they were in. Run with /// `--ignored --nocapture`. @@ -2038,6 +2417,54 @@ mod heap_range_tests { ms[2] ); } + // Parts made stale and their spans made again, as a pass finds them + // after the title wrote slots of many parts: a walk over the slots + // for each part, and one walk for all ([`super::spans_one_walk`]); + // 72,000 slots with every one and an eighth of them showing + // something, and 72,000 showing among 1,152,000 (27 MB of slots, a + // heap whose views lie far apart); warm, and cold as once a frame + // (96 MiB written over before each), the ways taken in turn and the + // median of 60 given. The spans of all parts are joined after + // either (the last column, with no part made again). + let mut over = vec![0u8; 96 << 20]; + for (slots, shown) in [(72_000u32, 1usize), (72_000, 8), (1_152_000, 16)] { + let mut kept = SweepRanges::::default(); + for slot in (0..slots).step_by(shown) { + let copy = &copies[slot as usize / shown * 7919 % 4399]; + kept.set(slot, Some((copy.clone(), u64::from(slot), u64::from(slot) + 64))); + } + for stale in [1u32, 2, 4, 8, 16] { + for cold in [false, true] { + let ways = [(Some(false), stale), (Some(true), stale), (None, 0)]; + let mut ms = [const { Vec::new() }; 3]; + for round in 0..60u8 { + // (In turn, first one way and then the other.) + for way in [0, 1, 2].map(|way| if round % 2 == 0 { way } else { 2 - way }) { + let (one, stale) = ways[way]; + super::SPANS_ONE_WALK_IN_TEST.set(one); + kept.stale = (u32::MAX.checked_shr(32 - stale).unwrap_or(0)) as u16; + if cold { + over.iter_mut().step_by(64).for_each(|b| *b = b.wrapping_add(round)); + std::hint::black_box(&over); + } + let t = std::time::Instant::now(); + assert_eq!(kept.spans().0.len(), 4399); + ms[way].push(t.elapsed().as_secs_f64() * 1e3); + } + } + super::SPANS_ONE_WALK_IN_TEST.set(None); + let [part, one, joined] = ms.map(|mut ms| { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] + }); + println!( + "{slots} slots, one in {shown} showing, {stale:2} parts stale, {}: the spans {part:.2} ms by a walk for each part, \ + {one:.2} ms in one walk ({joined:.2} ms of either joining the parts)", + if cold { "cold" } else { "warm" } + ); + } + } + } } } @@ -2264,61 +2691,28 @@ fn set(roots: &mut Vec, slot: u32, root: Root) { roots[slot] = root; } -/// The pass over the buffer views of `heap` that shaders pick by index -/// ([`State::heap_buffers`]): their host slots are made, and the host copies -/// they show are to be refreshed. -fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::host::HostHeap, frame: u64) -> Vec { - let started = std::time::Instant::now(); - // Per host heap: the host copy and range each slot's buffer view - // reads, kept from pass to pass. Only the slots written since the - // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s - // at best); all of them every 16 passes, because a view of a - // released resource goes stale without a write, and a slot written - // before its memory had a host copy is only made then. - let mut kept = host.buffer_sweep.lock().unwrap_or_else(|e| e.into_inner()); - #[cfg(feature = "diagnostics")] - if let Some(indexed) = crate::ab::pick("LEONIDA_INDEX_HEAP_SPANS") { - kept.ranges.change_backend(indexed_sweep_allowed(indexed, sweep_spans_in_ab, sweep_spans)); - } - let changed = host.buffer_changes(); - let all = kept.passes == 0 || (kept.passes % HEAP_ROUND == 0 && !heap_spread()); - let slots = if all { - kept.ranges.clear(); - host.buffer_slots() - } else if heap_spread() { - // The written ones, and this pass's part of the others (each once: - // a written slot of the part was looked at twice). - let (part, parts) = ((kept.passes % HEAP_ROUND) as u32, HEAP_ROUND as u32); - kept.ranges.forget_part(part); - let mut slots = host.buffer_slots_of(part, parts); - if !changed.is_empty() { - slots.extend(changed); - if sweep_spans() { - slots.sort_unstable(); - slots.dedup(); - } - } - slots - } else { - changed - }; - kept.passes += 1; +/// What a slot of the title's heap shows for the pass over its buffer views: +/// the copy and range its buffer view reads, and whether it is an unordered +/// view; `None` for a slot a draw's table has (the draw brings what it reads +/// up to date) and for one that shows no buffer. +type Shows = Option<(Span, bool)>; + +/// What slots `slots` of `heap` show ([`Shows`]), each with the record it +/// held as it was looked at (read before: a record written meanwhile is +/// another than the one kept), looked at some at a time on several threads; +/// their host slots are made +/// ([`crate::descriptor::host::HostHeap::mirror_for_pass`]). +fn look_at_slots( + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + frame: u64, + slots: &[u32], +) -> Vec<(u32, Option<[u32; 3]>, Shows)> { // Whether the device was there before the pass: a view that removes // it is named below. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); let alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); - let mut unordered = Vec::new(); - /// The title's heap, for the threads that look. - struct Shared<'a>(&'a crate::descriptor::Heap); - // SAFETY: a heap is free-threaded (its methods are called by any thread of - // the title's), and it lives until all of them have looked. - unsafe impl Sync for Shared<'_> {} - impl Shared<'_> { - fn handle(&self, index: u32) -> Option { - self.0.handle(index) - } - } - let heap = Shared(heap); + let heap = SharedHeap(heap); // What a slot of the title's shows: its copy and range, and whether it is // an unordered view. let look = |index: u32| { @@ -2342,7 +2736,13 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho let parts: Vec<&[u32]> = slots.chunks(AT_A_TIME).collect(); let found: Vec>> = parts.iter().map(|_| Default::default()).collect(); crate::land::each_view(false, parts.len(), &|n| { - let looked: Vec<_> = parts[n].iter().map(|&index| (index, look(index))).collect(); + let looked: Vec<_> = parts[n] + .iter() + .map(|&index| { + let seen = heap.handle(index).and_then(crate::descriptor::record_at); + (index, seen, look(index)) + }) + .collect(); // (After each piece while the device lives: a cheap query.) if alive && let Some(why) = crate::descriptor::host::device_removed() @@ -2358,7 +2758,297 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho } let _ = found[n].set(looked); }); - for (index, shows) in found.into_iter().filter_map(std::sync::OnceLock::into_inner).flatten() { + found.into_iter().filter_map(std::sync::OnceLock::into_inner).flatten().collect() +} + +/// The title's heap, for the threads that look at its slots. +struct SharedHeap<'a>(&'a crate::descriptor::Heap); +// SAFETY: a heap is free-threaded (its methods are called by any thread of +// the title's), and it lives until all of them have looked. +unsafe impl Sync for SharedHeap<'_> {} +impl SharedHeap<'_> { + fn handle(&self, index: u32) -> Option { + self.0.handle(index) + } +} + +/// Whether the pass over the heap's buffer views is looked ahead of, and how +/// often (`LEONIDA_HEAP_PRELOOK=1`, every `LEONIDA_HEAP_PRELOOK_MS`, 3 if not +/// given; off by default): while it waits for the next present, the thread +/// that records the lists ahead of frames ([`passes_ahead`]) looks at the +/// slots written since the last look and at the coming pass's part of the +/// others ([`heap_look_ahead`]), and the pass then looks only at those +/// written since, or whose look no longer holds ([`kept_from_ahead`]). +/// +/// What it is for (run e_base1, the title's world, the RX 7900 XT): the list +/// ahead of a frame took 13.8 ms to record, 4.9 of them looking at slots +/// (some 29,000 a pass: a sixteenth of 160,000 buffer slots, and those +/// written), and the line's thread stood 13.3 ms a frame waiting for it at +/// the frame's first submission: the list is begun at the line's present, +/// and the title, a frame ahead, has the next frame's first submission in +/// the line by then. A look ahead makes those slots' host descriptors, with +/// their copies found, before the present; what stays for the pass is, for +/// each slot looked at ahead, a read of its record, of the key its host slot +/// was made from and of the view's generation. Not measured in the game. +/// +/// What changes: a written slot's host descriptor shows its buffer from the +/// look on, where it showed none (or the view before it) until the pass; +/// lists sent between the two that read the slot by index read the copy as +/// its last refresh left it, where they read zeros. The title wrote the +/// record, so its lists in the air do not read the slot (on the console they +/// would read the new record too); the pass refreshes the copy before the +/// frame's first submission, as before. An unordered view found ahead is +/// declared written (`crate::picked`) from the look on, not from the pass. +/// What the pass keeps of a look is what its own look would find but for +/// one case: another copy found for the view's memory between the two. Its +/// own look would bring that one up to date while the slot goes on showing +/// the copy it was made with (the look does not make a slot again for that: +/// `HEAP_VIEWS_ELSEWHERE` counts such slots); kept, the pass brings up to +/// date the copy the slot shows. A slot that showed nothing at the look (a +/// draw's table had it at the look's frame, its memory had no copy yet) is +/// looked at again by the pass, whose own look, at its frame, may find a +/// buffer there. A panic in a look gives the pass back what the looks took: +/// the written slots, and its part. Only with the list ahead of a frame +/// recorded by a thread of its own ([`passes_ahead`] on, not +/// `LEONIDA_PASSES_AHEAD=2`) and with a part of the slots looked at in each +/// pass ([`heap_spread`], not `LEONIDA_HEAP_SPREAD=0`); without, no look +/// is made and nothing changes (the frame line counts none, and with the +/// passes ahead off is not printed). Off by default: its tests +/// cover what the pass keeps and what it looks at again, but no game run has +/// been made with it. +pub(crate) fn heap_prelook() -> Option { + let every = || { + static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + *EVERY.get_or_init(|| { + let ms = std::env::var("LEONIDA_HEAP_PRELOOK_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(3u64); + std::time::Duration::from_millis(ms.clamp(1, 100)) + }) + }; + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("LEONIDA_HEAP_PRELOOK") { + return on.then(every); + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + ON.get_or_init(|| crate::switch::on("LEONIDA_HEAP_PRELOOK")).then(every) +} + +/// What looks ahead of the pass over a heap's buffer views found +/// ([`heap_look_ahead`]), until the pass: the slots they found showing a +/// buffer, each with the record it held then; those they looked at that +/// showed none (a draw's table had the slot at the look's frame, its memory +/// had no copy yet, or its record was not read), which the pass looks at +/// again; and the pass whose part they looked at, plus one (0: none). +#[derive(Default)] +struct Ahead { + slots: Vec<(u32, [u32; 3])>, + nothing: Vec, + part_of: u64, +} + +/// Whether the pass keeps what a look ahead of it found for a slot that +/// showed a buffer then (`seen`: the record it held), instead of looking at +/// the slot again: it holds the same record (`now`), its host slot is made +/// from that record still (`made`: the key of the record it is made from; a +/// slot let go of, made null or made again since is not), no draw's table +/// has it (`tabled`: the pass leaves those to the draws) and the view is +/// alive (`live`: one of a released resource is looked at, as the pass's +/// part would). With all of these the pass's own look finds the same view, +/// and the copy its slot shows. +fn kept_from_ahead(seen: [u32; 3], now: Option<[u32; 3]>, made: Option, tabled: bool, live: bool) -> bool { + let key = u64::from(seen[2]) << 32 | u64::from(seen[1]); + now == Some(seen) && made == Some(key) && !tabled && live +} + +/// Of the slots looks ahead of the pass found ([`Ahead`]), those the pass +/// looks at again ([`kept_from_ahead`]), on several threads. +fn ahead_again(heap: &crate::descriptor::Heap, host: &crate::descriptor::host::HostHeap, frame: u64, ahead: &[(u32, [u32; 3])]) -> Vec { + let heap = SharedHeap(heap); + const AT_A_TIME: usize = 1024; + let parts: Vec<&[(u32, [u32; 3])]> = ahead.chunks(AT_A_TIME).collect(); + let found: Vec>> = parts.iter().map(|_| Default::default()).collect(); + crate::land::each_view(false, parts.len(), &|n| { + let again = parts[n] + .iter() + .filter(|&&(index, seen)| { + let now = heap.handle(index).and_then(crate::descriptor::record_at); + !kept_from_ahead(seen, now, host.made_key(index), host.copied_tabled(index, frame), crate::descriptor::record_live(seen)) + }) + .map(|&(index, _)| index) + .collect(); + let _ = found[n].set(again); + }); + found.into_iter().filter_map(std::sync::OnceLock::into_inner).flatten().collect() +} + +/// Since the last frame line: looks ahead of the pass over the heap's buffer +/// views; slots they looked at; slots looked at ahead that the pass kept, and +/// that it looked at again ([`heap_prelook`]). +pub(crate) static PRELOOK_STATS: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// A look ahead of the next pass over the buffer views of the heap the lists +/// ahead of frames are for ([`heap_prelook`]), by the thread that records +/// them while it waits for the present; `false` if there was nothing to look +/// at (no such heap, it is gone, or no shader has picked a buffer from it). +pub(crate) fn heap_look_ahead() -> bool { + // (Shared, as a recording holds it: the look and the pass it looks + // ahead of take turns under the heap's `buffer_sweep`.) + let _recording = AHEAD_RECORDING.read().unwrap_or_else(|e| e.into_inner()); + let at = AHEAD_HEAP.lock().unwrap_or_else(|e| e.into_inner()).0; + // (It stays from here on: `view_heap_gone` waits for this look.) + if at == 0 || !AHEAD_BUFFERS.load(Ordering::Relaxed) || crate::descriptor::with_heap(at, |_| ()).is_none() { + return false; + } + let heap = crate::descriptor::heap(at as This); + let Some(host) = heap.host().filter(|host| host.strides_gpu().is_some()) else { + return false; + }; + let _looking = crate::timeline::span("ahead of the present: the heap's buffer views looked at"); + look_ahead(heap, host, crate::frame::current()); + true +} + +/// [`heap_look_ahead`] of `heap`: the slots written since the last look (but +/// those a draw's table has, left to the pass) and, at the first look since +/// a pass, the coming pass's part of the others, looked at and kept as the +/// pass keeps them; how many were looked at. Only with a part of the slots +/// looked at in each pass ([`heap_spread`]), and once a pass has looked at +/// all of them. +fn look_ahead(heap: &crate::descriptor::Heap, host: &crate::descriptor::host::HostHeap, frame: u64) -> usize { + if !heap_spread() { + return 0; + } + let mut kept = host.buffer_sweep.lock().unwrap_or_else(|e| e.into_inner()); + if kept.passes == 0 { + return 0; + } + let (tabled, mut slots): (Vec, Vec) = host.buffer_changes().into_iter().partition(|&index| host.copied_tabled(index, frame)); + // (Whether a draw's table has them is the pass's to say, at its frame.) + host.buffer_changed_again(&tabled); + let next = kept.passes + 1; + if kept.ahead.part_of != next { + let part = (kept.passes % HEAP_ROUND) as u32; + kept.ranges.forget_part(part); + // What was found of the part before is looked at anew now. + kept.ahead.slots.retain(|&(index, _)| index % HEAP_ROUND as u32 != part); + kept.ahead.nothing.retain(|&index| index % HEAP_ROUND as u32 != part); + slots.extend(host.buffer_slots_of(part, HEAP_ROUND as u32)); + slots.sort_unstable(); + slots.dedup(); + kept.ahead.part_of = next; + } + kept.looked = slots.len(); + if slots.is_empty() { + return 0; + } + let looking = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + #[cfg(test)] + if look_ahead_tests::PANIC.with(std::cell::Cell::get) { + panic!("a look ahead of the pass panicked (test)"); + } + look_at_slots(heap, host, frame, &slots) + })); + let looked = match looking { + Ok(looked) => looked, + Err(panic) => { + // What the looks took is the pass's again: the slots written + // since its last look (written still, as are those looks before + // kept), and its part, which it looks at itself. + let ahead = std::mem::take(&mut kept.ahead); + host.buffer_changed_again(&slots); + host.buffer_changed_again(&ahead.slots.iter().map(|&(index, _)| index).collect::>()); + host.buffer_changed_again(&ahead.nothing); + drop(kept); + std::panic::resume_unwind(panic); + } + }; + // A slot looked at again is kept as it is found now. + kept.ahead.slots.retain(|(index, _)| slots.binary_search(index).is_err()); + kept.ahead.nothing.retain(|index| slots.binary_search(index).is_err()); + let mut unordered = Vec::new(); + for (index, seen, shows) in looked { + let range = shows.map(|(range, written)| { + if written { + unordered.push(range.clone()); + } + range + }); + match (&range, seen) { + (Some(_), Some(seen)) => kept.ahead.slots.push((index, seen)), + // The pass's own look, at its frame, may find what this one + // did not. + _ => kept.ahead.nothing.push(index), + } + kept.ranges.set(index, range); + } + if crate::picked::on() { + crate::picked::shown(unordered, false); + } + PRELOOK_STATS[0].fetch_add(1, Ordering::Relaxed); + PRELOOK_STATS[1].fetch_add(slots.len() as u64, Ordering::Relaxed); + slots.len() +} + +/// The pass over the buffer views of `heap` that shaders pick by index +/// ([`State::heap_buffers`]): their host slots are made, and the host copies +/// they show are to be refreshed. +fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::host::HostHeap, frame: u64) -> Vec { + let started = std::time::Instant::now(); + // Per host heap: the host copy and range each slot's buffer view + // reads, kept from pass to pass. Only the slots written since the + // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s + // at best); all of them every 16 passes, because a view of a + // released resource goes stale without a write, and a slot written + // before its memory had a host copy is only made then. + let mut kept = host.buffer_sweep.lock().unwrap_or_else(|e| e.into_inner()); + #[cfg(feature = "diagnostics")] + if let Some(indexed) = crate::ab::pick("LEONIDA_INDEX_HEAP_SPANS") { + kept.ranges.change_backend(indexed_sweep_allowed(indexed, sweep_spans_in_ab, sweep_spans)); + } + let changed = host.buffer_changes(); + let all = kept.passes == 0 || (kept.passes % HEAP_ROUND == 0 && !heap_spread()); + // What looks ahead of this pass found ([`heap_prelook`]; nothing + // without). + let ahead = std::mem::take(&mut kept.ahead); + let slots = if all { + kept.ranges.clear(); + host.buffer_slots() + } else if heap_spread() { + // The written ones, and this pass's part of the others (each once: + // a written slot of the part was looked at twice). The part may + // have been looked at ahead, and so may written ones: of those, the + // ones whose look no longer holds. + let (part, parts) = ((kept.passes % HEAP_ROUND) as u32, HEAP_ROUND as u32); + let mut slots = if ahead.part_of == kept.passes + 1 { + Vec::new() + } else { + kept.ranges.forget_part(part); + host.buffer_slots_of(part, parts) + }; + let mut again = if ahead.slots.is_empty() { Vec::new() } else { ahead_again(heap, host, frame, &ahead.slots) }; + if !ahead.slots.is_empty() || !ahead.nothing.is_empty() { + PRELOOK_STATS[2].fetch_add((ahead.slots.len() - again.len()) as u64, Ordering::Relaxed); + PRELOOK_STATS[3].fetch_add((again.len() + ahead.nothing.len()) as u64, Ordering::Relaxed); + } + // Those that showed nothing at the look: the pass's own look, at its + // frame, may find a buffer. + again.extend(ahead.nothing); + if !changed.is_empty() || !again.is_empty() { + let joined = !again.is_empty(); + slots.extend(changed); + slots.extend(again); + if sweep_spans() || joined { + slots.sort_unstable(); + slots.dedup(); + } + } + slots + } else { + changed + }; + kept.passes += 1; + kept.looked = slots.len(); + let mut unordered = Vec::new(); + for (index, _, shows) in look_at_slots(heap, host, frame, &slots) { let range = shows.map(|(range, written)| { if written { unordered.push(range.clone()); @@ -3073,6 +3763,10 @@ impl State { if batch_why() { list.batch_writer(&p.name); } + // Diagnostics (`LEONIDA_UNDECLARED_TRACE`): what this bind declares, + // and whether its program may store past that. + #[cfg(feature = "diagnostics")] + let traced = crate::host::undeclared::binding(list, &p.name, p.stages.iter().any(|stage| stage.translated().stores)); self.views_untold = false; // (Clears the cache if the switch changed since the last call.) self.cache.sync(); @@ -3334,6 +4028,11 @@ impl State { } } } + #[cfg(feature = "diagnostics")] + if let Some(traced) = traced { + let builder = crate::pipeline::is_builder(self.pipeline as This); + traced.bound(self.views_untold, || stores_declared(p, builder), || undeclared_why(p, builder)); + } // Depth textures it writes through unordered access: their colour // twins hold what they lack from here on. list.twins_written(); @@ -3670,29 +4369,18 @@ impl State { /// (`LEONIDA_UPLOAD_AHEAD=1`) or deferred behind the `neutral()` gray /// stand-in (`LEONIDA_SHOW_AFTER=1` / `shows_other`) have finished /// uploading and flipped to their real descriptors before a one-shot - /// decoration bake draw samples them. + /// decoration bake draw samples them. `before` is what + /// [`State::settle_for_bake`] did ahead of the bake's lock + /// ([`bake_quick`]), counted with this flush's own. fn flush_for_bake( &self, list: &HostList, host: &crate::descriptor::host::HostHeap, mut sync: Option<&mut BakeSync>, + before: (usize, bool, usize), ) { - static RESCUED: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; - let drained = crate::texture::ahead::drain(); - let mut settled = false; - let mut flipped = 0usize; - for _ in 0..4 { - let need_settle = host.needs_gpu_settle_for_bake(); - if need_settle { - settled = true; - crate::host::settle_for_fence(); - } - flipped += host.texture_views_remade(); - flipped += host.texture_slots_flip(); - if !need_settle || !host.needs_gpu_settle_for_bake() { - break; - } - } + let (drained, settled, flipped) = self.settle_for_bake(host); + let (drained, settled, flipped) = (drained + before.0, settled || before.1, flipped + before.2); let pending = host.take_pending_list_flips(); let mut promoted = 0usize; if !pending.is_empty() { @@ -3768,23 +4456,32 @@ impl State { promoted += 1; } } - if drained > 0 || settled || flipped > 0 || promoted > 0 { - let n = RESCUED[0].fetch_add(1, Ordering::Relaxed) + 1; - let all_drained = RESCUED[1].fetch_add(drained as u64, Ordering::Relaxed) + drained as u64; - let all_flipped = RESCUED[2].fetch_add(flipped as u64, Ordering::Relaxed) + flipped as u64; - let all_promoted = RESCUED[3].fetch_add(promoted as u64, Ordering::Relaxed) + promoted as u64; - if n.is_power_of_two() { - tracing::info!( - frame = crate::frame::current(), - flushes = n, - drained_ahead = all_drained, - flipped = all_flipped, - promoted_from_lists = all_promoted, - settled, - "flushed deferred texture stand-ins before decoration bake" - ); + bake_rescued(drained, settled, flipped, promoted); + } + + /// The part of [`State::flush_for_bake`] that needs no bake list (nor + /// the bake's lock, [`bake_quick`]): waits for the uploads on their way + /// ([`crate::texture::ahead::drain`]), settles what is in the air while + /// the heap needs it before a bake, and makes the flips and views that + /// were waiting for it. How many uploads it waited for, whether it + /// settled, and how many slots it flipped. + fn settle_for_bake(&self, host: &crate::descriptor::host::HostHeap) -> (usize, bool, usize) { + let drained = crate::texture::ahead::drain(); + let mut settled = false; + let mut flipped = 0usize; + for _ in 0..4 { + let need_settle = host.needs_gpu_settle_for_bake(); + if need_settle { + settled = true; + crate::host::settle_for_fence(); + } + flipped += host.texture_views_remade(); + flipped += host.texture_slots_flip(); + if !need_settle || !host.needs_gpu_settle_for_bake() { + break; } } + (drained, settled, flipped) } /// Whether a graphics draw is a one-shot texture compositor / decoration @@ -3850,126 +4547,155 @@ impl State { }; if is_bake { let began = std::time::Instant::now(); - let mut bake_slot = BAKE_UPLOAD.lock().unwrap_or_else(|e| e.into_inner()); - let gpu = crate::host::host(); - if bake_slot.is_none() - && let Some(gpu) = gpu - { - match gpu.new_list() { - Ok(upload_list) => *bake_slot = Some(BakeList(upload_list)), - Err(e) => tracing::warn!(error = %e, "no host list for synchronous bake uploads"), - } - } - let exact = bake_exact(); - // (With the uploads sent ahead: the number of their submission, once the list is let - // go of the slot below.) - let mut flown = None; - if let (Some(gpu), Some(BakeList(bake_list))) = (gpu, bake_slot.as_ref()) { - let mut sync = BakeSync { publish: Vec::new(), keep: Vec::new() }; - crate::texture::BAKING.set(exact); - self.flush_for_bake(bake_list, host, Some(&mut sync)); - let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); - let run_pass = left > 0 - && (first - || !exact - || { - let (writes, noted) = host.texture_news(); - noted || BAKE_SERVED.load(Ordering::Relaxed) != writes + 1 - }); - let mut served = false; - if run_pass { - let n = EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed) + 1; - if n.is_power_of_two() { - let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); - tracing::info!( - frame, - bakes = n, - queued_at_the_last_pass = slots, - due_at_the_last_pass = due, - uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), - "a draw of the title's decoration bake: textures picked by index are uploaded synchronously first (LEONIDA_BAKE_TEXTURES_MS=0: not)" - ); + // With `LEONIDA_BAKE_QUICK` the wait for the card comes first, outside the lock, and a + // draw with nothing left to do goes on without it ([`bake_quick`]). + bake_gate( + bake_quick(), + &BAKE_UPLOAD, + || self.settle_for_bake(host), + |&(drained, settled, flipped)| { + let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); + // This heap's flips pending in lists are among what `needs_gpu_settle_for_bake` + // counts; those a holder has taken and not shown yet, and its pass, keep + // `BAKE_BUSY` raised. + if crate::host::host().is_none() || !bake_may_pass(first, bake_exact(), left, host) { + return false; } - BAKE_SERVED.store(0, Ordering::Relaxed); - PASS_BUDGET.set(Some((left, 2 << 30, true))); - served = self.heap_textures(bake_list, heap, host, Some(&mut sync)); - PASS_BUDGET.set(None); - } - crate::texture::BAKING.set(false); - let recorded = bake_list.has_recorded_work(); - if bake_ahead() && (recorded || !sync.publish.is_empty()) { - if recorded { - bake_list.close(); + // What the lock's holder would do with no pass and nothing recorded. + bake_rescued(drained, settled, flipped, 0); + host.texture_views_remade(); + host.texture_slots_flip(); + list.wait_gate(crate::host::gate_pending()); + BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); + true + }, + |bake_slot, before| { + // Until this returns, on every way out: before the flush takes this heap's + // pending flips, through the pass, the uploads run and the slots shown (or the + // gate that shows them made, with `LEONIDA_BAKE_AHEAD`). + let _busy = BakeBusy::raise(); + let gpu = crate::host::host(); + if bake_slot.is_none() + && let Some(gpu) = gpu + { + match gpu.new_list() { + Ok(upload_list) => *bake_slot = Some(BakeList(upload_list)), + Err(e) => tracing::warn!(error = %e, "no host list for synchronous bake uploads"), + } } - // Shown by the gate's thread, the heap looked up again there (it may be gone). - let at = std::ptr::from_ref(heap) as usize; - let BakeSync { publish, keep } = - std::mem::replace(&mut sync, BakeSync { publish: Vec::new(), keep: Vec::new() }); - let keep = BakeKept(keep); - let show = move || { - crate::descriptor::with_heap(at, |heap| { - if let Some(host) = heap.host() { - for (index, handle, key) in publish { - let _ = host.publish_uploaded_slot(index, handle, key); + let exact = bake_exact(); + // (With the uploads sent ahead: the number of their submission, once the list is let + // go of the slot below.) + let mut flown = None; + if let (Some(gpu), Some(BakeList(bake_list))) = (gpu, bake_slot.as_ref()) { + let mut sync = BakeSync { publish: Vec::new(), keep: Vec::new() }; + crate::texture::BAKING.set(exact); + self.flush_for_bake(bake_list, host, Some(&mut sync), before); + let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); + let run_pass = left > 0 + && (first + || !exact + || { + let (writes, noted) = host.texture_news(); + noted || BAKE_SERVED.load(Ordering::Relaxed) != writes + 1 + }); + let mut served = false; + if run_pass { + let n = EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); + tracing::info!( + frame, + bakes = n, + queued_at_the_last_pass = slots, + due_at_the_last_pass = due, + uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), + "a draw of the title's decoration bake: textures picked by index are uploaded synchronously first (LEONIDA_BAKE_TEXTURES_MS=0: not)" + ); + } + // Released: a bake that passes the lock reads it (`bake_can_skip`). + BAKE_SERVED.store(0, Ordering::Release); + PASS_BUDGET.set(Some((left, 2 << 30, true))); + served = self.heap_textures(bake_list, heap, host, Some(&mut sync)); + PASS_BUDGET.set(None); + } + crate::texture::BAKING.set(false); + let recorded = bake_list.has_recorded_work(); + if bake_ahead() && (recorded || !sync.publish.is_empty()) { + if recorded { + bake_list.close(); + } + // Shown by the gate's thread, the heap looked up again there (it may be gone). + let at = std::ptr::from_ref(heap) as usize; + let BakeSync { publish, keep } = + std::mem::replace(&mut sync, BakeSync { publish: Vec::new(), keep: Vec::new() }); + let keep = BakeKept(keep); + let show = move || { + crate::descriptor::with_heap(at, |heap| { + if let Some(host) = heap.host() { + for (index, handle, key) in publish { + let _ = host.publish_uploaded_slot(index, handle, key); + } + } + }); + drop(keep); + }; + let (number, _) = gpu.execute_gated(recorded.then_some(bake_list), Box::new(show)); + if recorded { + if number == 0 { + bake_list.reset(); + } else { + flown = Some(number); } } - }); - drop(keep); - }; - let (number, _) = gpu.execute_gated(recorded.then_some(bake_list), Box::new(show)); - if recorded { - if number == 0 { + } else if recorded { + bake_list.close(); + gpu.execute_sync_internal(bake_list); bake_list.reset(); - } else { - flown = Some(number); + } else if !sync.publish.is_empty() { + crate::host::settle_for_fence(); + } + for (index, handle, key) in sync.publish { + let _ = host.publish_uploaded_slot(index, handle, key); } + host.texture_views_remade(); + host.texture_slots_flip(); + drop(sync.keep); + if run_pass && served && exact { + BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Release); + } + if let Some(number) = flown { + bake_flown(bake_slot, number); + } + // The bake's draw picks by index what this pass, or one on another thread, uploaded: + // its list waits behind a gate not opened yet (none in the synchronous form). + list.wait_gate(crate::host::gate_pending()); + BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); + return; } - } else if recorded { - bake_list.close(); - gpu.execute_sync_internal(bake_list); - bake_list.reset(); - } else if !sync.publish.is_empty() { - crate::host::settle_for_fence(); - } - for (index, handle, key) in sync.publish { - let _ = host.publish_uploaded_slot(index, handle, key); - } - host.texture_views_remade(); - host.texture_slots_flip(); - drop(sync.keep); - if run_pass && served && exact { - BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed); - } - if let Some(number) = flown { - bake_flown(&mut bake_slot, number); - } - // The bake's draw picks by index what this pass, or one on another thread, uploaded: - // its list waits behind a gate not opened yet (none in the synchronous form). - list.wait_gate(crate::host::gate_pending()); - BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); - return; - } - // Fallback when no host GPU list can be created (e.g. headless tests). - crate::texture::BAKING.set(exact); - self.flush_for_bake(list, host, None); - crate::texture::BAKING.set(false); - let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); - if left == 0 { - return; - } - if !first && exact { - let (writes, noted) = host.texture_news(); - if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 { - return; - } - } - EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed); - PASS_BUDGET.set(Some((left, 2 << 30, true))); - crate::texture::BAKING.set(exact); - let _ = self.heap_textures(list, heap, host, None); - crate::texture::BAKING.set(false); - PASS_BUDGET.set(None); - BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); + // Fallback when no host GPU list can be created (e.g. headless tests). + crate::texture::BAKING.set(exact); + self.flush_for_bake(list, host, None, before); + crate::texture::BAKING.set(false); + let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); + if left == 0 { + return; + } + if !first && exact { + let (writes, noted) = host.texture_news(); + if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 { + return; + } + } + EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed); + PASS_BUDGET.set(Some((left, 2 << 30, true))); + crate::texture::BAKING.set(exact); + let _ = self.heap_textures(list, heap, host, None); + crate::texture::BAKING.set(false); + PASS_BUDGET.set(None); + BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); + }, + ); return; } let budget = if first && early_ms > 0 { @@ -6703,7 +7429,7 @@ impl State { // host copies are kept alive by the list, and the signature is cached. unsafe { list.list.ExecuteIndirect( - &signature, + &*signature, max, &bounded, at, @@ -6721,7 +7447,7 @@ impl State { { // SAFETY: an open list with everything set; a buffer of zeros larger than any record, kept // for good, read through implicit promotion from the common state. - unsafe { list.list.ExecuteIndirect(&signature, 1, &zero.0, 0, None::<&ID3D12Resource>, 0) }; + unsafe { list.list.ExecuteIndirect(&*signature, 1, &zero.0, 0, None::<&ID3D12Resource>, 0) }; } if kind == MESH { self.mesh_scissor(list, false, mode); @@ -7158,16 +7884,52 @@ mod cache_tests { } } +/// A host command signature an indirect execution runs with: one made for +/// the process's life and lent ([`sigtable`]), or a reference of its own +/// (`LEONIDA_SIG_TABLE=0`, or a kind or stride past the table). +enum HostSig { + Kept(&'static ID3D12CommandSignature), + Own(ID3D12CommandSignature), +} + +impl std::ops::Deref for HostSig { + type Target = ID3D12CommandSignature; + fn deref(&self) -> &ID3D12CommandSignature { + match self { + HostSig::Kept(s) => s, + HostSig::Own(s) => s, + } + } +} + /// The host command signature for one argument of `kind` with records /// `stride` bytes apart (no root arguments, so no root signature), made -/// once. -fn host_signature(kind: u32, stride: u32) -> Option { - static MADE: std::sync::Mutex> = - std::sync::Mutex::new(Vec::new()); - let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); - if let Some((_, s)) = made.iter().find(|(k, _)| *k == (kind, stride)) { - return Some(s.clone()); +/// once. Lent out of a [`sigtable::SigTable`], with no lock taken and no +/// reference of its own (`LEONIDA_SIG_TABLE=0`: a reference out of one list +/// under one lock, as before; read on each call, so `LEONIDA_AB` turns it). +fn host_signature(kind: u32, stride: u32) -> Option { + if crate::toggled!("LEONIDA_SIG_TABLE") + && let Some(kept) = kept_host_signature(kind, stride) + { + return kept.map(HostSig::Kept); } + listed_host_signature(kind, stride).map(HostSig::Own) +} + +/// [`host_signature`] out of the table; `None` past it. +fn kept_host_signature(kind: u32, stride: u32) -> Option> { + static TABLE: sigtable::SigTable = sigtable::SigTable::new(); + TABLE.get_or_make(kind, stride, || make_host_signature(kind, stride)) +} + +/// [`host_signature`] out of the list there was before the table. +fn listed_host_signature(kind: u32, stride: u32) -> Option { + static MADE: sigtable::Listed<(u32, u32), ID3D12CommandSignature> = sigtable::Listed::new(); + MADE.get_or_make((kind, stride), || make_host_signature(kind, stride), Clone::clone) +} + +/// Makes [`host_signature`]; `None` where the host refuses it. +fn make_host_signature(kind: u32, stride: u32) -> Option { let argument = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32), ..Default::default() @@ -7191,19 +7953,21 @@ fn host_signature(kind: u32, stride: u32) -> Option { once!(error = %e, kind, stride, "host command signature refused"); return None; } - let signature = signature?; - made.push(((kind, stride), signature.clone())); - Some(signature) + signature } /// The host command signature of an indirect dispatch of a program run `pack.k` console groups /// to a host group: the three dwords of the console's grid set as root constants (`pack.words`, /// consecutive in the program's user data: the translator makes them so), then the dispatch, /// [`crate::indirect::PACKED`] bytes a record. One for each root signature and place of the -/// words, made once; `None` where they are not consecutive or the host refuses it. -fn pack_signature(root: &ID3D12RootSignature, pack: PackWords) -> Option { - static MADE: std::sync::Mutex> = - std::sync::Mutex::new(Vec::new()); +/// words, made once; `None` where they are not consecutive or the host refuses it. Lent out of +/// a [`sigtable::SigMap`], under its shared lock only and made outside it (`LEONIDA_SIG_TABLE=0`: +/// a reference out of one list under one lock, as before). +fn pack_signature(root: &ID3D12RootSignature, pack: PackWords) -> Option { + /// The root signature is kept with the command signature, made or (in the map) refused: the + /// key is its address. + type Made = (ID3D12RootSignature, ID3D12CommandSignature); + type Kept = (ID3D12RootSignature, Option); let [x, y, all] = pack.words; if y != x + 1 || all != y + 1 { once!(?pack, "the words of a packed program's console grid are not consecutive: its indirect dispatches are dropped"); @@ -7211,10 +7975,19 @@ fn pack_signature(root: &ID3D12RootSignature, pack: PackWords) -> Option = sigtable::SigMap::new(); + return KEPT + .get_or_make_pinned(key, || root.clone(), || make_pack_signature(root, pack, x)) + .map(HostSig::Kept); } + static MADE: sigtable::Listed<(usize, u32, u32), Made> = sigtable::Listed::new(); + let make = || Some((root.clone(), make_pack_signature(root, pack, x)?)); + MADE.get_or_make(key, make, |(_, s)| s.clone()).map(HostSig::Own) +} + +/// Makes [`pack_signature`] (its grid's first word set at `x`); `None` where the host refuses it. +fn make_pack_signature(root: &ID3D12RootSignature, pack: PackWords, x: u32) -> Option { let arguments = [ D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, @@ -7242,10 +8015,7 @@ fn pack_signature(root: &ID3D12RootSignature, pack: PackWords) -> Option case.0 = true, + 6 => case.6 = true, + 7 => case.7 = true, + _ => case.8 = true, + } + assert!(!skip(case), "{i}: the rest of the flush, or another's pass, is still due"); + } + } + + /// A bake that holds the lock takes the heap's flips pending in lists + /// before it shows them, and runs its pass with what milliseconds were + /// left when it began: until it is done no draw passes the lock, even + /// with no milliseconds left (none looks for news then), and once it is + /// the draw does. + #[test] + fn a_bake_does_not_pass_one_at_work_under_the_lock() { + let Some(gpu) = crate::host::host() else { return }; + let heap = crate::descriptor::host::HostHeap::new(false, 4).unwrap(); + let list = gpu.new_list().unwrap(); + heap.texture_slot_flip(&list, 0, 0, 1); + assert!(!bake_may_pass(false, true, 0, &heap), "a flip of the heap pending in a list"); + { + let _busy = BakeBusy::raise(); + assert_eq!(heap.take_pending_list_flips().len(), 1); + assert!(!heap.needs_gpu_settle_for_bake()); + assert!(!bake_may_pass(false, true, 0, &heap), "the holder took the flip and has not shown it"); + } + { + let _busy = BakeBusy::raise(); + assert!(!bake_may_pass(false, true, 0, &heap), "the holder's pass is under way"); + } + assert!(bake_may_pass(false, true, 0, &heap), "the holder is done"); + } + + /// Holds `lock` on another thread for 400 ms and runs `then` on this one + /// once it is held; how long `then` took. + fn with_lock_held(lock: &std::sync::Mutex, then: impl FnOnce()) -> Duration { + let (held, hold) = std::sync::mpsc::channel(); + std::thread::scope(|s| { + s.spawn(move || { + let guard = lock.lock().unwrap(); + held.send(()).unwrap(); + std::thread::sleep(Duration::from_millis(400)); + drop(guard); + }); + hold.recv().unwrap(); + let began = Instant::now(); + then(); + began.elapsed() + }) + } + + /// With the switch, a bake draw that needs nothing goes on while + /// another thread holds the lock (as one waiting for the card does): + /// the wait for the card and the look come before the lock. + #[test] + fn a_bake_with_nothing_to_do_does_not_wait_for_the_lock() { + let lock = std::sync::Mutex::new(0u32); + let mut passed = false; + let took = with_lock_held(&lock, || { + passed = bake_gate(true, &lock, || 7u32, |&found| found == 7, |_, _| panic!("the lock was taken")); + }); + assert!(passed); + assert!(took < Duration::from_millis(100), "it waited {took:?} for the lock"); + } + + /// Without the switch the lock comes first, as before: the draw waits + /// for the holder, and neither the settle before it nor the look runs. + #[test] + fn without_the_switch_a_bake_takes_the_lock_first() { + let lock = std::sync::Mutex::new(0u32); + let mut passed = true; + let took = with_lock_held(&lock, || { + passed = bake_gate( + false, + &lock, + || -> u32 { panic!("settled outside the lock") }, + |_| panic!("looked outside the lock"), + |held, found| { + assert_eq!(found, 0); + *held += 1; + }, + ); + }); + assert!(!passed); + assert!(took >= Duration::from_millis(200), "it took the lock after {took:?}"); + assert_eq!(*lock.lock().unwrap(), 1); + } + + /// With the switch and something left to do, the flush runs under the + /// lock after the settle and the look, with what the settle found. + #[test] + fn a_bake_with_work_left_runs_it_under_the_lock() { + let lock = std::sync::Mutex::new(0u32); + let order = std::cell::RefCell::new(Vec::new()); + let passed = bake_gate( + true, + &lock, + || { + assert!(lock.try_lock().is_ok(), "the settle runs without the lock"); + order.borrow_mut().push("settle"); + 3u32 + }, + |&found| { + order.borrow_mut().push("look"); + found == 0 + }, + |held, found| { + assert!(lock.try_lock().is_err(), "the flush runs under the lock"); + order.borrow_mut().push("flush"); + *held = found; + }, + ); + assert!(!passed); + assert_eq!(*order.borrow(), ["settle", "look", "flush"]); + assert_eq!(*lock.lock().unwrap(), 3); + } +} + #[cfg(test)] mod wait_tests { use super::*; @@ -8127,3 +9076,235 @@ mod wait_tests { assert!(!state.waited); } } + +#[cfg(test)] +mod look_ahead_tests { + use super::kept_from_ahead; + + thread_local! { + /// Whether a look ahead on this thread panics before it looks + /// (`super::look_ahead`). + pub(super) static PANIC: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + /// A heap of 64 slots with buffer views of 512 bytes each in slots 0 to + /// 17, over private title memory, and the first pass over them done; + /// `test` gets the heap, its host heap, a writer of a slot's view (of + /// the memory at an offset) and what a slot shows to the pass. + #[cfg(windows)] + fn with_passed_heap( + test: impl FnOnce( + &crate::descriptor::Heap, + &crate::descriptor::host::HostHeap, + &dyn Fn(u32, usize), + &dyn Fn(u32) -> Option<(usize, u64, u64)>, + ), + ) { + use crate::object::This; + if crate::host::host().is_none() || !super::heap_spread() { + return; // no host GPU, or the pass looks at all slots at once + } + let (h, Some(host)) = crate::descriptor::test_view_heap(64) else { + return; + }; + let heap = crate::descriptor::heap(h); + let (base, start) = crate::shadow::in_place_tests::private(1 << 20, 1 << 16); + let write = |slot: u32, at: usize| { + let resource = [1, 0, 0, 0, 512, 0, 1, 0x1_0001, 0, 1, 0, 1, 0, 0]; + let mut words = [0u32; 16]; + words[..10].copy_from_slice(&[10, 1, 5768, 0, 0, 0, 64, 0, 0, 0]); + words[10] = (start + at) as u32; + words[11] = ((start + at) as u64 >> 32) as u32; + crate::descriptor::create_placed_srv(std::ptr::null(), &resource, &words, heap.handle(slot).expect("a slot of the heap")); + }; + let shows = |slot: u32| { + let kept = host.buffer_sweep.lock().unwrap_or_else(|e| e.into_inner()); + let super::SweepState::Legacy(ranges) = &kept.ranges else { + panic!("the tests read the spans kept by slot (LEONIDA_INDEX_HEAP_SPANS off)"); + }; + ranges.ranges.0.get(slot as usize).cloned().flatten().map(|(copy, from, to)| (std::sync::Arc::as_ptr(©) as usize, from, to)) + }; + for slot in 0..18 { + write(slot, slot as usize * 512); + } + drop(super::heap_buffer_pass(heap, host, crate::frame::current())); + test(heap, host, &write, &shows); + crate::object::slot:: u32>(h, 0x10)(h); + crate::shadow::in_place_tests::give_back(base); + } + + /// What a pass of its own finds for slot `slot` of `heap`: the copy and + /// range of its view; its host slot is made from the record it holds. + #[cfg(windows)] + fn found(heap: &crate::descriptor::Heap, host: &crate::descriptor::host::HostHeap, slot: u32) -> Option<(usize, u64, u64)> { + let handle = heap.handle(slot).expect("a slot of the heap"); + let view = crate::descriptor::view(handle)?; + let found = crate::descriptor::host::buffer_copy(&view).map(|(copy, at, len)| (std::sync::Arc::as_ptr(©) as usize, at, at + len)); + if found.is_some() { + let [_, i, generation] = crate::descriptor::record_at(handle).expect("a record"); + assert_eq!(host.made_key(slot), Some(u64::from(generation) << 32 | u64::from(i)), "slot {slot} is made from its record"); + } + found + } + + /// A slot of the coming pass's part that showed nothing at the look + /// ahead, a draw's table having it at the look's frame, is looked at + /// again by the pass, at whose frame no table has it any more: it shows + /// its buffer after the pass, as after a pass of its own. + #[cfg(windows)] + #[test] + fn a_slot_that_showed_nothing_at_the_look_is_looked_at_by_the_pass() { + with_passed_heap(|heap, host, _, shows| { + // Slot 17 is of the second pass's part, as slot 1 is. + host.slot_tabled(17); + let frame = crate::frame::current(); + assert!(host.copied_tabled(17, frame)); + assert_eq!(super::look_ahead(heap, host, frame), 2); + assert_eq!(shows(17), None, "a draw's table had it at the look"); + // The pass, past the frames a table holds a slot. + let later = frame + 9; + assert!(!host.copied_tabled(17, later)); + drop(super::heap_buffer_pass(heap, host, later)); + assert_eq!(host.buffer_sweep.lock().unwrap().looked, 1, "the pass looked at slot 17 again"); + for slot in 0..18u32 { + assert_eq!(shows(slot), found(heap, host, slot), "slot {slot}"); + } + assert!(shows(17).is_some()); + }); + } + + /// A look ahead that panics gives the pass back what it took: the slots + /// written since the last pass, and the pass's part, which the pass then + /// looks at itself; each slot shows what a pass of its own finds. + #[cfg(windows)] + #[test] + fn a_look_ahead_that_panics_leaves_its_slots_to_the_pass() { + with_passed_heap(|heap, host, write, shows| { + let frame = crate::frame::current(); + for slot in 2..5 { + write(slot, 0x10000 + slot as usize * 512); + } + PANIC.with(|p| p.set(true)); + let looked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::look_ahead(heap, host, frame))); + PANIC.with(|p| p.set(false)); + assert!(looked.is_err(), "the look panicked"); + drop(super::heap_buffer_pass(heap, host, frame)); + for slot in 0..18u32 { + assert_eq!(shows(slot), found(heap, host, slot), "slot {slot}"); + } + assert!(shows(1).is_some() && shows(17).is_some(), "the pass looked at its part"); + }); + } + + /// The pass keeps what a look ahead of it found only while the slot holds + /// the record that was seen, is made from it, is no draw's table's and + /// names a view that is alive; anything else is looked at again. + #[test] + fn a_look_ahead_is_kept_only_while_the_slot_shows_what_it_saw() { + let seen = [0x4549_5676, 7, 3]; + let key = 3u64 << 32 | 7; + assert!(kept_from_ahead(seen, Some(seen), Some(key), false, true)); + // Written since, in place or by a call: another record, or none. + assert!(!kept_from_ahead(seen, Some([seen[0], 7, 4]), Some(key), false, true)); + assert!(!kept_from_ahead(seen, Some([seen[0], 8, 3]), Some(key), false, true)); + assert!(!kept_from_ahead(seen, None, Some(key), false, true)); + // Its host slot let go of, made null, or made from another record. + assert!(!kept_from_ahead(seen, Some(seen), Some(0), false, true)); + assert!(!kept_from_ahead(seen, Some(seen), Some(4u64 << 32 | 7), false, true)); + assert!(!kept_from_ahead(seen, Some(seen), None, false, true)); + // A draw's table has it now; the view's resource was released. + assert!(!kept_from_ahead(seen, Some(seen), Some(key), true, true)); + assert!(!kept_from_ahead(seen, Some(seen), Some(key), false, false)); + } + + /// With a look ahead of it (`LEONIDA_HEAP_PRELOOK`), the pass over the + /// heap's buffer views looks only at the slots written since the look, + /// at those whose record changed in place without a call, and at those + /// a draw's table took since; and what it keeps is what a pass of its + /// own would find: each slot's view's copy and range, its host slot made + /// from the record it holds now. + #[cfg(windows)] + #[test] + fn the_pass_looks_only_at_slots_written_since_the_look_ahead() { + use crate::object::This; + let Some(_device) = crate::host::host() else { + return; // no host GPU + }; + if !super::heap_spread() { + return; + } + const SLOTS: u32 = 64; + let (h, Some(host)) = crate::descriptor::test_view_heap(SLOTS) else { + return; + }; + let heap = crate::descriptor::heap(h); + let (base, start) = crate::shadow::in_place_tests::private(1 << 20, 1 << 16); + let handle = |slot: u32| heap.handle(slot).expect("a slot of the heap"); + // A buffer view of 512 bytes of the memory at `at` in `slot`, by the + // title's call. + let write = |slot: u32, at: usize| { + let resource = [1, 0, 0, 0, 512, 0, 1, 0x1_0001, 0, 1, 0, 1, 0, 0]; + let mut words = [0u32; 16]; + words[..10].copy_from_slice(&[10, 1, 5768, 0, 0, 0, 64, 0, 0, 0]); + words[10] = (start + at) as u32; + words[11] = ((start + at) as u64 >> 32) as u32; + crate::descriptor::create_placed_srv(std::ptr::null(), &resource, &words, handle(slot)); + }; + // The test's frame, in which the tables below take their slots too: + // tests beside it begin frames of the process meanwhile. + let frame = crate::frame::current(); + // (Slot 17 is of the second pass's part, as slot 1 is.) + for slot in 0..18 { + write(slot, slot as usize * 512); + } + // The first pass looks at all of them. + drop(super::heap_buffer_pass(heap, host, frame)); + let shows = |slot: u32| { + let kept = host.buffer_sweep.lock().unwrap(); + let super::SweepState::Legacy(ranges) = &kept.ranges else { + panic!("the tests read the spans kept by slot (LEONIDA_INDEX_HEAP_SPANS off)"); + }; + ranges.ranges.0.get(slot as usize).cloned().flatten().map(|(copy, from, to)| (std::sync::Arc::as_ptr(©) as usize, from, to)) + }; + assert_eq!(host.buffer_sweep.lock().unwrap().looked, 18); + assert!((0..18).all(|slot| shows(slot).is_some()), "every slot shows a copy of the memory"); + // The title writes eight of them again; a draw's table takes one. + for slot in 0..8 { + write(slot, 0x10000 + slot as usize * 512); + } + host.slot_tabled_in(7, frame); + // The look ahead: the written slots but the table's, and the coming + // pass's part of the others (slot 17; slot 1 is written). + assert_eq!(super::look_ahead(heap, host, frame), 8); + // Then, before the pass: a call writes slot 2 again, slot 3 gets + // slot 9's record as bytes, a draw's table takes slot 4, and a call + // writes slot 10, which the look did not see. + write(2, 0x20000); + // SAFETY: two slots of the test's heap. + unsafe { (handle(3) as *mut [u32; 3]).write_unaligned((handle(9) as *const [u32; 3]).read_unaligned()) }; + host.slot_tabled_in(4, frame); + write(10, 0x30000); + drop(super::heap_buffer_pass(heap, host, frame)); + // Slots 2 and 10 (written), 3 (another record), 4 and 7 (tables'); + // without the look: the nine written and the part's two. + assert_eq!(host.buffer_sweep.lock().unwrap().looked, 5, "the pass looked only at what changed since the look"); + // What a pass of its own finds for each slot. + for slot in 0..18u32 { + let found = if slot == 4 || slot == 7 { + None + } else { + let view = crate::descriptor::view(handle(slot)).expect("a view"); + crate::descriptor::host::buffer_copy(&view).map(|(copy, at, len)| (std::sync::Arc::as_ptr(©) as usize, at, at + len)) + }; + assert_eq!(shows(slot), found, "slot {slot}"); + if found.is_some() { + let [_, i, generation] = crate::descriptor::record_at(handle(slot)).expect("a record"); + assert_eq!(host.made_key(slot), Some(u64::from(generation) << 32 | u64::from(i)), "slot {slot} is made from its record"); + } + } + assert_eq!(shows(3).map(|s| s.1), Some((start + 9 * 512) as u64), "slot 3 shows slot 9's view"); + assert_eq!(shows(2).map(|s| s.1), Some((start + 0x20000) as u64)); + crate::object::slot:: u32>(h, 0x10)(h); + crate::shadow::in_place_tests::give_back(base); + } +} diff --git a/d3d12/crates/leonida-gpu/src/draw/sigtable.rs b/d3d12/crates/leonida-gpu/src/draw/sigtable.rs new file mode 100644 index 0000000000..7d3884e20f --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/draw/sigtable.rs @@ -0,0 +1,449 @@ +//! The host command signatures of indirect executions, found without a lock +//! (`LEONIDA_SIG_TABLE=0`: in one list under one lock, as before). +//! +//! Why: the title runs about 13,000 indirect executions a frame, on up to +//! eight recording threads at once. Each looked its host signature up in one +//! list of all that were made, under one lock held while the list was searched +//! (and while a signature was made), and took a reference of its own to the one +//! found (`AddRef` on an object every thread shares, `Release` after the +//! call). The threads queued on that lock: 0.1 to 4.8 ms of waiting a frame in +//! three scenes, and once six of the eight stood still for 3 ms together +//! because the thread holding it had been taken off its core, then 1 ms more +//! as it passed from one to the next. +//! +//! A signature of one argument depends on nothing but the argument's kind and +//! the records' stride, and lives as long as the process (as before: the list +//! kept every one it made). [`SigTable`] has one slot for each such pair, filled +//! once, and lends the signature in it: finding one is two indexes and a load, +//! with nothing written that another thread reads, and a slot being filled +//! holds up only those that want that slot. A kind or stride past the table +//! goes to the list as before ([`Listed`]). A packed dispatch's signature also +//! depends on its root signature: those are few and are kept in [`SigMap`], +//! looked through under a shared lock and made outside it. +//! +//! A refused signature is kept as refused in the table and the map (the list +//! asks the device again each time): what the device refuses for a kind and a +//! stride, or for a root signature, it refuses every time. The map keeps the +//! root signature in the slot whether its signature was made or refused, so +//! the address in the key stays that root's. + +use std::sync::{Mutex, OnceLock, RwLock}; + +use windows::Win32::Graphics::Direct3D12::{ + D3D12_INDIRECT_ARGUMENT_TYPE, D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH, D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED, +}; + +/// Strides a kind has slots for: records 0 to 124 bytes apart, in steps of +/// four bytes (a record is of dwords). The title's records are 12 to 20 bytes. +const STRIDES: usize = 32; + +/// One signature (`T`) for each kind of argument a list executes indirectly +/// (draw, indexed draw, dispatch, mesh dispatch) and stride below +/// `4 * STRIDES` bytes, each made at most once and kept as long as the table. +pub(crate) struct SigTable { + slots: [[OnceLock>; STRIDES]; 4], +} + +impl SigTable { + pub(crate) const fn new() -> Self { + Self { + slots: [const { [const { OnceLock::new() }; STRIDES] }; 4], + } + } + + /// The slot of an argument of `kind` (a `D3D12_INDIRECT_ARGUMENT_TYPE`) + /// with records `stride` bytes apart; `None` past the table. + fn slot(&self, kind: u32, stride: u32) -> Option<&OnceLock>> { + let row = match D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32) { + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW => 0, + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED => 1, + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH => 2, + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH => 3, + _ => return None, + }; + if !stride.is_multiple_of(4) { + return None; + } + self.slots[row].get(stride as usize / 4) + } + + /// The signature of `kind` and `stride`, made by `make` the first time it + /// is asked for (`None` inside: refused); `None` where the pair is past + /// the table and the caller has to keep it itself. Threads that ask for + /// the same pair while it is made wait for that one `make`; others do not. + pub(crate) fn get_or_make( + &self, + kind: u32, + stride: u32, + make: impl FnOnce() -> Option, + ) -> Option> { + Some(self.slot(kind, stride)?.get_or_init(make).as_ref()) + } +} + +/// Signatures (`T`) by a key of a few words (`K`), each made at most once +/// and kept for the process's life: a list of shared slots, looked through +/// under a shared lock and added to under the exclusive one, which is never +/// held while a signature is made. For keys that are few: one entry each. +pub(crate) struct SigMap { + made: RwLock>)>>, +} + +impl SigMap { + pub(crate) const fn new() -> Self { + Self { + made: RwLock::new(Vec::new()), + } + } + + /// The slot of `key`, added (empty) the first time. + fn slot(&self, key: K) -> &'static OnceLock> { + let find = |made: &[(K, &'static OnceLock>)]| { + made.iter().find(|(k, _)| *k == key).map(|(_, s)| *s) + }; + if let Some(slot) = find(&self.made.read().unwrap_or_else(|e| e.into_inner())) { + return slot; + } + let mut made = self.made.write().unwrap_or_else(|e| e.into_inner()); + if let Some(slot) = find(&made) { + return slot; // added meanwhile + } + // Kept for the process's life, as the signature in it; one a key. + let slot: &'static OnceLock> = Box::leak(Box::new(OnceLock::new())); + made.push((key, slot)); + slot + } + + /// The signature of `key`, made by `make` the first time it is asked for; + /// `None` where it was refused. As [`SigTable::get_or_make`], only threads + /// that ask for the same key while it is made wait for it. + pub(crate) fn get_or_make( + &self, + key: K, + make: impl FnOnce() -> Option, + ) -> Option<&'static T> { + self.slot(key).get_or_init(make).as_ref() + } +} + +impl SigMap)> { + /// [`SigMap::get_or_make`] for a key that holds an owner's address (a root + /// signature's): `owner` (a reference to it) is kept in the slot with what + /// `make` answered, made or refused, so the address cannot be freed and + /// handed to another owner the slot's answer does not hold for. A refusal + /// kept with no owner would be one a new owner at that address inherits. + pub(crate) fn get_or_make_pinned( + &self, + key: K, + owner: impl FnOnce() -> O, + make: impl FnOnce() -> Option, + ) -> Option<&'static T> { + self.get_or_make(key, || Some((owner(), make()))) + .and_then(|(_, made)| made.as_ref()) + } +} + +/// The signatures as they were kept before [`SigTable`] and [`SigMap`] (and +/// still are with `LEONIDA_SIG_TABLE=0`, or past the table): one list of +/// what was made by its key, under one lock held while the list is searched +/// and while one is made; a refusal is not kept, so the next asks again. +pub(crate) struct Listed { + made: Mutex>, +} + +impl Listed { + pub(crate) const fn new() -> Self { + Self { + made: Mutex::new(Vec::new()), + } + } + + /// What `out` takes from the entry of `key` (a reference of the caller's + /// own), made by `make` and added where there is none; `None` if refused. + pub(crate) fn get_or_make( + &self, + key: K, + make: impl FnOnce() -> Option, + out: impl Fn(&T) -> R, + ) -> Option { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, s)) = made.iter().find(|(k, _)| *k == key) { + return Some(out(s)); + } + let s = make()?; + let r = out(&s); + made.push((key, s)); + Some(r) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::mpsc; + use std::time::Duration; + + const DRAW: u32 = 0; + const INDEXED: u32 = 1; + const DISPATCH: u32 = 2; + const MESH: u32 = 10; + + /// A lookup of `key` that makes it with the closure given where it is not + /// made yet. + type Lookup<'a> = &'a (dyn Fn(u32, Box Option + Send>) + Sync); + + /// Whether, while one thread makes key 2 (and is held there), another + /// that looks up key 1, made before, waits for it: given up on after + /// 100 ms. + fn waits_for_another_make(lookup: Lookup) -> bool { + lookup(1, Box::new(|| Some(10))); + let (entered_tx, entered) = mpsc::channel(); + let (go_tx, go) = mpsc::channel::<()>(); + let (done_tx, done) = mpsc::channel(); + std::thread::scope(|s| { + s.spawn(move || { + lookup( + 2, + Box::new(move || { + entered_tx.send(()).unwrap(); + go.recv().ok(); + Some(20) + }), + ) + }); + entered.recv().unwrap(); + s.spawn(move || { + lookup(1, Box::new(|| Some(11))); + done_tx.send(()).ok(); + }); + let waited = done.recv_timeout(Duration::from_millis(100)).is_err(); + go_tx.send(()).unwrap(); + waited + }) + } + + /// Eight threads asking 100,000 times each for a few kinds and strides, + /// all at once from the start and with a make that takes a while (as the + /// device's does): each is made once, and every thread is lent the same one. + #[test] + fn a_signature_is_made_once_for_each_kind_and_stride() { + let table = SigTable::::new(); + let keys = [ + (DRAW, 16), + (INDEXED, 20), + (DISPATCH, 12), + (MESH, 12), + (DRAW, 32), + ]; + let makes: [AtomicUsize; 5] = Default::default(); + let start = std::sync::Barrier::new(8); + let seen: Vec> = std::thread::scope(|s| { + let threads: Vec<_> = (0..8) + .map(|t| { + let (table, makes, start) = (&table, &makes, &start); + s.spawn(move || { + let mut seen = vec![0; keys.len()]; + start.wait(); + for n in 0..100_000 { + let i = (n + t) % keys.len(); + let (kind, stride) = keys[i]; + let made = table.get_or_make(kind, stride, || { + makes[i].fetch_add(1, Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(5)); + Some(i as u32) + }); + let made = made.expect("inside the table").expect("made"); + assert_eq!(*made, i as u32); + let at = made as *const u32 as usize; + assert!( + seen[i] == 0 || seen[i] == at, + "two signatures for one kind and stride" + ); + seen[i] = at; + } + seen + }) + }) + .collect(); + threads.into_iter().map(|t| t.join().unwrap()).collect() + }); + for (i, made) in makes.iter().enumerate() { + assert_eq!( + made.load(Ordering::Relaxed), + 1, + "key {i} made more than once" + ); + } + assert!( + seen.iter().all(|s| *s == seen[0]), + "threads were lent different signatures" + ); + } + + #[test] + fn finding_a_made_signature_does_not_wait_for_another_being_made() { + let table = SigTable::::new(); + let lookup = |key: u32, make: Box Option + Send>| { + table.get_or_make(DRAW, 4 * key, make); + }; + assert!(!waits_for_another_make(&lookup)); + } + + /// What was wrong: with the list, a thread wanting a signature made long + /// ago waits while another thread makes a new one (or is off its core + /// with the lock held). + #[test] + fn the_listed_signatures_made_a_finding_wait_for_another_being_made() { + let listed = Listed::::new(); + let lookup = |key: u32, make: Box Option + Send>| { + listed.get_or_make(key, make, |s| *s); + }; + assert!(waits_for_another_make(&lookup)); + } + + #[test] + fn kinds_and_strides_past_the_table_are_left_to_the_caller() { + let table = SigTable::::new(); + let made = AtomicUsize::new(0); + let make = || { + made.fetch_add(1, Ordering::Relaxed); + Some(1) + }; + assert!( + table.get_or_make(DRAW, 6, make).is_none(), + "a stride that is not of dwords" + ); + assert!(table.get_or_make(DRAW, 128, make).is_none()); + assert!(table.get_or_make(INDEXED, 256, make).is_none()); + assert!( + table.get_or_make(7, 16, make).is_none(), + "a kind with root arguments" + ); + assert!(table.get_or_make(u32::MAX, 16, make).is_none()); + assert_eq!(made.load(Ordering::Relaxed), 0); + assert_eq!(table.get_or_make(MESH, 124, make), Some(Some(&1))); + assert_eq!( + table.get_or_make(DISPATCH, 0, || None), + Some(None), + "a refusal is kept" + ); + assert_eq!(table.get_or_make(DISPATCH, 0, make), Some(None)); + assert_eq!(made.load(Ordering::Relaxed), 1); + } + + #[test] + fn a_packed_signature_is_made_once_for_each_key_and_lent_to_every_thread() { + static MAP: SigMap<(usize, u32, u32), u32> = SigMap::new(); + let makes: [AtomicUsize; 3] = Default::default(); + let start = std::sync::Barrier::new(8); + let seen: Vec<[usize; 3]> = std::thread::scope(|s| { + let threads: Vec<_> = (0..8) + .map(|t| { + let (makes, start) = (&makes, &start); + s.spawn(move || { + let mut seen = [0; 3]; + start.wait(); + for n in 0..20_000 { + let i = (n + t) % 3; + let made = MAP + .get_or_make((0x1000 * (i + 1), 1, 4), || { + makes[i].fetch_add(1, Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(5)); + Some(i as u32) + }) + .expect("made"); + seen[i] = made as *const u32 as usize; + } + seen + }) + }) + .collect(); + threads.into_iter().map(|t| t.join().unwrap()).collect() + }); + assert!(makes.iter().all(|m| m.load(Ordering::Relaxed) == 1)); + assert!(seen.iter().all(|s| *s == seen[0])); + } + + #[test] + fn finding_a_made_packed_signature_does_not_wait_for_another_being_made() { + static MAP: SigMap = SigMap::new(); + let lookup = |key: u32, make: Box Option + Send>| { + MAP.get_or_make(key, make); + }; + assert!(!waits_for_another_make(&lookup)); + } + + /// What was wrong: a refused packed signature was kept with no root + /// signature, so the root could be freed and a new one with another layout + /// made at its address would inherit the refusal (its dispatches dropped). + /// The owner of a refused key stays alive in the map; the refusal is kept. + #[test] + fn a_refused_packed_signature_keeps_its_owner() { + use std::sync::Arc; + static MAP: SigMap, Option)> = SigMap::new(); + let owner = Arc::new(7); + let kept = Arc::downgrade(&owner); + let key = Arc::as_ptr(&owner) as usize; + let made = AtomicUsize::new(0); + let refuse = || { + made.fetch_add(1, Ordering::Relaxed); + None + }; + assert_eq!(MAP.get_or_make_pinned(key, || owner.clone(), refuse), None); + drop(owner); + assert!( + kept.upgrade().is_some(), + "a refused key's owner was let go: its address can be reused" + ); + assert_eq!(MAP.get_or_make_pinned(key, || Arc::new(8), refuse), None); + assert_eq!(made.load(Ordering::Relaxed), 1, "the refusal is kept"); + let owner = Arc::new(9); + let key = Arc::as_ptr(&owner) as usize; + let lent = MAP.get_or_make_pinned(key, || owner.clone(), || Some(90)); + assert_eq!(lent, Some(&90)); + assert_eq!(Arc::strong_count(&owner), 2, "a made key keeps its owner too"); + } + + /// With a host GPU: the host signature of a kind and stride is one object + /// on every thread, through the table and through the list alike. + #[test] + fn a_host_signature_is_one_object_on_every_thread() { + use windows::core::Interface; + if crate::host::host().is_none() { + return; // no host GPU + } + let raw = |kept: bool| { + std::thread::scope(|s| { + let threads: Vec<_> = (0..8) + .map(|_| { + s.spawn(move || { + if kept { + let signature = + super::super::kept_host_signature(DRAW, 16).flatten(); + signature.expect("made").as_raw() as usize + } else { + super::super::listed_host_signature(DRAW, 16) + .expect("made") + .as_raw() as usize + } + }) + }) + .collect(); + threads + .into_iter() + .map(|t| t.join().unwrap()) + .collect::>() + }) + }; + for kept in [true, false] { + let raw = raw(kept); + assert!( + raw.iter().all(|r| *r == raw[0] && *r != 0), + "kept {kept}: {raw:x?}" + ); + } + } +} diff --git a/d3d12/crates/leonida-gpu/src/fence.rs b/d3d12/crates/leonida-gpu/src/fence.rs index 3ca3d41558..20eaf968ca 100644 --- a/d3d12/crates/leonida-gpu/src/fence.rs +++ b/d3d12/crates/leonida-gpu/src/fence.rs @@ -106,12 +106,12 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c if event.is_null() { // With submissions sent to the card and not waited for // (`crate::host::late`) the signal may be behind them: they are - // settled, which sets it. + // settled, which sets it (with the relay, until it is set). #[cfg(windows)] if crate::host::late() { drop(waiters); crate::queue::before_sync(); - crate::host::settle_for_fence(); + crate::host::settle_for_fence_value(this, value); if fence.value.load(Ordering::Acquire) >= value { return S_OK; } @@ -188,6 +188,12 @@ extern "system" fn creation_flags(this: This) -> u32 { extern "system" fn gpu_address(this: This) -> u64 { (&raw const fence(this).value) as u64 } +/// [`gpu_address`] of the fence at `this`, from the pointer alone: nothing is +/// read, so it may be asked of a fence the title has let go of (a signal in +/// `crate::host`'s line keeps only the address). +pub(crate) fn value_at(this: usize) -> usize { + this + std::mem::offset_of!(Fence, value) +} /// IUnknown 3, object 4, device child 1, fence 3, fence 1 (2, a console /// one among them). @@ -235,6 +241,7 @@ mod tests { assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL); // The title reads the value at the fence's address. let at = slot:: u64>(f, 0x60)(f); + assert_eq!(value_at(f as usize), at as usize); // SAFETY: the fence's value. assert_eq!(unsafe { *(at as *const u64) }, 5); // SAFETY: ours. diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index b380d0c330..9c17ea914e 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -138,24 +138,6 @@ fn retired_push(entry: (u64, Retired)) { RETIRE_WAITS[0].fetch_add(1, Ordering::Relaxed); } -/// The retired objects' line of the frame lines, per frame ([`RETIRE_WAITS`]). -#[cfg(feature = "diagnostics")] -fn retire_waits_line(frames: f64) { - let n: Vec = RETIRE_WAITS.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect(); - if n.iter().all(|&v| v == 0.0) { - return; - } - tracing::info!( - "objects let go per frame that wait for a submission: {:.0}; their pushes that found the queue's lock taken, all threads: {:.1} waiting \ - {:.3} ms with one queue, {:.1} waiting {:.3} ms with a queue to each thread (LEONIDA_RETIRE_QUEUES)", - n[0], - n[1], - n[2] / 1e6, - n[3], - n[4] / 1e6, - ); -} - /// Submissions started and finished (waited for). static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -442,16 +424,18 @@ static RESIDENT: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic: /// device is lost. Both losses of 2026-11-25 were reads in memory given back /// seconds before (a block of textures; a list's scratch and a window of /// title memory). Kept are: empty blocks of textures ([`crate::pool`]) below -/// 85 % of the card's budget, windows of title memory and staging buffers -/// for five minutes with 12 GiB of the PC's memory free, and 1 GiB of -/// scratch chunks. +/// 85 % of the card's budget, windows of title memory and textures' staging +/// states for five minutes with 12 GiB of the PC's memory free (a staging +/// state keeps its buffer only while its texture changes often, +/// `crate::texture::release_staging`; else the buffer goes once its copy is +/// recorded), and 1 GiB of scratch chunks. pub(crate) fn keep_freed() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| std::env::var_os("LEONIDA_KEEP_FREED").is_none_or(|v| v != "0")) } -/// Effective idle timeout (in milliseconds) for system-RAM caches (staging -/// buffers, loose shadows, and the mapped pipeline library), scaled down +/// Effective idle timeout (in milliseconds) for system-RAM caches (textures' +/// staging states, loose shadows, and the mapped pipeline library), scaled down /// when free physical RAM is low. Never returns less than 2,000 ms. /// With plenty of it five minutes ([`keep_freed`]). pub(crate) fn ram_idle_ms(avail_phys: Option) -> u64 { @@ -502,7 +486,9 @@ pub(crate) fn references(object: &impl Interface) -> u32 { /// Once a second, before a submission starts: lets go of what nothing /// names any more (copies of windows of title memory, staging buffers, -/// host copies of textures the title fills). +/// host copies of textures the title fills, idle host lists nobody took, +/// memory submissions' sends came from that none took for a while). +/// Also behind flights in the air ([`sweep_no_settle`]). /// `LEONIDA_SWEEP=0` keeps everything, as before. fn sweep() { // The in-place probe and census, if asked for (`LEONIDA_INPLACE_PROBE`). @@ -524,17 +510,93 @@ fn sweep() { #[cfg(feature = "diagnostics")] crate::book::check(); crate::residency::refresh(); - if crate::residency::pressured() { + let pressured = crate::residency::pressured(); + if pressured { trim_spare_chunks(); trim_spare_backs(); + landsame::trim(); } + // The memory submissions' sends came from that none took for a while. + send::let_go_idle(host(), pressured); crate::pool::room(host().and_then(|h| h.video_memory())); + crate::list::trim_idle(); crate::pipeline::trim_library(); crate::shadow::let_go_idle(); crate::texture::let_go_idle(); crate::resource::let_go_idle(); } +/// Whether the sweep runs behind flights in the air, with no settle made +/// for it (`LEONIDA_SWEEP_NO_SETTLE=0`: every second and a half a +/// submission settles them first, as before). Read once. +/// +/// With the present sent ahead ([`late_free_present`]) something is always +/// in the air, so that settle was a full drain of the card under the +/// submission lock, the depth in the air (up to a frame) every 1.5 s; the +/// frame line counts it with the synchronous ones ("a synchronous +/// submission, a present or the sweep", [`WHY_SYNC`]), so what it cost alone +/// is not measured. Nothing the sweep lets go of needs it (read in the code, +/// 2026-11-29): what a flight still names it keeps by its references (host +/// copies of windows and textures go at a strong count of 1 and one COM +/// reference, staging states at a strong count of 1, a list in a flight +/// holding a clone of each, `HostList::keep`); what it drops goes through +/// [`retire`], which waits for every submission begun (and those queued) to +/// finish, plus [`bury_lag`]; its pools of spare memory (scratch chunks, +/// read-back buffers, sends, pool blocks) hold only what came back after +/// its submission had landed; and `crate::inplace::reap`, which lets heaps +/// over title memory go at one reference, already runs from the title's +/// frees with flights in the air. The sweep runs under the submission lock, +/// which the thread that lands flights never takes. What still wants +/// nothing in the air keeps the settle ([`sweep_wants_rest`]). +fn sweep_no_settle() -> bool { + crate::toggled!("LEONIDA_SWEEP_NO_SETTLE") +} + +/// Whether the sweep's moment needs nothing in the air, so that behind +/// flights a submission settles them for it every 1.5 s: with +/// `LEONIDA_SWEEP_NO_SETTLE=0`; for `upcheck::at_rest` (diagnostics, +/// `LEONIDA_UPCHECK`), which compares every copy with title memory and wants +/// no shader writing; and for the compare's results as a whole area with +/// the relay (`LEONIDA_COMPARE_RING=0`, [`ResultArea::Whole`]), which starts +/// from dword 0 again only when no plan is out: there the settle is what +/// brought it back, and without it the results' own full drain +/// (`Host::card_results_low`) would take its place. The ring gives each +/// plan's dwords back when its flight lands. +fn sweep_wants_rest() -> bool { + wants_rest(sweep_no_settle(), upcheck::on(), relay(), compare_ring()) +} + +/// [`sweep_wants_rest`] from what it reads: [`sweep_no_settle`], +/// `upcheck::on`, [`relay`] and [`compare_ring`]. +fn wants_rest(no_settle: bool, upcheck: bool, relay: bool, ring: bool) -> bool { + !no_settle || upcheck || (relay && !ring) +} + +/// Before a submission ([`Host::submit`]): whether the sweep runs, and +/// whether the flights in the air are settled for it first. `behind`: +/// flights are in the air (with [`late`]); `free_present`: +/// [`late_free_present`], without which a present settles and the sweep +/// runs then; `since_ms` since the sweep last ran here; `rest`: +/// [`sweep_wants_rest`]. With nothing in the air it runs (it lets itself +/// go once a second, [`sweep`]); behind flights with the present sent ahead +/// it runs at once when it needs no rest, and every 1.5 s after a settle +/// when it does, as before. +fn sweep_now(behind: bool, free_present: bool, since_ms: u64, rest: bool) -> (bool, bool) { + if !behind { + (true, false) + } else if !free_present { + (false, false) + } else if !rest { + (true, false) + } else { + let due = since_ms > 1500; + (due, due) + } +} + +#[cfg(test)] +mod sweep_now_tests; + /// The number of the newest submission begun, and of the newest of which all /// before it have finished too. pub(crate) fn submissions() -> (u64, u64) { @@ -606,6 +668,53 @@ fn bury(finished: u64) { } } +/// For the tests: what [`retire`] keeps that `picked` says is the test's own, +/// dropped as [`bury`] drops it once the submissions it waits for have run +/// (none run in a unit test). Returns how many. +#[cfg(test)] +pub(crate) fn bury_picked(picked: impl Fn(&dyn std::any::Any) -> bool) -> usize { + let mut n = 0; + for queue in &RETIRED { + let mut taken: Vec<(u64, Retired)> = Vec::new(); + { + let mut retired = queue.lock().unwrap_or_else(|e| e.into_inner()); + for entry in std::mem::take(&mut *retired) { + if matches!(&entry.1, Retired::Any(object) if picked(object.as_ref())) { + taken.push(entry); + } else { + retired.push_back(entry); + } + } + } + n += taken.len(); + drop(taken); + } + n +} + +/// For the tests: [`bury_picked`] for the resources descriptor slots let go +/// of ([`retire_resource`]) that `picked` says are the test's own. +#[cfg(test)] +pub(crate) fn bury_resources_picked(picked: impl Fn(&ID3D12Resource) -> bool) -> usize { + let mut n = 0; + for queue in &RETIRED { + let mut taken: Vec<(u64, Retired)> = Vec::new(); + { + let mut retired = queue.lock().unwrap_or_else(|e| e.into_inner()); + for entry in std::mem::take(&mut *retired) { + if matches!(&entry.1, Retired::Resource(object) if picked(object)) { + taken.push(entry); + } else { + retired.push_back(entry); + } + } + } + n += taken.len(); + drop(taken); + } + n +} + /// Takes out of `queues` what waited for submissions up to `finished`: of /// each queue its front, as far as the numbers there are not above /// `finished`. No queue's lock is held when what is returned is dropped. @@ -622,62 +731,7 @@ fn retired_take(queues: &[Mutex>], fi } #[cfg(test)] -mod retired_tests { - use super::{Retired, retired_queue, retired_take}; - use std::collections::VecDeque; - use std::sync::{Arc, Mutex}; - - /// Says its name when it is dropped. - struct Told(&'static str, Arc>>); - impl Drop for Told { - fn drop(&mut self) { - self.1.lock().unwrap().push(self.0); - } - } - - /// Whatever queue an object waits in, it goes when the submission it - /// waited for is behind it and not before; one behind a later number in - /// its queue (a thread overtaken) goes with that one, later than it could. - #[test] - fn what_is_retired_in_several_queues_goes_after_its_own_submission() { - let gone = Arc::new(Mutex::new(Vec::new())); - let queues: [Mutex>; 3] = [const { Mutex::new(VecDeque::new()) }; 3]; - let put = |queue: usize, at: u64, name: &'static str| { - queues[queue].lock().unwrap().push_back((at, Retired::Any(Box::new(Told(name, gone.clone()))))); - }; - put(0, 5, "a5"); - put(0, 7, "a7"); - put(1, 6, "b6"); - put(1, 4, "b4 behind b6"); - put(2, 9, "c9"); - let names = |taken: Vec<(u64, Retired)>| { - drop(taken); - std::mem::take(&mut *gone.lock().unwrap()) - }; - assert!(names(retired_take(&queues, 3)).is_empty()); - assert_eq!(names(retired_take(&queues, 5)), ["a5"]); - assert_eq!(names(retired_take(&queues, 6)), ["b6", "b4 behind b6"]); - assert!(names(retired_take(&queues, 8)) == ["a7"]); - assert_eq!(names(retired_take(&queues, 9)), ["c9"]); - assert!(queues.iter().all(|q| q.lock().unwrap().is_empty())); - } - - /// A thread keeps the queue it took, and threads take them in turn. - #[test] - fn a_thread_keeps_its_queue() { - if std::env::var_os("LEONIDA_RETIRE_QUEUES").is_some_and(|v| v == "0") { - return; - } - let mine = retired_queue(); - assert_eq!(retired_queue(), mine); - let others: Vec = (0..4).map(|_| std::thread::spawn(|| (retired_queue(), retired_queue())).join().unwrap()).map(|(a, b)| { - assert_eq!(a, b); - a - }).collect(); - assert!(others.iter().all(|&q| q < super::RETIRED_QUEUES)); - assert!(others.windows(2).any(|w| w[0] != w[1]), "{others:?}"); - } -} +mod retired_tests; /// What is handed to the reaper thread ([`reaper`]) and not dealt with /// yet, one for each retired object ([`bury`]), landed host list ([`land`]) @@ -1075,36 +1129,6 @@ fn gate_watch(gate: &'static Gate) { #[cfg(feature = "diagnostics")] static GATE_FOUND: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; -/// The gates' line of the frame lines, per frame ([`GATE_US`], [`GATE_FOUND`]). -#[cfg(feature = "diagnostics")] -fn gate_line(frames: f64) { - let [opened, us] = [0, 1].map(|i| GATE_US[i].swap(0, Ordering::Relaxed)); - let [open, shut] = [0, 1].map(|i| GATE_FOUND[i].swap(0, Ordering::Relaxed)); - if opened + open + shut == 0 { - return; - } - tracing::info!( - "gates in the card's queue per frame (LEONIDA_BAKE_AHEAD): {:.2} opened, {:.3} ms on average from the card reaching \ - the list they follow to the opening; submissions behind one {:.2} that found it open, {:.2} that made the card wait at it", - opened as f64 / frames, - us as f64 / 1e3 / opened.max(1) as f64, - open as f64 / frames, - shut as f64 / frames, - ); -} - -/// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the -/// frame's time. -fn card_clock_line(frames: f64, ms: f64) { - let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); - tracing::info!( - "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \ - {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \ - had not submitted; the submitting thread stood waiting for the card {stood:.1} ms", - if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 } - ); -} - /// Of the preparing: title memory copies (microseconds, bytes) and texture /// refreshes (microseconds, bytes hashed), since the last frame-rate line. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [ @@ -1132,10 +1156,12 @@ pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync: /// About host lists, for the memory line: lists made by the host since the /// start; preludes made (a list's second allocator and list, made when it -/// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the -/// bytes the process's private memory grew by while lists were being made -/// (what a list costs: host objects with the driver's command memory; 631 -/// lists were alive in run 65, each with a prelude it may never use). +/// first needs one, [`lazy_prelude`], or ahead, [`preludes`]: those count +/// here when made, so up to [`preludes::READY`] of them are spares no list +/// holds yet); and, in diagnostics builds, the bytes the process's private +/// memory grew by while lists were being made (what a list costs: host +/// objects with the driver's command memory; 631 lists were alive in run 65, +/// each with a prelude it may never use). /// Then the lists alive that were never reset since they were made: the /// host sides of title lists the title made and has not used (a host list /// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title @@ -1269,7 +1295,9 @@ fn create() -> windows::core::Result { // Diagnostics: the software adapter, on which a shader's wild access // is an access violation in this process (a crash report with the // address and instruction) instead of a GPU fault and driver reset. - if cfg!(feature = "diagnostics") && crate::switch::on("LEONIDA_D3D12_WARP") { + // (Tests too: the paths that need what the card here may not offer, + // card memory the CPU maps, run on it in a process of their own.) + if (cfg!(feature = "diagnostics") || cfg!(test)) && crate::switch::on("LEONIDA_D3D12_WARP") { let adapter = warp_adapter()?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); @@ -1282,6 +1310,9 @@ fn create() -> windows::core::Result { crate::tdr::log(); } let device = device.ok_or_else(windows::core::Error::empty)?; + // Whether the card's memory can be mapped by the CPU (a resizable + // BAR): every path that would put memory there falls back without it. + bar::log(&device); // Before anything is made with it (`LEONIDA_RECORD`). #[cfg(feature = "diagnostics")] crate::replay::record::from_env(&device); @@ -1445,151 +1476,23 @@ pub(crate) fn warp_adapter() -> windows::core::Result { } #[cfg(test)] -mod tests { - /// A list of ours is found by its name, with the debug layer's note or not. - #[cfg(feature = "diagnostics")] - #[test] - fn a_list_is_found_by_the_number_in_its_name() { - assert_eq!(super::list_number("leonida host list 7"), Some(7)); - assert_eq!(super::list_number("leonida host list 158 (debug layer indirect)"), Some(158)); - assert_eq!(super::list_number("leonida host list 7x"), None); - assert_eq!(super::list_number("leonida host list 7 x"), None); - assert_eq!(super::list_number("another list 7"), None); - assert_eq!(super::list_number(""), None); - } - - /// What is there of a range some of whose pages are not: those bytes, - /// counted, and zeros for the rest, whatever the buffer held. - #[test] - fn what_is_there_is_read_and_the_rest_is_zeros() { - use windows_sys::Win32::System::Memory::*; - const SIZE: usize = 0x8_0000; - // SAFETY: a reservation of ours; only committed pages are written. - unsafe { - let at = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::(); - assert!(!at.is_null()); - // 0-0x1_1000 and 0x3_0000-0x4_0000 are there. - for (from, len) in [(0, 0x1_1000), (0x3_0000, 0x1_0000)] { - assert!(!VirtualAlloc(at.add(from).cast(), len, MEM_COMMIT, PAGE_READWRITE).is_null()); - at.add(from).write_bytes(0x5a, len); - } - // From an address inside a page, as textures are packed. - let mut out = vec![0x77u8; SIZE - 0x300]; - assert_eq!(super::read_there(at.add(0x300), &mut out), 0x1_1000 - 0x300 + 0x1_0000); - for (i, &b) in out.iter().enumerate() { - let from = i + 0x300; - let there = from < 0x1_1000 || (0x3_0000..0x4_0000).contains(&from); - assert_eq!(b, if there { 0x5a } else { 0 }, "byte {from:#x}"); - } - // All there: one read. - let mut out = vec![0x77u8; 0x1_0000]; - assert_eq!(super::read_there(at.add(0x1000), &mut out), 0x1_0000); - assert!(out.iter().all(|&b| b == 0x5a)); - // Nothing there. - let mut out = vec![0x77u8; 0x1_0000]; - assert_eq!(super::read_there(at.add(0x5_0000), &mut out), 0); - assert!(out.iter().all(|&b| b == 0)); - assert_ne!(VirtualFree(at.cast(), 0, MEM_RELEASE), 0); - } - } - - /// Only what lies before, between and after the runs is zeroed (after - /// DoubleGhosty/cool_fox e8b62de); runs that overlap leave no gap. - #[test] - fn only_bytes_outside_the_runs_are_zeroed() { - let mut dst = [7u8; 16]; - super::zero_between(&mut dst, 100, &[(102, 3), (104, 2), (110, 4)]); - assert_eq!(dst, [0, 0, 7, 7, 7, 7, 0, 0, 0, 0, 7, 7, 7, 7, 0, 0]); - let mut dst = [7u8; 4]; - super::zero_between(&mut dst, 100, &[(100, 4)]); - assert_eq!(dst, [7; 4]); - super::zero_between(&mut dst, 100, &[]); - assert_eq!(dst, [0; 4]); - } - - /// Zeros for a title destination that went meanwhile are no fault. - #[test] - fn zeros_where_nothing_is_are_lost() { - use windows_sys::Win32::System::Memory::*; - // SAFETY: a reservation of ours, its first page committed. - unsafe { - let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::(); - assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null()); - at.write_bytes(7, 4096); - super::zero(at, 4096); - assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0)); - super::zero(at.add(4096), 4096); - VirtualFree(at.cast(), 0, MEM_RELEASE); - } - } - - #[test] - fn sparse_copies_preserve_islands_and_observe_remaps() { - use windows_sys::Win32::System::Memory::*; - const N: usize = 5 << 16; - // SAFETY: we reserve a private region, commit selected pages inside it, - // and only directly access the pages while they are writable. - unsafe { - let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::(); - assert!(!base.is_null()); - let mut expected = vec![0; N]; - for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] { - let at = base.add(offset); - assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); - at.write_bytes(value, 4096); - expected[offset..offset + 4096].fill(value); - } - for remap in [false, true] { - if remap { - let mut old = 0; - assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0); - expected[..4096].fill(0); - let at = base.add(1 << 16); - assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); - at.write_bytes(0xc7, 4096); - expected[1 << 16..(1 << 16) + 4096].fill(0xc7); - } - let mut out = vec![0xee; N]; - super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false); - assert_eq!(out[27..N - 27], expected[27..N - 27]); - assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee)); - } - assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); - } - } - - use super::*; - - #[test] - fn warp_adapter_accepts_only_software() { - // This probes DXGI without creating a D3D12 device or running a title. - // SAFETY: plain DXGI adapter queries. - let raw = unsafe { - let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) - else { - return; - }; - factory.EnumWarpAdapter::() - }; - let Ok(raw) = raw else { return }; - // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements - // IDXGIAdapter1; `raw` owns that interface. - let desc = unsafe { raw.cast::().unwrap().GetDesc1().unwrap() }; - eprintln!( - "EnumWarpAdapter: vendor={:#x}, flags={:#x}", - desc.VendorId, desc.Flags - ); - assert_eq!( - warp_adapter().is_ok(), - desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0, - ); - } -} +mod tests; /// The batches of clamped records in one scratch buffer -/// ([`HostList::batch_place`]). +/// ([`HostList::batch_place_table`]). const BATCHES: u32 = 8; +/// The largest indirect scratch buffer a host list keeps while it is idle +/// ([`HostList::idle_trim`]): what most frames' executions fit in. +const IDLE_INDIRECT_MOST: u64 = 1 << 20; + +/// Since the last frame-rate line: indirect scratch buffers past +/// [`IDLE_INDIRECT_MOST`] idle lists let go, and their bytes. Each is made +/// again by the next list that needs that much, so a count near one a frame +/// says a title runs such an execution every frame and pays a buffer for it +/// each time. +static IDLE_INDIRECT_TRIMS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + /// A host command list and its allocator, always used together. pub(crate) struct HostList { /// With when it was made ([`now_ms`]): [`allocator_trim`] takes an old @@ -1630,9 +1533,10 @@ pub(crate) struct HostList { /// Device-local scratch buffer for clamped indirect arguments (`indirect`), /// grown to the largest indirect execution recorded on the list. indirect_args: Mutex>, - /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and - /// how many batches of this recording have a place in them. - batch_args: Mutex<(Vec, u32)>, + /// Scratch buffers of the batched clamps (`crate::indirect::batch`), how + /// many batches of this recording have a place in them, and where their + /// passes read their tables ([`batch_tables`]). + batch_args: Mutex, /// Refreshes of host copies that a thread of ours is still finding, and /// where among the list's steps they belong ([`aside`]). coming: Mutex)>>, @@ -1670,7 +1574,8 @@ type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList); /// ([`now_ms`]), as the list's own ([`allocator_trim`]). type ListPrelude = (Mutex<(ID3D12CommandAllocator, u64)>, ID3D12GraphicsCommandList); -/// A prelude just made, as a host list keeps it. +/// A prelude just made or taken made ahead ([`preludes`]), as a host list +/// keeps it: its age counts from here. fn list_prelude((allocator, list): Prelude) -> ListPrelude { (Mutex::new((allocator, now_ms())), list) } @@ -1720,60 +1625,6 @@ struct TwinUse { late: bool, } -/// The pass that draws the twin of a depth plane into the plane: one -/// triangle over each mip of each slice, its pixel shader writing the -/// twin's texel as the depth, with the depth test "always" and no stencil -/// (the stencil plane is copied through a buffer and not touched here). -/// -/// A 16-bit twin holds whole steps of 1/65535, and the depth written is -/// the step times the float nearest 1/65535 (0x37800080). That is how -/// The title's tiled lighting computes the depth of the -/// rectangles it then draws with the test "equal", one class of materials -/// a draw (all six of its vertex shaders multiply the class number by that -/// constant), so the pass and the draw give the host the same float, and -/// the host turns the same float into the same 24 bits. The step divided -/// by 65535 is another float for 512 of the 65,536 steps (none under 257), -/// and lands in another 24-bit step for 127 of them (none under 385). -const PLANE_CORNERS: &str = r#" -float4 corner(uint i : SV_VertexID) : SV_Position { - return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0); -} -"#; -const PLANE_STEPS: &str = r#" -Texture2DArray twin : register(t0); -float plane(float4 p : SV_Position) : SV_Depth { - return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080); -} -"#; -const PLANE_FLOATS: &str = r#" -Texture2DArray twin : register(t0); -float plane(float4 p : SV_Position) : SV_Depth { - return twin.Load(int4(int2(p.xy), 0, 0)); -} -"#; - -/// Cached pipeline objects. Shader-visible descriptors belong to the -/// individual recorded pass instead: a command list may be submitted late -/// or more than once, so a global descriptor ring cannot safely wrap. -struct PlanePass { - made: Mutex)>>, -} - -/// The pass's root signature and pipeline for one kind of twin and one -/// depth format. -type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState); - -// SAFETY: D3D12 objects are free-threaded. -unsafe impl Send for PlanePass {} -// SAFETY: as above. -unsafe impl Sync for PlanePass {} - -fn plane_pass() -> Option<&'static PlanePass> { - static PASS: OnceLock = OnceLock::new(); - host()?; - Some(PASS.get_or_init(|| PlanePass { made: Mutex::default() })) -} - /// Compiles function `entry` of `source` for `target` with the system's /// compiler, as the indirect-argument clamp is (`crate::indirect`). pub(crate) fn compile( @@ -1822,347 +1673,6 @@ pub(crate) fn compile( Ok(bytes.to_vec()) } -impl PlanePass { - /// The root signature and pipeline for a twin of 16-bit steps (`steps`) - /// or of floats and the depth format `format`. - fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option { - let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); - if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) { - return pipeline.clone(); - } - let pipeline = match Self::make(steps, format) { - Ok(pipeline) => Some(pipeline), - Err(e) => { - tracing::warn!( - error = %e, - steps, - format = format.0, - "no pipeline to draw a depth plane from its twin: such planes stay as they are" - ); - None - } - }; - made.push((steps, format.0, pipeline.clone())); - pipeline - } - - fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result { - use windows::core::s; - let device = &host().ok_or_else(windows::core::Error::empty)?.device; - let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?; - let source = if steps { PLANE_STEPS } else { PLANE_FLOATS }; - let ps = compile(source, s!("plane"), s!("ps_5_1"))?; - let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { - pShaderBytecode: bytes.as_ptr().cast(), - BytecodeLength: bytes.len(), - }; - // Wine's HLSL compiler leaves RootSignature attributes out of the bytecode. - let range = D3D12_DESCRIPTOR_RANGE1 { - RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, - NumDescriptors: 1, - BaseShaderRegister: 0, - RegisterSpace: 0, - Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE, - OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND, - }; - let parameter = D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, - Anonymous: D3D12_ROOT_PARAMETER1_0 { - DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 { - NumDescriptorRanges: 1, - pDescriptorRanges: &range, - }, - }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, - }; - // SAFETY: the range, root signature and bytecode live through the calls. - unsafe { - let root = plane_root_signature(device, ¶meter)?; - let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - VS: code(&vs[..]), - PS: code(&ps[..]), - SampleMask: u32::MAX, - RasterizerState: D3D12_RASTERIZER_DESC { - FillMode: D3D12_FILL_MODE_SOLID, - CullMode: D3D12_CULL_MODE_NONE, - DepthClipEnable: true.into(), - ..Default::default() - }, - // Every texel is written; stencil stays off. - DepthStencilState: D3D12_DEPTH_STENCIL_DESC { - DepthEnable: true.into(), - DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, - DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, - ..Default::default() - }, - PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, - DSVFormat: format, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - ..Default::default() - }; - let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?; - Ok((root, pipeline)) - } - } -} - -/// Serializes the single root parameter used by the plane pass or its test draw. -/// -/// # Safety -/// Any descriptor ranges referenced by the parameter must live through this call. -pub(crate) unsafe fn plane_root_signature( - device: &ID3D12Device, - parameter: &D3D12_ROOT_PARAMETER1, -) -> windows::core::Result { - let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { - Version: D3D_ROOT_SIGNATURE_VERSION_1_1, - Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { - Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { - NumParameters: 1, - pParameters: parameter, - ..Default::default() - }, - }, - }; - let mut blob = None; - // SAFETY: the description borrows the live parameter and its ranges. - unsafe { - D3D12SerializeVersionedRootSignature(&desc, &mut blob, None)?; - let blob = blob.ok_or_else(windows::core::Error::empty)?; - let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()); - device.CreateRootSignature(0, bytes) - } -} - -/// Records into `list` the pass that draws `plane`, the twin of the depth -/// plane of `depth`, into that plane: `depth` in the depth-write state, -/// `plane` readable by pixel shaders. The pass sets the list's descriptor -/// heap, graphics root signature, pipeline, depth target, viewport, -/// scissor and topology and puts none of them back: it is for a list that -/// records nothing of the title's after it. -fn record_plane_pass( - owner: &HostList, - depth: &ID3D12Resource, - plane: &ID3D12Resource, -) { - let list = &owner.list; - let (Some(host), Some(pass)) = (host(), plane_pass()) else { - return; - }; - // SAFETY: live resources. - let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) }; - // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32 - // typeless one floats, read as R32_FLOAT (41). The depth view names - // the depth-stencil format of the texture's family (44: 45, 19: 20). - let steps = twin.Format.0 == 53; - let format = DXGI_FORMAT(match of.Format.0 { - 44 => 45, - 19 => 20, - typed => typed, - }); - let Some((root, pipeline)) = pass.pipeline(steps, format) else { - return; - }; - let count = u32::from(of.DepthOrArraySize) * u32::from(of.MipLevels); - if count == 0 { - return; - } - let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - // SAFETY: plain heap creation. Each subresource has one immutable - // descriptor, and the owner retains the heap through all submissions. - let views: ID3D12DescriptorHeap = match unsafe { - host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: count, - Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, - NodeMask: 0, - }) - } { - Ok(heap) => heap, - Err(e) => { - tracing::error!(error = %e, count, "no descriptor heap for depth plane pass"); - return; - } - }; - owner.keep(&views); - owner.keep(depth); - owner.keep(plane); - // SAFETY: live heap, open list. - let (base_cpu, base_gpu, step) = unsafe { - list.SetDescriptorHeaps(&[Some(views.clone())]); - ( - views.GetCPUDescriptorHandleForHeapStart().ptr, - views.GetGPUDescriptorHandleForHeapStart().ptr, - host.device.GetDescriptorHandleIncrementSize(kind), - ) - }; - for slice in 0..u32::from(of.DepthOrArraySize) { - for mip in 0..u32::from(of.MipLevels) { - let slot = slice * u32::from(of.MipLevels) + mip; - let view = D3D12_SHADER_RESOURCE_VIEW_DESC { - Format: DXGI_FORMAT(if steps { 57 } else { 41 }), - ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, - Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, - Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { - Texture2DArray: D3D12_TEX2D_ARRAY_SRV { - MostDetailedMip: mip, - MipLevels: 1, - FirstArraySlice: slice, - ArraySize: 1, - ..Default::default() - }, - }, - }; - let target = D3D12_DEPTH_STENCIL_VIEW_DESC { - Format: format, - ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY, - Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 { - Texture2DArray: D3D12_TEX2D_ARRAY_DSV { - MipSlice: mip, - FirstArraySlice: slice, - ArraySize: 1, - }, - }, - ..Default::default() - }; - let target = host.dsv(depth, Some(&target)); - let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1)); - let cpu = D3D12_CPU_DESCRIPTOR_HANDLE { - ptr: base_cpu + slot as usize * step as usize, - }; - let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { - ptr: base_gpu + u64::from(slot) * u64::from(step), - }; - // SAFETY: an open list; a slot of our heap; live resources and - // objects (the pass's own live as long as the process). - unsafe { - host.device - .CreateShaderResourceView(plane, Some(&view), cpu); - list.SetGraphicsRootSignature(&root); - list.SetPipelineState(&pipeline); - list.SetGraphicsRootDescriptorTable(0, gpu); - list.OMSetRenderTargets(0, None, false, Some(&target)); - list.RSSetViewports(&[D3D12_VIEWPORT { - TopLeftX: 0.0, - TopLeftY: 0.0, - Width: width as f32, - Height: height as f32, - MinDepth: 0.0, - MaxDepth: 1.0, - }]); - list.RSSetScissorRects(&[RECT { - left: 0, - top: 0, - right: width as i32, - bottom: height as i32, - }]); - list.IASetPrimitiveTopology( - windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4), - ); - list.DrawInstanced(3, 1, 0, 0); - } - crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed); - } - } -} - -/// Records into `list` the copy of a depth texture into its colour twin -/// (`colour`) or of the twin into the depth texture, both already in their -/// copy states: whole textures of one size in one format family, which the -/// host copies as they are; or, for the twin of a stencil plane, that plane -/// alone, through the twin's buffer. -fn record_twin_copy( - list: &ID3D12GraphicsCommandList, - depth: &ID3D12Resource, - twin: &crate::resource::Twin, - colour: bool, -) { - let (from, to) = if colour { - (depth, &twin.colour.texture) - } else { - (&twin.colour.texture, depth) - }; - crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed); - // shortcut: the depth plane's twin is not given the plane (that is a - // pass the other way: the plane read by a shader, the twin as its - // target). The twin then lacks what draws and clears wrote to the - // plane since shaders last wrote the twin. In the title - // nothing writes that plane but the twin's pass (its 192 draws against - // it only test, run 29), so the twin lacks nothing. Counted. - if colour && twin.plane.is_some() { - crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed); - } - let Some(through) = &twin.through else { - // SAFETY: an open list and two live textures. - unsafe { list.CopyResource(to, from) }; - return; - }; - // A stencil plane and its twin: each mip and slice of the plane goes - // into the buffer, laid out as the host lays the plane out for copies, - // and from the buffer into the other texture, whole subresources both - // times. In the depth texture the stencil plane's subresources follow - // the depth plane's; the twin has the one plane. - let Some(host) = host() else { return }; - // SAFETY: a live texture. - let of = unsafe { depth.GetDesc() }; - let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize); - let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize]; - // SAFETY: a plain query writing `planes` footprints. - unsafe { - host.device.GetCopyableFootprints( - &of, - planes, - planes, - 0, - Some(rows.as_mut_ptr()), - None, - None, - None, - ); - } - let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) }; - let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: a borrowed pointer the location never releases. - pResource: unsafe { std::mem::transmute_copy(texture) }, - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: index, - }, - }; - let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: as above. - pResource: unsafe { std::mem::transmute_copy(through) }, - Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - PlacedFootprint: *row, - }, - }; - let (common, source, dest) = ( - D3D12_RESOURCE_STATE_COMMON, - D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATE_COPY_DEST, - ); - // SAFETY: an open list and live resources; the buffer was made as big - // as these footprints, and rests in the common state between copies. - unsafe { - list.ResourceBarrier(&[transition(through, common, dest)]); - for (i, row) in rows.iter().enumerate() { - let index = first_from + i as u32; - list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None); - } - list.ResourceBarrier(&[transition(through, dest, source)]); - for (i, row) in rows.iter().enumerate() { - let index = first_to + i as u32; - list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None); - } - list.ResourceBarrier(&[transition(through, source, common)]); - } -} - /// Whether device-removed data is on (`LEONIDA_D3D12_DRED`, diagnostics /// builds). pub(crate) fn dred_on() -> bool { @@ -2572,6 +2082,24 @@ fn give_read_backs(buffers: Vec) { drop(gone); } +/// A read-back buffer a texture's landing held while it was written into +/// title memory (`crate::texback::mapped`): kept for the next read backs of +/// its size if the landing's reference is the last ([`give_read_backs`]), +/// else let go (the list that read it back gives it back at its reset). +pub(crate) fn give_read_back(buffer: ID3D12Resource) { + if sole(&buffer) { + give_read_backs(vec![buffer]); + } +} + +/// For tests: whether the read-back buffer at `raw` (its interface pointer) +/// is kept for the next read backs ([`give_read_backs`]). +#[cfg(test)] +pub(crate) fn read_back_kept(raw: usize) -> bool { + use windows::core::Interface; + SPARE_BACKS.lock().unwrap_or_else(|e| e.into_inner()).kept.iter().any(|(back, _)| back.0.as_raw() as usize == raw) +} + /// Lets go of the read-back buffers kept while host memory is pressured. fn trim_spare_backs() { let freed = { @@ -2582,31 +2110,8 @@ fn trim_spare_backs() { drop(freed); } -/// For the frame-rate line: what [`read_back_pool`] did per frame, if there -/// were read backs. -fn read_backs_line(frames: f64) { - let b: Vec = BACKS.iter().map(|b| b.swap(0, Ordering::Relaxed)).collect(); - if b.iter().all(|&n| n == 0) { - return; - } - let (kept, bytes) = { - let spare = SPARE_BACKS.lock().unwrap_or_else(|e| e.into_inner()); - (spare.kept.len(), spare.bytes) - }; - tracing::info!( - "read-back buffers per frame: {:.1} made, {:.1} taken from those kept; at their lists' resets {:.1} kept and {:.1} let go; \ - {kept} kept now, {:.1} MB (LEONIDA_READ_BACK_POOL=0: one made for each read back, as before; now {})", - b[0] as f64 / frames, - b[1] as f64 / frames, - b[2] as f64 / frames, - b[3] as f64 / frames, - bytes as f64 / (1 << 20) as f64, - if read_back_pool() { "on" } else { "off" } - ); -} - /// Whether the scratch buffers of the batched clamps -/// ([`HostList::batch_place`]) are shared by the lists +/// ([`HostList::batch_place_table`]) are shared by the lists /// (`LEONIDA_BATCH_SCRATCH_POOL=0`: a list keeps every one it ever took for /// as long as it lives, as before; `LEONIDA_AB` can name it). /// @@ -2638,7 +2143,7 @@ fn read_backs_line(frames: f64) { /// finished, and every recording leaves the buffers it used in the common /// state when it closes ([`HostList::batches_common`]); one that was never /// closed or never sent ran no state change at all. -fn batch_pool() -> bool { +pub(crate) fn batch_pool() -> bool { crate::toggled!("LEONIDA_BATCH_SCRATCH_POOL") } @@ -2650,15 +2155,51 @@ const BATCH_SCRATCH: u64 = (BATCHES * crate::indirect::batch::JOBS * crate::indi /// were when the list went. const SPARE_BATCHES_MOST: usize = 1024; -/// A scratch buffer of the batched clamps no list holds. -struct SpareBatch(ID3D12Resource); +/// A scratch buffer of the batched clamps no list holds, with its table +/// area if it has one ([`batch_tables`]). +struct SpareBatch(batch_tables::BatchScratch); -// SAFETY: a D3D12 resource (free-threaded) that nothing else names. +// SAFETY: D3D12 resources (free-threaded) that nothing else names, and a +// mapping written only by the list that holds them. unsafe impl Send for SpareBatch {} /// Those buffers ([`batch_pool`]). static SPARE_BATCHES: Mutex> = Mutex::new(Vec::new()); +#[cfg(test)] +thread_local! { + /// (Tests) The first error of the debug layer [`Host::log_messages`] + /// found on this thread since [`Host::errors_seen`] last asked. + static TEST_FIRST_ERROR: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// (Tests) A table of spare scratch buffers of the batched clamps the + /// thread's lists give theirs to and take them from instead of + /// [`SPARE_BATCHES`], while it is `Some` ([`own_spare_batches`]). + static TEST_SPARE_BATCHES: std::cell::RefCell>> = + const { std::cell::RefCell::new(None) }; +} + +/// (Tests) With `on` the thread's lists give the scratch buffers of their +/// batched clamps to a table of the thread's own, empty at first, and take +/// them from it: what a list takes is what the thread's lists gave, whatever +/// other tests do meanwhile. Without, the process's again (and the thread's +/// are let go). +#[cfg(test)] +pub(crate) fn own_spare_batches(on: bool) { + TEST_SPARE_BATCHES.set(on.then(Vec::new)); +} + +/// `f` on the table of spare scratch buffers of the batched clamps +/// ([`SPARE_BATCHES`]; in a test, its thread's own if it has one). +fn with_spare_batches(f: impl FnOnce(&mut Vec) -> R) -> R { + #[cfg(test)] + if let Some(mut own) = TEST_SPARE_BATCHES.with_borrow_mut(Option::take) { + let r = f(&mut own); + TEST_SPARE_BATCHES.set(Some(own)); + return r; + } + f(&mut SPARE_BATCHES.lock().unwrap_or_else(|e| e.into_inner())) +} + /// Since the last frame-rate line: scratch buffers of the batched clamps /// made, taken from the table, kept there at a list's reset, and let go there /// (the table full). @@ -2673,26 +2214,28 @@ fn batches_kept(kept: usize, given: usize, most: usize) -> usize { /// A list is done with the scratch buffers of its batched clamps (it was /// reset after its submissions ran): kept for the next recordings /// ([`batch_pool`]). -fn give_batches(mut buffers: Vec) { +fn give_batches(mut buffers: Vec) { if buffers.is_empty() { return; } { - let mut spare = SPARE_BATCHES.lock().unwrap_or_else(|e| e.into_inner()); - let kept = batches_kept(spare.len(), buffers.len(), SPARE_BATCHES_MOST); - BATCH_SCRATCHES[2].fetch_add(kept as u64, Ordering::Relaxed); - BATCH_SCRATCHES[3].fetch_add((buffers.len() - kept) as u64, Ordering::Relaxed); - spare.extend(buffers.drain(..kept).map(SpareBatch)); + with_spare_batches(|spare| { + let kept = batches_kept(spare.len(), buffers.len(), SPARE_BATCHES_MOST); + BATCH_SCRATCHES[2].fetch_add(kept as u64, Ordering::Relaxed); + BATCH_SCRATCHES[3].fetch_add((buffers.len() - kept) as u64, Ordering::Relaxed); + spare.extend(buffers.drain(..kept).map(SpareBatch)); + }); } // The rest is released outside the lock. drop(buffers); } /// A scratch buffer for eight batches of clamped records, in the common -/// state: one kept ([`SPARE_BATCHES`]) or a new one. -fn take_batch_scratch() -> Option { +/// state: one kept ([`SPARE_BATCHES`]), with the table area it had, or a new +/// one. +fn take_batch_scratch() -> Option { if batch_pool() - && let Some(SpareBatch(buffer)) = SPARE_BATCHES.lock().unwrap_or_else(|e| e.into_inner()).pop() + && let Some(SpareBatch(buffer)) = with_spare_batches(Vec::pop) { BATCH_SCRATCHES[1].fetch_add(1, Ordering::Relaxed); return Some(buffer); @@ -2700,7 +2243,7 @@ fn take_batch_scratch() -> Option { BATCH_SCRATCHES[0].fetch_add(1, Ordering::Relaxed); let made = host()?.uav_buffer(BATCH_SCRATCH)?; name(&made, || format!("indirect batches {BATCH_SCRATCH:#x}")); - Some(made) + Some(batch_tables::BatchScratch::new(made)) } /// Whether host command allocators are taken anew now and then @@ -2794,43 +2337,6 @@ fn allocator_refresh(allocator: &mut ID3D12CommandAllocator, made: &mut u64, whi true } -/// For the frame-rate line: what [`allocator_trim`] did since the last one, -/// if anything. -fn allocator_trim_line() { - let t: Vec = ALLOCATOR_TRIMS.iter().map(|t| t.swap(0, Ordering::Relaxed)).collect(); - if t.iter().all(|&n| n == 0) { - return; - } - tracing::info!( - "command allocators taken anew since the last line (LEONIDA_ALLOCATOR_TRIM=1): {} of host lists at their resets, {} of preludes; \ - {} idle host lists let go", - t[0], - t[1], - t[2] - ); -} - -/// For the frame-rate line: what [`batch_pool`] did per frame, if a batch -/// took a buffer or a list gave some back. -fn batch_scratch_line(frames: f64) { - let b: Vec = BATCH_SCRATCHES.iter().map(|b| b.swap(0, Ordering::Relaxed)).collect(); - if b.iter().all(|&n| n == 0) { - return; - } - let kept = SPARE_BATCHES.lock().unwrap_or_else(|e| e.into_inner()).len(); - tracing::info!( - "scratch buffers of batched clamps per frame: {:.1} made, {:.1} taken from those kept; at their lists' resets {:.1} kept and \ - {:.1} let go; {kept} kept now, {:.1} MB of the card's memory (LEONIDA_BATCH_SCRATCH_POOL=0: a list keeps all it ever took, \ - as before; now {})", - b[0] as f64 / frames, - b[1] as f64 / frames, - b[2] as f64 / frames, - b[3] as f64 / frames, - (kept as u64 * BATCH_SCRATCH) as f64 / (1 << 20) as f64, - if batch_pool() { "on" } else { "off" } - ); -} - /// A scratch chunk of `size` bytes: one kept ([`SPARE`], or [`SPARE_CARD`] with /// [`scratch_card`]) or a new one. fn take_chunk(host: &Host, size: u64) -> Option { @@ -2944,11 +2450,17 @@ struct CardWork { differs: (ID3D12Resource, usize, u64), /// Where the pieces that differ are fetched to: PC memory, mapped. fetched: Option<(ID3D12Resource, usize, u64)>, + /// The sizes of the last fetches into it ([`fetched::fit`]). + fetched_sizes: fetched::Sizes, /// The dwords of `differs` taken by plans whose results were not read - /// yet. - taken: u32, - /// Plans made and not done with (`Host::card_done`). - out: u32, + /// yet, and where the next plan's go. + results: ResultArea, + /// [`landsame`]'s passes, made at the first plan that lands in its + /// submission (`Some(None)`: they could not be). + land: Option>, + /// Timestamps for those lists not in a plan ([`owntimes`]), as `sync`. + #[cfg(feature = "diagnostics")] + stamps: Vec, } // SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only @@ -2957,231 +2469,15 @@ unsafe impl Send for CardWork {} static CARD_WORK: Mutex> = Mutex::new(None); -/// The compare of a declared range of a copy in the card's memory with -/// its bytes from before, one group per 64 KiB piece (cut at multiples of -/// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs` -/// gets a dword per piece, odd where a byte differs. The offsets are widened -/// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a -/// byte just outside the range costs a fetch that finds nothing. -/// -/// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and -/// one of them hashes their 64 hashes: 64 steps after one another. One thread -/// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's -/// 82 on the card (capture replay1, 405 of them), most of it waiting for -/// those steps. -pub(crate) const CARD_COMPARE: &str = r#" -#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)" -cbuffer Span : register(b0) { - uint first; // the first piece - uint skew; // where the copy starts in its piece 0 - uint size; // the copy's buffer, in bytes (a multiple of 64 KiB) - uint pieces; - uint out_at; // the first piece's dword in `differs`, in bytes - uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored) -}; -ByteAddressBuffer now : register(t0); -// 16 bytes per piece of the copy: the hash of its bytes when they were -// last sent up (or hashed whole, the first time). -RWByteAddressBuffer hashes : register(u0); -RWByteAddressBuffer differs : register(u1); -groupshared uint4 parts[64]; -[RootSignature(RS)] -[numthreads(64, 1, 1)] -void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) { - uint piece = first + id.x; - uint lo = piece * 65536u; - lo = lo > skew ? lo - skew : 0u; - uint hi = min((piece + 1u) * 65536u - skew, size); - lo = lo & ~15u; - hi = (hi + 15u) & ~15u; - uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread; - uint at = lo + thread * 16u; - // Eight loads at once: one after the other, each waits for memory. - [loop] - for (; at + 7168u < hi; at += 8192u) { - uint4 v0 = now.Load4(at + 0u); - uint4 v1 = now.Load4(at + 1024u); - uint4 v2 = now.Load4(at + 2048u); - uint4 v3 = now.Load4(at + 3072u); - uint4 v4 = now.Load4(at + 4096u); - uint4 v5 = now.Load4(at + 5120u); - uint4 v6 = now.Load4(at + 6144u); - uint4 v7 = now.Load4(at + 7168u); - h = (h ^ v0) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); - h = h.yzwx ^ (h >> 15); - h = (h ^ v1) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); - h = h.yzwx ^ (h >> 15); - h = (h ^ v2) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); - h = h.yzwx ^ (h >> 15); - h = (h ^ v3) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); - h = h.yzwx ^ (h >> 15); - h = (h ^ v4) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); - h = h.yzwx ^ (h >> 15); - h = (h ^ v5) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); - h = h.yzwx ^ (h >> 15); - h = (h ^ v6) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); - h = h.yzwx ^ (h >> 15); - h = (h ^ v7) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); - h = h.yzwx ^ (h >> 15); - } - [loop] - for (; at < hi; at += 1024u) { - h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); - h = h.yzwx ^ (h >> 15); - } - parts[thread] = h; - GroupMemoryBarrierWithGroupSync(); - if (thread != 0u) return; - h = parts[0]; - [loop] - for (uint i = 1u; i < 64u; ++i) { - h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); - h = h.yzwx ^ (h >> 15); - } - if (compare != 0u) { - // The flag, and above it 31 bits of the hash (`torn`). - uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u); - differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u)); - // With the copy-back on its own thread: the next compare of the - // piece finds what is written from here on. - if (compare == 2u) hashes.Store4(piece * 16u, h); - } else { - hashes.Store4(piece * 16u, h); - } -} -"#; +/// Bytes of the compare's results ([`CardWork::differs`]): a megabyte, +/// 262,144 pieces, 16 GB of declared ranges in one submission. +const CARD_RESULTS: u64 = 1 << 20; -/// The hash [`CARD_COMPARE`] gives of a piece with its flag. #[cfg(test)] -pub(crate) fn piece_hash(bytes: &[u8]) -> u32 { - torn::hash(bytes) -} - -/// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from -/// dword `at` on (`mode` as the shader's `compare`): a group per piece, in -/// parts a dispatch can hold. -/// -/// # Safety -/// The list is open with the compare's root signature, pipeline and buffers -/// set, and the pieces lie in the buffer. -unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) { - const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; - let mut done = 0; - while done < span.pieces { - let n = (span.pieces - done).min(MOST); - let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode]; - // SAFETY: the caller's. - unsafe { - list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); - list.Dispatch(n, 1, 1); - } - done += n; - } -} - -/// Whether the compares of ranges of one copy in the card's memory whose -/// pieces and result places follow each other go in one pass -/// (`LEONIDA_CARD_COMPARE_JOIN=0`: a pass each, as before). -/// -/// The compare ran a pass per declared range after the lists of every -/// submission, each a dispatch with its constants and two root views set: -/// some 390 a frame in the fork's count (walking in the prison). Joined, the -/// same pieces are hashed and flagged at the same places: a pass takes its -/// pieces from `first` on and writes piece `i`'s flag at dword `at + i`, and -/// two passes are joined only where the second goes on at both. -/// (After edsuuu/VI-BR-PORT 2f59f1d.) -fn compare_join() -> bool { - crate::toggled!("LEONIDA_CARD_COMPARE_JOIN") -} - -/// A pass of [`CARD_COMPARE`] after a submission's lists: the copy's card -/// side and its hashes (where the card has them), the bytes hashed of a -/// piece, the pieces, the first's place in the flags, the mode. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct ComparePass { - buffer: u64, - hashes: u64, - size: u32, - span: crate::shadow::CardSpan, - at: u32, - mode: u32, -} - -/// `passes` in order, with those joined that go on where the one before -/// them ends ([`compare_join`]): the same copy, piece size, mode and skew, -/// the next piece and the next place. -fn joined_compares(passes: impl Iterator, join: bool) -> Vec { - let mut out: Vec = Vec::new(); - for pass in passes { - match out.last_mut() { - Some(last) - if join - && (last.buffer, last.hashes, last.size, last.mode, last.span.skew) - == (pass.buffer, pass.hashes, pass.size, pass.mode, pass.span.skew) - && last.span.first + last.span.pieces == pass.span.first - && last.at + last.span.pieces == pass.at => - { - last.span.pieces += pass.span.pieces; - last.span.to = pass.span.to; - } - _ => out.push(pass), - } - } - out -} +mod result_ring_tests; #[cfg(test)] -mod compare_join_tests { - use super::{ComparePass, joined_compares}; - use crate::shadow::CardSpan; - - /// Joined, the passes hash the same pieces into the same places, in the - /// same order; only what goes on at both is joined. - #[test] - fn joined_compares_hash_the_same_pieces_into_the_same_places() { - const PIECE: u32 = 64 << 10; - let pass = |buffer: u64, first: u32, pieces: u32, at: u32, mode: u32| ComparePass { - buffer, - hashes: buffer + 1, - size: PIECE, - span: CardSpan { from: first * PIECE, to: (first + pieces) * PIECE, first, pieces, skew: 0 }, - at, - mode, - }; - let skewed = |mut p: ComparePass| { - p.span.skew = 4096; - p - }; - let all = [ - pass(100, 0, 2, 0, 1), - pass(100, 2, 3, 2, 1), // goes on: joined - pass(100, 5, 1, 5, 1), // and again - pass(100, 6, 1, 6, 2), // another mode - pass(100, 7, 1, 9, 2), // not the next place - pass(100, 9, 1, 10, 2), // not the next piece - pass(200, 10, 1, 11, 2), // another copy - pass(200, 11, 2, 12, 2), // goes on - skewed(pass(200, 13, 1, 14, 2)), // another skew - pass(200, 13, 1, 15, 2), // a piece again (two ranges in it) - ]; - // Each pass as (copy, mode, skew, piece, place) for every piece. - let pieces = |passes: &[ComparePass]| -> Vec<(u64, u32, u32, u32, u32)> { - passes - .iter() - .flat_map(|p| (0..p.span.pieces).map(move |i| (p.buffer, p.mode, p.span.skew, p.span.first + i, p.at + i))) - .collect() - }; - let joined = joined_compares(all.into_iter(), true); - assert_eq!(pieces(&joined), pieces(&all)); - assert_eq!(joined.len(), 7); - assert_eq!(joined[0], pass(100, 0, 6, 0, 1)); - assert_eq!((joined[0].span.from, joined[0].span.to), (0, 6 * PIECE)); - assert_eq!(joined[4], pass(200, 10, 3, 11, 2)); - // Not asked for: as they came. - assert_eq!(joined_compares(all.into_iter(), false), all); - assert!(joined_compares(std::iter::empty(), true).is_empty()); - } -} +mod compare_join_tests; /// Whether the pieces hashed again after ranges were sent up to a copy in /// the card's memory are hashed in runs of pieces that touch, each piece @@ -3200,8 +2496,10 @@ fn rehash_runs() -> bool { /// Since the last frame-rate line, of our own passes over copies in the /// card's memory: hash passes after ranges were sent up, the pieces they -/// hashed, and compare passes after the lists. -static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; +/// hashed, compare passes after the lists, the pieces those hashed, and the +/// pieces of declared ranges left to the range before them +/// ([`compare_share`]). +static CARD_PASSES: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; /// Whether what shaders wrote to copies in the card's memory is merged /// into title memory on several threads (`LEONIDA_WIDE_MERGE=1`; off by @@ -3263,6 +2561,22 @@ struct CardPlan { looks: Option, /// With [`send`]: the memory its sends come from. sends: Option, + /// Its dwords in the compare's results ([`ResultArea::take`]), given + /// back by `Host::card_done`. + results: u64, + /// With [`landsame`]: where the pieces its compare flagged were copied + /// in its own submission, given back by `Host::card_done`. + landing: Option, + /// [`landsame`]'s switch as it was when the plan was made: whether its + /// pieces are captured in its submission, whatever the switch says by + /// its landing. + capturing: Option, + /// The pieces its compare hashes ([`compare_share`]). + hashed: u64, + /// With [`owntimes`]: the card's stamps of its lists, read and given + /// back by `Host::card_done`. + #[cfg(feature = "diagnostics")] + stamps: Option, } /// One piece of submission-time work, in recorded order. @@ -3381,6 +2695,9 @@ struct Deferred { /// since the batch was opened with the program it was declared for. #[cfg(feature = "diagnostics")] batch_writers: (std::sync::Arc, Vec<(u64, u64, std::sync::Arc)>), + /// Diagnostics (`LEONIDA_UNDECLARED_TRACE=1`): what was told of watched copies. + #[cfg(feature = "diagnostics")] + undeclared: undeclared::Writers, /// Of them, those the list's prelude copies into their host copies if /// the submission finds them changed ([`HostList::upload_in_prelude`]). prelude_uploads: Vec, @@ -3405,10 +2722,17 @@ struct Deferred { /// indirect arguments; 0 if none. It stays readable until the next /// clamp into it ([`HostList::indirect_state`]). indirect_readable: usize, + /// Whether this recording copied into the card buffer of a host copy, + /// which it may leave in `COPY_DEST` ([`HostList::copied_into_copy`]). + copied_into_copy: bool, /// With [`list_fronts`]: what the list's steps say of its refreshes, made /// when the list is closed ([`Fronts`]); the submission's refreshes in /// front take them out ([`Batch::refresh_front`]). fronts: Option>, + /// With [`summary`]: what the list's steps say apart from title memory's + /// contents, made when the list is closed (or at the first question of a + /// list that has none); nothing takes it out. + summary: Option>, } impl Deferred { @@ -3559,9 +2883,10 @@ fn late_exact() -> bool { /// /// What is left out with it: the look whether the presented frame is black /// (diagnostics; it reads the frame back at once). A frame that is saved -/// or listed is presented the old way. Once every second and a half a -/// submission settles the flights all the same, for the sweep that lets -/// idle host objects go (it needs nothing in the air). +/// or listed is presented the old way. The sweep that lets idle host +/// objects go runs behind the flights ([`sweep_no_settle`]); only what wants +/// nothing in the air ([`sweep_wants_rest`]) has a submission settle them +/// every second and a half. pub(crate) fn late_free_present() -> bool { late_stage() > 2 } @@ -3687,65 +3012,7 @@ fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> { } #[cfg(test)] -mod relay_tests { - use super::{flagged_pieces, landable}; - - /// Two planes are composed into 10 bits only while Streamline presents, - /// the switch is on and the swap chain took the format. - #[test] - fn two_planes_are_composed_into_10_bits_under_streamline_only() { - use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM}; - assert_eq!(super::planes_format(true, true, false), DXGI_FORMAT_R10G10B10A2_UNORM); - assert_eq!(super::planes_format(false, true, false), DXGI_FORMAT_R8G8B8A8_UNORM); - assert_eq!(super::planes_format(true, false, false), DXGI_FORMAT_R8G8B8A8_UNORM); - assert_eq!(super::planes_format(true, true, true), DXGI_FORMAT_R8G8B8A8_UNORM); - } - - /// A removed device's fence value is not a value reached. - #[test] - fn a_removed_devices_fence_value_is_not_reached() { - assert!(!super::fence_reached(u64::MAX, 1)); - assert!(!super::fence_reached(6, 7)); - assert!(super::fence_reached(7, 7)); - assert!(super::fence_reached(8, 7)); - } - - /// Two flights and what follows each: nothing of the second lands - /// before the card has run it, and nothing behind a flight lands - /// before the flight. - #[test] - fn flights_land_in_the_order_they_were_sent() { - // Flight (fence 5), its write, a signal, flight (fence 6), its write. - let line = [Some(5), None, None, Some(6), None]; - assert_eq!(landable(&line, 4), 0); - assert_eq!(landable(&line, 5), 3); - assert_eq!(landable(&line, 6), 5); - assert_eq!(landable(&line, u64::MAX), 5); - // Signals with no flight ahead land at once; behind one they wait. - assert_eq!(landable(&[None, None], 0), 2); - assert_eq!(landable(&[None, Some(9), None], 8), 1); - assert_eq!(landable(&[], 3), 0); - // After the first three landed, the rest when its turn comes. - assert_eq!(landable(&line[3..], 5), 0); - assert_eq!(landable(&line[3..], 6), 2); - } - - /// A piece flagged under one range of a plan is fetched under every - /// range that holds a part of it; pieces of other copies are not. - #[test] - fn a_piece_flagged_under_one_range_is_fetched_under_all() { - let (a, b) = (0x1000usize, 0x2000usize); - // Copy a: piece 3 under two ranges, flagged under the first only; - // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged. - let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)]; - let fetch = flagged_pieces(&flags); - assert!(fetch.contains(&(a, 3))); - assert!(!fetch.contains(&(a, 4))); - assert!(!fetch.contains(&(b, 3))); - assert!(fetch.contains(&(b, 9))); - assert_eq!(fetch.len(), 2); - } -} +mod relay_tests; /// The most host lists in the air before the flights are settled /// (`LEONIDA_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the @@ -3826,6 +3093,200 @@ struct Flight { /// The list of ours that ran ahead of them ([`card_steps`]). own: Option, texture_back_ranges: Vec<(usize, usize)>, + /// What its shaders and read-backs may write (`back` and + /// `texture_back_ranges`), in order and joined ([`flight_writes`]): made + /// before it joins the line, for [`Line::cover`]; empty with + /// `LEONIDA_LINE_COVER=0` ([`line_cover`]), where nothing reads it. + joined: Vec<(usize, usize)>, +} + +/// What a flight declaring `back` and reading textures back into +/// `texture_back_ranges` may write, in order and joined ([`Flight::joined`]). +fn flight_writes(back: &[Declared], texture_back_ranges: &[(usize, usize)]) -> Vec<(usize, usize)> { + let mut joined = Vec::new(); + join_ranges( + &mut joined, + back.iter().flat_map(|(_, ranges)| ranges.iter().copied()).chain(texture_back_ranges.iter().copied()), + ); + joined +} + +/// What the flights in the line and those being landed may write, counted +/// ([`line_cover`]; [`Line::written`] is its joined view): pieces of title +/// memory in order and apart, each with how many of those flights declare +/// all of it. A flight joining adds its [`Flight::joined`], one landed takes +/// it away, each in one pass over both ([`Cover::change`]). +struct Cover(Vec<(usize, usize, u32)>); + +impl Cover { + const fn new() -> Self { + Cover(Vec::new()) + } + + /// One flight's `ranges` (in order and joined) are added, or taken away + /// if not `up` (they were added before). + fn change(&mut self, ranges: &[(usize, usize)], up: bool) { + if ranges.is_empty() { + return; + } + let pieces = std::mem::take(&mut self.0); + let mut out: Vec<(usize, usize, u32)> = Vec::with_capacity(pieces.len() + 2 * ranges.len()); + let (mut i, mut j, mut at) = (0, 0, 0); + loop { + line_step(1); + while pieces.get(i).is_some_and(|p| p.1 <= at) { + i += 1; + } + while ranges.get(j).is_some_and(|r| r.1 <= at) { + j += 1; + } + let (p, r) = (pieces.get(i), ranges.get(j)); + // From `lo`, the first byte either has from `at` on, to `hi`, + // the next place where either begins or ends. + let lo = match (p, r) { + (None, None) => break, + (Some(p), None) => p.0.max(at), + (None, Some(r)) => r.0.max(at), + (Some(p), Some(r)) => p.0.min(r.0).max(at), + }; + let in_p = p.filter(|p| p.0 <= lo); + let in_r = r.is_some_and(|r| r.0 <= lo); + let hi = [p.map(|p| if p.0 <= lo { p.1 } else { p.0 }), r.map(|r| if r.0 <= lo { r.1 } else { r.0 })] + .into_iter() + .flatten() + .min() + .unwrap_or(lo); + let mut count = in_p.map_or(0, |p| p.2); + if in_r { + debug_assert!(up || count > 0, "a flight's range taken away that was not added"); + count = if up { count + 1 } else { count.saturating_sub(1) }; + } + if count > 0 { + match out.last_mut() { + Some(last) if last.1 == lo && last.2 == count => last.1 = hi, + _ => out.push((lo, hi, count)), + } + } + at = hi; + } + self.0 = out; + } + + /// Its pieces, joined where they touch, into `out`. + fn joined(&self, out: &mut Vec<(usize, usize)>) { + out.clear(); + for &(from, to, _) in &self.0 { + line_step(1); + match out.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => out.push((from, to)), + } + } + } +} + +/// Whether [`Line::written`] is kept by a [`Cover`]: a flight joining adds +/// its ranges, one landed takes them away, each in one pass +/// (`LEONIDA_LINE_COVER=0`: made again from every flight in the line and +/// sorted at each landing, and sorted with each flight joining, as +/// before). +/// +/// Both run with [`LINE`] held: the sort was of every range of every +/// flight in the air, at each landing (several a frame), while the landing +/// thread, the title's fence signals and its value checks waited for the +/// lock. What that cost was not measured (the timeline's "landing: the +/// rest" holds it). +/// +/// Read once, and not through `crate::toggled!`: `LEONIDA_AB` (diagnostics +/// builds, `crate::ab`) would turn that on and off at presents, with +/// flights always in the air, and the cover keeps counts from a flight +/// joining to its landing. Counts added one way and not taken away the +/// other stayed in it for good (a read waiting for a landing that never +/// cleared them, holding the submission lock), and counts taken away that +/// were never added took another flight's range out of `written` while it +/// was in the air (title memory read before its copy-back wrote it). The +/// line keeps them one way from its first flight on besides +/// ([`Line::by_cover`]). Naming it in `LEONIDA_AB` does nothing: compare +/// two runs. +fn line_cover() -> bool { + #[cfg(test)] + if let Some(on) = COVER_NOW.with(std::cell::Cell::get) { + return on; + } + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_LINE_COVER").is_none_or(|v| v != "0")) +} + +#[cfg(test)] +thread_local! { + /// For the tests: what [`line_cover`] says on this thread from now on, + /// as `LEONIDA_AB` (`crate::ab`) made a `crate::toggled!` switch say at + /// each present. + static COVER_NOW: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +thread_local! { + /// For the tests: steps of the work [`Line`] does to keep `written` + /// ([`Cover`], [`join_ranges`]) on this thread. + static LINE_STEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[inline(always)] +fn line_step(_n: u64) { + #[cfg(test)] + LINE_STEPS.with(|s| s.set(s.get() + _n)); +} + +/// The declared ranges of several flights' copies (`declared`, in order), +/// each copy once, by `key` (its address), in the order first seen, with +/// its ranges in order of declaration: every one, or with `once` each once +/// (the first). Through a table of copies and one of ranges seen, one look +/// each: it was a walk of the copies so far for each copy, and with `once` +/// one of the copy's ranges so far for each range (`Host::settle`, +/// `Host::relay_land`), on the threads everything that waits for a landing +/// waits on. +fn declared_by_copy<'a, K: Clone + 'a>( + declared: impl IntoIterator)>, + key: impl Fn(&K) -> usize, + once: bool, +) -> Vec<(K, Vec<(usize, usize)>)> { + let mut out: Vec<(K, Vec<(usize, usize)>)> = Vec::new(); + let mut place: ByCopy = ByCopy::default(); + let mut seen: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault> = + std::collections::HashSet::default(); + for (copy, ranges) in declared { + merge_step(1); + let at = *place.entry(key(copy)).or_insert_with(|| { + out.push((copy.clone(), Vec::with_capacity(ranges.len()))); + out.len() - 1 + }); + let all = &mut out[at].1; + if once { + for &range in ranges { + merge_step(1); + if seen.insert((at, range.0, range.1)) { + all.push(range); + } + } + } else { + merge_step(ranges.len() as u64); + all.extend_from_slice(ranges); + } + } + out +} + +#[cfg(test)] +thread_local! { + /// For the tests: the looks [`declared_by_copy`] made on this thread. + static MERGE_STEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[inline(always)] +fn merge_step(_n: u64) { + #[cfg(test)] + MERGE_STEPS.with(|s| s.set(s.get() + _n)); } /// One thing in the line of what waits for the card, in order. @@ -3842,6 +3303,14 @@ struct Line { /// The title memory the flights' shaders and texture readbacks may write /// (address, end), in order and joined. written: Vec<(usize, usize)>, + /// The same, counted ([`line_cover`]), of the flights in the line and + /// those being landed, whose ranges are in `landing_joined`. + cover: Cover, + landing_joined: Vec>, + /// Whether `written` is kept by `cover`: [`line_cover`] as it was when + /// the first flight joined, for good, so that every count added is + /// taken away the same way. + by_cover: Option, /// Host lists in the flights. lists: usize, /// The value signalled on the host's fence behind the last flight. @@ -3861,23 +3330,134 @@ struct Line { in_hand: Vec<(usize, crate::queue::Written, usize)>, /// With [`card_steps`]: what the flights being landed write. landing: Vec, + /// Landings done ([`Line::landed`]), for [`relay_wait_apart`]. + landings: u64, } // SAFETY: D3D12 objects (free-threaded) and host lists nothing records // into; touched under the lock. unsafe impl Send for Line {} -static LINE: Mutex = Mutex::new(Line { - line: Vec::new(), - written: Vec::new(), - lists: 0, - target: 0, - settling: false, - poke: false, - landed: Vec::new(), - in_hand: Vec::new(), - landing: Vec::new(), -}); +impl Line { + const fn new() -> Line { + Line { + line: Vec::new(), + written: Vec::new(), + cover: Cover::new(), + landing_joined: Vec::new(), + by_cover: None, + lists: 0, + target: 0, + settling: false, + poke: false, + landed: Vec::new(), + in_hand: Vec::new(), + landing: Vec::new(), + landings: 0, + } + } + + /// A flight sent ahead joins the line, its bottom-of-pipe `writes` + /// behind it: what its shaders and read-backs may write joins + /// `written`, its host lists (at least one: our own list's flight names + /// none of the title's) are counted, and the host's fence will be at + /// its value when it has run. + fn push_flight(&mut self, mut flight: Flight, writes: Vec<(usize, crate::queue::Written, usize)>) { + if *self.by_cover.get_or_insert_with(line_cover) { + if flight.joined.is_empty() && (!flight.back.is_empty() || !flight.texture_back_ranges.is_empty()) { + // (Made before the lock while the switch is on: here only + // if it was not then, which a read-once switch never is.) + flight.joined = flight_writes(&flight.back, &flight.texture_back_ranges); + } + if !flight.joined.is_empty() { + self.cover.change(&flight.joined, true); + self.cover.joined(&mut self.written); + } + } else { + join_ranges( + &mut self.written, + flight.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()).chain(flight.texture_back_ranges.iter().copied()), + ); + } + self.lists += flight.order.len().max(1); + self.target = flight.fence; + self.line.push(Late::Run(flight)); + self.line.extend(writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); + } + + /// With [`relay`]: the first `n` things of the line are taken to be + /// landed ([`Host::relay_land`]). Until [`Line::landed`] says they are, + /// `written` still holds what their flights may write, `in_hand` their + /// bottom-of-pipe writes and `landing` (with [`card_steps`]) the copies + /// they do on the card: whoever looks at the line meanwhile finds them + /// as if still in the air. + fn take_landable(&mut self, n: usize) -> Vec { + self.settling = true; + let mut items: Vec = self.line.drain(..n).collect(); + if self.by_cover == Some(true) { + // Taken away from the cover once landed. + for item in &mut items { + if let Late::Run(flight) = item { + self.landing_joined.push(std::mem::take(&mut flight.joined)); + } + } + } + self.in_hand = items + .iter() + .filter_map(|l| match l { + Late::Write(at, what, bytes) => Some((*at, *what, *bytes)), + _ => None, + }) + .collect(); + if card_steps::stage() > 0 { + self.landing = card_steps::writers(&items); + } + items + } + + /// With [`relay`]: what [`Line::take_landable`] took has landed (its + /// host lists, `landed`, are kept to be reset). `written` and the + /// count of host lists are made again from the flights still in the + /// air. + fn landed(&mut self, landed: Vec<(Vec, Vec)>) { + self.landed.extend(landed); + self.in_hand.clear(); + self.landing.clear(); + self.landings += 1; + // What is still in the air, from the flights that are. + self.lists = 0; + for item in self.line.iter() { + if let Late::Run(flight) = item { + self.lists += flight.order.len().max(1); + } + } + if self.by_cover == Some(true) { + let landed = std::mem::take(&mut self.landing_joined); + if !landed.is_empty() { + for joined in &landed { + self.cover.change(joined, false); + } + self.cover.joined(&mut self.written); + } + } else { + self.written.clear(); + let mut ranges = Vec::new(); + for item in self.line.iter() { + if let Late::Run(flight) = item { + ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied())); + ranges.extend(flight.texture_back_ranges.iter().copied()); + } + } + join_ranges(&mut self.written, ranges); + } + self.settling = false; + // The landed lists are reset, and what queues hold looked at, + // by the helper thread (they take locks a waiter may hold). + self.poke = true; + } +} + +static LINE: Mutex = Mutex::new(Line::new()); /// Told when a flight joins [`LINE`] or it is poked. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new(); @@ -3930,22 +3510,30 @@ const WHY_RUN: usize = 7; const WHY_MOST: usize = 8; const WHY_WRITES: usize = 9; const WHY_FENCE: usize = 10; +/// Room in the compare's results for a submission sent ahead with the relay +/// (`Host::card_results_low`). It was counted as [`WHY_MOST`], which the +/// frame line calls "lists in the air", so a drain for [`late_most`] and one +/// for the results could not be told apart. After the places of +/// [`LATE_STATS`] that are not reasons (11 to 17). +const WHY_RESULTS: usize = 18; /// Since the last frame-rate line: submissions sent without a wait; /// settles; settles by reason ([`WHY_SYNC`]..); flights settled; /// microseconds settles waited for the card; value waits met by a flight's /// bottom-of-pipe write; fence signals set behind flights. /// Then: the settles for title memory read, by what read it (a buffer -/// copy, a fill of upload memory, a texture). -static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18]; +/// copy, a fill of upload memory, a texture); and the settles for room in +/// the compare's results ([`WHY_RESULTS`]). +static LATE_STATS: [std::sync::atomic::AtomicU64; 19] = [const { std::sync::atomic::AtomicU64::new(0) }; 19]; /// LOCAL (11/26): settles for refreshes of memory a flight writes through /// another copy (`upcheck::crossed`), since the last frame-rate line. static CROSS_SETTLES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// Since the last frame-rate line: the microseconds settles waited for the -/// card, by why they settled (the `WHY_` places). -static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; +/// card, by why they settled (the `WHY_` places; 11 to 17 unused). +static LATE_WAITED: [std::sync::atomic::AtomicU64; WHY_RESULTS + 1] = + [const { std::sync::atomic::AtomicU64::new(0) }; WHY_RESULTS + 1]; /// Whether `[from, to)` touches one of `ranges` (in order, joined). fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool { @@ -3959,9 +3547,13 @@ fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool { /// `ranges` with `more`, in order, joined where they overlap or touch. fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator) { ranges.extend(more.into_iter().filter(|r| r.0 < r.1)); - ranges.sort_unstable(); + ranges.sort_unstable_by(|a, b| { + line_step(1); + a.cmp(b) + }); let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); for &(from, to) in ranges.iter() { + line_step(1); match out.last_mut() { Some(last) if from <= last.1 => last.1 = last.1.max(to), _ => out.push((from, to)), @@ -3999,6 +3591,7 @@ fn late_blocked(runs: &[&HostList]) -> Option { /// Whether a shader's write went into `[at, at + len)` lately: into a 4 KiB page of them in the last 600 /// frames, or with `LEONIDA_LANDED_EXACT=1` into those bytes, by cells of 8 /// (`crate::watch::landed_lately_exact`: this span of 512 frames or the one before; `LEONIDA_AB` can name it). +/// The cells are kept only in a run where one of the two asks for them (`crate::watch::landed_cells_kept`). /// /// Why the cells are kept: the title's constants lie beside a small buffer its shaders write (16 bytes apart at /// the save), and by pages they never are the title's own: three copies of 0xd0 to 0x230 bytes a frame each @@ -4009,14 +3602,7 @@ fn late_blocked(runs: &[&HostList]) -> Option { /// waited is put into title memory by its landing, which is noted like a shader's write: once a destination /// is noted it stays so, whichever way the question is asked. That is the next thing to take apart. fn landed_lately(at: usize, len: usize) -> bool { - let exact = { - static ON: OnceLock = OnceLock::new(); - let on = *ON.get_or_init(|| std::env::var_os("LEONIDA_LANDED_EXACT").is_some_and(|v| v == "1")); - #[cfg(feature = "diagnostics")] - let on = crate::ab::pick("LEONIDA_LANDED_EXACT").unwrap_or(on); - on - }; - if exact { + if crate::watch::landed_exact() { crate::watch::landed_lately_exact(at, len) } else { crate::watch::landed_lately(at, len, 600) @@ -4044,12 +3630,19 @@ fn landed_lately(at: usize, len: usize) -> bool { /// for the first time, is read as it was before that flight. fn fill_is_titles(src: usize, len: usize) -> bool { const SMALL: usize = 64 << 10; + fill_title_on() && len <= SMALL && (crate::watch::written_since_taken(src, len) || !landed_lately(src, len)) +} + +/// Whether [`fill_is_titles`] can take any range for the title's own +/// (`LEONIDA_FILL_TITLE=1`): without it, flights' writes over any byte a fill +/// or copy reads stop it ([`summary::blocked`] goes by that). +fn fill_title_on() -> bool { static ON: OnceLock = OnceLock::new(); let on = *ON.get_or_init(|| std::env::var_os("LEONIDA_FILL_TITLE").is_some_and(|v| v == "1")); // Leonida: `LEONIDA_AB=,LEONIDA_FILL_TITLE` turns it on and off by turns in one run. #[cfg(feature = "diagnostics")] let on = crate::ab::pick("LEONIDA_FILL_TITLE").unwrap_or(on); - on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !landed_lately(src, len)) + on } /// Whether a copy at its place in a list ([`place`]) into bytes that flights in the air have declared @@ -4172,6 +3765,7 @@ fn blamed(why: usize, us: u64) { WHY_STALE => "title memory changed under shader writes", WHY_RUN => "a step of ours", WHY_MOST => "lists in the air", + WHY_RESULTS => "room in the compare's results", WHY_FENCE => "a blocking fence wait", _ => "another reason", }; @@ -4183,40 +3777,6 @@ fn blamed(why: usize, us: u64) { *e = (e.0 + 1, e.1 + us, at); } -/// For the frame-rate line: the five that waited longest. -#[cfg(feature = "diagnostics")] -fn log_blame(frames: f64) { - let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); - let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); - let mut all: Vec<_> = all.into_iter().collect(); - all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us)); - for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) { - // The passes that declare it written, the ones that do so most. - let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new(); - for ((a, b, _), (n, shaders)) in &wide { - if *a < at + len && at < *b { - *passes.entry(shaders).or_default() += n; - } - } - let mut passes: Vec<(&str, u64)> = passes.into_iter().collect(); - passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1)); - let passes: Vec = - passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect(); - tracing::info!( - "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \ - over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}", - us as f64 / 1e3 / frames, - n as f64 / frames, - passes.join(", "), - match (why.is_empty(), kind) { - (true, _) => "", - (_, "title memory changed under shader writes") => "; not put in under them: ", - _ => "; not done on the card: ", - }, - ); - } -} - /// Whether flights that write `written` stop a read of `len` bytes at `src`. fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool { touches(written, src, src + len) && !fill_is_titles(src, len) @@ -4232,6 +3792,40 @@ fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) /// may write (in order, joined); `count` whether the kind of read is /// counted for the frame line. fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option { + if written.is_empty() { + return None; + } + blocked_by_in(written, runs, summary::all(runs).as_deref(), count) +} + +/// [`blocked_by`] with the lists' summaries already in hand (`sums`, in the +/// order of `runs`; `None`: by the steps, [`summary`] being off). The relay +/// asks it again after every landing it waits through. +fn blocked_by_in(written: &[(usize, usize)], runs: &[&HostList], sums: Option<&[std::sync::Arc]>, count: bool) -> Option { + let Some(sums) = sums else { + return blocked_by_steps(written, runs, count); + }; + let found = match summary::blocked(written, sums) { + summary::Blocked::No => None, + summary::Blocked::Run => Some(WHY_RUN), + summary::Blocked::Read if !count => Some(WHY_READ), + // (The frame line's count and name of what stopped it: by the steps, + // which find the same.) + summary::Blocked::Read | summary::Blocked::Steps => return blocked_by_steps(written, runs, count), + }; + if summary::mode() == summary::Mode::Check { + // (With `LEONIDA_PLACED_TITLE=1` both ask what landed lately of a + // copy at its place, `placed_is_titles`, each when it gets there: a + // landing between the two can make them differ by its timing alone.) + let steps = blocked_by_steps(written, runs, false); + summary::compared("what flights stop", steps == found); + return steps; + } + found +} + +/// [`blocked_by`] by the steps of `runs`, one list's lock at a time. +fn blocked_by_steps(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option { if written.is_empty() { return None; } @@ -4242,7 +3836,9 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op #[cfg(feature = "diagnostics")] let mut placed_why: Vec<(usize, usize, &'static str)> = Vec::new(); for list in runs { - for step in &list.deferred().copies { + let deferred = list.deferred(); + summary::walked(deferred.copies.len()); + for step in &deferred.copies { match step { &Step::Copy(dst, src, len) => { if let Some(_read) = copy_blocked(written, dst, src, len) { @@ -4339,6 +3935,36 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so /// the title's bytes there would reach the card a submission late. fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc, usize, usize)> { + let pending = crate::shadow::Shadow::writes_pending; + let spans = match summary::all(runs) { + None => stale_spans_steps(runs, pending), + Some(sums) => { + if summary::mode() == summary::Mode::Check { + // (Both by the same answer per copy: [`summary::once`].) + let pending = summary::once(pending); + let spans = summary::stale_spans(&sums, &pending); + let steps = stale_spans_steps(runs, &pending); + let keys = |spans: &[(std::sync::Arc, usize, usize)]| -> Vec<(usize, usize, usize)> { + spans.iter().map(|s| (std::sync::Arc::as_ptr(&s.0) as usize, s.1, s.2)).collect() + }; + summary::compared("refreshes under flights' writes", keys(&steps) == keys(&spans)); + steps + } else { + summary::stale_spans(&sums, pending) + } + } + }; + stale_of(spans) +} + +/// What [`stale_under_flights`] looks at, by the steps of `runs`: the copies +/// they refresh that `pending` says shaders may be writing (asked once per +/// copy), in the order first refreshed, with the span of all their +/// refreshes. +fn stale_spans_steps( + runs: &[&HostList], + pending: impl Fn(&crate::shadow::Shadow) -> bool, +) -> Vec<(std::sync::Arc, usize, usize)> { use std::sync::Arc; // Per copy, the span of what is refreshed (a flush brings that much // up to date at most). @@ -4347,10 +3973,12 @@ fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc> = ByCopy::default(); for list in runs { - for step in &list.deferred().copies { + let deferred = list.deferred(); + summary::walked(deferred.copies.len()); + for step in &deferred.copies { if let Step::Refresh(shadow, address, len) = step { let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| { - shadow.writes_pending().then(|| { + pending(shadow).then(|| { spans.push((shadow.clone(), *address, *address + *len)); spans.len() - 1 }) @@ -4362,7 +3990,7 @@ fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc (usize, usize) { /// those give their shaders, write back or write when they are done, and it /// changes no title memory that they read ([`Step::Copy`], [`Step::Run`]). pub(crate) fn joinable<'a>(ahead: impl Iterator, next: &[&HostList]) -> bool { - if next.iter().any(|l| l.deferred().copies.iter().any(|s| matches!(s, Step::Copy(..) | Step::Run(_)))) { + let copy_or_run = match summary::all(next) { + Some(sums) => summary::copy_or_run(&sums), + None => next.iter().any(|l| { + let deferred = l.deferred(); + summary::walked(deferred.copies.len()); + deferred.copies.iter().any(|s| matches!(s, Step::Copy(..) | Step::Run(_))) + }), + }; + if copy_or_run { return false; } let ahead: Vec<&HostList> = ahead.collect(); @@ -4498,15 +4134,117 @@ pub(crate) fn late_signal(fence: usize, value: u64) -> bool { /// for the card: the part behind the wait goes to the card behind that /// flight, which is the order the wait asks for. If the flights may write /// the value in a way not known here (shaders, a timestamp, another -/// width), they are settled and memory is asked again. +/// width), they are settled and memory is asked again; with +/// [`exact_wait`] only until the last of them that may write it has +/// landed ([`value_landed`]). pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool { if let Some(met) = late_met_known(wait) { return met; } - settle_now(WHY_VALUE); + if exact_wait() { + let (at, bytes) = wait.place(); + settle_until(WHY_VALUE, |line| value_landed(line, at, bytes)); + } else { + settle_now(WHY_VALUE); + } wait.met() } +/// Whether a queue's wait for a memory value ([`late_met`]) waits, under +/// the relay's second stage ([`relay_exact`]), only until the flights that +/// may write the value have landed, not until everything in the air has +/// (`LEONIDA_EXACT_WAIT=0`: everything, as before; on by default); and the +/// title's blocking fence wait only until its fence is reached +/// ([`settle_for_fence_value`]). +/// +/// Why: the wait is asked on the thread that prepares every submission +/// (`leonida-submit`, `queue::behind`'s lane), under the submission lock, +/// and it is asked exactly when the value lies under a flight's declared +/// shader write. Those are conservative (the skinning passes declare the +/// title's whole 174 MB heap), so the waited value is often under the +/// first flights only while later ones, which never touch it, keep the +/// line full: the wait stood until those had landed too, and nothing was +/// prepared meanwhile. The frame line counts these waits ("a memory +/// value": `LATE_STATS[WHY_VALUE]`, `LATE_WAITED[WHY_VALUE]`); how many +/// there are a frame in the title is not measured yet. +/// +/// Why what it waits for is enough: what a value wait can observe is +/// title memory, and a flight's landing puts into title memory only what +/// [`card_steps::writers`] lists of it (its declared shader writes, the +/// copies it does on the card, its read-backs and texture read-backs, its +/// bottom-of-pipe writes), and the fences signalled behind it, whose values +/// are at their own addresses. Nothing else of a flight reaches title +/// memory. For a copy in the card's memory the relay fetches the pieces the +/// compare found differing, but each cut to the declared span +/// (`Shadow::card_piece`), and merges only inside that cut +/// (`Shadow::card_merge_relay`, `Shadow::land_card`); ranges found written +/// through a view nobody declared are in the flight's declared writes +/// (`crate::picked::with`), and those only looked at are never landed +/// (`CardRange::picked`). So a byte beside a declared range in the same +/// piece is not put into title memory by that flight's landing. +/// Flights land in the line's order and one thread lands them, so once the +/// last that may write the value has landed, memory holds the value it +/// will hold when everything has. A flight being landed counts as in the +/// air until its landing is done ([`Line::take_landable`]). What it does +/// not see: memory the card writes in place while it runs +/// (`crate::inplace`, off by default), which no landing puts there; the +/// settle before did not wait for that either, and a value that is not met +/// yet is asked again at every landing (its `poke`). +fn exact_wait() -> bool { + relay_exact() && crate::toggled!("LEONIDA_EXACT_WAIT") +} + +/// Whether something in the air (`line`), or being landed, may still put +/// bytes into title memory `[from, to)` ([`exact_wait`]). +fn line_may_write(line: &Line, from: usize, to: usize) -> bool { + let hits = |at: usize, end: usize| at < to && from < end; + // Flights being landed: out of `line.line`, but `written` holds what + // they declared until their landing is done, `in_hand` their + // bottom-of-pipe writes and `landing` the copies they do on the card. + touches(&line.written, from, to) + || line.in_hand.iter().any(|&(at, _, bytes)| hits(at, at + bytes)) + || line.landing.iter().any(|w| w.lands_in(from, to)) + // Those in the air, each from what it says it writes. + || card_steps::writers(&line.line).iter().any(|w| w.lands_in(from, to)) + || line.line.iter().any(|item| match item { + &Late::Signal(fence, _) => { + let at = crate::fence::value_at(fence); + hits(at, at + 8) + } + _ => false, + }) +} + +/// Whether a value wait at `[at, at + bytes)` is done waiting for landings +/// ([`late_met`] with [`exact_wait`]): nothing that is in the air or being +/// landed may write those bytes, or nothing at all is ([`line_drained`], what +/// the wait waited for before). +fn value_landed(line: &Line, at: usize, bytes: usize) -> bool { + line_drained(line) || !line_may_write(line, at, at + bytes) +} + +/// Nothing is in the air and nothing is being landed: what [`Host::settle`] +/// waits for under the relay. +fn line_drained(line: &Line) -> bool { + line.line.is_empty() && !line.settling +} + +/// [`settle_now`] for `why`, but with [`exact_wait`] only until `done` +/// says so of the line (looked at each time flights have landed), or +/// until nothing is in the air. Under the submission lock as the settle +/// is, so no submission is between the card and the line meanwhile. +fn settle_until(why: usize, done: impl Fn(&Line) -> bool) { + if !exact_wait() { + settle_now(why); + return; + } + let Some(host) = host() else { + return; + }; + let _submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + relay_wait(why, |line| line_drained(line) || done(line)); +} + /// [`late_met`] without a wait for the card; `None`: it has to be waited for. pub(crate) fn late_met_known(wait: &crate::list::ValueWait) -> Option { let (address, bytes) = wait.place(); @@ -4661,6 +4399,37 @@ pub(crate) fn settle_for_fence() { settle_now(WHY_FENCE); } +/// [`settle_for_fence`] for the title's blocking wait for `fence` to reach +/// `value` (`SetEventOnCompletion` without an event): with [`exact_wait`] +/// only until the fence has reached it ([`fence_landed`]). +/// +/// Its signal stands in the line behind the flights the title submitted +/// before it on that queue, and the thread that lands flights sets it when +/// it has landed those: what they wrote is in title memory then, and their +/// bottom-of-pipe writes are done, as after the settle. What it no longer +/// waits for are the flights behind the signal, which the title cannot +/// expect to have run. Where the signal is not in the line (a queue holds +/// it behind a wait, or it never comes) everything is landed, as before: +/// the caller's short wait for the value counts from there, and a held +/// queue may need those landings to go on. Not with `LEONIDA_TELL_EARLY=1` +/// ([`tell_early`]), where the fence is set before its flights' writes are +/// in title memory. +pub(crate) fn settle_for_fence_value(fence: crate::object::This, value: u64) { + if tell_early() { + settle_now(WHY_FENCE); + return; + } + settle_until(WHY_FENCE, |line| fence_landed(line, fence, value)); +} + +/// Whether the title's blocking wait for `fence` to reach `value` is done +/// waiting for landings ([`settle_for_fence_value`] with [`exact_wait`]): +/// the fence has reached it, or nothing is in the air or being landed +/// ([`line_drained`], what it waited for before). +fn fence_landed(line: &Line, fence: crate::object::This, value: u64) -> bool { + crate::fence::completed(fence) >= value || line_drained(line) +} + /// Leonida: the number of the last submission the card has finished (for lists sent ahead with /// [`Host::execute_ahead`], which may be reset once it has). pub(crate) fn finished_submission() -> u64 { @@ -4759,26 +4528,6 @@ pub(crate) fn wait_for_slots(mut take: impl FnMut() -> Option) -> Option = DYNAMIC_WAITS.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / frames).collect(); - if w[0] <= 0.0 { - return; - } - tracing::info!( - "dynamic descriptor slots: per frame {:.2} draws found none and waited {:.1} ms, {:.2} had their slots after a landing, \ - {:.2} settled everything in the air under the submission lock, {:.2} went without (LEONIDA_DYNAMIC_WAIT=1 waits for the \ - next landing without that lock: now {})", - w[0], - w[1] / 1000.0, - w[2], - w[3], - w[4], - if dynamic_wait() && relay() { "on" } else { "off" } - ); -} - /// Whether the fence's completed value says the card ran up to `target`: /// `u64::MAX` is what a removed device reports, not a value reached. /// @@ -4963,15 +4712,7 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { LATE_STATS[why].fetch_add(1, Ordering::Relaxed); let was_working = working(false); let waiting = std::time::Instant::now(); - let _waiting = crate::timeline::span(match why { - WHY_SYNC => "waiting for landings: everything (a present, the sweep)", - WHY_VALUE => "waiting for landings: a memory value", - WHY_STALE => "waiting for landings: title memory changed under shader writes", - WHY_READ => "waiting for landings: title memory read", - WHY_MOST => "waiting for landings: lists in the air", - WHY_FENCE => "waiting for landings: a blocking fence wait", - _ => "waiting for landings: another reason", - }); + let _waiting = crate::timeline::span(landing_wait(why)); while !done(&line) { line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner()); } @@ -4980,12 +4721,110 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { working(was_working); let us = waiting.elapsed().as_micros() as u64; LATE_STATS[12].fetch_add(us, Ordering::Relaxed); - LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed); + LATE_WAITED[why.min(WHY_RESULTS)].fetch_add(us, Ordering::Relaxed); + SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + blamed(why, us); +} + +/// [`relay_wait`] for a `done` too heavy to look at under [`LINE`]: `take` +/// copies out of the line what `done` needs (nothing, or `written`), under +/// the lock; `done` looks at that copy without it. `LEONIDA_LINE_APART=0`: +/// both under the lock, as before. +/// +/// [`LINE`] is the one lock of the submitting thread, the thread that lands +/// flights (at a landing's start and end), the helper thread, the title's +/// fence signals behind flights ([`late_signal`]) and its value checks +/// ([`late_met`]). A read of title memory that flights may write +/// ([`WHY_READ`]) looked at every step of the submission again at each +/// landing ([`blocked_by`], a lock of each list's steps), and one that +/// refreshes memory flights write ([`WHY_STALE`]) every stale range's +/// copy, all with [`LINE`] held: everyone else waited for that walk, the +/// landing thread's start of the next landing among them. What it costs +/// was not measured (the timeline's "waiting for landings: title memory +/// read" holds it with the wait itself). +/// +/// Nothing is missed in between: what makes `done` true comes with a +/// landing ([`Line::landed`] counts them in [`Line::landings`]), the wait +/// is for the next landing after the one the copy was taken at, and the +/// caller holds the submission lock, so no flight joins the line meanwhile. +fn relay_wait_apart(why: usize, take: impl Fn(&Line) -> S, done: impl Fn(&S) -> bool) { + if !line_apart() { + relay_wait(why, |line| done(&take(line))); + return; + } + let mut began = None; + wait_apart(&LINE, &LINE_LANDED, take, done, || { + LATE_STATS[1].fetch_add(1, Ordering::Relaxed); + LATE_STATS[why].fetch_add(1, Ordering::Relaxed); + began = Some((working(false), std::time::Instant::now(), crate::timeline::span(landing_wait(why)))); + }); + let Some((was_working, waiting, _waiting)) = began else { + return; + }; + stood(waiting); + working(was_working); + let us = waiting.elapsed().as_micros() as u64; + LATE_STATS[12].fetch_add(us, Ordering::Relaxed); + LATE_WAITED[why.min(WHY_RESULTS)].fetch_add(us, Ordering::Relaxed); SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed); #[cfg(feature = "diagnostics")] blamed(why, us); } +/// [`relay_wait_apart`]'s look and wait on `lock`, told by `landed`: what +/// `take` copies out under the lock is looked at by `done` without it, now +/// and after each landing past the one the copy was taken at, until it says +/// so. `waits` is called once, before the first wait, if there is one. +fn wait_apart( + lock: &Mutex, + landed: &std::sync::Condvar, + take: impl Fn(&Line) -> S, + done: impl Fn(&S) -> bool, + waits: impl FnOnce(), +) { + let mut seen = None; + let mut waits = Some(waits); + loop { + let copy = { + let mut line = lock.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(seen) = seen { + while line.landings == seen { + line = landed.wait(line).unwrap_or_else(|e| e.into_inner()); + } + } + seen = Some(line.landings); + take(&line) + }; + if done(©) { + return; + } + if let Some(waits) = waits.take() { + waits(); + } + } +} + +/// Whether [`relay_wait_apart`] looks without [`LINE`] +/// (`LEONIDA_LINE_APART=0`: under it, as before). Read once. +fn line_apart() -> bool { + crate::toggled!("LEONIDA_LINE_APART") +} + +/// The timeline's name for a [`relay_wait`] for `why`. +fn landing_wait(why: usize) -> &'static str { + match why { + WHY_SYNC => "waiting for landings: everything (a present, the sweep)", + WHY_VALUE => "waiting for landings: a memory value", + WHY_STALE => "waiting for landings: title memory changed under shader writes", + WHY_READ => "waiting for landings: title memory read", + WHY_MOST => "waiting for landings: lists in the air", + WHY_RESULTS => "waiting for landings: room in the compare's results", + WHY_FENCE => "waiting for landings: a blocking fence wait", + _ => "waiting for landings: another reason", + } +} + /// What the thread that lands flights fetches card copies' pieces with /// ([`relay`]): a list, a fence and an event of its own (the host's are /// behind the submission lock), and the memory the pieces come down to. @@ -4999,10 +4838,26 @@ struct RelayFetch { sent: u64, /// Buffer, mapping, bytes. buffer: Option<(ID3D12Resource, usize, u64)>, + /// The sizes of the last fetches into it ([`fetched::fit`]). + sizes: fetched::Sizes, /// Pieces caught while a later flight was writing them. suspects: torn::Suspects, /// What earlier fetches brought of flights not landed yet. had: crate::land::Had, + /// With [`landsame`]: what earlier fetches brought, by the last send + /// known to have gone to the queue ahead of each (not by flight: a + /// flight whose send is past it ran after the fetch, and its capture is + /// newer than those bytes; one up to it may have run before). + newer: crate::land::Had, +} + +/// What the thread that lands flights asks of the system for itself before +/// anything else: the fast cores, and above normal while +/// `crate::cores::relay_raised` says so (it ran at normal before, among the +/// title's busy threads, while the title spun on the fences it sets). +pub(crate) fn relay_thread_setup() -> crate::cores::Priority { + crate::cores::keep_on_fast_cores("leonida-relay"); + crate::cores::Priority::following(crate::cores::relay_raised) } /// The thread that lands flights ([`relay`]): as soon as the card has run @@ -5011,8 +4866,9 @@ struct RelayFetch { /// the card, or for a flight. It takes neither the submission lock nor /// anything a caller of [`Host::settle`] may hold: resetting the landed /// lists and looking at what queues hold are left to [`late_helper`]. +/// It runs above normal with `LEONIDA_RELAY_PRIORITY=1` ([`relay_thread_setup`]). fn relay_worker() { - crate::cores::keep_on_fast_cores("leonida-relay"); + let mut priority = relay_thread_setup(); let Some(host) = host() else { return; }; @@ -5022,6 +4878,7 @@ fn relay_worker() { }; let mut fetch: Option = None; loop { + priority.keep(); let next = { let mut line = line(); loop { @@ -5048,19 +4905,7 @@ fn relay_worker() { // The first thing is a flight the card has not run. break Err(fences[0].unwrap_or(0)); } - line.settling = true; - let items: Vec = line.line.drain(..n).collect(); - line.in_hand = items - .iter() - .filter_map(|l| match l { - Late::Write(at, what, bytes) => Some((*at, *what, *bytes)), - _ => None, - }) - .collect(); - if card_steps::stage() > 0 { - line.landing = card_steps::writers(&items); - } - break Ok(items); + break Ok(line.take_landable(n)); } }; match next { @@ -5174,165 +5019,17 @@ impl RelayBack { } } -/// For the frame-rate line, with [`late`]: what the line of flights did -/// per frame since the last one. -fn late_line(frames: f64) { - if !late() { - return; - } - if upcheck::cross_on() { - let n = CROSS_SETTLES.swap(0, Ordering::Relaxed) as f64 / frames; - tracing::info!("relay cross settles per frame (LEONIDA_RELAY_CROSS=1): {n:.1}"); - } - let s: Vec = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); - tracing::info!( - "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \ - settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \ - title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \ - a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \ - bottom-of-pipe writes (LEONIDA_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \ - {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights", - s[0], - s[1], - if s[1] > 0.0 { s[11] / s[1] } else { 0.0 }, - s[12] / 1000.0, - s[WHY_SYNC], - s[WHY_CARD_DONE], - s[WHY_VALUE], - s[WHY_STALE], - s[WHY_READ], - s[15], - s[16], - s[17], - s[WHY_RUN], - late_most(), - s[WHY_MOST], - s[WHY_WRITES], - s[WHY_FENCE], - s[13], - s[14], - ); - { - let w: Vec = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect(); - tracing::info!( - "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \ - the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \ - title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}", - w[WHY_SYNC], - w[WHY_CARD_DONE], - w[WHY_VALUE], - w[WHY_STALE], - w[WHY_READ], - w[WHY_RUN], - w[WHY_MOST], - w[WHY_WRITES], - w[WHY_FENCE], - ); - } - if relay() { - let r: Vec = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); - tracing::info!( - "the relay per frame (LEONIDA_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \ - beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \ - fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \ - \"settles\" above are waits of other threads for it)", - r[1], - r[0], - r[2] / 1000.0, - r[3] / 1000.0, - r[4] / 1000.0, - ); - if send::own() { - let t: Vec = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); - tracing::info!( - "bytes of submissions' own sent up per frame (LEONIDA_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \ - taking them out of the CPU sides", - t[0] / (1 << 20) as f64, - t[1], - t[2], - t[3] / 1000.0, - ); - } - let t: Vec = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); - if t[0] > 0.0 { - tracing::info!( - "fetched pieces checked per frame (LEONIDA_FETCH_CHECK): {:.1}, of which {:.2} were not what their flight ended with (caught while a later flight was at them, or title bytes went up meanwhile); {:.2} were found whole when fetched again", - t[0], - t[1], - t[2], - ); - } - } - crate::land::log(frames); - if place::on() { - let t: Vec = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); - tracing::info!( - "title buffer copies at their place in the lists, per frame (LEONIDA_COPIES_IN_PLACE): {:.1} of {:.1} KB, {:.1} of them out of what shaders wrote; {:.2} copies into textures out of what shaders wrote", - t[0], - t[1] / 1024.0, - t[2], - t[3], - ); - #[cfg(feature = "diagnostics")] - { - let ahead = place::AHEAD.swap(0, Ordering::Relaxed) as f64 / frames; - if ahead > 0.0 { - tracing::info!( - "copies at their place whose bytes wait for flights, read on the CPU only ahead of them, per frame \ - (LEONIDA_PLACED_READERS; 0 holds these too): {ahead:.2} submissions not held for flights" - ); - } - } - } - card_steps::log(frames); - read_backs_line(frames); - batch_scratch_line(frames); - allocator_trim_line(); - dynamic_wait_line(frames); - crate::draw::waits_line(frames); - #[cfg(feature = "diagnostics")] - crate::texture::alias_line(frames); - #[cfg(feature = "diagnostics")] - crate::draw::dispatch_sizes_line(frames); - #[cfg(feature = "diagnostics")] - crate::draw::indirect_runs_line(frames); - #[cfg(feature = "diagnostics")] - sync_callers::line(frames); - #[cfg(feature = "diagnostics")] - gate_line(frames); - #[cfg(feature = "diagnostics")] - crate::draw::batch_why_line(frames); - crate::watch::port_guard_line(frames); - #[cfg(feature = "diagnostics")] - crate::watch::fault_asks_line(frames); - #[cfg(feature = "diagnostics")] - retire_waits_line(frames); - #[cfg(feature = "diagnostics")] - buffers_made::line(); - #[cfg(feature = "diagnostics")] - crate::residency::line(); - crate::port_journal::line(frames); - crate::port::log(frames); - crate::port_cbv::log(frames); - crate::picked::log(frames); - #[cfg(feature = "diagnostics")] - log_blame(frames); - if late_exact() { - let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames); - tracing::info!( - "title bytes put in under flights' shader writes per frame (LEONIDA_LATE_WAIT=2): {pages:.0} pages looked at, \ - {runs:.0} changed runs, {:.2} MB", - bytes / (1 << 20) as f64 - ); - } -} - pub(crate) mod aside; pub(crate) mod awake; +pub(crate) mod bar; #[cfg(feature = "diagnostics")] pub(crate) mod buffers_made; +pub(crate) mod batch_tables; +pub(crate) use batch_tables::table_card as batch_table_card; mod card_steps; pub(crate) mod indirects; +// Host lists' preludes made ahead, off the submitting thread (`LEONIDA_PRELUDE_POOL`). +pub(crate) mod preludes; // Leonida: the dot letters of the panel and the F1 settings menu. mod font; #[cfg(feature = "diagnostics")] @@ -5344,8 +5041,22 @@ mod menu; // Leonida: the trainer menu laid over the picture (`leonida-menu`, F4). mod trainer; mod place; +mod fetched; +mod landsame; +/// Where memory the CPU fills and the card reads is best put on this PC +/// (a benchmark, ignored by default). +#[cfg(test)] +mod comparecost; +#[cfg(test)] +mod placement; mod send; +mod summary; +// For the frame line, with `LEONIDA_CLOSE_SUMMARY=check` (`crate::copystat`). +#[cfg(feature = "diagnostics")] +pub(crate) use summary::line as summary_line; +mod sendring; pub(crate) use send::{goes_as_words, words_under}; +pub(crate) use send::{last_number as send_number, numbered as send_numbered, reached as send_reached, wait as send_wait}; // For the frame line, with `LEONIDA_SEND_TAKE_BESIDE=check` (`crate::copystat`). #[cfg(feature = "diagnostics")] pub(crate) use send::beside_line as send_beside_line; @@ -5355,111 +5066,60 @@ mod torn; #[cfg(feature = "diagnostics")] mod traffic; pub(crate) mod upcheck; +// What wrote the card side of copies the up-copy check keeps flagging (`LEONIDA_UNDECLARED_TRACE`). +#[cfg(feature = "diagnostics")] +pub(crate) mod undeclared; #[cfg(feature = "diagnostics")] mod stamps; +// What our lists over copies in the card's memory take there (`LEONIDA_CARD_OWN_TIMES`). +#[cfg(feature = "diagnostics")] +mod owntimes; #[cfg(feature = "diagnostics")] pub(crate) use stamps::{timeline_ready, timeline_restart, timeline_stamps}; +mod buffers; +mod compare; +// The compare in the call of the submission's last lists (`LEONIDA_COMPARE_JOIN`). +mod compare_ecl; +pub(crate) use compare::CARD_COMPARE; +#[cfg(test)] +pub(crate) use compare::piece_hash; +use compare::{ + ComparePass, RESULTS_ROOM, ResultArea, card_pass, compare_join, compare_ring, compare_share, + joined_compares, shares_piece, unshared_compares, +}; +#[cfg(test)] +use compare::{ResultRing, TEST_SHARE}; +mod lines; +#[cfg(feature = "diagnostics")] +use lines::split_line; +use lines::{card_clock_line, late_line}; +mod planes; +#[cfg(test)] +pub(crate) use planes::plane_root_signature; +use planes::{record_plane_pass, record_twin_copy}; +mod present; +#[cfg(test)] +use present::planes_format; +use present::Presenter; +pub(crate) use present::{METER_FPS_TENTHS, swap_format}; #[cfg(test)] -mod late_tests { - use super::{continues, join_ranges, touches}; +mod declared_by_copy_tests; - #[test] - fn a_late_texture_readback_blocks_a_following_cpu_copy() { - use super::{INFINITE, WHY_READ, WaitForSingleObject, blocked_by, host, read_backs}; +#[cfg(test)] +mod line_cover_tests; - let Some(host) = host() else { - eprintln!("no D3D12 device; texture readback dependency not tested"); - return; - }; - let mut title = [0u8; 64]; - let producer = host.new_list().unwrap(); - let (upload, upload_bytes) = host.upload_buffer(512).unwrap(); - let readback = host.read_back_buffer(512).unwrap(); - // SAFETY: the live upload mapping holds 512 bytes; the producer is - // open and both buffers hold the full transfer range. - unsafe { - upload_bytes.write_bytes(0x5a, 512); - producer.list.CopyBufferRegion(&readback, 0, &upload, 0, 512); - } - producer.defer_read_back(readback, title.as_mut_ptr(), [16, 2, 32]); - producer.close(); +#[cfg(test)] +mod line_apart_tests; - let (submitted, sent) = host.submit(&[&producer], &[], true).unwrap(); - // SAFETY: the submission lock is held and the event and fence are - // ours. The test keeps the producer, upload and destination alive. - unsafe { - host.fence.SetEventOnCompletion(*submitted, host.event).unwrap(); - WaitForSingleObject(host.event, INFINITE); - } - if let Some(plan) = sent.card { - host.card_done(plan); - } - if let Some(own) = sent.own { - own.landed(); - } - drop(submitted); +#[cfg(test)] +mod exact_wait_tests; - let consumer = host.new_list().unwrap(); - let mut taken = [0u8; 16]; - consumer.defer_copy(taken.as_mut_ptr(), title[32..].as_ptr(), taken.len()); - assert_eq!(blocked_by(&sent.texture_back_ranges, &[&consumer], false), Some(WHY_READ)); - assert_eq!(sent.texture_back_ranges, [(title.as_ptr() as usize, title.as_ptr() as usize + 48)]); - read_backs(&producer); - assert_eq!(title[..16], [0x5a; 16]); - assert_eq!(title[16..32], [0; 16]); - assert_eq!(title[32..48], [0x5a; 16]); - consumer.close(); - eprintln!("the pending texture readback blocked a later CPU copy"); - } - - /// Copies join only when both ends continue and the whole does not - /// overlap itself. - #[test] - fn copies_join_only_end_to_end_and_apart() { - // (destination, source, bytes) - assert!(continues((1000, 5000, 16), (1016, 5016, 32))); - assert!(continues((5000, 1000, 16), (5016, 1016, 32))); - // A gap, or only one side continues. - assert!(!continues((1000, 5000, 16), (1020, 5016, 32))); - assert!(!continues((1000, 5000, 16), (1016, 5020, 32))); - assert!(!continues((1000, 5000, 16), (1000, 5000, 16))); - // Together they would overlap: the second reads what the first wrote. - assert!(!continues((1000, 1016, 16), (1016, 1032, 16))); - assert!(!continues((1016, 1000, 16), (1032, 1016, 16))); - // They touch without overlapping. - assert!(continues((1000, 1032, 16), (1016, 1048, 16))); - assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8))); - } - - /// Ranges are found by what they hold, not by where they start, and a - /// range that only touches another's end does not touch it. - #[test] - fn ranges_touch_where_they_overlap() { - let mut ranges = Vec::new(); - join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]); - assert_eq!(ranges, [(10, 25), (40, 60)]); - join_ranges(&mut ranges, [(25, 40)]); - assert_eq!(ranges, [(10, 60)]); - let ranges = [(10usize, 25usize), (40, 60), (100, 101)]; - for (from, to, hit) in [ - (0, 10, false), - (0, 11, true), - (24, 25, true), - (25, 40, false), - (25, 41, true), - (59, 200, true), - (60, 100, false), - (100, 101, true), - (101, 500, false), - (30, 30, false), - (50, 50, false), - ] { - assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}"); - } - assert!(!touches(&[], 0, usize::MAX)); - } -} +#[cfg(test)] +mod exact_fence_tests; + +#[cfg(test)] +mod late_tests; /// Whether a title buffer copy that continues the one recorded before it /// in its list becomes one step with it (`LEONIDA_JOIN_COPIES=1`; off by @@ -5508,16 +5168,151 @@ fn declare_once() -> bool { *ON.get_or_init(|| std::env::var("LEONIDA_DECLARE_ONCE").map_or(true, |v| v != "0")) } +/// Of the ranges a submission's shaders may write and those picked +/// (`crate::picked`), what the compare for copies in the card's memory is +/// asked about: the declared ranges of copies in the card's memory, per copy, +/// with the picked ones written if they land; and the ranges only looked at, +/// of copies with no declared range here (that says it). +fn card_declared<'a>(declared: &[Declared], picked: &'a crate::picked::Ranges) -> (Vec, Vec<&'a crate::picked::Range>) { + let declared: Vec = declared.iter().filter(|(shadow, _)| shadow.carded()).cloned().collect(); + let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared }; + let looked: Vec<&crate::picked::Range> = + picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| std::sync::Arc::ptr_eq(s, &l.0))).collect(); + (declared, looked) +} + +/// A range the compare takes ([`card_asked`]): its copy, its title range, +/// its pieces, whether it is only looked at, and whether its first piece is +/// the last of the declared range before it ([`compare_share`]). +type CardAsked = (std::sync::Arc, (usize, usize), crate::shadow::CardSpan, bool, bool); + +/// The ranges of [`card_declared`] the compare takes, in order: per copy its +/// declared ranges joined (each byte once, as the copy-back joins them), then +/// those only looked at. +fn card_asked(declared: &[Declared], looked: &[&crate::picked::Range]) -> Vec { + let share = compare_share(); + let mut asked = Vec::new(); + for (shadow, ranges) in declared { + let mut sorted = ranges.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + let mut last: Option = None; + for (from, to) in spans { + if let Some(span) = shadow.card_span(from, to) { + let shares = share && last.is_some_and(|l| shares_piece(&l, &span)); + asked.push((shadow.clone(), (from, to), span, false, shares)); + last = Some(span); + } + } + } + for (shadow, from, len) in looked { + if let Some(span) = shadow.card_span(*from, from + len) { + asked.push((shadow.clone(), (*from, from + len), span, true, false)); + } + } + asked +} + +/// What the compare for copies in the card's memory is asked about by a +/// submission, gathered once ([`card_declared`], then [`card_asked`], which +/// clone and sort every declared range): the submission waits for room in +/// the compare's results by it (`Host::card_results_short`), then places it +/// (`Host::card_before`). Neither depends on what happens between the two +/// (a copy's pieces are fixed by its place; whether it has the hashes from +/// before is asked when it is placed). +struct CardAsk<'a> { + declared: Vec, + looked: Vec<&'a crate::picked::Range>, + asked: Vec, +} + +/// See [`CardAsk`]; `None` without copies in the card's memory +/// ([`crate::shadow::cards`]). +fn card_ask<'a>(declared: &[Declared], picked: &'a crate::picked::Ranges) -> Option> { + if !crate::shadow::cards() { + return None; + } + let (declared, looked) = card_declared(declared, picked); + let asked = card_asked(&declared, &looked); + Some(CardAsk { declared, looked, asked }) +} + /// The ranges the shaders of `runs` may write, per host copy, as declared. /// One list's lock at a time: a submission may name a list twice. fn declared_writes(runs: &[&HostList]) -> Vec { + let Some(sums) = summary::all(runs) else { + return declared_writes_steps(runs); + }; + let declared = summary::declared(&sums); + if summary::mode() == summary::Mode::Check { + let steps = declared_writes_steps(runs); + let keys = |all: &[Declared]| -> Vec<(usize, Vec<(usize, usize)>)> { + all.iter().map(|(shadow, ranges)| (std::sync::Arc::as_ptr(shadow) as usize, ranges.clone())).collect() + }; + summary::compared("what shaders may write", keys(&steps) == keys(&declared)); + return steps; + } + declared +} + +/// What a submission of `runs` asks the write watch about (`LEONIDA_ASK_ONCE`; +/// without [`list_fronts`]' spans): per copy they refresh that is asked about +/// ([`crate::shadow::Shadow::asked_ahead`]), the span of all its refreshes. By +/// the lists' summaries ([`summary`]: each copy asked once whether it is +/// asked about), else by their steps. +fn asked_spans(runs: &[&HostList]) -> ByCopy<(usize, usize)> { + let asked = crate::shadow::Shadow::asked_ahead; + let Some(sums) = summary::all(runs) else { + return asked_steps(runs, asked); + }; + if summary::mode() == summary::Mode::Check { + // (Both by the same answer per copy: [`summary::once`].) + let asked = summary::once(asked); + let spans = summary::asked(&sums, &asked); + let steps = asked_steps(runs, &asked); + let same = steps.len() == spans.len() && steps.iter().all(|(k, v)| spans.get(k) == Some(v)); + summary::compared("what the write watch is asked about", same); + return steps; + } + summary::asked(&sums, asked) +} + +/// [`asked_spans`] by the steps of `runs`: per copy they refresh that `asked` +/// says is asked about, the span of all its refreshes. +fn asked_steps(runs: &[&HostList], asked: impl Fn(&crate::shadow::Shadow) -> bool) -> ByCopy<(usize, usize)> { + let mut spans: ByCopy<(usize, usize)> = ByCopy::default(); + for list in runs { + let deferred = list.deferred(); + summary::walked(deferred.copies.len()); + for step in &deferred.copies { + if let Step::Refresh(shadow, address, len) = step + && asked(shadow) + { + let span = spans.entry(std::sync::Arc::as_ptr(shadow) as usize).or_insert((*address, *address + *len)); + *span = (span.0.min(*address), span.1.max(*address + *len)); + } + } + } + spans +} + +/// [`declared_writes`] by the steps of `runs`. +fn declared_writes_steps(runs: &[&HostList]) -> Vec { let mut back: Vec = Vec::new(); // Where each copy is in it, and the ranges seen: dispatches declare the // same ranges thousands of times a frame. let mut places: ByCopy = ByCopy::default(); let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault>::default(); for list in runs { - for step in &list.deferred().copies { + let deferred = list.deferred(); + summary::walked(deferred.copies.len()); + for step in &deferred.copies { if let Step::GpuWrite(shadow, address, len) = step { let key = std::sync::Arc::as_ptr(shadow) as usize; if !seen.insert((key, *address, *len)) { @@ -5761,6 +5556,8 @@ impl Host { })() }; LISTS[1].fetch_add(1, Ordering::Relaxed); + #[cfg(test)] + preludes::MADE_HERE.with(|n| n.set(n.get() + 1)); match made { Ok(prelude) => Some(prelude), Err(e) => { @@ -5923,10 +5720,7 @@ impl Host { } let code = code.ok_or_else(windows::core::Error::empty)?; let list = || self.make_prelude().ok_or_else(windows::core::Error::empty); - // A megabyte of results: 262,144 pieces, 16 GB of declared ranges - // in one submission. - const RESULTS: u64 = 1 << 20; - let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?; + let (differs, data) = self.shared_buffer(CARD_RESULTS).ok_or_else(windows::core::Error::empty)?; name(&differs, || "card compare results".into()); // SAFETY: the blob's own bytes; the root signature is inside the // shader. @@ -5949,10 +5743,13 @@ impl Host { fetch: list()?, root, pso, - differs: (differs, data as usize, RESULTS), + differs: (differs, data as usize, CARD_RESULTS), fetched: None, - taken: 0, - out: 0, + fetched_sizes: fetched::Sizes::default(), + results: ResultArea::new((CARD_RESULTS / 4) as u32, compare_ring(), relay()), + land: None, + #[cfg(feature = "diagnostics")] + stamps: Vec::new(), }) } } @@ -5964,22 +5761,16 @@ impl Host { /// this submission's shaders may write get a compare to run after its /// lists. `None` if there is nothing to do. /// + /// `ask`: the declared ranges, with those picked that may be written + /// too, and the ranges to look at (`crate::picked`), as the compare + /// takes them ([`card_ask`]; `None` without copies in the card's + /// memory). /// `flown`: the submission is sent ahead with [`relay`]. Its compare /// then stores the hashes it makes (see [`flagged_pieces`] and /// `relay`). - /// `picked`: ranges that may be written too, and ranges to look at - /// (`crate::picked`). - fn card_before(&self, declared: &[Declared], picked: &crate::picked::Ranges, flown: bool) -> Option { + fn card_before(&self, ask: Option>, flown: bool) -> Option { use std::sync::Arc; - if !crate::shadow::cards() { - return None; - } - // The ranges this submission's shaders may write, per copy. - let declared: Vec = declared.iter().filter(|(shadow, _)| shadow.carded()).cloned().collect(); - let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared }; - // (Of a copy with a declared range here, that says it.) - let looked: Vec<&crate::picked::Range> = - picked.looked.iter().filter(|l| !declared.iter().any(|(s, _)| Arc::ptr_eq(s, &l.0))).collect(); + let CardAsk { declared, looked, asked } = ask?; // With the relay: the order of the queue is held from here until // what is taken is on the queue, and the taking is numbered. let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); @@ -5990,6 +5781,9 @@ impl Host { } None => 0, }; + // Once for the plan, counted before its send's number can be seen + // (`landsame::capturing`). + let capturing = landsame::Capturing::decide(flown); let gathering = crate::timeline::span("copies in the card's memory: what changed"); let mut dirty = crate::shadow::card_dirty(sent_as); gathering.end(); @@ -6017,8 +5811,12 @@ impl Host { let mut looks = None; // The bytes as they are now, whatever later submissions put there. let taking = crate::timeline::span("copies in the card's memory: taken"); - let own = if send::own() { send::take(self, &dirty) } else { None }; + // (Under the card's work: numbers are given and signalled in order.) + let number = send::number(self, !dirty.is_empty()); + let own = if send::own() { send::take(self, &dirty, number) } else { None }; taking.end(); + #[cfg(feature = "diagnostics")] + let mut stamps = if dirty.is_empty() { None } else { owntimes::take(self, &mut work.stamps, owntimes::on()) }; if !dirty.is_empty() { let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else { fail(format_args!("no host list to bring host copies in the card's memory up to date")); @@ -6032,6 +5830,10 @@ impl Host { (|| -> windows::core::Result<()> { allocator.Reset()?; list.Reset(allocator, None)?; + #[cfg(feature = "diagnostics")] + if let Some(stamps) = &stamps { + stamps.sends_from(list); + } // (`send::take`'s long copies run beside this recording, // which names offsets only; with the up-copy check they // are waited for first, as before.) @@ -6057,7 +5859,7 @@ impl Host { }; if own.is_none() { for &(a, b) in ranges { - list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64); + list.CopyBufferRegion(&shadow.buffer, a as u64, &staging, a as u64, (b - a) as u64); } } let bytes: u64 = ranges.iter().map(|&(a, b)| (b - a) as u64).sum(); @@ -6077,6 +5879,12 @@ impl Host { } } } + #[cfg(feature = "diagnostics")] + if let Some(stamps) = &stamps { + stamps.hashes_from(list); + } + #[cfg(feature = "diagnostics")] + let mut hash_passes = 0; if !sent.is_empty() { list.ResourceBarrier(&sent); } @@ -6114,10 +5922,18 @@ impl Host { let runs = if joins { crate::shadow::joined_piece_runs(runs) } else { runs }; CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::(), Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + hash_passes += runs.len() as u64; + } for run in runs { card_pass(list, &run, size as u32, 0, 0); } } + #[cfg(feature = "diagnostics")] + if let Some(stamps) = &mut stamps { + stamps.hashes_to(list, hash_passes); + } // The bytes the list sends are all there before it can // run (`send::take_beside`), and before the CPU sides // they come from are written again (the copies at their @@ -6128,6 +5944,11 @@ impl Host { } list.Close()?; self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); + // What it copies straight out of CPU sides is read once + // the card is past this (`send::direct`). + if number != 0 { + send::signal(self, number); + } Ok(()) })() }; @@ -6144,63 +5965,75 @@ impl Host { lists: used, sent_as, looks, - sends: own.map(send::Own::memory), + sends: own.and_then(send::Own::memory), + results: 0, + landing: None, + capturing, + hashed: 0, + #[cfg(feature = "diagnostics")] + stamps, }; // Each byte once, as the copy-back joins the declared ranges. The - // results go behind those of plans still in the air. - let mut at = work.taken; - for (shadow, ranges) in &declared { - let mut sorted = ranges.clone(); - sorted.sort_unstable(); - let mut spans: Vec<(usize, usize)> = Vec::new(); - for (from, to) in sorted { - match spans.last_mut() { - Some(last) if from <= last.1 => last.1 = last.1.max(to), - _ => spans.push((from, to)), - } - } - let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); - for (from, to) in spans { - let Some(span) = shadow.card_span(from, to) else { - continue; - }; - let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2; - plan.ranges.push(CardRange { - shadow: shadow.clone(), - declared: (from, to), - span, - at, - compared, - picked: false, - }); - if compared { - at += span.pieces; - } - } - } - for (shadow, from, len) in looked { - let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); - if let Some(span) = shadow.card_span(*from, from + len) - && twin - && u64::from(at + span.pieces) * 4 <= work.differs.2 - { - plan.ranges.push(CardRange { - shadow: shadow.clone(), - declared: (*from, from + len), - span, - at, - compared: true, - picked: true, - }); - at += span.pieces; - } - } - work.taken = at; + // results go in one run of the area, behind those of plans still in + // the air (`ResultArea::plan`); what does not fit there is fetched + // whole, and what is only looked at is left alone. + let twin = |shadow: &crate::shadow::Shadow| shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + let (placed, results) = + work.results.plan(asked, |(shadow, _, span, looked_only, shares)| (span.pieces, twin(shadow), *looked_only, *shares)); + plan.ranges = placed + .into_iter() + .map(|((shadow, range, span, looked_only, _), at, compared)| CardRange { shadow, declared: range, span, at, compared, picked: looked_only }) + .collect(); + plan.results = results; + RESULTS_ROOM.store(work.results.room(), Ordering::Relaxed); if plan.ranges.iter().any(|r| r.compared) { let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else { fail(format_args!("no host list for the compare of host copies in the card's memory")); }; + let passes = plan.ranges.iter().filter(|r| r.compared).filter_map(|r| { + let (Some((_, Some(before), _)), size) = (r.shadow.card_sides(), r.shadow.card_hash_size()) else { + return None; + }; + // SAFETY (both): live buffers. + let (buffer, hashes) = unsafe { (r.shadow.buffer.GetGPUVirtualAddress(), before.GetGPUVirtualAddress()) }; + Some(ComparePass { + buffer, + hashes, + size: size as u32, + span: r.span, + at: r.at, + // (What is only looked at keeps its hashes: what + // changed there is the next declared range's to land.) + mode: if flown && !r.picked { 2 } else { 1 }, + }) + }); + // Each piece once: a range on the last piece of the one before + // it begins after that piece (`compare_share`). + let asked_pieces: u64 = plan.ranges.iter().filter(|r| r.compared).map(|r| u64::from(r.span.pieces)).sum(); + let passes = joined_compares(unshared_compares(passes).into_iter(), compare_join()); + plan.hashed = passes.iter().map(|p| u64::from(p.span.pieces)).sum(); + CARD_PASSES[3].fetch_add(plan.hashed, Ordering::Relaxed); + CARD_PASSES[4].fetch_add(asked_pieces.saturating_sub(plan.hashed), Ordering::Relaxed); + // With `landsame`: the pieces flagged in the ranges it lands (the + // declared ones, mode 2) come down in this submission, as many + // as there is room for; its scan looks at exactly the flags of + // the passes that copy. As the plan was made to. + let landed: Vec = + if plan.capturing.is_some() { passes.iter().filter(|p| p.mode == 2).copied().collect() } else { Vec::new() }; + let land = if landed.is_empty() { + None + } else { + let psos = work.land.get_or_insert_with(|| landsame::make(&self.device, &work.root)).clone(); + let (list, base, end) = landsame::listed(landed.iter().map(|p| (p.at, p.span.pieces))); + psos.and_then(|psos| Some((psos, landsame::take(self, &list, base, end)?))) + }; let (allocator, list) = ✓ + #[cfg(feature = "diagnostics")] + if plan.stamps.is_none() { + plan.stamps = owntimes::take(self, &mut work.stamps, owntimes::on()); + } + #[cfg(feature = "diagnostics")] + let stamps = &mut plan.stamps; // SAFETY: the list's last run finished (its submission was // waited for, and it came back after that); live buffers; the // compare's own root signature. @@ -6218,59 +6051,71 @@ impl Host { }), }, }]); + // (Behind that barrier: the drain of the title's lists + // is not the compare's.) + #[cfg(feature = "diagnostics")] + if let Some(stamps) = stamps.as_ref() { + stamps.compare_from(list); + } list.SetComputeRootSignature(&work.root); list.SetPipelineState(&work.pso); list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); - let passes = plan.ranges.iter().filter(|r| r.compared).filter_map(|r| { - let (Some((_, Some(before), _)), size) = (r.shadow.card_sides(), r.shadow.card_hash_size()) else { - return None; - }; - Some(ComparePass { - buffer: r.shadow.buffer.GetGPUVirtualAddress(), - hashes: before.GetGPUVirtualAddress(), - size: size as u32, - span: r.span, - at: r.at, - // (What is only looked at keeps its hashes: what - // changed there is the next declared range's to land.) - mode: if flown && !r.picked { 2 } else { 1 }, - }) - }); - for pass in joined_compares(passes, compare_join()) { + for pass in &passes { list.SetComputeRootShaderResourceView(1, pass.buffer); list.SetComputeRootUnorderedAccessView(2, pass.hashes); card_pass(list, &pass.span, pass.size, pass.at, pass.mode); CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); } + if let Some((psos, landing)) = &land { + landsame::record(list, psos, landing, work.differs.0.GetGPUVirtualAddress(), &landed); + } + #[cfg(feature = "diagnostics")] + if let Some(stamps) = stamps.as_mut() { + stamps.compare_to(list, passes.len() as u64); + } list.Close()?; list.cast() })() }; + plan.landing = land.map(|(_, landing)| landing); match recorded { Ok(list) => plan.check = Some(list), Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")), } plan.lists.push((true, check)); } - work.out += 1; Some(plan) } - /// With [`relay`]: whether the compare's result area is half taken by - /// plans in the air. It starts from the beginning only when no plan is - /// out, so the caller lets the flights land first. + /// With [`relay`] and the whole area (`LEONIDA_COMPARE_RING=0`): whether + /// the compare's result area is half taken by plans in the air + /// ([`ResultArea::low`]). It starts from the beginning only when no plan + /// is out, so the caller lets the flights land first. fn card_results_low(&self) -> bool { - CARD_WORK - .lock() - .unwrap_or_else(|e| e.into_inner()) - .as_ref() - .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2) + CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|work| work.results.low()) + } + + /// With [`relay`] and the ring ([`compare_ring`]): the dwords the compare + /// of `ask` would take ([`Host::card_before`], counting every copy as + /// compared), if the ring has no run that long now. The caller + /// waits until flights have landed and given theirs back + /// ([`RESULTS_ROOM`]), rather than fetch the ranges that do not fit + /// whole; never if they ask for more than the whole ring + /// ([`ResultArea::short`]). + fn card_results_short(ask: Option<&CardAsk<'_>>) -> Option { + let room = RESULTS_ROOM.load(Ordering::Relaxed); + let ask = ask?; + if !compare_ring() || room == u32::MAX { + return None; + } + let want = ask.asked.iter().map(|a| u64::from(a.2.pieces - u32::from(a.4 && a.2.pieces > 0))).sum::(); + ResultArea::short(want, room, (CARD_RESULTS / 4) as u32) } /// The plan's submission has run and its results were read - /// ([`Host::card_back`]): its lists are free for the next plan. Called - /// when nothing of ours is on the card, so the compare's results start - /// from the beginning again. + /// ([`Host::card_back`], `relay_card_back`): its lists and its dwords of + /// the compare's results are free for the next plans + /// ([`ResultArea::give_back`]). fn card_done(&self, plan: CardPlan) { if let Some(looks) = plan.looks { looks.read(); @@ -6278,19 +6123,24 @@ impl Host { if let Some(memory) = plan.sends { send::give_back(memory); } + if let Some(landing) = plan.landing { + landsame::give_back(landing); + } + #[cfg(feature = "diagnostics")] + if let Some(stamps) = &plan.stamps { + owntimes::read(self, stamps); + } let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); let Some(work) = work.as_mut() else { return; }; + #[cfg(feature = "diagnostics")] + work.stamps.extend(plan.stamps); for (check, list) in plan.lists { if check { work.check.push(list) } else { work.sync.push(list) } } - work.out = work.out.saturating_sub(1); - // With the relay other plans may be on the card, their results - // not read yet: the area starts again only when none is out. - if !relay() || work.out == 0 { - work.taken = 0; - } + work.results.give_back(plan.results); + RESULTS_ROOM.store(work.results.room(), Ordering::Relaxed); } /// The relay's own list, fence, event for [`Host::relay_card_back`]. @@ -6329,8 +6179,10 @@ impl Host { event, sent: 0, buffer: None, + sizes: fetched::Sizes::default(), suspects: torn::Suspects::default(), had: crate::land::Had::default(), + newer: crate::land::Had::default(), }) } } @@ -6347,6 +6199,13 @@ impl Host { /// nothing is sent back up. `plans` come with the value signalled behind /// their flight. `meanwhile` is called while the fetch is on its way, if /// there is one. + /// + /// With [`landsame`] the pieces a plan's own submission copied down are + /// merged first, plan by plan, each as a fetch behind the plan's sends; + /// what is left (past its slots, not compared, wanted by a torn check, + /// or maybe older than an earlier fetch's bytes) is fetched as before and + /// merged after them; a captured piece an earlier fetch that ran after + /// its flight held whole is neither (`landsame::fate`). fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option, meanwhile: &mut dyn FnMut()) { use crate::land; let gathering = std::time::Instant::now(); @@ -6356,9 +6215,18 @@ impl Host { }; let mut pieces: Vec<(std::sync::Arc, usize, usize, u64)> = Vec::new(); let mut total = 0u64; + // With `landsame`, per plan in order: what its own submission copied + // down (copy, from, to, where it is), and the plan's send. + let mut captures: Vec<(Vec, u64)> = Vec::new(); + for (plan, _) in plans { + landsame::STATS[if plan.capturing.is_some() { 7 } else { 8 }].fetch_add(1, Ordering::Relaxed); + } if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) { fetch.had.landing(first); } + if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.0.sent_as).min()) { + fetch.newer.landing(first); + } // SAFETY: the mapping of the results. The compares of these plans // have run, and their dwords are given to no other plan before these // are done with (`card_done`). @@ -6366,34 +6234,65 @@ impl Host { if let Some(differs) = differs { // Pieces caught while a later flight was at them (`torn`). let suspects = fetch.as_ref().map(|f| &f.suspects); + // What earlier fetches brought newer than a flight's capture. + let newer = fetch.as_ref().map(|f| &f.newer); let mut seen = std::collections::HashSet::new(); for &(plan, behind) in plans { plan.picked_found(differs); + // The pieces its submission copied down, by copy and piece: + // where the slot is, and the offset in the copy it begins at. + let slots = plan.landing.as_ref().map(|l| landsame::slots_of(l, &plan.ranges)).unwrap_or_default(); let flags: Vec<(usize, u32, bool)> = plan .ranges .iter() .filter(|r| !r.picked) .flat_map(|r| { + let slots = &slots; (0..r.span.pieces).map(move |p| { + let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d)); let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged)); - (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted) + (copy, r.span.first + p, wanted && !slots.contains_key(&(copy, r.span.first + p))) }) }) .collect(); let fetched = flagged_pieces(&flags); + let mut captured: Vec = Vec::new(); + let mut seen_here = std::collections::HashSet::new(); for r in plan.ranges.iter().filter(|r| !r.picked) { let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; if upcheck::on() { upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize); } for p in 0..r.span.pieces { - if fetched.binary_search(&(copy, r.span.first + p)).is_err() { + let slot = slots.get(&(copy, r.span.first + p)).copied(); + if slot.is_none() && fetched.binary_search(&(copy, r.span.first + p)).is_err() { continue; } let (lo, hi) = r.shadow.card_piece(&r.span, p); + let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo); + // Held whole by a fetch that ran after the flight: + // left out. Maybe newer in an earlier fetch: fetched + // again, newer still (`landsame::fate`). + let fate = slot.filter(|_| lo < hi).map(|_| { + landsame::fate(fetch.as_ref().map(|f| &f.had), newer, behind, plan.sent_as, key) + }); + if fate == Some(landsame::Fate::Held) { + landsame::STATS[6].fetch_add(1, Ordering::Relaxed); + continue; + } + if let Some((at, from)) = slot + && fate == Some(landsame::Fate::Merged) + { + if seen_here.insert((copy, lo, hi)) { + if upcheck::on() { + upcheck::fetched(r.shadow.id(), lo); + } + captured.push((r.shadow.clone(), lo, hi, at + (lo - from))); + } + continue; + } if lo < hi && !seen.contains(&(copy, lo, hi)) { - let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo); if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) { land::count(land::stat::HAD, 1); land::count(land::stat::HAD_BYTES, (hi - lo) as u64); @@ -6411,6 +6310,9 @@ impl Host { } crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); } + if !captured.is_empty() { + captures.push((captured, plan.sent_as)); + } } } if land::on() { @@ -6430,6 +6332,28 @@ impl Host { .collect(); } land::spent(land::stat::GATHER, gathering); + // What the flights' own submissions brought down, first: a fetch + // below is newer than any of it. + let captured = !captures.is_empty(); + let captured_written = if captured { + let _landing = crate::timeline::span("landing: merging pieces landed in their submission"); + let merging = std::time::Instant::now(); + crate::shadow::elide::fetched(captures.iter().flat_map(|c| c.0.iter()).map(|(shadow, lo, hi, _)| (shadow, *lo, *hi))); + if let Some(f) = fetch.as_mut() { + f.suspects.landed(captures.iter().flat_map(|c| c.0.iter()).map(|(shadow, lo, _, _)| (shadow.id(), shadow.card_piece_of(*lo)))); + } + let written = landsame::merge(&captures); + land::spent(land::stat::CARD, merging); + written + } else { + 0 + }; + COPY_BACK[1].fetch_add(captured_written, Ordering::Relaxed); + // The notes of sends a later flight's capture is merged against stay + // (`landsame`): only those up to these flights' go, while a plan alive + // was made to capture (read after the count `after` is, whatever the + // switch says now). + let forget = |after: u64| landsame::forgotten(after, plans.iter().map(|p| p.0.sent_as), landsame::capturing()); if fetch.is_none() { *fetch = self.make_relay_fetch(); } @@ -6456,16 +6380,16 @@ impl Host { true => behind, false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()), }; - crate::shadow::relay_fetched(after); + crate::shadow::relay_fetched(forget(after)); + if captured { + landsame::STATS[4].fetch_add(1, Ordering::Relaxed); + } return; } let Some(f) = fetch.as_mut() else { fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (LEONIDA_RELAY=1)")); }; - if f.buffer.as_ref().is_none_or(|b| b.2 < total) { - let size = total.next_multiple_of(16 << 20); - f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); - } + fetched::fit(self, &mut f.buffer, total, &mut f.sizes); let Some((buffer, data, _)) = f.buffer.clone() else { fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, LEONIDA_RELAY=1)")); }; @@ -6477,7 +6401,7 @@ impl Host { // been given to the queue. On the copy queue, those landed here. let ahead = match copy_queue { Some(_) => 0, - None => line().target, + None => landsame::line_target(), }; // SAFETY: the list's last run was waited for by this thread; live // buffers (the copies are held by the plans); the fence and the @@ -6522,6 +6446,21 @@ impl Host { Ok(after) => after, Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, LEONIDA_RELAY=1)")), }; + // The last send known to have gone to the queue ahead of the fetch + // (`landsame`): a flight whose send is past it ran after the fetch, + // and its capture is newer than these bytes; one up to it may have + // run before. On the drawing queue that is `after`, the count the + // fetch went to the queue under (a later flight's sends, and its + // lists after them, wait for that lock). On the copy queue the fetch + // ran beside later submissions: only flights sent after it was done + // are known to have run after it. (Noted by the count after the wait + // on the drawing queue too, every flight sent meanwhile, run after + // the fetch, had its capture fetched again, and that fetch the next + // flights': one fetch per landing for good.) + let newer_as = match copy_queue { + Some(_) => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()), + None => after, + }; let us = waiting.elapsed().as_micros() as u64; RELAY_STATS[3].fetch_add(us, Ordering::Relaxed); { @@ -6586,9 +6525,17 @@ impl Host { ahead, pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)), ); + // For a later capture, by the plans alive (read after `newer_as`: + // a capturing plan sent up to it is counted, `landsame`). + if landsame::capturing() { + f.newer.fetched( + newer_as, + pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)), + ); + } } // Sends up to `after` are of no use to any later merge. - crate::shadow::relay_fetched(after); + crate::shadow::relay_fetched(forget(after)); } /// [`relay`], on the thread that lands flights: `items` are the first @@ -6642,15 +6589,11 @@ impl Host { } let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect(); // (Each byte once: the ranges are joined.) - let mut back: Vec = Vec::new(); - for flight in &flights { - for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) { - match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { - Some((_, all)) => all.extend_from_slice(ranges), - None => back.push((shadow.clone(), ranges.clone())), - } - } - } + let back = declared_by_copy( + flights.iter().flat_map(|f| f.back.iter()).filter(|(shadow, _)| !shadow.carded()), + |shadow| std::sync::Arc::as_ptr(shadow) as usize, + false, + ); let mut hand_back = relay_hand_back(&back); stage.next("landing: copies in the card's memory"); self.relay_card_back(&plans, fetch, &mut || { @@ -6726,39 +6669,7 @@ impl Host { self.log_messages(); crate::land::spent(crate::land::stat::REST, telling); RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); - { - let mut line = line(); - let Line { - line: items, - written, - lists, - settling, - poke, - landed: kept, - in_hand, - landing, - .. - } = &mut *line; - kept.extend(landed); - in_hand.clear(); - landing.clear(); - // What is still in the air, from the flights that are. - written.clear(); - *lists = 0; - let mut ranges = Vec::new(); - for item in items.iter() { - if let Late::Run(flight) = item { - *lists += flight.order.len().max(1); - ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied())); - ranges.extend(flight.texture_back_ranges.iter().copied()); - } - } - join_ranges(written, ranges); - *settling = false; - // The landed lists are reset, and what queues hold looked at, - // by the helper thread (they take locks a waiter may hold). - *poke = true; - } + line().landed(landed); LINE_MOVED.notify_all(); LINE_LANDED.notify_all(); } @@ -6807,10 +6718,7 @@ impl Host { let mut written = vec![0usize; plan.ranges.len()]; crate::shadow::elide::fetched(pieces.iter().map(|&(i, lo, hi, _)| (&plan.ranges[i].shadow, lo, hi))); if !pieces.is_empty() { - if work.fetched.as_ref().is_none_or(|f| f.2 < total) { - let size = total.next_multiple_of(16 << 20); - work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); - } + fetched::fit(self, &mut work.fetched, total, &mut work.fetched_sizes); let Some((fetched, data, _)) = &work.fetched else { fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)")); }; @@ -6974,30 +6882,23 @@ impl Host { }; let told = !sent.writes.is_empty(); let sizes = crate::memory::asked_sizes(order.iter().map(|&i| lists[i].host())); + // (Made before the line's lock: [`Flight::joined`].) + let flight = Flight { + number: sent.number, + fence: *submitted, + lists, + order, + card: sent.card, + joined: if line_cover() { flight_writes(&sent.back, &sent.texture_back_ranges) } else { Vec::new() }, + back: sent.back, + own: sent.own, + texture_back_ranges: sent.texture_back_ranges, + }; let most = { let mut line = line(); - let Line { line: items, written, lists: flying, target, .. } = &mut *line; - join_ranges( - written, - sent.back - .iter() - .flat_map(|(_, ranges)| ranges.iter().copied()) - .chain(sent.texture_back_ranges.iter().copied()), - ); - *flying += order.len(); - *target = *submitted; - items.push(Late::Run(Flight { - number: sent.number, - fence: *target, - lists, - order, - card: sent.card, - back: sent.back, - own: sent.own, - texture_back_ranges: sent.texture_back_ranges, - })); - items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); - *flying >= late_most() + // (`order` is not empty: `Host::execute_parts`.) + line.push_flight(flight, sent.writes); + line.lists >= late_most() }; LATE_STATS[0].fetch_add(1, Ordering::Relaxed); RELAY_MOVED.notify_one(); @@ -7133,30 +7034,18 @@ impl Host { }; then(*submitted); let number = sent.number; - { - let mut line = line(); - let Line { line: items, written, lists: flying, target, .. } = &mut *line; - join_ranges( - written, - sent.back - .iter() - .flat_map(|(_, ranges)| ranges.iter().copied()) - .chain(sent.texture_back_ranges.iter().copied()), - ); - *flying += 1; - *target = *submitted; - items.push(Late::Run(Flight { - number, - fence: *target, - lists: Vec::new(), - order: Vec::new(), - card: sent.card, - back: sent.back, - own: sent.own, - texture_back_ranges: sent.texture_back_ranges, - })); - items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); - } + let flight = Flight { + number, + fence: *submitted, + lists: Vec::new(), + order: Vec::new(), + card: sent.card, + joined: if line_cover() { flight_writes(&sent.back, &sent.texture_back_ranges) } else { Vec::new() }, + back: sent.back, + own: sent.own, + texture_back_ranges: sent.texture_back_ranges, + }; + line().push_flight(flight, sent.writes); LATE_STATS[0].fetch_add(1, Ordering::Relaxed); LINE_MOVED.notify_one(); RELAY_MOVED.notify_one(); @@ -7187,7 +7076,7 @@ impl Host { // nothing is being landed. Every point that settled before // comes here, so each still sees title memory, fences and // bottom-of-pipe values as after a settle. - relay_wait(why, |line| line.line.is_empty() && !line.settling); + relay_wait(why, line_drained); return; } let was_working = working(true); @@ -7202,6 +7091,8 @@ impl Host { } line.settling = true; line.written.clear(); + line.cover.0.clear(); + line.landing_joined.clear(); line.lists = 0; std::mem::take(&mut line.line) }; @@ -7233,7 +7124,7 @@ impl Host { } let gpu = waiting.elapsed(); LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); - LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + LATE_WAITED[why.min(WHY_RESULTS)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); #[cfg(feature = "diagnostics")] crate::copystat::card_waited(gpu.as_micros() as u64, || { @@ -7259,27 +7150,21 @@ impl Host { submitting(3, flights); let copying = std::time::Instant::now(); let mut seen = std::collections::HashSet::new(); - let mut back: Vec = Vec::new(); - for item in &items { - let Late::Run(flight) = item else { - continue; - }; + let flown = || { + items.iter().filter_map(|item| match item { + Late::Run(flight) => Some(flight), + _ => None, + }) + }; + for flight in flown() { if let Some(card) = &flight.card { self.card_back(card, submitted, &mut seen); } - for (shadow, ranges) in &flight.back { - match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { - Some((_, all)) => { - for range in ranges { - if !all.contains(range) { - all.push(*range); - } - } - } - None => back.push((shadow.clone(), ranges.clone())), - } - } } + // Each declared range of a copy once, as declared + // (`Shadow::copy_back_done` takes them so). + let back = + declared_by_copy(flown().flat_map(|f| f.back.iter()), |shadow| std::sync::Arc::as_ptr(shadow) as usize, true); hand_back(&back); COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed); } @@ -7344,7 +7229,7 @@ impl Host { for _ in 0..3 { #[cfg(feature = "diagnostics")] blame_stale(&stale); - relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to))); + relay_wait_apart(WHY_STALE, |_| (), |()| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to))); crate::watch::ask_once(ranges); stale = stale_under_flights(runs); if stale.is_empty() { @@ -7418,9 +7303,15 @@ impl Host { if relay_exact() && why == WHY_READ { // Only until the flights that may write what is read have // landed: their copy-back's end, not the card's other work. - relay_wait(why, |line| { - blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs) - }); + // The steps looked at without the line's lock + // ([`relay_wait_apart`]); by their summaries, taken once + // here for every look ([`summary`]). + let sums = summary::all(runs); + relay_wait_apart( + why, + |line| (line.written.clone(), card_steps::copies(line)), + |(written, copies)| blocked_by_in(written, runs, sums.as_deref(), false).is_none() && !card_steps::copied_read(copies, runs), + ); } else { self.settle(&mut submitted, why); } @@ -7449,26 +7340,30 @@ impl Host { stage.next("submit: the sweep"); let behind = late && flying(); // Before this submission counts as started: what the sweep lets go - // of is named by no list, and nothing runs now (behind flights the - // sweep waits for a submission that finds none in the air: there is - // one at every present). + // of is named by no list. Behind flights it runs without them + // settled ([`sweep_no_settle`]) with the present sent ahead; without + // that it waits for a submission that finds none in the air (there + // is one at every present). static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - if !behind { - if upcheck::on() { - upcheck::at_rest(self); - } - sweep(); - SWEPT.store(now_ms(), Ordering::Relaxed); - } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 { + let since = now_ms().saturating_sub(SWEPT.load(Ordering::Relaxed)); + let (sweeps, settles) = sweep_now(behind, late_free_present(), since, sweep_wants_rest()); + if settles { // With the present sent ahead nothing else brings a moment - // with nothing in the air: one is made for the sweep. + // with nothing in the air: one is made for what wants it + // ([`sweep_wants_rest`]). self.settle(&mut submitted, WHY_SYNC); - if upcheck::on() { + } + if sweeps { + if upcheck::on() && (!behind || settles) { upcheck::at_rest(self); } sweep(); SWEPT.store(now_ms(), Ordering::Relaxed); } + // Copies whose CPU side was title memory the title freed, protected + // or had mapped anew get one of their own before this submission's + // refreshes (`crate::shadow::from_title`, `LEONIDA_CARD_FROM_TITLE`). + crate::shadow::sources_going(); let behind = late && flying(); stage.next("submit: gathering what to ask about"); let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1; @@ -7506,22 +7401,8 @@ impl Host { ranges.extend(batch.spans.iter().filter(|s| s.0.asked_ahead()).map(|s| (s.1, s.2))); ranges } else { - let by_steps = || { - let mut spans: ByCopy<(usize, usize)> = ByCopy::default(); - for list in runs { - for step in &list.deferred().copies { - if let Step::Refresh(shadow, address, len) = step - && shadow.asked_ahead() - { - let span = spans - .entry(std::sync::Arc::as_ptr(shadow) as usize) - .or_insert((*address, *address + *len)); - *span = (span.0.min(*address), span.1.max(*address + *len)); - } - } - } - spans - }; + // (Or by the lists' summaries, [`asked_spans`].) + let by_steps = || asked_spans(runs); // (`list_fronts`: each list's refreshes per copy, found at its // close; `None` if one of the lists has none kept.) // (`check` asks every copy live, so that it compares what the steps give now.) @@ -7545,7 +7426,9 @@ impl Host { FrontsMode::Off => by_steps(), FrontsMode::On => by_fronts().unwrap_or_else(by_steps), FrontsMode::Check => { - let steps = by_steps(); + // (By the steps themselves, not the summaries, which + // are another thing kept at the close.) + let steps = asked_steps(runs, crate::shadow::Shadow::asked_ahead); if let Some(fronts) = by_fronts() { FRONTS_CHECK[1].fetch_add(1, Ordering::Relaxed); if fronts.len() != steps.len() || fronts.iter().any(|(k, v)| steps.get(k) != Some(v)) { @@ -7669,31 +7552,54 @@ impl Host { let flown = late && relay(); if flown && self.card_results_low() { let settling = std::time::Instant::now(); - self.settle(&mut submitted, WHY_MOST); + self.settle(&mut submitted, WHY_RESULTS); settled += settling.elapsed(); } // What shaders may write through views they pick: last, so that no // refresh of this submission leaves it alone. let picked = crate::picked::declare(runs); + let declared = declared_writes(runs); + let ask = card_ask(&declared, &picked); + // With the ring of results: until the oldest plans in the air have + // given back room enough for this one's ranges, not until nothing is + // in the air (`want` is at most the whole ring, which is free once + // nothing is: that is only a net). + if flown && let Some(want) = Self::card_results_short(ask.as_ref()) { + let settling = std::time::Instant::now(); + relay_wait(WHY_RESULTS, |line| { + RESULTS_ROOM.load(Ordering::Relaxed) >= want || (line.line.is_empty() && !line.settling) + }); + settled += settling.elapsed(); + } for (shadow, at, len) in &picked.written { shadow.writing(*at, *len); } - let declared = declared_writes(runs); - let card = self.card_before(&declared, &picked, flown); + let card = self.card_before(ask, flown); + // Diagnostics: the watched bytes looked at behind the sends. + #[cfg(feature = "diagnostics")] + let traced = undeclared::ahead(self, runs, this_submission, &picked); // The sends are taken: from here on the references hold what the // copies in the lists put. for (shadow, at, bytes) in batch.placed.drain(..) { shadow.placed_copy(at, &bytes); } - // A title list can leave a buffer promoted to COPY_DEST. Buffers - // decay to COMMON between ExecuteCommandLists calls, so submit - // the compare separately before signalling this submission's fence. - // Keep it in the list array so the timing end markers follow it. + // A title list can leave a buffer promoted to COPY_DEST (a copy at + // its place into a host copy's card buffer). Buffers decay to COMMON + // between ExecuteCommandLists calls, so the compare goes in a call + // of its own before this submission's fence is signalled, unless + // `LEONIDA_COMPARE_JOIN` joins it to the call of the last lists: + // where the card has enhanced barriers (a global one goes in front + // of it) and no list in that call copied into a host copy + // ([`Host::execute_with_compare`]). Kept in the list array so the + // timing end markers follow it. let compare_at = card.as_ref().and_then(|c| c.check.clone()).map(|list| { let at = lists.len(); lists.push(Some(list)); at }); + // And behind the lists, ahead of the compare. + #[cfg(feature = "diagnostics")] + let compare_at = undeclared::behind(traced.as_ref(), &mut lists, compare_at); #[cfg(feature = "diagnostics")] split.part(4); stage.next("submit: waiting for the heaps' records"); @@ -7738,18 +7644,20 @@ impl Host { // SAFETY: closed lists; the fence is ours. let signalled = unsafe { let mut from = 0; - for to in cuts.into_iter().chain([lists.len()]) { + for to in cuts { self.queue.ExecuteCommandLists(&lists[from..to]); from = to; } - if !compare.is_empty() { - self.queue.ExecuteCommandLists(compare); - } + // The last call, and the compare in it or behind it. + let copied = || compare_ecl::copied_from(runs, &firsts, from); + self.execute_with_compare(&lists[from..], compare, true, copied, *submitted); self.queue.Signal(&self.fence, *submitted) }; awake::sent(&self.device); #[cfg(feature = "diagnostics")] crate::timeline::sent(sending, *submitted, stamp); + #[cfg(feature = "diagnostics")] + undeclared::sent(self, traced); self.card_sent(); stage.next("submit: noting what is in the air"); if let Err(e) = signalled { @@ -7804,9 +7712,17 @@ impl Host { let started = std::time::Instant::now(); // SAFETY: closed lists; the fence and event are ours. unsafe { - self.queue.ExecuteCommandLists(group); - if i + 1 == groups.len() && !compare.is_empty() { - self.queue.ExecuteCommandLists(compare); + if i + 1 == groups.len() { + // (The timing run's compare in a call of its own, as its + // lists are.) + #[cfg(feature = "diagnostics")] + let may_join = !timing(); + #[cfg(not(feature = "diagnostics"))] + let may_join = true; + let copied = || compare_ecl::copied_from(runs, &firsts, 0); + self.execute_with_compare(group, compare, may_join, copied, *submitted); + } else { + self.queue.ExecuteCommandLists(group); } self.card_sent(); let waited = self @@ -7913,6 +7829,8 @@ impl Host { last_notes(runs) )); } + #[cfg(feature = "diagnostics")] + undeclared::sent(self, traced); submitting(3, runs.len()); stage.next("submit: copying back"); // What shaders wrote goes back before the bottom-of-pipe writes, @@ -8149,9 +8067,25 @@ impl Host { } queue.ClearStoredMessages(); } + #[cfg(test)] + if let Some(error) = &first_error { + TEST_FIRST_ERROR.with_borrow_mut(|kept| { + kept.get_or_insert_with(|| error.clone()); + }); + } first_error } + /// (Tests) The first error the debug layer reported on this thread since + /// the last ask: of those [`Host::log_messages`] logged and cleared since + /// (every submission ends with it), else of those it holds now. `None` + /// without the debug layer (its DLL is Windows' Graphics Tools). + #[cfg(test)] + pub(crate) fn errors_seen(&self) -> Option { + let now = self.log_messages(); + TEST_FIRST_ERROR.take().or(now) + } + /// A host render target view of `resource`, valid until it is recorded. pub(crate) fn rtv( &self, @@ -8352,6 +8286,11 @@ impl HostList { let fronts = fronts_of(&deferred.copies); deferred.fronts = Some(Box::new(fronts)); } + // And what the submission's other questions ask of them ([`summary`]). + if summary::mode() != summary::Mode::Off { + let _summary = crate::timeline::span("closing a host list: its steps' summary"); + summary::close(&mut self.deferred()); + } #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); @@ -8432,14 +8371,13 @@ impl HostList { } // The scratch buffers of its batched clamps, likewise: the next // recording to ask takes them ([`batch_pool`]). - if batch_pool() { - let given = { - let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner()); - args.1 = 0; - std::mem::take(&mut args.0) - }; - give_batches(given); - } + // (With their table areas: [`batch_tables`].) + let given = { + let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner()); + args.reset(); + if batch_pool() { std::mem::take(&mut args.buffers) } else { Vec::new() } + }; + give_batches(given); let reset = { let mut allocator = self.allocator.lock().unwrap_or_else(|e| e.into_inner()); let (allocator, made) = &mut *allocator; @@ -8873,13 +8811,16 @@ impl HostList { (real != *first) .then(|| transition(©.texture, host_state(real), host_state(*first))) })); - if barriers.is_empty() && syncs.is_empty() && uploads.is_empty() { + // The tables of the list's batched clamps, into the card's memory + // where its passes read them ([`batch_tables`]). + let tables = self.batch_args.lock().unwrap_or_else(|e| e.into_inner()).copies(); + batch_tables::copy_barriers(&tables, &mut to_copy, &mut barriers); + if barriers.is_empty() && syncs.is_empty() && uploads.is_empty() && tables.is_empty() { return None; } - let Some((allocator, list)) = self - .prelude - .get_or_init(|| host().and_then(|h| h.make_prelude()).map(list_prelude)) - .as_ref() + // (Made ahead on a thread of its own if one is ready: + // `LEONIDA_PRELUDE_POOL`, `preludes`.) + let Some((allocator, list)) = self.prelude.get_or_init(|| preludes::take().map(list_prelude)).as_ref() else { fail(format_args!("no host list for a state prelude")); }; @@ -8908,6 +8849,7 @@ impl HostList { for upload in uploads { upload.record(list); } + batch_tables::record_copies(list, &tables); if !barriers.is_empty() { list.ResourceBarrier(&barriers); } @@ -9417,37 +9359,66 @@ impl HostList { Some(buffer) } + /// The list goes idle (`crate::list::recycle`, after its reset): an + /// indirect scratch buffer past [`IDLE_INDIRECT_MOST`] is let go, behind + /// the submissions still running ([`retire_resource`]). The buffer only + /// grows, doubling, and the idle pool hands its lists to any title list, + /// so one large indirect execution kept its buffer of the card's memory + /// in that list for the rest of the run, in as many idle lists as ever + /// served one. The next recording that needs that much makes one anew + /// ([`HostList::indirect_scratch`] starts from none). + pub(crate) fn idle_trim(&self) { + let large = { + let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()); + if slot.as_ref().is_some_and(|&(_, cap)| cap > IDLE_INDIRECT_MOST) { slot.take() } else { None } + }; + if let Some((buffer, cap)) = large { + IDLE_INDIRECT_TRIMS[0].fetch_add(1, Ordering::Relaxed); + IDLE_INDIRECT_TRIMS[1].fetch_add(cap, Ordering::Relaxed); + retire_resource(buffer); + } + } + + /// (Tests) [`HostList::batch_place_table`]'s place alone, for a batch + /// whose pass is not recorded: its table is nowhere. + #[cfg(test)] + pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> { + self.batch_place_table(false, || Some((0, std::ptr::null_mut()))).map(|(place, _)| place) + } + /// Where the next batch of clamped records goes: a device-local buffer /// the list keeps until it is reset ([`batch_pool`]; without it, from /// recording to recording), the batch's place in it and the state the /// buffer is in. Every batch of a recording has a place of its own: the - /// executions before it may still read theirs. - pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> { - use crate::indirect::batch::{JOBS, SLOT}; - let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner()); - let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES); - if buffer == args.0.len() { - args.0.push(take_batch_scratch()?); - } - args.1 += 1; - // (Its first batch finds it as the recording before left it: - // `batches_common`.) - let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }; - Some((args.0[buffer].clone(), i * JOBS * SLOT, state)) + /// executions before it may still read theirs. And where the batch's + /// pass reads its table and the CPU fills it: with `card` in the card's + /// memory, copied there by the list's prelude ([`batch_tables`]), else + /// (or if no table area is to be had there) at `upload()`. `None`, and + /// no place taken, if there is neither. + pub(crate) fn batch_place_table( + &self, + card: bool, + upload: impl FnOnce() -> Option, + ) -> Option<((ID3D12Resource, u32, D3D12_RESOURCE_STATES), batch_tables::TablePlace)> { + self.batch_args.lock().unwrap_or_else(|e| e.into_inner()).place(card, upload) } /// Before the list closes: the scratch buffers of the batched clamps go - /// back to the common state, where the next recording expects them. + /// back to the common state, where the next recording expects them, and + /// so do the mirrors of their tables the passes read, which the list's + /// prelude is to fill ([`batch_tables`]). fn batches_common(&self) { let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner()); - let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize; - let barriers: Vec = args.0[..used] + let used = std::mem::take(&mut args.used).div_ceil(BATCHES) as usize; + let mut barriers: Vec = args.buffers[..used] .iter() - .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON)) + .map(|b| transition(&b.scratch, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON)) .collect(); + args.close(&mut barriers); if !barriers.is_empty() { // SAFETY: an open list and live buffers this recording left in - // `INDIRECT_ARGUMENT`. + // `INDIRECT_ARGUMENT`, and mirrors its prelude leaves in + // `NON_PIXEL_SHADER_RESOURCE`. unsafe { self.list.ResourceBarrier(&barriers) }; } } @@ -9591,7 +9562,10 @@ impl HostList { } /// Runs `work` when the list is submitted, in order with its copies. - /// `work` may write title memory (refreshes after it copy again). + /// `work` may write title memory (refreshes after it copy again). Work + /// that does what the title's GPU would do after the submissions in the + /// air calls [`crate::shadow::copying`] before it writes (copies in the + /// card's memory sent straight out of their CPU sides, `send::direct`). pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) { let mut deferred = self.deferred(); deferred.copies.push(Step::Run(Box::new(work))); @@ -9617,6 +9591,13 @@ impl HostList { self.deferred().copies.push(Step::Texture(staging)); } + /// For tests: a texture read-back the list lands once it has run, as + /// [`HostList::textures_back`] gives it one. + #[cfg(test)] + pub(crate) fn add_texture_back(&self, back: crate::texback::Back) { + self.deferred().texture_backs.push(back); + } + /// The list reads a title texture whose staging buffer its /// [`HostList::defer_texture`] step checks at submission: if that leaves /// the buffer with what the host copy lacks, the list's prelude copies it @@ -9673,6 +9654,9 @@ impl HostList { let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64); #[cfg(feature = "diagnostics")] let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64); + // The list goes to the card after this: what it copies into its + // read-back buffers may change (`crate::texback::mapped`). + self.deferred().texture_backs.iter().for_each(crate::texback::Back::submitted); for (i, step) in self.deferred().copies.iter().enumerate() { if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) { continue; @@ -9694,14 +9678,7 @@ impl HostList { crate::port_journal::prep_wrote(); } crate::port::copied(dst, src, len); - copy_mapped(dst as *mut u8, src as *const u8, len, true); - // With the submission's one asking: the journal learns it. - crate::watch::wrote(dst, len); - // What the card holds there may be another value although - // ours did not change. - if send::own() { - crate::shadow::send_copied(dst, len); - } + title_copy(dst, src, len); (started, len) } &Step::Fill(dst, src, len, _) => { @@ -9747,6 +9724,11 @@ impl HostList { ); } } + // Title memory and the destination's reference take the + // bytes: not under a card copy still to be made of them. + if free || titles { + crate::shadow::copying(p.dst, p.len); + } if let Some(bytes) = p.prepare(free, titles) { batch.placed.push((p.shadow.clone(), p.dst, bytes)); } @@ -9889,385 +9871,19 @@ impl std::hash::Hasher for AddressHash { } #[cfg(test)] -mod dynamic_wait_tests { - use super::take_after_landings; - use std::cell::Cell; - - /// A draw without slots asks again after each landing, and no more: it - /// stops with its slots, or when nothing was in the air at an asking - /// that found none (nothing can give slots back then). - #[test] - fn slots_are_asked_for_again_after_each_landing_while_something_flies() { - // There at once: nothing is waited for. - let (asked, waited) = (Cell::new(0), Cell::new(0)); - let take = || { - asked.set(asked.get() + 1); - Some(7) - }; - assert_eq!(take_after_landings(take, || true, || waited.set(waited.get() + 1)), Some(7)); - assert_eq!((asked.get(), waited.get()), (1, 0)); - - // Given back by the second landing. - let (asked, waited) = (Cell::new(0), Cell::new(0)); - let take = || { - asked.set(asked.get() + 1); - (waited.get() == 2).then_some(40) - }; - assert_eq!(take_after_landings(take, || true, || waited.set(waited.get() + 1)), Some(40)); - assert_eq!((asked.get(), waited.get()), (3, 2)); - - // Never: it stops at the asking that found the air empty, which is - // made after that look (a landing between the two is not missed). - let (asked, waited, looked) = (Cell::new(0), Cell::new(0), Cell::new(0)); - let take = || { - asked.set(asked.get() + 1); - None - }; - let in_air = || { - looked.set(looked.get() + 1); - assert_eq!(looked.get(), asked.get() + 1, "looked at before the asking"); - looked.get() < 3 - }; - assert_eq!(take_after_landings(take, in_air, || waited.set(waited.get() + 1)), None); - assert_eq!((asked.get(), waited.get(), looked.get()), (3, 2, 3)); - - // Nothing in the air, and the slots are there all the same (given - // back by the landing that emptied it): taken. - assert_eq!(take_after_landings(|| Some(1), || false, || panic!("nothing to wait for")), Some(1)); - } -} +mod dynamic_wait_tests; #[cfg(test)] -mod scratch_address_tests { - use super::*; - - /// A list's scratch memory is where its buffer is: the address kept - /// with a chunk is the buffer's own, pieces follow each other in whole - /// 256 bytes on the card as in the mapping, and a piece bigger than a - /// chunk has a buffer to itself. - #[test] - fn a_lists_scratch_memory_is_at_its_buffers_address() { - let Some(host) = host() else { - eprintln!("no D3D12 device; scratch addresses not tested"); - return; - }; - let list = host.new_list().unwrap(); - let (first, first_data) = list.scratch(100).unwrap(); - let (buffer, held, held_data) = list.scratch_held(300).unwrap(); - // SAFETY: a live buffer. - let base = unsafe { buffer.GetGPUVirtualAddress() }; - assert_eq!(first, base); - assert_eq!(held, base + 256); - assert_eq!(held_data as usize, first_data as usize + 256); - let (third, third_data) = list.scratch(1).unwrap(); - assert_eq!(third, base + 256 + 512); - assert_eq!(third_data as usize, first_data as usize + 256 + 512); - let (big, big_at, _) = list.scratch_held(SCRATCH_CHUNK + 1).unwrap(); - // SAFETY: a live buffer. - assert_eq!(big_at, unsafe { big.GetGPUVirtualAddress() }); - assert_ne!(big_at, base); - list.close(); - list.reset(); - } -} +mod scratch_address_tests; #[cfg(test)] -mod read_back_pool_tests { - use super::*; - use windows::core::Interface; - - #[test] - fn a_read_back_buffer_is_made_in_whole_64_kib() { - assert_eq!(read_back_size(0), 1 << 16); - assert_eq!(read_back_size(1), 1 << 16); - assert_eq!(read_back_size(512), 1 << 16); - assert_eq!(read_back_size(1 << 16), 1 << 16); - assert_eq!(read_back_size((1 << 16) + 1), 2 << 16); - assert_eq!(read_back_size(350_000), 6 << 16); - } - - /// A list's read-back buffer is the next read back's of its size once - /// the list is reset, and not before; one something else still names - /// when the list is reset is not kept. - #[test] - fn a_reset_lists_read_back_buffer_is_the_next_read_backs() { - let Some(host) = host() else { - eprintln!("no D3D12 device; the read-back buffers' table not tested"); - return; - }; - if !read_back_pool() { - return; - } - // (A size no other test reads back: the table is the process's.) - let size = (7 << 16) - 100; - let mut title = [0u8; 64]; - let list = host.new_list().unwrap(); - let buffer = host.read_back_buffer(size).unwrap(); - // SAFETY: a live buffer. - assert_eq!(unsafe { buffer.GetDesc() }.Width, 7 << 16); - let first = buffer.as_raw() as usize; - list.defer_read_back(buffer, title.as_mut_ptr(), [16, 2, 32]); - // The list holds it: another read back gets another buffer. - let other = host.read_back_buffer(size).unwrap(); - assert_ne!(other.as_raw() as usize, first); - list.close(); - list.reset(); - // Nobody's now: the next read back of that size takes it, once. - let again = host.read_back_buffer(size - 4096).unwrap(); - assert_eq!(again.as_raw() as usize, first); - let third = host.read_back_buffer(size).unwrap(); - assert_ne!(third.as_raw() as usize, first); - // Still named elsewhere when its list is reset: let go, not kept. - let named = again.clone(); - list.defer_read_back(again, title.as_mut_ptr(), [16, 2, 32]); - list.close(); - list.reset(); - assert!(sole(&named)); - let fourth = host.read_back_buffer(size).unwrap(); - assert_ne!(fourth.as_raw() as usize, first); - drop((other, third, fourth, named)); - } -} +mod read_back_pool_tests; #[cfg(test)] -mod batch_scratch_tests { - use super::*; - use windows::core::Interface; - - #[test] - fn the_table_of_batch_scratch_buffers_takes_what_it_has_room_for() { - assert_eq!(batches_kept(0, 5, 1024), 5); - assert_eq!(batches_kept(1020, 10, 1024), 4); - assert_eq!(batches_kept(1024, 3, 1024), 0); - // (Never more than it may hold, if it ever held more.) - assert_eq!(batches_kept(2000, 3, 1024), 0); - assert_eq!(batches_kept(7, 0, 1024), 0); - // A buffer holds eight batches of 256 records of 32 bytes. - assert_eq!(BATCH_SCRATCH, 65_536); - } - - /// (`LEONIDA_ALLOCATOR_TRIM`) An allocator is taken anew once it is as - /// old as the switch's seconds, which are 30 unless said, 5 to 3600. - #[test] - fn an_allocator_is_old_after_the_trims_seconds() { - assert_eq!(allocator_trim_secs(None), 30); - assert_eq!(allocator_trim_secs(Some(" 120 ")), 120); - assert_eq!(allocator_trim_secs(Some("1")), 5); - assert_eq!(allocator_trim_secs(Some("86400")), 3600); - assert_eq!(allocator_trim_secs(Some("soon")), 30); - assert!(!allocator_old(1_000, 30_999, 30)); - assert!(allocator_old(1_000, 31_000, 30)); - // (A clock read before the allocator's making is not after it.) - assert!(!allocator_old(5_000, 1_000, 30)); - } - - /// (`LEONIDA_ALLOCATOR_TRIM`) A list reset while its allocator is not - /// old keeps it; reset once it is old, the list has a new one, records - /// into it, closes and is reset again as any list. - #[test] - fn a_reset_takes_an_old_allocator_anew() { - let Some(host) = host() else { - eprintln!("no D3D12 device; the allocator trim not tested"); - return; - }; - let list = host.new_list().unwrap(); - let allocator = |l: &HostList| l.allocator.lock().unwrap().0.as_raw() as usize; - let first = allocator(&list); - TEST_ALLOCATOR_TRIM.set(Some(3600)); - list.close(); - list.reset(); - assert_eq!(allocator(&list), first, "not old yet"); - // (A trim of no seconds: every allocator is old.) - TEST_ALLOCATOR_TRIM.set(Some(0)); - let trims = ALLOCATOR_TRIMS[0].load(Ordering::Relaxed); - list.close(); - list.reset(); - let second = allocator(&list); - assert_ne!(second, first, "a new allocator"); - assert!(ALLOCATOR_TRIMS[0].load(Ordering::Relaxed) > trims); - // SAFETY: an open list. - unsafe { list.list.ClearState(None) }; - list.close(); - TEST_ALLOCATOR_TRIM.set(None); - list.reset(); - assert_eq!(allocator(&list), second, "without the switch: the one it has"); - list.close(); - list.reset(); - } - - /// A list's scratch buffers of batched clamps are its own until it is - /// reset, and nobody's after: the list holds none, the table (or whoever - /// took them from it since: the table is the process's) holds them, and - /// the next recording starts from a buffer's first place, in the common - /// state. - #[test] - fn a_reset_list_gives_its_batch_scratch_buffers_back() { - use crate::indirect::batch::{JOBS, SLOT}; - let Some(host) = host() else { - eprintln!("no D3D12 device; the table of batch scratch buffers not tested"); - return; - }; - if !batch_pool() { - return; - } - let list = host.new_list().unwrap(); - // Nine batches: eight in one buffer, the ninth in the next. - let places: Vec<_> = (0..9).map(|_| list.batch_place().unwrap()).collect(); - let raw = |i: usize| places[i].0.as_raw() as usize; - for i in 0..8 { - assert_eq!(raw(i), raw(0)); - assert_eq!(places[i].1, i as u32 * JOBS * SLOT); - let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }; - assert_eq!(places[i].2, state); - } - assert_ne!(raw(8), raw(0)); - assert_eq!((places[8].1, places[8].2), (0, D3D12_RESOURCE_STATE_COMMON)); - // SAFETY: a live buffer. - assert_eq!(unsafe { places[0].0.GetDesc() }.Width, BATCH_SCRATCH); - // While the list holds them, another list's batch gets another buffer. - let other = host.new_list().unwrap(); - let theirs = other.batch_place().unwrap(); - assert!(theirs.0.as_raw() as usize != raw(0) && theirs.0.as_raw() as usize != raw(8)); - list.close(); - list.reset(); - { - let args = list.batch_args.lock().unwrap(); - assert!(args.0.is_empty()); - assert_eq!(args.1, 0); - } - // Not let go: something holds each beside the references here. - assert!(!sole(&places[0].0) && !sole(&places[8].0)); - // The next recording of the list starts as its first did. - let again = list.batch_place().unwrap(); - assert_eq!((again.1, again.2), (0, D3D12_RESOURCE_STATE_COMMON)); - assert_ne!(again.0.as_raw(), theirs.0.as_raw()); - list.close(); - list.reset(); - other.close(); - other.reset(); - } -} +mod batch_scratch_tests; #[cfg(test)] -mod address_hash_tests { - use super::AddressHash; - use std::hash::{BuildHasher, BuildHasherDefault}; - - fn hash(key: K) -> u64 { - BuildHasherDefault::::default().hash_one(key) - } - - /// What a table makes of `hashes`: its place from the low bits, its tag - /// from the top seven. No two the same, every tag in use, and with as many - /// places as keys no place crowded and the keys looked at to find one not - /// many more than chance leaves (which is 1.5: a key and half of the others - /// at its place). - /// - /// Measured 2026-11-27, 4,096 keys: host copies 16, 48 and 64 bytes apart - /// 2.1, 1.8 and 2.0 keys looked at (the fullest place 22, 15 and 12 keys), - /// 192 bytes apart 1.5, a page and 64 KiB apart 1.1 and 1.2; root views - /// 2.0, fills 1.5. Not as even as the standard hash for keys a few bytes - /// apart, and far from all in one place. - fn spread(what: &str, hashes: &[u64]) { - let places = hashes.len().next_power_of_two(); - let mut at = vec![0u32; places]; - let mut tags = [false; 128]; - let mut seen = std::collections::BTreeSet::new(); - for &h in hashes { - assert!(seen.insert(h), "{what}: two keys with one hash"); - at[h as usize & (places - 1)] += 1; - tags[(h >> 57) as usize] = true; - } - let fullest = at.iter().copied().max().unwrap_or(0); - assert!(fullest <= 32, "{what}: {fullest} keys in one place of {places}"); - let looked: u64 = at.iter().map(|&n| u64::from(n) * u64::from(n + 1) / 2).sum(); - let looked = looked as f64 / hashes.len() as f64; - assert!(looked <= 2.5, "{what}: {looked:.2} keys looked at to find one"); - let used = tags.iter().filter(|&&t| t).count(); - assert!(used >= 120, "{what}: {used} tags of 128 in use"); - } - - /// The tables a list asks at every draw are keyed by addresses of ours - /// (host copies, title heaps, title addresses): keys that differ in few - /// bits, at even steps. This hash has to tell them apart as the standard - /// one did. - #[test] - fn the_keys_of_a_lists_per_draw_tables_spread() { - // Host copies by address: objects of one size, one after the other. - for step in [16usize, 48, 64, 192, 4096, 1 << 16] { - let keys: Vec = (0..4096).map(|i| hash(0x0000_01f4_8a20_0040usize + i * step)).collect(); - spread(&format!("copies {step} bytes apart"), &keys); - } - // Root views: (title heap, title address), bit 63 for a view that - // begins early (`crate::draw::State::root_srv_table`). - let heap = 0x0000_0234_5678_9000usize; - let keys: Vec = (0..2048u64) - .flat_map(|i| { - let address = 0x4_2000_0000 + i * 0x140; - [hash((heap, address)), hash((heap, address | 1 << 63))] - }) - .collect(); - spread("root views", &keys); - // Fills of scratch memory: (source, bytes). - let keys: Vec = (0..4096usize).map(|i| hash((0x2_8000_0000usize + (i / 4) * 0x100, 0x100usize << (i % 4)))).collect(); - spread("fills", &keys); - } - - /// What a hasher is handed, in order: a number, or so many bytes at once. - #[derive(Default)] - struct Handed(Vec<(bool, usize)>); - - impl std::hash::Hasher for Handed { - fn finish(&self) -> u64 { - 0 - } - fn write(&mut self, bytes: &[u8]) { - self.0.push((true, bytes.len())); - } - fn write_usize(&mut self, n: usize) { - self.0.push((false, n)); - } - } - - /// A descriptor record (tag, index, generation: the key of the views a - /// list made, `crate::descriptor::host::ListViews`) is handed over as its - /// length and its twelve bytes at once, and hashed in three steps: the - /// length, eight bytes, and the four left with their number. Records - /// that differ in one word hash apart, and a list's records spread. - #[test] - fn a_record_of_three_words_is_hashed_a_word_at_a_time() { - use std::hash::{Hash, Hasher}; - let record = [0x5649_4557u32, 0x0001_2345, 7]; - let mut handed = Handed::default(); - record.hash(&mut handed); - assert_eq!(handed.0, [(false, 3), (true, 12)], "the standard library hands a record over otherwise now"); - let mut by_hand = AddressHash::default(); - by_hand.write_usize(3); - by_hand.write_u64(u64::from(record[0]) | u64::from(record[1]) << 32); - by_hand.write_u64(u64::from(record[2]) | 4 << 56); - assert_eq!(hash(record), by_hand.finish()); - for word in 0..3 { - for bit in 0..32 { - let mut other = record; - other[word] ^= 1 << bit; - assert_ne!(hash(other), hash(record), "word {word}, bit {bit}"); - } - } - // The bytes left over count: a shorter key is not the longer one - // that ends in zeros. - let bytes = |b: &[u8]| { - let mut h = AddressHash::default(); - h.write(b); - h.finish() - }; - assert_ne!(bytes(b"ab"), bytes(b"ab\0")); - assert_ne!(bytes(b"12345678"), bytes(b"12345678\0")); - assert_eq!(bytes(&7u64.to_le_bytes()), hash(7u64)); - // A list's records: one tag, slots one after the other, a few generations. - let keys: Vec = (0..4096u32).map(|i| hash([0x5649_4557u32, 0x4000 + i / 2, 1 + i % 2])).collect(); - spread("records", &keys); - } -} +mod address_hash_tests; /// Since the last frame-rate line, nanoseconds of the submitting thread's /// preparing: the write-watch asking for a submission; the title's bytes put @@ -10310,93 +9926,6 @@ impl Split { } } -/// The split of the preparing, per frame, for the frame-rate line. -#[cfg(feature = "diagnostics")] -fn split_line(frames: f64) { - let ms: Vec = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); - let f: Vec = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); - let e: Vec = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect(); - let a: Vec = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect(); - let h: Vec = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); - let s: Vec = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect(); - tracing::info!( - "preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \ - writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \ - several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \ - card's memory, {:.1} sending the lists (LEONIDA_LIGHT_REFRESH is {}); ahead of these {:.1} waiting for the submission lock, {:.1} \ - planning steps done on the card, {:.1} waiting for flights, {:.1} the heaps' records and what is swept; at the end {:.1} waiting \ - for the heaps' records; asked early by a thread of its own {:.0} pieces of 2 MiB, {:.1} ms (LEONIDA_ASK_EARLY)", - ms[0], - ms[8], - ms[1], - ms[2], - ms[6], - f[0], - f[1], - f[2], - f[3], - ms[9], - ms[10] * 1e6, - ms[7], - ms[3], - ms[4], - ms[5], - if crate::watch::light() { "on" } else { "off" }, - ms[11], - ms[12], - ms[13], - ms[14], - ms[15], - e[0], - e[1] / 1e3, - ); - let scoped: Vec = SCOPED.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); - if copy_scoped() || scoped.iter().any(|&n| n > 0.0) { - tracing::info!( - "title writes of the steps per frame (LEONIDA_COPY_SCOPED is {}): {:.0} forgot only the copies refreshed ahead that they \ - touch (a forgetting of all of them not made), {:.0} copies kept, {:.0} forgotten; {:.0} forgot all of them (shown at too \ - many places)", - if copy_scoped() { "on" } else { "off" }, - scoped[0], - scoped[1], - scoped[3], - scoped[2], - ); - } - tracing::info!( - "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \ - written, {:.0} askings refused); {:.0} questions about holes; view ranges: {:.0} answered by their \ - bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \ - waiting for the guards, {:.1} ms changing protections; pages taken for the card: {:.1} MB compared, {:.1} MB of them \ - as they were, {:.1} MB to go up in {:.0} runs (LEONIDA_SEND_CHANGED)", - a[0], - a[1] / 1024.0, - a[11] / 1e6, - a[12], - a[10], - a[9], - a[2], - a[3], - a[4], - a[5], - a[6], - a[7] / 1e6, - a[8] / 1e6, - s[0] / 1048576.0, - s[1] / 1048576.0, - s[2] / 1048576.0, - s[3], - ); - tracing::info!( - "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures; the \ - first two beside the recording (LEONIDA_HEAP_PASS_ASIDE), {:.1} ms waited for at the lists' close", - h[0], - h[1], - h[2], - aside::WAITED.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames, - ); -} - /// Whether a submission's refreshes of host copies run on several threads, /// a copy to a thread (`LEONIDA_WIDE_REFRESH=0` disables it; `=1` forces it). /// @@ -10419,6 +9948,99 @@ fn wide_refresh() -> bool { }) } +/// Whether the looks at which of a flush's refreshes copy nothing +/// (`Shadow::nothing_new`) are made on the submitting thread, one after the +/// other, before any thread is woken, however many there are; only the +/// refreshes that may copy go to the threads beside it, and none is woken +/// when there are fewer than two (`LEONIDA_LOOK_FIRST=0`: a flush of more than +/// 256 refreshes, any with renderer port #6's planning, and the copies a +/// submission's shaders write, looked at on those threads, each just before +/// the refresh it may spare, as before). +/// +/// A look is a few reads under the journal's lock and its part's: some 30 ns +/// on one thread. 4,400 copies of the heap's buffer views that nothing wrote +/// took 0.14 ms looked at one after the other, 0.36-0.48 ms spread over the +/// threads, in pieces of one to 256 alike (test `refreshes_of_nothing_written`, +/// release build, the RX 7900 XT PC of 8 cores): not the handing out, then, +/// but, as we read it, every look on eight threads at once taking those +/// locks' lines from the others. The flush in front of the steps went from +/// 0.65 to 0.24 ms with the switch, flushes between them from 0.47 to 0.17. +/// In the running title 5,753 of a frame's 6,590 refreshes were known to copy +/// nothing and 5,795 were handed to the threads (a 5-minute run, 11.7 ms a +/// frame of the submitting thread in refreshes, on that PC); what the switch +/// saves there is not measured yet. +/// +/// The looks are the same, and they all come before the first refresh, as a +/// flush of 256 or fewer always had them (a refresh's asking may note writes +/// in another's range that came after the submission's asking: those are the +/// next submission's either way). The refreshes are the same. A flush whose +/// looks here take longer than [`LOOK_BUDGET`] (a few copies of hundreds of +/// megabytes the title wrote all over) hands the rest to the threads, looked +/// at there as before; the clock is asked every 64 looks, each 64 KiB page of +/// a look's range counted as one, so after every look of 4 MiB or more +/// ([`sift`]). +fn look_first() -> bool { + #[cfg(test)] + if let Some(on) = LOOK_FIRST_IN_TEST.get() { + return on; + } + crate::toggled!("LEONIDA_LOOK_FIRST") +} + +#[cfg(test)] +thread_local! { + /// [`look_first`], for the flushes this thread makes. + static LOOK_FIRST_IN_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// How long [`look_first`]'s looks of a flush go on before the rest are left +/// to the threads (a hypothesis: some ten times what 4,400 looks at copies +/// nothing wrote took on one thread). +const LOOK_BUDGET: std::time::Duration = std::time::Duration::from_micros(1500); + +/// How many looks [`sift`] makes between askings of the clock, a page of a +/// look's range counted as a look (the clock is about as dear as a look of a +/// range inside one page). +const SIFT_EVERY: usize = 64; + +/// Takes out of `spans` (copy, from, to) the refreshes [`Shadow::nothing_new`] +/// knows to copy nothing, looked at on this thread one after the other until +/// `budget` is spent ([`look_first`]); how many of those left, from the first, +/// were looked at. The others, after them in the order they came, were not: +/// they are looked at where they are refreshed. Of those left the order is +/// kept. +/// +/// The clock is asked once the looks since it was last asked come to +/// [`SIFT_EVERY`], a look counted as one and one more for each 64 KiB page of +/// its range (a look walks the journal page by page): every 64 looks of +/// ranges inside a page, and after each look of a range of 64 pages or more. +/// Counted by looks alone, a flush of fewer than 64 refreshes was never cut +/// short, however wide their ranges. +/// +/// [`Shadow::nothing_new`]: crate::shadow::Shadow::nothing_new +fn sift(spans: &mut Vec<(std::sync::Arc, usize, usize)>, budget: std::time::Duration) -> usize { + let started = std::time::Instant::now(); + let (mut kept, mut at, mut owed) = (0, 0, 0); + while at < spans.len() { + if owed >= SIFT_EVERY { + if started.elapsed() > budget { + break; + } + owed = 0; + } + let (shadow, from, to) = &spans[at]; + owed += 1 + (*to - *from) / crate::watch::PAGE; + if !shadow.nothing_new(*from, *to - *from) { + spans.swap(kept, at); + kept += 1; + } + at += 1; + } + // Those known to copy nothing lie between. + spans.drain(kept..at); + kept +} + fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option) -> bool { match setting { Some("1") => true, @@ -10428,20 +10050,7 @@ fn wide_refresh_enabled(setting: Option<&str>, logical_cpus: Option) -> b } #[cfg(test)] -mod wide_refresh_tests { - use super::wide_refresh_enabled; - - #[test] - fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() { - assert!(wide_refresh_enabled(None, Some(4))); - assert!(wide_refresh_enabled(None, Some(16))); - assert!(!wide_refresh_enabled(None, Some(2))); - assert!(!wide_refresh_enabled(None, None)); - assert!(wide_refresh_enabled(Some("1"), Some(1))); - assert!(!wide_refresh_enabled(Some("0"), Some(16))); - assert!(wide_refresh_enabled(Some("auto"), Some(4))); - } -} +mod wide_refresh_tests; /// A submission's refreshes not done yet, merged per buffer copy into the /// range that covers them: done before a step that writes title memory or @@ -10970,58 +10579,7 @@ fn join_fronts(fronts: &[ListFront], parts: &[usize]) -> Vec<(std::sync::Arc> 33) as usize % n - }; - for _ in 0..3000 { - let lists = 1 + next(8); - let copies = 1 + next(6); - let mut parts = Vec::new(); - let mut whole: Vec = Vec::new(); - let mut folds = Vec::new(); - for n in 0..lists { - if n > 0 && next(4) == 0 { - parts.push(n); - whole.push(Touch::Part); - } - let mut mine: Vec = Vec::new(); - for _ in 0..next(12) { - let key = 0x1000 * (1 + next(copies)); - if next(5) == 0 { - mine.push(Touch::Write(key)); - whole.push(Touch::Write(key)); - } else { - // (Refreshes of no bytes too: `Shadow::refresh` clamps - // a range to the copy's end.) - let from = next(100); - let to = from + next(51); - mine.push(Touch::Refresh(key, from, to)); - whole.push(Touch::Refresh(key, from, to)); - } - } - folds.push(fold_touches(mine.into_iter())); - } - let want = front_spans(whole.into_iter()); - let got = join_keys(folds.iter().map(|f| f.as_slice()), &parts); - assert_eq!(got, want, "parts {parts:?}"); - // And as the lists' kept parts are joined (`joined_keys`): one - // list's part as it is, more joined. - let fronts: Vec = folds.iter().map(|f| ListFront { copies: f.clone(), ..ListFront::default() }).collect(); - assert_eq!(joined_keys(&fronts, &parts), want, "lists {lists}, parts {parts:?}"); - } - } -} +mod front_tests; /// What a step is to the copies' refreshes, for [`written_spans`]. enum Touch { @@ -11063,73 +10621,7 @@ fn written_spans(steps: impl Iterator) -> Vec<(usize, usize, usize } #[cfg(test)] -mod written_spans_tests { - use super::{Touch, front_spans, split, written_spans}; - - #[test] - fn everything_is_refreshed_in_front_but_what_a_part_gave_its_shaders() { - use Touch::{Nothing, Part, Refresh, Title, Write}; - let found = front_spans( - [ - Refresh(1, 10, 20), - Refresh(1, 12, 25), - Refresh(2, 0, 5), - Nothing, - Write(1), - // (Around what the part's own shaders write.) - Refresh(1, 0, 100), - Write(3), - Refresh(3, 1, 2), - Title, - Refresh(4, 7, 9), - Part, - // The next part's bytes under the first one's writes. - Refresh(1, 30, 40), - Write(4), - Refresh(4, 0, 9), - ] - .into_iter(), - ); - assert_eq!(found, [(1, 10, 40), (2, 0, 5), (4, 7, 9)]); - } - - #[test] - fn a_submission_is_cut_between_its_lists() { - // Lists c and e are in neither half's order: they go with the first. - let Ok([first, second]) = split(vec!['a', 'b', 'c', 'd', 'e'], vec![1, 3, 0], 1) else { - panic!("no list is named twice"); - }; - let run = |(lists, order): &(Vec, Vec)| order.iter().map(|&i| lists[i]).collect::(); - assert_eq!((run(&first), run(&second)), ("b".into(), "da".into())); - assert_eq!(first.0.len() + second.0.len(), 5); - assert!(split(vec!['a', 'b'], vec![0, 1, 0], 2).is_err()); - assert!(split(vec!['a', 'b'], vec![0, 1], 0).is_err()); - } - - #[test] - fn what_is_written_is_refreshed_ahead_up_to_its_write_and_to_title_writes() { - use Touch::{Nothing, Refresh, Title, Write}; - let mut found = written_spans( - [ - Refresh(1, 10, 20), - Refresh(2, 0, 5), - Nothing, - Refresh(1, 30, 40), - Write(1), - Refresh(1, 0, 100), - Write(3), - Refresh(3, 1, 2), - Refresh(4, 7, 9), - Write(4), - Title, - Write(2), - ] - .into_iter(), - ); - found.sort_unstable(); - assert_eq!(found, [(1, 10, 40), (4, 7, 9)]); - } -} +mod written_spans_tests; /// Whether the fills of a submission's upload memory are done together on /// several threads (`LEONIDA_WIDE_FILLS=0`: one after the other, where the @@ -11197,12 +10689,27 @@ impl Batch { /// One walk over the steps for both, where there were two, each with a /// table of its own. fn copy_spans(&mut self, runs: &[&HostList]) { + // (By the lists' summaries, [`summary`]: the same spans in the same + // order.) + if summary::mode() == summary::Mode::On + && let Some(sums) = summary::all(runs) + { + summary::copy_spans(&sums, &mut self.spans, &mut self.spans_at); + return; + } + self.copy_spans_steps(runs); + } + + /// [`Batch::copy_spans`] by the steps of `runs`. + fn copy_spans_steps(&mut self, runs: &[&HostList]) { self.spans.clear(); self.spans_at.clear(); // (Most come several times on end.) let mut last = (0, 0); for list in runs { - for step in &list.deferred().copies { + let deferred = list.deferred(); + summary::walked(deferred.copies.len()); + for step in &deferred.copies { let Step::Refresh(shadow, address, len) = step else { continue; }; @@ -11529,20 +11036,30 @@ impl Batch { let _flush = crate::timeline::span("refreshes of copies"); let started = std::time::Instant::now(); let before = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed)); - // Those known to copy nothing are said so here, unless they are very - // many: then beside the others. + // Those known to copy nothing are said so here ([`look_first`]); with + // the switch off, unless they are very many: then beside the others. const FEW: usize = 256; let mut spans = spans; // (Renderer port #6: on the threads beside, whatever their number.) let many = spans.len() > FEW || crate::watch::port_guard_plan() && spans.len() + due.len() >= 4; - if !many { + // The spans from this one on are looked at where they are refreshed + // ([`look_first`]: those the time here did not reach). + let looked = if look_first() || !many { let _known = crate::timeline::span("refreshes in front: those known to copy nothing"); #[cfg(feature = "diagnostics")] let all = spans.len(); - spans.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + let looked = if look_first() { + sift(&mut spans, LOOK_BUDGET) + } else { + spans.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + spans.len() + }; #[cfg(feature = "diagnostics")] FLUSHES[2].fetch_add((all - spans.len()) as u64, Ordering::Relaxed); - } + looked + } else { + 0 + }; let ahead = spans.len() > 1; if ahead { let ranges: Vec<(usize, usize)> = spans.iter().filter(|r| r.0.asked_ahead()).map(|r| (r.1, r.2)).collect(); @@ -11557,7 +11074,7 @@ impl Batch { return; }; let (shadow, from, to) = &spans[i]; - if many && shadow.nothing_new(*from, *to - *from) { + if i >= looked && shadow.nothing_new(*from, *to - *from) { #[cfg(feature = "diagnostics")] FLUSHES[2].fetch_add(1, Ordering::Relaxed); return; @@ -11608,9 +11125,12 @@ impl Batch { let began = std::time::Instant::now(); let started = std::time::Instant::now(); let before = PREPARING[0].load(Ordering::Relaxed); + // Those from this one on are looked at on the threads ([`look_first`]). + let mut due = due; + let looked = if look_first() { sift(&mut due, LOOK_BUDGET) } else { 0 }; crate::shadow::wide_each(due.len(), move |i| { let (shadow, from, to) = &due[i]; - if !shadow.nothing_new(*from, *to - *from) { + if i < looked || !shadow.nothing_new(*from, *to - *from) { Self::update(shadow, *from, *to); } }); @@ -11690,16 +11210,25 @@ impl Batch { // Most of a flush's copies are as they were: they are told so here, // from what the submission's asking found, before anything is asked // and any thread woken. (Thousands of them, the heap's buffer views - // once a frame: on the threads, below.) + // once a frame: here too with [`look_first`], else on the threads, + // below.) const FEW: usize = 256; let light = crate::watch::light(); // Renderer port #6: looked at on the threads beside, below. let beside = light && crate::watch::port_guard_plan() && wide_refresh() && self.refreshes.len() >= 4; - if light && self.refreshes.len() <= FEW && !beside { + // The refreshes from this one on are looked at on the threads + // ([`look_first`]: those the time here did not reach). + let mut looked = 0; + if light && (look_first() || self.refreshes.len() <= FEW && !beside) { let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] let all = self.refreshes.len(); - self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + looked = if look_first() { + sift(&mut self.refreshes, LOOK_BUDGET) + } else { + self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + self.refreshes.len() + }; PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); #[cfg(feature = "diagnostics")] FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed); @@ -11731,7 +11260,7 @@ impl Batch { let refreshes = std::mem::take(&mut self.refreshes); crate::shadow::wide_each(refreshes.len(), move |i| { let (shadow, from, to) = &refreshes[i]; - if (refreshes.len() > FEW || beside) && shadow.nothing_new(*from, *to - *from) { + if i >= looked && shadow.nothing_new(*from, *to - *from) { #[cfg(feature = "diagnostics")] FLUSHES[2].fetch_add(1, Ordering::Relaxed); return; @@ -11759,6 +11288,25 @@ impl Batch { } } +/// A title buffer copy done on the CPU at submission (`Step::Copy`, in +/// [`HostList::run_deferred`]), `len` bytes from `src` into title memory at +/// `dst`, and what the copies in the card's memory that hold `dst` make of +/// it. In this order: a copy whose CPU side is (or was) the title memory +/// written here waits for the straight sends in the air that read it before +/// the write (`crate::shadow::source_copying`; `LEONIDA_CARD_FROM_TITLE`), +/// the write, then the copies' CPU sides of their own take the bytes, behind +/// the same wait (`crate::shadow::send_copied`: what the card holds there may +/// be another value although ours did not change). +fn title_copy(dst: usize, src: usize, len: usize) { + crate::shadow::source_copying(dst, len); + copy_mapped(dst as *mut u8, src as *const u8, len, true); + // With the submission's one asking: the journal learns it. + crate::watch::wrote(dst, len); + if send::own() { + crate::shadow::send_copied(dst, len); + } +} + /// Copies title memory at submission. The ranges were checked against their /// resources when recorded, but the title may since have unmapped pages of /// them (tiled memory, page mappings), which read as zeros here; a title @@ -12103,1659 +11651,82 @@ fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, us } } -impl Host { - /// The queue everything of ours runs on, for a call that must go to it - /// in order with the lists (`crate::tiles`: a texture's levels are - /// given memory ahead of the list that uploads them). - pub(crate) fn queue(&self) -> &ID3D12CommandQueue { - &self.queue - } - - /// A buffer of at least `size` bytes the card writes and we read (a read - /// back), in the state copies into it need: one a list was done with, if - /// one of its size is kept ([`read_back_pool`]), else a new one. - #[cfg_attr(feature = "diagnostics", track_caller)] - pub(crate) fn read_back_buffer(&self, size: u64) -> Option { - if !read_back_pool() { - return self.new_read_back_buffer(size); - } - let size = read_back_size(size); - let kept = SPARE_BACKS.lock().unwrap_or_else(|e| e.into_inner()).take(size); - if let Some(SpareBack(buffer)) = kept { - BACKS[1].fetch_add(1, Ordering::Relaxed); - return Some(buffer); - } - self.new_read_back_buffer(size) - } - - /// A new buffer of `size` bytes in read-back memory, in the state copies - /// into it need. - #[cfg_attr(feature = "diagnostics", track_caller)] - fn new_read_back_buffer(&self, size: u64) -> Option { - BACKS[0].fetch_add(1, Ordering::Relaxed); - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_READBACK, - ..Default::default() - }; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size.max(1), - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - ..Default::default() - }; - let mut buffer: Option = None; - // SAFETY: plain creation of a read-back buffer. - let made = unsafe { - self.device.CreateCommittedResource( - &heap, - D3D12_HEAP_FLAG_NONE, - &desc, - D3D12_RESOURCE_STATE_COPY_DEST, - None, - &mut buffer, - ) - }; - #[cfg(feature = "diagnostics")] - if let Some(b) = &buffer { - crate::census::made_at(b, "read-back buffers", std::panic::Location::caller()); - } - match made { - Ok(()) => buffer, - Err(e) => { - tracing::warn!(error = %e, size, "no read-back buffer"); - None - } - } +/// The size of a window's client area ((0, 0) for a minimised one, or one that is gone). +fn client_size(hwnd: HWND) -> (u32, u32) { + let mut rect = RECT::default(); + // SAFETY: a plain query with room for the answer. + match unsafe { GetClientRect(hwnd, &mut rect) } { + Ok(()) => ((rect.right - rect.left).max(0) as u32, (rect.bottom - rect.top).max(0) as u32), + Err(_) => (0, 0), } +} - #[cfg_attr(feature = "diagnostics", track_caller)] - pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { - #[cfg(feature = "diagnostics")] - let began = std::time::Instant::now(); - MADE[0].fetch_add(1, Ordering::Relaxed); - MADE[1].fetch_add(size, Ordering::Relaxed); - // A small one is placed in a block (`LEONIDA_SMALL_BUFFER_POOL`). - if let Some(placed) = crate::pool::small::buffer(&self.device, crate::pool::small::UPLOAD, size) { - #[cfg(feature = "diagnostics")] - buffers_made::made(buffers_made::UPLOAD, size, true, began, std::panic::Location::caller()); - return Some(placed); - } - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_UPLOAD, - ..Default::default() - }; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size.max(1), - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - ..Default::default() - }; - let mut buffer: Option = None; - let mut data = std::ptr::null_mut(); - // SAFETY: plain creation and mapping of an upload buffer. - let made = unsafe { - self.device - .CreateCommittedResource( - &heap, - not_resident(), - &desc, - D3D12_RESOURCE_STATE_GENERIC_READ, - None, - &mut buffer, - ) - .and_then(|()| { - let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; - resident(&self.device, b)?; - b.Map(0, None, Some(&mut data)) - }) - }; - #[cfg(feature = "diagnostics")] - if let Some(b) = &buffer { - crate::census::made_at(b, "upload buffers", std::panic::Location::caller()); - } - #[cfg(feature = "diagnostics")] - if made.is_ok() - && let Some(b) = &buffer - { - crate::book::made(b, || "an upload buffer".into()); - } - #[cfg(feature = "diagnostics")] - buffers_made::made(buffers_made::UPLOAD, size, false, began, std::panic::Location::caller()); - match made { - Ok(()) => Some((buffer?, data.cast())), - Err(e) => { - crate::residency::allocation_error(&e); - tracing::warn!(error = %e, size, "no upload buffer"); - None +/// A visible top-level window of this process: the one the title made, if +/// it made one. +fn title_window() -> Option { + extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL { + let mut process = 0; + // SAFETY: a window handle from the enumeration; `found` is ours. + unsafe { + GetWindowThreadProcessId(hwnd, Some(&mut process)); + if process == windows::Win32::System::Threading::GetCurrentProcessId() + && IsWindowVisible(hwnd).as_bool() + { + *(found.0 as *mut Option) = Some(hwnd); + return false.into(); } } + true.into() } + let mut found: Option = None; + // SAFETY: the callback only writes `found`, which outlives the call. + let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) }; + found } -/// The swap chain formats a presented texture can be copied into: its own -/// family's. -pub(crate) fn swap_format(format: DXGI_FORMAT) -> Option { - Some(match format.0 { - 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM, - 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM, - 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM, - 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT, - _ => return None, - }) +/// `state` without the bits the host texture's flags forbid: the console +/// lets the title name states its own resources allow (unordered access on +/// a depth target, whose host copy cannot have both). +pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 { + // SAFETY: a plain query. + legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state) } -const BUFFERS: u32 = 2; - -/// The format two presented planes are composed into: 8 bits a channel, or -/// 10 while Streamline presents (`streamline`) unless `ten` is off. DLSS -/// frame generation makes its frames from the swap chain's picture, and -/// from an 8-bit one they came out in bands (sky, skin: aki-runtime's runs -/// of 2026-11-27, gone with 10 bits). `refused`: the swap chain did not take -/// the 10-bit format, and 8 bits are composed as before. -/// -/// From aki-gta6/aki-runtime 2f43f8b and bdcb503 (Aki-Developer), GPL-3.0. -/// A single plane is not converted as there: it is copied in the title's -/// own format, 10 bits or more where the title has them. -fn planes_format(streamline: bool, ten: bool, refused: bool) -> DXGI_FORMAT { - if streamline && ten && !refused { DXGI_FORMAT_R10G10B10A2_UNORM } else { DXGI_FORMAT_R8G8B8A8_UNORM } +/// [`legal_state`] for a texture with resource flags `flags`. +pub(crate) fn legal_for(flags: u32, state: u32) -> u32 { + // (flag, set or clear forbids, state bits): render target, unordered + // access, depth, denied shader resource. + const FORBIDDEN: [(u32, bool, u32); 4] = [ + (0x1, false, 0x4), + (0x4, false, 0x8), + (0x2, false, 0x10 | 0x20), + (0x8, true, 0x40 | 0x80), + ]; + FORBIDDEN + .iter() + .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny) + .fold(state, |s, &(_, _, bits)| s & !bits) } -/// Whether two planes are composed into 10 bits under Streamline -/// ([`planes_format`]). On by default; `LEONIDA_PRESENT_10BIT=0`: 8 bits, as -/// before. -fn present_tenbit() -> bool { - static TEN: OnceLock = OnceLock::new(); - *TEN.get_or_init(|| std::env::var_os("LEONIDA_PRESENT_10BIT").is_none_or(|v| v != "0")) -} - -/// The swap chain refused the 10-bit format once ([`planes_format`]). -static TEN_REFUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -struct Presenter { - swap_chain: IDXGISwapChain3, - width: u32, - height: u32, - format: DXGI_FORMAT, - copy: HostList, - /// With presents sent ahead ([`late_free_present`]): a list for each - /// present in the air, and the submission it last flew as (it is used - /// again once that one has finished). - ahead: Vec<(HostList, u64)>, - hwnd: HWND, - meter: Meter, - composer: Option, +/// For adapters without device-removed data (the software one): the last +/// commands each list of the failed submission noted (diagnostics, with +/// `LEONIDA_D3D12_DRED`). +fn last_notes(runs: &[&HostList]) -> String { #[cfg(feature = "diagnostics")] - panel: panel::Panel, - menu: menu::Menu, - /// Leonida: the trainer menu (`trainer`). - trainer: trainer::Overlay, - /// What the Lua mods draw (`leonida-lua`): the same overlay, with a place of its own. - lua: trainer::Overlay, - /// The swap chain was made to show a frame as soon as it is presented ([`tearing`]): its - /// flags, kept for `ResizeBuffers`, which may not change them. - tearing: bool, - /// Presents ask for that; off for the rest of the run once such a present is refused. - presents_tearing: bool, -} - -/// Whether the swap chain shows a frame as soon as it is presented, not at the screen's next -/// refresh (`DXGI_FEATURE_PRESENT_ALLOW_TEARING`): `LEONIDA_TEARING=1`, where the system has -/// it; off by default (unset or `0`: presents wait for the refresh, as before). On a G-SYNC or -/// FreeSync screen nothing tears; on another a frame may. -/// -/// From trustno1-coder/VIctory-NVIDIA 8fc2254 (trustno1-coder; `VICTORY_TEARING`, on there), -/// GPL-3.0. Its account: a window in front, which Windows shows without its compositor -/// ("independent flip"), had each frame wait for a refresh with two buffers, frame times -/// rounded up to whole refreshes, about 2 frames a second fewer than the same window behind -/// another; and on an RTX 5070 at 1440p presents of this kind were not shown (a white window), -/// which is why a refused one ends them for the run. Off here until it has run in the game: -/// not measured on this tree, nor tried with Streamline's swap chain (`crate::fg`). -fn tearing(factory: &IDXGIFactory2) -> bool { - if !crate::switch::on("LEONIDA_TEARING") { - return false; - } - let Ok(factory) = factory.cast::() else { - return false; - }; - let mut allowed = windows::core::BOOL(0); - // SAFETY: a BOOL-sized answer for this feature. - let asked = unsafe { - factory.CheckFeatureSupport( - DXGI_FEATURE_PRESENT_ALLOW_TEARING, - (&raw mut allowed).cast(), - std::mem::size_of_val(&allowed) as u32, - ) - }; - asked.is_ok() && allowed.as_bool() -} - -/// The swap chain's flags for [`tearing`]. -fn chain_flags(tearing: bool) -> DXGI_SWAP_CHAIN_FLAG { - if tearing { DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING } else { DXGI_SWAP_CHAIN_FLAG(0) } -} - -/// The frame rate the meter last counted, in tenths of a frame a second (0: none yet): for the -/// line at the top of the picture (`menu.rs`). -pub(crate) static METER_FPS_TENTHS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - -/// The frame rate, shown in the window's caption every second and logged -/// every few seconds. -struct Meter { - since: std::time::Instant, - frames: u32, - #[cfg(feature = "diagnostics")] - copy_stats_frames: u64, - drawn: u64, - logged: std::time::Instant, - /// The caption the window had, once read. - caption: Option>, - /// Frame times and stalls, logged with the line. - stalls: frametime::Meter, -} - -impl Meter { - fn new() -> Self { - let now = std::time::Instant::now(); - Meter { - since: now, - frames: 0, - #[cfg(feature = "diagnostics")] - copy_stats_frames: 0, - drawn: crate::draw::drawn(), - logged: now, - caption: None, - stalls: frametime::Meter::new( - crate::pipeline::made(), - RESIDENT[1].load(Ordering::Relaxed), - ), - } - } - - /// Whether the next frame counted makes the frame-rate line. - #[cfg(feature = "diagnostics")] - fn line_due(&self) -> bool { - self.since.elapsed() >= std::time::Duration::from_secs(1) - } - - /// Counts a presented frame. - fn frame(&mut self, hwnd: HWND) { - #[cfg(feature = "diagnostics")] - tracing::debug!(target: "leonida_gpu::frame", token = crate::frame::current(), "present"); - #[cfg(feature = "diagnostics")] - crate::copystat::presented(); - self.stalls.presented(std::time::Instant::now()); - self.frames += 1; - #[cfg(feature = "diagnostics")] - { - self.copy_stats_frames += 1; - } - let elapsed = self.since.elapsed(); - if elapsed < std::time::Duration::from_secs(1) { - return; - } - let drawn = crate::draw::drawn(); - let frames = f64::from(self.frames); - let fps = frames / elapsed.as_secs_f64(); - let ms = elapsed.as_secs_f64() * 1000.0 / frames; - METER_FPS_TENTHS.store((fps * 10.0).round() as u32, Ordering::Relaxed); - let draws = (drawn - self.drawn) as f64 / frames; - (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn); - // The five-second lines come with this one. - let five = self.logged.elapsed() >= std::time::Duration::from_secs(5); - if five { - self.logged = std::time::Instant::now(); - // (Here: the frame times are this meter's.) - self.stalls.line( - crate::pipeline::making(), - crate::pipeline::made(), - RESIDENT[1].load(Ordering::Relaxed), - crate::residency::available_commit(), - ); - } - // (The copy counters run from one five-second line to the next.) - #[cfg(feature = "diagnostics")] - let copies = if five { std::mem::take(&mut self.copy_stats_frames) as f64 } else { 0.0 }; - #[cfg(not(feature = "diagnostics"))] - let copies = 0.0; - let due = MeterDue { frames, fps, ms, draws, copies, five }; - // Leonida: on a thread of their own ([`meter_beside`]), else here as before. - if !(meter_beside() && meter_lines_beside(due)) { - Self::lines(due); - } - self.show(hwnd, fps, ms, draws); - } - - /// The frame meter's lines of a second ([`Meter::frame`]), and every fifth - /// second's (`due.five`). - fn lines(due: MeterDue) { - let MeterDue { frames, fps, ms, draws, copies, five } = due; - #[cfg(not(feature = "diagnostics"))] - let _ = copies; - // Of a frame, ms preparing submissions and ms waiting for the GPU. - let [cpu, gpu] = [0, 1].map(|i| { - SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames - }); - let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| { - let scale = if i % 2 == 0 { 1e3 } else { 1e6 }; - PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames - }); - let [back_ms, back_mb] = [0, 1].map(|i| { - COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames - }); - let dropped = crate::draw::take_dropped() as f64 / frames; - let indirect = crate::list::take_indirect() as f64 / frames; - // Of those two together, by reason (`crate::drops`): what is left - // out on purpose apart from what was not meant to be. - let (drop_reasons, _, _) = crate::drops::line(frames); - let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed); - let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames; - let refused = BUDGET_NOTES[0].swap(0, Ordering::Relaxed) as f64 / frames; - let biggest = BUDGET_NOTES[1].swap(0, Ordering::Relaxed); - tracing::info!( - "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame; {refused:.2} indirect records a frame ran empty for want of their list's budget (2^27), the largest cost of one {biggest} (0: under 2^22)" - ); - let wide = WIDE_NOTES[0].swap(0, Ordering::Relaxed); - let wide_cut = WIDE_NOTES[1].swap(0, Ordering::Relaxed) as f64 / frames; - if wide > 0 { - tracing::info!( - "indirect dispatches: the most groups in x one asked for {wide}, more than the card is given (65535, or 2^20 where it runs them: indirect.rs, widest); {wide_cut:.0} groups a frame did not run for it" - ); - } - crate::shadow::exact_line(frames); - crate::draw::list_alias_line(frames); - crate::descriptor::sync_line(frames); - crate::port_descriptors::line(frames); - late_line(frames); - crate::queue::behind_line(frames); - card_clock_line(frames, ms); - #[cfg(feature = "diagnostics")] - spans::line(frames); - crate::shadow::back_line(frames); - #[cfg(feature = "diagnostics")] - split_line(frames); - { - let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); - let wc_left = crate::shadow::WC_LEFT.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames; - let [ro_declared, ro_left] = - [0, 1].map(|i| crate::shadow::GPU_RO_DECLARED[i].swap(0, Ordering::Relaxed) as f64 / 1e6 / frames); - if passes + compares + wc_left + ro_declared > 0.0 { - tracing::info!( - "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \ - ranges were sent up (LEONIDA_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes; \ - {wc_left:.1} MB declared written in write-combined memory left on the card (LEONIDA_WC_NO_BACK); \ - {ro_declared:.1} MB declared written in memory the console has the GPU read only, {ro_left:.1} MB of it \ - left out (LEONIDA_GPU_READ_ONLY_NO_BACK)", - if rehash_runs() { "on" } else { "off" } - ); - } - } - { - let [own, asking, still, all] = - [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); - if all >= 1.0 { - tracing::info!( - "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \ - is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \ - hold still (the runtime remapping it); the rest is reading, hashing and detiling" - ); - } - let [changes, waiting, held] = - [0, 1, 2].map(|i| crate::watch::REMAP_TIMES[i].swap(0, Ordering::Relaxed) as f64 / frames); - let longest = crate::watch::REMAP_TIMES[3].swap(0, Ordering::Relaxed) as f64 / 1000.0; - let [named, passed, stood] = - [0, 1, 2].map(|i| crate::watch::SPAN_READS[i].swap(0, Ordering::Relaxed) as f64 / frames); - if changes > 0.0 { - tracing::info!( - "the runtime's changes of mapping per frame: {changes:.1}, {:.2} ms waiting for reads in place to end, \ - {:.2} ms holding title memory still (longest {longest:.2} ms); of {named:.0} reads in place that named \ - their range, {passed:.1} went on beside a change of other memory and {stood:.1} waited for one of \ - their own (LEONIDA_REMAP_SPANS=0: all wait for every change)", - waiting / 1000.0, - held / 1000.0 - ); - } - let [through, left, filled, short] = - [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); - if through + left + filled > 0.0 { - tracing::info!( - "texture refreshes that did not wait for title memory to hold still, per frame (LEONIDA_TEXTURE_NO_WAIT=1): \ - {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there), \ - {filled:.1} first fillings from the pages there (LEONIDA_TEXTURE_FILL=0: left empty), {short:.1} of them \ - with less than was mapped (looked at again)" - ); - } - } - { - let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames); - if copies > 0.0 { - tracing::info!( - "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \ - (LEONIDA_JOIN_COPIES=1 makes those one copy with it: now {})", - if join_copies() { "on" } else { "off" } - ); - } - } - // Passes over the heap's buffer views for shaders that pick them by index. - let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames; - let picked_ms = - crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames; - // Copies between depth textures and their colour twins, each way. - let [twin_to_depth, twin_to_colour] = - [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames); - // Depth planes drawn from their twins. - let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames; - // Copies in the card's memory (`crate::shadow::cards`). - let card = crate::shadow::card_stats(); - #[cfg(feature = "diagnostics")] - let slow = crate::watch::slow_asks(); - // Over the same frames as the counts above. - #[cfg(feature = "diagnostics")] - let drops = crate::pipeline::take_drops(); - if five { - tracing::info!( - "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)", - crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed) - ); - crate::tiles::status(); - { - let [queued, due, away, partly, oldest] = - [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); - let [same, parts, tails] = - [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed)); - tracing::info!( - "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \ - {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \ - the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \ - as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \ - {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \ - {} ranges of memory mapped, unmapped or written under texture views ({} in a full list made smaller), {} slots made due by them, \ - {} made slots found unmapped and made null", - crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed), - crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed), - crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed), - crate::descriptor::host::STALE[0].load(Ordering::Relaxed), - crate::descriptor::host::STALE[1].load(Ordering::Relaxed), - crate::descriptor::host::STALE[2].load(Ordering::Relaxed), - crate::descriptor::host::STALE[3].load(Ordering::Relaxed), - crate::descriptor::host::STALE[4].load(Ordering::Relaxed) - ); - } - tracing::info!( - "slot writes past the lock of placed texture views (LEONIDA_SPANS_QUICK), since the start: {} of {}; \ - notes that left the texture queue's lock alone (LEONIDA_QUEUE_MARKS): {} slot records, {} table reads, \ - {} stale views", - crate::descriptor::host::SPANS_QUICK[0].load(Ordering::Relaxed), - crate::descriptor::host::SPANS_QUICK[0].load(Ordering::Relaxed) - + crate::descriptor::host::SPANS_QUICK[1].load(Ordering::Relaxed), - crate::descriptor::host::QUEUE_SPARED[0].load(Ordering::Relaxed), - crate::descriptor::host::QUEUE_SPARED[1].load(Ordering::Relaxed), - crate::descriptor::host::QUEUE_SPARED[2].load(Ordering::Relaxed) - ); - tracing::info!( - "views of table entries this thread had read (LEONIDA_VIEW_CACHE), since the start: {} answered so, {} read \ - under the lock; entries of tables read in place found brought up to date in their list \ - (LEONIDA_ENTRY_ONCE): {} of {}; placed textures found again with nothing in their memory \ - (LEONIDA_ALIAS_QUICK): {} of {}; tables made afresh found again by what they hold \ - (LEONIDA_CONTENT_TABLES): {} at their place, {} at another; host lists given to the title's lists \ - at their submission closed already (LEONIDA_CLOSED_AHEAD): {}, closed by the line's thread: {}; \ - dynamic slots whose resource their list keeps (LEONIDA_KEEP_BY_LIST): {}, {} of them its first", - crate::descriptor::VIEW_CACHE_COUNTS[0].load(Ordering::Relaxed), - crate::descriptor::VIEW_CACHE_COUNTS[1].load(Ordering::Relaxed), - crate::draw::ENTRY_ONCE[1].load(Ordering::Relaxed), - crate::draw::ENTRY_ONCE[0].load(Ordering::Relaxed) + crate::draw::ENTRY_ONCE[1].load(Ordering::Relaxed), - crate::resource::ALIAS_QUICK[0].load(Ordering::Relaxed), - crate::resource::ALIAS_QUICK[0].load(Ordering::Relaxed) + crate::resource::ALIAS_QUICK[1].load(Ordering::Relaxed), - crate::draw::CONTENT_TABLES[0].load(Ordering::Relaxed), - crate::draw::CONTENT_TABLES[1].load(Ordering::Relaxed), - crate::list::CLOSED_TAKEN[0].load(Ordering::Relaxed), - crate::list::CLOSED_TAKEN[1].load(Ordering::Relaxed), - crate::descriptor::host::KEEP_BY_LIST[0].load(Ordering::Relaxed), - crate::descriptor::host::KEEP_BY_LIST[1].load(Ordering::Relaxed) - ); - tracing::info!( - "slots of textures made while lists sent before them ran, shown once those had run (LEONIDA_SHOW_NEW_LATER={}), since the start: {}", - u8::from(crate::descriptor::host::show_new_later()), - crate::descriptor::host::NEW_LATER.load(Ordering::Relaxed) - ); - if crate::resource::held_only() { - let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed)); - let [flipped, missed] = [0, 1].map(|i| crate::descriptor::host::FLIPPED[i].load(Ordering::Relaxed)); - tracing::info!( - "textures from the first level viewed (LEONIDA_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \ - levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \ - {flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \ - out as the host copy held those bytes (LEONIDA_TEXTURE_SAME=0: made); {} MB of texture blocks free; \ - {} looks for textures to let go, {:.2} ms each, the longest {:.1}", - bytes >> 20, - whole >> 20, - crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed), - crate::pool::texture_room() >> 20, - crate::resource::SWEPT_US[0].load(Ordering::Relaxed), - crate::resource::SWEPT_US[1].load(Ordering::Relaxed) as f64 - / 1e3 - / crate::resource::SWEPT_US[0].load(Ordering::Relaxed).max(1) as f64, - crate::resource::SWEPT_US[2].load(Ordering::Relaxed) as f64 / 1e3 - ); - } - { - let mode = crate::watch::page_writes(); - let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed)); - let [kept, dropped, slots, uploaded] = - [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed)); - tracing::info!( - "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} in a full list made smaller); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (LEONIDA_PAGE_WRITES: unset or guards opens the guarded blocks, 0 counts only, 1, slots, all)", - bytes >> 20, - if mode & 1 != 0 { "opened, taken again" } else { "left as they were" }, - if mode & 4 != 0 { "told as well" } else { "counted only" }, - if mode & 2 != 0 { "made due again" } else { "left as they were" } - ); - } - #[cfg(feature = "diagnostics")] - tracing::info!( - "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms", - slow[0] as f64 / frames, - slow[1] as f64 / 1e3 / frames, - slow[2] as f64 / 1e3 - ); - if crate::shadow::cards() { - let per_frame = |i: usize| card[i] as f64 / frames; - tracing::info!( - "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \ - {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \ - ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)", - card[7], - card[8] >> 20, - card[9] >> 20, - per_frame(0) / 1e6, - per_frame(1), - per_frame(2), - per_frame(3), - per_frame(4) / 1e6, - per_frame(5), - per_frame(6) / 1e3 - ); - } - // Where the windows outside buffers lie (card or PC memory). - crate::shadow::window_line(); - tracing::info!( - "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ - {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \ - GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \ - dropped {dropped:.0} without a host pipeline ({making} being made) and \ - {indirect:.0} indirect, of both per frame: {drop_reasons}; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \ - textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \ - {picked_waiting} waiting, {picked_away} passed over unmapped; depth textures with unordered access: {du0} made, bound as depth {du1}x, cleared as depth {du2}x, unordered views refused {du3}x; buffer views left null as the host would refuse them: {refused}; {rawcuts}", - picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed), - picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20, - picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed), - picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed), - du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed), - du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed), - du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed), - du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed), - refused = format!( - "{} ({} copies made of views off their buffer's elements); depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass", - crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed), - crate::shadow::OWN_MADE.load(Ordering::Relaxed), - crate::resource::TWINS[0].load(Ordering::Relaxed), - crate::resource::TWINS[1].load(Ordering::Relaxed), - crate::resource::PLANES[1].load(Ordering::Relaxed), - crate::resource::PLANES[2].load(Ordering::Relaxed) - ), - rawcuts = crate::descriptor::host::raw_cuts_line(), - making = crate::pipeline::making(), - placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed), - objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed) - ); - #[cfg(feature = "diagnostics")] - { - let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames); - tracing::info!( - "what shaders wrote put into title memory per frame (LEONIDA_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps", - put[0], - put[1], - put[2] / 1e6, - put[3] - ); - crate::shadow::elide::log(frames); - traffic::line(copies); - crate::copystat::log(copies); - for (why, n) in drops.iter().take(40) { - tracing::info!( - "dropped {:.1}/frame without a host pipeline: {why}", - *n as f64 / frames - ); - } - } - } - } - - /// The window's caption with this second's frame rate. - fn show(&mut self, hwnd: HWND, fps: f64, ms: f64, draws: f64) { - if self.caption.is_none() { - // The window's own text, read without a message. - let mut buffer = vec![0u16; 512]; - // SAFETY: a window handle and a buffer of that length. - let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) }; - buffer.truncate(n.max(0) as usize); - self.caption = Some(buffer); - } - let Some(caption) = &self.caption else { return }; - // LOCAL (11/26): with frame generation, the frames shown too. - let shown = crate::fg::shown_per_frame(); - let text = if shown > 1 { - format!(" | Leonida {fps:.0} fps (frame gen {:.0} fps) {ms:.1} ms/frame {draws:.0} draws/frame", fps * f64::from(shown)) - } else { - format!(" | Leonida {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame") - }; - let mut text: Vec = caption.iter().copied().chain(text.encode_utf16()).collect(); - text.push(0); - // Setting the text waits for the window's thread (a title thread, - // which may not pump for a while), so a thread of ours does it and - // presenting never waits; it takes the newest text when free. - static PENDING: Mutex)>> = Mutex::new(None); - static SETTER: std::sync::Once = std::sync::Once::new(); - *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text)); - SETTER.call_once(|| { - let _ = std::thread::Builder::new() - .name("leonida-caption".into()) - .spawn(|| { - loop { - let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take(); - match next { - // SAFETY: a window handle and a NUL-terminated text. - Some((hwnd, text)) => unsafe { - let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr())); - }, - None => std::thread::sleep(std::time::Duration::from_millis(100)), - } - } - }); - }); - } -} - -/// What the frame meter's lines of a second are made from ([`Meter::lines`]). -#[derive(Clone, Copy)] -struct MeterDue { - /// The frames presented since the last line. - frames: f64, - fps: f64, - ms: f64, - draws: f64, - /// The frames the copy counters ran over (`crate::copystat::log`), with the five-second lines. - copies: f64, - /// The five-second lines come with this one. - five: bool, -} - -/// Leonida: `LEONIDA_METER_BESIDE` (on unless `0`): the frame meter's lines of each second are made on -/// a thread of their own instead of in the present, on the line's thread, which the frame waits for. -/// Made there they held that thread some 37 ms once a second (a timeline of run d141: 16.4 ms of it in -/// `VirtualQuery` for the copy counters' busiest ranges, the rest the lines themselves; a frame of the -/// line's thread is 45-60 ms of work). After kylepelham/El1xr d7ff66ab (`VICTORY_RAMLINE_BESIDE`: -/// that fork's present spikes every few seconds were its memory lines made in the present). -/// `LEONIDA_AB` can switch it. -fn meter_beside() -> bool { - crate::toggled!("LEONIDA_METER_BESIDE") -} - -/// Hands `due` to the meter's thread, made on first use (`false`: there is none). A line still waiting -/// for that thread when the next comes is joined to it: its frames are counted with the next one's. -fn meter_lines_beside(mut due: MeterDue) -> bool { - static DUE: (Mutex>, std::sync::Condvar) = (Mutex::new(None), std::sync::Condvar::new()); - static THREAD: std::sync::OnceLock = std::sync::OnceLock::new(); - let started = *THREAD.get_or_init(|| { - let made = std::thread::Builder::new().name("leonida-meter".into()).spawn(|| { - loop { - let due = { - let mut next = DUE.0.lock().unwrap_or_else(|e| e.into_inner()); - loop { - if let Some(due) = next.take() { - break due; - } - next = DUE.1.wait(next).unwrap_or_else(|e| e.into_inner()); - } - }; - Meter::lines(due); - } - }); - match made { - Ok(_) => { - tracing::info!("the frame meter's lines are made on a thread of their own (LEONIDA_METER_BESIDE=0: in the present)"); - true - } - Err(e) => { - tracing::warn!(error = %e, "no thread for the frame meter's lines: they are made in the present"); - false - } - } - }); - if !started { - return false; - } - let mut next = DUE.0.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(before) = next.take() { - due.frames += before.frames; - due.copies += before.copies; - due.five |= before.five; - } - *next = Some(due); - drop(next); - DUE.1.notify_one(); - true -} - -impl Host { - /// Shows `texture`, which is in `state` (a host state) and stays in it, - /// as frame `frame` (saved if captures are on). `None` if nothing was - /// shown; else, in diagnostics builds, whether the frame was black. - #[allow(dead_code)] - pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option { - self.present_planes(texture, state, None, frame) - } - - /// Shows `texture`, optionally alpha-compositing a second `overlay` plane - /// over it (Series S two-plane presentation), and returns them to their states. - pub(crate) fn present_planes( - &self, - texture: &ID3D12Resource, - state: u32, - overlay: Option<(&ID3D12Resource, u32)>, - frame: u64, - ) -> Option { - // SAFETY: a live resource. - let desc = unsafe { texture.GetDesc() }; - // Leonida: whether the title presents the interface on a plane of its own (what frame generation could be - // given as the interface, apart from the scene), said each time that changes, a few times at most. - { - static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); - static SAID: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); - let now = if overlay.is_some() { 2 } else { 1 }; - if LAST.swap(now, Ordering::Relaxed) != now && SAID.fetch_add(1, Ordering::Relaxed) < 6 { - match overlay { - Some((over, _)) => { - // SAFETY: a live overlay resource. - let d = unsafe { over.GetDesc() }; - tracing::info!( - frame, - scene = ?(desc.Width, desc.Height, desc.Format.0), - interface = ?(d.Width, d.Height, d.Format.0), - "presents: the interface on a plane of its own over the scene" - ); - } - None => tracing::info!(frame, scene = ?(desc.Width, desc.Height, desc.Format.0), "presents: one plane"), - } - } - } - let planes = overlay.and_then(|(over, over_state)| { - // SAFETY: a live overlay resource. - let over_desc = unsafe { over.GetDesc() }; - Some(( - over, - D3D12_RESOURCE_STATES(over_state as i32), - crate::compose::view(&desc)?, - crate::compose::view(&over_desc)?, - )) - }); - let format = if planes.is_some() { - planes_format(crate::fg::active(), present_tenbit(), TEN_REFUSED.load(Ordering::Relaxed)) - } else { - let Some(format) = swap_format(desc.Format) else { - tracing::warn!(format = desc.Format.0, "cannot present this format"); - return None; - }; - format - }; - let (width, height) = (desc.Width as u32, desc.Height); - let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); - if presenter.is_none() { - *presenter = match self.presenter(width, height, format) { - Ok(p) => Some(p), - Err(e) => { - tracing::warn!(error = %e, "no swap chain"); - return None; - } - }; - } - let state_u32 = state; - let p = presenter.as_mut()?; - if planes.is_some() && p.composer.is_none() { - match crate::compose::Composer::new(self, format) { - Ok(c) => p.composer = Some(c), - Err(e) => { - tracing::warn!(error = %e, "two-plane composer not made; showing base plane only"); - drop(presenter); - return self.present_planes(texture, state_u32, None, frame); - } - } - } - // Leonida: the swap chain is the picture, which the window stretches. With `LEONIDA_PRESENT_SCALE=fit` - // and a window of another shape it is a frame of the window's shape with the picture in its middle - // (`crate::aspect`), which the window then scales evenly. - let placed = if crate::aspect::fit() { - crate::aspect::frame((width, height), client_size(p.hwnd)) - } else { - crate::aspect::Frame::whole(width, height) - }; - let whole = placed.is_whole((width, height)); - if (p.width, p.height, p.format) != (placed.width, placed.height, format) { - // Presents sent ahead hold back buffers until they have run. - settle_now(WHY_SYNC); - // Leonida: FSR 3 frame generation's context goes with the buffers (made again at the next upscale). - crate::fsr::resizing(); - // SAFETY: no back buffer is held; every submission was waited for. - let resized = unsafe { - p.swap_chain - .ResizeBuffers(BUFFERS, placed.width, placed.height, format, chain_flags(p.tearing)) - }; - match resized { - Ok(()) => { - if p.format != format { - p.composer = None; - } - (p.width, p.height, p.format) = (placed.width, placed.height, format); - // Leonida: the trainer menu is painted for the height of what is shown. - leonida_menu::set_height(placed.height); - tracing::info!( - width = placed.width, - height = placed.height, - picture = ?(width, height), - at = ?(placed.left, placed.top), - format = format.0, - frame, - "the swap chain's buffers were made again for another size or format" - ); - self.log_video_memory("right after the swap chain's buffers were made again"); - } - Err(e) if planes.is_some() - && format == DXGI_FORMAT_R10G10B10A2_UNORM - && !TEN_REFUSED.swap(true, Ordering::Relaxed) => - { - // Once: the planes are composed into 8 bits from now on. - tracing::warn!(error = %e, "the swap chain does not take 10 bits a channel: the two planes are composed into 8, as before"); - drop(presenter); - return self.present_planes(texture, state_u32, overlay, frame); - } - Err(e) => { - tracing::warn!(error = %e, width, height, "swap chain not resized"); - return None; - } - } - } - if planes.is_some() && p.composer.is_none() { - match crate::compose::Composer::new(self, format) { - Ok(c) => p.composer = Some(c), - Err(e) => { - tracing::warn!(error = %e, "two-plane composer not made after resize; showing base plane only"); - drop(presenter); - return self.present_planes(texture, state_u32, None, frame); - } - } - } - let state = D3D12_RESOURCE_STATES(state_u32 as i32); - // SAFETY: our swap chain, list and live source texture(s). - unsafe { - let index = p.swap_chain.GetCurrentBackBufferIndex(); - let Ok(back) = p.swap_chain.GetBuffer::(index) else { - return None; - }; - // Leonida: what this present has to do for the trainer menu - // (`trainer`): one atomic load, and nothing more while the menu - // is closed and no screenshot is asked for. - let trainer_work = leonida_menu::work(); - // Leonida: the Lua mods are told a frame is presented (one load - // with LEONIDA_LUA=0; never waits for them). - leonida_lua::tick(); - // Sent ahead ([`late_free_present`]) unless the frame is to be - // read back at once (a saved or listed frame): then a list of - // its own, one whose last flight has finished or a new one. - #[cfg(feature = "diagnostics")] - let read_now = crate::capture::wanted(frame) - || crate::capture::listed(frame) - // Leonida: a screenshot asked for in the trainer menu is read back at once too. - || trainer_work & leonida_menu::SHOT != 0; - #[cfg(not(feature = "diagnostics"))] - let read_now = false; - let slot = if late_free_present() && !read_now { - let finished = FINISHED.load(Ordering::Acquire); - p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| { - let list = self.new_list().ok()?; - list.close(); - p.ahead.push((list, 0)); - Some(p.ahead.len() - 1) - }) - } else { - None - }; - let copy = match slot { - Some(i) => &p.ahead[i].0, - None => &p.copy, - }; - copy.reset(); - copy.keep(texture); - let list = ©.list; - let composed = if let Some((over, over_state, base_fmt, over_fmt)) = planes { - copy.keep(over); - if let Some(composer) = p.composer.as_mut() { - let mut pre = Vec::with_capacity(3); - if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { - pre.push(transition(texture, state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); - } - if over_state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { - pre.push(transition(over, over_state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); - } - pre.push(transition(&back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); - list.ResourceBarrier(&pre); - if !whole { - // The bars: black around the picture. - list.ClearRenderTargetView(self.rtv(Some(&back), None), &[0.0, 0.0, 0.0, 1.0], None); - } - let compose_slot = slot.map_or(0, |i| i + 1); - if let Err(err) = composer.record( - self, - compose_slot, - list, - [(texture, base_fmt), (over, over_fmt)], - &back, - (placed.left, placed.top), - (width, height), - ) { - copy.close(); - drop(back); - drop(presenter); - tracing::warn!(%err, "could not record display composite; presenting the base plane"); - return self.present_planes(texture, state_u32, None, frame); - } - static ONCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - if !ONCE.swap(true, Ordering::Relaxed) { - tracing::info!( - frame, - width, - height, - base_format = base_fmt.0, - overlay_format = over_fmt.0, - "display output: compositing two planes (overlay active)" - ); - } - let mut post = Vec::with_capacity(3); - if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { - post.push(transition(texture, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, state)); - } - if over_state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { - post.push(transition(over, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, over_state)); - } - post.push(transition( - &back, - D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATE_COPY_DEST, - )); - list.ResourceBarrier(&post); - true - } else { - false - } - } else { - false - }; - if !composed { - let mut pre = Vec::with_capacity(2); - if state != D3D12_RESOURCE_STATE_COPY_SOURCE { - pre.push(transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE)); - } - if whole { - pre.push(transition( - &back, - D3D12_RESOURCE_STATE_PRESENT, - D3D12_RESOURCE_STATE_COPY_DEST, - )); - list.ResourceBarrier(&pre); - list.CopyResource(&back, texture); - } else { - // Leonida: the bars (`crate::aspect`): the buffer cleared to black, then the picture copied - // into its middle as it is. - pre.push(transition(&back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); - list.ResourceBarrier(&pre); - list.ClearRenderTargetView(self.rtv(Some(&back), None), &[0.0, 0.0, 0.0, 1.0], None); - list.ResourceBarrier(&[transition( - &back, - D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATE_COPY_DEST, - )]); - let location = |resource: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { - pResource: std::mem::transmute_copy(resource), - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, - }; - list.CopyTextureRegion(&location(&back), placed.left, placed.top, 0, &location(texture), None); - } - } - // What the overlays are laid over: the whole buffer, bars and all. - let shown = (placed.width, placed.height); - // Leonida: the trainer menu's screenshot is this present's - // read-back too: the title's picture, before the panel and the - // menus are laid over it. - #[cfg(feature = "diagnostics")] - let shot = trainer::shot(trainer_work); - // (A recorded frame's present time, for the time from a key to the frame that shows it.) - #[cfg(feature = "diagnostics")] - crate::capture::note_present(frame); - #[cfg(feature = "diagnostics")] - let capture = (crate::capture::wanted(frame) || shot.is_some()) - .then(|| { - if composed { - list.ResourceBarrier(&[transition( - &back, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_COPY_SOURCE, - )]); - let res = crate::capture::read_back(&self.device, list, &back); - list.ResourceBarrier(&[transition( - &back, - D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATE_COPY_DEST, - )]); - res - } else { - crate::capture::read_back(&self.device, list, texture) - } - }) - .flatten(); - #[cfg(feature = "diagnostics")] - let probe = if slot.is_some() || composed { - None - } else { - crate::capture::probe(&self.device, list, texture) - }; - #[cfg(feature = "diagnostics")] - let watched = if composed { - None - } else { - crate::popwatch::take(&self.device, list, texture) - }; - #[cfg(feature = "diagnostics")] - p.panel.draw(self, copy, &back, shown, format); - p.menu.draw(self, copy, &back, shown, format); - // Leonida: what the Lua mods draw, then the trainer menu, where the - // panel and the F1 menu are put (so frame generation sees all alike). - if trainer_work & leonida_menu::LUA_DRAW != 0 { - p.lua.draw_lua(self, copy, &back, shown, format); - } - if trainer_work & leonida_menu::DRAW != 0 { - p.trainer.draw(self, copy, &back, shown, format); - } - #[cfg(not(feature = "diagnostics"))] - let _ = frame; - if composed { - list.ResourceBarrier(&[transition( - &back, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_PRESENT, - )]); - } else { - let mut post = Vec::with_capacity(2); - if state != D3D12_RESOURCE_STATE_COPY_SOURCE { - post.push(transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state)); - } - post.push(transition( - &back, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_PRESENT, - )); - list.ResourceBarrier(&post); - } - // Leonida: FSR 3 frame generation's prepare dispatch and configuration for this present (crate::fsr), - // last on the list before `Present`. Series S's base plane is the colour without the interface. - let hudless = (composed && whole).then_some((texture, state_u32)); - crate::fsr::before_present( - &self.device, - &p.swap_chain, - list, - [placed.width, placed.height], - format, - hudless, - &|t: &ID3D12Resource| copy.keep(t), - ); - copy.close(); - let flown = match slot { - Some(i) => { - let flown = self.execute_own(copy); - p.ahead[i].1 = flown; - flown - } - None => { - self.execute(&[copy]); - 0 - } - }; - #[cfg(feature = "diagnostics")] - if let Some(taken) = watched { - crate::popwatch::sent(taken, flown, frame); - } - #[cfg(not(feature = "diagnostics"))] - let _ = flown; - #[cfg(feature = "diagnostics")] - if let Some((buffer, footprint)) = capture { - if crate::capture::wanted(frame) { - crate::capture::save_read_back(frame, &buffer, &footprint); - } - // Leonida: the same read-back as the trainer menu's screenshot. - if let Some(path) = shot { - trainer::save_shot(path, &buffer, &footprint); - } - } - #[cfg(feature = "diagnostics")] - crate::replay::record::present(texture, state); - let mut showing = crate::timeline::span("the host's Present"); - // Leonida: held to a fraction of the recent mean interval (`LEONIDA_PRESENT_SMOOTH`). - crate::smooth::hold(); - // Leonida: for the A/B phase lines, when each frame is handed over to be shown. - #[cfg(feature = "diagnostics")] - crate::ab::shown(); - // Leonida: with bars, frame generation is told where in the buffer the picture is. - crate::fg::picture_box((!whole).then_some([placed.left, placed.top, width, height])); - // (With one plane, the texture whose copy without the interface is tagged.) - crate::fg::present_start(frame, (!composed).then_some(texture)); - if p.presents_tearing { - // ([`tearing`]: shown at once; a refused one ends that for the run.) - let shown = p.swap_chain.Present(0, DXGI_PRESENT_ALLOW_TEARING); - if shown.is_err() { - tracing::warn!(code = %shown, frame, "a present shown at once was refused; presenting at the next refresh for the rest of the run"); - p.presents_tearing = false; - let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); - } - } else { - let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); - } - crate::smooth::presented(); - crate::fg::present_end(frame); - showing.next("the frame meter"); - #[cfg(feature = "diagnostics")] - p.panel.frame(p.meter.line_due()); - p.menu.frame(); - p.meter.frame(p.hwnd); - showing.end(); - #[cfg(feature = "diagnostics")] - return Some(probe.is_some_and(|b| crate::capture::black(&b))); - #[cfg(not(feature = "diagnostics"))] - Some(false) - } - } - - fn presenter( - &self, - width: u32, - height: u32, - format: DXGI_FORMAT, - ) -> windows::core::Result { - let hwnd = match title_window() { - Some(hwnd) => hwnd, - // Leonida: a window of our own takes the shape `LEONIDA_ASPECT` asks for, as the title's does. - None => match crate::aspect::asked() { - Some(aspect) => { - let (w, h) = crate::aspect::widened(width as i32, height as i32, aspect); - window(w as u32, h as u32)? - } - None => window(width, height)?, - }, - }; - self.log_video_memory("right before the swap chain is made"); - // SAFETY: plain object creation for our window. - unsafe { - let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; - let tearing = tearing(&factory); - if tearing { - tracing::info!("swap chain: frames shown as soon as presented (LEONIDA_TEARING=1)"); - } - // LOCAL (11/26): with `LEONIDA_FRAME_GEN`, Streamline's proxy factory (crate::fg). - let factory = crate::fg::start(&self.device, factory); - let desc = DXGI_SWAP_CHAIN_DESC1 { - Width: width, - Height: height, - Format: format, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, - BufferCount: BUFFERS, - SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, - Flags: chain_flags(tearing).0 as u32, - ..Default::default() - }; - // Leonida: with `LEONIDA_FSR_FRAMEGEN=1` (and no Streamline swap chain), FidelityFX's frame interpolation - // swap chain (crate::fsr); as before if it cannot be made. - let swap_chain = match crate::fsr::swap_chain(&factory, &self.queue, hwnd, &desc) { - Some(swap_chain) => swap_chain, - None => factory - .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)? - .cast::()?, - }; - // Leonida: with `LEONIDA_CAPTURE_SHOWN=1`, what the swap chain shows is saved too (generated frames). - #[cfg(feature = "diagnostics")] - crate::shown::install(&swap_chain, &self.device, &self.queue); - let copy = self.new_list()?; - copy.close(); - tracing::info!(width, height, format = format.0, "presenting to a window"); - self.log_video_memory("right after the swap chain is made"); - Ok(Presenter { - swap_chain, - width, - height, - format, - copy, - ahead: Vec::new(), - hwnd, - meter: Meter::new(), - composer: None, - #[cfg(feature = "diagnostics")] - panel: panel::Panel::new(), - menu: menu::Menu::new(), - trainer: trainer::Overlay::new(height), - lua: trainer::Overlay::idle(), - tearing, - presents_tearing: tearing, - }) - } - } -} - -/// The size of a window's client area ((0, 0) for a minimised one, or one that is gone). -fn client_size(hwnd: HWND) -> (u32, u32) { - let mut rect = RECT::default(); - // SAFETY: a plain query with room for the answer. - match unsafe { GetClientRect(hwnd, &mut rect) } { - Ok(()) => ((rect.right - rect.left).max(0) as u32, (rect.bottom - rect.top).max(0) as u32), - Err(_) => (0, 0), - } -} - -/// A visible top-level window of this process: the one the title made, if -/// it made one. -fn title_window() -> Option { - extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL { - let mut process = 0; - // SAFETY: a window handle from the enumeration; `found` is ours. - unsafe { - GetWindowThreadProcessId(hwnd, Some(&mut process)); - if process == windows::Win32::System::Threading::GetCurrentProcessId() - && IsWindowVisible(hwnd).as_bool() - { - *(found.0 as *mut Option) = Some(hwnd); - return false.into(); - } - } - true.into() - } - let mut found: Option = None; - // SAFETY: the callback only writes `found`, which outlives the call. - let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) }; - found -} - -/// `state` without the bits the host texture's flags forbid: the console -/// lets the title name states its own resources allow (unordered access on -/// a depth target, whose host copy cannot have both). -pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 { - // SAFETY: a plain query. - legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state) -} - -/// [`legal_state`] for a texture with resource flags `flags`. -pub(crate) fn legal_for(flags: u32, state: u32) -> u32 { - // (flag, set or clear forbids, state bits): render target, unordered - // access, depth, denied shader resource. - const FORBIDDEN: [(u32, bool, u32); 4] = [ - (0x1, false, 0x4), - (0x4, false, 0x8), - (0x2, false, 0x10 | 0x20), - (0x8, true, 0x40 | 0x80), - ]; - FORBIDDEN - .iter() - .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny) - .fold(state, |s, &(_, _, bits)| s & !bits) -} - -impl Host { - /// PCI vendor ID of the adapter running the host device. - pub(crate) fn adapter_vendor_id(&self) -> Option { - // SAFETY: a plain query on the adapter kept with this device. - unsafe { self.adapter.as_ref()?.GetDesc1() }.ok().map(|desc| desc.VendorId) - } - - /// The card's memory as the system accounts it to this process, in - /// bytes: the budget and the use of the card's own memory, then of the - /// PC's memory shared with the card (where the system moves what does - /// not fit on the card). - pub(crate) fn video_memory(&self) -> Option<[u64; 4]> { - let adapter = self.adapter.as_ref()?; - let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); - let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); - // SAFETY: plain queries that fill our structures. - unsafe { - adapter - .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) - .ok()?; - adapter - .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) - .ok()?; - } - // The card's budget moved by 256 MB or more since the last look: - // said at once, with what was in use at the last look, so the log - // has the moment. (It fell from 11,242 MB to some 10,300 MB with - // the first world frame in runs 179 to 185, and the memory line, - // seconds later, was the first to show it. We reserve nothing - // and make the swap chain once, at the start.) - static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; - let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage]; - let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed)); - if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) { - tracing::info!( - "the system changed the budget of the card's memory from {} MB to {} MB (frame {}); at the last look {} MB of the card's and {} MB of the PC's shared memory were in use", - last[0] >> 20, - own.Budget >> 20, - crate::frame::current(), - last[1] >> 20, - last[2] >> 20 - ); - self.log_video_memory("right after that change"); - } - Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage]) - } - - /// Both of the system's memory groups for this process, in bytes: for - /// the card's own memory and then for the PC's memory shared with the - /// card, the budget, the use, what could still be reserved and what - /// is reserved (the layer reserves none). - pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> { - let adapter = self.adapter.as_ref()?; - let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); - let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); - // SAFETY: plain queries that fill our structures. - unsafe { - adapter - .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) - .ok()?; - adapter - .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) - .ok()?; - } - let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| { - [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation] - }; - Some([all(&own), all(&shared)]) - } - - /// Logs [`Self::video_memory_groups`], with `when` it is said. - pub(crate) fn log_video_memory(&self, when: &str) { - let Some([own, shared]) = self.video_memory_groups() else { - return; - }; - tracing::info!( - "video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved; the PC's shared with the card: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved (the layer reserves none)", - when, - own[0] >> 20, - own[1] >> 20, - own[2] >> 20, - own[3] >> 20, - shared[0] >> 20, - shared[1] >> 20, - shared[2] >> 20, - shared[3] >> 20 - ); - } - - /// A buffer in system memory that the CPU maps (write-back, so reading - /// it is fast too) and shaders read and write: for host copies of title - /// memory that shaders write, which upload memory cannot be. Starts in - /// the common state (buffers move out of it implicitly). - #[cfg_attr(feature = "diagnostics", track_caller)] - pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { - #[cfg(feature = "diagnostics")] - let began = std::time::Instant::now(); - MADE[2].fetch_add(1, Ordering::Relaxed); - MADE[3].fetch_add(size, Ordering::Relaxed); - // A small one is placed in a block (`LEONIDA_SMALL_BUFFER_POOL`). - if let Some(placed) = crate::pool::small::buffer(&self.device, crate::pool::small::SHARED, size) { - #[cfg(feature = "diagnostics")] - buffers_made::made(buffers_made::SHARED, size, true, began, std::panic::Location::caller()); - return Some(placed); - } - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_CUSTOM, - CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, - MemoryPoolPreference: D3D12_MEMORY_POOL_L0, - ..Default::default() - }; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size.max(1), - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - ..Default::default() - }; - let mut buffer: Option = None; - let mut data = std::ptr::null_mut(); - // SAFETY: plain creation and mapping of a CPU-visible buffer. - let made = unsafe { - self.device - .CreateCommittedResource( - &heap, - not_resident(), - &desc, - D3D12_RESOURCE_STATE_COMMON, - None, - &mut buffer, - ) - .and_then(|()| { - let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; - resident(&self.device, b)?; - mapped(&self.device)?; - b.Map(0, None, Some(&mut data)) - }) - }; - #[cfg(feature = "diagnostics")] - if let Some(b) = &buffer { - crate::census::made_at(b, "shared buffers", std::panic::Location::caller()); - } - #[cfg(feature = "diagnostics")] - if made.is_ok() - && let Some(b) = &buffer - { - crate::book::made(b, || "a shared buffer".into()); - } - #[cfg(feature = "diagnostics")] - buffers_made::made(buffers_made::SHARED, size, false, began, std::panic::Location::caller()); - match made { - Ok(()) => Some((buffer?, data.cast())), - Err(e) => { - tracing::warn!(error = %e, size, "no shared buffer"); - None - } - } - } - - /// Whether buffers can lie in the card's memory and be mapped by the CPU - /// (`D3D12_HEAP_TYPE_GPU_UPLOAD`: a resizable BAR, and a system and driver - /// that offer it); logged once. - pub(crate) fn mapped_card_memory(&self) -> bool { - static THERE: OnceLock = OnceLock::new(); - *THERE.get_or_init(|| { - let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); - // SAFETY: writes `options` of the given size. - let ok = unsafe { - self.device - .CheckFeatureSupport( - D3D12_FEATURE_D3D12_OPTIONS16, - (&raw mut options).cast(), - size_of_val(&options) as u32, - ) - .is_ok() - }; - let supported = ok && options.GPUUploadHeapSupported.as_bool(); - tracing::info!(supported, "card memory the CPU maps"); - supported - }) - } - - /// A buffer in the card's own memory that the CPU maps, shaders read and - /// (with `written`) may write. The CPU should only write it: a read of the - /// mapping crosses the bus a few bytes at a time. - #[cfg_attr(feature = "diagnostics", track_caller)] - pub(crate) fn mapped_card_buffer(&self, size: u64, written: bool) -> Option<(ID3D12Resource, *mut u8)> { - if !self.mapped_card_memory() { - return None; - } - MADE[4].fetch_add(1, Ordering::Relaxed); - MADE[5].fetch_add(size, Ordering::Relaxed); - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_GPU_UPLOAD, - ..Default::default() - }; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size.max(1), - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: if written { - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS - } else { - D3D12_RESOURCE_FLAG_NONE - }, - ..Default::default() - }; - let mut buffer: Option = None; - let mut data = std::ptr::null_mut(); - // SAFETY: plain creation and mapping of a CPU-visible buffer. - let made = unsafe { - self.device - .CreateCommittedResource( - &heap, - not_resident(), - &desc, - D3D12_RESOURCE_STATE_COMMON, - None, - &mut buffer, - ) - .and_then(|()| { - let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; - resident(&self.device, b)?; - mapped(&self.device)?; - b.Map(0, None, Some(&mut data)) - }) - }; - #[cfg(feature = "diagnostics")] - if let Some(b) = &buffer { - crate::census::made_at(b, "card buffers the CPU maps", std::panic::Location::caller()); - } - match made { - Ok(()) => Some((buffer?, data.cast())), - Err(e) => { - tracing::warn!(error = %e, size, "no buffer in card memory the CPU maps"); - None - } - } - } - - /// A device-local buffer shaders may write (unordered access) and indirect - /// execution may read, starting in the common state. - #[cfg_attr(feature = "diagnostics", track_caller)] - pub(crate) fn uav_buffer(&self, size: u64) -> Option { - MADE[4].fetch_add(1, Ordering::Relaxed); - MADE[5].fetch_add(size, Ordering::Relaxed); - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, - ..Default::default() - }; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size.max(1), - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - ..Default::default() - }; - let mut buffer: Option = None; - // SAFETY: plain creation of a device-local buffer. - let made = unsafe { - self.device.CreateCommittedResource( - &heap, - not_resident(), - &desc, - D3D12_RESOURCE_STATE_COMMON, - None, - &mut buffer, - ) - }; - #[cfg(feature = "diagnostics")] - if let Some(b) = &buffer { - crate::census::made_at(b, "card buffers", std::panic::Location::caller()); - crate::book::made(b, || "an unordered access buffer".into()); - } - let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| resident(&self.device, b))).and_then(|()| mapped(&self.device)); - match made { - Ok(()) => buffer, - Err(e) => { - tracing::warn!(error = %e, size, "no unordered-access buffer"); - None - } - } - } -} - -/// For adapters without device-removed data (the software one): the last -/// commands each list of the failed submission noted (diagnostics, with -/// `LEONIDA_D3D12_DRED`). -fn last_notes(runs: &[&HostList]) -> String { - #[cfg(feature = "diagnostics")] - { - let mut text = String::new(); - for (i, r) in runs.iter().enumerate() { - let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); - for (n, _) in notes.iter().rev().take(6).rev() { - text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len())); - } - } - text - } - #[cfg(not(feature = "diagnostics"))] - { - let _ = runs; - String::new() + { + let mut text = String::new(); + for (i, r) in runs.iter().enumerate() { + let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); + for (n, _) in notes.iter().rev().take(6).rev() { + text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len())); + } + } + text + } + #[cfg(not(feature = "diagnostics"))] + { + let _ = runs; + String::new() } } @@ -13946,49 +11917,10 @@ fn pump() { } #[cfg(test)] -mod trail { - /// The trail keeps the newest things, and the report made when the - /// host device is removed says them and the pipeline library's state - /// (no card is asked for any of it). - #[test] - fn the_removal_report_says_the_newest_things_done() { - for n in 0..super::TRAIL_MOST + 5 { - super::trail(|| format!("thing {n} done")); - } - let text = super::removal_context(); - assert!(text.contains("the submitting thread was")); - assert!(text.contains("pipeline library: no call running")); - assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4))); - assert!(!text.contains("thing 4 done"), "the oldest entries are dropped"); - } -} +mod trail; #[cfg(test)] -mod spare { - use super::Spare; - - /// Kept things come back by size, the last given first, and nothing is - /// kept past the limit. - #[test] - fn kept_things_come_back_by_size_within_the_limit() { - let mut spare: Spare = Spare::new(); - assert_eq!(spare.take(4), None); - assert_eq!(spare.give(1, 4, 10), None); - assert_eq!(spare.give(2, 1, 10), None); - assert_eq!(spare.give(3, 4, 10), None); - assert_eq!(spare.bytes, 9); - // Past the limit: handed back, nothing changes. - assert_eq!(spare.give(4, 4, 10), Some(4)); - assert_eq!(spare.bytes, 9); - assert_eq!(spare.take(2), None, "no thing of that size"); - assert_eq!(spare.take(4), Some(3)); - assert_eq!(spare.take(4), Some(1)); - assert_eq!(spare.take(4), None); - assert_eq!(spare.take(1), Some(2)); - assert_eq!(spare.bytes, 0); - assert!(spare.kept.is_empty()); - } -} +mod spare; #[cfg(test)] mod refresh_tests { @@ -14567,6 +12499,73 @@ mod refresh_tests { } } + /// `LEONIDA_LOOK_PARTS`: a range whose end pages the title wrote only in + /// 4 KiB beside it is known to copy nothing; written in a 4 KiB it holds + /// a byte of, it is not, and the refresh takes it. In view memory, where + /// the guards name only the block, a write beside it is a write in it, as + /// before. + #[test] + fn writes_beside_a_range_on_its_end_pages() { + crate::watch::LOOK_PARTS_IN_TEST.set(Some(true)); + const KIB4: usize = 4096; + for view in [false, true] { + let region = title(4 * PAGE, view); + // SAFETY: the test's own memory. + unsafe { std::ptr::write_bytes(region as *mut u8, 1, 4 * PAGE) }; + let data = memory(4 * PAGE); + let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, false); + // From inside the second 4 KiB of page 0 to inside the first of page 2. + let (at, end) = (region + KIB4 + 500, region + 2 * PAGE + 3000); + let look = |expected: bool, what: &str| { + // (Again if a submission of another test ended the asking.) + let mut known = false; + for _ in 0..100 { + crate::watch::ask_once(&[(at, end), (region + 3 * PAGE, region + 4 * PAGE)]); + known = copy.nothing_new(at, end - at); + if known || !expected { + break; + } + } + assert_eq!(known, expected, "view {view}: {what}"); + let copied = copy.update(at, end - at); + crate::watch::ask_once_end(); + // SAFETY: the copy's memory and title memory, written by nobody now. + let (held, there) = + unsafe { (std::slice::from_raw_parts(data.add(at - region), end - at), std::slice::from_raw_parts(at as *const u8, end - at)) }; + assert!(held == there, "view {view}: {what}: the copy holds what title memory holds"); + copied + }; + let write = |at: usize, value: u8| { + // SAFETY: the test's own memory. + unsafe { (at as *mut u8).write_volatile(value) } + }; + assert_eq!(look(false, "never taken"), end - at); + assert_eq!(look(true, "taken"), 0); + // Beside the range in its last page, and in its first. + write(region + 2 * PAGE + 5000, 7); + write(region + 100, 7); + if view { + look(false, "written beside, in its blocks"); + } else { + assert_eq!(look(true, "written beside, in its pages"), 0); + } + // In the 4 KiB of its last page that it holds. + write(region + 2 * PAGE + 2000, 8); + let copied = look(false, "written in its last page's part"); + if !view { + assert_eq!(copied, 3000); + } + // In the 4 KiB of its first page that it holds a part of, before it. + write(region + KIB4 + 100, 9); + let copied = look(false, "written in its first page's part"); + if !view { + assert_eq!(copied, KIB4 - 500); + } + assert_eq!(look(true, "taken again"), 0); + } + crate::watch::LOOK_PARTS_IN_TEST.set(None); + } + /// Of a copy in the card's memory only the dwords title memory changed go /// up, and none beside them, not even between two in 64 bytes; a page /// never taken goes up whole. @@ -14714,221 +12713,289 @@ mod refresh_tests { #[cfg(feature = "diagnostics")] println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64)); } -} - -#[cfg(test)] -mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file - use super::Batch; - use std::sync::Arc; - #[test] - fn a_texture_is_checked_once_per_submission() { + /// As a submission refreshes in front of its steps (`refresh_front`): + /// one asking, every span at once, the asking's end. The milliseconds of + /// the refreshes alone. + fn front(ranges: &[(Arc, usize, usize)]) -> f64 { + static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect(); + crate::watch::ask_once(&asked); let mut batch = Batch::default(); - let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16])); - // The first list sampling each texture checks it ... - assert!(batch.texture_due(&a)); - assert!(batch.texture_due(&b)); - // ... later lists of the same submission do not. - assert!(!batch.texture_due(&a)); - assert!(!batch.texture_due(&a.clone())); - assert!(!batch.texture_due(&b)); + let spans = ranges.iter().map(|(s, at, len)| (s.clone(), *at, *at + *len)).collect(); + let started = std::time::Instant::now(); + batch.refresh_spans(spans, Vec::new(), crate::timeline::span("bench")); + let took = started.elapsed().as_secs_f64() * 1e3; + crate::watch::ask_once_end(); + took } - #[test] - fn title_writes_make_textures_due_again() { + /// Prepares as [`submission`] does: the milliseconds of the flushes + /// alone. + fn flushes(ranges: &[(Arc, usize, usize)], flushes: usize) -> f64 { + static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect(); + crate::watch::ask_once(&asked); let mut batch = Batch::default(); - let a = Arc::new(1u32); - assert!(batch.texture_due(&a)); - assert!(!batch.texture_due(&a)); - // A copy into title memory or work that may write it may have - // changed the texture's memory. - batch.title_written(); - assert!(batch.texture_due(&a)); - assert!(!batch.texture_due(&a)); - // A fresh submission starts over. - let mut next = Batch::default(); - assert!(next.texture_due(&a)); - } - - /// `LEONIDA_BATCH_KEPT`: a batch given back comes back on the same thread - /// empty, with its room, and marked kept; another thread gets its own. + let mut took = 0.0; + for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) { + for (shadow, at, len) in part { + batch.add(shadow, *at, *len); + } + let started = std::time::Instant::now(); + batch.flush(); + took += started.elapsed().as_secs_f64() * 1e3; + } + crate::watch::ask_once_end(); + took + } + + /// `LEONIDA_LOOK_FIRST`: a flush of more refreshes than were ever looked + /// at on the submitting thread (256), none of whose copies was written + /// since it last took them, wakes no thread, in front of the steps or + /// between them; a byte the title wrote in one copy's range is taken. #[test] - fn a_kept_batch_comes_back_empty_with_its_room() { - std::thread::spawn(|| { - let mut batch = Batch::reused(); - assert!(batch.kept); - let a = Arc::new(1u32); - assert!(batch.texture_due(&a)); - batch.ranges.extend((0..1000).map(|i| (i, i + 1))); - batch.fills.push((1, 2, 3)); - batch.front = true; - let room = batch.ranges.capacity(); - batch.give_back(); - let mut again = Batch::reused(); - assert!(again.kept && !again.front); - assert!(again.ranges.is_empty() && again.fills.is_empty() && again.spans.is_empty()); - assert_eq!(again.ranges.capacity(), room); - assert!(again.texture_due(&a), "a new submission checks its textures again"); - std::thread::spawn(|| assert!(Batch::reused().ranges.capacity() == 0)).join().unwrap(); - }) - .join() - .unwrap(); + fn a_flush_that_copies_nothing_wakes_no_thread() { + use crate::shadow::WIDE_IN_TEST; + const EACH: usize = 2 * PAGE; + const N: usize = 300; + super::LOOK_FIRST_IN_TEST.set(Some(true)); + for view in [false, true] { + let region = title(N * EACH, view); + // SAFETY: the test's own memory. + unsafe { std::ptr::write_bytes(region as *mut u8, 1, N * EACH) }; + let data: Vec<*mut u8> = (0..N).map(|_| memory(EACH)).collect(); + let copies: Vec<(Arc, usize, usize)> = (0..N) + .map(|i| (Shadow::unbacked((region + i * EACH) as u64, data[i], EACH as u64, false), region + i * EACH + 100, EACH - 200)) + .collect(); + front(&copies); + // (Again if a submission of another test ended the asking.) + let quiet = |by: &dyn Fn()| { + (0..100).any(|_| { + let was = WIDE_IN_TEST.get(); + by(); + WIDE_IN_TEST.get() == was + }) + }; + assert!(quiet(&|| { front(&copies); }), "view {view}: in front of the steps"); + assert!(quiet(&|| { flushes(&copies, 1); }), "view {view}: a flush between them"); + // SAFETY: the test's own memory. + unsafe { ((region + 7 * EACH + 500) as *mut u8).write_volatile(9) }; + front(&copies); + // SAFETY: the copy's memory, written by the refreshes, which are done. + assert_eq!(unsafe { data[7].add(500).read_volatile() }, 9, "view {view}: the byte written"); + flushes(&copies, 2); + assert_eq!(unsafe { data[7].add(500).read_volatile() }, 9, "view {view}: the byte written"); + } + super::LOOK_FIRST_IN_TEST.set(None); } - /// The hashing a submission does for textures in physical-page memory, - /// with every list checking the textures it samples (before) and with - /// each checked once (after). Run with - /// `cargo test --release -p leonida-gpu -- --ignored --nocapture texture_checks`. + /// Whichever way the looks go (`LEONIDA_LOOK_FIRST` on and off), many + /// copies of both kinds of memory, a few written between submissions, + /// in front of the steps and in flushes between them: every refreshed + /// range holds what title memory holds. #[test] - #[ignore = "benchmark"] - fn texture_checks_per_submission() { - const TEXTURES: usize = 48; - const SIZE: usize = 4 << 20; - const LISTS: usize = 12; - let textures: Vec>> = (0..TEXTURES) - .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect())) - .collect(); - let submit = |dedupe: bool| { - let mut batch = Batch::default(); - let mut hashed = 0usize; - let started = std::time::Instant::now(); - for _ in 0..LISTS { - for t in &textures { - if !dedupe || batch.texture_due(t) { - std::hint::black_box(blake3::hash(t)); - hashed += 1; - } + fn writes_between_refreshes_are_taken_whoever_looks() { + const EACH: usize = PAGE + 4096; + const N: usize = 280; + let mut random = Random(0x0BAD_5EED_1234_5677); + for first in [true, false] { + super::LOOK_FIRST_IN_TEST.set(Some(first)); + let regions = [title(N * EACH, false), title(N * EACH, true)]; + let mut copies = Vec::new(); + let mut data = Vec::new(); + for ®ion in ®ions { + // SAFETY: the test's own memory. + unsafe { std::ptr::write_bytes(region as *mut u8, 1, N * EACH) }; + for i in 0..N { + let at = memory(EACH); + data.push((at, region + i * EACH)); + // Ranges that end inside pages, some over the next copy's. + let (from, to) = (region + i * EACH + 300, (region + i * EACH + EACH + 64 * (i % 3)).min(region + N * EACH)); + copies.push((Shadow::unbacked((region + i * EACH) as u64, at, EACH as u64, false), from, to - from)); + } + } + for round in 0..24 { + for _ in 0..random.below(12) { + let at = regions[random.below(2)] + random.below(N * EACH - 8); + // SAFETY: the test's own memory. + unsafe { (at as *mut u32).write_unaligned(round * 1000 + random.below(1000) as u32) }; + } + if round % 2 == 0 { + front(&copies); + } else { + flushes(&copies, 1 + round as usize % 3); + } + for ((_, at, len), &(held, start)) in copies.iter().zip(&data) { + let len = (*len).min(start + EACH - at); + // SAFETY: the copy's memory and title memory, written by + // nobody now. + let (held, there) = unsafe { + (std::slice::from_raw_parts(held.add(at - start), len), std::slice::from_raw_parts(*at as *const u8, len)) + }; + assert!(held == there, "looks first {first}, round {round}: the copy of {start:#x} is stale"); } } - (started.elapsed(), hashed) - }; - submit(false); // warm up - let (before, n_before) = submit(false); - let (after, n_after) = submit(true); - assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES)); - println!( - "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \ - before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)", - SIZE >> 20, - before.as_secs_f64() / after.as_secs_f64() - ); + } + super::LOOK_FIRST_IN_TEST.set(None); } + /// [`super::sift`]: those known to copy nothing go, the others stay in + /// order; with no time to look, the ones not reached stay as they came. #[test] - fn vram_idle_ms_scales_with_pressure() { - let vram_idle_ms = |memory| super::vram_idle_for(memory, false); - let keeps = |memory| super::vram_idle_for(memory, true); - let gib = 1024 * 1024 * 1024; - assert_eq!(keeps(Some([100, 67, 0, 0])), 600_000); - assert_eq!(keeps(Some([100, 68, 0, 0])), 30_000); - assert_eq!(keeps(Some([100, 75, 0, 0])), 2_500); - assert_eq!(keeps(Some([100, 85, 0, 0])), 1_000); - assert_eq!(keeps(None), 5_000); - // Normal (< 75%) - assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000); - assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000); - assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000); - // Moderate (75%..85%) - assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500); - assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500); - // High (>= 85%, including over-budget) - assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000); - assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000); - // Missing or zero budget falls back to normal - assert_eq!(vram_idle_ms(None), 5_000); - assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000); - } - + fn sifting_keeps_what_may_copy_in_order() { + const N: usize = 200; + let start = 0x5100_0000usize; + let data = memory(N * PAGE); + // A copy never taken may copy; a range outside its copy copies nothing. + let spans: Vec<(Arc, usize, usize)> = (0..N) + .map(|i| { + // SAFETY: inside the allocation. + let copy = Shadow::unbacked((start + i * PAGE) as u64, unsafe { data.add(i * PAGE) }, PAGE as u64, false); + let at = if i % 3 == 0 { start + i * PAGE + 64 } else { start + (i + 1) * PAGE + 64 }; + (copy, at, at + 128) + }) + .collect(); + let may: Vec = (0..N).filter(|i| i % 3 == 0).collect(); + let names = |s: &[(Arc, usize, usize)]| { + s.iter().map(|r| spans.iter().position(|c| Arc::ptr_eq(&c.0, &r.0)).unwrap()).collect::>() + }; + let mut all = spans.clone(); + let looked = super::sift(&mut all, std::time::Duration::MAX); + assert_eq!((looked, names(&all)), (may.len(), may.clone())); + let mut some = spans.clone(); + let looked = super::sift(&mut some, std::time::Duration::ZERO); + // Looked at up to the first time the clock was asked. + let reached = may.iter().filter(|&&i| i < super::SIFT_EVERY).count(); + assert_eq!(looked, reached); + assert_eq!(names(&some[..looked]), may[..reached]); + assert_eq!(names(&some[looked..]), (super::SIFT_EVERY..N).collect::>()); + } + + /// [`super::sift`] asks the clock after a look of a wide range, so a + /// flush of a few such looks is cut short by the time; a few looks of + /// ranges inside a page are all made. #[test] - fn textures_are_kept_while_the_card_has_room() { - use super::vram_keep; - let gib = 1 << 30; - assert_eq!(vram_keep(100 * gib, 87 * gib).0, 600_000); - // Past it: the longest idle ones, enough to come down to 85 %. - let (ms, bytes) = vram_keep(100 * gib, 90 * gib); - assert_eq!((ms, bytes), (5_000, 5 * gib)); - assert_eq!(vram_keep(100 * gib, 120 * gib), (1_500, 35 * gib)); - assert_eq!(vram_keep(0, 7).0, 5_000); - } - + fn sifting_asks_the_clock_after_a_wide_look() { + const PAGES: usize = 64; + let start = 0x5300_0000usize; + let copy = Shadow::unbacked(start as u64, memory(PAGES * PAGE), (PAGES * PAGE) as u64, false); + // A copy never taken: every range of it may copy. + let wide: Vec<(Arc, usize, usize)> = (0..3).map(|_| (copy.clone(), start, start + PAGES * PAGE)).collect(); + let mut some = wide.clone(); + assert_eq!(super::sift(&mut some, std::time::Duration::ZERO), 1, "the looks after a wide one wait for the clock"); + assert_eq!(some.len(), 3); + let narrow: Vec<(Arc, usize, usize)> = + (0..3).map(|i| (copy.clone(), start + i * PAGE + 64, start + i * PAGE + 192)).collect(); + let mut some = narrow.clone(); + assert_eq!(super::sift(&mut some, std::time::Duration::ZERO), 3); + let mut all = wide; + assert_eq!(super::sift(&mut all, std::time::Duration::MAX), 3); + } + + /// The refreshes of submissions nothing was written for since the last: + /// the 4,400 copies of the heap's buffer views, and the big heap copy + /// under 40 overlapping ranges its shaders write. Run with `--ignored + /// --nocapture` (`--release` for numbers that mean something). #[test] - fn ram_idle_ms_scales_with_pressure() { - let ram_idle_ms = |avail| super::ram_idle_for(avail, false); - assert_eq!(super::ram_idle_for(Some(12 << 30), true), 300_000); - assert_eq!(super::ram_idle_for(Some((12 << 30) - 1), true), 10_000); - assert_eq!(super::ram_idle_for(None, true), 10_000); - let gib = 1024 * 1024 * 1024; - // Normal (>= 4 GiB) - assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000); - assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000); - // Moderate (2 GiB..4 GiB) - assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000); - assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000); - // High (< 2 GiB) - assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000); - assert_eq!(ram_idle_ms(Some(0)), 2_000); - // Missing falls back to normal - assert_eq!(ram_idle_ms(None), 10_000); - } -} - -#[cfg(test)] -mod gate_tests { - use super::*; - - /// Leonida: a list behind the gate in the card's queue (`Host::execute_gated`, - /// `HostList::wait_gate`) runs only after what the gate's thread was given has been done, - /// however long that takes: the work writes a word into upload memory 30 ms after it is given - /// (the card has long reached the gate by then), and the list behind the gate copies the word - /// out. Without the gate the copy reads the 0 that was there before: `TEST_NO_GATE=1` leaves the - /// list's wait out, and the test fails (as it did on an RTX 4060 Ti, 2026-11-29). + #[ignore] + fn refreshes_of_nothing_written() { + const EACH: usize = 224 << 10; + const BIG: usize = 174 << 20; + let watched = title(3000 * EACH, false); + let views = title(1400 * EACH, true); + let big = title(BIG, true); + // SAFETY: the test's own memory. + unsafe { + std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH); + std::ptr::write_bytes(views as *mut u8, 1, 1400 * EACH); + std::ptr::write_bytes(big as *mut u8, 1, BIG); + } + let small: Vec<(Arc, usize, usize)> = (0..4400) + .map(|i| { + let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) }; + (Shadow::unbacked((start + at) as u64, memory(EACH), EACH as u64, false), start + at + 4000, EACH - 9000) + }) + .collect(); + let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG); + let all: Vec<_> = small.iter().cloned().chain([heap.clone()]).collect(); + // Taken once, whole; then the shaders' ranges. + front(&all); + front(&all); + for i in 0..40 { + heap.0.writing(big + i * 5920 + (i % 7) * PAGE * 61, PAGE * (3 + i % 5)); + } + let time = |what: &str, by: &dyn Fn() -> f64| { + let mut took: Vec = (0..40).map(|_| by()).collect(); + took.sort_by(f64::total_cmp); + println!("{what}: best {:.3} ms, median {:.3}", took[0], took[took.len() / 2]); + }; + for first in [false, true] { + super::LOOK_FIRST_IN_TEST.set(Some(first)); + println!("LEONIDA_LOOK_FIRST {}:", u8::from(first)); + time(" 4,400 copies in front", &|| front(&small)); + time(" 4,400 copies in 3 flushes", &|| flushes(&small, 3)); + time(" all in front", &|| front(&all)); + time(" the heap alone in front", &|| front(std::slice::from_ref(&heap))); + time(" 60 copies and the heap in front", &|| front(&all[4340..])); + time(" 200 copies in 1 flush", &|| flushes(&small[..200], 1)); + } + super::LOOK_FIRST_IN_TEST.set(None); + } + + /// `LEONIDA_LOOK_PARTS`: 2,000 copies of 160 KiB one after the other in + /// write-watched memory, each refreshed whole, the title writing a byte + /// in the first 4 KiB of every other one between submissions: that byte + /// lies in the last page of the copy before, beside its range. Run with + /// `--ignored --nocapture` (`--release` for numbers that mean something). #[test] - #[ignore = "wants LEONIDA_LATE_WAIT=3 and a process of its own"] - fn a_list_behind_the_gate_reads_what_was_done_before_it_opened() { - let Some(host) = host() else { - return; + #[ignore] + fn refreshes_beside_writes() { + const EACH: usize = 160 << 10; + const N: usize = 2000; + let region = title(N * EACH, false); + // SAFETY: the test's own memory. + unsafe { std::ptr::write_bytes(region as *mut u8, 1, N * EACH) }; + let copies: Vec<(Arc, usize, usize)> = (0..N) + .map(|i| (Shadow::unbacked((region + i * EACH) as u64, memory(EACH), EACH as u64, false), region + i * EACH, EACH)) + .collect(); + front(&copies); + front(&copies); + // The copies the bytes are written beside, not in. + let beside: Vec<_> = copies.iter().step_by(2).cloned().collect(); + let mut round = 0u8; + let mut time = |what: &str, refreshed: &[(Arc, usize, usize)]| { + let mut took: Vec = (0..40) + .map(|_| { + round = round.wrapping_add(1); + for i in (1..N).step_by(2) { + // SAFETY: the test's own memory. + unsafe { ((region + i * EACH + 8) as *mut u8).write_volatile(round) }; + } + front(refreshed) + }) + .collect(); + took.sort_by(f64::total_cmp); + println!("{what}: best {:.3} ms, median {:.3}", took[0], took[took.len() / 2]); }; - assert!(late(), "set LEONIDA_LATE_WAIT=3"); - let (slow_from, slow_to) = (host.uav_buffer(64 << 20).unwrap(), host.uav_buffer(64 << 20).unwrap()); - for round in 1..=4u32 { - let (upload, data) = host.upload_buffer(4096).unwrap(); - let (out, read) = host.shared_buffer(4096).unwrap(); - // SAFETY: inside the mappings. - unsafe { - data.cast::().write_volatile(0); - read.cast::().write_volatile(1); - } - // A list of ours that keeps the card busy a little, as the bake's uploads do. - let a = host.new_list().unwrap(); - // SAFETY: an open list; live buffers. - unsafe { - for _ in 0..4 { - a.list.CopyBufferRegion(&slow_to, 0, &slow_from, 0, 64 << 20); - } - } - a.close(); - let at = data as usize; - let then = Box::new(move || { - std::thread::sleep(std::time::Duration::from_millis(30)); - // SAFETY: the upload memory lives until the round's end, after the settle below. - unsafe { (at as *mut u32).write_volatile(0xC0DE_0000 | round) }; - }); - let (number, value) = host.execute_gated(Some(&a), then); - assert!(number > 0 && value > 0, "sent ahead with a gate, round {round}"); - // The list that needs it: the word copied out, behind the gate. - let b = host.new_list().unwrap(); - b.wait_gate(if std::env::var_os("TEST_NO_GATE").is_some() { 0 } else { value }); - // SAFETY: an open list; live buffers. - unsafe { b.list.CopyBufferRegion(&out, 0, &upload, 0, 4) }; - b.close(); - let last = host.execute_own(&b); - settle_now(WHY_SYNC); - assert!(FINISHED.load(Ordering::Acquire) >= last); - // SAFETY: the mapping, written by the list, which has landed. - let got = unsafe { read.cast::().read_volatile() }; - assert_eq!(got, 0xC0DE_0000 | round, "the word the gate's work wrote, round {round}"); - drop((a, b, upload, out)); + super::LOOK_FIRST_IN_TEST.set(Some(true)); + for parts in [false, true] { + crate::watch::LOOK_PARTS_IN_TEST.set(Some(parts)); + let on = u8::from(parts); + time(&format!("LEONIDA_LOOK_PARTS {on}: all 2,000 copies in front, 1,000 written"), &copies); + time(&format!("LEONIDA_LOOK_PARTS {on}: the 1,000 written beside in front"), &beside); + time(&format!("LEONIDA_LOOK_PARTS {on}: 100 of them"), &beside[..100]); } + crate::watch::LOOK_PARTS_IN_TEST.set(None); + super::LOOK_FIRST_IN_TEST.set(None); } } +#[cfg(test)] +mod batch; // Batch::texture_due lives here; `mod tests` is already taken at the top of this file + +#[cfg(test)] +mod gate_tests; + diff --git a/d3d12/crates/leonida-gpu/src/host/address_hash_tests.rs b/d3d12/crates/leonida-gpu/src/host/address_hash_tests.rs new file mode 100644 index 0000000000..40657dd0b0 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/address_hash_tests.rs @@ -0,0 +1,117 @@ +use super::AddressHash; +use std::hash::{BuildHasher, BuildHasherDefault}; + +fn hash(key: K) -> u64 { + BuildHasherDefault::::default().hash_one(key) +} + +/// What a table makes of `hashes`: its place from the low bits, its tag +/// from the top seven. No two the same, every tag in use, and with as many +/// places as keys no place crowded and the keys looked at to find one not +/// many more than chance leaves (which is 1.5: a key and half of the others +/// at its place). +/// +/// Measured 2026-11-27, 4,096 keys: host copies 16, 48 and 64 bytes apart +/// 2.1, 1.8 and 2.0 keys looked at (the fullest place 22, 15 and 12 keys), +/// 192 bytes apart 1.5, a page and 64 KiB apart 1.1 and 1.2; root views +/// 2.0, fills 1.5. Not as even as the standard hash for keys a few bytes +/// apart, and far from all in one place. +fn spread(what: &str, hashes: &[u64]) { + let places = hashes.len().next_power_of_two(); + let mut at = vec![0u32; places]; + let mut tags = [false; 128]; + let mut seen = std::collections::BTreeSet::new(); + for &h in hashes { + assert!(seen.insert(h), "{what}: two keys with one hash"); + at[h as usize & (places - 1)] += 1; + tags[(h >> 57) as usize] = true; + } + let fullest = at.iter().copied().max().unwrap_or(0); + assert!(fullest <= 32, "{what}: {fullest} keys in one place of {places}"); + let looked: u64 = at.iter().map(|&n| u64::from(n) * u64::from(n + 1) / 2).sum(); + let looked = looked as f64 / hashes.len() as f64; + assert!(looked <= 2.5, "{what}: {looked:.2} keys looked at to find one"); + let used = tags.iter().filter(|&&t| t).count(); + assert!(used >= 120, "{what}: {used} tags of 128 in use"); +} + +/// The tables a list asks at every draw are keyed by addresses of ours +/// (host copies, title heaps, title addresses): keys that differ in few +/// bits, at even steps. This hash has to tell them apart as the standard +/// one did. +#[test] +fn the_keys_of_a_lists_per_draw_tables_spread() { + // Host copies by address: objects of one size, one after the other. + for step in [16usize, 48, 64, 192, 4096, 1 << 16] { + let keys: Vec = (0..4096).map(|i| hash(0x0000_01f4_8a20_0040usize + i * step)).collect(); + spread(&format!("copies {step} bytes apart"), &keys); + } + // Root views: (title heap, title address), bit 63 for a view that + // begins early (`crate::draw::State::root_srv_table`). + let heap = 0x0000_0234_5678_9000usize; + let keys: Vec = (0..2048u64) + .flat_map(|i| { + let address = 0x4_2000_0000 + i * 0x140; + [hash((heap, address)), hash((heap, address | 1 << 63))] + }) + .collect(); + spread("root views", &keys); + // Fills of scratch memory: (source, bytes). + let keys: Vec = (0..4096usize).map(|i| hash((0x2_8000_0000usize + (i / 4) * 0x100, 0x100usize << (i % 4)))).collect(); + spread("fills", &keys); +} + +/// What a hasher is handed, in order: a number, or so many bytes at once. +#[derive(Default)] +struct Handed(Vec<(bool, usize)>); + +impl std::hash::Hasher for Handed { + fn finish(&self) -> u64 { + 0 + } + fn write(&mut self, bytes: &[u8]) { + self.0.push((true, bytes.len())); + } + fn write_usize(&mut self, n: usize) { + self.0.push((false, n)); + } +} + +/// A descriptor record (tag, index, generation: the key of the views a +/// list made, `crate::descriptor::host::ListViews`) is handed over as its +/// length and its twelve bytes at once, and hashed in three steps: the +/// length, eight bytes, and the four left with their number. Records +/// that differ in one word hash apart, and a list's records spread. +#[test] +fn a_record_of_three_words_is_hashed_a_word_at_a_time() { + use std::hash::{Hash, Hasher}; + let record = [0x5649_4557u32, 0x0001_2345, 7]; + let mut handed = Handed::default(); + record.hash(&mut handed); + assert_eq!(handed.0, [(false, 3), (true, 12)], "the standard library hands a record over otherwise now"); + let mut by_hand = AddressHash::default(); + by_hand.write_usize(3); + by_hand.write_u64(u64::from(record[0]) | u64::from(record[1]) << 32); + by_hand.write_u64(u64::from(record[2]) | 4 << 56); + assert_eq!(hash(record), by_hand.finish()); + for word in 0..3 { + for bit in 0..32 { + let mut other = record; + other[word] ^= 1 << bit; + assert_ne!(hash(other), hash(record), "word {word}, bit {bit}"); + } + } + // The bytes left over count: a shorter key is not the longer one + // that ends in zeros. + let bytes = |b: &[u8]| { + let mut h = AddressHash::default(); + h.write(b); + h.finish() + }; + assert_ne!(bytes(b"ab"), bytes(b"ab\0")); + assert_ne!(bytes(b"12345678"), bytes(b"12345678\0")); + assert_eq!(bytes(&7u64.to_le_bytes()), hash(7u64)); + // A list's records: one tag, slots one after the other, a few generations. + let keys: Vec = (0..4096u32).map(|i| hash([0x5649_4557u32, 0x4000 + i / 2, 1 + i % 2])).collect(); + spread("records", &keys); +} diff --git a/d3d12/crates/leonida-gpu/src/host/bar.rs b/d3d12/crates/leonida-gpu/src/host/bar.rs new file mode 100644 index 0000000000..c3df8a9a7d --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/bar.rs @@ -0,0 +1,268 @@ +//! Whether the card's own memory can be mapped by the CPU here (a resizable +//! BAR, "Smart Access Memory" on AMD), said once when the host device is made. +//! +//! Every path that puts memory the CPU fills in the card's own memory +//! (`LEONIDA_SEND_BAR`, `LEONIDA_WINDOWS_BAR_MB`, `LEONIDA_BAR_BUFFERS_MB`) +//! rests on `D3D12_HEAP_TYPE_GPU_UPLOAD`, which Direct3D offers +//! (`D3D12_OPTIONS16.GPUUploadHeapSupported`) only where the firmware opened +//! the whole of the card's memory to the CPU ("Above 4G decoding" and +//! "Re-Size BAR"), and the driver and Windows 11 take it. Without it each of +//! those paths falls back to the PC's memory without a word, and a log said +//! nothing either: on the RX 7900 XT of `docs/findings.md`'s last section +//! the card's memory window was 256 MiB (BAR off in the firmware) and +//! `GPUUploadHeapSupported` false, found by hand. Now the log's first lines +//! say both: Direct3D's answer and the size of the card's largest memory +//! window as Windows gave it out (the PCI resources of the device the +//! adapter is: `Win32_DeviceMemoryAddress` reads the same). 256 MiB is the +//! old fixed window; with the BAR resized it is the card's memory or more. + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::*; +use windows_sys::Win32::Devices::DeviceAndDriverInstallation as cm; + +/// Whether Direct3D offers `D3D12_HEAP_TYPE_GPU_UPLOAD` on `device`. +pub(crate) fn gpu_upload_heaps(device: &ID3D12Device) -> bool { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); + // SAFETY: writes `options` of the given size. + let ok = unsafe { + device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS16, (&raw mut options).cast(), size_of_val(&options) as u32) + .is_ok() + }; + ok && options.GPUUploadHeapSupported.as_bool() +} + +/// What DXGI says of `device`'s adapter. +fn adapter(device: &ID3D12Device) -> Option { + // SAFETY: plain DXGI queries. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter1 = factory.EnumAdapterByLuid(device.GetAdapterLuid()).ok()?; + adapter.GetDesc1().ok() + } +} + +/// Whether `device`'s adapter is the software one (WARP): no card, no PCI +/// memory window, and GPU upload heaps, where it offers them, in the PC's +/// memory. +pub(crate) fn software(device: &ID3D12Device) -> bool { + adapter(device).is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) +} + +/// [`said`] for `device`. +pub(crate) fn line(device: &ID3D12Device) -> String { + said(gpu_upload_heaps(device), window(device), software(device)) +} + +/// The bytes of the largest memory window Windows gave the PCI device that +/// `device`'s adapter is (the one the CPU reaches the card's memory +/// through); `None` for the software adapter or where it cannot be told. +/// With two cards of the same make and revision, the first one's. +pub(crate) fn window(device: &ID3D12Device) -> Option { + let desc = adapter(device)?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + return None; + } + let want = pci_id(desc.VendorId, desc.DeviceId, desc.SubSysId, desc.Revision); + for id in pci_devices()? { + if id.to_ascii_uppercase().starts_with(&want) { + return largest(&memory_ranges(&id)); + } + } + None +} + +/// The start of the device instance name of a PCI device with these IDs +/// (`PCI\VEN_1002&DEV_744C&SUBSYS_...&REV_C8`), upper case. +fn pci_id(vendor: u32, device: u32, subsystem: u32, revision: u32) -> String { + format!("PCI\\VEN_{vendor:04X}&DEV_{device:04X}&SUBSYS_{subsystem:08X}&REV_{revision:02X}") +} + +/// The device instance names of the PCI devices present. +fn pci_devices() -> Option> { + let filter: Vec = "PCI\0".encode_utf16().collect(); + let flags = cm::CM_GETIDLIST_FILTER_ENUMERATOR | cm::CM_GETIDLIST_FILTER_PRESENT; + let mut len = 0u32; + // SAFETY: a terminated filter; `len` is ours. + if unsafe { cm::CM_Get_Device_ID_List_SizeW(&mut len, filter.as_ptr(), flags) } != cm::CR_SUCCESS || len == 0 { + return None; + } + let mut list = vec![0u16; len as usize]; + // SAFETY: a buffer of `len` characters. + if unsafe { cm::CM_Get_Device_ID_ListW(filter.as_ptr(), list.as_mut_ptr(), len, flags) } != cm::CR_SUCCESS { + return None; + } + Some(list.split(|&c| c == 0).filter(|s| !s.is_empty()).map(String::from_utf16_lossy).collect()) +} + +/// The memory ranges (first and last byte) Windows gave device instance +/// `id`, below and above 4 GiB. +fn memory_ranges(id: &str) -> Vec<(u64, u64)> { + let name: Vec = id.encode_utf16().chain(std::iter::once(0)).collect(); + let mut ranges = Vec::new(); + let mut node = 0u32; + // SAFETY: a terminated name; the handles are freed below. + unsafe { + if cm::CM_Locate_DevNodeW(&mut node, name.as_ptr(), cm::CM_LOCATE_DEVNODE_NORMAL) != cm::CR_SUCCESS { + return ranges; + } + let mut conf = 0usize; + if cm::CM_Get_First_Log_Conf(&mut conf, node, cm::ALLOC_LOG_CONF) != cm::CR_SUCCESS { + return ranges; + } + for kind in [cm::ResType_Mem, cm::ResType_MemLarge] { + let mut at = conf; + let mut held = 0usize; + loop { + let mut next = 0usize; + if cm::CM_Get_Next_Res_Des(&mut next, at, kind, std::ptr::null_mut(), 0) != cm::CR_SUCCESS { + break; + } + if held != 0 { + cm::CM_Free_Res_Des_Handle(held); + } + held = next; + at = next; + let mut size = 0u32; + if cm::CM_Get_Res_Des_Data_Size(&mut size, next, 0) != cm::CR_SUCCESS || (size as usize) < size_of::() { + continue; + } + let mut data = vec![0u8; size as usize]; + if cm::CM_Get_Res_Des_Data(next, data.as_mut_ptr().cast(), size, 0) != cm::CR_SUCCESS { + continue; + } + // The two headers have the base and the end at the same + // offsets (packed, read as they lie). + let header = data.as_ptr().cast::().read_unaligned(); + let (base, end) = (header.MD_Alloc_Base, header.MD_Alloc_End); + if end > base { + ranges.push((base, end)); + } + } + if held != 0 { + cm::CM_Free_Res_Des_Handle(held); + } + } + cm::CM_Free_Log_Conf_Handle(conf); + } + ranges +} + +/// The bytes of the largest of `ranges` (first and last byte of each). +fn largest(ranges: &[(u64, u64)]) -> Option { + ranges.iter().map(|&(base, end)| end - base + 1).max() +} + +/// Above this a window is taken for a resized BAR: the fixed one is 256 MiB +/// (beside a few MiB of registers, in a range of its own or not). +const FIXED_MOST: u64 = 512 << 20; + +/// The line said at start: Direct3D's answer and the window; on the +/// software adapter (`software`), which has neither card memory nor a +/// window and may offer GPU upload heaps all the same (it does on Windows 11 +/// build 26300), that there is no BAR to speak of. +pub(crate) fn said(supported: bool, window: Option, software: bool) -> String { + if software { + return format!( + "resizable BAR: none, the software adapter (WARP) has no card memory and no memory window \ + (GPUUploadHeapSupported {supported}: its GPU upload heaps are the PC's memory; whether the card's BAR is on is not told here)" + ); + } + let window_mib = window.map_or_else(|| "not known".to_owned(), |w| format!("{} MiB", w >> 20)); + let state = match (supported, window) { + (true, _) => "on: buffers can lie in the card's memory and be written by the CPU", + (false, Some(w)) if w > FIXED_MOST => { + "the window is resized, but Direct3D does not offer GPU upload heaps (a driver or Windows that does not take it): buffers the CPU writes stay in the PC's memory" + } + (false, Some(_)) => { + "off: the card's memory window is the fixed one, so buffers the CPU writes stay in the PC's memory; \"Above 4G decoding\" and \"Re-Size BAR\" (Smart Access Memory) in the firmware turn it on" + } + (false, None) => "off: Direct3D does not offer GPU upload heaps, so buffers the CPU writes stay in the PC's memory", + }; + format!("resizable BAR {state} (GPUUploadHeapSupported {supported}, the card's largest memory window {window_mib})") +} + +/// Says [`said`] for `device` once. +pub(super) fn log(device: &ID3D12Device) { + tracing::info!("{}", line(device)); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The line tells a resized BAR from the fixed window, and both from a + /// Direct3D that offers nothing: the RX 7900 XT of `docs/findings.md` + /// had its 256 MiB window and two MiB of registers beside it in one + /// range, and `GPUUploadHeapSupported` false. + #[test] + fn the_line_tells_the_bar_on_from_off() { + let fixed = largest(&[(0xD000_0000, 0xE01F_FFFF), (0xF7C0_0000, 0xF7CF_FFFF)]); + assert_eq!(fixed, Some(258 << 20)); + let off = said(false, fixed, false); + assert!(off.starts_with("resizable BAR off"), "{off}"); + assert!(off.contains("258 MiB") && off.contains("Re-Size BAR"), "{off}"); + let resized = largest(&[(0x38_0000_0000, 0x3F_FFFF_FFFF), (0xF7C0_0000, 0xF7CF_FFFF)]); + assert_eq!(resized, Some(32 << 30)); + let on = said(true, resized, false); + assert!(on.starts_with("resizable BAR on") && on.contains("32768 MiB"), "{on}"); + let refused = said(false, resized, false); + assert!(refused.contains("does not offer"), "{refused}"); + assert!(said(false, None, false).contains("not known")); + assert_eq!(largest(&[]), None); + } + + /// The software adapter offers GPU upload heaps here and has no window: + /// the line does not say the BAR is on (before, it read "resizable BAR + /// on ... window not known" in every test run on WARP). + #[test] + fn the_software_adapter_is_not_said_to_have_a_bar() { + for supported in [true, false] { + let warp = said(supported, None, true); + assert!(!warp.starts_with("resizable BAR on") && !warp.starts_with("resizable BAR off"), "{warp}"); + assert!(warp.contains("software adapter") && warp.contains(&format!("GPUUploadHeapSupported {supported}")), "{warp}"); + } + } + + /// A device instance name is matched by its make, model, subsystem and + /// revision, as Windows writes them. + #[test] + fn the_adapter_is_found_by_its_pci_ids() { + assert_eq!(pci_id(0x1002, 0x744c, 0x0e3b_1da2, 0xcc), "PCI\\VEN_1002&DEV_744C&SUBSYS_0E3B1DA2&REV_CC"); + } + + /// The line is said for the host's device, whatever it is. Where no + /// window is found for a hardware adapter (a card a virtual machine + /// shares out, or one whose PCI IDs match no present device with + /// resources given out) it says so and passes: the line then says the + /// window is not known, which is right. + #[test] + fn the_hosts_line_is_said() { + let Some(host) = crate::host::host() else { + eprintln!("no D3D12 device; the BAR line was not tried"); + return; + }; + let line = line(&host.device); + eprintln!("{line}"); + assert!(line.starts_with("resizable BAR") && line.contains("GPUUploadHeapSupported"), "{line}"); + if !software(&host.device) && window(&host.device).is_none() { + eprintln!("no memory window found for the host's adapter (not a PCI device Windows gave resources to?)"); + } + } + + /// On a PC's own card the window is found (a hardware adapter that is a + /// PCI device has one): run by name where that holds, `--ignored`. + #[test] + #[ignore = "a PCI card of the PC's own: not so in a virtual machine"] + fn the_hosts_window_is_found() { + let Some(host) = crate::host::host() else { + eprintln!("no D3D12 device; the BAR line was not tried"); + return; + }; + let line = line(&host.device); + eprintln!("{line}"); + if !software(&host.device) { + assert!(window(&host.device).is_some(), "no memory window found for the host's card: {line}"); + } + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/batch.rs b/d3d12/crates/leonida-gpu/src/host/batch.rs new file mode 100644 index 0000000000..4aed688c6b --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/batch.rs @@ -0,0 +1,152 @@ +use super::Batch; +use std::sync::Arc; + +#[test] +fn a_texture_is_checked_once_per_submission() { + let mut batch = Batch::default(); + let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16])); + // The first list sampling each texture checks it ... + assert!(batch.texture_due(&a)); + assert!(batch.texture_due(&b)); + // ... later lists of the same submission do not. + assert!(!batch.texture_due(&a)); + assert!(!batch.texture_due(&a.clone())); + assert!(!batch.texture_due(&b)); +} + +#[test] +fn title_writes_make_textures_due_again() { + let mut batch = Batch::default(); + let a = Arc::new(1u32); + assert!(batch.texture_due(&a)); + assert!(!batch.texture_due(&a)); + // A copy into title memory or work that may write it may have + // changed the texture's memory. + batch.title_written(); + assert!(batch.texture_due(&a)); + assert!(!batch.texture_due(&a)); + // A fresh submission starts over. + let mut next = Batch::default(); + assert!(next.texture_due(&a)); +} + +/// `LEONIDA_BATCH_KEPT`: a batch given back comes back on the same thread +/// empty, with its room, and marked kept; another thread gets its own. +#[test] +fn a_kept_batch_comes_back_empty_with_its_room() { + std::thread::spawn(|| { + let mut batch = Batch::reused(); + assert!(batch.kept); + let a = Arc::new(1u32); + assert!(batch.texture_due(&a)); + batch.ranges.extend((0..1000).map(|i| (i, i + 1))); + batch.fills.push((1, 2, 3)); + batch.front = true; + let room = batch.ranges.capacity(); + batch.give_back(); + let mut again = Batch::reused(); + assert!(again.kept && !again.front); + assert!(again.ranges.is_empty() && again.fills.is_empty() && again.spans.is_empty()); + assert_eq!(again.ranges.capacity(), room); + assert!(again.texture_due(&a), "a new submission checks its textures again"); + std::thread::spawn(|| assert!(Batch::reused().ranges.capacity() == 0)).join().unwrap(); + }) + .join() + .unwrap(); +} + +/// The hashing a submission does for textures in physical-page memory, +/// with every list checking the textures it samples (before) and with +/// each checked once (after). Run with +/// `cargo test --release -p leonida-gpu -- --ignored --nocapture texture_checks`. +#[test] +#[ignore = "benchmark"] +fn texture_checks_per_submission() { + const TEXTURES: usize = 48; + const SIZE: usize = 4 << 20; + const LISTS: usize = 12; + let textures: Vec>> = (0..TEXTURES) + .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect())) + .collect(); + let submit = |dedupe: bool| { + let mut batch = Batch::default(); + let mut hashed = 0usize; + let started = std::time::Instant::now(); + for _ in 0..LISTS { + for t in &textures { + if !dedupe || batch.texture_due(t) { + std::hint::black_box(blake3::hash(t)); + hashed += 1; + } + } + } + (started.elapsed(), hashed) + }; + submit(false); // warm up + let (before, n_before) = submit(false); + let (after, n_after) = submit(true); + assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES)); + println!( + "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \ + before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)", + SIZE >> 20, + before.as_secs_f64() / after.as_secs_f64() + ); +} + +#[test] +fn vram_idle_ms_scales_with_pressure() { + let vram_idle_ms = |memory| super::vram_idle_for(memory, false); + let keeps = |memory| super::vram_idle_for(memory, true); + let gib = 1024 * 1024 * 1024; + assert_eq!(keeps(Some([100, 67, 0, 0])), 600_000); + assert_eq!(keeps(Some([100, 68, 0, 0])), 30_000); + assert_eq!(keeps(Some([100, 75, 0, 0])), 2_500); + assert_eq!(keeps(Some([100, 85, 0, 0])), 1_000); + assert_eq!(keeps(None), 5_000); + // Normal (< 75%) + assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000); + assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000); + assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000); + // Moderate (75%..85%) + assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500); + assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500); + // High (>= 85%, including over-budget) + assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000); + assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000); + // Missing or zero budget falls back to normal + assert_eq!(vram_idle_ms(None), 5_000); + assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000); +} + +#[test] +fn textures_are_kept_while_the_card_has_room() { + use super::vram_keep; + let gib = 1 << 30; + assert_eq!(vram_keep(100 * gib, 87 * gib).0, 600_000); + // Past it: the longest idle ones, enough to come down to 85 %. + let (ms, bytes) = vram_keep(100 * gib, 90 * gib); + assert_eq!((ms, bytes), (5_000, 5 * gib)); + assert_eq!(vram_keep(100 * gib, 120 * gib), (1_500, 35 * gib)); + assert_eq!(vram_keep(0, 7).0, 5_000); +} + +#[test] +fn ram_idle_ms_scales_with_pressure() { + let ram_idle_ms = |avail| super::ram_idle_for(avail, false); + assert_eq!(super::ram_idle_for(Some(12 << 30), true), 300_000); + assert_eq!(super::ram_idle_for(Some((12 << 30) - 1), true), 10_000); + assert_eq!(super::ram_idle_for(None, true), 10_000); + let gib = 1024 * 1024 * 1024; + // Normal (>= 4 GiB) + assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000); + assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000); + // Moderate (2 GiB..4 GiB) + assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000); + assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000); + // High (< 2 GiB) + assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000); + assert_eq!(ram_idle_ms(Some(0)), 2_000); + // Missing falls back to normal + assert_eq!(ram_idle_ms(None), 10_000); +} diff --git a/d3d12/crates/leonida-gpu/src/host/batch_scratch_tests.rs b/d3d12/crates/leonida-gpu/src/host/batch_scratch_tests.rs new file mode 100644 index 0000000000..242946538c --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/batch_scratch_tests.rs @@ -0,0 +1,115 @@ +use super::*; +use windows::core::Interface; + +#[test] +fn the_table_of_batch_scratch_buffers_takes_what_it_has_room_for() { + assert_eq!(batches_kept(0, 5, 1024), 5); + assert_eq!(batches_kept(1020, 10, 1024), 4); + assert_eq!(batches_kept(1024, 3, 1024), 0); + // (Never more than it may hold, if it ever held more.) + assert_eq!(batches_kept(2000, 3, 1024), 0); + assert_eq!(batches_kept(7, 0, 1024), 0); + // A buffer holds eight batches of 256 records of 32 bytes. + assert_eq!(BATCH_SCRATCH, 65_536); +} + +/// (`LEONIDA_ALLOCATOR_TRIM`) An allocator is taken anew once it is as +/// old as the switch's seconds, which are 30 unless said, 5 to 3600. +#[test] +fn an_allocator_is_old_after_the_trims_seconds() { + assert_eq!(allocator_trim_secs(None), 30); + assert_eq!(allocator_trim_secs(Some(" 120 ")), 120); + assert_eq!(allocator_trim_secs(Some("1")), 5); + assert_eq!(allocator_trim_secs(Some("86400")), 3600); + assert_eq!(allocator_trim_secs(Some("soon")), 30); + assert!(!allocator_old(1_000, 30_999, 30)); + assert!(allocator_old(1_000, 31_000, 30)); + // (A clock read before the allocator's making is not after it.) + assert!(!allocator_old(5_000, 1_000, 30)); +} + +/// (`LEONIDA_ALLOCATOR_TRIM`) A list reset while its allocator is not +/// old keeps it; reset once it is old, the list has a new one, records +/// into it, closes and is reset again as any list. +#[test] +fn a_reset_takes_an_old_allocator_anew() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the allocator trim not tested"); + return; + }; + let list = host.new_list().unwrap(); + let allocator = |l: &HostList| l.allocator.lock().unwrap().0.as_raw() as usize; + let first = allocator(&list); + TEST_ALLOCATOR_TRIM.set(Some(3600)); + list.close(); + list.reset(); + assert_eq!(allocator(&list), first, "not old yet"); + // (A trim of no seconds: every allocator is old.) + TEST_ALLOCATOR_TRIM.set(Some(0)); + let trims = ALLOCATOR_TRIMS[0].load(Ordering::Relaxed); + list.close(); + list.reset(); + let second = allocator(&list); + assert_ne!(second, first, "a new allocator"); + assert!(ALLOCATOR_TRIMS[0].load(Ordering::Relaxed) > trims); + // SAFETY: an open list. + unsafe { list.list.ClearState(None) }; + list.close(); + TEST_ALLOCATOR_TRIM.set(None); + list.reset(); + assert_eq!(allocator(&list), second, "without the switch: the one it has"); + list.close(); + list.reset(); +} + +/// A list's scratch buffers of batched clamps are its own until it is +/// reset, and nobody's after: the list holds none, the table (or whoever +/// took them from it since: the table is the process's) holds them, and +/// the next recording starts from a buffer's first place, in the common +/// state. +#[test] +fn a_reset_list_gives_its_batch_scratch_buffers_back() { + use crate::indirect::batch::{JOBS, SLOT}; + let Some(host) = host() else { + eprintln!("no D3D12 device; the table of batch scratch buffers not tested"); + return; + }; + if !batch_pool() { + return; + } + let list = host.new_list().unwrap(); + // Nine batches: eight in one buffer, the ninth in the next. + let places: Vec<_> = (0..9).map(|_| list.batch_place().unwrap()).collect(); + let raw = |i: usize| places[i].0.as_raw() as usize; + for i in 0..8 { + assert_eq!(raw(i), raw(0)); + assert_eq!(places[i].1, i as u32 * JOBS * SLOT); + let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }; + assert_eq!(places[i].2, state); + } + assert_ne!(raw(8), raw(0)); + assert_eq!((places[8].1, places[8].2), (0, D3D12_RESOURCE_STATE_COMMON)); + // SAFETY: a live buffer. + assert_eq!(unsafe { places[0].0.GetDesc() }.Width, BATCH_SCRATCH); + // While the list holds them, another list's batch gets another buffer. + let other = host.new_list().unwrap(); + let theirs = other.batch_place().unwrap(); + assert!(theirs.0.as_raw() as usize != raw(0) && theirs.0.as_raw() as usize != raw(8)); + list.close(); + list.reset(); + { + let args = list.batch_args.lock().unwrap(); + assert!(args.buffers.is_empty()); + assert_eq!(args.used, 0); + } + // Not let go: something holds each beside the references here. + assert!(!sole(&places[0].0) && !sole(&places[8].0)); + // The next recording of the list starts as its first did. + let again = list.batch_place().unwrap(); + assert_eq!((again.1, again.2), (0, D3D12_RESOURCE_STATE_COMMON)); + assert_ne!(again.0.as_raw(), theirs.0.as_raw()); + list.close(); + list.reset(); + other.close(); + other.reset(); +} diff --git a/d3d12/crates/leonida-gpu/src/host/batch_tables.rs b/d3d12/crates/leonida-gpu/src/host/batch_tables.rs new file mode 100644 index 0000000000..66f4ac2aae --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/batch_tables.rs @@ -0,0 +1,272 @@ +//! Leonida: the job tables of the batched clamps (`crate::indirect::batch`) in the card's own +//! memory (`LEONIDA_BATCH_TABLE_CARD`). +//! +//! A pass of the batched clamp reads its table before it does anything: the count, then (only +//! once that is known) its jobs, two reads one after the other. In upload memory (the PC's, where +//! the list's scratch memory is without a resizable BAR, [`scratch_card`]) each crosses the bus, +//! and the card waits for both with nothing else of the pass to do: some 4.9 ms a frame in 653 +//! passes in the timing run of the world scene (RX 7900 XT, 2026-11-30), a pass 4.8-5.0 us +//! where the same pass reading a table in the card's memory, the copy that puts it there +//! counted, takes 3.4-3.5 us (3.9 against 3.0 with pixel work in flight). +//! +//! So each scratch buffer of the batches ([`BatchScratch`]) has, besides, a table area for its +//! [`BATCHES`] batches ([`Tables`]): an upload buffer the CPU fills as before (what the list's +//! scratch memory held, at the same offsets of a table) and a buffer in the card's memory the +//! pass reads. The list's prelude copies the one into the other, once for every buffer of the +//! list's batches ([`HostList::prelude`]): the tables are whole by then, as the list is closed. +//! +//! Why every pass reads what the CPU wrote, and the records it clamps are still the only ones +//! an execution reads: the CPU writes a table only while its list is recorded (a recording drops +//! its open batch at its first use of another list, `crate::draw::State::batched`), so it is +//! final when the list closes; the list is submitted after it closes, and what the CPU wrote to +//! upload memory is the card's to read from the `ExecuteCommandLists` that sends it. The prelude +//! goes in the same `ExecuteCommandLists` as its list, right before it (`Host::submit`), and its +//! copy is followed by a transition of the mirror to `NON_PIXEL_SHADER_RESOURCE`, which waits for +//! the copy. The pass itself is as it was (`batch::record`: the same wait for every earlier +//! shader write, the same transitions of the scratch buffer), so it still sees every write to +//! the records it reads, and an execution still reads the clamped records only behind its +//! transition to `INDIRECT_ARGUMENT`. The list moves the mirror back to `COMMON` when it closes +//! ([`BatchArgs::close`]), with the scratch buffers: a list run twice in one submission copies +//! again only after its first run's passes have read the mirror, and the next recording finds it +//! where the prelude expects it. A table area is given back with its scratch buffer, at the list's +//! reset, when nothing that reads it can still run. +//! +//! Whether a batch reads its table from there is decided when it is opened and kept per batch +//! ([`BatchArgs::mirrored`]): a switch flipped while a list is recorded (`LEONIDA_AB`) leaves +//! the batches before as they were, and a pass never reads a table its prelude does not copy. + +use super::*; + +/// Whether passes of the batched clamp read their tables from the card's memory, copied there by +/// the list's prelude (module docs; `LEONIDA_BATCH_TABLE_CARD=0`: from upload memory, as before; +/// `LEONIDA_AB` by turns). Not where the list's scratch memory is in the card's memory already +/// ([`scratch_card`] with a resizable BAR): the table is there then. +pub(crate) fn table_card(host: &Host) -> bool { + crate::toggled!("LEONIDA_BATCH_TABLE_CARD") && !(scratch_card(host) && host.mapped_card_memory()) +} + +/// The bytes between two tables of a table area: [`crate::indirect::batch::TABLE`] on 256 bytes, +/// as a root view's address wants them (on 4 it would do, but the copy is one). +pub(crate) const STRIDE: u64 = crate::indirect::batch::TABLE.next_multiple_of(256); + +/// The table area of a scratch buffer of the batched clamps: a table for each of its batches +/// in a buffer in the card's memory the passes read (`mirror`), and in an upload buffer the CPU +/// fills (`staging`, mapped at `at`), [`STRIDE`] bytes apart in both. +pub(crate) struct Tables { + mirror: ID3D12Resource, + staging: ID3D12Resource, + at: usize, +} + +impl Tables { + /// A table area, the mirror in the common state; `None` if either buffer is not to be had. + fn make(host: &Host) -> Option { + let bytes = u64::from(BATCHES) * STRIDE; + let mirror = host.uav_buffer(bytes)?; + let (staging, at) = host.upload_buffer(bytes)?; + name(&mirror, || format!("indirect batch tables {bytes:#x}")); + name(&staging, || format!("indirect batch tables, the CPU's {bytes:#x}")); + BATCH_TABLES[4].fetch_add(1, Ordering::Relaxed); + Some(Tables { mirror, staging, at: at as usize }) + } +} + +/// A scratch buffer of the batched clamps (in the common state while no recording uses it), and +/// its table area once a batch in it wanted one ([`table_card`]). +pub(crate) struct BatchScratch { + pub(super) scratch: ID3D12Resource, + tables: Option, +} + +impl BatchScratch { + pub(super) fn new(scratch: ID3D12Resource) -> BatchScratch { + BatchScratch { scratch, tables: None } + } +} + +/// A copy of a table area the list's prelude records: from `staging` into `mirror`, `bytes` at +/// `from` of both. +#[derive(Clone)] +pub(crate) struct TableCopy { + mirror: ID3D12Resource, + staging: ID3D12Resource, + from: u64, + bytes: u64, +} + +/// A host list's scratch buffers of the batched clamps ([`HostList::batch_place_table`]). +#[derive(Default)] +pub(crate) struct BatchArgs { + /// The buffers, [`BATCHES`] batches in each. + pub(super) buffers: Vec, + /// How many batches of this recording have a place in them. + pub(super) used: u32, + /// By buffer: the batches of this recording whose pass reads its table from the buffer's + /// mirror (bit `i`: its batch `i`). + mirrored: Vec, + /// What the list's prelude copies, found when the list closed ([`BatchArgs::close`]). + copies: Vec, +} + +/// Since the last frame-rate line: passes of the batched clamp that read their table from the +/// card's memory, and from upload memory; copies of table areas recorded into preludes, and +/// their bytes; table areas made. +pub(crate) static BATCH_TABLES: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// Where a batch's pass reads its table and the CPU writes it ([`BatchArgs::place`]): the +/// table's address for the card and its mapped address. +pub(crate) type TablePlace = (u64, *mut u8); + +impl BatchArgs { + /// The next batch's place ([`HostList::batch_place_table`]): the scratch buffer, the batch's + /// offset in it and the state it is in, and where its table is. With `card` the table is in + /// the buffer's table area (made the first time a batch of the buffer wants it), and + /// otherwise, or if there is none to be had, `upload()`'s (the list's scratch memory). `None` + /// (and no place taken) if neither is. + pub(super) fn place( + &mut self, + card: bool, + upload: impl FnOnce() -> Option, + ) -> Option<((ID3D12Resource, u32, D3D12_RESOURCE_STATES), TablePlace)> { + use crate::indirect::batch::{JOBS, SLOT}; + let (buffer, i) = ((self.used / BATCHES) as usize, self.used % BATCHES); + if buffer == self.buffers.len() { + self.buffers.push(take_batch_scratch()?); + } + let this = &mut self.buffers[buffer]; + if card && this.tables.is_none() { + this.tables = host().and_then(Tables::make); + } + let mirrored = card && this.tables.is_some(); + let table = match &this.tables { + Some(t) if mirrored => { + let at = u64::from(i) * STRIDE; + // SAFETY: a live buffer. + (unsafe { t.mirror.GetGPUVirtualAddress() } + at, (t.at + at as usize) as *mut u8) + } + _ => upload()?, + }; + if self.mirrored.len() <= buffer { + self.mirrored.resize(buffer + 1, 0); + } + if mirrored { + self.mirrored[buffer] |= 1 << i; + } + BATCH_TABLES[usize::from(!mirrored)].fetch_add(1, Ordering::Relaxed); + self.used += 1; + // (Its first batch finds it as the recording before left it: `HostList::batches_common`.) + let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }; + Some(((this.scratch.clone(), i * JOBS * SLOT, state), table)) + } + + /// The list closes: the copies its prelude is to make, one for each buffer with mirrored + /// batches, from its first such table to the end of its last (whole tables: a table's jobs + /// past its count are not read, and the count is the CPU's to know only through memory it + /// writes and does not read); and into `barriers` the mirrors' transitions back to the common + /// state, behind the passes that read them. The recording is done with which batches were + /// mirrored. + pub(super) fn close(&mut self, barriers: &mut Vec) { + self.copies.clear(); + for (b, mask) in self.buffers.iter().zip(std::mem::take(&mut self.mirrored)) { + let Some(t) = b.tables.as_ref().filter(|_| mask != 0) else { + continue; + }; + let (first, last) = (u64::from(mask.trailing_zeros()), u64::from(7 - mask.leading_zeros())); + let bytes = (last - first) * STRIDE + crate::indirect::batch::TABLE; + self.copies.push(TableCopy { mirror: t.mirror.clone(), staging: t.staging.clone(), from: first * STRIDE, bytes }); + barriers.push(transition(&t.mirror, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON)); + } + } + + /// The list is reset: its next recording starts with no batch, and its prelude copies no + /// table until it closes again. + pub(super) fn reset(&mut self) { + self.used = 0; + self.mirrored.clear(); + self.copies.clear(); + } + + /// The copies of table areas the list's prelude makes ([`BatchArgs::close`]). + pub(super) fn copies(&self) -> Vec { + self.copies.clone() + } +} + +#[cfg(test)] +impl HostList { + /// (Tests) The scratch buffers of the list's batches, each with its table area's mirror and + /// upload buffer if it has them. + pub(crate) fn batch_buffers(&self) -> Vec<(ID3D12Resource, Option<(ID3D12Resource, ID3D12Resource)>)> { + let args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner()); + let tables = |t: &Tables| (t.mirror.clone(), t.staging.clone()); + args.buffers.iter().map(|b| (b.scratch.clone(), b.tables.as_ref().map(tables))).collect() + } +} + +#[cfg(test)] +thread_local! { + /// A test's hook, for the preludes its thread records: no copy of tables (the passes then + /// read whatever their mirror held). + pub(crate) static TEST_NO_TABLE_COPY: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// For [`HostList::prelude`]: each mirror of `copies` to the copy destination (into `to_copy`), +/// and on to `NON_PIXEL_SHADER_RESOURCE` after the copy (into `barriers`), where the list's +/// passes read it. From the common state, where the list's close left it ([`BatchArgs::close`]) +/// and where it was made: explicit both ways, not promoted, so that a list run twice in one +/// `ExecuteCommandLists` copies again only behind its first run's reads. +pub(super) fn copy_barriers(copies: &[TableCopy], to_copy: &mut Vec, barriers: &mut Vec) { + for c in copies { + to_copy.push(transition(&c.mirror, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)); + barriers.push(transition(&c.mirror, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)); + } +} + +/// Records `copies` into a prelude, between the barriers of [`copy_barriers`]. +/// +/// # Safety +/// `list` is open, and the mirrors are in the copy destination state. +pub(super) unsafe fn record_copies(list: &ID3D12GraphicsCommandList, copies: &[TableCopy]) { + for c in copies { + #[cfg(test)] + if TEST_NO_TABLE_COPY.get() { + continue; + } + // SAFETY: the caller's; live buffers of that many bytes. + unsafe { list.CopyBufferRegion(&c.mirror, c.from, &c.staging, c.from, c.bytes) }; + BATCH_TABLES[2].fetch_add(1, Ordering::Relaxed); + BATCH_TABLES[3].fetch_add(c.bytes, Ordering::Relaxed); + } +} + +/// For the frame-rate line: where passes of the batched clamp read their tables, per frame. +pub(super) fn line(frames: f64) { + let t: Vec = BATCH_TABLES.iter().map(|t| t.swap(0, Ordering::Relaxed)).collect(); + if t.iter().all(|&n| n == 0) { + return; + } + let on = host().is_some_and(table_card); + tracing::info!( + "tables of batched clamps per frame: {:.1} passes read theirs in the card's memory, {:.1} in upload memory; {:.1} copies \ + of them in preludes, {:.1} KB; {:.2} table areas made (LEONIDA_BATCH_TABLE_CARD=0: all in upload memory, as before; now {})", + t[0] as f64 / frames, + t[1] as f64 / frames, + t[2] as f64 / frames, + t[3] as f64 / frames / 1024.0, + t[4] as f64 / frames, + if on { "on" } else { "off" } + ); +} + +// A table fits in its place of a table area. +const _: () = assert!(STRIDE >= crate::indirect::batch::TABLE); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tables_lie_on_256_bytes() { + assert_eq!(STRIDE, 4352); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/buffers.rs b/d3d12/crates/leonida-gpu/src/host/buffers.rs new file mode 100644 index 0000000000..ebc7d5da3a --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/buffers.rs @@ -0,0 +1,442 @@ +//! The host's queue and the buffers it makes for others: read backs, uploads, +//! shared and mapped card buffers, UAVs; and the adapter's video memory. + +use super::*; + +impl Host { + /// The queue everything of ours runs on, for a call that must go to it + /// in order with the lists (`crate::tiles`: a texture's levels are + /// given memory ahead of the list that uploads them). + pub(crate) fn queue(&self) -> &ID3D12CommandQueue { + &self.queue + } + + /// A buffer of at least `size` bytes the card writes and we read (a read + /// back), in the state copies into it need: one a list was done with, if + /// one of its size is kept ([`read_back_pool`]), else a new one. + #[cfg_attr(feature = "diagnostics", track_caller)] + pub(crate) fn read_back_buffer(&self, size: u64) -> Option { + if !read_back_pool() { + return self.new_read_back_buffer(size); + } + let size = read_back_size(size); + let kept = SPARE_BACKS.lock().unwrap_or_else(|e| e.into_inner()).take(size); + if let Some(SpareBack(buffer)) = kept { + BACKS[1].fetch_add(1, Ordering::Relaxed); + return Some(buffer); + } + self.new_read_back_buffer(size) + } + + /// A new buffer of `size` bytes in read-back memory, in the state copies + /// into it need. + #[cfg_attr(feature = "diagnostics", track_caller)] + fn new_read_back_buffer(&self, size: u64) -> Option { + BACKS[0].fetch_add(1, Ordering::Relaxed); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain creation of a read-back buffer. + let made = unsafe { + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + }; + #[cfg(feature = "diagnostics")] + if let Some(b) = &buffer { + crate::census::made_at(b, "read-back buffers", std::panic::Location::caller()); + } + match made { + Ok(()) => buffer, + Err(e) => { + tracing::warn!(error = %e, size, "no read-back buffer"); + None + } + } + } + + #[cfg_attr(feature = "diagnostics", track_caller)] + pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + #[cfg(feature = "diagnostics")] + let began = std::time::Instant::now(); + MADE[0].fetch_add(1, Ordering::Relaxed); + MADE[1].fetch_add(size, Ordering::Relaxed); + // A small one is placed in a block (`LEONIDA_SMALL_BUFFER_POOL`). + if let Some(placed) = crate::pool::small::buffer(&self.device, crate::pool::small::UPLOAD, size) { + #[cfg(feature = "diagnostics")] + buffers_made::made(buffers_made::UPLOAD, size, true, began, std::panic::Location::caller()); + return Some(placed); + } + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_UPLOAD, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of an upload buffer. + let made = unsafe { + self.device + .CreateCommittedResource( + &heap, + not_resident(), + &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut buffer, + ) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + resident(&self.device, b)?; + b.Map(0, None, Some(&mut data)) + }) + }; + #[cfg(feature = "diagnostics")] + if let Some(b) = &buffer { + crate::census::made_at(b, "upload buffers", std::panic::Location::caller()); + } + #[cfg(feature = "diagnostics")] + if made.is_ok() + && let Some(b) = &buffer + { + crate::book::made(b, || "an upload buffer".into()); + } + #[cfg(feature = "diagnostics")] + buffers_made::made(buffers_made::UPLOAD, size, false, began, std::panic::Location::caller()); + match made { + Ok(()) => Some((buffer?, data.cast())), + Err(e) => { + crate::residency::allocation_error(&e); + tracing::warn!(error = %e, size, "no upload buffer"); + None + } + } + } +} + +impl Host { + /// PCI vendor ID of the adapter running the host device. + pub(crate) fn adapter_vendor_id(&self) -> Option { + // SAFETY: a plain query on the adapter kept with this device. + unsafe { self.adapter.as_ref()?.GetDesc1() }.ok().map(|desc| desc.VendorId) + } + + /// The card's memory as the system accounts it to this process, in + /// bytes: the budget and the use of the card's own memory, then of the + /// PC's memory shared with the card (where the system moves what does + /// not fit on the card). + pub(crate) fn video_memory(&self) -> Option<[u64; 4]> { + let adapter = self.adapter.as_ref()?; + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries that fill our structures. + unsafe { + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) + .ok()?; + } + // The card's budget moved by 256 MB or more since the last look: + // said at once, with what was in use at the last look, so the log + // has the moment. (It fell from 11,242 MB to some 10,300 MB with + // the first world frame in runs 179 to 185, and the memory line, + // seconds later, was the first to show it. We reserve nothing + // and make the swap chain once, at the start.) + static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage]; + let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed)); + if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) { + tracing::info!( + "the system changed the budget of the card's memory from {} MB to {} MB (frame {}); at the last look {} MB of the card's and {} MB of the PC's shared memory were in use", + last[0] >> 20, + own.Budget >> 20, + crate::frame::current(), + last[1] >> 20, + last[2] >> 20 + ); + self.log_video_memory("right after that change"); + } + Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage]) + } + + /// Both of the system's memory groups for this process, in bytes: for + /// the card's own memory and then for the PC's memory shared with the + /// card, the budget, the use, what could still be reserved and what + /// is reserved (the layer reserves none). + pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> { + let adapter = self.adapter.as_ref()?; + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries that fill our structures. + unsafe { + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) + .ok()?; + } + let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| { + [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation] + }; + Some([all(&own), all(&shared)]) + } + + /// Logs [`Self::video_memory_groups`], with `when` it is said. + pub(crate) fn log_video_memory(&self, when: &str) { + let Some([own, shared]) = self.video_memory_groups() else { + return; + }; + tracing::info!( + "video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved; the PC's shared with the card: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved (the layer reserves none)", + when, + own[0] >> 20, + own[1] >> 20, + own[2] >> 20, + own[3] >> 20, + shared[0] >> 20, + shared[1] >> 20, + shared[2] >> 20, + shared[3] >> 20 + ); + } + + /// A buffer in system memory that the CPU maps (write-back, so reading + /// it is fast too) and shaders read and write: for host copies of title + /// memory that shaders write, which upload memory cannot be. Starts in + /// the common state (buffers move out of it implicitly). + #[cfg_attr(feature = "diagnostics", track_caller)] + pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + #[cfg(feature = "diagnostics")] + let began = std::time::Instant::now(); + MADE[2].fetch_add(1, Ordering::Relaxed); + MADE[3].fetch_add(size, Ordering::Relaxed); + // A small one is placed in a block (`LEONIDA_SMALL_BUFFER_POOL`). + if let Some(placed) = crate::pool::small::buffer(&self.device, crate::pool::small::SHARED, size) { + #[cfg(feature = "diagnostics")] + buffers_made::made(buffers_made::SHARED, size, true, began, std::panic::Location::caller()); + return Some(placed); + } + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of a CPU-visible buffer. + let made = unsafe { + self.device + .CreateCommittedResource( + &heap, + not_resident(), + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + resident(&self.device, b)?; + mapped(&self.device)?; + b.Map(0, None, Some(&mut data)) + }) + }; + #[cfg(feature = "diagnostics")] + if let Some(b) = &buffer { + crate::census::made_at(b, "shared buffers", std::panic::Location::caller()); + } + #[cfg(feature = "diagnostics")] + if made.is_ok() + && let Some(b) = &buffer + { + crate::book::made(b, || "a shared buffer".into()); + } + #[cfg(feature = "diagnostics")] + buffers_made::made(buffers_made::SHARED, size, false, began, std::panic::Location::caller()); + match made { + Ok(()) => Some((buffer?, data.cast())), + Err(e) => { + tracing::warn!(error = %e, size, "no shared buffer"); + None + } + } + } + + /// Whether buffers can lie in the card's memory and be mapped by the CPU + /// (`D3D12_HEAP_TYPE_GPU_UPLOAD`: a resizable BAR, and a system and driver + /// that offer it); logged once. + pub(crate) fn mapped_card_memory(&self) -> bool { + static THERE: OnceLock = OnceLock::new(); + *THERE.get_or_init(|| { + let supported = bar::gpu_upload_heaps(&self.device); + tracing::info!(supported, "card memory the CPU maps"); + supported + }) + } + + /// A buffer in the card's own memory that the CPU maps, shaders read and + /// (with `written`) may write. The CPU should only write it: a read of the + /// mapping crosses the bus a few bytes at a time. + #[cfg_attr(feature = "diagnostics", track_caller)] + pub(crate) fn mapped_card_buffer(&self, size: u64, written: bool) -> Option<(ID3D12Resource, *mut u8)> { + if !self.mapped_card_memory() { + return None; + } + MADE[4].fetch_add(1, Ordering::Relaxed); + MADE[5].fetch_add(size, Ordering::Relaxed); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_GPU_UPLOAD, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: if written { + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS + } else { + D3D12_RESOURCE_FLAG_NONE + }, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of a CPU-visible buffer. + let made = unsafe { + self.device + .CreateCommittedResource( + &heap, + not_resident(), + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + resident(&self.device, b)?; + mapped(&self.device)?; + b.Map(0, None, Some(&mut data)) + }) + }; + #[cfg(feature = "diagnostics")] + if let Some(b) = &buffer { + crate::census::made_at(b, "card buffers the CPU maps", std::panic::Location::caller()); + } + match made { + Ok(()) => Some((buffer?, data.cast())), + Err(e) => { + tracing::warn!(error = %e, size, "no buffer in card memory the CPU maps"); + None + } + } + } + + /// A device-local buffer shaders may write (unordered access) and indirect + /// execution may read, starting in the common state. + #[cfg_attr(feature = "diagnostics", track_caller)] + pub(crate) fn uav_buffer(&self, size: u64) -> Option { + MADE[4].fetch_add(1, Ordering::Relaxed); + MADE[5].fetch_add(size, Ordering::Relaxed); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain creation of a device-local buffer. + let made = unsafe { + self.device.CreateCommittedResource( + &heap, + not_resident(), + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + }; + #[cfg(feature = "diagnostics")] + if let Some(b) = &buffer { + crate::census::made_at(b, "card buffers", std::panic::Location::caller()); + crate::book::made(b, || "an unordered access buffer".into()); + } + let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| resident(&self.device, b))).and_then(|()| mapped(&self.device)); + match made { + Ok(()) => buffer, + Err(e) => { + tracing::warn!(error = %e, size, "no unordered-access buffer"); + None + } + } + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/card_steps.rs b/d3d12/crates/leonida-gpu/src/host/card_steps.rs index 71b61b129c..0eeee88d37 100644 --- a/d3d12/crates/leonida-gpu/src/host/card_steps.rs +++ b/d3d12/crates/leonida-gpu/src/host/card_steps.rs @@ -205,6 +205,16 @@ pub(super) struct Writer { copy: bool, } +impl Writer { + /// Whether its landing may put bytes into title memory `[from, to)`: + /// only what it says it writes, whichever copy it goes through (a copy + /// in the card's memory merges only inside its declared span, + /// `exact_wait`). + pub(super) fn lands_in(&self, from: usize, to: usize) -> bool { + self.from < to && from < self.to + } +} + /// What `items` of the line write. pub(super) fn writers(items: &[Late]) -> Vec { let mut out = Vec::new(); diff --git a/d3d12/crates/leonida-gpu/src/host/compare.rs b/d3d12/crates/leonida-gpu/src/host/compare.rs new file mode 100644 index 0000000000..1139e73654 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/compare.rs @@ -0,0 +1,463 @@ +//! The compare's results area or ring ([`ResultArea`], [`ResultRing`]) and its +//! passes ([`CARD_COMPARE`], [`ComparePass`]). + +use super::*; + +/// Whether the compare's results are a ring ([`ResultRing`]; +/// `LEONIDA_COMPARE_RING=0`: the area as before, [`ResultArea::Whole`]). +/// +/// With [`relay`] the area went back to dword 0 only when no plan was out +/// (`Host::card_done`), which never happens while flights keep overlapping. +/// Once half of it was taken (131,072 pieces of 64 KiB, 8 GiB of declared +/// ranges) every submission sent ahead first waited until nothing was in the +/// air, under the submission lock ([`WHY_RESULTS`]), and what did not fit was +/// fetched whole. What brought `out` back to 0 was mostly the sweep's forced +/// settle every 1.5 s (`Host::submit`), which stays for this area alone +/// ([`sweep_wants_rest`]). How often that drain happens is a +/// hypothesis from the code, not measured: the frame line's "room in the +/// compare's results" counts it. With the ring a submission waits only when +/// the ring has no run long enough for its ranges, and only until the oldest +/// plans have landed; never for ranges longer than the whole ring, whose +/// rest is fetched whole however long it waits. Read once: a plan is given back to the area that +/// placed it. +pub(super) fn compare_ring() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_COMPARE_RING").is_none_or(|v| v != "0")) +} + +/// [`ResultArea::room`] of the compare's results, set under [`CARD_WORK`] +/// whenever a plan takes or gives back dwords: what a submission waiting for +/// room looks at while flights land, without the lock (the thread that lands +/// them takes it to give plans back). `u32::MAX` until the area is made. +pub(super) static RESULTS_ROOM: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(u32::MAX); + +/// The compare's results ([`CardWork::differs`]) as a ring of dwords +/// ([`compare_ring`]): a plan takes one run of them from the head, never +/// wrapped within it, so `differs[r.at + p]` of each of its ranges lies in +/// the run (`card_back`, `relay_card_back`). A run is free again when the +/// plan that took it was given back (its flight landed and its results were +/// read, `Host::card_done`) and so was every plan before it: the space is +/// taken back from the oldest run on, so a plan given back early frees +/// nothing until those before it are. +#[derive(Debug)] +pub(super) struct ResultRing { + /// Dwords in the area. + cap: u32, + /// The runs taken, oldest first: (ticket, from, to, given back). + out: std::collections::VecDeque<(u64, u32, u32, bool)>, + /// The next ticket; 0 is none. + next: u64, +} + +impl ResultRing { + pub(super) fn new(cap: u32) -> Self { + Self { cap, out: std::collections::VecDeque::new(), next: 1 } + } + + /// Where a plan asking for `want` dwords goes, and how many it may take + /// there: the free run behind the newest run if `want` fits in it, else + /// the one from dword 0 if it fits there (the end stays unused until the + /// oldest run has passed it), else the longer of the two. Wrapped (the + /// newest run ends before the oldest begins) only the space between them + /// is free. + pub(super) fn place(&self, want: u32) -> (u32, u32) { + let (Some(&(_, tail, _, _)), Some(&(_, _, head, _))) = (self.out.front(), self.out.back()) else { + return (0, self.cap); + }; + if head <= tail { + return (head, tail - head); + } + let end = self.cap - head; + if end >= want || end >= tail { (head, end) } else { (0, tail) } + } + + /// `[at, at + used)`, where [`ResultRing::place`] put it, is taken: its + /// ticket for [`ResultRing::give_back`], 0 if nothing was taken. + pub(super) fn take(&mut self, at: u32, used: u32) -> u64 { + if used == 0 { + return 0; + } + debug_assert!(u64::from(at) + u64::from(used) <= u64::from(self.cap), "a run past the end of the results"); + let ticket = self.next; + self.next += 1; + self.out.push_back((ticket, at, at + used, false)); + ticket + } + + /// The run of `ticket` was read: it and every run before it that was + /// read are free again. + pub(super) fn give_back(&mut self, ticket: u64) { + if let Some(run) = self.out.iter_mut().find(|r| r.0 == ticket) { + run.3 = true; + } + while self.out.front().is_some_and(|r| r.3) { + self.out.pop_front(); + } + } + + /// The most dwords one plan can take now. + pub(super) fn room(&self) -> u32 { + self.place(u32::MAX).1 + } +} + +/// Where the compare's results go in [`CardWork::differs`]. +#[derive(Debug)] +pub(super) enum ResultArea { + /// `LEONIDA_COMPARE_RING=0`, as before: each plan's dwords from `taken` + /// on, and the area starts from 0 again when a plan is given back, with + /// the relay (`held`) only when no plan is out. + Whole { cap: u32, taken: u32, out: u32, held: bool }, + Ring(ResultRing), +} + +impl ResultArea { + /// An area of `cap` dwords: a ring if `ring`; `held` for the whole area + /// with [`relay`]. + pub(super) fn new(cap: u32, ring: bool, held: bool) -> Self { + if ring { Self::Ring(ResultRing::new(cap)) } else { Self::Whole { cap, taken: 0, out: 0, held } } + } + + /// Where a plan asking for `want` dwords goes, and how many it may take + /// there (in one run). + pub(super) fn place(&self, want: u32) -> (u32, u32) { + match self { + Self::Whole { cap, taken, .. } => (*taken, cap.saturating_sub(*taken)), + Self::Ring(ring) => ring.place(want), + } + } + + /// A plan took `[at, at + used)` (from [`ResultArea::place`]; `used` + /// may be 0): what it gives back when it is done. Every plan takes, so + /// that the whole area counts those out. + pub(super) fn take(&mut self, at: u32, used: u32) -> u64 { + match self { + Self::Whole { taken, out, .. } => { + *taken = at + used; + *out += 1; + 0 + } + Self::Ring(ring) => ring.take(at, used), + } + } + + /// The compare of a plan's ranges, `asked` in order, each with what + /// `of` says of it (its pieces, whether its copy has hashes from before + /// to compare with, whether it is only looked at), in one run of the + /// area ([`ResultArea::place`] for the pieces of those that can be + /// compared): each range kept with the dword its flags go from and + /// whether it is compared, in order, those that do not fit fetched + /// whole and those only looked at that are not compared left out; and + /// the run's ticket, for [`ResultArea::give_back`] once the plan's + /// results are read (`Host::card_done`). + /// + /// `of`'s fourth answer says the range's first piece is the last piece of + /// the range just before it, of the same copy ([`compare_share`]): if + /// that one is compared, the range is placed on that piece's dword, so + /// the piece is hashed once and both read its flag. + pub(super) fn plan(&mut self, asked: Vec, of: impl Fn(&T) -> (u32, bool, bool, bool)) -> (Vec<(T, u32, bool)>, u64) { + let want = asked + .iter() + .map(&of) + .filter(|&(_, twin, _, _)| twin) + .map(|(pieces, _, _, shares)| u64::from(pieces - u32::from(shares && pieces > 0))) + .sum::() + .min(u64::from(u32::MAX)); + let (start, room) = self.place(want as u32); + let mut at = start; + let mut placed = Vec::with_capacity(asked.len()); + // Whether the range just before was compared. + let mut last = false; + for range in asked { + let (pieces, twin, looked_only, shares) = of(&range); + let shared = u32::from(shares && last && pieces > 0); + let compared = twin && u64::from(at - start) + u64::from(pieces - shared) <= u64::from(room); + last = compared; + if looked_only && !compared { + continue; + } + placed.push((range, if compared { at - shared } else { at }, compared)); + if compared { + at += pieces - shared; + } + } + (placed, self.take(start, at - start)) + } + + /// The plan that took `ticket` is done, its results read. + pub(super) fn give_back(&mut self, ticket: u64) { + match self { + Self::Whole { taken, out, held, .. } => { + *out = out.saturating_sub(1); + // With the relay other plans may be on the card, their + // results not read yet: the area starts again only when + // none is out. + if !*held || *out == 0 { + *taken = 0; + } + } + Self::Ring(ring) => ring.give_back(ticket), + } + } + + /// The most dwords one plan can take now. + pub(super) fn room(&self) -> u32 { + match self { + Self::Whole { cap, taken, .. } => cap.saturating_sub(*taken), + Self::Ring(ring) => ring.room(), + } + } + + /// Of a plan asking for `want` dwords when the ring has `room` of its + /// `cap`: the dwords to wait for ([`Host::card_results_short`]), if it + /// is short. Never more than the whole ring: what is past it is fetched + /// whole however long the plan waits, and waiting for an empty ring is + /// a full drain that buys a part of it at best. + pub(super) fn short(want: u64, room: u32, cap: u32) -> Option { + (want > u64::from(room) && want <= u64::from(cap)).then_some(want as u32) + } + + /// The whole area with the relay: half of it is taken by plans in the + /// air, and it starts from the beginning only when none is out, so the + /// caller lets every flight land first. Never for the ring, which waits + /// for room by what a plan asks (`Host::card_results_short`). + pub(super) fn low(&self) -> bool { + matches!(self, Self::Whole { cap, taken, .. } if u64::from(*taken) * 2 > u64::from(*cap)) + } +} + +/// The compare of a declared range of a copy in the card's memory with +/// its bytes from before, one group per 64 KiB piece (cut at multiples of +/// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs` +/// gets a dword per piece, odd where a byte differs. The offsets are widened +/// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a +/// byte just outside the range costs a fetch that finds nothing. +/// +/// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and +/// one of them hashes their 64 hashes: 64 steps after one another. One thread +/// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's +/// 82 on the card (capture replay1, 405 of them), most of it waiting for +/// those steps. +pub(crate) const CARD_COMPARE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)" +cbuffer Span : register(b0) { + uint first; // the first piece + uint skew; // where the copy starts in its piece 0 + uint size; // the copy's buffer, in bytes (a multiple of 64 KiB) + uint pieces; + uint out_at; // the first piece's dword in `differs`, in bytes + uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored) +}; +ByteAddressBuffer now : register(t0); +// 16 bytes per piece of the copy: the hash of its bytes when they were +// last sent up (or hashed whole, the first time). +RWByteAddressBuffer hashes : register(u0); +RWByteAddressBuffer differs : register(u1); +groupshared uint4 parts[64]; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) { + uint piece = first + id.x; + uint lo = piece * 65536u; + lo = lo > skew ? lo - skew : 0u; + uint hi = min((piece + 1u) * 65536u - skew, size); + lo = lo & ~15u; + hi = (hi + 15u) & ~15u; + uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread; + uint at = lo + thread * 16u; + // Eight loads at once: one after the other, each waits for memory. + [loop] + for (; at + 7168u < hi; at += 8192u) { + uint4 v0 = now.Load4(at + 0u); + uint4 v1 = now.Load4(at + 1024u); + uint4 v2 = now.Load4(at + 2048u); + uint4 v3 = now.Load4(at + 3072u); + uint4 v4 = now.Load4(at + 4096u); + uint4 v5 = now.Load4(at + 5120u); + uint4 v6 = now.Load4(at + 6144u); + uint4 v7 = now.Load4(at + 7168u); + h = (h ^ v0) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v1) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v2) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v3) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v4) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v5) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v6) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + h = (h ^ v7) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + } + [loop] + for (; at < hi; at += 1024u) { + h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + } + parts[thread] = h; + GroupMemoryBarrierWithGroupSync(); + if (thread != 0u) return; + h = parts[0]; + [loop] + for (uint i = 1u; i < 64u; ++i) { + h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + } + if (compare != 0u) { + // The flag, and above it 31 bits of the hash (`torn`). + uint folded = h.x ^ (h.y * 3u) ^ (h.z * 5u) ^ (h.w * 7u); + differs.Store(out_at + id.x * 4u, (folded << 1u) | (any(h != hashes.Load4(piece * 16u)) ? 1u : 0u)); + // With the copy-back on its own thread: the next compare of the + // piece finds what is written from here on. + if (compare == 2u) hashes.Store4(piece * 16u, h); + } else { + hashes.Store4(piece * 16u, h); + } +} +"#; + +/// The hash [`CARD_COMPARE`] gives of a piece with its flag. +#[cfg(test)] +pub(crate) fn piece_hash(bytes: &[u8]) -> u32 { + torn::hash(bytes) +} + +/// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from +/// dword `at` on (`mode` as the shader's `compare`): a group per piece, in +/// parts a dispatch can hold. +/// +/// # Safety +/// The list is open with the compare's root signature, pipeline and buffers +/// set, and the pieces lie in the buffer. +pub(super) unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) { + const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; + let mut done = 0; + while done < span.pieces { + let n = (span.pieces - done).min(MOST); + let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode]; + // SAFETY: the caller's. + unsafe { + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.Dispatch(n, 1, 1); + } + done += n; + } +} + +/// Whether the compares of ranges of one copy in the card's memory whose +/// pieces and result places follow each other go in one pass +/// (`LEONIDA_CARD_COMPARE_JOIN=0`: a pass each, as before). +/// +/// The compare ran a pass per declared range after the lists of every +/// submission, each a dispatch with its constants and two root views set: +/// some 390 a frame in the fork's count (walking in the prison). Joined, the +/// same pieces are hashed and flagged at the same places: a pass takes its +/// pieces from `first` on and writes piece `i`'s flag at dword `at + i`, and +/// two passes are joined only where the second goes on at both. +/// (After edsuuu/VI-BR-PORT 2f59f1d.) +pub(super) fn compare_join() -> bool { + crate::toggled!("LEONIDA_CARD_COMPARE_JOIN") +} + +/// A pass of [`CARD_COMPARE`] after a submission's lists: the copy's card +/// side and its hashes (where the card has them), the bytes hashed of a +/// piece, the pieces, the first's place in the flags, the mode. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct ComparePass { + pub(super) buffer: u64, + pub(super) hashes: u64, + pub(super) size: u32, + pub(super) span: crate::shadow::CardSpan, + pub(super) at: u32, + pub(super) mode: u32, +} + +/// Whether a declared range whose first piece is the last piece of the +/// declared range before it, in the same copy, has that piece hashed once +/// for both (`LEONIDA_CARD_COMPARE_SHARE=0`: once for each, as before). +/// +/// The declared ranges of a copy are joined where they overlap or touch +/// ([`card_asked`]), so two views a few bytes apart in one 64 KiB piece stay +/// two ranges, and each had its own pass hash the whole piece: a piece that +/// held `n` declared ranges was read `n` times on the card, and as the passes +/// of one piece do not go on at the next piece, none of them joined +/// ([`joined_compares`]). Shared, the second range is placed on the first's +/// last dword in the results ([`ResultArea::plan`]) and its pass begins one +/// piece later ([`unshared_compares`]), which then goes on where the first +/// ends and joins it. Each range still reads the flag of each of its pieces +/// and lands its own bytes of a flagged piece, as before; with the relay's +/// mode 2 (the hash stored) the second pass no longer races the first's +/// store of the same piece's hash. Measured on the RX 7900 XT +/// (`host::comparecost`, `docs/findings.md`). +pub(super) fn compare_share() -> bool { + #[cfg(test)] + if let Some(on) = TEST_SHARE.get() { + return on; + } + crate::toggled!("LEONIDA_CARD_COMPARE_SHARE") +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`compare_share`], for its thread only. + pub(super) static TEST_SHARE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Whether `next`, a declared range of the copy just after `last`, begins in +/// the piece `last` ends in ([`compare_share`]). +pub(super) fn shares_piece(last: &crate::shadow::CardSpan, next: &crate::shadow::CardSpan) -> bool { + last.pieces > 0 && next.pieces > 0 && last.first + last.pieces - 1 == next.first +} + +/// `passes` in order with no dword hashed twice: a pass whose first places +/// in the results the pass before it, of the same copy, has already (a range +/// placed on the last piece of the range before it, [`compare_share`]) +/// begins after them, and one left with no piece is dropped. Without shared +/// places nothing changes. +pub(super) fn unshared_compares(passes: impl Iterator) -> Vec { + let mut out: Vec = Vec::new(); + for mut pass in passes { + if let Some(last) = out.last() + && (last.buffer, last.hashes, last.size, last.mode, last.span.skew) + == (pass.buffer, pass.hashes, pass.size, pass.mode, pass.span.skew) + && (last.at..last.at + last.span.pieces).contains(&pass.at) + && last.span.first + (pass.at - last.at) == pass.span.first + { + let done = (last.at + last.span.pieces - pass.at).min(pass.span.pieces); + pass.at += done; + pass.span.first += done; + pass.span.pieces -= done; + } + if pass.span.pieces > 0 { + out.push(pass); + } + } + out +} + +/// `passes` in order, with those joined that go on where the one before +/// them ends ([`compare_join`]): the same copy, piece size, mode and skew, +/// the next piece and the next place. +pub(super) fn joined_compares(passes: impl Iterator, join: bool) -> Vec { + let mut out: Vec = Vec::new(); + for pass in passes { + match out.last_mut() { + Some(last) + if join + && (last.buffer, last.hashes, last.size, last.mode, last.span.skew) + == (pass.buffer, pass.hashes, pass.size, pass.mode, pass.span.skew) + && last.span.first + last.span.pieces == pass.span.first + && last.at + last.span.pieces == pass.at => + { + last.span.pieces += pass.span.pieces; + last.span.to = pass.span.to; + } + _ => out.push(pass), + } + } + out +} diff --git a/d3d12/crates/leonida-gpu/src/host/compare_ecl.rs b/d3d12/crates/leonida-gpu/src/host/compare_ecl.rs new file mode 100644 index 0000000000..d0f93f2564 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/compare_ecl.rs @@ -0,0 +1,463 @@ +//! The compare of a submission's host copies in the card's memory (the check +//! list [`Host::card_before`] records) sent in the `ExecuteCommandLists` call +//! of the submission's last lists (`LEONIDA_COMPARE_JOIN=1`; off by default: +//! a call of its own, as before). +//! +//! Since d1fe0bd01 the compare went to the queue in a call of its own after the +//! submission's lists, before its signal: a title list can leave a buffer +//! promoted to `COPY_DEST` (a copy at its place into a host copy's card buffer, +//! `HostList::place_copy`), a buffer decays to `COMMON` only at the end of a +//! call, and the compare reads the card buffers as shader resources (D3D12 +//! error 538). The call was for that state, not for order. On the RX 7900 XT +//! each call more cost the card 18-26 us over the boundary, with everything +//! already queued (a bench of tiny, small and wide lists: 21.6, 22.8, 21.5 us), +//! for the some 18 submissions a frame that compare, each on the chain of +//! fences the title's thread spins on. +//! +//! Joined, the call is the last lists, a list of ours that holds one global +//! barrier ([`place::wait_for_all`]: `SYNC_ALL` to `SYNC_ALL`, every access +//! before it, copies' writes too, done and seen before anything behind it, +//! which the compare's own null UAV barrier does not formally say of copies), +//! then the compare and the lists that stamp the submission's end. Still after +//! every list of the submission on the same queue, still before the signal the +//! relay, the landing and the title wait on; the buffers decay at the end of +//! the call, before the next submission's copies; the results, the landing and +//! the hashes are as before. Joined only where ([`compare_joins`]): +//! - the switch is on; +//! - the card has enhanced barriers (`D3D12_OPTIONS12`), which that barrier is; +//! - no list in the call copied into a host copy's card buffer +//! ([`HostList::copied_into_copy`]): the case of d1fe0bd01, whose state the +//! barrier does not change. Data does not hang on it (the barrier covers the +//! copies); only the state the debug layer holds the buffer in does. +//! +//! Not in the timing run (`LEONIDA_GPU_TIMING`), whose lists each go on their +//! own. Asked for (`crate::asked!`) until the state of d1fe0bd01 is seen clean +//! in the title with the debug layer and GPU-based validation; `LEONIDA_AB` +//! turns it by phases. The flag keeps apart only `COPY_DEST`: a host copy a +//! title list wrote as unordered access (promoted to that write state, which +//! nearly every compared buffer is) is read by the joined compare in the same +//! call. If the layer flags that too (538 or another state message), the +//! switch stays off, or goes apart for every list that writes a compared +//! buffer, or the compare takes its buffers' states in hand. The tests here +//! say whether the layer was there to judge; GPU-based validation in this +//! crate runs without state tracking (`create`), so states are the CPU +//! layer's word alone. + +use super::*; + +/// Since the last frame-rate line, of submissions with a compare: those sent +/// in the call of their last lists, those sent apart, and of these: for a +/// copy into a host copy, for a card without enhanced barriers, with the +/// switch off. +pub(super) static SENT: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; +const JOINED: usize = 0; +const APART: usize = 1; +const APART_COPIED: usize = 2; +const APART_NO_ENHANCED: usize = 3; +const APART_OFF: usize = 4; + +#[cfg(test)] +thread_local! { + /// For tests: the switch, on this thread, whatever the environment says. + pub(super) static TEST_JOIN: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// For tests: the place of [`SENT`] the last compare sent on this thread + /// counted in (for one sent apart, the reason's where there is one). + static TEST_LAST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Whether the compare may go in the call of a submission's last lists +/// (`LEONIDA_COMPARE_JOIN=1`; see the file). +pub(super) fn join_asked() -> bool { + #[cfg(test)] + if let Some(on) = TEST_JOIN.get() { + return on; + } + crate::asked!("LEONIDA_COMPARE_JOIN") +} + +/// Why the compare goes apart from its lists' call ([`SENT`]'s place), or +/// `None` where it is joined to it: by `switch`, whether the card has +/// `enhanced` barriers and whether a list of the call `copied` into a host +/// copy's card buffer. +fn apart(switch: bool, enhanced: bool, copied: bool) -> Option { + if !switch { + Some(APART_OFF) + } else if !enhanced { + Some(APART_NO_ENHANCED) + } else if copied { + Some(APART_COPIED) + } else { + None + } +} + +/// Whether the compare goes in the call of its lists ([`apart`]). +pub(super) fn compare_joins(switch: bool, enhanced: bool, copied: bool) -> bool { + apart(switch, enhanced, copied).is_none() +} + +/// Whether one of `runs` whose lists begin at or after `from` in the +/// submission's array (`firsts`: where each run's begin) copied into a host +/// copy's card buffer ([`HostList::copied_into_copy`]). +pub(super) fn copied_from(runs: &[&HostList], firsts: &[usize], from: usize) -> bool { + runs.iter().zip(firsts).any(|(run, &first)| first >= from && run.deferred().copied_into_copy) +} + +impl HostList { + /// The list has just recorded a copy into the card buffer of a host copy + /// (`Shadow::buffer`, which a compare reads): the buffer may stay in + /// `COPY_DEST` to the end of the call that sends the list, and the + /// submission's compare keeps a call of its own ([`compare_joins`]). + /// Until the list is reset. + /// + /// Not said of copies into buffers of ours (scratch, between, budget, + /// read-backs), which no compare reads, nor by `card_steps::record`, which + /// moves every buffer it copies into back to `COMMON` in the list. + pub(super) fn copied_into_copy(&self) { + self.deferred().copied_into_copy = true; + } +} + +/// Closed lists of ours, each one [`place::wait_for_all`], sent in front of a +/// joined compare: with the fence value of the last submission that sent it. +struct Waits { + allocator: ID3D12CommandAllocator, + lists: Vec<(ID3D12CommandList, u64)>, + next: usize, +} + +// SAFETY: free-threaded D3D12 objects, touched behind the lock. +unsafe impl Send for Waits {} + +static WAITS: Mutex> = Mutex::new(None); + +impl Host { + /// Sends `lists`, the last call of a submission, and `compare` (the check + /// list and the stamps behind it) after them: in one call where + /// [`compare_joins`] says so and `may_join` (not the timing run), with a + /// list of [`Host::wait_list`] between, else in a call of its own as + /// before. `copied` is asked only then; `number` is the fence value + /// signalled right behind. + /// + /// # Safety + /// Closed lists, as `ExecuteCommandLists` takes them. + pub(super) unsafe fn execute_with_compare( + &self, + lists: &[Option], + compare: &[Option], + may_join: bool, + copied: impl FnOnce() -> bool, + number: u64, + ) { + if compare.is_empty() { + // SAFETY: the caller's. + unsafe { self.queue.ExecuteCommandLists(lists) }; + return; + } + // (The card and the lists asked only with the switch on.) + let switch = may_join && join_asked(); + let (enhanced, copied) = (switch && place::enhanced_barriers(self), switch && copied()); + let wait = if may_join && compare_joins(switch, enhanced, copied) { self.wait_list(number) } else { None }; + // SAFETY (both): the caller's; the wait list is closed. + match wait { + Some(wait) => { + SENT[JOINED].fetch_add(1, Ordering::Relaxed); + #[cfg(test)] + TEST_LAST.set(Some(JOINED)); + let mut all = Vec::with_capacity(lists.len() + 1 + compare.len()); + all.extend_from_slice(lists); + all.push(Some(wait)); + all.extend_from_slice(compare); + unsafe { self.queue.ExecuteCommandLists(&all) }; + } + None => { + SENT[APART].fetch_add(1, Ordering::Relaxed); + let why = apart(switch, enhanced, copied).filter(|_| may_join); + if let Some(why) = why { + SENT[why].fetch_add(1, Ordering::Relaxed); + } + #[cfg(test)] + TEST_LAST.set(Some(why.unwrap_or(APART))); + unsafe { + self.queue.ExecuteCommandLists(lists); + self.queue.ExecuteCommandLists(compare); + } + } + } + } + + /// A closed list that holds [`place::wait_for_all`] alone, for submission + /// `number`: one no submission still on the card sent (made when every one + /// is). `None` if none could be made. + fn wait_list(&self, number: u64) -> Option { + let mut waits = WAITS.lock().unwrap_or_else(|e| e.into_inner()); + if waits.is_none() { + // SAFETY: plain object creation. + match unsafe { self.device.CreateCommandAllocator::(D3D12_COMMAND_LIST_TYPE_DIRECT) } { + Ok(allocator) => *waits = Some(Waits { allocator, lists: Vec::new(), next: 0 }), + Err(e) => { + tracing::warn!(error = %e, "no lists for the compare's call (LEONIDA_COMPARE_JOIN)"); + return None; + } + } + } + let waits = waits.as_mut()?; + // SAFETY: a plain query of our fence. + let done = unsafe { self.fence.GetCompletedValue() }; + let n = waits.lists.len(); + let i = match (0..n).map(|k| (waits.next + k) % n).find(|&i| waits.lists[i].1 <= done) { + Some(i) => i, + None => { + // SAFETY: one list of the allocator recorded at a time (the + // lock), each closed at once; an open list for the barrier. + let made = unsafe { + (|| -> windows::core::Result { + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &waits.allocator, None)?; + place::wait_for_all(self, &list); + list.Close()?; + list.cast() + })() + }; + match made { + Ok(list) => waits.lists.push((list, 0)), + Err(e) => { + tracing::warn!(error = %e, "no list for the compare's call (LEONIDA_COMPARE_JOIN)"); + return None; + } + } + n + } + }; + waits.lists[i].1 = number; + waits.next = (i + 1) % waits.lists.len(); + Some(waits.lists[i].0.clone()) + } + + /// For tests: the lists [`Host::wait_list`] made so far. + #[cfg(test)] + pub(super) fn wait_lists_made() -> usize { + WAITS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map_or(0, |w| w.lists.len()) + } +} + +/// For the frame-rate line, per frame over `frames` (taken out): compares +/// joined, apart, and of these for a copy, no enhanced barriers, the switch +/// off. +pub(super) fn per_frame(frames: f64) -> [f64; 5] { + SENT.each_ref().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames) +} + +#[cfg(test)] +mod tests { + use super::super::landsame::card_tests::{turn, writer}; + use super::super::{CARD_WORK, host, torn}; + use super::*; + use crate::shadow::Shadow; + use windows::Win32::System::Threading::{INFINITE, WaitForSingleObject}; + + /// Joined only with the switch on, on a card with enhanced barriers, and + /// no list of the call having copied into a host copy; apart, the first + /// of those that fails is the reason counted. + #[test] + fn the_compare_joins_only_asked_with_enhanced_barriers_and_no_copy_into_a_copy() { + for switch in [false, true] { + for enhanced in [false, true] { + for copied in [false, true] { + assert_eq!(compare_joins(switch, enhanced, copied), switch && enhanced && !copied, "{switch} {enhanced} {copied}"); + } + } + } + assert_eq!(apart(false, true, false), Some(APART_OFF)); + assert_eq!(apart(false, false, true), Some(APART_OFF)); + assert_eq!(apart(true, false, true), Some(APART_NO_ENHANCED)); + assert_eq!(apart(true, true, true), Some(APART_COPIED)); + assert_eq!(apart(true, true, false), None); + } + + const PIECE: usize = 64 << 10; + /// Bytes into the copy of what piece 1 (A) and piece 2 (B) are written at. + const A: usize = PIECE + 0x100; + const B: usize = 2 * PIECE + 0x40; + /// The dwords written of each. + const N: u32 = 16; + + /// What a submission through `Host::submit` did with its compare: where + /// [`SENT`] counted it, the pieces it flagged, the pieces it hashed. + #[derive(Debug, PartialEq)] + struct Done { + how: Option, + flagged: Vec, + hashed: u64, + } + + /// One list as the title's: writes declared at A and B of a copy in the + /// card's memory (four pieces, from a 64 KiB boundary on), a dispatch + /// storing at B, and with `copy_into_a` a copy into A before it (as a + /// copy at its place records one); sent ahead through `Host::submit` with + /// the switch `join`, and waited for. `None` without a copy in the card's + /// memory. + fn submit(host: &'static Host, join: bool, copy_into_a: bool) -> Option { + let room = vec![0u8; 6 * PIECE]; + let start = (room.as_ptr() as usize).next_multiple_of(PIECE); + let shadow = Shadow::carded_for_test(start as u64, (4 * PIECE) as u64)?; + let (root, pso) = writer(&host.device); + let list = host.new_list().expect("a host list"); + let bytes = u64::from(N) * 4; + for at in [A, B] { + shadow.gpu_writes(&list, (start + at) as u64, bytes); + } + let (upload, data) = host.upload_buffer(bytes).expect("upload memory"); + // SAFETY: an open list; the mapping holds `bytes`; live buffers, the + // ranges inside them; the writer's root signature. + unsafe { + if copy_into_a { + std::ptr::write_bytes(data, 0x5a, bytes as usize); + list.list.CopyBufferRegion(&shadow.buffer, A as u64, &upload, 0, bytes); + list.copied_into_copy(); + } + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + let constants = [B as u32, N, 0x1234_0001]; + list.list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.list.Dispatch(1, 1, 1); + } + list.keep(&upload); + list.close(); + TEST_JOIN.set(Some(join)); + TEST_LAST.set(None); + let submitted = host.submit(&[&list], &[], true); + TEST_JOIN.set(None); + let (submitted, sent) = submitted.expect("a submission sent ahead"); + // SAFETY: the submission lock is held; the fence and event are ours. + unsafe { + host.fence.SetEventOnCompletion(*submitted, host.event).unwrap(); + WaitForSingleObject(host.event, INFINITE); + } + let plan = sent.card.expect("a plan with a compare"); + let mut flagged = Vec::new(); + { + let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let differs = work.as_ref().expect("the compare's work").differs.1 as *const u32; + for r in plan.ranges.iter().filter(|r| r.compared) { + for p in 0..r.span.pieces { + // SAFETY: inside the results' mapping, which the card wrote. + if torn::flagged(unsafe { differs.add((r.at + p) as usize).read_volatile() }) { + flagged.push(r.span.first + p); + } + } + } + } + flagged.sort_unstable(); + flagged.dedup(); + let hashed = plan.hashed; + host.card_done(plan); + if let Some(own) = sent.own { + own.landed(); + } + drop(submitted); + drop((root, pso, room)); + Some(Done { how: TEST_LAST.get(), flagged, hashed }) + } + + /// The debug layer's word on `what`, said for which of the two it is: + /// with the layer (a diagnostics build, `LEONIDA_D3D12_DEBUG=1`, the + /// SDK layers installed), no error among its messages; without it, + /// `log_messages` is `None` whatever the queue did, so a line says the + /// state was not checked rather than passing for clean. The open question + /// of the switch (a host copy a title list promoted to a write state, + /// `UNORDERED_ACCESS` as `COPY_DEST`, read as a shader resource in the + /// same call) is answered only by a run with the layer. + fn debug_layer_says_nothing(host: &Host, what: &str) { + if host.messages.is_none() { + eprintln!("no debug layer (a diagnostics build, LEONIDA_D3D12_DEBUG=1, the SDK layers): the state of {what} was not checked"); + return; + } + assert_eq!(host.log_messages(), None, "the debug layer on {what}"); + eprintln!("the debug layer saw {what} and said nothing"); + } + + /// The compare sent in the call of the lists (an enhanced barrier list in + /// front of it) flags exactly the piece the dispatch wrote and hashes the + /// same pieces as the compare sent apart, with the switch on as off; on + /// a card without enhanced barriers it stays apart for that reason. + #[test] + fn a_compare_in_its_lists_call_flags_what_the_lists_wrote() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the compare in its lists' call was not tried"); + return; + }; + let _turn = turn(); + let Some(off) = submit(host, false, false) else { + eprintln!("no copies in the card's memory; the compare in its lists' call was not tried"); + return; + }; + let on = submit(host, true, false).expect("a copy in the card's memory"); + assert_eq!(off.how, Some(APART_OFF), "switched off, apart"); + assert_eq!(off.flagged, [2], "apart: piece B alone"); + let enhanced = place::enhanced_barriers(host); + assert_eq!(on.how, Some(if enhanced { JOINED } else { APART_NO_ENHANCED }), "enhanced barriers: {enhanced}"); + assert_eq!(on.flagged, [2], "in the lists' call: piece B alone"); + assert_eq!((on.hashed, off.hashed), (2, 2), "the declared pieces, once each"); + if enhanced { + assert!(Host::wait_lists_made() >= 1); + } + debug_layer_says_nothing(host, "a compare in its lists' call behind a dispatch that wrote its buffer"); + eprintln!("the compare with the switch on: {} (enhanced barriers: {enhanced})", if on.how == Some(JOINED) { "in its lists' call" } else { "apart" }); + } + + /// A list that copied into a host copy keeps the compare in a call of its + /// own, switch on; it flags the copied piece and the written one. + #[test] + fn a_copy_into_a_copy_keeps_the_compare_apart() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the compare behind a copy was not tried"); + return; + }; + let _turn = turn(); + let Some(done) = submit(host, true, true) else { + eprintln!("no copies in the card's memory; the compare behind a copy was not tried"); + return; + }; + let enhanced = place::enhanced_barriers(host); + assert_eq!(done.how, Some(if enhanced { APART_COPIED } else { APART_NO_ENHANCED }), "enhanced barriers: {enhanced}"); + assert_eq!(done.flagged, [1, 2], "pieces A and B"); + debug_layer_says_nothing(host, "a compare kept apart behind a copy into its buffer"); + } + + /// A copy at its place into a title buffer's host copy says so of its + /// list ([`HostList::copied_into_copy`]) until the list is reset. + #[test] + fn a_copy_at_its_place_marks_its_list() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + let Some(host) = host() else { + eprintln!("no D3D12 device; a copy at its place was not tried"); + return; + }; + if !place::on() { + return; + } + const LEN: usize = 4 * PIECE; + const WRITE_WATCH: u32 = 0x20_0000; + const RESOURCE: usize = 0x7c0e_ec11; + // SAFETY: memory of our own, never freed. + let base = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + crate::shadow::register(RESOURCE, base as u64, LEN as u64); + let shadow = crate::shadow::find(base as u64, 64).expect("a copy"); + let list = host.new_list().expect("a host list"); + let copied = || list.deferred().copied_into_copy; + assert!(!copied(), "a new list"); + let placed = list.place_copy(base + A, base + B, 64); + assert_eq!(placed, !shadow.in_place(), "done in the list unless the copy is title memory itself"); + assert_eq!(copied(), placed); + eprintln!("a copy at its place: {}", if placed { "in the list, which says so" } else { "in title memory itself" }); + list.close(); + list.reset(); + assert!(!copied(), "reset"); + list.close(); + drop((list, shadow)); + crate::shadow::unregister(RESOURCE, base as u64); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/compare_join_tests.rs b/d3d12/crates/leonida-gpu/src/host/compare_join_tests.rs new file mode 100644 index 0000000000..cde994783e --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/compare_join_tests.rs @@ -0,0 +1,144 @@ +use super::{ComparePass, joined_compares}; +use crate::shadow::CardSpan; + +/// Joined, the passes hash the same pieces into the same places, in the +/// same order; only what goes on at both is joined. +#[test] +fn joined_compares_hash_the_same_pieces_into_the_same_places() { + const PIECE: u32 = 64 << 10; + let pass = |buffer: u64, first: u32, pieces: u32, at: u32, mode: u32| ComparePass { + buffer, + hashes: buffer + 1, + size: PIECE, + span: CardSpan { from: first * PIECE, to: (first + pieces) * PIECE, first, pieces, skew: 0 }, + at, + mode, + }; + let skewed = |mut p: ComparePass| { + p.span.skew = 4096; + p + }; + let all = [ + pass(100, 0, 2, 0, 1), + pass(100, 2, 3, 2, 1), // goes on: joined + pass(100, 5, 1, 5, 1), // and again + pass(100, 6, 1, 6, 2), // another mode + pass(100, 7, 1, 9, 2), // not the next place + pass(100, 9, 1, 10, 2), // not the next piece + pass(200, 10, 1, 11, 2), // another copy + pass(200, 11, 2, 12, 2), // goes on + skewed(pass(200, 13, 1, 14, 2)), // another skew + pass(200, 13, 1, 15, 2), // a piece again (two ranges in it) + ]; + // Each pass as (copy, mode, skew, piece, place) for every piece. + let pieces = |passes: &[ComparePass]| -> Vec<(u64, u32, u32, u32, u32)> { + passes + .iter() + .flat_map(|p| (0..p.span.pieces).map(move |i| (p.buffer, p.mode, p.span.skew, p.span.first + i, p.at + i))) + .collect() + }; + let joined = joined_compares(all.into_iter(), true); + assert_eq!(pieces(&joined), pieces(&all)); + assert_eq!(joined.len(), 7); + assert_eq!(joined[0], pass(100, 0, 6, 0, 1)); + assert_eq!((joined[0].span.from, joined[0].span.to), (0, 6 * PIECE)); + assert_eq!(joined[4], pass(200, 10, 3, 11, 2)); + // Not asked for: as they came. + assert_eq!(joined_compares(all.into_iter(), false), all); + assert!(joined_compares(std::iter::empty(), true).is_empty()); +} + +/// The compare of declared ranges as `card_asked` and `Host::card_before` +/// plan it, without copies: `ranges` (copy, span) in order, each copy's +/// sorted and apart, placed in a result area of `cap` dwords and turned +/// into passes (mode 2, hashes at copy + 1). Each range kept with its +/// place and whether it is compared. +pub(super) fn planned(ranges: &[(u64, CardSpan)], cap: u32, share: bool) -> (Vec<(u64, CardSpan, u32, bool)>, Vec) { + let mut asked = Vec::new(); + for (i, &(copy, span)) in ranges.iter().enumerate() { + let shares = share && i > 0 && ranges[i - 1].0 == copy && super::shares_piece(&ranges[i - 1].1, &span); + asked.push((copy, span, shares)); + } + let (placed, _) = super::ResultArea::new(cap, true, false).plan(asked, |&(_, span, shares)| (span.pieces, true, false, shares)); + let kept: Vec<(u64, CardSpan, u32, bool)> = placed.into_iter().map(|((copy, span, _), at, compared)| (copy, span, at, compared)).collect(); + let passes = kept.iter().filter(|r| r.3).map(|&(copy, span, at, _)| ComparePass { buffer: copy, hashes: copy + 1, size: 1 << 30, span, at, mode: 2 }); + let passes = joined_compares(super::unshared_compares(passes).into_iter(), true); + (kept, passes) +} + +/// Declared ranges of two copies, several in one piece, some across +/// pieces, in result areas with room for all and for part: with +/// `LEONIDA_CARD_COMPARE_SHARE` every piece of every compared range is +/// hashed exactly once, at a dword that range reads for it, and no other +/// piece is; without it each range hashes all of its own (a piece that +/// holds several, once for each). +#[test] +fn shared_pieces_are_hashed_once_where_each_range_reads_them() { + const PIECE: u32 = 64 << 10; + let mut seed = 0x9e37_79b9_u32; + let mut next = |n: u32| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed % n + }; + for round in 0..400 { + let mut ranges: Vec<(u64, CardSpan)> = Vec::new(); + for copy in [100u64, 200] { + let skew = [0, 4100, PIECE - 16][next(3) as usize]; + let mut at = next(3 * PIECE); + for _ in 0..1 + next(12) { + let len = [1 + next(64), 1 + next(PIECE), 1 + next(4 * PIECE)][next(3) as usize]; + let (from, to) = (at, at + len); + let first = (from + skew) / PIECE; + ranges.push((copy, CardSpan { from, to, first, pieces: (to - 1 + skew) / PIECE - first + 1, skew })); + at = to + 1 + [next(64), next(PIECE), next(3 * PIECE)][next(3) as usize]; + } + } + let asked: u32 = ranges.iter().map(|r| r.1.pieces).sum(); + for cap in [1 << 16, asked / 2] { + let (kept, passes) = planned(&ranges, cap, true); + // (copy, piece) by dword, from the passes. + let mut by_dword = std::collections::HashMap::new(); + let mut hashed = Vec::new(); + for p in &passes { + for i in 0..p.span.pieces { + assert!(by_dword.insert(p.at + i, (p.buffer, p.span.first + i)).is_none(), "round {round}: a dword hashed twice"); + hashed.push((p.buffer, p.span.first + i)); + } + } + let mut wanted: Vec<(u64, u32)> = Vec::new(); + for &(copy, span, at, compared) in &kept { + if !compared { + continue; + } + for i in 0..span.pieces { + assert_eq!(by_dword.get(&(at + i)), Some(&(copy, span.first + i)), "round {round}: range {span:?} piece {i}"); + wanted.push((copy, span.first + i)); + } + } + let n = hashed.len(); + hashed.sort_unstable(); + hashed.dedup(); + assert_eq!(hashed.len(), n, "round {round}: a piece hashed twice"); + wanted.sort_unstable(); + wanted.dedup(); + assert_eq!(hashed, wanted, "round {round}: the pieces hashed are those of the ranges compared"); + // Without: each range's own. + let (kept, passes) = planned(&ranges, cap, false); + let own: u32 = kept.iter().filter(|r| r.3).map(|r| r.1.pieces).sum(); + assert_eq!(passes.iter().map(|p| p.span.pieces).sum::(), own); + } + } + // Four views in one piece and one across into the next: 6 pieces + // hashed without, 2 with, in one pass. + let span = |from: u32, to: u32| CardSpan { from, to, first: from / PIECE, pieces: (to - 1) / PIECE - from / PIECE + 1, skew: 0 }; + let views = [span(0, 16), span(4096, 4352), span(8192, 8448), span(12288, 12544), span(60000, PIECE + 50)].map(|s| (7u64, s)); + let (kept, shared) = planned(&views, 64, true); + assert_eq!(kept.iter().map(|r| r.2).collect::>(), [0, 0, 0, 0, 0]); + assert_eq!(shared.iter().map(|p| (p.span.first, p.span.pieces, p.at)).collect::>(), [(0, 2, 0)]); + let (kept, apart) = planned(&views, 64, false); + assert_eq!(kept.iter().map(|r| r.2).collect::>(), [0, 1, 2, 3, 4]); + assert_eq!(apart.iter().map(|p| p.span.pieces).sum::(), 6); + assert_eq!(apart.len(), 5, "passes of one piece do not join"); +} diff --git a/d3d12/crates/leonida-gpu/src/host/comparecost.rs b/d3d12/crates/leonida-gpu/src/host/comparecost.rs new file mode 100644 index 0000000000..007881cd85 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/comparecost.rs @@ -0,0 +1,260 @@ +//! What the compare after a submission's lists ([`CARD_COMPARE`], the +//! check list of `Host::card_before`) costs the card: a measurement, not a +//! check. Every submission that declares shader writes over a copy in the +//! card's memory has every 64 KiB piece of every declared range hashed on +//! the drawing queue, whatever the shaders wrote; nothing had timed it. +//! +//! On the host's device (the card, or the software adapter with +//! `LEONIDA_D3D12_WARP=1`), with the runtime's own compare (its root +//! signature and pipeline from `Host::make_card_work`, its passes planned as +//! `Host::card_before` plans them: `compare_join_tests::planned`, then +//! [`card_pass`]) over a device-local copy of each size, between timestamps +//! on a direct queue of its own: +//! +//! - **one range**: the whole copy declared as one range (64 KiB to 256 +//! MiB), mode 2 as the relay's flights have it (hashed, compared, the hash +//! stored); "cold" after the card's caches were swept by a 192 MiB copy +//! (the RX 7900 XT has 6 MB of L2 and 80 MB of last-level cache), "again" +//! the same passes right after in the same list; +//! - **views**: the copy declared as views of 256 bytes every 16 KiB, four +//! in each piece, ranges that do not touch (how close the title's views +//! in the big heap copy lie was not counted), with +//! `LEONIDA_CARD_COMPARE_SHARE` off and on: the passes, the pieces hashed +//! and the time, cold. +//! +//! Medians of [`RUNS`] after one run to warm up. In a frame the compare +//! runs beside nothing (the check list follows the submission's lists behind +//! a barrier): the cold column is what it pays for bytes nothing touched +//! lately, and what the submission's own lists just read or wrote may still +//! be in the caches, between the two columns. +//! +//! `LEONIDA_BENCH_CS=` times another form of the compare instead (its +//! HLSL, with the same root signature, constants and a group per piece). +//! +//! Run by name, no game needed: +//! `cargo test -p leonida-gpu --release --lib host::comparecost -- --ignored --nocapture` + +use super::*; +use crate::shadow::CardSpan; + +/// Runs of each measurement after the one that warms up. +const RUNS: usize = 9; +const PIECE: u32 = 64 << 10; +/// What sweeps the card's caches before a cold run. +const SWEEP: u64 = 192 << 20; + +/// A device-local buffer shaders may write. +fn device_buffer(device: &ID3D12Device, size: u64) -> ID3D12Resource { + let mut made: Option = None; + // SAFETY: plain creation with a valid description. + unsafe { + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() +} + +/// A barrier for every unordered access before it. +fn uav_barrier() -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }), + }, + } +} + +/// The spans of a copy of `size` bytes declared as `views` ranges of `len` +/// bytes, `step` apart, from offset 0 (title memory on 64 KiB). +fn views(size: u32, len: u32, step: u32) -> Vec<(u64, CardSpan)> { + (0..size / step) + .map(|k| { + let (from, to) = (k * step, (k * step + len).min(size)); + (1, CardSpan { from, to, first: from / PIECE, pieces: (to - 1) / PIECE - from / PIECE + 1, skew: 0 }) + }) + .collect() +} + +/// Another form of the compare (`LEONIDA_BENCH_CS=`: its source, with +/// [`CARD_COMPARE`]'s root signature and constants), compiled. +fn other_compare(device: &ID3D12Device, source: &str) -> (ID3D12RootSignature, ID3D12PipelineState) { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option = None; + let mut errors: Option = None; + // SAFETY: the source and names live through the calls; the blobs' own + // bytes. + unsafe { + let made = D3DCompile( + source.as_ptr().cast(), + source.len(), + windows::core::s!("bench compare"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + Some(&mut errors), + ); + if let Some(e) = &errors { + eprintln!("{}", String::from_utf8_lossy(std::slice::from_raw_parts(e.GetBufferPointer().cast::(), e.GetBufferSize()))); + } + made.unwrap(); + let code = code.unwrap(); + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes).unwrap(); + let pso = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, + ..Default::default() + }) + .unwrap(); + (root, pso) + } +} + +fn median(mut v: Vec) -> f64 { + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +#[test] +#[ignore = "benchmark; see the module notes"] +fn bench_card_compare_cost() { + let Some(host) = super::host() else { + eprintln!("no host GPU"); + return; + }; + let device = &host.device; + let work = host.make_card_work().expect("the card compare must be made"); + let (root, pso) = match std::env::var("LEONIDA_BENCH_CS") { + Ok(file) => other_compare(device, &std::fs::read_to_string(file).expect("the other compare's source")), + Err(_) => (work.root.clone(), work.pso.clone()), + }; + // SAFETY: plain D3D12 object creation and use with valid descriptions; + // every object outlives the lists recorded with it, and each list is + // waited for before what it used is touched again. + unsafe { + let queue: ID3D12CommandQueue = + device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + list.Close().unwrap(); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + let ticks_per_ms = queue.GetTimestampFrequency().unwrap() as f64 / 1e3; + let stamps: ID3D12QueryHeap = { + let mut heap: Option = None; + device.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: 3, NodeMask: 0 }, &mut heap).unwrap(); + heap.unwrap() + }; + let back = host.read_back_buffer(64).expect("a read-back buffer"); + let mut back_ptr = std::ptr::null_mut(); + back.Map(0, None, Some(&mut back_ptr)).unwrap(); + let sweep = [device_buffer(device, SWEEP), device_buffer(device, SWEEP)]; + let mut submitted = 0u64; + // Records `passes` cold, then again, between three stamps; runs the + // list and waits: the milliseconds of each. + let mut timed = |now: &ID3D12Resource, hashes: &ID3D12Resource, size: u32, passes: &[ComparePass]| -> (f64, f64) { + allocator.Reset().unwrap(); + list.Reset(&allocator, None).unwrap(); + list.CopyBufferRegion(&sweep[1], 0, &sweep[0], 0, SWEEP); + list.ResourceBarrier(&[uav_barrier()]); + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + list.SetComputeRootShaderResourceView(1, now.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, hashes.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + for round in 1..3 { + for pass in passes { + card_pass(&list, &pass.span, size, pass.at, pass.mode); + } + list.ResourceBarrier(&[uav_barrier()]); + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, round); + } + list.ResolveQueryData(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 3, &back, 0); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + submitted += 1; + queue.Signal(&fence, submitted).unwrap(); + fence.SetEventOnCompletion(submitted, event).unwrap(); + WaitForSingleObject(event, INFINITE); + let t: [u64; 3] = std::ptr::read_volatile(back_ptr.cast::<[u64; 3]>()); + ((t[1] - t[0]) as f64 / ticks_per_ms, (t[2] - t[1]) as f64 / ticks_per_ms) + }; + let mut whole = Vec::new(); + let mut viewed = Vec::new(); + for size in [64u32 << 10, 1 << 20, 4 << 20, 16 << 20, 64 << 20, 256 << 20] { + let now = device_buffer(device, u64::from(size)); + let hashes = device_buffer(device, crate::shadow::card_hash_bytes(u64::from(size))); + let cap = (work.differs.2 / 4) as u32; + // The hashes from before, as the first compare of a copy stores them. + let (_, first) = compare_join_tests::planned(&views(size, size, size), cap, true); + let stored: Vec = first.iter().map(|p| ComparePass { mode: 0, ..*p }).collect(); + timed(&now, &hashes, size, &stored); + let mut run = |passes: &[ComparePass]| { + let (mut cold, mut again) = (Vec::new(), Vec::new()); + for i in 0..=RUNS { + let (c, a) = timed(&now, &hashes, size, passes); + if i > 0 { + cold.push(c); + again.push(a); + } + } + (median(cold), median(again)) + }; + let (_, one) = compare_join_tests::planned(&views(size, size, size), cap, true); + let (cold, again) = run(&one); + whole.push((size, cold, again)); + let spans = views(size, 256, 16 << 10); + for share in [false, true] { + let (_, passes) = compare_join_tests::planned(&spans, cap, share); + let pieces: u32 = passes.iter().map(|p| p.span.pieces).sum(); + let (cold, _) = run(&passes); + viewed.push((size, spans.len(), share, passes.len(), pieces, cold)); + } + } + let _ = windows::Win32::Foundation::CloseHandle(event); + let gbs = |bytes: u32, ms: f64| f64::from(bytes) / ms / 1e6; + println!("| Declared | Pieces | Cold, ms | GB/s | Again, ms | GB/s |"); + println!("|---|---|---|---|---|---|"); + for (size, cold, again) in whole { + println!( + "| {} KiB as one range | {} | {cold:.3} | {:.0} | {again:.3} | {:.0} |", + size >> 10, + size / PIECE, + gbs(size, cold), + gbs(size, again) + ); + } + println!(); + println!("| Copy | Views of 256 bytes every 16 KiB | LEONIDA_CARD_COMPARE_SHARE | Passes | Pieces hashed | Cold, ms |"); + println!("|---|---|---|---|---|---|"); + for (size, ranges, share, passes, pieces, cold) in viewed { + println!("| {} KiB | {ranges} | {} | {passes} | {pieces} | {cold:.3} |", size >> 10, u8::from(share)); + } + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/declared_by_copy_tests.rs b/d3d12/crates/leonida-gpu/src/host/declared_by_copy_tests.rs new file mode 100644 index 0000000000..d66c8a42ee --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/declared_by_copy_tests.rs @@ -0,0 +1,83 @@ +use super::{MERGE_STEPS, declared_by_copy}; + +type Declared = (usize, Vec<(usize, usize)>); + +/// The merge as `Host::settle` and `Host::relay_land` made it: a walk of +/// the copies so far for each, and with `once` of the copy's ranges so +/// far for each range of a copy seen before. +fn walked(declared: &[Declared], once: bool) -> Vec { + let mut back: Vec = Vec::new(); + for (copy, ranges) in declared { + match back.iter_mut().find(|(c, _)| c == copy) { + Some((_, all)) if once => { + for range in ranges { + if !all.contains(range) { + all.push(*range); + } + } + } + Some((_, all)) => all.extend_from_slice(ranges), + None => back.push((*copy, ranges.clone())), + } + } + back +} + +fn next(state: &mut u64) -> u64 { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + *state +} + +/// The same copies in the same order, each with the same ranges in the +/// same order: all of them, or each once (the walk kept a repeat within +/// the first list of a copy, which the copy-back takes the same way: it +/// joins the ranges, and a range done with twice is done with). +#[test] +fn the_merge_by_table_is_the_merge_by_walk() { + let mut state = 0x853c_49e6_748f_ea9bu64; + for _ in 0..300 { + let declared: Vec = (0..(next(&mut state) % 24)) + .map(|_| { + let copy = 0x1000 * (1 + next(&mut state) % 6) as usize; + let ranges = (0..next(&mut state) % 6) + .map(|_| { + let at = (next(&mut state) % 8) as usize * 0x100; + (at, at + 0x100 * (1 + next(&mut state) % 3) as usize) + }) + .collect(); + (copy, ranges) + }) + .collect(); + assert_eq!(declared_by_copy(&declared, |c| *c, false), walked(&declared, false)); + let once: Vec = walked(&declared, true) + .into_iter() + .map(|(copy, ranges)| { + let mut seen = std::collections::HashSet::new(); + (copy, ranges.into_iter().filter(|r| seen.insert(*r)).collect()) + }) + .collect(); + assert_eq!(declared_by_copy(&declared, |c| *c, true), once); + } +} + +/// Four flights that each declare one range of 2,000 copies, and one +/// copy declared with 4,000 ranges: one look for each copy declared and +/// each range, not a walk (the walk made 8,004,000). +#[test] +fn merging_many_copies_and_ranges_is_one_look_each() { + let mut declared: Vec = Vec::new(); + for flight in 0..4usize { + declared.extend((0..2000usize).map(|c| (0x10_0000 * (c + 1), vec![(flight * 0x100, flight * 0x100 + 0x80)]))); + } + declared.push((0x8000_0000, (0..4000usize).map(|r| (r * 0x100, r * 0x100 + 0x80)).collect())); + let ranges = declared.iter().map(|(_, r)| r.len() as u64).sum::(); + for once in [false, true] { + MERGE_STEPS.with(|s| s.set(0)); + let back = declared_by_copy(&declared, |c| *c, once); + let steps = MERGE_STEPS.with(std::cell::Cell::get); + assert_eq!(back.len(), 2001); + assert!(steps <= declared.len() as u64 + ranges, "{steps} looks for {} copies declared and {ranges} ranges", declared.len()); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/dynamic_wait_tests.rs b/d3d12/crates/leonida-gpu/src/host/dynamic_wait_tests.rs new file mode 100644 index 0000000000..c659d10d04 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/dynamic_wait_tests.rs @@ -0,0 +1,45 @@ +use super::take_after_landings; +use std::cell::Cell; + +/// A draw without slots asks again after each landing, and no more: it +/// stops with its slots, or when nothing was in the air at an asking +/// that found none (nothing can give slots back then). +#[test] +fn slots_are_asked_for_again_after_each_landing_while_something_flies() { + // There at once: nothing is waited for. + let (asked, waited) = (Cell::new(0), Cell::new(0)); + let take = || { + asked.set(asked.get() + 1); + Some(7) + }; + assert_eq!(take_after_landings(take, || true, || waited.set(waited.get() + 1)), Some(7)); + assert_eq!((asked.get(), waited.get()), (1, 0)); + + // Given back by the second landing. + let (asked, waited) = (Cell::new(0), Cell::new(0)); + let take = || { + asked.set(asked.get() + 1); + (waited.get() == 2).then_some(40) + }; + assert_eq!(take_after_landings(take, || true, || waited.set(waited.get() + 1)), Some(40)); + assert_eq!((asked.get(), waited.get()), (3, 2)); + + // Never: it stops at the asking that found the air empty, which is + // made after that look (a landing between the two is not missed). + let (asked, waited, looked) = (Cell::new(0), Cell::new(0), Cell::new(0)); + let take = || { + asked.set(asked.get() + 1); + None + }; + let in_air = || { + looked.set(looked.get() + 1); + assert_eq!(looked.get(), asked.get() + 1, "looked at before the asking"); + looked.get() < 3 + }; + assert_eq!(take_after_landings(take, in_air, || waited.set(waited.get() + 1)), None); + assert_eq!((asked.get(), waited.get(), looked.get()), (3, 2, 3)); + + // Nothing in the air, and the slots are there all the same (given + // back by the landing that emptied it): taken. + assert_eq!(take_after_landings(|| Some(1), || false, || panic!("nothing to wait for")), Some(1)); +} diff --git a/d3d12/crates/leonida-gpu/src/host/exact_fence_tests.rs b/d3d12/crates/leonida-gpu/src/host/exact_fence_tests.rs new file mode 100644 index 0000000000..d8b11fea4e --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/exact_fence_tests.rs @@ -0,0 +1,42 @@ +use super::{Flight, Late, Line, fence_landed}; +use crate::object::{S_OK, This, slot}; + +/// The title blocks on a fence signalled behind the first of two +/// flights: the wait is done once the signal has landed, the second +/// flight still in the air (everything before waited for that too). A +/// value the fence has not reached waits for everything, as before. +#[test] +fn a_blocking_fence_wait_ends_when_its_signal_has_landed() { + let mut fence: This = std::ptr::null(); + assert_eq!(crate::fence::create(std::ptr::null(), 0, 0, &crate::fence::FENCE_IIDS[0], &mut fence), S_OK); + let flight = |number| Flight { + number, + fence: number, + lists: Vec::new(), + order: Vec::new(), + card: None, + back: Vec::new(), + own: None, + texture_back_ranges: Vec::new(), + joined: Vec::new(), + }; + let mut line = Line::new(); + line.push_flight(flight(1), Vec::new()); + line.line.push(Late::Signal(fence as usize, 7)); + line.push_flight(flight(2), Vec::new()); + assert!(!fence_landed(&line, fence, 7)); + // The first flight and the signal behind it land (`Host::relay_land` + // sets the fence before the landing is done). + let landing = line.take_landable(2); + assert!(matches!(landing[1], Late::Signal(_, 7))); + crate::fence::set(fence, 7); + line.landed(Vec::new()); + assert!(fence_landed(&line, fence, 7), "reached with the second flight in the air"); + assert!(!fence_landed(&line, fence, 8), "a value not reached waits for everything"); + drop(line.take_landable(1)); + assert!(!fence_landed(&line, fence, 8), "being landed"); + line.landed(Vec::new()); + assert!(fence_landed(&line, fence, 8), "nothing in the air"); + drop(landing); + assert_eq!(slot:: u32>(fence, 0x10)(fence), 0); +} diff --git a/d3d12/crates/leonida-gpu/src/host/exact_wait_tests.rs b/d3d12/crates/leonida-gpu/src/host/exact_wait_tests.rs new file mode 100644 index 0000000000..b8def8a015 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/exact_wait_tests.rs @@ -0,0 +1,110 @@ +use super::{Flight, Late, Line, line_drained, value_landed}; +use crate::queue::Written; +use crate::shadow::Shadow; + +/// A flight of the test's: its shaders declare `back`, its read-backs +/// write `texture_back_ranges`. +fn flight(number: u64, back: Vec, texture_back_ranges: Vec<(usize, usize)>) -> Flight { + Flight { + number, + fence: number, + lists: Vec::new(), + order: Vec::new(), + card: None, + joined: super::flight_writes(&back, &texture_back_ranges), + back, + own: None, + texture_back_ranges, + } +} + +/// The flight that may write a waited value is landed while a later one, +/// which declares other memory, is still in the air: the value wait is +/// done (everything before waited for the later one too). Until the +/// first one's landing is done it is not, nor while a flight that does +/// declare the value (wholly or in part), a bottom-of-pipe write there +/// of any kind, a read-back into it or a fence signalled at it is in the +/// air or being landed. A later flight that declares other bytes of a +/// copy in the card's memory, in the same 64 KiB piece as the value, is +/// not waited for: its landing merges only inside what it declared. +#[test] +fn a_value_wait_ends_when_the_flights_that_may_write_it_have_landed() { + const A: usize = 0x5000_0000; + const B: usize = 0x6000_0000; + let mut side = vec![0u8; 0x2000]; + let copy_a = Shadow::unbacked(A as u64, side.as_mut_ptr(), 0x1000, false); + let copy_b = Shadow::unbacked(B as u64, side[0x1000..].as_mut_ptr(), 0x1000, false); + let value = A + 0x100; + + let mut line = Line::new(); + assert!(line_drained(&line) && value_landed(&line, value, 4), "nothing in the air"); + line.push_flight(flight(1, vec![(copy_a.clone(), vec![(A, A + 0x1000)])], Vec::new()), Vec::new()); + line.push_flight(flight(2, vec![(copy_b.clone(), vec![(B, B + 0x1000)])], Vec::new()), Vec::new()); + assert!(!value_landed(&line, value, 4), "the first flight may write it"); + // The first flight is being landed: still as in the air. + let items = line.take_landable(1); + assert!(!value_landed(&line, value, 4), "being landed"); + line.landed(Vec::new()); + drop(items); + assert!(!line_drained(&line), "the second flight is in the air: the settle before still waited"); + assert!(value_landed(&line, value, 4), "no flight in the air may write it"); + assert!(value_landed(&line, 0x7000_0000, 8), "no flight may write there"); + assert!(!value_landed(&line, B + 0xffc, 8), "the second flight may write it"); + assert!(!value_landed(&line, B - 4, 8), "a value half under the second flight's write"); + + // Behind the second flight: a timestamp at the value (not a value + // that `late_met_known` can say meets the wait). + let mut line = Line::new(); + line.push_flight(flight(1, vec![(copy_a.clone(), vec![(A, A + 0x1000)])], Vec::new()), Vec::new()); + line.push_flight(flight(2, vec![(copy_b.clone(), vec![(B, B + 0x1000)])], Vec::new()), vec![(value, Written::GpuTimestamp, 8)]); + drop(line.take_landable(1)); + assert!(!value_landed(&line, value, 4), "the first flight is being landed"); + line.landed(Vec::new()); + assert!(!value_landed(&line, value, 4), "a bottom-of-pipe write in the air"); + drop(line.take_landable(2)); + assert!(!value_landed(&line, value, 4), "a bottom-of-pipe write being landed"); + line.landed(Vec::new()); + assert!(value_landed(&line, value, 4)); + + // A read-back into it; a fence whose value lies there. + let mut line = Line::new(); + line.push_flight(flight(1, Vec::new(), vec![(value, value + 4)]), Vec::new()); + assert!(!value_landed(&line, value, 4), "a read-back in the air"); + let mut line = Line::new(); + line.push_flight(flight(1, Vec::new(), Vec::new()), Vec::new()); + let fence = 0x9000_0000usize; + line.line.push(Late::Signal(fence, 3)); + let at = crate::fence::value_at(fence); + assert!(!value_landed(&line, at, 8), "a fence signalled at the value"); + assert!(value_landed(&line, at + 8, 8)); + + // A later flight declares other bytes of a copy in the card's memory + // that holds the value, in the same piece: its landing merges only + // inside its declared span (`Shadow::card_piece` cuts each piece to + // it), so the value is not its to write. + let mut card_side = vec![0u8; 0x20000]; + let carded = Shadow::unbacked(A as u64, card_side.as_mut_ptr(), 0x20000, true); + let mut line = Line::new(); + line.push_flight(flight(1, vec![(copy_a.clone(), vec![(A, A + 0x1000)])], Vec::new()), Vec::new()); + line.push_flight(flight(2, vec![(carded.clone(), vec![(A + 0x8000, A + 0x9000)])], Vec::new()), Vec::new()); + drop(line.take_landable(1)); + line.landed(Vec::new()); + assert!(value_landed(&line, value, 4), "beside what a copy in the card's memory declares, in its piece"); + assert!(!value_landed(&line, A + 0x8ffc, 8), "half under what it declares"); + drop(line.take_landable(1)); + assert!(value_landed(&line, value, 4), "beside what the flight being landed declares"); + assert!(!value_landed(&line, A + 0x8800, 4), "under what the flight being landed declares"); + line.landed(Vec::new()); + assert!(value_landed(&line, A + 0x8800, 4)); + + // A wide declaration (the title's heap as a whole) by a later flight. + let mut line = Line::new(); + line.push_flight(flight(1, vec![(copy_a.clone(), vec![(A, A + 0x1000)])], Vec::new()), Vec::new()); + line.push_flight(flight(2, vec![(copy_b.clone(), vec![(A - 0x1000, B + 0x1000)])], Vec::new()), Vec::new()); + drop(line.take_landable(1)); + line.landed(Vec::new()); + assert!(!value_landed(&line, value, 4), "the second flight declares it too"); + drop(line.take_landable(1)); + line.landed(Vec::new()); + assert!(line_drained(&line) && value_landed(&line, value, 4)); +} diff --git a/d3d12/crates/leonida-gpu/src/host/fetched.rs b/d3d12/crates/leonida-gpu/src/host/fetched.rs new file mode 100644 index 0000000000..324a577091 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/fetched.rs @@ -0,0 +1,282 @@ +//! How large the buffers are that pieces of copies in the card's memory are +//! fetched to: [`Host::card_back`]'s (`CardWork::fetched`) and the relay's +//! (`RelayFetch::buffer`). Both are shared buffers (the PC's memory, mapped +//! write-back, committed), one each for the run. +//! +//! Each was made anew only when a fetch did not fit, to that fetch rounded +//! up to 16 MiB, and never made smaller: one large fetch (the first compare +//! of a new copy, a range not compared that comes down whole, or the pieces +//! `torn::Check` fetches whole) left a buffer of its size committed for the +//! rest of the run. A frame's fetches were measured at 94 MB in 7 +//! ([`relay_copy`](super::relay_copy)'s notes); the largest single fetch of +//! a run is not recorded. +//! +//! [`fetch_size`] still grows a buffer at once, as before; with +//! [`shrink`] it also makes a smaller one once the last [`SEEN`] fetches, +//! and those of the idle time of the PC's memory +//! ([`crate::host::ram_idle_ms`], 2 s to 5 min), all needed at most a +//! quarter ([`OVER`]) of it: twice the largest of them ([`ROOM`]), in whole +//! 16 MiB, at least 16 MiB. One large fetch among them keeps the buffer as +//! it is, so sizes that come and go do not make a buffer each time. By +//! count alone a large fetch every [`SEEN`] fetches made the buffer smaller +//! and larger again each time, and [`SEEN`] fetches are under a second in +//! [`Host::card_back`] (one a plan, many a frame) or in menus. The frame +//! line counts the buffers made smaller and those made larger again +//! ([`STATS`]). + +use super::*; + +/// Whether the buffers pieces are fetched to are made smaller once the +/// fetches have been much smaller for a while (`LEONIDA_FETCH_SHRINK`, on by +/// default; `0`: they only grow, as before; `LEONIDA_AB` can name it). A +/// buffer made anew is a committed resource and a wait until it is resident, +/// on the thread that lands flights. +pub(super) fn shrink() -> bool { + crate::toggled!("LEONIDA_FETCH_SHRINK") +} + +/// Buffers are made in whole multiples of this, and none is smaller. +const STEP: u64 = 16 << 20; +/// How many of the last fetches decide whether a buffer is made smaller: +/// some 18 frames of the relay's 7 (a few seconds at the frame rates of the +/// world, `docs/README-fxceless.md`). +const SEEN: usize = 128; +/// A buffer is made smaller once the largest of the last [`SEEN`] fetches +/// needed at most this fraction of it. +const OVER: u64 = 4; +/// ... to this many times the largest of them. +const ROOM: u64 = 2; + +/// Since the last frame line: buffers made smaller, and buffers made larger +/// after the last one made of them was smaller. +pub(super) static STATS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The sizes of the last [`SEEN`] fetches into one buffer, and when the +/// last that needed more than an [`OVER`]th of it was. +pub(super) struct Sizes { + totals: [u64; SEEN], + seen: usize, + /// [`crate::host::coarse_ms`] of the last fetch that needed more than + /// an [`OVER`]th of the buffer it went to. + large_at: u64, + /// Whether the last buffer made was smaller than the one before. + shrunk: bool, +} + +impl Default for Sizes { + fn default() -> Self { + Sizes { + totals: [0; SEEN], + seen: 0, + large_at: 0, + shrunk: false, + } + } +} + +impl Sizes { + /// A buffer was made, `smaller` than the one before or not: which of + /// [`STATS`] counts it, if any (the first, and one larger after one + /// larger, are not counted). + fn made(&mut self, smaller: bool) -> Option { + let counted = if smaller { Some(0) } else { self.shrunk.then_some(1) }; + self.shrunk = smaller; + counted + } + + /// A smaller buffer could not be made at `now`: the next try waits + /// [`SEEN`] fetches and the idle time again. Without it every fetch + /// after tried again, each with a warning and an allocation error, on + /// the landing thread, while memory was short. + fn not_made(&mut self, now: u64) { + self.seen = 0; + self.large_at = now; + } +} + +/// The size of the buffer to make for a fetch of `total` bytes at `now` +/// ([`crate::host::coarse_ms`]), noted in `sizes`, into one of `current` +/// bytes (`None`: there is none); `None`: the current one serves. A buffer +/// is made to fit a fetch that does not fit, at once; with `shrink`, a +/// smaller one once the last [`SEEN`] fetches, this one among them, and +/// those of the last `idle_ms` (asked only then), all needed at most an +/// [`OVER`]th of it. +pub(super) fn fetch_size( + current: Option, + total: u64, + now: u64, + sizes: &mut Sizes, + shrink: bool, + idle_ms: impl FnOnce() -> u64, +) -> Option { + sizes.totals[sizes.seen % SEEN] = total; + sizes.seen += 1; + let fit = |bytes: u64| bytes.max(1).next_multiple_of(STEP); + if current.is_none_or(|c| total.saturating_mul(OVER) > c) { + sizes.large_at = now; + } + let Some(current) = current.filter(|&c| c >= total) else { + return Some(fit(total)); + }; + if !shrink || sizes.seen < SEEN || now.saturating_sub(sizes.large_at) < idle_ms() { + return None; + } + let largest = sizes.totals.iter().copied().max().unwrap_or(0); + let smaller = fit(largest.saturating_mul(ROOM)); + (largest.saturating_mul(OVER) <= current && smaller < current).then_some(smaller) +} + +/// Makes `buffer` (buffer, mapping, bytes) fit a fetch of `total` bytes, as +/// [`fetch_size`] says; it is left as it was if a smaller one cannot be +/// made ([`Sizes::not_made`]). The fetch into it before has been waited for, so a buffer made +/// smaller goes through [`retire_resource`] and is not read again. +pub(super) fn fit(host: &Host, buffer: &mut Option<(ID3D12Resource, usize, u64)>, total: u64, sizes: &mut Sizes) { + let current = buffer.as_ref().map(|b| b.2); + let now = crate::host::coarse_ms(); + let idle_ms = || crate::host::ram_idle_ms(crate::host::available_physical_ram()); + let Some(size) = fetch_size(current, total, now, sizes, shrink(), idle_ms) else { + return; + }; + let made = host.shared_buffer(size).map(|(made, data)| (made, data as usize, size)); + let smaller = current.is_some_and(|c| c >= total); + if made.is_some() + && let Some(counted) = sizes.made(smaller) + { + STATS[counted].fetch_add(1, Ordering::Relaxed); + } + if smaller { + // Smaller: the one in use stays if none was made, and the next try + // waits. + match made { + Some(made) => { + if let Some((old, ..)) = buffer.replace(made) { + retire_resource(old); + } + } + None => sizes.not_made(now), + } + return; + } + // (Larger: the old one is let go as before; `None` if none was made.) + *buffer = made; +} + +#[cfg(test)] +mod tests { + use super::{SEEN, Sizes, fetch_size}; + + const MIB: u64 = 1 << 20; + /// The idle time of the PC's memory with little of it free. + const IDLE_MS: u64 = 2_000; + + /// What [`run`] saw. + #[derive(Debug, PartialEq)] + struct Ran { + /// The buffer's size after the fetches. + size: u64, + /// Buffers made, in all. + made: usize, + /// Of them, made smaller, and made larger after one made smaller. + shrunk: usize, + again: usize, + } + + /// Runs the fetches `totals`, `apart_ms` apart, through [`fetch_size`] + /// from no buffer, as [`super::fit`] does. + fn run(totals: impl IntoIterator, apart_ms: u64, shrink: bool) -> Ran { + let (mut sizes, mut current) = (Sizes::default(), None); + let mut ran = Ran { size: 0, made: 0, shrunk: 0, again: 0 }; + for (i, total) in totals.into_iter().enumerate() { + let now = i as u64 * apart_ms; + if let Some(size) = fetch_size(current, total, now, &mut sizes, shrink, || IDLE_MS) { + assert!(size >= total, "a buffer of {size} made for a fetch of {total}"); + match sizes.made(current.is_some_and(|c| c >= total)) { + Some(0) => ran.shrunk += 1, + Some(_) => ran.again += 1, + None => {} + } + current = Some(size); + ran.made += 1; + } + assert!(current.is_some_and(|c| c >= total), "a fetch of {total} into {current:?}"); + } + ran.size = current.unwrap_or(0); + ran + } + + /// One fetch of 512 MiB and then 200 of 1 MiB: the buffer comes back to + /// 16 MiB. It only grew, and 512 MiB of the PC's memory stayed committed + /// for the rest of the run. + #[test] + fn a_large_fetch_leaves_no_large_buffer_behind() { + let totals = || std::iter::once(512 * MIB).chain(std::iter::repeat_n(MIB, 200)); + let ran = run(totals(), 100, true); + assert!(ran.size <= 32 * MIB, "{} MiB kept after 200 fetches of 1 MiB", ran.size / MIB); + assert_eq!((ran.made, ran.shrunk, ran.again), (2, 1, 0)); + // Before: it only grew. + assert_eq!(run(totals(), 100, false).size, 512 * MIB); + } + + /// Fetches that grow get a buffer that fits each, at once. + #[test] + fn growing_fetches_always_fit() { + let ran = run((1..=300).map(|i| i * 3 * MIB), 10, true); + assert_eq!(ran.size, (900 * MIB).next_multiple_of(16 * MIB)); + assert_eq!((ran.shrunk, ran.again), (0, 0)); + } + + /// A large fetch every 50 fetches keeps the buffer as it is: no buffer + /// made smaller and larger again and again. + #[test] + fn a_large_fetch_now_and_then_keeps_the_buffer() { + let totals = (0..2_000).map(|i| if i % 50 == 0 { 100 * MIB } else { 2 * MIB }); + assert_eq!(run(totals, 100, true), Ran { size: 112 * MIB, made: 1, shrunk: 0, again: 0 }); + // Once they stop, the buffer comes down after `SEEN` small ones. + let totals = (0..1_000).map(|i| if i < 500 && i % 50 == 0 { 100 * MIB } else { 2 * MIB }); + assert_eq!(run(totals, 100, true), Ran { size: 16 * MIB, made: 2, shrunk: 1, again: 0 }); + } + + /// A large fetch every 200 fetches, 5 ms apart (one a second, as in + /// [`super::Host::card_back`] with many plans a frame), keeps the + /// buffer: by count alone it was made smaller and larger again each + /// time, a committed buffer of 112 MiB made anew every second. + #[test] + fn a_large_fetch_every_second_keeps_the_buffer() { + let totals = (0..4_000).map(|i| if i % 200 == 0 { 100 * MIB } else { 2 * MIB }); + let ran = run(totals, 5, true); + assert_eq!(ran, Ran { size: 112 * MIB, made: 1, shrunk: 0, again: 0 }, "made smaller and larger again"); + // Once they stop, it comes down after the idle time. + let totals = (0..4_000).map(|i| if i < 2_000 && i % 200 == 0 { 100 * MIB } else { 2 * MIB }); + let (mut sizes, mut current, mut down) = (Sizes::default(), None, None); + for (i, total) in totals.enumerate() { + if let Some(size) = fetch_size(current, total, i as u64 * 5, &mut sizes, true, || IDLE_MS) { + if current.is_some() { + down = Some(i); + } + current = Some(size); + } + } + let last_large = 1_800; + assert_eq!(down, Some(last_large + IDLE_MS as usize / 5), "made smaller at fetch {down:?}"); + assert!(down.unwrap() - last_large >= SEEN); + assert_eq!(current, Some(16 * MIB)); + } + + /// A smaller buffer that cannot be made is tried again only after + /// [`SEEN`] more fetches: each fetch after the first failure tried + /// again, with a warning and an allocation error each. + #[test] + fn a_smaller_buffer_not_made_is_not_tried_at_each_fetch() { + let mut sizes = Sizes::default(); + let current = fetch_size(None, 512 * MIB, 0, &mut sizes, true, || IDLE_MS); + let mut tries = 0; + for i in 1..1_000u64 { + if fetch_size(current, MIB, i * 100, &mut sizes, true, || IDLE_MS).is_some() { + // None was made, as `fit` notes. + tries += 1; + sizes.not_made(i * 100); + } + } + assert_eq!(tries, 999 / SEEN, "{tries} tries in 999 fetches"); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/front_tests.rs b/d3d12/crates/leonida-gpu/src/host/front_tests.rs new file mode 100644 index 0000000000..fa2a0a3e46 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/front_tests.rs @@ -0,0 +1,50 @@ +use super::{ListFront, Touch, fold_touches, front_spans, join_keys, joined_keys}; + +/// Random submissions of lists (refreshes and shaders' writes of a few +/// copies, new parts now and then): each list folded on its own and the +/// folds joined in order give what the whole submission's touches give, +/// span for span, in the same order (renderer port #6's planning). +#[test] +fn lists_folded_apart_and_joined_give_the_submissions_spans() { + let mut seed = 0x9e37_79b9_u64; + let mut next = |n: usize| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as usize % n + }; + for _ in 0..3000 { + let lists = 1 + next(8); + let copies = 1 + next(6); + let mut parts = Vec::new(); + let mut whole: Vec = Vec::new(); + let mut folds = Vec::new(); + for n in 0..lists { + if n > 0 && next(4) == 0 { + parts.push(n); + whole.push(Touch::Part); + } + let mut mine: Vec = Vec::new(); + for _ in 0..next(12) { + let key = 0x1000 * (1 + next(copies)); + if next(5) == 0 { + mine.push(Touch::Write(key)); + whole.push(Touch::Write(key)); + } else { + // (Refreshes of no bytes too: `Shadow::refresh` clamps + // a range to the copy's end.) + let from = next(100); + let to = from + next(51); + mine.push(Touch::Refresh(key, from, to)); + whole.push(Touch::Refresh(key, from, to)); + } + } + folds.push(fold_touches(mine.into_iter())); + } + let want = front_spans(whole.into_iter()); + let got = join_keys(folds.iter().map(|f| f.as_slice()), &parts); + assert_eq!(got, want, "parts {parts:?}"); + // And as the lists' kept parts are joined (`joined_keys`): one + // list's part as it is, more joined. + let fronts: Vec = folds.iter().map(|f| ListFront { copies: f.clone(), ..ListFront::default() }).collect(); + assert_eq!(joined_keys(&fronts, &parts), want, "lists {lists}, parts {parts:?}"); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/gate_tests.rs b/d3d12/crates/leonida-gpu/src/host/gate_tests.rs new file mode 100644 index 0000000000..30f51d6dd4 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/gate_tests.rs @@ -0,0 +1,56 @@ +use super::*; + +/// Leonida: a list behind the gate in the card's queue (`Host::execute_gated`, +/// `HostList::wait_gate`) runs only after what the gate's thread was given has been done, +/// however long that takes: the work writes a word into upload memory 30 ms after it is given +/// (the card has long reached the gate by then), and the list behind the gate copies the word +/// out. Without the gate the copy reads the 0 that was there before: `TEST_NO_GATE=1` leaves the +/// list's wait out, and the test fails (as it did on an RTX 4060 Ti, 2026-11-29). +#[test] +#[ignore = "wants LEONIDA_LATE_WAIT=3 and a process of its own"] +fn a_list_behind_the_gate_reads_what_was_done_before_it_opened() { + let Some(host) = host() else { + return; + }; + assert!(late(), "set LEONIDA_LATE_WAIT=3"); + let (slow_from, slow_to) = (host.uav_buffer(64 << 20).unwrap(), host.uav_buffer(64 << 20).unwrap()); + for round in 1..=4u32 { + let (upload, data) = host.upload_buffer(4096).unwrap(); + let (out, read) = host.shared_buffer(4096).unwrap(); + // SAFETY: inside the mappings. + unsafe { + data.cast::().write_volatile(0); + read.cast::().write_volatile(1); + } + // A list of ours that keeps the card busy a little, as the bake's uploads do. + let a = host.new_list().unwrap(); + // SAFETY: an open list; live buffers. + unsafe { + for _ in 0..4 { + a.list.CopyBufferRegion(&slow_to, 0, &slow_from, 0, 64 << 20); + } + } + a.close(); + let at = data as usize; + let then = Box::new(move || { + std::thread::sleep(std::time::Duration::from_millis(30)); + // SAFETY: the upload memory lives until the round's end, after the settle below. + unsafe { (at as *mut u32).write_volatile(0xC0DE_0000 | round) }; + }); + let (number, value) = host.execute_gated(Some(&a), then); + assert!(number > 0 && value > 0, "sent ahead with a gate, round {round}"); + // The list that needs it: the word copied out, behind the gate. + let b = host.new_list().unwrap(); + b.wait_gate(if std::env::var_os("TEST_NO_GATE").is_some() { 0 } else { value }); + // SAFETY: an open list; live buffers. + unsafe { b.list.CopyBufferRegion(&out, 0, &upload, 0, 4) }; + b.close(); + let last = host.execute_own(&b); + settle_now(WHY_SYNC); + assert!(FINISHED.load(Ordering::Acquire) >= last); + // SAFETY: the mapping, written by the list, which has landed. + let got = unsafe { read.cast::().read_volatile() }; + assert_eq!(got, 0xC0DE_0000 | round, "the word the gate's work wrote, round {round}"); + drop((a, b, upload, out)); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/landsame.rs b/d3d12/crates/leonida-gpu/src/host/landsame.rs new file mode 100644 index 0000000000..10265a4c29 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/landsame.rs @@ -0,0 +1,1873 @@ +//! What shaders wrote to copies in the card's memory, brought down by the +//! submission that wrote it (`LEONIDA_LAND_IN_SUBMISSION=1`; off by default). +//! +//! With the relay ([`relay`]) the compare after a submission's lists flags +//! the 64 KiB pieces that changed, and the thread that lands flights then +//! fetched the flagged pieces with a list of its own and waited for it +//! (`Host::relay_card_back`). On the drawing queue that list runs behind +//! whatever was sent meanwhile: the thread stood 48 ms of a 120 ms frame +//! waiting for seven fetches of 94 MB ([`relay_copy`]'s notes), and +//! everything that waits for a landing waited with it. +//! +//! Here two passes of ours follow the compare in the same list +//! ([`SOURCE`]): one group numbers the flagged pieces of the ranges the +//! plan lands, in order (a prefix sum over the compare's flags: the n-th +//! flagged piece gets slot n, if the plan's [`Landing`] has that many), and +//! a group per piece copies each piece that got a slot into it, whole as +//! the compare hashes it. The landing is a shared buffer (the PC's memory, +//! mapped write-back, as the compare's results are): when the flight's +//! fence is reached its pieces are there. No second submission, no wait +//! beyond the flight's own, and no fetch that runs behind later flights. +//! +//! What still comes down with a fetch as before, after the captured pieces +//! are merged (the fetch is newer than any of them): pieces past the +//! landing's slots, ranges not compared, pieces only a torn check wants +//! (`torn::Suspects`), and pieces an earlier fetch may have brought newer +//! than the flight's own capture (`land::Had::touches`; merged after that +//! fetch, the capture would put a later flight's bytes back to older ones). +//! A piece held whole by an earlier fetch that ran after the flight is +//! neither merged nor fetched: that fetch's merge had it ([`fate`]). +//! +//! What a capture is merged as: the bytes the card held right after the +//! flight's lists, which ran behind the sends to card copies up to the +//! plan's own (`CardPlan::sent_as`) and ahead of every later one, on the +//! one queue. So it is merged as a fetch known to have run behind exactly +//! those sends (`Shadow::card_merge_relay`, `land_card`): the title's bytes +//! that went up later, or have still to go, are left out, and title CPU +//! writes in between stay the title's, as with a fetch on the copy queue. +//! Several flights landed together are merged in their order, each from its +//! own capture; the notes of sends are then let go only up to the last of +//! those flights' sends, since a later flight's capture is merged against +//! the sends after its own (`relay_fetched`). +//! +//! Not with the relay off (`Host::card_back`): there the settled plans' +//! pieces are merged against the CPU side as the one reference +//! (`Shadow::card_merge`), which leaves no title byte out; a second, older +//! capture merged after a first would take the title's bytes merged by the +//! first for shader writes. That path keeps its fetch. +//! +//! Not into title memory straight from the card, though a copy's title +//! memory could be opened in place (`crate::inplace`): the merge is by byte +//! against the CPU side, leaves out the title's bytes not yet on the card, +//! and notes every block it writes for the write watch and the guards +//! (`crate::land`). A store from the card would be a dword at least, over +//! title bytes the CPU writes meanwhile, with nothing noted. Copies in the +//! card's memory are big title buffers, which in place leaves alone +//! anyway (`LEONIDA_INPLACE=2` skips them). +//! +//! What it costs: every flight's flagged pieces cross the bus, where one +//! fetch for the flights landed together brought a piece flagged by several +//! of them once; and a landing buffer per plan in the air, at most [`most`] +//! bytes in all (a plan that finds no room has its pieces fetched as +//! before). Its passes run on the drawing queue as the fetch did; the copy +//! goes over the bus as the fetch's did (23-28 GB/s on the RX 7900 XT, +//! `docs/findings.md`). +//! +//! The switch is read once per plan, when `Host::card_before` makes it +//! ([`Capturing`], kept in the plan): with `LEONIDA_AB` naming it the switch +//! flips while flights are in the air, and a plan made with it on still has +//! its passes in its list when it lands, one made with it off has none. What +//! a plan does at its landing is its own: its pieces merged from its landing +//! if it has one, fetched if not. What the landing does for later plans is +//! by those plans, not by the switch then: the notes of sends a later +//! capture is merged against, and the fetches noted as maybe newer than a +//! later capture (`RelayFetch::newer`), are kept while any plan made to +//! capture is alive ([`capturing`]). A plan's decision is counted before its +//! send's number can be seen by a fetch (under the order of the queue), so a +//! fetch whose send count is past a capturing plan's send finds it counted, +//! unless it landed already and needs neither. + +use super::*; + +/// Whether plans made now capture their flights' flagged pieces in their own +/// submission (`LEONIDA_LAND_IN_SUBMISSION=1`; off by default). Read once per +/// plan ([`Capturing`]); with `LEONIDA_AB` naming it (diagnostics builds) it +/// flips per phase, and plans in the air keep what they were made with. +pub(super) fn on() -> bool { + #[cfg(test)] + if let Some(on) = TEST_ON.get() { + return on; + } + crate::asked!("LEONIDA_LAND_IN_SUBMISSION") +} + +/// Plans alive that were made to capture ([`Capturing`]). +static CAPTURING: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A plan's decision to capture its flagged pieces, made when the plan is +/// (`Host::card_before`, under the order of the queue, right after its send +/// is numbered): counted in [`CAPTURING`] until the plan is done with. +pub(super) struct Capturing(()); + +impl Capturing { + /// The decision for a plan made now: `None` (fetched as before) unless + /// it is `flown` with the relay and the switch is on. + pub(super) fn decide(flown: bool) -> Option { + (flown && on()).then(|| { + CAPTURING.fetch_add(1, Ordering::SeqCst); + Capturing(()) + }) + } +} + +impl Drop for Capturing { + fn drop(&mut self) { + CAPTURING.fetch_sub(1, Ordering::SeqCst); + } +} + +/// Whether any plan alive was made to capture: what a landing keeps for +/// later captures (the notes of sends, [`forgotten`]; fetches noted as maybe +/// newer, [`fate`]) is kept then, whatever the switch says now. Read after +/// the send count the landing goes by. +pub(super) fn capturing() -> bool { + CAPTURING.load(Ordering::SeqCst) > 0 +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`on`], for its thread only. + pub(super) static TEST_ON: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// A test's most slots for a plan, for its thread only. + pub(super) static TEST_SLOTS: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// A test's [`line_target`], for its thread only (its flights are not + /// in the line). + pub(super) static TEST_AHEAD: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// The most bytes of landing buffers alive, in plans and kept +/// (`LEONIDA_LAND_IN_SUBMISSION_MB`, 256). +pub(super) fn most() -> u64 { + static MOST: OnceLock = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("LEONIDA_LAND_IN_SUBMISSION_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(256).max(1) << 20 + }) +} + +/// A piece of a copy, as the compare cuts them. +pub(super) const PIECE: u64 = 64 << 10; +/// A slot: a piece as the compare hashes it, widened to 16 bytes at both +/// ends (`Shadow::card_hashed`): at most 16 bytes more than a piece. +pub(super) const SLOT: u64 = PIECE + 16; +/// The header's bytes: eight dwords ([`Layout::header`]). +const HEADER: u64 = 32; +/// The fewest slots a plan is given, and the step they grow in. +const FEWEST: u32 = 16; +/// How many of the last plans landed decide how many slots the next gets. +const SEEN: usize = 64; +/// Landing buffers kept for the next plans, at most (bytes). +const SPARE_MOST: u64 = 64 << 20; + +/// The passes of ours after the compare, with its root signature: `scan` +/// numbers the flagged pieces (one group), `copy` copies them (a group per +/// piece, as the compare's passes). The landing's header, as +/// [`Layout::header`] writes it: listed dwords, slots, flagged (the scan's +/// count, past the slots too), the first listed dword, and where the list, +/// the slot of each listed dword, the table (the dword of each slot) and the +/// slots are. +pub(super) const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)" +cbuffer Span : register(b0) { + uint first; // as the compare's + uint skew; + uint size; + uint pieces; + uint out_at; // the first piece's flag in `differs`, in bytes + uint unused; +}; +ByteAddressBuffer now : register(t0); +RWByteAddressBuffer landing : register(u0); +RWByteAddressBuffer differs : register(u1); +groupshared uint sums[1024]; + +[RootSignature(RS)] +[numthreads(1024, 1, 1)] +void scan(uint t : SV_GroupIndex) { + uint listed = landing.Load(0u); + uint slots = landing.Load(4u); + uint base = landing.Load(12u); + uint list = landing.Load(16u); + uint slot_of = landing.Load(20u); + uint table = landing.Load(24u); + uint per = (listed + 1023u) / 1024u; + uint from = min(t * per, listed); + uint to = min(from + per, listed); + uint count = 0u; + [loop] + for (uint i = from; i < to; ++i) { + count += differs.Load(landing.Load(list + i * 4u) * 4u) & 1u; + } + sums[t] = count; + GroupMemoryBarrierWithGroupSync(); + [unroll] + for (uint step = 1u; step < 1024u; step <<= 1u) { + uint add = t >= step ? sums[t - step] : 0u; + GroupMemoryBarrierWithGroupSync(); + sums[t] += add; + GroupMemoryBarrierWithGroupSync(); + } + uint slot = sums[t] - count; + if (t == 1023u) landing.Store(8u, sums[1023]); + [loop] + for (uint j = from; j < to; ++j) { + uint d = landing.Load(list + j * 4u); + uint s = 0xFFFFFFFFu; + if ((differs.Load(d * 4u) & 1u) != 0u) { + if (slot < slots) { + s = slot; + landing.Store(table + slot * 4u, d); + } + slot += 1u; + } + landing.Store(slot_of + (d - base) * 4u, s); + } +} + +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void copy(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) { + uint slots = landing.Load(4u); + uint base = landing.Load(12u); + uint s = landing.Load(landing.Load(20u) + (out_at / 4u + id.x - base) * 4u); + if (s >= slots) return; + uint piece = first + id.x; + uint lo = piece * 65536u; + lo = lo > skew ? lo - skew : 0u; + uint hi = min((piece + 1u) * 65536u - skew, size); + lo = lo & ~15u; + hi = (hi + 15u) & ~15u; + uint to = landing.Load(28u) + s * 65552u; + [loop] + for (uint at = lo + thread * 16u; at < hi; at += 1024u) { + landing.Store4(to + (at - lo), now.Load4(at)); + } +} +"#; + +/// Where things are in a landing buffer: the header, the dwords of the +/// compare's results the scan looks at (`listed`, in order), the slot of +/// each dword from the first listed to the last (`span` of them; `!0` for +/// none), the dword of each slot, and the slots, from a multiple of 256 on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Layout { + pub(super) listed: u32, + pub(super) span: u32, + pub(super) slots: u32, +} + +impl Layout { + pub(super) fn list_at(&self) -> u64 { + HEADER + } + + pub(super) fn slot_of_at(&self) -> u64 { + self.list_at() + 4 * u64::from(self.listed) + } + + pub(super) fn table_at(&self) -> u64 { + self.slot_of_at() + 4 * u64::from(self.span) + } + + pub(super) fn data_at(&self) -> u64 { + (self.table_at() + 4 * u64::from(self.slots)).next_multiple_of(256) + } + + /// Where slot `k` begins. + pub(super) fn slot_at(&self, k: u32) -> u64 { + self.data_at() + u64::from(k) * SLOT + } + + pub(super) fn bytes(&self) -> u64 { + self.slot_at(self.slots) + } + + /// The header's dwords, the first listed dword being `base`; the third + /// is the scan's. + pub(super) fn header(&self, base: u32) -> [u32; 8] { + let at = |b: u64| u32::try_from(b).unwrap_or(u32::MAX); + [self.listed, self.slots, 0, base, at(self.list_at()), at(self.slot_of_at()), at(self.table_at()), at(self.data_at())] + } + + /// The most slots a buffer of `bytes` holds with this list and span. + pub(super) fn slots_in(&self, bytes: u64) -> u32 { + let meta = Layout { slots: 0, ..*self }.data_at(); + let mut k = (bytes.saturating_sub(meta) / SLOT).min(u64::from(u32::MAX)) as u32; + // (A table dword each: a slot or two fewer at most.) + while k > 0 && (Layout { slots: k, ..*self }).bytes() > bytes { + k -= 1; + } + k + } +} + +/// The slots a plan of `listed` pieces to look at gets, the most any of the +/// last [`SEEN`] plans had flagged being `recent`: half again as many, in +/// steps of [`FEWEST`], at least that, never more than it has pieces. +pub(super) fn slots(listed: u32, recent: u32) -> u32 { + let guess = (u64::from(recent) * 3 / 2).max(u64::from(FEWEST)).next_multiple_of(u64::from(FEWEST)); + listed.min(guess.min(u64::from(u32::MAX)) as u32) +} + +/// The dwords of the compare's results a plan's pieces are flagged at, in +/// order (`runs`: a pass's first flag and its pieces), and the first and the +/// last + 1 of them. +pub(super) fn listed(runs: impl Iterator) -> (Vec, u32, u32) { + let list: Vec = runs.flat_map(|(at, pieces)| at..at + pieces).collect(); + let base = list.iter().copied().min().unwrap_or(0); + let end = list.iter().copied().max().map_or(0, |d| d + 1); + (list, base, end) +} + +/// What the scan left in a landing: how many pieces it found flagged (past +/// the slots too), and the dword of each slot it filled, in order. Only +/// the first `min(flagged, slots)` entries of the table are this plan's. +pub(super) fn captured(header: &[u32; 8], table: impl Fn(u32) -> u32) -> (u32, Vec<(u32, u32)>) { + let flagged = header[2]; + let filled = flagged.min(header[1]); + (flagged, (0..filled).map(|k| (table(k), k)).collect()) +} + +/// Since the last frame line: pieces landed out of their own submission +/// and their bytes, pieces flagged past a landing's slots, plans given a +/// landing, landings of the relay that needed no fetch at all, plans that +/// found no room for one, captured pieces left out as held whole by a fetch +/// that ran after their flight ([`fate`]); plans of the relay landed that +/// were made to capture ([`Capturing`]), and those made to fetch. +pub(super) static STATS: [std::sync::atomic::AtomicU64; 9] = [const { std::sync::atomic::AtomicU64::new(0) }; 9]; + +/// Bytes of landing buffers alive (in plans and kept). +pub(super) static ALIVE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A landing buffer: shared memory, mapped. +pub(super) struct Memory { + buffer: ID3D12Resource, + data: usize, + bytes: u64, +} + +// SAFETY: a D3D12 object (free-threaded) and its persistent mapping, used +// by one plan at a time. +unsafe impl Send for Memory {} +unsafe impl Sync for Memory {} + +impl Drop for Memory { + fn drop(&mut self) { + ALIVE.fetch_sub(self.bytes, Ordering::Relaxed); + } +} + +/// A plan's landing: its memory and where things are in it. +pub(super) struct Landing { + memory: Memory, + pub(super) layout: Layout, +} + +impl Landing { + pub(super) fn gpu(&self) -> u64 { + // SAFETY: a live buffer. + unsafe { self.memory.buffer.GetGPUVirtualAddress() } + } + + /// The header and the list, for the scan; `list` is the layout's. + fn prepare(&self, list: &[u32], base: u32) { + let header = self.layout.header(base); + let at = self.memory.data as *mut u32; + // SAFETY: the mapping holds the layout's bytes; the card is done with + // the buffer (its last plan landed before it was given back). + unsafe { + for (i, d) in header.iter().enumerate() { + at.add(i).write_volatile(*d); + } + let to = at.add((self.layout.list_at() / 4) as usize); + std::ptr::copy_nonoverlapping(list.as_ptr(), to, list.len()); + } + } + + /// The header as the card left it. + fn header(&self) -> [u32; 8] { + let at = self.memory.data as *const u32; + // SAFETY: inside the mapping; read once the plan's submission ran. + std::array::from_fn(|i| unsafe { at.add(i).read_volatile() }) + } + + /// Once the plan's submission ran: how many pieces were flagged, and + /// each slot filled by the dword of its flag in the compare's results. + pub(super) fn read(&self) -> (u32, std::collections::HashMap) { + let header = self.header(); + let table = (self.memory.data + self.layout.table_at() as usize) as *const u32; + // SAFETY: the table lies in the mapping; the card has run the scan. + let (flagged, filled) = captured(&header, |k| unsafe { table.add(k as usize).read_volatile() }); + (flagged, filled.into_iter().collect()) + } + + /// Where slot `k`'s bytes are on the CPU. + pub(super) fn slot_address(&self, k: u32) -> usize { + self.memory.data + self.layout.slot_at(k) as usize + } +} + +/// The landing buffers kept, and the last plans' flagged counts. +struct Pool { + spare: Vec, + recent: [u32; SEEN], + seen: usize, +} + +static POOL: Mutex = Mutex::new(Pool { spare: Vec::new(), recent: [0; SEEN], seen: 0 }); + +/// The most any of the last plans landed had flagged. +fn recent() -> u32 { + POOL.lock().unwrap_or_else(|e| e.into_inner()).recent.iter().copied().max().unwrap_or(0) +} + +/// Which of `spare` serves `need` bytes: the smallest that holds it, if it +/// is not more than four times as large. +fn fitting(spare: &[u64], need: u64) -> Option { + spare + .iter() + .enumerate() + .filter(|(_, b)| **b >= need && **b / 4 <= need) + .min_by_key(|(_, b)| **b) + .map(|(i, _)| i) +} + +/// A landing for a plan whose compare flags its pieces at `list` (dwords of +/// the compare's results, from `base` to `end`): a kept buffer that holds +/// it, or one made, within [`most`]. Fewer slots if that is all there is +/// room for; `None` if not one. +pub(super) fn take(host: &Host, list: &[u32], base: u32, end: u32) -> Option { + if list.is_empty() { + return None; + } + let want = slots(list.len() as u32, recent()); + #[cfg(test)] + let want = TEST_SLOTS.get().map_or(want, |most| want.min(most)); + let mut layout = Layout { listed: list.len() as u32, span: end - base, slots: want }; + let need = layout.bytes(); + let kept = { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let sizes: Vec = pool.spare.iter().map(|m| m.bytes).collect(); + match fitting(&sizes, need) { + Some(i) => Some(pool.spare.swap_remove(i)), + None => { + // Room for a new one: the kept ones go first, the largest + // first. + while ALIVE.load(Ordering::Relaxed) + need > most() && !pool.spare.is_empty() { + let largest = (0..pool.spare.len()).max_by_key(|&i| pool.spare[i].bytes).unwrap_or(0); + drop(pool.spare.swap_remove(largest)); + } + None + } + } + }; + let memory = match kept { + Some(memory) => memory, + None => { + let room = most().saturating_sub(ALIVE.load(Ordering::Relaxed)); + let size = need.next_multiple_of(64 << 10).min(room); + layout.slots = layout.slots.min(layout.slots_in(size)); + if layout.slots == 0 { + STATS[5].fetch_add(1, Ordering::Relaxed); + return None; + } + let (buffer, data) = host.shared_buffer(size)?; + name(&buffer, || "pieces shaders wrote to copies in the card's memory, landed in their submission".into()); + ALIVE.fetch_add(size, Ordering::Relaxed); + Memory { buffer, data: data as usize, bytes: size } + } + }; + layout.slots = layout.slots.min(layout.slots_in(memory.bytes)); + let landing = Landing { memory, layout }; + landing.prepare(list, base); + STATS[3].fetch_add(1, Ordering::Relaxed); + Some(landing) +} + +/// The plan of `landing` is done with (its submission ran and it landed, +/// or it is let go): the buffer is kept for the next plans, within +/// [`SPARE_MOST`], and what its scan counted decides their slots. +pub(super) fn give_back(landing: Landing) { + let (flagged, _) = captured(&landing.header(), |_| 0); + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let at = pool.seen % SEEN; + pool.recent[at] = flagged; + pool.seen += 1; + pool.spare.push(landing.memory); + let limit = SPARE_MOST.min(most() / 4); + while pool.spare.iter().map(|m| m.bytes).sum::() > limit { + // The oldest go. + drop(pool.spare.remove(0)); + } +} + +/// Drops the landing buffers kept (the PC's memory is pressured: the sweep). +pub(super) fn trim() { + let freed = std::mem::take(&mut POOL.lock().unwrap_or_else(|e| e.into_inner()).spare); + drop(freed); +} + +/// Up to which send the notes of sends to card copies may go +/// (`crate::shadow::relay_fetched`) once flights whose plans ran behind +/// sends `landed` were merged, a fetch among them having run after send +/// `after` (`after` itself with none): not past the last of those flights' +/// sends while a plan alive was made to capture (`on`, [`capturing`]). A +/// later flight's capture is merged against the sends after its own, which +/// may be older than `after`: their notes are what keep the title's bytes +/// that went up after it out of the merge. +pub(super) fn forgotten(after: u64, landed: impl Iterator, on: bool) -> u64 { + if on { after.min(landed.max().unwrap_or(0)) } else { after } +} + +/// What becomes of a piece a flight's own submission brought down. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Fate { + /// Merged, as a fetch behind the plan's sends. + Merged, + /// Left out: a fetch that ran after the flight held all of it. + Held, + /// Fetched again: an earlier fetch may hold newer bytes of it. + Fetched, +} + +/// The [`Fate`] of a captured `piece` (copy, title address, bytes) of the +/// flight behind which `behind` is signalled, whose plan ran behind send +/// `sent_as`. `had`: what earlier fetches brought, by the flights in the +/// line when each went to the queue (`RelayFetch::had`); `newer`: the same +/// by the last send known to have gone to the queue ahead of each +/// (`RelayFetch::newer`). +/// +/// A fetch with the flight in the line ran after its lists, so it brought +/// what the flight wrote or what flights after it wrote over that, and its +/// merge put that into title memory: a piece it held whole has nothing more +/// of the flight (as `land::Had::holds`), and the capture, older, is left +/// out without a fetch. A fetch noted at the flight's send or later may +/// have run after it (the flight's sends go to the queue under the order's +/// lock, its lists after the lock is let go): a capture of a block it +/// brought may be older than what it merged, and is fetched again. With +/// neither the capture is newer than every fetch merged so far. +/// +/// Left out and not fetched is what keeps one fetch from setting off +/// another for good: a fetch notes every flight in the air, those flights +/// flag the block it brought again, and a fetch of it again notes the next. +pub(super) fn fate(had: Option<&crate::land::Had>, newer: Option<&crate::land::Had>, behind: u64, sent_as: u64, piece: crate::land::Piece) -> Fate { + if had.is_some_and(|h| h.holds(behind, piece)) { + Fate::Held + } else if newer.is_some_and(|n| n.touches(sent_as, piece)) { + Fate::Fetched + } else { + Fate::Merged + } +} + +/// The value of the host's fence behind the last flight in the line: every +/// flight up to it has gone to the queue ([`Line::target`]). A test's own +/// with [`TEST_AHEAD`]. +pub(super) fn line_target() -> u64 { + #[cfg(test)] + if let Some(at) = TEST_AHEAD.get() { + return at; + } + line().target +} + +/// The passes after the compare, compiled with its root signature: `None` +/// if they could not be (then nothing is landed in the submission). +pub(super) fn make(device: &ID3D12Device, root: &ID3D12RootSignature) -> Option<(ID3D12PipelineState, ID3D12PipelineState)> { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let compile = |entry: windows::core::PCSTR| -> windows::core::Result { + let mut code: Option = None; + // SAFETY: the source and names live through the calls; the out + // pointer is ours; the blob's own bytes. + unsafe { + D3DCompile( + SOURCE.as_ptr().cast(), + SOURCE.len(), + windows::core::s!("landing in the submission"), + None, + None, + entry, + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + let code = code.ok_or_else(windows::core::Error::empty)?; + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + }) + } + }; + match (compile(windows::core::s!("scan")), compile(windows::core::s!("copy"))) { + (Ok(scan), Ok(copy)) => Some((scan, copy)), + (Err(e), _) | (_, Err(e)) => { + tracing::warn!(error = %e, "no landing in the submission (LEONIDA_LAND_IN_SUBMISSION): its passes could not be made"); + None + } + } +} + +/// A piece a flight's own submission brought down: its copy, its offsets +/// from and to in it (as `Shadow::card_piece` cuts it), and where its bytes +/// are on the CPU. +pub(super) type Captured = (std::sync::Arc, usize, usize, usize); + +/// Of a plan whose submission ran: by copy (its address) and piece, where +/// the slot its piece came down to is on the CPU and the offset in the copy +/// the slot begins at (the piece as the compare hashes it). Counted: the +/// pieces flagged past its slots. +pub(super) fn slots_of(landing: &Landing, ranges: &[CardRange]) -> std::collections::HashMap<(usize, u32), (usize, usize)> { + let (flagged, filled) = landing.read(); + STATS[2].fetch_add(u64::from(flagged.saturating_sub(landing.layout.slots)), Ordering::Relaxed); + let mut slots = std::collections::HashMap::new(); + if filled.is_empty() { + return slots; + } + for r in ranges.iter().filter(|r| r.compared && !r.picked) { + for p in 0..r.span.pieces { + if let Some(&k) = filled.get(&(r.at + p)) { + let piece = r.span.first + p; + let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; + slots.insert((copy, piece), (landing.slot_address(k), r.shadow.card_hashed(piece).0)); + } + } + } + slots +} + +/// Merges what flights' own submissions brought down, flight by flight in +/// their order, each as a fetch behind its plan's sends (`after`): with +/// [`crate::land`] on a few threads, in its order and jobs, else piece by +/// piece. Returns the bytes put into title memory. +pub(super) fn merge(captures: &[(Vec, u64)]) -> u64 { + use crate::land; + let mut written = 0; + for (captured, after) in captures { + STATS[0].fetch_add(captured.len() as u64, Ordering::Relaxed); + STATS[1].fetch_add(captured.iter().map(|(_, lo, hi, _)| (hi - lo) as u64).sum::(), Ordering::Relaxed); + if !land::on() { + let mut title = Vec::new(); + for (shadow, lo, hi, at) in captured { + // SAFETY: inside the landing's slot (`slots_of`), which the + // card wrote before the flight's fence and nothing writes + // until its plan is given back, after this. + let gpu = unsafe { std::slice::from_raw_parts(*at as *const u8, hi - lo) }; + let merged = shadow.card_merge_relay(*lo, gpu, *after, &mut title); + shadow.walls_merged(gpu.len(), merged); + written += merged as u64; + } + continue; + } + // In the order they are landed, each byte of a copy once: pieces + // joined there are of one piece of the copy (one 64 KiB block of + // title memory), so of one slot. + let keys: Vec = captured.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect(); + let ordered: Vec = land::ordered(&keys) + .into_iter() + .map(|(i, title, len)| { + let (shadow, first, _, at) = &captured[i]; + let lo = title - shadow.span().0 as usize; + (shadow.clone(), lo, lo + len, at + (lo - first)) + }) + .collect(); + let titles: Vec<(usize, usize)> = ordered.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect(); + let jobs = land::jobs(&titles); + let put = std::sync::atomic::AtomicU64::new(0); + land::each(jobs.len(), &|j| { + let working = std::time::Instant::now(); + let mut notes = land::Notes::default(); + for run in ordered[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) { + let addressed: Vec<(usize, usize, usize)> = run.iter().map(|(_, lo, hi, at)| (*lo, *hi, *at)).collect(); + // SAFETY: as above; the bytes stay until the landing ends. + put.fetch_add(unsafe { run[0].0.land_card(&addressed, *after, &mut notes) }, Ordering::Relaxed); + } + notes.flush(); + land::spent(land::stat::CARD_ALL, working); + }); + land::count(land::stat::JOBS, jobs.len() as u64); + written += put.into_inner(); + } + written +} + +/// Records the passes after the compare's (`passes`: those of the ranges +/// the plan lands, as the compare ran them) into `list`, whose root +/// signature, compare results (root view 3) and constants are the +/// compare's. +/// +/// # Safety +/// The list is open, the compare's passes recorded in it; live buffers. +pub(super) unsafe fn record( + list: &ID3D12GraphicsCommandList, + (scan, copy): &(ID3D12PipelineState, ID3D12PipelineState), + landing: &Landing, + differs: u64, + passes: &[ComparePass], +) { + let barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }; + // SAFETY: the caller's. + unsafe { + // The compare's flags, first. + list.ResourceBarrier(std::slice::from_ref(&barrier)); + list.SetPipelineState(scan); + // (Not read by the scan; set, as the signature has it.) + list.SetComputeRootShaderResourceView(1, differs); + list.SetComputeRootUnorderedAccessView(2, landing.gpu()); + list.Dispatch(1, 1, 1); + // The slots it gave, before the copies. + list.ResourceBarrier(std::slice::from_ref(&barrier)); + list.SetPipelineState(copy); + for pass in passes { + list.SetComputeRootShaderResourceView(1, pass.buffer); + card_pass(list, &pass.span, pass.size, pass.at, 0); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The parts of a landing lie one after the other and apart, the slots + /// from a multiple of 256, each [`SLOT`] long, inside the buffer. + #[test] + fn a_landings_parts_lie_apart_inside_it() { + for (listed, span, slots) in [(1, 1, 1), (3, 7, 2), (1000, 1200, 64), (262_144, 262_144, 4096), (5, 5, 0)] { + let l = Layout { listed, span, slots }; + assert_eq!(l.list_at(), HEADER); + assert_eq!(l.slot_of_at(), l.list_at() + 4 * u64::from(listed)); + assert_eq!(l.table_at(), l.slot_of_at() + 4 * u64::from(span)); + assert!(l.data_at() >= l.table_at() + 4 * u64::from(slots)); + assert_eq!(l.data_at() % 256, 0); + assert!(l.data_at() - (l.table_at() + 4 * u64::from(slots)) < 256); + for k in 0..slots.min(8) { + assert_eq!(l.slot_at(k + 1) - l.slot_at(k), SLOT); + } + assert_eq!(l.bytes(), l.data_at() + u64::from(slots) * SLOT); + let header = l.header(40); + assert_eq!(header, [ + listed, + slots, + 0, + 40, + l.list_at() as u32, + l.slot_of_at() as u32, + l.table_at() as u32, + l.data_at() as u32 + ]); + // What a buffer of its own size holds is at least what it was + // made for, and a buffer that holds `k` slots holds them all. + assert_eq!(l.slots_in(l.bytes()), slots); + assert_eq!(l.slots_in(l.bytes() - 1), slots.saturating_sub(1)); + let k = l.slots_in(16 << 20); + assert!(Layout { slots: k, ..l }.bytes() <= 16 << 20, "{k} slots in 16 MiB for {l:?}"); + } + // (The copy shader's slot step.) + assert!(SOURCE.contains(&format!("s * {SLOT}u"))); + } + + /// A piece of a copy lies in its slot whatever the copy's skew: what is + /// merged of it (`Shadow::card_piece`) lies between the 16-byte bounds + /// the compare hashes and the copy shader copies, which are at most + /// [`SLOT`] apart. + #[test] + fn every_part_of_a_piece_lies_in_its_slot() { + for skew in [0u32, 4, 16, 100, 4097, 65_520, 65_535] { + for len in [1u32, 300, 65_536, 200_000, 1 << 20] { + let size = len.next_multiple_of(16); + let pieces = (skew + len).div_ceil(65_536); + for piece in 0..pieces { + // As the shader cuts it. + let lo = (piece * 65_536).saturating_sub(skew); + let hi = ((piece + 1) * 65_536 - skew).min(size); + let (from, to) = (lo & !15, (hi + 15) & !15); + assert!(u64::from(to - from) <= SLOT, "skew {skew}, piece {piece}: {from}..{to}"); + assert!(to <= size); + // What is merged: the piece's bytes in the copy. + let (a, b) = (lo, ((piece + 1) * 65_536 - skew).min(len)); + assert!(from <= a && b <= to, "skew {skew} len {len} piece {piece}"); + } + } + } + } + + /// Slots: half again the most flagged lately, in steps of 16, at least + /// 16, never more than the plan's pieces. + #[test] + fn a_plan_gets_slots_by_what_plans_flagged_lately() { + assert_eq!(slots(1000, 0), 16); + assert_eq!(slots(5, 0), 5); + assert_eq!(slots(1000, 10), 16); + assert_eq!(slots(1000, 100), 160); + assert_eq!(slots(1000, 101), 160); + assert_eq!(slots(1000, 700), 1000); + assert_eq!(slots(0, 50), 0); + assert_eq!(slots(u32::MAX, u32::MAX), u32::MAX); + } + + /// The listed dwords are every pass's flags in order; the span from the + /// first to the last. + #[test] + fn the_scan_looks_at_every_landed_flag_in_order() { + let (list, base, end) = listed([(10u32, 3u32), (20, 2), (13, 1)].into_iter()); + assert_eq!(list, vec![10, 11, 12, 20, 21, 13]); + assert_eq!((base, end), (10, 22)); + assert_eq!(listed(std::iter::empty()), (Vec::new(), 0, 0)); + } + + /// What the CPU reads of the scan: the first `min(flagged, slots)` + /// entries of the table, never the stale ones behind them. + #[test] + fn only_the_slots_the_scan_filled_are_read() { + let table = [7u32, 9, 30, 99, 98]; + let header = |slots: u32, flagged: u32| [0, slots, flagged, 0, 0, 0, 0, 0]; + assert_eq!(captured(&header(5, 3), |k| table[k as usize]), (3, vec![(7, 0), (9, 1), (30, 2)])); + // Past the slots: counted, not read. + assert_eq!(captured(&header(2, 4), |k| table[k as usize]), (4, vec![(7, 0), (9, 1)])); + assert_eq!(captured(&header(5, 0), |k| table[k as usize]), (0, vec![])); + } + + /// A flight ran behind send 5 and captured its piece; the title then + /// wrote bytes of it that went up with send 6, and send 7 went up before + /// the flight lands, after the landing of flights behind sends up to 4 + /// fetched behind send 7. The notes kept up to what [`forgotten`] says + /// keep the title's bytes out of the capture's merge; let go up to the + /// fetch's send, as without captures, the capture's older bytes went + /// over them. + #[test] + fn notes_a_later_capture_needs_are_kept() { + assert_eq!(forgotten(7, [4, 2].into_iter(), true), 4); + assert_eq!(forgotten(3, [4].into_iter(), true), 3); + assert_eq!(forgotten(7, [4].into_iter(), false), 7); + assert_eq!(forgotten(7, std::iter::empty(), true), 0); + for (on, kept) in [(true, true), (false, false)] { + let mut title = vec![0x11u8; 4096]; + let mut side = title.clone(); + let shadow = crate::shadow::Shadow::unbacked(title.as_ptr() as u64, side.as_mut_ptr(), 4096, true); + // Send 6: the title's bytes went up. + title[256..272].fill(0x33); + side[256..272].fill(0x33); + shadow.sent_for_test(6, vec![(256, 272)], 0); + // Send 7, with the notes the landing before let go. + shadow.sent_for_test(7, Vec::new(), forgotten(7, [4].into_iter(), on)); + // The capture: what the card held after the flight, which wrote a + // dword at 0, before send 6. + let mut capture = vec![0x11u8; 4096]; + capture[0..4].copy_from_slice(&[0x22; 4]); + let mut scratch = Vec::new(); + shadow.card_merge_relay(0, &capture, 5, &mut scratch); + assert_eq!(title[0..4], [0x22; 4], "the shader's dword"); + assert_eq!(title[256..272] == [0x33; 16], kept, "the title's bytes with LEONIDA_LAND_IN_SUBMISSION={}", u8::from(on)); + } + } + + /// A fetch went to the drawing queue with the flights up to the one + /// behind fence 20 in the line and sends up to 7 ahead of it, and + /// brought block 3 of copy 1 whole and part of block 5. A capture of a + /// flight in the line then is left out where the fetch held it whole and + /// fetched again where it did not; one of a flight that had sent but was + /// not in the line yet (its lists may have gone after the fetch) is + /// fetched again; one of a flight sent after the fetch is merged, as is + /// any capture of what no fetch brought. + #[test] + fn a_capture_is_merged_left_out_or_fetched_by_where_its_flight_ran() { + use crate::land::{BLOCK, Had}; + let block = |copy: u64, n: usize| (copy, n * BLOCK, BLOCK); + let part = (1u64, 5 * BLOCK + 256, 1024); + let (mut had, mut newer) = (Had::default(), Had::default()); + had.fetched(20, [block(1, 3), part].into_iter()); + newer.fetched(7, [block(1, 3), part].into_iter()); + let fate = |behind: u64, sent_as: u64, piece| fate(Some(&had), Some(&newer), behind, sent_as, piece); + assert_eq!(fate(18, 6, block(1, 3)), Fate::Held); + assert_eq!(fate(20, 7, (1, 3 * BLOCK + 4096, 512)), Fate::Held, "a part of a block held whole"); + assert_eq!(fate(18, 6, block(1, 5)), Fate::Fetched, "more than the fetch held of its block"); + assert_eq!(fate(21, 7, block(1, 3)), Fate::Fetched, "sent ahead of the fetch, not in the line"); + assert_eq!(fate(22, 8, block(1, 3)), Fate::Merged, "sent after the fetch went to the queue"); + assert_eq!(fate(18, 6, block(2, 3)), Fate::Merged, "a copy the fetch did not bring"); + assert_eq!(fate(18, 6, block(1, 4)), Fate::Merged, "a block the fetch did not bring"); + assert_eq!(super::fate(None, None, 18, 6, block(1, 3)), Fate::Merged, "no fetch yet"); + } + + /// A kept buffer serves a landing that fits it, not one four times + /// smaller; the smallest that fits. + #[test] + fn a_kept_buffer_serves_what_fits_it() { + let mib = 1u64 << 20; + assert_eq!(fitting(&[4 * mib, 2 * mib, 8 * mib], 2 * mib), Some(1)); + assert_eq!(fitting(&[4 * mib, 8 * mib], 3 * mib), Some(0)); + assert_eq!(fitting(&[16 * mib], 3 * mib), None, "more than four times as large"); + assert_eq!(fitting(&[mib], 3 * mib), None); + assert_eq!(fitting(&[], 3 * mib), None); + } +} + +#[cfg(test)] +pub(super) mod card_tests { + use super::super::{CardAsk, CardPlan, ComparePass, Declared, Host, Prelude, card_asked, host}; + use super::*; + use crate::shadow::{CardSpan, Shadow}; + use windows::Win32::Foundation::HANDLE; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::Interface; + + /// One at a time: the switch is per thread, but the pool and its + /// counts are the process's (`compare_ecl`'s tests take turns too). + pub(in crate::host) fn turn() -> std::sync::MutexGuard<'static, ()> { + static TURN: Mutex<()> = Mutex::new(()); + TURN.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Lists of ours on the host's queue, and a fence to wait for them. + struct Rig { + host: &'static Host, + fence: ID3D12Fence, + event: HANDLE, + done: u64, + lists: Vec, + } + + impl Rig { + fn new(host: &'static Host) -> Rig { + // SAFETY: plain object creation. + let (fence, event) = unsafe { + (host.device.CreateFence::(0, D3D12_FENCE_FLAG_NONE).unwrap(), CreateEventW(None, false, false, None).unwrap()) + }; + Rig { host, fence, event, done: 0, lists: Vec::new() } + } + + /// A list of ours, recorded by `record` and sent. + fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) { + let (allocator, list) = self.host.make_prelude().expect("a list"); + // SAFETY: a fresh list. + unsafe { list.Reset(&allocator, None).unwrap() }; + record(&list); + // SAFETY: an open list of ours. + unsafe { + list.Close().unwrap(); + self.host.queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + } + self.lists.push((allocator, list)); + } + + /// A list recorded elsewhere (a plan's compare), sent. + fn send(&self, list: &ID3D12CommandList) { + // SAFETY: a closed list. + unsafe { self.host.queue.ExecuteCommandLists(&[Some(list.clone())]) }; + } + + /// Waits until the card has run everything sent: the value of the + /// fence behind it. + fn settle(&mut self) -> u64 { + self.done += 1; + // SAFETY: a live queue, fence and event of ours. + unsafe { + self.host.queue.Signal(&self.fence, self.done).unwrap(); + self.fence.SetEventOnCompletion(self.done, self.event).unwrap(); + WaitForSingleObject(self.event, INFINITE); + } + self.done + } + } + + impl Drop for Rig { + fn drop(&mut self) { + // SAFETY: our event. + unsafe { + let _ = windows::Win32::Foundation::CloseHandle(self.event); + } + } + } + + /// The passes of ours on the host's card, over two copies the + /// compare's results flag pieces of (one with a skew that is not a + /// multiple of 16): each flagged piece of the listed passes, in order, + /// is in its slot, whole as the compare hashes it, until the slots run + /// out; the table names each slot's flag; a flag nobody listed (a + /// range only looked at) gets no slot; the scan counts every flagged + /// piece it looked at, past the slots too. + #[test] + fn the_passes_put_each_flagged_piece_in_its_slot() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the landing passes were not tried"); + return; + }; + let _turn = turn(); + let work = host.make_card_work().expect("the card compare must be made"); + let psos = make(&host.device, &work.root).expect("the landing passes must be made"); + // Copy A: 3 pieces' bytes from 4100 bytes into its first piece, so 4 + // pieces; copy B: 2 pieces from 0. + let (skew_a, len_a) = (4100u32, 3 * PIECE as u32); + let (len_b, size_b) = (2 * PIECE as u32, 2 * PIECE as u32); + let size_a = len_a.next_multiple_of(16); + let (a, a_ptr) = host.shared_buffer(u64::from(len_a.next_multiple_of(PIECE as u32))).unwrap(); + let (b, b_ptr) = host.shared_buffer(u64::from(size_b)).unwrap(); + let bytes_a: Vec = (0..len_a).map(|i| (i.wrapping_mul(37) ^ (i >> 9)) as u8).collect(); + let bytes_b: Vec = (0..len_b).map(|i| (i.wrapping_mul(11) ^ (i >> 7) ^ 0x5a) as u8).collect(); + let differs = work.differs.1 as *mut u32; + // A's flags at dwords 100..104: pieces 0, 2, 3; 104 flagged but + // nobody's (only looked at); B's at 110..112, both. + let flags: [(u32, u32); 7] = [(100, 1), (101, 0), (102, 3), (103, 5), (104, 1), (110, 7), (111, 9)]; + // SAFETY: the mappings hold these bytes and dwords. + unsafe { + std::ptr::copy_nonoverlapping(bytes_a.as_ptr(), a_ptr, bytes_a.len()); + std::ptr::copy_nonoverlapping(bytes_b.as_ptr(), b_ptr, bytes_b.len()); + for (d, v) in flags { + differs.add(d as usize).write_volatile(v); + } + } + // SAFETY (both): live buffers. + let pass = |buffer: &ID3D12Resource, size: u32, len: u32, skew: u32, at: u32| ComparePass { + buffer: unsafe { buffer.GetGPUVirtualAddress() }, + hashes: 0, + size, + span: CardSpan { from: 0, to: len, first: 0, pieces: (skew + len).div_ceil(PIECE as u32), skew }, + at, + mode: 2, + }; + let passes = [pass(&a, size_a, len_a, skew_a, 100), pass(&b, size_b, len_b, 0, 110)]; + assert_eq!((passes[0].span.pieces, passes[1].span.pieces), (4, 2)); + let (list, base, end) = listed(passes.iter().map(|p| (p.at, p.span.pieces))); + TEST_SLOTS.set(Some(3)); + let landing = take(host, &list, base, end).expect("a landing"); + TEST_SLOTS.set(None); + assert_eq!(landing.layout.slots, 3); + let mut rig = Rig::new(host); + rig.run(|list| { + // SAFETY: an open list; the compare's root signature; live + // buffers; the pieces lie in them. + unsafe { + list.SetComputeRootSignature(&work.root); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + record(list, &psos, &landing, work.differs.0.GetGPUVirtualAddress(), &passes); + } + }); + rig.settle(); + let (flagged, filled) = landing.read(); + assert_eq!(flagged, 5, "flagged pieces the scan looked at"); + let mut table: Vec<(u32, u32)> = filled.into_iter().collect(); + table.sort_unstable(); + assert_eq!(table, vec![(100, 0), (102, 1), (103, 2)], "each slot's flag, in order"); + // As the compare cuts and widens a piece. + let hashed = |piece: u32, skew: u32, size: u32| { + let lo = (piece * PIECE as u32).saturating_sub(skew); + let hi = ((piece + 1) * PIECE as u32 - skew).min(size); + ((lo & !15) as usize, ((hi + 15) & !15) as usize) + }; + let padded = |bytes: &[u8], size: u32| { + let mut v = bytes.to_vec(); + v.resize(size as usize, 0); + v + }; + let whole_a = padded(&bytes_a, size_a); + for (slot, piece) in [(0u32, 0u32), (1, 2), (2, 3)] { + let (lo, hi) = hashed(piece, skew_a, size_a); + // SAFETY: inside the landing's mapping, which the card wrote. + let got = unsafe { std::slice::from_raw_parts(landing.slot_address(slot) as *const u8, hi - lo) }; + assert!(got == &whole_a[lo..hi], "copy A's piece {piece} in slot {slot} ({lo}..{hi})"); + } + // Where each listed flag's slot went: none for the unflagged and for + // those past the slots. + let slot_of = |d: u32| { + // SAFETY: inside the mapping. + unsafe { ((landing.memory.data + landing.layout.slot_of_at() as usize) as *const u32).add((d - base) as usize).read_volatile() } + }; + assert_eq!([100, 101, 102, 103, 110, 111].map(slot_of), [0, !0, 1, 2, !0, !0]); + give_back(landing); + drop((a, b)); + } + + /// What `card_tests`' copies hold: `LEN` bytes of title memory from 4100 + /// bytes into a 64 KiB block (a skew that is not a multiple of 16). + const LEN: usize = 6 * PIECE as usize; + const SKEW: usize = 4100; + + /// The tiny shader that stands for the title's: `count` dwords + /// `value`, `value + 1`, ... from byte `at` of the copy on. + const WRITER: &str = r#" +#define RS "RootConstants(num32BitConstants=3, b0), UAV(u0)" +cbuffer C : register(b0) { uint at; uint count; uint value; }; +RWByteAddressBuffer copy : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x < count) copy.Store(at + id.x * 4u, value + id.x); +} +"#; + + /// The writer, compiled. + pub(in crate::host) fn writer(device: &ID3D12Device) -> (ID3D12RootSignature, ID3D12PipelineState) { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option = None; + // SAFETY: the source and names live through the calls; the blob's + // own bytes. + unsafe { + D3DCompile( + WRITER.as_ptr().cast(), + WRITER.len(), + windows::core::s!("writer"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + ) + .unwrap(); + let code = code.unwrap(); + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes).unwrap(); + let pso = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, + ..Default::default() + }) + .unwrap(); + (root, pso) + } + } + + /// A title buffer with a copy in the card's memory, both sides holding + /// what title memory holds; and its first compare made (`whole`, as a + /// copy whose writes are declared for the first time gets). + struct Title { + _room: Vec, + start: usize, + shadow: std::sync::Arc, + } + + impl Title { + fn new(rig: &mut Rig) -> Option { + Title::seen(rig, |_| ()) + } + + /// As [`Title::new`]; `seen` looks at the first plan once the card + /// has run it, before it is given back. + fn seen(rig: &mut Rig, seen: impl FnOnce(&CardPlan)) -> Option<Title> { + let room = vec![0u8; LEN + 2 * PIECE as usize]; + let start = (room.as_ptr() as usize).next_multiple_of(PIECE as usize) + SKEW; + let mut title = Title { start, shadow: Shadow::carded_for_test(start as u64, LEN as u64)?, _room: room }; + for (i, b) in title.bytes_mut().iter_mut().enumerate() { + *b = (i.wrapping_mul(29) ^ (i >> 10)) as u8; + } + // The CPU side takes them, and a list of ours puts them on the + // card side (not left to a send, which another test's plan may + // take first). + title.shadow.refresh_for_test(start, start + LEN); + title.shadow.take_dirty(); + let (staging, _, _) = title.shadow.card_sides()?; + let staging = staging.clone(); + let buffer = title.shadow.buffer.clone(); + rig.run(|list| { + // SAFETY: an open list; live buffers of `LEN` bytes or more. + unsafe { list.CopyBufferRegion(&buffer, 0, &staging, 0, LEN as u64) } + }); + // The first compare: its hashes are made of the card side whole. + let plan = title.plan(rig.host, &[(0, LEN)]); + if let Some(check) = &plan.check { + rig.send(check); + } + let at = rig.settle(); + let mut fetch = None; + rig.host.relay_card_back(&[(&plan, at)], &mut fetch, &mut || {}); + seen(&plan); + rig.host.card_done(plan); + Some(title) + } + + fn bytes_mut(&mut self) -> &mut [u8] { + // SAFETY: the room's bytes, `LEN` of them from `start`. + unsafe { std::slice::from_raw_parts_mut(self.start as *mut u8, LEN) } + } + + /// A submission's plan, as one sent ahead with the relay makes it: + /// shader writes declared at `ranges` (offsets). + fn plan(&self, host: &Host, ranges: &[(usize, usize)]) -> CardPlan { + let declared: Vec<Declared> = + vec![(self.shadow.clone(), ranges.iter().map(|&(a, b)| (self.start + a, self.start + b)).collect())]; + let asked = card_asked(&declared, &[]); + host.card_before(Some(CardAsk { declared, looked: Vec::new(), asked }), true).expect("a plan") + } + } + + /// What one submission does: the writer stores `writes` (offset in the + /// copy, dwords, first value) into the card side, then the plan's + /// compare (and, with the switch, the landing) runs; the card is + /// waited for. The fence value behind it. + fn submit(rig: &mut Rig, title: &Title, plan: &CardPlan, writes: &[(usize, u32, u32)]) -> u64 { + let (root, pso) = writer(&rig.host.device); + let buffer = title.shadow.buffer.clone(); + rig.run(|list| { + // SAFETY: an open list; the writer's root signature; the writes + // lie in the card side. + unsafe { + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(1, buffer.GetGPUVirtualAddress()); + for &(at, count, value) in writes { + let constants = [at as u32, count, value]; + list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.Dispatch(count.div_ceil(64), 1, 1); + } + } + }); + if let Some(check) = &plan.check { + rig.send(check); + } + rig.settle() + } + + /// `bytes` with `writes` applied as the writer stores them. + fn written(bytes: &mut [u8], writes: &[(usize, u32, u32)]) { + for &(at, count, value) in writes { + for i in 0..count as usize { + bytes[at + 4 * i..at + 4 * i + 4].copy_from_slice(&(value + i as u32).to_le_bytes()); + } + } + } + + /// What the landing of `flights` (plans and the writes of each, sent + /// one after the other, the card waited for after each) left: title + /// memory, the fetches the landing thread sent and waited for, and what + /// it should hold. Title memory is written by the CPU at `title_writes` + /// after the flights ran and before they land, where no shader wrote. + /// `slots`: the most a plan gets. Last, the pieces the plans' compares + /// hashed. + #[allow(clippy::type_complexity)] + fn land(on: bool, slots: Option<u32>, flights: &[(&[(usize, usize)], &[(usize, u32, u32)])], title_writes: &[usize]) -> Option<(Vec<u8>, u64, Vec<u8>, u64)> { + let host = host()?; + let mut rig = Rig::new(host); + TEST_ON.set(Some(on)); + TEST_SLOTS.set(slots); + let Some(mut title) = Title::new(&mut rig) else { + TEST_ON.set(None); + TEST_SLOTS.set(None); + return None; + }; + let mut want = title.bytes_mut().to_vec(); + let mut plans = Vec::new(); + for (declared, writes) in flights { + let plan = title.plan(host, declared); + assert_eq!(plan.landing.is_some(), on, "a landing with the switch, none without"); + let at = submit(&mut rig, &title, &plan, writes); + written(&mut want, writes); + plans.push((plan, at)); + } + for &at in title_writes { + title.bytes_mut()[at] ^= 0xa5; + want[at] ^= 0xa5; + } + let mut fetch = None; + let landing: Vec<(&CardPlan, u64)> = plans.iter().map(|(p, at)| (p, *at)).collect(); + host.relay_card_back(&landing, &mut fetch, &mut || {}); + let sent = fetch.as_ref().map_or(0, |f| f.sent); + drop(landing); + let hashed = plans.iter().map(|(p, _)| p.hashed).sum(); + for (plan, _) in plans { + host.card_done(plan); + } + TEST_ON.set(None); + TEST_SLOTS.set(None); + Some((title.bytes_mut().to_vec(), sent, want, hashed)) + } + + /// Where the bytes first differ, for a message. + fn first_difference(a: &[u8], b: &[u8]) -> Option<usize> { + a.iter().zip(b).position(|(x, y)| x != y) + } + + /// A shader writes parts of three of the copy's six pieces (one write + /// across the edge of two), the title's CPU writes a byte beside them + /// before the flight lands: title memory ends up with both, with the + /// switch as without it, and with it the landing thread sends no fetch + /// and waits for none (without it, one). On the host's card. + #[test] + fn what_a_shader_wrote_lands_with_no_fetch_of_its_own() { + let _turn = turn(); + let edge = 3 * PIECE as usize - SKEW - 8; + let writes: &[(usize, u32, u32)] = &[(PIECE as usize + 100, 16, 0x1000), (edge, 4, 0x2000), (5 * PIECE as usize + 40, 1, 0x3000)]; + let declared: &[(usize, usize)] = &[(0, LEN)]; + let beside = [PIECE as usize + 20]; + for on in [false, true] { + let Some((got, sent, want, _)) = land(on, None, &[(declared, writes)], &beside) else { + eprintln!("no copies in the card's memory here; landing in the submission was not tried"); + return; + }; + assert!(got == want, "LEONIDA_LAND_IN_SUBMISSION={}: title memory differs at {:?}", u8::from(on), first_difference(&got, &want)); + assert_eq!(sent, u64::from(!on), "fetches the landing thread sent and waited for, LEONIDA_LAND_IN_SUBMISSION={}", u8::from(on)); + } + } + + /// More pieces flagged than the plan has slots for: those past them + /// come down with a fetch, after the captured ones are merged, and title + /// memory is the same. On the host's card. + #[test] + fn pieces_past_the_slots_are_fetched() { + let _turn = turn(); + let writes: &[(usize, u32, u32)] = &[(8, 3, 0x10), (2 * PIECE as usize, 3, 0x20), (4 * PIECE as usize + 64, 5, 0x30)]; + let declared: &[(usize, usize)] = &[(0, LEN)]; + let Some((got, sent, want, _)) = land(true, Some(1), &[(declared, writes)], &[]) else { + eprintln!("no copies in the card's memory here; landing in the submission was not tried"); + return; + }; + assert!(got == want, "title memory differs at {:?}", first_difference(&got, &want)); + assert_eq!(sent, 1, "the pieces past the slot are fetched"); + } + + /// Two flights landed together write the same piece, the second over a + /// dword of the first and beside it; two declared ranges of the second + /// hold parts of one piece (only the first range's compare flags it): + /// each flight's capture is merged in order, title memory holds the + /// second's dword, and nothing is fetched. On the host's card. + #[test] + fn flights_landed_together_are_merged_in_their_order() { + let _turn = turn(); + let p = PIECE as usize; + let first: &[(usize, u32, u32)] = &[(p + 400, 8, 0xaa00), (3 * p + 4, 2, 0xab00)]; + let second: &[(usize, u32, u32)] = &[(p + 412, 8, 0xbb00), (p + 2000, 1, 0xbc00)]; + let all: &[(usize, usize)] = &[(0, LEN)]; + // Two ranges in piece 1 (offsets p - SKEW .. 2p - SKEW): one ends + // where the other begins. + let split: &[(usize, usize)] = &[(0, p + 1000), (p + 1000, LEN)]; + for on in [false, true] { + let Some((got, sent, want, _)) = land(on, None, &[(all, first), (split, second)], &[3 * p + 100]) else { + eprintln!("no copies in the card's memory here; landing in the submission was not tried"); + return; + }; + assert!(got == want, "LEONIDA_LAND_IN_SUBMISSION={}: title memory differs at {:?}", u8::from(on), first_difference(&got, &want)); + assert_eq!(sent, u64::from(!on), "fetches, LEONIDA_LAND_IN_SUBMISSION={}", u8::from(on)); + } + } + + /// Views a few bytes apart in one piece, one across into the next, a + /// range of three pieces and a view in its last: six declared ranges that + /// do not touch, nine pieces between them, five pieces of the copy. A + /// shader writes in each, the title's CPU beside them. With + /// `LEONIDA_CARD_COMPARE_SHARE` the compare hashes the five once each + /// (without, all nine), and title memory ends with every write either + /// way: a flight landed in its submission or fetched, and a submission + /// waited for. On the host's card. + #[test] + fn ranges_in_one_piece_hash_it_once_and_land_the_same() { + let _turn = turn(); + let p = PIECE as usize; + // Piece k of the copy holds offsets k * p - SKEW .. (k + 1) * p - SKEW. + let declared: &[(usize, usize)] = + &[(p, p + 256), (p + 4096, p + 8192), (p + 30000, 2 * p + 100), (2 * p + 200, 2 * p + 300), (3 * p, 5 * p), (5 * p + 5000, 5 * p + 6000)]; + let writes: &[(usize, u32, u32)] = &[ + (p + 16, 4, 0x100), + (p + 4100, 2, 0x200), + (p + 30008, 1, 0x300), + (2 * p + 60, 2, 0x400), + (2 * p + 200, 1, 0x500), + (4 * p, 3, 0x600), + (5 * p + 5004, 2, 0x700), + ]; + let beside = [p + 1000, 2 * p + 150]; + for on in [false, true] { + for share in [false, true] { + super::super::TEST_SHARE.set(Some(share)); + let landed = land(on, None, &[(declared, writes)], &beside); + super::super::TEST_SHARE.set(None); + let Some((got, _, want, hashed)) = landed else { + eprintln!("no copies in the card's memory here; the shared compare was not tried"); + return; + }; + let switches = format!("LEONIDA_LAND_IN_SUBMISSION={} LEONIDA_CARD_COMPARE_SHARE={}", u8::from(on), u8::from(share)); + assert!(got == want, "{switches}: title memory differs at {:?}", first_difference(&got, &want)); + assert_eq!(hashed, if share { 5 } else { 9 }, "{switches}: pieces the compare hashed"); + } + } + // A submission that is waited for (no relay: the compare stores no + // hash, `Host::card_back` fetches and merges). + let host = host().expect("a device, as above"); + for share in [false, true] { + let mut rig = Rig::new(host); + let mut title = Title::new(&mut rig).expect("a copy in the card's memory, as above"); + let mut want = title.bytes_mut().to_vec(); + super::super::TEST_SHARE.set(Some(share)); + let ranges: Vec<Declared> = + vec![(title.shadow.clone(), declared.iter().map(|&(a, b)| (title.start + a, title.start + b)).collect())]; + let asked = card_asked(&ranges, &[]); + super::super::TEST_SHARE.set(None); + let plan = host.card_before(Some(CardAsk { declared: ranges, looked: Vec::new(), asked }), false).expect("a plan"); + submit(&mut rig, &title, &plan, writes); + written(&mut want, writes); + for &at in &beside { + title.bytes_mut()[at] ^= 0xa5; + want[at] ^= 0xa5; + } + { + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + host.card_back(&plan, &mut submitted, &mut std::collections::HashSet::new()); + } + let hashed = plan.hashed; + host.card_done(plan); + let got = title.bytes_mut().to_vec(); + assert!(got == want, "waited for, LEONIDA_CARD_COMPARE_SHARE={}: title memory differs at {:?}", u8::from(share), first_difference(&got, &want)); + assert_eq!(hashed, if share { 5 } else { 9 }, "waited for, LEONIDA_CARD_COMPARE_SHARE={}: pieces hashed", u8::from(share)); + } + } + + /// Three flights write a dword of one piece in turn, all run before the + /// first lands. The first's piece is past its one slot, so its landing + /// fetches it, after the third ran: the third's dword. The second's + /// capture of that piece is older than that fetch, and is fetched again + /// rather than merged: title memory never goes back to the second's + /// dword (merged, the capture put it there until the third landed). On + /// the host's card. + #[test] + fn a_capture_older_than_an_earlier_fetch_is_not_merged() { + let _turn = turn(); + let Some(host) = host() else { + eprintln!("no D3D12 device; landing in the submission was not tried"); + return; + }; + let mut rig = Rig::new(host); + TEST_ON.set(Some(true)); + let Some(mut title) = Title::new(&mut rig) else { + TEST_ON.set(None); + eprintln!("no copies in the card's memory here; landing in the submission was not tried"); + return; + }; + // No flight of the relay's in the line. + TEST_AHEAD.set(Some(0)); + let p = PIECE as usize; + let x = 3 * p + 64; + let all: &[(usize, usize)] = &[(0, LEN)]; + let flights: [(Option<u32>, &[(usize, u32, u32)]); 3] = + [(Some(1), &[(p + 8, 1, 0xa0), (x, 1, 0xa1)]), (None, &[(x, 1, 0xb1)]), (None, &[(x, 1, 0xc1)])]; + let mut plans = Vec::new(); + for (slots, writes) in flights { + TEST_SLOTS.set(slots); + let plan = title.plan(host, all); + TEST_SLOTS.set(None); + let at = submit(&mut rig, &title, &plan, writes); + plans.push((plan, at)); + } + let mut fetch = None; + let mut seen = Vec::new(); + for (plan, at) in &plans { + host.relay_card_back(&[(plan, *at)], &mut fetch, &mut || {}); + let got = u32::from_le_bytes(title.bytes_mut()[x..x + 4].try_into().unwrap()); + seen.push((got, fetch.as_ref().map_or(0, |f| f.sent))); + } + for (plan, _) in plans { + host.card_done(plan); + } + TEST_ON.set(None); + TEST_AHEAD.set(None); + // The first landing fetches (the third's dword); the second fetches + // its piece again; the third likewise (the fetch before may have run + // after it, as far as the landing knows without the relay's order). + assert_eq!(seen, vec![(0xc1, 1), (0xc1, 2), (0xc1, 3)], "the dword and the fetches after each landing"); + } + + /// The relay's order, for a test that gives its plans sends of their + /// own: the count of sends ([`QUEUE_ORDER`]) is set, and put back with + /// the test's switches when it ends (the tests run without the relay, + /// which alone takes that count). + struct Ordered(u64); + + impl Ordered { + fn new() -> Ordered { + Ordered(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())) + } + + fn set(n: u64) { + *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()) = n; + } + } + + impl Drop for Ordered { + fn drop(&mut self) { + Ordered::set(self.0); + TEST_ON.set(None); + TEST_SLOTS.set(None); + TEST_AHEAD.set(None); + } + } + + /// A flight of the relay's: a plan over the whole copy that ran behind + /// send `sent_as`, with at most `slots`, sent with `writes`. The plan + /// and the value behind it. + fn fly(rig: &mut Rig, title: &Title, sent_as: u64, slots: Option<u32>, writes: &[(usize, u32, u32)]) -> (CardPlan, u64) { + TEST_SLOTS.set(slots); + let mut plan = title.plan(rig.host, &[(0, LEN)]); + TEST_SLOTS.set(None); + plan.sent_as = sent_as; + let at = submit(rig, title, &plan, writes); + (plan, at) + } + + /// With the relay's order: flights 1-3 write one dword of a piece in + /// turn and run before the first lands, whose piece is past its one + /// slot and fetched; sends up to 3 have gone to the queue then, but only + /// flights up to the second are in the line (the third between its + /// sends and its lists), and flight 4 takes send 4 while the fetch is on + /// its way, and runs after it. The second's capture is held whole by + /// that fetch: left out, no fetch. The third's may be older than the + /// fetch: fetched again (flight 5 sends meanwhile). The fourth's is + /// held whole by that second fetch, the fifth, sent after it, is merged: + /// two fetches in all, where noting fetches by the last send after their + /// wait had every landing fetch the piece again. Title memory ends with + /// every write. On the host's card. + #[test] + fn flights_sent_after_a_fetch_land_with_no_further_fetch() { + let _turn = turn(); + let Some(host) = host() else { + eprintln!("no D3D12 device; landing in the submission was not tried"); + return; + }; + let mut rig = Rig::new(host); + let _order = Ordered::new(); + TEST_ON.set(Some(true)); + let Some(mut title) = Title::new(&mut rig) else { + eprintln!("no copies in the card's memory here; landing in the submission was not tried"); + return; + }; + let mut want = title.bytes_mut().to_vec(); + let p = PIECE as usize; + let x = 3 * p + 64; + let mut fetch = None; + let mut seen = Vec::new(); + let mut land = |title: &mut Title, flight: &(CardPlan, u64), meanwhile: Option<u64>, fetch: &mut Option<RelayFetch>| { + host.relay_card_back(&[(&flight.0, flight.1)], fetch, &mut || { + if let Some(n) = meanwhile { + Ordered::set(n); + } + }); + let got = u32::from_le_bytes(title.bytes_mut()[x..x + 4].try_into().unwrap()); + seen.push((got, fetch.as_ref().map_or(0, |f| f.sent))); + }; + let mut flights = Vec::new(); + let first: [(u64, Option<u32>, &[(usize, u32, u32)]); 3] = + [(1, Some(1), &[(p + 8, 1, 0xa0), (x, 1, 0xa1)]), (2, None, &[(x, 1, 0xb1)]), (3, None, &[(x, 1, 0xc1)])]; + for (sent_as, slots, writes) in first { + flights.push(fly(&mut rig, &title, sent_as, slots, writes)); + written(&mut want, writes); + } + Ordered::set(3); + TEST_AHEAD.set(Some(flights[1].1)); + land(&mut title, &flights[0], Some(4), &mut fetch); + flights.push(fly(&mut rig, &title, 4, None, &[(x, 1, 0xd1)])); + TEST_AHEAD.set(Some(flights[3].1)); + land(&mut title, &flights[1], None, &mut fetch); + land(&mut title, &flights[2], Some(5), &mut fetch); + flights.push(fly(&mut rig, &title, 5, None, &[(x, 1, 0xe1)])); + written(&mut want, &[(x, 1, 0xe1)]); + TEST_AHEAD.set(Some(flights[4].1)); + land(&mut title, &flights[3], None, &mut fetch); + land(&mut title, &flights[4], None, &mut fetch); + for (plan, _) in flights { + host.card_done(plan); + } + assert_eq!( + seen, + vec![(0xc1, 1), (0xc1, 1), (0xd1, 2), (0xd1, 2), (0xe1, 2)], + "the dword and the fetches after each landing" + ); + let got = title.bytes_mut().to_vec(); + assert!(got == want, "title memory differs at {:?}", first_difference(&got, &want)); + } + + /// With the relay's order: two flights write a dword each in one piece, + /// and then the title's CPU writes bytes of that piece, which go up to + /// the card with the next send. Each capture, older than those bytes, is + /// merged as behind its own plan's send, so the title's bytes stay; and + /// after the first landing let notes of sends go (`relay_fetched`, which + /// the next taking of changed ranges forgets them by), the second + /// flight's capture still finds the note of that send. Nothing fetched. + /// On the host's card. + #[test] + fn title_bytes_sent_after_a_flight_stay_over_its_capture() { + let _turn = turn(); + let Some(host) = host() else { + eprintln!("no D3D12 device; landing in the submission was not tried"); + return; + }; + let mut rig = Rig::new(host); + let _order = Ordered::new(); + TEST_ON.set(Some(true)); + let Some(mut title) = Title::new(&mut rig) else { + eprintln!("no copies in the card's memory here; landing in the submission was not tried"); + return; + }; + let mut want = title.bytes_mut().to_vec(); + // Past every send whose notes were let go so far. + let base = crate::shadow::relay_fetched_for_test() + 100; + let p = PIECE as usize; + let (one, two, t) = (p + 200, p + 600, p + 1000); + let first = fly(&mut rig, &title, base + 1, None, &[(one, 1, 0x1111_1111)]); + let second = fly(&mut rig, &title, base + 2, None, &[(two, 1, 0x2222_2222)]); + written(&mut want, &[(one, 1, 0x1111_1111), (two, 1, 0x2222_2222)]); + // The title's bytes: the CPU side takes them, they go up to the card + // and are noted with send base + 3, as the taking of them does. + for i in t..t + 16 { + title.bytes_mut()[i] ^= 0x5a; + want[i] ^= 0x5a; + } + title.shadow.refresh_for_test(title.start + t, title.start + t + 16); + title.shadow.take_dirty(); + let (staging, _, _) = title.shadow.card_sides().expect("a copy in the card's memory"); + let staging = staging.clone(); + let buffer = title.shadow.buffer.clone(); + rig.run(|list| { + // SAFETY: an open list; live buffers holding these bytes. + unsafe { list.CopyBufferRegion(&buffer, t as u64, &staging, t as u64, 16) } + }); + rig.settle(); + title.shadow.sent_for_test(base + 3, vec![(t, t + 16)], crate::shadow::relay_fetched_for_test()); + Ordered::set(base + 3); + let mut fetch = None; + host.relay_card_back(&[(&first.0, first.1)], &mut fetch, &mut || {}); + assert!(title.bytes_mut()[t..t + 16] == want[t..t + 16], "the title's bytes after the first capture's merge"); + assert_eq!(title.bytes_mut()[one..one + 4], 0x1111_1111u32.to_le_bytes(), "the first flight's dword"); + // The next taking of changed ranges forgets the notes let go. + title.shadow.sent_for_test(base + 4, Vec::new(), crate::shadow::relay_fetched_for_test()); + host.relay_card_back(&[(&second.0, second.1)], &mut fetch, &mut || {}); + let sent = fetch.as_ref().map_or(0, |f| f.sent); + host.card_done(first.0); + host.card_done(second.0); + let got = title.bytes_mut().to_vec(); + assert!(got == want, "title memory differs at {:?}", first_difference(&got, &want)); + assert_eq!(sent, 0, "fetches"); + } + + /// Where [`flipped`]'s flights all write a dword (piece 3 of the copy), + /// and where the title's CPU writes 16 bytes after they ran (piece 4). + const X: usize = 3 * PIECE as usize + 64; + const T: usize = 4 * PIECE as usize + 1000; + + /// With the relay's order: `flights` made one after the other, each with + /// the switch as it says and its writes, sent up behind sends of their + /// own; then the title's CPU writes 16 bytes at [`T`], which go up to the + /// card with the next send; then the switch is set to `at_landing`, and + /// the flights land one by one in their order, each plan done with after + /// its landing, and the notes of sends let go then are forgotten (as the + /// next taking of changed ranges does). No flight in the line (a fetch + /// holds no flight's piece whole). What [`X`] held after each landing + /// and the fetches sent so far; title memory; what it should hold. + #[allow(clippy::type_complexity)] + fn flipped(flights: &[(bool, &[(usize, u32, u32)])], at_landing: bool) -> Option<(Vec<(u32, u64)>, Vec<u8>, Vec<u8>)> { + let host = host()?; + let mut rig = Rig::new(host); + let _order = Ordered::new(); + TEST_ON.set(Some(false)); + let mut title = Title::new(&mut rig)?; + TEST_AHEAD.set(Some(0)); + let mut want = title.bytes_mut().to_vec(); + // Past every send whose notes were let go so far. + let base = crate::shadow::relay_fetched_for_test() + 100; + let mut made = Vec::new(); + for (i, &(on, writes)) in flights.iter().enumerate() { + TEST_ON.set(Some(on)); + let flight = fly(&mut rig, &title, base + 1 + i as u64, None, writes); + assert_eq!(flight.0.capturing.is_some(), on, "flight {i} made with LEONIDA_LAND_IN_SUBMISSION={}", u8::from(on)); + assert_eq!(flight.0.landing.is_some(), on, "flight {i}: a landing as it was made"); + written(&mut want, writes); + made.push(flight); + } + let title_send = base + 1 + flights.len() as u64; + for i in T..T + 16 { + title.bytes_mut()[i] ^= 0x5a; + want[i] ^= 0x5a; + } + title.shadow.refresh_for_test(title.start + T, title.start + T + 16); + title.shadow.take_dirty(); + let (staging, _, _) = title.shadow.card_sides().expect("a copy in the card's memory"); + let staging = staging.clone(); + let buffer = title.shadow.buffer.clone(); + rig.run(|list| { + // SAFETY: an open list; live buffers holding these bytes. + unsafe { list.CopyBufferRegion(&buffer, T as u64, &staging, T as u64, 16) } + }); + rig.settle(); + title.shadow.sent_for_test(title_send, vec![(T, T + 16)], crate::shadow::relay_fetched_for_test()); + Ordered::set(title_send); + TEST_ON.set(Some(at_landing)); + let mut fetch = None; + let mut seen = Vec::new(); + for (plan, at) in made { + host.relay_card_back(&[(&plan, at)], &mut fetch, &mut || {}); + host.card_done(plan); + title.shadow.sent_for_test(title_send + 1, Vec::new(), crate::shadow::relay_fetched_for_test()); + let got = u32::from_le_bytes(title.bytes_mut()[X..X + 4].try_into().unwrap()); + seen.push((got, fetch.as_ref().map_or(0, |f| f.sent))); + } + Some((seen, title.bytes_mut().to_vec(), want)) + } + + /// Flights made with the switch on, off, on, off (as `LEONIDA_AB` flips + /// it while they are in the air) all write a dword of one piece; the + /// first and the third a dword of another, where the title's CPU then + /// writes bytes that go up after every flight's send. Whatever the + /// switch says when they land: the first's capture is merged; the + /// second's fetch, behind every flight, brings the fourth's dword; the + /// third's capture of that piece is older than that fetch, and is + /// fetched again rather than merged (the fetch was noted for it, though + /// the plan that fetched was made with the switch off); its capture of + /// the other piece leaves the title's bytes alone (their send's note + /// was kept for it, though the landings before were of a plan whose + /// capture needed it no more and one that did not capture); the + /// fourth's fetch brings its dword. Every byte written ends in title + /// memory, the title's over the captures. On the host's card. + #[test] + fn flights_made_on_and_off_in_turn_land_every_byte() { + let _turn = turn(); + let p = PIECE as usize; + let flights: [(bool, &[(usize, u32, u32)]); 4] = [ + (true, &[(X, 1, 0xa1), (4 * p + 8, 1, 0xa2)]), + (false, &[(X, 1, 0xb1)]), + (true, &[(X, 1, 0xc1), (4 * p + 200, 1, 0xc2)]), + (false, &[(X, 1, 0xd1)]), + ]; + for at_landing in [false, true] { + let Some((seen, got, want)) = flipped(&flights, at_landing) else { + eprintln!("no copies in the card's memory here; landing in the submission was not tried"); + return; + }; + let switch = format!("LEONIDA_LAND_IN_SUBMISSION={} at the landings", u8::from(at_landing)); + assert_eq!(seen, vec![(0xa1, 0), (0xd1, 1), (0xd1, 2), (0xd1, 3)], "{switch}: the dword and the fetches after each landing"); + assert!(got == want, "{switch}: title memory differs at {:?}", first_difference(&got, &want)); + } + } + + /// Two flights write a dword each of one piece and one of another, + /// where the title's CPU then writes bytes that go up after both sends. + /// A flip of the switch between their making and their landing changes + /// nothing a plan does: made on, both are merged from their captures + /// with no fetch and the title's bytes stay (the note of their send is + /// kept for the second, the switch off by then); made off, each fetches, + /// the switch on by then. On the host's card. + #[test] + fn a_flip_after_a_plan_is_made_changes_nothing_it_does() { + let _turn = turn(); + let p = PIECE as usize; + for made in [true, false] { + let flights: [(bool, &[(usize, u32, u32)]); 2] = + [(made, &[(X, 1, 0xa1), (4 * p + 8, 1, 0xa2)]), (made, &[(X, 1, 0xb1), (4 * p + 200, 1, 0xb2)])]; + let expected = if made { vec![(0xa1, 0), (0xb1, 0)] } else { vec![(0xb1, 1), (0xb1, 2)] }; + for at_landing in [made, !made] { + let Some((seen, got, want)) = flipped(&flights, at_landing) else { + eprintln!("no copies in the card's memory here; landing in the submission was not tried"); + return; + }; + let switch = format!("LEONIDA_LAND_IN_SUBMISSION={} when made, {} at the landings", u8::from(made), u8::from(at_landing)); + assert_eq!(seen, expected, "{switch}: the dword and the fetches after each landing"); + assert!(got == want, "{switch}: title memory differs at {:?}", first_difference(&got, &want)); + } + } + } + + /// Landing buffers are kept for the next plans within their limit, and + /// none outlives the pool's trim or the plan that holds it: the bytes + /// counted alive come back to 0. On the host's card. + #[test] + fn landing_buffers_do_not_leak() { + let Some(host) = host() else { + eprintln!("no D3D12 device; landing buffers were not tried"); + return; + }; + let _turn = turn(); + trim(); + let alive = || ALIVE.load(Ordering::Relaxed); + assert_eq!(alive(), 0, "landing buffers alive before the test"); + let mut held = Vec::new(); + for n in [1u32, 5, 40, 200, 16, 3, 900, 64] { + let list: Vec<u32> = (1000..1000 + n).collect(); + TEST_SLOTS.set(Some(n)); + held.push(take(host, &list, 1000, 1000 + n).expect("a landing")); + } + TEST_SLOTS.set(None); + let made: u64 = held.iter().map(|l| l.memory.bytes).sum(); + assert_eq!(alive(), made); + // One let go without being given back (a plan dropped). + drop(held.pop()); + for landing in held { + give_back(landing); + } + let kept: u64 = POOL.lock().unwrap().spare.iter().map(|m| m.bytes).sum(); + assert!(kept <= SPARE_MOST.min(most() / 4), "{kept} bytes kept"); + assert_eq!(alive(), kept, "every buffer not kept is gone"); + // A plan that fits a kept buffer takes it: nothing more is made. + let list: Vec<u32> = (0..16).collect(); + let again = take(host, &list, 0, 16).expect("a landing"); + assert_eq!(alive(), kept); + give_back(again); + trim(); + assert_eq!(alive(), 0, "landing buffers alive after the trim"); + } + + /// Our two lists of a plan (`Host::card_before`: the sends and the hash + /// passes ahead of the submission, the compare behind it) are timed on + /// the card (`host::owntimes`): the first plan of a copy (sent up whole, + /// one hash pass over it, one compare pass) gives the three parts, the + /// counts of lists measured rise by one each and the pass counts of the + /// frame line by what was recorded between the stamps; with the switch + /// off no stamp is recorded or read. The debug layer says nothing (with + /// `LEONIDA_D3D12_DEBUG=1`). On the host's card. + #[cfg(feature = "diagnostics")] + #[test] + fn our_lists_are_timed_on_the_card() { + use super::super::{CARD_PASSES, owntimes}; + let _turn = turn(); + let Some(host) = host() else { + eprintln!("no D3D12 device; our lists were not timed"); + return; + }; + let counted = |i: usize| owntimes::OWN_TIMES[i].load(Ordering::Relaxed); + let passed = |i: usize| CARD_PASSES[i].load(Ordering::Relaxed); + for on in [true, false] { + let mut rig = Rig::new(host); + owntimes::TEST_ON.set(Some(on)); + owntimes::TEST_LAST.set(None); + let (lists, passes) = ([counted(3), counted(4)], [passed(0), passed(2)]); + let mut recorded = None; + let title = Title::seen(&mut rig, |plan| recorded = Some(plan.stamps.as_ref().map(|s| s.passes))); + owntimes::TEST_ON.set(None); + if title.is_none() { + eprintln!("no copies in the card's memory here; our lists were not timed"); + return; + } + let took = owntimes::TEST_LAST.take(); + assert_eq!(host.log_messages(), None); + let recorded = recorded.expect("the first plan was looked at"); + if !on { + assert_eq!(recorded, None, "LEONIDA_CARD_OWN_TIMES=0: no stamps"); + assert_eq!(took, None, "LEONIDA_CARD_OWN_TIMES=0: nothing read"); + continue; + } + // The sync list hashes whatever copy `shadow::card_dirty` gives, + // and other tests' copies (`send`'s, under their own turn) may be + // dirty then: at least the one pass over this copy. The compare + // is over this plan's declared range only: exactly one. + let [hashes, compares] = recorded.expect("stamps were taken for the plan"); + assert!(hashes >= 1, "one hash pass over the whole copy between the stamps, got {hashes}"); + assert_eq!(compares, 1, "one compare pass between the stamps"); + let took = took.expect("the stamps were read when the plan was given back"); + assert!(took.sends.is_some() && took.hashes.is_some() && took.compare.is_some(), "every part measured: {took:?}"); + // (Other tests' plans may add to these meanwhile; never less.) + assert!(counted(3) > lists[0] && counted(4) > lists[1], "lists measured: {:?} -> {:?}", lists, [counted(3), counted(4)]); + assert!(passed(0) > passes[0] && passed(2) > passes[1], "passes counted: {:?} -> {:?}", passes, [passed(0), passed(2)]); + } + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/late_tests.rs b/d3d12/crates/leonida-gpu/src/host/late_tests.rs new file mode 100644 index 0000000000..6b597c73c2 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/late_tests.rs @@ -0,0 +1,124 @@ +use super::{continues, join_ranges, touches}; + +/// A wait for room in the compare's results has a place and a name of its +/// own: it was counted as `WHY_MOST`, and the frame line's "lists in the +/// air" was both. Every reason has its own place in both counters, none +/// of them one of `LATE_STATS`' places that are not reasons (11 to 17). +#[test] +fn results_waits_are_told_apart_from_lists_in_the_air() { + use super::{ + LATE_STATS, LATE_WAITED, WHY_CARD_DONE, WHY_FENCE, WHY_MOST, WHY_READ, WHY_RESULTS, WHY_RUN, WHY_STALE, WHY_SYNC, + WHY_VALUE, WHY_WRITES, landing_wait, + }; + let reasons = + [WHY_SYNC, WHY_CARD_DONE, WHY_VALUE, WHY_STALE, WHY_READ, WHY_RUN, WHY_MOST, WHY_WRITES, WHY_FENCE, WHY_RESULTS]; + for (i, &why) in reasons.iter().enumerate() { + assert!(why < LATE_STATS.len() && why < LATE_WAITED.len(), "reason {why} has no place"); + assert!(!(11..=17).contains(&why), "reason {why} is a place of another count"); + assert!(!reasons[..i].contains(&why), "reason {why} twice"); + } + // Those the relay waits for, each named apart. + let waited = [WHY_SYNC, WHY_VALUE, WHY_STALE, WHY_READ, WHY_MOST, WHY_RESULTS, WHY_FENCE]; + let names: Vec<&str> = waited.iter().map(|&why| landing_wait(why)).collect(); + for (i, name) in names.iter().enumerate() { + assert_ne!(*name, landing_wait(usize::MAX), "reason {} unnamed", waited[i]); + assert!(!names[..i].contains(name), "{name} twice"); + } + assert_ne!(landing_wait(WHY_RESULTS), landing_wait(WHY_MOST)); +} + +#[test] +fn a_late_texture_readback_blocks_a_following_cpu_copy() { + use super::{INFINITE, WHY_READ, WaitForSingleObject, blocked_by, host, read_backs}; + + let Some(host) = host() else { + eprintln!("no D3D12 device; texture readback dependency not tested"); + return; + }; + let mut title = [0u8; 64]; + let producer = host.new_list().unwrap(); + let (upload, upload_bytes) = host.upload_buffer(512).unwrap(); + let readback = host.read_back_buffer(512).unwrap(); + // SAFETY: the live upload mapping holds 512 bytes; the producer is + // open and both buffers hold the full transfer range. + unsafe { + upload_bytes.write_bytes(0x5a, 512); + producer.list.CopyBufferRegion(&readback, 0, &upload, 0, 512); + } + producer.defer_read_back(readback, title.as_mut_ptr(), [16, 2, 32]); + producer.close(); + + let (submitted, sent) = host.submit(&[&producer], &[], true).unwrap(); + // SAFETY: the submission lock is held and the event and fence are + // ours. The test keeps the producer, upload and destination alive. + unsafe { + host.fence.SetEventOnCompletion(*submitted, host.event).unwrap(); + WaitForSingleObject(host.event, INFINITE); + } + if let Some(plan) = sent.card { + host.card_done(plan); + } + if let Some(own) = sent.own { + own.landed(); + } + drop(submitted); + + let consumer = host.new_list().unwrap(); + let mut taken = [0u8; 16]; + consumer.defer_copy(taken.as_mut_ptr(), title[32..].as_ptr(), taken.len()); + assert_eq!(blocked_by(&sent.texture_back_ranges, &[&consumer], false), Some(WHY_READ)); + assert_eq!(sent.texture_back_ranges, [(title.as_ptr() as usize, title.as_ptr() as usize + 48)]); + read_backs(&producer); + assert_eq!(title[..16], [0x5a; 16]); + assert_eq!(title[16..32], [0; 16]); + assert_eq!(title[32..48], [0x5a; 16]); + consumer.close(); + eprintln!("the pending texture readback blocked a later CPU copy"); +} + +/// Copies join only when both ends continue and the whole does not +/// overlap itself. +#[test] +fn copies_join_only_end_to_end_and_apart() { + // (destination, source, bytes) + assert!(continues((1000, 5000, 16), (1016, 5016, 32))); + assert!(continues((5000, 1000, 16), (5016, 1016, 32))); + // A gap, or only one side continues. + assert!(!continues((1000, 5000, 16), (1020, 5016, 32))); + assert!(!continues((1000, 5000, 16), (1016, 5020, 32))); + assert!(!continues((1000, 5000, 16), (1000, 5000, 16))); + // Together they would overlap: the second reads what the first wrote. + assert!(!continues((1000, 1016, 16), (1016, 1032, 16))); + assert!(!continues((1016, 1000, 16), (1032, 1016, 16))); + // They touch without overlapping. + assert!(continues((1000, 1032, 16), (1016, 1048, 16))); + assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8))); +} + +/// Ranges are found by what they hold, not by where they start, and a +/// range that only touches another's end does not touch it. +#[test] +fn ranges_touch_where_they_overlap() { + let mut ranges = Vec::new(); + join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]); + assert_eq!(ranges, [(10, 25), (40, 60)]); + join_ranges(&mut ranges, [(25, 40)]); + assert_eq!(ranges, [(10, 60)]); + let ranges = [(10usize, 25usize), (40, 60), (100, 101)]; + for (from, to, hit) in [ + (0, 10, false), + (0, 11, true), + (24, 25, true), + (25, 40, false), + (25, 41, true), + (59, 200, true), + (60, 100, false), + (100, 101, true), + (101, 500, false), + (30, 30, false), + (50, 50, false), + ] { + assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}"); + } + assert!(!touches(&[], 0, usize::MAX)); +} diff --git a/d3d12/crates/leonida-gpu/src/host/line_apart_tests.rs b/d3d12/crates/leonida-gpu/src/host/line_apart_tests.rs new file mode 100644 index 0000000000..d814f0356b --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/line_apart_tests.rs @@ -0,0 +1,79 @@ +use super::{Line, wait_apart}; +use std::sync::{Condvar, Mutex}; + +/// The look a wait makes after each landing runs without the line's +/// lock: the thread that lands flights, the title's fence signals and +/// its value checks can take it meanwhile. What the look needs is +/// copied out under the lock, at each landing again. +#[test] +fn the_look_after_each_landing_runs_without_the_lines_lock() { + let lock = Mutex::new(Line::new()); + lock.lock().unwrap().written = vec![(0x1000, 0x2000)]; + let landed = Condvar::new(); + let looks = Mutex::new(Vec::new()); + let waited = std::cell::Cell::new(0); + std::thread::scope(|s| { + let lands = s.spawn(|| { + // Lands once the wait has looked and found it not done. + while looks.lock().unwrap().is_empty() { + std::thread::yield_now(); + } + let mut line = lock.lock().unwrap(); + line.written.clear(); + line.landings += 1; + drop(line); + landed.notify_all(); + }); + wait_apart( + &lock, + &landed, + |line| line.written.clone(), + |written| { + looks.lock().unwrap().push(lock.try_lock().is_ok()); + written.is_empty() + }, + || waited.set(waited.get() + 1), + ); + lands.join().unwrap(); + }); + assert_eq!(*looks.lock().unwrap(), [true, true], "both looks without the lock"); + assert_eq!(waited.get(), 1); +} + +/// A landing between the copy and the look is not missed: the wait is +/// for a landing after the one the copy was taken at, so it looks again +/// at once instead of waiting for one more (which never comes here). +#[test] +fn a_landing_between_the_copy_and_the_look_is_not_missed() { + let lock = Mutex::new(Line::new()); + lock.lock().unwrap().written = vec![(0x1000, 0x2000)]; + let landed = Condvar::new(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::scope(|s| { + s.spawn(|| { + wait_apart( + &lock, + &landed, + |line| line.written.clone(), + |written| { + if !written.is_empty() { + // The landing, with no one told. + let mut line = lock.lock().unwrap(); + line.written.clear(); + line.landings += 1; + } + written.is_empty() + }, + || (), + ); + tx.send(()).unwrap(); + }); + let back = rx.recv_timeout(std::time::Duration::from_secs(10)); + if back.is_err() { + // Let the waiting thread go before failing. + lock.lock().unwrap().landings += 1; + landed.notify_all(); + } + assert!(back.is_ok(), "the wait missed a landing"); + }); +} diff --git a/d3d12/crates/leonida-gpu/src/host/line_cover_tests.rs b/d3d12/crates/leonida-gpu/src/host/line_cover_tests.rs new file mode 100644 index 0000000000..89a27b08d7 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/line_cover_tests.rs @@ -0,0 +1,219 @@ +use super::{COVER_NOW, Flight, LINE_STEPS, Late, Line, join_ranges}; + +/// A flight of the test's whose read-backs write `ranges` (as given, +/// in no order). +fn flight(number: u64, ranges: Vec<(usize, usize)>) -> Flight { + Flight { + number, + fence: number, + lists: Vec::new(), + order: Vec::new(), + card: None, + back: Vec::new(), + own: None, + joined: super::flight_writes(&[], &ranges), + texture_back_ranges: ranges, + } +} + +/// xorshift64. +fn next(state: &mut u64) -> u64 { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + *state +} + +/// `n` ranges in `[0, span)`, in no order, some empty, some touching +/// or equal to others. +fn ranges(state: &mut u64, n: usize, span: u64) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = Vec::with_capacity(n); + for _ in 0..n { + let at = (next(state) % span) as usize; + let len = match next(state) % 8 { + 0 => 0, + 1 => 0x10000, + _ => (next(state) % 0x8000) as usize, + }; + match (next(state) % 10, out.last().copied()) { + (0, Some(last)) => out.push(last), + (1, Some(last)) => out.push((last.1, last.1 + len)), + _ => out.push((at, at + len)), + } + } + out +} + +/// What `written` must be: every range of the flights in the line and +/// of those being landed, joined. +fn expected(line: &Line, landing: &[Vec<(usize, usize)>]) -> Vec<(usize, usize)> { + let mut all = Vec::new(); + let ranges = line + .line + .iter() + .filter_map(|l| match l { + Late::Run(f) => Some(f.texture_back_ranges.clone()), + _ => None, + }) + .chain(landing.iter().cloned()) + .flatten(); + join_ranges(&mut all, ranges); + all +} + +/// Whatever flights join, overlap, touch, repeat each other's ranges and +/// land (one or several at a time), `written` is what joining every +/// range of those in the air and being landed gives, as when it was made +/// again from them at each landing. +#[test] +fn written_is_every_range_in_the_air_joined_whatever_joins_and_lands() { + let mut state = 0x9e37_79b9_7f4a_7c15u64; + for round in 0..200 { + let mut line = Line::new(); + // Ranges of the flights taken to be landed, as given. + let mut landing: Vec<Vec<(usize, usize)>> = Vec::new(); + let mut number = 0; + for _ in 0..40 { + let in_air = line.line.len(); + match next(&mut state) % 4 { + 0 | 1 => { + number += 1; + let n = (next(&mut state) % 12) as usize; + let span = if round % 2 == 0 { 0x40000 } else { 0x400_0000 }; + line.push_flight(flight(number, ranges(&mut state, n, span)), Vec::new()); + } + 2 if landing.is_empty() && in_air > 0 => { + let n = 1 + (next(&mut state) as usize) % in_air; + landing = line + .take_landable(n) + .into_iter() + .filter_map(|l| match l { + Late::Run(f) => Some(f.texture_back_ranges), + _ => None, + }) + .collect(); + } + _ if !landing.is_empty() => { + line.landed(Vec::new()); + landing.clear(); + } + _ => {} + } + assert_eq!(line.written, expected(&line, &landing), "round {round}"); + } + } +} + +/// What [`super::line_cover`] says changing between a flight joining, +/// being taken to be landed and landing (as `LEONIDA_AB` turned a +/// `crate::toggled!` switch on and off at presents, with flights always +/// in the air) leaves `written` what joining every range in the air +/// gives, and nothing once all have landed: the line keeps its counts +/// one way from its first flight on. Counts kept one way and taken away +/// the other stayed in the cover for good (a read waiting for a landing +/// that never cleared them), or took another flight's range out of +/// `written` while it was still in the air. +#[test] +fn written_holds_whatever_the_switch_says_between_join_take_and_land() { + let mut state = 0x6a09_e667_f3bc_c909u64; + for round in 0..200 { + let mut line = Line::new(); + let mut landing: Vec<Vec<(usize, usize)>> = Vec::new(); + let mut number = 0; + for step in 0..48 { + COVER_NOW.with(|c| c.set(Some(next(&mut state) & 1 == 0))); + let in_air = line.line.len(); + // The last steps land everything. + let draining = step >= 40; + match next(&mut state) % 4 { + 0 | 1 if !draining => { + number += 1; + let n = (next(&mut state) % 12) as usize; + line.push_flight(flight(number, ranges(&mut state, n, 0x40000)), Vec::new()); + } + _ if landing.is_empty() && in_air > 0 => { + let n = if draining { in_air } else { 1 + (next(&mut state) as usize) % in_air }; + landing = line + .take_landable(n) + .into_iter() + .filter_map(|l| match l { + Late::Run(f) => Some(f.texture_back_ranges), + _ => None, + }) + .collect(); + } + _ if !landing.is_empty() => { + line.landed(Vec::new()); + landing.clear(); + } + _ => {} + } + assert_eq!(line.written, expected(&line, &landing), "round {round}, step {step}"); + } + if !landing.is_empty() { + line.landed(Vec::new()); + } + assert!(line.line.is_empty() && line.written.is_empty(), "round {round}: {:?} left", line.written); + assert!(line.cover.0.is_empty(), "round {round}: counts left in the cover"); + } + COVER_NOW.with(|c| c.set(None)); +} + +/// A flight made while the switch said off (its ranges not joined +/// before the lock, `Host::send_late`) joining a line kept by the +/// cover is counted all the same, and its landing takes it away. +#[test] +fn a_flight_not_joined_before_the_lock_is_counted_all_the_same() { + COVER_NOW.with(|c| c.set(Some(true))); + let mut line = Line::new(); + line.push_flight(flight(1, vec![(0x100, 0x200)]), Vec::new()); + let mut bare = flight(2, vec![(0x180, 0x300), (0x400, 0x500)]); + bare.joined.clear(); + line.push_flight(bare, Vec::new()); + assert_eq!(line.written, vec![(0x100, 0x300), (0x400, 0x500)]); + drop(line.take_landable(1)); + line.landed(Vec::new()); + assert_eq!(line.written, vec![(0x180, 0x300), (0x400, 0x500)]); + drop(line.take_landable(1)); + line.landed(Vec::new()); + assert!(line.written.is_empty() && line.cover.0.is_empty()); + COVER_NOW.with(|c| c.set(None)); +} + +/// Steps the line takes under its lock to keep `written`, with 16 +/// flights of 1,024 ranges each joining and then landing one by one: +/// a pass over what is in the air for each, not a sort of it. Measured +/// here: 388,396 steps, against 3,055,321 with `LEONIDA_LINE_COVER=0` +/// (comparisons of the sorts and the joins after them). +#[test] +fn keeping_written_is_one_pass_over_what_is_in_the_air() { + const FLIGHTS: u64 = 16; + const RANGES: usize = 1024; + let mut state = 0x2545_f491_4f6c_dd1du64; + let mut line = Line::new(); + let (mut steps, mut budget) = (0u64, 0u64); + let mut in_air: Vec<usize> = Vec::new(); + let mut measure = |line: &mut Line, f: &mut dyn FnMut(&mut Line), ranges: u64| { + LINE_STEPS.with(|s| s.set(0)); + f(line); + steps += LINE_STEPS.with(std::cell::Cell::get); + budget += 4 * (ranges + 1); + }; + for number in 1..=FLIGHTS { + let f = flight(number, ranges(&mut state, RANGES, 1 << 34)); + let n = f.joined.len(); + in_air.push(n); + let total = in_air.iter().sum::<usize>() as u64; + let mut f = Some(f); + measure(&mut line, &mut |line| line.push_flight(f.take().unwrap(), Vec::new()), total + n as u64); + } + while !in_air.is_empty() { + let total = in_air.iter().sum::<usize>() as u64; + drop(line.take_landable(1)); + in_air.remove(0); + measure(&mut line, &mut |line| line.landed(Vec::new()), total); + } + assert!(line.written.is_empty()); + assert!(steps <= budget, "{steps} steps for a budget of {budget}"); + eprintln!("keeping written: {steps} steps for a budget of {budget}"); +} diff --git a/d3d12/crates/leonida-gpu/src/host/lines.rs b/d3d12/crates/leonida-gpu/src/host/lines.rs new file mode 100644 index 0000000000..308a756f68 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/lines.rs @@ -0,0 +1,490 @@ +//! The frame lines: what the host counted per frame, logged with the frame rate. + +use super::*; + +/// The retired objects' line of the frame lines, per frame ([`RETIRE_WAITS`]). +#[cfg(feature = "diagnostics")] +fn retire_waits_line(frames: f64) { + let n: Vec<f64> = RETIRE_WAITS.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if n.iter().all(|&v| v == 0.0) { + return; + } + tracing::info!( + "objects let go per frame that wait for a submission: {:.0}; their pushes that found the queue's lock taken, all threads: {:.1} waiting \ + {:.3} ms with one queue, {:.1} waiting {:.3} ms with a queue to each thread (LEONIDA_RETIRE_QUEUES)", + n[0], + n[1], + n[2] / 1e6, + n[3], + n[4] / 1e6, + ); +} + +/// The gates' line of the frame lines, per frame ([`GATE_US`], [`GATE_FOUND`]). +#[cfg(feature = "diagnostics")] +fn gate_line(frames: f64) { + let [opened, us] = [0, 1].map(|i| GATE_US[i].swap(0, Ordering::Relaxed)); + let [open, shut] = [0, 1].map(|i| GATE_FOUND[i].swap(0, Ordering::Relaxed)); + if opened + open + shut == 0 { + return; + } + tracing::info!( + "gates in the card's queue per frame (LEONIDA_BAKE_AHEAD): {:.2} opened, {:.3} ms on average from the card reaching \ + the list they follow to the opening; submissions behind one {:.2} that found it open, {:.2} that made the card wait at it", + opened as f64 / frames, + us as f64 / 1e3 / opened.max(1) as f64, + open as f64 / frames, + shut as f64 / frames, + ); +} + +/// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the +/// frame's time. +pub(super) fn card_clock_line(frames: f64, ms: f64) { + let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + tracing::info!( + "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \ + {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \ + had not submitted; the submitting thread stood waiting for the card {stood:.1} ms", + if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 } + ); +} + +/// For the frame-rate line: what [`read_back_pool`] did per frame, if there +/// were read backs. +fn read_backs_line(frames: f64) { + let b: Vec<u64> = BACKS.iter().map(|b| b.swap(0, Ordering::Relaxed)).collect(); + if b.iter().all(|&n| n == 0) { + return; + } + let (kept, bytes) = { + let spare = SPARE_BACKS.lock().unwrap_or_else(|e| e.into_inner()); + (spare.kept.len(), spare.bytes) + }; + tracing::info!( + "read-back buffers per frame: {:.1} made, {:.1} taken from those kept; at their lists' resets {:.1} kept and {:.1} let go; \ + {kept} kept now, {:.1} MB (LEONIDA_READ_BACK_POOL=0: one made for each read back, as before; now {})", + b[0] as f64 / frames, + b[1] as f64 / frames, + b[2] as f64 / frames, + b[3] as f64 / frames, + bytes as f64 / (1 << 20) as f64, + if read_back_pool() { "on" } else { "off" } + ); +} + +/// For the frame-rate line: what [`allocator_trim`] did since the last one, +/// if anything. +fn allocator_trim_line() { + let t: Vec<u64> = ALLOCATOR_TRIMS.iter().map(|t| t.swap(0, Ordering::Relaxed)).collect(); + if t.iter().all(|&n| n == 0) { + return; + } + tracing::info!( + "command allocators taken anew since the last line (LEONIDA_ALLOCATOR_TRIM=1): {} of host lists at their resets, {} of preludes; \ + {} idle host lists let go", + t[0], + t[1], + t[2] + ); +} + +/// For the frame-rate line: what [`batch_pool`] did per frame, if a batch +/// took a buffer or a list gave some back. +fn batch_scratch_line(frames: f64) { + // (Where their passes read their tables: `LEONIDA_BATCH_TABLE_CARD`.) + batch_tables::line(frames); + let b: Vec<u64> = BATCH_SCRATCHES.iter().map(|b| b.swap(0, Ordering::Relaxed)).collect(); + if b.iter().all(|&n| n == 0) { + return; + } + let kept = SPARE_BATCHES.lock().unwrap_or_else(|e| e.into_inner()).len(); + tracing::info!( + "scratch buffers of batched clamps per frame: {:.1} made, {:.1} taken from those kept; at their lists' resets {:.1} kept and \ + {:.1} let go; {kept} kept now, {:.1} MB of the card's memory (LEONIDA_BATCH_SCRATCH_POOL=0: a list keeps all it ever took, \ + as before; now {})", + b[0] as f64 / frames, + b[1] as f64 / frames, + b[2] as f64 / frames, + b[3] as f64 / frames, + (kept as u64 * BATCH_SCRATCH) as f64 / (1 << 20) as f64, + if batch_pool() { "on" } else { "off" } + ); +} + +/// For the frame-rate line: what [`HostList::idle_trim`] let go per frame, +/// if anything. +fn idle_indirect_line(frames: f64) { + let t: Vec<u64> = IDLE_INDIRECT_TRIMS.iter().map(|t| t.swap(0, Ordering::Relaxed)).collect(); + if t[0] == 0 { + return; + } + tracing::info!( + "indirect scratch buffers past 1 MiB let go by idle host lists per frame: {:.2}, {:.2} MB of the card's memory \ + (each made again by the next list that needs it)", + t[0] as f64 / frames, + t[1] as f64 / frames / (1 << 20) as f64 + ); +} + +/// For the frame-rate line: the five that waited longest. +#[cfg(feature = "diagnostics")] +fn log_blame(frames: f64) { + let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); + let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); + let mut all: Vec<_> = all.into_iter().collect(); + all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us)); + for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) { + // The passes that declare it written, the ones that do so most. + let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new(); + for ((a, b, _), (n, shaders)) in &wide { + if *a < at + len && at < *b { + *passes.entry(shaders).or_default() += n; + } + } + let mut passes: Vec<(&str, u64)> = passes.into_iter().collect(); + passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1)); + let passes: Vec<String> = + passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect(); + tracing::info!( + "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \ + over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}", + us as f64 / 1e3 / frames, + n as f64 / frames, + passes.join(", "), + match (why.is_empty(), kind) { + (true, _) => "", + (_, "title memory changed under shader writes") => "; not put in under them: ", + _ => "; not done on the card: ", + }, + ); + } +} + +/// For the frame-rate line: [`DYNAMIC_WAITS`] per frame, if any draw found +/// no slot. +fn dynamic_wait_line(frames: f64) { + let w: Vec<f64> = DYNAMIC_WAITS.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if w[0] <= 0.0 { + return; + } + tracing::info!( + "dynamic descriptor slots: per frame {:.2} draws found none and waited {:.1} ms, {:.2} had their slots after a landing, \ + {:.2} settled everything in the air under the submission lock, {:.2} went without (LEONIDA_DYNAMIC_WAIT=1 waits for the \ + next landing without that lock: now {})", + w[0], + w[1] / 1000.0, + w[2], + w[3], + w[4], + if dynamic_wait() && relay() { "on" } else { "off" } + ); +} + +/// For the frame-rate line, with [`late`]: what the line of flights did +/// per frame since the last one. Also, late or not, the sends straight out +/// of CPU sides (`LEONIDA_SEND_DIRECT`). +pub(super) fn late_line(frames: f64) { + // Whether or not submissions go late or through the relay: a send + // straight out of a CPU side can be in the air at a write of ours + // either way (with the switch off, as `LEONIDA_AB` can turn it, the line + // comes when there was something to count). + let d: Vec<f64> = send::DIRECT_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if send::direct() || d.iter().any(|&n| n > 0.0) { + tracing::info!( + "bytes the card copied straight out of CPU sides per frame (LEONIDA_SEND_DIRECT): {:.1} MB; {:.2} waits for \ + the card before a write of ours into what it was still to copy, {:.2} ms", + d[0] / (1 << 20) as f64, + d[1], + d[2] / 1000.0, + ); + } + // Small title buffers' card sides in card memory the CPU maps. + let m: Vec<f64> = send::MAPPED_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if m.iter().any(|&n| n > 0.0) { + tracing::info!( + "bytes the CPU wrote straight into card sides in card memory it maps per frame (LEONIDA_BAR_BUFFERS_MB): {:.1} MB in {:.0} runs", + m[0] / (1 << 20) as f64, + m[1], + ); + } + if !late() { + return; + } + if upcheck::cross_on() { + let n = CROSS_SETTLES.swap(0, Ordering::Relaxed) as f64 / frames; + tracing::info!("relay cross settles per frame (LEONIDA_RELAY_CROSS=1): {n:.1}"); + } + let s: Vec<f64> = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + // (Of every submission with a compare, sent ahead or waited for.) + let c = compare_ecl::per_frame(frames); + tracing::info!( + "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \ + settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \ + title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \ + a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, room in the compare's results {:.1}, \ + bottom-of-pipe writes (LEONIDA_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \ + {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights; \ + compares of copies in the card's memory sent in their lists' call {:.1}, in a call apart {:.1} (for a copy into a host \ + copy {:.1}, no enhanced barriers {:.1}, the switch off {:.1}; LEONIDA_COMPARE_JOIN {})", + s[0], + s[1], + if s[1] > 0.0 { s[11] / s[1] } else { 0.0 }, + s[12] / 1000.0, + s[WHY_SYNC], + s[WHY_CARD_DONE], + s[WHY_VALUE], + s[WHY_STALE], + s[WHY_READ], + s[15], + s[16], + s[17], + s[WHY_RUN], + late_most(), + s[WHY_MOST], + s[WHY_RESULTS], + s[WHY_WRITES], + s[WHY_FENCE], + s[13], + s[14], + c[0], + c[1], + c[2], + c[3], + c[4], + if compare_ecl::join_asked() { "on" } else { "off" }, + ); + { + let w: Vec<f64> = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect(); + tracing::info!( + "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \ + the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \ + title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, room in the compare's results {:.1}, \ + bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}", + w[WHY_SYNC], + w[WHY_CARD_DONE], + w[WHY_VALUE], + w[WHY_STALE], + w[WHY_READ], + w[WHY_RUN], + w[WHY_MOST], + w[WHY_RESULTS], + w[WHY_WRITES], + w[WHY_FENCE], + ); + } + if relay() { + let r: Vec<f64> = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "the relay per frame (LEONIDA_RELAY=1): {:.1} flights landed in {:.1} landings by the thread that copies back, \ + beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \ + fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \ + \"settles\" above are waits of other threads for it)", + r[1], + r[0], + r[2] / 1000.0, + r[3] / 1000.0, + r[4] / 1000.0, + ); + if send::own() { + let t: Vec<f64> = send::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let (out, kept, buffers) = send::held(); + let made: Vec<f64> = send::MADE_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "bytes of submissions' own sent up per frame (LEONIDA_SEND_OWN): {:.1} MB in {:.0} runs, {:.0} words in scatters; {:.2} ms \ + taking them out of the CPU sides; {} MiB of memory held by submissions not done with, {} MiB kept spare \ + (LEONIDA_SEND_TRIM; with LEONIDA_SEND_RING the free bytes of the ring's open buffer; {} buffers); {:.2} buffers made a frame, {:.1} MiB", + t[0] / (1 << 20) as f64, + t[1], + t[2], + t[3] / 1000.0, + out >> 20, + kept >> 20, + buffers, + made[0], + made[1] / (1 << 20) as f64, + ); + } + let t: Vec<f64> = torn::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if t[0] > 0.0 { + tracing::info!( + "fetched pieces checked per frame (LEONIDA_FETCH_CHECK): {:.1}, of which {:.2} were not what their flight ended with (caught while a later flight was at them, or title bytes went up meanwhile); {:.2} were found whole when fetched again", + t[0], + t[1], + t[2], + ); + } + } + let f: Vec<u64> = fetched::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed)).collect(); + if f.iter().any(|&n| n > 0) { + tracing::info!( + "buffers pieces are fetched to, since the last line (LEONIDA_FETCH_SHRINK): {} made smaller, {} made larger again", + f[0], + f[1], + ); + } + crate::land::log(frames); + if place::on() { + let t: Vec<f64> = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "title buffer copies at their place in the lists, per frame (LEONIDA_COPIES_IN_PLACE): {:.1} of {:.1} KB, {:.1} of them out of what shaders wrote; {:.2} copies into textures out of what shaders wrote", + t[0], + t[1] / 1024.0, + t[2], + t[3], + ); + #[cfg(feature = "diagnostics")] + { + let ahead = place::AHEAD.swap(0, Ordering::Relaxed) as f64 / frames; + if ahead > 0.0 { + tracing::info!( + "copies at their place whose bytes wait for flights, read on the CPU only ahead of them, per frame \ + (LEONIDA_PLACED_READERS; 0 holds these too): {ahead:.2} submissions not held for flights" + ); + } + } + } + card_steps::log(frames); + read_backs_line(frames); + batch_scratch_line(frames); + idle_indirect_line(frames); + allocator_trim_line(); + dynamic_wait_line(frames); + crate::draw::waits_line(frames); + #[cfg(feature = "diagnostics")] + crate::texture::alias_line(frames); + #[cfg(feature = "diagnostics")] + crate::draw::dispatch_sizes_line(frames); + #[cfg(feature = "diagnostics")] + crate::draw::indirect_runs_line(frames); + #[cfg(feature = "diagnostics")] + sync_callers::line(frames); + #[cfg(feature = "diagnostics")] + gate_line(frames); + #[cfg(feature = "diagnostics")] + crate::draw::batch_why_line(frames); + crate::watch::port_guard_line(frames); + #[cfg(feature = "diagnostics")] + crate::watch::fault_asks_line(frames); + #[cfg(feature = "diagnostics")] + retire_waits_line(frames); + #[cfg(feature = "diagnostics")] + buffers_made::line(); + #[cfg(feature = "diagnostics")] + crate::residency::line(); + crate::port_journal::line(frames); + crate::port::log(frames); + crate::port_cbv::log(frames); + crate::picked::log(frames); + #[cfg(feature = "diagnostics")] + log_blame(frames); + if late_exact() { + let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames); + tracing::info!( + "title bytes put in under flights' shader writes per frame (LEONIDA_LATE_WAIT=2): {pages:.0} pages looked at, \ + {runs:.0} changed runs, {:.2} MB", + bytes / (1 << 20) as f64 + ); + } +} + +/// The split of the preparing, per frame, for the frame-rate line. +#[cfg(feature = "diagnostics")] +pub(super) fn split_line(frames: f64) { + let ms: Vec<f64> = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); + let f: Vec<f64> = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let e: Vec<f64> = crate::watch::early_asks().iter().map(|&n| n as f64 / frames).collect(); + let a: Vec<f64> = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect(); + let h: Vec<f64> = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); + let s: Vec<f64> = crate::shadow::send_stats().iter().map(|&n| n as f64 / frames).collect(); + tracing::info!( + "preparing per frame, the submitting thread: {:.1} ms asking the write watch ({:.1} of them finding what to ask), {:.1} putting the title's bytes under flights' \ + writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \ + several threads, {:.1} one at a time in {:.0} before shader writes; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \ + card's memory, {:.1} sending the lists (LEONIDA_LIGHT_REFRESH is {}); ahead of these {:.1} waiting for the submission lock, {:.1} \ + planning steps done on the card, {:.1} waiting for flights, {:.1} the heaps' records and what is swept; at the end {:.1} waiting \ + for the heaps' records; asked early by a thread of its own {:.0} pieces of 2 MiB, {:.1} ms (LEONIDA_ASK_EARLY)", + ms[0], + ms[8], + ms[1], + ms[2], + ms[6], + f[0], + f[1], + f[2], + f[3], + ms[9], + ms[10] * 1e6, + ms[7], + ms[3], + ms[4], + ms[5], + if crate::watch::light() { "on" } else { "off" }, + ms[11], + ms[12], + ms[13], + ms[14], + ms[15], + e[0], + e[1] / 1e3, + ); + let scoped: Vec<f64> = SCOPED.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if copy_scoped() || scoped.iter().any(|&n| n > 0.0) { + tracing::info!( + "title writes of the steps per frame (LEONIDA_COPY_SCOPED is {}): {:.0} forgot only the copies refreshed ahead that they \ + touch (a forgetting of all of them not made), {:.0} copies kept, {:.0} forgotten; {:.0} forgot all of them (shown at too \ + many places)", + if copy_scoped() { "on" } else { "off" }, + scoped[0], + scoped[1], + scoped[3], + scoped[2], + ); + } + tracing::info!( + "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB ({:.1} ms, {:.0} pages of 4 KiB found \ + written, {:.0} askings refused, {:.0} left out for view memory known as such (LEONIDA_VIEWS_UNASKED)); {:.0} \ + allocations looked up to plan the askings by, {:.0} of them unplannable (LEONIDA_ASK_BY_ALLOCATION); {:.0} questions \ + about holes; view ranges: {:.0} answered by their bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks \ + made read-only, {:.0} opened by ourselves; {:.1} ms waiting for the guards, {:.1} ms changing protections; pages taken \ + for the card: {:.1} MB compared, {:.1} MB of them as they were, {:.1} MB to go up in {:.0} runs (LEONIDA_SEND_CHANGED)", + a[0], + a[1] / 1024.0, + a[11] / 1e6, + a[12], + a[10], + a[13], + a[14], + a[15], + a[9], + a[2], + a[3], + a[4], + a[5], + a[6], + a[7] / 1e6, + a[8] / 1e6, + s[0] / 1048576.0, + s[1] / 1048576.0, + s[2] / 1048576.0, + s[3], + ); + // Per pass that asked for its spans. + let [spans, stale, walks, slots, showing] = [0, 1, 2, 3, 4].map(|i| crate::draw::SPAN_WALKS[i].swap(0, Ordering::Relaxed) as f64); + let per = spans.max(1.0); + tracing::info!( + "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures; the \ + first two beside the recording (LEONIDA_HEAP_PASS_ASIDE), {:.1} ms waited for at the lists' close; of its 16 parts a pass made \ + {:.2} parts' spans again from their slots in {:.2} walks over them, {:.0} of its {:.0} slots showing something \ + (LEONIDA_SPANS_ONE_WALK is {})", + h[0], + h[1], + h[2], + aside::WAITED.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames, + stale / per, + walks / per, + showing / per, + slots / per, + if crate::draw::spans_one_walk() { "on" } else { "off" }, + ); +} diff --git a/d3d12/crates/leonida-gpu/src/host/owntimes.rs b/d3d12/crates/leonida-gpu/src/host/owntimes.rs new file mode 100644 index 0000000000..1841f3c167 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/owntimes.rs @@ -0,0 +1,290 @@ +//! Diagnostics: what our own lists over copies in the card's memory +//! ([`crate::shadow::cards`]) take on the card, measured there +//! (`LEONIDA_CARD_OWN_TIMES=1`; off by default, as in a `LEONIDA_AB` run in +//! the world on an RX 7900 XT the stamps cost +2.8 % on the frame median and +//! +2.2 % on the submitting thread, s.e. 1.9 % and 1.2 %). +//! +//! They are two, and in no other table: the list a plan runs ahead of its +//! submission (`Host::card_before`: the ranges sent up, as copies or +//! `send::Own`'s scatter passes, then one barrier call, then the hash passes +//! over the pieces sent up) and the compare after its lists (a barrier on +//! every earlier shader write, a compare pass per joined range, then +//! `landsame`'s passes). The timing run's commands are noted inside the +//! title's host lists only (`note_op`), and the timeline's card spans begin +//! at a stamp behind the first list, so the first shows as idle between +//! submissions and the second in no line at all. Both run on the drawing +//! queue, so with the card the frame (some 35 of 46 ms busy in the world +//! scene, `docs/findings.md`) their time is the frame's. +//! +//! A plan that records either takes a set of five timestamps and a read back +//! of them ([`Set`]); the card writes them where the lists are and resolves +//! them before each list's end; `Host::card_done`, which runs once the +//! plan's submission has, reads them and gives the set back. Slots 0..2: the +//! first list's start, its last send (stamp 1, before the barrier call that +//! precedes the hash passes), its last hash pass. Slots 3..4: the compare's +//! start, after its leading barrier (the drain of the title's lists is the +//! title's, not ours), and its end. A plan without one of the lists leaves +//! its slots unwritten: the words are zeroed when a set is taken and a pair +//! counts only where both stamps are there and the second is not before the +//! first. The card writes a stamp once what was before it in the list has +//! got so far, not necessarily ended: stamp 1 parts the sends from the hash +//! passes as near as the card allows, stamps 0 and 2 frame the whole. +//! +//! Timestamps order nothing and cost the card a write each: the switch is +//! on in every diagnostics run so the A/B phases attribute our time, and +//! `=0` records none. Builds without diagnostics have none of this. + +use std::sync::atomic::AtomicU64; + +use super::*; + +/// The first list's start, its last send, its last hash pass. +const SENDS_FROM: u32 = 0; +const HASHES_FROM: u32 = 1; +const HASHES_TO: u32 = 2; +/// The compare's start (after its leading barrier) and end. +const COMPARE_FROM: u32 = 3; +const COMPARE_TO: u32 = 4; +const SLOTS: u32 = 5; + +/// Whether our lists over copies in the card's memory are timed on the card +/// (`LEONIDA_CARD_OWN_TIMES=1`; off: no queries). +pub(super) fn on() -> bool { + #[cfg(test)] + if let Some(on) = TEST_ON.get() { + return on; + } + crate::asked!("LEONIDA_CARD_OWN_TIMES") +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`on`], for its thread only. + pub(super) static TEST_ON: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; + /// What `Host::card_done` read on this thread last ([`Took`]). + pub(super) static TEST_LAST: std::cell::Cell<Option<Took>> = const { std::cell::Cell::new(None) }; +} + +/// Since the last frame-rate line: microseconds of sends up, of hash passes +/// after them and of compares; first lists and compares measured. +pub(super) static OWN_TIMES: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +/// A plan's timestamps: a heap of [`SLOTS`] and a read back of a tick count +/// each, mapped for good. +pub(super) struct Set { + heap: ID3D12QueryHeap, + back: ID3D12Resource, + /// The read back's mapping. + ticks: usize, + /// The hash passes and compare passes recorded between the stamps (for + /// the tests). + pub(super) passes: [u64; 2], +} + +// SAFETY: D3D12 objects (free-threaded) and a mapping only the plan that +// holds the set reads or writes. +unsafe impl Send for Set {} + +/// What one plan's stamps gave, in microseconds: sends up, hash passes, +/// compare (`None`: that part was not recorded, or its stamps are not there). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) struct Took { + pub(super) sends: Option<u64>, + pub(super) hashes: Option<u64>, + pub(super) compare: Option<u64>, +} + +/// A set for a plan that records one of our lists: one given back, or a new +/// one; with its words zeroed. `None` with `on` false (no queries), or if +/// none can be made (said once; no stamps from then on). +pub(super) fn take(host: &Host, kept: &mut Vec<Set>, on: bool) -> Option<Set> { + static NONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !on || NONE.load(Ordering::Relaxed) { + return None; + } + let set = match kept.pop() { + Some(set) => set, + None => match make(host) { + Ok(set) => set, + Err(e) => { + if !NONE.swap(true, Ordering::Relaxed) { + tracing::warn!(error = %e, "our lists over copies in the card's memory are not timed on the card"); + } + return None; + } + }, + }; + // SAFETY: the mapping holds `SLOTS` tick counts; the plan that had the + // set last was done (its submission ran before it came back). + unsafe { std::ptr::write_bytes(set.ticks as *mut u64, 0, SLOTS as usize) }; + Some(Set { passes: [0; 2], ..set }) +} + +fn make(host: &Host) -> windows::core::Result<Set> { + let back = host.read_back_buffer(u64::from(SLOTS) * 8).ok_or_else(windows::core::Error::empty)?; + name(&back, || "our lists' timestamps, read back".into()); + // SAFETY: plain object creation; a read back in the state resolves need, + // mapped once and kept so. + unsafe { + let mut heap: Option<ID3D12QueryHeap> = None; + host.device.CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: SLOTS, + NodeMask: 0, + }, + &mut heap, + )?; + let heap = heap.ok_or_else(windows::core::Error::empty)?; + let mut ticks = std::ptr::null_mut(); + back.Map(0, None, Some(&mut ticks))?; + if ticks.is_null() { + return Err(windows::core::Error::empty()); + } + Ok(Set { heap, back, ticks: ticks as usize, passes: [0; 2] }) + } +} + +impl Set { + /// The first list begins (right after its reset, before any send). + /// + /// # Safety + /// An open direct list of ours. + pub(super) unsafe fn sends_from(&self, list: &ID3D12GraphicsCommandList) { + // SAFETY: the caller's; a slot of the heap. + unsafe { list.EndQuery(&self.heap, D3D12_QUERY_TYPE_TIMESTAMP, SENDS_FROM) }; + } + + /// The first list's sends are recorded; its hash passes follow. + /// + /// # Safety + /// As [`Set::sends_from`]. + pub(super) unsafe fn hashes_from(&self, list: &ID3D12GraphicsCommandList) { + // SAFETY: the caller's; a slot of the heap. + unsafe { list.EndQuery(&self.heap, D3D12_QUERY_TYPE_TIMESTAMP, HASHES_FROM) }; + } + + /// The first list's last hash pass is recorded (`passes` of them): its + /// three stamps go to the read back. + /// + /// # Safety + /// As [`Set::sends_from`], and the list recorded the two stamps before. + pub(super) unsafe fn hashes_to(&mut self, list: &ID3D12GraphicsCommandList, passes: u64) { + self.passes[0] = passes; + // SAFETY: the caller's; slots of the heap, and their words in the + // read back (8 bytes each, from 0). + unsafe { + list.EndQuery(&self.heap, D3D12_QUERY_TYPE_TIMESTAMP, HASHES_TO); + list.ResolveQueryData(&self.heap, D3D12_QUERY_TYPE_TIMESTAMP, SENDS_FROM, 3, &self.back, 8 * u64::from(SENDS_FROM)); + } + } + + /// The compare begins (after its barrier on every earlier shader write). + /// + /// # Safety + /// As [`Set::sends_from`]. + pub(super) unsafe fn compare_from(&self, list: &ID3D12GraphicsCommandList) { + // SAFETY: the caller's; a slot of the heap. + unsafe { list.EndQuery(&self.heap, D3D12_QUERY_TYPE_TIMESTAMP, COMPARE_FROM) }; + } + + /// The compare's last pass is recorded (`passes` compare passes): its two + /// stamps go to the read back. + /// + /// # Safety + /// As [`Set::sends_from`], and the list recorded [`Set::compare_from`]. + pub(super) unsafe fn compare_to(&mut self, list: &ID3D12GraphicsCommandList, passes: u64) { + self.passes[1] = passes; + // SAFETY: the caller's; slots of the heap, and their words in the + // read back (from 24). + unsafe { + list.EndQuery(&self.heap, D3D12_QUERY_TYPE_TIMESTAMP, COMPARE_TO); + list.ResolveQueryData(&self.heap, D3D12_QUERY_TYPE_TIMESTAMP, COMPARE_FROM, 2, &self.back, 8 * u64::from(COMPARE_FROM)); + } + } + + /// What the stamps say, once the card has run the plan's lists. + fn took(&self, frequency: u64) -> Took { + // SAFETY: the mapping holds `SLOTS` tick counts; the card wrote what + // it wrote of them before the plan's submission was done. + let ticks: [u64; SLOTS as usize] = unsafe { std::ptr::read_volatile(self.ticks as *const [u64; SLOTS as usize]) }; + Took { + sends: between(ticks[SENDS_FROM as usize], ticks[HASHES_FROM as usize], frequency), + hashes: between(ticks[HASHES_FROM as usize], ticks[HASHES_TO as usize], frequency), + compare: between(ticks[COMPARE_FROM as usize], ticks[COMPARE_TO as usize], frequency), + } + } +} + +/// Microseconds from `from` to `to` (card ticks at `frequency` a second); +/// `None` unless both were written and `to` is not before `from`. +fn between(from: u64, to: u64, frequency: u64) -> Option<u64> { + (from != 0 && to != 0 && to >= from && frequency != 0).then(|| (u128::from(to - from) * 1_000_000 / u128::from(frequency)) as u64) +} + +/// `Host::card_done`: the plan's lists have run; what its stamps say goes to +/// the frame-rate line, and in a timing run (`LEONIDA_GPU_TIMING`) to the +/// card's time by command, as `ours sends`, `ours rehash` and `ours compare`. +pub(super) fn read(host: &Host, set: &Set) -> Took { + static FREQUENCY: OnceLock<u64> = OnceLock::new(); + // SAFETY: a plain query. + let frequency = *FREQUENCY.get_or_init(|| unsafe { host.queue.GetTimestampFrequency() }.unwrap_or(0)); + let took = set.took(frequency); + if let (Some(sends), Some(hashes)) = (took.sends, took.hashes) { + OWN_TIMES[0].fetch_add(sends, Ordering::Relaxed); + OWN_TIMES[1].fetch_add(hashes, Ordering::Relaxed); + OWN_TIMES[3].fetch_add(1, Ordering::Relaxed); + } + if let Some(compare) = took.compare { + OWN_TIMES[2].fetch_add(compare, Ordering::Relaxed); + OWN_TIMES[4].fetch_add(1, Ordering::Relaxed); + } + if timing() { + for (what, us) in [("ours sends", took.sends), ("ours rehash", took.hashes), ("ours compare", took.compare)] { + if let Some(us) = us { + crate::copystat::command_took(what, us as f64 / 1e3); + } + } + } + #[cfg(test)] + TEST_LAST.set(Some(took)); + took +} + +/// For the line of our passes over copies in the card's memory: what they +/// took on the card per frame, and whether anything was measured. +pub(super) fn line_part(frames: f64) -> (String, bool) { + let [sends, hashes, compare, synced, checked] = [0, 1, 2, 3, 4].map(|i| OWN_TIMES[i].swap(0, Ordering::Relaxed) as f64); + let ms = |us: f64| us / 1e3 / frames; + ( + format!( + "; on the card per frame: sends up {:.2} ms in {:.1} lists, rehash {:.2} ms, compare {:.2} ms in {:.1} lists \ + (LEONIDA_CARD_OWN_TIMES)", + ms(sends), + synced / frames, + ms(hashes), + ms(compare), + checked / frames + ), + synced + checked > 0.0, + ) +} + +#[cfg(test)] +mod tests { + use super::between; + + /// A pair counts only where both stamps are there, in order; ticks go to + /// microseconds by the card's frequency. + #[test] + fn only_written_pairs_in_order_count() { + assert_eq!(between(1_000, 3_000, 1_000_000), Some(2_000)); + assert_eq!(between(5, 5, 1_000), Some(0)); + assert_eq!(between(0, 3_000, 1_000_000), None, "a start the list never wrote"); + assert_eq!(between(1_000, 0, 1_000_000), None, "an end the list never wrote"); + assert_eq!(between(3_000, 1_000, 1_000_000), None, "an end before the start"); + assert_eq!(between(1, 2, 0), None, "no frequency"); + // Ticks of a 100 MHz clock over a long frame do not overflow. + assert_eq!(between(1, 1 + 100_000_000 * 3_600, 100_000_000), Some(3_600_000_000)); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/place.rs b/d3d12/crates/leonida-gpu/src/host/place.rs index e26386b1db..c0bd21aa31 100644 --- a/d3d12/crates/leonida-gpu/src/host/place.rs +++ b/d3d12/crates/leonida-gpu/src/host/place.rs @@ -62,12 +62,27 @@ pub(super) struct Placed { } impl Placed { + /// For tests: a copy at its place as `HostList::place_copy` records one. + #[cfg(test)] + pub(super) fn for_tests(dst: usize, src: usize, len: usize, shadow: std::sync::Arc<Shadow>, from: Option<usize>) -> Placed { + Placed { dst, src, len, shadow, from } + } + + /// What [`Placed::waits`] goes by, apart from the copy's host copy ([`Fact`]). + pub(super) fn fact(&self) -> Fact { + Fact { + dst: self.dst, + src: self.src, + len: self.len, + takes: self.from.is_some(), + } + } + /// Whether the copy's bytes are the title's own although flights in the air (`written`) declare them /// (`super::placed_is_titles`): the destination by what has landed there, and the source either not /// declared or the title's by the rule for fills (`super::fill_is_titles`). pub(super) fn titles(&self, written: &[(usize, usize)]) -> bool { - super::placed_is_titles(self.dst, self.len, touches(written, self.dst, self.dst + self.len)) - && (!touches(written, self.src, self.src + self.len) || super::fill_is_titles(self.src, self.len)) + self.fact().titles(written) } /// Diagnostics: why [`Placed::titles`] did not take the copy for the title's own, for the wait's name. @@ -88,17 +103,7 @@ impl Placed { /// Whether flights that write `written` are waited for. pub(super) fn waits(&self, written: &[(usize, usize)]) -> Waits { - if self.titles(written) { - return Waits::No; - } - let source = touches(written, self.src, self.src + self.len); - if source && self.from.is_some() { - return Waits::Yes; - } - match source || touches(written, self.dst, self.dst + self.len) { - true => Waits::ForReaders, - false => Waits::No, - } + self.fact().waits(written) } /// At submission, in the order of the steps: the list's upload memory @@ -134,6 +139,41 @@ impl Placed { } } +/// What the CPU's questions about a copy at its place go by: its title addresses and whether it takes its +/// source in upload memory of the list. Fixed when the step is recorded, so a list's summary keeps it +/// (`super::summary`); what flights write and what landed lately are asked when it is looked at. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Fact { + pub(super) dst: usize, + pub(super) src: usize, + pub(super) len: usize, + /// The list copies from its own upload memory, which takes the source's bytes on the CPU. + pub(super) takes: bool, +} + +impl Fact { + /// [`Placed::titles`]. + pub(super) fn titles(&self, written: &[(usize, usize)]) -> bool { + super::placed_is_titles(self.dst, self.len, touches(written, self.dst, self.dst + self.len)) + && (!touches(written, self.src, self.src + self.len) || super::fill_is_titles(self.src, self.len)) + } + + /// [`Placed::waits`]. + pub(super) fn waits(&self, written: &[(usize, usize)]) -> Waits { + if self.titles(written) { + return Waits::No; + } + let source = touches(written, self.src, self.src + self.len); + if source && self.takes { + return Waits::Yes; + } + match source || touches(written, self.dst, self.dst + self.len) { + true => Waits::ForReaders, + false => Waits::No, + } + } +} + /// Whether a copy waits for flights before its submission is prepared: not; /// yes, as it takes a source on the CPU that they may write; or only if /// another step of the submission reads its destination on the CPU. @@ -246,13 +286,11 @@ pub(super) fn reader( }) } -/// Everything recorded so far is done, and seen, before what follows. -/// -/// # Safety -/// An open list. -unsafe fn wait_for_all(host: &Host, list: &ID3D12GraphicsCommandList) { +/// Whether the host's card has enhanced barriers (`D3D12_OPTIONS12`), asked +/// once: [`wait_for_all`] is then one global barrier. +pub(super) fn enhanced_barriers(host: &Host) -> bool { static ENHANCED: OnceLock<bool> = OnceLock::new(); - let enhanced = *ENHANCED.get_or_init(|| { + *ENHANCED.get_or_init(|| { let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); // SAFETY: a feature structure of its size. let known = unsafe { @@ -263,7 +301,15 @@ unsafe fn wait_for_all(host: &Host, list: &ID3D12GraphicsCommandList) { ) }; known.is_ok() && o.EnhancedBarriersSupported.as_bool() - }); + }) +} + +/// Everything recorded so far is done, and seen, before what follows. +/// +/// # Safety +/// An open list. +pub(super) unsafe fn wait_for_all(host: &Host, list: &ID3D12GraphicsCommandList) { + let enhanced = enhanced_barriers(host); // SAFETY: the caller's. unsafe { if enhanced && let Ok(list) = list.cast::<ID3D12GraphicsCommandList7>() { @@ -363,6 +409,9 @@ impl HostList { }, (None, None) => return false, } + // (`to.buffer` may be left in `COPY_DEST` to the end of the call that + // sends the list: the submission's compare keeps a call of its own.) + self.copied_into_copy(); unsafe { wait_for_all(host, &self.list) }; STATS[0].fetch_add(1, Ordering::Relaxed); STATS[1].fetch_add(len as u64, Ordering::Relaxed); diff --git a/d3d12/crates/leonida-gpu/src/host/placement.rs b/d3d12/crates/leonida-gpu/src/host/placement.rs new file mode 100644 index 0000000000..0eb65e266c --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/placement.rs @@ -0,0 +1,976 @@ +//! Where memory the CPU fills and the card reads is best put on this PC: a +//! measurement, not a check (it asserts only that the card read the bytes +//! the CPU wrote). Every decision that leaves card memory the CPU maps +//! (`LEONIDA_SEND_BAR`, `LEONIDA_WINDOWS_BAR_MB`) and title memory in place +//! (`LEONIDA_INPLACE`, `LEONIDA_PORT_CONSTANTS`) off was measured on an +//! NVIDIA card or the software adapter (send.rs `on_card`, findings.md); +//! this asks the same of whatever card the host device is on. +//! +//! For buffers of 1, 16 and 256 MiB in each placement: +//! +//! - **default via upload**: the CPU fills an upload buffer and the card +//! copies it into a device-local one (the card side of a card copy and +//! the staging of textures); the copy is the "card copy" column, the +//! shader then reads the device-local buffer; +//! - **upload**: `D3D12_HEAP_TYPE_UPLOAD`, write-combined system memory +//! (submission sends, texture staging); +//! - **GPU upload**: `D3D12_HEAP_TYPE_GPU_UPLOAD`, card memory the CPU maps +//! through a resizable BAR (`Host::mapped_card_buffer`), if +//! `D3D12_OPTIONS16.GPUUploadHeapSupported`; +//! - **custom L0 write-back**: cached system memory (`Host::shared_buffer`, +//! the host copies of title buffers and windows); +//! - **opened**: plain `VirtualAlloc` memory opened with +//! `OpenExistingHeapFromAddress` and a buffer placed over it, as title +//! memory in place is (`inplace::open`, `inplace::place`); the opening +//! itself is timed too. +//! +//! What is timed, median of [`RUNS`] after one run to warm up: +//! +//! 1. the CPU filling the buffer from cached memory of its own, with the +//! C runtime's `memcpy` (what `copy_nonoverlapping` calls, and what +//! `send::take` and `Shadow::copy` do) and with non-temporal stores +//! (`vmovntdq`, 32 bytes a store, one thread); +//! 2. the card reading it, on a direct queue (where the runtime's card +//! copies run) between timestamps, in two submissions so that the +//! shader's first read is not of what the copy left in the card's caches: +//! a `CopyBufferRegion` into a device-local buffer; then, the CPU having +//! written the buffer again, a compute shader that reads every byte in +//! coalesced 16-byte loads (a grid-stride loop over 1,024 groups of 256) +//! and folds them into one XOR, compared with the CPU's, twice in a row +//! ("again": what a second reader in the same submission pays); +//! 3. the CPU reading the mapping back ([`READ_RUNS`] times), with ordinary +//! loads (what `send_changed`'s compares or a snapshot do) and with SSE4.1 +//! streaming loads (`movntdqa`, the one way to read write-combined memory +//! a line at a time). +//! +//! The 1 MiB buffers fit the card's L2 (6 MB on an RX 7900 XT) and every +//! size up to 16 MiB its last-level cache (80 MB) and the CPU's L3 (32 MB on +//! a Ryzen 7 5800X); 256 MiB fits none of them. The CPU-side figures move +//! with whatever else the PC runs (single-threaded, bound by its memory). +//! +//! The test binary exports no `D3D12SDKVersion`, so it runs on Windows' own +//! `D3D12Core.dll`, not the Agility SDK `Get-D3D12.cmd` fetches (1.614.1) +//! for `leonida.exe`; the output names the one loaded and its SDK version. +//! +//! The GPU upload rows are there only where Direct3D offers GPU upload heaps +//! (`crate::host::bar`, whose line opens the output and the log): on a card, +//! where the firmware has resized its memory window, and on the software +//! adapter (`LEONIDA_D3D12_WARP=1`), whose heaps of that type are the PC's +//! memory and have no BAR behind them. Then the output ends with them side +//! by side with upload memory and custom L0 write-back at each size; on a +//! card those are the numbers that decide `LEONIDA_SEND_BAR`, +//! `LEONIDA_WINDOWS_BAR_MB` and `LEONIDA_BAR_BUFFERS_MB` on this PC. Without +//! such heaps it says why there are none. +//! +//! Run by name, no game needed (release: the CPU loops are ours): +//! `cargo test -p leonida-gpu --release --lib host::placement -- --ignored --nocapture` + +use std::ffi::c_void; +use std::time::Instant; + +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::System::LibraryLoader::{GetModuleFileNameW, GetProcAddress}; +use windows::core::{PCSTR, s}; +use windows_sys::Win32::System::Memory as mem; + +use super::*; + +/// The sizes measured. +const SIZES: [usize; 3] = [1 << 20, 16 << 20, 256 << 20]; +/// Runs of each measurement after the one that warms up. +const RUNS: usize = 15; +/// Runs of the CPU reading back (write-combined memory reads slowly). +const READ_RUNS: usize = 3; +/// Groups of the reading shader, and threads in a group. +const GROUPS: u32 = 1024; +const GROUP: u32 = 256; +/// The unit heaps are opened on. +const K64: usize = 64 << 10; + +const READER: &str = r#" +#define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)" +cbuffer Bounds : register(b0) { +uint vectors; +uint threads; +}; +ByteAddressBuffer src : register(t0); +RWByteAddressBuffer folded : register(u0); +groupshared uint4 part[256]; +[RootSignature(RS)] +[numthreads(256, 1, 1)] +void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { +uint4 acc = uint4(0, 0, 0, 0); +for (uint i = id.x; i < vectors; i += threads) { + acc ^= src.Load4(i * 16); +} +part[gi] = acc; +GroupMemoryBarrierWithGroupSync(); +[unroll] +for (uint s = 128; s > 0; s >>= 1) { + if (gi < s) { + part[gi] ^= part[gi + s]; + } + GroupMemoryBarrierWithGroupSync(); +} +if (gi == 0) { + uint was; + folded.InterlockedXor(0, part[0].x, was); + folded.InterlockedXor(4, part[0].y, was); + folded.InterlockedXor(8, part[0].z, was); + folded.InterlockedXor(12, part[0].w, was); +} +} +"#; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Place { + DefaultViaUpload, + Upload, + GpuUpload, + CustomL0, + Opened, +} + +impl Place { + fn name(self) -> &'static str { + match self { + Place::DefaultViaUpload => "default via upload", + Place::Upload => "upload", + Place::GpuUpload => "GPU upload (BAR)", + Place::CustomL0 => "custom L0 write-back", + Place::Opened => "opened (FromAddress)", + } + } +} + +/// One placement of one size: what the CPU writes, what the card reads. +/// (Fields drop in this order: the buffers and the heap before the memory +/// they stand on.) +struct Placed { + /// Mapped (or the `VirtualAlloc`ed memory), filled by the CPU. + cpu: *mut u8, + /// What the CPU's address is in, for the card (the upload staging for + /// default via upload). + filled: ID3D12Resource, + /// The device-local buffer default via upload copies into. + target: Option<ID3D12Resource>, + _heap: Option<ID3D12Heap>, + /// Milliseconds the opening took. + opened_ms: Option<f64>, + _alloc: Option<Alloc>, +} + +/// Memory of our own from `VirtualAlloc`, released when dropped. +struct Alloc(*mut c_void); + +impl Drop for Alloc { + fn drop(&mut self) { + // An opened heap lets go of the pages a moment after its last + // reference (inplace.rs's test waits the same way). + for _ in 0..500 { + // SAFETY: our own allocation; nothing refers to it any more. + if unsafe { mem::VirtualFree(self.0, 0, mem::MEM_RELEASE) } != 0 { + return; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + } +} + +fn desc(size: usize, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + } +} + +/// A committed buffer, mapped if the heap lets the CPU map it. +fn committed( + device: &ID3D12Device, + heap: D3D12_HEAP_PROPERTIES, + size: usize, + state: D3D12_RESOURCE_STATES, + flags: D3D12_RESOURCE_FLAGS, + map: bool, +) -> windows::core::Result<(ID3D12Resource, *mut u8)> { + let mut made: Option<ID3D12Resource> = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping with valid descriptions. + unsafe { + device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc(size, flags), + state, + None, + &mut made, + )?; + let made = made.ok_or_else(windows::core::Error::empty)?; + if map { + made.Map(0, None, Some(&mut data))?; + } + Ok((made, data.cast())) + } +} + +fn heap(kind: D3D12_HEAP_TYPE) -> D3D12_HEAP_PROPERTIES { + D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + } +} + +fn make(device: &ID3D12Device, place: Place, size: usize) -> windows::core::Result<Placed> { + let plain = |filled: ID3D12Resource, cpu: *mut u8| Placed { + cpu, + filled, + target: None, + _heap: None, + opened_ms: None, + _alloc: None, + }; + let none = D3D12_RESOURCE_FLAG_NONE; + let common = D3D12_RESOURCE_STATE_COMMON; + match place { + Place::DefaultViaUpload => { + let (staging, cpu) = committed( + device, + heap(D3D12_HEAP_TYPE_UPLOAD), + size, + D3D12_RESOURCE_STATE_GENERIC_READ, + none, + true, + )?; + let (target, _) = committed( + device, + heap(D3D12_HEAP_TYPE_DEFAULT), + size, + common, + none, + false, + )?; + Ok(Placed { + target: Some(target), + ..plain(staging, cpu) + }) + } + Place::Upload => { + let (b, cpu) = committed( + device, + heap(D3D12_HEAP_TYPE_UPLOAD), + size, + D3D12_RESOURCE_STATE_GENERIC_READ, + none, + true, + )?; + Ok(plain(b, cpu)) + } + Place::GpuUpload => { + let (b, cpu) = committed( + device, + heap(D3D12_HEAP_TYPE_GPU_UPLOAD), + size, + common, + none, + true, + )?; + Ok(plain(b, cpu)) + } + Place::CustomL0 => { + let props = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let (b, cpu) = committed(device, props, size, common, none, true)?; + Ok(plain(b, cpu)) + } + Place::Opened => { + let bytes = size.div_ceil(K64) * K64; + // SAFETY: an allocation of our own, released in `Drop`. + let alloc = unsafe { + mem::VirtualAlloc( + std::ptr::null(), + bytes, + mem::MEM_RESERVE | mem::MEM_COMMIT, + mem::PAGE_READWRITE, + ) + }; + if alloc.is_null() { + return Err(windows::core::Error::from_thread()); + } + let alloc = Alloc(alloc); + let began = Instant::now(); + let (buffer, h) = + crate::inplace::open(device, crate::inplace::From::Region(alloc.0 as usize)) + .and_then(|h| Ok((crate::inplace::place(device, &h, 0, bytes as u64)?, h)))?; + Ok(Placed { + cpu: alloc.0.cast(), + filled: buffer, + target: None, + _heap: Some(h), + opened_ms: Some(began.elapsed().as_secs_f64() * 1e3), + _alloc: Some(alloc), + }) + } + } +} + +/// `len` bytes from `src` to `dst` in non-temporal stores of 32 bytes. +/// +/// # Safety +/// AVX is there, `dst` is 32-byte aligned, `len` is a multiple of 128, and +/// both ranges are valid. +#[target_feature(enable = "avx")] +unsafe fn copy_streaming(src: *const u8, dst: *mut u8, len: usize) { + use std::arch::x86_64::*; + let mut at = 0; + while at < len { + // SAFETY: the caller's ranges and alignment. + unsafe { + let a = _mm256_loadu_si256(src.add(at).cast()); + let b = _mm256_loadu_si256(src.add(at + 32).cast()); + let c = _mm256_loadu_si256(src.add(at + 64).cast()); + let d = _mm256_loadu_si256(src.add(at + 96).cast()); + _mm256_stream_si256(dst.add(at).cast(), a); + _mm256_stream_si256(dst.add(at + 32).cast(), b); + _mm256_stream_si256(dst.add(at + 64).cast(), c); + _mm256_stream_si256(dst.add(at + 96).cast(), d); + } + at += 128; + } + _mm_sfence(); +} + +/// The sum of `len` bytes read with ordinary loads. +fn read_plain(src: *const u8, len: usize) -> u64 { + // SAFETY: the caller's mapping, `len` a multiple of 8. + let words = unsafe { std::slice::from_raw_parts(src.cast::<u64>(), len / 8) }; + words.iter().fold(0u64, |a, &w| a.wrapping_add(w)) +} + +/// The XOR of `len` bytes read with streaming loads of 16 bytes. +/// +/// # Safety +/// SSE4.1 is there, `src` is 16-byte aligned and `len` a multiple of 64. +#[target_feature(enable = "sse4.1")] +unsafe fn read_streaming(src: *const u8, len: usize) -> u64 { + use std::arch::x86_64::*; + let mut acc = _mm_setzero_si128(); + let mut at = 0; + while at < len { + // SAFETY: the caller's range and alignment. + unsafe { + let a = _mm_stream_load_si128(src.add(at).cast()); + let b = _mm_stream_load_si128(src.add(at + 16).cast()); + let c = _mm_stream_load_si128(src.add(at + 32).cast()); + let d = _mm_stream_load_si128(src.add(at + 48).cast()); + acc = _mm_xor_si128(acc, _mm_xor_si128(_mm_xor_si128(a, b), _mm_xor_si128(c, d))); + } + at += 64; + } + let mut out = [0u64; 2]; + // SAFETY: 16 bytes into an array of 16. + unsafe { _mm_storeu_si128(out.as_mut_ptr().cast(), acc) }; + out[0] ^ out[1] +} + +/// The XOR of every 16-byte vector, as the shader folds them. +fn fold(bytes: &[u8]) -> [u32; 4] { + let mut acc = [0u32; 4]; + for v in bytes.chunks_exact(16) { + for (k, a) in acc.iter_mut().enumerate() { + *a ^= u32::from_le_bytes(v[k * 4..k * 4 + 4].try_into().unwrap()); + } + } + acc +} + +/// Median, least and most. +fn spread(v: &mut [f64]) -> [f64; 3] { + v.sort_by(f64::total_cmp); + [v[v.len() / 2], v[0], v[v.len() - 1]] +} + +/// GB/s (10^9 bytes a second). +fn rate(bytes: usize, seconds: f64) -> f64 { + bytes as f64 / seconds / 1e9 +} + +fn compile_reader() -> Vec<u8> { + let mut code: Option<ID3DBlob> = None; + let mut errors: Option<ID3DBlob> = None; + // SAFETY: the source and names outlive the call. + unsafe { + let made = D3DCompile( + READER.as_ptr().cast(), + READER.len(), + s!("placement"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + Some(&mut errors), + ); + if let Err(e) = made { + let text = errors.map(|b| { + String::from_utf8_lossy(std::slice::from_raw_parts( + b.GetBufferPointer().cast::<u8>(), + b.GetBufferSize(), + )) + .into_owned() + }); + panic!("the reader does not compile: {e} {text:?}"); + } + let code = code.unwrap(); + std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()) + .to_vec() + } +} + +/// The `D3D12Core.dll` this process loaded, and its `D3D12SDKVersion`. +fn runtime() -> String { + // SAFETY: plain module queries on a module the device keeps loaded. + unsafe { + let Ok(module) = GetModuleHandleW(w!("D3D12Core.dll")) else { + return "no D3D12Core.dll loaded".to_owned(); + }; + let mut path = [0u16; 520]; + let len = GetModuleFileNameW(Some(module), &mut path) as usize; + let path = String::from_utf16_lossy(&path[..len]); + let version = GetProcAddress(module, PCSTR(c"D3D12SDKVersion".as_ptr().cast())) + .map(|f| *(f as *const u32)); + format!("{path}, D3D12SDKVersion {version:?}") + } +} + +/// Adapter, driver, memory and the features that matter here. +fn describe(device: &ID3D12Device) -> Vec<String> { + let mut lines = Vec::new(); + // SAFETY: plain DXGI and feature queries into structures of their size. + unsafe { + let adapter = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| f.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid())); + if let Ok(a) = &adapter { + if let Ok(d) = a.GetDesc1() { + let len = d + .Description + .iter() + .position(|&c| c == 0) + .unwrap_or(d.Description.len()); + let driver = a.CheckInterfaceSupport(&IDXGIDevice::IID).unwrap_or(0); + lines.push(format!( + "adapter {} (vendor {:04x} device {:04x}), driver {}.{}.{}.{}, \ + {} MiB of its own memory, {} MiB shared", + String::from_utf16_lossy(&d.Description[..len]), + d.VendorId, + d.DeviceId, + (driver >> 48) & 0xffff, + (driver >> 32) & 0xffff, + (driver >> 16) & 0xffff, + driver & 0xffff, + d.DedicatedVideoMemory >> 20, + d.SharedSystemMemory >> 20, + )); + } + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + if a.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .is_ok() + { + lines.push(format!("budget of its own memory {} MiB", own.Budget >> 20)); + } + } + let mut o16 = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); + let o16_ok = device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS16, + (&raw mut o16).cast(), + size_of_val(&o16) as u32, + ) + .is_ok(); + let mut arch = D3D12_FEATURE_DATA_ARCHITECTURE1::default(); + let arch_ok = device + .CheckFeatureSupport( + D3D12_FEATURE_ARCHITECTURE1, + (&raw mut arch).cast(), + size_of_val(&arch) as u32, + ) + .is_ok(); + lines.push(format!( + "OPTIONS16 answered {o16_ok}, GPUUploadHeapSupported {}; ARCHITECTURE1 answered {arch_ok}, \ + UMA {} CacheCoherentUMA {}", + o16.GPUUploadHeapSupported.as_bool(), + arch.UMA.as_bool(), + arch.CacheCoherentUMA.as_bool() + )); + lines.push(format!( + "runtime {}; ID3D12Device13 (OpenExistingHeapFromAddress1) {}", + runtime(), + device.cast::<ID3D12Device13>().is_ok() + )); + } + lines.push(super::bar::line(device)); + lines.push(format!( + "CPU: AVX {}, SSE4.1 {}", + std::is_x86_feature_detected!("avx"), + std::is_x86_feature_detected!("sse4.1") + )); + lines +} + +/// What one placement of one size measured, in GB/s: median, least and +/// most (`None`: the CPU does not map it). +struct Row { + fill_memcpy: [f64; 3], + fill_streaming: [f64; 3], + card_copy: [f64; 3], + card_read: [f64; 3], + card_again: [f64; 3], + read_plain: Option<[f64; 3]>, + read_streaming: Option<[f64; 3]>, + opened_ms: Option<f64>, +} + +#[test] +#[ignore = "benchmark; see the module notes"] +fn bench_host_memory_placement() { + let Some(host) = super::host() else { + eprintln!("no host GPU"); + return; + }; + assert!( + std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("sse4.1"), + "the streaming loops need AVX and SSE4.1" + ); + let device = &host.device; + for line in describe(device) { + eprintln!("{line}"); + } + let gpu_upload = host.mapped_card_memory(); + // SAFETY: plain D3D12 object creation and use with valid descriptions; + // every object outlives the lists recorded with it, and each list is + // waited for before what it used is touched again. + unsafe { + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .unwrap(); + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .unwrap(); + list.Close().unwrap(); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + let frequency = queue.GetTimestampFrequency().unwrap() as f64; + let mut submitted = 0u64; + + let reader = compile_reader(); + let root: ID3D12RootSignature = device.CreateRootSignature(0, &reader).unwrap(); + let pso: ID3D12PipelineState = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: reader.as_ptr().cast(), + BytecodeLength: reader.len(), + }, + ..Default::default() + }) + .unwrap(); + let stamps: ID3D12QueryHeap = { + let mut heap: Option<ID3D12QueryHeap> = None; + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 3, + NodeMask: 0, + }, + &mut heap, + ) + .unwrap(); + heap.unwrap() + }; + let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + let common = D3D12_RESOURCE_STATE_COMMON; + let (folded, _) = committed( + device, + heap(D3D12_HEAP_TYPE_DEFAULT), + 256, + common, + uav, + false, + ) + .unwrap(); + let (zeros, zeros_ptr) = committed( + device, + heap(D3D12_HEAP_TYPE_UPLOAD), + 256, + D3D12_RESOURCE_STATE_GENERIC_READ, + D3D12_RESOURCE_FLAG_NONE, + true, + ) + .unwrap(); + std::ptr::write_bytes(zeros_ptr, 0, 256); + let (back, back_ptr) = committed( + device, + heap(D3D12_HEAP_TYPE_READBACK), + 256, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_FLAG_NONE, + true, + ) + .unwrap(); + + let places = [ + Place::DefaultViaUpload, + Place::Upload, + Place::GpuUpload, + Place::CustomL0, + Place::Opened, + ]; + let mut table: Vec<(Place, usize, Option<Row>, String)> = Vec::new(); + for size in SIZES { + // What the CPU fills from: cached memory of its own, touched. + let source: Vec<u8> = (0..size) + .map(|i| (i as u32).wrapping_mul(2_654_435_761).to_le_bytes()[i & 3]) + .collect(); + let expected = fold(&source); + let (sink, _) = committed( + device, + heap(D3D12_HEAP_TYPE_DEFAULT), + size, + common, + uav, + false, + ) + .unwrap(); + let vectors = (size / 16) as u32; + let groups = GROUPS.min(vectors.div_ceil(GROUP)); + let threads = groups * GROUP; + for place in places { + if place == Place::GpuUpload && !gpu_upload { + table.push(( + place, + size, + None, + "not offered: GPUUploadHeapSupported is false".to_owned(), + )); + continue; + } + let placed = match make(device, place, size) { + Ok(p) => p, + Err(e) => { + table.push((place, size, None, format!("not made: {e}"))); + continue; + } + }; + let mut fills = [Vec::new(), Vec::new()]; + let mut card = [Vec::new(), Vec::new(), Vec::new()]; + let mut reads = [Vec::new(), Vec::new()]; + for run in 0..=RUNS { + let t = Instant::now(); + std::ptr::copy_nonoverlapping(source.as_ptr(), placed.cpu, size); + let memcpy_s = t.elapsed().as_secs_f64(); + let t = Instant::now(); + copy_streaming(source.as_ptr(), placed.cpu, size); + let streaming_s = t.elapsed().as_secs_f64(); + + // The card, in two submissions so that the shader's + // first read is not of what the copy left in the card's + // caches: the copy, then the shader reading twice. + let mut submit = |record: &dyn Fn(&ID3D12GraphicsCommandList)| -> [u64; 3] { + allocator.Reset().unwrap(); + list.Reset(&allocator, None).unwrap(); + record(&list); + list.ResolveQueryData(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 3, &back, 0); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some( + list.cast::<ID3D12CommandList>().unwrap(), + )]); + submitted += 1; + queue.Signal(&fence, submitted).unwrap(); + fence.SetEventOnCompletion(submitted, event).unwrap(); + WaitForSingleObject(event, INFINITE); + assert!( + device.GetDeviceRemovedReason().is_ok(), + "the device was removed reading {}", + place.name() + ); + let t = std::slice::from_raw_parts(back_ptr.cast::<u64>(), 3); + [t[0], t[1], t[2]] + }; + let t = submit(&|list| { + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + // Into the device-local buffer the shader then reads + // (default via upload), or into one of ours. + let to = placed.target.as_ref().unwrap_or(&sink); + list.CopyBufferRegion(to, 0, &placed.filled, 0, size as u64); + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 2); + }); + let copy_s = t[1].saturating_sub(t[0]) as f64 / frequency; + if placed.target.is_none() { + // Written again, as by the CPU before a submission. + std::ptr::copy_nonoverlapping(source.as_ptr(), placed.cpu, size); + } + let read_from = placed.target.as_ref().unwrap_or(&placed.filled); + let t = submit(&|list| { + list.CopyBufferRegion(&folded, 0, &zeros, 0, 32); + list.ResourceBarrier(&[transition( + &folded, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + let bounds = [vectors, threads]; + list.SetComputeRoot32BitConstants(0, 2, bounds.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, read_from.GetGPUVirtualAddress()); + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + for k in 0..2u64 { + list.SetComputeRootUnorderedAccessView( + 2, + folded.GetGPUVirtualAddress() + 16 * k, + ); + list.Dispatch(groups, 1, 1); + // The second read starts when the first has + // ended, so that each is timed alone. + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1 + k as u32); + } + list.ResourceBarrier(&[transition( + &folded, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + list.CopyBufferRegion(&back, 64, &folded, 0, 32); + list.ResourceBarrier(&[transition( + &folded, + D3D12_RESOURCE_STATE_COPY_SOURCE, + common, + )]); + }); + let read_s = t[1].saturating_sub(t[0]) as f64 / frequency; + let again_s = t[2].saturating_sub(t[1]) as f64 / frequency; + let got = std::slice::from_raw_parts(back_ptr.add(64).cast::<[u32; 4]>(), 2); + assert_eq!( + got, + [expected; 2], + "the card read other bytes than the CPU wrote ({}, {} MiB)", + place.name(), + size >> 20 + ); + + // The CPU reading back, where it maps the memory. + let readable = placed.target.is_none(); + let (plain_s, streamed_s) = if readable && run <= READ_RUNS { + let t = Instant::now(); + std::hint::black_box(read_plain(placed.cpu, size)); + let plain_s = t.elapsed().as_secs_f64(); + let t = Instant::now(); + std::hint::black_box(read_streaming(placed.cpu, size)); + (plain_s, t.elapsed().as_secs_f64()) + } else { + (0.0, 0.0) + }; + if run == 0 { + continue; + } + fills[0].push(rate(size, memcpy_s)); + fills[1].push(rate(size, streaming_s)); + card[0].push(rate(size, copy_s)); + card[1].push(rate(size, read_s)); + card[2].push(rate(size, again_s)); + if plain_s > 0.0 { + reads[0].push(rate(size, plain_s)); + reads[1].push(rate(size, streamed_s)); + } + } + let read = |v: &mut Vec<f64>| (!v.is_empty()).then(|| spread(v)); + let row = Row { + fill_memcpy: spread(&mut fills[0]), + fill_streaming: spread(&mut fills[1]), + card_copy: spread(&mut card[0]), + card_read: spread(&mut card[1]), + card_again: spread(&mut card[2]), + read_plain: read(&mut reads[0]), + read_streaming: read(&mut reads[1]), + opened_ms: placed.opened_ms, + }; + let say = |s: Option<[f64; 3]>| { + s.map_or("-".to_owned(), |[m, lo, hi]| { + format!("{m:.2} ({lo:.2}-{hi:.2})") + }) + }; + eprintln!( + "{:<22} {:>3} MiB: fill memcpy {}, NT {}; card copy {}, shader read {}, again {}; \ + CPU read {}, streaming {} GB/s", + place.name(), + size >> 20, + say(Some(row.fill_memcpy)), + say(Some(row.fill_streaming)), + say(Some(row.card_copy)), + say(Some(row.card_read)), + say(Some(row.card_again)), + say(row.read_plain), + say(row.read_streaming) + ); + table.push((place, size, Some(row), String::new())); + } + } + + let gbs = |v: Option<[f64; 3]>| v.map_or("-".to_owned(), |v| format!("{:.2}", v[0])); + eprintln!(); + eprintln!( + "| Placement | Size | CPU fill, memcpy | CPU fill, NT stores | Card copy to DEFAULT | \ + Card shader read | Card shader read again | CPU read, plain | CPU read, streaming |" + ); + eprintln!("|---|---|---|---|---|---|---|---|---|"); + for (place, size, row, why) in &table { + match row { + Some(r) => { + let name = match r.opened_ms { + Some(ms) => format!("{} (opening {ms:.1} ms)", place.name()), + None => place.name().to_owned(), + }; + eprintln!( + "| {name} | {} MiB | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {} | {} |", + size >> 20, + r.fill_memcpy[0], + r.fill_streaming[0], + r.card_copy[0], + r.card_read[0], + r.card_again[0], + gbs(r.read_plain), + gbs(r.read_streaming) + ); + } + None => eprintln!("| {} | {} MiB | {why} ||||||| ", place.name(), size >> 20), + } + } + eprintln!( + "(GB/s, 10^9 bytes a second, medians of {RUNS} runs; CPU reads of {READ_RUNS}. \ + Default via upload: the fills go to its upload staging, the card copy is staging \ + into the device-local buffer, the shader reads the device-local buffer.)" + ); + eprintln!(); + for line in gpu_upload_lines(gpu_upload, &table) { + eprintln!("{line}"); + } + } +} + +/// The GPU upload rows beside those they would replace, one line a size; +/// or, without them, why there are none. +fn gpu_upload_lines(offered: bool, table: &[(Place, usize, Option<Row>, String)]) -> Vec<String> { + if !offered { + return vec![ + "No GPU upload (BAR) rows: GPUUploadHeapSupported is false (see the resizable BAR line above): \ + LEONIDA_SEND_BAR, LEONIDA_WINDOWS_BAR_MB and LEONIDA_BAR_BUFFERS_MB fall back to the PC's memory here." + .to_owned(), + ]; + } + let row = |place: Place, size: usize| { + table.iter().find(|(p, s, ..)| *p == place && *s == size).and_then(|(_, _, row, _)| row.as_ref()) + }; + let mut lines = vec!["GPU upload (BAR) against the placements it would replace, medians in GB/s:".to_owned()]; + let mut sizes: Vec<usize> = table.iter().map(|(_, s, ..)| *s).collect(); + sizes.dedup(); + for size in sizes { + let Some(bar) = row(Place::GpuUpload, size) else { + let why = table.iter().find(|(p, s, ..)| *p == Place::GpuUpload && *s == size).map_or("", |t| t.3.as_str()); + lines.push(format!(" {:>3} MiB: GPU upload not measured ({why})", size >> 20)); + continue; + }; + let other = |place: Place, pick: fn(&Row) -> f64| row(place, size).map_or("-".to_owned(), |r| format!("{:.2}", pick(r))); + lines.push(format!( + " {:>3} MiB: card shader read {:.2} (upload {}, custom L0 {}, device-local {}); again {:.2}; \ + CPU fill {:.2} (upload {}, custom L0 {}); CPU plain read {} (never done on these: write-combined)", + size >> 20, + bar.card_read[0], + other(Place::Upload, |r| r.card_read[0]), + other(Place::CustomL0, |r| r.card_read[0]), + other(Place::DefaultViaUpload, |r| r.card_read[0]), + bar.card_again[0], + bar.fill_memcpy[0], + other(Place::Upload, |r| r.fill_memcpy[0]), + other(Place::CustomL0, |r| r.fill_memcpy[0]), + bar.read_plain.map_or("-".to_owned(), |r| format!("{:.2}", r[0])), + )); + } + lines +} + +#[cfg(test)] +mod lines_tests { + use super::*; + + fn row(read: f64, fill: f64) -> Option<Row> { + Some(Row { + fill_memcpy: [fill; 3], + fill_streaming: [fill; 3], + card_copy: [1.0; 3], + card_read: [read; 3], + card_again: [read; 3], + read_plain: Some([0.15; 3]), + read_streaming: Some([5.0; 3]), + opened_ms: None, + }) + } + + /// Where GPU upload heaps are offered the output ends with their rows + /// beside upload, custom L0 and device-local memory at each size; where + /// not, with one line that says so (the table alone said "not offered" + /// in a cell, easy to miss). + #[test] + fn the_gpu_upload_rows_are_said_side_by_side() { + let m = 1 << 20; + let table = vec![ + (Place::DefaultViaUpload, m, row(300.0, 28.0), String::new()), + (Place::Upload, m, row(26.0, 27.0), String::new()), + (Place::GpuUpload, m, row(250.0, 20.0), String::new()), + (Place::CustomL0, m, row(25.5, 28.5), String::new()), + (Place::GpuUpload, 16 * m, None, "not made: E_OUTOFMEMORY".to_owned()), + ]; + let lines = gpu_upload_lines(true, &table); + assert_eq!(lines.len(), 3, "{lines:#?}"); + assert!(lines[1].contains("1 MiB: card shader read 250.00 (upload 26.00, custom L0 25.50, device-local 300.00)"), "{}", lines[1]); + assert!(lines[1].contains("CPU fill 20.00 (upload 27.00, custom L0 28.50)"), "{}", lines[1]); + assert!(lines[2].contains("16 MiB: GPU upload not measured (not made: E_OUTOFMEMORY)"), "{}", lines[2]); + let none = gpu_upload_lines(false, &table); + assert_eq!(none.len(), 1); + assert!(none[0].contains("GPUUploadHeapSupported is false"), "{}", none[0]); + // One line each, its words a space apart. + for line in lines.iter().chain(&none) { + assert!(!line.contains('\n') && !line.trim_start().contains(" "), "{line:?}"); + } + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/planes.rs b/d3d12/crates/leonida-gpu/src/host/planes.rs new file mode 100644 index 0000000000..781f4a25bc --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/planes.rs @@ -0,0 +1,399 @@ +//! The pass that draws the twin of a depth plane into the plane, and the copy +//! between a depth texture and its colour twin. + +use super::*; + +/// The pass that draws the twin of a depth plane into the plane: one +/// triangle over each mip of each slice, its pixel shader writing the +/// twin's texel as the depth, with the depth test "always" and no stencil +/// (the stencil plane is copied through a buffer and not touched here). +/// +/// A 16-bit twin holds whole steps of 1/65535, and the depth written is +/// the step times the float nearest 1/65535 (0x37800080). That is how +/// The title's tiled lighting computes the depth of the +/// rectangles it then draws with the test "equal", one class of materials +/// a draw (all six of its vertex shaders multiply the class number by that +/// constant), so the pass and the draw give the host the same float, and +/// the host turns the same float into the same 24 bits. The step divided +/// by 65535 is another float for 512 of the 65,536 steps (none under 257), +/// and lands in another 24-bit step for 127 of them (none under 385). +const PLANE_CORNERS: &str = r#" +float4 corner(uint i : SV_VertexID) : SV_Position { + return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0); +} +"#; +const PLANE_STEPS: &str = r#" +Texture2DArray<uint> twin : register(t0); +float plane(float4 p : SV_Position) : SV_Depth { + return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080); +} +"#; +const PLANE_FLOATS: &str = r#" +Texture2DArray<float> twin : register(t0); +float plane(float4 p : SV_Position) : SV_Depth { + return twin.Load(int4(int2(p.xy), 0, 0)); +} +"#; + +/// Cached pipeline objects. Shader-visible descriptors belong to the +/// individual recorded pass instead: a command list may be submitted late +/// or more than once, so a global descriptor ring cannot safely wrap. +struct PlanePass { + made: Mutex<Vec<(bool, i32, Option<PlanePipeline>)>>, +} + +/// The pass's root signature and pipeline for one kind of twin and one +/// depth format. +type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState); + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for PlanePass {} +// SAFETY: as above. +unsafe impl Sync for PlanePass {} + +fn plane_pass() -> Option<&'static PlanePass> { + static PASS: OnceLock<PlanePass> = OnceLock::new(); + host()?; + Some(PASS.get_or_init(|| PlanePass { made: Mutex::default() })) +} + +impl PlanePass { + /// The root signature and pipeline for a twin of 16-bit steps (`steps`) + /// or of floats and the depth format `format`. + fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option<PlanePipeline> { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) { + return pipeline.clone(); + } + let pipeline = match Self::make(steps, format) { + Ok(pipeline) => Some(pipeline), + Err(e) => { + tracing::warn!( + error = %e, + steps, + format = format.0, + "no pipeline to draw a depth plane from its twin: such planes stay as they are" + ); + None + } + }; + made.push((steps, format.0, pipeline.clone())); + pipeline + } + + fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result<PlanePipeline> { + use windows::core::s; + let device = &host().ok_or_else(windows::core::Error::empty)?.device; + let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?; + let source = if steps { PLANE_STEPS } else { PLANE_FLOATS }; + let ps = compile(source, s!("plane"), s!("ps_5_1"))?; + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + // Wine's HLSL compiler leaves RootSignature attributes out of the bytecode. + let range = D3D12_DESCRIPTOR_RANGE1 { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE, + OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND, + }; + let parameter = D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 { + NumDescriptorRanges: 1, + pDescriptorRanges: &range, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + }; + // SAFETY: the range, root signature and bytecode live through the calls. + unsafe { + let root = plane_root_signature(device, ¶meter)?; + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: code(&vs[..]), + PS: code(&ps[..]), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // Every texel is written; stencil stays off. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + DSVFormat: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?; + Ok((root, pipeline)) + } + } +} + +/// Serializes the single root parameter used by the plane pass or its test draw. +/// +/// # Safety +/// Any descriptor ranges referenced by the parameter must live through this call. +pub(crate) unsafe fn plane_root_signature( + device: &ID3D12Device, + parameter: &D3D12_ROOT_PARAMETER1, +) -> windows::core::Result<ID3D12RootSignature> { + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: 1, + pParameters: parameter, + ..Default::default() + }, + }, + }; + let mut blob = None; + // SAFETY: the description borrows the live parameter and its ranges. + unsafe { + D3D12SerializeVersionedRootSignature(&desc, &mut blob, None)?; + let blob = blob.ok_or_else(windows::core::Error::empty)?; + let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()); + device.CreateRootSignature(0, bytes) + } +} + +/// Records into `list` the pass that draws `plane`, the twin of the depth +/// plane of `depth`, into that plane: `depth` in the depth-write state, +/// `plane` readable by pixel shaders. The pass sets the list's descriptor +/// heap, graphics root signature, pipeline, depth target, viewport, +/// scissor and topology and puts none of them back: it is for a list that +/// records nothing of the title's after it. +pub(super) fn record_plane_pass( + owner: &HostList, + depth: &ID3D12Resource, + plane: &ID3D12Resource, +) { + let list = &owner.list; + let (Some(host), Some(pass)) = (host(), plane_pass()) else { + return; + }; + // SAFETY: live resources. + let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) }; + // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32 + // typeless one floats, read as R32_FLOAT (41). The depth view names + // the depth-stencil format of the texture's family (44: 45, 19: 20). + let steps = twin.Format.0 == 53; + let format = DXGI_FORMAT(match of.Format.0 { + 44 => 45, + 19 => 20, + typed => typed, + }); + let Some((root, pipeline)) = pass.pipeline(steps, format) else { + return; + }; + let count = u32::from(of.DepthOrArraySize) * u32::from(of.MipLevels); + if count == 0 { + return; + } + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + // SAFETY: plain heap creation. Each subresource has one immutable + // descriptor, and the owner retains the heap through all submissions. + let views: ID3D12DescriptorHeap = match unsafe { + host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + } { + Ok(heap) => heap, + Err(e) => { + tracing::error!(error = %e, count, "no descriptor heap for depth plane pass"); + return; + } + }; + owner.keep(&views); + owner.keep(depth); + owner.keep(plane); + // SAFETY: live heap, open list. + let (base_cpu, base_gpu, step) = unsafe { + list.SetDescriptorHeaps(&[Some(views.clone())]); + ( + views.GetCPUDescriptorHandleForHeapStart().ptr, + views.GetGPUDescriptorHandleForHeapStart().ptr, + host.device.GetDescriptorHandleIncrementSize(kind), + ) + }; + for slice in 0..u32::from(of.DepthOrArraySize) { + for mip in 0..u32::from(of.MipLevels) { + let slot = slice * u32::from(of.MipLevels) + mip; + let view = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(if steps { 57 } else { 41 }), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: mip, + MipLevels: 1, + FirstArraySlice: slice, + ArraySize: 1, + ..Default::default() + }, + }, + }; + let target = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: format, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_DSV { + MipSlice: mip, + FirstArraySlice: slice, + ArraySize: 1, + }, + }, + ..Default::default() + }; + let target = host.dsv(depth, Some(&target)); + let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1)); + let cpu = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: base_cpu + slot as usize * step as usize, + }; + let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: base_gpu + u64::from(slot) * u64::from(step), + }; + // SAFETY: an open list; a slot of our heap; live resources and + // objects (the pass's own live as long as the process). + unsafe { + host.device + .CreateShaderResourceView(plane, Some(&view), cpu); + list.SetGraphicsRootSignature(&root); + list.SetPipelineState(&pipeline); + list.SetGraphicsRootDescriptorTable(0, gpu); + list.OMSetRenderTargets(0, None, false, Some(&target)); + list.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: width as f32, + Height: height as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + list.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }]); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4), + ); + list.DrawInstanced(3, 1, 0, 0); + } + crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed); + } + } +} + +/// Records into `list` the copy of a depth texture into its colour twin +/// (`colour`) or of the twin into the depth texture, both already in their +/// copy states: whole textures of one size in one format family, which the +/// host copies as they are; or, for the twin of a stencil plane, that plane +/// alone, through the twin's buffer. +pub(super) fn record_twin_copy( + list: &ID3D12GraphicsCommandList, + depth: &ID3D12Resource, + twin: &crate::resource::Twin, + colour: bool, +) { + let (from, to) = if colour { + (depth, &twin.colour.texture) + } else { + (&twin.colour.texture, depth) + }; + crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed); + // shortcut: the depth plane's twin is not given the plane (that is a + // pass the other way: the plane read by a shader, the twin as its + // target). The twin then lacks what draws and clears wrote to the + // plane since shaders last wrote the twin. In the title + // nothing writes that plane but the twin's pass (its 192 draws against + // it only test, run 29), so the twin lacks nothing. Counted. + if colour && twin.plane.is_some() { + crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed); + } + let Some(through) = &twin.through else { + // SAFETY: an open list and two live textures. + unsafe { list.CopyResource(to, from) }; + return; + }; + // A stencil plane and its twin: each mip and slice of the plane goes + // into the buffer, laid out as the host lays the plane out for copies, + // and from the buffer into the other texture, whole subresources both + // times. In the depth texture the stencil plane's subresources follow + // the depth plane's; the twin has the one plane. + let Some(host) = host() else { return }; + // SAFETY: a live texture. + let of = unsafe { depth.GetDesc() }; + let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize); + let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize]; + // SAFETY: a plain query writing `planes` footprints. + unsafe { + host.device.GetCopyableFootprints( + &of, + planes, + planes, + 0, + Some(rows.as_mut_ptr()), + None, + None, + None, + ); + } + let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) }; + let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: index, + }, + }; + let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(through) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: *row, + }, + }; + let (common, source, dest) = ( + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + // SAFETY: an open list and live resources; the buffer was made as big + // as these footprints, and rests in the common state between copies. + unsafe { + list.ResourceBarrier(&[transition(through, common, dest)]); + for (i, row) in rows.iter().enumerate() { + let index = first_from + i as u32; + list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None); + } + list.ResourceBarrier(&[transition(through, dest, source)]); + for (i, row) in rows.iter().enumerate() { + let index = first_to + i as u32; + list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None); + } + list.ResourceBarrier(&[transition(through, source, common)]); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/preludes.rs b/d3d12/crates/leonida-gpu/src/host/preludes.rs new file mode 100644 index 0000000000..a0494a2929 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/preludes.rs @@ -0,0 +1,235 @@ +//! Host lists' preludes made ahead, on a thread of their own +//! (`LEONIDA_PRELUDE_POOL`, on by default). A host list makes its prelude the +//! first time a submission needs one ([`super::lazy_prelude`]), and host lists +//! are made anew in steady play (the idle ones are let go once a second), so +//! preludes were made on the submitting thread, inside the submission, while +//! the card stood idle for it and the title spun on its fence: a 30 s +//! sampling profile in play found 297 samples of `leonida-submit` making one +//! (`CreateCommandAllocator`, mostly in the kernel's thunks), 3.8 % of that +//! thread, about 1.9 ms a frame. A thread `leonida-preludes` now keeps +//! [`READY`] made, and [`HostList::prelude`] takes one of them; with none +//! ready it makes its own, as before, and wakes the thread. +//! `LEONIDA_PRELUDE_POOL=0`: every prelude is made where it is taken. +//! +//! An allocator and a closed list may be made on any thread (D3D12 is free +//! threaded there); a prelude is reset and recorded only at a submission, +//! under its list's allocator lock, as before. Its age for +//! `LEONIDA_ALLOCATOR_TRIM` counts from when a list took it +//! ([`super::list_prelude`]), not from when it was made. + +use super::*; + +/// Preludes kept made; the thread is woken when fewer than half are left. +pub(crate) const READY: usize = 16; + +/// Whether preludes are made ahead (see the module's note). +pub(crate) fn on() -> bool { + crate::toggled!("LEONIDA_PRELUDE_POOL") +} + +/// Things made ahead by a thread of their own with `fill`, taken by others. +pub(crate) struct Ready<T> { + state: Mutex<State<T>>, + wake: std::sync::Condvar, + started: std::sync::Once, + /// The thread's name. + name: &'static str, + /// Makes one; `None` ends the thread (things are then made where they + /// are taken). + fill: fn() -> Option<T>, + /// Since the start: taken made ahead; made where they were taken (none + /// ready, or the switch off). + counts: [std::sync::atomic::AtomicU64; 2], +} + +struct State<T> { + ready: Vec<T>, + /// The thread is to make until [`READY`] are ready. + wanted: bool, +} + +impl<T: Send + 'static> Ready<T> { + pub(crate) const fn new(name: &'static str, fill: fn() -> Option<T>) -> Self { + Self { + state: Mutex::new(State { ready: Vec::new(), wanted: true }), + wake: std::sync::Condvar::new(), + started: std::sync::Once::new(), + name, + fill, + counts: [const { std::sync::atomic::AtomicU64::new(0) }; 2], + } + } + + fn state(&self) -> std::sync::MutexGuard<'_, State<T>> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Starts the thread that makes them, once; it fills at once. + pub(crate) fn warm(&'static self) { + self.started.call_once(|| { + let spawned = std::thread::Builder::new().name(self.name.into()).spawn(move || { + crate::cores::keep_many_on_fast_cores(self.name); + self.make_ahead() + }); + if let Err(e) = spawned { + tracing::info!(error = %e, thread = self.name, "no thread to make ahead; made where taken"); + } + }); + } + + /// The thread: makes until [`READY`] are ready, outside the lock, then + /// waits to be woken. + fn make_ahead(&self) { + loop { + { + let mut state = self.state(); + if state.ready.len() >= READY { + state.wanted = false; + } + while !state.wanted { + state = self.wake.wait(state).unwrap_or_else(|e| e.into_inner()); + } + } + let Some(made) = (self.fill)() else { + tracing::info!(thread = self.name, "nothing more made ahead; made where taken"); + return; + }; + self.state().ready.push(made); + } + } + + /// One made ahead, the thread woken when fewer than half are left; with + /// none ready, `make_here` makes it, and the thread is woken. + pub(crate) fn take(&'static self, make_here: impl FnOnce() -> Option<T>) -> Option<T> { + self.warm(); + let mut state = self.state(); + let taken = state.ready.pop(); + if (taken.is_none() || state.ready.len() < READY / 2) && !state.wanted { + state.wanted = true; + self.wake.notify_one(); + } + drop(state); + match taken { + Some(taken) => { + self.counts[0].fetch_add(1, Ordering::Relaxed); + Some(taken) + } + None => self.here(make_here), + } + } + + /// Made where it is taken, and counted so. + pub(crate) fn here(&self, make_here: impl FnOnce() -> Option<T>) -> Option<T> { + self.counts[1].fetch_add(1, Ordering::Relaxed); + make_here() + } + + /// How many are ready now (made ahead, held by no list yet). + #[cfg_attr(not(any(test, feature = "diagnostics")), allow(dead_code))] + pub(crate) fn len(&self) -> usize { + self.state().ready.len() + } + + /// Since the start: taken made ahead, made where they were taken. + #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] + pub(crate) fn counts(&self) -> [u64; 2] { + self.counts.each_ref().map(|c| c.load(Ordering::Relaxed)) + } +} + +fn make_one() -> Option<Prelude> { + host()?.make_prelude() +} + +/// Host lists' preludes, made ahead. +pub(crate) static PRELUDES: Ready<Prelude> = Ready::new("leonida-preludes", make_one); + +/// A prelude for a host list that needs one now: made ahead if one is +/// ready ([`on`]), else made here. +pub(super) fn take() -> Option<Prelude> { + let here = || host().and_then(|h| h.make_prelude()); + if on() { PRELUDES.take(here) } else { PRELUDES.here(here) } +} + +#[cfg(test)] +thread_local! { + /// Preludes [`Host::make_prelude`] made on this thread (plain data: no + /// destructor to register). + pub(crate) static MADE_HERE: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::AtomicBool; + use std::time::{Duration, Instant}; + + /// The threads [`fill`] ran on; while [`HELD`], it waits ([`WAITING`]). + static FILLED_ON: Mutex<Vec<std::thread::ThreadId>> = Mutex::new(Vec::new()); + static HELD: AtomicBool = AtomicBool::new(false); + static WAITING: AtomicBool = AtomicBool::new(false); + + fn fill() -> Option<u32> { + while HELD.load(Ordering::Acquire) { + WAITING.store(true, Ordering::Release); + std::thread::sleep(Duration::from_millis(1)); + } + WAITING.store(false, Ordering::Release); + let mut on = FILLED_ON.lock().unwrap(); + on.push(std::thread::current().id()); + Some(on.len() as u32) + } + + static READY_U32: Ready<u32> = Ready::new("leonida-test-ready", fill); + + fn until(what: &str, mut done: impl FnMut() -> bool) { + let began = Instant::now(); + while !done() { + assert!(began.elapsed() < Duration::from_secs(10), "{what}: not within 10 s"); + std::thread::sleep(Duration::from_millis(1)); + } + } + + /// What is taken was made ahead on the pool's thread, not by the taker; + /// with none ready, the taker makes one (counted) and the thread fills + /// again. + #[test] + fn preludes_are_taken_made_ahead_and_made_here_only_when_none_are_ready() { + let pool = &READY_U32; + pool.warm(); + until("warm", || pool.len() == READY); + let me = std::thread::current().id(); + assert!(FILLED_ON.lock().unwrap().iter().all(|t| *t != me), "made on the pool's thread"); + let mut made_here = 0; + let taken = pool.take(|| { + made_here += 1; + Some(0) + }); + assert!(taken.is_some_and(|t| t != 0) && made_here == 0, "taken made ahead, none made here"); + assert_eq!(pool.counts(), [1, 0]); + // Drained with the thread held (waiting in `fill`, so nothing comes + // in after): the next is made here, once. + HELD.store(true, Ordering::Release); + let mut drained = 0; + let mut drain = || { + while pool.len() > 0 { + assert!(pool.take(|| panic!("one was ready")).is_some()); + drained += 1; + } + }; + until("held", || { + drain(); + WAITING.load(Ordering::Acquire) + }); + drain(); + let taken = pool.take(|| { + made_here += 1; + Some(0) + }); + assert_eq!((taken, made_here), (Some(0), 1), "none ready: made here"); + assert_eq!(pool.counts(), [1 + drained, 1]); + HELD.store(false, Ordering::Release); + until("filled again", || pool.len() == READY); + assert!(FILLED_ON.lock().unwrap().iter().all(|t| *t != me)); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/present.rs b/d3d12/crates/leonida-gpu/src/host/present.rs new file mode 100644 index 0000000000..ced113b547 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/present.rs @@ -0,0 +1,1161 @@ +//! Presenting: the swap chain ([`Presenter`]), the frame-rate meter +//! ([`Meter`]) and `Host::present`. + +use super::*; + +/// The swap chain formats a presented texture can be copied into: its own +/// family's. +pub(crate) fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> { + Some(match format.0 { + 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM, + 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM, + 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM, + 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT, + _ => return None, + }) +} + +const BUFFERS: u32 = 2; + +/// The format two presented planes are composed into: 8 bits a channel, or +/// 10 while Streamline presents (`streamline`) unless `ten` is off. DLSS +/// frame generation makes its frames from the swap chain's picture, and +/// from an 8-bit one they came out in bands (sky, skin: aki-runtime's runs +/// of 2026-11-27, gone with 10 bits). `refused`: the swap chain did not take +/// the 10-bit format, and 8 bits are composed as before. +/// +/// From aki-gta6/aki-runtime 2f43f8b and bdcb503 (Aki-Developer), GPL-3.0. +/// A single plane is not converted as there: it is copied in the title's +/// own format, 10 bits or more where the title has them. +pub(super) fn planes_format(streamline: bool, ten: bool, refused: bool) -> DXGI_FORMAT { + if streamline && ten && !refused { DXGI_FORMAT_R10G10B10A2_UNORM } else { DXGI_FORMAT_R8G8B8A8_UNORM } +} + +/// Whether two planes are composed into 10 bits under Streamline +/// ([`planes_format`]). On by default; `LEONIDA_PRESENT_10BIT=0`: 8 bits, as +/// before. +fn present_tenbit() -> bool { + static TEN: OnceLock<bool> = OnceLock::new(); + *TEN.get_or_init(|| std::env::var_os("LEONIDA_PRESENT_10BIT").is_none_or(|v| v != "0")) +} + +/// The swap chain refused the 10-bit format once ([`planes_format`]). +static TEN_REFUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub(super) struct Presenter { + swap_chain: IDXGISwapChain3, + width: u32, + height: u32, + format: DXGI_FORMAT, + copy: HostList, + /// With presents sent ahead ([`late_free_present`]): a list for each + /// present in the air, and the submission it last flew as (it is used + /// again once that one has finished). + ahead: Vec<(HostList, u64)>, + hwnd: HWND, + meter: Meter, + composer: Option<crate::compose::Composer>, + #[cfg(feature = "diagnostics")] + panel: panel::Panel, + menu: menu::Menu, + /// Leonida: the trainer menu (`trainer`). + trainer: trainer::Overlay, + /// What the Lua mods draw (`leonida-lua`): the same overlay, with a place of its own. + lua: trainer::Overlay, + /// The swap chain was made to show a frame as soon as it is presented ([`tearing`]): its + /// flags, kept for `ResizeBuffers`, which may not change them. + tearing: bool, + /// Presents ask for that; off for the rest of the run once such a present is refused. + presents_tearing: bool, +} + +/// Whether the swap chain shows a frame as soon as it is presented, not at the screen's next +/// refresh (`DXGI_FEATURE_PRESENT_ALLOW_TEARING`): `LEONIDA_TEARING=1`, where the system has +/// it; off by default (unset or `0`: presents wait for the refresh, as before). On a G-SYNC or +/// FreeSync screen nothing tears; on another a frame may. +/// +/// From trustno1-coder/VIctory-NVIDIA 8fc2254 (trustno1-coder; `VICTORY_TEARING`, on there), +/// GPL-3.0. Its account: a window in front, which Windows shows without its compositor +/// ("independent flip"), had each frame wait for a refresh with two buffers, frame times +/// rounded up to whole refreshes, about 2 frames a second fewer than the same window behind +/// another; and on an RTX 5070 at 1440p presents of this kind were not shown (a white window), +/// which is why a refused one ends them for the run. Off here until it has run in the game: +/// not measured on this tree, nor tried with Streamline's swap chain (`crate::fg`). +fn tearing(factory: &IDXGIFactory2) -> bool { + if !crate::switch::on("LEONIDA_TEARING") { + return false; + } + let Ok(factory) = factory.cast::<IDXGIFactory5>() else { + return false; + }; + let mut allowed = windows::core::BOOL(0); + // SAFETY: a BOOL-sized answer for this feature. + let asked = unsafe { + factory.CheckFeatureSupport( + DXGI_FEATURE_PRESENT_ALLOW_TEARING, + (&raw mut allowed).cast(), + std::mem::size_of_val(&allowed) as u32, + ) + }; + asked.is_ok() && allowed.as_bool() +} + +/// The swap chain's flags for [`tearing`]. +fn chain_flags(tearing: bool) -> DXGI_SWAP_CHAIN_FLAG { + if tearing { DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING } else { DXGI_SWAP_CHAIN_FLAG(0) } +} + +/// The frame rate the meter last counted, in tenths of a frame a second (0: none yet): for the +/// line at the top of the picture (`menu.rs`). +pub(crate) static METER_FPS_TENTHS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// The frame rate, shown in the window's caption every second and logged +/// every few seconds. +struct Meter { + since: std::time::Instant, + frames: u32, + #[cfg(feature = "diagnostics")] + copy_stats_frames: u64, + drawn: u64, + logged: std::time::Instant, + /// The caption the window had, once read. + caption: Option<Vec<u16>>, + /// Frame times and stalls, logged with the line. + stalls: frametime::Meter, +} + +impl Meter { + fn new() -> Self { + let now = std::time::Instant::now(); + Meter { + since: now, + frames: 0, + #[cfg(feature = "diagnostics")] + copy_stats_frames: 0, + drawn: crate::draw::drawn(), + logged: now, + caption: None, + stalls: frametime::Meter::new( + crate::pipeline::made(), + RESIDENT[1].load(Ordering::Relaxed), + ), + } + } + + /// Whether the next frame counted makes the frame-rate line. + #[cfg(feature = "diagnostics")] + fn line_due(&self) -> bool { + self.since.elapsed() >= std::time::Duration::from_secs(1) + } + + /// Counts a presented frame. + fn frame(&mut self, hwnd: HWND) { + #[cfg(feature = "diagnostics")] + tracing::debug!(target: "leonida_gpu::frame", token = crate::frame::current(), "present"); + #[cfg(feature = "diagnostics")] + crate::copystat::presented(); + self.stalls.presented(std::time::Instant::now()); + self.frames += 1; + #[cfg(feature = "diagnostics")] + { + self.copy_stats_frames += 1; + } + let elapsed = self.since.elapsed(); + if elapsed < std::time::Duration::from_secs(1) { + return; + } + let drawn = crate::draw::drawn(); + let frames = f64::from(self.frames); + let fps = frames / elapsed.as_secs_f64(); + let ms = elapsed.as_secs_f64() * 1000.0 / frames; + METER_FPS_TENTHS.store((fps * 10.0).round() as u32, Ordering::Relaxed); + let draws = (drawn - self.drawn) as f64 / frames; + (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn); + // The five-second lines come with this one. + let five = self.logged.elapsed() >= std::time::Duration::from_secs(5); + if five { + self.logged = std::time::Instant::now(); + // (Here: the frame times are this meter's.) + self.stalls.line( + crate::pipeline::making(), + crate::pipeline::made(), + RESIDENT[1].load(Ordering::Relaxed), + crate::residency::available_commit(), + ); + } + // (The copy counters run from one five-second line to the next.) + #[cfg(feature = "diagnostics")] + let copies = if five { std::mem::take(&mut self.copy_stats_frames) as f64 } else { 0.0 }; + #[cfg(not(feature = "diagnostics"))] + let copies = 0.0; + let due = MeterDue { frames, fps, ms, draws, copies, five }; + // Leonida: on a thread of their own ([`meter_beside`]), else here as before. + if !(meter_beside() && meter_lines_beside(due)) { + Self::lines(due); + } + self.show(hwnd, fps, ms, draws); + } + + /// The frame meter's lines of a second ([`Meter::frame`]), and every fifth + /// second's (`due.five`). + fn lines(due: MeterDue) { + let MeterDue { frames, fps, ms, draws, copies, five } = due; + #[cfg(not(feature = "diagnostics"))] + let _ = copies; + // Of a frame, ms preparing submissions and ms waiting for the GPU. + let [cpu, gpu] = [0, 1].map(|i| { + SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames + }); + let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| { + let scale = if i % 2 == 0 { 1e3 } else { 1e6 }; + PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames + }); + let [back_ms, back_mb] = [0, 1].map(|i| { + COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames + }); + let dropped = crate::draw::take_dropped() as f64 / frames; + let indirect = crate::list::take_indirect() as f64 / frames; + // Of those two together, by reason (`crate::drops`): what is left + // out on purpose apart from what was not meant to be. + let (drop_reasons, _, _) = crate::drops::line(frames); + let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed); + let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames; + let refused = BUDGET_NOTES[0].swap(0, Ordering::Relaxed) as f64 / frames; + let biggest = BUDGET_NOTES[1].swap(0, Ordering::Relaxed); + tracing::info!( + "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame; {refused:.2} indirect records a frame ran empty for want of their list's budget (2^27), the largest cost of one {biggest} (0: under 2^22)" + ); + let wide = WIDE_NOTES[0].swap(0, Ordering::Relaxed); + let wide_cut = WIDE_NOTES[1].swap(0, Ordering::Relaxed) as f64 / frames; + if wide > 0 { + tracing::info!( + "indirect dispatches: the most groups in x one asked for {wide}, more than the card is given (65535, or 2^20 where it runs them: indirect.rs, widest); {wide_cut:.0} groups a frame did not run for it" + ); + } + crate::shadow::exact_line(frames); + crate::draw::list_alias_line(frames); + crate::descriptor::sync_line(frames); + crate::port_descriptors::line(frames); + late_line(frames); + crate::queue::behind_line(frames); + #[cfg(feature = "diagnostics")] + crate::smooth::line(frames); + card_clock_line(frames, ms); + #[cfg(feature = "diagnostics")] + spans::line(frames); + crate::shadow::back_line(frames); + #[cfg(feature = "diagnostics")] + split_line(frames); + { + let [passes, pieces, compares, compared, shared] = + [0, 1, 2, 3, 4].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); + let wc_left = crate::shadow::WC_LEFT.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames; + let [ro_declared, ro_left] = + [0, 1].map(|i| crate::shadow::GPU_RO_DECLARED[i].swap(0, Ordering::Relaxed) as f64 / 1e6 / frames); + // What those took on the card, measured there (`owntimes`). + #[cfg(feature = "diagnostics")] + let (on_card, timed) = owntimes::line_part(frames); + #[cfg(not(feature = "diagnostics"))] + let (on_card, timed) = (String::new(), false); + if passes + compares + wc_left + ro_declared > 0.0 || timed { + tracing::info!( + "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \ + ranges were sent up (LEONIDA_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes over \ + {compared:.0} pieces,{shared:.0} more pieces left to the declared range before them (LEONIDA_CARD_COMPARE_SHARE); \ + {wc_left:.1} MB declared written in write-combined memory left on the card (LEONIDA_WC_NO_BACK); \ + {ro_declared:.1} MB declared written in memory the console has the GPU read only, {ro_left:.1} MB of it \ + left out (LEONIDA_GPU_READ_ONLY_NO_BACK){on_card}", + if rehash_runs() { "on" } else { "off" } + ); + } + } + { + let [own, asking, still, all] = + [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + if all >= 1.0 { + tracing::info!( + "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \ + is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \ + hold still (the runtime remapping it); the rest is reading, hashing and detiling" + ); + } + let [changes, waiting, held] = + [0, 1, 2].map(|i| crate::watch::REMAP_TIMES[i].swap(0, Ordering::Relaxed) as f64 / frames); + let longest = crate::watch::REMAP_TIMES[3].swap(0, Ordering::Relaxed) as f64 / 1000.0; + let [named, passed, stood] = + [0, 1, 2].map(|i| crate::watch::SPAN_READS[i].swap(0, Ordering::Relaxed) as f64 / frames); + if changes > 0.0 { + tracing::info!( + "the runtime's changes of mapping per frame: {changes:.1}, {:.2} ms waiting for reads in place to end, \ + {:.2} ms holding title memory still (longest {longest:.2} ms); of {named:.0} reads in place that named \ + their range, {passed:.1} went on beside a change of other memory and {stood:.1} waited for one of \ + their own (LEONIDA_REMAP_SPANS=0: all wait for every change)", + waiting / 1000.0, + held / 1000.0 + ); + } + let [through, left, filled, short] = + [0, 1, 2, 3].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); + if through + left + filled > 0.0 { + tracing::info!( + "texture refreshes that did not wait for title memory to hold still, per frame (LEONIDA_TEXTURE_NO_WAIT=1): \ + {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there), \ + {filled:.1} first fillings from the pages there (LEONIDA_TEXTURE_FILL=0: left empty), {short:.1} of them \ + with less than was mapped (looked at again)" + ); + } + } + { + let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames); + if copies > 0.0 { + tracing::info!( + "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \ + (LEONIDA_JOIN_COPIES=1 makes those one copy with it: now {})", + if join_copies() { "on" } else { "off" } + ); + } + } + // Passes over the heap's buffer views for shaders that pick them by index. + let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames; + let picked_ms = + crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames; + // Copies between depth textures and their colour twins, each way. + let [twin_to_depth, twin_to_colour] = + [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames); + // Depth planes drawn from their twins. + let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames; + // Copies in the card's memory (`crate::shadow::cards`). + let card = crate::shadow::card_stats(); + #[cfg(feature = "diagnostics")] + let slow = crate::watch::slow_asks(); + // Over the same frames as the counts above. + #[cfg(feature = "diagnostics")] + let drops = crate::pipeline::take_drops(); + if five { + tracing::info!( + "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)", + crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed) + ); + crate::tiles::status(); + { + let [queued, due, away, partly, oldest] = + [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); + let [same, parts, tails] = + [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed)); + tracing::info!( + "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \ + {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \ + the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \ + as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \ + {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \ + {} ranges of memory mapped, unmapped or written under texture views ({} in a full list made smaller), {} slots made due by them, \ + {} made slots found unmapped and made null", + crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed), + crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed), + crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed), + crate::descriptor::host::STALE[0].load(Ordering::Relaxed), + crate::descriptor::host::STALE[1].load(Ordering::Relaxed), + crate::descriptor::host::STALE[2].load(Ordering::Relaxed), + crate::descriptor::host::STALE[3].load(Ordering::Relaxed), + crate::descriptor::host::STALE[4].load(Ordering::Relaxed) + ); + } + tracing::info!( + "slot writes past the lock of placed texture views (LEONIDA_SPANS_QUICK), since the start: {} of {}; \ + notes that left the texture queue's lock alone (LEONIDA_QUEUE_MARKS): {} slot records, {} table reads, \ + {} stale views; table reads that found it held and left their slot to its next holder \ + (LEONIDA_TABLED_INBOX): {}", + crate::descriptor::host::SPANS_QUICK[0].load(Ordering::Relaxed), + crate::descriptor::host::SPANS_QUICK[0].load(Ordering::Relaxed) + + crate::descriptor::host::SPANS_QUICK[1].load(Ordering::Relaxed), + crate::descriptor::host::QUEUE_SPARED[0].load(Ordering::Relaxed), + crate::descriptor::host::QUEUE_SPARED[1].load(Ordering::Relaxed), + crate::descriptor::host::QUEUE_SPARED[2].load(Ordering::Relaxed), + crate::descriptor::host::TABLED_INBOX.load(Ordering::Relaxed) + ); + tracing::info!( + "views of table entries this thread had read (LEONIDA_VIEW_CACHE), since the start: {} answered so, {} read \ + under the lock; entries of tables read in place found brought up to date in their list \ + (LEONIDA_ENTRY_ONCE): {} of {}; placed textures found again with nothing in their memory \ + (LEONIDA_ALIAS_QUICK): {} of {}; tables made afresh found again by what they hold \ + (LEONIDA_CONTENT_TABLES): {} at their place, {} at another; host lists given to the title's lists \ + at their reset closed already (LEONIDA_CLOSED_AHEAD): {}, closed by the resetting thread: {}; \ + dynamic slots whose resource their list keeps (LEONIDA_KEEP_BY_LIST): {}, {} of them its first", + crate::descriptor::VIEW_CACHE_COUNTS[0].load(Ordering::Relaxed), + crate::descriptor::VIEW_CACHE_COUNTS[1].load(Ordering::Relaxed), + crate::draw::ENTRY_ONCE[1].load(Ordering::Relaxed), + crate::draw::ENTRY_ONCE[0].load(Ordering::Relaxed) + crate::draw::ENTRY_ONCE[1].load(Ordering::Relaxed), + crate::resource::ALIAS_QUICK[0].load(Ordering::Relaxed), + crate::resource::ALIAS_QUICK[0].load(Ordering::Relaxed) + crate::resource::ALIAS_QUICK[1].load(Ordering::Relaxed), + crate::draw::CONTENT_TABLES[0].load(Ordering::Relaxed), + crate::draw::CONTENT_TABLES[1].load(Ordering::Relaxed), + crate::list::CLOSED_TAKEN[0].load(Ordering::Relaxed), + crate::list::CLOSED_TAKEN[1].load(Ordering::Relaxed), + crate::descriptor::host::KEEP_BY_LIST[0].load(Ordering::Relaxed), + crate::descriptor::host::KEEP_BY_LIST[1].load(Ordering::Relaxed) + ); + tracing::info!( + "slots of textures made while lists sent before them ran, shown once those had run (LEONIDA_SHOW_NEW_LATER={}), since the start: {}", + u8::from(crate::descriptor::host::show_new_later()), + crate::descriptor::host::NEW_LATER.load(Ordering::Relaxed) + ); + if crate::resource::held_only() { + let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed)); + let [flipped, missed] = [0, 1].map(|i| crate::descriptor::host::FLIPPED[i].load(Ordering::Relaxed)); + tracing::info!( + "textures from the first level viewed (LEONIDA_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \ + levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \ + {flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \ + out as the host copy held those bytes (LEONIDA_TEXTURE_SAME=0: made); {} MB of texture blocks free; \ + {} looks for textures to let go, {:.2} ms each, the longest {:.1}", + bytes >> 20, + whole >> 20, + crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed), + crate::pool::texture_room() >> 20, + crate::resource::SWEPT_US[0].load(Ordering::Relaxed), + crate::resource::SWEPT_US[1].load(Ordering::Relaxed) as f64 + / 1e3 + / crate::resource::SWEPT_US[0].load(Ordering::Relaxed).max(1) as f64, + crate::resource::SWEPT_US[2].load(Ordering::Relaxed) as f64 / 1e3 + ); + } + { + let mode = crate::watch::page_writes(); + let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed)); + let [kept, dropped, slots, uploaded] = + [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed)); + tracing::info!( + "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} in a full list made smaller); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (LEONIDA_PAGE_WRITES: unset or guards opens the guarded blocks, 0 counts only, 1, slots, all)", + bytes >> 20, + if mode & 1 != 0 { "opened, taken again" } else { "left as they were" }, + if mode & 4 != 0 { "told as well" } else { "counted only" }, + if mode & 2 != 0 { "made due again" } else { "left as they were" } + ); + } + #[cfg(feature = "diagnostics")] + tracing::info!( + "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms", + slow[0] as f64 / frames, + slow[1] as f64 / 1e3 / frames, + slow[2] as f64 / 1e3 + ); + if crate::shadow::cards() { + let per_frame = |i: usize| card[i] as f64 / frames; + tracing::info!( + "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \ + {:.1} MB sent up in {:.0} ranges, {:.0} piece reads by declared ranges (a piece two ranges share counts \ + twice; the compare passes line counts the pieces hashed), {:.0} pieces fetched \ + ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)", + card[7], + card[8] >> 20, + card[9] >> 20, + per_frame(0) / 1e6, + per_frame(1), + per_frame(2), + per_frame(3), + per_frame(4) / 1e6, + per_frame(5), + per_frame(6) / 1e3 + ); + // (Taken every period: with `LEONIDA_AB` a phase with the + // switch off still lands plans made in the one before.) + let [pieces, bytes, past, given, unfetched, refused, held, captured, fetched] = + [0, 1, 2, 3, 4, 5, 6, 7, 8].map(|i| landsame::STATS[i].swap(0, Ordering::Relaxed) as f64 / frames); + if landsame::on() || captured > 0.0 { + tracing::info!( + "pieces landed in their own submission (LEONIDA_LAND_IN_SUBMISSION), per frame: {pieces:.0} ({:.1} MB), \ + {past:.0} flagged past their plan's room (fetched), {held:.0} held whole by a fetch that ran \ + after their flight (left out), {given:.1} plans given a landing, {refused:.1} found no room, \ + {unfetched:.1} landings of the relay with no fetch at all; plans of the relay landed: \ + {captured:.1} made to capture, {fetched:.1} made to fetch; {} MB of landing buffers", + bytes / 1e6, + landsame::ALIVE.load(Ordering::Relaxed) >> 20 + ); + } + } + // Where the windows outside buffers lie (card or PC memory). + crate::shadow::window_line(); + tracing::info!( + "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ + {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \ + GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \ + dropped {dropped:.0} without a host pipeline ({making} being made) and \ + {indirect:.0} indirect, of both per frame: {drop_reasons}; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \ + textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \ + {picked_waiting} waiting, {picked_away} passed over unmapped; depth textures with unordered access: {du0} made, bound as depth {du1}x, cleared as depth {du2}x, unordered views refused {du3}x; buffer views left null as the host would refuse them: {refused}; {rawcuts}", + picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed), + picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20, + picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed), + picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed), + du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed), + du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed), + du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed), + du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed), + refused = format!( + "{} ({} copies made of views off their buffer's elements); depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass", + crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed), + crate::shadow::OWN_MADE.load(Ordering::Relaxed), + crate::resource::TWINS[0].load(Ordering::Relaxed), + crate::resource::TWINS[1].load(Ordering::Relaxed), + crate::resource::PLANES[1].load(Ordering::Relaxed), + crate::resource::PLANES[2].load(Ordering::Relaxed) + ), + rawcuts = crate::descriptor::host::raw_cuts_line(), + making = crate::pipeline::making(), + placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed), + objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed) + ); + #[cfg(feature = "diagnostics")] + { + let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames); + tracing::info!( + "what shaders wrote put into title memory per frame (LEONIDA_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps", + put[0], + put[1], + put[2] / 1e6, + put[3] + ); + crate::shadow::elide::log(frames); + traffic::line(copies); + crate::copystat::log(copies); + for (why, n) in drops.iter().take(40) { + tracing::info!( + "dropped {:.1}/frame without a host pipeline: {why}", + *n as f64 / frames + ); + } + } + } + } + + /// The window's caption with this second's frame rate. + fn show(&mut self, hwnd: HWND, fps: f64, ms: f64, draws: f64) { + if self.caption.is_none() { + // The window's own text, read without a message. + let mut buffer = vec![0u16; 512]; + // SAFETY: a window handle and a buffer of that length. + let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) }; + buffer.truncate(n.max(0) as usize); + self.caption = Some(buffer); + } + let Some(caption) = &self.caption else { return }; + // LOCAL (11/26): with frame generation, the frames shown too. + let shown = crate::fg::shown_per_frame(); + let text = if shown > 1 { + format!(" | Leonida {fps:.0} fps (frame gen {:.0} fps) {ms:.1} ms/frame {draws:.0} draws/frame", fps * f64::from(shown)) + } else { + format!(" | Leonida {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame") + }; + let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect(); + text.push(0); + // Setting the text waits for the window's thread (a title thread, + // which may not pump for a while), so a thread of ours does it and + // presenting never waits; it takes the newest text when free. + static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None); + static SETTER: std::sync::Once = std::sync::Once::new(); + *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text)); + SETTER.call_once(|| { + let _ = std::thread::Builder::new() + .name("leonida-caption".into()) + .spawn(|| { + loop { + let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take(); + match next { + // SAFETY: a window handle and a NUL-terminated text. + Some((hwnd, text)) => unsafe { + let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr())); + }, + None => std::thread::sleep(std::time::Duration::from_millis(100)), + } + } + }); + }); + } +} + +/// What the frame meter's lines of a second are made from ([`Meter::lines`]). +#[derive(Clone, Copy)] +struct MeterDue { + /// The frames presented since the last line. + frames: f64, + fps: f64, + ms: f64, + draws: f64, + /// The frames the copy counters ran over (`crate::copystat::log`), with the five-second lines. + copies: f64, + /// The five-second lines come with this one. + five: bool, +} + +/// Leonida: `LEONIDA_METER_BESIDE` (on unless `0`): the frame meter's lines of each second are made on +/// a thread of their own instead of in the present, on the line's thread, which the frame waits for. +/// Made there they held that thread some 37 ms once a second (a timeline of run d141: 16.4 ms of it in +/// `VirtualQuery` for the copy counters' busiest ranges, the rest the lines themselves; a frame of the +/// line's thread is 45-60 ms of work). After kylepelham/El1xr d7ff66ab (`VICTORY_RAMLINE_BESIDE`: +/// that fork's present spikes every few seconds were its memory lines made in the present). +/// `LEONIDA_AB` can switch it. +fn meter_beside() -> bool { + crate::toggled!("LEONIDA_METER_BESIDE") +} + +/// Hands `due` to the meter's thread, made on first use (`false`: there is none). A line still waiting +/// for that thread when the next comes is joined to it: its frames are counted with the next one's. +fn meter_lines_beside(mut due: MeterDue) -> bool { + static DUE: (Mutex<Option<MeterDue>>, std::sync::Condvar) = (Mutex::new(None), std::sync::Condvar::new()); + static THREAD: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let started = *THREAD.get_or_init(|| { + let made = std::thread::Builder::new().name("leonida-meter".into()).spawn(|| { + loop { + let due = { + let mut next = DUE.0.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(due) = next.take() { + break due; + } + next = DUE.1.wait(next).unwrap_or_else(|e| e.into_inner()); + } + }; + Meter::lines(due); + } + }); + match made { + Ok(_) => { + tracing::info!("the frame meter's lines are made on a thread of their own (LEONIDA_METER_BESIDE=0: in the present)"); + true + } + Err(e) => { + tracing::warn!(error = %e, "no thread for the frame meter's lines: they are made in the present"); + false + } + } + }); + if !started { + return false; + } + let mut next = DUE.0.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(before) = next.take() { + due.frames += before.frames; + due.copies += before.copies; + due.five |= before.five; + } + *next = Some(due); + drop(next); + DUE.1.notify_one(); + true +} + +impl Host { + /// Shows `texture`, which is in `state` (a host state) and stays in it, + /// as frame `frame` (saved if captures are on). `None` if nothing was + /// shown; else, in diagnostics builds, whether the frame was black. + #[allow(dead_code)] + pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> { + self.present_planes(texture, state, None, frame) + } + + /// Shows `texture`, optionally alpha-compositing a second `overlay` plane + /// over it (Series S two-plane presentation), and returns them to their states. + pub(crate) fn present_planes( + &self, + texture: &ID3D12Resource, + state: u32, + overlay: Option<(&ID3D12Resource, u32)>, + frame: u64, + ) -> Option<bool> { + // SAFETY: a live resource. + let desc = unsafe { texture.GetDesc() }; + // Leonida: whether the title presents the interface on a plane of its own (what frame generation could be + // given as the interface, apart from the scene), said each time that changes, a few times at most. + { + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + static SAID: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + let now = if overlay.is_some() { 2 } else { 1 }; + if LAST.swap(now, Ordering::Relaxed) != now && SAID.fetch_add(1, Ordering::Relaxed) < 6 { + match overlay { + Some((over, _)) => { + // SAFETY: a live overlay resource. + let d = unsafe { over.GetDesc() }; + tracing::info!( + frame, + scene = ?(desc.Width, desc.Height, desc.Format.0), + interface = ?(d.Width, d.Height, d.Format.0), + "presents: the interface on a plane of its own over the scene" + ); + } + None => tracing::info!(frame, scene = ?(desc.Width, desc.Height, desc.Format.0), "presents: one plane"), + } + } + } + let planes = overlay.and_then(|(over, over_state)| { + // SAFETY: a live overlay resource. + let over_desc = unsafe { over.GetDesc() }; + Some(( + over, + D3D12_RESOURCE_STATES(over_state as i32), + crate::compose::view(&desc)?, + crate::compose::view(&over_desc)?, + )) + }); + let format = if planes.is_some() { + planes_format(crate::fg::active(), present_tenbit(), TEN_REFUSED.load(Ordering::Relaxed)) + } else { + let Some(format) = swap_format(desc.Format) else { + tracing::warn!(format = desc.Format.0, "cannot present this format"); + return None; + }; + format + }; + let (width, height) = (desc.Width as u32, desc.Height); + let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); + if presenter.is_none() { + *presenter = match self.presenter(width, height, format) { + Ok(p) => Some(p), + Err(e) => { + tracing::warn!(error = %e, "no swap chain"); + return None; + } + }; + } + let state_u32 = state; + let p = presenter.as_mut()?; + if planes.is_some() && p.composer.is_none() { + match crate::compose::Composer::new(self, format) { + Ok(c) => p.composer = Some(c), + Err(e) => { + tracing::warn!(error = %e, "two-plane composer not made; showing base plane only"); + drop(presenter); + return self.present_planes(texture, state_u32, None, frame); + } + } + } + // Leonida: the swap chain is the picture, which the window stretches. With `LEONIDA_PRESENT_SCALE=fit` + // and a window of another shape it is a frame of the window's shape with the picture in its middle + // (`crate::aspect`), which the window then scales evenly. + let placed = if crate::aspect::fit() { + crate::aspect::frame((width, height), client_size(p.hwnd)) + } else { + crate::aspect::Frame::whole(width, height) + }; + let whole = placed.is_whole((width, height)); + if (p.width, p.height, p.format) != (placed.width, placed.height, format) { + // Presents sent ahead hold back buffers until they have run. + settle_now(WHY_SYNC); + // Leonida: FSR 3 frame generation's context goes with the buffers (made again at the next upscale). + crate::fsr::resizing(); + // SAFETY: no back buffer is held; every submission was waited for. + let resized = unsafe { + p.swap_chain + .ResizeBuffers(BUFFERS, placed.width, placed.height, format, chain_flags(p.tearing)) + }; + match resized { + Ok(()) => { + if p.format != format { + p.composer = None; + } + (p.width, p.height, p.format) = (placed.width, placed.height, format); + // Leonida: the trainer menu is painted for the height of what is shown. + leonida_menu::set_height(placed.height); + tracing::info!( + width = placed.width, + height = placed.height, + picture = ?(width, height), + at = ?(placed.left, placed.top), + format = format.0, + frame, + "the swap chain's buffers were made again for another size or format" + ); + self.log_video_memory("right after the swap chain's buffers were made again"); + } + Err(e) if planes.is_some() + && format == DXGI_FORMAT_R10G10B10A2_UNORM + && !TEN_REFUSED.swap(true, Ordering::Relaxed) => + { + // Once: the planes are composed into 8 bits from now on. + tracing::warn!(error = %e, "the swap chain does not take 10 bits a channel: the two planes are composed into 8, as before"); + drop(presenter); + return self.present_planes(texture, state_u32, overlay, frame); + } + Err(e) => { + tracing::warn!(error = %e, width, height, "swap chain not resized"); + return None; + } + } + } + if planes.is_some() && p.composer.is_none() { + match crate::compose::Composer::new(self, format) { + Ok(c) => p.composer = Some(c), + Err(e) => { + tracing::warn!(error = %e, "two-plane composer not made after resize; showing base plane only"); + drop(presenter); + return self.present_planes(texture, state_u32, None, frame); + } + } + } + let state = D3D12_RESOURCE_STATES(state_u32 as i32); + // SAFETY: our swap chain, list and live source texture(s). + unsafe { + let index = p.swap_chain.GetCurrentBackBufferIndex(); + let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else { + return None; + }; + // Leonida: what this present has to do for the trainer menu + // (`trainer`): one atomic load, and nothing more while the menu + // is closed and no screenshot is asked for. + let trainer_work = leonida_menu::work(); + // Leonida: the Lua mods are told a frame is presented (one load + // with LEONIDA_LUA=0; never waits for them). + leonida_lua::tick(); + // Sent ahead ([`late_free_present`]) unless the frame is to be + // read back at once (a saved or listed frame): then a list of + // its own, one whose last flight has finished or a new one. + #[cfg(feature = "diagnostics")] + let read_now = crate::capture::wanted(frame) + || crate::capture::listed(frame) + // Leonida: a screenshot asked for in the trainer menu is read back at once too. + || trainer_work & leonida_menu::SHOT != 0; + #[cfg(not(feature = "diagnostics"))] + let read_now = false; + let slot = if late_free_present() && !read_now { + let finished = FINISHED.load(Ordering::Acquire); + p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| { + let list = self.new_list().ok()?; + list.close(); + p.ahead.push((list, 0)); + Some(p.ahead.len() - 1) + }) + } else { + None + }; + let copy = match slot { + Some(i) => &p.ahead[i].0, + None => &p.copy, + }; + copy.reset(); + copy.keep(texture); + let list = ©.list; + let composed = if let Some((over, over_state, base_fmt, over_fmt)) = planes { + copy.keep(over); + if let Some(composer) = p.composer.as_mut() { + let mut pre = Vec::with_capacity(3); + if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + pre.push(transition(texture, state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); + } + if over_state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + pre.push(transition(over, over_state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); + } + pre.push(transition(&back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); + list.ResourceBarrier(&pre); + if !whole { + // The bars: black around the picture. + list.ClearRenderTargetView(self.rtv(Some(&back), None), &[0.0, 0.0, 0.0, 1.0], None); + } + let compose_slot = slot.map_or(0, |i| i + 1); + if let Err(err) = composer.record( + self, + compose_slot, + list, + [(texture, base_fmt), (over, over_fmt)], + &back, + (placed.left, placed.top), + (width, height), + ) { + copy.close(); + drop(back); + drop(presenter); + tracing::warn!(%err, "could not record display composite; presenting the base plane"); + return self.present_planes(texture, state_u32, None, frame); + } + static ONCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !ONCE.swap(true, Ordering::Relaxed) { + tracing::info!( + frame, + width, + height, + base_format = base_fmt.0, + overlay_format = over_fmt.0, + "display output: compositing two planes (overlay active)" + ); + } + let mut post = Vec::with_capacity(3); + if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + post.push(transition(texture, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, state)); + } + if over_state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + post.push(transition(over, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, over_state)); + } + post.push(transition( + &back, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_DEST, + )); + list.ResourceBarrier(&post); + true + } else { + false + } + } else { + false + }; + if !composed { + let mut pre = Vec::with_capacity(2); + if state != D3D12_RESOURCE_STATE_COPY_SOURCE { + pre.push(transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE)); + } + if whole { + pre.push(transition( + &back, + D3D12_RESOURCE_STATE_PRESENT, + D3D12_RESOURCE_STATE_COPY_DEST, + )); + list.ResourceBarrier(&pre); + list.CopyResource(&back, texture); + } else { + // Leonida: the bars (`crate::aspect`): the buffer cleared to black, then the picture copied + // into its middle as it is. + pre.push(transition(&back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); + list.ResourceBarrier(&pre); + list.ClearRenderTargetView(self.rtv(Some(&back), None), &[0.0, 0.0, 0.0, 1.0], None); + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); + let location = |resource: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(resource), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + list.CopyTextureRegion(&location(&back), placed.left, placed.top, 0, &location(texture), None); + } + } + // What the overlays are laid over: the whole buffer, bars and all. + let shown = (placed.width, placed.height); + // Leonida: the trainer menu's screenshot is this present's + // read-back too: the title's picture, before the panel and the + // menus are laid over it. + #[cfg(feature = "diagnostics")] + let shot = trainer::shot(trainer_work); + // (A recorded frame's present time, for the time from a key to the frame that shows it.) + #[cfg(feature = "diagnostics")] + crate::capture::note_present(frame); + #[cfg(feature = "diagnostics")] + let capture = (crate::capture::wanted(frame) || shot.is_some()) + .then(|| { + if composed { + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let res = crate::capture::read_back(&self.device, list, &back); + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); + res + } else { + crate::capture::read_back(&self.device, list, texture) + } + }) + .flatten(); + #[cfg(feature = "diagnostics")] + let probe = if slot.is_some() || composed { + None + } else { + crate::capture::probe(&self.device, list, texture) + }; + #[cfg(feature = "diagnostics")] + let watched = if composed { + None + } else { + crate::popwatch::take(&self.device, list, texture) + }; + #[cfg(feature = "diagnostics")] + p.panel.draw(self, copy, &back, shown, format); + p.menu.draw(self, copy, &back, shown, format); + // Leonida: what the Lua mods draw, then the trainer menu, where the + // panel and the F1 menu are put (so frame generation sees all alike). + if trainer_work & leonida_menu::LUA_DRAW != 0 { + p.lua.draw_lua(self, copy, &back, shown, format); + } + if trainer_work & leonida_menu::DRAW != 0 { + p.trainer.draw(self, copy, &back, shown, format); + } + #[cfg(not(feature = "diagnostics"))] + let _ = frame; + if composed { + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PRESENT, + )]); + } else { + let mut post = Vec::with_capacity(2); + if state != D3D12_RESOURCE_STATE_COPY_SOURCE { + post.push(transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state)); + } + post.push(transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PRESENT, + )); + list.ResourceBarrier(&post); + } + // Leonida: FSR 3 frame generation's prepare dispatch and configuration for this present (crate::fsr), + // last on the list before `Present`. Series S's base plane is the colour without the interface. + let hudless = (composed && whole).then_some((texture, state_u32)); + crate::fsr::before_present( + &self.device, + &p.swap_chain, + list, + [placed.width, placed.height], + format, + hudless, + &|t: &ID3D12Resource| copy.keep(t), + ); + copy.close(); + let flown = match slot { + Some(i) => { + let flown = self.execute_own(copy); + p.ahead[i].1 = flown; + flown + } + None => { + self.execute(&[copy]); + 0 + } + }; + #[cfg(feature = "diagnostics")] + if let Some(taken) = watched { + crate::popwatch::sent(taken, flown, frame); + } + #[cfg(not(feature = "diagnostics"))] + let _ = flown; + #[cfg(feature = "diagnostics")] + if let Some((buffer, footprint)) = capture { + if crate::capture::wanted(frame) { + crate::capture::save_read_back(frame, &buffer, &footprint); + } + // Leonida: the same read-back as the trainer menu's screenshot. + if let Some(path) = shot { + trainer::save_shot(path, &buffer, &footprint); + } + } + #[cfg(feature = "diagnostics")] + crate::replay::record::present(texture, state); + let mut showing = crate::timeline::span("the host's Present"); + // Leonida: held to a fraction of the recent mean interval (`LEONIDA_PRESENT_SMOOTH`), but + // not while other submissions or presents stand in the line not yet sent, which the + // line's thread sends after this one (`LEONIDA_SMOOTH_YIELD`). + crate::smooth::hold(crate::smooth::waiting(crate::queue::queued())); + // Leonida: for the A/B phase lines, when each frame is handed over to be shown. + #[cfg(feature = "diagnostics")] + crate::ab::shown(); + // Leonida: with bars, frame generation is told where in the buffer the picture is. + crate::fg::picture_box((!whole).then_some([placed.left, placed.top, width, height])); + // (With one plane, the texture whose copy without the interface is tagged.) + crate::fg::present_start(frame, (!composed).then_some(texture)); + if p.presents_tearing { + // ([`tearing`]: shown at once; a refused one ends that for the run.) + let shown = p.swap_chain.Present(0, DXGI_PRESENT_ALLOW_TEARING); + if shown.is_err() { + tracing::warn!(code = %shown, frame, "a present shown at once was refused; presenting at the next refresh for the rest of the run"); + p.presents_tearing = false; + let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + } + } else { + let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + } + crate::smooth::presented(); + crate::fg::present_end(frame); + showing.next("the frame meter"); + #[cfg(feature = "diagnostics")] + p.panel.frame(p.meter.line_due()); + p.menu.frame(); + p.meter.frame(p.hwnd); + showing.end(); + #[cfg(feature = "diagnostics")] + return Some(probe.is_some_and(|b| crate::capture::black(&b))); + #[cfg(not(feature = "diagnostics"))] + Some(false) + } + } + + fn presenter( + &self, + width: u32, + height: u32, + format: DXGI_FORMAT, + ) -> windows::core::Result<Presenter> { + let hwnd = match title_window() { + Some(hwnd) => hwnd, + // Leonida: a window of our own takes the shape `LEONIDA_ASPECT` asks for, as the title's does. + None => match crate::aspect::asked() { + Some(aspect) => { + let (w, h) = crate::aspect::widened(width as i32, height as i32, aspect); + window(w as u32, h as u32)? + } + None => window(width, height)?, + }, + }; + self.log_video_memory("right before the swap chain is made"); + // SAFETY: plain object creation for our window. + unsafe { + let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + let tearing = tearing(&factory); + if tearing { + tracing::info!("swap chain: frames shown as soon as presented (LEONIDA_TEARING=1)"); + } + // LOCAL (11/26): with `LEONIDA_FRAME_GEN`, Streamline's proxy factory (crate::fg). + let factory = crate::fg::start(&self.device, factory); + let desc = DXGI_SWAP_CHAIN_DESC1 { + Width: width, + Height: height, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount: BUFFERS, + SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, + Flags: chain_flags(tearing).0 as u32, + ..Default::default() + }; + // Leonida: with `LEONIDA_FSR_FRAMEGEN=1` (and no Streamline swap chain), FidelityFX's frame interpolation + // swap chain (crate::fsr); as before if it cannot be made. + let swap_chain = match crate::fsr::swap_chain(&factory, &self.queue, hwnd, &desc) { + Some(swap_chain) => swap_chain, + None => factory + .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)? + .cast::<IDXGISwapChain3>()?, + }; + // Leonida: with `LEONIDA_CAPTURE_SHOWN=1`, what the swap chain shows is saved too (generated frames). + #[cfg(feature = "diagnostics")] + crate::shown::install(&swap_chain, &self.device, &self.queue); + let copy = self.new_list()?; + copy.close(); + tracing::info!(width, height, format = format.0, "presenting to a window"); + self.log_video_memory("right after the swap chain is made"); + Ok(Presenter { + swap_chain, + width, + height, + format, + copy, + ahead: Vec::new(), + hwnd, + meter: Meter::new(), + composer: None, + #[cfg(feature = "diagnostics")] + panel: panel::Panel::new(), + menu: menu::Menu::new(), + trainer: trainer::Overlay::new(height), + lua: trainer::Overlay::idle(), + tearing, + presents_tearing: tearing, + }) + } + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/read_back_pool_tests.rs b/d3d12/crates/leonida-gpu/src/host/read_back_pool_tests.rs new file mode 100644 index 0000000000..8aaf9c41b2 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/read_back_pool_tests.rs @@ -0,0 +1,54 @@ +use super::*; +use windows::core::Interface; + +#[test] +fn a_read_back_buffer_is_made_in_whole_64_kib() { + assert_eq!(read_back_size(0), 1 << 16); + assert_eq!(read_back_size(1), 1 << 16); + assert_eq!(read_back_size(512), 1 << 16); + assert_eq!(read_back_size(1 << 16), 1 << 16); + assert_eq!(read_back_size((1 << 16) + 1), 2 << 16); + assert_eq!(read_back_size(350_000), 6 << 16); +} + +/// A list's read-back buffer is the next read back's of its size once +/// the list is reset, and not before; one something else still names +/// when the list is reset is not kept. +#[test] +fn a_reset_lists_read_back_buffer_is_the_next_read_backs() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the read-back buffers' table not tested"); + return; + }; + if !read_back_pool() { + return; + } + // (A size no other test reads back: the table is the process's.) + let size = (7 << 16) - 100; + let mut title = [0u8; 64]; + let list = host.new_list().unwrap(); + let buffer = host.read_back_buffer(size).unwrap(); + // SAFETY: a live buffer. + assert_eq!(unsafe { buffer.GetDesc() }.Width, 7 << 16); + let first = buffer.as_raw() as usize; + list.defer_read_back(buffer, title.as_mut_ptr(), [16, 2, 32]); + // The list holds it: another read back gets another buffer. + let other = host.read_back_buffer(size).unwrap(); + assert_ne!(other.as_raw() as usize, first); + list.close(); + list.reset(); + // Nobody's now: the next read back of that size takes it, once. + let again = host.read_back_buffer(size - 4096).unwrap(); + assert_eq!(again.as_raw() as usize, first); + let third = host.read_back_buffer(size).unwrap(); + assert_ne!(third.as_raw() as usize, first); + // Still named elsewhere when its list is reset: let go, not kept. + let named = again.clone(); + list.defer_read_back(again, title.as_mut_ptr(), [16, 2, 32]); + list.close(); + list.reset(); + assert!(sole(&named)); + let fourth = host.read_back_buffer(size).unwrap(); + assert_ne!(fourth.as_raw() as usize, first); + drop((other, third, fourth, named)); +} diff --git a/d3d12/crates/leonida-gpu/src/host/relay_tests.rs b/d3d12/crates/leonida-gpu/src/host/relay_tests.rs new file mode 100644 index 0000000000..0649b6a6c9 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/relay_tests.rs @@ -0,0 +1,57 @@ +use super::{flagged_pieces, landable}; + +/// Two planes are composed into 10 bits only while Streamline presents, +/// the switch is on and the swap chain took the format. +#[test] +fn two_planes_are_composed_into_10_bits_under_streamline_only() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM}; + assert_eq!(super::planes_format(true, true, false), DXGI_FORMAT_R10G10B10A2_UNORM); + assert_eq!(super::planes_format(false, true, false), DXGI_FORMAT_R8G8B8A8_UNORM); + assert_eq!(super::planes_format(true, false, false), DXGI_FORMAT_R8G8B8A8_UNORM); + assert_eq!(super::planes_format(true, true, true), DXGI_FORMAT_R8G8B8A8_UNORM); +} + +/// A removed device's fence value is not a value reached. +#[test] +fn a_removed_devices_fence_value_is_not_reached() { + assert!(!super::fence_reached(u64::MAX, 1)); + assert!(!super::fence_reached(6, 7)); + assert!(super::fence_reached(7, 7)); + assert!(super::fence_reached(8, 7)); +} + +/// Two flights and what follows each: nothing of the second lands +/// before the card has run it, and nothing behind a flight lands +/// before the flight. +#[test] +fn flights_land_in_the_order_they_were_sent() { + // Flight (fence 5), its write, a signal, flight (fence 6), its write. + let line = [Some(5), None, None, Some(6), None]; + assert_eq!(landable(&line, 4), 0); + assert_eq!(landable(&line, 5), 3); + assert_eq!(landable(&line, 6), 5); + assert_eq!(landable(&line, u64::MAX), 5); + // Signals with no flight ahead land at once; behind one they wait. + assert_eq!(landable(&[None, None], 0), 2); + assert_eq!(landable(&[None, Some(9), None], 8), 1); + assert_eq!(landable(&[], 3), 0); + // After the first three landed, the rest when its turn comes. + assert_eq!(landable(&line[3..], 5), 0); + assert_eq!(landable(&line[3..], 6), 2); +} + +/// A piece flagged under one range of a plan is fetched under every +/// range that holds a part of it; pieces of other copies are not. +#[test] +fn a_piece_flagged_under_one_range_is_fetched_under_all() { + let (a, b) = (0x1000usize, 0x2000usize); + // Copy a: piece 3 under two ranges, flagged under the first only; + // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged. + let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)]; + let fetch = flagged_pieces(&flags); + assert!(fetch.contains(&(a, 3))); + assert!(!fetch.contains(&(a, 4))); + assert!(!fetch.contains(&(b, 3))); + assert!(fetch.contains(&(b, 9))); + assert_eq!(fetch.len(), 2); +} diff --git a/d3d12/crates/leonida-gpu/src/host/result_ring_tests.rs b/d3d12/crates/leonida-gpu/src/host/result_ring_tests.rs new file mode 100644 index 0000000000..22300be9d8 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/result_ring_tests.rs @@ -0,0 +1,271 @@ +use super::{ResultArea, ResultRing}; + +/// The area's dwords (1 MiB of results) and a plan's: 40,000 pieces of +/// 64 KiB, about 2.4 GiB of declared ranges. +const CAP: u32 = 1 << 18; +const PLAN: u32 = 40_000; + +/// Plans of `PLAN` dwords, `out` of them in the air at once, landing in +/// the order they were made, `plans` times: the first plan the area +/// could not place whole without a drain (with the whole area, the first +/// made when half of it was taken: `Host::card_results_low`), if any. +/// Checks that no two runs in the air share a dword and none wraps. +fn first_drain(mut area: ResultArea, out: usize, plans: usize) -> Option<usize> { + let mut air: std::collections::VecDeque<(u64, u32, u32)> = std::collections::VecDeque::new(); + for plan in 0..plans { + if area.low() { + return Some(plan); + } + let (at, room) = area.place(PLAN); + if room < PLAN { + return Some(plan); + } + assert!(at + PLAN <= CAP, "plan {plan} wraps within its run"); + for &(_, from, to) in &air { + assert!(at + PLAN <= from || to <= at, "plan {plan} at {at} over a run in the air {from}..{to}"); + } + air.push_back((area.take(at, PLAN), at, at + PLAN)); + if air.len() == out { + area.give_back(air.pop_front().unwrap().0); + } + } + None +} + +/// With three plans always in the air the ring never needs a drain for +/// room. The whole area (`LEONIDA_COMPARE_RING=0`, the policy before) +/// never starts again while one is out: at the fifth plan half of it is +/// taken and every flight had to land. +#[test] +fn the_ring_has_room_while_plans_overlap() { + assert_eq!(first_drain(ResultArea::new(CAP, true, true), 3, 1000), None); + assert_eq!(first_drain(ResultArea::new(CAP, false, true), 3, 1000), Some(4)); + // Without the relay each plan is given back before the next. + assert_eq!(first_drain(ResultArea::new(CAP, false, false), 1, 1000), None); +} + +/// A plan waits for room only when the ring is short of it and the whole +/// ring could hold it: one asking for more is placed at once, its rest +/// fetched whole, rather than drain every flight for nothing. +#[test] +fn a_plan_longer_than_the_ring_does_not_wait() { + assert_eq!(ResultArea::short(40, 50, 100), None); + assert_eq!(ResultArea::short(50, 50, 100), None); + assert_eq!(ResultArea::short(60, 50, 100), Some(60)); + assert_eq!(ResultArea::short(100, 0, 100), Some(100)); + assert_eq!(ResultArea::short(101, 50, 100), None, "more than the whole ring"); + assert_eq!(ResultArea::short(u64::from(u32::MAX) + 1, 0, 100), None); + assert_eq!(ResultArea::short(101, 100, 100), None, "an empty ring that is still short"); +} + +/// A plan's ranges as `Host::card_before` places them ([`ResultArea::plan`]) +/// with the ring partly taken: those compared lie, in order and one +/// behind the other, in the run it placed, clear of the runs in the air; +/// what does not fit there or has no hashes is fetched whole and what is +/// only looked at is left out; and the tickets given back as +/// `Host::card_done` gives them back free the whole ring again. +#[test] +fn a_plan_compares_in_its_run_and_gives_it_back() { + // (name, pieces, has hashes from before, only looked at) + type R = (&'static str, u32, bool, bool); + let of = |r: &R| (r.1, r.2, r.3, false); + let mut area = ResultArea::new(100, true, true); + let (first, a) = area.plan(vec![("a", 60, true, false)], of); + assert_eq!(first.iter().map(|&(r, at, c)| (r.0, at, c)).collect::<Vec<_>>(), [("a", 0, true)]); + assert_eq!(area.room(), 40); + // 65 dwords wanted, 40 behind the first: the first 30 fit; the copy + // with no hashes is fetched whole, the look past the end is left + // out, the last range past the end is fetched whole. + let asked: Vec<R> = vec![("b", 30, true, false), ("c", 5, false, false), ("d", 20, true, true), ("e", 15, true, false)]; + let (second, b) = area.plan(asked, of); + assert_eq!( + second.iter().map(|&(r, at, c)| (r.0, at, c)).collect::<Vec<_>>(), + [("b", 60, true), ("c", 90, false), ("e", 90, false)] + ); + assert_eq!(area.room(), 10, "b took 60..90"); + // The first read: the next plan wraps to dword 0, b still in the air. + area.give_back(a); + let (third, c) = area.plan(vec![("f", 25, true, true), ("g", 25, true, false), ("h", 5, true, false)], of); + assert_eq!( + third.iter().map(|&(r, at, c)| (r.0, at, c)).collect::<Vec<_>>(), + [("f", 0, true), ("g", 25, true), ("h", 50, true)] + ); + for &(r, at, _) in &third { + assert!(at + r.1 <= 60, "{} clear of b at 60..90", r.0); + } + assert_eq!(area.room(), 5, "only 55..60 between the newest run and b"); + // A plan with nothing to compare takes nothing and gives nothing back. + let (fourth, d) = area.plan(vec![("i", 7, false, false), ("j", 3, false, true)], of); + assert_eq!(fourth.iter().map(|&(r, at, c)| (r.0, at, c)).collect::<Vec<_>>(), [("i", 55, false)]); + assert_eq!(d, 0); + // Given back out of order, then in: the whole ring is free. + area.give_back(c); + assert_eq!(area.room(), 5); + area.give_back(b); + area.give_back(d); + assert_eq!(area.room(), 100); + assert_eq!(area.plan(vec![("k", 100, true, false)], of).0[0].1, 0); +} + +/// A plan that does not fit behind the newest run goes to dword 0 if the +/// oldest has passed it, never across the end; the space of a plan given +/// back before those made earlier is free only when they are too. +#[test] +fn the_ring_wraps_between_runs_and_frees_in_order() { + let mut ring = ResultRing::new(100); + assert_eq!(ring.place(60), (0, 100)); + let a = ring.take(0, 60); + assert_eq!(ring.place(30), (60, 40)); + let b = ring.take(60, 30); + // 10 left at the end, nothing before the oldest: the longer run. + assert_eq!(ring.place(20), (90, 10)); + assert_eq!(ring.room(), 10); + ring.give_back(a); + // 10 at the end, 60 from 0: wrapped. + assert_eq!(ring.place(20), (0, 60)); + assert_eq!(ring.place(5), (90, 10)); + let c = ring.take(0, 50); + // Wrapped: only between the newest (ends at 50) and the oldest (60). + assert_eq!(ring.place(5), (50, 10)); + let d = ring.take(50, 10); + assert_eq!(ring.place(1), (60, 0)); + assert_eq!(ring.room(), 0); + // Given back out of order: nothing is free before `b` is. + ring.give_back(c); + assert_eq!(ring.room(), 0); + ring.give_back(b); + // `c` went with `b`: `d` holds 50..60. + assert_eq!(ring.place(40), (60, 40)); + assert_eq!(ring.place(45), (0, 50)); + ring.give_back(d); + assert_eq!(ring.place(100), (0, 100)); + // A plan that took nothing has nothing to give back. + assert_eq!(ring.take(0, 0), 0); + ring.give_back(0); + assert_eq!(ring.room(), 100); +} + +/// Plans of every size, up to three in the air, given back in order: a +/// run never crosses the end or another run in the air, and with none in +/// the air the whole ring is free. +#[test] +fn the_ring_never_overlaps_runs_in_the_air() { + let mut ring = ResultRing::new(1000); + let mut air: std::collections::VecDeque<(u64, u32, u32)> = std::collections::VecDeque::new(); + let mut seed = 0x2545_f491_u32; + for _ in 0..20_000 { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + let want = seed % 400; + let (at, room) = ring.place(want); + let used = want.min(room); + assert!(at + used <= 1000); + for &(_, from, to) in &air { + assert!(used == 0 || from == to || at + used <= from || to <= at, "{at}+{used} over {from}..{to}"); + } + air.push_back((ring.take(at, used), at, at + used)); + if air.len() > 3 || seed % 3 == 0 { + ring.give_back(air.pop_front().unwrap().0); + } + if air.is_empty() { + assert_eq!(ring.room(), 1000); + } + } +} + +/// On the card ([`super::card_pass`] with the host's compare): a plan +/// placed at the end of the results and the next one, wrapped to dword 0 +/// while the first is still unread, each find their flags at their own +/// dwords, and the second leaves the first's alone. +#[test] +fn card_compare_flags_land_where_the_ring_places_them() { + use super::{CreateEventW, INFINITE, WaitForSingleObject, card_pass, host, torn}; + use windows::Win32::Graphics::Direct3D12::{D3D12_FENCE_FLAG_NONE, ID3D12Fence}; + use windows::core::Interface; + let Some(host) = host() else { + eprintln!("no D3D12 device; the compare at a wrapped place was not tested"); + return; + }; + let work = host.make_card_work().expect("the card compare must be made"); + let cap = (work.differs.2 / 4) as u32; + const PIECE: usize = 64 << 10; + const PIECES: u32 = 3; + let size = PIECE * PIECES as usize; + // A first plan of all but 4 dwords; one of 3 behind it, at the end; + // the first is read: the next of 3 does not fit behind the second + // and goes to 0, the second still in the air. + let mut ring = ResultRing::new(cap); + let (at, room) = ring.place(cap - 4); + let first = ring.take(at, room.min(cap - 4)); + let (end, _) = ring.place(PIECES); + let second = ring.take(end, PIECES); + ring.give_back(first); + let (wrapped, room) = ring.place(PIECES); + assert_eq!((end, wrapped), (cap - 4, 0)); + assert!(room >= PIECES); + ring.take(wrapped, PIECES); + assert_eq!(ring.room(), cap - 4 - PIECES); + let _ = second; + + let (now, now_ptr) = host.shared_buffer(size as u64).expect("a buffer for the copy"); + let (hashes, _) = host.shared_buffer(16 * u64::from(PIECES)).expect("a buffer for the hashes"); + let content: Vec<u8> = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + let differs = work.differs.1 as *mut u32; + // SAFETY: the mappings hold `size` bytes and `cap` dwords. + unsafe { + std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size); + for d in (0..PIECES + 1).chain(cap - 4..cap) { + differs.add(d as usize).write_volatile(7); + } + } + let (allocator, list) = host.make_prelude().expect("a list"); + // SAFETY: plain objects of our own. + let (fence, event) = unsafe { + (host.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).unwrap(), CreateEventW(None, false, false, None).unwrap()) + }; + let span = crate::shadow::CardSpan { from: 0, to: size as u32, first: 0, pieces: PIECES, skew: 0 }; + let mut signalled = 0; + // One pass of the compare, at `at` in the results, run and waited for. + let mut pass = |at: u32, mode: u32| { + signalled += 1; + // SAFETY: the list's last run was waited for; live buffers, the + // compare's own root signature; the pieces lie in the copy and + // `at + PIECES` dwords in the results. + unsafe { + allocator.Reset().unwrap(); + list.Reset(&allocator, None).unwrap(); + list.SetComputeRootSignature(&work.root); + list.SetPipelineState(&work.pso); + list.SetComputeRootShaderResourceView(1, now.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, hashes.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + card_pass(&list, &span, size as u32, at, mode); + list.Close().unwrap(); + host.queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + host.queue.Signal(&fence, signalled).unwrap(); + fence.SetEventOnCompletion(signalled, event).unwrap(); + WaitForSingleObject(event, INFINITE); + } + }; + // SAFETY (each): inside the mappings, which the card has written. + let flags = |from: u32| -> [u32; 3] { [0, 1, 2].map(|p| unsafe { differs.add((from + p) as usize).read_volatile() }) }; + let set = |at: usize, value: u8| unsafe { now_ptr.add(at).write_volatile(value) }; + // The hashes, as the pass after the bytes went up stores them. + pass(0, 0); + assert_eq!(flags(0), [7, 7, 7]); + // The second plan, at the end: piece 1 changed. + set(PIECE + 99, content[PIECE + 99] ^ 0x40); + pass(end, 1); + // The third, wrapped to 0: piece 1 back as it was, piece 2 changed. + set(PIECE + 99, content[PIECE + 99]); + set(2 * PIECE + 5, content[2 * PIECE + 5] ^ 0x01); + pass(wrapped, 1); + let read = |from: u32| flags(from).map(|d| u32::from(torn::flagged(d))); + assert_eq!(read(end), [0, 1, 0], "the second plan's flags, read after the third ran"); + assert_eq!(read(wrapped), [0, 0, 1], "the third plan's flags, at dword 0"); + // SAFETY: inside the mapping. + let around = unsafe { [differs.add(PIECES as usize).read_volatile(), differs.add(cap as usize - 1).read_volatile()] }; + assert_eq!(around, [7, 7], "nothing outside the two runs"); + eprintln!("the compare's flags landed at dwords {end}.. and, wrapped, {wrapped}.."); +} diff --git a/d3d12/crates/leonida-gpu/src/host/retired_tests.rs b/d3d12/crates/leonida-gpu/src/host/retired_tests.rs new file mode 100644 index 0000000000..5aa5101de7 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/retired_tests.rs @@ -0,0 +1,54 @@ +use super::{Retired, retired_queue, retired_take}; +use std::collections::VecDeque; +use std::sync::{Arc, Mutex}; + +/// Says its name when it is dropped. +struct Told(&'static str, Arc<Mutex<Vec<&'static str>>>); +impl Drop for Told { + fn drop(&mut self) { + self.1.lock().unwrap().push(self.0); + } +} + +/// Whatever queue an object waits in, it goes when the submission it +/// waited for is behind it and not before; one behind a later number in +/// its queue (a thread overtaken) goes with that one, later than it could. +#[test] +fn what_is_retired_in_several_queues_goes_after_its_own_submission() { + let gone = Arc::new(Mutex::new(Vec::new())); + let queues: [Mutex<VecDeque<(u64, Retired)>>; 3] = [const { Mutex::new(VecDeque::new()) }; 3]; + let put = |queue: usize, at: u64, name: &'static str| { + queues[queue].lock().unwrap().push_back((at, Retired::Any(Box::new(Told(name, gone.clone()))))); + }; + put(0, 5, "a5"); + put(0, 7, "a7"); + put(1, 6, "b6"); + put(1, 4, "b4 behind b6"); + put(2, 9, "c9"); + let names = |taken: Vec<(u64, Retired)>| { + drop(taken); + std::mem::take(&mut *gone.lock().unwrap()) + }; + assert!(names(retired_take(&queues, 3)).is_empty()); + assert_eq!(names(retired_take(&queues, 5)), ["a5"]); + assert_eq!(names(retired_take(&queues, 6)), ["b6", "b4 behind b6"]); + assert!(names(retired_take(&queues, 8)) == ["a7"]); + assert_eq!(names(retired_take(&queues, 9)), ["c9"]); + assert!(queues.iter().all(|q| q.lock().unwrap().is_empty())); +} + +/// A thread keeps the queue it took, and threads take them in turn. +#[test] +fn a_thread_keeps_its_queue() { + if std::env::var_os("LEONIDA_RETIRE_QUEUES").is_some_and(|v| v == "0") { + return; + } + let mine = retired_queue(); + assert_eq!(retired_queue(), mine); + let others: Vec<usize> = (0..4).map(|_| std::thread::spawn(|| (retired_queue(), retired_queue())).join().unwrap()).map(|(a, b)| { + assert_eq!(a, b); + a + }).collect(); + assert!(others.iter().all(|&q| q < super::RETIRED_QUEUES)); + assert!(others.windows(2).any(|w| w[0] != w[1]), "{others:?}"); +} diff --git a/d3d12/crates/leonida-gpu/src/host/scratch_address_tests.rs b/d3d12/crates/leonida-gpu/src/host/scratch_address_tests.rs new file mode 100644 index 0000000000..9f07b08096 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/scratch_address_tests.rs @@ -0,0 +1,30 @@ +use super::*; + +/// A list's scratch memory is where its buffer is: the address kept +/// with a chunk is the buffer's own, pieces follow each other in whole +/// 256 bytes on the card as in the mapping, and a piece bigger than a +/// chunk has a buffer to itself. +#[test] +fn a_lists_scratch_memory_is_at_its_buffers_address() { + let Some(host) = host() else { + eprintln!("no D3D12 device; scratch addresses not tested"); + return; + }; + let list = host.new_list().unwrap(); + let (first, first_data) = list.scratch(100).unwrap(); + let (buffer, held, held_data) = list.scratch_held(300).unwrap(); + // SAFETY: a live buffer. + let base = unsafe { buffer.GetGPUVirtualAddress() }; + assert_eq!(first, base); + assert_eq!(held, base + 256); + assert_eq!(held_data as usize, first_data as usize + 256); + let (third, third_data) = list.scratch(1).unwrap(); + assert_eq!(third, base + 256 + 512); + assert_eq!(third_data as usize, first_data as usize + 256 + 512); + let (big, big_at, _) = list.scratch_held(SCRATCH_CHUNK + 1).unwrap(); + // SAFETY: a live buffer. + assert_eq!(big_at, unsafe { big.GetGPUVirtualAddress() }); + assert_ne!(big_at, base); + list.close(); + list.reset(); +} diff --git a/d3d12/crates/leonida-gpu/src/host/send.rs b/d3d12/crates/leonida-gpu/src/host/send.rs index d2a2ef0fd4..8abe025234 100644 --- a/d3d12/crates/leonida-gpu/src/host/send.rs +++ b/d3d12/crates/leonida-gpu/src/host/send.rs @@ -18,6 +18,11 @@ //! card copies them from there. Runs of a few words, which a refresh that //! sends only what changed makes many of, go as pairs of offset and value, //! stored by one dispatch per copy; the others as a copy each. +//! +//! The runs the title's CPU wrote are copied by the card straight out of +//! the CPU sides ([`direct`], `LEONIDA_SEND_DIRECT`): only what we write +//! into title memory at submission needs the submission's memory, and the +//! copy into it was a second CPU copy of every dirty byte. use super::*; use crate::shadow::Shadow; @@ -27,6 +32,151 @@ pub(super) fn own() -> bool { *ON.get_or_init(|| std::env::var_os("LEONIDA_SEND_OWN").is_none_or(|v| v != "0")) } +/// Whether runs the card copies out of the copies' CPU sides go up straight +/// from there, not through the submission's memory (`LEONIDA_SEND_DIRECT`, +/// on by default with [`own`]; `0`: every run through it, as before; +/// `LEONIDA_AB` can name it: the writes of ours that wait for straight sends +/// in the air go on doing so once it is off, [`numbered`]). +/// +/// Every dirty byte of a copy in the card's memory was copied twice on the +/// CPU: title memory into the CPU side (the refresh), then the CPU side into +/// the submission's memory, here, on the submitting thread (73-93 MB a frame +/// at 13-28 GB/s, 3-7 ms: `docs/findings.md`, the RX 7900 XT's placement +/// table, where the card copies out of the write-back CPU side as fast as +/// out of upload memory, 24-28 GB/s). Now the second copy is left to the +/// card, but where we write a copy at submission (`crate::shadow::direct`): +/// the title's buffer copies done on the CPU, whose bytes a submission in the +/// air must not read. Those pieces still go through the submission's memory, +/// and before we write one that a send in the air reads, the card is waited +/// for ([`wait`]; counted in the frame line: none in a steady state is what +/// `crate::shadow::direct`'s simulation says, the game is not measured). +/// The opened arenas, whose CPU side recording threads write, are left as +/// they were. +/// +/// What changes for the title's own CPU writes: a submission's card copy +/// may take what the title wrote after it was prepared, as before +/// [`own`] and as the arenas always did. The title is told of a submission +/// once the card has run it, so it does not write what that one reads. +pub(crate) fn direct() -> bool { + #[cfg(test)] + if let Some(on) = TEST_DIRECT.get() { + return on && own(); + } + own() && crate::toggled!("LEONIDA_SEND_DIRECT") +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`direct`], for its thread only. + pub(crate) static TEST_DIRECT: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; +} + +/// The fence the card signals behind each list that copies straight out of +/// CPU sides, with the number of its send ([`number`]); `None` if it could +/// not be made (then nothing goes straight). +fn fence(host: &Host) -> Option<&'static ID3D12Fence> { + static FENCE: OnceLock<Option<ID3D12Fence>> = OnceLock::new(); + FENCE + .get_or_init(|| { + // SAFETY: plain object creation. + let fence: ID3D12Fence = unsafe { host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE) }.ok()?; + name(&fence, || "leonida: sends straight out of CPU sides".into()); + Some(fence) + }) + .as_ref() +} + +/// The last send number given ([`number`]) and the last signalled. +static NUMBER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static SIGNALLED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A number for the send `Host::card_before` is about to make, if runs +/// may go straight ([`direct`]) and it sends something: 0 otherwise. The +/// caller holds the card's work (one send at a time) and signals it +/// ([`signal`]) once the list is on the queue, whatever the list holds: +/// a number noted in the air and never signalled would be waited for for +/// good. +pub(super) fn number(host: &Host, sends: bool) -> u64 { + if !sends || !direct() || fence(host).is_none() { + return 0; + } + NUMBER.fetch_add(1, Ordering::AcqRel) + 1 +} + +/// The list of send `number` (not 0) is on the queue. +pub(super) fn signal(host: &Host, number: u64) { + let Some(fence) = fence(host) else { + return; + }; + // SAFETY: a live queue and fence; numbers rise (given and signalled + // under the card's work). + if unsafe { host.queue.Signal(fence, number) }.is_ok() { + SIGNALLED.fetch_max(number, Ordering::AcqRel); + } +} + +/// The last send number given out: a write at submission noted now is +/// past it ([`crate::shadow::direct`]). +pub(crate) fn last_number() -> u64 { + NUMBER.load(Ordering::Acquire) +} + +/// Whether a send was ever numbered, so may have copied straight out of a +/// CPU side and be in the air: a write of ours at submission is then +/// guarded (`crate::shadow::copying`), whatever [`direct`] says now. It is +/// not the switch: `LEONIDA_AB` turns that at a present, with sends that +/// went straight still on the queue, and a write unguarded then went under +/// one (`a_copy_of_ours_waits_for_a_straight_send_once_the_switch_is_off`). +/// With the switch off from the start nothing is numbered and the guard +/// costs nothing. +pub(crate) fn numbered() -> bool { + last_number() != 0 +} + +/// The last send the card is past: `u64::MAX` without a fence, or when the +/// device is gone (its fence says `u64::MAX`, and nothing waits on it). +pub(crate) fn reached() -> u64 { + let Some(fence) = host().and_then(fence) else { + return u64::MAX; + }; + // SAFETY: a plain query. + unsafe { fence.GetCompletedValue() } +} + +/// Waits until the card is past send `number` ([`direct`]): we are about to +/// write what it copies out of a CPU side. Counted for the frame line. +pub(crate) fn wait(number: u64) { + if number == 0 || reached() >= number { + return; + } + let Some(fence) = host().and_then(fence) else { + return; + }; + if number > SIGNALLED.load(Ordering::Acquire) { + // (Not on the queue yet: only the thread that sends could signal + // it, and it is this one. Not seen; would hang.) + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(number, "a send straight out of a CPU side waited for before it was on the queue")); + return; + } + let began = std::time::Instant::now(); + // SAFETY: a live fence; with no event the call returns once the fence + // has the value (or the device is gone). + let _ = unsafe { fence.SetEventOnCompletion(number, HANDLE::default()) }; + DIRECT_STATS[1].fetch_add(1, Ordering::Relaxed); + DIRECT_STATS[2].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); +} + +/// Since the last frame-rate line ([`direct`]): bytes the card copied +/// straight out of CPU sides, waits for the card before a write of ours, +/// microseconds of them. +pub(super) static DIRECT_STATS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Since the last frame-rate line: bytes the CPU wrote straight into card +/// sides in card memory it maps (`LEONIDA_BAR_BUFFERS_MB`, +/// `crate::shadow::Shadow::card_bar`), and the runs. +pub(super) static MAPPED_STATS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + /// Runs up to this many bytes go as pairs. const SHORT: usize = 256; @@ -105,24 +255,275 @@ fn pass(host: &Host) -> Option<&'static Pass> { .as_ref() } -/// Memory a submission's sends come from, mapped. +/// Memory a submission's sends come from, mapped: a buffer of its own, or +/// a carve of the ring's ([`ring`]). pub(super) struct Memory { buffer: ID3D12Resource, + /// The mapping at `at`. data: usize, + /// Where the memory begins in `buffer`: 0 for a buffer of its own. + at: u64, size: u64, + /// The carve's ticket in [`RING`]; 0 for a buffer of its own. + ticket: u64, } // SAFETY: a D3D12 object (free-threaded) and its mapping, with one owner. unsafe impl Send for Memory {} +impl Drop for Memory { + /// A carve dropped without [`give_back`] (a plan dropped without + /// `Host::card_done`, which nothing does now) comes back once every + /// submission running now has finished ([`crate::host::retire`]): never + /// while the card may read it, and never held for good, where the ring + /// would keep every carve behind it. + fn drop(&mut self) { + let ticket = std::mem::take(&mut self.ticket); + if ticket != 0 { + crate::host::retire(Unreturned(ticket, self.size)); + } + } +} + +/// A carve that comes back when it is dropped ([`Memory`]'s drop). +struct Unreturned(u64, u64); + +impl Drop for Unreturned { + fn drop(&mut self) { + OUT.fetch_sub(self.1, Ordering::Relaxed); + ring_give_back(self.0); + } +} + +/// One of the ring's buffers, mapped ([`ring`]). +#[derive(Clone)] +pub(super) struct Block { + buffer: ID3D12Resource, + data: usize, +} + +// SAFETY: a D3D12 object (free-threaded) and its mapping; the ring hands +// out carves that do not overlap. +unsafe impl Send for Block {} + +/// The ring the sends come from with [`ring`]. +static RING: Mutex<super::sendring::Ring<Block>> = Mutex::new(super::sendring::Ring::new()); + +/// Whether a submission's sends come from a ring of buffers +/// (`super::sendring`; `LEONIDA_SEND_RING`, on by default with [`own`]; +/// `0`: a buffer of its own from the spares, as before; `LEONIDA_AB` can +/// name it: a carve goes back to the ring and a buffer to the spares, +/// whichever the switch says by then). +/// +/// On by default: the bytes on the card are the same, read from another +/// offset; the hazard is a carve reused while a submission in the air reads +/// it, and the ring frees nothing ahead of what was carved before it, +/// landed or not (`super::sendring`'s tests, out of order over 20,000 +/// carves), and only what `Host::card_done` gives back, as the spares were. +/// On the card: `submissions_in_the_air_each_send_their_bytes_from_one_ring`. +pub(crate) fn ring() -> bool { + #[cfg(test)] + if let Some(on) = TEST_RING.get() { + return on && own(); + } + own() && crate::toggled!("LEONIDA_SEND_RING") +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`ring`], for its thread only. + pub(crate) static TEST_RING: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; +} + +/// Since the last frame-rate line: buffers made for sends (spares or the +/// ring's) and their bytes. +pub(super) static MADE_STATS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// A mapped buffer of `size` bytes for sends: in the card's memory with +/// [`on_card`] where it can be, else upload memory. +fn make(host: &Host, size: u64, what: &'static str) -> Option<(ID3D12Resource, usize)> { + let mapped = if on_card() { host.mapped_card_buffer(size, false) } else { None }; + let (buffer, data) = match mapped { + Some(made) => made, + None => host.upload_buffer(size)?, + }; + name(&buffer, || what.into()); + MADE_STATS[0].fetch_add(1, Ordering::Relaxed); + MADE_STATS[1].fetch_add(size, Ordering::Relaxed); + Some((buffer, data as usize)) +} + +/// A carve of `size` bytes of the ring ([`ring`]), with a buffer made for +/// it if none has room (outside the ring's lock: only the thread that +/// holds the card's work carves, and a give back meanwhile only leaves +/// more room). +fn carve(host: &Host, size: u64) -> Option<Memory> { + let now = crate::host::coarse_ms(); + let asked = RING.lock().unwrap_or_else(|e| e.into_inner()).carve(size, now); + let (carved, gone) = match asked { + Ok(carved) => (carved, Vec::new()), + Err(made) => { + let (buffer, data) = make(host, made, "bytes submissions send up, a ring")?; + RING.lock().unwrap_or_else(|e| e.into_inner()).add(size, now, Block { buffer, data }, made) + } + }; + release(gone); + Some(Memory { + data: carved.memory.data + carved.at as usize, + buffer: carved.memory.buffer, + at: carved.at, + size: size.max(1).next_multiple_of(super::sendring::ALIGN), + ticket: carved.ticket, + }) +} + +/// The ring's buffers that went, released once every submission running +/// now has finished. +fn release(gone: Vec<Block>) { + for block in gone { + crate::host::retire_resource(block.buffer); + } +} + +/// The carve of `ticket` came back. +fn ring_give_back(ticket: u64) { + let gone = RING.lock().unwrap_or_else(|e| e.into_inner()).give_back(ticket); + release(gone); +} + /// What submissions that have run gave back. -static SPARE: Mutex<Vec<Memory>> = Mutex::new(Vec::new()); +static SPARE: Mutex<Pool<Memory>> = Mutex::new(Pool::new()); + +/// Bytes of memory held by submissions not done with (taken, not given +/// back yet): for the frame line. +static OUT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// At most this much is kept (of the card's memory, with [`on_card`]). fn kept() -> u64 { if on_card() { 256 << 20 } else { 768 << 20 } } +/// Whether the memory sends come from is made to the size asked for and +/// given back when no submission took it for a while (`LEONIDA_SEND_TRIM`, +/// on by default; `0`: as before; `LEONIDA_AB` can name it). +/// +/// Before, each was made in doubles of at least 8 MiB ([`made_size`]): a +/// submission that sent 4 KiB held 8 MiB of the upload heap until it had +/// landed, and one of 9 MiB held 16; with the relay's submissions in the air +/// the bytes held were up to two to three times those sent (from the +/// rounding, with some 3 MB a submission at 73-93 MB a frame: a hypothesis, +/// not counted). And what came back was kept up to [`kept`] for the rest of +/// the run: after a burst (the world loading) up to 768 MiB of the PC's +/// memory that the card maps, in menus too, with nothing that ever trimmed +/// it. A spare however much larger served what asked, so a burst's largest +/// buffer, taken by the small submissions after it, was never idle either. +/// +/// Now memory is made to within an eighth of the size asked for +/// ([`STEPS`]), a spare serves only what asks for more than half of it or +/// would be made as large ([`SLACK`]), and the sweep ([`let_go_idle`]) lets go of what no +/// submission took for the idle time of the PC's memory +/// ([`crate::host::ram_idle_ms`]; the card's, [`crate::host::vram_idle_ms`], +/// with [`on_card`]), and while the PC's memory is pressured of all but +/// what came back in the last [`PRESSED_MS`]. +/// How often memory is made again is not measured: the frame line counts +/// the bytes held and kept. +fn trim() -> bool { + crate::toggled!("LEONIDA_SEND_TRIM") +} + +/// Memory is made in sizes at most this many to a power of two apart: an +/// eighth of the power of two at or below the size asked for, so what is +/// made is less than an eighth over what is asked ([`trim`]). +const STEPS: u64 = 8; +/// The least memory made ([`trim`]). Sends are some 3 MB a submission on +/// average (the frame's 73-93 MB over some 30 submissions); those of a few +/// words take this. A buffer of up to `crate::pool::small::MOST` is placed +/// in a shared block of the upload heap. +const LEAST: u64 = 1 << 20; +/// The least before ([`trim`] off), made in doubles. +const LEAST_BEFORE: u64 = 8 << 20; +/// A spare serves what asks for more than this fraction of it, or for which +/// as large a one would be made (sends of up to [`LEAST`]): what a +/// submission holds is less than twice what it sends, or what would be made +/// for it ([`trim`], [`most_served`]). Without a bound a burst's largest +/// buffer served every small submission after it, and was never idle; with +/// one by twice what would be made, a spare of 2 MiB served a send of 4 KiB +/// and one of 2.25 MiB a send of 1.01 MiB. +const SLACK: u64 = 2; + +/// The size of memory made for `size` bytes of sends: within an eighth +/// ([`STEPS`]) with [`trim`], else in doubles of at least 8 MiB, as before. +pub(super) fn made_size(size: u64, trim: bool) -> u64 { + if !trim { + return size.max(LEAST_BEFORE).next_power_of_two(); + } + if size <= LEAST { + return LEAST; + } + let below = 1u64 << (63 - size.leading_zeros()); + size.next_multiple_of(below / STEPS) +} + +/// The largest spare that serves `size` bytes of sends: with [`trim`] one +/// under [`SLACK`] times them, or what would be made for them if that is +/// more; any without. +fn most_served(size: u64, trim: bool) -> u64 { + if !trim { + return u64::MAX; + } + made_size(size, true).max(size.saturating_mul(SLACK).saturating_sub(1)) +} + +/// Spare memory of submissions that have run: its size, the memory, and when +/// it came back ([`crate::host::coarse_ms`]). +struct Pool<M> { + spare: Vec<(u64, M, u64)>, +} + +impl<M> Pool<M> { + const fn new() -> Self { + Pool { spare: Vec::new() } + } + + /// Bytes kept. + fn bytes(&self) -> u64 { + self.spare.iter().map(|&(size, ..)| size).sum() + } + + /// The smallest spare of at least `size` bytes and at most `most`. + fn take(&mut self, size: u64, most: u64) -> Option<M> { + let fit = self + .spare + .iter() + .enumerate() + .filter(|(_, (s, ..))| (size..=most).contains(s)) + .min_by_key(|(_, (s, ..))| *s) + .map(|(i, _)| i)?; + Some(self.spare.swap_remove(fit).1) + } + + /// Keeps `memory` of `size` bytes, come back at `now`; past `kept` bytes + /// the largest go (the newcomer too, if it is one of them). Returns + /// those that go, for the caller to release once the lock is released. + fn give(&mut self, size: u64, memory: M, now: u64, kept: u64) -> Vec<M> { + self.spare.push((size, memory, now)); + self.spare.sort_by_key(|&(s, ..)| std::cmp::Reverse(s)); + let mut bytes = self.bytes(); + let mut gone = 0; + while bytes > kept && gone < self.spare.len() { + bytes -= self.spare[gone].0; + gone += 1; + } + self.spare.drain(..gone).map(|(_, m, _)| m).collect() + } + + /// Takes out the spares that came back `idle_ms` or more before `now`; + /// the others keep their order. + fn idle(&mut self, now: u64, idle_ms: u64) -> Vec<M> { + self.spare.extract_if(.., |&mut (.., at)| now.saturating_sub(at) >= idle_ms).map(|(_, m, _)| m).collect() + } +} + /// Whether the memory lies in the card's memory, written by the CPU through /// the bus (`LEONIDA_SEND_BAR=1`): the copies on the card's drawing queue, which /// nothing overlaps, then cross no bus. In a captured frame they took 5.4 ms of @@ -136,48 +537,121 @@ fn on_card() -> bool { } fn memory(host: &Host, size: u64) -> Option<Memory> { - { - let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); - let fit = spare.iter().enumerate().filter(|(_, m)| m.size >= size).min_by_key(|(_, m)| m.size).map(|(i, _)| i); - if let Some(i) = fit { - return Some(spare.swap_remove(i)); - } + if ring() { + let memory = carve(host, size)?; + OUT.fetch_add(memory.size, Ordering::Relaxed); + return Some(memory); } - // By doubles, so that the next of about this size finds it: what - // submissions send differs from frame to frame. - let size = size.max(8 << 20).next_power_of_two(); - let mapped = if on_card() { host.mapped_card_buffer(size, false) } else { None }; - let (buffer, data) = match mapped { - Some(made) => made, - None => host.upload_buffer(size)?, + let trim = trim(); + let spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size, most_served(size, trim)); + let memory = match spare { + Some(memory) => memory, + None => { + // A little over the size (by doubles without `trim`), so that + // the next of about this size finds it: what submissions send + // differs from frame to frame. + let size = made_size(size, trim); + let (buffer, data) = make(host, size, "bytes a submission sends up")?; + Memory { buffer, data, at: 0, size, ticket: 0 } + } }; - name(&buffer, || "bytes a submission sends up".into()); - Some(Memory { - buffer, - data: data as usize, - size, - }) + OUT.fetch_add(memory.size, Ordering::Relaxed); + Some(memory) } -/// The submission has run. -pub(super) fn give_back(memory: Memory) { - let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); - spare.push(memory); - spare.sort_by_key(|m| std::cmp::Reverse(m.size)); - while spare.iter().map(|m| m.size).sum::<u64>() > kept() { - spare.remove(0); +/// The submission has run. What goes past [`kept`] is released after the +/// lock is released, as [`let_go_idle`]'s is: the thread that lands flights +/// gives back and the submitting thread takes under it, and the release of +/// a buffer of up to hundreds of MiB ran under it before. +/// A carve of the ring ([`ring`]) is free again once those carved before +/// it in its buffer are. +pub(super) fn give_back(mut memory: Memory) { + OUT.fetch_sub(memory.size, Ordering::Relaxed); + let ticket = std::mem::take(&mut memory.ticket); + if ticket != 0 { + ring_give_back(ticket); + return; + } + let now = crate::host::coarse_ms(); + let gone = SPARE.lock().unwrap_or_else(|e| e.into_inner()).give(memory.size, memory, now, kept()); + for memory in gone { + crate::host::retire_resource(memory.buffer.clone()); } } +/// While the PC's memory is pressured, spares that came back less than this +/// long ago are kept all the same ([`let_go_idle`]): a frame or two of +/// submissions at the world's frame rates, the memory the next submissions +/// take. With none kept, each sweep under pressure let go of that too, the +/// next some 30 submissions made theirs anew (above `crate::pool::small::MOST` +/// a committed resource each, 1.6 ms an upload buffer in `docs/findings.md`), +/// and what was let go waited in +/// [`crate::host::retire_resource`]'s line meanwhile: more held, not less. +const PRESSED_MS: u64 = 250; + +/// How long a spare must not have been taken to go ([`let_go_idle`]): +/// [`PRESSED_MS`] while the PC's memory is `pressured`, else `idle_ms`. +fn idle_for(pressured: bool, idle_ms: impl FnOnce() -> u64) -> u64 { + if pressured { PRESSED_MS } else { idle_ms() } +} + +/// Once a second, from the host's sweep: lets go of the memory no +/// submission took for the idle time ([`trim`]), and while the PC's memory +/// is `pressured` of all but what came back in the last [`PRESSED_MS`]. +/// Memory is spare only once its submission has landed; it goes through +/// [`crate::host::retire_resource`] all the same, as idle spares of copies +/// of views do. The ring ([`ring`]) closes a buffer more than twice what +/// the bytes in the air lately ask for, and lets every buffer go after the +/// idle time with no carve (`super::sendring::Ring::let_go`), whatever +/// [`trim`] says. +pub(super) fn let_go_idle(host: Option<&Host>, pressured: bool) { + if !own() { + return; + } + let idle_ms = idle_for(pressured, || { + if on_card() { + crate::host::vram_idle_ms(host.and_then(Host::video_memory)) + } else { + crate::host::ram_idle_ms(crate::host::available_physical_ram()) + } + }); + let now = crate::host::coarse_ms(); + release(RING.lock().unwrap_or_else(|e| e.into_inner()).let_go(now, idle_ms)); + if !trim() { + return; + } + let gone = SPARE.lock().unwrap_or_else(|e| e.into_inner()).idle(now, idle_ms); + for memory in gone { + crate::host::retire_resource(memory.buffer.clone()); + } +} + +/// For the frame line: bytes of memory held by submissions not done with, +/// bytes kept spare (the free bytes of the ring's open buffer with the +/// spares; those of closed buffers draining are never carved again), and +/// the ring's buffers ([`ring`]; a carve given back before those before it +/// counts as held until they are). +pub(super) fn held() -> (u64, u64, usize) { + let (free, buffers) = { + let ring = RING.lock().unwrap_or_else(|e| e.into_inner()); + (ring.free(), ring.buffers()) + }; + (OUT.load(Ordering::Relaxed), SPARE.lock().unwrap_or_else(|e| e.into_inner()).bytes() + free, buffers) +} + /// Since the last frame-rate line: bytes copied, runs copied, words stored, /// microseconds of taking them out of the CPU sides (with [`take_beside`], /// and of waiting for the copies given to the kept threads: [`Own::settle`]). pub(super) static STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; /// One copy's sends: ranges copied (offset in the copy, in the memory, -/// bytes), and its pairs (where in the memory, how many). +/// bytes), ranges the card copies straight out of the CPU side (offset, +/// bytes; [`direct`]), and its pairs (where in the memory, how many). struct Copy { runs: Vec<(usize, u64, usize)>, + straight: Vec<(usize, usize)>, + /// The short runs that go as pairs, in order. + shorts: Vec<(usize, usize)>, pairs: (u64, u32), } @@ -239,7 +713,7 @@ pub(crate) fn beside_line() -> Option<String> { }) } -/// Where a submission's bytes are taken to. +/// Where a submission's bytes are taken to: none if all go straight. pub(super) struct Own { /// The long copies into the memory, while they are not waited for /// ([`take_beside`]). (First: dropped, it waits, before the memory @@ -248,47 +722,93 @@ pub(super) struct Own { /// With `LEONIDA_SEND_TAKE_BESIDE=check`: those copies (from, to, /// bytes). moved: Vec<(usize, usize, usize)>, - memory: Memory, + memory: Option<Memory>, copies: Vec<Copy>, } /// Runs whose pairs are one piece of work. const RUNS_AT_A_TIME: usize = 4096; -/// Takes what `dirty` sends up out of the CPU sides. -pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)]) -> Option<Own> { +/// Takes what `dirty` sends up out of the CPU sides; `number`: the send's +/// ([`number`]; 0: nothing goes straight). +/// +/// A copy whose card side lies in card memory the CPU maps +/// (`LEONIDA_BAR_BUFFERS_MB`, `Shadow::card_bar`) has what may go straight +/// written into that side here, by the CPU, out of its CPU side, short runs +/// as well as long ones: no card copy, no pairs. The CPU only writes that +/// memory (a read would cross the bus a few bytes at a time). What may not go +/// straight goes through the submission's memory as for any copy +/// (`Shadow::card_split_mapped`). +pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)], number: u64) -> Option<Own> { let began = std::time::Instant::now(); pass(host)?; // Runs of whole words of the copy: only those are pairs. (A byte beside // them in a word may be the card's.) let short = |&(a, b): &(usize, usize)| short(a, b - a); + let reached = if number != 0 { reached() } else { 0 }; let mut at = 0u64; let mut copies = Vec::with_capacity(dirty.len()); - for (_, ranges) in dirty { - let mut runs = Vec::new(); - for &(a, b) in ranges.iter().filter(|r| !short(r)) { - runs.push((a, at, b - a)); - at += ((b - a) as u64).next_multiple_of(16); - } - let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum(); - copies.push(Copy { runs, pairs: (at, words as u32) }); + // Into card memory the CPU maps: (from, to, bytes). + let mut mapped: Vec<(usize, usize, usize)> = Vec::new(); + for (shadow, ranges) in dirty { + let (mut runs, mut straight) = (Vec::new(), Vec::new()); + let bar = shadow.card_bar().filter(|_| number != 0); + let from = shadow.card_data() as usize; + let (parts, mut shorts) = match bar { + Some(_) => ( + shadow.card_split_mapped(ranges.iter().copied(), number, reached).unwrap_or_else(|| ranges.iter().map(|&(a, b)| (a, b, false)).collect()), + Vec::new(), + ), + None => { + let long = ranges.iter().copied().filter(|r| !short(r)); + let parts = match (number != 0).then(|| shadow.card_split(long.clone(), number, reached)).flatten() { + Some(parts) => parts, + None => long.map(|(a, b)| (a, b, false)).collect(), + }; + (parts, ranges.iter().copied().filter(short).collect()) + } + }; + for (a, b, direct) in parts { + match bar { + Some(side) if direct => mapped.push((from + a, side + a, b - a)), + _ if direct => straight.push((a, b - a)), + Some(_) if short(&(a, b)) => shorts.push((a, b)), + _ => { + runs.push((a, at, b - a)); + at += ((b - a) as u64).next_multiple_of(16); + } + } + } + let words: usize = shorts.iter().map(|r| (r.1 - r.0) / 4).sum(); + copies.push(Copy { runs, straight, shorts, pairs: (at, words as u32) }); at += (words as u64 * 8).next_multiple_of(16); } + let straight: u64 = copies.iter().flat_map(|c| &c.straight).map(|s| s.1 as u64).sum(); + DIRECT_STATS[0].fetch_add(straight, Ordering::Relaxed); + let written: u64 = mapped.iter().map(|m| m.2 as u64).sum(); + if !mapped.is_empty() { + MAPPED_STATS[0].fetch_add(written, Ordering::Relaxed); + MAPPED_STATS[1].fetch_add(mapped.len() as u64, Ordering::Relaxed); + crate::shadow::copy_all(mapped); + // Out of the processor's write-combining buffers before the list + // that the submission's shaders follow goes to the queue. + std::sync::atomic::fence(Ordering::SeqCst); + } if at == 0 { - return None; + return (straight > 0 || written > 0).then_some(Own { beside: None, moved: Vec::new(), memory: None, copies }); } let memory = memory(host, at)?; let mut moves: Vec<(usize, usize, usize)> = Vec::new(); let mut work: Vec<(usize, &[(usize, usize)], usize)> = Vec::new(); - for ((shadow, ranges), copy) in dirty.iter().zip(&copies) { + for ((shadow, _), copy) in dirty.iter().zip(&copies) { let from = shadow.card_data() as usize; moves.extend(copy.runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n))); // (80,000 runs of some words a frame: in pieces of work.) let mut to = memory.data + copy.pairs.0 as usize; - for ranges in ranges.chunks(RUNS_AT_A_TIME) { - let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum(); + for shorts in copy.shorts.chunks(RUNS_AT_A_TIME) { + let words: usize = shorts.iter().map(|r| (r.1 - r.0) / 4).sum(); if words > 0 { - work.push((from, ranges, to)); + work.push((from, shorts, to)); to += words * 8; } } @@ -296,12 +816,22 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, us let one = |i: usize| { let (from, ranges, to) = work[i]; let mut to = to as *mut [u32; 2]; - for &(a, b) in ranges.iter().filter(|r| short(r)) { + for &(a, b) in ranges { for offset in (a..b).step_by(4) { - // SAFETY: inside the copy's mapping (its CPU side, which - // the thread that asked, and waits, alone writes in these - // ranges) and inside the memory, which has room for every - // pair, a piece of work's behind the last one's. + // SAFETY: inside the copy's mapping (its CPU side) and + // inside the memory, which has room for every pair, a piece + // of work's behind the last one's. The thread that asked, + // and waits, alone writes in these ranges of a CPU side, + // but for a side that is memory of ours (`Shadow::opened`, + // an arena of `crate::memory`'s): there a recording thread + // may write a word while it is read here, or while + // `copy_all` below reads its run. Two plain accesses at + // once are a race the language leaves undefined. What the + // processor reads is the old bytes or the new ones, and + // the writer resends what it wrote after it wrote it, so + // the next submission sends the new ones. (Before, a + // refresh read the arena through the kernel while it was + // written, with the same outcome.) unsafe { let word = ((from + offset) as *const u32).read_unaligned(); to.write([offset as u32, word]); @@ -323,7 +853,7 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, us Some(crate::shadow::copy_all_beside(moves)) }; STATS[3].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); - Some(Own { beside, moved, memory, copies }) + Some(Own { beside, moved, memory: Some(memory), copies }) } impl Own { @@ -376,11 +906,21 @@ impl Own { let dest = D3D12_RESOURCE_STATE_COPY_DEST; let (mut first, mut last) = (Vec::new(), Vec::new()); for ((shadow, _), copy) in dirty.iter().zip(&self.copies) { - for &(a, from, n) in ©.runs { - // SAFETY: the caller's; live buffers, ranges inside them. - unsafe { list.CopyBufferRegion(&shadow.buffer, a as u64, &self.memory.buffer, from, n as u64) }; + if let Some(memory) = &self.memory { + for &(a, from, n) in ©.runs { + // SAFETY: the caller's; live buffers, ranges inside them. + unsafe { list.CopyBufferRegion(&shadow.buffer, a as u64, &memory.buffer, memory.at + from, n as u64) }; + } + } + if let Some((staging, ..)) = shadow.card_sides() { + for &(a, n) in ©.straight { + // SAFETY: the caller's; live buffers (the plan holds the + // copy until its submission has run), ranges inside them. + unsafe { list.CopyBufferRegion(&shadow.buffer, a as u64, &staging, a as u64, n as u64) }; + } } - let mut state = (looked(shadow) || !copy.runs.is_empty()).then_some(dest); + let sent = !copy.runs.is_empty() || !copy.straight.is_empty(); + let mut state = (looked(shadow) || sent).then_some(dest); if copy.pairs.1 > 0 { if let Some(was) = state { first.push(transition(&shadow.buffer, was, write)); @@ -390,7 +930,7 @@ impl Own { let hashed = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); if let Some(was) = state && hashed - && (!copy.runs.is_empty() || copy.pairs.1 > 0) + && (sent || copy.pairs.1 > 0) { last.push(transition(&shadow.buffer, was, read)); } @@ -401,11 +941,13 @@ impl Own { list.ResourceBarrier(&first); } if let Some(pass) = pass(host) + && let Some(memory) = &self.memory && self.copies.iter().any(|c| c.pairs.1 > 0) { list.SetComputeRootSignature(&pass.root); list.SetPipelineState(&pass.pso); - list.SetComputeRootShaderResourceView(1, self.memory.buffer.GetGPUVirtualAddress()); + // (A carve's address is a multiple of `sendring::ALIGN`.) + list.SetComputeRootShaderResourceView(1, memory.buffer.GetGPUVirtualAddress() + memory.at); for ((shadow, _), copy) in dirty.iter().zip(&self.copies).filter(|(_, c)| c.pairs.1 > 0) { list.SetComputeRootUnorderedAccessView(2, shadow.buffer.GetGPUVirtualAddress()); const MOST: u32 = 64 * D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; @@ -429,7 +971,1497 @@ impl Own { /// The memory, to be kept until the submission has run. (The copies /// given to the kept threads are waited for before it returns, if /// [`Own::settle`] has not.) - pub(super) fn memory(self) -> Memory { + pub(super) fn memory(self) -> Option<Memory> { self.memory } } + +#[cfg(test)] +mod pool_tests { + use super::{LEAST, Pool, idle_for, made_size, most_served}; + + const MIB: u64 = 1 << 20; + + /// What is made for a submission's sends is less than an eighth over + /// them: in doubles of at least 8 MiB a send of 4 KiB held 8 MiB and + /// one of 9 MiB held 16 until its submission had landed. + #[test] + fn memory_made_for_sends_is_within_an_eighth_of_them() { + for size in [4 << 10, MIB - 1, MIB + 1, 3_000_000, 8 * MIB, 8 * MIB + 1, 9 * MIB, 130 * MIB, 513 * MIB] { + let made = made_size(size, true); + assert!(made >= size, "{made} made for {size}"); + assert!(made == LEAST || made * 8 < size * 9, "{made} bytes made for {size}: an eighth over or more"); + } + assert_eq!(made_size(4 << 10, true), LEAST); + // Before: doubles of at least 8 MiB. + assert_eq!(made_size(4 << 10, false), 8 * MIB); + assert_eq!(made_size(9 * MIB, false), 16 * MIB); + assert_eq!(made_size(130 * MIB, false), 256 * MIB); + } + + /// What a burst left kept goes once no submission took it for the idle + /// time, and what came back since stays: nothing trimmed the spare + /// memory, and up to 768 MiB of it stayed for the rest of the run. + #[test] + fn a_bursts_memory_goes_once_idle() { + const IDLE_MS: u64 = 10_000; + const KEPT: u64 = 768 * MIB; + let mut pool: Pool<u32> = Pool::new(); + // A burst: three of 256 MiB come back at 1 s, all kept. + for id in 0..3 { + assert!(pool.give(256 * MIB, id, 1_000, KEPT).is_empty()); + } + // A fourth is past what is kept: one of the largest goes, out of + // the pool (released by the caller, after the lock). + assert_eq!(pool.give(256 * MIB, 3, 1_000, KEPT).len(), 1); + assert_eq!(pool.bytes(), KEPT); + // A small one comes back at 9 s, and one more large one makes room. + assert_eq!(pool.give(4 * MIB, 9, 9_000, KEPT).len(), 1); + assert!(pool.idle(10_999, IDLE_MS).is_empty(), "nothing has been idle that long"); + let gone = pool.idle(1_000 + IDLE_MS, IDLE_MS); + assert_eq!(gone.len(), 2, "{} of the burst's two left let go", gone.len()); + assert_eq!(pool.bytes(), 4 * MIB); + assert_eq!(pool.idle(9_000 + IDLE_MS, IDLE_MS), [9]); + assert_eq!(pool.bytes(), 0); + } + + /// While the PC's memory is pressured the sweep lets go of what no + /// submission took for a while, not of what came back a moment ago: + /// that went too, and the next submissions made theirs anew while it + /// waited to be released. + #[test] + fn under_pressure_what_just_came_back_stays() { + let mut pool: Pool<u32> = Pool::new(); + pool.give(4 * MIB, 1, 1_000, u64::MAX); + pool.give(4 * MIB, 2, 1_900, u64::MAX); + pool.give(4 * MIB, 3, 1_984, u64::MAX); + let idle_ms = idle_for(true, || unreachable!("the idle time is not asked under pressure")); + assert_eq!(pool.idle(2_000, idle_ms), [1], "under pressure"); + assert_eq!(pool.bytes(), 8 * MIB); + // Without pressure the idle time holds. + assert!(pool.idle(2_000, idle_for(false, || 10_000)).is_empty()); + } + + /// A burst's large spare does not serve small sends: taken by every + /// small submission after the burst, it was never idle and never went. + #[test] + fn small_sends_leave_a_bursts_large_spare_idle() { + let mut pool: Pool<u32> = Pool::new(); + pool.give(256 * MIB, 1, 0, u64::MAX); + let small = 3_000_000; + assert_eq!(pool.take(small, most_served(small, true)), None, "a 256 MiB spare served a send of 3 MB"); + assert_eq!(pool.take(small, most_served(small, false)), Some(1), "before, it did"); + pool.give(256 * MIB, 1, 0, u64::MAX); + let large = 200 * MIB; + assert_eq!(pool.take(large, most_served(large, true)), Some(1), "a send of 200 MiB takes it"); + } + + /// What a submission holds of a spare is less than twice what it sends, + /// or no more than would be made for it: bounded by twice what would be + /// made, a spare of 2 MiB served a send of 4 KiB, and one of 2.25 MiB a + /// send of 1.01 MiB. + #[test] + fn a_spare_holds_less_than_twice_the_send() { + for size in [4 << 10, 512 << 10, MIB - 1, MIB, MIB + 1, MIB + MIB / 100, 3_000_000, 9 * MIB, 130 * MIB] { + let (most, made) = (most_served(size, true), made_size(size, true)); + assert!(most >= made, "a spare as large as is made for {size} does not serve it"); + assert!(most < 2 * size || most == made, "a spare of {most} serves a send of {size}"); + } + let mut pool: Pool<u32> = Pool::new(); + pool.give(2 * MIB, 2, 0, u64::MAX); + pool.give(MIB, 1, 0, u64::MAX); + let small = 4 << 10; + assert_eq!(pool.take(small, most_served(small, true)), Some(1), "the least made serves a send of 4 KiB"); + assert_eq!(pool.take(small, most_served(small, true)), None, "a spare of 2 MiB served a send of 4 KiB"); + let half = 1_200_000; + assert_eq!(pool.take(half, most_served(half, true)), Some(2), "a send of more than half takes it"); + pool.give(2 * MIB + MIB / 4, 3, 0, u64::MAX); + let over = MIB + MIB / 100; + assert_eq!(pool.take(over, most_served(over, true)), None, "a spare of 2.25 MiB served a send of 1.01 MiB"); + assert_eq!(pool.take(half, most_served(half, true)), Some(3)); + } + + /// Submissions of 1 to 5 MiB, 30 a frame, each given back two frames + /// after it was taken, for 300 frames: the memory held by submissions in + /// the air is less than half of what doubles of at least 8 MiB held (and + /// with what is kept spare, less than 60 %), and after the first frames + /// nearly every submission takes a spare. + #[test] + fn steady_sends_hold_less_and_still_find_spares() { + const FRAMES: u64 = 300; + const EACH: u64 = 30; + const KEPT: u64 = 768 * MIB; + let run = |trim: bool| { + let mut pool: Pool<u64> = Pool::new(); + let mut sizes = std::collections::HashMap::new(); + let mut air: std::collections::VecDeque<Vec<u64>> = std::collections::VecDeque::new(); + let (mut made, mut made_late, mut out, mut most, mut most_out, mut next) = (0u64, 0u64, 0u64, 0u64, 0u64, 0u64); + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + for frame in 0..FRAMES { + let mut taken = Vec::new(); + for _ in 0..EACH { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + let size = MIB + (seed >> 33) % (4 * MIB); + let id = match pool.take(size, most_served(size, trim)) { + Some(id) => id, + None => { + made += 1; + if frame >= FRAMES / 2 { + made_late += 1; + } + next += 1; + sizes.insert(next, made_size(size, trim)); + next + } + }; + out += sizes[&id]; + taken.push(id); + } + most = most.max(out + pool.bytes()); + most_out = most_out.max(out); + air.push_back(taken); + if air.len() > 2 { + for id in air.pop_front().unwrap() { + out -= sizes[&id]; + for gone in pool.give(sizes[&id], id, frame, KEPT) { + sizes.remove(&gone); + } + } + } + } + (made, made_late, most, most_out) + }; + let (made, made_late, most, out) = run(true); + let (_, _, most_before, out_before) = run(false); + assert!(out * 2 < out_before, "{} MiB held in the air, {} before", out >> 20, out_before >> 20); + assert!(most * 10 < most_before * 6, "{} MiB held and kept, {} before", most >> 20, most_before >> 20); + assert!(made_late * 100 < FRAMES / 2 * EACH, "{made_late} made in the last 150 frames ({made} in all)"); + } + + /// The same sends from the ring (`LEONIDA_SEND_RING`, `super::super::sendring`): + /// after the first frames no buffer is made at all, where the spares + /// (with `LEONIDA_SEND_TRIM`) went on making some (each a committed + /// resource made resident, released at a sweep: here 121, one of them in + /// the last 150 frames, against 6 and none), and once warm the ring + /// holds less than the spares held in the air and kept (352 MiB against + /// 391; while it grows, 640 at most). + #[test] + fn steady_sends_from_the_ring_make_no_buffers_once_warm() { + use super::super::sendring::{Ring, tests::carve}; + const FRAMES: u64 = 300; + const EACH: u64 = 30; + const KEPT: u64 = 768 * MIB; + const IDLE_MS: u64 = 10_000; + // The sizes of the sends, 1 to 5 MiB, the same for both. + let sizes: Vec<u64> = { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + (0..FRAMES * EACH) + .map(|_| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + MIB + (seed >> 33) % (4 * MIB) + }) + .collect() + }; + // The spares: made, made in the last 150 frames, most held and kept. + let pool = { + let mut pool: Pool<u64> = Pool::new(); + let mut made_sizes = std::collections::HashMap::new(); + let mut air: std::collections::VecDeque<Vec<u64>> = std::collections::VecDeque::new(); + let (mut made, mut made_late, mut out, mut most, mut late, mut next) = (0u64, 0u64, 0u64, 0u64, 0u64, 0u64); + for frame in 0..FRAMES { + let now = frame * 16; + let mut taken = Vec::new(); + for &size in &sizes[(frame * EACH) as usize..((frame + 1) * EACH) as usize] { + let id = pool.take(size, most_served(size, true)).unwrap_or_else(|| { + made += 1; + made_late += u64::from(frame >= FRAMES / 2); + next += 1; + made_sizes.insert(next, made_size(size, true)); + next + }); + out += made_sizes[&id]; + taken.push(id); + } + most = most.max(out + pool.bytes()); + if frame >= FRAMES / 2 { + late = late.max(out + pool.bytes()); + } + pool.idle(now, IDLE_MS); + air.push_back(taken); + if air.len() > 2 { + for id in air.pop_front().unwrap() { + out -= made_sizes[&id]; + for gone in pool.give(made_sizes[&id], id, now, KEPT) { + made_sizes.remove(&gone); + } + } + } + } + (made, made_late, most, late) + }; + let ring = { + let mut ring = Ring::new(); + let mut air: std::collections::VecDeque<Vec<u64>> = std::collections::VecDeque::new(); + let (mut made, mut made_late, mut most, mut late) = (0u32, 0u32, 0u64, 0u64); + for frame in 0..FRAMES { + let now = frame * 16; + let mut taken = Vec::new(); + for &size in &sizes[(frame * EACH) as usize..((frame + 1) * EACH) as usize] { + let was = made; + taken.push(carve(&mut ring, size, now, &mut made).0.ticket); + made_late += u32::from(made > was && frame >= FRAMES / 2); + most = most.max(ring.bytes()); + if frame >= FRAMES / 2 { + late = late.max(ring.bytes()); + } + } + ring.let_go(now, IDLE_MS); + air.push_back(taken); + if air.len() > 2 { + for ticket in air.pop_front().unwrap() { + ring.give_back(ticket); + } + } + } + (made, made_late, most, late) + }; + eprintln!( + "spares: {} made, {} late, {} MiB at most, {} late; ring: {} made, {} late, {} MiB at most, {} late", + pool.0, + pool.1, + pool.2 >> 20, + pool.3 >> 20, + ring.0, + ring.1, + ring.2 >> 20, + ring.3 >> 20 + ); + assert_eq!(ring.1, 0, "buffers the ring made in the last 150 frames ({} in all)", ring.0); + assert!(pool.1 > 0, "the spares made none late either ({} in all)", pool.0); + assert!(ring.3 < pool.3, "the ring held {} MiB in the last 150 frames, the spares {}", ring.3 >> 20, pool.3 >> 20); + // (While it grows, a buffer it replaces is held until its carves have + // landed: in the first frames the two together.) + assert!(ring.2 < 2 * pool.2, "the ring held {} MiB, the spares {}", ring.2 >> 20, pool.2 >> 20); + } +} + +#[cfg(test)] +mod direct_tests { + use super::*; + + /// One at a time: the counters and the queue's order are the process's. + fn turn() -> std::sync::MutexGuard<'static, ()> { + static TURN: Mutex<()> = Mutex::new(()); + TURN.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// The copy's bytes. + const LEN: usize = 4 << 20; + /// What the title writes: across three of the card's pieces, no pairs. + const RUN: (usize, usize) = (60 << 10, (260 << 10) + 12); + + /// Title memory of the copy, with value `v` in `RUN`. + fn fill(title: &mut [u8], v: u8) { + for (i, b) in title[RUN.0..RUN.1].iter_mut().enumerate() { + *b = (i as u8).wrapping_mul(7).wrapping_add(v); + } + } + + /// What the card side holds in `RUN`, read back behind each send. + struct Rig { + host: &'static Host, + fence: ID3D12Fence, + event: HANDLE, + done: u64, + read: (ID3D12Resource, *mut u8), + lists: Vec<Prelude>, + plans: Vec<CardPlan>, + } + + impl Rig { + fn new(host: &'static Host) -> Rig { + Rig::with_slots(host, 4) + } + + /// With `slots` read-back slots. + fn with_slots(host: &'static Host, slots: usize) -> Rig { + // SAFETY: plain object creation. + let (fence, event) = unsafe { + (host.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).unwrap(), CreateEventW(None, false, false, None).unwrap()) + }; + let read = host.shared_buffer((slots * (RUN.1 - RUN.0)) as u64).expect("a buffer to read back into"); + Rig { host, fence, event, done: 0, read, lists: Vec::new(), plans: Vec::new() } + } + + /// The copy's changes go up (`Host::card_before`, no shader writes + /// declared), and a list of ours behind them copies the card side's + /// `RUN` into read-back slot `slot`: what a submission's draws would + /// read there. + /// + /// Another test's submission may take the copy's changes first + /// (`card_dirty` takes every copy's): then its send carries them, + /// and the list here goes on the queue once that send is on it (it + /// holds the card's work from its taking, where the copy's counts + /// move, until then). + fn send(&mut self, shadow: &Shadow, slot: usize) { + let counted = shadow.direct_for_test(); + let ask = CardAsk { declared: Vec::new(), looked: Vec::new(), asked: Vec::new() }; + let plan = self.host.card_before(Some(ask), false); + let ours = plan.as_ref().is_some_and(|p| p._synced.iter().any(|s| std::ptr::eq(&**s, shadow))); + self.plans.extend(plan); + if !ours { + let began = std::time::Instant::now(); + while shadow.direct_for_test() == counted && began.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + drop(CARD_WORK.lock().unwrap_or_else(|e| e.into_inner())); + } + let (allocator, list) = self.host.make_prelude().expect("a list"); + let n = (RUN.1 - RUN.0) as u64; + // SAFETY: a fresh list; live buffers, ranges inside them. + unsafe { + list.Reset(&allocator, None).unwrap(); + list.CopyBufferRegion(&self.read.0, slot as u64 * n, &shadow.buffer, RUN.0 as u64, n); + list.Close().unwrap(); + self.host.queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + } + self.lists.push((allocator, list)); + } + + /// Waits until the card has run everything sent: what the title + /// waits for (a fence, a bottom-of-pipe write) before it writes + /// memory a submission reads. + fn settle(&mut self) { + self.done += 1; + // SAFETY: a live queue, fence and event of ours. + unsafe { + self.host.queue.Signal(&self.fence, self.done).unwrap(); + self.fence.SetEventOnCompletion(self.done, self.event).unwrap(); + WaitForSingleObject(self.event, INFINITE); + } + } + + /// Waits for everything sent; the plans are done with. Returns what + /// each slot read. + fn finish(&mut self, slots: usize) -> Vec<Vec<u8>> { + self.settle(); + for plan in self.plans.drain(..) { + self.host.card_done(plan); + } + let n = RUN.1 - RUN.0; + // SAFETY: the mapping holds `slots` slots (the caller's); the card is + // done with it. + (0..slots).map(|s| unsafe { std::slice::from_raw_parts(self.read.1.add(s * n), n) }.to_vec()).collect() + } + } + + impl Drop for Rig { + fn drop(&mut self) { + // SAFETY: our event. + unsafe { + let _ = windows::Win32::Foundation::CloseHandle(self.event); + } + } + } + + /// The queue held on a fence of ours: the card runs nothing sent after + /// [`Gate::shut`] until the gate opens, at the latest when it is + /// dropped (a test that fails before it opens leaves the queue, the + /// process's, going). + struct Gate { + fence: ID3D12Fence, + opening: Option<std::thread::JoinHandle<()>>, + } + + impl Gate { + fn shut(host: &Host) -> Gate { + // SAFETY: plain object creation; the queue waits for it, and the + // drop signals it. + let fence: ID3D12Fence = unsafe { host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE) }.unwrap(); + // SAFETY: a live queue and fence. + unsafe { host.queue.Wait(&fence, 1) }.unwrap(); + Gate { fence, opening: None } + } + + /// Opens the gate `ms` milliseconds from now, from another thread. + fn open_in(&mut self, ms: u64) { + let fence = self.fence.clone(); + self.opening = Some(std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(ms)); + // SAFETY: a live fence. + unsafe { fence.Signal(1) }.unwrap(); + })); + } + } + + impl Drop for Gate { + fn drop(&mut self) { + // SAFETY: a live fence (signalled with 1 at most twice). + let _ = unsafe { self.fence.Signal(1) }; + if let Some(opening) = self.opening.take() { + let _ = opening.join(); + } + } + } + + /// Bytes the title's CPU wrote go up out of the CPU side with no copy + /// into the submission's memory: before, each was copied there on the + /// submitting thread (73-93 MB a frame), while the card copies out of + /// the CPU side as fast. Two submissions, title memory written before + /// each, the second time once the card ran the first (what the title + /// waits for; the card is held back 200 ms so that it is behind): each + /// reads its own bytes on the card. Counted for this copy alone. On the + /// host's card. + #[test] + fn what_the_title_wrote_goes_up_straight_out_of_the_cpu_side() { + let Some(host) = host() else { + eprintln!("no D3D12 device; sends straight out of CPU sides were not tried"); + return; + }; + let _turn = turn(); + TEST_DIRECT.set(Some(true)); + let mut title = vec![0u8; LEN]; + let start = title.as_ptr() as usize; + let Some(shadow) = Shadow::carded_for_test(start as u64, LEN as u64) else { + eprintln!("no copies in the card's memory here"); + return; + }; + let mut rig = Rig::new(host); + let mut gate = Gate::shut(host); + gate.open_in(200); + let (straight, copied, _) = shadow.direct_for_test(); + for (slot, v) in [(0, 1u8), (1, 2u8)] { + if slot > 0 { + // The title writes again once it was told the card ran the + // submission before: the CPU side is no longer the send's + // own bytes (without this wait the card, held back, read + // the second write for the first). + rig.settle(); + } + fill(&mut title, v); + shadow.refresh_for_test(start + RUN.0, start + RUN.1); + rig.send(&shadow, slot); + } + let read = rig.finish(2); + drop(gate); + TEST_DIRECT.set(None); + let (now_straight, now_copied, _) = shadow.direct_for_test(); + let (straight, copied) = (now_straight - straight, now_copied - copied); + let mut want = vec![0u8; LEN]; + for (slot, v) in [(0, 1u8), (1, 2u8)] { + fill(&mut want, v); + assert!(read[slot] == want[RUN.0..RUN.1], "the card side after send {slot} is not what the title wrote for it"); + } + assert_eq!(copied, 0, "bytes copied into the submissions' memory on the CPU"); + assert_eq!(straight, 2 * (RUN.1 - RUN.0) as u64, "bytes the card copied straight out of the CPU side"); + drop(shadow); + } + + /// A buffer copy of ours at submission into what a send in the air still + /// copies straight out of the CPU side waits until the card has copied + /// it: that submission reads the title's bytes from before, the next the + /// copy's. The card is held back (a wait on a fence of ours on its + /// queue) until a moment after the copy began. Without the wait the + /// first read the copy's bytes. The pieces copied into go through the + /// submission's memory from then on. On the host's card. + #[test] + fn a_copy_of_ours_waits_for_a_send_in_the_air_that_reads_its_bytes() { + over_a_send_in_the_air(false); + } + + /// As above, with the switch turned off between the send and the copy + /// (`LEONIDA_AB` can turn it at a present while sends are in the air): + /// what is in the air was sent straight, and the copy still waits for + /// it. Without that the first read the copy's bytes. + #[test] + fn a_copy_of_ours_waits_for_a_straight_send_once_the_switch_is_off() { + over_a_send_in_the_air(true); + } + + /// A send straight out of the CPU side, held on the queue, then a + /// buffer copy of ours over it (`off`: with `direct` turned off between + /// them); each submission's bytes are read back. + fn over_a_send_in_the_air(off: bool) { + let Some(host) = host() else { + eprintln!("no D3D12 device; sends straight out of CPU sides were not tried"); + return; + }; + let _turn = turn(); + TEST_DIRECT.set(Some(true)); + let mut title = vec![0u8; LEN]; + let start = title.as_ptr() as usize; + let Some(shadow) = Shadow::carded_for_test(start as u64, LEN as u64) else { + eprintln!("no copies in the card's memory here"); + return; + }; + let mut rig = Rig::new(host); + let mut gate = Gate::shut(host); + let (_, copied, waits) = shadow.direct_for_test(); + fill(&mut title, 1); + shadow.refresh_for_test(start + RUN.0, start + RUN.1); + rig.send(&shadow, 0); + if off { + TEST_DIRECT.set(Some(false)); + } + // The card is let go a moment after the copy below began. + gate.open_in(200); + let began = std::time::Instant::now(); + // The title's buffer copy, done at the next submission (`Step::Copy`). + fill(&mut title, 2); + crate::shadow::send_copied(start + RUN.0, RUN.1 - RUN.0); + let waited = began.elapsed(); + rig.send(&shadow, 1); + let read = rig.finish(2); + drop(gate); + TEST_DIRECT.set(None); + let (_, now_copied, now_waits) = shadow.direct_for_test(); + let (copied, waits) = (now_copied - copied, now_waits - waits); + let mut want = vec![0u8; LEN]; + for (slot, v) in [(0, 1u8), (1, 2u8)] { + fill(&mut want, v); + assert!(read[slot] == want[RUN.0..RUN.1], "the card side after send {slot} is not the bytes it was prepared with"); + } + assert_eq!(waits, 1, "waits for the card before the copy ({waited:?})"); + if !off { + assert_eq!(copied, (RUN.1 - RUN.0) as u64, "the copy's pieces go through the submission's memory"); + } + drop(shadow); + } + + /// Submissions in the air at once each send their own bytes out of one + /// buffer of the ring ([`ring`]): the card is held back while six are + /// prepared, title memory written before each (through the submissions' + /// memory: [`direct`] off), and each reads its own bytes on the card; + /// their carves lie apart in one buffer, where the spares made a buffer + /// for each. Then six more once the first six have landed and given + /// their carves back: the same buffer again, and the right bytes. On the + /// host's card. The ring is the process's and other tests' submissions + /// carve from it meanwhile: a buffer more is allowed for each the ring + /// added during a round, and the same buffer is asked of the second + /// round only if none was added from the first round's carves on. + #[test] + fn submissions_in_the_air_each_send_their_bytes_from_one_ring() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the ring of sends was not tried"); + return; + }; + let _turn = turn(); + TEST_DIRECT.set(Some(false)); + TEST_RING.set(Some(true)); + const N: usize = 6; + let mut title = vec![0u8; LEN]; + let start = title.as_ptr() as usize; + let Some(shadow) = Shadow::carded_for_test(start as u64, LEN as u64) else { + TEST_DIRECT.set(None); + TEST_RING.set(None); + eprintln!("no copies in the card's memory here"); + return; + }; + let made = || RING.lock().unwrap_or_else(|e| e.into_inner()).made(); + let mut buffers = Vec::new(); + let mut ends = Vec::new(); + for round in 0..2u8 { + let mut rig = Rig::with_slots(host, N); + let gate = Gate::shut(host); + let began = made(); + for slot in 0..N { + fill(&mut title, round * N as u8 + slot as u8 + 1); + shadow.refresh_for_test(start + RUN.0, start + RUN.1); + rig.send(&shadow, slot); + } + // The carves of the plans that sent this copy (another test's + // submission may have taken a change first, `Rig::send`). + let carves: Vec<(usize, u64, u64)> = rig + .plans + .iter() + .filter(|p| p._synced.iter().any(|s| std::ptr::eq(&**s, &*shadow))) + .filter_map(|p| p.sends.as_ref()) + .map(|m| (m.buffer.as_raw() as usize, m.at, m.size)) + .collect(); + let grew = made() - began; + ends.push(made()); + drop(gate); + let read = rig.finish(N); + let mut want = vec![0u8; LEN]; + for (slot, read) in read.iter().enumerate() { + fill(&mut want, round * N as u8 + slot as u8 + 1); + assert!(*read == want[RUN.0..RUN.1], "round {round}: the card side after send {slot} is not the bytes it was prepared with"); + } + assert!(carves.len() >= N - 1, "round {round}: {} of the {N} sends took this copy's bytes", carves.len()); + for (i, a) in carves.iter().enumerate() { + assert!(a.2 >= (RUN.1 - RUN.0) as u64, "a carve of {} bytes", a.2); + for b in &carves[..i] { + assert!(a.0 != b.0 || a.1 + a.2 <= b.1 || b.1 + b.2 <= a.1, "round {round}: carves in the air over each other"); + } + } + let mut distinct: Vec<usize> = carves.iter().map(|c| c.0).collect(); + distinct.sort_unstable(); + distinct.dedup(); + // (Two if the ring grew meanwhile, or more if other tests' carves + // made it grow again.) + let most = 1 + grew.max(1) as usize; + assert!(distinct.len() <= most, "round {round}: {} buffers for {} sends in the air", distinct.len(), carves.len()); + buffers.push(distinct); + } + TEST_DIRECT.set(None); + TEST_RING.set(None); + if ends[1] == ends[0] { + assert!(buffers[1].iter().any(|b| buffers[0].contains(b)), "the second round carved from another buffer"); + } else { + eprintln!("the ring grew between the rounds (other tests' carves): the second round's buffer was not compared"); + } + drop(shadow); + } + + /// Title memory of `LEN` bytes, private and committed whole (what the + /// host opens as a heap: the title's own `XMemVirtualAlloc` memory), on a + /// 64 KiB line; given back once whatever stood over it let go. Then + /// whether the title's release was told done ([`TitleMemory::give_back`]), + /// and the allocation's base. + struct TitleMemory(usize, bool, usize); + + impl TitleMemory { + fn new() -> TitleMemory { + use windows_sys::Win32::System::Memory as mem; + // SAFETY: an allocation of the test's own. + let at = unsafe { mem::VirtualAlloc(std::ptr::null(), LEN, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(at, 0, "title memory"); + TitleMemory(at, false, at) + } + + /// As [`TitleMemory::new`], for a copy `of` that: a window's on a + /// `LEN` line (one window of the grid, `LEN` the 4 MiB cell), inside + /// an allocation of its own committed whole. + fn of(of: Of) -> TitleMemory { + use windows_sys::Win32::System::Memory as mem; + match of { + Of::Buffer => TitleMemory::new(), + Of::Window => { + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 2 * LEN, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0, "title memory"); + TitleMemory(base.next_multiple_of(LEN), false, base) + } + } + } + + /// The title releases the allocation through the runtime's path + /// (`title_memory_free`, what `leonida_hle`'s xmem calls): what the + /// title is told. Told done, the release is the runtime's from then on + /// (kept for a heap still over the memory, done once the heap went), + /// and the title does not ask again: each ask the host refused for the + /// heap was kept once more, and once the first was done the others + /// stood over addresses the host gives other memory next. + fn give_back(&mut self) -> i32 { + use windows_sys::Win32::System::Memory as mem; + let at = self.2; + // SAFETY: the test's own allocation, released as the title would. + let told = crate::inplace::title_memory_free(at, 0, mem::MEM_RELEASE, || unsafe { + mem::VirtualFree(at as *mut std::ffi::c_void, 0, mem::MEM_RELEASE) + }); + self.1 |= told != 0; + told + } + + fn bytes(&mut self) -> &mut [u8] { + // SAFETY: the allocation, `LEN` bytes, committed. + unsafe { std::slice::from_raw_parts_mut(self.0 as *mut u8, LEN) } + } + + /// Whether the allocation is gone. + fn released(&self) -> bool { + use windows_sys::Win32::System::Memory as mem; + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(self.0 as *const std::ffi::c_void, &mut info, size_of_val(&info)) }; + n != 0 && info.State == mem::MEM_FREE + } + } + + impl Drop for TitleMemory { + fn drop(&mut self) { + // (A heap over it goes a moment after its last buffer.) Through the + // runtime's path, so that a hold let go of over it is forgotten + // with it, not left over addresses another test's memory gets; asked + // again only while refused and not taken over. + for _ in 0..300 { + if self.released() || (!self.1 && self.give_back() != 0 && self.released()) { + return; + } + crate::inplace::reap(); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + } + } + + /// What a test's copy whose CPU side is title memory is: a big title + /// buffer's (`lookup`, made as `Shadow::from_title_for_test` makes it) or + /// a window of memory outside buffers with a side in the card's memory + /// (`loose` itself, with `LEONIDA_CARD_WINDOWS_MB`: + /// `crate::shadow::card_window_for_test`). + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + enum Of { + Buffer, + Window, + } + + /// A copy as [`sourced`] made it; a window leaves the tables when it goes + /// (before its title memory does: declared after it). + struct Sourced(Option<std::sync::Arc<Shadow>>, Of); + + impl std::ops::Deref for Sourced { + type Target = Shadow; + fn deref(&self) -> &Shadow { + self.0.as_ref().expect("the copy") + } + } + + impl Drop for Sourced { + fn drop(&mut self) { + if let Some(shadow) = self.0.take() + && self.1 == Of::Window + { + let (start, len) = shadow.span(); + drop(crate::shadow::window_gone(start, len)); + } + } + } + + /// A copy in the card's memory of `title` (`LEN` bytes) whose CPU side + /// is the title memory itself (`crate::shadow::from_title`), made as `of` + /// is with `LEONIDA_CARD_FROM_TITLE=1`. `None` where the host cannot open + /// memory as a heap (said), or makes no such copies in the card's memory. + fn sourced(host: &Host, title: &TitleMemory, of: Of) -> Option<Sourced> { + if host.device.cast::<ID3D12Device13>().is_err() { + eprintln!("no ID3D12Device13 here: title memory cannot be a copy's CPU side"); + return None; + } + let shadow = match of { + Of::Buffer => { + crate::shadow::TEST_FROM_TITLE.set(Some(true)); + let shadow = Shadow::from_title_for_test(title.0 as u64, LEN as u64); + crate::shadow::TEST_FROM_TITLE.set(None); + shadow + } + Of::Window => { + let window = crate::shadow::card_window_for_test(title.0 as u64, LEN as u64, true); + if window.is_none() { + eprintln!("no window with a side in the card's memory here"); + } + window + } + }; + let shadow = Sourced(Some(shadow?), of); + assert!(shadow.sourced(), "the CPU side is a buffer of its own: the host did not open the title memory ({of:?})"); + Some(shadow) + } + + /// With `LEONIDA_CARD_FROM_TITLE`, title memory written before each of two + /// submissions reaches the card side with no byte copied on the CPU: the + /// CPU side is the title memory itself, the refresh notes the pages and + /// the card copies them out of it. Before, each was copied from title + /// memory into the CPU side by the refresh (`Card::taken`), then by the + /// card. The title writes again once the card ran the first (the card is + /// held back 200 ms). On the host's card. + #[test] + fn title_memory_reaches_the_card_side_with_no_copy_on_the_cpu() { + reaches_the_card_side_with_no_copy_on_the_cpu(Of::Buffer); + } + + /// As above, for a window of title memory outside buffers with a side in + /// the card's memory (`LEONIDA_CARD_WINDOWS_MB`). Before, a window's CPU + /// side was a buffer of its own however the switch was set + /// (`crate::shadow::loose` asked only for that), and each refresh copied + /// the title's bytes into it. + #[test] + fn a_windows_title_memory_reaches_the_card_side_with_no_copy_on_the_cpu() { + reaches_the_card_side_with_no_copy_on_the_cpu(Of::Window); + } + + fn reaches_the_card_side_with_no_copy_on_the_cpu(of: Of) { + let Some(host) = host() else { + eprintln!("no D3D12 device; title memory as a CPU side was not tried"); + return; + }; + let _turn = turn(); + TEST_DIRECT.set(Some(true)); + let mut title = TitleMemory::of(of); + let start = title.0; + let Some(shadow) = sourced(host, &title, of) else { + return; + }; + let mut rig = Rig::new(host); + let mut gate = Gate::shut(host); + gate.open_in(200); + let (straight, copied, _) = shadow.direct_for_test(); + for (slot, v) in [(0, 1u8), (1, 2u8)] { + if slot > 0 { + rig.settle(); + } + fill(title.bytes(), v); + shadow.update(start + RUN.0, RUN.1 - RUN.0); + rig.send(&shadow, slot); + } + let read = rig.finish(2); + drop(gate); + TEST_DIRECT.set(None); + let (now_straight, now_copied, _) = shadow.direct_for_test(); + let mut want = vec![0u8; LEN]; + for (slot, v) in [(0, 1u8), (1, 2u8)] { + fill(&mut want, v); + assert!(read[slot] == want[RUN.0..RUN.1], "the card side after send {slot} is not what the title wrote for it"); + } + assert_eq!(shadow.taken_for_test(), 0, "bytes copied from title memory into the CPU side"); + assert_eq!(now_copied - copied, 0, "bytes copied into the submissions' memory on the CPU"); + assert_eq!(now_straight - straight, 2 * (RUN.1 - RUN.0) as u64, "bytes the card copied straight out of title memory"); + assert!(shadow.sourced()); + drop(shadow); + } + + /// A buffer copy of ours at submission (`Step::Copy`) into title memory + /// that is a copy's CPU side, under a send in the air that copies it + /// straight: the write waits for that send first + /// (`crate::shadow::source_copying`, ahead of the write), so that + /// submission reads the title's bytes from before and the next the + /// copy's. Without it (`send_copied` waits after the write, as for a CPU + /// side of its own) the card, held back, read the copy's bytes for both. + /// Through `Step::Copy`'s own steps (`title_copy`). On the host's card. + #[test] + fn a_copy_of_ours_into_title_memory_that_is_a_cpu_side_waits_first() { + ours_into_a_cpu_side_waits_first(Of::Buffer); + } + + /// As above, into title memory that is a window's CPU side. + #[test] + fn a_copy_of_ours_into_a_windows_title_memory_that_is_its_cpu_side_waits_first() { + ours_into_a_cpu_side_waits_first(Of::Window); + } + + fn ours_into_a_cpu_side_waits_first(of: Of) { + let Some(host) = host() else { + eprintln!("no D3D12 device; title memory as a CPU side was not tried"); + return; + }; + let _turn = turn(); + TEST_DIRECT.set(Some(true)); + let mut title = TitleMemory::of(of); + let start = title.0; + let Some(shadow) = sourced(host, &title, of) else { + return; + }; + let mut rig = Rig::new(host); + let mut gate = Gate::shut(host); + let (_, _, waits) = shadow.direct_for_test(); + fill(title.bytes(), 1); + shadow.update(start + RUN.0, RUN.1 - RUN.0); + rig.send(&shadow, 0); + gate.open_in(200); + // The title's buffer copy, done at the next submission (`Step::Copy`). + let mut source = vec![0u8; LEN]; + fill(&mut source, 2); + title_copy(start + RUN.0, source.as_ptr() as usize + RUN.0, RUN.1 - RUN.0); + rig.send(&shadow, 1); + let read = rig.finish(2); + drop(gate); + TEST_DIRECT.set(None); + let mut want = vec![0u8; LEN]; + for (slot, v) in [(0, 1u8), (1, 2u8)] { + fill(&mut want, v); + assert!(read[slot] == want[RUN.0..RUN.1], "the card side after send {slot} is not the bytes it was prepared with"); + } + assert_eq!(shadow.direct_for_test().2 - waits, 1, "waits for the card before the copy"); + drop(shadow); + } + + /// As above, the copy given a CPU side of its own (shaders are declared + /// to write a piece away from the run, `Shadow::unsource`) while the send + /// out of title memory is still in the air: the buffer copy of ours into + /// the run still waits for that send before it writes title memory, which + /// the send reads when the card gets to it. Without it (only copies whose + /// CPU side is title memory now were waited for first) the write went in + /// under the send, which, held back, read the copy's bytes for both + /// submissions. On the host's card. + #[test] + fn a_copy_of_ours_into_title_memory_that_was_a_cpu_side_waits_first() { + ours_into_what_was_a_cpu_side_waits_first(Of::Buffer); + } + + /// As above, into title memory that was a window's CPU side. + #[test] + fn a_copy_of_ours_into_a_windows_title_memory_that_was_its_cpu_side_waits_first() { + ours_into_what_was_a_cpu_side_waits_first(Of::Window); + } + + fn ours_into_what_was_a_cpu_side_waits_first(of: Of) { + let Some(host) = host() else { + eprintln!("no D3D12 device; title memory as a CPU side was not tried"); + return; + }; + let _turn = turn(); + TEST_DIRECT.set(Some(true)); + let mut title = TitleMemory::of(of); + let start = title.0; + let Some(shadow) = sourced(host, &title, of) else { + return; + }; + let mut rig = Rig::new(host); + let mut gate = Gate::shut(host); + fill(title.bytes(), 1); + shadow.update(start + RUN.0, RUN.1 - RUN.0); + rig.send(&shadow, 0); + gate.open_in(200); + // At the next submission: shaders are declared to write the last + // piece, then the title's buffer copy into the run (`Step::Copy`). + shadow.writing(start + LEN - (64 << 10), 4096); + assert!(!shadow.sourced(), "a CPU side of its own"); + let mut source = vec![0u8; LEN]; + fill(&mut source, 2); + title_copy(start + RUN.0, source.as_ptr() as usize + RUN.0, RUN.1 - RUN.0); + rig.send(&shadow, 1); + let read = rig.finish(2); + drop(gate); + TEST_DIRECT.set(None); + let mut want = vec![0u8; LEN]; + for (slot, v) in [(0, 1u8), (1, 2u8)] { + fill(&mut want, v); + assert!(read[slot] == want[RUN.0..RUN.1], "the card side after send {slot} is not the bytes it was prepared with"); + } + drop(shadow); + } + + /// The title releases memory that is a copy's CPU side, through the + /// runtime's path (`title_memory_free`, what `leonida_hle`'s xmem calls): + /// it is told the release is done although the heap over the memory still + /// stands; before the next submission the copy gets a CPU side of its own + /// with the memory's bytes (`crate::shadow::sources_going`), and once the + /// card is done with the buffer over the memory, the allocation is + /// released. Without the let-go the copy kept the heap, and the title's + /// memory, for as long as it lived. On the host's card. + #[test] + fn a_free_of_title_memory_that_is_a_cpu_side_is_done_once_its_heap_went() { + free_done_once_its_heap_went(Of::Buffer); + } + + /// As above, of memory that is a window's CPU side. + #[test] + fn a_free_of_a_windows_title_memory_is_done_once_its_heap_went() { + free_done_once_its_heap_went(Of::Window); + } + + fn free_done_once_its_heap_went(of: Of) { + let Some(host) = host() else { + eprintln!("no D3D12 device; title memory as a CPU side was not tried"); + return; + }; + if !crate::inplace::frees() { + return; + } + let _turn = turn(); + TEST_DIRECT.set(Some(true)); + let mut title = TitleMemory::of(of); + let start = title.0; + let Some(shadow) = sourced(host, &title, of) else { + return; + }; + let mut rig = Rig::new(host); + fill(title.bytes(), 1); + shadow.update(start + RUN.0, RUN.1 - RUN.0); + rig.send(&shadow, 0); + let read = rig.finish(1); + let mut want = vec![0u8; LEN]; + fill(&mut want, 1); + assert!(read[0] == want[RUN.0..RUN.1], "the card side before the free"); + let old = shadow.card_sides().expect("two sides").0.as_raw() as usize; + + assert_ne!(title.give_back(), 0, "the title's VirtualFree succeeds"); + assert!(!title.released(), "kept for the heap meanwhile"); + // Before the next submission. + crate::shadow::sources_going(); + assert!(!shadow.sourced(), "the copy has a CPU side of its own"); + assert!(shadow.card_held(RUN.0, RUN.1 - RUN.0) == want[RUN.0..RUN.1], "with the memory's bytes"); + // The submissions that may have used the old side have run. + crate::host::bury_picked(|object| object.downcast_ref::<ID3D12Resource>().is_some_and(|r| r.as_raw() as usize == old)); + let released = (0..500).any(|_| { + crate::inplace::reap(); + let done = title.released(); + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + TEST_DIRECT.set(None); + assert!(released, "released once the heap over it went"); + drop(shadow); + } + + /// The title makes a page of memory that is a copy's CPU side read-only, + /// through the runtime's path (`title_memory_protect`, what + /// `leonida_hle`'s xmem calls): it is told the protection is made, with + /// the old one, although the heap over the memory still stands (the page + /// keeps its writes meanwhile); before the next submission the copy gets + /// a CPU side of its own with the memory's bytes + /// (`crate::shadow::sources_going`), and once the card is done with the + /// buffer over the memory the protection is made. On the host's card. + #[test] + fn a_protection_of_title_memory_that_is_a_cpu_side_is_made_once_its_heap_went() { + protection_made_once_its_heap_went(Of::Buffer); + } + + /// As above, of memory that is a window's CPU side. + #[test] + fn a_protection_of_a_windows_title_memory_is_made_once_its_heap_went() { + protection_made_once_its_heap_went(Of::Window); + } + + fn protection_made_once_its_heap_went(of: Of) { + use windows_sys::Win32::System::Memory as mem; + let Some(host) = host() else { + eprintln!("no D3D12 device; title memory as a CPU side was not tried"); + return; + }; + if !crate::inplace::frees() || !crate::inplace::protects() { + return; + } + let _turn = turn(); + TEST_DIRECT.set(Some(true)); + let mut title = TitleMemory::of(of); + let start = title.0; + let Some(shadow) = sourced(host, &title, of) else { + return; + }; + let mut rig = Rig::new(host); + fill(title.bytes(), 1); + shadow.update(start + RUN.0, RUN.1 - RUN.0); + rig.send(&shadow, 0); + let read = rig.finish(1); + let mut want = vec![0u8; LEN]; + fill(&mut want, 1); + assert!(read[0] == want[RUN.0..RUN.1], "the card side before the protection"); + let old = shadow.card_sides().expect("two sides").0.as_raw() as usize; + // The protection the host says the page at `at` has. + let protection = |at: usize| { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + unsafe { mem::VirtualQuery(at as *const std::ffi::c_void, &mut info, size_of_val(&info)) }; + info.Protect + }; + + // A page inside the run, made read-only as the title would. + let at = start + (64 << 10); + let mut was = 0u32; + let out: *mut u32 = &mut was; + // SAFETY: the test's own memory, and a live out pointer. + let done = crate::inplace::title_memory_protect(at, 4096, mem::PAGE_READONLY, out, || unsafe { + mem::VirtualProtect(at as *const std::ffi::c_void, 4096, mem::PAGE_READONLY, out) + }); + assert_ne!(done, 0, "the title's VirtualProtect succeeds"); + assert_eq!(was, mem::PAGE_READWRITE, "with the old protection"); + assert_eq!(protection(at), mem::PAGE_READWRITE, "the protection waits for the heap"); + // Before the next submission. + crate::shadow::sources_going(); + assert!(!shadow.sourced(), "the copy has a CPU side of its own"); + assert!(shadow.card_held(RUN.0, RUN.1 - RUN.0) == want[RUN.0..RUN.1], "with the memory's bytes"); + // The submissions that may have used the old side have run. + crate::host::bury_picked(|object| object.downcast_ref::<ID3D12Resource>().is_some_and(|r| r.as_raw() as usize == old)); + let made = (0..500).any(|_| { + crate::inplace::reap(); + let done = protection(at) == mem::PAGE_READONLY; + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + TEST_DIRECT.set(None); + assert!(made, "made once the heap over it went"); + drop(shadow); + } + + /// Shaders are declared to write a copy whose CPU side is title memory, + /// after the title wrote it since the last send: the copy gets a CPU side + /// of its own first, with title memory's bytes, and all of it goes up + /// again; what the merge then compares the card's bytes with is that + /// side, so a byte the title writes after the send stays the title's and + /// a byte the shaders wrote lands. Without it the merge compared with + /// title memory itself: the title's later byte differed from the card's + /// and was put back to the card's old one. On the host's card. + #[test] + fn a_copy_declared_written_later_gets_a_cpu_side_of_its_own() { + declared_written_later_gets_a_side_of_its_own(Of::Buffer); + } + + /// As above, for a window whose CPU side is title memory. + #[test] + fn a_window_declared_written_later_gets_a_cpu_side_of_its_own() { + declared_written_later_gets_a_side_of_its_own(Of::Window); + } + + fn declared_written_later_gets_a_side_of_its_own(of: Of) { + let Some(host) = host() else { + eprintln!("no D3D12 device; title memory as a CPU side was not tried"); + return; + }; + let _turn = turn(); + TEST_DIRECT.set(Some(true)); + let mut title = TitleMemory::of(of); + let start = title.0; + let Some(shadow) = sourced(host, &title, of) else { + return; + }; + let mut rig = Rig::new(host); + fill(title.bytes(), 1); + shadow.update(start + RUN.0, RUN.1 - RUN.0); + rig.send(&shadow, 0); + // Written again before the declaration, not refreshed. + fill(title.bytes(), 2); + // At the next submission shaders are declared to write a piece. + shadow.writing(start + RUN.0, 4096); + assert!(!shadow.sourced(), "a CPU side of its own"); + assert_ne!(shadow.card_data() as usize, start); + let mut want = vec![0u8; LEN]; + fill(&mut want, 2); + assert!(shadow.card_held(RUN.0, RUN.1 - RUN.0) == want[RUN.0..RUN.1], "with title memory's bytes"); + assert_eq!(shadow.taken_for_test(), LEN as u64, "taken whole, once"); + rig.send(&shadow, 1); + let read = rig.finish(2); + // (No refresh took the second write: what went up is the side whole.) + assert!(read[1] == want[RUN.0..RUN.1], "the card side after the copy went up whole"); + // After that submission ran: the title wrote one byte after its send, + // the shaders another. + let (title_at, shader_at) = (RUN.0 + 100, RUN.0 + 200); + title.bytes()[title_at] ^= 0x5a; + let mut gpu = want[RUN.0..RUN.0 + 4096].to_vec(); + gpu[shader_at - RUN.0] ^= 0xa5; + let mut scratch = Vec::new(); + shadow.card_merge(RUN.0, &gpu, &mut scratch); + assert_eq!(title.bytes()[title_at], want[title_at] ^ 0x5a, "the title's byte stays"); + assert_eq!(title.bytes()[shader_at], want[shader_at] ^ 0xa5, "the shaders' byte lands"); + TEST_DIRECT.set(None); + drop(shadow); + } + + /// Copies whose card side lies in card memory the CPU maps + /// (`LEONIDA_BAR_BUFFERS_MB`): [`bar_run`] in a process of its own, on + /// the software adapter, which offers that memory + /// (`GPUUploadHeapSupported` on this PC's, Windows 11 build 26300), and on the host's + /// card too where it does (a resizable BAR). A process of its own: the + /// host device is the process's, and its first numbered send matters. + /// Where neither offers it, says so and passes. + #[test] + fn card_sides_the_cpu_writes_hold_each_submissions_bytes() { + let card = host().is_some_and(|h| h.mapped_card_memory()); + for warp in [true, false] { + if !warp && !card { + eprintln!("the host's card offers no card memory the CPU maps (resizable BAR off): tried on the software adapter only"); + continue; + } + let mut command = std::process::Command::new(std::env::current_exe().unwrap()); + command + .args(["--exact", "host::send::direct_tests::bar_run", "--ignored", "--nocapture", "--test-threads=1"]) + .env("LEONIDA_BAR_BUFFERS_MB", "64") + .env_remove("LEONIDA_ADAPTER") + .env_remove("LEONIDA_RELAY") + .env_remove("LEONIDA_SEND_OWN") + .env_remove("LEONIDA_SEND_DIRECT") + .env_remove("LEONIDA_CARD_BUFFERS") + .env_remove("LEONIDA_CARD_BUFFERS_MIN_MB"); + if warp { + command.env("LEONIDA_D3D12_WARP", "1"); + } else { + command.env_remove("LEONIDA_D3D12_WARP"); + } + let output = command.output().expect("the run"); + let text = format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + let on = if warp { "the software adapter" } else { "the host's card" }; + assert!(output.status.success(), "the run on {on} failed:\n{text}"); + if let Some(why) = text.lines().find(|l| l.starts_with("BAR SKIPPED")) { + eprintln!("not tried on {on}: {why}"); + continue; + } + assert!(text.contains("BAR RAN"), "the run on {on} did not run:\n{text}"); + eprintln!("ran on {on}"); + } + } + + /// The card side's bytes at `RUN`, read by the CPU through the mapping: + /// only tests do (a read crosses the bus a few bytes at a time). + fn mapped_run(shadow: &Shadow) -> Vec<u8> { + let side = shadow.card_bar().expect("a card side the CPU maps"); + // SAFETY: the mapping holds the copy's bytes; nothing writes it now. + unsafe { std::slice::from_raw_parts((side + RUN.0) as *const u8, RUN.1 - RUN.0) }.to_vec() + } + + /// What [`card_sides_the_cpu_writes_hold_each_submissions_bytes`] runs, + /// in order (the first needs a process in which no send was numbered). + #[test] + #[ignore = "run by card_sides_the_cpu_writes_hold_each_submissions_bytes in a process of its own"] + fn bar_run() { + let Some(host) = host() else { + eprintln!("BAR SKIPPED: no D3D12 device"); + return; + }; + let line = crate::host::bar::line(&host.device); + if !host.mapped_card_memory() { + eprintln!("BAR SKIPPED: {line}"); + return; + } + eprintln!("{line}"); + let _turn = turn(); + bar_a_first_copy_of_ours_waits_for_the_card(host); + bar_what_the_title_wrote_is_written_by_the_cpu(host); + bar_a_copy_of_ours_goes_behind_a_submission_in_the_air(host); + bar_a_small_buffer_gets_such_a_side(host); + bar_what_shaders_wrote_is_found_on_the_card(host); + bar_a_copy_the_cpu_writes_is_not_looked_at(host); + TEST_DIRECT.set(None); + eprintln!("BAR RAN"); + } + + /// A buffer copy of ours at submission before any send was numbered, + /// with an earlier send still on the queue: the next send, the first + /// numbered one, takes the copy's pieces through the submission's memory + /// (behind what is in the air), not into the card side by the CPU at + /// once. Without the note (`copying` and `send_copied` noted nothing + /// before a numbered send) the first submission's read was another's. + fn bar_a_first_copy_of_ours_waits_for_the_card(host: &'static Host) { + assert!(!crate::host::send_numbered(), "a send was numbered in this process before"); + let mut title = vec![0u8; LEN]; + let start = title.as_ptr() as usize; + let shadow = Shadow::barred_for_test(start as u64, LEN as u64).expect("a copy whose card side the CPU maps"); + let mut rig = Rig::new(host); + let mut gate = Gate::shut(host); + // Unnumbered: through the submission's memory, held on the queue. + TEST_DIRECT.set(Some(false)); + fill(&mut title, 1); + shadow.refresh_for_test(start + RUN.0, start + RUN.1); + rig.send(&shadow, 0); + TEST_DIRECT.set(Some(true)); + gate.open_in(200); + fill(&mut title, 2); + crate::shadow::send_copied(start + RUN.0, RUN.1 - RUN.0); + rig.send(&shadow, 1); + assert!(crate::host::send_numbered(), "the second send is numbered"); + let read = rig.finish(2); + drop(gate); + let mut want = vec![0u8; LEN]; + for (slot, v) in [(0, 1u8), (1, 2u8)] { + fill(&mut want, v); + assert!(read[slot] == want[RUN.0..RUN.1], "the card side after send {slot} is not the bytes it was prepared with"); + } + drop(shadow); + } + + /// Bytes the title's CPU wrote are written into the card side by the CPU + /// when they are taken: the side holds them while the card, held back, + /// has run nothing, and no byte goes through the submission's memory. + /// Each submission reads its own (the title writes again once it was + /// told the card ran the one before). + fn bar_what_the_title_wrote_is_written_by_the_cpu(host: &'static Host) { + TEST_DIRECT.set(Some(true)); + let mut title = vec![0u8; LEN]; + let start = title.as_ptr() as usize; + let shadow = Shadow::barred_for_test(start as u64, LEN as u64).expect("a copy whose card side the CPU maps"); + let mut rig = Rig::new(host); + let mut gate = Gate::shut(host); + let mut want = vec![0u8; LEN]; + for (slot, v) in [(0, 1u8), (1, 2u8)] { + if slot > 0 { + rig.settle(); + } + fill(&mut title, v); + shadow.refresh_for_test(start + RUN.0, start + RUN.1); + rig.send(&shadow, slot); + fill(&mut want, v); + assert!(mapped_run(&shadow) == want[RUN.0..RUN.1], "the card side does not hold send {slot}'s bytes when it is taken"); + if slot == 0 { + gate.open_in(100); + } + } + let read = rig.finish(2); + drop(gate); + for (slot, v) in [(0, 1u8), (1, 2u8)] { + fill(&mut want, v); + assert!(read[slot] == want[RUN.0..RUN.1], "the card read other bytes after send {slot}"); + } + let (straight, copied, waits) = shadow.direct_for_test(); + assert_eq!((straight, copied, waits), (2 * (RUN.1 - RUN.0) as u64, 0, 0), "bytes written by the CPU, through the submission's memory, waits"); + drop(shadow); + } + + /// A buffer copy of ours at submission into what a submission held on + /// the queue reads: the card side keeps that submission's bytes (the copy + /// goes up through the submission's memory, behind it) and nothing waits + /// (nothing is in the air: the CPU wrote the first send's bytes at once). + /// If the CPU wrote the copy into the side too, the first read the copy. + fn bar_a_copy_of_ours_goes_behind_a_submission_in_the_air(host: &'static Host) { + TEST_DIRECT.set(Some(true)); + let mut title = vec![0u8; LEN]; + let start = title.as_ptr() as usize; + let shadow = Shadow::barred_for_test(start as u64, LEN as u64).expect("a copy whose card side the CPU maps"); + let mut rig = Rig::new(host); + let mut gate = Gate::shut(host); + fill(&mut title, 1); + shadow.refresh_for_test(start + RUN.0, start + RUN.1); + rig.send(&shadow, 0); + gate.open_in(200); + let began = std::time::Instant::now(); + fill(&mut title, 2); + crate::shadow::send_copied(start + RUN.0, RUN.1 - RUN.0); + let waited = began.elapsed(); + rig.send(&shadow, 1); + let read = rig.finish(2); + drop(gate); + let mut want = vec![0u8; LEN]; + for (slot, v) in [(0, 1u8), (1, 2u8)] { + fill(&mut want, v); + assert!(read[slot] == want[RUN.0..RUN.1], "the card side after send {slot} is not the bytes it was prepared with"); + } + let (straight, copied, waits) = shadow.direct_for_test(); + assert_eq!(waits, 0, "waits for the card before the copy ({waited:?})"); + assert_eq!((straight, copied), ((RUN.1 - RUN.0) as u64, (RUN.1 - RUN.0) as u64), "written by the CPU, through the submission's memory"); + drop(shadow); + } + + /// With `LEONIDA_BAR_BUFFERS_MB`, a small title buffer's copy is made + /// with one side, as without it; the sweep makes it again with its card + /// side in card memory the CPU maps once it was read in enough + /// submissions, never written, and nothing but the table holds it (not + /// while a list does). Then its CPU side is write-back memory, which + /// every CPU read of the copy reads, and the bytes are counted. Once + /// shaders are declared to write it, the sweep makes it again with one + /// side, for good, and the bytes are no longer counted. Before, the first + /// copy had its side there at once, read once or not. + fn bar_a_small_buffer_gets_such_a_side(_host: &'static Host) { + const SMALL: usize = 256 << 10; + let before = Shadow::bar_bytes_for_test(); + let title = vec![0u8; SMALL]; + let start = title.as_ptr() as u64; + let ours = |o: &dyn std::any::Any| o.downcast_ref::<std::sync::Arc<Shadow>>().is_some_and(|s| s.span().0 == start); + crate::shadow::register(0xba7, start, SMALL as u64); + let first = crate::shadow::find(start, SMALL as u64).expect("a copy"); + assert!(first.card_sides().is_none(), "a new small copy has a card side"); + // Read often, but held (as a list not yet reset holds it): it stays. + first.read_in_for_test(64); + crate::shadow::bar_sweep_for_test(); + let again = crate::shadow::find(start, SMALL as u64).expect("a copy"); + assert!(std::sync::Arc::ptr_eq(&first, &again), "a copy something held was made again"); + drop((first, again)); + crate::shadow::bar_sweep_for_test(); + assert_eq!(crate::host::bury_picked(ours), 1, "the copy that moved went"); + let shadow = crate::shadow::find(start, SMALL as u64).expect("a copy"); + let side = shadow.card_bar().expect("the card side of a small buffer's copy in card memory the CPU maps"); + let heap = |r: &ID3D12Resource| { + let mut heap = D3D12_HEAP_PROPERTIES::default(); + // SAFETY: a live buffer. + unsafe { r.GetHeapProperties(Some(&mut heap), None) }.expect("heap properties"); + heap + }; + assert_eq!(heap(&shadow.buffer).Type, D3D12_HEAP_TYPE_GPU_UPLOAD, "what shaders see"); + let (staging, ..) = shadow.card_sides().expect("two sides"); + let cpu = heap(&staging); + assert!( + cpu.Type == D3D12_HEAP_TYPE_CUSTOM && cpu.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + "the CPU's side is not write-back memory" + ); + assert_ne!(shadow.card_data() as usize, side, "the CPU's side is the card side"); + assert_eq!(Shadow::bar_bytes_for_test(), before + SMALL as u64); + // Not written: it stays there, however much it is read. + shadow.read_in_for_test(64); + let id = shadow.id(); + drop(shadow); + crate::shadow::bar_sweep_for_test(); + let shadow = crate::shadow::find(start, SMALL as u64).expect("a copy"); + assert_eq!(shadow.id(), id, "a copy there that nothing wrote was made again"); + // Written by shaders: back to one side, the bytes no longer counted. + shadow.written_for_test(); + drop(shadow); + crate::shadow::bar_sweep_for_test(); + assert_eq!(crate::host::bury_picked(ours), 1, "the written copy went"); + assert_eq!(Shadow::bar_bytes_for_test(), before, "a copy that went is still counted"); + let shadow = crate::shadow::find(start, SMALL as u64).expect("a copy"); + assert!(shadow.card_sides().is_none(), "a written buffer's copy has a card side"); + shadow.read_in_for_test(64); + drop(shadow); + crate::shadow::bar_sweep_for_test(); + let shadow = crate::shadow::find(start, SMALL as u64).expect("a copy"); + assert!(shadow.card_sides().is_none(), "a buffer once written went there again"); + crate::shadow::unregister(0xba7, start); + drop(shadow); + assert_eq!(Shadow::bar_bytes_for_test(), before); + drop(title); + } + + /// Shaders write a copy whose card side the CPU maps, in a declared + /// range: the compare on the card finds the piece, a card copy fetches + /// it, and the bytes go into title memory and the CPU's side, the rest + /// of the title left as it was. Nothing of it is read through the + /// mapping on the CPU (the merge compares with the CPU's side). + fn bar_what_shaders_wrote_is_found_on_the_card(host: &'static Host) { + TEST_DIRECT.set(Some(true)); + let mut title = vec![0u8; LEN]; + let start = title.as_ptr() as usize; + let shadow = Shadow::barred_for_test(start as u64, LEN as u64).expect("a copy whose card side the CPU maps"); + let mut rig = Rig::new(host); + fill(&mut title, 1); + shadow.refresh_for_test(start + RUN.0, start + RUN.1); + rig.send(&shadow, 0); + rig.settle(); + let declared: Vec<Declared> = vec![(shadow.clone(), vec![(start + RUN.0, start + RUN.1)])]; + let asked = card_asked(&declared, &[]); + let plan = host.card_before(Some(CardAsk { declared, looked: Vec::new(), asked }), false).expect("a plan"); + // "Shaders": a copy into the card side, 64 bytes at RUN.0 + 4096. + const AT: usize = RUN.0 + 4096; + let wrote: Vec<u8> = (0..64u8).map(|i| i ^ 0xa5).collect(); + let (source, mapped) = host.upload_buffer(64).expect("an upload buffer"); + let (allocator, list) = host.make_prelude().expect("a list"); + // SAFETY: a fresh list; live buffers, ranges inside them; the + // upload buffer's mapping holds 64 bytes. + unsafe { + std::ptr::copy_nonoverlapping(wrote.as_ptr(), mapped.cast::<u8>(), 64); + list.Reset(&allocator, None).unwrap(); + list.CopyBufferRegion(&shadow.buffer, AT as u64, &source, 0, 64); + list.Close().unwrap(); + let check = plan.check.clone().expect("a compare after the lists"); + host.queue.ExecuteCommandLists(&[Some(list.cast().unwrap()), Some(check)]); + } + rig.settle(); + { + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + host.card_back(&plan, &mut submitted, &mut std::collections::HashSet::new()); + } + host.card_done(plan); + let mut want = vec![0u8; LEN]; + fill(&mut want, 1); + want[AT..AT + 64].copy_from_slice(&wrote); + // (Written through its address by the merge.) + std::hint::black_box(title.as_mut_ptr()); + // SAFETY: the test's title memory, `LEN` bytes. + let seen = unsafe { std::slice::from_raw_parts(start as *const u8, LEN) }; + assert!(seen[RUN.0..RUN.1] == want[RUN.0..RUN.1], "title memory does not hold what the shaders wrote, and only that"); + assert_eq!(shadow.card_held(AT, 64), wrote, "the CPU's side does not hold what the shaders wrote"); + rig.finish(0); + drop((list, allocator, source)); + drop(shadow); + } + + /// The up-copy check (`LEONIDA_UPCOPY_CHECK=1`, `upcheck::record`) does + /// not look at a copy whose card side the CPU maps: the CPU wrote the + /// title's bytes into that side before the look is recorded, and one + /// such copy sent all straight was left in `COPY_DEST` by the look, with + /// nothing in the list to take it out, while the hash pass read it. + fn bar_a_copy_the_cpu_writes_is_not_looked_at(host: &'static Host) { + let title = vec![0u8; LEN]; + let start = title.as_ptr() as u64; + let shadow = Shadow::barred_for_test(start, LEN as u64).expect("a copy whose card side the CPU maps"); + crate::host::upcheck::note(shadow.id(), RUN.0, &[1u8; 64], &[2u8; 64]); + let (allocator, list) = host.make_prelude().expect("a list"); + // SAFETY: a fresh list. + unsafe { list.Reset(&allocator, None).unwrap() }; + let looks = crate::host::upcheck::record(host, &list, &[(shadow.clone(), vec![(RUN.0, RUN.0 + 64)])]); + assert!(looks.is_none(), "a copy whose card side the CPU wrote was looked at"); + // SAFETY: the list is ours; nothing was recorded into it. + unsafe { list.Close().unwrap() }; + drop((list, allocator, shadow, title)); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/sendring.rs b/d3d12/crates/leonida-gpu/src/host/sendring.rs new file mode 100644 index 0000000000..6347040190 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/sendring.rs @@ -0,0 +1,502 @@ +//! The memory submissions' sends come from as a ring of buffers +//! (`LEONIDA_SEND_RING`, on by default with `LEONIDA_SEND_OWN`; `0`: a +//! buffer of its own for each submission, from the pool of spares, as +//! before: `super::send`'s `Pool`, `LEONIDA_SEND_TRIM`). +//! +//! The pool made a committed upload buffer for each submission that found +//! no spare to its size (`CreateCommittedResource`, `MakeResident`, `Map`: +//! 1.6 ms an upload buffer, `docs/findings.md`'s small-buffer row) and +//! released those the sweep found idle, so sizes that drift from frame to +//! frame went on making and releasing; each held up to an eighth more than +//! it sent (`made_size`), and a spare served up to twice the send. +//! +//! Here a submission carves its bytes at the head of the one open buffer, +//! never wrapped within a carve, and they are free again when its +//! submission has landed and so has every carve before it in that buffer: +//! space comes back in the order it was carved, as the card runs the +//! submissions (`Host::card_done`, in the relay's landing order or after a +//! wait), so a carve given back early frees nothing until those before it +//! are, and nothing carved can lie over bytes a submission in the air +//! still reads. A buffer is made for the bytes in the air (the most seen +//! in the last idle time, or now with the carve that did not fit), an +//! eighth over them and room for the largest carve twice ([`Ring::made_for`]); +//! the buffer it replaces is closed, carved no more, and goes when its +//! last carve comes back. The sweep closes the open buffer when it is +//! more than [`SHRINK`] times what would be made now, and lets go of every +//! buffer with nothing out once no submission carved for the idle time. +//! A carve of more than [`OUTSIZE`] (the world loading) gets a buffer of +//! its own, closed from the start, so a burst does not size the ring: its +//! bytes count neither in the bytes in the air nor as the largest carve. +//! +//! What it changes on the card: nothing; the bytes are the same, read from +//! another offset (copies from the carve's offset, the scatter's pairs +//! through a root view at the carve's address, which is a multiple of +//! [`ALIGN`]). How many buffers the pool made in a frame was not counted +//! (a hypothesis that it is a few a second at drifting sizes); the frame +//! line now counts the buffers made for sends either way. + +use std::collections::VecDeque; + +/// Carves begin at multiples of this (a root view's address, and the +/// placement of constant data, ask no more). +pub(super) const ALIGN: u64 = 256; +/// The least buffer made. +pub(super) const LEAST: u64 = 4 << 20; +/// A buffer is made for the bytes in the air and this many of the largest +/// carve over them: carves landing in order leave less than one unused at +/// the end before the head comes round, and one more fits behind that. +pub(super) const CARVES: u64 = 2; +/// And a part of the bytes in the air over them (an eighth): for +/// submissions that land out of order, whose carves stay held until those +/// before them have landed, and for frames that send more than the last. +pub(super) const OVER: u64 = 8; +/// The open buffer is closed by the sweep when it is more than this many +/// times what would be made for the bytes in the air lately. +pub(super) const SHRINK: u64 = 2; +/// A carve of more than this gets a buffer of its own. +pub(super) const OUTSIZE: u64 = 64 << 20; + +/// A carve out (its ticket, `[from, to)` in its buffer, given back). +#[derive(Debug)] +struct Run { + ticket: u64, + from: u64, + to: u64, + back: bool, +} + +/// One buffer of the ring. +#[derive(Debug)] +struct Part<M> { + size: u64, + memory: M, + /// The carves not free again, oldest first. + out: VecDeque<Run>, + /// Carved from; one at most. + open: bool, + /// One of the ring's, not made for a carve past [`OUTSIZE`]: only these + /// count in the bytes in the air and the largest carve that size what + /// is made ([`Ring::air`]). + ring: bool, +} + +impl<M> Part<M> { + /// Where a carve of `want` bytes goes in the buffer, if it fits: behind + /// the newest carve, else from 0 up to the oldest (the end stays unused + /// until the oldest has passed it). Wrapped (the newest carve ends at or + /// before the oldest begins) only the space between them is free. + fn place(&self, want: u64) -> Option<u64> { + let (Some(tail), Some(head)) = (self.out.front(), self.out.back()) else { + return (want <= self.size).then_some(0); + }; + let (tail, head) = (tail.from, head.to); + if head <= tail { + return (want <= tail - head).then_some(head); + } + if want <= self.size - head { + Some(head) + } else { + (want <= tail).then_some(0) + } + } + + fn held(&self) -> u64 { + self.out.iter().map(|r| r.to - r.from).sum() + } +} + +/// A carve: its ticket, for [`Ring::give_back`], its offset in the buffer, +/// and the buffer. +#[derive(Debug)] +pub(super) struct Carved<M> { + pub(super) ticket: u64, + pub(super) at: u64, + pub(super) memory: M, +} + +/// The ring's buffers and what is carved of them. +#[derive(Debug)] +pub(super) struct Ring<M> { + parts: Vec<Part<M>>, + /// The last ticket given; 0 is none. + tickets: u64, + /// The most bytes in the air, and the largest carve, since `since` (ms). + peak: u64, + largest: u64, + since: u64, + /// When the last carve was made (ms). + last: u64, + /// Buffers ever added. + made: u64, +} + +impl<M: Clone> Ring<M> { + pub(super) const fn new() -> Self { + Ring { parts: Vec::new(), tickets: 0, peak: 0, largest: 0, since: 0, last: 0, made: 0 } + } + + /// Bytes of every buffer. + #[cfg(test)] + pub(super) fn bytes(&self) -> u64 { + self.parts.iter().map(|p| p.size).sum() + } + + /// Bytes carved and not free again (given back out of order counts + /// until those before it are). + #[cfg(test)] + pub(super) fn held(&self) -> u64 { + self.parts.iter().map(Part::held).sum() + } + + /// Bytes of the open buffer not held: those carves can take, now or + /// once the carves before the head come round (the unused space of + /// closed buffers and of carves past [`OUTSIZE`] is never carved again). + pub(super) fn free(&self) -> u64 { + self.parts.iter().filter(|p| p.open).map(|p| p.size - p.held()).sum() + } + + /// Buffers. + pub(super) fn buffers(&self) -> usize { + self.parts.len() + } + + /// Buffers ever added ([`Ring::add`]): a test's carves that see it + /// unchanged came from the buffer open before them. + #[cfg(test)] + pub(super) fn made(&self) -> u64 { + self.made + } + + /// Bytes in the air that size the ring: those of the ring's buffers, + /// not of carves past [`OUTSIZE`], which have buffers of their own. + fn air(&self) -> u64 { + self.parts.iter().filter(|p| p.ring).map(Part::held).sum() + } + + /// What is made for `air` bytes in the air with carves of up to + /// `carve`: an eighth over them ([`OVER`]) and [`CARVES`] of the largest + /// carve, at least [`LEAST`], made within an eighth as `send`'s pool + /// makes its buffers. + fn made_for(air: u64, carve: u64) -> u64 { + let want = air.saturating_add(air / OVER).saturating_add(carve.saturating_mul(CARVES)); + super::send::made_size(want.max(LEAST), true).next_multiple_of(ALIGN) + } + + fn carved(&mut self, part: usize, at: u64, want: u64) -> Carved<M> { + self.tickets += 1; + let ticket = self.tickets; + let part = &mut self.parts[part]; + debug_assert!(at + want <= part.size, "a carve past the end of its buffer"); + part.out.push_back(Run { ticket, from: at, to: at + want, back: false }); + let carved = Carved { ticket, at, memory: part.memory.clone() }; + if part.ring { + self.peak = self.peak.max(self.air()); + self.largest = self.largest.max(want); + } + carved + } + + /// `want` bytes at `now` (ms), carved from the open buffer; else + /// `Err(size)`: a buffer of `size` bytes is to be made, and given with + /// [`Ring::add`] (made outside the caller's lock: only one thread + /// carves, the others only give back, which leaves more room). + pub(super) fn carve(&mut self, want: u64, now: u64) -> Result<Carved<M>, u64> { + let want = want.max(1).next_multiple_of(ALIGN); + self.last = now; + if want > OUTSIZE { + return Err(super::send::made_size(want, true).next_multiple_of(ALIGN)); + } + let open = self.parts.iter().position(|p| p.open); + if let Some(i) = open + && let Some(at) = self.parts[i].place(want) + { + return Ok(self.carved(i, at, want)); + } + Err(Self::made_for((self.air() + want).max(self.peak), want.max(self.largest))) + } + + /// A buffer of `size` bytes made as [`Ring::carve`] asked, and the carve + /// of `want` bytes in it; and the buffers that go now (the open one it + /// replaces, if nothing is out of it), for the caller to release once + /// its lock is released. One past [`OUTSIZE`] is closed from the start. + pub(super) fn add(&mut self, want: u64, now: u64, memory: M, size: u64) -> (Carved<M>, Vec<M>) { + let want = want.max(1).next_multiple_of(ALIGN); + self.last = now; + let outsize = want > OUTSIZE; + self.made += 1; + let mut gone = Vec::new(); + if !outsize { + for part in &mut self.parts { + part.open = false; + } + gone = self.closed_empty(); + } + self.parts.push(Part { size, memory, out: VecDeque::new(), open: !outsize, ring: !outsize }); + let i = self.parts.len() - 1; + (self.carved(i, 0, want.min(size)), gone) + } + + /// Takes out the closed buffers with nothing out. + fn closed_empty(&mut self) -> Vec<M> { + self.parts.extract_if(.., |p| !p.open && p.out.is_empty()).map(|p| p.memory).collect() + } + + /// The submission of `ticket` has run: its carve, and every carve before + /// it in its buffer that came back, are free again. Returns the buffers + /// that go (closed, nothing out), for the caller to release. + pub(super) fn give_back(&mut self, ticket: u64) -> Vec<M> { + let Some(part) = self.parts.iter_mut().find(|p| p.out.iter().any(|r| r.ticket == ticket)) else { + return Vec::new(); + }; + if let Some(run) = part.out.iter_mut().find(|r| r.ticket == ticket) { + run.back = true; + } + while part.out.front().is_some_and(|r| r.back) { + part.out.pop_front(); + } + if part.open || !part.out.is_empty() { + return Vec::new(); + } + self.closed_empty() + } + + /// From the sweep at `now` (ms): with no carve for `idle_ms`, every + /// buffer with nothing out goes; else once every `idle_ms` the open + /// buffer is closed if it is more than [`SHRINK`] times what would be + /// made for the most in the air since the last time (it goes when its + /// last carve comes back; the next carve makes one to size). Returns + /// the buffers that go now. + pub(super) fn let_go(&mut self, now: u64, idle_ms: u64) -> Vec<M> { + if now.saturating_sub(self.last) >= idle_ms { + self.window(now); + return self.parts.extract_if(.., |p| p.out.is_empty()).map(|p| p.memory).collect(); + } + if now.saturating_sub(self.since) < idle_ms { + return Vec::new(); + } + let want = Self::made_for(self.peak, self.largest); + for part in self.parts.iter_mut().filter(|p| p.open) { + if part.size > want.saturating_mul(SHRINK) { + part.open = false; + } + } + self.window(now); + self.closed_empty() + } + + /// The most in the air and the largest carve are counted again from + /// `now`, from what is out now of the ring's buffers. + fn window(&mut self, now: u64) { + self.peak = self.air(); + self.largest = self.parts.iter().filter(|p| p.ring).flat_map(|p| &p.out).map(|r| r.to - r.from).max().unwrap_or(0); + self.since = now; + } +} + +#[cfg(test)] +pub(super) mod tests { + use super::{ALIGN, Carved, LEAST, OUTSIZE, Ring}; + + const MIB: u64 = 1 << 20; + + /// A buffer of the tests: its number and size. + pub(in crate::host) type B = (u32, u64); + + /// Carves `want` at `now`, making a buffer as asked (counted in `made`); + /// returns the carve and the buffers that went. + pub(in crate::host) fn carve(ring: &mut Ring<B>, want: u64, now: u64, made: &mut u32) -> (Carved<B>, Vec<B>) { + match ring.carve(want, now) { + Ok(c) => (c, Vec::new()), + Err(size) => { + *made += 1; + ring.add(want, now, (*made, size), size) + } + } + } + + /// Carves are given out at the head and come round to the start once the + /// oldest have come back, never over one not free: a carve that came + /// back before those before it frees nothing, and the end that a carve + /// does not fit in stays unused (a carve never wraps within itself). + #[test] + fn carves_wrap_round_behind_what_came_back() { + let mut ring: Ring<B> = Ring::new(); + let mut made = 0; + let a = carve(&mut ring, MIB, 0, &mut made).0; + assert_eq!((made, a.at, a.memory.1), (1, 0, LEAST), "the least buffer for 1 MiB"); + let b = carve(&mut ring, 2 * MIB, 0, &mut made).0; + let c = carve(&mut ring, MIB - 1, 0, &mut made).0; + assert_eq!((b.at, c.at, made), (MIB, 3 * MIB, 1)); + assert!(ring.carve(1, 0).is_err(), "full"); + ring.give_back(a.ticket); + let d = carve(&mut ring, MIB, 0, &mut made).0; + assert_eq!((d.at, made), (0, 1), "round to the start, where a was"); + assert!(ring.carve(1, 0).is_err(), "wrapped up to b: full"); + ring.give_back(c.ticket); + assert!(ring.carve(1, 0).is_err(), "c came back before b: nothing is free"); + ring.give_back(b.ticket); + let e = carve(&mut ring, 3 * MIB, 0, &mut made).0; + assert_eq!((e.at, made), (MIB, 1), "b and c free: behind d up to the end"); + assert!(ring.carve(1, 0).is_err(), "the end reached, d out at the start"); + ring.give_back(d.ticket); + let f = carve(&mut ring, 1, 0, &mut made).0; + assert_eq!((f.at, made), (0, 1)); + let g = carve(&mut ring, 1, 0, &mut made).0; + assert_eq!(g.at, ALIGN, "sizes are carved in multiples of the alignment"); + } + + /// Whatever is carved lies clear of every carve not free (it goes to a + /// new buffer when there is no room), and a buffer goes only with no + /// carve in the air: checked over 20,000 carves landing in a shuffled + /// order within a window of eight, as the relay's flights and the + /// waits of submissions without it may give them back. + #[test] + fn landing_out_of_order_never_frees_bytes_in_the_air() { + let mut ring: Ring<B> = Ring::new(); + let mut made = 0; + // (buffer, from, to, ticket) of every carve in the air. + let mut air: Vec<(u32, u64, u64, u64)> = Vec::new(); + let mut gone: Vec<B> = Vec::new(); + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..20_000 { + let want = 4096 + next() % (2 * MIB); + let (c, went) = carve(&mut ring, want, 0, &mut made); + gone.extend(went); + let to = c.at + want.next_multiple_of(ALIGN); + assert!(to <= c.memory.1, "a carve past its buffer's end"); + for &(id, from, until, _) in &air { + assert!(id != c.memory.0 || to <= from || until <= c.at, "a carve at {}..{to} over one in the air {from}..{until}", c.at); + } + assert!(!gone.iter().any(|g| g.0 == c.memory.0), "carved from a buffer let go"); + air.push((c.memory.0, c.at, to, c.ticket)); + if air.len() == 8 { + // One of the eight lands, any of them. + let landed = air.swap_remove((next() % 8) as usize); + for g in ring.give_back(landed.3) { + assert!(!air.iter().any(|a| a.0 == g.0), "buffer {} let go with carves in the air", g.0); + gone.push(g); + } + } + } + for (.., ticket) in air.drain(..) { + gone.extend(ring.give_back(ticket)); + } + assert_eq!(ring.held(), 0); + assert_eq!(ring.buffers(), 1, "the open buffer alone is left"); + assert!(made < 20, "{made} buffers made for 20,000 carves"); + } + + /// The ring grows by a new buffer when a carve does not fit, sized from + /// the bytes in the air; the one it replaces goes when its last carve + /// comes back. The sweep closes a buffer more than twice what the last + /// idle time asked for, and with no carve for the idle time lets every + /// buffer go. A carve past `OUTSIZE` gets a buffer of its own and leaves + /// the ring as it was. + #[test] + fn the_ring_grows_by_a_buffer_and_shrinks_when_idle() { + const IDLE: u64 = 10_000; + let mut ring: Ring<B> = Ring::new(); + let mut made = 0; + let small = carve(&mut ring, MIB, 0, &mut made).0; + let first = small.memory; + // A burst of 40 MiB in the air: new buffers, the first closed. + let mut burst = Vec::new(); + for _ in 0..10 { + burst.push(carve(&mut ring, 4 * MIB, 100, &mut made).0); + } + assert!(made >= 2, "the ring grew"); + let big = burst.last().unwrap().memory; + assert!(ring.bytes() >= 41 * MIB); + assert!(ring.buffers() >= 2); + assert!(ring.give_back(small.ticket).contains(&first), "the first buffer goes with its last carve"); + for c in burst.drain(..) { + ring.give_back(c.ticket); + } + assert_eq!((ring.buffers(), ring.bytes()), (1, big.1), "the burst's closed buffers went with their carves"); + // Steady sends of 1 MiB, one in the air at a time, for twice the + // idle time: the burst's buffer is closed. + let mut t = 200; + while t < 200 + 2 * IDLE { + let c = carve(&mut ring, MIB, t, &mut made).0; + assert!(ring.let_go(t, IDLE).iter().all(|g| g.0 != c.memory.0), "a buffer let go with a carve in the air"); + ring.give_back(c.ticket); + t += 16; + } + let steady = carve(&mut ring, MIB, t, &mut made).0; + assert!(steady.memory.1 < big.1, "the burst's buffer was closed for a smaller one"); + assert_eq!(steady.memory.1, LEAST, "{} MiB for 1 MiB in the air", steady.memory.1 >> 20); + ring.give_back(steady.ticket); + assert_eq!(ring.buffers(), 1, "the burst's buffer went once its carves had come back"); + // A carve past `OUTSIZE`: a buffer of its own, gone when it comes back. + let huge = carve(&mut ring, OUTSIZE + 1, t, &mut made).0; + assert_ne!(huge.memory, steady.memory); + assert!(huge.memory.1 < (OUTSIZE + 1) * 9 / 8 + ALIGN); + assert_eq!(ring.give_back(huge.ticket), [huge.memory]); + assert_eq!(ring.buffers(), 1); + let after = carve(&mut ring, MIB, t, &mut made).0; + assert_eq!(after.memory, steady.memory, "the open buffer stayed open"); + ring.give_back(after.ticket); + // No carve for the idle time: every buffer goes. + assert!(ring.let_go(t + IDLE - 1, IDLE).is_empty()); + assert_eq!(ring.let_go(t + IDLE, IDLE), [steady.memory]); + assert_eq!((ring.buffers(), ring.bytes()), (0, 0)); + } + + /// A carve past `OUTSIZE` in the air sizes nothing: the buffer made when + /// ordinary carves outgrow the open one is made for the ordinary bytes + /// in the air, and the sweep still closes an open buffer far over what + /// they ask for. Counted with it, a 100 MiB send made the next 1 MiB + /// carve that did not fit a buffer of some 330 MiB, and kept a burst's + /// buffer open for as long as the send was out. + #[test] + fn a_carve_past_outsize_does_not_size_the_ring() { + const IDLE: u64 = 10_000; + let mut ring: Ring<B> = Ring::new(); + let mut made = 0; + let mut small = vec![carve(&mut ring, MIB, 0, &mut made).0]; + assert_eq!(small[0].memory.1, LEAST); + let huge = carve(&mut ring, 100 * MIB, 0, &mut made).0; + assert_eq!(made, 2, "a buffer of its own"); + for _ in 0..4 { + small.push(carve(&mut ring, MIB, 0, &mut made).0); + } + assert_eq!(made, 3, "the fifth MiB did not fit the least buffer"); + let grown = small.last().unwrap().memory; + let ordinary = Ring::<B>::made_for(5 * MIB, MIB); + assert!(grown.1 <= ordinary, "{} MiB made for 5 MiB of ordinary sends in the air", grown.1 >> 20); + for c in small.drain(..) { + ring.give_back(c.ticket); + } + // A burst's buffer, then steady 1 MiB sends with the huge carve + // still out over two idle times: the burst's buffer is closed. + let mut burst = Vec::new(); + for _ in 0..10 { + burst.push(carve(&mut ring, 4 * MIB, 100, &mut made).0); + } + let big = burst.last().unwrap().memory; + for c in burst.drain(..) { + ring.give_back(c.ticket); + } + let mut t = 200; + while t < 200 + 2 * IDLE { + let c = carve(&mut ring, MIB, t, &mut made).0; + ring.let_go(t, IDLE); + ring.give_back(c.ticket); + t += 16; + } + let steady = carve(&mut ring, MIB, t, &mut made).0; + assert!(steady.memory.1 < big.1, "the burst's buffer stayed open while the huge carve was out"); + assert_eq!(steady.memory.1, LEAST); + ring.give_back(steady.ticket); + assert_eq!(ring.give_back(huge.ticket), [huge.memory]); + assert_eq!(ring.buffers(), 1); + assert_eq!(ring.free(), LEAST, "the open buffer's bytes, all free"); + } +} + diff --git a/d3d12/crates/leonida-gpu/src/host/spare.rs b/d3d12/crates/leonida-gpu/src/host/spare.rs new file mode 100644 index 0000000000..c940e4855e --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/spare.rs @@ -0,0 +1,23 @@ +use super::Spare; + +/// Kept things come back by size, the last given first, and nothing is +/// kept past the limit. +#[test] +fn kept_things_come_back_by_size_within_the_limit() { + let mut spare: Spare<u32> = Spare::new(); + assert_eq!(spare.take(4), None); + assert_eq!(spare.give(1, 4, 10), None); + assert_eq!(spare.give(2, 1, 10), None); + assert_eq!(spare.give(3, 4, 10), None); + assert_eq!(spare.bytes, 9); + // Past the limit: handed back, nothing changes. + assert_eq!(spare.give(4, 4, 10), Some(4)); + assert_eq!(spare.bytes, 9); + assert_eq!(spare.take(2), None, "no thing of that size"); + assert_eq!(spare.take(4), Some(3)); + assert_eq!(spare.take(4), Some(1)); + assert_eq!(spare.take(4), None); + assert_eq!(spare.take(1), Some(2)); + assert_eq!(spare.bytes, 0); + assert!(spare.kept.is_empty()); +} diff --git a/d3d12/crates/leonida-gpu/src/host/summary.rs b/d3d12/crates/leonida-gpu/src/host/summary.rs new file mode 100644 index 0000000000..a497c2686f --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/summary.rs @@ -0,0 +1,672 @@ +//! What a closed list's steps say that does not depend on what title memory +//! holds, found once, when the list is closed, by the thread that closes it +//! (`LEONIDA_CLOSE_SUMMARY`; on by default; `0`: every question walks the +//! steps, as before; `check`: both, compared, the steps' answer taken; +//! `LEONIDA_AB` can turn it on and off while the title runs). +//! +//! The thread that prepares a submission went over every step of every list +//! for each question it asks of them: whether flights in the air stop the +//! preparing ([`super::blocked_by`]: once, then again after every landing the +//! relay waits through, `relay_wait_apart`), which refreshed ranges of copies +//! shaders may be writing the title changed ([`super::stale_under_flights`]), +//! what the write watch is asked about (per copy, the span of its refreshes) +//! and what shaders may write ([`super::declared_writes`]); each with the +//! list's lock held for the walk, most with a table of copies made anew. A +//! frame has some 20,000 refreshes of 4,500 copies and 13,000 copies and fills +//! of upload memory, on the one thread `docs/findings.md` calls the wall. +//! +//! Every answer is made of two kinds of things. Facts fixed when a step is +//! recorded: title addresses (a copy's source and destination, a fill's +//! source, a texture's or movie plane's memory, a copy at its place), which +//! host copy a step names, where the list's first step of ours that may write +//! title memory stands. And what is looked at when the question is asked: +//! what flights write now, which copies shaders are writing now, which the +//! write watch asks about, what landed lately. The first kind is kept here +//! ([`Summary`]); the second is asked at submission as it was, of the +//! summaries' copies and ranges instead of the steps. Nothing takes a summary +//! out, so a list submitted twice has it both times; title memory changing +//! between the close and a submission changes nothing kept. +//! +//! A summary is for the steps it was made from. Steps are only added to a +//! list until its reset, which drops the summary with them (as does +//! `card_steps`' taking its list's `Deferred` whole), so one whose list has +//! more steps than it counted (a list asked about while still open, as tests +//! do) is made again. A list with none (our own of `card_steps`, one closed +//! while the switch was off) has it made at its first question, on the +//! submitting thread: one walk instead of one per question. +//! +//! Where an answer needs more than a summary knows, the steps are walked as +//! before: with `LEONIDA_FILL_TITLE` (a small fill or copy source flights +//! declare may be the title's own, per range by what landed lately), when a +//! copy at its place waits only for its readers ([`place::reader`] goes by +//! the steps' order), and for the frame line's counts and names of what +//! stopped a submission (once one is stopped: a settle follows). +//! +//! On by default: every answer is the steps' by construction (the same rule +//! asked of joined ranges instead of each step's; per copy instead of per +//! refresh where the question is asked of the copy), and `tests` compare each +//! with the steps' over random lists of every kind of step but textures, +//! summaries made at the close, made late and made again, lists named twice +//! and asked again with other flights in the air. Measured there only: four +//! closed lists of some 490 steps each, asked what a submission asks of them, +//! walk 8,231 steps by the steps and none by their summaries. Not measured +//! with the game. + +use super::*; +use crate::shadow::Shadow; +use std::sync::Arc; + +/// What a list's steps say, apart from what title memory holds. +#[derive(Default)] +pub(super) struct Summary { + /// How many steps it was made from. + steps: usize, + /// The title memory that the steps ahead of the list's first + /// [`Step::Run`] (all of them, without one) read on the CPU at submission + /// or copy into: copies' sources and destinations, fills' sources, + /// textures' and movie planes' memory; in order, joined. What + /// [`super::blocked_by`] asks of each of those steps. + reads: Vec<(usize, usize)>, + /// The copies at their place among those steps, in order. + placed: Vec<place::Fact>, + /// The list has a [`Step::Run`]. + run: bool, + /// The list has a [`Step::Copy`] or a [`Step::Run`] ([`super::joinable`]). + copy_or_run: bool, + /// Per host copy the list refreshes, in the order of its first refresh, + /// the span of all its refreshes (from, to). + refreshed: Vec<(Arc<Shadow>, usize, usize)>, + /// The ranges (from, to) the list's shaders may write, per host copy in + /// the order first declared, each (address, bytes) once, in the order + /// declared. + declared: Vec<Declared>, +} + +impl Summary { + /// From a list's steps, in one walk. + pub(super) fn of(steps: &[Step]) -> Summary { + walked(steps.len()); + let mut s = Summary { + steps: steps.len(), + ..Summary::default() + }; + let mut reads: Vec<(usize, usize)> = Vec::new(); + let mut refreshed_at: ByCopy<usize> = ByCopy::default(); + let mut declared_at: ByCopy<usize> = ByCopy::default(); + let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default(); + // (Refreshes of one copy mostly come several times on end.) + let mut last = (0, 0); + for step in steps { + match step { + &Step::Copy(dst, src, len) => { + s.copy_or_run = true; + if !s.run { + reads.push((src, src + len)); + reads.push((dst, dst + len)); + } + } + &Step::Fill(_, src, len, _) if !s.run => reads.push((src, src + len)), + Step::Texture(staging) if !s.run => { + let (at, len) = staging.memory(); + reads.push((at, at + len)); + } + &Step::Plane((at, len), _) if !s.run => reads.push((at, at.saturating_add(len))), + Step::Placed(p) if !s.run => s.placed.push(p.fact()), + Step::Run(_) => { + s.run = true; + s.copy_or_run = true; + } + Step::Refresh(shadow, address, len) => { + let (from, to) = (*address, *address + *len); + let key = Arc::as_ptr(shadow) as usize; + let i = if last.0 == key { + last.1 + } else { + *refreshed_at.entry(key).or_insert_with(|| { + s.refreshed.push((shadow.clone(), from, to)); + s.refreshed.len() - 1 + }) + }; + last = (key, i); + let r = &mut s.refreshed[i]; + (r.1, r.2) = (r.1.min(from), r.2.max(to)); + } + Step::GpuWrite(shadow, address, len) => { + let key = Arc::as_ptr(shadow) as usize; + if seen.insert((key, *address, *len)) { + let i = *declared_at.entry(key).or_insert_with(|| { + s.declared.push((shadow.clone(), Vec::new())); + s.declared.len() - 1 + }); + s.declared[i].1.push((*address, *address + *len)); + } + } + _ => {} + } + } + join_ranges(&mut s.reads, reads); + s + } +} + +/// What [`mode`] asks for. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Mode { + /// Every question walks the steps, as before. + Off, + /// The lists' summaries. + On, + /// Both, compared ([`CHECK`]); the steps' answer is taken. + Check, +} + +/// See the module's note. +pub(super) fn mode() -> Mode { + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("LEONIDA_CLOSE_SUMMARY") { + return if on { Mode::On } else { Mode::Off }; + } + static MODE: OnceLock<Mode> = OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("LEONIDA_CLOSE_SUMMARY").as_deref() { + Ok("0") => Mode::Off, + Ok("check") => Mode::Check, + _ => Mode::On, + }) +} + +/// At a list's close: its summary, kept with its steps. +pub(super) fn close(deferred: &mut Deferred) { + if mode() != Mode::Off { + deferred.summary = Some(Arc::new(Summary::of(&deferred.copies))); + } +} + +/// `list`'s summary as kept, or made now (and kept) if it has none for its +/// steps as they are. +pub(super) fn of(list: &HostList) -> Arc<Summary> { + let mut deferred = list.deferred(); + if let Some(kept) = &deferred.summary + && kept.steps == deferred.copies.len() + { + return kept.clone(); + } + let made = Arc::new(Summary::of(&deferred.copies)); + deferred.summary = Some(made.clone()); + made +} + +/// The summaries of `runs`, in order, one list's lock at a time; `None` with +/// the switch off. +pub(super) fn all(runs: &[&HostList]) -> Option<Vec<Arc<Summary>>> { + (mode() != Mode::Off).then(|| runs.iter().map(|list| of(list)).collect()) +} + +/// What [`blocked`] finds. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Blocked { + No, + /// A step reads (or a title copy writes) what flights may write. + Read, + /// A step of ours that may write title memory comes first. + Run, + /// The summaries cannot say: the steps are walked ([`super::blocked_by`]). + Steps, +} + +/// [`super::blocked_by`] of the lists whose summaries are `sums`, against +/// `written` (in order, joined): the steps up to the first [`Step::Run`] of +/// the submission, as the walk takes them; a read stopped by `written` +/// anywhere among them, else that `Run`. +pub(super) fn blocked(written: &[(usize, usize)], sums: &[Arc<Summary>]) -> Blocked { + if written.is_empty() { + return Blocked::No; + } + // (Per range, by what landed lately.) + if fill_title_on() { + return Blocked::Steps; + } + let mut readers = false; + for s in sums { + if meets(written, &s.reads) { + return Blocked::Read; + } + for p in &s.placed { + match p.waits(written) { + place::Waits::Yes => return Blocked::Read, + place::Waits::ForReaders => readers = true, + place::Waits::No => {} + } + } + if s.run { + return Blocked::Run; + } + } + if readers { Blocked::Steps } else { Blocked::No } +} + +/// Whether two lists of ranges, each in order and joined, share a byte. +pub(super) fn meets(a: &[(usize, usize)], b: &[(usize, usize)]) -> bool { + let (mut i, mut j) = (0, 0); + while i < a.len() && j < b.len() { + if a[i].1 <= b[j].0 { + i += 1; + } else if b[j].1 <= a[i].0 { + j += 1; + } else { + return true; + } + } + false +} + +/// Per copy the lists refresh and `asked` says the write watch is asked +/// about, the span of all their refreshes of it. +pub(super) fn asked(sums: &[Arc<Summary>], asked: impl Fn(&Shadow) -> bool) -> ByCopy<(usize, usize)> { + let mut spans: ByCopy<(usize, usize)> = ByCopy::default(); + for s in sums { + for (shadow, from, to) in &s.refreshed { + if asked(shadow) { + let span = spans.entry(Arc::as_ptr(shadow) as usize).or_insert((*from, *to)); + *span = (span.0.min(*from), span.1.max(*to)); + } + } + } + spans +} + +/// The copies the lists refresh that `pending` says shaders may be writing +/// (asked once per copy), in the order first refreshed, with the span of all +/// their refreshes: what [`super::stale_under_flights`] looks at. +pub(super) fn stale_spans(sums: &[Arc<Summary>], pending: impl Fn(&Shadow) -> bool) -> Vec<(Arc<Shadow>, usize, usize)> { + if let [one] = sums { + return one.refreshed.iter().filter(|r| pending(&r.0)).cloned().collect(); + } + let mut spans: Vec<(Arc<Shadow>, usize, usize)> = Vec::new(); + let mut places: ByCopy<Option<usize>> = ByCopy::default(); + for s in sums { + for (shadow, from, to) in &s.refreshed { + let place = places.entry(Arc::as_ptr(shadow) as usize).or_insert_with(|| { + pending(shadow).then(|| { + spans.push((shadow.clone(), *from, *to)); + spans.len() - 1 + }) + }); + if let Some(i) = *place { + let span = &mut spans[i]; + (span.1, span.2) = (span.1.min(*from), span.2.max(*to)); + } + } + } + spans +} + +/// Per copy the lists refresh, in the order first refreshed, the span of all +/// their refreshes, into `spans`, and where each copy (by address) is in it +/// (`Batch::copy_spans`). +pub(super) fn copy_spans(sums: &[Arc<Summary>], spans: &mut Vec<(Arc<Shadow>, usize, usize)>, at: &mut ByCopy<usize>) { + spans.clear(); + at.clear(); + for s in sums { + for (shadow, from, to) in &s.refreshed { + match at.entry(Arc::as_ptr(shadow) as usize) { + std::collections::hash_map::Entry::Occupied(i) => { + let span = &mut spans[*i.get()]; + (span.1, span.2) = (span.1.min(*from), span.2.max(*to)); + } + std::collections::hash_map::Entry::Vacant(place) => { + place.insert(spans.len()); + spans.push((shadow.clone(), *from, *to)); + } + } + } + } +} + +/// [`super::declared_writes`] of the lists: per copy in the order first +/// declared, each range (address, bytes) once in the order declared. One +/// list's are its own as they are. +pub(super) fn declared(sums: &[Arc<Summary>]) -> Vec<Declared> { + if let [one] = sums { + return one.declared.clone(); + } + let mut back: Vec<Declared> = Vec::new(); + let mut places: ByCopy<usize> = ByCopy::default(); + let mut seen = std::collections::HashSet::<(usize, usize, usize), std::hash::BuildHasherDefault<AddressHash>>::default(); + for s in sums { + for (shadow, ranges) in &s.declared { + let key = Arc::as_ptr(shadow) as usize; + for &(from, to) in ranges { + if !seen.insert((key, from, to - from)) { + continue; + } + let i = *places.entry(key).or_insert_with(|| { + back.push((shadow.clone(), Vec::new())); + back.len() - 1 + }); + back[i].1.push((from, to)); + } + } + } + back +} + +/// Whether one of the lists has a [`Step::Copy`] or a [`Step::Run`]. +pub(super) fn copy_or_run(sums: &[Arc<Summary>]) -> bool { + sums.iter().any(|s| s.copy_or_run) +} + +/// With [`Mode::Check`]: `ask` (which copies shaders are writing, which the +/// write watch asks about) asked once per host copy, its answer kept, so that +/// the summaries' answer and the steps' go by the same: the relay thread can +/// land a flight between the two, and a difference would come of the timing. +pub(super) fn once(ask: impl Fn(&Shadow) -> bool) -> impl Fn(&Shadow) -> bool { + let kept = std::cell::RefCell::new(ByCopy::<bool>::default()); + move |shadow| *kept.borrow_mut().entry(std::ptr::from_ref(shadow) as usize).or_insert_with(|| ask(shadow)) +} + +/// Since the start, with `LEONIDA_CLOSE_SUMMARY=check`: answers of the +/// summaries that differed from the steps' (must be 0; what flights stop can +/// differ by a landing's timing with `LEONIDA_PLACED_TITLE=1`, see +/// [`super::blocked_by_in`]), and those compared. +static CHECK: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// With [`Mode::Check`]: one answer compared. +pub(super) fn compared(what: &'static str, same: bool) { + CHECK[1].fetch_add(1, Ordering::Relaxed); + if !same { + let n = CHECK[0].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + tracing::warn!(n, what, "a submission's lists' summaries gave another answer than their steps (LEONIDA_CLOSE_SUMMARY=check)"); + } + } +} + +/// For the frame-rate line, with `LEONIDA_CLOSE_SUMMARY=check`. +#[cfg(feature = "diagnostics")] +pub(crate) fn line() -> Option<String> { + (mode() == Mode::Check).then(|| { + format!( + "lists' summaries made at their close against their steps (LEONIDA_CLOSE_SUMMARY=check), since the start: {} comparisons, {} that differed (must be 0)", + CHECK[1].load(Ordering::Relaxed), + CHECK[0].load(Ordering::Relaxed) + ) + }) +} + +#[cfg(test)] +thread_local! { + /// For the tests: steps walked on this thread by the questions a + /// submission asks of its lists' steps, and by [`Summary::of`]. + static WALKED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + +/// `n` steps walked for a question of the submission's ([`WALKED`]). +#[inline(always)] +pub(super) fn walked(_n: usize) { + #[cfg(test)] + WALKED.with(|w| w.set(w.get() + _n as u64)); +} + +/// For the tests: [`WALKED`] so far on this thread. +#[cfg(test)] +pub(super) fn walked_so_far() -> u64 { + WALKED.with(std::cell::Cell::get) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A small generator of numbers, the same every run. + struct Dice(u64); + + impl Dice { + fn below(&mut self, n: usize) -> usize { + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (self.0 >> 33) as usize % n + } + } + + /// Host copies with no buffer behind them, of title memory at 0x1000 on. + fn copies(n: usize) -> Vec<Arc<Shadow>> { + (0..n) + .map(|i| { + let data = Box::leak(vec![0u8; 0x1000].into_boxed_slice()); + Shadow::unbacked(0x1000 * (i as u64 + 1), data.as_mut_ptr(), 0x1000, false) + }) + .collect() + } + + /// A step of every kind a summary looks at but textures (a staging + /// buffer needs a title texture), over a few KiB so that they meet: a + /// step of ours that may write title memory now and then, ranges of no + /// bytes too. + fn step(dice: &mut Dice, shadows: &[Arc<Shadow>]) -> Step { + let at = |dice: &mut Dice| 0x1000 + dice.below(0x1000); + let len = |dice: &mut Dice| dice.below(96); + let copy = |dice: &mut Dice| shadows[dice.below(shadows.len())].clone(); + match dice.below(40) { + 0 => Step::Run(Box::new(|| {})), + 1..=4 => Step::Copy(at(dice), at(dice), len(dice)), + 5..=10 => Step::Fill(0, at(dice), len(dice), None), + 11..=13 => { + let from = at(dice); + Step::Host(Box::new(|| {}), (from, from + len(dice))) + } + 14 => Step::Plane((at(dice), len(dice)), Box::new(|| {})), + 15..=18 => { + let from = (dice.below(2) == 0).then_some(0x10); + Step::Placed(place::Placed::for_tests(at(dice), at(dice), 1 + len(dice), copy(dice), from)) + } + 19..=27 => Step::GpuWrite(copy(dice), at(dice), len(dice)), + _ => Step::Refresh(copy(dice), at(dice), len(dice)), + } + } + + /// Ranges flights write, in order and joined, some none. + fn written(dice: &mut Dice) -> Vec<(usize, usize)> { + let mut ranges = Vec::new(); + let more: Vec<(usize, usize)> = (0..dice.below(4)) + .map(|_| { + let from = 0x1000 + dice.below(0x1000); + (from, from + 1 + dice.below(256)) + }) + .collect(); + join_ranges(&mut ranges, more); + ranges + } + + fn keyed(spans: &[(Arc<Shadow>, usize, usize)]) -> Vec<(usize, usize, usize)> { + spans.iter().map(|s| (Arc::as_ptr(&s.0) as usize, s.1, s.2)).collect() + } + + fn keyed_declared(all: &[Declared]) -> Vec<(usize, Vec<(usize, usize)>)> { + all.iter().map(|(shadow, ranges)| (Arc::as_ptr(shadow) as usize, ranges.clone())).collect() + } + + /// Random submissions of synthetic lists: each question a submission asks + /// of its lists' steps gets the same answer from their summaries, span for + /// span and in the same order where the order is kept. Summaries made at + /// the close, made at the first question, and made again for a list given + /// steps since; lists named twice by a submission and asked again with + /// other flights in the air (what flights write, which copies shaders are + /// writing and which the write watch asks about all change between the + /// close and a submission, and between two submissions of a list). + #[test] + fn summaries_answer_what_the_steps_answer() { + let Some(host) = host() else { + eprintln!("no D3D12 device; lists' summaries not compared with their steps"); + return; + }; + let shadows = copies(6); + let lists: Vec<HostList> = (0..5).map(|_| host.new_list().unwrap()).collect(); + let mut dice = Dice(0x5eed_1e55); + let mut answers = [0usize; 4]; + for _ in 0..400 { + for list in &lists { + let mut deferred = list.deferred(); + *deferred = Deferred::default(); + deferred.copies = (0..dice.below(40)).map(|_| step(&mut dice, &shadows)).collect(); + match dice.below(3) { + // At the close. + 0 => close(&mut deferred), + // At the close, and steps since. + 1 => { + close(&mut deferred); + let more: Vec<Step> = (0..1 + dice.below(4)).map(|_| step(&mut dice, &shadows)).collect(); + deferred.copies.extend(more); + } + // None: made at the first question. + _ => {} + } + } + let runs: Vec<&HostList> = (0..1 + dice.below(5)).map(|_| &lists[dice.below(lists.len())]).collect(); + for _ in 0..6 { + let sums: Vec<Arc<Summary>> = runs.iter().map(|list| of(list)).collect(); + let written = written(&mut dice); + let steps = blocked_by_steps(&written, &runs, false); + assert_eq!(blocked_by_in(&written, &runs, Some(&sums), false), steps, "written {written:?}"); + answers[match steps { + None => 0, + Some(WHY_READ) => 1, + Some(WHY_RUN) => 2, + Some(_) => 3, + }] += 1; + let mask = dice.below(64); + let pending = |shadow: &Shadow| shadows.iter().position(|s| std::ptr::eq(Arc::as_ptr(s), shadow)).is_some_and(|i| mask & (1 << i) != 0); + assert_eq!(keyed(&stale_spans(&sums, pending)), keyed(&stale_spans_steps(&runs, pending))); + let mut by_steps: Vec<_> = asked_steps(&runs, pending).into_iter().collect(); + let mut by_sums: Vec<_> = asked(&sums, pending).into_iter().collect(); + by_steps.sort_unstable(); + by_sums.sort_unstable(); + assert_eq!(by_sums, by_steps); + assert_eq!(keyed_declared(&declared(&sums)), keyed_declared(&declared_writes_steps(&runs))); + let (mut a, mut b) = (Batch::default(), Batch::default()); + copy_spans(&sums, &mut a.spans, &mut a.spans_at); + b.copy_spans_steps(&runs); + assert_eq!(keyed(&a.spans), keyed(&b.spans)); + assert!(a.spans_at.len() == b.spans_at.len() && a.spans_at.iter().all(|(k, i)| b.spans_at.get(k) == Some(i))); + let walked = runs.iter().any(|l| l.deferred().copies.iter().any(|s| matches!(s, Step::Copy(..) | Step::Run(_)))); + assert_eq!(copy_or_run(&sums), walked); + } + } + // Every answer came up. + assert!(answers[..3].iter().all(|&n| n > 50), "answers (none, read, run, other) {answers:?}"); + for list in &lists { + *list.deferred() = Deferred::default(); + } + } + + /// A summary is for the steps it was made from: one whose list was given + /// steps since is made again at the next question, and kept from then on + /// (asked twice, the list's steps are walked once). + #[test] + fn a_list_given_steps_since_its_summary_has_it_made_again() { + let Some(host) = host() else { + eprintln!("no D3D12 device; a summary's steps not tested"); + return; + }; + let shadow = copies(1).remove(0); + let list = host.new_list().unwrap(); + { + let mut deferred = list.deferred(); + deferred.copies.push(Step::Refresh(shadow.clone(), 0x1000, 0x10)); + close(&mut deferred); + deferred.copies.push(Step::Copy(0x1800, 0x1900, 0x10)); + } + let before = walked_so_far(); + let made = of(&list); + assert_eq!(walked_so_far() - before, 2); + assert!(made.copy_or_run && made.reads == [(0x1800, 0x1810), (0x1900, 0x1910)]); + assert_eq!(keyed(&made.refreshed), [(Arc::as_ptr(&shadow) as usize, 0x1000, 0x1010)]); + assert!(Arc::ptr_eq(&made, &of(&list))); + assert_eq!(walked_so_far() - before, 2); + *list.deferred() = Deferred::default(); + } + + /// The questions `Host::submit` asks of a submission's closed lists (what + /// flights stop, the refreshes under their writes, what the write watch + /// is asked about, what shaders may write, whether a part can be joined) + /// walk none of their steps: each list's were walked once, at its close. + /// By the steps (`LEONIDA_CLOSE_SUMMARY=0`, the code before) each question + /// walks them all again. + #[test] + fn a_submissions_questions_walk_no_steps_of_closed_lists() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the walks of a submission not counted"); + return; + }; + // (Off, or `check`, which walks the steps too on purpose.) + if mode() != Mode::On { + eprintln!("LEONIDA_CLOSE_SUMMARY is 0 or check; the walks of a submission not counted"); + return; + } + let shadows = copies(6); + let mut dice = Dice(0xc105e); + let lists: Vec<HostList> = (0..4).map(|_| host.new_list().unwrap()).collect(); + let mut steps = 0; + for list in &lists { + // (No step of ours: what flights stop is asked of every step.) + let mine: Vec<Step> = (0..500).map(|_| step(&mut dice, &shadows)).filter(|s| !matches!(s, Step::Run(_))).collect(); + steps += mine.len() as u64; + list.deferred().copies = mine; + let before = walked_so_far(); + list.close(); + assert_eq!(walked_so_far() - before, list.deferred().copies.len() as u64, "one walk at the close"); + } + let runs: Vec<&HostList> = lists.iter().collect(); + // Flights write beyond every step's bytes. + let written = [(0x10_0000, 0x10_1000)]; + let ask = |runs: &[&HostList]| { + let before = walked_so_far(); + assert_eq!(blocked_by(&written, runs, false), None); + let _ = stale_under_flights(runs); + let _ = asked_spans(runs); + let _ = declared_writes(runs); + let _ = joinable(runs[..1].iter().copied(), &runs[1..]); + walked_so_far() - before + }; + assert_eq!(ask(&runs), 0, "the submission's questions walked steps"); + // The same lists submitted again: still none. + assert_eq!(ask(&runs), 0); + // By the steps, as before: every question walks every list. + let before = walked_so_far(); + let _ = blocked_by_steps(&written, &runs, false); + let _ = stale_spans_steps(&runs, Shadow::writes_pending); + let _ = asked_steps(&runs, Shadow::asked_ahead); + let _ = declared_writes_steps(&runs); + assert!(walked_so_far() - before >= 4 * steps, "{} of {steps} steps", walked_so_far() - before); + for list in &lists { + list.reset(); + } + } + + /// What `check` compares goes by one answer per copy: a predicate whose + /// answer changes between two askings (a flight landing between the + /// summaries' answer and the steps') is asked once per copy through + /// [`once`], and both walks see the first answer. + #[test] + fn check_asks_each_copy_once_for_both_answers() { + let shadows = copies(3); + let asked = std::cell::Cell::new(0usize); + // Yes the first time a copy is asked, no from then on. + let seen = std::cell::RefCell::new(Vec::<usize>::new()); + let flips = |shadow: &Shadow| { + asked.set(asked.get() + 1); + let key = std::ptr::from_ref(shadow) as usize; + let first = !seen.borrow().contains(&key); + seen.borrow_mut().push(key); + first + }; + let kept = once(flips); + let sums = [Arc::new(Summary { + refreshed: shadows.iter().map(|s| (s.clone(), 0x1000, 0x1010)).collect(), + ..Summary::default() + })]; + let a = keyed(&stale_spans(&sums, &kept)); + let b = keyed(&stale_spans(&sums, &kept)); + assert_eq!(a.len(), 3); + assert_eq!(a, b); + assert_eq!(asked.get(), 3); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/sweep_now_tests.rs b/d3d12/crates/leonida-gpu/src/host/sweep_now_tests.rs new file mode 100644 index 0000000000..533f1a288f --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/sweep_now_tests.rs @@ -0,0 +1,40 @@ +use super::{sweep_now, wants_rest}; + +/// The settle stays for `LEONIDA_SWEEP_NO_SETTLE=0`, for the up-copy +/// check and for the relay with the compare's results as a whole area +/// (`LEONIDA_COMPARE_RING=0`); with none of those the sweep wants no +/// rest, the relay with the ring included. +#[test] +fn the_settle_stays_only_for_what_wants_rest() { + // LEONIDA_SWEEP_NO_SETTLE=0: whatever else is on. + for others in 0..8 { + assert!(wants_rest(false, others & 1 != 0, others & 2 != 0, others & 4 != 0), "{others:03b}"); + } + // The up-copy check: whatever else is on. + for others in 0..4 { + assert!(wants_rest(true, true, others & 1 != 0, others & 2 != 0), "{others:02b}"); + } + assert!(wants_rest(false, false, true, true), "LEONIDA_SWEEP_NO_SETTLE=0 settles as before"); + assert!(wants_rest(true, true, true, true), "the up-copy check wants nothing in the air"); + assert!(wants_rest(true, false, true, false), "the whole area comes back only at rest"); + assert!(!wants_rest(true, false, true, true), "the ring gives plans back as flights land"); + assert!(!wants_rest(true, false, false, false), "without the relay the area comes back at each settle"); +} + +/// Behind flights with the present sent ahead, a sweep that needs no +/// rest runs at once and never settles; one that does settles every +/// 1.5 s, as all of them did (`LEONIDA_SWEEP_NO_SETTLE=0`). With +/// nothing in the air it runs without a settle, and behind flights +/// without the present sent ahead it waits for the present's settle. +#[test] +fn the_sweep_behind_flights_settles_only_for_what_wants_rest() { + for since in [0, 999, 1500, 1501, 60_000] { + assert_eq!(sweep_now(true, true, since, false), (true, false), "behind flights, {since} ms"); + assert_eq!(sweep_now(false, true, since, false), (true, false)); + assert_eq!(sweep_now(false, false, since, true), (true, false)); + assert_eq!(sweep_now(true, false, since, false), (false, false)); + assert_eq!(sweep_now(true, false, since, true), (false, false)); + let due = since > 1500; + assert_eq!(sweep_now(true, true, since, true), (due, due), "wanting rest, {since} ms"); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/tests.rs b/d3d12/crates/leonida-gpu/src/host/tests.rs new file mode 100644 index 0000000000..43e75a4cc4 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/tests.rs @@ -0,0 +1,138 @@ +/// A list of ours is found by its name, with the debug layer's note or not. +#[cfg(feature = "diagnostics")] +#[test] +fn a_list_is_found_by_the_number_in_its_name() { + assert_eq!(super::list_number("leonida host list 7"), Some(7)); + assert_eq!(super::list_number("leonida host list 158 (debug layer indirect)"), Some(158)); + assert_eq!(super::list_number("leonida host list 7x"), None); + assert_eq!(super::list_number("leonida host list 7 x"), None); + assert_eq!(super::list_number("another list 7"), None); + assert_eq!(super::list_number(""), None); +} + +/// What is there of a range some of whose pages are not: those bytes, +/// counted, and zeros for the rest, whatever the buffer held. +#[test] +fn what_is_there_is_read_and_the_rest_is_zeros() { + use windows_sys::Win32::System::Memory::*; + const SIZE: usize = 0x8_0000; + // SAFETY: a reservation of ours; only committed pages are written. + unsafe { + let at = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>(); + assert!(!at.is_null()); + // 0-0x1_1000 and 0x3_0000-0x4_0000 are there. + for (from, len) in [(0, 0x1_1000), (0x3_0000, 0x1_0000)] { + assert!(!VirtualAlloc(at.add(from).cast(), len, MEM_COMMIT, PAGE_READWRITE).is_null()); + at.add(from).write_bytes(0x5a, len); + } + // From an address inside a page, as textures are packed. + let mut out = vec![0x77u8; SIZE - 0x300]; + assert_eq!(super::read_there(at.add(0x300), &mut out), 0x1_1000 - 0x300 + 0x1_0000); + for (i, &b) in out.iter().enumerate() { + let from = i + 0x300; + let there = from < 0x1_1000 || (0x3_0000..0x4_0000).contains(&from); + assert_eq!(b, if there { 0x5a } else { 0 }, "byte {from:#x}"); + } + // All there: one read. + let mut out = vec![0x77u8; 0x1_0000]; + assert_eq!(super::read_there(at.add(0x1000), &mut out), 0x1_0000); + assert!(out.iter().all(|&b| b == 0x5a)); + // Nothing there. + let mut out = vec![0x77u8; 0x1_0000]; + assert_eq!(super::read_there(at.add(0x5_0000), &mut out), 0); + assert!(out.iter().all(|&b| b == 0)); + assert_ne!(VirtualFree(at.cast(), 0, MEM_RELEASE), 0); + } +} + +/// Only what lies before, between and after the runs is zeroed (after +/// DoubleGhosty/cool_fox e8b62de); runs that overlap leave no gap. +#[test] +fn only_bytes_outside_the_runs_are_zeroed() { + let mut dst = [7u8; 16]; + super::zero_between(&mut dst, 100, &[(102, 3), (104, 2), (110, 4)]); + assert_eq!(dst, [0, 0, 7, 7, 7, 7, 0, 0, 0, 0, 7, 7, 7, 7, 0, 0]); + let mut dst = [7u8; 4]; + super::zero_between(&mut dst, 100, &[(100, 4)]); + assert_eq!(dst, [7; 4]); + super::zero_between(&mut dst, 100, &[]); + assert_eq!(dst, [0; 4]); +} + +/// Zeros for a title destination that went meanwhile are no fault. +#[test] +fn zeros_where_nothing_is_are_lost() { + use windows_sys::Win32::System::Memory::*; + // SAFETY: a reservation of ours, its first page committed. + unsafe { + let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>(); + assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null()); + at.write_bytes(7, 4096); + super::zero(at, 4096); + assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0)); + super::zero(at.add(4096), 4096); + VirtualFree(at.cast(), 0, MEM_RELEASE); + } +} + +#[test] +fn sparse_copies_preserve_islands_and_observe_remaps() { + use windows_sys::Win32::System::Memory::*; + const N: usize = 5 << 16; + // SAFETY: we reserve a private region, commit selected pages inside it, + // and only directly access the pages while they are writable. + unsafe { + let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>(); + assert!(!base.is_null()); + let mut expected = vec![0; N]; + for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] { + let at = base.add(offset); + assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); + at.write_bytes(value, 4096); + expected[offset..offset + 4096].fill(value); + } + for remap in [false, true] { + if remap { + let mut old = 0; + assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0); + expected[..4096].fill(0); + let at = base.add(1 << 16); + assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); + at.write_bytes(0xc7, 4096); + expected[1 << 16..(1 << 16) + 4096].fill(0xc7); + } + let mut out = vec![0xee; N]; + super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false); + assert_eq!(out[27..N - 27], expected[27..N - 27]); + assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee)); + } + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); + } +} + +use super::*; + +#[test] +fn warp_adapter_accepts_only_software() { + // This probes DXGI without creating a D3D12 device or running a title. + // SAFETY: plain DXGI adapter queries. + let raw = unsafe { + let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0)) + else { + return; + }; + factory.EnumWarpAdapter::<IDXGIAdapter>() + }; + let Ok(raw) = raw else { return }; + // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements + // IDXGIAdapter1; `raw` owns that interface. + let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() }; + eprintln!( + "EnumWarpAdapter: vendor={:#x}, flags={:#x}", + desc.VendorId, desc.Flags + ); + assert_eq!( + warp_adapter().is_ok(), + desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0, + ); +} diff --git a/d3d12/crates/leonida-gpu/src/host/torn.rs b/d3d12/crates/leonida-gpu/src/host/torn.rs index 1efde9628e..2f131c42a9 100644 --- a/d3d12/crates/leonida-gpu/src/host/torn.rs +++ b/d3d12/crates/leonida-gpu/src/host/torn.rs @@ -53,6 +53,17 @@ impl Suspects { flagged || (!self.0.is_empty() && self.0.contains(&piece)) } + /// `pieces` came down in their flight's own submission + /// (`super::landsame`): what it ended with, not caught in the middle. + pub(super) fn landed(&mut self, pieces: impl Iterator<Item = Piece>) { + if self.0.is_empty() { + return; + } + for piece in pieces { + self.0.remove(&piece); + } + } + /// `piece` was fetched; `same`: it was what the last of the flights /// landed ended with. pub(super) fn fetched(&mut self, piece: Piece, same: bool) { diff --git a/d3d12/crates/leonida-gpu/src/host/trail.rs b/d3d12/crates/leonida-gpu/src/host/trail.rs new file mode 100644 index 0000000000..b4f9b236b6 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/trail.rs @@ -0,0 +1,14 @@ +/// The trail keeps the newest things, and the report made when the +/// host device is removed says them and the pipeline library's state +/// (no card is asked for any of it). +#[test] +fn the_removal_report_says_the_newest_things_done() { + for n in 0..super::TRAIL_MOST + 5 { + super::trail(|| format!("thing {n} done")); + } + let text = super::removal_context(); + assert!(text.contains("the submitting thread was")); + assert!(text.contains("pipeline library: no call running")); + assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4))); + assert!(!text.contains("thing 4 done"), "the oldest entries are dropped"); +} diff --git a/d3d12/crates/leonida-gpu/src/host/undeclared.rs b/d3d12/crates/leonida-gpu/src/host/undeclared.rs new file mode 100644 index 0000000000..48faa543df --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/undeclared.rs @@ -0,0 +1,1706 @@ +//! Diagnostics (`LEONIDA_UNDECLARED_TRACE=1`, with `LEONIDA_UPCOPY_CHECK=1`; +//! off by default, and not in builds without diagnostics): what wrote the +//! card side of a copy that the up-copy check ([`super::upcheck`]) keeps +//! finding unlike its CPU side, told in the run that finds it. +//! +//! The check says where the card holds what the CPU side does not (at a +//! send, or at rest), not what put it there. A copy it flags in two frames +//! is watched ([`flagged`]): up to [`MOST`] copies, [`WINDOW`] bytes of each +//! from the 64 KiB piece flagged last. For every submission from then on, +//! two looks of ours compare the watched bytes on the card with a snapshot +//! the card keeps of them, and take the snapshot anew: +//! +//! - **ahead** of the submission's lists, behind its sends ([`ahead`], a call +//! of its own): what changed since the last submission's lists ran is what +//! its sends put there (or other work of ours on the queue in between, +//! none of which writes a card side); +//! - **behind** its lists, ahead of its compare ([`behind`], first in the +//! compare's call): what changed is what its lists wrote. +//! +//! So which submission changed the bytes, and whether its lists or its sends +//! did, is known exactly, with the words' span and one word's values before +//! and after. A submission not looked at (the switch off for a while under +//! `LEONIDA_AB`, more than [`RING`] in the air) has the snapshots taken anew +//! at the next look, which then says nothing of what changed in between. +//! +//! With a change by its lists goes what the submission's lists told of those +//! bytes while they were recorded ([`Writers`]): +//! +//! - every shader write declared over them (`Shadow::gpu_writes`): the list, +//! the draw or dispatch (`bind n`: the n-th of the list counted from when +//! the watch began, with its program's shaders), the line that declared +//! it (a root view, a view in a table, an address the shader stores by, a +//! copy at its place, `host/place.rs`) and what became of the declaration: +//! compared and landed, kept on the card (`LEONIDA_WC_NO_BACK`), elided, +//! cut where the GPU only reads; named first, and kept apart from the +//! rest, so that no number of other binds hides one; +//! - the programs whose binds store past the views their bind declared +//! (views they pick from the heap, stores by address, scalar stores, a +//! view not declared at its bind, a table the bind did not walk), with how +//! many binds of each: such a program may write the watched bytes without +//! telling; +//! - views picked from the heap declared or looked at for the copy +//! (`crate::picked`); +//! - whether the words that changed lie in a write declared there at all. +//! +//! With a change ahead of the lists goes how many of the words changed are +//! ones the lists of an earlier submission had changed (a send undoing a +//! shader's write), and of which submissions: the card keeps, beside the +//! snapshot, the submission whose lists last changed each watched word, which +//! the look behind the lists sets and the look ahead of them reads and +//! clears; with it, how often the lists asked refreshes of the bytes, the +//! title's copies done on the CPU into them in this submission (they go up +//! with its own sends), and the last submission whose lists wrote values +//! there at the bottom of the pipe or read texels back there (those land on +//! the CPU behind its lists, and go up with a later send). +//! +//! Textures placed over the same bytes are not among them: they write a +//! texture of their own, never the buffer's card side. +//! +//! What the lines say of the causes `docs/findings.md` weighs: +//! +//! - shader writes kept on the card and undone by sends: a submission's +//! lists change the bytes under a declaration kept on the card (or a +//! program that picks its views), and a later submission's sends change +//! them back, "N of the W words were last changed by the lists of +//! submission n", the CPU side's value standing again; +//! - the title rewriting records a shader then changes in place: the sends +//! change words the lists changed too, but each send carries a value the +//! title wrote anew (the CPU side moves from one send to the next, which +//! the up-copy check's own lines show), not the one that stood before the +//! lists ran; refreshes and changes in turns are no sign of it, they come +//! with the cause above as well; +//! - a copy at its place bringing card data the CPU side lacks: the +//! declaration's line is in `host/place.rs`; +//! - a write in a flight that declared nothing there: a change by the lists +//! with no write declared there, or only programs that store past their +//! views; +//! - the card side never moving while the check keeps flagging the watched +//! bytes: what moved is the CPU side (a copy at its place writes only that +//! side, a landing); said once per copy. +//! +//! Each look reads the watched bytes on the card once (at most 4 MiB twice +//! per submission), and each list keeps at most [`KEPT`] declarations and a +//! count per program that stores past its views; what the lists told is +//! gathered, in one walk of them for all watched copies, only for copies +//! with lines left: [`LINES`] per copy, then a sum every few seconds. +//! Nothing is recorded while nothing is watched. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicU64}; +use std::sync::{Arc, Weak}; + +use super::*; +use crate::shadow::Shadow; + +/// Copies watched at once. +const MOST: usize = 16; +/// Bytes watched of each, from a piece on. +const WINDOW: usize = 256 << 10; +const PIECE: usize = 64 << 10; +/// Submissions whose looks may be on the card at once; past them a look is +/// lost (and the snapshots are taken anew). +const RING: usize = 64; +/// Bytes of an answer: words changed, a word's offset, its value before and +/// after, the lowest and highest offset changed; of them, the words an +/// earlier submission's lists had changed, the lowest and highest such +/// submission, and one such word's offset, value before and after. +const ANSWER: usize = 48; +/// An answer as the pass leaves it before it runs. +const UNANSWERED: [u32; ANSWER / 4] = [0, 0, 0, 0, u32::MAX, 0, 0, u32::MAX, 0, 0, 0, 0]; +/// Lines per watched copy; then sums. +const LINES: u32 = 24; +/// What a line names of a submission's declarations, and of its programs +/// that store past them, at most. +const TOLD: usize = 8; +/// Declarations into watched copies a list keeps, at most; and programs +/// that store past their views it counts. +const KEPT: usize = 1024; + +/// On for the tests that ask (one at a time, `turn`), whatever the +/// switches say: in every thread, so that submissions of other tests on +/// the host's queue are looked at too. +#[cfg(test)] +static TEST_ON: AtomicBool = AtomicBool::new(false); + +/// `LEONIDA_UNDECLARED_TRACE=1` (`crate::asked!`), which feeds on the +/// up-copy check: nothing without `LEONIDA_UPCOPY_CHECK=1` too. +pub(crate) fn on() -> bool { + #[cfg(test)] + if TEST_ON.load(Ordering::Relaxed) { + return true; + } + if !crate::asked!("LEONIDA_UNDECLARED_TRACE") { + return false; + } + let check = super::upcheck::on(); + if !check { + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| tracing::warn!("LEONIDA_UNDECLARED_TRACE feeds on LEONIDA_UPCOPY_CHECK=1, which is off: nothing is traced")); + } + check +} + +/// The numbers of the copies watched (0: none), read where lists are +/// recorded. +static WATCHED: [AtomicU64; MOST] = [const { AtomicU64::new(0) }; MOST]; +/// Whether any is. +static ANY: AtomicBool = AtomicBool::new(false); + +fn watched(copy: u64) -> bool { + WATCHED.iter().any(|w| w.load(Ordering::Relaxed) == copy) +} + +/// What a list's recording told of watched copies, until its reset (in its +/// `Deferred`). +#[derive(Default)] +pub(crate) struct Writers { + /// Draws and dispatches bound since the watch began. + binds: u32, + /// The bind under way and its program's shaders. + now: Option<(u32, Arc<str>)>, + /// The last program's shaders (one string for a run of binds). + last: Option<Arc<str>>, + /// Declared writes into watched copies, at most [`KEPT`]; and how many + /// past them were not kept. + declared: Vec<Writer>, + unkept: u32, + /// Binds of programs that may store past what their bind declared: per + /// program's shaders and reason, how many and the first; at most + /// [`KEPT`] programs, and the binds of others past them. + past: HashMap<(Arc<str>, &'static str), (u32, u32)>, + past_more: u32, +} + +/// A declared write into a watched copy. +#[derive(Clone, PartialEq)] +struct Writer { + bind: Option<(u32, Arc<str>)>, + copy: u64, + /// Offsets in the copy. + from: usize, + to: usize, + /// What became of the declaration. + what: &'static str, + at: &'static std::panic::Location<'static>, +} + +impl Writers { + fn keep(&mut self, writer: Writer) { + if self.declared.last() == Some(&writer) { + return; + } + if self.declared.len() < KEPT { + self.declared.push(writer); + } else { + self.unkept += 1; + } + } +} + +/// A draw or dispatch is being bound in `list` with a program of `shaders` +/// (`stores`: one that can store to buffers). Until it is dropped, what is +/// declared is noted with it. +pub(crate) fn binding<'a>(list: &'a HostList, shaders: &str, stores: bool) -> Option<Binding<'a>> { + if !ANY.load(Ordering::Relaxed) || !on() { + return None; + } + let mut deferred = list.deferred(); + let w = &mut deferred.undeclared; + w.binds += 1; + if !stores { + return None; + } + let name = match w.last.take() { + Some(name) if &*name == shaders => name, + _ => Arc::from(shaders), + }; + w.last = Some(name.clone()); + w.now = Some((w.binds, name)); + Some(Binding { list }) +} + +/// A bind under way ([`binding`]). +pub(crate) struct Binding<'a> { + list: &'a HostList, +} + +impl Binding<'_> { + /// The bind went through, walking every table it binds unless `untold`; + /// `declared` says whether all its program stores goes through views + /// such a bind declares, and `why` why not. A program that may store + /// past what was declared is counted, with the reason. + pub(crate) fn bound(self, untold: bool, declared: impl FnOnce() -> bool, why: impl FnOnce() -> &'static str) { + let why = if untold { + Some("a table its bind did not go through") + } else if !declared() { + Some(why()) + } else { + None + }; + let Some(what) = why else { + return; + }; + let mut deferred = self.list.deferred(); + let w = &mut deferred.undeclared; + let Some((bind, shaders)) = w.now.clone() else { + return; + }; + let room = w.past.len() < KEPT; + match w.past.entry((shaders, what)) { + std::collections::hash_map::Entry::Occupied(mut e) => e.get_mut().0 += 1, + std::collections::hash_map::Entry::Vacant(e) if room => { + e.insert((1, bind)); + } + std::collections::hash_map::Entry::Vacant(_) => w.past_more += 1, + } + } +} + +impl Drop for Binding<'_> { + fn drop(&mut self) { + self.list.deferred().undeclared.now = None; + } +} + +/// `Shadow::gpu_writes` was asked for `len` bytes at `address` of `shadow` +/// in `list`, and did `what` with them; its caller is noted. +#[track_caller] +pub(crate) fn declares(list: &HostList, shadow: &Shadow, address: u64, len: u64, what: &'static str) { + if !ANY.load(Ordering::Relaxed) || !watched(shadow.id()) || !on() { + return; + } + let Some(from) = shadow.offset_in(address) else { + return; + }; + let to = from + len.min(shadow.left(address)); + let at = std::panic::Location::caller(); + let mut deferred = list.deferred(); + let bind = deferred.undeclared.now.clone(); + deferred.undeclared.keep(Writer { bind, copy: shadow.id(), from: from as usize, to: to as usize, what, at }); +} + +/// A copy watched. +struct Watch { + copy: Weak<Shadow>, + id: u64, + span: (u64, u64), + /// Offsets watched. + from: usize, + to: usize, + /// Its place in the snapshot and the submissions' tags, in windows. + slot: usize, + /// No snapshot of it taken yet: the next look takes one (and clears the + /// tags) only. + fresh: bool, + /// Submissions looked at, those whose lists changed it, whose sends did. + looked: u64, + by_lists: u64, + by_sends: u64, + /// The same since the last sum. + since: (u64, u64, u64), + lines: u32, + /// The last submission whose lists wrote values into the bytes at the + /// bottom of the pipe or read texels back there, and what they did. + after: Option<(u64, String)>, + /// Flagged again with no change seen: said. + said: bool, +} + +/// One copy as a submission's looks take it. +struct Looked { + copy: Arc<Shadow>, + id: u64, + from: usize, + to: usize, + slot: usize, + fresh: bool, + /// What the lists told (for a copy with lines left), and what the lists + /// of an earlier submission left on the CPU behind them. + told: Option<Told>, + earlier: Option<(u64, String)>, +} + +/// What a submission's lists told of one copy's watched bytes ([`told`]). +struct Told { + /// For a change by the lists. + lists: String, + /// The writes they declared there (offsets in the copy), and whether a + /// list kept not all its declarations. + declared: Vec<(usize, usize)>, + unkept: bool, + /// For a change ahead of them: the refreshes they asked there and the + /// title's copies done on the CPU into the bytes. + ahead: String, + /// Bottom-of-pipe writes and read-backs into the bytes, for the lines + /// of later submissions. + after: Option<String>, +} + +/// A submission's looks, from [`ahead`] until they have run. +pub(super) struct Traced { + pending: Pending, + behind: Option<ID3D12CommandList>, +} + +struct Pending { + fence: u64, + /// Its place in the answers' ring. + ring: usize, + submission: u64, + frame: u64, + looked: Vec<Looked>, + lists: Vec<Prelude>, +} + +/// A change one look found (offsets in the copy). +#[derive(Clone, Debug)] +pub(super) struct Change { + pub(super) span: (u64, u64), + pub(super) window: (usize, usize), + pub(super) submission: u64, + pub(super) frame: u64, + /// Its lists (else what went up ahead of them). + pub(super) lists: bool, + pub(super) words: u32, + pub(super) low: usize, + pub(super) high: usize, + /// A word changed: its offset, the value before and after. + pub(super) word: (usize, u32, u32), + pub(super) told: String, +} + +#[derive(Default)] +struct State { + /// Per copy flagged: in how many frames, the last. + flagged: std::collections::HashMap<u64, (u32, u64)>, + watches: Vec<Watch>, + /// The snapshot (a window per slot) and behind it the tags (the same), + /// the answers' ring and its mapping, our fence and its last value. + kept: Option<ID3D12Resource>, + answers: Option<(ID3D12Resource, usize)>, + fence: Option<ID3D12Fence>, + signalled: u64, + pending: std::collections::VecDeque<Pending>, + spare: Vec<Prelude>, + looks: u64, + lost: u64, + summed: u64, + /// The last submission [`ahead`] was asked of. + last: u64, + #[cfg(test)] + changes: Vec<Change>, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); + +/// The bytes a flag at offset `at` of a copy of `len` bytes has watched: +/// from its piece, [`WINDOW`] of them or to the copy's last whole word. +fn window(len: usize, at: usize) -> (usize, usize) { + let from = (at & !(PIECE - 1)).min(len & !(PIECE - 1)); + (from, (from + WINDOW).min(len & !3)) +} + +/// The title addresses `LEONIDA_UNDECLARED_WATCH` names (hex, by commas): +/// a copy holding one is watched from its piece without waiting for a flag, +/// so that a run where the check finds nothing there (another setting of a +/// switch) still tells what changes those bytes. +fn asked_watch() -> &'static [u64] { + static ASKED: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new(); + ASKED.get_or_init(|| parse_watch(&std::env::var("LEONIDA_UNDECLARED_WATCH").unwrap_or_default())) +} + +fn parse_watch(v: &str) -> Vec<u64> { + v.split(',').filter_map(|a| u64::from_str_radix(a.trim().trim_start_matches("0x"), 16).ok()).collect() +} + +/// A copy the at-rest look goes through: watched at once if it holds an +/// address [`asked_watch`] names. +pub(super) fn asked(shadow: &Arc<Shadow>) { + let asked = asked_watch(); + if asked.is_empty() || !on() { + return; + } + let (start, len) = shadow.span(); + let Some(&address) = asked.iter().find(|&&a| a >= start && a < start + len) else { + return; + }; + { + let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let state = state.get_or_insert_with(State::default); + if state.watches.iter().any(|w| w.id == shadow.id()) { + return; + } + // (As if flagged in a frame before: the flag below watches it.) + state.flagged.insert(shadow.id(), (1, u64::MAX)); + } + flagged(shadow, (address - start) as usize, "asked for (LEONIDA_UNDECLARED_WATCH)"); +} + +/// The up-copy check found the card side of `shadow` unlike its CPU side +/// at offset `at` (`how`: at a send, at rest). +pub(super) fn flagged(shadow: &Arc<Shadow>, at: usize, how: &'static str) { + if !on() || !shadow.carded() || shadow.card_bar().is_some() { + return; + } + let frame = crate::frame::current(); + let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let state = state.get_or_insert_with(State::default); + if let Some(w) = state.watches.iter_mut().find(|w| w.id == shadow.id()) { + if !w.said && !w.fresh && w.looked > 0 && w.by_lists + w.by_sends == 0 && (w.from..w.to).contains(&at) { + w.said = true; + tracing::warn!( + "undeclared trace: {:#x}+{:#x} is flagged again {how} at +{at:#x}, but no submission has changed +{:#x}..{:#x} on the card \ + in the {} looked at since it was watched: its CPU side moved (a copy at its place writes only that side, or a landing)", + w.span.0, + w.span.1, + w.from, + w.to, + w.looked + ); + } + return; + } + if state.flagged.len() >= 4096 && !state.flagged.contains_key(&shadow.id()) { + return; + } + let e = state.flagged.entry(shadow.id()).or_insert((0, u64::MAX)); + if e.1 != frame { + *e = (e.0 + 1, frame); + } + if e.0 < 2 || state.watches.len() >= MOST { + return; + } + let Some(slot) = (0..MOST).find(|s| !state.watches.iter().any(|w| w.slot == *s)) else { + return; + }; + let span = shadow.span(); + let (from, to) = window(span.1 as usize, at); + if to <= from { + return; + } + tracing::warn!( + "undeclared trace: watching {:#x}+{:#x} at +{from:#x}..{to:#x} (flagged {how} in {} frames)", + span.0, + span.1, + e.0 + ); + WATCHED[slot].store(shadow.id(), Ordering::Relaxed); + ANY.store(true, Ordering::Relaxed); + state.watches.push(Watch { + copy: Arc::downgrade(shadow), + id: shadow.id(), + span, + from, + to, + slot, + fresh: true, + looked: 0, + by_lists: 0, + by_sends: 0, + since: (0, 0, 0), + lines: 0, + after: None, + said: false, + }); +} + +/// The pass: words of the card's buffer from `at` against the snapshot from +/// `kept`; the snapshot takes each word that differs, and the answer at +/// `answer` counts them, keeps the first found (its offset from `at`, the +/// snapshot's value, the card's) and the lowest and highest offset. Behind +/// the snapshot, from `tags`, a word per word watched: the submission whose +/// lists last changed it. `mode` 1 (behind the lists) tags each word that +/// differs with `tag`; 0 (ahead of them) counts apart those of the words +/// that differ that are tagged, keeps the lowest and highest tag and one +/// such word, and clears their tags; 2 (a first look) clears every tag. +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=7, b0), SRV(t0), UAV(u0), UAV(u1)" +cbuffer Look : register(b0) { uint at; uint words; uint kept; uint answer; uint tags; uint mode; uint tag; }; +ByteAddressBuffer card : register(t0); +RWByteAddressBuffer snapshot : register(u0); +RWByteAddressBuffer found : register(u1); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= words) return; + uint k = id.x * 4u, n, m; + if (mode == 2u) snapshot.Store(tags + k, 0u); + uint c = card.Load(at + k), s = snapshot.Load(kept + k); + if (c == s) return; + snapshot.Store(kept + k, c); + found.InterlockedAdd(answer, 1u, n); + found.InterlockedMin(answer + 16u, k); + found.InterlockedMax(answer + 20u, k); + if (n == 0u) found.Store3(answer + 4u, uint3(k, s, c)); + if (mode == 1u) { + snapshot.Store(tags + k, tag); + } else if (mode == 0u) { + uint t = snapshot.Load(tags + k); + if (t != 0u) { + snapshot.Store(tags + k, 0u); + found.InterlockedAdd(answer + 24u, 1u, m); + found.InterlockedMin(answer + 28u, t); + found.InterlockedMax(answer + 32u, t); + if (m == 0u) found.Store3(answer + 36u, uint3(k, s, c)); + } + } +} +"#; + +struct Pass { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +fn pass(host: &Host) -> Option<&'static Pass> { + static PASS: OnceLock<Option<Pass>> = OnceLock::new(); + PASS.get_or_init(|| { + let code = compile(SOURCE, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?; + // SAFETY: the code lives through the calls; the root signature is + // inside it. + unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?; + let pso: ID3D12PipelineState = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }) + .ok()?; + Some(Pass { root, pso }) + } + }) + .as_ref() +} + +impl State { + /// The snapshot and tags, the answers and the fence, made the first + /// time. + fn made(&mut self, host: &Host) -> Option<()> { + if self.kept.is_none() { + let kept = host.uav_buffer((2 * MOST * WINDOW) as u64)?; + name(&kept, || "undeclared trace: the watched bytes as the card held them, and whose lists changed them".into()); + self.kept = Some(kept); + } + if self.answers.is_none() { + let (answers, data) = host.shared_buffer((RING * 2 * MOST * ANSWER) as u64)?; + self.answers = Some((answers, data as usize)); + } + if self.fence.is_none() { + // SAFETY: a plain fence on our device. + self.fence = Some(unsafe { host.device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) }.ok()?); + } + Some(()) + } + + /// The answers of look `look` (0 ahead, 1 behind) of ring place `ring`. + fn answers(&self, ring: usize, look: usize) -> *mut [u32; ANSWER / 4] { + let data = self.answers.as_ref().map_or(0, |a| a.1); + (data + (ring * 2 + look) * MOST * ANSWER) as *mut [u32; ANSWER / 4] + } + + /// Records one look over `looked` into `list`, its answers at ring place + /// `ring`, look `look`, for submission `submission`. + fn record(&self, pass: &Pass, list: &ID3D12GraphicsCommandList, looked: &[Looked], ring: usize, look: usize, submission: u64) { + let (Some(kept), Some((answers, _))) = (&self.kept, &self.answers) else { + return; + }; + let first = (ring * 2 + look) * MOST * ANSWER; + // (A tag is never 0, which is none.) + let tag = (submission as u32).max(1); + // SAFETY: an open list whose compute state this sets whole; live + // buffers (`looked` holds the copies), the ranges in them; the + // answers' place is ours until they are read. + unsafe { + let to = self.answers(ring, look); + for i in 0..MOST { + to.add(i).write(UNANSWERED); + } + list.SetComputeRootSignature(&pass.root); + list.SetPipelineState(&pass.pso); + list.SetComputeRootUnorderedAccessView(2, kept.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, answers.GetGPUVirtualAddress()); + for (i, l) in looked.iter().enumerate() { + let words = (l.to - l.from) / 4; + let mode = match (look, l.fresh) { + (1, _) => 1, + (_, true) => 2, + _ => 0, + }; + list.SetComputeRootShaderResourceView(1, l.copy.buffer.GetGPUVirtualAddress()); + let constants = [ + l.from as u32, + words as u32, + (l.slot * WINDOW) as u32, + (first + i * ANSWER) as u32, + ((MOST + l.slot) * WINDOW) as u32, + mode, + tag, + ]; + list.SetComputeRoot32BitConstants(0, constants.len() as u32, constants.as_ptr().cast(), 0); + list.Dispatch(words.div_ceil(64) as u32, 1, 1); + } + } + } + + /// A list of ours, open. + fn list(&mut self, host: &Host) -> Option<Prelude> { + let (allocator, list) = self.spare.pop().or_else(|| host.make_prelude())?; + // SAFETY: its last run is over (it came back with its answers). + unsafe { + allocator.Reset().ok()?; + list.Reset(&allocator, None).ok()?; + } + Some((allocator, list)) + } + + /// Reads the answers of the submissions the card is done with. + fn read(&mut self) { + let Some(fence) = &self.fence else { + return; + }; + // SAFETY: a plain query. + let done = unsafe { fence.GetCompletedValue() }; + // (A device removed answers all ones.) + if done == u64::MAX { + return; + } + while self.pending.front().is_some_and(|p| p.fence <= done) { + let Some(p) = self.pending.pop_front() else { + break; + }; + for look in 0..2 { + let answers = self.answers(p.ring, look); + for (i, l) in p.looked.iter().enumerate() { + if look == 0 && l.fresh { + continue; + } + // SAFETY: the answers' mapping; the card wrote them. + let answer = unsafe { answers.add(i).read_volatile() }; + self.counted(&p, l, look == 1, answer); + } + } + self.spare.extend(p.lists); + } + self.sum(); + } + + /// One look's answer for one copy. + fn counted(&mut self, p: &Pending, l: &Looked, lists: bool, answer: [u32; ANSWER / 4]) { + let [words, k, was, now, low, high, over, first, last, over_k, over_was, over_now] = answer; + let Some(w) = self.watches.iter_mut().find(|w| w.id == l.id && w.slot == l.slot) else { + return; + }; + if lists { + w.looked += 1; + w.since.0 += 1; + } + if words == 0 { + return; + } + let (low, high) = (l.from + low as usize, l.from + high as usize + 4); + let told = match &l.told { + None => String::new(), + Some(told) if lists => said_lists(told, low, high), + Some(told) => { + let over = (over > 0).then_some((over, (first, last), (l.from + over_k as usize, over_was, over_now))); + said_ahead(words, over, &told.ahead, l.earlier.as_ref()) + } + }; + let change = Change { + span: w.span, + window: (l.from, l.to), + submission: p.submission, + frame: p.frame, + lists, + words, + low, + high, + word: (l.from + k as usize, was, now), + told, + }; + if lists { + w.by_lists += 1; + w.since.1 += 1; + } else { + w.by_sends += 1; + w.since.2 += 1; + } + if w.lines < LINES { + w.lines += 1; + tracing::warn!("{}", line(&change)); + } + #[cfg(test)] + self.changes.push(change); + } + + /// Every few seconds, past the lines: the sums. + fn sum(&mut self) { + let now = now_ms(); + if now < self.summed + 4000 { + return; + } + self.summed = now; + for w in &mut self.watches { + let (looked, lists, sends) = std::mem::take(&mut w.since); + if w.lines >= LINES && looked > 0 { + tracing::info!( + "undeclared trace: {:#x}+{:#x} at +{:#x}..{:#x}: {looked} submissions looked at since the last sum, {lists} changed it by their \ + lists, {sends} ahead of them; {} looks lost in all (more than {RING} submissions in the air)", + w.span.0, + w.span.1, + w.from, + w.to, + self.lost + ); + } + } + } +} + +/// What a change by the lists over `low..high` is said with. +fn said_lists(told: &Told, low: usize, high: usize) -> String { + let under = told.declared.iter().any(|&(a, b)| a < high && low < b); + let lies = if under { + "a write it declared" + } else if told.unkept { + "no write kept of those it declared (a list declared more into watched copies than it keeps)" + } else { + "no write it declared" + }; + format!("{}; what changed lies in {lies}", told.lists) +} + +/// What a change of `words` words ahead of the lists is said with: how many +/// of them the lists of earlier submissions had changed, of which (the +/// first and last) and one such word (its offset, the lists' value, the +/// value now), then `ahead` and what an `earlier` submission's lists left +/// on the CPU. +fn said_ahead(words: u32, over: Option<(u32, (u32, u32), (usize, u32, u32))>, ahead: &str, earlier: Option<&(u64, String)>) -> String { + let over = match over { + Some((n, (first, last), (at, was, now))) => { + let by = if first == last { + format!("submission {first}") + } else { + format!("submissions {first} to {last}") + }; + format!("{n} of the {words} words were last changed by the lists of {by} (+{at:#x}: {was:#x} -> {now:#x}{})", shape(was, now)) + } + None => "none of them a word the lists of a submission looked at had changed".into(), + }; + let earlier = earlier.map_or(String::new(), |(n, what)| format!("; the lists of submission {n} (the last to) {what}")); + format!("{over}; {ahead}{earlier}") +} + +/// What one value became, where it says something. +fn shape(was: u32, now: u32) -> &'static str { + if was ^ now == 0x8000_0000 { + ", the sign flipped" + } else if was == 0 { + ", from zero" + } else if now == 0 { + ", to zero" + } else { + "" + } +} + +/// The line of a change. +fn line(c: &Change) -> String { + let (at, was, now) = c.word; + let what = if c.lists { + "its lists changed" + } else { + "what went up ahead of its lists (its sends, or our work since the last submission) changed" + }; + format!( + "undeclared trace: {:#x}+{:#x} at +{:#x}..{:#x}: submission {} (frame {}): {what} {} words in +{:#x}..{:#x} (+{at:#x}: {was:#x} -> \ + {now:#x}{}); {}", + c.span.0, + c.span.1, + c.window.0, + c.window.1, + c.submission, + c.frame, + c.words, + c.low, + c.high, + shape(was, now), + c.told + ) +} + +/// Things said, each once with how often, in the order first said. +#[derive(Default)] +struct Said { + all: Vec<(String, u32)>, + at: HashMap<String, usize>, +} + +impl Said { + fn add(&mut self, what: String) { + match self.at.get(&what) { + Some(&i) => self.all[i].1 += 1, + None => { + self.at.insert(what.clone(), self.all.len()); + self.all.push((what, 1)); + } + } + } + + /// At most [`TOLD`] of them, then how many more (`more` names them). + fn said(&self, more: &str) -> Vec<String> { + let mut said: Vec<String> = + self.all.iter().take(TOLD).map(|(what, n)| if *n > 1 { format!("{what} ({n} times)") } else { what.clone() }).collect(); + if self.all.len() > TOLD { + said.push(format!("{} {more} more", self.all.len() - TOLD)); + } + said + } +} + +/// What `runs` told of the watched bytes of each of `copies` (the copy, the +/// offsets watched), in one walk; `picked` from `crate::picked::declare`. +fn told(runs: &[&HostList], copies: &[(&Shadow, usize, usize)], picked: &crate::picked::Ranges) -> Vec<Told> { + struct Of { + id: u64, + start: usize, + from: usize, + to: usize, + declared: Said, + ranges: Vec<(usize, usize)>, + refreshed: u32, + copies: Said, + after: Said, + picked: Said, + } + let mut of: Vec<Of> = copies + .iter() + .map(|&(copy, from, to)| Of { + id: copy.id(), + start: copy.span().0 as usize, + from, + to, + declared: Said::default(), + ranges: Vec::new(), + refreshed: 0, + copies: Said::default(), + after: Said::default(), + picked: Said::default(), + }) + .collect(); + // The programs that store past their views: per list, shaders and why, + // how many binds and the first; and binds of programs not counted. + let mut past: Vec<(usize, Arc<str>, &'static str, u32, u32)> = Vec::new(); + let (mut past_more, mut unkept) = (0, false); + for (i, list) in runs.iter().enumerate() { + let deferred = list.deferred(); + let w = &deferred.undeclared; + unkept |= w.unkept > 0; + past_more += w.past_more; + past.extend(w.past.iter().map(|((shaders, why), &(n, first))| (i, shaders.clone(), *why, n, first))); + for d in &w.declared { + for o in of.iter_mut().filter(|o| o.id == d.copy && d.from < o.to && o.from < d.to) { + let bind = d.bind.as_ref().map_or(String::from("outside a bind"), |(n, shaders)| format!("bind {n} of {shaders}")); + o.declared.add(format!("list {i} {bind} declared +{:#x}..{:#x} at {}:{}: {}", d.from, d.to, d.at.file(), d.at.line(), d.what)); + o.ranges.push((d.from, d.to)); + } + } + let meets = |o: &Of, at: usize, len: usize| at < o.start + o.to && o.start + o.from < at + len; + for step in &deferred.copies { + match step { + &Step::Copy(dst, src, len) => { + for o in of.iter_mut().filter(|o| meets(o, dst, len)) { + o.copies.add(format!("list {i}: a title copy done on the CPU from {src:#x}")); + } + } + Step::Refresh(shadow, at, len) => { + for o in of.iter_mut().filter(|o| o.id == shadow.id() && meets(o, *at, *len)) { + o.refreshed += 1; + } + } + _ => {} + } + } + for &(dst, _, len) in &deferred.writes { + for o in of.iter_mut().filter(|o| meets(o, dst, len)) { + o.after.add("wrote values there at the bottom of the pipe".into()); + } + } + for (_, dst, [_, rows, pitch]) in &deferred.backs { + for o in of.iter_mut().filter(|o| meets(o, *dst, rows * pitch)) { + o.after.add("read texels back there".into()); + } + } + } + for (ranges, how) in [(&picked.written, "declared for it, found written"), (&picked.looked, "looked at in turn")] { + for (shadow, at, len) in ranges { + for o in of.iter_mut().filter(|o| o.id == shadow.id() && *at < o.start + o.to && o.start + o.from < at + len) { + o.picked.add(format!("views picked from the heap: {how}")); + if std::ptr::eq(ranges, &picked.written) { + let at = at.saturating_sub(o.start); + o.ranges.push((at, at + len)); + } + } + } + } + // Most binds first. + past.sort_by(|a, b| b.3.cmp(&a.3).then(a.0.cmp(&b.0)).then(a.4.cmp(&b.4))); + let mut stores: Vec<String> = past + .iter() + .take(TOLD) + .map(|(i, shaders, why, n, first)| { + if *n > 1 { + format!("list {i} binds {first} and {} more of {shaders} store past what their bind declared ({why})", n - 1) + } else { + format!("list {i} bind {first} of {shaders} stores past what its bind declared ({why})") + } + }) + .collect(); + if past.len() > TOLD { + stores.push(format!("{} programs more store past what their bind declared", past.len() - TOLD)); + } + if past_more > 0 { + stores.push(format!("{past_more} binds of programs not counted store past what their bind declared")); + } + of.into_iter() + .map(|o| { + let mut said = o.declared.said("declarations"); + said.extend(o.picked.said("picked")); + said.extend(stores.iter().cloned()); + let lists = if said.is_empty() { + "nothing in it was told of these bytes (no write declared there, no program storing past its views)".into() + } else { + format!("in it: {}", said.join("; ")) + }; + let mut ahead = vec![format!("its lists ask {} refreshes there", o.refreshed)]; + ahead.extend(o.copies.said("title copies")); + let after = (!o.after.all.is_empty()).then(|| o.after.said("").join(", ")); + Told { lists, declared: o.ranges, unkept, ahead: ahead.join("; "), after } + }) + .collect() +} + +/// Submission `submission` of `runs` has sent its bytes up and its lists +/// are next: the look ahead of them goes to the queue now, and the one +/// behind them is made, for [`behind`]. `None` if nothing is watched. +pub(super) fn ahead(host: &Host, runs: &[&HostList], submission: u64, picked: &crate::picked::Ranges) -> Option<Traced> { + if !on() || !ANY.load(Ordering::Relaxed) { + return None; + } + let pass = pass(host)?; + let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let state = state.as_mut()?; + state.read(); + // A submission between the last asked and this one was not looked at + // (the switch was off, or nothing was watched): what it changed is not + // this one's, so the snapshots are taken anew. + if submission != state.last + 1 { + state.watches.iter_mut().for_each(|w| w.fresh = true); + } + state.last = submission; + // Copies gone are watched no more. + state.watches.retain(|w| { + let alive = w.copy.strong_count() > 0; + if !alive { + WATCHED[w.slot].store(0, Ordering::Relaxed); + } + alive + }); + if state.watches.is_empty() { + ANY.store(false, Ordering::Relaxed); + return None; + } + if state.pending.len() >= RING { + state.lost += 1; + state.watches.iter_mut().for_each(|w| w.fresh = true); + return None; + } + if state.made(host).is_none() { + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| tracing::warn!("undeclared trace: no room for the snapshot of the watched bytes; nothing is traced")); + return None; + } + let live: Vec<(Arc<Shadow>, usize)> = + state.watches.iter().enumerate().filter_map(|(i, w)| Some((w.copy.upgrade()?, i))).collect(); + // What the lists told, of the copies with lines left only. + let telling: Vec<(&Shadow, usize, usize)> = live + .iter() + .filter(|(_, i)| state.watches[*i].lines < LINES) + .map(|(copy, i)| (&**copy, state.watches[*i].from, state.watches[*i].to)) + .collect(); + let mut told = told(runs, &telling, picked).into_iter(); + let mut looked = Vec::new(); + for (copy, i) in live { + let w = &mut state.watches[i]; + let (told, earlier) = if w.lines < LINES { + let told = told.next(); + let earlier = w.after.clone(); + if let Some(after) = told.as_ref().and_then(|t| t.after.clone()) { + w.after = Some((submission, after)); + } + (told, earlier) + } else { + (None, None) + }; + looked.push(Looked { copy, id: w.id, from: w.from, to: w.to, slot: w.slot, fresh: w.fresh, told, earlier }); + w.fresh = false; + } + let ring = (state.looks % RING as u64) as usize; + state.looks += 1; + // Both recorded before either goes: a list that is not sent goes back + // to the spares, none is let go of on the card. + let mut lists = Vec::new(); + let mut closed = Vec::new(); + for look in 0..2 { + let Some((allocator, list)) = state.list(host) else { + break; + }; + state.record(pass, &list, &looked, ring, look, submission); + // SAFETY: an open list of ours. + let made = unsafe { list.Close() }.ok().and_then(|()| list.cast::<ID3D12CommandList>().ok()); + lists.push((allocator, list)); + match made { + Some(made) => closed.push(made), + None => break, + } + } + let [ahead, behind] = &closed[..] else { + state.watches.iter_mut().for_each(|w| w.fresh = true); + state.spare.extend(lists); + return None; + }; + // A call of its own: the copies' buffers begin it in the common state, + // and are left in it for the lists. + // SAFETY: a closed list; the queue is the host's. + unsafe { host.queue.ExecuteCommandLists(&[Some(ahead.clone())]) }; + Some(Traced { + pending: Pending { fence: 0, ring, submission, frame: crate::frame::current(), looked, lists }, + behind: Some(behind.clone()), + }) +} + +/// The look behind the lists goes first in the compare's part of `lists` +/// (a call of its own, or after the barrier list that joins it to the +/// last lists': a buffer a list left in a write state is not read so in the +/// call it was left in); the compare's place after it. +pub(super) fn behind(traced: Option<&Traced>, lists: &mut Vec<Option<ID3D12CommandList>>, compare_at: Option<usize>) -> Option<usize> { + let Some(behind) = traced.and_then(|t| t.behind.clone()) else { + return compare_at; + }; + let at = compare_at.unwrap_or(lists.len()); + lists.insert(at, Some(behind)); + Some(at) +} + +/// The submission is on the queue, its looks with it: our fence follows. +pub(super) fn sent(host: &Host, traced: Option<Traced>) { + let Some(mut traced) = traced else { + return; + }; + let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let Some(state) = state.as_mut() else { + return; + }; + let Some(fence) = state.fence.clone() else { + return; + }; + state.signalled += 1; + // SAFETY: our fence, on the host's queue. + if unsafe { host.queue.Signal(&fence, state.signalled) }.is_err() { + state.watches.iter_mut().for_each(|w| w.fresh = true); + return; + } + traced.pending.fence = state.signalled; + state.pending.push_back(traced.pending); + state.read(); +} + +#[cfg(test)] +mod tests { + use super::super::landsame::card_tests::{turn, writer}; + use super::*; + + const N: u32 = 16; + + /// This thread traces (whatever the switches say) until it is dropped; + /// then nothing is watched. + struct On; + + impl On { + fn new() -> On { + TEST_ON.store(true, Ordering::Relaxed); + On + } + } + + impl Drop for On { + fn drop(&mut self) { + TEST_ON.store(false, Ordering::Relaxed); + *STATE.lock().unwrap_or_else(|e| e.into_inner()) = None; + WATCHED.iter().for_each(|w| w.store(0, Ordering::Relaxed)); + ANY.store(false, Ordering::Relaxed); + } + } + + #[test] + fn the_addresses_asked_for_are_read_with_or_without_0x() { + assert_eq!(parse_watch("0xd624f2660, db5047000,,zz"), vec![0xd624f2660, 0xdb5047000]); + assert!(parse_watch("").is_empty()); + } + + #[test] + fn the_window_is_the_flagged_piece_and_what_follows_in_the_copy() { + assert_eq!(window(4 * PIECE, 2 * PIECE + 0x40), (2 * PIECE, 4 * PIECE)); + assert_eq!(window(16 * PIECE, 0x10), (0, WINDOW)); + // (A ring's slot of 0x117500 bytes, flagged at +0x1524 and near + // its end.) + assert_eq!(window(0x11_7500, 0x1524), (0, WINDOW)); + assert_eq!(window(0x11_7500, 0x11_7400), (0x11_0000, 0x11_7500)); + // Past the copy's last whole piece: the piece the copy ends in. + assert_eq!(window(0x11_7502, 0x20_0000), (0x11_0000, 0x11_7500)); + } + + #[test] + fn a_change_says_its_submission_its_span_and_how_a_value_moved() { + let c = Change { + span: (0xdb50_47000, 0x11_7500), + window: (0, 0x4_0000), + submission: 7, + frame: 2300, + lists: true, + words: 321, + low: 0x1524, + high: 0x1a28, + word: (0x1524, 0x3f80_0016, 0xbf80_0016), + told: "in it: list 0 bind 2 of [x] stores past what its bind declared (views picked from the heap)".into(), + }; + let said = line(&c); + assert!(said.contains("0xdb5047000+0x117500 at +0x0..0x40000: submission 7 (frame 2300): its lists changed 321 words"), "{said}"); + assert!(said.contains("+0x1524..0x1a28 (+0x1524: 0x3f800016 -> 0xbf800016, the sign flipped)"), "{said}"); + assert!(said.ends_with("(views picked from the heap)"), "{said}"); + assert_eq!(shape(0, 0x8000_0000), ", the sign flipped"); + assert_eq!(shape(0, 0x3c00_3c00), ", from zero"); + assert_eq!(shape(0x3f80_0016, 0x3f80_0000), ""); + let over = Some((3, (5, 5), (0x1528, 0x3f80_0000, 0))); + let said = said_ahead(32, over, "its lists ask 2 refreshes there", Some(&(4, "wrote values there at the bottom of the pipe".into()))); + assert_eq!( + said, + "3 of the 32 words were last changed by the lists of submission 5 (+0x1528: 0x3f800000 -> 0x0, to zero); its lists ask 2 \ + refreshes there; the lists of submission 4 (the last to) wrote values there at the bottom of the pipe" + ); + let said = said_ahead(32, Some((3, (5, 9), (0x1528, 1, 2))), "x", None); + assert!(said.starts_with("3 of the 32 words were last changed by the lists of submissions 5 to 9"), "{said}"); + assert_eq!(said_ahead(32, None, "x", None), "none of them a word the lists of a submission looked at had changed; x"); + } + + /// What the card side holds at `at`, `n` words; nothing in the air. + fn card(host: &Host, shadow: &Shadow, at: usize, n: usize) -> Vec<u32> { + let (held, data) = host.shared_buffer((n * 4) as u64).unwrap(); + let (allocator, list) = host.make_prelude().unwrap(); + // SAFETY: a fresh list of ours; live buffers, the ranges in them; the + // mapping holds `n` words once the card has run the copy. + unsafe { + allocator.Reset().unwrap(); + list.Reset(&allocator, None).unwrap(); + list.CopyBufferRegion(&held, 0, &shadow.buffer, at as u64, (n * 4) as u64); + list.Close().unwrap(); + host.queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + } + wait(host); + // SAFETY: the mapping, written. + unsafe { std::slice::from_raw_parts(data.cast::<u32>(), n) }.to_vec() + } + + /// Waits for everything on the host's queue, our fence's last value + /// with it, and reads the answers. + fn wait(host: &Host) { + // SAFETY: plain objects of ours, waited for before they go. + unsafe { + let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + host.queue.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, event).unwrap(); + WaitForSingleObject(event, INFINITE); + let _ = windows::Win32::Foundation::CloseHandle(event); + } + if let Some(state) = STATE.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + state.read(); + } + } + + /// `list` as the title's, through `Host::submit` sent ahead, and waited + /// for: its number. + fn submit(host: &'static Host, list: &HostList) -> u64 { + list.close(); + let (submitted, sent) = host.submit(&[list], &[], true).expect("a submission sent ahead"); + drop(submitted); + wait(host); + let number = sent.number; + if let Some(plan) = sent.card { + host.card_done(plan); + } + if let Some(own) = sent.own { + own.landed(); + } + number + } + + /// The changes found so far, taken. + fn changes() -> Vec<Change> { + STATE.lock().unwrap_or_else(|e| e.into_inner()).as_mut().map_or_else(Vec::new, |s| std::mem::take(&mut s.changes)) + } + + /// A dispatch stores into a copy in the card's memory through a view its + /// bind did not declare (the bind of a program that picks its views, as + /// `crate::draw` notes it), beside a bind that declares a write + /// elsewhere in the copy and one that declares a write in the watched + /// bytes. Once the check has flagged the copy in two frames, the look + /// behind the submission's lists finds the words, and the line names + /// that submission, the bind that picks its views and the declaration + /// in the window (by the line that made it and what became of it), not + /// the one outside; the next submission's sends put the CPU side's bytes + /// back over the words, and the look ahead of its lists says so. + #[test] + fn a_store_nobody_declared_is_traced_to_its_submission_and_bind() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the trace was not tried"); + return; + }; + let _turn = turn(); + let Some((room, start, shadow)) = four_pieces() else { + eprintln!("no copies in the card's memory; the trace was not tried"); + return; + }; + let _on = On::new(); + // Bytes into the copy: a declared write outside the window (piece + // 1), the store nobody declared (piece 2, where the window begins), + // a declared write in the window that stores nothing (piece 3). + const A: usize = PIECE + 0x100; + const B: usize = 2 * PIECE + 0x40; + const C: usize = 3 * PIECE + 0x80; + flagged(&shadow, B, "at rest"); + assert!(!watched(shadow.id()), "one frame flagged is not enough"); + crate::frame::test_advance(); + flagged(&shadow, B, "at rest"); + assert!(watched(shadow.id()), "flagged in two frames"); + // The first look takes the snapshot only. + let first = host.new_list().unwrap(); + submit(host, &first); + assert!(changes().is_empty(), "nothing changed yet"); + let (root, pso) = writer(&host.device); + let list = host.new_list().unwrap(); + let all_declared = || panic!("asked only of a program whose stores are not all declared"); + { + let bind = binding(&list, "[declares elsewhere]", true).expect("a bind noted"); + shadow.gpu_writes(&list, (start + A) as u64, 64); + bind.bound(false, || true, all_declared); + } + assert!(binding(&list, "[stores nothing]", false).is_none(), "counted, not noted"); + binding(&list, "[picks its views]", true).expect("a bind noted").bound(false, || false, || "views picked from the heap"); + { + let bind = binding(&list, "[declares in the window]", true).expect("a bind noted"); + shadow.gpu_writes(&list, (start + C) as u64, 64); + bind.bound(false, || true, all_declared); + } + binding(&list, "[binds a table it did not walk]", true).expect("a bind noted").bound(true, || true, all_declared); + let declared = list.deferred().undeclared.declared.iter().filter(|w| w.copy == shadow.id()).count(); + assert_eq!(declared, 2, "the declared writes are noted"); + // SAFETY: an open list; the writer's root signature; the words lie in + // the card side. + unsafe { + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + let constants = [B as u32, N, 0x1234_0001]; + list.list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.list.Dispatch(1, 1, 1); + } + let number = submit(host, &list); + assert_eq!(card(host, &shadow, B, 1), [0x1234_0001], "the store is on the card"); + let found = changes(); + eprintln!("{}", found.iter().map(line).collect::<Vec<_>>().join("\n")); + let [c] = &found[..] else { panic!("one change: {found:?}") }; + assert_eq!((c.submission, c.lists, c.words, c.low, c.high), (number, true, N, B, B + 4 * N as usize)); + assert_eq!((c.word.0 - B) % 4, 0, "a word of the store"); + assert!(c.told.contains("bind 3 of [picks its views] stores past what its bind declared (views picked from the heap)"), "{}", c.told); + let there = format!("bind 4 of [declares in the window] declared +{C:#x}..{:#x} at {}:", C + 64, file!()); + assert!(c.told.contains(&there) && c.told.contains(": declared"), "the declaration in the window, by its line: {}", c.told); + let untold = "bind 5 of [binds a table it did not walk] stores past what its bind declared (a table its bind did not go through)"; + assert!(c.told.contains(untold), "{}", c.told); + assert!(!c.told.contains("[declares elsewhere]"), "a declaration outside the window is not named: {}", c.told); + assert!(c.told.ends_with("what changed lies in no write it declared"), "{}", c.told); + // The title's bytes there (zeros) go up again: the look ahead of the + // next submission's lists finds the store undone. + shadow.refresh_for_test(start + B, start + B + 64); + let next = host.new_list().unwrap(); + let after = submit(host, &next); + assert_eq!(card(host, &shadow, B, 1), [0], "the send put the CPU side's zeros back"); + let found = changes(); + eprintln!("{}", found.iter().map(line).collect::<Vec<_>>().join("\n")); + let [c] = &found[..] else { panic!("one change: {found:?}") }; + assert_eq!((c.submission, c.lists, c.words, c.low), (after, false, N, B)); + let over = format!("{N} of the {N} words were last changed by the lists of submission {number} (+"); + assert!(c.told.starts_with(&over), "{}", c.told); + drop((root, pso, room)); + } + + /// [`N`] words from `value` on at `at` of the card side, stored by a + /// dispatch recorded in `list` (a title list: nothing declared). + fn stores(list: &HostList, shadow: &Shadow, (root, pso): &(ID3D12RootSignature, ID3D12PipelineState), at: usize, value: u32) { + // SAFETY: an open list; the writer's root signature; the words lie in + // the card side. + unsafe { + list.list.SetComputeRootSignature(root); + list.list.SetPipelineState(pso); + list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + let constants = [at as u32, N, value]; + list.list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.list.Dispatch(1, 1, 1); + } + } + + /// `shadow` flagged at `at` in two frames, and its first look (which + /// takes the snapshot only) behind it. + fn watch(host: &'static Host, shadow: &Arc<Shadow>, at: usize) { + flagged(shadow, at, "at rest"); + crate::frame::test_advance(); + flagged(shadow, at, "at rest"); + assert!(watched(shadow.id()), "flagged in two frames"); + submit(host, &host.new_list().unwrap()); + assert!(changes().is_empty(), "nothing changed yet"); + } + + /// More binds than a line names, and than a list could keep one by one, + /// of programs that store past the views their bind declared, come in a + /// list ahead of a bind that declares a write in the watched bytes, and + /// the dispatch stores there: the line names the declaration (by its + /// line, and what became of it), says that what changed lies in it, and + /// counts the other programs' binds. + #[test] + fn binds_past_their_views_hide_no_declaration_in_the_window() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the trace was not tried"); + return; + }; + let _turn = turn(); + let Some((room, start, shadow)) = four_pieces() else { + eprintln!("no copies in the card's memory; the trace was not tried"); + return; + }; + let _on = On::new(); + const C: usize = 3 * PIECE + 0x80; + const PAST: u32 = 1100; + watch(host, &shadow, C); + let writer = writer(&host.device); + let list = host.new_list().unwrap(); + for i in 0..PAST { + let bind = binding(&list, &format!("[picks {}]", i % 10), true).expect("a bind noted"); + bind.bound(false, || false, || "views picked from the heap"); + } + { + let bind = binding(&list, "[declares in the window]", true).expect("a bind noted"); + shadow.gpu_writes(&list, (start + C) as u64, 64); + bind.bound(false, || true, || panic!("all declared")); + } + stores(&list, &shadow, &writer, C, 0x1234_0001); + let number = submit(host, &list); + let found = changes(); + eprintln!("{}", found.iter().map(line).collect::<Vec<_>>().join("\n")); + let [c] = &found[..] else { panic!("one change: {found:?}") }; + assert_eq!((c.submission, c.lists, c.words, c.low, c.high), (number, true, N, C, C + 4 * N as usize)); + let there = format!("bind {} of [declares in the window] declared +{C:#x}..{:#x} at {}:", PAST + 1, C + 64, file!()); + assert!(c.told.starts_with(&format!("in it: list 0 {there}")) && c.told.contains(": declared"), "named first: {}", c.told); + assert!(c.told.ends_with("what changed lies in a write it declared"), "{}", c.told); + let most = format!("list 0 binds 1 and {} more of [picks 0] store past what their bind declared", PAST / 10 - 1); + assert!(c.told.contains(&most), "counted per program: {}", c.told); + assert!(c.told.contains("2 programs more store past what their bind declared"), "{}", c.told); + drop((writer, room)); + } + + /// The lists of a submission store words at two places in the watched + /// bytes; the next submission's sends change words between them only. + /// The look ahead of its lists says that none of the words it found + /// changed were the lists' (a span over both stores would hold them). + #[test] + fn a_send_beside_words_the_lists_changed_is_not_said_over_them() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the trace was not tried"); + return; + }; + let _turn = turn(); + let Some((mut room, start, shadow)) = four_pieces() else { + eprintln!("no copies in the card's memory; the trace was not tried"); + return; + }; + let _on = On::new(); + const B: usize = 2 * PIECE + 0x40; + const M: usize = B + 0x100; + const D: usize = B + 0x200; + watch(host, &shadow, B); + let writer = writer(&host.device); + let list = host.new_list().unwrap(); + stores(&list, &shadow, &writer, B, 0x1234_0001); + stores(&list, &shadow, &writer, D, 0x5678_0001); + let number = submit(host, &list); + let found = changes(); + let [c] = &found[..] else { panic!("one change: {found:?}") }; + assert_eq!((c.submission, c.lists, c.words, c.low, c.high), (number, true, 2 * N, B, D + 4 * N as usize)); + // The title writes between the stores; its bytes go up. + let at = start - room.as_ptr() as usize + M; + room[at..at + 64].fill(0x11); + shadow.refresh_for_test(start + M, start + M + 64); + let after = submit(host, &host.new_list().unwrap()); + assert_eq!(card(host, &shadow, M, 1), [0x1111_1111], "the send is on the card"); + let found = changes(); + eprintln!("{}", found.iter().map(line).collect::<Vec<_>>().join("\n")); + let [c] = &found[..] else { panic!("one change: {found:?}") }; + assert_eq!((c.submission, c.lists, c.words, c.low, c.high), (after, false, N, M, M + 64)); + assert!(c.told.starts_with("none of them a word the lists of a submission looked at had changed"), "{}", c.told); + assert!(!c.told.contains(&format!("submission {number}")), "{}", c.told); + drop((writer, room)); + } + + /// A submission is not looked at (the switch off while it runs) and its + /// lists store into the watched bytes; the next one, looked at again, + /// changes nothing there. What the first did is laid on no submission: + /// the snapshot is taken anew, and the next change is found as before. + #[test] + fn a_submission_not_looked_at_lays_its_change_on_no_other() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the trace was not tried"); + return; + }; + let _turn = turn(); + let Some((room, _, shadow)) = four_pieces() else { + eprintln!("no copies in the card's memory; the trace was not tried"); + return; + }; + let on = On::new(); + const B: usize = 2 * PIECE + 0x40; + watch(host, &shadow, B); + let writer = writer(&host.device); + TEST_ON.store(false, Ordering::Relaxed); + let list = host.new_list().unwrap(); + stores(&list, &shadow, &writer, B, 0x1234_0001); + submit(host, &list); + TEST_ON.store(true, Ordering::Relaxed); + assert_eq!(card(host, &shadow, B, 1), [0x1234_0001], "the store is on the card"); + submit(host, &host.new_list().unwrap()); + let found = changes(); + assert!(found.is_empty(), "laid on a submission that did not make it: {}", found.iter().map(line).collect::<Vec<_>>().join("\n")); + let list = host.new_list().unwrap(); + stores(&list, &shadow, &writer, B, 0x5678_0001); + let number = submit(host, &list); + let found = changes(); + let [c] = &found[..] else { panic!("one change: {found:?}") }; + assert_eq!((c.submission, c.lists, c.words, c.low), (number, true, N, B)); + drop((writer, room, on)); + } + + /// The title's copies done on the CPU into the watched bytes go up with + /// the submission's own sends: they are said with a change ahead of its + /// lists, not with one by them. + #[test] + fn title_copies_into_the_bytes_go_with_the_sends_not_the_lists() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the trace was not tried"); + return; + }; + let _turn = turn(); + let Some((room, start, shadow)) = four_pieces() else { + eprintln!("no copies in the card's memory; the trace was not tried"); + return; + }; + let source = [0u8; 64]; + let list = host.new_list().unwrap(); + list.defer_copy((start + PIECE) as *mut u8, source.as_ptr(), 64); + list.defer_copy((start + 3 * PIECE) as *mut u8, source.as_ptr(), 64); + let told = told(&[&list], &[(&shadow, 0, 2 * PIECE)], &crate::picked::Ranges::default()); + let [t] = &told[..] else { panic!("one copy told") }; + let copy = format!("list 0: a title copy done on the CPU from {:#x}", source.as_ptr() as usize); + assert_eq!(t.ahead, format!("its lists ask 0 refreshes there; {copy}"), "only the copy into the window"); + assert!(!t.lists.contains("title copy"), "{}", t.lists); + drop((list, room, source)); + } + + /// A copy in the card's memory of four pieces, from a piece on in room + /// of our own (kept with it): its title address. + fn four_pieces() -> Option<(Vec<u8>, usize, Arc<Shadow>)> { + let room = vec![0u8; 6 * PIECE]; + let start = (room.as_ptr() as usize).next_multiple_of(PIECE); + let shadow = Shadow::carded_for_test(start as u64, (4 * PIECE) as u64)?; + Some((room, start, shadow)) + } + + /// [`N`] words from `value` on at `at` of the card side, stored by a + /// list of ours (nobody told), and waited for. + fn store(host: &Host, shadow: &Shadow, at: usize, value: u32) { + let (root, pso) = writer(&host.device); + let (allocator, list) = host.make_prelude().unwrap(); + // SAFETY: a fresh list of ours; the writer's root signature; the + // words lie in the card side; all of it lives until the wait. + unsafe { + allocator.Reset().unwrap(); + list.Reset(&allocator, None).unwrap(); + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + let constants = [at as u32, N, value]; + list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.Dispatch(1, 1, 1); + list.Close().unwrap(); + host.queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + } + wait(host); + } + + /// The window watched of `copy`. + fn window_of(copy: u64) -> Option<(usize, usize)> { + let state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + state.as_ref()?.watches.iter().find(|w| w.id == copy).map(|w| (w.from, w.to)) + } + + /// The up-copy check's look at rest finds the card side unlike the CPU + /// side in a piece, in two frames: the copy is watched from that piece. + #[test] + fn the_look_at_rest_has_a_copy_it_flags_in_two_frames_watched() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the look at rest was not tried"); + return; + }; + let _turn = turn(); + let Some((room, _, shadow)) = four_pieces() else { + eprintln!("no copies in the card's memory; the look at rest was not tried"); + return; + }; + let _on = On::new(); + store(host, &shadow, 2 * PIECE + 0x40, 0x5678_0001); + for frame in 0..2 { + assert!(!watched(shadow.id()), "frame {frame}: not yet"); + assert!(super::super::upcheck::look_for_test(host).is_some_and(|words| words >= u64::from(N)), "the look finds the words"); + crate::frame::test_advance(); + } + assert!(watched(shadow.id()), "flagged at rest in two frames"); + assert_eq!(window_of(shadow.id()), Some((2 * PIECE, 4 * PIECE))); + drop(room); + } + + /// The up-copy check's look at a send finds a send putting the CPU + /// side's older words over words the card wrote, in two frames: the copy + /// is watched from that piece. + #[test] + fn a_send_over_words_the_card_wrote_has_the_copy_watched() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the look at a send was not tried"); + return; + }; + let _turn = turn(); + let Some((room, _, shadow)) = four_pieces() else { + eprintln!("no copies in the card's memory; the look at a send was not tried"); + return; + }; + let _on = On::new(); + const B: usize = 3 * PIECE + 0x80; + store(host, &shadow, B, 0x5678_0001); + // A refresh took the piece, the title had not changed it: what goes + // up is the CPU side's zeros. + let zeros = vec![0u8; 64]; + for frame in 0..2 { + assert!(!watched(shadow.id()), "frame {frame}: not yet"); + super::super::upcheck::note(shadow.id(), B, &zeros, &zeros); + let (allocator, list) = host.make_prelude().unwrap(); + // SAFETY: a fresh list of ours, waited for before it goes. + unsafe { + allocator.Reset().unwrap(); + list.Reset(&allocator, None).unwrap(); + } + let looks = super::super::upcheck::record(host, &list, &[(shadow.clone(), vec![(B, B + 64)])]).expect("a look"); + // SAFETY: an open list of ours; the queue is the host's. + unsafe { + list.Close().unwrap(); + host.queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + } + wait(host); + looks.read(); + crate::frame::test_advance(); + } + assert!(watched(shadow.id()), "flagged at a send in two frames"); + assert_eq!(window_of(shadow.id()), Some((3 * PIECE, 4 * PIECE))); + drop(room); + } + + /// A declaration into a watched copy is noted with what became of it: + /// one over title memory the GPU only reads loses those parts + /// (`LEONIDA_GPU_READ_ONLY_NO_BACK`, on), another is declared whole. + #[test] + fn a_declaration_is_noted_with_what_became_of_it() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the notes of declarations were not tried"); + return; + }; + let _turn = turn(); + let Some((room, start, shadow)) = four_pieces() else { + eprintln!("no copies in the card's memory; the notes of declarations were not tried"); + return; + }; + let _on = On::new(); + flagged(&shadow, 0x40, "at rest"); + crate::frame::test_advance(); + flagged(&shadow, 0x40, "at rest"); + assert_eq!(window_of(shadow.id()), Some((0, 4 * PIECE))); + let read_only = start + PIECE; + crate::shadow::title_memory_gpu_read_only(read_only, 0x100); + let list = host.new_list().unwrap(); + { + let bind = binding(&list, "[stores]", true).expect("a bind noted"); + shadow.gpu_writes(&list, read_only as u64, 0x200); + shadow.gpu_writes(&list, (start + 2 * PIECE) as u64, 0x40); + bind.bound(false, || true, || panic!("all declared")); + } + crate::shadow::write_combined_freed(read_only, 0); + let noted: Vec<_> = list.deferred().undeclared.declared.iter().map(|w| (w.from, w.to, w.what)).collect(); + assert_eq!(noted, [ + (PIECE, PIECE + 0x200, "declared, less the parts the GPU only reads (LEONIDA_GPU_READ_ONLY_NO_BACK)"), + (2 * PIECE, 2 * PIECE + 0x40, "declared"), + ]); + drop(room); + } + + /// Off (no switch, and the test's own not set): a copy flagged in two + /// frames is not watched, binds and declarations note nothing, and a + /// submission gets no look. + #[test] + fn off_nothing_is_watched_noted_or_looked_at() { + let Some(host) = host() else { + eprintln!("no D3D12 device; the trace off was not tried"); + return; + }; + let _turn = turn(); + assert!(!on(), "off unless asked"); + let room = vec![0u8; 3 * PIECE]; + let start = (room.as_ptr() as usize).next_multiple_of(PIECE); + let Some(shadow) = Shadow::carded_for_test(start as u64, PIECE as u64) else { + eprintln!("no copies in the card's memory; the trace off was not tried"); + return; + }; + flagged(&shadow, 0x40, "at rest"); + crate::frame::test_advance(); + flagged(&shadow, 0x40, "at rest"); + assert!(!watched(shadow.id())); + assert!(STATE.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_none_or(|s| s.flagged.is_empty() && s.watches.is_empty())); + let list = host.new_list().unwrap(); + assert!(binding(&list, "[stores]", true).is_none()); + declares(&list, &shadow, start as u64, 64, "declared"); + let deferred = list.deferred(); + assert!(deferred.undeclared.declared.is_empty() && deferred.undeclared.past.is_empty() && deferred.undeclared.binds == 0); + drop(deferred); + assert!(ahead(host, &[&list], 1, &crate::picked::Ranges::default()).is_none()); + drop(room); + } +} diff --git a/d3d12/crates/leonida-gpu/src/host/upcheck.rs b/d3d12/crates/leonida-gpu/src/host/upcheck.rs index eb9a60e4c0..cc08be8abe 100644 --- a/d3d12/crates/leonida-gpu/src/host/upcheck.rs +++ b/d3d12/crates/leonida-gpu/src/host/upcheck.rs @@ -152,6 +152,15 @@ static STALE: Mutex<BTreeMap<(u64, u64), Stale>> = Mutex::new(BTreeMap::new()); /// Records the looks at what `dirty` sends up into `list`, ahead of the /// sends. +/// +/// Not at a copy whose card side lies in card memory the CPU maps +/// (`LEONIDA_BAR_BUFFERS_MB`, `Shadow::card_bar`): `send::take` has written +/// what the title wrote into that side already, before this list is +/// recorded, so the look would find the new bytes where it looks for the +/// old. And such a copy that everything went to straight has no copy in +/// the list to leave `COPY_DEST` behind (`Own::record`), where a look +/// leaves it, while the pass that hashes it then reads it as a shader +/// resource. pub(super) fn record( host: &Host, list: &ID3D12GraphicsCommandList, @@ -161,7 +170,11 @@ pub(super) fn record( let mut all: Vec<(std::sync::Arc<Shadow>, Taken)> = Vec::new(); let mut total = 0; for (shadow, _) in dirty { - for taken in noted.remove(&shadow.id()).unwrap_or_default() { + let takes = noted.remove(&shadow.id()).unwrap_or_default(); + if shadow.card_bar().is_some() { + continue; + } + for taken in takes { total += 2 * taken.was.len(); if total <= MOST { all.push((shadow.clone(), taken)); @@ -227,6 +240,10 @@ impl Looks { e.looked += 1; e.bytes += *bytes as u64; if words > 0 { + // (What wrote the card there, from here on: + // `LEONIDA_UNDECLARED_TRACE`.) + #[cfg(feature = "diagnostics")] + super::undeclared::flagged(shadow, at as usize, "at a send"); e.sends += 1; e.words += u64::from(words); if e.some.len() < 4 { @@ -551,6 +568,12 @@ fn run(host: &Host, f: impl FnOnce(&ID3D12GraphicsCommandList)) -> Option<()> { } } +/// [`look`], for the tests of what it feeds (`super::undeclared`). +#[cfg(all(test, feature = "diagnostics"))] +pub(super) fn look_for_test(host: &Host) -> Option<u64> { + look(host) +} + /// The words that differ. fn look(host: &Host) -> Option<u64> { let pass = pass(host)?; @@ -558,6 +581,8 @@ fn look(host: &Host) -> Option<u64> { // (copy, offset, bytes) let mut pieces: Vec<(std::sync::Arc<Shadow>, usize, usize)> = Vec::new(); for shadow in &copies { + #[cfg(feature = "diagnostics")] + super::undeclared::asked(shadow); // What has not gone up yet differs rightly. let dirty = shadow.card_dirty_now(); let len = shadow.span().1 as usize & !3; @@ -611,6 +636,10 @@ fn look(host: &Host) -> Option<u64> { words: a[0], }) .collect(); + #[cfg(feature = "diagnostics")] + for d in &differs { + super::undeclared::flagged(&d.shadow, d.at, "at rest"); + } let bytes: u64 = pieces.iter().map(|p| p.2 as u64).sum(); let words: u64 = differs.iter().map(|d| u64::from(d.words)).sum(); tracing::info!( diff --git a/d3d12/crates/leonida-gpu/src/host/wide_refresh_tests.rs b/d3d12/crates/leonida-gpu/src/host/wide_refresh_tests.rs new file mode 100644 index 0000000000..dae72f54bb --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/wide_refresh_tests.rs @@ -0,0 +1,12 @@ +use super::wide_refresh_enabled; + +#[test] +fn parallel_refresh_is_default_on_multicore_and_can_be_overridden() { + assert!(wide_refresh_enabled(None, Some(4))); + assert!(wide_refresh_enabled(None, Some(16))); + assert!(!wide_refresh_enabled(None, Some(2))); + assert!(!wide_refresh_enabled(None, None)); + assert!(wide_refresh_enabled(Some("1"), Some(1))); + assert!(!wide_refresh_enabled(Some("0"), Some(16))); + assert!(wide_refresh_enabled(Some("auto"), Some(4))); +} diff --git a/d3d12/crates/leonida-gpu/src/host/written_spans_tests.rs b/d3d12/crates/leonida-gpu/src/host/written_spans_tests.rs new file mode 100644 index 0000000000..967865f314 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/written_spans_tests.rs @@ -0,0 +1,65 @@ +use super::{Touch, front_spans, split, written_spans}; + +#[test] +fn everything_is_refreshed_in_front_but_what_a_part_gave_its_shaders() { + use Touch::{Nothing, Part, Refresh, Title, Write}; + let found = front_spans( + [ + Refresh(1, 10, 20), + Refresh(1, 12, 25), + Refresh(2, 0, 5), + Nothing, + Write(1), + // (Around what the part's own shaders write.) + Refresh(1, 0, 100), + Write(3), + Refresh(3, 1, 2), + Title, + Refresh(4, 7, 9), + Part, + // The next part's bytes under the first one's writes. + Refresh(1, 30, 40), + Write(4), + Refresh(4, 0, 9), + ] + .into_iter(), + ); + assert_eq!(found, [(1, 10, 40), (2, 0, 5), (4, 7, 9)]); +} + +#[test] +fn a_submission_is_cut_between_its_lists() { + // Lists c and e are in neither half's order: they go with the first. + let Ok([first, second]) = split(vec!['a', 'b', 'c', 'd', 'e'], vec![1, 3, 0], 1) else { + panic!("no list is named twice"); + }; + let run = |(lists, order): &(Vec<char>, Vec<usize>)| order.iter().map(|&i| lists[i]).collect::<String>(); + assert_eq!((run(&first), run(&second)), ("b".into(), "da".into())); + assert_eq!(first.0.len() + second.0.len(), 5); + assert!(split(vec!['a', 'b'], vec![0, 1, 0], 2).is_err()); + assert!(split(vec!['a', 'b'], vec![0, 1], 0).is_err()); +} + +#[test] +fn what_is_written_is_refreshed_ahead_up_to_its_write_and_to_title_writes() { + use Touch::{Nothing, Refresh, Title, Write}; + let mut found = written_spans( + [ + Refresh(1, 10, 20), + Refresh(2, 0, 5), + Nothing, + Refresh(1, 30, 40), + Write(1), + Refresh(1, 0, 100), + Write(3), + Refresh(3, 1, 2), + Refresh(4, 7, 9), + Write(4), + Title, + Write(2), + ] + .into_iter(), + ); + found.sort_unstable(); + assert_eq!(found, [(1, 10, 40), (4, 7, 9)]); +} diff --git a/d3d12/crates/leonida-gpu/src/indirect.rs b/d3d12/crates/leonida-gpu/src/indirect.rs index a81dcf0d1a..763d54d10c 100644 --- a/d3d12/crates/leonida-gpu/src/indirect.rs +++ b/d3d12/crates/leonida-gpu/src/indirect.rs @@ -860,15 +860,30 @@ fn batch_clamp() -> Option<&'static Clamp> { /// and the scratch buffer its places are in. Replaces the list's compute /// root signature and pipeline (callers bind theirs after). `None` if the /// clamp is not available. +/// +/// The pass reads its table from the card's memory where it can +/// (`LEONIDA_BATCH_TABLE_CARD`, `crate::host::batch_tables`), else from the +/// list's scratch memory. pub(crate) fn open_batch( list: &HostList, source: (u64, &ID3D12Resource), recent: &[(u64, ID3D12Resource)], +) -> Option<(batch::Table, ID3D12Resource)> { + let card = host().is_some_and(crate::host::batch_table_card); + open_batch_with(list, source, recent, card) +} + +/// [`open_batch`], its pass reading its table from the card's memory with +/// `card_table` (if a table area is to be had there) and from the list's +/// scratch memory without. +pub(crate) fn open_batch_with( + list: &HostList, + source: (u64, &ID3D12Resource), + recent: &[(u64, ID3D12Resource)], + card_table: bool, ) -> Option<(batch::Table, ID3D12Resource)> { let c = batch_clamp()?; let budget = list.budget()?; - let (jobs, at) = list.scratch(batch::TABLE)?; - let (dst, base, before) = list.batch_place()?; let gpu = |b: &ID3D12Resource| { // SAFETY: a live buffer. Some(unsafe { b.GetGPUVirtualAddress() }).filter(|at| at.is_multiple_of(4)) @@ -902,14 +917,19 @@ pub(crate) fn open_batch( let _ = &read; batch::Wait::All }; + // The last thing that may fail: a place taken is a batch the list's close + // expects recorded (its buffer's state). + let ((dst, base, before), (jobs, at)) = + list.batch_place_table(card_table, || list.scratch(batch::TABLE))?; #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::IndirectBounded, 1); // (A command of its own for the timing run: its time was the next execution's.) #[cfg(feature = "diagnostics")] list.note_op(|| "clamp batch".to_owned()); batch::record(c, &list.list, (&dst, before), budget, sources, jobs, wait); - // SAFETY: the list's own upload memory of that many bytes, 256-byte - // aligned, until it is reset. + // SAFETY: the list's own mapped memory of that many bytes, 256-byte + // aligned, until it is reset: its scratch memory, or its batch's table in + // the upload buffer of a table area the list holds until then. Some((unsafe { batch::Table::new(at, base, ids) }, dst)) } @@ -3964,6 +3984,219 @@ void main() { assert_eq!(hits, 20 + 20 + 1 + 7, "the first batch has record 0 as it was, the second as written"); } + /// For the tests of tables in the card's memory: the worker, a signature of one dispatch and + /// two source buffers of 16 dispatch records each (32 bytes apart), record `i` of the first + /// asking for `1 + i` groups and of the second for `100 + i`. + fn table_sources(host: &crate::host::Host) -> Option<(Clamp, ID3D12CommandSignature, Vec<ID3D12Resource>)> { + let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + let signature = one_argument(&host.device, 2, 12); + let mut sources = Vec::new(); + for first in [1u32, 100] { + let (buffer, ptr) = host.shared_buffer(1024)?; + for i in 0..16u32 { + for (w, word) in [first + i, 1, 1].into_iter().enumerate() { + // SAFETY: inside the mapping. + unsafe { ptr.cast::<u32>().add(i as usize * 8 + w).write_volatile(word) }; + } + } + sources.push(buffer); + } + Some((worker, signature, sources)) + } + + /// Records `batches` batches into `list`, batch `k` reading its table from the card's + /// memory if `card(k)` (`open_batch_with`), each with four executions of records `from` + /// and up of both sources into the hit counter at `hits`: the hits they make. + fn record_table_batches( + list: &HostList, + (worker, signature, sources): &(Clamp, ID3D12CommandSignature, Vec<ID3D12Resource>), + hits: u64, + batches: u32, + from: u32, + card: impl Fn(u32) -> bool, + ) -> u32 { + let mut expected = 0; + for k in 0..batches { + let (mut table, scratch) = + open_batch_with(list, (1, &sources[0]), &[(1, sources[0].clone()), (2, sources[1].clone())], card(k)).unwrap(); + // SAFETY: an open list; the worker's root signature and pipeline; buffers the test + // holds until the list has run. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits); + } + for (id, record) in [(1u64, from + k % 4), (2, from + 2), (1, from), (2, from + 2)] { + let at = table.place(id, u64::from(record) * 32, 2).unwrap(); + // SAFETY: as above. + unsafe { list.list.ExecuteIndirect(signature, 1, &scratch, at, None, 0) }; + expected += record + if id == 1 { 1 } else { 100 }; + } + } + expected + } + + /// The hits a run made since the counter was zeroed ([`record_table_batches`]). + fn hits_now(ptr: *mut u8) -> u32 { + // SAFETY: the list has run; a mapped buffer. + unsafe { (ptr as *const u32).read_volatile() } + } + + /// (`LEONIDA_BATCH_TABLE_CARD`) Batches whose passes read their tables from the card's + /// memory, more than one scratch buffer holds (two table areas), twice: every execution runs + /// what it asked for, and only because the list's prelude copied the tables there (without + /// the copy the passes read whatever the mirrors held, and the executions with them). Where + /// the debug layer is installed (Windows' Graphics Tools), it found no barrier naming a state + /// a buffer is not in, in the recording or in the submission ([`Host::errors_seen`]: every + /// submission ends by logging and clearing what it found); without it nothing is checked + /// there. + #[test] + fn batches_read_their_tables_from_the_cards_memory() { + let Some(host) = super::host() else { + return; + }; + let _ = host.errors_seen(); + let (Ok(list), Some(made), Some((hits_buf, hits_ptr))) = (host.new_list(), table_sources(host), host.shared_buffer(256)) + else { + return; + }; + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + for skip_copy in [false, false, true] { + // SAFETY: the mapping holds 256 bytes; nothing runs. + unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) }; + // (Records the other tests here do not ask for: what a mirror kept of theirs is not + // these tables.) + let from = if skip_copy { 9 } else { 3 }; + let expected = record_table_batches(&list, &made, hits_gpu, 12, from, |_| true); + list.close(); + assert_eq!(host.errors_seen(), None, "the debug layer found an error"); + crate::host::batch_tables::TEST_NO_TABLE_COPY.set(skip_copy); + host.execute(&[&list]); + crate::host::batch_tables::TEST_NO_TABLE_COPY.set(false); + assert_eq!(host.errors_seen(), None, "the debug layer found an error"); + list.reset(); + if skip_copy { + assert_ne!(hits_now(hits_ptr), expected, "without the prelude's copy the passes read no such tables"); + } else { + assert_eq!(hits_now(hits_ptr), expected, "every execution runs what it asked for"); + } + } + } + + /// (`LEONIDA_BATCH_TABLE_CARD`) A list sent twice in one submission: its prelude copies the + /// tables before each run (the second copy behind the first run's passes, which its close + /// moved the mirrors back to the common state behind), and each run's executions run what + /// they asked for. How many runs there were a dispatch of the list counts apart: WARP runs + /// both, the RX 7900 XT's driver one (a list of that one dispatch alone too, 2026-11-30). + #[test] + fn a_list_run_twice_in_one_submission_reads_its_tables_twice() { + let Some(host) = super::host() else { + return; + }; + let _ = host.errors_seen(); + let (Ok(list), Some(made), Some((hits_buf, hits_ptr))) = (host.new_list(), table_sources(host), host.shared_buffer(256)) + else { + return; + }; + // SAFETY: a live buffer; the mapping holds 256 bytes and nothing runs. + let hits_gpu = unsafe { + std::ptr::write_bytes(hits_ptr, 0, 256); + hits_buf.GetGPUVirtualAddress() + }; + let expected = record_table_batches(&list, &made, hits_gpu, 10, 4, |_| true); + // SAFETY: an open list; the worker's root signature and pipeline (bound by the last + // batch); a buffer the test holds until the list has run. + unsafe { + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu + 64); + list.list.Dispatch(1, 1, 1); + } + list.close(); + host.execute(&[&list, &list]); + assert_eq!(host.errors_seen(), None, "the debug layer found an error"); + list.reset(); + // SAFETY: the list has run; inside the mapping. + let runs = unsafe { hits_ptr.add(64).cast::<u32>().read_volatile() }; + assert!(runs >= 1, "the list ran"); + assert_eq!(hits_now(hits_ptr), runs * expected, "every run runs what it asked for"); + } + + /// (`LEONIDA_BATCH_TABLE_CARD`) A table area goes back with its scratch buffer when the + /// list is reset, and the next list to take it reads its own tables there: a list of three + /// batches after one of twelve takes the scratch buffer the first list gave back last, with + /// the same table area, and runs its own executions and none of the first list's. (The + /// thread's own table of spare buffers: whatever other tests take and give meanwhile.) + #[test] + fn a_table_area_taken_again_holds_the_new_lists_tables() { + let Some(host) = super::host() else { + return; + }; + if !crate::host::batch_pool() { + return; + } + let _ = host.errors_seen(); + let (Ok(a), Ok(b), Some(made), Some((hits_buf, hits_ptr))) = + (host.new_list(), host.new_list(), table_sources(host), host.shared_buffer(256)) + else { + return; + }; + crate::host::own_spare_batches(true); + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + let mut given = Vec::new(); + for (list, batches, from) in [(&a, 12, 2), (&b, 3, 7)] { + // SAFETY: the mapping holds 256 bytes; nothing runs. + unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) }; + let expected = record_table_batches(list, &made, hits_gpu, batches, from, |_| true); + let buffers = list.batch_buffers(); + assert!(buffers.iter().all(|b| b.1.is_some()), "every buffer has a table area"); + if given.is_empty() { + assert_eq!(buffers.len(), 2, "twelve batches: two buffers"); + // (Held here: no buffer made since is where one of these is.) + given = buffers; + } else { + assert_eq!(buffers.len(), 1, "three batches: one buffer"); + assert_eq!(buffers[0].0.as_raw(), given[1].0.as_raw(), "the buffer the first list gave back last"); + assert_eq!(buffers[0].1, given[1].1, "with its table area"); + } + list.close(); + host.execute(&[list]); + assert_eq!(host.errors_seen(), None, "the debug layer found an error"); + list.reset(); + assert_eq!(hits_now(hits_ptr), expected, "{batches} batches run their own executions only"); + } + crate::host::own_spare_batches(false); + } + + /// (`LEONIDA_BATCH_TABLE_CARD=0`, and the switch flipped while a list is recorded) Tables in + /// the list's scratch memory, as before, and a list whose batches read theirs from either + /// place by turns: the prelude copies those of the card's memory only, and every execution + /// runs what it asked for. + #[test] + fn batches_read_their_tables_from_upload_memory_or_either() { + let Some(host) = super::host() else { + return; + }; + let _ = host.errors_seen(); + let (Ok(list), Some(made), Some((hits_buf, hits_ptr))) = (host.new_list(), table_sources(host), host.shared_buffer(256)) + else { + return; + }; + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + let ways: [&dyn Fn(u32) -> bool; 3] = [&|_| false, &|k| k % 2 == 1, &|k| k % 3 == 0]; + for card in ways { + // SAFETY: the mapping holds 256 bytes; nothing runs. + unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) }; + let expected = record_table_batches(&list, &made, hits_gpu, 13, 1, card); + list.close(); + host.execute(&[&list]); + assert_eq!(host.errors_seen(), None, "the debug layer found an error"); + list.reset(); + assert_eq!(hits_now(hits_ptr), expected, "every execution runs what it asked for"); + } + } + /// What clamps of a frame cost on the card one by one and in batches /// (ignored: a measurement): 2,355 executions of an empty dispatch, in /// 49 lists' worth of runs, as in the captured frame. diff --git a/d3d12/crates/leonida-gpu/src/indirect/batch.rs b/d3d12/crates/leonida-gpu/src/indirect/batch.rs index 0d5c441e44..5db4200438 100644 --- a/d3d12/crates/leonida-gpu/src/indirect/batch.rs +++ b/d3d12/crates/leonida-gpu/src/indirect/batch.rs @@ -3,11 +3,18 @@ //! at the first of them. //! //! The executions that come after it are not known yet when the pass is -//! recorded, so it reads what to clamp from a table of jobs in upload -//! memory, which the CPU goes on filling while the list is recorded: the -//! pass is as wide as the table and its threads past the count do nothing. -//! An execution that asks for a record already in the table (the title's -//! tile classes) reads the same clamped one. +//! recorded, so it reads what to clamp from a table of jobs the CPU goes on +//! filling in mapped memory while the list is recorded: the pass is as wide +//! as the table and its threads past the count do nothing. An execution that +//! asks for a record already in the table (the title's tile classes) reads +//! the same clamped one. +//! +//! The pass usually reads the table from the card's memory: the CPU fills it +//! in an upload buffer and the list's prelude copies it into the card's +//! memory, the table whole by then, ahead of the list in the same submission +//! (`LEONIDA_BATCH_TABLE_CARD`, `crate::host::batch_tables`). Otherwise +//! (the switch off, or the list's scratch memory in the card's memory +//! already) it reads it where the CPU writes it, the list's scratch memory. //! //! What the records charge the list's budget is as for records clamped //! alone, times the executions that read them. @@ -19,7 +26,7 @@ use crate::host::transition; /// The jobs of one pass. pub(crate) const JOBS: u32 = 256; -/// The bytes of its table in upload memory: the count, then the jobs. +/// The bytes of its table: the count, then the jobs. pub(crate) const TABLE: u64 = 16 + 16 * JOBS as u64; /// The bytes of a clamped record's place in the scratch buffer. pub(crate) const SLOT: u32 = 32; @@ -249,7 +256,7 @@ pub(crate) fn job(source: u32, kind: u32, times: u32) -> u32 { /// keeps which record is where. #[derive(Default)] pub(crate) struct Table { - /// The table in upload memory ([`TABLE`] bytes). + /// The table in mapped memory, where the CPU fills it ([`TABLE`] bytes). at: usize, /// The place of the first clamped record in the scratch buffer. base: u32, @@ -343,7 +350,10 @@ pub(super) enum Wait<'a> { /// Records the pass over the table at `jobs` (a host address) into `dst`, /// which is in state `before` and left in `INDIRECT_ARGUMENT`: after every /// earlier shader write (the title's argument passes), before what reads -/// the clamped records. +/// the clamped records. The table is final when the list runs: in upload +/// memory (common state, promoted), or in the card's memory, where the +/// list's prelude copied it and left it in `NON_PIXEL_SHADER_RESOURCE` +/// (`crate::host::batch_tables`). pub(super) fn record( c: &Clamp, l: &ID3D12GraphicsCommandList, @@ -375,7 +385,8 @@ pub(super) fn record( } first.push(transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)); // SAFETY: an open list; our root signature and pipeline; live buffers: - // the sources and the table are read in the common state (promoted). + // the sources are read in the common state (promoted), and the table so + // or as its list's prelude left it (above). unsafe { l.ResourceBarrier(&first); l.SetComputeRootSignature(&c.root); diff --git a/d3d12/crates/leonida-gpu/src/inplace.rs b/d3d12/crates/leonida-gpu/src/inplace.rs index 504a5b4ec1..af0ffa0387 100644 --- a/d3d12/crates/leonida-gpu/src/inplace.rs +++ b/d3d12/crates/leonida-gpu/src/inplace.rs @@ -21,7 +21,11 @@ //! committed view of a section. //! - `OpenExistingHeapFromFileMapping` takes a section made with //! `SEC_COMMIT` and refuses one made with `SEC_RESERVE` (how `xmem` -//! makes the title's page pool today). The heap is the section, not a +//! makes the title's page pool unless `LEONIDA_SECTION_COMMIT=1`, and +//! its sections larger than 64 MiB either way; on the RX 7900 XT too, +//! E_INVALIDARG: `leonida_hle`'s `a_committed_section_opens_as_a_heap`, +//! which reads the pool in place through +//! [`title_memory_reads_in_place`]). The heap is the section, not a //! view of it: views may be unmapped, mapped elsewhere or made //! read-only, and the section's handle closed, with the heap alive. //! Opening it locks nothing (256 MiB: 0.2 ms, no working set). @@ -29,7 +33,10 @@ //! L0), shared and cross-adapter shared, 64 KiB aligned. A buffer in it //! must have `ALLOW_CROSS_ADAPTER`; unordered access beside it is taken. //! A texture must be row-major with one level. Tile mappings into such -//! a heap are refused and REMOVE THE DEVICE: never call them. +//! a heap are refused and REMOVE THE DEVICE: never call them on a device +//! that matters. On the RX 7900 XT too: Direct3D takes no tiles in a +//! cross-adapter heap, which every opened heap is (`tiled`'s probe, which +//! asks on a device of its own). //! - While a heap opened from an address stands, the title cannot //! decommit, release or protect the pages in it (`VirtualFree` and //! `VirtualProtect` fail with error 87), nor unmap a view in it. Pages @@ -37,7 +44,8 @@ use std::collections::BTreeMap; use std::ffi::c_void; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; @@ -48,13 +56,17 @@ use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; use windows::core::{Interface, s}; use windows_sys::Win32::System::Memory as mem; +mod tiled; + /// The unit heaps and placed buffers are cut on, and the console's page. const K64: usize = 64 << 10; /// The host's write watching (not in windows-sys' memory module). const MEM_WRITE_WATCH: u32 = 0x20_0000; /// `LEONIDA_INPLACE_PROBE`: 0 (unset) nothing; 1 the probe on memory of -/// its own at the first sweep, and the census 30 and 150 seconds later; +/// its own at the first sweep (then, with `LEONIDA_INPLACE_PROBE_TILES=1`, +/// `tiled`'s, of tiles mapped onto such memory, on a device of its own), +/// and the census 30 and 150 seconds later; /// 2 also opens one part of the title's own memory for a moment at the /// first census. pub(crate) fn probe_level() -> u8 { @@ -66,12 +78,17 @@ pub(crate) fn probe_level() -> u8 { /// buffers that lies in private memory committed whole is not copied: a /// part of the title's allocation is opened as a host heap and the window /// is a buffer placed over it ([`place_for`]). 2: title buffers too, -/// except the big ones in the card's memory. +/// except the big ones in the card's memory (with [`last`], a big one the +/// card's memory turned down is opened in place too). /// /// What stage 1 covers is private memory (`XMemVirtualAlloc`'s). View -/// memory (the page pool) is turned down here: its section is made -/// reserved, which the host refuses, and what a view shows changes when -/// the title maps pages. +/// memory (the page pool) is turned down by default: its sections are made +/// reserved, which the host refuses. With `LEONIDA_SECTION_COMMIT=1` +/// (`xmem`, off by default) the small ones are made committed and open as +/// heaps ([`From::Section`], [`title_memory_reads_in_place`]), and a window +/// or title buffer that is one run of such a section is placed in it +/// ([`sections`]); what a view shows changes when the title maps pages, and +/// what is in place there is let go then ([`title_memory_freeing`]). /// /// What it assumes, for 2: nothing reads title memory that a submission /// not yet run writes through such a buffer. With every submission waited @@ -79,16 +96,61 @@ pub(crate) fn probe_level() -> u8 { /// since the flights' rules know shader writes only by the ranges copies /// declare. Do not combine 2 with late wait. /// -/// shortcut: while a window is in place the title cannot decommit, free -/// or protect its pages (the call fails with error 87; the probe shows -/// it). The title's heaps are allocated once and kept, and nothing of the -/// kind was seen; [`title_memory_freeing`] is there for the runtime to -/// call before such a call once it takes them over. +/// While a window is in place the title cannot decommit, free or protect +/// its pages (the call fails with error 87; the probe shows it). The +/// title's `VirtualFree` is the runtime's (`leonida_hle`'s xmem): what is +/// in place over the memory is let go first (`crate::watch::title_memory_freed` +/// calls [`title_memory_freeing`]), and a free the heaps still in the way +/// refuse is done when they are gone ([`title_memory_free_held`]). +/// +/// The title's `VirtualProtect` is the runtime's too (xmem's): what is in +/// place over the pages is let go first and a protection the heaps still in +/// the way refuse is made when they are gone ([`title_memory_protect`]). +/// +/// Private memory is opened by a thread of its own, not by the ask +/// ([`asynchronous`], `LEONIDA_INPLACE_ASYNC`): the first ask of a window or +/// title buffer gets a copy, and what was opened takes its place later. pub(crate) fn level() -> u8 { + #[cfg(test)] + if let Some(level) = TEST_LEVEL.get() { + return level; + } static LEVEL: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); *LEVEL.get_or_init(|| std::env::var("LEONIDA_INPLACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) } +#[cfg(test)] +thread_local! { + /// A test's [`level`], for its thread only (what a window or a title + /// buffer is made as is decided on the thread that asks for it). + pub(crate) static TEST_LEVEL: std::cell::Cell<Option<u8>> = const { std::cell::Cell::new(None) }; + /// For a test, on its thread only: the views of this range (address, + /// bytes) are forgotten between a placement in a section and + /// [`in_section`]'s second look, as when the title maps other pages + /// there meanwhile. + pub(crate) static TEST_REMAPPED_WHILE_PLACING: std::cell::Cell<Option<(usize, usize)>> = const { std::cell::Cell::new(None) }; + /// A test's [`asynchronous`], for its thread only. + pub(crate) static TEST_ASYNC: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; +} + +/// `LEONIDA_INPLACE_LAST`: on (unset), with [`level`] on, title memory is +/// opened in place only where its copy would be kept in the PC's memory +/// alone. A window outside buffers that gets a side in the card's memory +/// (`LEONIDA_CARD_WINDOWS_MB`) or lies in card memory the CPU maps +/// (`LEONIDA_WINDOWS_BAR_MB`) keeps it, and a big title buffer the card's +/// memory turned down (no room, past `LEONIDA_CARD_BUFFERS_MB`, 1 GiB or +/// more) is opened in place at level 2 instead of copied. Such a copy is +/// read by the card over the bus as the title memory in place is (both are +/// write-back memory of the PC's, 23 to 28 GB/s on the RX 7900 XT: +/// findings.md, the placement table), so it was a duplicate of the title's +/// bytes with a refresh of every page written; a side in the card's memory +/// is read 25 to 40 times as fast by what many waves read many times. +/// `LEONIDA_INPLACE_LAST=0`: as before, a window is opened in place ahead +/// of both, and a big title buffer never is. +pub(crate) fn last() -> bool { + crate::toggled!("LEONIDA_INPLACE_LAST") +} + /// The most title memory in place at once, in bytes /// (`LEONIDA_INPLACE_MB`, 4096): opening locks the pages into the PC's /// memory, also those the title never touched. @@ -100,8 +162,136 @@ fn most() -> u64 { /// In place now: windows and their bytes, title buffers and their bytes; /// then, since the start: asks turned down because the memory is a view /// or not private memory committed whole, because the host refused, -/// because of [`most`]; and what was let go because its memory changed. -static STATS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; +/// because of [`most`]; and what was let go because its memory changed; +/// the title's releases done later because a heap was in the way +/// ([`title_memory_free_held`]), its decommits of memory in place kept +/// committed (zeroed), and later releases given up on ([`GIVE_UP_MS`]); +/// descriptor slots made to let go of a buffer over memory the title gave +/// up ([`slots_let_go`]); the title's protections made later because a heap +/// was in the way, and those given up on ([`title_memory_protect`]); the +/// title's reservations at a fixed address made once the releases kept +/// there were done ([`title_memory_reserve`]); windows and title buffers +/// opened in their section of physical pages ([`in_section`]); opened in +/// the background ([`asynchronous`]), of them taken by a later ask, switched +/// from a copy at a safe point ([`switch_ready`]), and given up on unused +/// ([`READY_MS`]); copies asked to be opened again once their memory was +/// read-write again ([`again`]); shaders declared to write either side of a +/// switch while lists still held the copy ([`written_across_switch`]). +static STATS: [AtomicU64; 22] = [const { AtomicU64::new(0) }; 22]; + +/// `LEONIDA_INPLACE_FREE`: on (unset), the title's frees of memory in +/// place let go of it and are done once its heaps are gone ([`hold`], +/// [`title_memory_free_held`]). `LEONIDA_INPLACE_FREE=0`: as before, what +/// is in place stays in the tables, the title's free fails with error 87 +/// and its memory is kept for good (the heap with it, until its copy is +/// let go for some other reason, if ever). +pub(crate) fn frees() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_INPLACE_FREE").is_none_or(|v| v != "0")) +} + +/// `LEONIDA_INPLACE_SLOTS`: on (unset), when the title frees or decommits +/// memory a buffer of ours is placed over, the descriptor slots that view +/// that buffer let go of it ([`slots_let_go`]; for a protection, once the +/// submissions sent before have run, [`Ripe`]); else (`=0`, as before) a +/// slot keeps it until the title writes the slot again, which it need not +/// ever do for memory it gave up, and the release waits for as long. +fn slots() -> bool { + crate::toggled!("LEONIDA_INPLACE_SLOTS") +} + +/// A buffer [`place_for`] placed over title memory, held by us as well +/// ([`HELD`]): the 64 KiB pages its heap was opened on, `[at, end)`. Once +/// we let go of it too ([`reap`]), `None`, and since when (ms). +struct Hold { + at: usize, + end: usize, + buffer: Option<ID3D12Resource>, + let_go: u64, +} + +// SAFETY: a D3D12 resource (free-threaded), only counted and released. +unsafe impl Send for Hold {} + +/// Every buffer placed over title memory whose heap may still stand. A +/// placed buffer keeps its heap (on the software adapter a buffer alone, +/// with every reference to the heap dropped, still has the host refuse the +/// release: the test of [`title_memory_free_held`]); and whoever still +/// shows the buffer (the copy's tables, a list in flight, an object +/// [`crate::host::retire`] keeps for the submissions that may use it, a +/// descriptor slot) holds a reference to it. While any does, the heap stands and the title's pages +/// under it can be neither decommitted nor released. Ours is the one +/// reference those do not have: when it is the last ([`reap`]) nothing +/// can reach the heap any more, and it goes with it. That moment is not +/// known otherwise. (Descriptor slots kept the buffer until the title wrote +/// them again, which it need not do for memory it freed; they now let go +/// of it when the title frees the memory, [`slots_let_go`].) +/// +/// A hold let go of stays noted for [`GIVE_UP_MS`]: the heap goes with our +/// reference, but the host does not always let go of its pages at once, +/// and a free it refuses meanwhile is still the heap's doing, to be taken +/// over as one a standing hold is in the way of ([`title_memory_free_held`]). +/// Over pages the host does free meanwhile it is forgotten at once +/// ([`holds_freed`]): the host kept them for no heap, and the addresses may +/// be the title's new memory's next. +static HELD: std::sync::Mutex<Vec<Hold>> = std::sync::Mutex::new(Vec::new()); + +/// The title's releases of memory under a heap ([`title_memory_free_held`]), +/// done when no hold is in the way any more: the allocation `[at, end)`, +/// and since when (ms) no hold has been ([`GIVE_UP_MS`]; 0: one still is). +static PENDING: std::sync::Mutex<Vec<(usize, usize, u64)>> = std::sync::Mutex::new(Vec::new()); + +/// The title's protections of memory under a heap ([`title_memory_protect`]), +/// made in the order the title asked for them when no hold is in the way any +/// more: the pages `[at, end)`, the protection, since when (ms) no hold +/// has been ([`GIVE_UP_MS`]; 0: one still is), and whether the submissions +/// sent before the title asked have run ([`Ripe`]). +static PROTECTS: std::sync::Mutex<Vec<(usize, usize, u32, u64, Arc<AtomicBool>)>> = std::sync::Mutex::new(Vec::new()); + +/// Retired ([`crate::host::retire`]) when the title protects memory in place +/// ([`let_go_under`]), so dropped once the submissions sent before have run: +/// from then on no submission reads the descriptor slots that still view +/// the buffers there without making them again first, and they can be +/// made null ([`slots_again`]). Until then a slot goes on showing the buffer: +/// the title may read the memory on the GPU after protecting it, and the +/// memory is still the title's while the heap stands. +struct Ripe(Arc<AtomicBool>); + +impl Drop for Ripe { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + RIPENED.store(true, Ordering::Release); + } +} + +/// Some [`Ripe`] went since [`slots_again`] last looked: it looks at once. +static RIPENED: AtomicBool = AtomicBool::new(false); + +/// Holds (those let go of lately too), pending releases and protections, +/// so that [`tick`] looks at none while there are none. +static WAITING: AtomicU64 = AtomicU64::new(0); + +/// `LEONIDA_INPLACE_PROTECT`: on (unset), the title's `VirtualProtect` of +/// memory a heap opened in place stands over lets go of what is in place +/// there and is made once the heap is gone ([`title_memory_protect`]). +/// `=0`: as before, the call goes to the host alone and fails with error 87 +/// while the heap stands. +pub(crate) fn protects() -> bool { + crate::toggled!("LEONIDA_INPLACE_PROTECT") +} + +/// How often [`tick`] lets go of holds nothing else has and tries the +/// releases again (ms). +const REAP_MS: u64 = 100; + +/// A release still refused this long after no hold was in the way any more +/// is given up on (said once each): the heap is gone, so what refuses it is +/// not ours. Releasing a heap is not always at once: a busy adapter lets go +/// of its pages a moment after the last reference (the test of +/// `place_part` waits up to five seconds for it on the software adapter). +/// For as long, a hold let go of is still taken to be in the way of the +/// title's frees ([`HELD`]). +const GIVE_UP_MS: u64 = 30_000; /// A buffer placed over title memory, and its heap. pub(crate) struct Placed { @@ -113,13 +303,21 @@ pub(crate) struct Placed { pub(crate) bias: u64, } -/// Opens the 64 KiB pages that hold title memory `[start, start + len)` -/// as a heap of their own and places one buffer over all of them. `Err` -/// with nothing if the memory is not private memory committed whole -/// (nothing was asked of the host), with the host's error if it refused. -pub(crate) fn place_part(device: &ID3D12Device, start: u64, len: u64) -> Result<Placed, Option<windows::core::Error>> { +/// The 64 KiB pages that hold `[start, start + len)`: the first, and +/// their bytes. +fn opened_pages(start: u64, len: u64) -> (u64, u64) { let at = start & !(K64 as u64 - 1); - let bytes = (start + len.max(1)).next_multiple_of(K64 as u64) - at; + (at, (start + len.max(1)).next_multiple_of(K64 as u64) - at) +} + +/// Opens the 64 KiB pages that hold memory `[start, start + len)` as a +/// heap of their own and places one buffer over all of them. `Err` with +/// nothing if the memory is not private memory committed whole (nothing +/// was asked of the host), with the host's error if it refused. (Not held, +/// [`hold`]: the runtime's own memory, the arenas `crate::shadow` opens by +/// address, is never the title's to free.) +pub(crate) fn place_part(device: &ID3D12Device, start: u64, len: u64) -> Result<Placed, Option<windows::core::Error>> { + let (at, bytes) = opened_pages(start, len); if !private_whole(at as usize, bytes as usize) { return Err(None); } @@ -130,964 +328,2992 @@ pub(crate) fn place_part(device: &ID3D12Device, start: u64, len: u64) -> Result< Ok(Placed { buffer, heap, gpu, bias: start - at }) } -/// Title memory `[start, start + len)` in place, for a window outside -/// buffers or a title buffer, if [`level`] asks for it and the memory can -/// be opened; `None` leaves the caller to make a copy, as before. -pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option<Placed> { - if level() < if window { 1 } else { 2 } { - return None; - } - // View memory: known from the runtime without asking Windows. - if cover(start as usize, len as usize) != Cover::None { - STATS[4].fetch_add(1, Ordering::Relaxed); - return None; - } - if STATS[1].load(Ordering::Relaxed) + STATS[3].load(Ordering::Relaxed) + len > most() { - STATS[6].fetch_add(1, Ordering::Relaxed); - return None; +/// `buffer`, placed over the pages of title memory `[start, start + len)` +/// ([`place_part`]): kept in [`HELD`] until nothing else holds it +/// ([`frees`]). +fn hold(start: u64, len: u64, buffer: &ID3D12Resource) { + if !frees() { + return; } - let host = crate::host::host()?; - match place_part(&host.device, start, len) { - Ok(placed) => { - let at = if window { 0 } else { 2 }; - STATS[at].fetch_add(1, Ordering::Relaxed); - STATS[at + 1].fetch_add(len, Ordering::Relaxed); - Some(placed) - } - Err(None) => { - STATS[4].fetch_add(1, Ordering::Relaxed); - None - } - Err(Some(e)) => { - if STATS[5].fetch_add(1, Ordering::Relaxed) < 8 { - tracing::warn!(start = format_args!("{start:#x}"), len, error = %e, "title memory not opened in place: a copy instead"); + let (at, bytes) = opened_pages(start, len); + let (at, end) = (at as usize, (at + bytes) as usize); + let mut held = HELD.lock().unwrap_or_else(|e| e.into_inner()); + held.push(Hold { at, end, buffer: Some(buffer.clone()), let_go: 0 }); + WAITING.fetch_add(1, Ordering::Relaxed); +} + +/// Lets go of the holds nothing but [`HELD`] has any more (their heaps go +/// with them; the holds stay noted as let go of), forgets those let go of +/// [`GIVE_UP_MS`] ago, then tries again the releases they were in the way +/// of. +pub(crate) fn reap() { + let now = crate::host::now_ms().max(1); + let gone: Vec<ID3D12Resource> = { + let mut held = HELD.lock().unwrap_or_else(|e| e.into_inner()); + let before = held.len(); + let mut gone = Vec::new(); + held.retain_mut(|h| { + let Some(buffer) = &h.buffer else { + return now < h.let_go + GIVE_UP_MS; + }; + if crate::host::references(buffer) <= 1 { + gone.extend(h.buffer.take()); + h.let_go = now; } - None - } - } + true + }); + WAITING.fetch_sub((before - held.len()) as u64, Ordering::Relaxed); + gone + }; + // (Released with no lock held: the driver's work.) + drop(gone); + release_pending(); + protect_pending(); + slots_again(); } -/// Something placed elsewhere (`crate::port`) in the same form: counted as -/// [`place_for`] counts, so that [`gone`] takes it off again. -pub(crate) fn counted(window: bool, bytes: u64) { - let at = if window { 0 } else { 2 }; - STATS[at].fetch_add(1, Ordering::Relaxed); - STATS[at + 1].fetch_add(bytes, Ordering::Relaxed); +/// The buffers of the standing holds over `[at, end)` that the tables show +/// no more ([`crate::shadow::in_place_shown`]), as raw interface pointers: +/// those whose descriptor slots are stale. One the tables still show is +/// still the title's memory to the runtime (a heap stands over whole 64 KiB +/// pages, so a free or protection of a page beside a window's bytes is +/// under the window's heap too), and a draw would make its slots again from +/// the same buffer. +fn stale_buffers(at: usize, end: usize) -> Vec<usize> { + let held: Vec<(usize, usize, usize)> = { + let held = HELD.lock().unwrap_or_else(|e| e.into_inner()); + held.iter() + .filter(|h| h.at < end && h.end > at) + .filter_map(|h| Some((h.buffer.as_ref()?.as_raw() as usize, h.at, h.end))) + .collect() + }; + let Some(low) = held.iter().map(|h| h.1).min() else { + return Vec::new(); + }; + let high = held.iter().map(|h| h.2).max().unwrap_or(low); + let shown = crate::shadow::in_place_shown(low as u64, high as u64); + held.into_iter().map(|h| h.0).filter(|b| !shown.contains(b)).collect() } -/// What [`place_for`] gave is gone. -pub(crate) fn gone(window: bool, bytes: u64) { - let at = if window { 0 } else { 2 }; - STATS[at].fetch_sub(1, Ordering::Relaxed); - STATS[at + 1].fetch_sub(bytes, Ordering::Relaxed); +/// The descriptor slots that view a buffer a standing hold has over +/// `[at, end)` let go of it ([`slots_let_go_of`]), if the tables show it no +/// more ([`stale_buffers`]): the title freed, decommitted or protected that +/// memory, and a slot keeps what it views until the title writes it again, +/// which it need not ever do. Returns how many; none with [`slots`] off. +/// `now` as [`crate::descriptor::let_go_of_buffers`] takes it: on for a free +/// (the title is done with the memory on the GPU too), off for a protection +/// (title slots are only made again before they are next read, and let go +/// of once the submissions sent before have run, [`Ripe`]). +fn slots_let_go(at: usize, end: usize, now: bool) -> u32 { + if !slots() { + return 0; + } + slots_let_go_of(&stale_buffers(at, end), now) } -/// Title memory `[at, at + len)` is about to show something else, or the -/// title is about to decommit, free or protect it: what is in place there -/// is let go (the tables forget it; its heap goes when the last list and -/// slot that hold it do). Called for memory the runtime maps anew; for -/// the runtime to call before the title's own `VirtualFree` once it takes -/// that call over. -pub fn title_memory_freeing(at: usize, len: usize) { - // Renderer port 1's regions there: no longer what the title shows. - crate::port::forget(at, len); - if STATS[0].load(Ordering::Relaxed) + STATS[2].load(Ordering::Relaxed) == 0 { - return; +/// The descriptor slots that view one of `buffers` let go of it +/// ([`crate::descriptor::let_go_of_buffers`]). Every slot of every view heap +/// is looked at (a lock each), so not for none. +fn slots_let_go_of(buffers: &[usize], now: bool) -> u32 { + if buffers.is_empty() { + return 0; } - let gone = crate::shadow::in_place_let_go(at as u64, len as u64); - STATS[7].fetch_add(gone, Ordering::Relaxed); + // (No lock of ours held: slots are made under their own locks, and a + // slot made of title memory in place takes [`HELD`]'s, [`hold`].) + let n = crate::descriptor::let_go_of_buffers(buffers, now); + STATS[11].fetch_add(u64::from(n), Ordering::Relaxed); + n } -/// The line of what is in place, every ten seconds while [`level`] is on. -fn say() { +/// [`slots_let_go`] (with `now`) again over the releases a standing hold +/// still keeps waiting ([`PENDING`]) and the protections it does whose +/// submissions sent before have run ([`PROTECTS`], [`Ripe`]), once a second +/// and at once when one has just ripened ([`RIPENED`]): a list that held +/// such a buffer in a dynamic slot of its own gives the slot back when it is +/// reset, and a thread that made a slot of the buffer just before it left +/// the tables made it after the first asking. The slots are looked at once +/// for all of them, and only while some such buffer is out of the tables +/// ([`stale_buffers`]): a few milliseconds on the submitting thread +/// ([`tick`]) for the title's view heap, once a second for as long (the +/// lists that hold the buffer are reset within the bury lag). +/// +/// shortcut: a slot a thread made of a protected buffer just before it left +/// the tables (a lookup that raced the protection) is made null here +/// unasked, while submissions sent since the protection may read it; the +/// slots the protection itself found are made again before they are read. +fn slots_again() { static LAST: AtomicU64 = AtomicU64::new(0); + if !slots() { + return; + } let now = crate::host::now_ms(); let last = LAST.load(Ordering::Relaxed); - if now < last + 10_000 || LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_err() { + if RIPENED.swap(false, Ordering::AcqRel) { + LAST.store(now, Ordering::Relaxed); + } else if now < last + 1000 || LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_err() { return; } - let s: Vec<u64> = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); - tracing::info!( - "title memory in place: {} windows {} MB, {} title buffers {} MB (no copy, no refresh, no copy-back); turned down: {} view memory or not private memory committed whole, \ - {} refused by the host, {} over LEONIDA_INPLACE_MB; {} let go because their memory changed", - s[0], - s[1] >> 20, - s[2], - s[3] >> 20, - s[4], - s[5], - s[6], - s[7] - ); + slots_again_now(); } -/// What a heap is opened on. -pub(crate) enum From { - /// A whole `VirtualAlloc` allocation, by its base address. - Region(usize), - /// A committed part of one: address and bytes. - Part(usize, usize), - /// A section made with `SEC_COMMIT`, by its handle. - Section(usize), +/// [`slots_again`]'s asking, whenever it is due. +fn slots_again_now() { + let mut waiting: Vec<(usize, usize)> = + PENDING.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|p| p.2 == 0).map(|p| (p.0, p.1)).collect(); + waiting.extend( + PROTECTS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter(|p| p.3 == 0 && p.4.load(Ordering::Acquire)) + .map(|p| (p.0, p.1)), + ); + let mut buffers: Vec<usize> = waiting.into_iter().flat_map(|(at, end)| stale_buffers(at, end)).collect(); + buffers.sort_unstable(); + buffers.dedup(); + slots_let_go_of(&buffers, true); } -/// Opens a heap on memory the process has. -pub(crate) fn open(device: &ID3D12Device, from: From) -> windows::core::Result<ID3D12Heap> { - // SAFETY: the calls take an address or a handle and check both - // themselves; a refusal is an error code. - unsafe { - match from { - From::Region(at) => device.cast::<ID3D12Device3>()?.OpenExistingHeapFromAddress(at as *const c_void), - From::Part(at, bytes) => device.cast::<ID3D12Device13>()?.OpenExistingHeapFromAddress1(at as *const c_void, bytes), - From::Section(handle) => device.cast::<ID3D12Device3>()?.OpenExistingHeapFromFileMapping(HANDLE(handle as *mut c_void)), +/// Of `[at, end)`, the parts some hold stands over, in address order, those +/// that touch made one. +fn held_parts(holds: &[(usize, usize)], at: usize, end: usize) -> Vec<(usize, usize)> { + let mut parts: Vec<(usize, usize)> = + holds.iter().filter(|h| h.0 < end && h.1 > at).map(|h| (h.0.max(at), h.1.min(end))).collect(); + parts.sort_unstable(); + let mut joined: Vec<(usize, usize)> = Vec::with_capacity(parts.len()); + for (from, to) in parts { + match joined.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => joined.push((from, to)), } } + joined } -fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { - D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: size.max(1), - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, - Flags: flags, - ..Default::default() +/// Of `[at, end)`, what no part of `held` (as [`held_parts`] gives them) +/// covers, in address order. +fn free_parts(held: &[(usize, usize)], at: usize, end: usize) -> Vec<(usize, usize)> { + let mut free = Vec::new(); + let mut from = at; + for &(h0, h1) in held { + if h0 > from { + free.push((from, h0)); + } + from = from.max(h1); } + if from < end { + free.push((from, end)); + } + free } -/// A buffer of `size` bytes at `offset` (a multiple of 64 KiB) of an -/// opened heap, which shaders may read and write, in the common state. -pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: u64) -> windows::core::Result<ID3D12Resource> { - let mut placed: Option<ID3D12Resource> = None; - // The heap is cross-adapter shared, so the buffer must say so too. - let flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - // SAFETY: plain creation in a live heap. - unsafe { device.CreatePlacedResource(heap, offset, &buffer_desc(size, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut placed)? }; - let placed = placed.ok_or_else(windows::core::Error::empty)?; - #[cfg(feature = "diagnostics")] - crate::census::placed(&placed, "buffers placed in title memory"); - Ok(placed) +/// What [`HELD`] stands over, as (first byte, end): the holds that stand, +/// and those let go of lately. +fn holds_now() -> (Vec<(usize, usize)>, Vec<(usize, usize)>) { + let held = HELD.lock().unwrap_or_else(|e| e.into_inner()); + let (standing, let_go): (Vec<&Hold>, Vec<&Hold>) = held.iter().partition(|h| h.buffer.is_some()); + (standing.iter().map(|h| (h.at, h.end)).collect(), let_go.iter().map(|h| (h.at, h.end)).collect()) } -// The title's views of its physical pages, as the runtime maps them: the -// census needs them to say which view memory is one run of a section (one -// placed buffer could show it) and which is scattered pages. - -struct Views { - /// By address: bytes, the section's handle, the offset in it. - views: BTreeMap<usize, (usize, usize, u64)>, - /// By section and byte offset of a 64 KiB page: the address of that - /// page in every view that shows it. A write through one view of a - /// page is a write of the bytes every other view shows - /// (`crate::watch` guards them all). - pages: BTreeMap<(usize, u64), Vec<usize>>, - /// Of those, how many are shown more than once. - pages_twice: usize, - /// Sections by handle: bytes, and whether made committed. (In maps, not - /// vectors looked through: with `LEONIDA_SECTION_MB` an allocation of the - /// title's is thousands of sections, and [`beside`] and [`beside_page`] - /// look one up for every landing and every store of the title's that is - /// made beside the guards; after Fayberr's fork fa064482 and - /// LooperSalty's ee8b92e, GPL-3.0, which changed the same with their - /// small sections.) - sections: BTreeMap<usize, (u64, bool)>, - /// Our own view of a whole section, by its handle (0: the host gave - /// none), made when first asked for ([`beside`]) and kept. - whole: BTreeMap<usize, usize>, +/// The host let the title free `[at, end)` (a release or a decommit it +/// did): no heap keeps those pages any more, so the holds let go of lately +/// ([`HELD`]) are forgotten over them, and one that reaches past them keeps +/// the rest. Noted on for [`GIVE_UP_MS`], such a hold stood over whatever +/// memory the title was given at those addresses next and was taken for a +/// heap in the way of its frees there: a decommit of the new memory beside +/// a hold let go of just then was cut where the old hold had been, and the +/// part it joined with the new one's pages, which the host still refused, +/// was kept committed and zeroed ([`title_memory_free_held`]) instead of +/// decommitted. +fn holds_freed(at: usize, end: usize) { + let mut held = HELD.lock().unwrap_or_else(|e| e.into_inner()); + if !held.iter().any(|h| h.buffer.is_none() && h.at < end && h.end > at) { + return; + } + let before = held.len(); + let mut rest = Vec::new(); + held.retain(|h| { + if h.buffer.is_some() || h.at >= end || h.end <= at { + return true; + } + rest.extend(free_parts(&[(at, end)], h.at, h.end).into_iter().map(|(a, b)| Hold { at: a, end: b, buffer: None, let_go: h.let_go })); + false + }); + held.extend(rest); + let after = held.len(); + drop(held); + if after > before { + WAITING.fetch_add((after - before) as u64, Ordering::Relaxed); + } else { + WAITING.fetch_sub((before - after) as u64, Ordering::Relaxed); + } } -/// Read by many threads at once (write faults, landings), changed when the -/// runtime maps or unmaps. -static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views { - views: BTreeMap::new(), - pages: BTreeMap::new(), - pages_twice: 0, - sections: BTreeMap::new(), - whole: BTreeMap::new(), -}); +/// The pending releases no standing hold is in the way of any more, tried +/// again. (One let go of lately is not waited for: its heap is gone, and +/// the host lets go of the pages when it does.) +fn release_pending() { + let (holds, _) = holds_now(); + let now = crate::host::now_ms().max(1); + let mut released = Vec::new(); + let mut pending = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + let before = pending.len(); + pending.retain_mut(|(at, end, clear)| { + if !held_parts(&holds, *at, *end).is_empty() { + *clear = 0; + return true; + } + let _going = crate::texture::title_memory_going(*at, *end - *at); + // SAFETY: an allocation the title released, kept reserved for it + // since: nothing else is at the address. + if unsafe { mem::VirtualFree(*at as *mut c_void, 0, mem::MEM_RELEASE) } != 0 { + released.push((*at, *end)); + return false; + } + if *clear == 0 { + *clear = now; + return true; + } + if now < *clear + GIVE_UP_MS { + return true; + } + STATS[10].fetch_add(1, Ordering::Relaxed); + tracing::warn!( + at = format_args!("{at:#x}"), + bytes = *end - *at, + error = %std::io::Error::last_os_error(), + "the title's release of memory that was in place is still refused with no heap over it: given up (the allocation stays)" + ); + false + }); + WAITING.fetch_sub((before - pending.len()) as u64, Ordering::Relaxed); + drop(pending); + for (at, end) in released { + holds_freed(at, end); + decommitted_gone(at, end); + } +} -fn views() -> std::sync::RwLockReadGuard<'static, Views> { - VIEWS.read().unwrap_or_else(|e| e.into_inner()) +/// The allocation `at` lies in: its base and end, from the host's account +/// of it; `None` for memory that is free. +fn allocation_of(at: usize) -> Option<(usize, usize)> { + let ask = |address: usize| { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(address as *const c_void, &mut info, size_of_val(&info)) }; + (n != 0 && info.State != mem::MEM_FREE) + .then(|| (info.AllocationBase as usize, (info.BaseAddress as usize).saturating_add(info.RegionSize))) + }; + let (base, mut end) = ask(at)?; + while let Some((_, next)) = ask(end).filter(|&(b, _)| b == base) { + end = next; + } + Some((base, end)) } -fn views_mut() -> std::sync::RwLockWriteGuard<'static, Views> { - VIEWS.write().unwrap_or_else(|e| e.into_inner()) +/// What the title's `VirtualFree(at, len, kind)` frees, as the host takes +/// it: the whole allocation for a release or a decommit with no size at +/// its base, else the 4 KiB pages of a decommit (cut to the allocation); +/// `None` for any other call, or memory that is free. +fn freed_pages(at: usize, len: usize, kind: u32) -> Option<(usize, usize)> { + let (base, end) = allocation_of(at)?; + match kind { + mem::MEM_RELEASE | mem::MEM_DECOMMIT if len == 0 && at == base => Some((base, end)), + mem::MEM_DECOMMIT if len != 0 => Some((at & !0xfff, at.saturating_add(len).next_multiple_of(0x1000).min(end))), + _ => None, + } } -/// The runtime made a section of `bytes` for physical pages; `committed` -/// if with `SEC_COMMIT` (only such a section can be opened as a heap). -pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { - let mut v = views_mut(); - // A handle's number given out again: the view was of the section that - // had it before (it stays mapped: someone may be writing through it). - v.whole.remove(§ion); - v.sections.insert(section, (bytes, committed)); +/// Whether `[at, at + len)` (`len` 0: the allocation at `at`) lies in an +/// allocation the title released whose release is kept for a heap +/// ([`PENDING`]): memory that is free to the title. +fn released_already(at: usize, len: usize) -> bool { + let end = at.saturating_add(len.max(1)); + PENDING.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|p| p.0 < end && p.1 > at) } -/// The runtime lets go of a section, and of its handle: no view the title -/// sees is of it any more, and [`beside`]'s view goes. -pub fn title_memory_section_gone(section: usize) { - let whole = { - let mut v = views_mut(); - v.whole.remove(§ion) +/// The title's `VirtualFree(at, len, kind)` was refused with error 87 +/// (`ERROR_INVALID_PARAMETER`): if a heap opened in place is what refuses +/// it (a hold stands over the memory, or was let go of lately: [`HELD`]), +/// the free is taken over and `true` returned, for the title to be told it +/// is done; `false` (nothing asked of the host, the last error as it was) +/// if not, or with [`frees`] off. +/// +/// What was in place there was let go before the call +/// ([`title_memory_freeing`]), and the descriptor slots that show it let go +/// of it here ([`slots_let_go`]), but its heap stands until the submissions +/// that may use it have run ([`crate::host::retire`]) and the lists that +/// hold it in slots of their own are reset: not at once. So: +/// +/// - A release (`MEM_RELEASE`, the whole allocation) is tried again here +/// after [`reap`], and if still refused kept ([`PENDING`]): the +/// allocation stays reserved, so nothing else comes to its addresses, +/// and is released when no hold stands over it ([`release_pending`], +/// from [`tick`]). +/// - A decommit (`MEM_DECOMMIT`) decommits now what no hold stands over +/// (cut where holds let go of lately were, whose pages the host may +/// still keep: one call is all or nothing), and zeroes what of it the +/// host still refuses and what holds stand over (pages the title commits +/// again read as zeros, as decommitted pages do), which stays committed +/// until the title releases the allocation, and reads as reserved to its +/// `XMemVirtualQuery` meanwhile ([`DECOMMITTED`]). Decommitting it later +/// instead could take pages the title has committed again since and is +/// writing: its own `VirtualAlloc` is the runtime's now (`leonida_hle`'s +/// xmem, [`title_memory_alloc`]), but a commit between the look and the +/// decommit would lose its pages all the same, and a call the runtime +/// does not take (`NtAllocateVirtualMemory`) is never seen. +pub(crate) fn title_memory_free_held(at: usize, len: usize, kind: u32) -> bool { + if !frees() || WAITING.load(Ordering::Relaxed) == 0 { + return false; + } + let Some((from, to)) = freed_pages(at, len, kind) else { + return false; }; - if let Some(base) = whole.filter(|&base| base != 0) { - // SAFETY: a view of ours. Who writes through it found the section - // in a view the title saw and holds off its unmapping - // (`crate::watch::title_memory_reading`), which came before this. - unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: base as *mut c_void }) }; + let (standing, let_go) = holds_now(); + if held_parts(&standing, from, to).is_empty() && held_parts(&let_go, from, to).is_empty() { + return false; } + // The slots that view a buffer placed there let go of it (the title + // gave the memory up; not one a window beside it in the same 64 KiB + // page still shows), then what nothing else holds goes. (What this + // lets go of stays noted, [`HELD`]: its pages are still seen to below.) + slots_let_go(from, to, true); + reap(); + if kind == mem::MEM_RELEASE { + // (Free memory to the title now, whether released now or later: + // what it decommitted there before is nothing of its any more.) + decommitted_gone(from, to); + // SAFETY: the title's own release of its allocation. + if unsafe { mem::VirtualFree(at as *mut c_void, 0, mem::MEM_RELEASE) } == 0 { + let mut pending = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + // (Once only: a second note would outlive the release it is of.) + if !pending.iter().any(|p| p.0 == from && p.1 == to) { + STATS[8].fetch_add(1, Ordering::Relaxed); + pending.push((from, to, 0)); + WAITING.fetch_add(1, Ordering::Relaxed); + } + } else { + holds_freed(from, to); + } + return true; + } + let (standing, let_go) = holds_now(); + let held = held_parts(&standing, from, to); + let mut kept = false; + for (a, b) in free_parts(&held, from, to) { + let late = held_parts(&let_go, a, b); + for (c, d) in free_parts(&late, a, b).into_iter().chain(late) { + // SAFETY: pages of the title's allocation it asked to decommit. + if unsafe { mem::VirtualFree(c as *mut c_void, d - c, mem::MEM_DECOMMIT) } == 0 { + kept |= zero_committed(c, d); + decommitted_kept(c, d); + } else { + holds_freed(c, d); + decommitted_gone(c, d); + } + } + } + for &(a, b) in &held { + // (Under a heap opened in place: committed and read-write when it + // was opened, and neither can change while it stands.) + kept |= zero_committed(a, b); + decommitted_kept(a, b); + } + if kept { + STATS[9].fetch_add(1, Ordering::Relaxed); + } + true } -/// The runtime mapped `[at, at + len)` as a view of `section` from -/// `offset` on. Call after [`crate::title_memory_remapped`] of the range. -pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { - { - let mut v = views_mut(); - v.views.insert(at, (len, section, offset)); - for k in 0..len.div_ceil(K64) { - let shown = v.pages.entry((section, offset + (k * K64) as u64)).or_default(); - shown.push(at + k * K64); - let twice = shown.len() == 2; - v.pages_twice += usize::from(twice); +/// The title's `VirtualFree(at, len, kind)`, which `leonida_hle`'s xmem +/// takes; `free` is the host's call (xmem's, with what it notes of the +/// memory around it). What the GPU side noted of the memory goes first +/// ([`crate::watch::title_memory_freed`]: the address may be other +/// memory's the moment it is free; not for splitting or joining +/// placeholders, which changes nothing they show), then `free` runs, and a +/// free the host refused with error 87 goes to [`title_memory_free_held`]; +/// what of the holds let go of lately lies over memory the host did free +/// is forgotten ([`holds_freed`]). Returns what the title is told: `TRUE` +/// for a free taken over, else `free`'s answer, with the thread's last +/// error as `free` left it. +pub fn title_memory_free(at: usize, len: usize, kind: u32, free: impl FnOnce() -> i32) -> i32 { + use windows_sys::Win32::Foundation::{ERROR_INVALID_ADDRESS, ERROR_INVALID_PARAMETER, GetLastError, SetLastError}; + // Not while the opener opens memory ([`GATE`]). + let _gate = gate_shared(); + // Memory the title released already, the release kept for a heap + // ([`PENDING`]), is free memory to the title: a free of it is refused as + // the host refuses one of free memory, and nothing is done. Before, a + // second release of it was taken over again and noted twice, and the + // note left over once the first was done released whatever the host + // gave out at that address next, under its new owner. + if WAITING.load(Ordering::Relaxed) != 0 && released_already(at, len) { + // SAFETY: the thread's last error, as the host's call would leave it. + unsafe { SetLastError(ERROR_INVALID_ADDRESS) }; + return 0; + } + // Not while a texture is detiled from these pages in place + // (`crate::texture::title_memory_going`). + let _going = crate::texture::title_memory_going(at, len); + /// Not in windows-sys' memory module. + const MEM_COALESCE_PLACEHOLDERS: u32 = 1; + let freeing = kind & (mem::MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS) == 0; + // What the free takes, asked before it: a released allocation is not + // there to ask about after. (Only while something is noted.) + let mut pages = None; + if freeing { + crate::watch::title_memory_freed(at, len); + protects_freed(at, len, kind); + if WAITING.load(Ordering::Relaxed) != 0 || DECOMMITTED_ANY.load(Ordering::Acquire) { + pages = freed_pages(at, len, kind); } } - // This view is writable from now on: a guard over the same bytes at - // another view must look at them again, and the pages are noted written - // there (`crate::watch`). - crate::watch::views_mapped(section, offset, len); + let freed = free(); + if freed != 0 + && let Some((from, to)) = pages + { + holds_freed(from, to); + decommitted_gone(from, to); + } + if freed != 0 || !freeing { + return freed; + } + // SAFETY: a plain read of the thread's last error. + let error = unsafe { GetLastError() }; + if error == ERROR_INVALID_PARAMETER && title_memory_free_held(at, len, kind) { + return 1; + } + // SAFETY: the thread's last error set back to the host's. + unsafe { SetLastError(error) }; + freed } -/// What `[at, at + len)` showed is gone ([`crate::title_memory_remapped`]): -/// the views that touch it are forgotten (the runtime tells again those it -/// maps anew). -pub(crate) fn views_gone(at: usize, len: usize) { - let mut v = views_mut(); - if v.views.is_empty() { - return; +/// The 4 KiB pages that hold `[at, at + len)`, as the host's protection +/// takes them: the first, and the end. +fn host_pages(at: usize, len: usize) -> (usize, usize) { + (at & !0xfff, at.saturating_add(len.max(1)).next_multiple_of(0x1000)) +} + +/// Of the protections that wait ([`PROTECTS`]), the newest over any of +/// `[at, end)`: the one the title last asked for there, which is what it +/// takes the memory's protection to be. +fn protect_waits(at: usize, end: usize) -> Option<u32> { + if WAITING.load(Ordering::Relaxed) == 0 { + return None; } - let end = at.saturating_add(len); - let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base); - let gone: Vec<usize> = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect(); - for base in gone { - let Some((bytes, section, offset)) = v.views.remove(&base) else { - continue; - }; - for k in 0..bytes.div_ceil(K64) { - let key = (section, offset + (k * K64) as u64); - if let Some(pages) = v.pages.get_mut(&key) { - let page = base + k * K64; - let before = pages.len(); - pages.retain(|&shown| shown != page); - let after = pages.len(); - if after == 0 { - v.pages.remove(&key); - } - v.pages_twice = v.pages_twice.saturating_sub(usize::from(before >= 2 && after < 2)); - } - } + PROTECTS.lock().unwrap_or_else(|e| e.into_inner()).iter().rev().find(|p| p.0 < end && p.1 > at).map(|p| p.2) +} + +/// Whether the protection `new` is one the host could make: a single kind +/// of access (the low byte), whatever modifiers follow. One the host would +/// refuse anyway is not taken over: its error 87 is the title's. +fn host_protection(new: u32) -> bool { + (new & 0xff).is_power_of_two() +} + +/// Whether the protection `new` gives execute access, which pages under a +/// heap lack (they are read-write: a heap opens only such pages). Made late +/// ([`PROTECTS`]), a protection that takes access away costs the title at +/// most a fault it expected and did not get; execute made late is a fault +/// where it expects none (code it wrote and made executable, jumped to +/// before the heap is gone: a DEP violation). So that part is made at once +/// ([`protect_later`]). +fn adds_execute(new: u32) -> bool { + new & 0xf0 != 0 +} + +/// The title's `VirtualProtect(at, len, new, old)`, which `leonida_hle`'s +/// xmem takes; `protect` is the host's call with those arguments. Returns +/// what the title is told: `TRUE` for a protection taken over, else +/// `protect`'s answer, with the thread's last error as it left it. +/// +/// While a heap opened in place stands over the pages the host refuses the +/// call with error 87 (the probe shows it). So when it does and a hold of +/// ours stands over them (or was let go of lately, [`HELD`]): +/// +/// - what is in place under those heaps, over their whole 64 KiB pages, is +/// let go ([`let_go_under`]: the next ask makes a copy, or opens the +/// memory anew once it is read-write and nothing waits over it, +/// [`place_for`]), the descriptor slots that view its buffers are made +/// again before they are next read and let go of them once the +/// submissions sent before have run ([`Ripe`]), and what nothing else +/// holds goes ([`reap`]); then the host is asked again. +/// - If it still refuses (the heap stands until the submissions that may +/// use it have run, [`crate::host::retire`]), the protection waits +/// ([`PROTECTS`]) and is made when no hold stands over the pages +/// ([`protect_pending`], from [`tick`]); the title is told it is done, +/// with the protection the pages have now as the old one. +/// +/// A protection of pages one already waits over waits behind it, whatever +/// the host would say now: made first, it would be undone by the older one +/// made later. Its old protection is the newest that waits there, and what +/// is in place under the heaps it adds is let go as above. A free +/// of the pages takes what waits over them away ([`protects_freed`]). +/// +/// What this costs the title while a protection waits (until the bury lag's +/// submissions have run, about two frames): the pages keep the access they +/// had (read-write: a heap opens only such pages), so a write the title +/// meant to fault does not, and its own `VirtualQuery` sees the old +/// protection. Access taken away and given back again is made in that +/// order, so it ends as asked. Execute access the title adds is made at +/// once ([`adds_execute`], [`protect_later`]): the host takes a protection +/// that gives more access under a heap (execute-read-write over read-write) +/// and refuses only one that gives less (measured on WARP: read-only, +/// execute-read, execute, no access and guard pages all error 87); a +/// protection of execute without write gives write up later, as the others. +/// +/// Read-write given back to pages a heap stood over when access was taken +/// away from them asks for the copies made there since to be opened in +/// place again ([`again`]). +pub fn title_memory_protect(at: usize, len: usize, new: u32, old: *mut u32, protect: impl Fn() -> i32) -> i32 { + // As a free ([`GATE`]). + let _gate = gate_shared(); + let done = protect_title(at, len, new, old, protect); + if done != 0 && new == mem::PAGE_READWRITE { + let (from, to) = host_pages(at, len); + again(from, to); } + done } -/// The 64 KiB pages of `[start, end)` that the title shows at other -/// addresses too, in address order, each with those; not the ones it shows -/// in very many views (`crate::watch::MANY_VIEWS`). -pub(crate) fn shown_elsewhere(start: usize, end: usize) -> Vec<(usize, Vec<usize>)> { - let v = views(); - let mut out = Vec::new(); - if start >= end || v.pages_twice == 0 { - return out; +/// [`title_memory_protect`]'s work, under [`GATE`]. +fn protect_title(at: usize, len: usize, new: u32, old: *mut u32, protect: impl Fn() -> i32) -> i32 { + use windows_sys::Win32::Foundation::{ERROR_INVALID_PARAMETER, GetLastError, SetLastError}; + // As a free (`crate::texture::title_memory_going`). + let _going = crate::texture::title_memory_going(at, len); + // (No old protection to write: the host's refusal is the title's.) + if !protects() || !frees() || old.is_null() || !host_protection(new) || WAITING.load(Ordering::Relaxed) == 0 { + return protect(); } - let first = v.views.range(..=start).next_back().filter(|(base, view)| *base + view.0 > start).map(|(base, _)| *base); - for (&base, &(bytes, section, offset)) in v.views.range(first.unwrap_or(start)..end) { - let from = start.max(base) & !(K64 - 1); - for page in (from..end.min(base + bytes)).step_by(K64) { - let Some(shown) = v.pages.get(&(section, offset + (page - base) as u64)) else { - continue; - }; - if (2..=crate::watch::MANY_VIEWS).contains(&shown.len()) { - out.push((page, shown.iter().copied().filter(|&at| at != page).collect())); - } + let (from, to) = host_pages(at, len); + if let Some(shown) = protect_waits(from, to) { + let ripe = let_go_under(from, to); + if protect_later(from, to, new, old, Some(shown), ripe) { + return 1; } + // SAFETY: the thread's last error set as the host's refusal under + // a heap sets it. + unsafe { SetLastError(ERROR_INVALID_PARAMETER) }; + return 0; } - out + let done = protect(); + if done != 0 { + return done; + } + // SAFETY: a plain read of the thread's last error. + let error = unsafe { GetLastError() }; + if error == ERROR_INVALID_PARAMETER && title_memory_protect_held(from, to, new, old, &protect) { + return 1; + } + // SAFETY: the thread's last error set back to the host's. + unsafe { SetLastError(error) }; + done } -/// The 64 KiB pages at other addresses that show a page of `[start, end)`, -/// however many views show it (unlike [`shown_elsewhere`]); `None` if they are -/// more than `most`. -pub(crate) fn shown_anywhere_else(start: usize, end: usize, most: usize) -> Option<Vec<usize>> { - let v = views(); - let mut out = Vec::new(); - if start >= end || v.pages_twice == 0 { - return Some(out); +/// [`title_memory_protect`] for a protection of the pages `[from, to)` the +/// host refused with error 87: `true` if a hold is what refuses it and it +/// was made or waits ([`PROTECTS`]); `false` (nothing waits) if not. +fn title_memory_protect_held(from: usize, to: usize, new: u32, old: *mut u32, protect: &impl Fn() -> i32) -> bool { + let (standing, let_go) = holds_now(); + if held_parts(&standing, from, to).is_empty() && held_parts(&let_go, from, to).is_empty() { + return false; } - let first = v.views.range(..=start).next_back().filter(|(base, view)| *base + view.0 > start).map(|(base, _)| *base); - for (&base, &(bytes, section, offset)) in v.views.range(first.unwrap_or(start)..end) { - let from = start.max(base) & !(K64 - 1); - for page in (from..end.min(base + bytes)).step_by(K64) { - let Some(shown) = v.pages.get(&(section, offset + (page - base) as u64)) else { - continue; - }; - if shown.len() < 2 { - continue; - } - if out.len() + shown.len() - 1 > most { - return None; - } - out.extend(shown.iter().copied().filter(|&at| at != page)); - } + let ripe = let_go_under(from, to); + reap(); + if protect() != 0 { + return true; } - Some(out) + protect_later(from, to, new, old, None, ripe) } -/// The address of the 64 KiB page shown at `page` in every title view that -/// shows it, `page`'s own address included; empty if `page` is not a view. -pub(crate) fn pages_of(page: usize) -> Vec<usize> { - let v = views(); - let Some((&base, &(bytes, section, offset))) = v.views.range(..=page).next_back() else { - return Vec::new(); - }; - let within = page.wrapping_sub(base); - if within >= bytes || !within.is_multiple_of(K64) { - return Vec::new(); +/// What is in place under the heaps that stand over the pages `[from, to)` +/// is let go ([`title_memory_freeing`], over each heap's whole 64 KiB +/// pages), and the descriptor slots that view their buffers let go of them +/// ([`slots_let_go`]), for a protection of those pages: the host refuses one +/// of any 4 KiB page under a heap, and the heap goes only when nothing shows +/// its buffer. Let go of over the protected bytes alone, a window whose +/// bytes lie beside them in the same 64 KiB page stayed in the tables, and +/// the protection waited for as long. +/// +/// The title may go on reading protected memory on the GPU, so its slots +/// are not made null at once: they are made again before they are next read +/// and go on showing the buffer until then (still the title's memory while +/// the heap stands), and are made null once the submissions sent before +/// have run (the returned flag, [`Ripe`]; [`slots_again`]). Made null at +/// once, a submission sent before that read a title slot by index read +/// zeros for memory the title still held valid. +fn let_go_under(from: usize, to: usize) -> Arc<AtomicBool> { + let (standing, _) = holds_now(); + let under: Vec<(usize, usize)> = standing.into_iter().filter(|h| h.0 < to && h.1 > from).collect(); + for &(at, end) in &under { + title_memory_freeing(at, end - at); } - v.pages.get(&(section, offset + within as u64)).cloned().unwrap_or_default() + if !under.is_empty() { + slots_let_go(from, to, false); + // (After the let-go, which forgets what was noted there.) + again_noted(&under); + } + let ripe = Arc::new(AtomicBool::new(false)); + crate::host::retire(Ripe(ripe.clone())); + ripe } -/// The title views that show any of the physical bytes `[offset, offset + -/// len)` of `section`, as `(address, bytes)` ranges in address order; not -/// those of a page shown in very many views (`MANY_VIEWS`). -pub(crate) fn views_of_section(section: usize, offset: u64, len: usize) -> Vec<(usize, usize)> { - if len == 0 { - return Vec::new(); +/// The protection `new` of the pages `[from, to)` waits ([`PROTECTS`]), +/// its slots let go of once `ripe` ([`Ripe`]); the title is told the old +/// one: `shown` (the newest that waits there), else what the host says the +/// first page has. Execute access `new` gives is made now, with write kept +/// ([`adds_execute`]); if the host refuses even that, nothing waits and +/// `false` is returned, for the title to be refused (told done, it would +/// fault where it expects none). +fn protect_later(from: usize, to: usize, new: u32, old: *mut u32, shown: Option<u32>, ripe: Arc<AtomicBool>) -> bool { + let was = shown.unwrap_or_else(|| { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + unsafe { mem::VirtualQuery(from as *const c_void, &mut info, size_of_val(&info)) }; + info.Protect + }); + // (Under the lock [`protect_pending`] makes them under: none it makes + // comes between, to be undone by this one.) + let mut protects = PROTECTS.lock().unwrap_or_else(|e| e.into_inner()); + let mut before = 0; + // SAFETY: pages of the title's whose protection it asked for, given + // more access than they have. + if adds_execute(new) && unsafe { mem::VirtualProtect(from as *const c_void, to - from, mem::PAGE_EXECUTE_READWRITE, &mut before) } == 0 { + return false; } - let v = views(); - let end = offset.saturating_add(len as u64); - let mut pages: Vec<usize> = Vec::new(); - let mut at = offset - offset % K64 as u64; - while at < end { - if let Some(shown) = v.pages.get(&(section, at)) - && shown.len() <= crate::watch::MANY_VIEWS - { - pages.extend(shown.iter().copied()); + // SAFETY: the title's out pointer (checked not null), written as the + // host would have. + unsafe { old.write_unaligned(was) }; + STATS[12].fetch_add(1, Ordering::Relaxed); + protects.push((from, to, new, 0, ripe)); + WAITING.fetch_add(1, Ordering::Relaxed); + true +} + +/// The protections that wait ([`PROTECTS`]), made in order where no +/// standing hold is in the way any more and no older one over the same +/// pages still waits. One the host refuses with another error than 87 (the +/// pages went) is dropped; one it still refuses [`GIVE_UP_MS`] after no hold +/// was in the way is given up on (said each time). +fn protect_pending() { + use windows_sys::Win32::Foundation::{ERROR_INVALID_PARAMETER, GetLastError}; + if WAITING.load(Ordering::Relaxed) == 0 { + return; + } + let (holds, _) = holds_now(); + let now = crate::host::now_ms().max(1); + let mut protects = PROTECTS.lock().unwrap_or_else(|e| e.into_inner()); + if protects.is_empty() { + return; + } + let before = protects.len(); + let mut waiting: Vec<(usize, usize)> = Vec::new(); + let mut writable: Vec<(usize, usize)> = Vec::new(); + protects.retain_mut(|(at, end, new, clear, _)| { + if !held_parts(&holds, *at, *end).is_empty() { + *clear = 0; + waiting.push((*at, *end)); + return true; } - match at.checked_add(K64 as u64) { - Some(next) => at = next, - None => break, + if waiting.iter().any(|w| w.0 < *end && w.1 > *at) { + waiting.push((*at, *end)); + return true; } - } - pages.sort_unstable(); - pages.dedup(); - let mut runs: Vec<(usize, usize)> = Vec::with_capacity(pages.len()); - for page in pages { - match runs.last_mut() { - Some((first, bytes)) if *first + *bytes == page => *bytes += K64, - _ => runs.push((page, K64)), + let mut old = 0; + let _going = crate::texture::title_memory_going(*at, *end - *at); + // SAFETY: pages of the title's whose protection it asked for. + if unsafe { mem::VirtualProtect(*at as *const c_void, *end - *at, *new, &mut old) } != 0 { + if *new == mem::PAGE_READWRITE { + writable.push((*at, *end)); + } + return false; + } + // SAFETY: a plain read of the thread's last error. + let error = unsafe { GetLastError() }; + if error == ERROR_INVALID_PARAMETER && (*clear == 0 || now < *clear + GIVE_UP_MS) { + if *clear == 0 { + *clear = now; + } + waiting.push((*at, *end)); + return true; } + STATS[13].fetch_add(1, Ordering::Relaxed); + tracing::warn!( + at = format_args!("{at:#x}"), + bytes = *end - *at, + protect = format_args!("{new:#x}"), + error = %std::io::Error::from_raw_os_error(error as i32), + "the title's protection of memory that was in place is still refused with no heap over it: given up" + ); + false + }); + WAITING.fetch_sub((before - protects.len()) as u64, Ordering::Relaxed); + drop(protects); + for (from, to) in writable { + again(from, to); } - runs } -/// How many bytes of `[at, at + len)` views of physical pages show; `None` -/// if no view touches it (nothing is mapped there, or memory of another -/// kind). The runtime's own record of what it mapped: no question to the -/// host. -pub(crate) fn shown_bytes(at: usize, len: usize) -> Option<u64> { - let end = at.saturating_add(len); - let v = views(); - let first = v.views.range(..=at).next_back(); - let rest = v.views.range(at.saturating_add(1)..end.max(at.saturating_add(1))); - let (mut there, mut any) = (0u64, false); - for (&base, view) in first.into_iter().chain(rest) { - let (from, to) = (base.max(at), base.saturating_add(view.0).min(end)); - if from < to { - there += (to - from) as u64; - any = true; +/// The title frees `[at, at + len)` (`kind` as `VirtualFree` takes it): the +/// protections that wait over it ([`PROTECTS`]) are cut to what is left +/// (nothing of the allocation, for a release). +fn protects_freed(at: usize, len: usize, kind: u32) { + if WAITING.load(Ordering::Relaxed) == 0 { + return; + } + let (from, to) = if kind & mem::MEM_RELEASE != 0 { + match allocation_of(at) { + Some(whole) => whole, + None => return, } + } else { + host_pages(at, len) + }; + let mut protects = PROTECTS.lock().unwrap_or_else(|e| e.into_inner()); + if !protects.iter().any(|p| p.0 < to && p.1 > from) { + return; + } + let before = protects.len(); + let cut: Vec<(usize, usize, u32, u64, Arc<AtomicBool>)> = protects + .iter() + .flat_map(|&(a, b, new, clear, ref ripe)| { + let parts = if a < to && b > from { free_parts(&[(from, to)], a, b) } else { vec![(a, b)] }; + parts.into_iter().map(move |(a, b)| (a, b, new, clear, ripe.clone())) + }) + .collect(); + *protects = cut; + let after = protects.len(); + drop(protects); + if after > before { + WAITING.fetch_add((after - before) as u64, Ordering::Relaxed); + } else { + WAITING.fetch_sub((before - after) as u64, Ordering::Relaxed); } - any.then_some(there) } -/// What of `[at, at + len)` views of physical pages show, in order, pieces -/// that touch as one: (address, bytes). Empty: nothing, or memory of another -/// kind. -pub(crate) fn shown_runs(at: usize, len: usize) -> Vec<(usize, usize)> { - let end = at.saturating_add(len); - let v = views(); - let first = v.views.range(..=at).next_back(); - let rest = v.views.range(at.saturating_add(1)..end.max(at.saturating_add(1))); - let mut runs: Vec<(usize, usize)> = Vec::new(); - for (&base, view) in first.into_iter().chain(rest) { - let (from, to) = (base.max(at), base.saturating_add(view.0).min(end)); - if from >= to { - continue; - } - match runs.last_mut() { - Some((run, bytes)) if *run + *bytes == from => *bytes += to - from, - _ => runs.push((from, to - from)), - } +/// The title's decommits a heap opened in place was in the way of, kept +/// committed and zeroed instead ([`title_memory_free_held`]): the pages, as +/// (first byte, end, the host's allocation base), in address order, those +/// that touch in the same allocation made one (two allocations side by side +/// are not: [`decommit_noted`]). Memory +/// the title asked to be reserved: it reads so to the title's query +/// ([`title_memory_as_asked`], [`query_decommits`]). Forgotten where the +/// title gets memory there again ([`title_memory_alloc`]: a commit, or a new +/// reservation over a record gone stale) and where the host frees the pages +/// (a decommit or release it did, at once or later: [`decommitted_gone`]). +/// +/// shortcut: a commit the runtime does not take (`NtAllocateVirtualMemory`, +/// which nothing in the repository says the title imports) leaves the pages +/// reading as reserved until the title decommits or releases them. +static DECOMMITTED: std::sync::Mutex<Vec<(usize, usize, usize)>> = std::sync::Mutex::new(Vec::new()); + +/// Whether [`DECOMMITTED`] holds any. +static DECOMMITTED_ANY: AtomicBool = AtomicBool::new(false); + +/// The title's decommit of `[at, end)` is kept committed and zeroed +/// ([`DECOMMITTED`]), noted by the allocation each of its pages is in (the +/// host's `AllocationBase`: committed, they have one). +fn decommitted_kept(at: usize, end: usize) { + let mut from = at; + while from < end { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(from as *const c_void, &mut info, size_of_val(&info)) }; + let to = if n == 0 { end } else { (info.BaseAddress as usize).saturating_add(info.RegionSize).clamp(from + 1, end) }; + let base = if n == 0 { 0 } else { info.AllocationBase as usize }; + decommit_noted(&mut DECOMMITTED.lock().unwrap_or_else(|e| e.into_inner()), from, to, base); + from = to; + } + if end > at { + DECOMMITTED_ANY.store(true, Ordering::Release); } - runs } -/// How the views cover `[at, at + len)`. -#[derive(Debug, PartialEq, Eq, Clone, Copy)] -pub(crate) enum Cover { - /// No view holds its first byte. - None, - /// Views hold a part of it only. - Holes, - /// Views hold all of it, from more than one place. - Scattered, - /// All of it is one run of one section: the section and the offset of - /// `at` in it. - Run(usize, u64), +/// `[from, to)` of the allocation at `base` noted among the decommits kept +/// (`kept`, as [`DECOMMITTED`] has them), joined with those of the same +/// allocation it touches or overlaps. Not with those of another: host +/// allocations are 64 KiB pages and often side by side, and a record that +/// ran from one into the next would have the title's query tell a region +/// over two allocations ([`as_asked`]), which `VirtualQuery` never does. +fn decommit_noted(kept: &mut Vec<(usize, usize, usize)>, from: usize, to: usize, base: usize) { + if to <= from { + return; + } + let (mut from, mut to) = (from, to); + // (Those noted of one allocation never touch one another: whatever + // touches the new range touches it, not only what it is joined with.) + kept.retain(|&(a, b, of)| { + let joined = of == base && a <= to && b >= from; + if joined { + (from, to) = (from.min(a), to.max(b)); + } + !joined + }); + let place = kept.partition_point(|&(a, _, _)| a < from); + kept.insert(place, (from, to, base)); } -fn cover_in(views: &BTreeMap<usize, (usize, usize, u64)>, at: usize, len: usize) -> Cover { - let end = at + len.max(1); - let Some((&base, &(bytes, section, offset))) = views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at) else { - return Cover::None; - }; - let first = (section, offset + (at - base) as u64); - let (mut reached, mut one) = (base + bytes, true); - while reached < end { - let Some(&(bytes, s, o)) = views.get(&reached) else { - return Cover::Holes; - }; - one &= s == first.0 && o == first.1 + (reached - at) as u64; - reached += bytes; +/// `[at, end)` is no longer a decommit kept for the title ([`DECOMMITTED`]): +/// the host freed it, or the title has memory there again. +fn decommitted_gone(at: usize, end: usize) { + if !DECOMMITTED_ANY.load(Ordering::Acquire) { + return; } - if one { Cover::Run(first.0, first.1) } else { Cover::Scattered } + let mut kept = DECOMMITTED.lock().unwrap_or_else(|e| e.into_inner()); + if !kept.iter().any(|&(a, b, _)| a < end && b > at) { + return; + } + let cut: Vec<(usize, usize, usize)> = kept + .iter() + .flat_map(|&(a, b, of)| { + if a < end && b > at { free_parts(&[(at, end)], a, b).into_iter().map(|(c, d)| (c, d, of)).collect() } else { vec![(a, b, of)] } + }) + .collect(); + *kept = cut; + DECOMMITTED_ANY.store(!kept.is_empty(), Ordering::Release); } -/// [`Cover`] of `[at, at + len)` by the title's views as they are now. -pub(crate) fn cover(at: usize, len: usize) -> Cover { - cover_in(&views().views, at, len) +/// `LEONIDA_INPLACE_QUERY_DECOMMITS`: on (unset), with [`queries`], a +/// decommit of the title's kept committed and zeroed for a heap +/// ([`DECOMMITTED`]) reads as reserved memory to its `XMemVirtualQuery`, +/// as it asked ([`title_memory_as_asked`]). `=0`: as before, committed, as +/// the host has it. +fn query_decommits() -> bool { + crate::toggled!("LEONIDA_INPLACE_QUERY_DECOMMITS") } -/// The whole stretch of views around `[at, at + len)` that follow one -/// another in memory and in one section alike, if the range is one run of a -/// section ([`Cover::Run`]): its first address, its bytes, the section and -/// the offset of its first byte in it. -pub(crate) fn stretch(at: usize, len: usize) -> Option<(usize, usize, usize, u64)> { - let v = views(); - stretch_in(&v.views, at, len) +/// `LEONIDA_INPLACE_QUERY`: on (unset), the title's `XMemVirtualQuery` +/// (`leonida_hle`'s xmem) is told what the title asked for where a heap +/// opened in place has the runtime do it later: a release kept for the +/// title ([`PENDING`]) reads as free memory, a protection that waits +/// ([`PROTECTS`]) as made ([`title_memory_as_asked`]). `=0`: as before, +/// what the host has, until the heap is gone. +fn queries() -> bool { + crate::toggled!("LEONIDA_INPLACE_QUERY") } -fn stretch_in(views: &BTreeMap<usize, (usize, usize, u64)>, at: usize, len: usize) -> Option<(usize, usize, usize, u64)> { - let Cover::Run(section, offset) = cover_in(views, at, len) else { - return None; +/// The host's answer to a query of the title's memory at `at` +/// (`VirtualQuery`'s, in `info`), made what the title asked for where the +/// runtime does it later ([`queries`]): memory the title released and the +/// runtime keeps reserved for a heap ([`PENDING`]) is free, to the end of +/// that allocation and on over the free memory after it, as the host gives +/// a run of free pages; a protection the title asked for that waits for a +/// heap ([`PROTECTS`], the newest over the page) is the page's, and the +/// region ends where a waiting protection begins or ends. The title is told +/// those protections and releases are done ([`title_memory_protect`], +/// [`title_memory_free`]); its own query said otherwise until the heap was +/// gone, about two frames. +/// +/// A decommit under a heap kept committed and zeroed instead +/// ([`title_memory_free_held`], [`DECOMMITTED`]) is reserved memory +/// ([`query_decommits`]), on over the reserved memory and other such +/// decommits after it in the allocation, as the host gives a run of +/// reserved pages; and a committed region ends where one begins. Before, it +/// read as committed (graphics memory to `XMemVirtualQuery`) until the title +/// released the allocation: the title's `VirtualAlloc` was the host's own, +/// and a commit of the pages again could not be seen to end the record. +pub fn title_memory_as_asked(at: usize, info: &mut mem::MEMORY_BASIC_INFORMATION) { + let decommits = query_decommits() && DECOMMITTED_ANY.load(Ordering::Acquire); + if !queries() || (WAITING.load(Ordering::Relaxed) == 0 && !decommits) { + return; + } + let pending: Vec<(usize, usize)> = PENDING.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|p| (p.0, p.1)).collect(); + let protects: Vec<(usize, usize, u32)> = PROTECTS.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|p| (p.0, p.1, p.2)).collect(); + let decommitted: Vec<(usize, usize, usize)> = if decommits { DECOMMITTED.lock().unwrap_or_else(|e| e.into_inner()).clone() } else { Vec::new() }; + let host_at = |end: usize| { + // SAFETY: plain data filled in by the query. + let mut next: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(end as *const c_void, &mut next, size_of_val(&next)) }; + (n != 0).then_some(next) }; - // Every view of the stretch has the same address less section offset. - let delta = at as i128 - offset as i128; - let follows = |a: usize, s: usize, o: u64| s == section && a as i128 - o as i128 == delta; - let (&first, &(n, _, _)) = views.range(..=at).next_back()?; - let mut start = first; - for (&a, &(n, s, o)) in views.range(..first).rev() { - if a + n != start || !follows(a, s, o) { - break; + let free_after = |end: usize| { + host_at(end).filter(|next| next.State == mem::MEM_FREE).map(|next| (next.BaseAddress as usize).saturating_add(next.RegionSize)) + }; + let reserved_after = |end: usize, base: usize| { + host_at(end) + .filter(|next| next.State == mem::MEM_RESERVE && next.AllocationBase as usize == base) + .map(|next| (next.BaseAddress as usize).saturating_add(next.RegionSize)) + }; + as_asked(at, info, &pending, &protects, &decommitted, free_after, reserved_after); +} + +/// [`title_memory_as_asked`] with the releases kept (first byte, end), the +/// protections that wait (first byte, end, protection; oldest first), the +/// decommits kept (first byte, end, allocation base; in address order, none +/// of one allocation touching), +/// `free_after`: the end of the run of free memory the host has at an +/// address, if it has free memory there, and `reserved_after`: the end of +/// the run of reserved memory the host has at an address in the allocation +/// whose base is given, if it has reserved memory of that allocation there. +fn as_asked( + at: usize, + info: &mut mem::MEMORY_BASIC_INFORMATION, + pending: &[(usize, usize)], + protects: &[(usize, usize, u32)], + decommitted: &[(usize, usize, usize)], + free_after: impl Fn(usize) -> Option<usize>, + reserved_after: impl Fn(usize, usize) -> Option<usize>, +) { + let page = at & !0xfff; + if let Some(&(_, mut end)) = pending.iter().find(|p| p.0 <= page && page < p.1) { + // On over the free memory and the other releases kept after it. + loop { + if let Some(&(_, next)) = pending.iter().find(|p| p.0 == end) { + end = next; + } else if let Some(next) = free_after(end).filter(|&next| next > end) { + end = next; + } else { + break; + } } - start = a; + info.BaseAddress = page as *mut c_void; + info.AllocationBase = std::ptr::null_mut(); + info.AllocationProtect = 0; + info.RegionSize = end - page; + info.State = mem::MEM_FREE; + info.Protect = mem::PAGE_NOACCESS; + info.Type = 0; + return; } - let mut stop = first + n; - for (&a, &(n, s, o)) in views.range(first + 1..) { - if a != stop || !follows(a, s, o) { - break; + // A decommit kept (committed on the host), or the host's reserved memory + // one may follow: reserved, on over those after it in the allocation + // (only its own: the next allocation may begin where this one ends). + let host_end = (info.BaseAddress as usize).saturating_add(info.RegionSize); + let base = info.AllocationBase as usize; + let kept = |page: usize| decommitted.iter().find(|d| d.0 <= page && page < d.1 && d.2 == base).map(|d| d.1); + let reserved = match info.State { + _ if decommitted.is_empty() => None, + mem::MEM_COMMIT => kept(page), + mem::MEM_RESERVE => Some(host_end), + _ => None, + }; + if let Some(mut end) = reserved { + loop { + if let Some(next) = kept(end) { + end = next; + } else if let Some(next) = reserved_after(end, base).filter(|&next| next > end) { + end = next; + } else { + break; + } } - stop = a + n; + if info.State == mem::MEM_COMMIT || end != host_end { + info.BaseAddress = page as *mut c_void; + info.RegionSize = end - page; + info.State = mem::MEM_RESERVE; + info.Protect = 0; + } + return; } - Some((start, stop - start, section, (start as i128 - delta) as u64)) -} - -/// Another address of the title memory `[at, at + len)`, if it is a view of -/// the title's pages, all of it one run of a section: in a view of ours of -/// the whole section, which is never guarded (`crate::watch`) nor changed. -/// -/// The section's pages are reserved and the runtime commits each before it -/// shows it, which holds for every view of the section. The caller holds -/// `crate::watch::title_memory_reading`: until it lets go the title sees -/// the same pages at `at`. -pub(crate) fn beside(at: usize, len: usize) -> Option<usize> { - let known = { - let v = views(); - let Cover::Run(section, offset) = cover_in(&v.views, at, len) else { - return None; - }; - v.whole.get(§ion).map(|&base| (base, offset)) - }; - if let Some((base, offset)) = known { - return (base != 0).then(|| base + offset as usize); + if info.State != mem::MEM_COMMIT { + return; } - let mut v = views_mut(); - let Cover::Run(section, offset) = cover_in(&v.views, at, len) else { - return None; - }; - let base = match v.whole.get(§ion) { - Some(&base) => base, - None => { - let &(bytes, _) = v.sections.get(§ion)?; - // SAFETY: the whole of a section the runtime made; a view the - // title sees is of it, so its handle is open. - let base = unsafe { mem::MapViewOfFile(section as _, mem::FILE_MAP_WRITE, 0, 0, bytes as usize) }.Value as usize; - if base == 0 { - tracing::warn!(error = %std::io::Error::last_os_error(), "no view of the title's pages beside its own"); - } - v.whole.insert(section, base); - base - } - }; - (base != 0).then(|| base + offset as usize) -} - -/// Our own address of the 64 KiB page the title sees at `page` ([`beside`]), -/// and every address the title sees it at (0: no more); `None` if the page is -/// in no view of a section, or in very many. While the caller holds -/// `crate::watch::title_memory_reading`. -pub(crate) fn beside_page(page: usize) -> Option<(usize, [usize; 8])> { - for asked in [false, true] { - { - let v = views(); - let (&base, &(bytes, section, offset)) = v.views.range(..=page).next_back()?; - let within = page.wrapping_sub(base); - if within >= bytes || !within.is_multiple_of(K64) { - return None; - } - let offset = offset + within as u64; - if let Some(&whole) = v.whole.get(§ion) { - let mut shown = [0; 8]; - let all = v.pages.get(&(section, offset))?; - shown.get_mut(..all.len())?.copy_from_slice(all); - return (whole != 0).then(|| (whole + offset as usize, shown)); + let mut end = host_end; + if let Some(&(_, _, new)) = protects.iter().rev().find(|p| p.0 <= page && page < p.1) { + info.Protect = new; + } + for &(from, to, _) in protects { + for edge in [from, to] { + if edge > page && edge < end { + end = edge; } } - if asked || beside(page, K64).is_none() { - return None; + } + // (Nor past a release or a decommit kept for the title.) + for from in pending.iter().map(|p| p.0).chain(decommitted.iter().map(|d| d.0)) { + if from > page && from < end { + end = from; } } - None + info.RegionSize = end - (info.BaseAddress as usize); } -/// Whether `[at, at + len)` is private memory, all committed and -/// read-write: what [`From::Part`] takes. One question to Windows (it -/// walks the page tables to the end of the pages that share the first -/// one's state: a millisecond in the title's big blocks, so ask when a -/// copy is made, not when it is used). -pub(crate) fn private_whole(at: usize, len: usize) -> bool { - // SAFETY: plain data filled in by the query. - let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - // SAFETY: a valid out pointer of the right size. - let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; - n != 0 - && info.State == mem::MEM_COMMIT - && info.Type == mem::MEM_PRIVATE - && info.Protect == mem::PAGE_READWRITE - && (info.BaseAddress as usize).saturating_add(info.RegionSize) >= at.saturating_add(len) +/// `LEONIDA_INPLACE_AGAIN`: on (unset), with [`level`] on, once the title +/// gives read-write back to all of the 64 KiB pages a heap stood over when +/// it took access away from some of them, the copies made there since are +/// asked to be opened in place again ([`again`]); else (`=0`, as before) +/// they stay copies for as long as they are used. +fn agains() -> bool { + crate::toggled!("LEONIDA_INPLACE_AGAIN") } -fn hr<T>(result: &windows::core::Result<T>) -> String { - match result { - Ok(_) => "ok".to_owned(), - Err(e) => format!("REFUSED {:#010x} ({})", e.code().0, e.message().trim()), - } -} +/// The pages of heaps a protection let go of ([`let_go_under`]), as (first +/// byte, end), to be opened again once they are read-write ([`again`]); +/// forgotten when the memory changes ([`title_memory_freeing`]). A heap +/// opens only pages that are all committed and read-write +/// ([`private_whole`]), so a 64 KiB page with mixed protections is a copy; +/// and a copy made there stays the copy while it is used, whatever the +/// title does with the pages after: without this, memory the title once +/// protected never had a heap again. +static AGAIN: std::sync::Mutex<Vec<(usize, usize)>> = std::sync::Mutex::new(Vec::new()); -/// A queue, a list and a fence of the probe's own on `device`: nothing of -/// the host's submissions is touched. -pub(crate) struct Rig { - device: ID3D12Device, - queue: ID3D12CommandQueue, - allocator: ID3D12CommandAllocator, - list: ID3D12GraphicsCommandList, - fence: ID3D12Fence, - done: u64, - event: HANDLE, -} +/// Whether [`AGAIN`] holds any. +static AGAIN_ANY: AtomicBool = AtomicBool::new(false); -impl Drop for Rig { - fn drop(&mut self) { - // SAFETY: our event. - unsafe { - let _ = windows::Win32::Foundation::CloseHandle(self.event); +/// The most ranges [`AGAIN`] keeps: the oldest go first. +const AGAIN_MOST: usize = 1024; + +/// The pages of the heaps `under` were let go of for a protection: noted +/// ([`AGAIN`]). +fn again_noted(under: &[(usize, usize)]) { + if !agains() || level() == 0 { + return; + } + let mut noted = AGAIN.lock().unwrap_or_else(|e| e.into_inner()); + for &range in under { + if !noted.contains(&range) { + noted.push(range); } } + let over = noted.len().saturating_sub(AGAIN_MOST); + noted.drain(..over); + AGAIN_ANY.store(!noted.is_empty(), Ordering::Release); } -impl Rig { - pub(crate) fn new(device: &ID3D12Device) -> windows::core::Result<Rig> { - // SAFETY: plain creation of objects of our own. - unsafe { - let queue: ID3D12CommandQueue = - device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })?; - let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; - list.Close()?; - let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let event = CreateEventW(None, false, false, None)?; - Ok(Rig { device: device.clone(), queue, allocator, list, fence, done: 0, event }) - } +/// `[at, at + len)` changes: what [`AGAIN`] noted over it is forgotten. +fn again_gone(at: usize, len: usize) { + if !AGAIN_ANY.load(Ordering::Acquire) { + return; } + let end = at.saturating_add(len.max(1)); + let mut noted = AGAIN.lock().unwrap_or_else(|e| e.into_inner()); + noted.retain(|&(a, b)| a >= end || b <= at); + AGAIN_ANY.store(!noted.is_empty(), Ordering::Release); +} - /// Records with `record`, runs it and waits (ten seconds at most). - fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> windows::core::Result<()> { - // SAFETY: our own list and queue, one run at a time. - unsafe { - self.allocator.Reset()?; - self.list.Reset(&self.allocator, None)?; - record(&self.list); - self.list.Close()?; - self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]); - self.done += 1; - self.queue.Signal(&self.fence, self.done)?; - self.fence.SetEventOnCompletion(self.done, self.event)?; - if WaitForSingleObject(self.event, 10_000).0 != 0 { - return Err(windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)); +/// The title made the pages `[from, to)` read-write: each range [`AGAIN`] +/// noted over them that is now all committed and read-write, with no +/// protection waiting over it, is forgotten, and the copies the tables have +/// there that could be in place ([`crate::shadow::copies_over`]) are asked of +/// the opener ([`open_asked`]), which opens them; each takes its copy's place +/// once that copy can go ([`switch_ready`]). +fn again(from: usize, to: usize) { + if !AGAIN_ANY.load(Ordering::Acquire) || !agains() { + return; + } + let level = level(); + if level == 0 { + return; + } + let ripe: Vec<(usize, usize)> = { + let mut noted = AGAIN.lock().unwrap_or_else(|e| e.into_inner()); + let ripe: Vec<(usize, usize)> = noted + .iter() + .copied() + .filter(|&(a, b)| a < to && b > from && protect_waits(a, b).is_none() && private_whole(a, b - a)) + .collect(); + noted.retain(|range| !ripe.contains(range)); + AGAIN_ANY.store(!noted.is_empty(), Ordering::Release); + ripe + }; + for (a, b) in ripe { + for (start, len, window) in crate::shadow::copies_over(a as u64, b as u64) { + if level >= if window { 1 } else { 2 } { + STATS[20].fetch_add(1, Ordering::Relaxed); + ask_opener(Ask { start, len, window }); } - self.device.GetDeviceRemovedReason() } } +} - fn committed(&self, kind: D3D12_HEAP_TYPE, size: u64, state: D3D12_RESOURCE_STATES) -> windows::core::Result<ID3D12Resource> { - let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; - let mut buffer: Option<ID3D12Resource> = None; - // SAFETY: plain creation. - unsafe { - self.device - .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, D3D12_RESOURCE_FLAG_NONE), state, None, &mut buffer)? - }; - buffer.ok_or_else(windows::core::Error::empty) - } +/// `LEONIDA_INPLACE_RESERVE`: on (unset), the title's reservation at a +/// fixed address the host refuses because a release of the title's kept for +/// it lies there ([`PENDING`]) is made again once those releases are done, +/// if they can be ([`title_memory_reserve`]). `=0`: as before, it fails +/// until [`tick`] does them. +fn reserves() -> bool { + crate::toggled!("LEONIDA_INPLACE_RESERVE") +} - /// What the GPU reads of `size` bytes of `resource` from `offset`. - pub(crate) fn fetch(&mut self, resource: &ID3D12Resource, offset: u64, size: usize) -> windows::core::Result<Vec<u8>> { - let back = self.committed(D3D12_HEAP_TYPE_READBACK, size as u64, D3D12_RESOURCE_STATE_COPY_DEST)?; - // SAFETY: two live buffers, the range inside both. - self.run(|list| unsafe { list.CopyBufferRegion(&back, 0, resource, offset, size as u64) })?; - let mut data = std::ptr::null_mut(); - // SAFETY: the mapping holds `size` bytes until unmapped. - unsafe { - back.Map(0, None, Some(&mut data))?; - let bytes = std::slice::from_raw_parts(data.cast::<u8>(), size).to_vec(); - back.Unmap(0, None); - Ok(bytes) - } - } +/// `LEONIDA_INPLACE_RELEASE_FIRST`: on (unset), with [`reserves`], the +/// title's allocation at a fixed address that touches a release kept for it +/// does that release first, and is refused while it cannot be done +/// ([`title_memory_reserve`]): a commit of released pages is no longer taken +/// inside the reservation kept for the title. `=0`: as before, the host is +/// asked first and the release done only if it refused. +fn release_first() -> bool { + crate::toggled!("LEONIDA_INPLACE_RELEASE_FIRST") +} - /// The GPU writes `bytes` at `offset` of `resource` (a copy). - pub(crate) fn store(&mut self, resource: &ID3D12Resource, offset: u64, bytes: &[u8]) -> windows::core::Result<()> { - let up = self.committed(D3D12_HEAP_TYPE_UPLOAD, bytes.len() as u64, D3D12_RESOURCE_STATE_GENERIC_READ)?; - let mut data = std::ptr::null_mut(); - // SAFETY: the mapping holds the buffer's bytes until unmapped. - unsafe { - up.Map(0, None, Some(&mut data))?; - std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.cast::<u8>(), bytes.len()); - up.Unmap(0, None); +/// How long [`title_memory_reserve`] waits, at most, for the host to let go +/// of the pages of heaps whose last reference went just then (ms): a busy +/// adapter lets go a moment later ([`GIVE_UP_MS`]); on the software adapter +/// an idle one lets go at once. +const RESERVE_WAIT_MS: u64 = 50; + +/// The title's allocation at the fixed address `[at, at + len)` (a +/// reservation, or a commit of pages it reserved before), which +/// `leonida_hle`'s xmem makes with `reserve` (the host's call); returns what +/// the title is told: `reserve`'s answer, the thread's last error as it left +/// it. +/// +/// A release of the title's that a heap opened in place was in the way of +/// is kept reserved until the heap is gone ([`PENDING`], done from +/// [`tick`] every [`REAP_MS`]): nothing of the title's is at its addresses +/// any more, though the host still has them reserved. So when the title's +/// addresses touch such a release, the release is done first: the +/// descriptor slots that view a buffer there let go of it +/// ([`slots_let_go`]), what nothing else holds goes and the releases are +/// tried again ([`reap`]); while no standing hold is in the way, the host is +/// given [`RESERVE_WAIT_MS`] to let go of the heaps' pages; and once the +/// releases are done the host is asked. A release a heap still stands over +/// (the submissions that may use it have not run) stays, and the title is +/// refused with error 487 (`ERROR_INVALID_ADDRESS`): what the host says to a +/// reservation of addresses it has reserved, and what the console says to a +/// commit of memory that is free. +/// +/// Before ([`release_first`] off), the host was asked first and the release +/// done only if it refused. A reservation was refused (error 487) and made +/// once the release was done; but a commit of the released pages +/// (`MEM_COMMIT` alone) was taken, inside the reservation kept for the +/// title, and those pages went with the release later, under a title told +/// they were committed. +pub fn title_memory_reserve(at: usize, len: usize, reserve: impl Fn() -> *mut c_void) -> *mut c_void { + use windows_sys::Win32::Foundation::{ERROR_INVALID_ADDRESS, GetLastError, SetLastError}; + if at == 0 || !reserves() || !released(at, len) { + return reserve(); + } + if !release_first() { + let got = reserve(); + if !got.is_null() { + return got; } - // SAFETY: two live buffers, the range inside both. - self.run(|list| unsafe { list.CopyBufferRegion(resource, offset, &up, 0, bytes.len() as u64) }) + // SAFETY: a plain read of the thread's last error. + let error = unsafe { GetLastError() }; + if release_pending_over(at, len) { + let got = reserve(); + if !got.is_null() { + STATS[14].fetch_add(1, Ordering::Relaxed); + return got; + } + } + // SAFETY: the thread's last error set back to the host's. + unsafe { SetLastError(error) }; + return got; + } + if !release_pending_over(at, len) { + // SAFETY: the thread's last error set as the host's refusal of + // addresses it has reserved sets it. + unsafe { SetLastError(ERROR_INVALID_ADDRESS) }; + return std::ptr::null_mut(); } + let got = reserve(); + if !got.is_null() { + STATS[14].fetch_add(1, Ordering::Relaxed); + } + got +} - /// A compute shader stores, through a root unordered-access view at - /// `gpu`, the sum of the buffer's first two words in its third. - fn shade(&mut self, gpu: u64) -> windows::core::Result<()> { - const SOURCE: &str = "#define RS \"UAV(u0)\"\nRWByteAddressBuffer b : register(u0);\n[RootSignature(RS)]\n[numthreads(1, 1, 1)]\nvoid main() { b.Store(8, b.Load(0) + b.Load(4)); }\n"; - let mut code: Option<ID3DBlob> = None; - // SAFETY: the source and names live through the call; then the - // blob's own bytes, which hold the root signature too. - let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { - D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("inplace"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?; - let code = code.ok_or_else(windows::core::Error::empty)?; - let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); - let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; - let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, - ..Default::default() - })?; - (root, pso) - }; - // SAFETY: an open list of ours; the view names a live buffer. - self.run(|list| unsafe { - list.SetComputeRootSignature(&root); - list.SetPipelineState(&pso); - list.SetComputeRootUnorderedAccessView(0, gpu); - list.Dispatch(1, 1, 1); - }) +/// The title's allocation `[at, at + len)` (`at` 0: where the host chooses; +/// `kind` as `VirtualAlloc` takes it), which `leonida_hle`'s xmem makes with +/// `alloc` (the host's call) for an `XMemVirtualAlloc` at an address of the +/// title's and for the title's own `VirtualAlloc` and `VirtualAllocEx`: +/// [`title_memory_reserve`], then, if it is made, a reservation or a commit, +/// the pages it got are no decommit kept for the title any more +/// ([`DECOMMITTED`]: committed again, they read as committed; a new +/// reservation can only be where a record went stale). Returns what the +/// title is told, `alloc`'s answer, the thread's last error as it left it. +pub fn title_memory_alloc(at: usize, len: usize, kind: u32, alloc: impl Fn() -> *mut c_void) -> *mut c_void { + let got = title_memory_reserve(at, len, alloc); + if !got.is_null() && kind & (mem::MEM_COMMIT | mem::MEM_RESERVE) != 0 && DECOMMITTED_ANY.load(Ordering::Acquire) { + let (from, to) = host_pages(if at == 0 { got as usize } else { at }, len); + decommitted_gone(from, to); } + got +} - /// Milliseconds the card takes to copy `bytes` of `from` into its own - /// memory, the best of three. - fn copy_ms(&mut self, from: &ID3D12Resource, bytes: u64) -> windows::core::Result<f64> { - let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; - let mut to: Option<ID3D12Resource> = None; - // SAFETY: plain creation. - unsafe { - self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, None, &mut to)? - }; - let to = to.ok_or_else(windows::core::Error::empty)?; - let mut best = f64::MAX; - for _ in 0..3 { - let started = std::time::Instant::now(); - // SAFETY: two live buffers of `bytes` bytes or more. - self.run(|list| unsafe { list.CopyBufferRegion(&to, 0, from, 0, bytes) })?; - best = best.min(started.elapsed().as_secs_f64() * 1000.0); +/// The releases kept for the title that touch `[at, at + len)` ([`PENDING`]) +/// done now if they can be ([`title_memory_reserve`]); whether none is left +/// there. +fn release_pending_over(at: usize, len: usize) -> bool { + let end = at.saturating_add(len.max(1)); + let over: Vec<(usize, usize)> = + PENDING.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|p| p.0 < end && p.1 > at).map(|p| (p.0, p.1)).collect(); + for &(from, to) in &over { + slots_let_go(from, to, true); + } + reap(); + let started = std::time::Instant::now(); + loop { + if !released(at, len) { + return true; } - Ok(best) + let (standing, _) = holds_now(); + if over.iter().any(|&(from, to)| !held_parts(&standing, from, to).is_empty()) + || started.elapsed() >= std::time::Duration::from_millis(RESERVE_WAIT_MS) + { + return false; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + release_pending(); } } -fn fill(at: *mut u8, len: usize, seed: u8) { - for i in 0..len { - // SAFETY: the caller's own committed memory of `len` bytes. - unsafe { at.add(i).write((i as u8).wrapping_mul(31).wrapping_add(seed)) }; +/// Zeroes what of the title's `[at, end)` is committed and writable, for a +/// decommit the host refused ([`title_memory_free_held`]); whether any +/// was. Committed pages that are not writable are left as they are (said +/// once): no heap of ours stands over those, as one would have kept them +/// read-write. +fn zero_committed(at: usize, end: usize) -> bool { + const WRITABLE: u32 = mem::PAGE_READWRITE | mem::PAGE_WRITECOPY | mem::PAGE_EXECUTE_READWRITE | mem::PAGE_EXECUTE_WRITECOPY; + let mut zeroed = false; + let mut from = at; + while from < end { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + if unsafe { mem::VirtualQuery(from as *const c_void, &mut info, size_of_val(&info)) } == 0 { + break; + } + let to = (info.BaseAddress as usize).saturating_add(info.RegionSize).min(end); + if info.State == mem::MEM_COMMIT && info.Protect & WRITABLE != 0 && info.Protect & mem::PAGE_GUARD == 0 { + // SAFETY: pages the title asked to decommit, committed and + // writable (the host said so just now). + unsafe { std::ptr::write_bytes(from as *mut u8, 0, to - from) }; + zeroed = true; + } else if info.State == mem::MEM_COMMIT { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!( + at = format_args!("{from:#x}"), + bytes = to - from, + protect = format_args!("{:#x}", info.Protect), + "the title's decommit refused over pages that are not writable: they keep what they hold" + ); + }); + } + from = to; } + zeroed } -fn same(at: *const u8, bytes: &[u8]) -> bool { - // SAFETY: the caller's own committed memory of that length. - unsafe { std::slice::from_raw_parts(at, bytes.len()) == bytes } +/// Whether `[at, at + len)` touches an allocation the title released that +/// is kept for it ([`PENDING`]): nothing of the title's is there. +fn released(at: usize, len: usize) -> bool { + if WAITING.load(Ordering::Relaxed) == 0 { + return false; + } + let end = at.saturating_add(len.max(1)); + PENDING.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|p| p.0 < end && p.1 > at) } -/// The process's working set in MB. -fn working_set_mb() -> u64 { - use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; - let mut counters = PROCESS_MEMORY_COUNTERS { cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, ..Default::default() }; - // SAFETY: our own process and a sized structure. - unsafe { K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut counters, counters.cb) }; - counters.WorkingSetSize as u64 >> 20 +/// Whether title memory `[start, start + len)` is not to be opened in place +/// in its allocation ([`place_for`]): view memory (known from the runtime +/// without asking Windows; one run of a section is opened in the section +/// instead, [`in_section`]); or a heap over its 64 KiB pages ([`opened_pages`], what +/// [`place_part`] opens) would lie over an allocation the title released +/// and we keep for it (nothing of the title's), or over pages whose +/// protection waits for a heap ([`PROTECTS`]: a new one would keep it +/// waiting). Asked of the bytes alone, a heap was opened over a page beside +/// them whose protection waited. +fn kept_from(start: u64, len: u64) -> bool { + let (at, bytes) = opened_pages(start, len); + let (at, bytes) = (at as usize, bytes as usize); + cover(start as usize, len as usize) != Cover::None || released(at, bytes) || protect_waits(at, at + bytes).is_some() } -/// What the probe found. The lines are the whole account; the flags are -/// what the stages build on. -#[derive(Default)] -pub(crate) struct Probe { - pub(crate) lines: Vec<String>, - /// A part of private, write-watched memory opens, a buffer in it shows - /// the memory's bytes to the GPU, also those the CPU wrote afterwards. - pub(crate) part_reads: bool, - /// What the GPU writes there (a copy, and a shader through unordered - /// access) the CPU reads at the memory's address. - pub(crate) part_writes: bool, - /// The same two for a committed section, through a view of it. - pub(crate) section_reads: bool, - pub(crate) section_writes: bool, - /// The section's heap outlives the view: the GPU's write with no view - /// mapped shows in a view mapped afterwards. - pub(crate) section_outlives_views: bool, - /// A section made with `SEC_RESERVE` (as `xmem` makes the page pool) - /// was refused. - pub(crate) reserved_section_refused: bool, +/// Title memory `[start, start + len)` in place, for a window outside +/// buffers or a title buffer, if [`level`] asks for it and the memory can +/// be opened; `None` leaves the caller to make a copy, as before. View +/// memory that is one run of a section ([`Cover::Run`]) is opened in its +/// section ([`in_section`]), the rest in its allocation ([`place_part`]). +pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option<Placed> { + if level() < if window { 1 } else { 2 } { + return None; + } + if let Cover::Run(section, offset) = cover(start as usize, len as usize) + && sections() + { + return in_section(start, len, window, section, offset); + } + if kept_from(start, len) { + STATS[4].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + tiled::turned_down(start, len); + return None; + } + if asynchronous() { + return ready_for(start, len, window); + } + let placed = opened(start, len, window)?; + hold(start, len, &placed.buffer); + Some(placed) } -/// Tries the openings on memory of the probe's own, made the way `xmem` -/// makes title memory, with a queue of its own on `device`; `memory` -/// gives the card's memory account (`Host::video_memory`) where there is -/// one. Nothing of the title's is touched. `mb` is the size of the cost -/// measurement (0 leaves it out). -pub(crate) fn probe(device: &ID3D12Device, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) -> Probe { - let mut p = Probe::default(); - let mut rig = match Rig::new(device) { - Ok(rig) => rig, - Err(e) => { - p.lines.push(format!("no queue of its own: {e}")); - return p; - } - }; - let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); - // SAFETY: a plain query that fills our structure. - let _ = unsafe { device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, (&raw mut options).cast(), size_of_val(&options) as u32) }; - p.lines.push(format!( - "the device: ID3D12Device3 {}, ID3D12Device13 {} (parts of an allocation); cross-adapter row-major textures {}; heap tier {}", - device.cast::<ID3D12Device3>().is_ok(), - device.cast::<ID3D12Device13>().is_ok(), - options.CrossAdapterRowMajorTextureSupported.as_bool(), - options.ResourceHeapTier.0 - )); - // SAFETY: memory of the probe's own, made and released here; every - // address used lies inside it. - unsafe { - private(&mut p, &mut rig); - section(&mut p, &mut rig); - if mb > 0 { - cost(&mut p, &mut rig, memory, mb); +/// Title memory `[start, start + len)` opened for the CPU's side of a copy +/// in the card's memory (`crate::shadow::from_title`): not gated by +/// [`level`], not within [`most`] (the copies in the card's memory have their +/// own line, `LEONIDA_CARD_BUFFERS_MB`) and not counted with what is in place +/// (the copy is one: what shaders read is its card side). One run of a +/// committed section is placed in the section ([`place_in_section`]; looked +/// at again after, as [`in_section`] does: the caller holds the table the +/// let-go takes the copy's name from), other memory in its allocation +/// ([`place_part`]) and held ([`hold`]), as [`place_for`] places and holds +/// it, so that the title's frees and protections of it are taken over while +/// the heap stands. `Err` says why not. +pub(crate) fn place_source(start: u64, len: u64) -> Result<Placed, &'static str> { + let host = crate::host::host().ok_or("no host device")?; + if let Cover::Run(section, offset) = cover(start as usize, len as usize) + && sections() + { + let placed = place_in_section(&host.device, section, offset, len).map_err(|_| "a section the host does not open")?; + if cover(start as usize, len as usize) != Cover::Run(section, offset) { + return Err("the title mapped other pages there meanwhile"); } + return Ok(placed); } - p.lines.push(format!( - "VERDICT: private memory in place: reads {}, writes {}; the page pool's section in place: reads {}, writes {}, whatever the views do {}; \ - a reserved section is refused {} (the pool must be made committed to be opened)", - p.part_reads, p.part_writes, p.section_reads, p.section_writes, p.section_outlives_views, p.reserved_section_refused - )); - p + if kept_from(start, len) { + return Err("view memory, or memory the title gave up or protects"); + } + let placed = place_part(&host.device, start, len).map_err(|_| "not private memory committed whole, or the host refused")?; + hold(start, len, &placed.buffer); + Ok(placed) } -fn describe(heap: &ID3D12Heap) -> String { - // SAFETY: a plain query. - let d = unsafe { heap.GetDesc() }; - format!( - "heap of {} KiB: type {} (4 = custom), CPU pages {} (3 = write-back), pool {} (1 = the PC's memory), alignment {}, flags {:#x} (0x1 shared, 0x20 cross-adapter, 0x200 write watch, 0x400 shader atomics)", - d.SizeInBytes >> 10, - d.Properties.Type.0, - d.Properties.CPUPageProperty.0, - d.Properties.MemoryPoolPreference.0, - d.Alignment, - d.Flags.0 - ) +/// `LEONIDA_INPLACE_ASYNC`: on (unset), with [`level`] on, private title +/// memory is not opened on the thread that asks for it ([`place_for`], under +/// the tables' lock, on a list thread): the ask goes to a thread of its own +/// (the opener, [`open_asked`]) and the caller makes a copy, as when the +/// memory cannot be opened. What the opener opened is held at once +/// ([`hold`], [`READY`]) and goes in place at the next ask of the same +/// memory ([`ready_for`]), or in the place of the copy made meanwhile once +/// that copy can go without losing anything ([`switch_ready`], from +/// [`tick`]); what is neither within [`READY_MS`] is let go. `=0`: as before, +/// opened on the asking thread. +/// +/// Opening costs about 1 ms for a part of 1 MiB and 2 to 6 ms for 16 MiB on +/// the RX 7900 XT (36 for 256 MiB; 70 on the software adapter), and locks +/// every page (findings.md, the placement table): a list thread's recording, +/// and every other thread that wanted the tables' lock, stood that long at +/// each new window or title buffer. Memory of views (sections: opening one +/// locks nothing and takes 0.2 ms, once a section) and the runtime's own +/// ([`place_ours`]) are still opened at once. +/// +/// What keeps it right: the opener looks at the memory, opens it and holds +/// it under [`GATE`], which the title's frees and protections hold shared +/// for their whole call, so that one meets either no heap of the opener's or +/// one held ([`HELD`]) and in [`READY`], which [`title_memory_freeing`] lets +/// go of before the free or the protection (so the host refuses it for no +/// heap of ours that the runtime does not know of). A copy is switched only +/// if shaders were never declared to write it (no write in flight or kept +/// out of title memory: `LEONIDA_WC_NO_BACK`, copy-back elision) and no +/// descriptor slot views it ([`crate::shadow::in_place_switch`]); lists may +/// still hold it ([`switch_held`]); title writes are in title memory either +/// way. A copy a slot views stays a copy (the slot would go on reading it, +/// never brought up to date). +pub(crate) fn asynchronous() -> bool { + #[cfg(test)] + if let Some(on) = TEST_ASYNC.get() { + return on; + } + crate::toggled!("LEONIDA_INPLACE_ASYNC") } -/// Private memory, reserved as `xmem` reserves the title's heaps -/// (committed, read-write, write-watched): a part of it opened. -unsafe fn private(p: &mut Probe, rig: &mut Rig) { - const SIZE: usize = 64 * K64; - // SAFETY (the whole function): the allocation below, `SIZE` bytes. - unsafe { - let base = mem::VirtualAlloc(std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>(); - if base.is_null() { - p.lines.push("private memory: none to try with".to_owned()); +/// What [`place_for`] asked the opener for: title memory `[start, start + +/// len)`, as a window outside buffers or a title buffer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Ask { + start: u64, + len: u64, + window: bool, +} + +impl Ask { + /// Whether the heap opened for it would stand over any of `[at, end)`: + /// it is opened over whole 64 KiB pages ([`opened_pages`]). + fn over(&self, at: usize, end: usize) -> bool { + let (first, bytes) = opened_pages(self.start, self.len); + (first as usize) < end && (first + bytes) as usize > at + } +} + +/// The asks the opener has not taken yet, oldest first. +static ASKED: std::sync::Mutex<std::collections::VecDeque<Ask>> = std::sync::Mutex::new(std::collections::VecDeque::new()); + +/// Rung for each ask ([`ASKED`]). +static ASKED_RUNG: std::sync::Condvar = std::sync::Condvar::new(); + +/// The most asks that wait: more are not made (the copy stays a copy). +const ASKED_MOST: usize = 4096; + +/// Title memory the opener opened, held ([`hold`]) and not yet in the +/// tables: the ask, the placement, and since when (ms). +struct Ready { + ask: Ask, + placed: Placed, + at: u64, +} + +// SAFETY: D3D12 objects (free-threaded), only kept and handed on. +unsafe impl Send for Ready {} + +/// What the opener opened, for [`ready_for`] and [`switch_ready`]. +static READY: std::sync::Mutex<Vec<Ready>> = std::sync::Mutex::new(Vec::new()); + +/// Whether [`READY`] holds any, for [`tick`] and [`anything_placed`] to look +/// only then. +static READY_ANY: AtomicBool = AtomicBool::new(false); + +/// The bytes asked for of what [`READY`] holds, counted against [`most`]. +static READY_BYTES: AtomicU64 = AtomicU64::new(0); + +/// How long what the opener opened waits to go in place (ms): a copy that +/// a slot views that long (or, with [`switch_held`] off, a list holds), or +/// shaders were declared to write, keeps its place, and the heap is let go, +/// so that it does not lock the pages for nothing. +const READY_MS: u64 = 10_000; + +/// `LEONIDA_INPLACE_SWITCH_HELD`: on (unset), with [`asynchronous`], what +/// the opener opened takes the place of the copy made meanwhile although +/// lists still hold that copy ([`crate::shadow::in_place_switch`]): each +/// list brings the copy it holds up to date at its submission, or reads +/// what was copied into it then, and keeps it alive until it is reset; +/// lists recorded from then on get the title memory in place. `=0`: as +/// before, only a copy nothing but the table holds is switched; a list +/// holds the copy from the draw that reads it until two submissions after +/// it ran, so memory read every frame was always held when the sweep +/// looked, the heap waited [`READY_MS`] beside the copy and was let go, and +/// that memory stayed a copy for good (and so did what [`again`] asked +/// for). +/// +/// Risky part: until the lists let go of the copy, two views of the same +/// bytes stand; shaders declared to write either one meanwhile are counted +/// ([`written_across_switch`]). Only memory shaders were never declared to +/// write is switched. On by default under [`level`], which is off. +pub(crate) fn switch_held() -> bool { + crate::toggled!("LEONIDA_INPLACE_SWITCH_HELD") +} + +/// Shaders were declared to write title memory `[start, start + len)` in +/// place, or the copy it took the place of, while lists still held that +/// copy ([`switch_held`]): a list submitted after the writer may read the +/// bytes from before through the other one, until the copy-back. Counted +/// for the say line, said once. +pub(crate) fn written_across_switch(start: u64, len: u64) { + if STATS[21].fetch_add(1, Ordering::Relaxed) == 0 { + tracing::warn!( + start = format_args!("{start:#x}"), + len, + "shaders write title memory switched in place while a list still held its copy: a later list may read the bytes from before until they are copied back (LEONIDA_INPLACE_SWITCH_HELD=0 keeps such copies)" + ); + } +} + +/// Held alone by the opener while it looks at memory, opens it and holds +/// what it opened ([`open_asked`]), and by [`switch_ready`] while it puts +/// what was opened in the tables; shared by the title's frees and +/// protections ([`title_memory_free`], [`title_memory_protect`]) for their +/// whole call. Without it a free could meet a heap the opener had just +/// opened and not yet held (refused with error 87 and not taken over), and +/// memory protected between the opener's look and its opening was opened +/// read-only to the CPU and writable to the card. +/// +/// What a free or protection may wait for: one opening, and an opening is +/// of the whole ask, a heap and one buffer over all of it: about 1 ms for +/// 1 MiB and 2 to 6 ms for 16 MiB on the RX 7900 XT (a window, mostly 4 MiB +/// or less), but a title buffer at level 2 is opened whole, up to [`most`]: +/// 36 ms for 256 MiB, 70 on the software adapter (findings.md, the +/// placement table). std's lock queues new readers behind a waiting +/// writer, so the title's frees and protections on every thread that come +/// once the opener waits for the lock wait for that opening too. How long +/// the title waits so in the game is not measured. +static GATE: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +/// [`GATE`] shared, for a title's free or protection. +fn gate_shared() -> std::sync::RwLockReadGuard<'static, ()> { + GATE.read().unwrap_or_else(|e| e.into_inner()) +} + +/// [`place_for`] with [`asynchronous`]: what the opener opened for the same +/// ask, if it did ([`READY`], counted as in place from now on); else the +/// ask goes to the opener, within [`most`], and the caller makes a copy. +fn ready_for(start: u64, len: u64, window: bool) -> Option<Placed> { + let ask = Ask { start, len, window }; + let taken = { + let mut ready = READY.lock().unwrap_or_else(|e| e.into_inner()); + let taken = ready.iter().position(|r| r.ask == ask).map(|i| ready.swap_remove(i)); + READY_ANY.store(!ready.is_empty(), Ordering::Release); + taken + }; + if let Some(ready) = taken { + READY_BYTES.fetch_sub(len, Ordering::Relaxed); + counted(window, len); + STATS[17].fetch_add(1, Ordering::Relaxed); + return Some(ready.placed); + } + if STATS[1].load(Ordering::Relaxed) + STATS[3].load(Ordering::Relaxed) + READY_BYTES.load(Ordering::Relaxed) + len > most() { + STATS[6].fetch_add(1, Ordering::Relaxed); + return None; + } + ask_opener(ask); + None +} + +/// `ask` waits for the opener ([`ASKED`]), once; the opener is started at +/// the first. (Not in the tests: they open what was asked themselves, +/// [`open_asked`], on the software adapter.) +fn ask_opener(ask: Ask) { + { + let mut asked = ASKED.lock().unwrap_or_else(|e| e.into_inner()); + if asked.len() >= ASKED_MOST || asked.contains(&ask) { return; } - // The part: 16 pages from the 16th on. - let (at, bytes) = (base.add(16 * K64), 16 * K64); - let whole = open(&rig.device, From::Region(base as usize)); - p.lines.push(format!("private memory, the whole allocation (OpenExistingHeapFromAddress): {}", hr(&whole))); - drop(whole); - let opened = open(&rig.device, From::Part(at as usize, bytes)); - p.lines.push(format!("private memory, a part of it (OpenExistingHeapFromAddress1): {}", hr(&opened))); - if let Ok(heap) = &opened { - p.lines.push(format!(" {}", describe(heap))); - let placed = place(&rig.device, heap, K64 as u64, 4 * K64 as u64); - p.lines.push(format!(" a buffer placed in it (cross-adapter, unordered access): {}", hr(&placed))); - if let Ok(buffer) = &placed { - let memory = at.add(K64); - fill(memory, 4 * K64, 1); - let first = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); - fill(memory, 4 * K64, 77); - let second = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); - p.part_reads = first && second; - p.lines.push(format!(" the GPU reads the memory's bytes: {first}; and those the CPU wrote afterwards, with no call in between: {second}")); - mem::ResetWriteWatch(base.cast(), SIZE); - let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x5a).collect(); - let copied = rig.store(buffer, 4096, &new).is_ok() && same(memory.add(4096), &new); - let (mut found, mut count, mut granularity) = ([0usize; 64], 64usize, 0u32); - let watched = mem::GetWriteWatch(0, base.cast(), SIZE, found.as_mut_ptr().cast(), &mut count, &mut granularity) == 0; - memory.cast::<[u32; 3]>().write([40, 2, 0]); - let shaded = rig.shade(buffer.GetGPUVirtualAddress()); - let shader = shaded.is_ok() && memory.cast::<[u32; 3]>().read()[2] == 42; - p.part_writes = copied && shader; - p.lines.push(format!( - " the CPU reads at the memory's address what the GPU wrote: by a copy {copied}; by a shader through unordered access {shader} ({}); \ - write watching saw {} of the copy's 16 pages{}", - hr(&shaded), - if watched { count } else { 0 }, - if watched { "" } else { " (the asking failed)" } - )); - } - // What the title can still do with the pages while the heap stands. - let mut old = 0; - let protect_in = mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READONLY, &mut old) != 0; - if protect_in { - mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READWRITE, &mut old); + asked.push_back(ask); + } + ASKED_RUNG.notify_one(); + #[cfg(not(test))] + { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + if let Err(e) = std::thread::Builder::new().name("leonida-inplace".into()).spawn(opener) { + tracing::warn!(error = %e, "no thread to open title memory in place: none is"); } - let decommit_in = mem::VirtualFree(at.add(9 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; - let decommit_out = mem::VirtualFree(base.add(40 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; - p.lines.push(format!( - " with the heap standing, the title's own calls: read-only inside the part {protect_in}, decommit inside {decommit_in}, decommit outside {decommit_out} \ - (false inside means the heap must go before the title frees or guards those pages)" - )); - drop(placed); - } - drop(opened); - let freed = mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE) != 0; - p.lines.push(format!(" released after the heap went: {freed}")); + }); } } -/// A section and a view of it in a placeholder, as `xmem` maps physical -/// pages: reserved (as it is made today) and committed. -unsafe fn section(p: &mut Probe, rig: &mut Rig) { - const SIZE: usize = 32 * K64; - // SAFETY (the whole function): the sections, placeholder and views - // made below. - unsafe { - let process = windows_sys::Win32::System::Threading::GetCurrentProcess(); - let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; - let reserved = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_RESERVE, 0, SIZE as u32, std::ptr::null()); - if !reserved.is_null() { - let opened = open(&rig.device, From::Section(reserved as usize)); - p.reserved_section_refused = opened.is_err(); - p.lines.push(format!("a section made reserved, as the page pool is today (OpenExistingHeapFromFileMapping): {}", hr(&opened))); - drop(opened); - windows_sys::Win32::Foundation::CloseHandle(reserved); - } - let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null()); - let hole = mem::VirtualAlloc2(process, std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_RESERVE_PLACEHOLDER, mem::PAGE_NOACCESS, std::ptr::null_mut(), 0).cast::<u8>(); - if handle.is_null() || hole.is_null() { - p.lines.push("a committed section: none to try with".to_owned()); - return; - } - // Pages 4..12 of the section at the placeholder's start. - mem::VirtualFree(hole.cast(), 8 * K64, mem::MEM_RELEASE | mem::MEM_PRESERVE_PLACEHOLDER); - let view = mem::MapViewOfFile3(handle, process, hole.cast(), (4 * K64) as u64, 8 * K64, mem::MEM_REPLACE_PLACEHOLDER, mem::PAGE_READWRITE, std::ptr::null_mut(), 0); - let opened = open(&rig.device, From::Section(handle as usize)); - p.lines.push(format!("a section made committed (OpenExistingHeapFromFileMapping): {}", hr(&opened))); - let mut unmapped = false; - if let (Ok(heap), false) = (&opened, view.Value.is_null()) { - p.lines.push(format!(" {}", describe(heap))); - // The section's page 5 is the view's second page. - let placed = place(&rig.device, heap, 5 * K64 as u64, 2 * K64 as u64); - p.lines.push(format!(" a buffer placed at the section's offset of a view's pages: {}", hr(&placed))); - if let Ok(buffer) = &placed { - let memory = hole.add(K64); - fill(memory, 2 * K64, 3); - p.section_reads = rig.fetch(buffer, 0, 2 * K64).is_ok_and(|got| same(memory, &got)); - let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x33).collect(); - p.section_writes = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); - // The guard of `watch.rs`: the view read-only. - let mut old = 0; - let guarded = mem::VirtualProtect(memory.cast(), K64, mem::PAGE_READONLY, &mut old) != 0; - let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x44).collect(); - let through = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); - // The view goes; the GPU writes; another view shows it. - unmapped = mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER) != 0; - let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x55).collect(); - let stored = rig.store(buffer, 0, &new).is_ok(); - let other = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, (5 * K64) as u32, K64); - p.section_outlives_views = unmapped && stored && !other.Value.is_null() && same(other.Value.cast(), &new); - p.lines.push(format!( - " the GPU reads the view's bytes {}; the CPU reads through the view what the GPU wrote {}; the view made read-only under the heap {guarded}, \ - and the GPU writes it all the same {through}; the view unmapped under the heap {unmapped}, the GPU's write then shows in a view mapped afterwards {}", - p.section_reads, p.section_writes, p.section_outlives_views - )); - if !other.Value.is_null() { - mem::UnmapViewOfFile(other); +/// The opener's thread: each ask, oldest first, on the host's device. +#[cfg(not(test))] +fn opener() { + loop { + let ask = { + let mut asked = ASKED.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(ask) = asked.pop_front() { + break ask; } + asked = ASKED_RUNG.wait(asked).unwrap_or_else(|e| e.into_inner()); } + }; + if let Some(host) = crate::host::host() { + open_asked(&host.device, ask); } - drop(opened); - if !unmapped && !view.Value.is_null() { - mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER); - } - windows_sys::Win32::Foundation::CloseHandle(handle); - // The placeholder was split in two: each half is released. - mem::VirtualFree(hole.cast(), 0, mem::MEM_RELEASE); - mem::VirtualFree(hole.add(8 * K64).cast(), 0, mem::MEM_RELEASE); } } -/// What opening costs, on `mb` MB each of private memory never touched -/// and of a committed section never touched: the time, the working set, -/// the card's account of the PC's memory shared with it; and how fast the -/// card copies out of such a heap against a shared buffer of today's kind. -unsafe fn cost(p: &mut Probe, rig: &mut Rig, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) { - let bytes = mb << 20; - let shared = || memory().map_or(0, |m| m[3] >> 20); - let ms = |speed: Option<f64>| speed.map_or("?".to_owned(), |ms| format!("{ms:.1}")); - // SAFETY (the whole function): the allocation and the section below. - unsafe { - let base = mem::VirtualAlloc(std::ptr::null(), bytes, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>(); +/// The opener's work for one ask, on `device`: under [`GATE`], the memory +/// opened in place if it still can be ([`kept_from`], [`most`], +/// [`place_part`]), held ([`hold`]) and kept for a later ask or a switch +/// ([`READY`]). Whether it was. +fn open_asked(device: &ID3D12Device, ask: Ask) -> bool { + let Ask { start, len, window: _ } = ask; + let _gate = GATE.write().unwrap_or_else(|e| e.into_inner()); + if READY.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|r| r.ask == ask) { + return false; + } + if kept_from(start, len) { + STATS[4].fetch_add(1, Ordering::Relaxed); + return false; + } + if STATS[1].load(Ordering::Relaxed) + STATS[3].load(Ordering::Relaxed) + READY_BYTES.load(Ordering::Relaxed) + len > most() { + STATS[6].fetch_add(1, Ordering::Relaxed); + return false; + } + match place_part(device, start, len) { + Ok(placed) => { + hold(start, len, &placed.buffer); + READY_BYTES.fetch_add(len, Ordering::Relaxed); + STATS[16].fetch_add(1, Ordering::Relaxed); + let mut ready = READY.lock().unwrap_or_else(|e| e.into_inner()); + ready.push(Ready { ask, placed, at: crate::host::now_ms() }); + READY_ANY.store(true, Ordering::Release); + true + } + Err(None) => { + STATS[4].fetch_add(1, Ordering::Relaxed); + false + } + Err(Some(e)) => { + if STATS[5].fetch_add(1, Ordering::Relaxed) < 8 { + tracing::warn!(start = format_args!("{start:#x}"), len, error = %e, "title memory not opened in place: a copy instead"); + } + false + } + } +} + +/// Title memory `[at, at + len)` is about to change ([`title_memory_freeing`]): +/// the asks over it are dropped, and what the opener opened over it is let +/// go (its heap goes with its hold, [`reap`]). +fn ready_gone(at: usize, len: usize) { + let end = at.saturating_add(len.max(1)); + ASKED.lock().unwrap_or_else(|e| e.into_inner()).retain(|ask| !ask.over(at, end)); + if !READY_ANY.load(Ordering::Acquire) { + return; + } + let gone: Vec<Ready> = { + let mut ready = READY.lock().unwrap_or_else(|e| e.into_inner()); + let gone = ready.extract_if(.., |r| r.ask.over(at, end)).collect(); + READY_ANY.store(!ready.is_empty(), Ordering::Release); + gone + }; + for r in &gone { + READY_BYTES.fetch_sub(r.ask.len, Ordering::Relaxed); + STATS[7].fetch_add(1, Ordering::Relaxed); + } +} + +/// What the opener opened ([`READY`]) put in the tables in the place of the +/// copy made meanwhile, where that copy can go now +/// ([`crate::shadow::in_place_switch`]); what found no copy waits for a later +/// ask; what waited [`READY_MS`] is let go. From [`tick`], before a +/// submission; not while the opener, or a title's free or protection, holds +/// [`GATE`] (the next tick then). +fn switch_ready() { + switch_ready_at(crate::host::now_ms(), false); +} + +/// [`switch_ready`] at `now` (ms); with `wait`, waiting for [`GATE`] (the +/// tests, whose threads free memory beside). +fn switch_ready_at(now: u64, wait: bool) { + if !READY_ANY.load(Ordering::Acquire) { + return; + } + let _gate = if wait { + GATE.write().unwrap_or_else(|e| e.into_inner()) + } else { + let Ok(gate) = GATE.try_write() else { + return; + }; + gate + }; + // (Out of the lock while the tables are taken: an ask takes it under + // their lock, [`ready_for`].) + let taken = std::mem::take(&mut *READY.lock().unwrap_or_else(|e| e.into_inner())); + let mut kept = Vec::new(); + let mut unused = Vec::new(); + for Ready { ask, placed, at } in taken { + counted(ask.window, ask.len); + match crate::shadow::in_place_switch(ask.start, ask.len, ask.window, placed) { + Ok(()) => { + READY_BYTES.fetch_sub(ask.len, Ordering::Relaxed); + STATS[18].fetch_add(1, Ordering::Relaxed); + } + Err(placed) => { + gone(ask.window, ask.len); + if now < at + READY_MS { + kept.push(Ready { ask, placed, at }); + } else { + READY_BYTES.fetch_sub(ask.len, Ordering::Relaxed); + STATS[19].fetch_add(1, Ordering::Relaxed); + unused.push(placed); + } + } + } + } + let mut ready = READY.lock().unwrap_or_else(|e| e.into_inner()); + ready.extend(kept); + READY_ANY.store(!ready.is_empty(), Ordering::Release); + drop(ready); + // (Their heaps go with their holds, [`reap`].) + drop(unused); +} + +/// [`place_part`] of `[start, start + len)` within [`most`], counted as a +/// window or a title buffer in place. +fn opened(start: u64, len: u64, window: bool) -> Option<Placed> { + if STATS[1].load(Ordering::Relaxed) + STATS[3].load(Ordering::Relaxed) + len > most() { + STATS[6].fetch_add(1, Ordering::Relaxed); + return None; + } + let host = crate::host::host()?; + match place_part(&host.device, start, len) { + Ok(placed) => { + counted(window, len); + Some(placed) + } + Err(None) => { + STATS[4].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + tiled::turned_down(start, len); + None + } + Err(Some(e)) => { + if STATS[5].fetch_add(1, Ordering::Relaxed) < 8 { + tracing::warn!(start = format_args!("{start:#x}"), len, error = %e, "title memory not opened in place: a copy instead"); + } + None + } + } +} + +/// `LEONIDA_INPLACE_OURS`: on (unset), with [`level`] 1 or more, memory of +/// the runtime's own that shaders read as title memory is not copied as if +/// it were the title's. An upload arena (`crate::upload`: what the title's +/// lists get from `allocate_upload`, the structure builder's instance +/// descriptions) is opened in place ([`place_ours`]) instead of a 4 MiB +/// copy in the PC's memory, or, from the card's least size on (4 MiB on +/// budgets of 12 to 20 GiB), a card side and a CPU side of 4 MiB each for +/// bytes the card reads once; in place is what a host upload heap is (the +/// PC's memory, read over the bus). The directory of memory by address +/// (`crate::memory`, 16 MiB) is its copy's CPU side itself +/// (`crate::shadow::by_address_opened`, as the arenas of memory by address +/// are) and sends the entries its one writer changes, instead of a 16 MiB +/// buffer with the same bytes that every list's refresh compared with it. +/// `LEONIDA_INPLACE_OURS=0`, or `LEONIDA_INPLACE` off (the default): copied +/// as title memory, as before. +pub(crate) fn ours() -> bool { + level() >= 1 && crate::toggled!("LEONIDA_INPLACE_OURS") +} + +/// Memory of ours `[start, start + len)` that the title's shaders read as +/// title memory, in place ([`ours`]): opened as [`place_for`] opens title +/// memory and counted with title buffers, but not held ([`hold`]): the +/// title never frees it. +pub(crate) fn place_ours(start: u64, len: u64) -> Option<Placed> { + if !ours() { + return None; + } + opened(start, len, false) +} + +/// `LEONIDA_INPLACE_SECTIONS`: on (unset), with [`level`] on, title memory +/// in the page pool (views of sections of physical pages) that is one run +/// of a section made committed (`LEONIDA_SECTION_COMMIT=1`, `xmem`; or under +/// Wine, where sections are made committed whole) is opened in place in its +/// section ([`in_section`]): the heap is the section, a buffer placed at the +/// run's offset. `LEONIDA_INPLACE_SECTIONS=0`, or a section made reserved +/// (the default): turned down, a copy as before. +/// +/// What holds it up, measured without the game: the host opens a committed +/// section and the card reads the title's bytes through the buffer, also +/// after the view is unmapped and the section's handle closed (the heap is +/// the section; `a_title_buffer_in_a_committed_section_is_read_in_place`, +/// on the RX 7900 XT, and `warp_a_run_of_a_committed_section_opens_in_it`); +/// opening it locks nothing, so the title's frees, protections and +/// unmappings of the pages are not refused as under [`From::Part`] and +/// nothing is held ([`hold`]). What the buffer shows is the section's +/// physical pages, not the address: when the title maps other pages there +/// (or unmaps them) the runtime tells [`title_memory_freeing`] and what is +/// in place there is let go, as a placement in the allocation is; a +/// placement made while that happened is let go at once ([`in_section`] +/// looks again), and the descriptor slots that view it let go of it before +/// the next submission ([`unheld_gone`]). The pages stay the section's +/// while a buffer over them lives, so one a list still holds reads the +/// bytes the title gave up, never memory that went elsewhere. The card's writes reach the +/// pages, so the title sees them at every address it shows them at; another +/// host copy of the same pages is not told (as with any placement: +/// `crate::shadow::Shadow::gpu_writes`), which in the page pool, whose pages +/// the title shows at more than one address, is likelier. +fn sections() -> bool { + crate::toggled!("LEONIDA_INPLACE_SECTIONS") +} + +/// Title memory `[start, start + len)`, one run of `section` from `offset` +/// on, in place in the section ([`place_in_section`]), within [`most`] +/// (counted with the rest, though a section's heap locks nothing), counted +/// as a window or a title buffer in place. +fn in_section(start: u64, len: u64, window: bool, section: usize, offset: u64) -> Option<Placed> { + if STATS[1].load(Ordering::Relaxed) + STATS[3].load(Ordering::Relaxed) + len > most() { + STATS[6].fetch_add(1, Ordering::Relaxed); + return None; + } + let host = crate::host::host()?; + match place_in_section(&host.device, section, offset, len) { + Ok(placed) => { + counted(window, len); + #[cfg(test)] + if let Some((at, bytes)) = TEST_REMAPPED_WHILE_PLACING.take() { + // The title maps other pages there now (the let-go that + // follows waits for the caller's table lock). + views_gone(at, bytes); + } + // Still what the title shows there: else it mapped other pages + // meanwhile, and the let-go that followed (`title_memory_freeing`, + // after the views were forgotten) may have looked before this was + // counted. The caller holds the table the let-go takes this out + // of until it is in it. + if cover(start as usize, len as usize) != Cover::Run(section, offset) { + gone(window, len); + STATS[7].fetch_add(1, Ordering::Relaxed); + return None; + } + STATS[15].fetch_add(1, Ordering::Relaxed); + Some(placed) + } + Err(None) => { + STATS[4].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + tiled::turned_down(start, len); + None + } + Err(Some(e)) => { + if STATS[5].fetch_add(1, Ordering::Relaxed) < 8 { + tracing::warn!( + start = format_args!("{start:#x}"), + len, + error = %e, + "title memory not opened in place in its section: a copy instead" + ); + } + None + } + } +} + +/// `len` bytes of `section` from `offset` on, in a heap opened on the +/// section ([`From::Section`], one per section and device: +/// [`section_heap`]) and a buffer placed over the 64 KiB pages that hold +/// them. `Err` with nothing if the runtime made no such section, made it +/// reserved (which the host refuses) or the bytes pass its end; with the +/// host's error if it refused (it is not asked again for that section). +pub(crate) fn place_in_section(device: &ID3D12Device, section: usize, offset: u64, len: u64) -> Result<Placed, Option<windows::core::Error>> { + let Some(&(bytes, committed)) = views().sections.get(§ion) else { + return Err(None); + }; + let first = offset - offset % K64 as u64; + let bias = offset - first; + let width = (bias + len.max(1)).next_multiple_of(K64 as u64); + if !committed || first + width > bytes { + return Err(None); + } + let heap = section_heap(device, section).map_err(Some)?; + let buffer = place(device, &heap, first, width).map_err(Some)?; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() } + bias; + Ok(Placed { buffer, heap, gpu, bias }) +} + +/// Heaps opened on sections of physical pages, by device and section +/// handle (`None`: the host refused); forgotten when the runtime lets go of +/// the section or gives its handle's number to another +/// ([`title_memory_section`], [`title_memory_section_gone`]). A buffer +/// placed in one holds the heap itself. +#[allow(clippy::type_complexity)] +static SECTION_HEAPS: std::sync::Mutex<BTreeMap<(usize, usize), Option<ID3D12Heap>>> = std::sync::Mutex::new(BTreeMap::new()); + +/// The heap opened on `section` on `device`, opened when first asked for. +/// One per section: every placement opening its own mapped the whole +/// section for the card again (sections are 16 MiB by default, up to the +/// whole allocation under Wine). +fn section_heap(device: &ID3D12Device, section: usize) -> windows::core::Result<ID3D12Heap> { + let key = (device.as_raw() as usize, section); + let mut heaps = SECTION_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + match heaps.get(&key) { + Some(Some(heap)) => return Ok(heap.clone()), + Some(None) => return Err(windows::core::Error::from(windows::Win32::Foundation::E_INVALIDARG)), + None => {} + } + let opened = open(device, From::Section(section)); + heaps.insert(key, opened.as_ref().ok().cloned()); + opened +} + +/// The runtime lets go of `section` (or its handle's number names another +/// from now on): the heaps opened on it are forgotten. +fn section_heaps_gone(section: usize) { + let gone: Vec<Option<ID3D12Heap>> = { + let mut heaps = SECTION_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let keys: Vec<(usize, usize)> = heaps.keys().filter(|key| key.1 == section).copied().collect(); + keys.into_iter().filter_map(|key| heaps.remove(&key)).collect() + }; + // Released after the lock. + drop(gone); +} + +/// Something placed elsewhere (`crate::port`) in the same form: counted as +/// [`place_for`] counts, so that [`gone`] takes it off again. +pub(crate) fn counted(window: bool, bytes: u64) { + let at = if window { 0 } else { 2 }; + STATS[at].fetch_add(1, Ordering::Relaxed); + STATS[at + 1].fetch_add(bytes, Ordering::Relaxed); +} + +/// What [`place_for`] gave is gone. +pub(crate) fn gone(window: bool, bytes: u64) { + let at = if window { 0 } else { 2 }; + STATS[at].fetch_sub(1, Ordering::Relaxed); + STATS[at + 1].fetch_sub(bytes, Ordering::Relaxed); +} + +/// Title memory `[at, at + len)` is about to show something else, or the +/// title is about to decommit, free or protect it: what is in place there +/// is let go (the tables forget it; its heap goes when the last list and +/// slot that hold it do, [`reap`]). Called for memory the runtime maps +/// anew, and before the title's own `VirtualFree` +/// (`crate::watch::title_memory_freed`). +pub fn title_memory_freeing(at: usize, len: usize) { + // Renderer port 1's regions there: no longer what the title shows. + crate::port::forget(at, len); + // What the opener opened there, before the tables are looked at: an ask + // that takes it puts it in them under their lock ([`ready_for`]). + ready_gone(at, len); + // And what was noted to be opened again there ([`AGAIN`]). + again_gone(at, len); + if !anything_placed() && !crate::shadow::sourced_any() { + return; + } + let gone = crate::shadow::in_place_let_go(at as u64, len as u64); + STATS[7].fetch_add(gone.len() as u64, Ordering::Relaxed); + unheld_gone(gone); +} + +/// Of the buffers [`title_memory_freeing`] took out of the tables, those +/// nothing holds for the title's frees ([`HELD`]): placements in a section +/// of physical pages ([`in_section`]), whose heap locks nothing, so the +/// title maps other pages there with no free or protection the runtime +/// sees. Kept for the descriptor slots that view them to let go of them +/// before the next submission ([`slots_let_go_of_unheld`], from [`tick`]), +/// with [`slots`] on. +/// +/// A slot shows the section's physical pages, not the address: kept, a +/// title descriptor written once for page-pool memory went on reading the +/// pages the title gave up after it mapped others there (and whatever it +/// wrote into them once it mapped them elsewhere), where the console reads +/// the address, and the copy it viewed before had the new pages' bytes at +/// the next refresh; and it kept the section's heap (and its commit) for +/// as long. (The placements that are held let go of their slots where the +/// title's free or protection is seen: [`title_memory_free_held`], +/// [`let_go_under`].) Not at once: the runtime maps with its own locks held +/// (`leonida_hle`'s xmem), and every slot of every view heap is looked at +/// under the slots' locks, which a thread making a slot holds while it may +/// wait for that mapping to end (`crate::watch::title_memory_remapping`). +/// +/// shortcut: a list recorded after the title mapped other pages there and +/// submitted before the slots were let go of reads the old pages through +/// them, and one recorded before and submitted after reads zeros; as with +/// any placement, a list that holds the buffer in a dynamic slot of its own +/// reads the old pages until it is reset. +fn unheld_gone(gone: Vec<ID3D12Resource>) { + if gone.is_empty() || !slots() { + return; + } + let held: Vec<usize> = { + let held = HELD.lock().unwrap_or_else(|e| e.into_inner()); + held.iter().filter_map(|h| Some(h.buffer.as_ref()?.as_raw() as usize)).collect() + }; + let mut unheld = UNHELD_GONE.lock().unwrap_or_else(|e| e.into_inner()); + unheld.extend(gone.into_iter().filter(|b| !held.contains(&(b.as_raw() as usize)))); + UNHELD_WAITING.store(!unheld.is_empty(), Ordering::Release); +} + +/// The buffers [`unheld_gone`] keeps (held here, so that no other buffer +/// takes the address they are known by until their slots are let go of). +static UNHELD_GONE: std::sync::Mutex<Vec<ID3D12Resource>> = std::sync::Mutex::new(Vec::new()); + +/// Whether [`UNHELD_GONE`] has any, for [`tick`] to look at it only then. +static UNHELD_WAITING: AtomicBool = AtomicBool::new(false); + +/// The descriptor slots that view a buffer [`unheld_gone`] keeps let go of +/// it now ([`slots_let_go_of`], with `now`: the title gave up those pages +/// at that address); the buffers go after (retired already). Returns how +/// many slots. On the submitting thread before a submission ([`tick`]), no +/// lock of the runtime's held. +pub(crate) fn slots_let_go_of_unheld() -> u32 { + if !UNHELD_WAITING.swap(false, Ordering::AcqRel) { + return 0; + } + let gone = std::mem::take(&mut *UNHELD_GONE.lock().unwrap_or_else(|e| e.into_inner())); + let raw: Vec<usize> = gone.iter().map(|b| b.as_raw() as usize).collect(); + let n = slots_let_go_of(&raw, true); + drop(gone); + n +} + +/// Whether anything is in place now ([`place_for`], [`counted`]). +pub(crate) fn anything_placed() -> bool { + STATS[0].load(Ordering::Relaxed) + STATS[2].load(Ordering::Relaxed) != 0 || READY_ANY.load(Ordering::Acquire) +} + +/// The line of what is in place, every ten seconds while [`level`] is on. +fn say() { + static LAST: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms(); + let last = LAST.load(Ordering::Relaxed); + if now < last + 10_000 || LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + let s: Vec<u64> = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + tracing::info!( + "title memory in place: {} windows {} MB, {} title buffers {} MB (no copy, no refresh, no copy-back), {} opened so far in their section of physical \ + pages (LEONIDA_INPLACE_SECTIONS); turned down: {} view memory not one run of a committed section or not private memory committed whole, \ + {} refused by the host, {} over LEONIDA_INPLACE_MB; {} let go because their memory changed; the title's frees under a heap: {} releases done \ + once it went ({} waiting, {} given up), {} decommits kept committed and zeroed (LEONIDA_INPLACE_FREE), {} descriptor slots let go of \ + a buffer over memory given up (LEONIDA_INPLACE_SLOTS); the title's protections under a heap: {} made once it went ({} waiting, \ + {} given up) (LEONIDA_INPLACE_PROTECT); {} reservations at a fixed address made once the releases kept there were done \ + (LEONIDA_INPLACE_RESERVE); {} opened in the background, {} taken by a later ask, {} switched from a copy at a safe point, {} given up \ + unused, {} MB waiting (LEONIDA_INPLACE_ASYNC), {} shader writes declared on either side of a switch while lists held the copy (LEONIDA_INPLACE_SWITCH_HELD); {} copies asked again once their memory was read-write again (LEONIDA_INPLACE_AGAIN)", + s[0], + s[1] >> 20, + s[2], + s[3] >> 20, + s[15], + s[4], + s[5], + s[6], + s[7], + s[8], + PENDING.lock().unwrap_or_else(|e| e.into_inner()).len(), + s[10], + s[9], + s[11], + s[12], + PROTECTS.lock().unwrap_or_else(|e| e.into_inner()).len(), + s[13], + s[14], + s[16], + s[17], + s[18], + s[19], + READY_BYTES.load(Ordering::Relaxed) >> 20, + s[21], + s[20] + ); + #[cfg(feature = "diagnostics")] + if let Some(line) = tiled::line() { + tracing::info!("{line}"); + } +} + +/// What a heap is opened on. +pub(crate) enum From { + /// A whole `VirtualAlloc` allocation, by its base address. + Region(usize), + /// A committed part of one: address and bytes. + Part(usize, usize), + /// A section made with `SEC_COMMIT`, by its handle. + Section(usize), +} + +/// Opens a heap on memory the process has. +pub(crate) fn open(device: &ID3D12Device, from: From) -> windows::core::Result<ID3D12Heap> { + // SAFETY: the calls take an address or a handle and check both + // themselves; a refusal is an error code. + unsafe { + match from { + From::Region(at) => device.cast::<ID3D12Device3>()?.OpenExistingHeapFromAddress(at as *const c_void), + From::Part(at, bytes) => device.cast::<ID3D12Device13>()?.OpenExistingHeapFromAddress1(at as *const c_void, bytes), + From::Section(handle) => device.cast::<ID3D12Device3>()?.OpenExistingHeapFromFileMapping(HANDLE(handle as *mut c_void)), + } + } +} + +fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + } +} + +/// A buffer of `size` bytes at `offset` (a multiple of 64 KiB) of an +/// opened heap, which shaders may read and write, in the common state. +pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: u64) -> windows::core::Result<ID3D12Resource> { + let mut placed: Option<ID3D12Resource> = None; + // The heap is cross-adapter shared, so the buffer must say so too. + let flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + // SAFETY: plain creation in a live heap. + unsafe { device.CreatePlacedResource(heap, offset, &buffer_desc(size, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut placed)? }; + let placed = placed.ok_or_else(windows::core::Error::empty)?; + #[cfg(feature = "diagnostics")] + crate::census::placed(&placed, "buffers placed in title memory"); + Ok(placed) +} + +// The title's views of its physical pages, as the runtime maps them: the +// census needs them to say which view memory is one run of a section (one +// placed buffer could show it) and which is scattered pages. + +struct Views { + /// By address: bytes, the section's handle, the offset in it. + views: BTreeMap<usize, (usize, usize, u64)>, + /// By section and byte offset of a 64 KiB page: the address of that + /// page in every view that shows it. A write through one view of a + /// page is a write of the bytes every other view shows + /// (`crate::watch` guards them all). + pages: BTreeMap<(usize, u64), Vec<usize>>, + /// Of those, how many are shown more than once. + pages_twice: usize, + /// Sections by handle: bytes, and whether made committed. (In maps, not + /// vectors looked through: with `LEONIDA_SECTION_MB` an allocation of the + /// title's is thousands of sections, and [`beside`] and [`beside_page`] + /// look one up for every landing and every store of the title's that is + /// made beside the guards; after Fayberr's fork fa064482 and + /// LooperSalty's ee8b92e, GPL-3.0, which changed the same with their + /// small sections.) + sections: BTreeMap<usize, (u64, bool)>, + /// Our own view of a whole section, by its handle (0: the host gave + /// none), made when first asked for ([`beside`]) and kept. + whole: BTreeMap<usize, usize>, +} + +/// Read by many threads at once (write faults, landings), changed when the +/// runtime maps or unmaps. +static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views { + views: BTreeMap::new(), + pages: BTreeMap::new(), + pages_twice: 0, + sections: BTreeMap::new(), + whole: BTreeMap::new(), +}); + +fn views() -> std::sync::RwLockReadGuard<'static, Views> { + VIEWS.read().unwrap_or_else(|e| e.into_inner()) +} + +fn views_mut() -> std::sync::RwLockWriteGuard<'static, Views> { + VIEWS.write().unwrap_or_else(|e| e.into_inner()) +} + +/// The runtime made a section of `bytes` for physical pages; `committed` +/// if with `SEC_COMMIT` (only such a section can be opened as a heap). +pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { + { + let mut v = views_mut(); + // A handle's number given out again: the view was of the section that + // had it before (it stays mapped: someone may be writing through it). + v.whole.remove(§ion); + v.sections.insert(section, (bytes, committed)); + } + // And so were the heaps opened on it ([`section_heap`]). + section_heaps_gone(section); +} + +/// The runtime lets go of a section, and of its handle: no view the title +/// sees is of it any more, and [`beside`]'s view goes. +pub fn title_memory_section_gone(section: usize) { + let whole = { + let mut v = views_mut(); + v.whole.remove(§ion) + }; + // The buffers placed in it hold their heap, and with it the section. + section_heaps_gone(section); + if let Some(base) = whole.filter(|&base| base != 0) { + // SAFETY: a view of ours. Who writes through it found the section + // in a view the title saw and holds off its unmapping + // (`crate::watch::title_memory_reading`), which came before this. + unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: base as *mut c_void }) }; + } +} + +/// The runtime mapped `[at, at + len)` as a view of `section` from +/// `offset` on. Call after [`crate::title_memory_remapped`] of the range. +pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { + { + let mut v = views_mut(); + v.views.insert(at, (len, section, offset)); + for k in 0..len.div_ceil(K64) { + let shown = v.pages.entry((section, offset + (k * K64) as u64)).or_default(); + shown.push(at + k * K64); + let twice = shown.len() == 2; + v.pages_twice += usize::from(twice); + } + } + // This view is writable from now on: a guard over the same bytes at + // another view must look at them again, and the pages are noted written + // there (`crate::watch`). + crate::watch::views_mapped(section, offset, len); + #[cfg(feature = "diagnostics")] + tiled::views_changed(at, len, true); +} + +/// Whether the card reads the title memory `[at, at + len)` in place from +/// its section: the section the runtime noted behind it, all of it one run +/// ([`title_memory_view`], [`Cover::Run`]), opened as a host heap +/// ([`From::Section`]: the heap is the section, so it does not change when +/// the title maps the pages elsewhere), a buffer placed at the run's offset +/// in it, and what the card copies out of the buffer equal to what the CPU +/// reads at `at`. `None` without a host device; `Some(Err)` if the range is +/// not one run of a section the runtime made, or the host refuses (as it +/// does a section made with `SEC_RESERVE`). For the runtime's tests of how +/// it makes the page pool (`leonida_hle`'s xmem, `LEONIDA_SECTION_COMMIT`); +/// nothing is held once it returns. The caller keeps the range mapped. +pub fn title_memory_reads_in_place(at: usize, len: usize) -> Option<Result<bool, String>> { + let host = crate::host::host()?; + let Cover::Run(section, offset) = cover(at, len) else { + return Some(Err(format!("{at:#x}+{len:#x} is not one run of a section"))); + }; + if !views().sections.contains_key(§ion) { + return Some(Err(format!("no section {section:#x} made by the runtime"))); + } + let read = || -> windows::core::Result<bool> { + let heap = open(&host.device, From::Section(section))?; + let start = offset - offset % K64 as u64; + let within = (offset - start) as usize; + let buffer = place(&host.device, &heap, start, (within + len).next_multiple_of(K64) as u64)?; + let got = Rig::new(&host.device)?.fetch(&buffer, within as u64, len)?; + let mut seen = vec![0u8; len]; + // SAFETY: the caller's mapped title memory of `len` bytes. + unsafe { std::ptr::copy_nonoverlapping(at as *const u8, seen.as_mut_ptr(), len) }; + Ok(got == seen) + }; + Some(read().map_err(|e| e.to_string())) +} + +/// Title memory `[at, at + len)` (private memory committed whole) opened in +/// place on the host device and held as [`place_for`] holds what it opens +/// ([`hold`]), for the runtime's tests of the title's frees, protections, +/// reservations and queries of such memory through the glue (`leonida_hle`'s +/// xmem): the heap stands while the returned object lives, as while a list +/// or a descriptor slot shows its buffer, and nothing else holds it (it is in +/// no table). `None` without a host device, one that does not open parts of +/// an allocation, or with `LEONIDA_INPLACE_FREE=0`; `Err` if refused. +pub fn title_memory_held_in_place(at: usize, len: usize) -> Option<Result<HeldInPlace, String>> { + let host = crate::host::host()?; + if host.device.cast::<ID3D12Device13>().is_err() || !frees() { + return None; + } + Some(match place_part(&host.device, at as u64, len as u64) { + Ok(placed) => { + hold(at as u64, len as u64, &placed.buffer); + Ok(HeldInPlace(Some(placed.buffer))) + } + Err(e) => Err(format!("{e:?}")), + }) +} + +/// A buffer [`title_memory_held_in_place`] placed over title memory. Dropped, +/// it lets go of the buffer and what waited for its heap is tried again +/// ([`reap`]), as [`tick`] would next. +pub struct HeldInPlace(Option<ID3D12Resource>); + +impl Drop for HeldInPlace { + fn drop(&mut self) { + drop(self.0.take()); + reap(); + } +} + +/// What `[at, at + len)` showed is gone ([`crate::title_memory_remapped`]): +/// the views that touch it are forgotten (the runtime tells again those it +/// maps anew). +pub(crate) fn views_gone(at: usize, len: usize) { + #[cfg(feature = "diagnostics")] + tiled::views_changed(at, len, false); + let mut v = views_mut(); + if v.views.is_empty() { + return; + } + let end = at.saturating_add(len); + let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base); + let gone: Vec<usize> = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect(); + for base in gone { + let Some((bytes, section, offset)) = v.views.remove(&base) else { + continue; + }; + for k in 0..bytes.div_ceil(K64) { + let key = (section, offset + (k * K64) as u64); + if let Some(pages) = v.pages.get_mut(&key) { + let page = base + k * K64; + let before = pages.len(); + pages.retain(|&shown| shown != page); + let after = pages.len(); + if after == 0 { + v.pages.remove(&key); + } + v.pages_twice = v.pages_twice.saturating_sub(usize::from(before >= 2 && after < 2)); + } + } + } +} + +/// The 64 KiB pages of `[start, end)` that the title shows at other +/// addresses too, in address order, each with those; not the ones it shows +/// in very many views (`crate::watch::MANY_VIEWS`). +pub(crate) fn shown_elsewhere(start: usize, end: usize) -> Vec<(usize, Vec<usize>)> { + let v = views(); + let mut out = Vec::new(); + if start >= end || v.pages_twice == 0 { + return out; + } + let first = v.views.range(..=start).next_back().filter(|(base, view)| *base + view.0 > start).map(|(base, _)| *base); + for (&base, &(bytes, section, offset)) in v.views.range(first.unwrap_or(start)..end) { + let from = start.max(base) & !(K64 - 1); + for page in (from..end.min(base + bytes)).step_by(K64) { + let Some(shown) = v.pages.get(&(section, offset + (page - base) as u64)) else { + continue; + }; + if (2..=crate::watch::MANY_VIEWS).contains(&shown.len()) { + out.push((page, shown.iter().copied().filter(|&at| at != page).collect())); + } + } + } + out +} + +/// The 64 KiB pages at other addresses that show a page of `[start, end)`, +/// however many views show it (unlike [`shown_elsewhere`]); `None` if they are +/// more than `most`. +pub(crate) fn shown_anywhere_else(start: usize, end: usize, most: usize) -> Option<Vec<usize>> { + let v = views(); + let mut out = Vec::new(); + if start >= end || v.pages_twice == 0 { + return Some(out); + } + let first = v.views.range(..=start).next_back().filter(|(base, view)| *base + view.0 > start).map(|(base, _)| *base); + for (&base, &(bytes, section, offset)) in v.views.range(first.unwrap_or(start)..end) { + let from = start.max(base) & !(K64 - 1); + for page in (from..end.min(base + bytes)).step_by(K64) { + let Some(shown) = v.pages.get(&(section, offset + (page - base) as u64)) else { + continue; + }; + if shown.len() < 2 { + continue; + } + if out.len() + shown.len() - 1 > most { + return None; + } + out.extend(shown.iter().copied().filter(|&at| at != page)); + } + } + Some(out) +} + +/// The address of the 64 KiB page shown at `page` in every title view that +/// shows it, `page`'s own address included; empty if `page` is not a view. +pub(crate) fn pages_of(page: usize) -> Vec<usize> { + let v = views(); + let Some((&base, &(bytes, section, offset))) = v.views.range(..=page).next_back() else { + return Vec::new(); + }; + let within = page.wrapping_sub(base); + if within >= bytes || !within.is_multiple_of(K64) { + return Vec::new(); + } + v.pages.get(&(section, offset + within as u64)).cloned().unwrap_or_default() +} + +/// The title views that show any of the physical bytes `[offset, offset + +/// len)` of `section`, as `(address, bytes)` ranges in address order; not +/// those of a page shown in very many views (`MANY_VIEWS`). +pub(crate) fn views_of_section(section: usize, offset: u64, len: usize) -> Vec<(usize, usize)> { + if len == 0 { + return Vec::new(); + } + let v = views(); + let end = offset.saturating_add(len as u64); + let mut pages: Vec<usize> = Vec::new(); + let mut at = offset - offset % K64 as u64; + while at < end { + if let Some(shown) = v.pages.get(&(section, at)) + && shown.len() <= crate::watch::MANY_VIEWS + { + pages.extend(shown.iter().copied()); + } + match at.checked_add(K64 as u64) { + Some(next) => at = next, + None => break, + } + } + pages.sort_unstable(); + pages.dedup(); + let mut runs: Vec<(usize, usize)> = Vec::with_capacity(pages.len()); + for page in pages { + match runs.last_mut() { + Some((first, bytes)) if *first + *bytes == page => *bytes += K64, + _ => runs.push((page, K64)), + } + } + runs +} + +/// How many bytes of `[at, at + len)` views of physical pages show; `None` +/// if no view touches it (nothing is mapped there, or memory of another +/// kind). The runtime's own record of what it mapped: no question to the +/// host. +pub(crate) fn shown_bytes(at: usize, len: usize) -> Option<u64> { + let end = at.saturating_add(len); + let v = views(); + let first = v.views.range(..=at).next_back(); + let rest = v.views.range(at.saturating_add(1)..end.max(at.saturating_add(1))); + let (mut there, mut any) = (0u64, false); + for (&base, view) in first.into_iter().chain(rest) { + let (from, to) = (base.max(at), base.saturating_add(view.0).min(end)); + if from < to { + there += (to - from) as u64; + any = true; + } + } + any.then_some(there) +} + +/// What of `[at, at + len)` views of physical pages show, in order, pieces +/// that touch as one: (address, bytes). Empty: nothing, or memory of another +/// kind. +pub(crate) fn shown_runs(at: usize, len: usize) -> Vec<(usize, usize)> { + let end = at.saturating_add(len); + let v = views(); + let first = v.views.range(..=at).next_back(); + let rest = v.views.range(at.saturating_add(1)..end.max(at.saturating_add(1))); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for (&base, view) in first.into_iter().chain(rest) { + let (from, to) = (base.max(at), base.saturating_add(view.0).min(end)); + if from >= to { + continue; + } + match runs.last_mut() { + Some((run, bytes)) if *run + *bytes == from => *bytes += to - from, + _ => runs.push((from, to - from)), + } + } + runs +} + +/// How the views cover `[at, at + len)`. +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub(crate) enum Cover { + /// No view holds its first byte. + None, + /// Views hold a part of it only. + Holes, + /// Views hold all of it, from more than one place. + Scattered, + /// All of it is one run of one section: the section and the offset of + /// `at` in it. + Run(usize, u64), +} + +fn cover_in(views: &BTreeMap<usize, (usize, usize, u64)>, at: usize, len: usize) -> Cover { + let end = at + len.max(1); + let Some((&base, &(bytes, section, offset))) = views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at) else { + return Cover::None; + }; + let first = (section, offset + (at - base) as u64); + let (mut reached, mut one) = (base + bytes, true); + while reached < end { + let Some(&(bytes, s, o)) = views.get(&reached) else { + return Cover::Holes; + }; + one &= s == first.0 && o == first.1 + (reached - at) as u64; + reached += bytes; + } + if one { Cover::Run(first.0, first.1) } else { Cover::Scattered } +} + +/// [`Cover`] of `[at, at + len)` by the title's views as they are now. +pub(crate) fn cover(at: usize, len: usize) -> Cover { + cover_in(&views().views, at, len) +} + +/// The whole stretch of views around `[at, at + len)` that follow one +/// another in memory and in one section alike, if the range is one run of a +/// section ([`Cover::Run`]): its first address, its bytes, the section and +/// the offset of its first byte in it. +pub(crate) fn stretch(at: usize, len: usize) -> Option<(usize, usize, usize, u64)> { + let v = views(); + stretch_in(&v.views, at, len) +} + +fn stretch_in(views: &BTreeMap<usize, (usize, usize, u64)>, at: usize, len: usize) -> Option<(usize, usize, usize, u64)> { + let Cover::Run(section, offset) = cover_in(views, at, len) else { + return None; + }; + // Every view of the stretch has the same address less section offset. + let delta = at as i128 - offset as i128; + let follows = |a: usize, s: usize, o: u64| s == section && a as i128 - o as i128 == delta; + let (&first, &(n, _, _)) = views.range(..=at).next_back()?; + let mut start = first; + for (&a, &(n, s, o)) in views.range(..first).rev() { + if a + n != start || !follows(a, s, o) { + break; + } + start = a; + } + let mut stop = first + n; + for (&a, &(n, s, o)) in views.range(first + 1..) { + if a != stop || !follows(a, s, o) { + break; + } + stop = a + n; + } + Some((start, stop - start, section, (start as i128 - delta) as u64)) +} + +/// Another address of the title memory `[at, at + len)`, if it is a view of +/// the title's pages, all of it one run of a section: in a view of ours of +/// the whole section, which is never guarded (`crate::watch`) nor changed. +/// +/// The section is made committed, or its pages are reserved and the +/// runtime commits each before it shows it, which holds for every view of +/// the section. The caller holds +/// `crate::watch::title_memory_reading`: until it lets go the title sees +/// the same pages at `at`. +pub(crate) fn beside(at: usize, len: usize) -> Option<usize> { + let known = { + let v = views(); + let Cover::Run(section, offset) = cover_in(&v.views, at, len) else { + return None; + }; + v.whole.get(§ion).map(|&base| (base, offset)) + }; + if let Some((base, offset)) = known { + return (base != 0).then(|| base + offset as usize); + } + let mut v = views_mut(); + let Cover::Run(section, offset) = cover_in(&v.views, at, len) else { + return None; + }; + let base = match v.whole.get(§ion) { + Some(&base) => base, + None => { + let &(bytes, _) = v.sections.get(§ion)?; + // SAFETY: the whole of a section the runtime made; a view the + // title sees is of it, so its handle is open. + let base = unsafe { mem::MapViewOfFile(section as _, mem::FILE_MAP_WRITE, 0, 0, bytes as usize) }.Value as usize; + if base == 0 { + tracing::warn!(error = %std::io::Error::last_os_error(), "no view of the title's pages beside its own"); + } + v.whole.insert(section, base); + base + } + }; + (base != 0).then(|| base + offset as usize) +} + +/// Our own address of the 64 KiB page the title sees at `page` ([`beside`]), +/// and every address the title sees it at (0: no more); `None` if the page is +/// in no view of a section, or in very many. While the caller holds +/// `crate::watch::title_memory_reading`. +pub(crate) fn beside_page(page: usize) -> Option<(usize, [usize; 8])> { + for asked in [false, true] { + { + let v = views(); + let (&base, &(bytes, section, offset)) = v.views.range(..=page).next_back()?; + let within = page.wrapping_sub(base); + if within >= bytes || !within.is_multiple_of(K64) { + return None; + } + let offset = offset + within as u64; + if let Some(&whole) = v.whole.get(§ion) { + let mut shown = [0; 8]; + let all = v.pages.get(&(section, offset))?; + shown.get_mut(..all.len())?.copy_from_slice(all); + return (whole != 0).then(|| (whole + offset as usize, shown)); + } + } + if asked || beside(page, K64).is_none() { + return None; + } + } + None +} + +/// Whether `[at, at + len)` is private memory, all committed and +/// read-write: what [`From::Part`] takes. One question to Windows (it +/// walks the page tables to the end of the pages that share the first +/// one's state: a millisecond in the title's big blocks, so ask when a +/// copy is made, not when it is used). +pub(crate) fn private_whole(at: usize, len: usize) -> bool { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + n != 0 + && info.State == mem::MEM_COMMIT + && info.Type == mem::MEM_PRIVATE + && info.Protect == mem::PAGE_READWRITE + && (info.BaseAddress as usize).saturating_add(info.RegionSize) >= at.saturating_add(len) +} + +fn hr<T>(result: &windows::core::Result<T>) -> String { + match result { + Ok(_) => "ok".to_owned(), + Err(e) => format!("REFUSED {:#010x} ({})", e.code().0, e.message().trim()), + } +} + +/// A queue, a list and a fence of the probe's own on `device`: nothing of +/// the host's submissions is touched. +pub(crate) struct Rig { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + done: u64, + event: HANDLE, +} + +impl Drop for Rig { + fn drop(&mut self) { + // SAFETY: our event. + unsafe { + let _ = windows::Win32::Foundation::CloseHandle(self.event); + } + } +} + +impl Rig { + pub(crate) fn new(device: &ID3D12Device) -> windows::core::Result<Rig> { + // SAFETY: plain creation of objects of our own. + unsafe { + let queue: ID3D12CommandQueue = + device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })?; + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.Close()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + Ok(Rig { device: device.clone(), queue, allocator, list, fence, done: 0, event }) + } + } + + /// Records with `record`, runs it and waits (ten seconds at most). + fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> windows::core::Result<()> { + // SAFETY: our own list and queue, one run at a time. + unsafe { + self.allocator.Reset()?; + self.list.Reset(&self.allocator, None)?; + record(&self.list); + self.list.Close()?; + self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]); + self.done += 1; + self.queue.Signal(&self.fence, self.done)?; + self.fence.SetEventOnCompletion(self.done, self.event)?; + if WaitForSingleObject(self.event, 10_000).0 != 0 { + return Err(windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)); + } + self.device.GetDeviceRemovedReason() + } + } + + fn committed(&self, kind: D3D12_HEAP_TYPE, size: u64, state: D3D12_RESOURCE_STATES) -> windows::core::Result<ID3D12Resource> { + let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain creation. + unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, D3D12_RESOURCE_FLAG_NONE), state, None, &mut buffer)? + }; + buffer.ok_or_else(windows::core::Error::empty) + } + + /// What the GPU reads of `size` bytes of `resource` from `offset`. + pub(crate) fn fetch(&mut self, resource: &ID3D12Resource, offset: u64, size: usize) -> windows::core::Result<Vec<u8>> { + let back = self.committed(D3D12_HEAP_TYPE_READBACK, size as u64, D3D12_RESOURCE_STATE_COPY_DEST)?; + // SAFETY: two live buffers, the range inside both. + self.run(|list| unsafe { list.CopyBufferRegion(&back, 0, resource, offset, size as u64) })?; + let mut data = std::ptr::null_mut(); + // SAFETY: the mapping holds `size` bytes until unmapped. + unsafe { + back.Map(0, None, Some(&mut data))?; + let bytes = std::slice::from_raw_parts(data.cast::<u8>(), size).to_vec(); + back.Unmap(0, None); + Ok(bytes) + } + } + + /// The GPU writes `bytes` at `offset` of `resource` (a copy). + pub(crate) fn store(&mut self, resource: &ID3D12Resource, offset: u64, bytes: &[u8]) -> windows::core::Result<()> { + let up = self.committed(D3D12_HEAP_TYPE_UPLOAD, bytes.len() as u64, D3D12_RESOURCE_STATE_GENERIC_READ)?; + let mut data = std::ptr::null_mut(); + // SAFETY: the mapping holds the buffer's bytes until unmapped. + unsafe { + up.Map(0, None, Some(&mut data))?; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.cast::<u8>(), bytes.len()); + up.Unmap(0, None); + } + // SAFETY: two live buffers, the range inside both. + self.run(|list| unsafe { list.CopyBufferRegion(resource, offset, &up, 0, bytes.len() as u64) }) + } + + /// A compute shader stores, through a root unordered-access view at + /// `gpu`, the sum of the buffer's first two words in its third. + fn shade(&mut self, gpu: u64) -> windows::core::Result<()> { + const SOURCE: &str = "#define RS \"UAV(u0)\"\nRWByteAddressBuffer b : register(u0);\n[RootSignature(RS)]\n[numthreads(1, 1, 1)]\nvoid main() { b.Store(8, b.Load(0) + b.Load(4)); }\n"; + let mut code: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the call; then the + // blob's own bytes, which hold the root signature too. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("inplace"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?; + let code = code.ok_or_else(windows::core::Error::empty)?; + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, + ..Default::default() + })?; + (root, pso) + }; + // SAFETY: an open list of ours; the view names a live buffer. + self.run(|list| unsafe { + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, gpu); + list.Dispatch(1, 1, 1); + }) + } + + /// Milliseconds the card takes to copy `bytes` of `from` into its own + /// memory, the best of three. + fn copy_ms(&mut self, from: &ID3D12Resource, bytes: u64) -> windows::core::Result<f64> { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut to: Option<ID3D12Resource> = None; + // SAFETY: plain creation. + unsafe { + self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, None, &mut to)? + }; + let to = to.ok_or_else(windows::core::Error::empty)?; + let mut best = f64::MAX; + for _ in 0..3 { + let started = std::time::Instant::now(); + // SAFETY: two live buffers of `bytes` bytes or more. + self.run(|list| unsafe { list.CopyBufferRegion(&to, 0, from, 0, bytes) })?; + best = best.min(started.elapsed().as_secs_f64() * 1000.0); + } + Ok(best) + } +} + +fn fill(at: *mut u8, len: usize, seed: u8) { + for i in 0..len { + // SAFETY: the caller's own committed memory of `len` bytes. + unsafe { at.add(i).write((i as u8).wrapping_mul(31).wrapping_add(seed)) }; + } +} + +fn same(at: *const u8, bytes: &[u8]) -> bool { + // SAFETY: the caller's own committed memory of that length. + unsafe { std::slice::from_raw_parts(at, bytes.len()) == bytes } +} + +/// The process's working set in MB. +fn working_set_mb() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + let mut counters = PROCESS_MEMORY_COUNTERS { cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, ..Default::default() }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut counters, counters.cb) }; + counters.WorkingSetSize as u64 >> 20 +} + +/// What the probe found. The lines are the whole account; the flags are +/// what the stages build on. +#[derive(Default)] +pub(crate) struct Probe { + pub(crate) lines: Vec<String>, + /// A part of private, write-watched memory opens, a buffer in it shows + /// the memory's bytes to the GPU, also those the CPU wrote afterwards. + pub(crate) part_reads: bool, + /// What the GPU writes there (a copy, and a shader through unordered + /// access) the CPU reads at the memory's address. + pub(crate) part_writes: bool, + /// The same two for a committed section, through a view of it. + pub(crate) section_reads: bool, + pub(crate) section_writes: bool, + /// The section's heap outlives the view: the GPU's write with no view + /// mapped shows in a view mapped afterwards. + pub(crate) section_outlives_views: bool, + /// A section made with `SEC_RESERVE` (as `xmem` makes the page pool + /// unless `LEONIDA_SECTION_COMMIT=1`) was refused. + pub(crate) reserved_section_refused: bool, +} + +/// Tries the openings on memory of the probe's own, made the way `xmem` +/// makes title memory, with a queue of its own on `device`; `memory` +/// gives the card's memory account (`Host::video_memory`) where there is +/// one. Nothing of the title's is touched. `mb` is the size of the cost +/// measurement (0 leaves it out). +pub(crate) fn probe(device: &ID3D12Device, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) -> Probe { + let mut p = Probe::default(); + let mut rig = match Rig::new(device) { + Ok(rig) => rig, + Err(e) => { + p.lines.push(format!("no queue of its own: {e}")); + return p; + } + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + // SAFETY: a plain query that fills our structure. + let _ = unsafe { device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, (&raw mut options).cast(), size_of_val(&options) as u32) }; + p.lines.push(format!( + "the device: ID3D12Device3 {}, ID3D12Device13 {} (parts of an allocation); cross-adapter row-major textures {}; heap tier {}", + device.cast::<ID3D12Device3>().is_ok(), + device.cast::<ID3D12Device13>().is_ok(), + options.CrossAdapterRowMajorTextureSupported.as_bool(), + options.ResourceHeapTier.0 + )); + // SAFETY: memory of the probe's own, made and released here; every + // address used lies inside it. + unsafe { + private(&mut p, &mut rig); + section(&mut p, &mut rig); + if mb > 0 { + cost(&mut p, &mut rig, memory, mb); + } + } + p.lines.push(format!( + "VERDICT: private memory in place: reads {}, writes {}; the page pool's section in place: reads {}, writes {}, whatever the views do {}; \ + a reserved section is refused {} (the pool must be made committed to be opened)", + p.part_reads, p.part_writes, p.section_reads, p.section_writes, p.section_outlives_views, p.reserved_section_refused + )); + p +} + +fn describe(heap: &ID3D12Heap) -> String { + // SAFETY: a plain query. + let d = unsafe { heap.GetDesc() }; + format!( + "heap of {} KiB: type {} (4 = custom), CPU pages {} (3 = write-back), pool {} (1 = the PC's memory), alignment {}, flags {:#x} (0x1 shared, 0x20 cross-adapter, 0x200 write watch, 0x400 shader atomics)", + d.SizeInBytes >> 10, + d.Properties.Type.0, + d.Properties.CPUPageProperty.0, + d.Properties.MemoryPoolPreference.0, + d.Alignment, + d.Flags.0 + ) +} + +/// Private memory, reserved as `xmem` reserves the title's heaps +/// (committed, read-write, write-watched): a part of it opened. +unsafe fn private(p: &mut Probe, rig: &mut Rig) { + const SIZE: usize = 64 * K64; + // SAFETY (the whole function): the allocation below, `SIZE` bytes. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>(); + if base.is_null() { + p.lines.push("private memory: none to try with".to_owned()); + return; + } + // The part: 16 pages from the 16th on. + let (at, bytes) = (base.add(16 * K64), 16 * K64); + let whole = open(&rig.device, From::Region(base as usize)); + p.lines.push(format!("private memory, the whole allocation (OpenExistingHeapFromAddress): {}", hr(&whole))); + drop(whole); + let opened = open(&rig.device, From::Part(at as usize, bytes)); + p.lines.push(format!("private memory, a part of it (OpenExistingHeapFromAddress1): {}", hr(&opened))); + if let Ok(heap) = &opened { + p.lines.push(format!(" {}", describe(heap))); + let placed = place(&rig.device, heap, K64 as u64, 4 * K64 as u64); + p.lines.push(format!(" a buffer placed in it (cross-adapter, unordered access): {}", hr(&placed))); + if let Ok(buffer) = &placed { + let memory = at.add(K64); + fill(memory, 4 * K64, 1); + let first = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); + fill(memory, 4 * K64, 77); + let second = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); + p.part_reads = first && second; + p.lines.push(format!(" the GPU reads the memory's bytes: {first}; and those the CPU wrote afterwards, with no call in between: {second}")); + mem::ResetWriteWatch(base.cast(), SIZE); + let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x5a).collect(); + let copied = rig.store(buffer, 4096, &new).is_ok() && same(memory.add(4096), &new); + let (mut found, mut count, mut granularity) = ([0usize; 64], 64usize, 0u32); + let watched = mem::GetWriteWatch(0, base.cast(), SIZE, found.as_mut_ptr().cast(), &mut count, &mut granularity) == 0; + memory.cast::<[u32; 3]>().write([40, 2, 0]); + let shaded = rig.shade(buffer.GetGPUVirtualAddress()); + let shader = shaded.is_ok() && memory.cast::<[u32; 3]>().read()[2] == 42; + p.part_writes = copied && shader; + p.lines.push(format!( + " the CPU reads at the memory's address what the GPU wrote: by a copy {copied}; by a shader through unordered access {shader} ({}); \ + write watching saw {} of the copy's 16 pages{}", + hr(&shaded), + if watched { count } else { 0 }, + if watched { "" } else { " (the asking failed)" } + )); + } + // What the title can still do with the pages while the heap stands. + let mut old = 0; + let protect_in = mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READONLY, &mut old) != 0; + if protect_in { + mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READWRITE, &mut old); + } + let decommit_in = mem::VirtualFree(at.add(9 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + let decommit_out = mem::VirtualFree(base.add(40 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + p.lines.push(format!( + " with the heap standing, the title's own calls: read-only inside the part {protect_in}, decommit inside {decommit_in}, decommit outside {decommit_out} \ + (false inside means the heap must go before the title frees or guards those pages)" + )); + drop(placed); + } + drop(opened); + let freed = mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE) != 0; + p.lines.push(format!(" released after the heap went: {freed}")); + } +} + +/// A section and a view of it in a placeholder, as `xmem` maps physical +/// pages: reserved (as the page pool is made unless +/// `LEONIDA_SECTION_COMMIT=1`) and committed. +unsafe fn section(p: &mut Probe, rig: &mut Rig) { + const SIZE: usize = 32 * K64; + // SAFETY (the whole function): the sections, placeholder and views + // made below. + unsafe { + let process = windows_sys::Win32::System::Threading::GetCurrentProcess(); + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let reserved = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_RESERVE, 0, SIZE as u32, std::ptr::null()); + if !reserved.is_null() { + let opened = open(&rig.device, From::Section(reserved as usize)); + p.reserved_section_refused = opened.is_err(); + p.lines.push(format!("a section made reserved, as the page pool is without LEONIDA_SECTION_COMMIT=1 (OpenExistingHeapFromFileMapping): {}", hr(&opened))); + drop(opened); + windows_sys::Win32::Foundation::CloseHandle(reserved); + } + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null()); + let hole = mem::VirtualAlloc2(process, std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_RESERVE_PLACEHOLDER, mem::PAGE_NOACCESS, std::ptr::null_mut(), 0).cast::<u8>(); + if handle.is_null() || hole.is_null() { + p.lines.push("a committed section: none to try with".to_owned()); + return; + } + // Pages 4..12 of the section at the placeholder's start. + mem::VirtualFree(hole.cast(), 8 * K64, mem::MEM_RELEASE | mem::MEM_PRESERVE_PLACEHOLDER); + let view = mem::MapViewOfFile3(handle, process, hole.cast(), (4 * K64) as u64, 8 * K64, mem::MEM_REPLACE_PLACEHOLDER, mem::PAGE_READWRITE, std::ptr::null_mut(), 0); + let opened = open(&rig.device, From::Section(handle as usize)); + p.lines.push(format!("a section made committed (OpenExistingHeapFromFileMapping): {}", hr(&opened))); + let mut unmapped = false; + if let (Ok(heap), false) = (&opened, view.Value.is_null()) { + p.lines.push(format!(" {}", describe(heap))); + // The section's page 5 is the view's second page. + let placed = place(&rig.device, heap, 5 * K64 as u64, 2 * K64 as u64); + p.lines.push(format!(" a buffer placed at the section's offset of a view's pages: {}", hr(&placed))); + if let Ok(buffer) = &placed { + let memory = hole.add(K64); + fill(memory, 2 * K64, 3); + p.section_reads = rig.fetch(buffer, 0, 2 * K64).is_ok_and(|got| same(memory, &got)); + let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x33).collect(); + p.section_writes = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); + // The guard of `watch.rs`: the view read-only. + let mut old = 0; + let guarded = mem::VirtualProtect(memory.cast(), K64, mem::PAGE_READONLY, &mut old) != 0; + let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x44).collect(); + let through = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); + // The view goes; the GPU writes; another view shows it. + unmapped = mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER) != 0; + let new: Vec<u8> = (0..K64).map(|i| (i as u8) ^ 0x55).collect(); + let stored = rig.store(buffer, 0, &new).is_ok(); + let other = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, (5 * K64) as u32, K64); + p.section_outlives_views = unmapped && stored && !other.Value.is_null() && same(other.Value.cast(), &new); + p.lines.push(format!( + " the GPU reads the view's bytes {}; the CPU reads through the view what the GPU wrote {}; the view made read-only under the heap {guarded}, \ + and the GPU writes it all the same {through}; the view unmapped under the heap {unmapped}, the GPU's write then shows in a view mapped afterwards {}", + p.section_reads, p.section_writes, p.section_outlives_views + )); + if !other.Value.is_null() { + mem::UnmapViewOfFile(other); + } + } + } + drop(opened); + if !unmapped && !view.Value.is_null() { + mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER); + } + windows_sys::Win32::Foundation::CloseHandle(handle); + // The placeholder was split in two: each half is released. + mem::VirtualFree(hole.cast(), 0, mem::MEM_RELEASE); + mem::VirtualFree(hole.add(8 * K64).cast(), 0, mem::MEM_RELEASE); + } +} + +/// What opening costs, on `mb` MB each of private memory never touched +/// and of a committed section never touched: the time, the working set, +/// the card's account of the PC's memory shared with it; and how fast the +/// card copies out of such a heap against a shared buffer of today's kind. +unsafe fn cost(p: &mut Probe, rig: &mut Rig, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) { + let bytes = mb << 20; + let shared = || memory().map_or(0, |m| m[3] >> 20); + let ms = |speed: Option<f64>| speed.map_or("?".to_owned(), |ms| format!("{ms:.1}")); + // SAFETY (the whole function): the allocation and the section below. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), bytes, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>(); if !base.is_null() { let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); let opened = open(&rig.device, From::Part(base as usize, bytes)); @@ -1105,447 +3331,1942 @@ unsafe fn cost(p: &mut Probe, rig: &mut Rig, memory: &dyn Fn() -> Option<[u64; 4 drop((placed, opened)); mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); } - let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; - let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, (bytes as u64 >> 32) as u32, bytes as u32, std::ptr::null()); - if !handle.is_null() { - let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); - let opened = open(&rig.device, From::Section(handle as usize)); - let took = started.elapsed().as_secs_f64() * 1000.0; - let (set_opened, account_opened) = (working_set_mb(), shared()); - let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); - let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); - p.lines.push(format!( - "cost, {mb} MB of a committed section never touched: {}; opened in {took:.1} ms; working set {set} -> {set_opened} -> after the card read all of it {} MB; \ - shared with the card {account} -> {account_opened} -> {} MB; the card copies it out in {} ms", - hr(&opened), - working_set_mb(), - shared(), - ms(speed) - )); - drop((placed, opened)); - windows_sys::Win32::Foundation::CloseHandle(handle); + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, (bytes as u64 >> 32) as u32, bytes as u32, std::ptr::null()); + if !handle.is_null() { + let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); + let opened = open(&rig.device, From::Section(handle as usize)); + let took = started.elapsed().as_secs_f64() * 1000.0; + let (set_opened, account_opened) = (working_set_mb(), shared()); + let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); + let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); + p.lines.push(format!( + "cost, {mb} MB of a committed section never touched: {}; opened in {took:.1} ms; working set {set} -> {set_opened} -> after the card read all of it {} MB; \ + shared with the card {account} -> {account_opened} -> {} MB; the card copies it out in {} ms", + hr(&opened), + working_set_mb(), + shared(), + ms(speed) + )); + drop((placed, opened)); + windows_sys::Win32::Foundation::CloseHandle(handle); + } + // Today's kind of host copy, for the comparison. + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + let made = rig.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &buffer_desc(bytes as u64, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ); + if let (Ok(()), Some(buffer)) = (made, buffer) { + let speed = rig.copy_ms(&buffer, bytes as u64).ok(); + p.lines.push(format!("cost, for comparison: the card copies {mb} MB out of a shared buffer of today's kind in {} ms", ms(speed))); + } + } +} + +// The census: which of the title memory that has host copies today could +// be opened, and by which opening. + +/// Counts and bytes by kind, in the order of [`KINDS`]. +#[derive(Default, Clone, Copy)] +struct Tally([(u64, u64); 6]); + +const KINDS: [&str; 6] = [ + "private, committed whole (a part can be opened)", + "view memory, one run of a section (one placed buffer)", + "view memory, scattered pages", + "view memory with unmapped pages", + "private but not committed whole, or guarded", + "other", +]; + +fn kind_of(at: usize, len: usize, known: &mut Vec<(usize, usize)>) -> usize { + match cover(at, len) { + Cover::Run(..) => return 1, + Cover::Scattered => return 2, + Cover::Holes => return 3, + Cover::None => {} + } + let end = at + len; + if known.iter().any(|&(from, to)| from <= at && end <= to) { + return 0; + } + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + if n == 0 { + return 5; + } + let reach = (info.BaseAddress as usize).saturating_add(info.RegionSize); + if info.Type == mem::MEM_PRIVATE && info.State == mem::MEM_COMMIT && info.Protect == mem::PAGE_READWRITE { + known.push((info.BaseAddress as usize, reach)); + return if reach >= end { 0 } else { 4 }; + } + match info.Type { + mem::MEM_PRIVATE => 4, + mem::MEM_MAPPED => 3, + _ => 5, + } +} + +/// The census lines for `spans` (start, bytes, whether a window outside +/// buffers). +fn census_of(spans: &[(u64, u64, bool)]) -> Vec<String> { + let mut known = Vec::new(); + let (mut buffers, mut windows) = (Tally::default(), Tally::default()); + for &(start, len, window) in spans { + let kind = kind_of(start as usize, len as usize, &mut known); + let tally = if window { &mut windows } else { &mut buffers }; + tally.0[kind].0 += 1; + tally.0[kind].1 += len; + } + let mut lines = Vec::new(); + for (name, tally) in [("title buffers", buffers), ("windows outside buffers", windows)] { + let all = tally.0.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)); + lines.push(format!("census, {name}: {} of {} MB", all.0, all.1 >> 20)); + for (kind, &(n, bytes)) in KINDS.iter().zip(&tally.0) { + if n > 0 { + lines.push(format!("census, {kind}: {n} of {} MB", bytes >> 20)); + } + } + } + let v = views(); + let (count, bytes) = (v.views.len(), v.views.values().map(|view| view.0 as u64).sum::<u64>()); + let pages = v.views.values().filter(|view| view.0 == K64).count(); + let big = v.views.values().map(|view| view.0).max().unwrap_or(0); + lines.push(format!( + "census, the title's views of physical pages: {count} of {} MB; {pages} of them one 64 KiB page; the longest {} MB", + bytes >> 20, + big >> 20 + )); + // (The first few: with `LEONIDA_SECTION_MB` there are thousands, all alike.) + if v.sections.len() > 8 { + lines.push(format!( + "census, {} sections of {} MB in all; the first 8 follow", + v.sections.len(), + v.sections.values().map(|s| s.0).sum::<u64>() >> 20 + )); + } + for &(bytes, committed) in v.sections.values().take(8) { + lines.push(format!( + "census, a section of {} MB, {}", + bytes >> 20, + if committed { "committed: it can be opened as one heap" } else { "reserved: refused as a heap until it is made with SEC_COMMIT" } + )); + } + lines +} + +/// With [`probe_level`] 2: one part of the title's own private memory +/// (the start of the biggest such title buffer, 4 MiB at most) is opened +/// for a moment, a buffer placed, 64 KiB read by the GPU and compared +/// with what the CPU reads there (the title may be writing it meanwhile: +/// the count of equal bytes is given), and all of it released. While the +/// heap stands (milliseconds) a `VirtualFree` of the title's on those +/// pages would fail. +fn real_part(spans: &[(u64, u64, bool)]) -> Vec<String> { + let Some(host) = crate::host::host() else { + return Vec::new(); + }; + let mut known = Vec::new(); + let found = spans + .iter() + .filter(|s| !s.2 && s.1 >= 2 * K64 as u64) + .filter(|s| kind_of(s.0 as usize, s.1 as usize, &mut known) == 0) + .max_by_key(|s| s.1); + let Some(&(start, len, _)) = found else { + return vec!["the title's memory: no title buffer in private, committed memory to try".to_owned()]; + }; + let at = (start as usize).next_multiple_of(K64); + let bytes = ((start + len) as usize).saturating_sub(at).min(4 << 20) & !(K64 - 1); + if bytes == 0 || !private_whole(at, bytes) { + return vec!["the title's memory: the buffer found holds no whole 64 KiB page that is still committed".to_owned()]; + } + let mut lines = Vec::new(); + let (set, started) = (working_set_mb(), std::time::Instant::now()); + let opened = open(&host.device, From::Part(at, bytes)); + lines.push(format!( + "the title's memory, {} KiB at {at:#x} (of the title buffer {start:#x}+{len:#x}): {}; in {:.1} ms; working set {set} -> {} MB", + bytes >> 10, + hr(&opened), + started.elapsed().as_secs_f64() * 1000.0, + working_set_mb() + )); + if let Ok(heap) = &opened { + let placed = place(&host.device, heap, 0, bytes as u64); + lines.push(format!(" a buffer placed over it: {}", hr(&placed))); + if let (Ok(buffer), Ok(mut rig)) = (&placed, Rig::new(&host.device)) { + let mut before = vec![0u8; K64]; + crate::host::copy_mapped(before.as_mut_ptr(), at as *const u8, K64, false); + let got = rig.fetch(buffer, 0, K64); + let mut after = vec![0u8; K64]; + crate::host::copy_mapped(after.as_mut_ptr(), at as *const u8, K64, false); + match got { + Ok(got) => { + let equal = (0..K64).filter(|&i| got[i] == before[i] || got[i] == after[i]).count(); + let zeros = got.iter().filter(|&&b| b == 0).count(); + lines.push(format!( + " the GPU read 64 KiB of the title's own bytes: {equal} of {K64} equal to what the CPU read just before or just after ({zeros} of them zero)" + )); + } + Err(e) => lines.push(format!(" the GPU's read failed: {e}")), + } + } + } + lines +} + +/// Called by the thread that submits, before a submission (`host::sweep`): +/// every [`REAP_MS`], with holds or pending releases, [`reap`]; with +/// [`probe_level`], the probe at the first call, the census (on a thread of +/// its own: it asks Windows about every copy) 30 and 150 seconds later. +pub(crate) fn tick() { + if level() > 0 { + say(); + } + slots_let_go_of_unheld(); + switch_ready(); + if WAITING.load(Ordering::Relaxed) != 0 { + static LAST: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms(); + let last = LAST.load(Ordering::Relaxed); + if now >= last + REAP_MS && LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_ok() { + reap(); + } + } + if probe_level() == 0 { + return; + } + static STARTED: AtomicU64 = AtomicU64::new(0); + static DONE: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms().max(1); + let started = match STARTED.compare_exchange(0, now, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => { + let Some(host) = crate::host::host() else { + return; + }; + let mb = std::env::var("LEONIDA_INPLACE_PROBE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64usize); + let took = std::time::Instant::now(); + let probe = probe(&host.device, &|| host.video_memory(), mb.min(1024)); + for line in &probe.lines { + tracing::info!("in place probe: {line}"); + } + tracing::info!("in place probe: took {:.0} ms", took.elapsed().as_secs_f64() * 1000.0); + if tiled::asked() { + let took = std::time::Instant::now(); + for line in &tiled::probe_beside(&host.device, mb).lines { + tracing::info!("in place probe, tiles: {line}"); + } + tracing::info!("in place probe, tiles: took {:.0} ms", took.elapsed().as_secs_f64() * 1000.0); + } + now + } + Err(started) => started, + }; + let due = match DONE.load(Ordering::Relaxed) { + 0 => now >= started + 30_000, + 1 => now >= started + 150_000, + _ => false, + }; + if due { + let which = DONE.fetch_add(1, Ordering::Relaxed); + std::thread::spawn(move || { + let spans = crate::shadow::spans(); + for line in census_of(&spans) { + tracing::info!("in place {line}"); + } + if which == 0 && probe_level() >= 2 { + for line in real_part(&spans) { + tracing::info!("in place probe: {line}"); + } + } + }); + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// Views as the runtime tells them: a range inside one view, or over + /// views that continue each other in one section, is one run; over + /// views from elsewhere it is scattered; over a gap it has holes. + #[test] + fn the_views_say_how_much_of_a_range_is_there() { + const K64: usize = 64 << 10; + // Addresses nothing has: only the record is asked. + let at = 0x7ff1_0000_0000_usize; + for (block, blocks) in [(0, 1), (1, 1), (4, 2)] { + super::title_memory_view(at + block * K64, blocks * K64, 7, 0); + } + let shown = |from: usize, len: usize| super::shown_bytes(at + from, len); + assert_eq!(shown(0, 8 * K64), Some(4 * K64 as u64)); + assert_eq!(shown(100, K64), Some(K64 as u64)); + assert_eq!(shown(K64 + 100, 2 * K64), Some(K64 as u64 - 100)); + assert_eq!(shown(5 * K64 + 1, 10), Some(10)); + assert_eq!(shown(2 * K64, 2 * K64), None); + assert_eq!(shown(6 * K64, 2 * K64), None); + // The same as runs: views that touch are one, cut to the range. + let runs = |from: usize, len: usize| super::shown_runs(at + from, len); + assert_eq!(runs(0, 8 * K64), vec![(at, 2 * K64), (at + 4 * K64, 2 * K64)]); + assert_eq!(runs(100, K64), vec![(at + 100, K64)]); + assert_eq!(runs(5 * K64 + 1, 10), vec![(at + 5 * K64 + 1, 10)]); + assert_eq!(runs(2 * K64, 2 * K64), vec![]); + super::views_gone(at + K64, K64); + assert_eq!(shown(0, 2 * K64), Some(K64 as u64)); + assert_eq!(runs(0, 2 * K64), vec![(at, K64)]); + super::views_gone(at, 8 * K64); + assert_eq!(shown(0, 8 * K64), None); + } + + #[test] + fn views_say_what_one_placed_buffer_could_show() { + let mut views = BTreeMap::new(); + let at = 0x7_0000_0000usize; + views.insert(at, (4 * K64, 9, 16 * K64 as u64)); + // Continues the first in the section. + views.insert(at + 4 * K64, (2 * K64, 9, 20 * K64 as u64)); + // Follows in address, from elsewhere in the section. + views.insert(at + 6 * K64, (K64, 9, 3 * K64 as u64)); + // After a gap of one page. + views.insert(at + 8 * K64, (K64, 9, 4 * K64 as u64)); + assert_eq!(cover_in(&views, at + K64, 2 * K64), Cover::Run(9, 17 * K64 as u64)); + assert_eq!(cover_in(&views, at + K64, 5 * K64), Cover::Run(9, 17 * K64 as u64)); + assert_eq!(cover_in(&views, at, 7 * K64), Cover::Scattered); + assert_eq!(cover_in(&views, at + 6 * K64, 3 * K64), Cover::Holes); + assert_eq!(cover_in(&views, at + 7 * K64, K64), Cover::None); + assert_eq!(cover_in(&views, at - K64, 2 * K64), Cover::None); + } + + /// The stretch around a run: views on both sides that follow in memory + /// and in the section, up to a view from elsewhere or a gap. + #[test] + fn a_stretch_is_the_views_around_a_run_that_follow_in_the_section() { + let mut views = BTreeMap::new(); + let at = 0x7_2000_0000usize; + // From elsewhere in the section, just below. + views.insert(at - K64, (K64, 9, 40 * K64 as u64)); + for (k, n) in [(0usize, 2usize), (2, 3), (5, 1)] { + views.insert(at + k * K64, (n * K64, 9, ((10 + k) * K64) as u64)); + } + // Next in memory, of another section; then a gap. + views.insert(at + 6 * K64, (K64, 8, 16 * K64 as u64)); + views.insert(at + 8 * K64, (K64, 9, 18 * K64 as u64)); + let whole = Some((at, 6 * K64, 9, 10 * K64 as u64)); + assert_eq!(stretch_in(&views, at + 3 * K64 + 5, 10), whole); + assert_eq!(stretch_in(&views, at, 6 * K64), whole); + assert_eq!(stretch_in(&views, at + 5 * K64, 2 * K64), None, "into the other section"); + assert_eq!(stretch_in(&views, at + 6 * K64, K64), Some((at + 6 * K64, K64, 8, 16 * K64 as u64))); + assert_eq!(stretch_in(&views, at + 7 * K64, K64), None, "the gap"); + } + + /// What the runtime forgets when memory is mapped anew. + #[test] + fn remapped_memory_forgets_its_views() { + let at = 0x7_4000_0000usize; + title_memory_view(at, 4 * K64, 77, 0); + title_memory_view(at + 4 * K64, K64, 77, 4 * K64 as u64); + assert_eq!(cover(at, 5 * K64), Cover::Run(77, 0)); + // One page inside the first view goes: the whole view is forgotten + // (the runtime maps and tells again what stays of it). + views_gone(at + K64, K64); + assert_eq!(cover(at, K64), Cover::None); + assert_eq!(cover(at + 4 * K64, K64), Cover::Run(77, 4 * K64 as u64)); + views_gone(at + 4 * K64, K64); + assert_eq!(cover(at + 4 * K64, K64), Cover::None); + } + + /// Only private memory committed whole, read-write, is taken for a part. + #[test] + fn only_private_memory_committed_whole_is_a_part() { + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE, mem::PAGE_NOACCESS).cast::<u8>(); + assert!(!base.is_null()); + assert!(!private_whole(base as usize, K64), "reserved only"); + mem::VirtualAlloc(base.cast(), 4 * K64, mem::MEM_COMMIT, mem::PAGE_READWRITE); + assert!(private_whole(base as usize, 4 * K64)); + assert!(private_whole(base as usize + K64, 2 * K64)); + assert!(!private_whole(base as usize, 5 * K64), "reaches into the reserved half"); + let mut old = 0; + mem::VirtualProtect(base.cast(), K64, mem::PAGE_READONLY, &mut old); + assert!(!private_whole(base as usize, 2 * K64), "a guarded page"); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + } + + pub(crate) fn warp() -> Option<ID3D12Device> { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::*; + // SAFETY: plain DXGI queries and device creation on the software + // adapter; a card is never opened. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let desc = adapter.cast::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option<ID3D12Device> = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + device } - // Today's kind of host copy, for the comparison. - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_CUSTOM, - CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, - MemoryPoolPreference: D3D12_MEMORY_POOL_L0, - ..Default::default() + } + + /// The probe, whole, on the software adapter: the same calls the card + /// gets. The runtime's and the kernel's rules hold there; the card's + /// driver is what a run with `LEONIDA_INPLACE_PROBE=1` adds. + #[test] + fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() { + eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened"); + return; + } + let probe = probe(&device, &|| None, 4); + for line in &probe.lines { + eprintln!("in place probe: {line}"); + } + assert!(probe.part_reads, "the GPU reads private memory in place"); + assert!(probe.part_writes, "GPU writes land in private memory"); + assert!(probe.section_reads && probe.section_writes, "a committed section in place"); + assert!(probe.section_outlives_views, "the section's heap does not depend on views"); + assert!(probe.reserved_section_refused, "a reserved section is refused"); + } + + /// Stage 1's own call on the software adapter: a title buffer that + /// begins and ends off the 64 KiB lines is placed over its pages, the + /// GPU reads the buffer's bytes at the offset the views use, and its + /// write lands at the title's address. Memory that is not committed + /// whole is turned down without asking the host. + #[test] + fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() { + return; + } + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>(); + let (start, len) = (base as u64 + K64 as u64 + 0x1230, 2 * K64 as u64 + 5); + let placed = place_part(&device, start, len).unwrap_or_else(|e| panic!("not placed: {e:?}")); + assert_eq!(placed.bias, 0x1230); + assert_eq!(placed.gpu, placed.buffer.GetGPUVirtualAddress() + 0x1230); + assert_eq!(placed.buffer.GetDesc().Width, 3 * K64 as u64, "the pages that hold the buffer"); + let mut rig = Rig::new(&device).unwrap(); + fill(start as *mut u8, len as usize, 7); + let got = rig.fetch(&placed.buffer, placed.bias, len as usize).unwrap(); + assert!(same(start as *const u8, &got), "the GPU reads the title buffer's bytes"); + rig.store(&placed.buffer, placed.bias + 16, &[0xa5; 64]).unwrap(); + assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); + drop(placed); + // Half of it decommitted: turned down, the host not asked. + // The heap lets go of the pages a moment after its last + // reference, if the adapter is busy with other tests' work. + let gone = (0..500).any(|_| { + let done = mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(gone, "the heap keeps the pages"); + assert!(matches!(place_part(&device, start, len), Err(None))); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + } + + /// Holds standing over `[at, end)` ([`HELD`]): not let go of. (Those + /// let go of stay noted a while, until the host frees their pages + /// through the runtime's path, [`holds_freed`].) + pub(crate) fn standing_over(at: usize, end: usize) -> usize { + HELD.lock().unwrap().iter().filter(|h| h.at < end && h.end > at && h.buffer.is_some()).count() + } + + /// Title memory placed as [`place_for`] places it, without asking + /// [`level`]: held. + fn place_held(device: &ID3D12Device, start: usize, len: usize) -> Placed { + let placed = place_part(device, start as u64, len as u64).unwrap_or_else(|e| panic!("not placed: {e:?}")); + hold(start as u64, len as u64, &placed.buffer); + placed + } + + /// Memory opened by address for the runtime's own arenas + /// (`crate::shadow::by_address_opened`, through [`place_part`]) is + /// never the title's to free: nothing holds it, so its buffer goes + /// with the arena's copy and [`tick`] has nothing to reap for it. + /// Before, every arena was held, and reaped every [`REAP_MS`] for good + /// even with `LEONIDA_INPLACE` off. + #[test] + fn warp_memory_placed_by_address_is_not_held() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() { + return; + } + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 2 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let placed = place_part(&device, base as u64, 2 * K64 as u64).unwrap_or_else(|e| panic!("not placed: {e:?}")); + assert_eq!(standing_over(base, base + 2 * K64), 0, "an arena's memory is not held"); + assert_eq!(crate::host::references(&placed.buffer), 1, "nobody else has the buffer"); + drop(placed); + let released = (0..500).any(|_| { + // SAFETY: the test's own allocation. + let done = unsafe { mem::VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE) } != 0; + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(released, "released once the heap went"); + } + + /// Releases kept for the title in `[at, end)` ([`PENDING`]). + fn pending_over(at: usize, end: usize) -> usize { + PENDING.lock().unwrap().iter().filter(|p| p.0 < end && p.1 > at).count() + } + + /// The title's `VirtualFree` through the runtime's own path + /// ([`title_memory_free`], which `leonida_hle`'s xmem calls), the host's + /// call given as xmem gives it. + fn title_frees(at: usize, len: usize, kind: u32) -> bool { + // SAFETY: the test's own allocation. + title_memory_free(at, len, kind, || unsafe { mem::VirtualFree(at as *mut c_void, len, kind) }) != 0 + } + + /// The title releases its allocation `[base, end)` through the runtime's + /// path ([`title_frees`]): whether the release was done within five + /// seconds, at once or, kept for a heap ([`PENDING`]), by [`reap`] once + /// the host let go of it. (Released with the host's own call instead, + /// the holds let go of there stay noted ([`HELD`]) over addresses the + /// next test's allocation may get.) + fn title_released(base: usize, end: usize) -> bool { + title_frees(base, 0, mem::MEM_RELEASE) + && (0..500).any(|_| { + reap(); + let done = pending_over(base, end) == 0; + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }) + } + + /// The title releases its allocation at `base` through the runtime's path + /// ([`title_memory_free`]): whether the host's own call did it, at once + /// (no heap was left over the memory; a release taken over for one is + /// not this). Released with the host's call alone, the holds let go of + /// over it stayed noted ([`HELD`]) for [`GIVE_UP_MS`] over addresses the + /// next test's allocation may get, and its decommit beside them was cut + /// where they had been (`warp_a_decommit_the_host_still_refuses_once_the_hold_went_zeroes` + /// failed so in most runs of the suite). + fn host_releases(base: usize) -> bool { + let mut host = 0; + title_memory_free(base, 0, mem::MEM_RELEASE, || { + // SAFETY: the test's own allocation. + host = unsafe { mem::VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE) }; + host + }); + host != 0 + } + + /// The state the host says the page at `at` is in. + fn page_state(at: usize) -> u32 { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + info.State + } + + /// [`as_asked`]'s `reserved_after` where the host has no reserved memory. + fn no_reserved(_: usize, _: usize) -> Option<usize> { + None + } + + /// Decommits kept for the title ([`DECOMMITTED`]) in `[at, end)`. + fn decommitted_over(at: usize, end: usize) -> Vec<(usize, usize)> { + DECOMMITTED.lock().unwrap().iter().filter(|d| d.0 < end && d.1 > at).map(|d| (d.0, d.1)).collect() + } + + /// What the title's query of `at` is told ([`title_memory_as_asked`] over + /// the host's answer). + fn queried(at: usize) -> mem::MEMORY_BASIC_INFORMATION { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + assert_ne!(unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }, 0); + title_memory_as_asked(at, &mut info); + info + } + + /// (`LEONIDA_INPLACE_QUERY_DECOMMITS`) A decommit kept committed and + /// zeroed for a heap is reserved memory to the title's query ([`as_asked`]): + /// from the page asked on over the host's reserved memory and other such + /// decommits after it in the same allocation; a committed region before + /// one ends where it begins, and the host's reserved memory before one + /// goes on over it; with none kept, what the host says. + #[test] + fn a_query_tells_a_decommit_kept_as_reserved() { + let host = |base: usize, size: usize, state: u32, protect: u32| { + // SAFETY: plain data; zero is a valid value. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + info.BaseAddress = base as *mut c_void; + info.AllocationBase = 0x30_0000 as *mut c_void; + info.AllocationProtect = mem::PAGE_READWRITE; + info.RegionSize = size; + info.State = state; + info.Protect = protect; + info.Type = mem::MEM_PRIVATE; + info }; - let mut buffer: Option<ID3D12Resource> = None; - let made = rig.device.CreateCommittedResource( - &heap, - D3D12_HEAP_FLAG_NONE, - &buffer_desc(bytes as u64, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), - D3D12_RESOURCE_STATE_COMMON, - None, - &mut buffer, - ); - if let (Ok(()), Some(buffer)) = (made, buffer) { - let speed = rig.copy_ms(&buffer, bytes as u64).ok(); - p.lines.push(format!("cost, for comparison: the card copies {mb} MB out of a shared buffer of today's kind in {} ms", ms(speed))); + // The allocation [0x30_0000, 0x36_0000): committed on the host but for + // [0x32_0000, 0x34_0000), which it decommitted; the title decommitted + // [0x31_0000, 0x32_0000) and [0x34_0000, 0x35_0000) too. + let decommitted = [(0x31_0000, 0x32_0000, 0x30_0000), (0x34_0000, 0x35_0000, 0x30_0000)]; + let reserved_after = |end: usize, base: usize| (base == 0x30_0000 && end == 0x32_0000).then_some(0x34_0000); + let free_after = |_: usize| None; + + let mut info = host(0x30_0000, 0x2_0000, mem::MEM_COMMIT, mem::PAGE_READWRITE); + as_asked(0x30_0010, &mut info, &[], &[], &decommitted, free_after, reserved_after); + assert_eq!((info.State, info.Protect, info.RegionSize), (mem::MEM_COMMIT, mem::PAGE_READWRITE, 0x1_0000), "committed, to the decommit"); + + let mut info = host(0x31_0000, 0x1_0000, mem::MEM_COMMIT, mem::PAGE_READWRITE); + as_asked(0x31_0abc, &mut info, &[], &[], &decommitted, free_after, reserved_after); + assert_eq!((info.State, info.Protect), (mem::MEM_RESERVE, 0), "reserved, as the title asked"); + assert_eq!((info.BaseAddress as usize, info.RegionSize), (0x31_0000, 0x4_0000), "on over the reserved memory and the next decommit"); + assert_eq!((info.AllocationBase as usize, info.AllocationProtect, info.Type), (0x30_0000, mem::PAGE_READWRITE, mem::MEM_PRIVATE)); + + let mut info = host(0x33_0000, 0x1_0000, mem::MEM_RESERVE, 0); + as_asked(0x33_0000, &mut info, &[], &[], &decommitted, free_after, reserved_after); + assert_eq!((info.State, info.BaseAddress as usize, info.RegionSize), (mem::MEM_RESERVE, 0x33_0000, 0x2_0000), "the host's reserved memory, on over the decommit after it"); + + let mut info = host(0x34_8000, 0x8000, mem::MEM_COMMIT, mem::PAGE_READWRITE); + as_asked(0x34_8000, &mut info, &[], &[], &decommitted, free_after, reserved_after); + assert_eq!((info.State, info.RegionSize), (mem::MEM_RESERVE, 0x8000), "to the decommit's end"); + + let mut info = host(0x35_0000, 0x1_0000, mem::MEM_COMMIT, mem::PAGE_READWRITE); + as_asked(0x35_0000, &mut info, &[], &[], &decommitted, free_after, reserved_after); + assert_eq!((info.State, info.Protect, info.RegionSize), (mem::MEM_COMMIT, mem::PAGE_READWRITE, 0x1_0000), "past them, the host's"); + + let mut info = host(0x31_0000, 0x1_0000, mem::MEM_COMMIT, mem::PAGE_READWRITE); + as_asked(0x31_0000, &mut info, &[], &[], &[], free_after, reserved_after); + assert_eq!((info.State, info.RegionSize), (mem::MEM_COMMIT, 0x1_0000), "none kept: the host's"); + let mut info = host(0x32_0000, 0x2_0000, mem::MEM_RESERVE, 0); + as_asked(0x32_0000, &mut info, &[], &[], &[], free_after, reserved_after); + assert_eq!((info.State, info.RegionSize), (mem::MEM_RESERVE, 0x2_0000)); + // A release kept for the title is free memory, decommits in it or not. + let mut info = host(0x31_0000, 0x1_0000, mem::MEM_COMMIT, mem::PAGE_READWRITE); + as_asked(0x31_0000, &mut info, &[(0x30_0000, 0x36_0000)], &[], &decommitted, free_after, reserved_after); + assert_eq!(info.State, mem::MEM_FREE); + } + + /// (`LEONIDA_INPLACE_QUERY_DECOMMITS`) Two allocations side by side, a + /// decommit kept at the end of the first and one at the start of the + /// second: the title's query of the first stops at its end, from a + /// decommit kept or from the host's reserved memory before one + /// ([`as_asked`]), and the two are noted apart ([`decommit_noted`]), so no + /// region it is told runs into the next allocation, as `VirtualQuery`'s + /// never does. + #[test] + fn a_query_of_a_decommit_kept_stays_in_its_allocation() { + let (a, b) = (0x10_0000, 0x11_0000); + let host = |at: usize, size: usize, state: u32, protect: u32, of: usize| { + // SAFETY: plain data; zero is a valid value. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + info.BaseAddress = at as *mut c_void; + info.AllocationBase = of as *mut c_void; + info.AllocationProtect = mem::PAGE_READWRITE; + info.RegionSize = size; + info.State = state; + info.Protect = protect; + info.Type = mem::MEM_PRIVATE; + info + }; + let mut decommitted = Vec::new(); + decommit_noted(&mut decommitted, 0x10_f000, 0x11_0000, a); + decommit_noted(&mut decommitted, 0x11_0000, 0x11_1000, b); + assert_eq!(decommitted, vec![(0x10_f000, 0x11_0000, a), (0x11_0000, 0x11_1000, b)], "apart: two allocations"); + // (The host's reserved memory of A is [0x10_e000, 0x10_f000) only.) + let reserved_after = |_: usize, _: usize| None; + let free_after = |_: usize| None; + + let mut info = host(0x10_f000, 0x1000, mem::MEM_COMMIT, mem::PAGE_READWRITE, a); + as_asked(0x10_f000, &mut info, &[], &[], &decommitted, free_after, reserved_after); + assert_eq!((info.State, info.BaseAddress as usize, info.RegionSize), (mem::MEM_RESERVE, 0x10_f000, 0x1000), "a decommit kept: to A's end"); + let mut info = host(0x10_e000, 0x1000, mem::MEM_RESERVE, 0, a); + as_asked(0x10_e000, &mut info, &[], &[], &decommitted, free_after, reserved_after); + assert_eq!((info.State, info.BaseAddress as usize, info.RegionSize), (mem::MEM_RESERVE, 0x10_e000, 0x2000), "the host's reserved memory: to A's end"); + let mut info = host(0x11_0000, 0x1000, mem::MEM_COMMIT, mem::PAGE_READWRITE, b); + as_asked(0x11_0800, &mut info, &[], &[], &decommitted, free_after, reserved_after); + assert_eq!((info.State, info.BaseAddress as usize, info.RegionSize, info.AllocationBase as usize), (mem::MEM_RESERVE, 0x11_0000, 0x1000, b), "B's own"); + + // In one allocation, those that touch or overlap are made one, in + // address order. + decommit_noted(&mut decommitted, 0x10_e000, 0x10_f000, a); + decommit_noted(&mut decommitted, 0x10_0000, 0x10_1000, a); + decommit_noted(&mut decommitted, 0x11_0800, 0x11_2000, b); + assert_eq!(decommitted, vec![(0x10_0000, 0x10_1000, a), (0x10_e000, 0x11_0000, a), (0x11_0000, 0x11_2000, b)]); + } + + /// (`LEONIDA_INPLACE_QUERY_DECOMMITS`) Through the runtime's own path, on + /// the host's memory: a decommit kept over the end of one allocation and + /// the start of the next one beside it ([`decommitted_kept`]) is noted by + /// each, and the title's query ([`title_memory_as_asked`]) of either stays + /// in it; both go once the allocations are released. + #[test] + fn a_decommit_kept_over_two_allocations_is_noted_by_each() { + const K64: usize = 0x1_0000; + // Two allocations side by side, where the host had 128 KiB free. + let (a, b) = (0..20) + .find_map(|_| { + // SAFETY: a reservation of the test's own, released at once. + let p = unsafe { mem::VirtualAlloc(std::ptr::null_mut(), 2 * K64, mem::MEM_RESERVE, mem::PAGE_READWRITE) } as usize; + assert_ne!(p, 0); + // SAFETY: as above. + assert_ne!(unsafe { mem::VirtualFree(p as *mut c_void, 0, mem::MEM_RELEASE) }, 0); + let commit = mem::MEM_RESERVE | mem::MEM_COMMIT; + // SAFETY: the test's own allocations at addresses just freed. + let a = unsafe { mem::VirtualAlloc(p as *mut c_void, K64, commit, mem::PAGE_READWRITE) } as usize; + // SAFETY: as above. + let b = unsafe { mem::VirtualAlloc((p + K64) as *mut c_void, K64, commit, mem::PAGE_READWRITE) } as usize; + if a == p && b == p + K64 { + return Some((a, b)); + } + // (Another test took one of them in between.) + for got in [a, b].into_iter().filter(|&got| got != 0) { + assert!(host_releases(got)); + } + None + }) + .expect("two allocations side by side"); + + decommitted_kept(b - 0x1000, b + 0x1000); + assert_eq!(decommitted_over(a, b + K64), vec![(b - 0x1000, b), (b, b + 0x1000)], "apart, one per allocation"); + let bases: Vec<usize> = DECOMMITTED.lock().unwrap().iter().filter(|d| d.0 < b + K64 && d.1 > a).map(|d| d.2).collect(); + assert_eq!(bases, vec![a, b]); + if query_decommits() && queries() { + let info = queried(b - 0x1000); + assert_eq!((info.State, info.BaseAddress as usize, info.RegionSize, info.AllocationBase as usize), (mem::MEM_RESERVE, b - 0x1000, 0x1000, a), "to A's end"); + let info = queried(b); + assert_eq!((info.State, info.BaseAddress as usize, info.RegionSize, info.AllocationBase as usize), (mem::MEM_RESERVE, b, 0x1000, b), "B's own"); } + + assert!(host_releases(a) && host_releases(b)); + assert_eq!(decommitted_over(a, b + K64), vec![], "nothing kept over memory released"); } -} -// The census: which of the title memory that has host copies today could -// be opened, and by which opening. + /// What the title is told of its memory where the runtime does what it + /// asked later ([`as_asked`]): a release kept for it is free memory on + /// to the end of the free run after it; the newest protection that waits + /// over a page is the page's, and a region ends where one begins or + /// ends; elsewhere, and in memory not committed, what the host says. + #[test] + fn a_query_tells_what_the_title_asked_for() { + let host = |base: usize, size: usize, state: u32, protect: u32| { + // SAFETY: plain data; zero is a valid value. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + info.BaseAddress = base as *mut c_void; + info.AllocationBase = 0x10_0000 as *mut c_void; + info.RegionSize = size; + info.State = state; + info.Protect = protect; + info.Type = mem::MEM_PRIVATE; + info + }; + let pending = [(0x10_0000, 0x14_0000), (0x14_0000, 0x15_0000)]; + let protects = [(0x20_1000, 0x20_3000, mem::PAGE_READONLY), (0x20_2000, 0x20_4000, mem::PAGE_NOACCESS)]; + let free_after = |end: usize| (end == 0x15_0000).then_some(0x18_0000); -/// Counts and bytes by kind, in the order of [`KINDS`]. -#[derive(Default, Clone, Copy)] -struct Tally([(u64, u64); 6]); + let mut info = host(0x12_0000, 0x2_0000, mem::MEM_COMMIT, mem::PAGE_READWRITE); + as_asked(0x12_0abc, &mut info, &pending, &protects, &[], free_after, no_reserved); + assert_eq!(info.State, mem::MEM_FREE, "a release kept for the title"); + assert_eq!((info.BaseAddress as usize, info.RegionSize), (0x12_0000, 0x6_0000), "to the end of the free run"); + assert_eq!((info.AllocationBase as usize, info.Protect, info.Type), (0, mem::PAGE_NOACCESS, 0)); -const KINDS: [&str; 6] = [ - "private, committed whole (a part can be opened)", - "view memory, one run of a section (one placed buffer)", - "view memory, scattered pages", - "view memory with unmapped pages", - "private but not committed whole, or guarded", - "other", -]; + let mut info = host(0x20_0000, 0x10_000, mem::MEM_COMMIT, mem::PAGE_READWRITE); + as_asked(0x20_0010, &mut info, &pending, &protects, &[], free_after, no_reserved); + assert_eq!((info.Protect, info.RegionSize), (mem::PAGE_READWRITE, 0x1000), "the host's, to the first waiting protection"); + let mut info = host(0x20_1000, 0xf000, mem::MEM_COMMIT, mem::PAGE_READWRITE); + as_asked(0x20_1000, &mut info, &pending, &protects, &[], free_after, no_reserved); + assert_eq!((info.Protect, info.RegionSize), (mem::PAGE_READONLY, 0x1000), "what waits there"); + let mut info = host(0x20_2000, 0xe000, mem::MEM_COMMIT, mem::PAGE_READWRITE); + as_asked(0x20_2fff, &mut info, &pending, &protects, &[], free_after, no_reserved); + assert_eq!((info.Protect, info.RegionSize), (mem::PAGE_NOACCESS, 0x1000), "the newest that waits"); + let mut info = host(0x20_4000, 0xc000, mem::MEM_COMMIT, mem::PAGE_READWRITE); + as_asked(0x20_4000, &mut info, &pending, &protects, &[], free_after, no_reserved); + assert_eq!((info.Protect, info.RegionSize), (mem::PAGE_READWRITE, 0xc000), "past them, the host's"); + let mut info = host(0x20_1000, 0xf000, mem::MEM_RESERVE, 0); + as_asked(0x20_1000, &mut info, &pending, &protects, &[], free_after, no_reserved); + assert_eq!((info.State, info.Protect, info.RegionSize), (mem::MEM_RESERVE, 0, 0xf000), "not committed: the host's"); + } + + /// Of a range, what holds stand over and what they leave. + #[test] + fn a_free_is_cut_into_what_heaps_stand_over_and_the_rest() { + let holds = [(0x3_0000, 0x5_0000), (0x1_0000, 0x2_0000), (0x4_0000, 0x6_0000), (0x9_0000, 0xa_0000)]; + let held = held_parts(&holds, 0x1_8000, 0x9_4000); + assert_eq!(held, vec![(0x1_8000, 0x2_0000), (0x3_0000, 0x6_0000), (0x9_0000, 0x9_4000)]); + assert_eq!(free_parts(&held, 0x1_8000, 0x9_4000), vec![(0x2_0000, 0x3_0000), (0x6_0000, 0x9_0000)]); + assert_eq!(held_parts(&holds, 0x6_0000, 0x9_0000), vec![]); + assert_eq!(free_parts(&[], 0x6_0000, 0x9_0000), vec![(0x6_0000, 0x9_0000)]); + assert_eq!(free_parts(&[(0, 0x10_0000)], 0x1000, 0x2000), vec![]); + } + + /// The title releases memory a window is in place over, through the + /// runtime's path: the window leaves the tables at once, and the title + /// is told the release is done although the heap still stands (the + /// submissions that may use the window have not run, and a descriptor + /// slot shows its buffer). Once neither holds it the allocation is + /// released, and no hold is left. Before, the window stayed in the + /// tables and the title's call failed with error 87 for good. + #[test] + fn warp_the_title_releases_memory_in_place_once_its_heap_is_gone() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() { + return; + } + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let (start, len) = (base + K64 + 0x40, 2 * K64); + let placed = place_held(&device, start, len); + // A descriptor slot that shows the window's buffer. + let slot = placed.buffer.clone(); + let window = crate::shadow::in_place_window(placed, start as u64, len as u64); + let ours = std::sync::Arc::as_ptr(&window); + drop(window); + assert_eq!(standing_over(base, base + 8 * K64), 1); + + assert!(title_frees(base, 0, mem::MEM_RELEASE), "the title's VirtualFree succeeds"); + assert!(!crate::shadow::in_place_window_there(start as u64, len as u64), "the window is let go"); + assert_eq!(pending_over(base, base + 8 * K64), 1, "the release waits for the heap"); + assert!(allocation_of(base).is_some(), "kept reserved for the title meanwhile"); + assert!(released(start, 16), "nothing goes in place over it"); + + // The submissions that may use the window have run. + let buried = crate::host::bury_picked(|object| { + object.downcast_ref::<std::sync::Arc<crate::shadow::Shadow>>().is_some_and(|s| std::sync::Arc::as_ptr(s) == ours) + }); + assert_eq!(buried, 1, "the window waited for them"); + reap(); + assert_eq!(pending_over(base, base + 8 * K64), 1, "the slot still shows the buffer"); + // The slot is written again. + drop(slot); + let released = (0..500).any(|_| { + reap(); + let done = allocation_of(base).is_none(); + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(released, "released once the heap went"); + assert_eq!(standing_over(base, base + 8 * K64), 0, "no hold stands"); + assert_eq!(pending_over(base, base + 8 * K64), 0); + assert!(!anything_placed(), "nothing is counted in place"); + } + + /// The title decommits memory a heap stands over: what no heap stands + /// over is decommitted at once, the rest reads as zeros and stays + /// committed (the title may commit it again with the host's own call) + /// until the title releases the allocation. + #[test] + fn warp_a_decommit_under_a_heap_zeroes_what_it_cannot_take() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() { + return; + } + // SAFETY: an allocation of the test's own, written and read while + // committed. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as usize; + assert_ne!(base, 0); + std::ptr::write_bytes(base as *mut u8, 0xab, 8 * K64); + let placed = place_held(&device, base + 2 * K64, K64); + assert!(title_frees(base + K64, 4 * K64, mem::MEM_DECOMMIT), "the title's decommit succeeds"); + let state = |page: usize| { + let mut info: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + mem::VirtualQuery((base + page * K64) as *const c_void, &mut info, size_of_val(&info)); + info.State + }; + assert_eq!([state(0), state(1), state(2), state(3), state(4), state(5)], [ + mem::MEM_COMMIT, + mem::MEM_RESERVE, + mem::MEM_COMMIT, + mem::MEM_RESERVE, + mem::MEM_RESERVE, + mem::MEM_COMMIT + ]); + assert!(same((base + 2 * K64) as *const u8, &vec![0; K64]), "what the heap stands over reads as zeros"); + assert!(same(base as *const u8, &vec![0xab; K64]), "outside the decommit untouched"); + drop(placed); + assert!(title_released(base, base + 8 * K64), "released once the heap went"); + } + } + + /// (`LEONIDA_INPLACE_QUERY_DECOMMITS`) The title decommits memory a heap + /// stands over, through the runtime's path: what the host keeps + /// committed and zeroed reads as reserved to its query + /// ([`title_memory_as_asked`]), on over the pages decommitted beside it; + /// committed again ([`title_memory_alloc`], as `leonida_hle`'s xmem makes + /// the title's `VirtualAlloc` and `XMemVirtualAlloc`), it reads as + /// committed, zeros; decommitted again, reserved again; and once the + /// title released the allocation nothing is kept over it. Before, it read + /// as committed until the title released the allocation. + #[test] + fn warp_a_decommit_kept_under_a_heap_reads_as_reserved_until_committed_again() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() { + return; + } + // SAFETY: an allocation of the test's own, written and read while + // committed. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as usize; + assert_ne!(base, 0); + // Memory the host just gave out (as in + // `warp_a_decommit_the_host_still_refuses_once_the_hold_went_zeroes`). + holds_freed(base, base + 8 * K64); + std::ptr::write_bytes(base as *mut u8, 0xab, 8 * K64); + let placed = place_held(&device, base + 2 * K64, K64); + assert!(title_frees(base + K64, 4 * K64, mem::MEM_DECOMMIT), "the title's decommit succeeds"); + assert_eq!(page_state(base + 2 * K64), mem::MEM_COMMIT, "kept committed under the heap"); + let info = queried(base + 2 * K64 + 0x10); + assert_eq!((info.State, info.Protect), (mem::MEM_RESERVE, 0), "reserved, as the title asked"); + assert_eq!((info.BaseAddress as usize, info.RegionSize), (base + 2 * K64, 3 * K64), "on over the pages decommitted after it"); + let info = queried(base + K64); + assert_eq!((info.State, info.RegionSize), (mem::MEM_RESERVE, 4 * K64), "the host's reserved page, on over it"); + assert_eq!(queried(base).State, mem::MEM_COMMIT); -fn kind_of(at: usize, len: usize, known: &mut Vec<(usize, usize)>) -> usize { - match cover(at, len) { - Cover::Run(..) => return 1, - Cover::Scattered => return 2, - Cover::Holes => return 3, - Cover::None => {} + let page = base + 2 * K64; + let commit = || mem::VirtualAlloc(page as *const c_void, K64, mem::MEM_COMMIT, mem::PAGE_READWRITE); + assert_eq!(title_memory_alloc(page, K64, mem::MEM_COMMIT, commit) as usize, page, "committed again"); + let info = queried(page); + assert_eq!((info.State, info.Protect, info.RegionSize), (mem::MEM_COMMIT, mem::PAGE_READWRITE, K64)); + assert!(same(page as *const u8, &vec![0; K64]), "committed again: zeros"); + assert_eq!(queried(base + K64).RegionSize, K64, "the reserved page before it ends there"); + + assert!(title_frees(page, K64, mem::MEM_DECOMMIT)); + assert_eq!((queried(page).State, queried(page).RegionSize), (mem::MEM_RESERVE, 3 * K64), "decommitted again"); + drop(placed); + assert!(title_released(base, base + 8 * K64), "released once the heap went"); + assert_eq!(decommitted_over(base, base + 8 * K64), vec![], "nothing kept over memory the title released"); + } } - let end = at + len; - if known.iter().any(|&(from, to)| from <= at && end <= to) { - return 0; + + /// Placed over `[start, start + len)` as [`place_held`] does, then let + /// go of by all but [`HELD`] and the heap: the moment a heap's last + /// reference went and the host has not yet let go of its pages (a busy + /// adapter's moment, [`GIVE_UP_MS`]; here the heap is kept for it). + fn place_and_leave_the_heap(device: &ID3D12Device, start: usize, len: usize) -> ID3D12Heap { + let Placed { buffer, heap, .. } = place_held(device, start, len); + drop(buffer); + heap } - // SAFETY: plain data filled in by the query. - let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; - // SAFETY: a valid out pointer of the right size. - let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; - if n == 0 { - return 5; + + /// The title decommits memory whose hold this very call lets go of + /// ([`reap`]) while the host still keeps the heap's pages: what the + /// host refuses reads as zeros and stays committed, the rest is + /// decommitted. Before, the pages of the hold just let go of were put + /// with the rest in one decommit, which the host refused whole; that + /// was not looked at and the title was told it was done, its pages + /// all still committed with their old bytes. + #[test] + fn warp_a_decommit_the_host_still_refuses_once_the_hold_went_zeroes() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() { + return; + } + // SAFETY: an allocation of the test's own, written and read while + // committed. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as usize; + assert_ne!(base, 0); + // Memory the host just gave out: a hold let go of over these + // addresses is another test's, whose memory went with the host's + // own call ([`holds_freed`] is the runtime's path). + holds_freed(base, base + 8 * K64); + std::ptr::write_bytes(base as *mut u8, 0xab, 8 * K64); + let heap = place_and_leave_the_heap(&device, base + 2 * K64, K64); + assert!(title_frees(base + K64, 4 * K64, mem::MEM_DECOMMIT), "the title's decommit succeeds"); + assert_eq!(standing_over(base, base + 8 * K64), 0, "the hold was let go of"); + let state = |page: usize| { + let mut info: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + mem::VirtualQuery((base + page * K64) as *const c_void, &mut info, size_of_val(&info)); + info.State + }; + assert_eq!([state(1), state(2), state(3), state(4), state(5)], [ + mem::MEM_RESERVE, + mem::MEM_COMMIT, + mem::MEM_RESERVE, + mem::MEM_RESERVE, + mem::MEM_COMMIT + ]); + assert!(same((base + 2 * K64) as *const u8, &vec![0; K64]), "what the host still keeps reads as zeros"); + drop(heap); + assert!(title_released(base, base + 8 * K64), "released once the heap went"); + } } - let reach = (info.BaseAddress as usize).saturating_add(info.RegionSize); - if info.Type == mem::MEM_PRIVATE && info.State == mem::MEM_COMMIT && info.Protect == mem::PAGE_READWRITE { - known.push((info.BaseAddress as usize, reach)); - return if reach >= end { 0 } else { 4 }; + + /// The title releases its allocation twice while a heap stands over it: + /// the first release is taken over and kept for the heap ([`PENDING`]), + /// the second is refused as one of free memory (error 487) and noted no + /// more. Before, it was taken over again and noted twice; once the first + /// was done, the note left over released the memory the host gave out + /// at the same address next. + #[test] + fn warp_a_second_release_of_memory_kept_for_a_heap_is_refused() { + use windows_sys::Win32::Foundation::{ERROR_INVALID_ADDRESS, GetLastError}; + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() { + return; + } + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 4 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + holds_freed(base, base + 4 * K64); + let Placed { buffer: list, .. } = place_held(&device, base + K64, K64); + assert!(title_frees(base, 0, mem::MEM_RELEASE), "the first release is taken over"); + assert_eq!(pending_over(base, base + 4 * K64), 1); + assert!(!title_frees(base, 0, mem::MEM_RELEASE), "the second is refused"); + // SAFETY: a plain read of the thread's last error. + assert_eq!(unsafe { GetLastError() }, ERROR_INVALID_ADDRESS, "as for free memory"); + assert!(!title_frees(base + K64, K64, mem::MEM_DECOMMIT), "and so is a decommit in it"); + assert_eq!(pending_over(base, base + 4 * K64), 1, "noted once"); + drop(list); + let released = (0..500).any(|_| { + reap(); + let done = pending_over(base, base + 4 * K64) == 0; + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(released, "released once the heap went"); + assert_eq!(standing_over(base, base + 4 * K64), 0, "no hold stands"); } - match info.Type { - mem::MEM_PRIVATE => 4, - mem::MEM_MAPPED => 3, - _ => 5, + + /// The title releases memory whose hold was let go of already (the + /// window went, the slot was written again, [`tick`] reaped) while the + /// host still keeps the heap's pages: the release is taken over and + /// done once the host lets go. Before, with no hold standing, it was + /// not taken over: the title got error 87 and its memory stayed + /// reserved for good, as with no take-over at all. + #[test] + fn warp_a_release_before_the_host_let_go_of_a_heap_is_taken_over() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() { + return; + } + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 4 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let heap = place_and_leave_the_heap(&device, base + K64, K64); + reap(); + assert_eq!(standing_over(base, base + 4 * K64), 0, "the hold was let go of"); + assert!(title_frees(base, 0, mem::MEM_RELEASE), "the title's VirtualFree succeeds"); + assert_eq!(pending_over(base, base + 4 * K64), 1, "the release waits for the host"); + assert!(allocation_of(base).is_some(), "kept reserved for the title meanwhile"); + drop(heap); + let released = (0..500).any(|_| { + reap(); + let done = allocation_of(base).is_none(); + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(released, "released once the host let go"); + assert_eq!(pending_over(base, base + 4 * K64), 0); } -} -/// The census lines for `spans` (start, bytes, whether a window outside -/// buffers). -fn census_of(spans: &[(u64, u64, bool)]) -> Vec<String> { - let mut known = Vec::new(); - let (mut buffers, mut windows) = (Tally::default(), Tally::default()); - for &(start, len, window) in spans { - let kind = kind_of(start as usize, len as usize, &mut known); - let tally = if window { &mut windows } else { &mut buffers }; - tally.0[kind].0 += 1; - tally.0[kind].1 += len; + /// Pages 1 to 3 of the title's four at `base`, all committed, as the + /// host has them after the title decommits them, a hold over page 2 let + /// go of just then while the host still keeps its heap's pages + /// ([`place_and_leave_the_heap`]); the heap goes after. + fn decommitted_beside_a_hold_let_go_of(device: &ID3D12Device, base: usize) -> [u32; 3] { + let heap = place_and_leave_the_heap(device, base + 2 * K64, K64); + assert!(title_frees(base + K64, 3 * K64, mem::MEM_DECOMMIT), "the title's decommit succeeds"); + let states = [page_state(base + K64), page_state(base + 2 * K64), page_state(base + 3 * K64)]; + drop(heap); + states } - let mut lines = Vec::new(); - for (name, tally) in [("title buffers", buffers), ("windows outside buffers", windows)] { - let all = tally.0.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)); - lines.push(format!("census, {name}: {} of {} MB", all.0, all.1 >> 20)); - for (kind, &(n, bytes)) in KINDS.iter().zip(&tally.0) { - if n > 0 { - lines.push(format!("census, {kind}: {n} of {} MB", bytes >> 20)); + + /// A hold let go of is forgotten over the memory the host frees under it + /// ([`holds_freed`]): released once the host let go of the heap + /// ([`release_pending`]), released at once, or decommitted at once + /// ([`title_memory_free`]). New memory there, at the same addresses or + /// committed again with the host's own call, then decommits as anywhere + /// else beside a hold let go of: the host's refusal under that hold's + /// heap keeps its page alone. Before, the old hold stayed noted for + /// [`GIVE_UP_MS`], was taken to be in the way, and the decommit was cut + /// with its page joined to the new hold's: refused whole, both were kept + /// committed and zeroed. (So + /// `warp_a_decommit_the_host_still_refuses_once_the_hold_went_zeroes` + /// failed about one run in five of the suite, when its allocation got + /// the addresses an earlier test's hold had been over.) + #[test] + fn warp_a_hold_let_go_of_is_forgotten_over_the_memory_the_host_freed() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() { + return; + } + const SIZE: usize = 4 * K64; + for way in ["released once the host let go", "released at once", "decommitted at once"] { + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + // A hold over page 1, let go of; the host keeps its heap's pages. + let heap = place_and_leave_the_heap(&device, base + K64, K64); + reap(); + assert_eq!(standing_over(base, base + SIZE), 0, "{way}: the hold was let go of"); + if way == "released once the host let go" { + assert!(title_frees(base, 0, mem::MEM_RELEASE), "{way}: the title's VirtualFree succeeds"); + assert_eq!(pending_over(base, base + SIZE), 1, "{way}: the release waits for the host"); + drop(heap); + let released = (0..500).any(|_| { + reap(); + let done = pending_over(base, base + SIZE) == 0; + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(released, "{way}: released once the host let go"); + } else { + drop(heap); + if way == "released at once" { + // The host lets go of the heap's pages: seen by its own + // decommit of them, which the runtime does not see. + let gone = (0..500).any(|_| { + // SAFETY: the test's own allocation. + let done = unsafe { mem::VirtualFree((base + K64) as *mut c_void, K64, mem::MEM_DECOMMIT) } != 0; + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(gone, "{way}: the host let go of the heap"); + assert!(title_frees(base, 0, mem::MEM_RELEASE), "{way}: the title's VirtualFree succeeds"); + assert_eq!(pending_over(base, base + SIZE), 0, "{way}: done at once"); + } else { + // Taken over (the page kept, zeroed) while the host still + // keeps the heap's pages, then the host's. + let decommitted = (0..500).any(|_| { + let done = title_frees(base + K64, K64, mem::MEM_DECOMMIT) && page_state(base + K64) == mem::MEM_RESERVE; + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(decommitted, "{way}: decommitted once the host let go"); + } + } + if way == "decommitted at once" { + // The title commits the page again with the host's own call, + // which is not the runtime's. + // SAFETY: a page of the test's own allocation. + let again = unsafe { mem::VirtualAlloc((base + K64) as *const c_void, K64, mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_eq!(again, base + K64, "{way}: committed again"); + } else { + // The title's new memory, at the same addresses. + // SAFETY: the addresses the test's allocation was at, free. + let again = unsafe { mem::VirtualAlloc(base as *const c_void, SIZE, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_eq!(again, base, "{way}: new memory at the same addresses"); } + assert_eq!( + decommitted_beside_a_hold_let_go_of(&device, base), + [mem::MEM_RESERVE, mem::MEM_COMMIT, mem::MEM_RESERVE], + "{way}: the page under the new hold's heap is kept, no other" + ); + assert!(title_released(base, base + SIZE), "{way}: released once the heap went"); } } - let v = views(); - let (count, bytes) = (v.views.len(), v.views.values().map(|view| view.0 as u64).sum::<u64>()); - let pages = v.views.values().filter(|view| view.0 == K64).count(); - let big = v.views.values().map(|view| view.0).max().unwrap_or(0); - lines.push(format!( - "census, the title's views of physical pages: {count} of {} MB; {pages} of them one 64 KiB page; the longest {} MB", - bytes >> 20, - big >> 20 - )); - // (The first few: with `LEONIDA_SECTION_MB` there are thousands, all alike.) - if v.sections.len() > 8 { - lines.push(format!( - "census, {} sections of {} MB in all; the first 8 follow", - v.sections.len(), - v.sections.values().map(|s| s.0).sum::<u64>() >> 20 - )); + + /// The title's reservation at a fixed address through the runtime's + /// own path ([`title_memory_reserve`], which `leonida_hle`'s xmem + /// calls), the host's call given as xmem gives it. + fn title_reserves(at: usize, len: usize) -> usize { + // SAFETY: a reservation at the test's own addresses. + title_memory_reserve(at, len, || unsafe { mem::VirtualAlloc(at as *const c_void, len, mem::MEM_RESERVE, mem::PAGE_READWRITE) }) as usize } - for &(bytes, committed) in v.sections.values().take(8) { - lines.push(format!( - "census, a section of {} MB, {}", - bytes >> 20, - if committed { "committed: it can be opened as one heap" } else { "reserved: refused as a heap until it is made with SEC_COMMIT" } - )); + + /// The title releases memory a heap stands over, and reserves the same + /// addresses again: while a list holds the heap's buffer the release is + /// kept and the reservation refused (error 487, the host's); once the + /// list is reset, before [`tick`] came by, the reservation does the + /// release first and is made. Before, it was refused until the next + /// [`tick`] did the release ([`REAP_MS`]), where the console's succeeds. + #[test] + fn warp_a_reservation_over_a_release_kept_for_a_heap_does_the_release_first() { + use windows_sys::Win32::Foundation::{ERROR_INVALID_ADDRESS, GetLastError}; + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() || !reserves() { + return; + } + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 4 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let Placed { buffer: list, .. } = place_held(&device, base + K64, K64); + assert!(title_frees(base, 0, mem::MEM_RELEASE), "the title's VirtualFree succeeds"); + assert_eq!(pending_over(base, base + 4 * K64), 1, "the release waits for the heap"); + + assert_eq!(title_reserves(base, 4 * K64), 0, "refused while the list holds the heap"); + // SAFETY: a plain read of the thread's last error. + assert_eq!(unsafe { GetLastError() }, ERROR_INVALID_ADDRESS, "the host's error"); + assert_eq!(pending_over(base, base + 4 * K64), 1); + + drop(list); + assert_eq!(title_reserves(base, 4 * K64), base, "the title's reservation is made"); + assert_eq!(pending_over(base, base + 4 * K64), 0, "the release was done first"); + assert_eq!(standing_over(base, base + 4 * K64), 0, "no hold stands"); + // SAFETY: the test's own reservation. + assert_ne!(unsafe { mem::VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE) }, 0); } - lines -} -/// With [`probe_level`] 2: one part of the title's own private memory -/// (the start of the biggest such title buffer, 4 MiB at most) is opened -/// for a moment, a buffer placed, 64 KiB read by the GPU and compared -/// with what the CPU reads there (the title may be writing it meanwhile: -/// the count of equal bytes is given), and all of it released. While the -/// heap stands (milliseconds) a `VirtualFree` of the title's on those -/// pages would fail. -fn real_part(spans: &[(u64, u64, bool)]) -> Vec<String> { - let Some(host) = crate::host::host() else { - return Vec::new(); - }; - let mut known = Vec::new(); - let found = spans - .iter() - .filter(|s| !s.2 && s.1 >= 2 * K64 as u64) - .filter(|s| kind_of(s.0 as usize, s.1 as usize, &mut known) == 0) - .max_by_key(|s| s.1); - let Some(&(start, len, _)) = found else { - return vec!["the title's memory: no title buffer in private, committed memory to try".to_owned()]; - }; - let at = (start as usize).next_multiple_of(K64); - let bytes = ((start + len) as usize).saturating_sub(at).min(4 << 20) & !(K64 - 1); - if bytes == 0 || !private_whole(at, bytes) { - return vec!["the title's memory: the buffer found holds no whole 64 KiB page that is still committed".to_owned()]; + /// The title's `VirtualProtect` through the runtime's own path + /// ([`title_memory_protect`], which `leonida_hle`'s xmem calls), the + /// host's call given as xmem gives it: whether the title is told it is + /// done, and the old protection it is told. + fn title_protects(at: usize, len: usize, new: u32) -> (bool, u32) { + let mut old = 0u32; + let out: *mut u32 = &mut old; + // SAFETY: the test's own allocation, and a live out pointer. + let done = title_memory_protect(at, len, new, out, || unsafe { mem::VirtualProtect(at as *const c_void, len, new, out) }) != 0; + (done, old) } - let mut lines = Vec::new(); - let (set, started) = (working_set_mb(), std::time::Instant::now()); - let opened = open(&host.device, From::Part(at, bytes)); - lines.push(format!( - "the title's memory, {} KiB at {at:#x} (of the title buffer {start:#x}+{len:#x}): {}; in {:.1} ms; working set {set} -> {} MB", - bytes >> 10, - hr(&opened), - started.elapsed().as_secs_f64() * 1000.0, - working_set_mb() - )); - if let Ok(heap) = &opened { - let placed = place(&host.device, heap, 0, bytes as u64); - lines.push(format!(" a buffer placed over it: {}", hr(&placed))); - if let (Ok(buffer), Ok(mut rig)) = (&placed, Rig::new(&host.device)) { - let mut before = vec![0u8; K64]; - crate::host::copy_mapped(before.as_mut_ptr(), at as *const u8, K64, false); - let got = rig.fetch(buffer, 0, K64); - let mut after = vec![0u8; K64]; - crate::host::copy_mapped(after.as_mut_ptr(), at as *const u8, K64, false); - match got { - Ok(got) => { - let equal = (0..K64).filter(|&i| got[i] == before[i] || got[i] == after[i]).count(); - let zeros = got.iter().filter(|&&b| b == 0).count(); - lines.push(format!( - " the GPU read 64 KiB of the title's own bytes: {equal} of {K64} equal to what the CPU read just before or just after ({zeros} of them zero)" - )); - } - Err(e) => lines.push(format!(" the GPU's read failed: {e}")), - } - } + + /// The protection the host says the page at `at` has. + fn protection(at: usize) -> u32 { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + info.Protect } - lines -} -/// Called once a second by the thread that submits, before a submission -/// (`host::sweep`): with [`probe_level`], the probe at the first call, the -/// census (on a thread of its own: it asks Windows about every copy) 30 -/// and 150 seconds later. -pub(crate) fn tick() { - if level() > 0 { - say(); + /// The title makes memory a window is in place over read-only, then + /// gives one page of it its writes back, through the runtime's path: + /// the window leaves the tables at once, and the title is told both are + /// done, with the old protections it would see, although the heap still + /// stands (the submissions that may use the window have not run, and a + /// list holds its buffer). Once neither holds it, both are made, in + /// that order. A protection of pages no heap stands over is the host's + /// at once. Before, the title's `VirtualProtect` was not the runtime's: + /// it failed with error 87 and the window stayed in the tables. + #[test] + fn warp_the_title_protects_memory_in_place_once_its_heap_is_gone() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() || !protects() { + return; + } + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let (start, len) = (base + K64 + 0x40, 2 * K64); + let placed = place_held(&device, start, len); + // A list that holds the window's buffer. + let list = placed.buffer.clone(); + let window = crate::shadow::in_place_window(placed, start as u64, len as u64); + let ours = std::sync::Arc::as_ptr(&window); + drop(window); + + assert_eq!(title_protects(base + K64, 3 * K64, mem::PAGE_READONLY), (true, mem::PAGE_READWRITE), "the title's VirtualProtect succeeds"); + assert!(!crate::shadow::in_place_window_there(start as u64, len as u64), "the window is let go"); + assert_eq!(protection(base + K64), mem::PAGE_READWRITE, "the protection waits for the heap"); + assert!(protect_waits(start, start + 16).is_some(), "nothing goes in place over it"); + assert_eq!(title_protects(base + 2 * K64, K64, mem::PAGE_READWRITE), (true, mem::PAGE_READONLY), "a protection behind it"); + assert_eq!(title_protects(base + 6 * K64, K64, mem::PAGE_READONLY), (true, mem::PAGE_READWRITE)); + assert_eq!(protection(base + 6 * K64), mem::PAGE_READONLY, "no heap there: made at once"); + + // The submissions that may use the window have run, the list is reset. + let buried = crate::host::bury_picked(|object| { + object.downcast_ref::<std::sync::Arc<crate::shadow::Shadow>>().is_some_and(|s| std::sync::Arc::as_ptr(s) == ours) + }); + assert_eq!(buried, 1, "the window waited for them"); + drop(list); + let made = (0..500).any(|_| { + reap(); + let done = protect_waits(base, base + 8 * K64).is_none(); + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(made, "made once the heap went"); + assert_eq!( + [protection(base + K64), protection(base + 2 * K64), protection(base + 3 * K64)], + [mem::PAGE_READONLY, mem::PAGE_READWRITE, mem::PAGE_READONLY], + "in the order the title asked" + ); + assert_eq!(standing_over(base, base + 8 * K64), 0, "no hold stands"); + assert!(title_frees(base, 0, mem::MEM_RELEASE), "the title releases the allocation"); + assert_eq!(pending_over(base, base + 8 * K64), 0, "released at once: the heap is gone"); } - if probe_level() == 0 { - return; + + /// The title releases memory a buffer of ours is placed over while + /// slots of a host view heap view the buffer: a title slot and a + /// dynamic slot a list gave back let go of it at the release, a dynamic + /// slot a list still holds keeps it, and once that list gives it back + /// and the slots are asked again the release is done. Before, every + /// slot kept the buffer until the title wrote it again, which it does + /// not for memory it freed: the release waited for good. + #[test] + fn slots_over_memory_the_title_released_let_go_of_its_buffer() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(host) = crate::host::host() else { return }; + if host.device.cast::<ID3D12Device13>().is_err() || !frees() || !slots() { + return; + } + let (title_heap, Some(heap)) = crate::descriptor::test_view_heap(8) else { return }; + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 4 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let (start, len) = (base + K64, K64); + let placed = place_part(&host.device, start as u64, len as u64).unwrap_or_else(|e| panic!("not placed on the host's device: {e:?}")); + hold(start as u64, len as u64, &placed.buffer); + let buffer = placed.buffer.clone(); + drop(placed); + let raw = [buffer.as_raw() as usize]; + // A title slot, a dynamic slot a list gave back, one a list holds. + heap.raw_at(3, &buffer, 0, len as u64); + let given = heap.dynamic(1).expect("a dynamic slot"); + heap.raw_at(given, &buffer, 0, len as u64); + heap.release(given, 1); + let held = heap.dynamic(1).expect("a dynamic slot"); + heap.raw_at(held, &buffer, 0, len as u64); + drop(buffer); + let ours = |r: &ID3D12Resource| r.as_raw() as usize == raw[0]; + + assert!(title_frees(base, 0, mem::MEM_RELEASE), "the title's VirtualFree succeeds"); + assert!(!heap.keeps_one_of(3, &raw), "the title slot let go of the buffer"); + assert!(!heap.keeps_one_of(given, &raw), "the dynamic slot given back let go of it"); + assert!(heap.keeps_one_of(held, &raw), "the dynamic slot a list holds keeps it"); + // The submissions that may read the two slots have run. + assert_eq!(crate::host::bury_resources_picked(ours), 2, "the slots' buffer waited for them"); + reap(); + assert_eq!(pending_over(base, base + 4 * K64), 1, "the held slot keeps the heap"); + // The list is reset; the slots are asked again ([`slots_again`]). + heap.release(held, 1); + assert_eq!(slots_let_go(base, base + 4 * K64, true), 1); + assert_eq!(crate::host::bury_resources_picked(ours), 1); + let released = (0..500).any(|_| { + reap(); + let done = allocation_of(base).is_none(); + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(released, "released once the heap went"); + assert_eq!(standing_over(base, base + 4 * K64), 0, "no hold stands"); + assert_eq!(pending_over(base, base + 4 * K64), 0); + crate::object::slot::<extern "system" fn(crate::object::This) -> u32>(title_heap, 0x10)(title_heap); } - static STARTED: AtomicU64 = AtomicU64::new(0); - static DONE: AtomicU64 = AtomicU64::new(0); - let now = crate::host::now_ms().max(1); - let started = match STARTED.compare_exchange(0, now, Ordering::Relaxed, Ordering::Relaxed) { - Ok(_) => { - let Some(host) = crate::host::host() else { - return; - }; - let mb = std::env::var("LEONIDA_INPLACE_PROBE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64usize); - let took = std::time::Instant::now(); - let probe = probe(&host.device, &|| host.video_memory(), mb.min(1024)); - for line in &probe.lines { - tracing::info!("in place probe: {line}"); + + /// The title makes memory a heap stands over executable, through the + /// runtime's path: told it is done, and the pages can be executed at once + /// (execute-read-write: the host takes more access under a heap); the + /// write it gave up goes once the heap is gone. One behind a protection + /// that waits is the same. Before, the execute waited with the rest: the + /// title was told it was done, and code it wrote there and jumped to + /// while the heap stood faulted (DEP). + #[test] + fn warp_execute_the_title_gives_memory_in_place_is_made_at_once() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() || !protects() { + return; + } + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 4 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let (start, len) = (base + K64, K64); + let window = crate::shadow::in_place_window(place_held(&device, start, len), start as u64, len as u64); + let ours = std::sync::Arc::as_ptr(&window); + drop(window); + + assert_eq!(title_protects(start, 0x1000, mem::PAGE_EXECUTE_READ), (true, mem::PAGE_READWRITE), "the title's VirtualProtect succeeds"); + assert_eq!(protection(start), mem::PAGE_EXECUTE_READWRITE, "executable at once, the write given up later"); + assert!(protect_waits(start, start + 0x1000).is_some(), "the rest waits for the heap"); + assert_eq!(title_protects(start + 0x1000, 0x1000, mem::PAGE_READONLY), (true, mem::PAGE_READWRITE)); + assert_eq!(title_protects(start + 0x1000, 0x1000, mem::PAGE_EXECUTE), (true, mem::PAGE_READONLY), "behind the one that waits"); + assert_eq!(protection(start + 0x1000), mem::PAGE_EXECUTE_READWRITE, "executable at once too"); + + // The submissions that may use the window have run. + let buried = crate::host::bury_picked(|object| { + object.downcast_ref::<std::sync::Arc<crate::shadow::Shadow>>().is_some_and(|s| std::sync::Arc::as_ptr(s) == ours) + }); + assert_eq!(buried, 1); + let made = (0..500).any(|_| { + reap(); + let done = protect_waits(base, base + 4 * K64).is_none(); + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); } - tracing::info!("in place probe: took {:.0} ms", took.elapsed().as_secs_f64() * 1000.0); - now + done + }); + assert!(made, "made once the heap went"); + assert_eq!([protection(start), protection(start + 0x1000)], [mem::PAGE_EXECUTE_READ, mem::PAGE_EXECUTE], "as the title asked"); + assert_eq!(standing_over(base, base + 4 * K64), 0, "no hold stands"); + assert!(title_frees(base, 0, mem::MEM_RELEASE), "the title releases the allocation"); + assert_eq!(pending_over(base, base + 4 * K64), 0, "released at once: the heap is gone"); + } + + /// The title protects a 4 KiB page beside a window's bytes, in the same + /// 64 KiB page: the host refuses it for the window's heap, which stands + /// over the whole 64 KiB page. The window leaves the tables, nothing is + /// opened anew over that page while the protection waits, and once the + /// submissions that may use the window have run the protection is made. + /// Before, only what lay over the protected bytes was let go: the window + /// stayed in the tables, its heap with it, and the protection waited for + /// as long, the title told it was done. + #[test] + fn warp_a_protection_beside_a_window_in_the_same_page_lets_the_window_go() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() || !protects() { + return; } - Err(started) => started, - }; - let due = match DONE.load(Ordering::Relaxed) { - 0 => now >= started + 30_000, - 1 => now >= started + 150_000, - _ => false, - }; - if due { - let which = DONE.fetch_add(1, Ordering::Relaxed); - std::thread::spawn(move || { - let spans = crate::shadow::spans(); - for line in census_of(&spans) { - tracing::info!("in place {line}"); + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 4 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let (start, len) = (base + K64 + 0x40, 0x100); + let window = crate::shadow::in_place_window(place_held(&device, start, len), start as u64, len as u64); + let ours = std::sync::Arc::as_ptr(&window); + drop(window); + let page = base + K64 + 0x8000; + + assert_eq!(title_protects(page, 0x1000, mem::PAGE_READONLY), (true, mem::PAGE_READWRITE), "the title's VirtualProtect succeeds"); + assert_eq!(protection(page), mem::PAGE_READWRITE, "the protection waits for the heap"); + assert!(!crate::shadow::in_place_window_there(start as u64, len as u64), "the window under the same heap is let go"); + assert!(kept_from(start as u64, len as u64), "nothing is opened again over the page whose protection waits"); + + // The submissions that may use the window have run. + let buried = crate::host::bury_picked(|object| { + object.downcast_ref::<std::sync::Arc<crate::shadow::Shadow>>().is_some_and(|s| std::sync::Arc::as_ptr(s) == ours) + }); + assert_eq!(buried, 1, "the window waited for them"); + let made = (0..500).any(|_| { + reap(); + let done = protect_waits(base, base + 4 * K64).is_none(); + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); } - if which == 0 && probe_level() >= 2 { - for line in real_part(&spans) { - tracing::info!("in place probe: {line}"); - } + done + }); + assert!(made, "made once the heap went"); + assert_eq!([protection(page), protection(start)], [mem::PAGE_READONLY, mem::PAGE_READWRITE]); + assert_eq!(standing_over(base, base + 4 * K64), 0, "no hold stands"); + assert!(title_frees(base, 0, mem::MEM_RELEASE), "the title releases the allocation"); + assert_eq!(pending_over(base, base + 4 * K64), 0, "released at once: the heap is gone"); + } + + /// The title protects memory a window is in place over while a title + /// slot of a view heap views the window's buffer (as one a shader picks + /// by index): the window leaves the tables, but the slot goes on + /// showing the buffer (the title's memory still, while the heap stands) + /// for as long as the submissions sent before the protection may run, + /// asked again or not; once they have, it lets go of it, and once the + /// submissions that may use the window have run too, the protection is + /// made. Before, the slot was made null at the protection: a submission + /// sent before it that read the slot by index read zeros, for memory the + /// title still held valid. + #[test] + fn slots_over_memory_the_title_protects_show_it_until_the_submissions_before_have_run() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(host) = crate::host::host() else { return }; + if host.device.cast::<ID3D12Device13>().is_err() || !frees() || !slots() || !protects() { + return; + } + let (title_heap, Some(heap)) = crate::descriptor::test_view_heap(8) else { return }; + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 4 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let (start, len) = (base + K64, K64); + let placed = place_part(&host.device, start as u64, len as u64).unwrap_or_else(|e| panic!("not placed on the host's device: {e:?}")); + hold(start as u64, len as u64, &placed.buffer); + let buffer = placed.buffer.clone(); + let window = crate::shadow::in_place_window(placed, start as u64, len as u64); + let shadow = std::sync::Arc::as_ptr(&window); + drop(window); + let raw = [buffer.as_raw() as usize]; + heap.raw_at(3, &buffer, 0, len as u64); + drop(buffer); + + assert_eq!(title_protects(base, 4 * K64, mem::PAGE_READONLY), (true, mem::PAGE_READWRITE), "the title's VirtualProtect succeeds"); + assert!(!crate::shadow::in_place_window_there(start as u64, len as u64), "the window is let go"); + assert!(heap.keeps_one_of(3, &raw), "the slot still shows the buffer while the submissions sent before may run"); + slots_again_now(); + assert!(heap.keeps_one_of(3, &raw), "and when asked again"); + assert_eq!(protection(start), mem::PAGE_READWRITE, "the protection waits"); + + // The submissions sent before the protection have run. + let ripe = PROTECTS.lock().unwrap().iter().find(|p| p.0 < start + len && p.1 > start).map(|p| p.4.clone()).expect("the protection waits"); + let ripened = crate::host::bury_picked(|object| object.downcast_ref::<Ripe>().is_some_and(|r| Arc::ptr_eq(&r.0, &ripe))); + assert_eq!(ripened, 1, "the slots waited for them"); + reap(); + assert!(!heap.keeps_one_of(3, &raw), "the slot let go of the buffer"); + // The submissions that may use the window and the slot have run. + let buried = crate::host::bury_picked(|object| { + object.downcast_ref::<std::sync::Arc<crate::shadow::Shadow>>().is_some_and(|s| std::sync::Arc::as_ptr(s) == shadow) + }); + assert_eq!(buried, 1); + assert_eq!(crate::host::bury_resources_picked(|r| r.as_raw() as usize == raw[0]), 1); + let made = (0..500).any(|_| { + reap(); + let done = protect_waits(base, base + 4 * K64).is_none(); + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); } + done }); + assert!(made, "made once the heap went"); + assert_eq!(protection(start), mem::PAGE_READONLY); + assert_eq!(standing_over(base, base + 4 * K64), 0, "no hold stands"); + assert!(title_frees(base, 0, mem::MEM_RELEASE), "the title releases the allocation"); + assert_eq!(pending_over(base, base + 4 * K64), 0, "released at once: the heap is gone"); + crate::object::slot::<extern "system" fn(crate::object::This) -> u32>(title_heap, 0x10)(title_heap); } -} - -#[cfg(test)] -pub(crate) mod tests { - use super::*; - /// Views as the runtime tells them: a range inside one view, or over - /// views that continue each other in one section, is one run; over - /// views from elsewhere it is scattered; over a gap it has holes. + /// The title decommits a 4 KiB page beside a window's bytes, under the + /// window's heap: the window stays in the tables (its memory is still + /// the title's), and so does the buffer in the descriptor slot that + /// views it. Once the title releases the allocation the slot lets go of + /// it. Before, the decommit made every slot that viewed a buffer of a + /// heap over the page let go of it, the window's too: null views read + /// as zeros, made again by the next draw from the same buffer, and + /// again once a second while anything waited. #[test] - fn the_views_say_how_much_of_a_range_is_there() { - const K64: usize = 64 << 10; - // Addresses nothing has: only the record is asked. - let at = 0x7ff1_0000_0000_usize; - for (block, blocks) in [(0, 1), (1, 1), (4, 2)] { - super::title_memory_view(at + block * K64, blocks * K64, 7, 0); + fn slots_keep_a_window_still_shown_through_a_decommit_beside_it() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(host) = crate::host::host() else { return }; + if host.device.cast::<ID3D12Device13>().is_err() || !frees() || !slots() { + return; } - let shown = |from: usize, len: usize| super::shown_bytes(at + from, len); - assert_eq!(shown(0, 8 * K64), Some(4 * K64 as u64)); - assert_eq!(shown(100, K64), Some(K64 as u64)); - assert_eq!(shown(K64 + 100, 2 * K64), Some(K64 as u64 - 100)); - assert_eq!(shown(5 * K64 + 1, 10), Some(10)); - assert_eq!(shown(2 * K64, 2 * K64), None); - assert_eq!(shown(6 * K64, 2 * K64), None); - // The same as runs: views that touch are one, cut to the range. - let runs = |from: usize, len: usize| super::shown_runs(at + from, len); - assert_eq!(runs(0, 8 * K64), vec![(at, 2 * K64), (at + 4 * K64, 2 * K64)]); - assert_eq!(runs(100, K64), vec![(at + 100, K64)]); - assert_eq!(runs(5 * K64 + 1, 10), vec![(at + 5 * K64 + 1, 10)]); - assert_eq!(runs(2 * K64, 2 * K64), vec![]); - super::views_gone(at + K64, K64); - assert_eq!(shown(0, 2 * K64), Some(K64 as u64)); - assert_eq!(runs(0, 2 * K64), vec![(at, K64)]); - super::views_gone(at, 8 * K64); - assert_eq!(shown(0, 8 * K64), None); + let (title_heap, Some(heap)) = crate::descriptor::test_view_heap(8) else { return }; + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 4 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let (start, len) = (base + K64 + 0x40, 0x100); + let placed = place_part(&host.device, start as u64, len as u64).unwrap_or_else(|e| panic!("not placed on the host's device: {e:?}")); + hold(start as u64, len as u64, &placed.buffer); + let buffer = placed.buffer.clone(); + let window = crate::shadow::in_place_window(placed, start as u64, len as u64); + let shadow = std::sync::Arc::as_ptr(&window); + drop(window); + let raw = [buffer.as_raw() as usize]; + heap.raw_at(3, &buffer, 0, len as u64); + drop(buffer); + + assert!(title_frees(base + K64 + 0x8000, 0x1000, mem::MEM_DECOMMIT), "the title's VirtualFree succeeds"); + assert!(crate::shadow::in_place_window_there(start as u64, len as u64), "the window is still shown"); + assert!(heap.keeps_one_of(3, &raw), "and so the slot keeps its buffer"); + + assert!(title_frees(base, 0, mem::MEM_RELEASE), "the title releases the allocation"); + assert!(!heap.keeps_one_of(3, &raw), "the slot let go of the buffer"); + // The submissions that may use the window and the slot have run. + let buried = crate::host::bury_picked(|object| { + object.downcast_ref::<std::sync::Arc<crate::shadow::Shadow>>().is_some_and(|s| std::sync::Arc::as_ptr(s) == shadow) + }); + assert_eq!(buried, 1); + assert_eq!(crate::host::bury_resources_picked(|r| r.as_raw() as usize == raw[0]), 1); + let released = (0..500).any(|_| { + reap(); + let done = allocation_of(base).is_none(); + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(released, "released once the heap went"); + assert_eq!(standing_over(base, base + 4 * K64), 0, "no hold stands"); + crate::object::slot::<extern "system" fn(crate::object::This) -> u32>(title_heap, 0x10)(title_heap); } - #[test] - fn views_say_what_one_placed_buffer_could_show() { - let mut views = BTreeMap::new(); - let at = 0x7_0000_0000usize; - views.insert(at, (4 * K64, 9, 16 * K64 as u64)); - // Continues the first in the section. - views.insert(at + 4 * K64, (2 * K64, 9, 20 * K64 as u64)); - // Follows in address, from elsewhere in the section. - views.insert(at + 6 * K64, (K64, 9, 3 * K64 as u64)); - // After a gap of one page. - views.insert(at + 8 * K64, (K64, 9, 4 * K64 as u64)); - assert_eq!(cover_in(&views, at + K64, 2 * K64), Cover::Run(9, 17 * K64 as u64)); - assert_eq!(cover_in(&views, at + K64, 5 * K64), Cover::Run(9, 17 * K64 as u64)); - assert_eq!(cover_in(&views, at, 7 * K64), Cover::Scattered); - assert_eq!(cover_in(&views, at + 6 * K64, 3 * K64), Cover::Holes); - assert_eq!(cover_in(&views, at + 7 * K64, K64), Cover::None); - assert_eq!(cover_in(&views, at - K64, 2 * K64), Cover::None); + /// [`level`] and [`asynchronous`] for this thread's asks, as a test sets + /// them; as they were once dropped. + struct Background; + + impl Background { + fn new(level: u8) -> Background { + TEST_LEVEL.set(Some(level)); + TEST_ASYNC.set(Some(true)); + Background + } } - /// The stretch around a run: views on both sides that follow in memory - /// and in the section, up to a view from elsewhere or a gap. - #[test] - fn a_stretch_is_the_views_around_a_run_that_follow_in_the_section() { - let mut views = BTreeMap::new(); - let at = 0x7_2000_0000usize; - // From elsewhere in the section, just below. - views.insert(at - K64, (K64, 9, 40 * K64 as u64)); - for (k, n) in [(0usize, 2usize), (2, 3), (5, 1)] { - views.insert(at + k * K64, (n * K64, 9, ((10 + k) * K64) as u64)); + impl Drop for Background { + fn drop(&mut self) { + TEST_LEVEL.set(None); + TEST_ASYNC.set(None); } - // Next in memory, of another section; then a gap. - views.insert(at + 6 * K64, (K64, 8, 16 * K64 as u64)); - views.insert(at + 8 * K64, (K64, 9, 18 * K64 as u64)); - let whole = Some((at, 6 * K64, 9, 10 * K64 as u64)); - assert_eq!(stretch_in(&views, at + 3 * K64 + 5, 10), whole); - assert_eq!(stretch_in(&views, at, 6 * K64), whole); - assert_eq!(stretch_in(&views, at + 5 * K64, 2 * K64), None, "into the other section"); - assert_eq!(stretch_in(&views, at + 6 * K64, K64), Some((at + 6 * K64, K64, 8, 16 * K64 as u64))); - assert_eq!(stretch_in(&views, at + 7 * K64, K64), None, "the gap"); } - /// What the runtime forgets when memory is mapped anew. - #[test] - fn remapped_memory_forgets_its_views() { - let at = 0x7_4000_0000usize; - title_memory_view(at, 4 * K64, 77, 0); - title_memory_view(at + 4 * K64, K64, 77, 4 * K64 as u64); - assert_eq!(cover(at, 5 * K64), Cover::Run(77, 0)); - // One page inside the first view goes: the whole view is forgotten - // (the runtime maps and tells again what stays of it). - views_gone(at + K64, K64); - assert_eq!(cover(at, K64), Cover::None); - assert_eq!(cover(at + 4 * K64, K64), Cover::Run(77, 4 * K64 as u64)); - views_gone(at + 4 * K64, K64); - assert_eq!(cover(at + 4 * K64, K64), Cover::None); + /// [`switch_ready`], waiting for [`GATE`] if a test's free holds it. + pub(crate) fn switch_ready_now() { + switch_ready_at(crate::host::now_ms(), true); } - /// Only private memory committed whole, read-write, is taken for a part. - #[test] - fn only_private_memory_committed_whole_is_a_part() { - // SAFETY: an allocation of the test's own. + /// Whether `ask` waits for the opener ([`ASKED`]). + fn asked(ask: Ask) -> bool { + ASKED.lock().unwrap().contains(&ask) + } + + /// The opener's work for `ask`, on `device`, once it was asked for + /// (taken out of [`ASKED`] as the opener takes it). + fn open_now(device: &ID3D12Device, ask: Ask) -> bool { + let mut queue = ASKED.lock().unwrap(); + let Some(i) = queue.iter().position(|a| *a == ask) else { + return false; + }; + queue.remove(i); + drop(queue); + open_asked(device, ask) + } + + /// The opener's work for the window `[start, start + len)` once it was + /// asked for, on `device` ([`open_now`]). + pub(crate) fn open_window_now(device: &ID3D12Device, start: u64, len: u64) -> bool { + open_now(device, Ask { start, len, window: true }) + } + + /// What the opener opened for `ask` waits ([`READY`]). + fn ready(ask: Ask) -> bool { + READY.lock().unwrap().iter().any(|r| r.ask == ask) + } + + /// A copy of `[start, start + len)` in the tables as a window, as a + /// lookup makes while the opener opens: its buffer committed on + /// `device`. + fn copy_window(device: &ID3D12Device, start: u64, len: u64) -> Arc<crate::shadow::Shadow> { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain creation with valid descriptions. unsafe { - let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE, mem::PAGE_NOACCESS).cast::<u8>(); - assert!(!base.is_null()); - assert!(!private_whole(base as usize, K64), "reserved only"); - mem::VirtualAlloc(base.cast(), 4 * K64, mem::MEM_COMMIT, mem::PAGE_READWRITE); - assert!(private_whole(base as usize, 4 * K64)); - assert!(private_whole(base as usize + K64, 2 * K64)); - assert!(!private_whole(base as usize, 5 * K64), "reaches into the reserved half"); - let mut old = 0; - mem::VirtualProtect(base.cast(), K64, mem::PAGE_READONLY, &mut old); - assert!(!private_whole(base as usize, 2 * K64), "a guarded page"); - mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(len, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + .expect("a buffer"); } + crate::shadow::copy_window(buffer.expect("a buffer"), start, len) } - pub(crate) fn warp() -> Option<ID3D12Device> { - use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; - use windows::Win32::Graphics::Dxgi::*; - // SAFETY: plain DXGI queries and device creation on the software - // adapter; a card is never opened. - unsafe { - let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; - let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; - let desc = adapter.cast::<IDXGIAdapter1>().ok()?.GetDesc1().ok()?; - if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { - return None; + /// The window over `[start, start + len)` out of the tables and the + /// retired objects (the test's memory goes back), and every hold over + /// `[at, end)` let go of. + fn window_cleared(start: u64, len: u64, at: usize, end: usize) { + if let Some(window) = crate::shadow::window_gone(start, len) { + let ours = Arc::as_ptr(&window); + drop(window); + crate::host::bury_picked(|object| object.downcast_ref::<Arc<crate::shadow::Shadow>>().is_some_and(|s| Arc::as_ptr(s) == ours)); + } + crate::host::bury_picked(|object| { + object.downcast_ref::<Arc<crate::shadow::Shadow>>().is_some_and(|s| s.span().0 >= at as u64 && s.span().0 < end as u64) + }); + let gone = (0..500).any(|_| { + reap(); + let none = standing_over(at, end) == 0; + if !none { + std::thread::sleep(std::time::Duration::from_millis(10)); } - let mut device: Option<ID3D12Device> = None; - D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; - device + none + }); + assert!(gone, "no hold stands over the test's memory"); + } + + /// (`LEONIDA_INPLACE_ASYNC`) A window of private memory is not opened by + /// the ask: the ask goes to the opener and the lookup makes a copy. What + /// the opener opened is held at once (a free would find it), and goes in + /// the place of the copy at the next tick, while a list still holds the + /// copy (`LEONIDA_INPLACE_SWITCH_HELD`: memory read every frame always is + /// held); the list keeps its copy, alive and noted as switched, and the + /// card then reads the title's bytes through what is in place. Before, + /// the ask opened the memory itself, on the list thread, under the + /// tables' lock; and then a copy a list held was not switched. + #[test] + fn warp_a_window_is_opened_in_the_background_and_switched_in_at_a_safe_point() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() { + return; } + let _background = Background::new(1); + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let (start, len) = ((base + K64) as u64, 2 * K64 as u64); + let ask = Ask { start, len, window: true }; + + assert!(place_for(start, len, true).is_none(), "the ask does not open the memory"); + assert!(asked(ask), "the opener is asked"); + assert_eq!(standing_over(base, base + 8 * K64), 0, "nothing opened yet"); + // The lookup's copy meanwhile, held by a list being recorded. + let list = copy_window(&device, start, len); + assert!(open_now(&device, ask), "the opener opens it"); + assert!(ready(ask)); + assert_eq!(standing_over(base, base + 8 * K64), 1, "held as soon as opened"); + + let switched = STATS[18].load(Ordering::Relaxed); + switch_ready_now(); + let window = crate::shadow::window_there(start, len).expect("a window"); + assert!(window.in_place(), "the window is the title memory in place now, though a list holds the copy"); + assert!(!ready(ask)); + assert!(STATS[18].load(Ordering::Relaxed) > switched, "counted as switched"); + assert!(!list.in_place() && list.switched_for_test(), "the list keeps its copy, noted as switched"); + // SAFETY: a live buffer (the list's `Arc` keeps the copy and its buffer). + assert_ne!(unsafe { list.buffer.GetGPUVirtualAddress() }, 0); + let ours = Arc::as_ptr(&list); + drop(list); + crate::host::bury_picked(|object| object.downcast_ref::<Arc<crate::shadow::Shadow>>().is_some_and(|s| Arc::as_ptr(s) == ours)); + let mut rig = Rig::new(&device).unwrap(); + fill(start as *mut u8, len as usize, 11); + let got = rig.fetch(&window.buffer, window.offset(start), len as usize).unwrap(); + assert!(same(start as *const u8, &got), "the card reads the title's bytes"); + drop(window); + window_cleared(start, len, base, base + 8 * K64); + assert!(host_releases(base)); } - /// The probe, whole, on the software adapter: the same calls the card - /// gets. The runtime's and the kernel's rules hold there; the card's - /// driver is what a run with `LEONIDA_INPLACE_PROBE=1` adds. + /// A copy shaders were declared to write, or a descriptor slot views, is + /// never switched: the first may hold what title memory does not (a write + /// to copy back, or one kept out of it), the second would leave the slot + /// reading a copy nobody brings up to date. What the opener opened then + /// waits [`READY_MS`] and is let go, its heap with it: the pages are not + /// locked for nothing. #[test] - fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() { + fn warp_a_copy_written_or_viewed_is_not_switched_and_what_was_opened_goes() { let _turn = crate::indirect::tests::warp_turn(); let Some(device) = warp() else { return }; - if device.cast::<ID3D12Device13>().is_err() { - eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened"); + if device.cast::<ID3D12Device13>().is_err() || !frees() { return; } - let probe = probe(&device, &|| None, 4); - for line in &probe.lines { - eprintln!("in place probe: {line}"); + let _background = Background::new(1); + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 4 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let (start, len) = (base as u64, K64 as u64); + let ask = Ask { start, len, window: true }; + assert!(place_for(start, len, true).is_none()); + let copy = copy_window(&device, start, len); + assert!(open_now(&device, ask)); + + let slot = copy.buffer.clone(); + let raw = copy.buffer.as_raw(); + drop(copy); + switch_ready_now(); + assert!(ready(ask), "not while a slot views the copy"); + drop(slot); + crate::shadow::window_there(start, len).expect("a window").written_for_test(); + switch_ready_now(); + assert!(ready(ask), "nor once shaders were declared to write it"); + assert_eq!(crate::shadow::window_there(start, len).expect("a window").buffer.as_raw(), raw, "the copy keeps its place"); + + switch_ready_at(crate::host::now_ms() + READY_MS, true); + assert!(!ready(ask), "let go once it waited that long"); + window_cleared(start, len, base, base + 4 * K64); + assert!(host_releases(base), "no heap is left over it"); + } + + /// A copy the directory of memory by address numbered is never switched, + /// held by lists or not (`LEONIDA_INPLACE_SWITCH_HELD`): the directory + /// keeps it for good and shows shaders that one, so it would stand beside + /// the title memory in place for as long, a second view of the same bytes. + #[test] + fn warp_a_copy_memory_by_address_numbered_is_not_switched() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() { + return; } - assert!(probe.part_reads, "the GPU reads private memory in place"); - assert!(probe.part_writes, "GPU writes land in private memory"); - assert!(probe.section_reads && probe.section_writes, "a committed section in place"); - assert!(probe.section_outlives_views, "the section's heap does not depend on views"); - assert!(probe.reserved_section_refused, "a reserved section is refused"); + let _background = Background::new(1); + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 4 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let (start, len) = (base as u64, K64 as u64); + let ask = Ask { start, len, window: true }; + assert!(place_for(start, len, true).is_none()); + let copy = copy_window(&device, start, len); + assert!(open_now(&device, ask)); + copy.note_numbered(); + let raw = copy.buffer.as_raw(); + drop(copy); + switch_ready_now(); + assert!(ready(ask), "not switched"); + assert_eq!(crate::shadow::window_there(start, len).expect("a window").buffer.as_raw(), raw, "the copy keeps its place"); + switch_ready_at(crate::host::now_ms() + READY_MS, true); + assert!(!ready(ask)); + window_cleared(start, len, base, base + 4 * K64); + assert!(host_releases(base), "no heap is left over it"); } - /// Stage 1's own call on the software adapter: a title buffer that - /// begins and ends off the 64 KiB lines is placed over its pages, the - /// GPU reads the buffer's bytes at the offset the views use, and its - /// write lands at the title's address. Memory that is not committed - /// whole is turned down without asking the host. + /// The title protects or releases memory the opener opened and nothing + /// took yet: what was opened is let go first and the call is made at + /// once, where the heap would have had it wait (or refused it, error 87, + /// had it not been held); and a later ask of that memory opens nothing + /// for it. Then an ask takes what the opener opened, counted in place. #[test] - fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() { + fn warp_the_title_protects_and_frees_memory_the_opener_opened_at_once() { let _turn = crate::indirect::tests::warp_turn(); let Some(device) = warp() else { return }; - if device.cast::<ID3D12Device13>().is_err() { + if device.cast::<ID3D12Device13>().is_err() || !frees() || !protects() { return; } + let _background = Background::new(1); // SAFETY: an allocation of the test's own. - unsafe { - let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::<u8>(); - let (start, len) = (base as u64 + K64 as u64 + 0x1230, 2 * K64 as u64 + 5); - let placed = place_part(&device, start, len).unwrap_or_else(|e| panic!("not placed: {e:?}")); - assert_eq!(placed.bias, 0x1230); - assert_eq!(placed.gpu, placed.buffer.GetGPUVirtualAddress() + 0x1230); - assert_eq!(placed.buffer.GetDesc().Width, 3 * K64 as u64, "the pages that hold the buffer"); - let mut rig = Rig::new(&device).unwrap(); - fill(start as *mut u8, len as usize, 7); - let got = rig.fetch(&placed.buffer, placed.bias, len as usize).unwrap(); - assert!(same(start as *const u8, &got), "the GPU reads the title buffer's bytes"); - rig.store(&placed.buffer, placed.bias + 16, &[0xa5; 64]).unwrap(); - assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); - drop(placed); - // Half of it decommitted: turned down, the host not asked. - // The heap lets go of the pages a moment after its last - // reference, if the adapter is busy with other tests' work. - let gone = (0..500).any(|_| { - let done = mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; - if !done { - std::thread::sleep(std::time::Duration::from_millis(10)); - } - done - }); - assert!(gone, "the heap keeps the pages"); - assert!(matches!(place_part(&device, start, len), Err(None))); - mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 4 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let (start, len) = ((base + K64) as u64, K64 as u64); + let ask = Ask { start, len, window: true }; + assert!(place_for(start, len, true).is_none()); + assert!(open_now(&device, ask)); + + let page = base + K64 + 0x2000; + assert_eq!(title_protects(page, 0x1000, mem::PAGE_READONLY), (true, mem::PAGE_READWRITE)); + assert_eq!(protection(page), mem::PAGE_READONLY, "made at once"); + assert!(!ready(ask), "what was opened is let go"); + assert!(protect_waits(page, page + 0x1000).is_none(), "nothing waits"); + assert!(place_for(start, len, true).is_none()); + assert!(!open_now(&device, ask), "a 64 KiB page of mixed protections is not opened"); + assert_eq!(title_protects(page, 0x1000, mem::PAGE_READWRITE), (true, mem::PAGE_READONLY)); + + assert!(place_for(start, len, true).is_none()); + assert!(open_now(&device, ask)); + assert!(title_frees(base, 0, mem::MEM_RELEASE), "the title's VirtualFree succeeds"); + assert!(!ready(ask)); + let released = (0..500).any(|_| { + reap(); + let done = allocation_of(base).is_none(); + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(released, "released at once, or once the host let go of the heap"); + assert_eq!(pending_over(base, base + 4 * K64), 0); + assert!(!asked(ask)); + + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 2 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let ask = Ask { start: base as u64, len: K64 as u64, window: false }; + TEST_LEVEL.set(Some(2)); + assert!(place_for(ask.start, ask.len, false).is_none()); + assert!(open_now(&device, ask)); + let before = STATS[2].load(Ordering::Relaxed); + let placed = place_for(ask.start, ask.len, false).expect("the later ask takes what was opened"); + assert!(STATS[2].load(Ordering::Relaxed) > before, "counted in place"); + assert!(!ready(ask)); + gone(false, ask.len); + drop(placed); + window_cleared(0, 0, base, base + 2 * K64); + assert!(host_releases(base)); + } + + /// (`LEONIDA_INPLACE_AGAIN`) The title takes write access from a page of + /// a window in place, and gives it back once the heap went: the window + /// was let go for the protection, and the copy a lookup made meanwhile + /// (the 64 KiB page had mixed protections, which no heap opens) is asked + /// to be opened in place again, then takes the copy's place; so too when + /// both protections waited for the heap and are made together. Before, + /// the copy stayed for as long as it was used. + #[test] + fn warp_memory_protected_and_given_write_back_is_opened_in_place_again() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + if device.cast::<ID3D12Device13>().is_err() || !frees() || !protects() || !agains() { + return; + } + let _background = Background::new(1); + for waited in [false, true] { + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), 4 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let (start, len) = (base as u64, 2 * K64 as u64); + let ask = Ask { start, len, window: true }; + let placed = place_held(&device, base, 2 * K64); + let window = crate::shadow::in_place_window(placed, start, len); + let ours = Arc::as_ptr(&window); + drop(window); + let page = base + K64 + 0x5000; + let bury = || { + crate::host::bury_picked(|object| object.downcast_ref::<Arc<crate::shadow::Shadow>>().is_some_and(|s| Arc::as_ptr(s) == ours)); + reap(); + }; + + assert_eq!(title_protects(page, 0x1000, mem::PAGE_READONLY), (true, mem::PAGE_READWRITE)); + assert!(!crate::shadow::in_place_window_there(start, len), "the window is let go"); + // The lookup's copy meanwhile. + drop(copy_window(&device, start, len)); + assert!(place_for(start, len, true).is_none()); + assert!(!open_now(&device, ask), "a 64 KiB page of mixed protections (or one whose protection waits) is not opened"); + if waited { + assert_eq!(title_protects(page, 0x1000, mem::PAGE_READWRITE), (true, mem::PAGE_READONLY), "waits behind"); + assert!(!asked(ask), "not before it is made"); + bury(); + } else { + bury(); + assert_eq!(protection(page), mem::PAGE_READONLY, "made once the heap went"); + assert!(!asked(ask)); + assert_eq!(title_protects(page, 0x1000, mem::PAGE_READWRITE), (true, mem::PAGE_READONLY)); + } + assert_eq!(protection(page), mem::PAGE_READWRITE); + assert!(asked(ask), "the copy is asked to be opened in place again"); + assert!(open_now(&device, ask)); + switch_ready_now(); + assert!(crate::shadow::window_there(start, len).expect("a window").in_place(), "in place again"); + window_cleared(start, len, base, base + 4 * K64); + assert!(host_releases(base)); } } + /// The title's free waits for an opening in progress ([`GATE`]): it then + /// meets a heap of the opener's that is held, or none. + #[test] + fn a_free_waits_for_the_opener() { + let _turn = crate::indirect::tests::warp_turn(); + let opening = GATE.write().unwrap(); + // SAFETY: an allocation of the test's own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0); + let done = Arc::new(AtomicBool::new(false)); + let freeing = { + let done = done.clone(); + std::thread::spawn(move || { + assert!(title_frees(base, 0, mem::MEM_RELEASE)); + done.store(true, Ordering::Release); + }) + }; + std::thread::sleep(std::time::Duration::from_millis(50)); + assert!(!done.load(Ordering::Acquire), "not while the opener opens"); + drop(opening); + freeing.join().unwrap(); + assert!(done.load(Ordering::Acquire)); + } + /// The census names each kind of memory. #[test] fn census_tells_private_memory_from_views() { @@ -1565,4 +5286,151 @@ pub(crate) mod tests { mem::VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE); } } + + /// (Diagnostics) An ask over scattered single pages of a committed + /// section is turned down by [`place_for`] and the census of tiles + /// counts it as one they could hold, alive; the title's unmapping of a + /// page under it ([`views_gone`]) is counted as unmapped, its mapping of + /// another there ([`title_memory_view`]) as mapped, and the census's + /// line lets it go once it is no copy. + #[cfg(feature = "diagnostics")] + #[test] + fn scattered_pages_of_a_committed_section_turned_down_are_counted_as_tiles() { + // Addresses and a section number nothing else has: only the record + // is asked. + let (section, at, len) = (usize::MAX - 0x75, 0x7ff3_0000_0000usize, 4 * K64); + title_memory_section(section, 64 * K64 as u64, true); + for (k, page) in [9u64, 3, 7, 1].into_iter().enumerate() { + title_memory_view(at + k * K64, K64, section, page * K64 as u64); + } + TEST_LEVEL.set(Some(1)); + let turned = STATS[4].load(Ordering::Relaxed); + let placed = place_for(at as u64, len as u64, true); + TEST_LEVEL.set(None); + assert!(placed.is_none(), "not one run of a section: turned down"); + assert!(STATS[4].load(Ordering::Relaxed) > turned, "counted as turned down"); + let (alive, mapped, unmapped) = tiled::seen(at, len); + assert!(alive, "the census counts it as one tiles could hold, alive"); + + views_gone(at + 2 * K64, K64); + let (_, mapped_now, unmapped_now) = tiled::seen(at, len); + assert_eq!(unmapped_now, unmapped + 1, "the page unmapped under it"); + assert_eq!(mapped_now, mapped, "an unmapping is no mapping"); + title_memory_view(at + 2 * K64, K64, section, 20 * K64 as u64); + let (_, mapped_now, unmapped_now) = tiled::seen(at, len); + assert_eq!(mapped_now, (mapped.0 + 1, mapped.1 + 1), "the view mapped over it"); + assert_eq!(unmapped_now, unmapped + 1, "a mapping is no unmapping"); + + let line = tiled::line().expect("a census line"); + assert!(line.contains("tiles could hold"), "{line}"); + assert!(!tiled::seen(at, len).0, "no copy of it: let go by the line"); + views_gone(at, len); + title_memory_section_gone(section); + } + + /// A title buffer placed in its section while the title maps other + /// pages there (after the placement, before it is in the tables) is + /// let go at once: [`in_section`] looks at the run again once it has + /// counted it, the counts go back, and the buffer is a copy instead. + /// Left, it showed the section's old pages at an address that no + /// longer shows them, and the let-go that came before it had found + /// nothing to let go of. + #[test] + fn a_placement_in_a_section_the_title_maps_other_pages_over_meanwhile_is_let_go() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(_host) = crate::shadow::in_place_tests::host_that_opens() else { return }; + if !sections() { + return; + } + let _asked = crate::shadow::in_place_tests::Asked::new(2, true); + const SIZE: usize = 4 * K64; + // SAFETY: a section and a view of the test's own. + let (handle, view) = unsafe { + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null()); + assert!(!handle.is_null(), "a committed section"); + let view = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, 0, SIZE).Value as usize; + assert_ne!(view, 0); + (handle, view) + }; + title_memory_section(handle as usize, SIZE as u64, true); + title_memory_view(view, SIZE, handle as usize, 0); + let (start, len) = (view + 0x100, 3 * K64); + crate::shadow::in_place_tests::write(start, len, 21); + let count = || [STATS[2].load(Ordering::Relaxed), STATS[3].load(Ordering::Relaxed), STATS[7].load(Ordering::Relaxed)]; + let before = count(); + TEST_REMAPPED_WHILE_PLACING.set(Some((view, SIZE))); + crate::shadow::register(start, start as u64, len as u64); + let shadow = crate::shadow::find(start as u64, len as u64); + crate::shadow::unregister(start, start as u64); + let reached = TEST_REMAPPED_WHILE_PLACING.take().is_none(); + let shadow = shadow.expect("a copy"); + assert!(reached, "the buffer was placed in its section"); + assert!(!shadow.in_place(), "not left in place over pages the title no longer shows there"); + assert_eq!(count(), [before[0], before[1], before[2] + 1], "counted back, and as let go"); + drop(shadow); + // SAFETY: the test's own view and section. + unsafe { + mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut c_void }); + title_memory_section_gone(handle as usize); + windows_sys::Win32::Foundation::CloseHandle(handle); + } + } + + /// A run of a committed section the runtime noted is opened in the + /// section, one heap for every buffer placed in it: the card reads the + /// bytes the title sees at the run's address, and its write is there; + /// once the view is unmapped and the handle closed it still reads them + /// (the heap is the section), and the section's heap is forgotten with + /// it. A reserved section, one the runtime never made and bytes past the + /// end are turned down without asking the host. + #[test] + fn warp_a_run_of_a_committed_section_opens_in_it() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = warp() else { return }; + const SIZE: usize = 8 * K64; + // SAFETY: a section and a view of the test's own. + unsafe { + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null()); + assert!(!handle.is_null(), "a committed section"); + let section = handle as usize; + // The section's pages 2 to 5 in one view. + let view = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, (2 * K64) as u32, 4 * K64).Value as usize; + assert_ne!(view, 0); + title_memory_section(section, SIZE as u64, true); + title_memory_view(view, 4 * K64, section, (2 * K64) as u64); + let (at, len) = (view + K64 + 0x340, 2 * K64); + fill(at as *mut u8, len, 11); + assert_eq!(cover(at, len), Cover::Run(section, (3 * K64 + 0x340) as u64)); + let placed = place_in_section(&device, section, (3 * K64 + 0x340) as u64, len as u64).unwrap_or_else(|e| panic!("not placed: {e:?}")); + assert_eq!(placed.bias, 0x340); + assert_eq!(placed.gpu, placed.buffer.GetGPUVirtualAddress() + 0x340); + assert_eq!(placed.buffer.GetDesc().Width, 3 * K64 as u64, "the section's pages that hold the bytes"); + let other = place_in_section(&device, section, (2 * K64) as u64, K64 as u64).unwrap_or_else(|e| panic!("not placed: {e:?}")); + assert_eq!(other.heap.as_raw(), placed.heap.as_raw(), "one heap for the section"); + drop(other); + let mut rig = Rig::new(&device).unwrap(); + let got = rig.fetch(&placed.buffer, placed.bias, len).unwrap(); + assert!(same(at as *const u8, &got), "the card reads the bytes the title sees"); + rig.store(&placed.buffer, placed.bias + 8, &[0x5a; 32]).unwrap(); + assert!(same((at + 8) as *const u8, &[0x5a; 32]), "the card's write is at the title's address"); + assert!(matches!(place_in_section(&device, section, (7 * K64) as u64, 2 * K64 as u64), Err(None)), "past the end"); + // (Numbers no handle of the process has.) + let (reserved, unknown) = (usize::MAX - 0x71, usize::MAX - 0x73); + title_memory_section(reserved, SIZE as u64, false); + assert!(matches!(place_in_section(&device, reserved, 0, K64 as u64), Err(None)), "a reserved section"); + assert!(matches!(place_in_section(&device, unknown, 0, K64 as u64), Err(None)), "a section never made"); + title_memory_section_gone(reserved); + // The title unmaps the view and the runtime lets go of the section. + let seen = std::slice::from_raw_parts(at as *const u8, len).to_vec(); + views_gone(view, 4 * K64); + mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut c_void }); + title_memory_section_gone(section); + windows_sys::Win32::Foundation::CloseHandle(handle); + assert!(!SECTION_HEAPS.lock().unwrap().keys().any(|key| key.1 == section), "the section's heap is forgotten with it"); + let again = rig.fetch(&placed.buffer, placed.bias, len).unwrap(); + assert!(again == seen, "the heap is the section: its bytes outlive the view and the handle"); + } + } } diff --git a/d3d12/crates/leonida-gpu/src/inplace/tiled.rs b/d3d12/crates/leonida-gpu/src/inplace/tiled.rs new file mode 100644 index 0000000000..3dec2bac35 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/inplace/tiled.rs @@ -0,0 +1,1410 @@ +//! Title memory made of scattered 64 KiB pages of the page pool, read and +//! written by the card where it is: a reserved (tiled) buffer whose 64 KiB +//! tiles are mapped (`UpdateTileMappings`) onto a heap opened on the pool's +//! section ([`super::From::Section`]), the buffer's tiles in the order of the +//! title's addresses and the heap's in that of the physical pages: the +//! console's own page table, kept by the card's. `xmem` maps the title's +//! physical pages one 64 KiB view at a time (a census under Wine: 102,971 +//! views of 12,856 MB, nearly all one page, in three committed sections), so +//! a window of title memory is seldom one run of a section, which is all one +//! placed buffer shows ([`super::in_section`]): with `LEONIDA_INPLACE=1 +//! LEONIDA_SECTION_COMMIT=1` the title had 32 MB placed that way and 1,838 +//! asks turned down as view memory not one run of a committed section. +//! +//! What the RX 7900 XT answers (tiled resources tier 4; the software +//! adapter the same): no. The first `UpdateTileMappings` onto the section's +//! heap removes the device (`DXGI_ERROR_INVALID_CALL`), and so onto private +//! memory opened in part, and onto a heap of ours made shared and +//! cross-adapter, while one made shared alone takes the tile: Direct3D takes +//! no tiles in a cross-adapter heap, and every heap opened on memory the +//! process has is one. The same steps on a heap of ours all hold: tiles in a +//! scattered order, two on one page, read the CPU's writes with no call in +//! between, a shader's unordered-access writes reach the pages, a remap and +//! an unmap work, and the card reads through them as fast as through one +//! placed buffer. `UpdateTileMappings` of 1, 64 and 1024 tiles a range each: +//! 19, 23 and 2,021 us of CPU, 0.2, 1.1 and 20 ms until a fence after it. +//! +//! Nothing here maps tiles for the title. This file holds: +//! +//! - [`probe`]: whether the card takes such tiles and what they cost +//! (`LEONIDA_INPLACE_PROBE` with `LEONIDA_INPLACE_PROBE_TILES=1`, after +//! [`super::probe`]). The software adapter and the RX 7900 XT answer a +//! tile mapping into an opened heap by removing the device (the notes at +//! the top of `inplace.rs`), so the probe runs on a device of its own, +//! made by the device factory and not kept as the process's one device +//! for the adapter: a refusal removes that one, and on both the device +//! made as the host makes the title's stands after such removals and +//! still copies (the tests). Other cards and drivers are not shown, +//! hence asked for, not on. In a process where the factory makes none, +//! the probe is left out. +//! - In diagnostics builds, a census of the asks turned down as view memory +//! not one run of a committed section ([`turned_down`]): how many could be +//! tiles of committed sections, the pages and sections they span, and how +//! often the title maps or unmaps pages under those still alive +//! ([`views_changed`]: a tiled window would pay an `UpdateTileMappings` +//! for each). One line every ten seconds beside the in-place line +//! ([`line`]). + +#[cfg(any(test, feature = "diagnostics"))] +use std::collections::{BTreeMap, BTreeSet}; + +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, ID3DBlob}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter, IDXGIAdapter1, IDXGIFactory4}; +use windows::Win32::System::Threading::WaitForSingleObject; +use windows::core::{Interface, s}; +use windows_sys::Win32::System::Memory as mem; + +use super::{From, K64, Rig, buffer_desc, describe, fill, hr, open, place}; + +/// The tiles of the probe's scattered buffer: fifteen pages of the heap in +/// an order of their own, and a sixteenth tile on the first one's page. +const TILES: u32 = 16; + +/// `LEONIDA_INPLACE_PROBE_TILES`: off (unset); `=1` runs [`probe`] with the +/// in-place probe (`LEONIDA_INPLACE_PROBE`). Asked for, not on by default: +/// it removes devices on the title's adapter on purpose, and that the +/// title's own stands after it is shown on the RX 7900 XT only (beside a +/// device made as the host makes the title's, +/// `card_tiles_over_a_committed_section`), not on other cards or drivers, +/// nor yet in the title's process. +pub(crate) fn asked() -> bool { + crate::asked!("LEONIDA_INPLACE_PROBE_TILES") +} + +/// What the probe found. The lines are the whole account; the flags are +/// what a tiled window would build on. +#[derive(Default)] +pub(crate) struct Tiles { + pub(crate) lines: Vec<String>, + /// The device's tiled resources tier (0: none; 2 or more reads an + /// unmapped tile as zero). + pub(crate) tier: i32, + /// On a device of its own: not the process's device for the adapter. + pub(crate) own_device: bool, + /// A reserved buffer's tiles mapped in a scattered order onto a heap + /// made by `CreateHeap` show its pages in that order: the probe's own + /// steps hold on this card. + pub(crate) ours_map: bool, + /// The committed section opened as a heap is taken as tiles' memory: the + /// mapping left the device standing and the tiles show its pages. + pub(crate) section_maps: bool, + /// Through those tiles the card reads what the CPU wrote through the + /// section's view, also afterwards with no call in between. + pub(crate) reads: bool, + /// The same through a shader's root view. + pub(crate) shader_reads: bool, + /// A shader's unordered-access writes through the tiles show in the + /// CPU's view after the fence, those of two tiles on one page alike. + pub(crate) writes: bool, + /// A tile mapped to another page later shows that page. + pub(crate) remaps: bool, + /// A tile unmapped reads zero and a write there reaches no page. + pub(crate) unmaps: bool, + /// The step the device was lost at, with its reason. + pub(crate) lost: Option<String>, + /// After such a loss ([`why`]): a heap of ours made shared and + /// cross-adapter loses the device the same way while one made shared + /// alone takes the tile, so what the host refuses is tiles in a + /// cross-adapter heap, which every heap opened on memory the process has + /// is (`OpenExistingHeapFromAddress*`, `OpenExistingHeapFromFileMapping`). + pub(crate) cross_adapter_refused: bool, + /// `UpdateTileMappings` of 1, 64 and 1024 scattered tiles (a range of + /// one tile each), on the section's heap if it took tiles, else on ours: + /// tiles, microseconds of CPU in the call, microseconds until a fence + /// signalled after it, the best of three. + pub(crate) costs: Vec<(u32, f64, f64)>, +} + +/// The probe on the adapter of `device` (the host's), on a device of its +/// own; `mb` is the section's size (16 pages a MB; 2 to 64 MB). +pub(crate) fn probe_beside(device: &ID3D12Device, mb: usize) -> Tiles { + // SAFETY: plain DXGI queries. + let adapter = unsafe { + CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0)).and_then(|f| f.EnumAdapterByLuid::<IDXGIAdapter>(device.GetAdapterLuid())) + }; + match adapter { + Ok(adapter) => probe(&adapter, Some(device), false, false, mb), + Err(e) => { + let mut t = Tiles::default(); + t.lines.push(format!("the host's adapter: {}", hr(&Err::<(), _>(e)))); + verdict(&mut t); + t + } + } +} + +/// Tiles of a reserved buffer over a committed section of `mb` MB opened as +/// a heap, on `adapter`, on a device of the probe's own ([`own_device`]): +/// first the same steps on a heap of ours (`CreateHeap`), which says the +/// steps themselves hold; what reading through placed and upload buffers +/// costs; then the section's tiles, whose mapping may remove the device +/// (the rest is left out then). `not` is a device the probe must not run on +/// (the host's); with `shared`, the process's device for the adapter is +/// taken if the factory makes none (a test's process). With `debug`, the +/// factory's debug layer, where installed: what it says is in the lines. +pub(crate) fn probe(adapter: &IDXGIAdapter, not: Option<&ID3D12Device>, shared: bool, debug: bool, mb: usize) -> Tiles { + let mut t = Tiles::default(); + // SAFETY: device creation on a live adapter. + let made = unsafe { own_device(adapter, shared, debug) }; + let (device, own, layered) = match made { + Ok(made) => made, + Err(e) => { + t.lines.push(e); + verdict(&mut t); + return t; + } + }; + t.own_device = own && not.is_none_or(|not| not.as_raw() != device.as_raw()); + if not.is_some_and(|not| not.as_raw() == device.as_raw()) { + t.lines.push("the device made is the host's own: not run (a refused tile mapping would remove it)".to_owned()); + verdict(&mut t); + return t; + } + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + // SAFETY: a plain query that fills our structure. + let _ = unsafe { device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, (&raw mut options).cast(), size_of_val(&options) as u32) }; + t.tier = options.TiledResourcesTier.0; + // SAFETY: plain queries. + let name = unsafe { adapter.cast::<IDXGIAdapter1>().and_then(|a| a.GetDesc1()) } + .map(|d| String::from_utf16_lossy(&d.Description).trim_end_matches('\0').to_owned()) + .unwrap_or_default(); + t.lines.push(format!( + "the device: {name}, {}; tiled resources tier {}, heap tier {}; debug layer {}", + if t.own_device { "a device of the probe's own (ID3D12DeviceFactory)" } else { "the process's device for the adapter" }, + t.tier, + options.ResourceHeapTier.0, + if layered { "on" } else { "off" } + )); + if t.tier < 1 { + t.lines.push("no tiled resources: nothing to try".to_owned()); + verdict(&mut t); + return t; + } + let mut rig = match Rig::new(&device) { + Ok(rig) => rig, + Err(e) => { + t.lines.push(format!("no queue of its own: {e}")); + verdict(&mut t); + return t; + } + }; + let said = layered.then(|| device.cast::<ID3D12InfoQueue>().ok()).flatten(); + let pages = (mb.clamp(2, 64) << 20) / K64; + // SAFETY: memory and objects of the probe's own, made and released here; + // every address used lies inside the section's view. + unsafe { run(&mut t, &mut rig, said.as_ref(), pages) }; + drop(rig); + if t.lost.is_some() && t.own_device { + why(&mut t, adapter); + } + verdict(&mut t); + t +} + +/// A device on `adapter` and whether it is the probe's own (made by +/// `ID3D12DeviceFactory` with `DISALLOW_STORING_NEW_DEVICE_AS_SINGLETON`: +/// another `D3D12CreateDevice` on the adapter still gets the process's), and +/// whether its debug layer is on; with `shared`, the process's device if the +/// factory makes none. +unsafe fn own_device(adapter: &IDXGIAdapter, shared: bool, debug: bool) -> Result<(ID3D12Device, bool, bool), String> { + // SAFETY (the whole function): plain creation and configuration calls. + unsafe { + let mut factory: Option<ID3D12DeviceFactory> = None; + let asked = D3D12GetInterface(&CLSID_D3D12DeviceFactory, &mut factory); + let why = match (asked, factory) { + (Ok(()), Some(factory)) => { + let flagged = factory.SetFlags(D3D12_DEVICE_FACTORY_FLAG_DISALLOW_STORING_NEW_DEVICE_AS_SINGLETON); + let layered = debug && factory.GetConfigurationInterface::<ID3D12Debug>(&CLSID_D3D12Debug).map(|layer| layer.EnableDebugLayer()).is_ok(); + let mut device: Option<ID3D12Device> = None; + match flagged.and_then(|()| factory.CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, &mut device)) { + Ok(()) => match device { + Some(device) => return Ok((device, true, layered)), + None => "the device factory made no device".to_owned(), + }, + Err(e) => format!("the device factory's device: {}", hr(&Err::<(), _>(e))), + } + } + (asked, _) => format!("no device factory (D3D12GetInterface): {}", hr(&asked)), + }; + if !shared { + return Err(format!("{why}: no device of the probe's own, not run (a refused tile mapping removes the device)")); + } + let mut device: Option<ID3D12Device> = None; + D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(|e| format!("{why}; D3D12CreateDevice: {}", hr(&Err::<(), _>(e))))?; + device.map(|device| (device, false, false)).ok_or_else(|| format!("{why}; D3D12CreateDevice made none")) + } +} + +/// Whether the device stands after `step`, after a fence signalled on the +/// rig's queue behind what is there (tile mappings among it); what the +/// debug layer said meanwhile (its errors and warnings) goes to the lines. +/// A lost device is noted in [`Tiles::lost`]. +fn standing(t: &mut Tiles, rig: &mut Rig, said: Option<&ID3D12InfoQueue>, step: &str) -> bool { + let settled = settle(rig); + if let Some(queue) = said { + // SAFETY: each message is read into a buffer of the size the queue + // reports, then the queue is emptied. + unsafe { + for i in 0..queue.GetNumStoredMessages() { + let mut size = 0; + if queue.GetMessage(i, None, &mut size).is_err() || size == 0 { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>(); + if queue.GetMessage(i, Some(message), &mut size).is_ok() && (*message).Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0 { + let m = &*message; + let text = String::from_utf8_lossy(std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength)); + t.lines.push(format!(" the debug layer, at {step} (severity {}, id {}): {}", m.Severity.0, m.ID.0, text.trim_end_matches('\0'))); + } + } + queue.ClearStoredMessages(); + } + } + match settled { + Ok(()) => true, + Err(e) => { + let lost = format!("{step}: {}", short(&e)); + t.lines.push(format!(" THE DEVICE IS LOST after {lost}")); + t.lost.get_or_insert(lost); + false + } + } +} + +/// An error's code and the first line of its text (the host's text is in +/// the PC's language and runs over several lines). +fn short(e: &windows::core::Error) -> String { + format!("{:#010x} ({})", e.code().0, e.message().lines().next().unwrap_or_default().trim()) +} + +/// A fence signalled on the rig's queue behind what is there, waited for +/// (ten seconds at most); the device's removal reason then. +fn settle(rig: &mut Rig) -> windows::core::Result<()> { + rig.done += 1; + // SAFETY: our queue, fence and event. + unsafe { + rig.queue.Signal(&rig.fence, rig.done)?; + rig.fence.SetEventOnCompletion(rig.done, rig.event)?; + if WaitForSingleObject(rig.event, 10_000).0 != 0 { + return Err(windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)); + } + rig.device.GetDeviceRemovedReason() + } +} + +/// Tiles `first..` of `buffer` mapped on the rig's queue, a range of one +/// tile each: onto page `p` of `heap` for `Some(p)`, to nothing for `None`. +/// The microseconds the call took on the CPU. +fn map(rig: &Rig, buffer: &ID3D12Resource, heap: &ID3D12Heap, first: u32, pages: &[Option<u32>]) -> f64 { + let at = D3D12_TILED_RESOURCE_COORDINATE { X: first, Y: 0, Z: 0, Subresource: 0 }; + let size = D3D12_TILE_REGION_SIZE { NumTiles: pages.len() as u32, ..Default::default() }; + let flags: Vec<D3D12_TILE_RANGE_FLAGS> = pages.iter().map(|p| if p.is_some() { D3D12_TILE_RANGE_FLAG_NONE } else { D3D12_TILE_RANGE_FLAG_NULL }).collect(); + let starts: Vec<u32> = pages.iter().map(|p| p.unwrap_or(0)).collect(); + let counts = vec![1u32; pages.len()]; + let began = std::time::Instant::now(); + // SAFETY: a live reserved buffer and a live heap; one region of + // `pages.len()` tiles, as many ranges of one tile, in arrays of that + // length that live through the call. What the host refuses it answers + // by removing the device ([`standing`] looks). + unsafe { + rig.queue.UpdateTileMappings( + buffer, + 1, + Some(&raw const at), + Some(&raw const size), + heap, + pages.len() as u32, + Some(flags.as_ptr()), + Some(starts.as_ptr()), + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + } + began.elapsed().as_secs_f64() * 1e6 +} + +/// `count` tiles from the first mapped onto pages `0..count` of `heap` as +/// one range: what a run of pages costs, against [`map`]'s range a tile. +fn map_run(rig: &Rig, buffer: &ID3D12Resource, heap: &ID3D12Heap, count: u32) -> f64 { + let at = D3D12_TILED_RESOURCE_COORDINATE::default(); + let size = D3D12_TILE_REGION_SIZE { NumTiles: count, ..Default::default() }; + let (flags, start) = (D3D12_TILE_RANGE_FLAG_NONE, 0u32); + let began = std::time::Instant::now(); + // SAFETY: as in [`map`], with one range of `count` tiles. + unsafe { + rig.queue.UpdateTileMappings( + buffer, + 1, + Some(&raw const at), + Some(&raw const size), + heap, + 1, + Some(&raw const flags), + Some(&raw const start), + Some(&raw const count), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + } + began.elapsed().as_secs_f64() * 1e6 +} + +/// A stride that visits every page of `pages` once (`i * stride % pages`). +fn stride(pages: usize) -> usize { + [37, 41, 43].into_iter().find(|s| !pages.is_multiple_of(*s)).unwrap_or(1) +} + +/// The page of each of the [`TILES`] tiles: fifteen pages spread over the +/// heap, last first; the sixteenth tile on the first tile's page. +fn layout(pages: usize) -> Vec<u32> { + let step = stride(pages); + let mut tiles: Vec<u32> = (0..TILES as usize - 1).rev().map(|k| ((k * step + 3) % pages) as u32).collect(); + tiles.push(tiles[0]); + tiles +} + +/// The word at `offset` of page `page` of `cpu`. +/// +/// # Safety +/// `cpu` is mapped for the page. +unsafe fn word(cpu: *const u8, page: u32, offset: usize) -> u32 { + // SAFETY: the caller's mapping. + unsafe { cpu.add(page as usize * K64 + offset).cast::<u32>().read_unaligned() } +} + +/// What a root parameter of [`dispatch`] gets. +enum Root { + Constant(u32), + Srv(u64), + Uav(u64), +} + +/// A compute program of `source` (root signature in it, `RS`), `groups` +/// groups, its root parameters set in order. +fn dispatch(rig: &mut Rig, source: &str, roots: &[Root], groups: u32) -> windows::core::Result<()> { + let mut code: Option<ID3DBlob> = None; + // SAFETY: the source and names live through the call; then the blob's + // own bytes, which hold the root signature too. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + D3DCompile(source.as_ptr().cast(), source.len(), s!("tiles"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?; + let code = code.ok_or_else(windows::core::Error::empty)?; + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()); + let root: ID3D12RootSignature = rig.device.CreateRootSignature(0, bytes)?; + let pso = rig.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, + ..Default::default() + })?; + (root, pso) + }; + // SAFETY: an open list of ours; the views name live buffers. + rig.run(|list| unsafe { + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + for (i, root) in roots.iter().enumerate() { + match *root { + Root::Constant(value) => list.SetComputeRoot32BitConstant(i as u32, value, 0), + Root::Srv(gpu) => list.SetComputeRootShaderResourceView(i as u32, gpu), + Root::Uav(gpu) => list.SetComputeRootUnorderedAccessView(i as u32, gpu), + } + } + list.Dispatch(groups, 1, 1); + }) +} + +/// Each group reads the word at `t * 1024` of its tile through a root +/// shader resource view and stores it at `(group * 64 + t) * 4`. +const READ: &str = "#define RS \"SRV(t0), UAV(u0)\"\nByteAddressBuffer i : register(t0);\nRWByteAddressBuffer o : register(u0);\n[RootSignature(RS)]\n[numthreads(64, 1, 1)]\nvoid main(uint3 g : SV_GroupID, uint t : SV_GroupIndex) { o.Store((g.x * 64 + t) * 4, i.Load(g.x * 65536 + t * 1024)); }\n"; + +/// Each group but the first stores `salt + group * 256 + t` at +/// `t * 1024 + 4` of its tile, through a root unordered-access view. +const WRITE: &str = "#define RS \"RootConstants(num32BitConstants=1, b0), UAV(u0)\"\ncbuffer c : register(b0) { uint salt; };\nRWByteAddressBuffer o : register(u0);\n[RootSignature(RS)]\n[numthreads(64, 1, 1)]\nvoid main(uint3 g : SV_GroupID, uint t : SV_GroupIndex) { if (g.x != 0) o.Store(g.x * 65536 + t * 1024 + 4, salt + g.x * 256 + t); }\n"; + +/// What [`check`] found for one heap. +#[derive(Default)] +struct Found { + maps: bool, + reads: bool, + shader_reads: bool, + writes: bool, + remaps: bool, + unmaps: bool, +} + +/// A buffer the card can write, in its own memory. +fn card_buffer(rig: &Rig, size: u64) -> windows::core::Result<ID3D12Resource> { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain creation. + unsafe { + rig.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &buffer_desc(size, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + )? + }; + buffer.ok_or_else(windows::core::Error::empty) +} + +/// A reserved buffer of `tiles` tiles, `flags` beside unordered access. +fn reserved(rig: &Rig, tiles: u32, flags: D3D12_RESOURCE_FLAGS) -> windows::core::Result<ID3D12Resource> { + let mut buffer: Option<ID3D12Resource> = None; + let desc = buffer_desc(tiles as u64 * K64 as u64, flags | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + // SAFETY: plain creation. + unsafe { rig.device.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer)? }; + buffer.ok_or_else(windows::core::Error::empty) +} + +/// The steps on `on` (a heap, the CPU's address of it, its pages), with +/// `buffer` a reserved buffer of [`TILES`] tiles: its tiles mapped in the +/// order of [`layout`], the card's reads of the CPU's writes, a shader's +/// reads and writes, a remap and an unmap; a line of what each did. +/// `None` once the device is lost. +/// +/// # Safety +/// `cpu` is mapped for the heap's `pages` pages, and is the same memory. +unsafe fn check(t: &mut Tiles, rig: &mut Rig, said: Option<&ID3D12InfoQueue>, on: (&ID3D12Heap, *mut u8, usize), buffer: &ID3D12Resource, what: &str) -> Option<Found> { + let (heap, cpu, pages) = on; + let mut found = Found::default(); + let tiles = layout(pages); + let size = TILES as usize * K64; + let fill_pages = |seed: u8| { + for &page in &tiles { + // SAFETY: a page of the caller's mapping. + fill(unsafe { cpu.add(page as usize * K64) }, K64, seed ^ page as u8); + } + }; + // What tile `k` of `got` should show: its page, as the CPU reads it. + // SAFETY: pages of the caller's mapping. + let shows = |got: &[u8], k: usize| unsafe { std::slice::from_raw_parts(cpu.add(tiles[k] as usize * K64), K64) } == &got[k * K64..(k + 1) * K64]; + fill_pages(1); + let pages_of: Vec<Option<u32>> = tiles.iter().map(|&p| Some(p)).collect(); + let took = map(rig, buffer, heap, 0, &pages_of); + if !standing(t, rig, said, &format!("the scattered mapping on {what}")) { + return None; + } + let first = rig.fetch(buffer, 0, size).is_ok_and(|got| (0..TILES as usize).all(|k| shows(&got, k))); + found.maps = first; + fill_pages(2); + let second = rig.fetch(buffer, 0, size).is_ok_and(|got| (0..TILES as usize).all(|k| shows(&got, k))); + found.reads = first && second; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let out = card_buffer(rig, (TILES * 64 * 4) as u64); + let shaded = out.as_ref().map_err(Clone::clone).and_then(|out| { + // SAFETY: a live buffer. + dispatch(rig, READ, &[Root::Srv(gpu), Root::Uav(unsafe { out.GetGPUVirtualAddress() })], TILES)?; + rig.fetch(out, 0, (TILES * 64 * 4) as usize) + }); + found.shader_reads = shaded.as_ref().is_ok_and(|got| { + (0..TILES as usize * 64).all(|i| { + let (k, at) = (i / 64, (i % 64) * 1024); + // SAFETY: a page of the caller's mapping. + u32::from_le_bytes(got[i * 4..i * 4 + 4].try_into().unwrap_or_default()) == unsafe { word(cpu, tiles[k], at) } + }) + }); + if !standing(t, rig, said, &format!("a shader's reads on {what}")) { + return None; + } + // Groups 1..16 write; group 15's tile shows the first tile's page. + let wrote = |salt: u32, k: usize, page: u32| (0..64).all(|i| unsafe { word(cpu, page, i * 1024 + 4) } == salt + k as u32 * 256 + i as u32); + let salt = 0xc0de_0000; + let written = dispatch(rig, WRITE, &[Root::Constant(salt), Root::Uav(gpu)], TILES); + found.writes = written.is_ok() && (1..TILES as usize).all(|k| wrote(salt, k, tiles[k])); + let twice = written.is_ok() && wrote(salt, TILES as usize - 1, tiles[0]); + if !standing(t, rig, said, &format!("a shader's writes on {what}")) { + return None; + } + // Tile 1 onto a page no tile shows. + let spare = (0..pages as u32).find(|p| !tiles.contains(p)).unwrap_or(0); + // SAFETY: a page of the caller's mapping. + fill(unsafe { cpu.add(spare as usize * K64) }, K64, 0x99); + map(rig, buffer, heap, 1, &[Some(spare)]); + let remapped = standing(t, rig, said, &format!("a remap on {what}")); + // SAFETY: a page of the caller's mapping. + let spare_bytes = unsafe { std::slice::from_raw_parts(cpu.add(spare as usize * K64), K64) }; + found.remaps = remapped && rig.fetch(buffer, K64 as u64, K64).is_ok_and(|got| got == spare_bytes); + if !remapped { + return None; + } + // Tile 2 to nothing: it reads zero (tier 2 and up), a write there is lost. + map(rig, buffer, heap, 2, &[None]); + let unmapped = standing(t, rig, said, &format!("an unmap on {what}")); + if !unmapped { + return None; + } + let zeros = rig.fetch(buffer, 2 * K64 as u64, K64).is_ok_and(|got| got.iter().all(|&b| b == 0)); + let again = 0xd00d_0000; + let lost_write = dispatch(rig, WRITE, &[Root::Constant(again), Root::Uav(gpu)], TILES).is_ok() && wrote(salt, 2, tiles[2]); + found.unmaps = zeros && lost_write; + if !standing(t, rig, said, &format!("a write to an unmapped tile on {what}")) { + return None; + } + t.lines.push(format!( + " on {what}: {TILES} tiles mapped in a scattered order over {} pages (the last on the first's page), in {took:.0} us of CPU: \ + the card reads each tile's page {first}; and what the CPU wrote after, with no call in between {second}; a shader through a root \ + view reads them {} ({}); its unordered-access writes show at the pages' CPU address after the fence {} ({}), the two tiles on one page alike {twice}; \ + tile 1 mapped to another page later shows it {}; tile 2 unmapped reads zero {zeros}, and a write there reaches no page {lost_write}", + TILES - 1, + found.shader_reads, + hr(&shaded), + found.writes, + hr(&written), + found.remaps + )); + Some(found) +} + +/// [`Tiles::costs`] on `heap` of `pages` pages: a reserved buffer of 1024 +/// tiles, mapped 1, 64 and 1024 tiles at a time, a range of one tile each +/// (the title's scattered pages) and as one run; three times each, the +/// best. `None` once the device is lost. +fn costs(t: &mut Tiles, rig: &mut Rig, said: Option<&ID3D12InfoQueue>, heap: &ID3D12Heap, pages: usize, flags: D3D12_RESOURCE_FLAGS, what: &str) -> Option<Vec<(u32, f64, f64)>> { + let buffer = match reserved(rig, 1024, flags) { + Ok(buffer) => buffer, + Err(e) => { + t.lines.push(format!(" on {what}, a reserved buffer of 1024 tiles: {}", hr(&Err::<(), _>(e)))); + return Some(Vec::new()); + } + }; + let step = stride(pages); + let mut out = Vec::new(); + let mut said_line = Vec::new(); + for count in [1u32, 64, 1024] { + let pages_of: Vec<Option<u32>> = (0..count as usize).map(|k| Some(((k * step + 3) % pages) as u32)).collect(); + let (mut cpu, mut fenced, mut run_cpu, mut run_fenced) = (f64::MAX, f64::MAX, f64::MAX, f64::MAX); + for _ in 0..3 { + let began = std::time::Instant::now(); + cpu = cpu.min(map(rig, &buffer, heap, 0, &pages_of)); + if !standing(t, rig, said, &format!("{count} tiles mapped on {what}")) { + return None; + } + fenced = fenced.min(began.elapsed().as_secs_f64() * 1e6); + if count as usize <= pages { + let began = std::time::Instant::now(); + run_cpu = run_cpu.min(map_run(rig, &buffer, heap, count)); + if !standing(t, rig, said, &format!("a run of {count} tiles mapped on {what}")) { + return None; + } + run_fenced = run_fenced.min(began.elapsed().as_secs_f64() * 1e6); + } + } + out.push((count, cpu, fenced)); + let run = if run_cpu < f64::MAX { format!("; as one run of pages {run_cpu:.0} and {run_fenced:.0} us") } else { String::new() }; + said_line.push(format!( + "{count} tiles a range each {cpu:.0} us of CPU ({:.2} a tile), {fenced:.0} us to the fence{run}", + cpu / count as f64 + )); + } + t.lines.push(format!(" on {what}, UpdateTileMappings (best of 3): {}", said_line.join("; "))); + Some(out) +} + +/// The steps on a heap of ours, on the section's heap, and the costs. +/// +/// # Safety +/// The probe's own memory: made, used and released here. +unsafe fn run(t: &mut Tiles, rig: &mut Rig, said: Option<&ID3D12InfoQueue>, pages: usize) { + let bytes = pages * K64; + // SAFETY (the whole function): the heap, section and view made below; + // every address used lies inside the view of `bytes` bytes. + unsafe { + // A heap of ours, as `CreateHeap` makes it: the PC's memory, write-back, + // as the opened section's heap is; a placed buffer over all of it, + // mapped, is the CPU's side. + let properties = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let desc = D3D12_HEAP_DESC { SizeInBytes: bytes as u64, Properties: properties, Alignment: K64 as u64, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }; + let mut ours: Option<ID3D12Heap> = None; + let made = rig.device.CreateHeap(&desc, &mut ours); + t.lines.push(format!("a heap of ours of {} MB (CreateHeap, the PC's memory, write-back): {}", bytes >> 20, hr(&made))); + if let Some(heap) = &ours { + let mut side: Option<ID3D12Resource> = None; + let placed = rig.device.CreatePlacedResource(heap, 0, &buffer_desc(bytes as u64, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, None, &mut side); + let mut data = std::ptr::null_mut(); + let mapped = placed.and_then(|()| side.as_ref().ok_or_else(windows::core::Error::empty)?.Map(0, None, Some(&mut data))); + let buffer = reserved(rig, TILES, D3D12_RESOURCE_FLAG_NONE); + t.lines.push(format!(" a buffer placed over it, mapped for the CPU: {}; a reserved buffer of {TILES} tiles: {}", hr(&mapped), hr(&buffer))); + if let (Ok(()), Ok(buffer)) = (&mapped, &buffer) { + let Some(found) = check(t, rig, said, (heap, data.cast(), pages), buffer, "the heap of ours") else { + return; + }; + t.ours_map = found.maps && found.reads && found.shader_reads && found.writes && found.remaps; + } + if let Some(side) = &side { + side.Unmap(0, None); + } + match costs(t, rig, said, heap, pages, D3D12_RESOURCE_FLAG_NONE, "the heap of ours") { + Some(costs) => t.costs = costs, + None => return, + } + // What tiles cost the card's reads, against one placed buffer. + let tiled = read_through_tiles(rig, heap, pages, D3D12_RESOURCE_FLAG_NONE); + let placed = side.as_ref().and_then(|side| rig.copy_ms(side, bytes as u64).ok()); + if !standing(t, rig, said, "the copies out of the heap of ours") { + return; + } + t.lines.push(format!( + " the card copies the {} MB of the heap of ours out into its own memory (best of 3): through tiles over all its pages in a scattered order {}; \ + through a buffer placed over it {}", + bytes >> 20, + speed(bytes as u64, tiled), + speed(bytes as u64, placed) + )); + } + drop(ours); + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, (bytes as u64 >> 32) as u32, bytes as u32, std::ptr::null()); + if handle.is_null() { + t.lines.push("a committed section: none to try with".to_owned()); + return; + } + let view = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, 0, bytes); + if view.Value.is_null() { + t.lines.push("a committed section: no view of it".to_owned()); + windows_sys::Win32::Foundation::CloseHandle(handle); + return; + } + section(t, rig, said, handle as usize, view.Value.cast(), pages); + mem::UnmapViewOfFile(view); + windows_sys::Win32::Foundation::CloseHandle(handle); + } +} + +/// The committed section `handle` of `pages` pages, seen by the CPU at +/// `cpu`, opened as a heap: what reading it through a placed buffer and an +/// upload buffer costs, then its tiles. +/// +/// # Safety +/// `cpu` is a view of the whole section. +unsafe fn section(t: &mut Tiles, rig: &mut Rig, said: Option<&ID3D12InfoQueue>, handle: usize, cpu: *mut u8, pages: usize) { + let bytes = (pages * K64) as u64; + let opened = open(&rig.device, From::Section(handle)); + t.lines.push(format!("a section of {} MB made committed, as the page pool with LEONIDA_SECTION_COMMIT=1, opened as a heap: {}", bytes >> 20, hr(&opened))); + let Ok(heap) = opened else { + return; + }; + t.lines.push(format!(" {}", describe(&heap))); + // The card's reads through the kinds of buffer a window could be. + let speed = |ms: Option<f64>| speed(bytes, ms); + let placed = place(&rig.device, &heap, 0, bytes); + let through_placed = placed.as_ref().ok().and_then(|b| rig.copy_ms(b, bytes).ok()); + let upload = rig.committed(D3D12_HEAP_TYPE_UPLOAD, bytes, D3D12_RESOURCE_STATE_GENERIC_READ); + let through_upload = upload.as_ref().ok().and_then(|b| rig.copy_ms(b, bytes).ok()); + drop((placed, upload)); + if !standing(t, rig, said, "the copies out of a placed and an upload buffer") { + return; + } + t.lines.push(format!( + " the card copies the {} MB out into its own memory (best of 3): through a buffer placed in the section's heap {}; out of an upload buffer {}", + bytes >> 20, + speed(through_placed), + speed(through_upload) + )); + // A reserved buffer as the placed ones in such a heap are made + // (cross-adapter), else without it. + let (buffer, flags) = match reserved(rig, TILES, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER) { + Ok(buffer) => { + t.lines.push(format!(" a reserved buffer of {TILES} tiles, cross-adapter as a placed buffer in this heap must be: ok")); + (buffer, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER) + } + Err(e) => { + let plain = reserved(rig, TILES, D3D12_RESOURCE_FLAG_NONE); + t.lines.push(format!(" a reserved buffer of {TILES} tiles, cross-adapter: {}; without: {}", hr(&Err::<(), _>(e)), hr(&plain))); + match plain { + Ok(buffer) => (buffer, D3D12_RESOURCE_FLAG_NONE), + Err(_) => return, + } + } + }; + // SAFETY: the caller's view of the whole section. + let found = unsafe { check(t, rig, said, (&heap, cpu, pages), &buffer, "the section's heap") }; + let Some(found) = found else { + return; + }; + t.section_maps = found.maps; + t.reads = found.reads; + t.shader_reads = found.shader_reads; + t.writes = found.writes; + t.remaps = found.remaps; + t.unmaps = found.unmaps; + drop(buffer); + let Some(costs) = costs(t, rig, said, &heap, pages, flags, "the section's heap") else { + return; + }; + if !costs.is_empty() { + t.costs = costs; + } + let through_tiles = read_through_tiles(rig, &heap, pages, flags); + if !standing(t, rig, said, "the section's tiles, read whole") { + return; + } + t.lines.push(format!(" the card copies the {} MB out through tiles over all of the section's pages, in a scattered order: {}", bytes >> 20, speed(through_tiles))); +} + +/// Milliseconds and GB/s of a copy of `bytes`; `?` for none. +fn speed(bytes: u64, ms: Option<f64>) -> String { + ms.map_or("?".to_owned(), |ms| format!("{ms:.2} ms, {:.1} GB/s", bytes as f64 / ms / 1e6)) +} + +/// Milliseconds the card takes to copy all of `heap`'s `pages` pages into +/// its own memory through a reserved buffer whose tiles show each page once, +/// in a scattered order (the best of three). +fn read_through_tiles(rig: &mut Rig, heap: &ID3D12Heap, pages: usize, flags: D3D12_RESOURCE_FLAGS) -> Option<f64> { + let buffer = reserved(rig, pages as u32, flags).ok()?; + let step = stride(pages); + let order: Vec<Option<u32>> = (0..pages).map(|k| Some(((k * step + 3) % pages) as u32)).collect(); + map(rig, &buffer, heap, 0, &order); + settle(rig).ok()?; + rig.copy_ms(&buffer, (pages * K64) as u64).ok() +} + +/// What a single tile is mapped onto in [`why`]'s tries. +#[derive(Clone, Copy)] +enum Pool { + /// A committed section of the try's own, opened as a heap. + Section, + /// Private memory of the try's own, committed, a part of it opened. + Private, + /// A heap made by `CreateHeap` with these properties and flags. + Ours(D3D12_HEAP_TYPE, D3D12_HEAP_FLAGS), +} + +/// After the section's heap was refused: which part of it the host +/// refuses. Each try on a new device of the probe's own (the refusal +/// removes it): one tile of a reserved buffer mapped onto a heap that +/// differs from the section's in one thing, whether the device stands +/// after it and, where the CPU sees the heap, whether the tile shows what +/// the CPU wrote. +fn why(t: &mut Tiles, adapter: &IDXGIAdapter) { + let (custom, default) = (D3D12_HEAP_TYPE_CUSTOM, D3D12_HEAP_TYPE_DEFAULT); + let (shared, cross) = (D3D12_HEAP_FLAG_SHARED, D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER); + let (plain, crossing) = (D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER); + let tries: [(&str, Pool, D3D12_RESOURCE_FLAGS); 7] = [ + ("the section's heap, a reserved buffer without cross-adapter", Pool::Section, plain), + ("private memory, a part opened as a heap (OpenExistingHeapFromAddress1), a cross-adapter reserved buffer", Pool::Private, crossing), + ("a heap of ours made shared and cross-adapter (default), a cross-adapter reserved buffer", Pool::Ours(default, cross), crossing), + ("a heap of ours made shared and cross-adapter (custom, the PC's memory, write-back), a cross-adapter reserved buffer", Pool::Ours(custom, cross), crossing), + ("a heap of ours made shared, not cross-adapter (default)", Pool::Ours(default, shared), plain), + ("a heap of ours made shared, not cross-adapter (custom, the PC's memory, write-back)", Pool::Ours(custom, shared), plain), + ("a heap of ours, neither (custom, the PC's memory, write-back)", Pool::Ours(custom, D3D12_HEAP_FLAG_NONE), plain), + ]; + let mut stood = Vec::new(); + for (what, pool, flags) in tries { + let (line, stands) = try_one(adapter, pool, flags); + t.lines.push(format!(" which part is refused: {what}: {line}")); + stood.push(stands); + } + t.cross_adapter_refused = stood[2] == Some(false) && stood[4] == Some(true); +} + +/// [`why`]'s one try: its line, and whether the device stood after the +/// mapping (`None`: not made as far). +fn try_one(adapter: &IDXGIAdapter, pool: Pool, flags: D3D12_RESOURCE_FLAGS) -> (String, Option<bool>) { + const PAGES: usize = 16; + // SAFETY: device creation on a live adapter. + let device = match unsafe { own_device(adapter, false, false) } { + Ok((device, true, _)) => device, + Ok(_) => return ("no device of the probe's own: not tried".to_owned(), None), + Err(e) => return (e, None), + }; + let Ok(mut rig) = Rig::new(&device) else { + return ("no queue".to_owned(), None); + }; + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + // The memory, the CPU's address of it (null: none), and the heap. + // SAFETY: memory of the try's own, released below. + let (handle, cpu) = unsafe { + match pool { + Pool::Section => { + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, (PAGES * K64) as u32, std::ptr::null()); + let view = if handle.is_null() { std::ptr::null_mut() } else { mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, 0, PAGES * K64).Value }; + (handle, view.cast::<u8>()) + } + Pool::Private => (std::ptr::null_mut(), mem::VirtualAlloc(std::ptr::null(), PAGES * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE).cast::<u8>()), + Pool::Ours(..) => (std::ptr::null_mut(), std::ptr::null_mut()), + } + }; + let heap = match pool { + Pool::Section if !cpu.is_null() => open(&device, From::Section(handle as usize)), + Pool::Private if !cpu.is_null() => open(&device, From::Part(cpu as usize, PAGES * K64)), + Pool::Ours(kind, heap_flags) => { + let properties = if kind == D3D12_HEAP_TYPE_CUSTOM { + D3D12_HEAP_PROPERTIES { Type: kind, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() } + } else { + D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() } + }; + let desc = D3D12_HEAP_DESC { SizeInBytes: (PAGES * K64) as u64, Properties: properties, Alignment: K64 as u64, Flags: heap_flags }; + let mut heap: Option<ID3D12Heap> = None; + // SAFETY: plain creation. + unsafe { device.CreateHeap(&desc, &mut heap) }.and_then(|()| heap.ok_or_else(windows::core::Error::empty)) + } + _ => Err(windows::core::Error::empty()), + }; + let (line, stands) = match heap { + Err(e) => (format!("the heap {}", hr(&Err::<(), _>(e))), None), + Ok(heap) => match reserved(&rig, 1, flags) { + Err(e) => (format!("the heap ok; the reserved buffer {}", hr(&Err::<(), _>(e))), None), + Ok(buffer) => { + if !cpu.is_null() { + fill(cpu.wrapping_add(5 * K64), K64, 0x21); + } + map(&rig, &buffer, &heap, 0, &[Some(5)]); + match settle(&mut rig) { + Err(e) => (format!("the heap ok, the reserved buffer ok; one tile mapped: THE DEVICE IS LOST {}", short(&e)), Some(false)), + Ok(()) if cpu.is_null() => ("the heap ok, the reserved buffer ok; one tile mapped: the device stands".to_owned(), Some(true)), + Ok(()) => { + // SAFETY: the try's own memory, `PAGES` pages. + let page = unsafe { std::slice::from_raw_parts(cpu.add(5 * K64), K64) }; + let shows = rig.fetch(&buffer, 0, K64).is_ok_and(|got| got == page); + (format!("the heap ok, the reserved buffer ok; one tile mapped: the device stands, the tile shows the CPU's bytes {shows}"), Some(true)) + } + } + } + }, + }; + drop(rig); + drop(device); + // SAFETY: what was made above, nothing of it in use any more. + unsafe { + match pool { + Pool::Section => { + if !cpu.is_null() { + mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: cpu.cast() }); + } + if !handle.is_null() { + windows_sys::Win32::Foundation::CloseHandle(handle); + } + } + Pool::Private if !cpu.is_null() => { + mem::VirtualFree(cpu.cast(), 0, mem::MEM_RELEASE); + } + _ => {} + } + } + (line, stands) +} + +/// The probe's last line, as [`super::probe`]'s. +fn verdict(t: &mut Tiles) { + let costs: Vec<String> = t.costs.iter().map(|&(n, cpu, fenced)| format!("{n} tiles {cpu:.0}/{fenced:.0} us")).collect(); + t.lines.push(format!( + "VERDICT: tiles over title memory: tiled resources tier {}, on a device of its own {}; scattered tiles on a heap of ours {}; the page pool's \ + section opened as a heap taken as tiles' memory {}{}{}; through scattered tiles the card reads the CPU's writes {}, by a shader {}; its \ + unordered-access writes reach the CPU's view {}; a remap {}; an unmap {}; UpdateTileMappings, a range a tile, CPU/to the fence: {}", + t.tier, + t.own_device, + t.ours_map, + t.section_maps, + t.lost.as_ref().map_or(String::new(), |lost| format!(" (THE DEVICE WAS LOST after {lost})")), + if t.cross_adapter_refused { + "; the host refuses tiles in any cross-adapter heap (one of ours made so loses the device too, one made shared alone does not), and \ + every heap opened on memory the process has is one: no tiled window over title memory on this host" + } else { + "" + }, + t.reads, + t.shader_reads, + t.writes, + t.remaps, + t.unmaps, + if costs.is_empty() { "not measured".to_owned() } else { costs.join(", ") } + )); +} + +// The census (diagnostics builds): the asks turned down as view memory not +// one run of a committed section, and what tiles would make of them. + +/// What tiles could make of title memory that one placed buffer cannot +/// show, by the runtime's record of the title's views. +#[cfg(any(test, feature = "diagnostics"))] +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Tiling { + /// Every 64 KiB page in a view of a section made committed, the views + /// on 64 KiB lines in the address and in the section: how many pages, + /// and the distinct sections (each a heap to open and a range of + /// `UpdateTileMappings` calls of its own), in order. + Tiles { pages: usize, sections: Vec<usize> }, + /// Every page in a view, but some of a section made reserved (or not + /// known), which the host does not open. + Reserved, + /// Some page in no view. + Holes, + /// A view off the 64 KiB lines. + OffLines, +} + +/// [`Tiling`] of the 64 KiB pages that hold `[at, at + len)` by `views` (by +/// address: bytes, section, offset) and `sections` (by handle: bytes, +/// whether made committed). +#[cfg(any(test, feature = "diagnostics"))] +pub(crate) fn tiling_in(views: &BTreeMap<usize, (usize, usize, u64)>, sections: &BTreeMap<usize, (u64, bool)>, at: usize, len: usize) -> Tiling { + let mut page = at & !(K64 - 1); + let end = at.saturating_add(len.max(1)).saturating_add(K64 - 1) & !(K64 - 1); + let (mut pages, mut found, mut reserved) = (0, Vec::new(), false); + while page < end { + let Some((&base, &(bytes, section, offset))) = views.range(..=page).next_back().filter(|(base, view)| **base + view.0 > page) else { + return Tiling::Holes; + }; + if !base.is_multiple_of(K64) || !bytes.is_multiple_of(K64) || !offset.is_multiple_of(K64 as u64) { + return Tiling::OffLines; + } + reserved |= !sections.get(§ion).is_some_and(|s| s.1); + if !found.contains(§ion) { + found.push(section); + } + let stop = (base + bytes).min(end); + pages += (stop - page) / K64; + page = stop; + } + if reserved { + return Tiling::Reserved; + } + found.sort_unstable(); + Tiling::Tiles { pages, sections: found } +} + +/// The census's counts. +#[cfg(any(test, feature = "diagnostics"))] +#[derive(Default)] +pub(crate) struct Census { + /// Asks turned down and their bytes: tiles could hold them, in views of + /// a reserved section, with pages in no view, off the 64 KiB lines. + kinds: [(u64, u64); 4], + /// Of those tiles could hold: their pages, the distinct sections of all, + /// the most sections of one. + pages: u64, + sections: BTreeSet<usize>, + most: usize, + /// Those tiles could hold that are still alive as copies, by (address, + /// bytes); and the longest, to bound a look for those over a range. + alive: BTreeSet<(usize, usize)>, + longest: usize, + /// Since the last line: the title's views mapped over an alive one and + /// their pages, the pages unmapped under one. + mapped: (u64, u64), + unmapped: u64, + /// When the last line was made (ms). + since: u64, +} + +#[cfg(any(test, feature = "diagnostics"))] +impl Census { + /// A census begun at `now` (ms, `crate::host::now_ms`): the first line's + /// rates are over the time since then (from 0, the process's start, they + /// came out too low by the uptime over the census's age). + pub(crate) fn starting(now: u64) -> Census { + Census { since: now, ..Census::default() } + } + + /// An ask over `[at, at + len)` turned down, of `tiling`. + pub(crate) fn turned_down(&mut self, at: usize, len: usize, tiling: Tiling) { + let kind = match tiling { + Tiling::Tiles { pages, sections } => { + self.pages += pages as u64; + self.most = self.most.max(sections.len()); + self.sections.extend(sections); + if self.alive.insert((at, len)) { + self.longest = self.longest.max(len); + } + 0 + } + Tiling::Reserved => 1, + Tiling::Holes => 2, + Tiling::OffLines => 3, + }; + self.kinds[kind].0 += 1; + self.kinds[kind].1 += len as u64; + } + + /// Whether any is alive (for [`views_changed`] to look only then). + pub(crate) fn any_alive(&self) -> bool { + !self.alive.is_empty() + } + + /// The title mapped (`mapped`) or unmapped a view over `[at, at + len)`: + /// counted if it lies over one alive. + pub(crate) fn changed(&mut self, at: usize, len: usize, mapped: bool) { + let end = at.saturating_add(len); + let over = self.alive.range((at.saturating_sub(self.longest), 0)..(end, 0)).any(|&(start, bytes)| start < end && start + bytes > at); + if !over { + return; + } + let pages = len.div_ceil(K64) as u64; + if mapped { + self.mapped.0 += 1; + self.mapped.1 += pages; + } else { + self.unmapped += pages; + } + } + + /// Only the copies in `alive` (address, bytes: `crate::shadow::spans`) + /// stay alive. + pub(crate) fn prune(&mut self, alive: &std::collections::HashSet<(u64, u64)>) { + self.alive.retain(|&(at, len)| alive.contains(&(at as u64, len as u64))); + self.longest = self.alive.iter().map(|a| a.1).max().unwrap_or(0); + } + + /// The line at `now` (ms); the rates are over the time since the last, + /// or since the census began ([`Census::starting`]). + pub(crate) fn line(&mut self, now: u64) -> String { + let seconds = (now.saturating_sub(self.since) as f64 / 1000.0).max(0.001); + let alive = (self.alive.len(), self.alive.iter().map(|a| a.1 as u64).sum::<u64>()); + let k = self.kinds; + let all = k.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)); + let line = format!( + "title memory in place, census of tiles (diagnostics): view memory turned down as not one run of a committed section, {} asks of {} MB; \ + tiles could hold {} of {} MB (every 64 KiB page in a view of a committed section, on 64 KiB lines: {} pages, {} distinct sections, \ + at most {} for one), {} of {} MB are in views of a reserved section, {} of {} MB have pages in no view, {} have views off the 64 KiB lines; \ + of those tiles could hold, alive now {} of {} MB; over them the title mapped {:.1} views a second ({:.1} pages: a tiled window pays an \ + UpdateTileMappings for each) and unmapped {:.1} pages a second", + all.0, + all.1 >> 20, + k[0].0, + k[0].1 >> 20, + self.pages, + self.sections.len(), + self.most, + k[1].0, + k[1].1 >> 20, + k[2].0, + k[2].1 >> 20, + k[3].0, + alive.0, + alive.1 >> 20, + self.mapped.0 as f64 / seconds, + self.mapped.1 as f64 / seconds, + self.unmapped as f64 / seconds + ); + self.mapped = (0, 0); + self.unmapped = 0; + self.since = now; + line + } +} + +#[cfg(feature = "diagnostics")] +static CENSUS: std::sync::Mutex<Option<Census>> = std::sync::Mutex::new(None); + +/// Whether [`CENSUS`] holds any alive ([`views_changed`] looks only then). +#[cfg(feature = "diagnostics")] +static ANY_ALIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +#[cfg(feature = "diagnostics")] +fn census() -> std::sync::MutexGuard<'static, Option<Census>> { + CENSUS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// An ask over `[start, start + len)` was turned down (`super::place_for`, +/// `super::in_section`): counted if it is view memory. A walk over the +/// views of its pages under the views' read lock (a 4 MiB window of single +/// pages: 64 lookups), once an ask that makes a copy. +#[cfg(feature = "diagnostics")] +pub(crate) fn turned_down(start: u64, len: u64) { + let (at, len) = (start as usize, len as usize); + let tiling = { + let v = super::views(); + if super::cover_in(&v.views, at, len) == super::Cover::None { + return; + } + tiling_in(&v.views, &v.sections, at, len) + }; + let mut census = census(); + let census = census.get_or_insert_with(|| Census::starting(crate::host::now_ms())); + census.turned_down(at, len, tiling); + ANY_ALIVE.store(census.any_alive(), std::sync::atomic::Ordering::Relaxed); +} + +/// The title mapped (`mapped`) or unmapped a view over `[at, at + len)` +/// (`super::title_memory_view`, `super::views_gone`): one relaxed load while +/// none the census counts is alive, else a lock and a look in a map. +#[cfg(feature = "diagnostics")] +pub(crate) fn views_changed(at: usize, len: usize, mapped: bool) { + if !ANY_ALIVE.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + if let Some(census) = census().as_mut() { + census.changed(at, len, mapped); + } +} + +/// The census line, with `super::say`'s every ten seconds; `None` before +/// any ask was turned down. Those alive are looked up among the copies +/// (`crate::shadow::spans`: a lock and a list of every copy, some thousands). +#[cfg(feature = "diagnostics")] +pub(crate) fn line() -> Option<String> { + if census().is_none() { + return None; + } + let alive: std::collections::HashSet<(u64, u64)> = crate::shadow::spans().into_iter().map(|s| (s.0, s.1)).collect(); + let mut census = census(); + let census = census.as_mut()?; + census.prune(&alive); + ANY_ALIVE.store(census.any_alive(), std::sync::atomic::Ordering::Relaxed); + Some(census.line(crate::host::now_ms())) +} + +/// For tests: whether the census holds `[at, at + len)` alive as an ask +/// tiles could hold, and what it counted since its last line: the views +/// mapped over those alive and their pages, the pages unmapped under them. +#[cfg(all(test, feature = "diagnostics"))] +pub(crate) fn seen(at: usize, len: usize) -> (bool, (u64, u64), u64) { + census().as_ref().map_or((false, (0, 0), 0), |c| (c.alive.contains(&(at, len)), c.mapped, c.unmapped)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SECTION: usize = 0x40; + const OTHER: usize = 0x44; + const RESERVED: usize = 0x48; + + fn sections() -> BTreeMap<usize, (u64, bool)> { + BTreeMap::from([(SECTION, (64 << 20, true)), (OTHER, (64 << 20, true)), (RESERVED, (64 << 20, false))]) + } + + /// Pages of `section` at `at`, one view each, in the order given. + fn single_pages(views: &mut BTreeMap<usize, (usize, usize, u64)>, at: usize, section: usize, pages: &[u64]) { + for (k, &page) in pages.iter().enumerate() { + views.insert(at + k * K64, (K64, section, page * K64 as u64)); + } + } + + /// Scattered single pages of committed sections are what tiles hold: + /// counted by the pages that hold the range (a range off the lines + /// takes the pages it touches) and the distinct sections. + #[test] + fn scattered_pages_of_committed_sections_are_tiles() { + let at = 0x7_8000_0000usize; + let mut views = BTreeMap::new(); + single_pages(&mut views, at, SECTION, &[9, 3, 700, 4]); + // Two pages of another committed section, as one view. + views.insert(at + 4 * K64, (2 * K64, OTHER, 20 * K64 as u64)); + let s = sections(); + assert_eq!(tiling_in(&views, &s, at, 4 * K64), Tiling::Tiles { pages: 4, sections: vec![SECTION] }); + assert_eq!(tiling_in(&views, &s, at, 6 * K64), Tiling::Tiles { pages: 6, sections: vec![SECTION, OTHER] }); + // From inside the second page to inside the fifth: four pages. + assert_eq!(tiling_in(&views, &s, at + K64 + 100, 3 * K64), Tiling::Tiles { pages: 4, sections: vec![SECTION, OTHER] }); + // A byte at the end of a page and one past it: two pages. + assert_eq!(tiling_in(&views, &s, at + 2 * K64 - 1, 2), Tiling::Tiles { pages: 2, sections: vec![SECTION] }); + // An empty ask is its page. + assert_eq!(tiling_in(&views, &s, at + 5 * K64, 0), Tiling::Tiles { pages: 1, sections: vec![OTHER] }); + } + + /// A page of a reserved section, or of one the runtime never told, + /// cannot be a tile: the host does not open such a section. + #[test] + fn a_page_of_a_reserved_or_unknown_section_is_not_tiles() { + let at = 0x7_9000_0000usize; + let mut views = BTreeMap::new(); + single_pages(&mut views, at, SECTION, &[1, 2]); + single_pages(&mut views, at + 2 * K64, RESERVED, &[5]); + single_pages(&mut views, at + 3 * K64, 0x99, &[5]); + let s = sections(); + assert_eq!(tiling_in(&views, &s, at, 2 * K64), Tiling::Tiles { pages: 2, sections: vec![SECTION] }); + assert_eq!(tiling_in(&views, &s, at, 3 * K64), Tiling::Reserved); + assert_eq!(tiling_in(&views, &s, at + 3 * K64, K64), Tiling::Reserved, "a section the runtime never told"); + } + + /// A page in no view, at the start, inside or at the end, and views off + /// the 64 KiB lines. + #[test] + fn holes_and_views_off_the_lines_are_not_tiles() { + let at = 0x7_a000_0000usize; + let mut views = BTreeMap::new(); + single_pages(&mut views, at, SECTION, &[1, 2]); + single_pages(&mut views, at + 3 * K64, SECTION, &[3]); + let s = sections(); + assert_eq!(tiling_in(&views, &s, at, 4 * K64), Tiling::Holes, "a gap inside"); + assert_eq!(tiling_in(&views, &s, at - K64, 2 * K64), Tiling::Holes, "a gap at the start"); + assert_eq!(tiling_in(&views, &s, at + 3 * K64, 2 * K64), Tiling::Holes, "a gap at the end"); + let mut off = BTreeMap::new(); + off.insert(at, (K64, SECTION, 4096u64)); + assert_eq!(tiling_in(&off, &s, at, K64), Tiling::OffLines, "a section offset off the lines"); + let mut short = BTreeMap::new(); + short.insert(at, (K64 / 2, SECTION, 0u64)); + assert_eq!(tiling_in(&short, &s, at, 100), Tiling::OffLines, "a view of half a page"); + } + + /// The counts: kinds and bytes, pages and sections of those tiles could + /// hold, the title's mappings and unmappings over those alive (not over + /// others, nor those let go), per second since the last line. + #[test] + fn the_census_counts_kinds_and_mappings_over_those_alive() { + let mut c = Census::starting(0); + let at = 0x7_b000_0000usize; + c.turned_down(at, 4 * K64, Tiling::Tiles { pages: 4, sections: vec![1, 2] }); + c.turned_down(at + 16 * K64, K64, Tiling::Tiles { pages: 1, sections: vec![2] }); + c.turned_down(at + 32 * K64, 2 * K64, Tiling::Reserved); + c.turned_down(at + 40 * K64, 3 * K64, Tiling::Holes); + c.turned_down(at + 48 * K64, K64, Tiling::OffLines); + assert!(c.any_alive()); + // Over the first (its third page), the second, and nothing alive. + c.changed(at + 2 * K64, K64, true); + c.changed(at + 15 * K64, 2 * K64, true); + c.changed(at + 32 * K64, K64, true); + c.changed(at + 3 * K64, 2 * K64, false); + c.changed(at + 20 * K64, K64, false); + let line = c.line(2_000); + assert!(line.contains("5 asks of 0 MB"), "{line}"); + assert!(line.contains("tiles could hold 2 of 0 MB"), "{line}"); + assert!(line.contains("5 pages, 2 distinct sections, at most 2 for one"), "{line}"); + assert!(line.contains("1 of 0 MB are in views of a reserved section"), "{line}"); + assert!(line.contains("1 of 0 MB have pages in no view, 1 have views off"), "{line}"); + assert!(line.contains("alive now 2 of 0 MB"), "{line}"); + assert!(line.contains("mapped 1.0 views a second (1.5 pages"), "{line}"); + assert!(line.contains("unmapped 1.0 pages a second"), "{line}"); + // The first copy is let go: the mappings over it count no more. + let alive = std::collections::HashSet::from([((at + 16 * K64) as u64, K64 as u64)]); + c.prune(&alive); + c.changed(at, K64, true); + let line = c.line(3_000); + assert!(line.contains("alive now 1 of 0 MB"), "{line}"); + assert!(line.contains("mapped 0.0 views a second"), "{line}"); + c.prune(&std::collections::HashSet::new()); + assert!(!c.any_alive()); + } + + /// The first line's rates are over the time since the census began, not + /// since the process did: begun at 95 s, five mappings by 100 s are one + /// a second (from 0 they came out 0.05). + #[test] + fn the_first_lines_rates_are_over_the_census_own_time() { + let mut c = Census::starting(95_000); + let at = 0x7_c000_0000usize; + c.turned_down(at, 2 * K64, Tiling::Tiles { pages: 2, sections: vec![1] }); + for _ in 0..5 { + c.changed(at, K64, true); + c.changed(at + K64, K64, false); + } + let line = c.line(100_000); + assert!(line.contains("mapped 1.0 views a second (1.0 pages"), "{line}"); + assert!(line.contains("unmapped 1.0 pages a second"), "{line}"); + c.changed(at, K64, true); + let line = c.line(101_000); + assert!(line.contains("mapped 1.0 views a second"), "and since the last line after it: {line}"); + } + + /// The layout the probe maps: fifteen distinct pages, the last tile on + /// the first's page, a stride that visits every page once. + #[test] + fn the_probes_layout_scatters_distinct_pages() { + for pages in [32usize, 64, 1024, 37 * 16] { + let tiles = layout(pages); + assert_eq!(tiles.len(), TILES as usize); + assert_eq!(tiles[TILES as usize - 1], tiles[0]); + let distinct: BTreeSet<u32> = tiles[..TILES as usize - 1].iter().copied().collect(); + assert_eq!(distinct.len(), TILES as usize - 1, "{pages} pages"); + assert!(tiles.windows(2).any(|w| w[1] < w[0]), "not in order"); + let step = stride(pages); + let all: BTreeSet<usize> = (0..pages).map(|k| (k * step + 3) % pages).collect(); + assert_eq!(all.len(), pages); + } + } + + /// A copy to the card and back on `device`, after a fence: whether it + /// still works, and the bytes come back. + fn copies(device: &ID3D12Device, fill: u8) -> Result<(), String> { + let mut rig = Rig::new(device).map_err(|e| format!("no queue: {}", short(&e)))?; + let buffer = card_buffer(&rig, K64 as u64).map_err(|e| format!("no buffer: {}", short(&e)))?; + rig.store(&buffer, 0x100, &[fill; 256]).map_err(|e| format!("the copy in: {}", short(&e)))?; + let back = rig.fetch(&buffer, 0x100, 256).map_err(|e| format!("the copy out: {}", short(&e)))?; + if back.iter().all(|&b| b == fill) { Ok(()) } else { Err("the bytes did not come back".to_owned()) } + } + + /// The probe on the card of this PC as the title's process runs it + /// ([`probe_beside`]): beside a device made as the host makes the + /// title's (`D3D12CreateDevice`, the process's device for the adapter), + /// on a device of the probe's own, whose removal by a refused tile + /// mapping must leave the title's standing: after the probe the title's + /// device reports no removal and a copy and a fence on it still + /// complete. `cargo test -p leonida-gpu --lib + /// card_tiles_over_a_committed_section -- --ignored --nocapture`. Prints + /// the lines; asserts that the steps hold on a heap of ours (the card's + /// answer for the section's heap is what it reports). With + /// `LEONIDA_INPLACE_PROBE_DEBUG=1` the factory's debug layer says why a + /// step is refused. + #[test] + #[ignore = "runs on the card of this PC"] + fn card_tiles_over_a_committed_section() { + // SAFETY: plain DXGI queries. + let adapter = unsafe { + CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0)).and_then(|f| f.EnumAdapters1(0)).and_then(|a| a.cast::<IDXGIAdapter>()) + }; + let Ok(adapter) = adapter else { + eprintln!("no adapter"); + return; + }; + let mut title: Option<ID3D12Device> = None; + // SAFETY: device creation on a live adapter. + unsafe { D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut title) }.expect("the title's device"); + let title = title.expect("the title's device"); + copies(&title, 0x3c).expect("the title's device copies before the probe"); + let debug = std::env::var_os("LEONIDA_INPLACE_PROBE_DEBUG").is_some_and(|v| v == "1"); + let mb = std::env::var("LEONIDA_INPLACE_PROBE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64); + let tiles = probe(&adapter, Some(&title), false, debug, mb); + for line in &tiles.lines { + eprintln!("in place probe, tiles: {line}"); + } + // SAFETY: a plain query. + let removed = unsafe { title.GetDeviceRemovedReason() }; + let after = copies(&title, 0xc3); + eprintln!( + "in place probe, tiles: the title's device after the probe: removal reason {}, a copy and a fence on it {}", + hr(&removed), + after.as_ref().map_or_else(Clone::clone, |()| "complete".to_owned()) + ); + assert!(removed.is_ok(), "the title's device was removed by the probe"); + after.expect("the title's device still copies after the probe"); + assert!(tiles.own_device, "the probe ran on a device of its own beside the title's"); + assert!(tiles.tier >= 1, "no tiled resources on this card"); + assert!(tiles.ours_map, "the probe's steps on a heap of ours"); + } + + /// The same on the software adapter, on a device of its own: the steps + /// on a heap of ours hold there too, and whatever the section's heap + /// does to that device, no other device in the process is touched. + #[test] + fn warp_tiles_probe_on_a_device_of_its_own() { + let _turn = crate::indirect::tests::warp_turn(); + let Ok(adapter) = crate::host::warp_adapter() else { return }; + let Some(shared) = super::super::tests::warp() else { return }; + let tiles = probe(&adapter, Some(&shared), false, false, 2); + for line in &tiles.lines { + eprintln!("in place probe, tiles: {line}"); + } + if !tiles.own_device { + eprintln!("no device of the probe's own here: not run"); + return; + } + assert!(tiles.tier >= 1); + assert!(tiles.ours_map, "the probe's steps on a heap of ours"); + // Either the section's heap takes tiles, or the probe says why not. + assert!(tiles.section_maps || tiles.cross_adapter_refused, "a refusal the probe cannot explain"); + // SAFETY: a plain query. + assert!(unsafe { shared.GetDeviceRemovedReason() }.is_ok(), "the process's device stands"); + copies(&shared, 0x5a).expect("the process's device still copies"); + } + + /// The probe that removes devices on the title's adapter runs only when + /// asked for (`LEONIDA_INPLACE_PROBE_TILES=1`), not with every + /// `LEONIDA_INPLACE_PROBE=1`. + #[test] + fn the_tiles_probe_runs_only_when_asked_for() { + if std::env::var_os("LEONIDA_INPLACE_PROBE_TILES").is_some() { + return; + } + assert!(!asked(), "off while unset"); + } +} diff --git a/d3d12/crates/leonida-gpu/src/land.rs b/d3d12/crates/leonida-gpu/src/land.rs index d0c8ef1170..069035bab7 100644 --- a/d3d12/crates/leonida-gpu/src/land.rs +++ b/d3d12/crates/leonida-gpu/src/land.rs @@ -134,7 +134,10 @@ pub(crate) mod stat { pub(crate) const TB_WORK: usize = 33; pub(crate) const TB_WRITTEN: usize = 34; pub(crate) const TB_REPLACED: usize = 35; - pub(crate) const COUNT: usize = 36; + /// Texture read-backs read in their mapped buffer and not written, the + /// list submitted again while they were tiled (`texback::mapped`). + pub(crate) const TB_OVERTAKEN: usize = 36; + pub(crate) const COUNT: usize = 37; } static STATS: [AtomicU64; stat::COUNT] = [const { AtomicU64::new(0) }; stat::COUNT]; @@ -202,11 +205,13 @@ pub(crate) fn log(frames: f64) { ms(stat::RB_DONE), ); tracing::info!( - "texture read-backs written per frame (LEONIDA_TEXBACK_ASYNC={}): {:.1}, {:.1} replaced by a newer one first; \ + "texture read-backs written per frame (LEONIDA_TEXBACK_ASYNC={}): {:.1}, {:.1} replaced by a newer one first, \ + {:.1} left to a newer one because the list was submitted again while they were read in place; \ waiting for the mapping locks {:.2} ms, tiling and writing {:.2} ms", u8::from(std::env::var_os("LEONIDA_TEXBACK_ASYNC").is_none_or(|v| v != "0")), s[stat::TB_WRITTEN], s[stat::TB_REPLACED], + s[stat::TB_OVERTAKEN], ms(stat::TB_WAIT), ms(stat::TB_WORK), ); @@ -564,6 +569,14 @@ impl Had { *behind >= fence && all.get(&(copy, at / BLOCK)).is_some_and(|had| had.0 <= at && at + len <= had.1) }) } + + /// Whether a fetch noted with `fence` or later brought any of the block + /// of the piece (`host::landsame`, which notes fetches by the last send + /// known to have gone to the queue ahead of them): only the longest part + /// of a block is kept, so any is the block. Pieces lie within a block. + pub(crate) fn touches(&self, fence: u64, (copy, at, _): Piece) -> bool { + self.0.iter().any(|(behind, all)| *behind >= fence && all.contains_key(&(copy, at / BLOCK))) + } } /// Whether a piece is put through a view of ours while the runtime changes @@ -759,7 +772,10 @@ unsafe fn piece_at( let since = crate::watch::changes(); let (mut pages, mut new_pages, mut blocks, mut dwords, mut missing) = (0, 0u64, 0, 0, 0); let mut span: Option<(usize, usize)> = None; - // The cells of each page that something was put into ([`new_cells`]). + // The cells of each page that something was put into ([`new_cells`]), in a run that keeps them + // (`crate::watch::landed_cells_kept`): in any other, working them out was a second pass over every page that + // differs and a read of title memory for nothing. + let keep_cells = crate::watch::landed_cells_kept(); let mut landed: Vec<(usize, crate::watch::Cells)> = Vec::new(); for_pages(title, parts, |from, n| { pages += 1; @@ -767,8 +783,12 @@ unsafe fn piece_at( return; } // (Before the merge makes the reference equal to the card's bytes.) - // SAFETY: the caller's: both are ours for the part's bytes. - let cells = unsafe { new_cells(title + from, now.add(from), held.add(from), n) }; + let cells = if keep_cells { + // SAFETY: the caller's: both are ours for the part's bytes. + unsafe { new_cells(title + from, now.add(from), held.add(from), n) } + } else { + [0u64; 8] + }; // SAFETY: the caller's; title memory, by an address that shows it // (`beside`) or the title's own. let merge = |take| unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) }; diff --git a/d3d12/crates/leonida-gpu/src/lib.rs b/d3d12/crates/leonida-gpu/src/lib.rs index f800cb40f6..b14f71aae9 100644 --- a/d3d12/crates/leonida-gpu/src/lib.rs +++ b/d3d12/crates/leonida-gpu/src/lib.rs @@ -152,7 +152,10 @@ pub fn frame_phase() -> u32 { copystat::phase() } #[cfg(windows)] -pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view}; +pub use inplace::{ + HeldInPlace, title_memory_alloc, title_memory_as_asked, title_memory_free, title_memory_freeing, title_memory_held_in_place, title_memory_protect, + title_memory_reads_in_place, title_memory_reserve, title_memory_section, title_memory_section_gone, title_memory_view, +}; #[cfg(windows)] pub use shadow::{title_memory_gpu_read_only, title_memory_write_combined}; #[cfg(windows)] diff --git a/d3d12/crates/leonida-gpu/src/list.rs b/d3d12/crates/leonida-gpu/src/list.rs index 1bdf12ea0e..76852101b4 100644 --- a/d3d12/crates/leonida-gpu/src/list.rs +++ b/d3d12/crates/leonida-gpu/src/list.rs @@ -221,25 +221,84 @@ impl Detached { } } -/// A host list that has run and waits to be used again, the bytes of -/// upload memory it keeps, and when it was put by (`crate::host::now_ms`). +/// A host list that has run and waits to be used again, and when it was put +/// by (`crate::host::now_ms`). The bytes of upload memory it keeps are the +/// pool's ([`Pool`]). #[cfg(windows)] -struct Idle(crate::host::HostList, u64, u64); +struct Idle(crate::host::HostList, u64); // SAFETY: D3D12 objects are free-threaded, and an idle list is touched by // nobody until it is taken out again. #[cfg(windows)] unsafe impl Send for Idle {} +/// Things kept to be used again, the oldest first, each with the bytes of +/// upload memory it keeps. +#[cfg(windows)] +struct Pool<T> { + kept: Vec<(T, u64)>, + bytes: u64, + /// The fewest kept at any time since the last [`Pool::trim`]: the + /// oldest that many were not taken since then. + low: usize, +} + +#[cfg(windows)] +impl<T> Pool<T> { + const fn new() -> Self { + Pool { kept: Vec::new(), bytes: 0, low: 0 } + } + + /// The thing given last. + fn take(&mut self) -> Option<T> { + let (thing, bytes) = self.kept.pop()?; + self.bytes -= bytes; + self.low = self.low.min(self.kept.len()); + Some(thing) + } + + /// Keeps `thing`, which keeps `bytes`, unless that takes the pool past + /// `most` things or bytes: then it comes back. + fn give(&mut self, thing: T, bytes: u64, most: (usize, u64)) -> Option<T> { + if self.kept.len() >= most.0 || self.bytes + bytes > most.1 { + return Some(thing); + } + self.bytes += bytes; + self.kept.push((thing, bytes)); + None + } + + /// Takes out the oldest `n` things. + fn take_oldest(&mut self, n: usize) -> Vec<(T, u64)> { + let gone: Vec<(T, u64)> = self.kept.drain(..n.min(self.kept.len())).collect(); + self.bytes -= gone.iter().map(|(_, bytes)| bytes).sum::<u64>(); + // The ones taken out were the oldest of those nobody took. + self.low = self.low.saturating_sub(gone.len()); + gone + } + + /// Takes out the oldest half (rounded up) of the things nobody took + /// since the last trim, so that what is kept follows what was needed + /// lately. Halving rather than taking out all of them keeps a need that + /// comes and goes from making things anew every time. + fn trim(&mut self) -> Vec<(T, u64)> { + let gone: Vec<(T, u64)> = self.kept.drain(..self.low.div_ceil(2)).collect(); + self.bytes -= gone.iter().map(|(_, bytes)| bytes).sum::<u64>(); + self.low = self.kept.len(); + gone + } +} + /// Host lists that have run, reset and ready to record: the host side of /// a list a queue held, or of a part of a list cut at a wait, is taken -/// from the title's list at its submission, and the title's list needs -/// another. Each was made new and thrown away after its run: a hundred a -/// frame in gameplay, each two command allocators and two lists, and for -/// four in ten a budget and an argument buffer (run 61: "104 host lists -/// made 21.2 ms" a frame, and the graphics kernel's time to free them). +/// from the title's list at its submission, and the title's list takes +/// another at its next reset. Each was made new and thrown away after its +/// run: a hundred a frame in gameplay, each two command allocators and two +/// lists, and for four in ten a budget and an argument buffer (run 61: +/// "104 host lists made 21.2 ms" a frame, and the graphics kernel's time to +/// free them). #[cfg(windows)] -static IDLE: std::sync::Mutex<(Vec<Idle>, u64)> = std::sync::Mutex::new((Vec::new(), 0)); +static IDLE: std::sync::Mutex<Pool<Idle>> = std::sync::Mutex::new(Pool::new()); /// The most host lists kept idle (128 were too few: flights land several at /// a time, so lists were thrown away and others made in the same frame, with @@ -251,12 +310,12 @@ static IDLE: std::sync::Mutex<(Vec<Idle>, u64)> = std::sync::Mutex::new((Vec::ne const IDLE_MOST: (usize, u64) = (512, 256 << 20); /// Host lists that have run, reset and closed again by the thread that recycles them ([`recycle`]), for -/// [`detach`] and [`detach_parts`]: the title's list gets a new host list there, closed, as the title's next call on -/// it is a reset. Taken from [`IDLE`] they were closed by the line's thread, which sends every submission (its -/// `Close` calls 3.6 % of its samples, profile `submit-d61`, 2026-11-29). `LEONIDA_CLOSED_AHEAD=0`: closed there, as -/// before. +/// [`reset`]: a submitted title list holds no host list ([`detach`], [`detach_parts`]) and takes one, closed, at its +/// reset, which resets it again. At the submission, where they were taken before, the line's thread closed them (its +/// `Close` calls 3.6 % of its samples, profile `submit-d61`, 2026-11-29). `LEONIDA_CLOSED_AHEAD=0`: taken from +/// [`IDLE`] and closed by the thread that resets the title's list. Trimmed as [`IDLE`] is ([`trim_idle`]). #[cfg(windows)] -static IDLE_CLOSED: std::sync::Mutex<Vec<Closed>> = std::sync::Mutex::new(Vec::new()); +static IDLE_CLOSED: std::sync::Mutex<Pool<Closed>> = std::sync::Mutex::new(Pool::new()); /// A list of [`IDLE_CLOSED`]. #[cfg(windows)] @@ -276,17 +335,16 @@ fn closed_ahead() -> bool { crate::toggled!("LEONIDA_CLOSED_AHEAD") } -/// Since the start: lists [`detach`] and [`detach_parts`] took closed from [`IDLE_CLOSED`], and those they closed -/// themselves. +/// Since the start: lists [`reset`] took closed from [`IDLE_CLOSED`], and those it closed itself. #[cfg(windows)] pub(crate) static CLOSED_TAKEN: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; -/// A host list for the title's list after its submission: closed, for the reset that comes next. +/// A host list for a title list that holds none since its submission: closed, for its reset. #[cfg(windows)] fn fresh_closed() -> Option<crate::host::HostList> { use std::sync::atomic::Ordering::Relaxed; if closed_ahead() - && let Some(Closed(list)) = IDLE_CLOSED.lock().unwrap_or_else(|e| e.into_inner()).pop() + && let Some(Closed(list)) = IDLE_CLOSED.lock().unwrap_or_else(|e| e.into_inner()).take() { CLOSED_TAKEN[0].fetch_add(1, Relaxed); return Some(list); @@ -318,20 +376,35 @@ fn pools() -> bool { /// after its reset, or a new one. #[cfg(windows)] fn fresh_list() -> Option<crate::host::HostList> { - let idle = { - let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); - let taken = idle.0.pop(); - if let Some(Idle(_, bytes, _)) = &taken { - idle.1 -= bytes; - } - taken - }; + let idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()).take(); match idle { - Some(Idle(list, _, _)) => Some(list), + Some(Idle(list, _)) => Some(list), None => crate::host::host().and_then(|h| h.new_list().ok()), } } +/// Lets go of idle host lists nobody took lately ([`Pool::trim`]), once a +/// second (`crate::host::sweep`). A command allocator keeps the memory of +/// the most a list ever recorded into it over its resets, and the pool +/// hands its lists to any title list, so every idle list grows to the size +/// of the largest recording; the pool may keep [`IDLE_MOST`] of them, +/// which a burst of landed flights fills and nothing emptied before. +#[cfg(windows)] +pub(crate) fn trim_idle() { + let gone = IDLE.lock().unwrap_or_else(|e| e.into_inner()).trim(); + if !gone.is_empty() { + // Freeing allocators is the driver's work: done where retired + // objects are dropped (the reaper thread), not on the submitting + // thread that sweeps. + crate::host::retire(gone); + } + // The lists closed ahead ([`IDLE_CLOSED`]) grow as the others do. + let gone = IDLE_CLOSED.lock().unwrap_or_else(|e| e.into_inner()).trim(); + if !gone.is_empty() { + crate::host::retire(gone); + } +} + /// The host sides of lists whose submission has run (submissions are /// waited for; `ran` names the ones it ran, by their place in `lists`): /// what they held is let go, as before, and the host lists are reset and @@ -345,41 +418,50 @@ pub(crate) fn recycle(lists: Vec<Detached>, ran: &[usize]) { // The descriptor slots and the upload memory its commands named. drop(_state); drop(_uploads); - // Reset and closed here for the line's next detaches ([`IDLE_CLOSED`]), while that pool wants some. - if ran.contains(&i) && closed_ahead() && IDLE_CLOSED.lock().unwrap_or_else(|e| e.into_inner()).len() < CLOSED_MOST { + // Reset and closed here for the title lists' next resets ([`IDLE_CLOSED`]), while that pool wants some. + if ran.contains(&i) + && closed_ahead() + && IDLE_CLOSED.lock().unwrap_or_else(|e| e.into_inner()).kept.len() < CLOSED_MOST + { host.reset(); + host.idle_trim(); + let bytes = host.scratch_kept(); host.close_empty(); - IDLE_CLOSED.lock().unwrap_or_else(|e| e.into_inner()).push(Closed(host)); + let mut closed = IDLE_CLOSED.lock().unwrap_or_else(|e| e.into_inner()); + let refused = closed.give(Closed(host), bytes, (CLOSED_MOST, IDLE_MOST.1)); + drop(closed); + // (Dropped outside the lock.) + drop(refused); continue; } - if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 { + if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).kept.len() >= IDLE_MOST.0 { continue; } // As the title's reset does: what the list kept for its commands // goes, its allocators stay. host.reset(); + host.idle_trim(); let bytes = host.scratch_kept(); + let now = crate::host::now_ms(); let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); - if idle.0.len() < IDLE_MOST.0 && idle.1 + bytes <= IDLE_MOST.1 { - let now = crate::host::now_ms(); - idle.0.push(Idle(host, bytes, now)); - idle.1 += bytes; - // (`LEONIDA_ALLOCATOR_TRIM=1`) Lists the frames did not need for - // that long are let go, with their allocators: the pool is last - // in, first out, so its oldest are the surplus of a spike, and - // nothing resets them again. Their submissions have run, as - // every idle list's (one the full pool turns away goes the same - // way). - if let Some(secs) = crate::host::allocator_trim() { - let n = stale(idle.0.iter().map(|i| i.2), now, secs * 1000); - let gone: Vec<Idle> = idle.0.drain(..n).collect(); - idle.1 -= gone.iter().map(|i| i.1).sum::<u64>(); + let refused = idle.give(Idle(host, now), bytes, IDLE_MOST); + // (`LEONIDA_ALLOCATOR_TRIM=1`) Lists the frames did not need for + // that long are let go, with their allocators: the pool is last in, + // first out, so its oldest are the surplus of a spike, and nothing + // resets them again. Their submissions have run, as every idle + // list's (one the full pool turns away goes the same way). + let gone = match crate::host::allocator_trim() { + Some(secs) if refused.is_none() => { + let n = stale(idle.kept.iter().map(|(i, _)| i.1), now, secs * 1000); crate::host::ALLOCATOR_TRIMS[2].fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed); - // Released outside the lock. - drop(idle); - drop(gone); + idle.take_oldest(n) } - } + _ => Vec::new(), + }; + // (Dropped outside the lock.) + drop(idle); + drop(refused); + drop(gone); } } @@ -461,8 +543,8 @@ pub(crate) fn cut_list(this: This) -> bool { pub(crate) type Parts = Vec<(Vec<ValueWait>, Vec<Detached>, Vec<usize>)>; /// Takes the host sides of the submitted `lists`, part by part ([`cut`]), -/// and leaves each list a new, closed host list for its next reset, as -/// [`detach`] does. What comes back is in the order the queue runs it: a +/// and leaves each list without one until its next reset, as [`detach`] +/// does. What comes back is in the order the queue runs it: a /// new entry starts at every part that has waits; host lists without /// waits join the entry before them. The list's upload memory and draw /// state (its dynamic descriptor slots) go with its last part, which runs @@ -492,13 +574,11 @@ pub(crate) fn detach_parts(lists: &[This]) -> Parts { } continue; } - let Some(fresh) = fresh_closed() else { - continue; - }; // SAFETY: one of our lists, closed and submitted: nothing records // into it until the title resets it. let list = unsafe { &mut *this.cast_mut().cast::<List>() }; - let Some(host) = list.host.replace(fresh) else { + // The list takes another host list at its reset ([`reset`]). + let Some(host) = list.host.take() else { continue; }; let earlier = std::mem::take(&mut list.earlier); @@ -578,8 +658,8 @@ fn ahead_list(record: impl FnOnce(&crate::host::HostList) -> bool) -> Option<Det } /// Takes the host sides of submitted lists (each once, however often the -/// submission names it) and leaves each list a new, closed host list for -/// its next reset: what was taken, and which of them run in what order. +/// submission names it) and leaves each list without one until its next +/// reset ([`reset`]): what was taken, and which of them run in what order. #[cfg(windows)] pub(crate) fn detach(lists: &[This]) -> (Vec<Detached>, Vec<usize>) { let mut taken: Vec<(This, Detached)> = Vec::new(); @@ -592,14 +672,11 @@ pub(crate) fn detach(lists: &[This]) -> (Vec<Detached>, Vec<usize>) { order.push(i); continue; } - let Some(fresh) = fresh_closed() else { - continue; - }; let list = this.cast_mut().cast::<List>(); // SAFETY: one of our lists, closed and submitted: nothing records // into it until the title resets it. let (host, uploads, state) = unsafe { - let Some(host) = (*list).host.replace(fresh) else { + let Some(host) = (*list).host.take() else { continue; }; let uploads = @@ -798,6 +875,19 @@ extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT let list = unsafe { &mut *this.cast_mut().cast::<List>() }; list.earlier.clear(); list.gate.clear(); + // A submission took the list's host list ([`detach`]): it takes one + // now. A submitted list used to get a new one at once and keep it + // until this reset, which for a list the title leaves alone for a + // while is a command allocator grown to the size of some other + // list's recording, kept for nothing. Closed, so that its reset + // below is the same as the one the list had before; closed ahead by + // the thread that recycles lists if `LEONIDA_CLOSED_AHEAD` is on + // ([`fresh_closed`]). + if list.host.is_none() + && let Some(fresh) = fresh_closed() + { + list.host = Some(fresh); + } } #[cfg(windows)] with_state(this, |host, state| { @@ -1953,6 +2043,8 @@ extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: if crate::texture::committed(src as *const u8, len) && crate::texture::committed(dst as *const u8, len) { + // A command behind the submissions in the air, done now. + crate::shadow::copying(dst as usize, len); // SAFETY: both ranges are committed title memory. unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) }; } @@ -2606,6 +2698,21 @@ impl ValueWait { /// The waits lists recorded since their last reset, by list. static VALUE_WAITS: std::sync::Mutex<Vec<(usize, ValueWait)>> = std::sync::Mutex::new(Vec::new()); +/// A list the title releases neither submitted nor reset takes the waits it +/// recorded with it. They stayed filed by its address for good, and a list +/// made later at that address took them with its first submission: a wait +/// for a value nothing writes then held that queue. (Here, before the +/// list's memory is free: a list made there after has waits of its own.) +impl Drop for List { + fn drop(&mut self) { + let at = std::ptr::from_ref::<List>(self) as usize; + let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + if !waits.is_empty() { + waits.retain(|&(list, _)| list != at); + } + } +} + /// The waits of the submitted `lists` that are not met yet (taken from /// them): what the console's GPU would stop at. The title orders work /// between its queues this way (the title: the compute queue's @@ -2962,6 +3069,65 @@ mod tests { assert_eq!(stale(std::iter::empty(), 40_000, 30_000), 0); } + /// A host list put by in the idle pool lets go of an indirect scratch + /// buffer past 1 MiB, which it kept for whichever title list took it + /// next; a smaller one it keeps. + #[cfg(windows)] + #[test] + fn an_idle_list_lets_go_of_a_large_indirect_scratch() { + use windows::core::Interface; + let Some(host) = crate::host::host() else { + eprintln!("no D3D12 device; idle host lists not tested"); + return; + }; + // SAFETY: a live buffer. + let width = |buffer: &windows::Win32::Graphics::Direct3D12::ID3D12Resource| unsafe { buffer.GetDesc() }.Width; + // Through the pool and back. Other tests give lists to it and take + // them too: ours is among the last given, unless one took it. The + // lists taken out above ours go back in their order, so a test that + // expects its own list back still finds it. Only the pool's + // functions are used: its layout is not the same on every branch. + let detached = |host| Detached { host, _uploads: Vec::new(), _state: Default::default() }; + let round_trip = |list: crate::host::HostList| { + let raw = list.list.as_raw(); + list.close(); + recycle(vec![detached(list)], &[0]); + let mut others = Vec::new(); + let mut ours = None; + for _ in 0..16 { + let Some(l) = fresh_list() else { break }; + if l.list.as_raw() == raw { + ours = Some(l); + break; + } + l.close(); + others.push(detached(l)); + } + others.reverse(); + let all: Vec<usize> = (0..others.len()).collect(); + recycle(others, &all); + ours + }; + let list = host.new_list().unwrap(); + assert_eq!(width(&list.indirect_scratch(1).unwrap()), 64 << 10); + let large = list.indirect_scratch(2 << 20).unwrap(); + assert_eq!(width(&large), 2 << 20); + drop(large); + let Some(list) = round_trip(list) else { + eprintln!("another test took the list from the pool"); + return; + }; + assert_eq!(width(&list.indirect_scratch(1).unwrap()), 64 << 10, "the large buffer was let go"); + // One within the bound stays with the list. + let kept = list.indirect_scratch(1 << 20).unwrap().as_raw(); + let Some(list) = round_trip(list) else { + eprintln!("another test took the list from the pool"); + return; + }; + assert_eq!(list.indirect_scratch(1).unwrap().as_raw(), kept, "1 MiB is kept"); + list.close(); + } + /// After edsuuu/VI-BR-PORT 7377418. #[test] fn a_compression_scratch_is_cut_to_the_level_it_is_copied_into() { @@ -3089,6 +3255,167 @@ mod tests { assert_eq!(release(allocator), 0); } + /// A title list that was submitted holds no host list, and so no command + /// allocator grown by what it recorded, until the title resets it. Each + /// used to get a new host list at its submission and keep it while it + /// was idle, so every title list kept one alive besides those in flight + /// and in the pool. + #[cfg(windows)] + #[test] + fn a_submitted_list_keeps_no_host_list_until_its_reset() { + if crate::host::host().is_none() { + eprintln!("no D3D12 device; the host lists of submitted lists are not tested"); + return; + } + const LISTS: usize = 64; + let null = std::ptr::null(); + let mut allocator = null; + assert_eq!(create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), S_OK); + let lists: Vec<This> = (0..LISTS) + .map(|_| { + let mut list = null; + assert_eq!(create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), S_OK); + list + }) + .collect(); + let held = |lists: &[This]| lists.iter().filter(|&&l| host_list(l).is_some()).count(); + assert_eq!(held(&lists), LISTS, "a new list records at once"); + for round in 0..4 { + for &list in &lists { + // (A new list starts open.) + if round > 0 { + assert_eq!(reset(list, allocator, null), S_OK); + assert!(host_list(list).is_some(), "round {round}: a reset list records"); + } + assert_eq!(close(list), S_OK); + } + // Submitted, run and landed, as a queue that holds its lists + // does it: their host sides are taken and given back once run. + let (taken, order) = detach(&lists); + assert_eq!(taken.len(), LISTS); + recycle(taken, &order); + assert_eq!(held(&lists), 0, "round {round}: submitted lists keep host lists alive"); + } + let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); + for list in lists { + assert_eq!(release(list), 0); + } + assert_eq!(release(allocator), 0); + } + + /// The idle pool follows what was needed lately: after a burst fills it + /// to the most, a steady need of a few lists a second leaves it with + /// about those few. Each trim lets go of the oldest half of those + /// nobody took since the one before, and never of those that were taken. + #[cfg(windows)] + #[test] + fn idle_lists_nobody_takes_are_let_go() { + let mut pool: Pool<u32> = Pool::new(); + for i in 0..IDLE_MOST.0 as u32 { + assert_eq!(pool.give(i, 1, IDLE_MOST), None); + } + assert_eq!(pool.give(9999, 1, IDLE_MOST), Some(9999), "no more than the most"); + assert_eq!(pool.give(9999, IDLE_MOST.1, (usize::MAX, IDLE_MOST.1)), Some(9999), "no more bytes than the most"); + // Given since the last trim: nobody had the time to take them. + assert!(pool.trim().is_empty()); + let mut kept = Vec::new(); + for second in 0..12 { + // Eight lists recorded, run and given back. + let taken: Vec<u32> = (0..8).map(|_| pool.take().expect("kept")).collect(); + for &t in &taken { + assert_eq!(pool.give(t, 1, IDLE_MOST), None); + } + let gone = pool.trim(); + assert!(gone.iter().all(|(t, _)| !taken.contains(t)), "second {second}: a list in use was let go"); + if second == 0 { + assert_eq!(gone.len(), (IDLE_MOST.0 - 8).div_ceil(2)); + assert_eq!(gone[0].0, 0, "the oldest go first"); + } + kept = taken; + } + assert_eq!(pool.kept.len(), 8, "what is kept is what was needed lately"); + assert_eq!(pool.bytes, 8); + assert!(pool.kept.iter().all(|(t, _)| kept.contains(t))); + // Nothing needed at all: the pool empties. + for _ in 0..8 { + pool.trim(); + } + assert!(pool.kept.is_empty() && pool.bytes == 0); + } + + /// `LEONIDA_ALLOCATOR_TRIM`'s cut of the oldest idle lists keeps the + /// pool's bytes, and its count of those nobody took, true. + #[cfg(windows)] + #[test] + fn taking_out_the_oldest_keeps_the_pools_counts() { + let mut pool: Pool<u32> = Pool::new(); + for i in 0..6 { + assert_eq!(pool.give(i, 10 + u64::from(i), IDLE_MOST), None); + } + assert!(pool.trim().is_empty()); + // Nobody takes any for a while: the six are all untouched. + let gone = pool.take_oldest(2); + assert_eq!(gone.iter().map(|(t, _)| *t).collect::<Vec<_>>(), [0, 1], "the oldest go first"); + assert_eq!(pool.bytes, 12 + 13 + 14 + 15); + assert_eq!(pool.low, 4, "four untouched ones are left"); + assert!(pool.take_oldest(99).len() == 4 && pool.kept.is_empty() && pool.bytes == 0 && pool.low == 0); + } + + /// A wait a list recorded goes with the list when the title releases it + /// neither submitted nor reset. Where lists are not cut at their waits + /// (`LEONIDA_CUT_WAITS=0`, or waits held list by list) waits are filed + /// by list address: the entry stayed for good, and a list made later at + /// that address took it with its first submission, so a wait for a + /// value nothing writes held that list's queue. + #[test] + fn a_released_lists_waits_go_with_it() { + let null = std::ptr::null(); + let mut allocator = null; + assert_eq!(create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), S_OK); + let new_list = || { + let mut list = null; + assert_eq!(create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list), S_OK); + list + }; + let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); + let list = new_list(); + let at = list as usize; + // Filed as `wait_for` files it where lists are not cut: a wait that + // is never met (comparison 1), on memory that is there (a wait on + // memory that is not counts as met). + let value = Box::new(0u32); + let never = ValueWait { address: std::ptr::from_ref(&*value) as u64, comparison: 1, reference: 0, wide: false }; + VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner()).push((at, never)); + assert_eq!(release(list), 0); + let left = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.0 == at).count(); + // A list made where the released one was (the host's heap hands a + // block of a size out again, not always first), else the address + // alone: the waits a submission of a list there takes. + let mut kept = Vec::new(); + let mut reused = None; + for _ in 0..64 { + let other = new_list(); + if other as usize == at { + reused = Some(other); + break; + } + kept.push(other); + } + if reused.is_none() { + eprintln!("no list was made where the released one was: its address alone is submitted"); + } + let inherited = unmet_waits(&[reused.unwrap_or(list)]).len(); + for other in kept.into_iter().chain(reused) { + assert_eq!(release(other), 0); + } + assert_eq!(release(allocator), 0); + assert_eq!( + (left, inherited), + (0, 0), + "(waits left of the released list, unmet waits a list at its address submits)" + ); + } + /// An offset near `u64::MAX` must not overflow and write outside the /// query destination buffer. #[test] diff --git a/d3d12/crates/leonida-gpu/src/list/thin.rs b/d3d12/crates/leonida-gpu/src/list/thin.rs index ab25e1c2bf..71cc0dda23 100644 --- a/d3d12/crates/leonida-gpu/src/list/thin.rs +++ b/d3d12/crates/leonida-gpu/src/list/thin.rs @@ -83,6 +83,11 @@ impl Front { { recording.abandoned.store(true, Release); } + // Upload memory that only these words name is given back by + // `translate`, which they never reach now: it goes here, or its + // blocks stay taken for good. (Words handed over are always + // translated, also those of a recording let go of.) + free_uploads(&self.words); self.words.clear(); } @@ -804,6 +809,21 @@ extern "system" fn copy_texture_region_x( copy_texture_region(this, dst, x, y, z, src, source_box); } +/// Gives back the upload memory the `UPLOAD` calls of `stream` name, for a +/// stream that is never translated ([`translate`] keeps it for its list). +fn free_uploads(stream: &[u64]) { + let mut i = 0; + while i < stream.len() { + let (op, len) = (stream[i] & 0xffff, (stream[i] >> 16) as usize); + if op == UPLOAD { + // SAFETY: made by `allocate_upload`, named once, in a stream that + // is never translated. + drop(unsafe { Box::from_raw(stream[i + 1] as *mut Upload) }); + } + i += 1 + len; + } +} + /// Makes the calls of a stream on `list`: how many, and whether the last one /// closed it. Once `left` says so only what must not be lost is done. fn translate(list: This, stream: &[u64], left: impl Fn() -> bool) -> (u64, bool) { @@ -1046,6 +1066,30 @@ mod tests { assert_eq!(record(0), [0; RECORD]); } + /// Upload memory that only words not handed over yet name is given back + /// when the list is reset or released before it is closed: those words + /// are never translated, which is where it is given back otherwise. + #[test] + fn uploads_of_words_never_handed_over_are_given_back() { + for released in [false, true] { + let mut f = Front::default(); + f.begin(0, std::ptr::null()); + let mut upload = Upload::new(100).unwrap(); + let start = upload.start() as usize; + // Only what is given back from now on counts: an upload at this + // place before was another one. + let before = held(&crate::upload::GIVEN_BACK).len(); + f.put(UPLOAD, &[Box::into_raw(Box::new(upload)) as u64]); + if released { + drop(f); + } else { + f.begin(0, std::ptr::null()); + } + let given_back = held(&crate::upload::GIVEN_BACK); + assert!(given_back[before..].contains(&start), "released {released}: never given back"); + } + } + /// A recording the line stands with is hurried, once; one translated to /// its end is not. #[test] diff --git a/d3d12/crates/leonida-gpu/src/memory.rs b/d3d12/crates/leonida-gpu/src/memory.rs index 223f760ce3..228eb01aff 100644 --- a/d3d12/crates/leonida-gpu/src/memory.rs +++ b/d3d12/crates/leonida-gpu/src/memory.rs @@ -18,7 +18,8 @@ //! in it; one for all lists, entries only ever go from empty to filled. //! The CPU writes it in memory of its own and shaders read a copy of that //! on the card, brought up to date as title memory is (over the bus, every -//! step of every ray waited for it); +//! step of every ray waited for it), or, with `crate::inplace::ours`, by +//! the entries written ([`Memory::sent`]); //! - per view heap a run of slots with a raw unordered access view of each //! numbered copy (slot 0 of the run: a null view, for pages without a //! copy); @@ -234,7 +235,20 @@ impl Memory { let bytes = u64::from(MEMORY_PAGES) * 8; // Zeroed, and watched for writes as the title's memory is. let entries = crate::upload::reserve(bytes as usize)?; - let directory = crate::shadow::by_address(entries as u64, bytes)?; + // Memory of ours with one writer, under the mutex + // (`crate::inplace::ours`): its copy's CPU side is the directory + // itself where the host opens it, and what is written in it is resent + // ([`Memory::sent`]); else a buffer of 16 MiB beside it, which every + // list's refresh compares with it. + let directory = if crate::inplace::ours() { + crate::shadow::by_address_opened(entries as u64, bytes)? + } else { + crate::shadow::by_address(entries as u64, bytes)? + }; + if directory.side_is_memory() { + // All of it once, as a new copy's first refresh sends it. + directory.resend(0, bytes as usize); + } crate::host::name(&directory.buffer, || "title memory by address: directory".into()); let (faults, data) = host.shared_buffer(u64::from(MEMORY_FAULTS) * 4)?; crate::host::name(&faults, || "title memory by address: faults".into()); @@ -277,6 +291,17 @@ impl Memory { unsafe { self.directory.0.add(page as usize * 2) } } + /// The entries of pages `[first, end)` were written: with the directory + /// its copy's CPU side ([`Shadow::side_is_memory`]) nothing compares it, + /// so they go up before the next submission as they are now. + fn sent(&self, first: u64, end: u64) { + if let Some((from, to)) = entry_bytes(first, end) + && self.directory.1.side_is_memory() + { + self.directory.1.resend(from, to); + } + } + /// The place in `copies` of the copy that holds `page`, if one does. fn copy_of(&self, page: u64) -> Option<usize> { if page >= u64::from(MEMORY_PAGES) { @@ -321,6 +346,9 @@ impl Memory { if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { return None; } + // Held for good: not to be put out of the tables for title memory + // in place while shaders are shown this one (`crate::shadow::in_place_switch`). + shadow.note_numbered(); self.copies.push(shadow); let n = self.copies.len() - 1; self.numbers.insert(key, n); @@ -355,14 +383,16 @@ impl Memory { let entry = self.entry(at / PAGE); // SAFETY: an entry of the directory. if unsafe { entry.read() } == 0 { - close(entry, n, at - first); + close(entry, n, shadow.offset(at)); } at += PAGE; } + self.sent(first.div_ceil(PAGE), at / PAGE); } // SAFETY: as above. if unsafe { self.entry(page).read() } == 0 { - close(self.entry(page), n, start - shadow.span().0); + close(self.entry(page), n, shadow.offset(start)); + self.sent(page, page + 1); } return true; } @@ -374,6 +404,7 @@ impl Memory { { self.windows += 1; fill(self.entry(page), n, 0); + self.sent(page, page + 1); return true; } return false; @@ -402,9 +433,16 @@ impl Memory { let Some(at) = crate::upload::reserve(ARENA as usize) else { return false; }; - let Some(n) = crate::shadow::by_address(at as u64, ARENA).and_then(|s| self.number(s)) else { + // Its copy's CPU side is the arena itself where the host opens it: + // what changes in it goes up as `bring` and `take` find it. + let Some(n) = crate::shadow::by_address_opened(at as u64, ARENA).and_then(|s| self.number(s)) else { return false; }; + if self.copies[n].side_is_memory() { + // All of it goes up once, as a new copy's first refresh sends it. + // (Once it is numbered: a copy refused here is dropped.) + self.copies[n].resend(0, ARENA as usize); + } self.arenas.push((n, at)); // The lowest first. self.free.extend((0..(ARENA / PAGE) as usize).rev().map(|i| (n, at + i * PAGE as usize))); @@ -415,7 +453,8 @@ impl Memory { fn hold(&mut self, page: u64, at: usize, copy: usize) { self.pages.insert(page, Held { at, copy, taken: 0, looked: u64::MAX, born: self.frame, owners: 0, theirs: false }); self.order.push(page); - fill(self.entry(page), copy, at as u64 - self.copies[copy].span().0); + fill(self.entry(page), copy, self.copies[copy].offset(at as u64)); + self.sent(page, page + 1); } /// The packed structure at `address` is gone: the pages it alone had are @@ -430,6 +469,7 @@ impl Memory { self.pages.remove(&page); // SAFETY: an entry of the directory, under the mutex. unsafe { self.entry(page).write_volatile(0) }; + self.sent(page, page + 1); } } self.stats.gone += 1; @@ -491,9 +531,10 @@ impl Memory { ); for page in first.div_ceil(PAGE)..(first + len) / PAGE { if self.copy_of(page) == Some(n) { - fill(self.entry(page), n, page * PAGE - first); + fill(self.entry(page), n, self.copies[n].offset(page * PAGE)); } } + self.sent(first.div_ceil(PAGE), (first + len) / PAGE); } /// [`Memory::map`] of the pages of `[address, address + len)`, up to the @@ -538,6 +579,9 @@ impl Memory { let never = std::mem::replace(&mut held.taken, now.max(1)) == 0; let shadow = &self.copies[held.copy]; let base = held.at - shadow.span().0 as usize; + // Of an arena that is its copy's CPU side the dwords that + // changed go up as they are found here: nothing compares it. + let mut changed = Vec::new(); let mut title = [0u8; PIECE]; for piece in (0..PAGE as usize).step_by(PIECE) { let from = (page * PAGE) as usize + piece; @@ -545,10 +589,16 @@ impl Memory { crate::host::copy_mapped(title.as_mut_ptr(), from as *const u8, PIECE, false); // SAFETY: a page of an arena of ours, under the mutex. let ours = unsafe { std::slice::from_raw_parts_mut((held.at + piece) as *mut u8, PIECE) }; - self.stats.changed += merge(&title, ours, never) as u64 * 4; + let runs = merge(&title, ours, never); + self.stats.changed += runs.iter().map(|r| r.1 as u64).sum::<u64>(); + if shadow.side_is_memory() && !never { + changed.extend(runs.into_iter().map(|(at, n)| (base + piece + at, base + piece + at + n))); + } } if never { shadow.resend(base, base + PAGE as usize); + } else if !changed.is_empty() { + shadow.resend_runs(changed.into_iter()); } } self.stats.micros += started.elapsed().as_micros() as u64; @@ -663,6 +713,9 @@ impl Memory { let Some(held) = self.pages.get(&page) else { return }; let shadow = &self.copies[held.copy]; let base = held.at - shadow.span().0 as usize; + // (As in `bring`: of an arena that is its copy's CPU side the dwords + // that changed go up from here.) + let mut changed = Vec::new(); let mut title = [0u8; PIECE]; let mut at = from; while at < to { @@ -670,14 +723,28 @@ impl Memory { crate::host::copy_mapped(title.as_mut_ptr(), (page as usize * PAGE as usize + at) as *const u8, n, false); // SAFETY: a page of an arena of ours, under the mutex. let ours = unsafe { std::slice::from_raw_parts_mut((held.at + at) as *mut u8, n) }; - if *ours != title[..n] { + if shadow.side_is_memory() && !whole { + // Only here do the dwords that changed matter: they are what + // goes up. Found 32 bytes at a time, as a refresh finds them + // (this runs at a submission). + let runs = crate::shadow::word_runs_put(held.at + at, &title[..n], ours); + changed.extend(runs.into_iter().map(|(a, len)| (base + at + a, base + at + a + len))); + } else if *ours != title[..n] { + // Sent whole, or compared at the next refresh: what differs + // is not needed here. ours.copy_from_slice(&title[..n]); - crate::watch::wrote(held.at + at, n); + // (Nothing asks the write watch about an arena that is its + // copy's CPU side.) + if !shadow.side_is_memory() { + crate::watch::wrote(held.at + at, n); + } } at += n; } if whole { shadow.resend(base + from, base + to); + } else if !changed.is_empty() { + shadow.resend_runs(changed.into_iter()); } } @@ -873,6 +940,31 @@ fn close(entry: *mut u32, n: usize, offset: u64) { fill(entry, n | MEMORY_READ_ONLY as usize, offset); } +/// The bytes of `shadow`'s buffer its raw view shows, from its first byte: +/// to the copy's end. The directory gives a page's offset in the buffer +/// ([`Shadow::offset`]), which for title memory in place counts the bytes +/// before the title memory's first (a heap is opened on whole 64 KiB pages, +/// a title buffer need not begin on one: `crate::inplace::Placed::bias`). +/// Counted from the title memory's first byte (as before), a shader's +/// address reached the buffer that many bytes early, and the structure +/// builder's stores landed there in the title's own memory. +fn viewed(shadow: &Shadow) -> u64 { + let (start, len) = shadow.span(); + shadow.offset(start + len) +} + +/// The directory's bytes `[from, to)` that hold the entries of pages +/// `[first, end)`, cut to the directory; `None` if none of them is in it. +/// A numbered copy may reach past the directory's 2^37 bytes of title +/// address space (title memory goes up to 2^40): [`Memory::opens`] names +/// all of its pages, and a range past the directory's end would be a copy +/// out of its buffer at the next submission (`crate::host` records the +/// sends unchecked), which can remove the device. +fn entry_bytes(first: u64, end: u64) -> Option<(usize, usize)> { + let end = end.min(u64::from(MEMORY_PAGES)); + (first < end).then(|| (first as usize * 8, end as usize * 8)) +} + /// The offset first: a shader that sees the number sees it too. fn fill(entry: *mut u32, n: usize, offset: u64) { // SAFETY: an entry of the directory, under the mutex. @@ -894,24 +986,28 @@ fn packed_len(header: u64) -> Option<u64> { (version & 0xFFFF == 6 && marks & 0x8100 == 0x8100 && nodes > 0 && len <= PACKED).then_some(len) } -/// Puts what `title` holds into `ours` (what was last taken): the dwords that -/// differ. How many. -fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> usize { +/// Puts what `title` holds into `ours` (what was last taken; as long as +/// `title`): the dwords that differ, all of it if `never`. The runs that +/// changed, as (offset, bytes) in order. +fn merge(title: &[u8], ours: &mut [u8], never: bool) -> Vec<(usize, usize)> { if never { ours.copy_from_slice(title); - return PIECE / 4; + return if title.is_empty() { Vec::new() } else { vec![(0, title.len())] }; } if ours == title { - return 0; + return Vec::new(); } - let mut changed = 0; - for (t, o) in title.chunks_exact(4).zip(ours.chunks_exact_mut(4)) { + let mut runs: Vec<(usize, usize)> = Vec::new(); + for (i, (t, o)) in title.chunks(4).zip(ours.chunks_mut(4)).enumerate() { if t != o { o.copy_from_slice(t); - changed += 1; + match runs.last_mut() { + Some((at, n)) if *at + *n == i * 4 => *n += t.len(), + _ => runs.push((i * 4, t.len())), + } } } - changed + runs } /// Before a draw whose shader reads title memory by address: what its @@ -1065,8 +1161,7 @@ pub(crate) fn ready( } }; for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) { - let (_, len) = shadow.span(); - heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len); + heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, viewed(shadow)); } m.heaps.insert(key, (base, m.copies.len() as u32)); // Every copy by every list that has come to by-address memory, whoever @@ -1307,15 +1402,296 @@ mod tests { fn a_piece_takes_what_changed() { let mut title = [7u8; PIECE]; let mut ours = vec![0u8; PIECE]; - assert_eq!(merge(&title, &mut ours, true), PIECE / 4); + assert_eq!(merge(&title, &mut ours, true), [(0, PIECE)]); assert_eq!(ours, title); - assert_eq!(merge(&title, &mut ours, false), 0); + assert_eq!(merge(&title, &mut ours, false), []); // A dword of it. title[41] = 8; - assert_eq!(merge(&title, &mut ours, false), 1); + assert_eq!(merge(&title, &mut ours, false), [(40, 4)]); + assert_eq!(ours, title); + // Dwords side by side are one run, and the runs are in order. + title[4..12].fill(9); + title[100] = 9; + assert_eq!(merge(&title, &mut ours, false), [(4, 8), (100, 4)]); assert_eq!(ours, title); } + /// The process's commit charge (its private bytes). + fn commit() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, ..Default::default() }; + // SAFETY: our own process and a sized structure. + let read = unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + // (Failed, every reading would be 0 and nothing measured.) + assert_ne!(read, 0, "the process's memory counters"); + c.PagefileUsage as u64 + } + + /// The tests here that make arenas, one at a time: what one makes is + /// not counted in another's commit. + fn arenas_turn() -> std::sync::MutexGuard<'static, ()> { + static TURN: Mutex<()> = Mutex::new(()); + TURN.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// An arena is in the PC's memory once: the CPU's side of its copy on + /// the card is the arena itself, not a second buffer of its size with + /// the same bytes (64 MiB more commit per arena, and the structure + /// builder keeps up to 48). On the host's card, as the other tests that + /// need one. + #[test] + fn an_arena_is_in_the_pcs_memory_once() { + let Some(host) = host() else { return }; + if !crate::shadow::cards() || !host.card_ready() { + return; + } + // A host that does not open memory as a heap of its own (no + // ID3D12Device13, or a driver that refuses) keeps the CPU's side a + // buffer of its own, as designed. (The block is never let go: the + // heap lets go of its pages a moment after its last reference.) + let block = crate::upload::reserve(1 << 16).expect("a block"); + if let Err(e) = crate::inplace::place_part(&host.device, block as u64, 1 << 16) { + eprintln!("memory is not opened as a heap here ({e:?}): an arena's copy keeps a CPU side of its own"); + return; + } + let _turn = arenas_turn(); + // Three times each, as other tests make and free memory meanwhile. + // First what the copy's side on the card costs by itself (some + // drivers charge the process for the card's memory too: 64 MiB on an + // AMD RX 7900 XT): the most of three, all kept until the end, as the + // driver hands memory let go of out again without a charge. + let mut cards = Vec::new(); + let mut card = 0; + for _ in 0..3 { + let before = commit(); + cards.push(host.uav_buffer(ARENA).expect("a buffer on the card")); + card = card.max(commit().saturating_sub(before)); + } + // Then an arena, the least of three. + let mut m = Memory::new().expect("title memory by address"); + let mut sides = Vec::new(); + let mut grew = u64::MAX; + for _ in 0..3 { + let before = commit(); + assert!(m.another(), "an arena"); + grew = grew.min(commit().saturating_sub(before)); + let &(n, at) = m.arenas.last().expect("an arena"); + sides.push((at, m.copies[n].card_data() as usize)); + } + eprintln!( + "an arena of {} MiB: {} MiB more commit, its side on the card {} MiB; (arena, CPU side): {sides:x?}", + ARENA >> 20, + grew >> 20, + card >> 20 + ); + for (at, side) in sides { + assert_eq!(side, at, "the CPU's side of the arena's copy is the arena itself"); + } + assert!( + grew < card + ARENA + ARENA / 2, + "an arena of {} MiB took {} MiB of commit beside its side on the card", + ARENA >> 20, + grew.saturating_sub(card) >> 20 + ); + } + + /// With `crate::inplace::ours` (`LEONIDA_INPLACE` on) the directory is + /// its copy's CPU side itself, not a buffer of 16 MiB beside it with the + /// same bytes: nothing is copied into that side at submission, and an + /// entry written goes up as it is ([`Memory::sent`]). On the host's card. + #[test] + fn the_directory_is_its_copys_cpu_side_and_sends_the_entries_written() { + let Some(host) = host() else { return }; + if !crate::shadow::cards() || !host.card_ready() { + return; + } + // (As `an_arena_is_in_the_pcs_memory_once`: a host that does not open + // memory keeps a side of its own, as designed.) + let block = crate::upload::reserve(1 << 16).expect("a block"); + if let Err(e) = crate::inplace::place_part(&host.device, block as u64, 1 << 16) { + eprintln!("memory is not opened as a heap here ({e:?}): the directory's copy keeps a CPU side of its own"); + return; + } + let _turn = arenas_turn(); + let _asked = crate::shadow::in_place_tests::Asked::new(1, false); + let mut m = Memory::new().expect("title memory by address"); + let directory = m.directory.1.clone(); + let bytes = MEMORY_PAGES as usize * 8; + assert!(directory.side_is_memory(), "the directory is its copy's CPU side"); + assert_eq!(directory.card_data() as usize, m.directory.0 as usize); + assert!(m.another(), "an arena"); + let (aside, data) = host.shared_buffer(PAGE).expect("a buffer"); + // A list that brings every copy up to date when it is submitted, as + // a list that reads memory by address does. + let run = |m: &Memory, record: &dyn Fn(&ID3D12GraphicsCommandList)| { + let list = host.new_list().expect("a host list"); + m.bring_up(&list); + record(&list.list); + list.close(); + host.execute(&[&list]); + }; + // The whole directory goes up once, as it is now. + run(&m, &|_| {}); + let page = 0x4_2345; + let (copy, at) = m.free.pop().expect("a free page"); + m.hold(page, at, copy); + assert_eq!(directory.update(m.directory.0 as usize, bytes), 0, "nothing is copied into the CPU's side"); + // SAFETY: an open list; live buffers, the ranges inside them. + run(&m, &|list| unsafe { list.CopyBufferRegion(&aside, 0, &directory.buffer, page * 8, 8) }); + // SAFETY: the mapping and the entry, 8 bytes each; `execute` waited + // for the copy. + let (got, entry) = unsafe { (std::slice::from_raw_parts(data.cast::<u32>().cast_const(), 2), std::slice::from_raw_parts(m.entry(page).cast_const(), 2)) }; + assert_eq!(entry[0] as usize, copy + 1, "the page's copy is numbered in the entry"); + assert_eq!(got, entry, "the entry written went up to the card's side"); + } + + /// A title buffer in place (`crate::inplace`, level 2) that does not + /// begin on a 64 KiB line is found by address where its bytes are: the + /// directory gives a page's offset in the buffer counting the bytes the + /// heap has before the buffer's first ([`Shadow::offset`]), and its raw + /// view reaches the copy's end ([`viewed`]); the card reads the title's + /// bytes there, and what it stores there is in the title's memory at that + /// address. Before, the offset was counted from the title buffer's first + /// byte: a shader's address reached the title memory 0x100 bytes early, + /// and the structure builder's stores landed there. On the host's card. + #[test] + fn a_title_buffer_in_place_off_a_64_kib_line_is_found_by_address() { + let Some(host) = host() else { return }; + if !crate::shadow::cards() || !host.card_ready() { + return; + } + let block = crate::upload::reserve(3 * PAGE as usize).expect("title memory"); + if let Err(e) = crate::inplace::place_part(&host.device, block as u64, PAGE) { + eprintln!("memory is not opened as a heap here ({e:?}): nothing is in place"); + return; + } + let _turn = arenas_turn(); + let _asked = crate::shadow::in_place_tests::Asked::new(2, true); + // To the end of the page after: the raw view must reach 0x100 bytes + // past the title buffer's length. + let (start, len) = (block + 0x100, 2 * PAGE as usize - 0x100); + // SAFETY: the test's own memory. + let words = unsafe { std::slice::from_raw_parts_mut(start as *mut u32, len / 4) }; + for (i, word) in words.iter_mut().enumerate() { + *word = 0x5a00_0000 | i as u32; + } + crate::shadow::register(start, start as u64, len as u64); + let mut m = Memory::new().expect("title memory by address"); + // The one page the buffer holds whole. + let page = (block as u64 + PAGE) / PAGE; + let mapped = m.map(page); + crate::shadow::unregister(start, start as u64); + assert!(mapped, "the page is the title buffer's"); + let shadow = m.copies[m.copy_of(page).expect("numbered")].clone(); + assert!(shadow.in_place(), "the title buffer is in place"); + assert_eq!(shadow.offset(start as u64), 0x100, "its buffer begins on the 64 KiB line before it"); + // SAFETY: the page's entry, two dwords. + let offset = u64::from(unsafe { m.entry(page).add(1).read() }); + assert_eq!(offset, shadow.offset(page * PAGE), "the page's offset in the buffer"); + assert!(offset + PAGE <= viewed(&shadow), "the raw view reaches the page's end"); + let mut rig = crate::inplace::Rig::new(&host.device).expect("a queue of the test's own"); + let got = rig.fetch(&shadow.buffer, offset + 8, 4).expect("the card's copy"); + assert_eq!(got, (0x5a00_0000u32 | (0xff00 / 4 + 2)).to_le_bytes(), "the card reads the title's dword at the page's byte 8"); + rig.store(&shadow.buffer, offset + 12, &0xb11du32.to_le_bytes()).expect("the card's store"); + // SAFETY: the test's own memory; the store has run. + let (stored, before) = unsafe { (((page * PAGE) as *const u32).add(3).read(), ((page * PAGE) as *const u32).sub(61).read()) }; + assert_eq!(stored, 0xb11d, "the card's store is in the title's memory at the page's byte 12"); + assert_eq!(before, 0x5a00_0000 | (0xff00 / 4 - 61), "and not 0x100 bytes before it"); + drop(shadow); + drop(m); + crate::shadow::in_place_tests::give_back(block); + } + + /// What the title changed in a page of an arena goes up by the dword, + /// and what the card's side holds beside it stays (the structure + /// builder's work is only there): with the arena as its copy's CPU side + /// nothing compares the two, so `bring` says what it changed. On the + /// host's card. + #[test] + fn an_arena_sends_up_only_the_dwords_the_title_changed() { + let Some(host) = host() else { return }; + if !crate::shadow::cards() || !host.card_ready() { + return; + } + let _turn = arenas_turn(); + let mut m = Memory::new().expect("title memory by address"); + assert!(m.another(), "an arena"); + // A page of title memory of the test's own, where the directory + // reaches. + let title = crate::upload::reserve(PAGE as usize).expect("a page"); + // SAFETY: the test's own page, never let go. + let words = unsafe { std::slice::from_raw_parts_mut(title as *mut u32, PAGE as usize / 4) }; + for (i, word) in words.iter_mut().enumerate() { + *word = i as u32; + } + let page = title as u64 / PAGE; + let (copy, at) = m.free.pop().expect("a free page"); + m.hold(page, at, copy); + let shadow = m.copies[copy].clone(); + let offset = at as u64 - shadow.span().0; + // Taken whole the first time. + m.frame = 1; + m.bring(page, page + 1); + let (aside, data) = host.shared_buffer(PAGE).expect("a buffer"); + // A list that brings every copy up to date when it is submitted, as + // a list that reads memory by address does. + let run = |m: &Memory, record: &dyn Fn(&ID3D12GraphicsCommandList)| { + let list = host.new_list().expect("a host list"); + m.bring_up(&list); + record(&list.list); + list.close(); + host.execute(&[&list]); + }; + // A store on the card's side alone, as the builder's: dword 10. + // SAFETY: the mapping of the buffer just made. + unsafe { data.cast::<u32>().write(0xb11d) }; + // SAFETY: an open list; live buffers, the ranges inside them. + run(&m, &|list| unsafe { list.CopyBufferRegion(&shadow.buffer, offset + 40, &aside, 0, 4) }); + // The title changes dword 20, and the page is taken again. + words[20] = 0x7171; + m.frame = 2; + m.bring(page, page + 1); + // SAFETY: as above. + run(&m, &|list| unsafe { list.CopyBufferRegion(&aside, 0, &shadow.buffer, offset, PAGE) }); + // SAFETY: the mapping; `execute` waited for the copy. + let got = unsafe { std::slice::from_raw_parts(data.cast::<u32>().cast_const(), PAGE as usize / 4) }; + assert_eq!(got[20], 0x7171, "the dword the title changed went up"); + assert_eq!(got[10], 0xb11d, "the card's own dword stayed"); + assert_eq!(&got[..10], &words[..10], "the page went up whole the first time"); + assert_eq!(&got[21..], &words[21..]); + // The same of a page taken at a submission (`land`, of a page not + // in a packed structure): dword 11 on the card's side alone, dword + // 30 changed by the title. + // SAFETY: the mapping, which no copy uses now. + unsafe { data.cast::<u32>().write(0xb11e) }; + // SAFETY: as above. + run(&m, &|list| unsafe { list.CopyBufferRegion(&shadow.buffer, offset + 44, &aside, 0, 4) }); + words[30] = 0x7172; + m.take(page, 0, PAGE as usize, false); + // SAFETY: as above. + run(&m, &|list| unsafe { list.CopyBufferRegion(&aside, 0, &shadow.buffer, offset, PAGE) }); + // SAFETY: as above. + let got = unsafe { std::slice::from_raw_parts(data.cast::<u32>().cast_const(), PAGE as usize / 4) }; + assert_eq!(got[30], 0x7172, "the dword the title changed went up from `take`"); + assert_eq!((got[10], got[11]), (0xb11d, 0xb11e), "the card's own dwords stayed"); + assert_eq!(got[20], 0x7171); + } + + /// The entries a writer sends up stay in the directory: a copy that + /// reaches past its 2^37 bytes of title address space sends the entries + /// of its pages inside it, and one wholly past it sends none. Before, + /// [`Memory::opens`]'s pages past the end went to the next submission as + /// a copy out of the directory's buffer. + #[test] + fn the_entries_sent_stay_in_the_directory() { + let last = u64::from(MEMORY_PAGES); + assert_eq!(entry_bytes(5, 7), Some((40, 56))); + assert_eq!(entry_bytes(last - 2, last + 30), Some((MEMORY_PAGES as usize * 8 - 16, MEMORY_PAGES as usize * 8))); + assert_eq!(entry_bytes(last + 1, last + 30), None); + assert_eq!(entry_bytes(7, 7), None); + } + #[test] fn a_packed_structure_is_known_by_its_header() { let header = |version: u32, nodes: u32| u64::from(version) | u64::from(nodes) << 32; diff --git a/d3d12/crates/leonida-gpu/src/object.rs b/d3d12/crates/leonida-gpu/src/object.rs index 8253bfbdaf..6f111b86e0 100644 --- a/d3d12/crates/leonida-gpu/src/object.rs +++ b/d3d12/crates/leonida-gpu/src/object.rs @@ -80,6 +80,14 @@ pub(crate) fn add_ref_alive(this: This) -> bool { refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n > 0).then(|| n + 1)).is_ok() } +/// How many references an object has now (for who may drop the last one: +/// `crate::resource`'s eviction of placed textures). +#[cfg(windows)] +pub(crate) fn references(this: This) -> u32 { + // SAFETY: `this` is one of our objects, not freed yet. + unsafe { &*this }.refs.load(Ordering::Acquire) +} + pub(crate) extern "system" fn release(this: This) -> u32 { // SAFETY: `this` is one of our objects. let refs = &unsafe { &*this }.refs; diff --git a/d3d12/crates/leonida-gpu/src/picked.rs b/d3d12/crates/leonida-gpu/src/picked.rs index cbb54549db..87fd981efa 100644 --- a/d3d12/crates/leonida-gpu/src/picked.rs +++ b/d3d12/crates/leonida-gpu/src/picked.rs @@ -147,6 +147,8 @@ fn ask(shader: Arc<crate::pipeline::Shader>) { if let Some(t) = shader.translated() { t.picks.store(if yes { YES } else { NO }, Relaxed); } + // Its container was kept for this answer (`Shader::translated`). + shader.let_container_go(); } }); Mutex::new(send) diff --git a/d3d12/crates/leonida-gpu/src/pipeline.rs b/d3d12/crates/leonida-gpu/src/pipeline.rs index f8a7652f65..89ac6af661 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline.rs @@ -7,7 +7,7 @@ //! The title creates some 60,000 pipelines in its first 20 //! seconds and draws with a few dozen (decision 0007, step 3). Shader //! containers are shared by content hash and translated once, on first -//! use (decision 0003). +//! use (decision 0003); a translated shader lets its container go. //! //! shortcut: only vertex plus pixel pipelines from streams and compute //! pipelines get host pipelines; mesh, tessellation and geometry stages, @@ -60,11 +60,24 @@ pub(crate) struct Shader { pub(crate) stage: &'static str, /// The first 8 bytes of its BLAKE3, as logged. pub(crate) hash: String, - container: Vec<u8>, + /// Its whole BLAKE3 (its key in [`SHADERS`]) and its size, which stay + /// when the container goes. + full: [u8; 32], + size: usize, + /// The container, until the shader is translated ([`Shader::translated`]). + /// The title passes one for each of its programs, and only a minority is + /// ever translated, but a translated one has every later read of its + /// container answered apart: the program's name and whether its samplers + /// are made linear in [`Translated`], what pipeline creation asks in + /// [`Facts`]. Readers take a reference, so that one that still reads it + /// (a translation, the pipeline book) does not hold the others up. + container: Mutex<Option<Arc<[u8]>>>, /// Its part in the stand-in for the indirect light. #[cfg(windows)] pub(crate) ambient: Option<crate::ambient::Role>, #[cfg(windows)] + facts: OnceLock<Facts>, + #[cfg(windows)] translated: OnceLock<Option<Translated>>, /// A pixel shader translated for draws under the console's sample mask, in this form /// ([`Shader::masked`]); `None` for the title's own. Its hash is the title's shader's: what @@ -76,6 +89,19 @@ pub(crate) struct Shader { masked_twins: Mutex<Vec<Arc<Shader>>>, } +/// What creating a pipeline asks of the containers of its shaders. It is +/// answered once per shader, at the first creation or at the latest when the +/// container goes ([`Shader::translated`]): a pipeline created afterwards +/// from the same bytes gets the shader, which no longer has its container. +#[cfg(windows)] +struct Facts { + /// A program of the ray-tracing structure builder ([`of_builder`]). + builder: bool, + /// Which of the programs `make` may leave out by name it is, a bit for + /// each of `make::NAMES`. + named: u8, +} + impl std::fmt::Debug for Shader { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} {}", self.stage, self.hash)?; @@ -91,7 +117,8 @@ impl std::fmt::Debug for Shader { static SHADERS: Mutex<Option<HashMap<[u8; 32], Arc<Shader>>>> = Mutex::new(None); /// For the memory lines: containers kept and their bytes, translations -/// kept and the bytes of their host code. None of them is ever let go. +/// kept and the bytes of their host code. A container is let go when its +/// shader is translated ([`Shader::translated`]); a translation never is. static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; /// What the shader table and the pipeline library keep in memory: @@ -143,10 +170,14 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> { Arc::new(Shader { stage, hash: full.to_hex()[..16].to_owned(), - container: bytes.to_vec(), + full: *full.as_bytes(), + size: bytes.len(), + container: Mutex::new(Some(bytes.into())), #[cfg(windows)] ambient: (stage == "compute").then(|| crate::ambient::role(bytes)).flatten(), #[cfg(windows)] + facts: OnceLock::new(), + #[cfg(windows)] translated: OnceLock::new(), #[cfg(windows)] mask: None, @@ -157,6 +188,44 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> { .clone() } +impl Shader { + /// The container, while the shader keeps it. + #[cfg_attr(not(windows), allow(dead_code))] + fn container(&self) -> Option<Arc<[u8]>> { + let kept = self.container.lock().unwrap_or_else(|e| e.into_inner()); + kept.clone() + } + + /// Lets the container go: what is read of it later is kept apart. + #[cfg(windows)] + pub(crate) fn let_container_go(&self) { + use std::sync::atomic::Ordering::Relaxed; + let mut kept = self.container.lock().unwrap_or_else(|e| e.into_inner()); + // A masked twin's container is its title shader's, counted once there. + if kept.take().is_some() && self.mask.is_none() { + KEPT[0].fetch_sub(1, Relaxed); + KEPT[1].fetch_sub(self.size as u64, Relaxed); + } + } + + /// What creating a pipeline asks of the container ([`Facts`]). + #[cfg(windows)] + fn facts(&self) -> &Facts { + self.facts.get_or_init(|| { + let Some(container) = self.container().filter(|_| self.stage == "compute") else { + return Facts { + builder: false, + named: 0, + }; + }; + Facts { + builder: spilled(&container), + named: make::names(&container), + } + }) + } +} + /// A translated shader and the console resources its code reads. #[cfg(windows)] pub(crate) struct Translated { @@ -181,6 +250,11 @@ pub(crate) struct Translated { /// A compute program translated to run several console groups to a host group /// (`LEONIDA_GROUP_PACK`): where its console grid goes (`crate::draw::pack_of`). pub(crate) pack: Option<crate::draw::PackWords>, + /// The program's own name in its container ([`program_name`]), for the + /// logs of a refused host pipeline after the container has gone. + pub(crate) program: Option<String>, + /// Whether its immediate samplers filter linearly (`host::linear_samplers`). + pub(crate) linear_samplers: bool, /// Whether a bound packed program was logged (`crate::draw::pack_of`). pub(crate) pack_logged: std::sync::atomic::AtomicBool, /// Whether it stores through a view it picks from the heap by an index, @@ -194,11 +268,14 @@ pub(crate) struct Translated { #[cfg(windows)] impl Shader { /// The translation, made on first use; a shader that does not - /// translate is logged once. + /// translate is logged once. A shader that translates lets its container + /// go then. pub(crate) fn translated(&self) -> Option<&Translated> { self.translated .get_or_init(|| { - let done = translate(&self.container, self.mask); + // Still here: it goes below, once, after the translation. + let container = self.container()?; + let done = translate(&container, &self.hash, self.mask); // `LEONIDA_SHADER_SAVE=<dir>`: each shader as the title gave it (`.cdxil`) and as // translated (`.dxil`), by the hash crash reports name it with if let Some(dir) = std::env::var_os("LEONIDA_SHADER_SAVE") { @@ -210,7 +287,7 @@ impl Shader { None => String::new(), }; let stem = format!("{}.{}{masked}", self.hash, self.stage); - let _ = std::fs::write(dir.join(format!("{stem}.cdxil")), &self.container); + let _ = std::fs::write(dir.join(format!("{stem}.cdxil")), &*container); if let Ok(t) = &done { let _ = std::fs::write(dir.join(format!("{stem}.dxil")), &t.host.dxil); } @@ -240,6 +317,20 @@ impl Shader { "shader does not translate; its pipelines' draws are dropped" ), } + // Nothing translates it again, and what is read of the container from here on + // was kept above or is in its facts, so the container goes. Not while + // `crate::picked` may still read the programs of a shader that stores: it lets + // the container go when it has its answer. Not for the title's own pixel + // shaders either: a draw under the sample mask makes a masked twin of one + // ([`Shader::masked`]) only once its pipeline is made, and the twin is + // translated from the same container. A twin, translated, lets its copy go. + if let Ok(t) = &done { + self.facts(); + let twins_later = self.stage == "pixel" && self.mask.is_none(); + if !(t.stores && crate::picked::on()) && !twins_later { + self.let_container_go(); + } + } done.ok() }) .as_ref() @@ -264,8 +355,11 @@ impl Shader { let twin = Arc::new(Shader { stage: self.stage, hash: self.hash.clone(), - container: self.container.clone(), + full: self.full, + size: self.size, + container: Mutex::new(self.container()), ambient: None, + facts: OnceLock::new(), translated: OnceLock::new(), mask: Some(mask), masked_twins: Mutex::new(Vec::new()), @@ -274,17 +368,20 @@ impl Shader { twin } - /// The console programs of the container; `None` if they are not known. + /// The console programs of the container; `None` if they are not known, + /// or if the container has gone ([`Shader::translated`] keeps it for + /// `crate::picked`, the one caller). pub(crate) fn programs(&self) -> Option<Vec<leonida_shader::NativeProgram>> { use leonida_shader::{Container, FourCC}; - let c = Container::parse(&self.container).ok()?; + let container = self.container()?; + let c = Container::parse(&container).ok()?; let part = c.part(FourCC::DXIL).or(c.part(FourCC::ACCC))?; leonida_shader::native_programs(part.data).ok() } } #[cfg(windows)] -fn translate(container: &[u8], mask: Option<leonida_shader::emit::PixelMask>) -> Result<Translated, String> { +fn translate(container: &[u8], hash: &str, mask: Option<leonida_shader::emit::PixelMask>) -> Result<Translated, String> { use leonida_shader::{Container, FourCC, HwStage}; // The translation depends on it (a view index past a capped heap). crate::descriptor::host::probe_view_limit(); @@ -332,6 +429,8 @@ fn translate(container: &[u8], mask: Option<leonida_shader::emit::PixelMask>) -> stores_past_views, writes, pack, + program: program_name(container), + linear_samplers: crate::pipeline::host::linear_samplers(hash, container), pack_logged: Default::default(), picks: Default::default(), bound: Default::default(), @@ -383,12 +482,16 @@ static BUILDER: Mutex<Builder> = Mutex::new(Builder { /// Whether `shaders` are a pipeline of the structure builder. #[cfg(windows)] fn of_builder(shaders: &[Arc<Shader>]) -> bool { - use leonida_shader::{Container, FourCC}; let [shader] = shaders else { return false }; - if shader.stage != "compute" { - return false; - } - let Ok(c) = Container::parse(&shader.container) else { + shader.facts().builder +} + +/// Whether a compute container has a program with a spilled user-data table, +/// as the structure builder's programs do ([`Facts::builder`]). +#[cfg(windows)] +fn spilled(container: &[u8]) -> bool { + use leonida_shader::{Container, FourCC}; + let Ok(c) = Container::parse(container) else { return false; }; c.part(FourCC::DXIL) @@ -752,7 +855,7 @@ pub(crate) fn bound(this: This) { } let frame = crate::frame::current(); for shader in &p.shaders { - tracing::info!(pipeline = ?this, frame, stage = shader.stage, size = shader.container.len(), hash = %shader.hash, "first bind"); + tracing::info!(pipeline = ?this, frame, stage = shader.stage, size = shader.size, hash = %shader.hash, "first bind"); } } @@ -1386,7 +1489,7 @@ mod tests { pipeline(p) .shaders .iter() - .map(|s| (s.stage, s.container.clone())) + .map(|s| (s.stage, s.container().expect("not translated").to_vec())) .collect() } @@ -1432,13 +1535,113 @@ mod tests { assert_eq!(slot::<extern "system" fn(This) -> u32>(p, 0x10)(p), 0); } + /// The bytes of its container that a shader still keeps. + #[cfg(windows)] + fn held(shader: &Shader) -> usize { + shader.container().map_or(0, |c| c.len()) + } + + /// A console compute container as the title passes one: a `DXBC` header + /// and an `ACCC` part with an `FSPX` program of 64 threads that only ends + /// (`s_endpgm`), then `tail`, past the size the header gives (the parser + /// stops there), which tells containers apart. + #[cfg(windows)] + fn compute_container(tail: &[u8]) -> Vec<u8> { + fn put(out: &mut Vec<u8>, words: &[u32]) { + out.extend(words.iter().flat_map(|w| w.to_le_bytes())); + } + // The pipeline registers: threads 64x1x1 (+0x0c), wave32 (+0x12 bit 4). + let mut packet = vec![0u8; 0x1c]; + for (at, half) in [(0x0c, 64u16), (0x0e, 1), (0x10, 1), (0x12, 1 << 4)] { + packet[at..at + 2].copy_from_slice(&half.to_le_bytes()); + } + let code = 0xbf81_0000u32.to_le_bytes(); + // The program metadata: no records, one dword of code. + let mut meta = Vec::new(); + put(&mut meta, &[0x403, 0x18 - 0x14, 1, 0, 0, 0]); + let parts: [(u32, &[u8]); 3] = [(0, &packet), (6, &code), (7, &meta)]; + let mut fspx = b"FSPX".to_vec(); + let mut at = 0x10 + 16 * parts.len(); + let size = at + parts.iter().map(|(_, data)| data.len()).sum::<usize>(); + put(&mut fspx, &[1, parts.len() as u32, size as u32]); + for (kind, data) in parts { + put(&mut fspx, &[kind, at as u32, data.len() as u32, 0]); + at += data.len(); + } + for (_, data) in parts { + fspx.extend(data); + } + let mut out = b"DXBC".to_vec(); + out.extend([0; 16]); + put(&mut out, &[1, (0x24 + 8 + fspx.len()) as u32, 1, 0x24]); + out.extend(b"ACCC"); + put(&mut out, &[fspx.len() as u32]); + out.extend(fspx); + out.extend(tail); + out + } + + /// A translated shader keeps what is still read of its container, and + /// lets the container go: the title passes one for each of its tens of + /// thousands of programs, and every pipeline that shares the shader + /// shares the translation. A pipeline created afterwards from the same + /// bytes shares the shader, and pipeline creation answers for it what it + /// answered while the container was there. + #[cfg(windows)] + #[test] + fn translated_shaders_let_their_containers_go() { + const COUNT: usize = 64; + let tail = |n: usize| { + let mut tail = vec![0u8; 32 << 10]; + tail[..8].copy_from_slice(&(n as u64).to_le_bytes()); + // Each a program `make` leaves out by its name, as long as the + // ray-tracing structure builder is off (`make::left_out`). + tail[100..120].copy_from_slice(b"CS_RaytracingResolve"); + tail + }; + let containers: Vec<Vec<u8>> = (0..COUNT).map(|n| compute_container(&tail(n))).collect(); + let create = |container: &[u8]| { + let desc = ComputeHead { + root: std::ptr::null(), + stage: Bytecode { + code: container.as_ptr(), + size: container.len(), + }, + }; + let mut p = std::ptr::null(); + let hr = create_compute(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p); + assert_eq!(hr, S_OK); + p + }; + let pipelines: Vec<This> = containers.iter().map(|c| create(c)).collect(); + let shaders: Vec<&Arc<Shader>> = + pipelines.iter().map(|&p| &pipeline(p).shaders[0]).collect(); + let all_held = || shaders.iter().map(|s| held(s)).sum::<usize>(); + let total: usize = containers.iter().map(Vec::len).sum(); + assert_eq!(all_held(), total); + + for s in &shaders { + assert!(s.translated().is_some(), "{s:?} translates"); + } + assert_eq!(all_held(), 0, "of {total} bytes"); + + let again = create(&containers[0]); + assert!(Arc::ptr_eq(&pipeline(again).shaders[0], shaders[0])); + assert!(pipeline(again).shaders[0].translated().is_some()); + // Left out by its name, as the first pipeline with it was. + assert_eq!(why_gone(again), why_gone(pipelines[0])); + for p in pipelines.into_iter().chain([again]) { + assert_eq!(slot::<extern "system" fn(This) -> u32>(p, 0x10)(p), 0); + } + } + /// The stream layout the title builds (title+0x86f090): root /// signature, five shader slots (the first a mesh shader), blend, sample /// mask, rasterizer, depth-stencil 1, sample description, input layout, - /// topology, render target and depth formats: 0x2b0 bytes. - #[test] - fn streams_yield_their_shaders() { - let (ms, ps) = ([9u8; 7], [4u8; 5]); + /// topology, render target and depth formats: 0x2b0 bytes. With mesh + /// shader `ms`, pixel shader `ps`, topology type `topology` and one + /// render target of format 28. + fn mesh_stream(ms: &[u8], ps: &[u8], topology: u64) -> This { let mut stream = vec![0u8; 0x2b0]; let mut put = |at: usize, v: u64| stream[at..at + 8].copy_from_slice(&v.to_le_bytes()); for (at, kind) in [ @@ -1463,8 +1666,7 @@ mod tests { put(0x20, ms.len() as u64); put(0x30, ps.as_ptr() as u64); put(0x38, ps.len() as u64); - // Topology type 3 (triangles), one render target of format 28. - put(0x278, 14 | 3 << 32); + put(0x278, 14 | topology << 32); put(0x280, 15 | 28 << 32); put(0x2a0, 1 << 32); let desc = StreamDesc { @@ -1474,6 +1676,14 @@ mod tests { let mut p = std::ptr::null(); let hr = create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p); assert_eq!(hr, S_OK); + p + } + + #[test] + fn streams_yield_their_shaders() { + let (ms, ps) = ([9u8; 7], [4u8; 5]); + // Topology type 3 (triangles). + let p = mesh_stream(&ms, &ps, 3); assert_eq!(shaders(p), [("mesh", ms.to_vec()), ("pixel", ps.to_vec())]); #[cfg(windows)] { @@ -1486,6 +1696,25 @@ mod tests { } } + /// Pipelines created with the same graphics state share one copy of it, + /// and one with another state has its own. Each title pipeline kept a + /// copy of its own for the session: 84,000 of them, of some 5,700 + /// different states. + #[cfg(windows)] + #[test] + fn pipelines_of_one_graphics_state_share_it() { + let (ms, ps) = ([7u8; 9], [6u8; 3]); + let state = |p: This| -> *const host::GraphicsState { + pipeline(p).host.graphics.as_deref().unwrap() + }; + let (a, b) = (mesh_stream(&ms, &ps, 3), mesh_stream(&ms, &ps, 3)); + assert_eq!(state(a), state(b)); + // Topology type 2 (lines). + let lines = mesh_stream(&ms, &ps, 2); + assert_ne!(state(a), state(lines)); + assert_eq!(pipeline(lines).host.graphics.as_deref().unwrap().topology.0, 2); + } + /// A buffer the title owns: it need not be aligned for the stream in it. #[repr(align(8))] struct Aligned([u8; 0x2b8]); diff --git a/d3d12/crates/leonida-gpu/src/pipeline/host.rs b/d3d12/crates/leonida-gpu/src/pipeline/host.rs index 18054240e1..86a9b59b4c 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/host.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/host.rs @@ -174,8 +174,10 @@ fn linear_filter(filter: u32) -> u32 { } } -/// The filter of an immediate sampler of `shader` ([`LinearScope`]). -fn static_filter(shader: &Shader, filter: u32) -> u32 { +/// Whether the immediate samplers of the program with `hash` and `container` +/// are made linear ([`LinearScope`]). Asked when it is translated, as its +/// container goes then (`Shader::translated`). +pub(super) fn linear_samplers(hash: &str, container: &[u8]) -> bool { static SCOPE: std::sync::OnceLock<LinearScope> = std::sync::OnceLock::new(); let scope = SCOPE.get_or_init(|| { let scope = LinearScope::parse(&std::env::var("LEONIDA_STATIC_SAMPLERS_LINEAR").unwrap_or_default()); @@ -184,7 +186,12 @@ fn static_filter(shader: &Shader, filter: u32) -> u32 { } scope }); - if scope.takes(&shader.hash, &shader.container) { linear_filter(filter) } else { filter } + scope.takes(hash, container) +} + +/// The filter of an immediate sampler of `shader` ([`linear_samplers`]). +fn static_filter(shader: &Shader, filter: u32) -> u32 { + if shader.translated().is_some_and(|t| t.linear_samplers) { linear_filter(filter) } else { filter } } fn integer_format(f: DXGI_FORMAT) -> bool { @@ -837,7 +844,7 @@ impl HostPipeline { Err(e) => { { let names: Vec<_> = - stages.iter().filter_map(|(s, _)| crate::pipeline::program_name(&s.container)).collect(); + stages.iter().filter_map(|(s, _)| s.translated()?.program.clone()).collect(); tracing::warn!(error = %e, ?shaders, ?names, "host pipeline refused"); } host.log_messages(); @@ -1005,7 +1012,7 @@ impl HostPipeline { Err(e) => { { let names: Vec<_> = - stages.iter().filter_map(|(s, _)| crate::pipeline::program_name(&s.container)).collect(); + stages.iter().filter_map(|(s, _)| s.translated()?.program.clone()).collect(); tracing::warn!(error = %e, ?shaders, ?names, "host pipeline refused"); } host.log_messages(); diff --git a/d3d12/crates/leonida-gpu/src/pipeline/known.rs b/d3d12/crates/leonida-gpu/src/pipeline/known.rs index e7c8558a34..c5cea2ed0b 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/known.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/known.rs @@ -101,16 +101,22 @@ pub(super) fn note(key: &str, shaders: &[Arc<Shader>], graphics: Option<&Graphic let mut entry = id.to_vec(); entry.push(shaders.len() as u8); for s in shaders { - let hash = *blake3::hash(&s.container).as_bytes(); + let hash = s.full; let stage = STAGES.iter().position(|&x| x == s.stage).unwrap_or(0) as u8; entry.push(stage); entry.extend(hash); - if book.shaders.insert(hash) { + // A translated shader has let its container go, but not before the first creation with + // it was noted here: `hand_out` notes a pipeline before it can start making one. (Were + // it gone, `make` would pass over the pipeline, whose shader the file would lack.) + if !book.shaders.contains(&hash) + && let Some(container) = s.container() + { + book.shaders.insert(hash); let new = &mut book.new[0]; new.push(stage); new.extend(hash); - new.extend((s.container.len() as u32).to_le_bytes()); - new.extend(&s.container); + new.extend((container.len() as u32).to_le_bytes()); + new.extend(&*container); } } entry.push(u8::from(graphics.is_some())); diff --git a/d3d12/crates/leonida-gpu/src/pipeline/library.rs b/d3d12/crates/leonida-gpu/src/pipeline/library.rs index c446aabcb3..a92d59d86b 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/library.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/library.rs @@ -9,10 +9,26 @@ //! an entry whose description differs, so neither is ever used. NVIDIA //! pipelines with static samplers are named by the places of their //! samplers too ([`super::places`]), or left to the driver's own cache. +//! +//! The library is kept for one set of translated shaders: the +//! fingerprint of what made them (the translator, its settings, what it +//! was told of the host, and the driver: [`super::known::fingerprint`], +//! the one `leonida warm` keeps its list by) is written beside it as +//! `host-pipelines.fingerprint`. A start whose fingerprint is not the +//! one written there (or finds none) starts an empty library, and its +//! first save writes that over the old one. Entries of an earlier +//! translation are never loaded again (their names hash the old code), +//! yet they were kept: every save wrote the whole library back, so the +//! file (and what the host reads of it) only grew with each translator +//! change. A save deletes the fingerprint before it renames a library +//! of other shaders over the file and writes the new one after, so a +//! save cut short leaves no fingerprint (an empty library next start), +//! never a stale library under the current fingerprint. //! 2. The title pipelines a run drew or dispatched with are listed by a key //! known when the title creates them (their shader containers and //! graphics state); the next run hands those to the workers at -//! creation, during loading. +//! creation, during loading. A pipeline stays listed for two runs after +//! the last one that drew with it ([`early_runs`]). //! //! Library calls overlap: the host documents the library as safe to use //! from several threads ("The pipeline library is thread-safe to use, and @@ -49,7 +65,7 @@ //! 16,352 of 16,384 pages read zeros with the handle closed, none with it //! open (the test below). `LEONIDA_LIBRARY_HANDLE=0`: closed, as before. -use std::collections::HashSet; +use std::collections::HashMap; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Mutex, MutexGuard, OnceLock, RwLock}; @@ -209,13 +225,37 @@ enum Blob { impl Blob { /// The library file in `dir`: a library a save left beside it - /// ([`NEXT_FILE`]) takes its place first. + /// ([`NEXT_FILE`]) takes its place first. None when it was saved for + /// other shaders than this run's ([`reuse_blob`]). fn of(dir: &std::path::Path) -> Blob { let path = dir.join(LIBRARY_FILE); let next = dir.join(NEXT_FILE); if next.exists() && std::fs::rename(&next, &path).is_err() { tracing::warn!("the host pipeline library saved last could not take the old one's place"); } + // The fingerprint is that of the library the next start opens: of + // the waiting one while it is still there, so the older file under + // the name is not taken for it. That file may be of the shaders + // before them (a save that started empty and could not replace it + // left the waiting one), so even under this run's fingerprint it is + // not opened: the run starts empty, and its first save replaces a + // library of these shaders with what it made. Pipelines to compile + // again, once, rather than stale ones kept for good. + let stored = if next.exists() { + None + } else { + std::fs::read_to_string(dir.join(FINGERPRINT_FILE)).ok() + }; + if !reuse_blob(stored.as_deref(), shaders()) { + if path.exists() { + tracing::info!( + stored = stored.as_deref().unwrap_or("none").trim(), + current = shaders(), + "host pipeline library saved for other shaders; starting an empty one" + ); + } + return Blob::None; + } if mapped() && let Some(file) = Mapped::open(&path) { @@ -440,6 +480,27 @@ const LIBRARY_FILE: &str = "host-pipelines.bin"; /// had it mapped (a system that refuses to replace a mapped file): the next /// start renames it over the library first ([`Blob::of`]). const NEXT_FILE: &str = "host-pipelines.next"; +/// The fingerprint of the shaders the library on disk was made for +/// ([`shaders`]), of the library the next start opens. +const FINGERPRINT_FILE: &str = "host-pipelines.fingerprint"; + +/// What this run's host pipelines are made from, as [`FINGERPRINT_FILE`] +/// holds it: the translator, its settings and what it was told of the +/// host, and the driver ([`super::known::fingerprint`]). Not our +/// executable: a rebuild that translates the same way keeps the library. +fn shaders() -> &'static str { + static NOW: OnceLock<String> = OnceLock::new(); + NOW.get_or_init(super::known::fingerprint) +} + +/// Whether a library saved with the fingerprint `stored` is opened by a run +/// whose shaders have the fingerprint `current`: only when they are the +/// same. With none (a library saved before fingerprints were written, or a +/// save cut short between its rename and the fingerprint) it is not: the +/// stale pipelines of an earlier translation would stay in it for good. +fn reuse_blob(stored: Option<&str>, current: &str) -> bool { + !current.is_empty() && stored.is_some_and(|stored| stored.trim() == current) +} const EARLY_FILE: &str = "early-pipelines.txt"; /// Title pipelines listed for an early start, at most. const EARLY_MAX: usize = 100_000; @@ -655,27 +716,22 @@ pub(crate) fn save(now: bool) { } *last = Some(std::time::Instant::now()); } - if let Err(e) = std::fs::create_dir_all(dir) { - tracing::warn!(error = %e, "host pipeline library not saved"); - return; - } - let tmp = dir.join(LIBRARY_FILE).with_extension("tmp"); // The bytes of the library written to `tmp`; 0 when no pipeline was // added: the library on disk is then what it was, and only the early // list is written (a title pipeline first drawn with wrote all 1,352 MB - // of the library again: run 60's second save). - let bytes = { + // of the library again: run 60's second save). None: nothing to save. + save_in(dir, |tmp| { let _all = one_call(); // No store between asking the size and writing; loads go on. let _alone = library.saving.write().unwrap_or_else(|e| e.into_inner()); let added = library.added.load(Ordering::Relaxed); if !USED_CHANGED.swap(false, Ordering::Relaxed) && added == 0 { - return; + return None; } // SAFETY: a plain query. let size = if added == 0 { 0 } else { unsafe { library.library.GetSerializedSize() } }; if added == 0 { - 0 + Some(0) } else if !now && size as u64 > in_play_most() { // Leonida: not while the title runs. The whole library is written each time, and a pipeline made // while playing (a place first seen) asked for that every 20 s: with 1.2 GB of it, a frame of 8.9 s @@ -691,22 +747,55 @@ pub(crate) fn save(now: bool) { "host pipeline library: not written while the title runs (it is larger than LEONIDA_LIBRARY_PLAY_SAVE_MB); the end of the run writes it" ) }); - 0 + Some(0) } else { let _call = call("serialise", "the whole library"); - if let Err(e) = serialise(&library.library, &tmp, size) { + if let Err(e) = serialise(&library.library, tmp, size) { tracing::warn!(error = %e, "host pipeline library not serialised"); - let _ = std::fs::remove_file(&tmp); - return; + let _ = std::fs::remove_file(tmp); + return None; } library.added.store(0, Ordering::Relaxed); SAVED.store(size as u64, Ordering::Relaxed); - size + Some(size) } - }; + }); +} + +/// One save into `dir`: `serialised` writes the library to the file it is +/// given (its bytes; 0: none added, only the lists are written; None: +/// nothing to save), then the library takes the old one's place with its +/// fingerprint, then the slow and early lists are written. The result, +/// unless there was nothing to save. +/// +/// Saves never overlap, from the first byte serialised to the early list: +/// they share the file the library is serialised to. A worker save that +/// had serialised and was renaming that file into place while the +/// shutdown save truncated and refilled it (the shutdown save's own lock +/// on the library is free once the worker's serialisation ends) renamed a +/// library still being written, under its fingerprint; the shutdown save +/// then found no file to rename, failed, and wrote neither list. One lock +/// for the whole save rather than a file of its own for each: two saves +/// cannot then rename in the other order (an older library over a newer +/// one), and nothing is left to clean up. Taken after the `SAVE_EVERY` +/// check, so a worker that finds a save running returns there instead of +/// waiting for it; no caller of [`save`] holds a lock, and no lock taken +/// inside is held by anyone who saves, so it cannot deadlock. +fn save_in( + dir: &std::path::Path, + serialised: impl FnOnce(&std::path::Path) -> Option<usize>, +) -> Option<std::io::Result<usize>> { + static SAVING: Mutex<()> = Mutex::new(()); + let _whole = SAVING.lock().unwrap_or_else(|e| e.into_inner()); + if let Err(e) = std::fs::create_dir_all(dir) { + tracing::warn!(error = %e, "host pipeline library not saved"); + return Some(Err(e)); + } + let tmp = dir.join(LIBRARY_FILE).with_extension("tmp"); + let bytes = serialised(&tmp)?; // Through `used`: a process that asked for none yet (`leonida shaders`) // must not write the earlier runs' list over with nothing. - let used: Vec<String> = used().iter().flatten().cloned().collect(); + let used: Vec<String> = used().as_ref().map(|e| e.lines(early_runs())).unwrap_or_default(); let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) }; if bytes > 0 && library_written.is_ok() { // In place unless the system refused and the new one waits beside it. @@ -726,7 +815,7 @@ pub(crate) fn save(now: bool) { let written = library_written .and_then(|()| write_atomically(&dir.join(SLOW_FILE), slow.join("\n").as_bytes())) .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes())); - match written { + match &written { Ok(()) => tracing::info!( bytes, early = used.len(), @@ -737,6 +826,7 @@ pub(crate) fn save(now: bool) { ), Err(e) => tracing::warn!(error = %e, "host pipeline library not saved"), } + Some(written.map(|()| bytes)) } /// Writes the library's `size` serialised bytes to the file `tmp`: through @@ -763,9 +853,42 @@ fn serialise(library: &ID3D12PipelineLibrary1, tmp: &std::path::Path, size: usiz /// the mapping goes on reading the old one for as long as a handle on it /// is open ([`holds`]; with none, only the pages in memory at that moment /// stay: the rest read as zeros). Where a system refuses, the new library -/// is left beside it as [`NEXT_FILE`] for the next start. +/// is left beside it as [`NEXT_FILE`] for the next start. The new library +/// was made for this run's shaders ([`replace_library_for`]). fn replace_library(dir: &std::path::Path, tmp: &std::path::Path) -> std::io::Result<()> { - std::fs::rename(tmp, dir.join(LIBRARY_FILE)).or_else(|_| std::fs::rename(tmp, dir.join(NEXT_FILE))) + replace_library_for(dir, tmp, shaders()) +} + +/// As [`replace_library`], for a library made for the shaders with the +/// fingerprint `current` ([`shaders`]). When [`FINGERPRINT_FILE`] holds +/// another (this run started empty), it is deleted before the rename and +/// written after: a save cut short in between leaves a library with no +/// fingerprint, which the next start does not open. Written first, a crash +/// before the rename would leave the old library under this fingerprint, +/// and every later save would keep its stale pipelines. Saves never overlap +/// ([`save_in`]): one could delete the fingerprint the other just wrote and +/// then fail its rename. +fn replace_library_for(dir: &std::path::Path, tmp: &std::path::Path, current: &str) -> std::io::Result<()> { + let noted = dir.join(FINGERPRINT_FILE); + let same = reuse_blob(std::fs::read_to_string(¬ed).ok().as_deref(), current); + if !same { + match std::fs::remove_file(¬ed) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e), + _ => {} + } + } + if std::fs::rename(tmp, dir.join(LIBRARY_FILE)).is_ok() { + // A library an earlier save left waiting is older than this one, + // yet the next start would rename it over this one, and open it + // under this fingerprint. + match std::fs::remove_file(dir.join(NEXT_FILE)) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound && !same => return Err(e), + _ => {} + } + } else { + std::fs::rename(tmp, dir.join(NEXT_FILE))?; + } + if same { Ok(()) } else { write_atomically(¬ed, current.as_bytes()) } } /// Writes `bytes` to a temporary file beside `path`, then renames it over @@ -829,25 +952,97 @@ pub(crate) fn note_time(key: &str, ms: u64) { } } -/// Title pipeline keys requested by draws or dispatches (this run and the last). -static USED: Mutex<Option<HashSet<String>>> = Mutex::new(None); +/// Title pipeline keys requested by draws or dispatches (this run and the +/// last, [`early_runs`]). +static USED: Mutex<Option<Early>> = Mutex::new(None); static USED_CHANGED: AtomicBool = AtomicBool::new(false); -fn used() -> std::sync::MutexGuard<'static, Option<HashSet<String>>> { +/// How many runs' title pipelines the early list keeps: 2, those this run +/// requested and those the run before did, so a pipeline is started early +/// by the two runs after the last one that drew with it. The list held +/// every run's: each pipeline drawn with in any earlier run was started at +/// the title's creation of it, at every load, and kept as a host pipeline +/// for the whole session whether this run drew with it or not. It grew +/// with every place visited, and at `EARLY_MAX` it stopped taking new ones. +/// `LEONIDA_EARLY_RUNS=<n>`: n runs; 0: every run's, as before. +fn early_runs() -> u64 { + static RUNS: OnceLock<u64> = OnceLock::new(); + *RUNS.get_or_init(|| { + std::env::var("LEONIDA_EARLY_RUNS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2) + }) +} + +/// The early list ([`EARLY_FILE`]): a key and the run that last requested +/// it on each line. Runs are counted by the list itself: this one is one +/// past the newest written down. A line with a key alone (a list written +/// before runs were counted) is one of run 0. +struct Early { + /// This run's number. + run: u64, + keys: HashMap<String, u64>, +} + +impl Early { + fn read(text: &str) -> Early { + let mut keys: HashMap<String, u64> = HashMap::new(); + for line in text.lines() { + let mut words = line.split_ascii_whitespace(); + let Some(key) = words.next() else { continue }; + let run = words.next().and_then(|r| r.parse().ok()).unwrap_or(0); + let last = keys.entry(key.to_owned()).or_insert(run); + *last = run.max(*last); + } + let run = keys.values().copied().max().unwrap_or(0).saturating_add(1); + Early { run, keys } + } + + /// Whether a run on the list requested `key`. + fn has(&self, key: &str) -> bool { + self.keys.contains_key(key) + } + + /// This run requested `key`; whether the list changed: a key new to it, + /// or one an earlier run requested last (its run is written again). + fn note(&mut self, key: &str) -> bool { + if let Some(last) = self.keys.get_mut(key) { + return std::mem::replace(last, self.run) != self.run; + } + self.keys.len() < EARLY_MAX && self.keys.insert(key.to_owned(), self.run).is_none() + } + + /// The lines to write, by key: the keys requested in the last `runs` + /// runs (0: in any). They are counted back from the newest run on the + /// list, which is this one once it has requested a pipeline: a process + /// that requests none (one that only translates shaders) writes the + /// list back as it found it, and is not a run that ages the others out. + fn lines(&self, runs: u64) -> Vec<String> { + let newest = self.keys.values().copied().max().unwrap_or(0); + let mut kept: Vec<(&String, &u64)> = self + .keys + .iter() + .filter(|&(_, &last)| runs == 0 || last.saturating_add(runs) > newest) + .collect(); + kept.sort_unstable(); + kept.into_iter().map(|(key, last)| format!("{key} {last}")).collect() + } +} + +fn used() -> std::sync::MutexGuard<'static, Option<Early>> { let mut used = USED.lock().unwrap_or_else(|e| e.into_inner()); if used.is_none() { let listed = DIR .get() .and_then(|d| std::fs::read_to_string(d.join(EARLY_FILE)).ok()) .unwrap_or_default(); - let set: HashSet<String> = listed.lines().filter(|l| !l.is_empty()).map(str::to_owned).collect(); - tracing::info!(pipelines = set.len(), "title pipelines to start early"); - *used = Some(set); + let early = Early::read(&listed); + tracing::info!(pipelines = early.keys.len(), "title pipelines to start early"); + *used = Some(early); } used } -/// Whether the title pipeline with `key` was requested in this or an earlier run. +/// Whether the title pipeline with `key` was requested in this run or one +/// of the earlier runs the early list keeps ([`early_runs`]). /// /// `LEONIDA_EARLY_ALL=1`: every title pipeline is started at creation, /// requested before or not, so that the driver's own cache holds it for @@ -857,14 +1052,12 @@ pub(crate) fn wanted_early(key: &str) -> bool { if *ALL.get_or_init(|| std::env::var_os("LEONIDA_EARLY_ALL").is_some_and(|v| v == "1")) { return true; } - used().as_ref().is_some_and(|s| s.contains(key)) + used().as_ref().is_some_and(|early| early.has(key)) } /// A draw or dispatch requested the title pipeline with `key`. pub(crate) fn note_used(key: &str) { - let mut used = used(); - let set = used.get_or_insert_with(HashSet::new); - if set.len() < EARLY_MAX && set.insert(key.to_owned()) { + if used().get_or_insert_with(|| Early::read("")).note(key) { USED_CHANGED.store(true, Ordering::Relaxed); } } @@ -918,6 +1111,8 @@ mod tests { fn the_library_file_is_mapped_and_replaced() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(LIBRARY_FILE); + // A library of this run's shaders. + std::fs::write(dir.path().join(FINGERPRINT_FILE), shaders()).unwrap(); assert!(matches!(Blob::of(dir.path()), Blob::None), "no file yet"); std::fs::write(&path, b"").unwrap(); assert!(matches!(Blob::of(dir.path()), Blob::None), "an empty file"); @@ -944,6 +1139,112 @@ mod tests { assert!(!dir.path().join(NEXT_FILE).exists()); } + #[test] + fn a_library_is_reused_only_for_the_same_shaders() { + assert!(reuse_blob(Some("0123456789abcdef"), "0123456789abcdef")); + // As a file holds it, with a line end added by hand. + assert!(reuse_blob(Some("0123456789abcdef\r\n"), "0123456789abcdef")); + assert!(!reuse_blob(Some("fedcba9876543210"), "0123456789abcdef"), "a translator change"); + assert!(!reuse_blob(None, "0123456789abcdef"), "saved before fingerprints, or a save cut short"); + assert!(!reuse_blob(Some(""), "0123456789abcdef")); + assert!(!reuse_blob(Some(""), "")); + } + + /// The library of an earlier translation is not opened (main opened + /// whatever the file held, and saved it back whole with the new + /// pipelines); one saved for this run's shaders is. + #[test] + fn a_library_saved_for_other_shaders_is_not_opened() { + let dir = tempfile::tempdir().unwrap(); + let old = b"pipelines of an earlier translation".repeat(64); + std::fs::write(dir.path().join(LIBRARY_FILE), &old).unwrap(); + let noted = dir.path().join(FINGERPRINT_FILE); + assert!(matches!(Blob::of(dir.path()), Blob::None), "no fingerprint written"); + std::fs::write(¬ed, "not these shaders").unwrap(); + assert!(matches!(Blob::of(dir.path()), Blob::None), "the fingerprint of other shaders"); + std::fs::write(¬ed, shaders()).unwrap(); + assert_eq!(Blob::of(dir.path()).bytes(), &old[..], "the fingerprint of these shaders"); + } + + /// A save writes the fingerprint of its shaders with the library, drops + /// a library left waiting by an earlier save, and leaves no fingerprint + /// that names other shaders than the library's. + #[test] + fn a_save_writes_its_fingerprint_with_the_library() { + let dir = tempfile::tempdir().unwrap(); + let (library, next, noted) = + (dir.path().join(LIBRARY_FILE), dir.path().join(NEXT_FILE), dir.path().join(FINGERPRINT_FILE)); + let tmp = library.with_extension("tmp"); + std::fs::write(&library, b"old").unwrap(); + std::fs::write(&next, b"older, waiting").unwrap(); + std::fs::write(¬ed, "old shaders").unwrap(); + std::fs::write(&tmp, b"new").unwrap(); + replace_library_for(dir.path(), &tmp, "new shaders").unwrap(); + assert_eq!(std::fs::read(&library).unwrap(), b"new"); + assert!(!next.exists(), "the waiting library would have taken the new one's place"); + assert_eq!(std::fs::read_to_string(¬ed).unwrap(), "new shaders"); + // A later save of the same shaders keeps the fingerprint. + std::fs::write(&tmp, b"newer").unwrap(); + replace_library_for(dir.path(), &tmp, "new shaders").unwrap(); + assert_eq!(std::fs::read(&library).unwrap(), b"newer"); + assert_eq!(std::fs::read_to_string(¬ed).unwrap(), "new shaders"); + // A save for other shaders cut short before its library is in place + // (here: no new library to rename) leaves no fingerprint: the + // library on disk is opened by neither the old shaders nor these. + replace_library_for(dir.path(), &tmp, "other shaders").unwrap_err(); + assert!(!noted.exists()); + } + + /// A worker save and the shutdown save overlapping: the second starts + /// once the first has serialised its library and not yet renamed it into + /// place. Both succeed, and what is left is the second's whole library + /// under this run's fingerprint, with the lists. (With only the + /// serialisation and the rename locked, the second refilled the file the + /// first then renamed, and the first failed its own rename and wrote no + /// list.) + #[test] + fn overlapping_saves_leave_one_whole_library_and_its_lists() { + const LEN: usize = 1 << 20; + // Worked out once, first: in the second save it may outlast the gap. + let current = shaders(); + let dir = tempfile::tempdir().unwrap(); + let library = dir.path().join(LIBRARY_FILE); + std::fs::write(&library, b"a library of other shaders").unwrap(); + std::fs::write(dir.path().join(FINGERPRINT_FILE), "old shaders").unwrap(); + // Serialises a library of `LEN` bytes of `byte`, as `serialise` does. + fn fill(tmp: &std::path::Path, byte: u8) -> Option<usize> { + match Mapped::create(tmp, LEN) { + Some(mut file) => file.bytes_mut().fill(byte), + None => std::fs::write(tmp, vec![byte; LEN]).unwrap(), + } + Some(LEN) + } + let (serialised, gap) = std::sync::mpsc::channel(); + let first = { + let dir = dir.path().to_owned(); + std::thread::spawn(move || { + save_in(&dir, |tmp| { + let bytes = fill(tmp, 1); + serialised.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(300)); + bytes + }) + }) + }; + gap.recv().unwrap(); + let second = save_in(dir.path(), |tmp| fill(tmp, 2)); + let first = first.join().unwrap(); + assert_eq!(first.unwrap().unwrap(), LEN); + assert_eq!(second.unwrap().unwrap(), LEN); + let saved = std::fs::read(&library).unwrap(); + assert_eq!(saved.len(), LEN); + assert!(saved.iter().all(|&b| b == 2), "the second save's library, whole"); + assert_eq!(std::fs::read_to_string(dir.path().join(FINGERPRINT_FILE)).unwrap(), current); + assert!(dir.path().join(SLOW_FILE).exists() && dir.path().join(EARLY_FILE).exists()); + assert!(!library.with_extension("tmp").exists()); + assert!(!dir.path().join(NEXT_FILE).exists()); + } + /// The bytes at `at` of the pattern the test below writes. fn pattern(at: usize, out: &mut [u8]) { for (i, word) in out.chunks_exact_mut(4).enumerate() { @@ -1013,6 +1314,93 @@ mod tests { } } + /// The keys an early list's text holds, sorted. + fn listed(text: &str) -> Vec<&str> { + let mut keys: Vec<&str> = text.lines().filter_map(|l| l.split(' ').next()).collect(); + keys.sort_unstable(); + keys + } + + /// Five runs, each drawing with pipelines of its own: the list the last + /// one writes holds those of that run and the one before, and the next + /// run starts only those early. It held every run's, so each pipeline + /// drawn with in any run ever became a host pipeline at every load. + #[test] + fn the_early_list_keeps_the_last_two_runs() { + let mut text = String::new(); + for run in 1..=5 { + let mut early = Early::read(&text); + for n in 0..2 { + assert!(early.note(&format!("run{run}-{n}"))); + } + text = early.lines(2).join("\n"); + } + assert_eq!(listed(&text), ["run4-0", "run4-1", "run5-0", "run5-1"]); + let next = Early::read(&text); + assert!(next.has("run4-0") && next.has("run5-1")); + assert!(!next.has("run3-0") && !next.has("run1-0")); + } + + /// A pipeline drawn with again in a later run stays listed from then on. + #[test] + fn a_pipeline_drawn_with_again_stays_listed() { + let mut text = String::new(); + for run in 1..=5 { + let mut early = Early::read(&text); + early.note(&format!("run{run}")); + if run % 2 == 1 { + // The list changes (its run is written down), once a run. + assert!(early.note("odd-runs")); + assert!(!early.note("odd-runs")); + } + text = early.lines(2).join("\n"); + } + assert_eq!(listed(&text), ["odd-runs", "run4", "run5"]); + } + + /// A list written before runs were counted (a key alone on each line) + /// still loads: its keys are started early, kept for one more run and + /// then age as the others do. + #[test] + fn an_early_list_without_runs_still_loads() { + let mut early = Early::read("old-a\nold-b\n\n"); + assert!(early.has("old-a") && early.has("old-b")); + early.note("new"); + let text = early.lines(2).join("\n"); + assert_eq!(listed(&text), ["new", "old-a", "old-b"]); + let mut next = Early::read(&text); + next.note("new"); + next.note("old-b"); + assert_eq!(listed(&next.lines(2).join("\n")), ["new", "old-b"]); + } + + /// A process that requests no pipeline (one that only translates + /// shaders) writes the list back as it found it: it is not a run that + /// ages the others out. + #[test] + fn a_process_that_requests_nothing_writes_the_list_back() { + let mut text = String::new(); + for run in 1..=3 { + let mut early = Early::read(&text); + early.note(&format!("run{run}")); + text = early.lines(2).join("\n"); + } + assert_eq!(Early::read(&text).lines(2).join("\n"), text); + assert_eq!(listed(&text), ["run2", "run3"]); + } + + /// `LEONIDA_EARLY_RUNS=0`: every run's pipelines stay listed, as before. + #[test] + fn no_count_of_runs_keeps_every_run() { + let mut text = String::new(); + for run in 1..=4 { + let mut early = Early::read(&text); + early.note(&format!("run{run}")); + text = early.lines(0).join("\n"); + } + assert_eq!(listed(&text), ["run1", "run2", "run3", "run4"]); + } + #[test] fn concurrent_write_atomically_never_fails_or_truncates() { let dir = tempfile::tempdir().unwrap(); diff --git a/d3d12/crates/leonida-gpu/src/pipeline/make.rs b/d3d12/crates/leonida-gpu/src/pipeline/make.rs index 66e4e82aed..ba30dfc806 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/make.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/make.rs @@ -21,9 +21,9 @@ //! its end (run textures-d2, the first after a new translation; Belobug //! 18e57db8 found the same). -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; -use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, Weak}; use std::time::{Duration, Instant}; use super::Shader; @@ -32,7 +32,8 @@ use super::host::{GraphicsState, HostPipeline, TargetFormats}; /// What a host pipeline is made from, and the host pipeline once made. pub(crate) struct Pending { shaders: Vec<Arc<Shader>>, - pub(crate) graphics: Option<Box<GraphicsState>>, + /// Shared with every pipeline of the same state ([`shared_state`]). + pub(crate) graphics: Option<Arc<GraphicsState>>, queue_state: AtomicU8, /// Taken by a worker from [`Queue::slow`]. was_slow: AtomicBool, @@ -58,10 +59,24 @@ pub(crate) struct Pending { variant: OnceLock<Arc<Pending>>, } -fn named(shaders: &[Arc<Shader>], name: &[u8]) -> bool { - shaders +/// The compute programs [`left_out`] may leave out, by a name their container +/// holds. Looked for once per shader (`Shader::facts`): a translated shader +/// no longer has its container when the title creates another pipeline with it. +const NAMES: [&[u8]; 2] = [b"CS_RaytracingResolve", b"CS_ScreenProbes_ActivateRays"]; + +/// Which of [`NAMES`] `container` holds, a bit for each. +pub(super) fn names(container: &[u8]) -> u8 { + NAMES .iter() - .any(|s| s.stage == "compute" && s.container.windows(name.len()).any(|w| w == name)) + .enumerate() + .filter(|(_, name)| container.windows(name.len()).any(|w| w == **name)) + .fold(0, |bits, (n, _)| bits | 1 << n) +} + +/// Whether one of `shaders` is a compute program with `name`, one of [`NAMES`]. +fn named(shaders: &[Arc<Shader>], name: &[u8]) -> bool { + let bit = NAMES.iter().position(|n| *n == name).map_or(0, |n| 1 << n); + shaders.iter().any(|s| s.facts().named & bit != 0) } fn left_out(shaders: &[Arc<Shader>]) -> Option<&'static str> { @@ -153,6 +168,7 @@ unsafe impl Sync for Pending {} impl Pending { pub(crate) fn new(shaders: Vec<Arc<Shader>>, graphics: Option<Box<GraphicsState>>) -> Pending { + let described = graphics.as_ref().map(|g| g.describe()); let mut key = blake3::Hasher::new(); for s in &shaders { key.update(s.stage.as_bytes()); @@ -164,12 +180,13 @@ impl Pending { key.update(&mask.position_row.map_or(u64::MAX, u64::from).to_le_bytes()); } } - key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); + key.update(described.as_deref().unwrap_or_default().as_bytes()); let scene_input = scene_input(&shaders); let screen = (graphics.as_ref().is_some_and(|g| g.screen_pass()) && shaders.iter().all(|s| s.stage != "mesh")) || scene_input; let left_out = left_out(&shaders); + let graphics = graphics.zip(described).map(|(g, described)| shared_state(g, &described)); Pending { screen, scene_input, @@ -231,6 +248,39 @@ impl Pending { } } +/// The one copy of the graphics state `state`, described as `described`: +/// pipelines of the same state share it. The title creates 84,000 pipelines +/// from some 5,700 different states, and each kept a copy of its own for +/// the session (about 540 bytes, its input elements and their names on +/// top). The description holds everything the state does (it names the +/// host pipeline in the library), so equal descriptions are equal states. +/// Held weakly: a state goes with the last pipeline that has it, and the +/// table lets go of those gone each time it has doubled. +fn shared_state(state: Box<GraphicsState>, described: &str) -> Arc<GraphicsState> { + struct Held(Weak<GraphicsState>); + // SAFETY: as for `Pending`: a state is only read after creation. + unsafe impl Send for Held {} + /// The states by the hash of their description, and the size at which + /// the table is next swept of states gone. + static STATES: Mutex<Option<(HashMap<[u8; 32], Held>, usize)>> = Mutex::new(None); + const SWEEP_AT: usize = 1024; + let id = *blake3::hash(described.as_bytes()).as_bytes(); + let mut states = STATES.lock().unwrap_or_else(|e| e.into_inner()); + let (table, sweep_at) = states.get_or_insert_with(|| (HashMap::new(), SWEEP_AT)); + if let Some(shared) = table.get(&id).and_then(|held| held.0.upgrade()) { + return shared; + } + // (The input elements point into the names' own buffers, which the + // move into the shared allocation leaves where they are.) + let shared: Arc<GraphicsState> = Arc::from(state); + table.insert(id, Held(Arc::downgrade(&shared))); + if table.len() >= *sweep_at { + table.retain(|_, held| held.0.strong_count() > 0); + *sweep_at = (table.len() * 2).max(SWEEP_AT); + } + shared +} + /// Why a pipeline has no host pipeline (diagnostics): its shaders that do /// not translate, else "refused" or "being made"; `None` if it has one. #[cfg(feature = "diagnostics")] diff --git a/d3d12/crates/leonida-gpu/src/pool.rs b/d3d12/crates/leonida-gpu/src/pool.rs index c035377049..08af9029e3 100644 --- a/d3d12/crates/leonida-gpu/src/pool.rs +++ b/d3d12/crates/leonida-gpu/src/pool.rs @@ -633,9 +633,15 @@ impl Drop for StagingPiece { } } -/// `bytes` of upload memory, all zeros: the buffer it lies in, where in -/// that buffer, and its mapping. `None`: not pooled. -pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPiece, ID3D12Resource, u64, *mut u8)> { +/// `bytes` of upload memory, all zeros unless `zeroed` is false (the caller +/// writes all of it the card reads, and a piece given out again keeps what +/// it held): the buffer it lies in, where in that buffer, and its mapping. +/// `None`: not pooled. +pub(crate) fn staging( + host: &crate::host::Host, + bytes: u64, + zeroed: bool, +) -> Option<(StagingPiece, ID3D12Resource, u64, *mut u8)> { if !on() { return None; } @@ -656,7 +662,7 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi let owned = StagingPiece(piece); // SAFETY: the piece lies in the block's mapping. let data = unsafe { memory.1.add(piece.start as usize) }; - if again { + if again && zeroed { // What is not detiled into it (an unmapped texture) uploads zeros, // as from a buffer of its own. // SAFETY: the piece is ours alone. @@ -1119,12 +1125,12 @@ mod tests { assert_eq!(resting(), before + 1); // SAFETY: the piece's mapping, 4096 bytes of it ours. unsafe { - let (piece, _, at, data) = staging(host, 4096).unwrap(); + let (piece, _, at, data) = staging(host, 4096, true).unwrap(); assert!(at.is_multiple_of(512)); std::ptr::write_bytes(data, 0xAB, 4096); drop(piece); lock(&STAGING).rested(u64::MAX); - let (_piece, _, _, data) = staging(host, 4096).unwrap(); + let (_piece, _, _, data) = staging(host, 4096, true).unwrap(); assert!((0..4096).all(|i| *data.add(i) == 0)); // SAFETY: plain query. assert!(host.device.GetDeviceRemovedReason().is_ok()); diff --git a/d3d12/crates/leonida-gpu/src/queue.rs b/d3d12/crates/leonida-gpu/src/queue.rs index 6c095d2544..43209ac9b7 100644 --- a/d3d12/crates/leonida-gpu/src/queue.rs +++ b/d3d12/crates/leonida-gpu/src/queue.rs @@ -623,7 +623,23 @@ fn ahead_begin() { { let mut ahead = lock(&AHEAD.0); while ahead.state != 1 { - ahead = AHEAD.1.wait(ahead).unwrap_or_else(|e| e.into_inner()); + // Meanwhile, every few milliseconds, a look ahead of + // the next list's pass over the heap's buffer views + // (`crate::draw::heap_prelook`). + let Some(every) = crate::draw::heap_prelook() else { + ahead = AHEAD.1.wait(ahead).unwrap_or_else(|e| e.into_inner()); + continue; + }; + let (back, over) = AHEAD.1.wait_timeout(ahead, every).unwrap_or_else(|e| e.into_inner()); + ahead = back; + if over.timed_out() && ahead.state != 1 { + drop(ahead); + // (A panic in the look gives the pass back what + // the looks took: the written slots, and its + // part, `crate::draw::heap_prelook`.) + let _ = std::panic::catch_unwind(crate::draw::heap_look_ahead); + ahead = lock(&AHEAD.0); + } } } let recorded = if crate::draw::ahead_split() { @@ -682,6 +698,13 @@ fn ahead_line(frames: f64) { micros / 1000.0, waited / 1000.0 ); + let [looks, looked, kept, again] = [0, 1, 2, 3].map(|i| crate::draw::PRELOOK_STATS[i].swap(0, Ordering::Relaxed) as f64 / frames); + if crate::draw::heap_prelook().is_some() { + tracing::info!( + "looks ahead of the lists' passes over the heap's buffer views per frame (LEONIDA_HEAP_PRELOOK=1): {looks:.1} looks at \ + {looked:.0} slots; of the slots looked at ahead the passes kept {kept:.0} and looked at {again:.0} again" + ); + } } /// Whether a queue may pass `wait`: memory holds the value, or, with diff --git a/d3d12/crates/leonida-gpu/src/resource.rs b/d3d12/crates/leonida-gpu/src/resource.rs index b137896b0a..5e9337fbaf 100644 --- a/d3d12/crates/leonida-gpu/src/resource.rs +++ b/d3d12/crates/leonida-gpu/src/resource.rs @@ -1011,9 +1011,59 @@ fn place<'a>( pub(crate) struct Memory { ptr: NonNull<u8>, layout: Layout, - /// Set when the memory came from the title's allocator, with these - /// allocation attributes (it goes back there). - attributes: Option<u64>, + /// Where it came from, and so where it goes back. + source: Source, +} + +/// Where a [`Memory`] came from. +#[derive(Clone, Copy, Debug)] +enum Source { + /// Our allocator. + Ours, + /// The title's allocator ([`use_allocator`]), with these allocation + /// attributes. + Title(u64), + /// The runtime's memory for heaps ([`use_heap_memory`]), freed by this. + Heap(HeapMemoryFree), +} + +/// `(size, alignment)`: zeroed title memory for a heap, or null. +pub type HeapMemory = fn(usize, usize) -> *mut c_void; +/// Frees what a [`HeapMemory`] gave. +pub type HeapMemoryFree = fn(*mut c_void); +static HEAP_MEMORY: std::sync::OnceLock<(HeapMemory, HeapMemoryFree)> = std::sync::OnceLock::new(); + +#[cfg(test)] +thread_local! { + /// A test's [`HEAP_MEMORY`], for its thread only. + static TEST_HEAP_MEMORY: std::cell::Cell<Option<(HeapMemory, HeapMemoryFree)>> = const { std::cell::Cell::new(None) }; +} + +/// The heaps the title makes through the device (`CreateHeap`) take their +/// memory from the runtime, as on the console, where a heap is title memory: +/// `leonida-hle` gives a write-watched reservation below 2^40 of its own +/// (xmem `heap_memory`). Their placed resources' host copies then refresh +/// the pages the title wrote (`crate::watch` asks the kernel); of our +/// allocator's memory nothing is known, and every refresh took a copy whole +/// and compared it. A whole reservation can also be opened in place +/// (`LEONIDA_INPLACE`). The runtime names it before the device exists. +pub fn use_heap_memory(alloc: HeapMemory, free: HeapMemoryFree) { + let _ = HEAP_MEMORY.set((alloc, free)); +} + +fn heap_memory() -> Option<(HeapMemory, HeapMemoryFree)> { + #[cfg(test)] + if let Some(memory) = TEST_HEAP_MEMORY.get() { + return Some(memory); + } + HEAP_MEMORY.get().copied() +} + +/// Whether heaps take the runtime's memory ([`use_heap_memory`]; +/// `LEONIDA_HEAP_WATCHED=0`: ours, as before). +fn heaps_watched() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_HEAP_WATCHED").is_none_or(|v| v != "0")) } pub type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void; @@ -1106,10 +1156,37 @@ impl Memory { Ok(Memory { ptr, layout, - attributes: Some(attributes), + source: Source::Title(attributes), }) } + /// A heap's memory: the runtime's if it named some + /// ([`use_heap_memory`], [`heaps_watched`]), else our own (and our own + /// if the runtime has none to give); zeroed either way. + fn for_heap(info: AllocationInfo) -> Result<Memory, HRESULT> { + let ours = Memory::new; + let Some((alloc, free)) = heap_memory().filter(|_| heaps_watched()) else { + return ours(info); + }; + let Some(layout) = usize::try_from(info.size) + .ok() + .zip(usize::try_from(info.alignment).ok()) + .filter(|&(size, _)| size > 0) + .and_then(|(size, align)| Layout::from_size_align(size, align).ok()) + else { + return ours(info); + }; + // (Zeroed by the runtime: a fresh reservation.) + match NonNull::new(alloc(layout.size(), layout.align()).cast::<u8>()) { + Some(ptr) => Ok(Memory { + ptr, + layout, + source: Source::Heap(free), + }), + None => ours(info), + } + } + /// `size` zeroed bytes aligned to `alignment` (a power of two). pub(crate) fn zeroed(size: u64, alignment: u64) -> Result<Memory, HRESULT> { Memory::new(AllocationInfo { size, alignment }) @@ -1130,22 +1207,29 @@ impl Memory { let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(E_OUTOFMEMORY)?; // The big ones are named in the log: the memory line counts our own // allocations by size, and these are the title's memory given out - // of ours (a heap it made through the device, a descriptor heap). + // of ours (a descriptor heap; a heap it made through the device + // only with `LEONIDA_HEAP_WATCHED=0` or when xmem refused one, + // [`Memory::for_heap`]). if info.size >= 32 << 20 { - tracing::info!(mb = info.size >> 20, at = ?ptr, "memory for the title from our allocator (a heap or a descriptor heap)"); + tracing::info!( + mb = info.size >> 20, + at = ?ptr, + "memory for the title from our allocator (a descriptor heap, or a heap with LEONIDA_HEAP_WATCHED=0 or when xmem refused one)" + ); } Ok(Memory { ptr, layout, - attributes: None, + source: Source::Ours, }) } } impl Drop for Memory { fn drop(&mut self) { - match (self.attributes, ALLOCATOR.get()) { - (Some(attributes), Some(&(_, free))) => free(self.ptr.as_ptr().cast(), attributes), + match (self.source, ALLOCATOR.get()) { + (Source::Title(attributes), Some(&(_, free))) => free(self.ptr.as_ptr().cast(), attributes), + (Source::Heap(free), _) => free(self.ptr.as_ptr().cast()), // SAFETY: allocated in `new` with this layout. _ => unsafe { dealloc(self.ptr.as_ptr(), self.layout) }, } @@ -1182,7 +1266,7 @@ pub(crate) extern "system" fn create_heap( size: desc.size, alignment: desc.alignment.max(KIB_64), }; - let memory = match Memory::new(info) { + let memory = match Memory::for_heap(info) { Ok(memory) => memory, Err(hr) => return hr, }; @@ -1310,7 +1394,10 @@ struct Hosted { state: u32, clear: Option<[u32; 5]>, /// When the host copy was last asked for (`crate::host::moment`), - /// written under `made`'s lock. + /// written under `made`'s lock; 0 while there is no host copy (never + /// made, or let go: [`let_go_copy`], [`want_level`]), so that the sweep's + /// look by age ([`idle_by_age`]) passes over the textures it has nothing + /// to take from, without their locks. used: std::sync::atomic::AtomicU64, /// The host refused to make it: not tried again. refused: std::sync::atomic::AtomicBool, @@ -1318,13 +1405,18 @@ struct Hosted { /// never): it is tried again on a use after [`NO_ROOM_AGAIN_MS`] /// ([`NoTexture::ForNow`]). no_room: std::sync::atomic::AtomicU64, - /// Its host copy was let go as idle once. + /// Its host copy was let go as idle once (by a placed texture released + /// and made anew for the same key too: [`GONE_PLACED`]). gone: std::sync::atomic::AtomicBool, /// How many times its host copy was made again after it was let go - /// ([`favour_reused`]). + /// ([`favour_reused`]; carried as `gone`). remade: std::sync::atomic::AtomicU32, /// A texture of [`PLACED_TEXTURES`]. placed: std::sync::atomic::AtomicBool, + /// When [`texture_at`] last handed it out (`crate::host::moment`), + /// written under that table's lock: every view, draw and texture pass + /// that names a placed texture asks for it there ([`evict_placed`]). + named: std::sync::atomic::AtomicU64, /// The lowest level a view asked for since it had no host copy /// ([`want_level`]; `u32::MAX`: none said). wanted: std::sync::atomic::AtomicU32, @@ -1468,6 +1560,8 @@ pub(crate) fn want_level(this: This, first: u32) { if let Some(old) = made.take() { REPLACED.lock().unwrap_or_else(|e| e.into_inner()).push((crate::host::moment(), old)); } + // No host copy until the next use makes the new one ([`Hosted::used`]). + r.host.used.store(0, Relaxed); } /// Counts for the memory line: host copies of textures the title fills @@ -2378,23 +2472,31 @@ fn sweep_batch(all: &std::collections::BTreeSet<usize>, from: usize, limit: usiz /// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames. /// /// The next use makes the host copy anew and uploads the title's memory -/// again (its staging state goes with it). The title resource stays: its -/// address is what views and lists name. +/// again (its staging state goes with it). The title resource stays while +/// anything may name it: its address is what views and lists name. After +/// the copies, those of placed textures whose title memory the title +/// unmapped go on the same terms after seconds instead of the card's idle +/// time ([`let_go_unmapped`]; `LEONIDA_PLACED_UNMAPPED=0`: kept to that +/// time, as before). Then placed textures that nothing has named for a minute and +/// that have no host copy leave their table and are released a second +/// later ([`evict_placed`]; `LEONIDA_PLACED_EVICT=0`: kept for the run), +/// timed apart ([`PLACED_EVICT_US`]) from the look for copies +/// ([`SWEPT_US`]). /// shortcut: [`host_resource`] hands out the host texture without holding /// it; a thread that asked for it and has not yet recorded its use (which /// makes the list or the slot hold it) is protected by that idle time alone. /// Every caller uses it at once, within the title's call. /// Called before a submission starts, by the thread that submits. -/// `LEONIDA_TEXTURE_SWEEP=0` lets nothing go. +/// `LEONIDA_TEXTURE_SWEEP=0` lets nothing idle go; copies replaced by ones +/// with more levels go all the same. #[cfg(windows)] pub(crate) fn let_go_idle() { use std::sync::atomic::Ordering::Relaxed; const IDLE_FRAMES: u64 = 4; - static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - if !*ON.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { - return; - } - // Copies replaced by ones with more levels, as any let go. + // Copies replaced by ones with more levels, as any let go. Before the + // switch below, which must not keep them: nothing uses them any more and + // nothing else lets them go, so with the sweep off they would be held + // for good. { let mut replaced = REPLACED.lock().unwrap_or_else(|e| e.into_inner()); let (gone, keep): (Vec<_>, Vec<_>) = @@ -2405,6 +2507,10 @@ pub(crate) fn let_go_idle() { crate::host::retire(made); } } + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { + return; + } let memory = crate::host::host().and_then(|h| h.video_memory()); static KEEP: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); let keep = *KEEP @@ -2428,21 +2534,10 @@ pub(crate) fn let_go_idle() { // For the trail (`crate::host::trail`): how many went, their bytes, // and the first one. let (mut went, mut bytes, mut first) = (0u64, 0u64, None); + let began = std::time::Instant::now(); let all = textures(); // With a limit, the longest idle first. - let mut by_age: Vec<(u64, usize)> = Vec::new(); - if most != u64::MAX { - for &at in all.iter() { - // SAFETY: as below. - let r = unsafe { &*(at as *const Resource) }; - let used = r.host.used.load(Relaxed); - if used != 0 && fills(&r.desc) && crate::host::long_ago(used, idle_ms, IDLE_FRAMES) { - let remade = if favour_reused() { r.host.remade.load(Relaxed) } else { 0 }; - by_age.push((idle_rank(used, remade), at)); - } - } - by_age.sort_unstable(); - } + let by_age = if most != u64::MAX { idle_by_age(&all, idle_ms, IDLE_FRAMES) } else { Vec::new() }; // Without one, while textures are kept for minutes, a part of them at // each look, the next one at the next: a play has over 100,000 // (`LEONIDA_TEXTURE_SWEEP=whole`: all each time, as before). @@ -2459,44 +2554,7 @@ pub(crate) fn let_go_idle() { }; let from = if part == PART { FROM.load(Relaxed) } else { 0 }; let mut looked = 0; - let began = std::time::Instant::now(); - // Lets go of the host copy of the texture at `at` if it has been out of - // use for `ms` and `frames` and only its title texture holds it: its - // bytes, if it went. - let let_go = |at: usize, ms: u64, frames: u64| -> Option<u64> { - // SAFETY: a texture leaves the table before it is freed, under the - // lock held here (`Drop for Resource`). - let r = unsafe { &*(at as *const Resource) }; - // (Without its lock first: most were used lately or have none.) - let used = r.host.used.load(Relaxed); - if used == 0 || !fills(&r.desc) || !crate::host::long_ago(used, ms, frames) || crate::texture::host_wrote(at) { - return None; - } - let gone = { - let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); - let idle = made.as_ref().is_some_and(|(host, _)| { - crate::host::long_ago(r.host.used.load(Relaxed), ms, frames) - && std::sync::Arc::strong_count(host) == 1 - && crate::host::references(&host.texture) == 1 - }); - if idle { - // Under the lock: the next use must not find the staging - // state of the texture let go (it says "uploaded"). - crate::texture::unstage(at as This); - r.host.wanted.store(u32::MAX, Relaxed); - made.take() - } else { - None - } - }; - let (host, _) = gone?; - r.host.gone.store(true, Relaxed); - KINDS[2].fetch_add(1, Relaxed); - KINDS[3].fetch_add(host.bytes, Relaxed); - let bytes = host.bytes; - crate::host::retire(host); - Some(bytes) - }; + let let_go =|at: usize, ms: u64, frames: u64| let_go_copy(&all, at, ms, frames); for at in sweep_batch(&all, from, part, crate::toggled!("LEONIDA_SWEEP_WRAP")).chain(by_age.iter().map(|&(_, at)| at)) { if bytes >= most { break; @@ -2529,9 +2587,33 @@ pub(crate) fn let_go_idle() { COMMIT_FLOOR[1].fetch_add(copies, Relaxed); COMMIT_FLOOR[2].fetch_add(freed, Relaxed); } + // Placed textures nothing names any more: out of their table, a part at + // each look, and released a second later. After the table of textures' + // lock is given back: `texture_at` takes the two the other way round. + drop(all); + let swept = began.elapsed().as_micros() as u64; SWEPT_US[0].fetch_add(1, Relaxed); - SWEPT_US[1].fetch_add(began.elapsed().as_micros() as u64, Relaxed); - SWEPT_US[2].fetch_max(began.elapsed().as_micros() as u64, Relaxed); + SWEPT_US[1].fetch_add(swept, Relaxed); + SWEPT_US[2].fetch_max(swept, Relaxed); + let began = std::time::Instant::now(); + // Host copies of placed textures over memory the title unmapped: before + // the release below, which takes only textures without one. + if placed_unmapped() { + let (copies, freed) = let_go_unmapped(UNMAPPED_IDLE_MS, UNMAPPED_IDLE_FRAMES, UNMAPPED_MAPPED_MS, UNMAPPED_PART); + went += copies; + bytes += freed; + } + if placed_evict() { + let mut cursor = PLACED_CURSOR.lock().unwrap_or_else(|e| e.into_inner()); + let from = cursor.unwrap_or((0, [0; 14])); + *cursor = evict_placed(from, u64::MAX, PLACED_EVICT_MS, PLACED_EVICT_FRAMES, PLACED_EVICT_PART).1; + } + for held in evicted_due(1000, IDLE_FRAMES) { + crate::host::retire(held); + } + let evicting = began.elapsed().as_micros() as u64; + PLACED_EVICT_US[0].fetch_add(evicting, Relaxed); + PLACED_EVICT_US[1].fetch_max(evicting, Relaxed); if went > 0 { crate::host::trail(|| { format!( @@ -2543,6 +2625,94 @@ pub(crate) fn let_go_idle() { } } +/// For [`let_go_idle`] with a limit of bytes: the textures of `all` (the +/// table, under its lock) that have a host copy out of use for `ms` and +/// `frames`, the longest idle first ([`idle_rank`]), with their rank. +/// +/// Only those with a host copy: a copy let go leaves [`Hosted::used`] at 0. +/// It stayed at the copy's last use before, so every texture whose copy had +/// ever gone was sorted again at each look under pressure, then found with +/// nothing to take under its lock (as by the commit floor's walk of all). +/// Measured: the look took 2.2 ms without `LEONIDA_COMMIT_FLOOR` and 11.6 ms +/// with it (`d3d12/docs/findings.md`), over a table of tens of thousands of +/// placed textures: [`SWEPT_US`], which then began after this look, so the +/// numbers are the walks' alone (the commit floor's one passes over those +/// textures now too, without their locks); how long this look took then is +/// not known. +#[cfg(windows)] +fn idle_by_age(all: &std::collections::BTreeSet<usize>, ms: u64, frames: u64) -> Vec<(u64, usize)> { + use std::sync::atomic::Ordering::Relaxed; + let reused = favour_reused(); + let mut by_age = Vec::new(); + for &at in all { + // SAFETY: a texture leaves the table before it is freed, under the + // lock the caller holds (`Drop for Resource`). + let r = unsafe { &*(at as *const Resource) }; + let used = r.host.used.load(Relaxed); + if used != 0 && fills(&r.desc) && crate::host::long_ago(used, ms, frames) { + let remade = if reused { r.host.remade.load(Relaxed) } else { 0 }; + by_age.push((idle_rank(used, remade), at)); + } + } + by_age.sort_unstable(); + by_age +} + +/// For [`let_go_idle`]: lets go of the host copy of the texture at `at`, one +/// of `_all` (the table, whose lock the caller holds), if it has been out of +/// use for `ms` and `frames` and only its title texture holds it: its bytes, +/// if it went. [`Hosted::used`] goes to 0 with it. +#[cfg(windows)] +fn let_go_copy(_all: &std::collections::BTreeSet<usize>, at: usize, ms: u64, frames: u64) -> Option<u64> { + use std::sync::atomic::Ordering::Relaxed; + // SAFETY: a texture leaves the table before it is freed, under the + // lock held by the caller (`Drop for Resource`). + let r = unsafe { &*(at as *const Resource) }; + // (Without its lock first: most were used lately or have none.) + let used = r.host.used.load(Relaxed); + if used == 0 || !fills(&r.desc) || !crate::host::long_ago(used, ms, frames) || crate::texture::host_wrote(at) { + return None; + } + let_go_made(r, at, ms, frames) +} + +/// The let go of [`let_go_copy`] and [`let_go_unmapped`] once the texture at +/// `at`, `r`, is known alive (the caller holds the table of textures' lock, +/// or a reference) and to be one whose copy may go (filled by the title, the +/// host never wrote it): its host copy goes if it has been out of use for +/// `ms` and `frames` and only the texture holds it; its bytes, if it went. +#[cfg(windows)] +fn let_go_made(r: &Resource, at: usize, ms: u64, frames: u64) -> Option<u64> { + use std::sync::atomic::Ordering::Relaxed; + let gone = { + let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + let idle = made.as_ref().is_some_and(|(host, _)| { + crate::host::long_ago(r.host.used.load(Relaxed), ms, frames) + && std::sync::Arc::strong_count(host) == 1 + && crate::host::references(&host.texture) == 1 + }); + if idle { + // Under the lock: the next use must not find the staging + // state of the texture let go (it says "uploaded"). + crate::texture::unstage(at as This); + r.host.wanted.store(u32::MAX, Relaxed); + // Under the lock too, as every write of it: nothing to take + // until the next use makes a copy and says when. + r.host.used.store(0, Relaxed); + made.take() + } else { + None + } + }; + let (host, _) = gone?; + r.host.gone.store(true, Relaxed); + KINDS[2].fetch_add(1, Relaxed); + KINDS[3].fetch_add(host.bytes, Relaxed); + let bytes = host.bytes; + crate::host::retire(host); + Some(bytes) +} + /// Sweeps made with little left to commit ([`commit_floor`]), and the host /// copies they let go beyond what the card's rule lets go, and their bytes, /// since the start. @@ -2641,8 +2811,14 @@ fn idle_rank(used: u64, remade: u32) -> u64 { (used & 0xffff_ffff) + u64::from(remade.min(8)) * 200 } -/// Since the start: looks of [`let_go_idle`], their microseconds, and the -/// longest one's. +/// Since the start: looks of [`let_go_idle`] for host copies to let go, +/// their microseconds, and the longest one's: from taking the table of +/// textures to giving it back, the look by age ([`idle_by_age`]), the walk +/// and the commit floor's walk; not the release of copies replaced before +/// it nor of placed textures after it ([`PLACED_EVICT_US`]). The look by +/// age was left out until the release of placed textures came (the timer +/// began after it), so the 2.2 and 11.6 ms of `d3d12/docs/findings.md` are +/// the walks alone. #[cfg(windows)] pub(crate) static SWEPT_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; @@ -2715,7 +2891,8 @@ pub(crate) fn targets_census() -> [u64; 12] { /// shaders write); and, of the host copies of placed textures the title /// fills, the bytes of those whose title memory is not mapped any more and /// of those a descriptor slot still shows (the card holds a texture the -/// title has given up for as long as a slot shows it). The last two are +/// title has given up for as long as a slot shows it; one nothing holds goes +/// within seconds, [`let_go_unmapped`]). The last two are /// estimates from every 16th such texture: asking Windows about the memory /// of all 16,000 takes too long. #[cfg(all(windows, feature = "diagnostics"))] @@ -2848,7 +3025,7 @@ impl Drop for HostTexture { } /// How many textures placed in title memory have a resource of ours -/// (never released), for the memory line. +/// ([`evict_placed`] releases them), for the memory line. #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn placed_textures() -> u64 { PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).len() as u64 @@ -3266,6 +3443,7 @@ fn hand_out_resource( gone: std::sync::atomic::AtomicBool::new(false), remade: std::sync::atomic::AtomicU32::new(0), placed: std::sync::atomic::AtomicBool::new(false), + named: std::sync::atomic::AtomicU64::new(0), wanted: std::sync::atomic::AtomicU32::new(u32::MAX), grown: std::sync::atomic::AtomicBool::new(false), }, @@ -3347,7 +3525,12 @@ impl Drop for Resource { crate::host::retire(twin); } } - crate::texture::forget(std::ptr::from_ref::<Resource>(self) as usize); + // What `texture::forget` clears holds textures only (staging + // buffers, textures the host copied into, alias copies): a buffer's + // release took its four global locks for nothing. + if self.desc.dimension != BUFFER { + crate::texture::forget(std::ptr::from_ref::<Resource>(self) as usize); + } crate::descriptor::forget(std::ptr::from_ref::<Resource>(self) as usize); if self.desc.dimension == BUFFER { crate::shadow::unregister( @@ -3514,9 +3697,12 @@ pub(crate) extern "system" fn create_at_address( /// resource object (device 0x230, the title's streamed and /// interface textures), by address and description: a resource at that /// 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. +/// The resource is kept while anything may name it (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, and the resource +/// itself goes once it has had no host copy and nothing has asked for it +/// for a minute ([`evict_placed`]; `LEONIDA_PLACED_EVICT=0`: kept for the +/// run, as before). #[cfg(windows)] static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32; 14]), usize>> = std::sync::Mutex::new(std::collections::BTreeMap::new()); @@ -3528,7 +3714,11 @@ static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32; /// their waits for contended locks 55 % were under `placed_texture` (profile `list-d207`, 2026-11-30; /// `view_cast_serial` alone 34 %), and the diagnostics-only count of filler twins took a second lock /// and a tree's search on most calls besides (with this on, only with `LEONIDA_PLACED_TWINS=1`). -/// What a table holds is never taken out: [`PLACED_TEXTURES`] keeps its resources for the run. +/// A texture leaves its table only when [`evict_placed`] takes it out of [`PLACED_TEXTURES`]: it is +/// taken out of the table in front first, under its write lock, and its stamp ([`Hosted::named`], +/// which [`texture_at`] sets under the shared lock) looked at once more. That is done with the switch +/// off as well: entries put in front while `LEONIDA_AB` had it on stay there, and would hand out a +/// released texture once it is on again. #[cfg(windows)] fn placed_shards() -> bool { crate::toggled!("LEONIDA_PLACED_SHARDS") @@ -3672,10 +3862,15 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> { let desc = &key; // Leonida: found before, found again under a shared lock (`placed_shards`). let shards = placed_shards(); - if shards - && let Some(&r) = placed_shard(address, desc).read().unwrap_or_else(|e| e.into_inner()).get(&(address, *desc)) - { - return Some(r as This); + if shards { + let table = placed_shard(address, desc).read().unwrap_or_else(|e| e.into_inner()); + if let Some(&r) = table.get(&(address, *desc)) { + // Stamped under the table's shared lock: [`evict_placed`] takes a + // texture out of the table under its write lock before its last + // look at the stamp. + named_now(r as This); + return Some(r as This); + } } let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); // How many resources the filler alone would have added (a count for @@ -3706,6 +3901,7 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> { } }; if let Some(&r) = map.get(&(address, *desc)) { + named_now(r as This); found(r); return Some(r as This); } @@ -3728,15 +3924,536 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> { return None; } map.insert((address, *desc), out as usize); + PLACED_ANY.store(true, std::sync::atomic::Ordering::Relaxed); found(out as usize); crate::texture::placed_in_host_written(address, desc); resource(out) .host .placed .store(true, std::sync::atomic::Ordering::Relaxed); + // Released before, after the sweep had let its copy go: the copy it gets + // is one made again, as if the resource had stayed. + let remade = GONE_PLACED.lock().unwrap_or_else(|e| e.into_inner()).take(placed_hash(&(address, *desc))); + if let Some(remade) = remade { + let host = &resource(out).host; + host.gone.store(true, std::sync::atomic::Ordering::Relaxed); + host.remade.store(remade, std::sync::atomic::Ordering::Relaxed); + } + named_now(out); Some(out) } +/// [`Hosted::named`]: placed texture `this` is handed out now (under the +/// lock of [`PLACED_TEXTURES`], or under the shared lock of its table in +/// front, [`placed_shards`]). +#[cfg(windows)] +fn named_now(this: This) { + use std::sync::atomic::Ordering::Relaxed; + let named = &resource(this).host.named; + let now = crate::host::moment(); + if named.load(Relaxed) != now { + named.store(now, Relaxed); + } +} + +/// Whether placed textures nothing has named for long and that have no host +/// copy are released ([`evict_placed`]); `LEONIDA_PLACED_EVICT=0` keeps every +/// one for the run, as before. +#[cfg(windows)] +fn placed_evict() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_PLACED_EVICT").is_none_or(|v| v != "0")) +} + +/// How long nothing must have named a placed texture ([`Hosted::named`]) for +/// [`let_go_idle`] to release it, and for how many frames: far longer than a +/// thread takes from [`texture_at`] to recording what it found, so no thread +/// can be holding the bare pointer. A texture asked for again is made again, +/// with no host copy, as on its first view; if the sweep had let its copy +/// go, the copy it gets counts as made again ([`GONE_PLACED`]). +#[cfg(windows)] +const PLACED_EVICT_MS: u64 = 60_000; +#[cfg(windows)] +const PLACED_EVICT_FRAMES: u64 = 600; + +/// Placed textures [`let_go_idle`] looks at for release at each look, from +/// where the last look stopped ([`PLACED_CURSOR`]): the table is walked under +/// its lock, which every view of a placed texture takes. +#[cfg(windows)] +const PLACED_EVICT_PART: usize = 4096; + +/// Where the next look for placed textures to release begins (`None`: at +/// the first). +#[cfg(windows)] +static PLACED_CURSOR: std::sync::Mutex<Option<(u64, [u32; 14])>> = std::sync::Mutex::new(None); + +/// Placed textures taken out of [`PLACED_TEXTURES`] ([`evict_placed`]) and +/// when, for a second and a few frames more before their reference is given +/// up ([`evicted_due`]): a thread that read the table just before (the +/// diagnostics' `placed_known` and `texture_at_made` hand out what they find +/// without a reference) is done with what it found by then, as for +/// [`REPLACED`]. +#[cfg(windows)] +static EVICTED: std::sync::Mutex<Vec<(u64, usize)>> = std::sync::Mutex::new(Vec::new()); + +/// Since the start: placed textures released, and the most in the table. +#[cfg(windows)] +pub(crate) static PLACED_EVICTED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Since the start: the microseconds of [`let_go_idle`]'s release of placed +/// textures ([`evict_placed`], [`evicted_due`] and their retire; since +/// `LEONIDA_PLACED_UNMAPPED`, [`let_go_unmapped`] too), one at each +/// of its looks ([`SWEPT_US`] counts them), and the longest one's. +#[cfg(windows)] +pub(crate) static PLACED_EVICT_US: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +#[cfg(all(windows, test))] +thread_local! { + /// Run by [`evict_placed`] on this thread for a texture it has just taken + /// out of its table in front, before it looks at the stamp again: what a + /// thread that found the texture there before would do meanwhile. + static AFTER_SHARD_REMOVAL: std::cell::Cell<Option<fn(This)>> = const { std::cell::Cell::new(None) }; +} + +/// Takes out of [`PLACED_TEXTURES`] the placed textures from key `from` on, +/// below address `below`, that can go: up to `limit` looked at. How many +/// went, and the key to go on from (`None`: the table's end was reached). +/// +/// A placed texture is made by [`texture_at`] for each address and +/// description the title ever viewed, and none was released: 18,639 of +/// them with host copies after nine minutes of run 24, where streaming gives +/// the memory of a texture to others with other descriptions. One goes when +/// - nothing named it for `ms` and `frames` ([`Hosted::named`], stamped +/// under the lock of this table or under the shared lock of its table in +/// front ([`placed_shards`]); one that would go is first taken out of the +/// table in front under its write lock, and its stamp looked at again, +/// so no thread still holds it once it has left, and one named since +/// stays); +/// - it has no host copy (never made, or let go by the sweep): no list not +/// yet reset names it and no descriptor slot shows it, since both hold the +/// copy of what they name (`HostList::transition`, `HostHeap::kept`), and +/// the sweep lets a copy go only when nothing but the texture holds it; +/// - the table holds its only reference (none taken since, as [`alias_of`] +/// takes of the textures it pins); +/// - the host never wrote it (what [`crate::texture::host_wrote`] notes of +/// it goes with the texture) and the host did not refuse it (a refused one +/// would be tried again); +/// - no descriptor slot waits for its host copy (`crate::descriptor`). +/// +/// Its last reference goes later ([`evicted_due`]), through +/// `crate::host::retire`: `Drop for Resource` takes it out of the table of +/// textures and forgets its staging state, its views and its tickets, as +/// for a texture the title releases. Keys in a list not yet reset that +/// asked `HostList::first_use` about it while it had no copy may name a new +/// texture at the same address; that list then records no upload for it +/// (not seen, and not reachable within these idle times by a list that is +/// reset every frame). +#[cfg(windows)] +fn evict_placed(from: (u64, [u32; 14]), below: u64, ms: u64, frames: u64, limit: usize) -> (u64, Option<(u64, [u32; 14])>) { + use std::sync::atomic::Ordering::Relaxed; + let mut gone = Vec::new(); + let mut next = None; + if from >= (below, [0; 14]) { + return (0, None); + } + { + let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + PLACED_EVICTED[1].fetch_max(map.len() as u64, Relaxed); + for (looked, (&key, &at)) in map.range(from..(below, [0; 14])).enumerate() { + if looked == limit { + next = Some(key); + break; + } + // SAFETY: the table holds a reference to each texture in it. + let r = unsafe { &*(at as *const Resource) }; + let mut goes = crate::host::long_ago(r.host.named.load(Relaxed), ms, frames) + && crate::object::references(at as This) == 1 + && !r.host.refused.load(Relaxed) + && !crate::texture::host_wrote(at) + && !crate::descriptor::waits(at) + && r.host.made.lock().unwrap_or_else(|e| e.into_inner()).is_none(); + // Found in the tables in front (`placed_shards`) without this + // table's lock: taken out of there first, under the write lock, + // and the stamp looked at again (a thread that found it before + // stamped it under the shared lock). Kept if it was named since; + // the next look for it here puts it back in front. Whatever the + // switch says now: `LEONIDA_AB` can turn it off and on again, and + // an entry put there while it was on would otherwise outlive the + // texture and be handed out once it is on again. + if goes { + placed_shard(key.0, &key.1).write().unwrap_or_else(|e| e.into_inner()).remove(&key); + #[cfg(test)] + if let Some(hook) = AFTER_SHARD_REMOVAL.with(std::cell::Cell::get) { + hook(at as This); + } + goes = crate::host::long_ago(r.host.named.load(Relaxed), ms, frames); + } + if goes { + gone.push(key); + } + } + let now = crate::host::moment(); + let mut evicted = EVICTED.lock().unwrap_or_else(|e| e.into_inner()); + let mut gone_placed = GONE_PLACED.lock().unwrap_or_else(|e| e.into_inner()); + for key in &gone { + if let Some(at) = map.remove(key) { + // SAFETY: the reference the table held goes with it, later. + let r = unsafe { &*(at as *const Resource) }; + if r.host.gone.load(Relaxed) { + gone_placed.keep(placed_hash(key), r.host.remade.load(Relaxed), GONE_PLACED_MOST); + } + evicted.push((now, at)); + } + } + } + PLACED_EVICTED[0].fetch_add(gone.len() as u64, Relaxed); + (gone.len() as u64, next) +} + +/// Placed textures [`evict_placed`] released after the sweep had let their +/// host copy go ([`Hosted::gone`]): how many times that copy was made again +/// ([`Hosted::remade`]), by a hash of their key in [`PLACED_TEXTURES`] +/// ([`placed_hash`]). [`texture_at`] hands both to the texture it makes anew +/// for that key, so that its first copy counts as made again ([`KINDS`] on +/// the memory line, [`favour_reused`], the card's accounting of copies gone +/// against never made), as it did while the resource stayed. The newest +/// [`GONE_PLACED_MOST`] only: the copy of one forgotten counts as a first. +/// Taken after the lock of [`PLACED_TEXTURES`]. +#[cfg(windows)] +static GONE_PLACED: std::sync::Mutex<GonePlaced> = std::sync::Mutex::new(GonePlaced::new()); + +/// How many [`GONE_PLACED`] keeps, a few MB: sixteen of the sweep's looks +/// that release all they look at ([`PLACED_EVICT_PART`]). +#[cfg(windows)] +const GONE_PLACED_MOST: usize = 1 << 16; + +/// See [`GONE_PLACED`]. +#[cfg(windows)] +struct GonePlaced { + /// By key hash: the times made again, and when it was kept ([`Self::next`]). + by_key: std::collections::BTreeMap<u64, (u32, u64)>, + /// Key hashes as they were kept and when, the oldest first; one whose + /// time is no longer that of its entry was taken or kept again since. + order: std::collections::VecDeque<(u64, u64)>, + next: u64, +} + +#[cfg(windows)] +impl GonePlaced { + const fn new() -> Self { + Self { by_key: std::collections::BTreeMap::new(), order: std::collections::VecDeque::new(), next: 0 } + } + + /// Keeps `remade` for `key`, forgetting the oldest beyond `most`. + fn keep(&mut self, key: u64, remade: u32, most: usize) { + self.by_key.insert(key, (remade, self.next)); + self.order.push_back((key, self.next)); + self.next += 1; + let live = |by_key: &std::collections::BTreeMap<u64, (u32, u64)>, &(key, at): &(u64, u64)| { + by_key.get(&key).is_some_and(|&(_, kept)| kept == at) + }; + while self.by_key.len() > most || self.order.front().is_some_and(|front| !live(&self.by_key, front)) { + let Some(front) = self.order.pop_front() else { + break; + }; + if live(&self.by_key, &front) { + self.by_key.remove(&front.0); + } + } + // Taken ones behind a live front: dropped once they are as many again. + if self.order.len() > 2 * most.max(1) { + let by_key = &self.by_key; + self.order.retain(|entry| live(by_key, entry)); + } + } + + /// The times made again kept for `key`, forgotten here. + fn take(&mut self, key: u64) -> Option<u32> { + self.by_key.remove(&key).map(|(remade, _)| remade) + } +} + +/// The hash [`GONE_PLACED`] keeps a key of [`PLACED_TEXTURES`] by: two keys +/// with one hash would only share their count. +#[cfg(windows)] +fn placed_hash(key: &(u64, [u32; 14])) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::hash::DefaultHasher::new(); + key.hash(&mut hasher); + hasher.finish() +} + +/// The placed textures [`evict_placed`] took out of the table `ms` and +/// `frames` ago or more, each with the reference the table held. +#[cfg(windows)] +fn evicted_due(ms: u64, frames: u64) -> Vec<Held> { + let mut evicted = EVICTED.lock().unwrap_or_else(|e| e.into_inner()); + let (due, keep): (Vec<_>, Vec<_>) = evicted.drain(..).partition(|&(at, _)| crate::host::long_ago(at, ms, frames)); + *evicted = keep; + due.into_iter().map(|(_, at)| Held(at as This)).collect() +} + +/// Whether the host copies of placed textures whose title memory the title +/// unmapped or freed go at the sweep's next look ([`let_go_unmapped`]), once +/// out of use for [`UNMAPPED_IDLE_MS`] and [`UNMAPPED_IDLE_FRAMES`] frames +/// and held by nothing but the texture, instead of after the card's idle +/// time (ten minutes while it has room); `LEONIDA_PLACED_UNMAPPED=0`: kept +/// until then, as before. Measured in a world run on the RX 7900 XT before +/// it: 1,443 MB of host copies of placed textures whose first page was not +/// mapped any more (the memory line's estimate from every 16th, `census`), +/// none of them shown by a descriptor slot. +/// +/// On by default: a copy goes on the same terms as the sweep's own let go +/// ([`let_go_copy`]: no list not yet reset and no descriptor slot holds it, +/// no slot waits for it, the host never wrote it), only sooner, and only +/// while the texture's first page is still not mapped when the sweep looks. +/// A texture the title maps memory under again and views is made again from +/// title memory, as any copy the sweep let go. What changes is when a copy +/// goes, never what a draw reads while it has one; the tests cover a copy a +/// list holds, one a slot holds, one used lately and memory mapped again +/// before the look. +#[cfg(windows)] +fn placed_unmapped() -> bool { + crate::toggled!("LEONIDA_PLACED_UNMAPPED") +} + +/// How long a placed texture whose title memory was unmapped must be out of +/// use for [`let_go_unmapped`] to let its host copy go, and for how many +/// frames: as the sweep's look under the commit floor ([`FLOOR_IDLE_MS`]), +/// far longer than a thread takes from [`host_resource`] (which hands out +/// the copy without holding it) to recording its use. +#[cfg(windows)] +const UNMAPPED_IDLE_MS: u64 = FLOOR_IDLE_MS; +#[cfg(windows)] +const UNMAPPED_IDLE_FRAMES: u64 = FLOOR_IDLE_FRAMES; + +/// Placed textures [`let_go_unmapped`] looks at in one look of the sweep, +/// from where the last one stopped: each costs a question about its first +/// page (`crate::texture::committed`). +#[cfg(windows)] +const UNMAPPED_PART: usize = 4096; + +/// How many ranges [`UNMAPPED`] keeps before neighbours are joined: the +/// runtime unmaps physical pages one 64 KiB view at a time. +#[cfg(windows)] +const UNMAPPED_MOST: usize = 4096; + +/// Whether [`texture_at`] ever made a placed texture: until then the title's +/// unmappings are not noted ([`title_memory_unmapped`]). +#[cfg(windows)] +static PLACED_ANY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Title memory unmapped or freed since the sweep last looked +/// ([`title_memory_unmapped`]), as ranges of addresses; joined into fewer, +/// wider ones beyond [`UNMAPPED_MOST`] (a wider range only puts more +/// textures to the test of their first page). A lock of its own, taken +/// under the runtime's locks and taking none. +#[cfg(windows)] +static UNMAPPED: std::sync::Mutex<Vec<(u64, u64)>> = std::sync::Mutex::new(Vec::new()); + +/// Keys of [`PLACED_TEXTURES`] whose first page lay in memory the title +/// unmapped, while [`let_go_unmapped`] has yet to let their host copy go +/// or find that it never will (memory mapped there for +/// [`UNMAPPED_MAPPED_MS`], no copy, one the sweep never takes, the texture +/// released), with since when (`crate::host::moment`) its first page has +/// been found mapped at every look; and where the next look begins. Taken +/// after the lock of [`PLACED_TEXTURES`]. +#[cfg(windows)] +#[allow(clippy::type_complexity)] +static UNMAPPED_PLACED: std::sync::Mutex<( + std::collections::BTreeMap<(u64, [u32; 14]), Option<u64>>, + Option<(u64, [u32; 14])>, +)> = std::sync::Mutex::new((std::collections::BTreeMap::new(), None)); + +/// How long [`let_go_unmapped`] keeps looking at a texture whose first page +/// it finds mapped before it gives it up: the title is told of an unmapping +/// before the memory goes (`crate::watch::title_memory_unmapping` before +/// `UnmapViewOfFile2`; xmem tells all of a change's unmappings before its +/// calls; `crate::watch::title_memory_freed` before the free, which can fail +/// and be done later). A look in between found the page still mapped and +/// gave the texture up at once: its copy waited for the card's idle time. +/// Memory mapped there again for this long is taken to be the title's again. +/// A free the host refuses until a heap goes and that is done later than +/// this (`crate::inplace::title_memory_free_held`, up to 30 s) still leaves +/// its copies to the card's idle time. +#[cfg(windows)] +const UNMAPPED_MAPPED_MS: u64 = 5_000; + +/// Since the start: host copies [`let_go_unmapped`] let go, and their bytes. +#[cfg(windows)] +pub(crate) static PLACED_UNMAPPED_GONE: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The title is about to unmap or free its memory `[at, at + len)` +/// (`crate::watch::title_memory_unmapping`, `title_memory_freed`): the +/// placed textures whose first page lies there are looked at by the sweep's +/// next look ([`let_go_unmapped`]). Noted only, under a lock of its own: +/// the runtime calls this with its locks held, and [`texture_at`] takes +/// locks of the watch while it holds [`PLACED_TEXTURES`]. Whether the memory +/// is still unmapped is asked at the look: a free can fail, and the title +/// can map memory there again in between. +#[cfg(windows)] +pub(crate) fn title_memory_unmapped(at: usize, len: usize) { + if len == 0 || !unmappings_noted() { + return; + } + let mut ranges = UNMAPPED.lock().unwrap_or_else(|e| e.into_inner()); + ranges.push((at as u64, at.saturating_add(len) as u64)); + if ranges.len() > UNMAPPED_MOST { + crate::descriptor::host::compact(&mut ranges, UNMAPPED_MOST); + } +} + +/// Whether [`title_memory_unmapped`] notes what it is told: the switch is on +/// and [`texture_at`] ever made a placed texture (for +/// `crate::watch::title_memory_freed` too, which asks where a whole +/// allocation ends only then). +#[cfg(windows)] +pub(crate) fn unmappings_noted() -> bool { + PLACED_ANY.load(std::sync::atomic::Ordering::Relaxed) && placed_unmapped() +} + +/// For tests without a device: as if [`texture_at`] had made a placed +/// texture, so that [`unmappings_noted`]. +#[cfg(all(windows, test))] +pub(crate) fn placed_any_for_test() { + PLACED_ANY.store(true, std::sync::atomic::Ordering::Relaxed); +} + +/// What [`let_go_unmapped`] makes of a placed texture it looks at. +#[cfg(any(windows, test))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Unmapped { + /// Its host copy went (its bytes). + Gone(u64), + /// Looked at again at a later look: its copy is in use or held. + Again, + /// Its first page is mapped: looked at again until it has been for + /// [`UNMAPPED_MAPPED_MS`] (the unmapping may not be done yet). + Mapped, + /// Not looked at again: it has no copy, or the sweep never takes its + /// copy. + Done, +} + +/// The step of [`let_go_unmapped`] for one texture, from what is known of +/// it: whether it has a host copy, whether the sweep may take that copy at +/// all (one the title fills and the host never wrote), whether its first +/// page is mapped now, whether its copy is out of use and no descriptor +/// slot waits for it; `let_go` lets the copy go if only the texture holds +/// it, and says its bytes. +#[cfg(any(windows, test))] +fn unmapped_step( + copy: bool, + takes: bool, + mapped: impl FnOnce() -> bool, + idle: impl FnOnce() -> bool, + let_go: impl FnOnce() -> Option<u64>, +) -> Unmapped { + if !copy || !takes { + return Unmapped::Done; + } + if mapped() { + return Unmapped::Mapped; + } + if !idle() { + return Unmapped::Again; + } + let_go().map_or(Unmapped::Again, Unmapped::Gone) +} + +/// For [`let_go_idle`]: lets go of the host copies of placed textures whose +/// first page lies in memory the title unmapped or freed +/// ([`title_memory_unmapped`]) and is not mapped now, once out of use for +/// `ms` and `frames` and held by nothing but the texture: no list not yet +/// reset, no descriptor slot ([`let_go_made`]), no slot waiting for it +/// (`crate::descriptor::waits`). Up to `limit` of those noted are looked at, +/// from where the last look stopped; one whose first page is found mapped at +/// every look for `mapped_ms` is given up (the title's again). How many went +/// and their bytes. +/// +/// The textures stay in [`PLACED_TEXTURES`] (their address is what views +/// and lists name; [`evict_placed`] releases them later as any): one the +/// title maps memory under again and views is made again from title memory +/// at its next use. Each is looked at with a reference of ours, taken under +/// the table's lock and given back after, so none is released meanwhile +/// ([`evict_placed`] wants the table's reference alone) and no other lock +/// is taken under the table's. +#[cfg(windows)] +fn let_go_unmapped(ms: u64, frames: u64, mapped_ms: u64, limit: usize) -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + let ranges = std::mem::take(&mut *UNMAPPED.lock().unwrap_or_else(|e| e.into_inner())); + let held: Vec<((u64, [u32; 14]), Held)> = { + let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + let mut marked = UNMAPPED_PLACED.lock().unwrap_or_else(|e| e.into_inner()); + let (keys, from) = &mut *marked; + // (Unmapped again: found mapped since a new unmapping only.) + for (start, end) in ranges { + keys.extend(map.range((start, [0; 14])..(end, [0; 14])).map(|(&key, _)| (key, None))); + } + let start = from.take().unwrap_or((0, [0; 14])); + let part: Vec<_> = keys.range(start..).chain(keys.range(..start)).take(limit).map(|(&key, _)| key).collect(); + if part.len() == limit { + *from = keys.range(part[limit - 1]..).nth(1).map(|(&key, _)| key); + } + let mut held = Vec::with_capacity(part.len()); + for key in part { + match map.get(&key) { + Some(&at) => { + crate::object::add_ref(at as This); + held.push((key, Held(at as This))); + } + None => { + keys.remove(&key); + } + } + } + held + }; + let (mut went, mut bytes, mut done, mut mapped) = (0, 0, Vec::new(), Vec::new()); + for (key, texture) in &held { + let at = texture.get() as usize; + let r = resource(texture.get()); + let step = unmapped_step( + r.host.used.load(Relaxed) != 0, + fills(&r.desc) && !crate::texture::host_wrote(at), + // Its first page, as the memory line asks ([`census`]). + || crate::texture::committed(r.data().cast_const(), 1), + || crate::host::long_ago(r.host.used.load(Relaxed), ms, frames) && !crate::descriptor::waits(at), + || let_go_made(r, at, ms, frames), + ); + match step { + Unmapped::Gone(gone) => { + went += 1; + bytes += gone; + done.push(*key); + } + Unmapped::Done => done.push(*key), + Unmapped::Again => mapped.push((*key, false)), + Unmapped::Mapped => mapped.push((*key, true)), + } + } + drop(held); + if !done.is_empty() || !mapped.is_empty() { + let now = crate::host::moment(); + let mut marked = UNMAPPED_PLACED.lock().unwrap_or_else(|e| e.into_inner()); + for key in &done { + marked.0.remove(key); + } + for (key, found) in mapped { + let Some(since) = marked.0.get_mut(&key) else { continue }; + if !found { + *since = None; + } else if crate::host::long_ago(*since.get_or_insert(now), mapped_ms, 0) { + marked.0.remove(&key); + } + } + } + PLACED_UNMAPPED_GONE[0].fetch_add(went, Relaxed); + PLACED_UNMAPPED_GONE[1].fetch_add(bytes, Relaxed); + (went, bytes) +} + pub(crate) extern "system" fn create_placed( _: This, heap: This, @@ -3856,7 +4573,7 @@ extern "system" fn gpu_address(this: This) -> u64 { if at >> 40 != 0 { static ONCE: [std::sync::Once; 2] = [std::sync::Once::new(), std::sync::Once::new()]; let backing = match r.backing { - Backing::Committed(ref m) => format!("committed, attributes {:?}", m.attributes), + Backing::Committed(ref m) => format!("committed, memory {:?}", m.source), Backing::Placed { offset, .. } => format!("placed in a heap at {offset:#x}"), Backing::Address(_) => "at a title address".into(), }; @@ -4040,6 +4757,24 @@ mod tests { } } + /// A buffer's release leaves the texture maps (`texture::forget`) alone; + /// a texture's still clears them. + #[cfg(windows)] + #[test] + fn only_a_texture_release_clears_the_texture_maps() { + let forgotten = || crate::texture::FORGOTTEN.with(std::cell::Cell::get); + let null = std::ptr::null(); + let before = forgotten(); + let mut data = null; + assert_eq!(create_committed(null, &PROPERTIES, 0, &buffer(4096), 0, null.cast(), &RESOURCE_IIDS[0], &mut data), S_OK); + crate::object::release_boxed::<Resource>(data); + assert_eq!(forgotten(), before, "a buffer's release"); + let mut image = null; + assert_eq!(create_committed(null, &PROPERTIES, 0, &texture(4, 4, 28, 1), 0, null.cast(), &RESOURCE_IIDS[0], &mut image), S_OK); + crate::object::release_boxed::<Resource>(image); + assert_eq!(forgotten(), before + 1, "a texture's release"); + } + fn heap(size: u64) -> This { let desc = HeapDesc { size, @@ -4080,6 +4815,51 @@ mod tests { ); } + /// What this test's heaps got and gave back ([`watched_heap_memory`]). + #[cfg(windows)] + static HEAP_MEMORY_FREED: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new()); + + /// A [`HeapMemory`] as leonida-hle's (xmem `heap_memory`): a + /// write-watched reservation of its own. + #[cfg(windows)] + fn watched_heap_memory(size: usize, _align: usize) -> *mut c_void { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + // SAFETY: a fresh reservation of our choice. + unsafe { VirtualAlloc(std::ptr::null(), size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } + } + + #[cfg(windows)] + fn watched_heap_free(at: *mut c_void) { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, VirtualFree}; + HEAP_MEMORY_FREED.lock().unwrap().push(at as usize); + // SAFETY: a reservation of `watched_heap_memory`'s. + assert_ne!(unsafe { VirtualFree(at, 0, MEM_RELEASE) }, 0); + } + + /// A heap the title makes takes the runtime's memory, which is + /// write-watched: the GPU side asks the kernel which of its pages were + /// written, where of our allocator's memory it knew nothing (and copies + /// of it were taken whole). It goes back to the runtime with the heap. + #[cfg(windows)] + #[test] + fn heaps_take_the_runtimes_write_watched_memory() { + const LEN: usize = 4 << 20; + TEST_HEAP_MEMORY.set(Some((watched_heap_memory, watched_heap_free))); + let heap = heap(LEN as u64); + TEST_HEAP_MEMORY.set(None); + // SAFETY: a heap we just made. + let at = unsafe { (*heap.cast::<Heap>()).memory.address() } as usize; + assert_eq!(at as u64 % KIB_64, 0); + assert!(crate::watch::writes(at, at + LEN, true).is_some(), "nothing is known of what is written in the heap at {at:#x}"); + // SAFETY: inside the heap's memory. + unsafe { (at as *mut u8).add(3 * crate::watch::PAGE + 17).write(1) }; + let (_, written) = crate::watch::writes(at, at + LEN, true).expect("write-watched"); + assert!(written.iter().any(|&(page, _)| page == at / crate::watch::PAGE + 3), "{written:?}"); + assert_eq!(slot::<Release>(heap, 0x10)(heap), 0); + assert!(HEAP_MEMORY_FREED.lock().unwrap().contains(&at), "the heap's memory never went back"); + } + #[test] fn device_setup_heap_properties_and_resources_at_addresses() { let device = crate::device::device(); @@ -5583,4 +6363,531 @@ float4 lit() : SV_Target { return 1.0; } assert_eq!((more.base, d.Width, d.MipLevels), (0, 256, 9)); assert!(more.serial != copy.serial && more.grown.load(std::sync::atomic::Ordering::Relaxed)); } + + /// With the sweep off (`LEONIDA_TEXTURE_SWEEP=0`), a host copy replaced + /// by one with more levels still goes once nothing may be about to + /// record its use: nothing else lets it go. In a process of its own, + /// since the switch is read once. + #[cfg(windows)] + #[test] + fn replaced_copies_go_with_the_sweep_off() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const CHILD: &str = "LEONIDA_REPLACED_CHILD"; + if std::env::var_os(CHILD).is_none() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "resource::tests::replaced_copies_go_with_the_sweep_off", "--nocapture"]) + .env(CHILD, "1") + .env("LEONIDA_TEXTURE_SWEEP", "0") + .output() + .unwrap(); + assert!( + out.status.success(), + "the run with the sweep off failed:\n{}\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + return; + } + if crate::host::host().is_none() || !held_only() { + return; + } + // As in `a_placed_texture_is_kept_from_the_level_viewed`: a copy from + // level 2, replaced by one from level 0. + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = placed_bytes(&desc).unwrap(); + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + let texture = texture_at(at as u64, &desc).unwrap(); + want_level(texture, 2); + let copy = host_copy(texture).unwrap(); + want_level(texture, 0); + let replaced = || { + let replaced = REPLACED.lock().unwrap_or_else(|e| e.into_inner()); + replaced.iter().any(|(_, (old, _))| std::sync::Arc::ptr_eq(old, ©)) + }; + assert!(replaced()); + // Long enough ago: four frames and a second. + for _ in 0..4 { + crate::frame::test_advance(); + } + std::thread::sleep(std::time::Duration::from_millis(1200)); + let_go_idle(); + assert!(!replaced(), "the replaced copy is still held"); + } + + /// A texture whose host copy the sweep let go is out of its look by age + /// until a use makes the copy again: under pressure that look sorted + /// every texture whose copy had ever gone, at each look + /// (RS-PLACED-SWEEP-GONE-COPIES). A copy replaced by one with more + /// levels is out of it as well until that one is made. + #[cfg(windows)] + #[test] + fn a_copy_let_go_leaves_the_look_by_age() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + if crate::host::host().is_none() { + return; + } + // A frame begun: in a process's first tenth of a second without one + // the moment is 0, which `used` reads as no copy. + crate::frame::test_advance(); + // As in `a_placed_texture_is_kept_from_the_level_viewed`. + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = placed_bytes(&desc).unwrap() as usize; + const N: usize = 4; + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole * N, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + assert!(!at.is_null()); + let placed: Vec<usize> = + (0..N).map(|i| texture_at(at as u64 + (i * whole) as u64, &desc).unwrap() as usize).collect(); + for &texture in &placed { + drop(host_copy(texture as This).unwrap()); + } + let ours = |by_age: &[(u64, usize)]| by_age.iter().filter(|(_, at)| placed.contains(at)).count(); + { + let all = textures(); + assert_eq!(ours(&idle_by_age(&all, 0, 0)), N, "the copies just made are not in the look"); + for &texture in &placed { + assert!(let_go_copy(&all, texture, 0, 0).is_some(), "a copy only its texture holds stayed"); + } + assert_eq!(ours(&idle_by_age(&all, 0, 0)), 0, "textures whose copy was let go are still looked at by age"); + assert!(placed.iter().all(|&texture| let_go_copy(&all, texture, 0, 0).is_none())); + } + // Made again on the next use (from level 2, as a view asks): back in + // the look. + if held_only() { + want_level(placed[0] as This, 2); + } + let again = host_copy(placed[0] as This).unwrap(); + assert_eq!(ours(&idle_by_age(&textures(), 0, 0)), 1); + drop(again); + // Replaced by one from level 0, not made yet: out of it. + if held_only() { + want_level(placed[0] as This, 0); + assert_eq!(ours(&idle_by_age(&textures(), 0, 0)), 0, "a replaced copy is still looked at by age"); + } + } + + /// Placed textures that nothing has named for long and that have no host + /// copy leave their table, a part at each look, and are released a while + /// later; one named lately, one with another reference and one with a + /// host copy stay; one asked for again is made again. + #[cfg(windows)] + #[test] + fn placed_textures_nothing_names_are_released() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + // As in `a_copy_let_go_leaves_the_look_by_age`. + crate::frame::test_advance(); + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = placed_bytes(&desc).unwrap() as usize; + const N: usize = 8; + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole * N, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) } as u64; + assert!(at != 0); + let below = at + (whole * N) as u64; + let key = |i: usize| (at + (i * whole) as u64, desc); + let placed: Vec<usize> = (0..N).map(|i| texture_at(key(i).0, &desc).unwrap() as usize).collect(); + let in_table = || { + let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + map.range((at, [0; 14])..(below, [0; 14])).count() + }; + assert_eq!(in_table(), N); + // Named a moment ago: none goes by the times the sweep gives. + assert_eq!(evict_placed(key(0), below, PLACED_EVICT_MS, PLACED_EVICT_FRAMES, usize::MAX), (0, None)); + // One with a reference of its own, one with a host copy (with a card). + crate::object::add_ref(placed[0] as This); + let copy = crate::host::host().map(|_| host_copy(placed[1] as This).unwrap()); + let kept = 1 + usize::from(copy.is_some()); + // A part: the first four looked at, the next look from the fifth. + let (first, next) = evict_placed(key(0), below, 0, 0, 4); + assert_eq!((first, next), ((4 - kept) as u64, Some(key(4))), "placed textures nothing names stayed"); + assert_eq!(evict_placed(next.unwrap(), below, 0, 0, usize::MAX), (4, None)); + assert_eq!(in_table(), kept); + // Released after a while, not at once: a thread that read the table + // just before may still look at what it found. + let ours = |held: &[Held]| held.iter().filter(|h| placed.contains(&(h.get() as usize))).count(); + let early = evicted_due(60_000, 600); + assert_eq!(ours(&early), 0); + drop(early); + assert!(placed[kept..].iter().all(|&p| textures().contains(&p))); + assert!(placed[kept..].iter().all(|&p| crate::object::references(p as This) == 1)); + let due = evicted_due(0, 0); + assert_eq!(ours(&due), N - kept); + { + // (No placed texture is made meanwhile at an address just freed.) + let _placed = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + drop(due); + let all = textures(); + assert!(placed[kept..].iter().all(|p| !all.contains(p)), "a released placed texture is still in the table of textures"); + } + // Asked for again: made again, as on its first view. + let again = texture_at(key(N - 1).0, &desc).unwrap(); + assert_eq!(in_table(), kept + 1); + assert!(resource(again).host.placed.load(std::sync::atomic::Ordering::Relaxed)); + if crate::host::host().is_some() { + assert!(host_copy(again).is_some()); + } + crate::object::release(placed[0] as This); + drop(copy); + } + + /// A placed texture that leaves [`PLACED_TEXTURES`] leaves its table in + /// front ([`placed_shards`]) too, whatever the switch says at that look: + /// one put there while `LEONIDA_AB` had it on and released while it was + /// off was handed out, freed, once it was on again. + #[cfg(windows)] + #[test] + fn a_released_placed_texture_leaves_the_tables_in_front() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + // As in `placed_textures_nothing_names_are_released`. + crate::frame::test_advance(); + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = placed_bytes(&desc).unwrap() as usize; + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) } as u64; + assert!(at != 0); + let old = texture_at(at, &desc).unwrap(); + let in_front = || placed_shard(at, &desc).read().unwrap_or_else(|e| e.into_inner()).get(&(at, desc)).copied(); + // In front as a look with the switch on leaves it, whether it is on now or not. + placed_shard(at, &desc).write().unwrap_or_else(|e| e.into_inner()).insert((at, desc), old as usize); + assert_eq!(evict_placed((at, [0; 14]), at + whole as u64, 0, 0, usize::MAX), (1, None)); + assert_eq!(in_front(), None, "a released placed texture is still in its table in front"); + // Asked for again: made anew, not the one released. + let again = texture_at(at, &desc).unwrap(); + assert_ne!(again, old, "a released placed texture was handed out again"); + } + + /// A placed texture named after [`evict_placed`] took it out of its table + /// in front, as a thread that found it there before does under the shared + /// lock, stays: it is not released, and asked for again it is the same. + /// One named long ago, with nothing in between, goes. + #[cfg(windows)] + #[test] + fn a_placed_texture_named_while_it_leaves_the_table_in_front_stays() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + // As in `placed_textures_nothing_names_are_released`. + crate::frame::test_advance(); + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = placed_bytes(&desc).unwrap() as usize; + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole * 2, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) } as u64; + assert!(at != 0); + let other = at + whole as u64; + let below = other + whole as u64; + let (named, idle) = (texture_at(at, &desc).unwrap(), texture_at(other, &desc).unwrap()); + // Both in front, and both unnamed for the frames asked below. + for (key, r) in [(at, named), (other, idle)] { + placed_shard(key, &desc).write().unwrap_or_else(|e| e.into_inner()).insert((key, desc), r as usize); + } + for _ in 0..3 { + crate::frame::test_advance(); + } + let in_table = |key: u64| PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).contains_key(&(key, desc)); + // Named once it has left the table in front: only that one is kept. + static NAMED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + NAMED.store(named as usize, std::sync::atomic::Ordering::Relaxed); + AFTER_SHARD_REMOVAL.with(|hook| { + hook.set(Some(|r| { + if r as usize == NAMED.load(std::sync::atomic::Ordering::Relaxed) { + named_now(r); + } + })); + }); + let gone = evict_placed((at, [0; 14]), below, 0, 3, usize::MAX); + AFTER_SHARD_REMOVAL.with(|hook| hook.set(None)); + assert_eq!(gone, (1, None), "a texture named after it left the table in front was released"); + assert!(in_table(at) && !in_table(other)); + assert_eq!(texture_at(at, &desc).unwrap(), named, "a texture named while it left was not the one handed out"); + } + + /// A placed texture released after the sweep had let its host copy go + /// and made anew for its key keeps that: its first copy counts as made + /// again, with the times before ([`KINDS`], [`favour_reused`]), not as + /// a first make. One whose copy never went starts afresh. + #[cfg(windows)] + #[test] + fn a_released_placed_texture_made_anew_keeps_its_copy_made_again() { + use std::sync::atomic::Ordering::Relaxed; + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + // As in `placed_textures_nothing_names_are_released`. + crate::frame::test_advance(); + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = placed_bytes(&desc).unwrap() as usize; + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole * 2, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) } as u64; + assert!(at != 0); + let below = at + (whole * 2) as u64; + let (went, kept) = (texture_at(at, &desc).unwrap(), texture_at(at + whole as u64, &desc).unwrap()); + // As the sweep leaves one whose copy it let go, made again twice and + // let go again since. + resource(went).host.gone.store(true, Relaxed); + resource(went).host.remade.store(2, Relaxed); + assert!(!resource(kept).host.gone.load(Relaxed)); + assert_eq!(evict_placed((at, [0; 14]), below, 0, 0, usize::MAX), (2, None)); + // (Their last references go with the next look of the sweep; not + // taken here, where another test may be counting what is due.) + let again = texture_at(at, &desc).unwrap(); + assert!(resource(again).host.gone.load(Relaxed), "a placed texture made anew forgot that its copy was let go"); + assert_eq!(resource(again).host.remade.load(Relaxed), 2); + let fresh = texture_at(at + whole as u64, &desc).unwrap(); + assert!(!resource(fresh).host.gone.load(Relaxed)); + assert_eq!(resource(fresh).host.remade.load(Relaxed), 0); + // Its next copy is one made again (with a card). + if crate::host::host().is_some() { + drop(host_copy(again).unwrap()); + assert_eq!(resource(again).host.remade.load(Relaxed), 3); + } + // Handed over once: released and made anew again without a copy + // let go in between, it would have started afresh. + assert_eq!(GONE_PLACED.lock().unwrap_or_else(|e| e.into_inner()).take(placed_hash(&(at, desc))), None); + } + + /// [`GonePlaced`] keeps the newest `most`, a key kept again counting as + /// new, and drops the order of those taken. + #[cfg(windows)] + #[test] + fn gone_placed_keeps_the_newest() { + let mut gone = GonePlaced::new(); + gone.keep(1, 10, 2); + gone.keep(2, 20, 2); + gone.keep(1, 11, 2); + gone.keep(3, 30, 2); + assert_eq!((gone.take(2), gone.take(1), gone.take(3)), (None, Some(11), Some(30))); + for key in 0..100 { + gone.keep(key, 0, 2); + assert_eq!(gone.take(key), Some(0)); + } + gone.keep(7, 1, 2); + assert!(gone.order.len() <= 5, "taken keys left in the order: {}", gone.order.len()); + assert_eq!(gone.by_key.len(), 1); + } + + /// [`unmapped_step`]: a texture with no host copy and one whose copy the + /// sweep never takes are done with, without asking more; one whose first + /// page is mapped is told apart, without asking more; one in use, or + /// whose copy something else holds, is looked at again; the rest goes. + #[test] + fn an_unmapped_placed_texture_s_step() { + let never = || -> bool { panic!("asked") }; + let never_go = || -> Option<u64> { panic!("let go") }; + assert_eq!(unmapped_step(false, true, never, never, never_go), Unmapped::Done); + assert_eq!(unmapped_step(true, false, never, never, never_go), Unmapped::Done); + assert_eq!(unmapped_step(true, true, || true, never, never_go), Unmapped::Mapped); + assert_eq!(unmapped_step(true, true, || false, || false, never_go), Unmapped::Again); + assert_eq!(unmapped_step(true, true, || false, || true, || None), Unmapped::Again); + assert_eq!(unmapped_step(true, true, || false, || true, || Some(4096)), Unmapped::Gone(4096)); + } + + /// Taken by the tests that call [`let_go_unmapped`] with times of their + /// own: a look takes every texture noted, another test's too. + #[cfg(windows)] + static UNMAPPED_LOOKS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + /// RS-PLACED-UNMAPPED-RELEASE. The host copy of a placed texture whose + /// title memory the title unmapped goes at the sweep's look once nothing + /// but the texture holds it, without the card's idle time; one a list + /// holds, one a descriptor slot holds and one used lately stay, as does + /// one over memory mapped again before the look and one over memory + /// nobody unmapped. Mapped again with other bytes, the texture is made + /// again from title memory and the card reads the new bytes. + #[cfg(windows)] + #[test] + fn a_placed_texture_s_copy_goes_with_its_memory_and_is_made_again() { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_DECOMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree}; + const COPY_SOURCE: u32 = 0x800; + let Some(host) = crate::host::host() else { return }; + if !placed_unmapped() { + return; + } + let _looks = UNMAPPED_LOOKS.lock().unwrap_or_else(|e| e.into_inner()); + // As in `a_copy_let_go_leaves_the_look_by_age`. + crate::frame::test_advance(); + // 256x256 BC7, nine levels; each texture in memory of its own (a + // reservation that stays, as in the tests above). + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = placed_bytes(&desc).unwrap() as usize; + const GOES: usize = 0; + const LIST: usize = 1; + const SLOT: usize = 2; + const AGAIN: usize = 3; + const STAYS: usize = 4; + let memory: Vec<*mut u8> = (0..5) + // SAFETY: memory of our own that stays. + .map(|_| unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>()) + .collect(); + assert!(memory.iter().all(|at| !at.is_null())); + let paint = |at: *mut u8, seed: usize| { + // SAFETY: memory of ours, committed. + unsafe { (0..whole).for_each(|i| at.add(i).write((i * seed + i / 509 + seed) as u8)) }; + }; + memory.iter().for_each(|&at| paint(at, 13)); + let placed: Vec<This> = memory.iter().map(|&at| texture_at(at as u64, &desc).unwrap()).collect(); + for &texture in &placed { + want_level(texture, 0); + } + let copies: Vec<_> = placed.iter().map(|&texture| host_copy(texture).unwrap()).collect(); + let made = |i: usize| resource(placed[i]).host.made.lock().unwrap_or_else(|e| e.into_inner()).is_some(); + // A list holds the second's copy, a slot the third's (a reference to + // its host texture, as `HostHeap::kept` takes). + let mut list_holds = Some(copies[LIST].clone()); + let mut slot_holds = Some(copies[SLOT].texture.clone()); + drop(copies); + // The title unmaps all but the last; the fourth is mapped again, with + // other bytes, before the sweep looks. + let unmap = |i: usize| { + crate::watch::title_memory_unmapping(memory[i] as usize, whole); + // SAFETY: memory of ours; the reservation stays. + assert!(unsafe { VirtualFree(memory[i].cast(), whole, MEM_DECOMMIT) } != 0); + }; + let map_again = |i: usize, seed: usize| { + // SAFETY: the reservation above. + assert!(!unsafe { VirtualAlloc(memory[i].cast(), whole, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + paint(memory[i], seed); + crate::watch::title_memory_remapped(memory[i] as usize, whole); + }; + (GOES..=AGAIN).for_each(unmap); + map_again(AGAIN, 29); + let noted = |i: usize| { + let marked = UNMAPPED_PLACED.lock().unwrap_or_else(|e| e.into_inner()); + marked.0.contains_key(&(memory[i] as u64, desc)) + }; + // Used a moment ago: none goes by the sweep's times. + let gone_before = PLACED_UNMAPPED_GONE[0].load(Relaxed); + // (Memory found mapped is given up at once here, as the title's.) + let_go_unmapped(60_000, 600, 0, usize::MAX); + assert!((0..5).all(made), "a copy used a moment ago went"); + assert!(noted(GOES) && noted(LIST) && noted(SLOT)); + assert!(!noted(AGAIN), "a texture over memory mapped again is still looked at"); + assert!(!noted(STAYS), "a texture over memory nobody unmapped is looked at"); + // Out of use: the copy only its texture holds goes. + let_go_unmapped(0, 0, 0, usize::MAX); + assert!(!made(GOES), "the copy of a placed texture whose memory is unmapped stayed"); + assert!(PLACED_UNMAPPED_GONE[0].load(Relaxed) > gone_before); + assert!(!noted(GOES)); + assert!(made(LIST), "a copy a list holds went"); + assert!(made(SLOT), "a copy a slot holds went"); + assert!(made(AGAIN) && made(STAYS)); + // Once the list is reset and the slot written over, they go too. + drop(list_holds.take()); + drop(slot_holds.take()); + let_go_unmapped(0, 0, 0, usize::MAX); + assert!(!made(LIST) && !made(SLOT)); + assert!(!noted(LIST) && !noted(SLOT)); + assert!(made(AGAIN) && made(STAYS)); + // The title maps memory under the first again, with other bytes, and + // views it: made again from title memory. + map_again(GOES, 31); + let_go_unmapped(0, 0, 0, usize::MAX); + assert_eq!(texture_at(memory[GOES] as u64, &desc), Some(placed[GOES]), "the texture left its table"); + if !crate::texture::prelude_upload() { + return; + } + want_level(placed[GOES], 0); + let copy = host_copy(placed[GOES]).unwrap(); + assert!(made(GOES)); + let layout = texture_memory(placed[GOES]) + .and_then(|(_, d)| texture_layout(&d).map(|t| t.planes[0].layout.clone())) + .unwrap(); + let (pitch, rows) = (1024usize, 64usize); + let mut now = vec![0u8; pitch * rows]; + // SAFETY: the memory above, committed again. + let tiled = unsafe { std::slice::from_raw_parts(memory[GOES], whole) }; + layout.detile(tiled, 0, 0, &mut now, pitch, pitch * rows).unwrap(); + // A list reads level 0 into a buffer of its own, as a title's copy. + let back = host.read_back_buffer((pitch * rows) as u64).unwrap(); + let list = host.new_list().unwrap(); + crate::texture::upload_from(&list, placed[GOES], 0); + crate::list::ensure_state(&list, placed[GOES], COPY_SOURCE); + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(&back) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(98), + Width: 256, + Height: 256, + Depth: 1, + RowPitch: pitch as u32, + }, + }, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(©.texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + // SAFETY: an open list and live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + list.close(); + host.execute(&[&list]); + let mut data = std::ptr::null_mut(); + // SAFETY: a read-back buffer of that size, whose list has run. + let seen = unsafe { + back.Map(0, None, Some(&mut data)).unwrap(); + let seen = std::slice::from_raw_parts(data.cast::<u8>(), pitch * rows).to_vec(); + back.Unmap(0, None); + seen + }; + assert!(seen == now, "the copy made again does not hold what title memory holds now"); + drop(copy); + } + + /// The title is told of an unmapping before the memory goes: a look of + /// the sweep in between finds the first page still mapped. The texture + /// is looked at again, and its copy goes at the look after the memory + /// went; found mapped at every look for the time given, it is given up. + #[cfg(windows)] + #[test] + fn a_placed_texture_noted_before_its_memory_goes_is_looked_at_again() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_DECOMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree}; + if crate::host::host().is_none() || !placed_unmapped() { + return; + } + let _looks = UNMAPPED_LOOKS.lock().unwrap_or_else(|e| e.into_inner()); + crate::frame::test_advance(); + // As in the test above: 256x256 BC7, nine levels, each in memory of + // its own (a reservation that stays). + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = placed_bytes(&desc).unwrap() as usize; + let memory: Vec<*mut u8> = (0..2) + // SAFETY: memory of our own that stays. + .map(|_| unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>()) + .collect(); + assert!(memory.iter().all(|at| !at.is_null())); + // SAFETY: memory of ours, committed. + memory.iter().for_each(|&at| unsafe { (0..whole).for_each(|i| at.add(i).write((i * 7 + i / 509) as u8)) }); + let placed: Vec<This> = memory.iter().map(|&at| texture_at(at as u64, &desc).unwrap()).collect(); + for &texture in &placed { + want_level(texture, 0); + drop(host_copy(texture).unwrap()); + } + let made = |i: usize| resource(placed[i]).host.made.lock().unwrap_or_else(|e| e.into_inner()).is_some(); + let noted = |i: usize| { + let marked = UNMAPPED_PLACED.lock().unwrap_or_else(|e| e.into_inner()); + marked.0.contains_key(&(memory[i] as u64, desc)) + }; + // Told of, not yet gone: the look finds the memory mapped. + (0..2).for_each(|i| crate::watch::title_memory_unmapping(memory[i] as usize, whole)); + let_go_unmapped(0, 0, 60_000, usize::MAX); + assert!(made(0) && made(1)); + assert!(noted(0), "a texture whose memory was still going is not looked at again"); + // Gone now: the next look lets its copy go. + // SAFETY: memory of ours; the reservation stays. + assert!(unsafe { VirtualFree(memory[0].cast(), whole, MEM_DECOMMIT) } != 0); + let_go_unmapped(0, 0, 60_000, usize::MAX); + assert!(!made(0), "the copy stayed once the memory went"); + assert!(!noted(0)); + // The second's memory never goes: still looked at within the time, + // given up after it. + assert!(made(1) && noted(1)); + let_go_unmapped(0, 0, 0, usize::MAX); + assert!(made(1), "the copy of a texture over mapped memory went"); + assert!(!noted(1), "a texture over memory mapped all along is still looked at"); + } } diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 6c00c7d5e7..ba58e09a8d 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -316,6 +316,7 @@ impl CopiedState { } } +mod direct; pub(crate) mod elide; /// A title buffer's host copy. @@ -329,7 +330,12 @@ pub(crate) struct Shadow { /// The bytes of `buffer`, once asked. width: std::sync::OnceLock<u64>, pub(crate) buffer: ID3D12Resource, - data: *mut u8, + /// Where the CPU's side is mapped ([`Shadow::data`]). Of a copy in the + /// card's memory whose CPU side is the title memory itself + /// ([`from_title`]) it is `start`, until [`Shadow::unsource`] gives it a + /// buffer of its own: changed once, from there to that, and read where + /// it is used. + data: std::sync::atomic::AtomicPtr<u8>, gpu: u64, /// Where the title buffer starts and how long it is. start: u64, @@ -339,8 +345,8 @@ pub(crate) struct Shadow { /// Whether the memory is write-watched: unknown, yes, no. watched: AtomicU8, /// Ranges shaders of a submission not yet copied back may be writing: - /// title memory there is older than the copy. - pending: Mutex<Vec<(usize, usize)>>, + /// title memory there is older than the copy ([`Pending`]). + pending: Mutex<Pending>, /// Whether `pending` holds a range: written under its lock, read without /// ([`Shadow::may_pend`]). has_pending: std::sync::atomic::AtomicBool, @@ -350,9 +356,9 @@ pub(crate) struct Shadow { flights: Mutex<Flights>, /// The copy's bytes before the submission ran, for the ranges its /// shaders write (`pending`), each at its offset in the copy: what the - /// GPU wrote differs. Room for the whole copy; only those ranges' bytes - /// are set (and read). - before: Mutex<Option<Vec<u8>>>, + /// GPU wrote differs. Room for the 64 KiB pieces those ranges are in + /// ([`Snapshot`]); only those ranges' bytes are set (and read). + before: Mutex<Option<Snapshot>>, /// Held shared while pieces of the copy are landed (`crate::land`), each /// its own bytes of it on several threads, and alone while title bytes /// go in under shader writes ([`Shadow::merge_under_writes`]), which @@ -374,6 +380,10 @@ pub(crate) struct Shadow { unsized_asks: AtomicU64, /// Whether shaders were ever declared to write it. written: std::sync::atomic::AtomicBool, + /// With [`bar_buffers_most`]: the submissions the copy was read in (asked + /// to be brought up to date by a list recorded while that submission was + /// the newest begun), and the number of the last of them ([`bar_sweep`]). + read_in: [AtomicU64; 2], /// A number no other copy has had. Its address is no name for a copy: /// one let go and another made may share it. id: u64, @@ -401,6 +411,27 @@ pub(crate) struct Shadow { /// and the bytes from the buffer's first byte to `start` (the heap /// begins on a 64 KiB line; a title buffer need not). place: Option<(windows::Win32::Graphics::Direct3D12::ID3D12Heap, u64)>, + /// Of a copy with two sides over memory of ours ([`by_address_opened`]): + /// the memory itself is the CPU's side, opened as this heap, and + /// `Card::staging` is a buffer placed over all of it. Nothing is copied + /// into that side and nothing compares it with the memory: whoever + /// writes the memory says which bytes changed ([`Shadow::resend`]). It + /// may write while a submission takes bytes out of the side to send + /// them; what it changed is resent after it wrote, so the next send has + /// it. + opened: Option<windows::Win32::Graphics::Direct3D12::ID3D12Heap>, + /// Numbered by the directory of memory by address (`crate::memory`), + /// which keeps the copies it numbered for good and shows shaders this + /// one: never put out of the tables for title memory in place + /// ([`in_place_switch`]). + numbered: std::sync::atomic::AtomicBool, + /// Put out of the tables for title memory in place while something + /// still held it ([`in_place_switch`]): shaders declared to write it + /// from then on are counted (`crate::inplace::written_across_switch`). + switched: std::sync::atomic::AtomicBool, + /// Of title memory in place that took the place of a copy something + /// still held ([`in_place_switch`]): that copy, while it lives. + replaced: std::sync::OnceLock<std::sync::Weak<Shadow>>, } /// What a copy in the card's memory ([`cards`]) has beside the buffer @@ -408,8 +439,20 @@ pub(crate) struct Shadow { struct Card { /// The CPU's side, in the PC's memory: what `data` maps. Title memory /// is copied into it as into any copy, and what changed in it goes to - /// the card's side before the next submission. - staging: ID3D12Resource, + /// the card's side before the next submission. With [`from_title`], a + /// buffer placed over the title memory itself, until + /// [`Shadow::unsource`] puts a buffer of its own here (the one lock + /// write); read through [`Shadow::card_sides`]. + staging: RwLock<ID3D12Resource>, + /// Bytes refreshes copied from title memory into the CPU's side, since + /// the copy was made: none for one whose CPU side is title memory + /// ([`from_title`]). + taken: AtomicU64, + /// Whether the CPU's side was title memory once ([`from_title`]) and is + /// a buffer of its own now ([`Shadow::unsource`]; set before the swap): + /// straight sends out of title memory may still be in the air, and our + /// writes there wait for them first all the same ([`source_copying`]). + unsourced: std::sync::atomic::AtomicBool, /// The card side's bytes as they were when the submission's shaders /// started, in the card's memory too: made when shader writes are /// first declared for the copy, and compared with the card's side, on @@ -433,11 +476,38 @@ struct Card { has_dirty: std::sync::atomic::AtomicBool, /// Whether `sent` holds a send: written under its lock, read without. has_sent: std::sync::atomic::AtomicBool, + /// With `LEONIDA_SEND_DIRECT` (`crate::host::send`): where we wrote the + /// copy at submission, and the ranges the card is still to copy out of + /// `staging` ([`direct`]). + direct: Mutex<direct::Direct>, + /// With [`bar_buffers_most`]: where the card's side is mapped (it lies + /// in card memory the CPU maps), 0 for a side in device-local memory. + /// Written only, by `crate::host::send` ([`Shadow::card_bar`]). + bar: usize, /// The buffers' bytes (the title buffer's, rounded up to 64 KiB). size: u64, } impl Card { + /// A card's side's rest: `staging` the CPU's side, `bar` where the card + /// side is mapped (0: device-local memory), `size` the buffers' bytes. + fn new(staging: ID3D12Resource, bar: usize, size: u64) -> Card { + Card { + staging: RwLock::new(staging), + taken: AtomicU64::new(0), + unsourced: Default::default(), + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + touched: Default::default(), + has_dirty: Default::default(), + has_sent: Default::default(), + direct: Mutex::default(), + bar, + size, + } + } + /// The ranges of offsets `[from, to)` whose bytes a fetch sent after /// `fetched_after` did not see: those not gone up yet (`dirty`) and those /// sent after it (`sent`). @@ -802,23 +872,261 @@ fn card_queue() -> bool { /// drops them too where it goes through all of them). fn note_carded(shadow: &Arc<Shadow>) { static SWEPT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - let mut carded = CARDED.lock().unwrap_or_else(|e| e.into_inner()); - carded.insert(Arc::as_ptr(shadow) as usize, Arc::downgrade(shadow)); - if carded.len() >= 2 * SWEPT.load(Ordering::Relaxed) + 64 { - carded.retain(|_, weak| weak.strong_count() > 0); - SWEPT.store(carded.len(), Ordering::Relaxed); + { + let mut carded = CARDED.lock().unwrap_or_else(|e| e.into_inner()); + carded.insert(Arc::as_ptr(shadow) as usize, Arc::downgrade(shadow)); + if carded.len() >= 2 * SWEPT.load(Ordering::Relaxed) + 64 { + carded.retain(|_, weak| weak.strong_count() > 0); + SWEPT.store(carded.len(), Ordering::Relaxed); + } + } + // (Swept the same way, on its own count: `card_dirty` sweeps `CARDED` + // alone.) + static SPANS_SWEPT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let mut spans = CARDED_SPANS.lock().unwrap_or_else(|e| e.into_inner()); + let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize); + spans.insert(start, end, Arc::downgrade(shadow)); + if spans.len() >= 2 * SPANS_SWEPT.load(Ordering::Relaxed) + 64 { + spans.retain(|weak| weak.strong_count() > 0); + SPANS_SWEPT.store(spans.len(), Ordering::Relaxed); + } +} + +/// For tests: the entries of `copies` leave [`CARDED`] and [`CARDED_SPANS`]. +/// A copy from [`Shadow::unbacked`] is never let go, so its entries never +/// die and are never swept; left there, any later walk of the copies in the +/// card's memory in the same process meets a copy whose memory the test +/// freed and whose buffer is no interface (`crate::host::upcheck` calls it). +#[cfg(test)] +fn unnote_carded(copies: &[Arc<Shadow>]) { + let ours = |at: usize| copies.iter().any(|c| Arc::as_ptr(c) as usize == at); + CARDED.lock().unwrap_or_else(|e| e.into_inner()).retain(|&at, _| !ours(at)); + CARDED_SPANS.lock().unwrap_or_else(|e| e.into_inner()).retain(|weak| !ours(weak.as_ptr() as usize)); +} + +/// The copies of [`CARDED`] by the title memory they hold, for +/// [`send_copied`] ([`carded_over`]). +static CARDED_SPANS: Mutex<Spans<std::sync::Weak<Shadow>>> = Mutex::new(Spans::new()); + +/// Whether [`send_copied`] finds the copies in the card's memory a copy on +/// the CPU wrote by the title memory they hold ([`CARDED_SPANS`]; +/// `LEONIDA_CARDED_INDEX=0`: it goes through every copy in the card's +/// memory, as before). +/// +/// `send_copied` runs for every buffer copy a list does on the CPU while +/// submissions take their own send memory (`crate::host::send::own`, on by +/// default), and for each it made every copy in the card's memory strong +/// (a weak reference upgraded, in a new `Vec`) to find the one or two that +/// hold the copy's destination: with the small buffers on the card too +/// that is thousands of copies per buffer copy (3,540 in run int-m-kb). +fn carded_index() -> bool { + crate::toggled!("LEONIDA_CARDED_INDEX") +} + +/// The copies in the card's memory that hold some of title memory `[from, +/// to)`. +fn carded_over(from: usize, to: usize) -> Vec<Arc<Shadow>> { + if !carded_index() { + return carded_copies(); + } + CARDED_SPANS.lock().unwrap_or_else(|e| e.into_inner()).over(from, to).filter_map(std::sync::Weak::upgrade).collect() +} + +/// Spans `[start, end)`, each with a value, in order of their start, and +/// for each the furthest end of it and of every span before it: the spans +/// that overlap a stretch are found by two searches and a look at those +/// between, which all begin before the stretch ends and some of which (or +/// a span before them) reach past its start. Spans may overlap and nest. +/// Made for spans that are added seldom and asked about often: an insert +/// moves the spans after it. +struct Spans<T> { + spans: Vec<(usize, usize, T)>, + reach: Vec<usize>, +} + +/// For tests: the spans [`Spans::over`] looked at on this thread. +#[cfg(test)] +thread_local! { + static SPANS_LOOKED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + +impl<T> Spans<T> { + const fn new() -> Self { + Spans { spans: Vec::new(), reach: Vec::new() } + } + + fn len(&self) -> usize { + self.spans.len() + } + + fn insert(&mut self, start: usize, end: usize, value: T) { + let i = self.spans.partition_point(|s| s.0 <= start); + self.spans.insert(i, (start, end, value)); + self.reach.insert(i, 0); + self.reach_from(i); + } + + /// Keeps the spans whose value `keep` says yes to. + fn retain(&mut self, mut keep: impl FnMut(&T) -> bool) { + self.spans.retain(|s| keep(&s.2)); + self.reach.truncate(self.spans.len()); + self.reach_from(0); + } + + /// `reach` made again from span `i` on. + fn reach_from(&mut self, i: usize) { + let mut reach = if i == 0 { 0 } else { self.reach[i - 1] }; + for (r, s) in self.reach[i..].iter_mut().zip(&self.spans[i..]) { + reach = reach.max(s.1); + *r = reach; + } + } + + /// The values of the spans that overlap `[from, to)`, in order of start. + fn over(&self, from: usize, to: usize) -> impl Iterator<Item = &T> { + // Before `first` every span (and all before it) ends by `from`; + // from `last` on every span begins at `to` or later. + let first = self.reach.partition_point(|&r| r <= from); + let last = self.spans.partition_point(|s| s.0 < to).max(first); + #[cfg(test)] + SPANS_LOOKED.with(|l| l.set(l.get() + (last - first) as u64)); + self.spans[first..last].iter().filter(move |s| s.1 > from && from < to).map(|s| &s.2) + } +} + +#[cfg(test)] +mod spans_tests { + use super::*; + + /// What overlaps a stretch is what a walk of every span finds, with + /// spans that nest and overlap, as spans come and go; and a stretch + /// among many apart spans looks at the one it is in. + #[test] + fn spans_that_overlap_a_stretch_are_found_by_search() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut random = |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % n as u64) as usize + }; + let mut spans = Spans::new(); + let mut all: Vec<(usize, usize, u32)> = Vec::new(); + for round in 0..2000u32 { + let start = random(10_000); + // Mostly short, now and then one over much of the rest. + let len = if random(20) == 0 { random(5000) } else { 1 + random(50) }; + spans.insert(start, start + len, round); + all.push((start, start + len, round)); + if random(10) == 0 { + let gone = random(4); + spans.retain(|&v| v % 4 != gone as u32 || v == round); + all.retain(|&(_, _, v)| v % 4 != gone as u32 || v == round); + } + let from = random(10_100); + let to = from + random(80); + let mut found: Vec<u32> = spans.over(from, to).copied().collect(); + let mut walked: Vec<u32> = all.iter().filter(|&&(a, b, _)| a < to && b > from && from < to).map(|s| s.2).collect(); + found.sort_unstable(); + walked.sort_unstable(); + assert_eq!(found, walked, "round {round}: {from}..{to}"); + assert_eq!(spans.len(), all.len()); + } + let mut apart = Spans::new(); + for i in 0..10_000usize { + apart.insert(i * 100, i * 100 + 50, i); + } + SPANS_LOOKED.with(|l| l.set(0)); + assert_eq!(apart.over(777_010, 777_020).copied().collect::<Vec<_>>(), [7770]); + assert_eq!(apart.over(777_060, 777_070).count(), 0); + assert!(SPANS_LOOKED.with(|l| l.get()) <= 2); + } + + /// A buffer copy on the CPU into one copy in the card's memory, among + /// 512 others and one big copy that holds 64 of them: [`send_copied`] + /// looks at the copy that holds the destination, not at every copy in + /// the card's memory. (The copies hold title memory nobody maps: the one + /// written is busy whole, so nothing is copied or sent.) + #[test] + fn a_cpu_copy_looks_at_the_card_copies_it_writes() { + const STRIDE: usize = 0x1_0000; + const EACH: usize = 0x8000; + let base = 0x7a00_0000_0000usize; + let mut side = vec![0u8; 64 * STRIDE]; + // Their entries go before `side` does, also when an assertion fails. + struct Ours(Vec<Arc<Shadow>>); + impl Drop for Ours { + fn drop(&mut self) { + unnote_carded(&self.0); + } + } + impl std::ops::Deref for Ours { + type Target = Vec<Arc<Shadow>>; + fn deref(&self) -> &Vec<Arc<Shadow>> { + &self.0 + } + } + let mut ours = Ours(Vec::new()); + for i in 0..512 { + let copy = Shadow::unbacked((base + i * STRIDE) as u64, side.as_mut_ptr(), EACH as u64, true); + note_carded(©); + ours.0.push(copy); + } + let big = Shadow::unbacked((base + 100 * STRIDE) as u64, side.as_mut_ptr(), (64 * STRIDE) as u64, true); + note_carded(&big); + ours.0.push(big.clone()); + // Busy whole: nothing of it is sent. + let target = &ours[200]; + let span = (target.start as usize, (target.start + target.len) as usize); + target.pending.lock().unwrap().insert(span); + target.has_pending.store(true, Ordering::Release); + SEND_COPIED_LOOKED.with(|l| l.set(0)); + send_copied(base + 200 * STRIDE + 0x100, 0x10); + let looked = SEND_COPIED_LOOKED.with(|l| l.get()); + assert_eq!(looked, 1, "send_copied looked at {looked} copies in the card's memory"); + // What `carded_over` finds of ours is what holds the stretch. + let ids = |from: usize, to: usize| -> Vec<u64> { + let mut found: Vec<u64> = carded_over(from, to).iter().map(|s| s.id).filter(|id| ours.iter().any(|o| o.id == *id)).collect(); + found.sort_unstable(); + found + }; + let walked = |from: usize, to: usize| -> Vec<u64> { + let mut held: Vec<u64> = ours + .iter() + .filter(|s| (s.start as usize) < to && (s.start + s.len) as usize > from) + .map(|s| s.id) + .collect(); + held.sort_unstable(); + held + }; + for (from, to) in [(base + 200 * STRIDE + 0x100, base + 200 * STRIDE + 0x110), (base + 120 * STRIDE + EACH + 4, base + 120 * STRIDE + EACH + 8)] { + assert_eq!(ids(from, to), walked(from, to)); + } + let (from, to) = (base + 130 * STRIDE + 0x10, base + 133 * STRIDE + 0x10); + assert_eq!(ids(from, to), walked(from, to)); + assert_eq!(walked(from, to).len(), 5); + // Gone from the copies in the card's memory before their memory is. + let at: Vec<usize> = ours.iter().map(|c| Arc::as_ptr(c) as usize).collect(); + drop(ours); + let left = carded_copies().iter().filter(|c| at.contains(&(Arc::as_ptr(c) as usize))).count(); + let spans = CARDED_SPANS.lock().unwrap().spans.iter().filter(|s| at.contains(&(s.2.as_ptr() as usize))).count(); + assert_eq!((left, spans), (0, 0), "the test's copies stay noted in the card's memory"); + drop(side); } } /// Since the last frame line: bytes copied to card sides and the ranges -/// they were; pieces compared on the card, pieces fetched and their -/// bytes; the waits for the card the fetches added and their microseconds. +/// they were; the pieces of the declared ranges whose compare was read (a +/// piece two ranges share counts once for each; `host::CARD_PASSES[3]` +/// counts it once, as hashed), pieces fetched and their bytes; the waits +/// for the card the fetches added and their microseconds. pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; pub(crate) fn live_span_bytes() -> u64 { CARD_BYTES[0].load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed) + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed) + + BAR_BYTES.load(Ordering::Relaxed) } /// [`CARD_STATS`], taken; then the copies in the card's memory, their @@ -831,7 +1139,8 @@ pub(crate) fn card_stats() -> [u64; 10] { out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).values().filter(|w| w.strong_count() > 0).count() as u64; out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed) - + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed); + + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed) + + BAR_BYTES.load(Ordering::Relaxed); out[9] = CARD_BYTES[1].load(Ordering::Relaxed); out } @@ -876,11 +1185,243 @@ fn card_all() -> bool { *ON.get_or_init(|| std::env::var_os("LEONIDA_CARD_ALL").is_some_and(|v| v == "1")) } +/// Whether a title buffer's copy in the card's memory ([`cards`]) has the +/// title memory itself for its CPU side (`LEONIDA_CARD_FROM_TITLE=1`; off by +/// default): no `Card::staging` of its own, and no CPU copy of what the +/// title writes. Read when a copy is made. +/// +/// Such a copy had two buffers: the card side, and the CPU's side in the +/// PC's memory, of the same size (`Card::staging`). A refresh copied the +/// pages the title wrote from title memory into the CPU's side on the CPU, +/// and the card copied them from there into its side (straight with +/// `LEONIDA_SEND_DIRECT`, `crate::host::send`). With the switch, where the +/// title memory can be opened as a heap of the host's +/// (`crate::inplace::place_source`: private memory committed whole, or one +/// run of a committed section, from a 64 KiB line on), the CPU's side is a +/// buffer placed over the title memory: the refresh notes the pages written +/// (the write watch, as before) and copies nothing, and the card copies them +/// out of the title memory into its side. The card reads opened title +/// memory as fast as upload memory (23-28 GB/s on the RX 7900 XT, +/// `docs/findings.md`, the placement table). The CPU's side's RAM (the +/// copy's size, resident once touched) is not taken; the memory line counts +/// it (`memory`, diagnostics builds). +/// +/// What it rests on: +/// +/// - shaders do not write the copy. The CPU's side is the reference for +/// what they wrote (the card side as it was before them, which the merge +/// compares with, [`Shadow::card_merge`]) and for the dwords a copy that +/// keeps undeclared stores sends ([`Shadow::keep_stores`]). Title memory +/// is not that: the title writes it after a send. Whether shaders write a +/// copy is not known when it is made, so a write declared for it +/// ([`Shadow::writing`], at submission) or such a mark gives it a buffer of +/// its own first ([`Shadow::unsource`]): filled from title memory, and all +/// of it sent up again once. +/// - what a submission in the air reads of the CPU's side: the title's later +/// CPU writes, as with `LEONIDA_SEND_DIRECT` (the title is told of a +/// submission once the card has run it, so it does not write what that +/// one reads). What *we* write into title memory at submission is written +/// into the CPU's side at once here, so it waits for the straight sends in +/// the air that read its pieces before it writes ([`copying`]; for the +/// title's buffer copies done on the CPU, which wrote title memory before +/// that wait and the CPU's side after it, [`source_copying`]; so too once +/// the copy has a side of its own, for the sends out of title memory +/// recorded before). +/// - the title's frees, decommits and protections of the memory, which the +/// host refuses while the heap stands, and the runtime's mapping of other +/// pages there: the runtime's glue lets go of what is in place there +/// ([`in_place_let_go`]), as of a window in place, and such a copy gets a +/// buffer of its own before the next submission ([`sources_going`]); the +/// heap goes once the card is done with it, and the title's call is made +/// then (`crate::inplace::title_memory_free_held`, `title_memory_protect`). +/// +/// Not with `LEONIDA_SEND_CHANGED=1` (it compares each dword with the CPU's +/// side), nor with `LEONIDA_INPLACE_FREE=0` or `LEONIDA_INPLACE_PROTECT=0` +/// (nothing would let go of the heap, [`source_wanted`]), nor for a card side +/// in card memory the CPU maps. Off by default: +/// nothing is measured with the title, whose big heap may be declared +/// written in its first frame (then the opening, which locks its pages, buys +/// nothing), and the free of memory under such a copy now waits for a +/// submission; each hazard above has a test on the host's card +/// (`crate::host::send`'s `direct_tests`). Windows outside buffers with a +/// side in the card's memory too ([`from_title_windows`]). +pub(crate) fn from_title() -> bool { + #[cfg(test)] + if let Some(on) = TEST_FROM_TITLE.get() { + return on; + } + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("LEONIDA_CARD_FROM_TITLE")) +} + +#[cfg(test)] +thread_local! { + /// A test's [`from_title`], for its thread only. + pub(crate) static TEST_FROM_TITLE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; +} + +/// Whether a window of title memory outside buffers with a side in the +/// card's memory ([`window_room_for`], `LEONIDA_CARD_WINDOWS_MB`) has the +/// title memory itself for its CPU side, as a big title buffer's copy has +/// with [`from_title`] (`LEONIDA_CARD_FROM_TITLE_WINDOWS`: on, under +/// `LEONIDA_CARD_FROM_TITLE`, which stays off by default; `=0`, title +/// buffers alone, as before). +/// +/// Such a window had a CPU side of its own, its size in the PC's memory, and +/// each refresh copied the pages the title wrote into it on the CPU; windows +/// are two thirds of the PC memory the card shares (run 104: 861 windows, +/// 3,552 MB of 5,400, [`window_card_most`]). Made in [`loose`] as +/// [`source_side`] makes a buffer's, and kept right by what keeps a buffer's +/// right, none of which asks whether the copy is a window: our writes at +/// submission ([`copying`], [`source_copying`] over the carded index), a +/// declared shader write or kept stores ([`Shadow::unsource`]), the title's +/// frees, protections and the runtime's remapping of sections +/// ([`in_place_let_go`], [`sources_going`]). Windows are 64 KiB aligned +/// (their grid, or [`TAIL_STEP`]), so the host opens one whole where its +/// memory is one allocation committed whole or one run of a committed +/// section; else it keeps a side of its own (counted, `SOURCED[3]`). +/// +/// Not for memory by address ([`by_address`]): its copy keeps what shaders +/// store there undeclared and sends only the dwords that differ from its +/// CPU side (`changes_only`), which title memory cannot be (as +/// [`Shadow::keep_stores`] says). Not for windows with two sides in the PC's +/// memory (`LEONIDA_WINDOWS_OWN`, [`window_own_for`]): their second side is +/// there so that submissions in the air keep the bytes they were prepared +/// with, which a CPU side of title memory would not add to. +/// +/// What it adds to [`from_title`]'s case: a window is a second view of title +/// memory a title buffer inside it may also have; the copy-back of what +/// shaders wrote to such a buffer writes title memory after its submission +/// ran, and a send of the window recorded before it, still in the air, may +/// read some of those bytes where its own CPU side read none of them until +/// the next refresh. Both are bytes the memory held. The next refresh takes +/// the same pages as before (only what it does with them changes, +/// [`Shadow::copy`]), and sends whole what it would have copied into a side +/// of its own. Not measured with the title. +fn from_title_windows() -> bool { + from_title() && crate::toggled!("LEONIDA_CARD_FROM_TITLE_WINDOWS") +} + +/// Copies whose CPU side is title memory ([`from_title`]) alive, and their +/// CPU sides' bytes not made; then, since the start: such copies made, asks +/// the host turned down (not openable, off a 64 KiB line), and copies given a +/// side of their own because shaders write them, because their memory +/// changed, or because none could be made then. +static SOURCED: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + +/// Whether a copy's CPU side is title memory ([`from_title`]) now, told +/// without looking at any copy. +pub(crate) fn sourced_any() -> bool { + SOURCED[0].load(Ordering::Relaxed) != 0 +} + +/// The CPU's side of a new copy in the card's memory of title memory +/// `[start, start + len)`, `size` bytes: a buffer placed over the title +/// memory, if [`from_title`] asks for it and the host opens it from the +/// copy's first byte on; counted in [`SOURCED`] until the copy is given a +/// side of its own or goes. +fn source_side(start: u64, len: u64, size: u64) -> Option<ID3D12Resource> { + if !source_wanted(from_title(), send_changed(), crate::inplace::frees(), crate::inplace::protects()) { + return None; + } + // Counted before it is opened: a let-go of the memory meanwhile + // (`crate::inplace::title_memory_freeing`) looks for such copies then, + // and finds this one once the caller's table lock is free. + SOURCED[0].fetch_add(1, Ordering::Relaxed); + match crate::inplace::place_source(start, len) { + // SAFETY: a live buffer. + Ok(placed) if placed.bias == 0 && unsafe { placed.buffer.GetDesc() }.Width >= size => { + SOURCED[1].fetch_add(size, Ordering::Relaxed); + SOURCED[2].fetch_add(1, Ordering::Relaxed); + Some(placed.buffer) + } + // (The placed buffer goes; a hold of it is reaped.) + Ok(_) | Err(_) => { + SOURCED[0].fetch_sub(1, Ordering::Relaxed); + SOURCED[3].fetch_add(1, Ordering::Relaxed); + None + } + } +} + +/// Whether a new copy's CPU side is asked of title memory ([`source_side`]): +/// [`from_title`] on (`on`), not `LEONIDA_SEND_CHANGED=1` (`changed`), and +/// the title's frees (`frees`, `LEONIDA_INPLACE_FREE`) and protections +/// (`protects`, `LEONIDA_INPLACE_PROTECT`) of memory a heap stands over taken +/// over. With either of those off nothing lets go of the heap: the title's +/// `VirtualFree` or `VirtualProtect` of a big buffer's memory, an ordinary +/// copy's without the switch, would fail with error 87 for as long as the +/// copy lives. +fn source_wanted(on: bool, changed: bool, frees: bool, protects: bool) -> bool { + on && !changed && frees && protects +} + +#[cfg(test)] +mod source_tests { + use super::source_wanted; + + /// A copy's CPU side is title memory only with the switch on, without + /// `LEONIDA_SEND_CHANGED=1`, and while the title's frees and protections + /// of memory under a heap are taken over. Before, the copy was made over + /// title memory with `LEONIDA_INPLACE_FREE=0` or + /// `LEONIDA_INPLACE_PROTECT=0`, and nothing let go of the heap. + #[test] + fn title_memory_is_a_cpu_side_only_where_its_frees_and_protections_are_taken_over() { + assert!(source_wanted(true, false, true, true)); + assert!(!source_wanted(false, false, true, true), "the switch off"); + assert!(!source_wanted(true, true, true, true), "LEONIDA_SEND_CHANGED=1"); + assert!(!source_wanted(true, false, false, true), "LEONIDA_INPLACE_FREE=0"); + assert!(!source_wanted(true, false, true, false), "LEONIDA_INPLACE_PROTECT=0"); + } +} + +/// Copies whose title memory the title frees, decommits or protects, or the +/// runtime maps other pages over, while it is their CPU side +/// ([`in_place_let_go`]): they get a side of their own before the next +/// submission ([`sources_going`]). +static SOURCES_GOING: Mutex<Vec<Arc<Shadow>>> = Mutex::new(Vec::new()); + +/// Whether [`SOURCES_GOING`] has any. +static SOURCES_WAITING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Before a submission, on the submitting thread: the copies +/// [`in_place_let_go`] named get a CPU side of their own +/// ([`Shadow::unsource`]); one nothing else holds any more just goes. Their +/// buffers over title memory go once the card is done with them, and with +/// them the heaps that refuse the title's call (`crate::inplace::reap`). +/// Not where the let-go is seen: the runtime may hold its own locks there +/// (`leonida_hle`'s xmem), and the fill is a copy of the whole buffer. +pub(crate) fn sources_going() { + if !SOURCES_WAITING.swap(false, Ordering::AcqRel) { + return; + } + let going = std::mem::take(&mut *SOURCES_GOING.lock().unwrap_or_else(|e| e.into_inner())); + for shadow in going { + if Arc::strong_count(&shadow) > 1 && shadow.unsource("its title memory is freed, protected or mapped anew") { + SOURCED[5].fetch_add(1, Ordering::Relaxed); + } + } +} + +#[cfg(test)] +thread_local! { + /// For a test, on its thread only: the card's memory has no room for a + /// title buffer's copy ([`card_room_for`] turns every one down). + static TEST_CARD_FULL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// For a test, on its thread only: [`window_card_most`] in bytes, as + /// `LEONIDA_CARD_WINDOWS_MB` would set it. + static TEST_WINDOW_CARD_MOST: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) }; +} + /// [`card_for`] in the card's own memory. fn card_room_for(size: u64) -> Option<ID3D12Resource> { if !cards() { return None; } + #[cfg(test)] + if TEST_CARD_FULL.get() { + return None; + } let (least, most) = card_limits(); if size < least || size >= 1 << 30 { return None; @@ -956,8 +1497,13 @@ fn card_room_for(size: u64) -> Option<ID3D12Resource> { /// [`reserve_card_budgets`]: the texture queue keeps this number's room and /// windows go up to 97 hundredths). The CPU's side stays in the PC's /// memory, so the memory shared with the card does not shrink by this -/// alone; what moves is what shaders read. +/// alone; what moves is what shaders read. (With [`from_title_windows`] that +/// side is the title memory itself where the host opens it: no copy of it.) fn window_card_most() -> u64 { + #[cfg(test)] + if let Some(most) = TEST_WINDOW_CARD_MOST.get() { + return most; + } static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); *MOST.get_or_init(|| { std::env::var("LEONIDA_CARD_WINDOWS_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0) << 20 @@ -967,17 +1513,13 @@ fn window_card_most() -> u64 { /// Bytes alive of windows' card sides ([`window_card_most`]). static WINDOW_CARD_BYTES: AtomicU64 = AtomicU64::new(0); -/// A buffer in the card's memory for a window of `size` bytes, if it is to -/// be there ([`window_card_most`]). -fn window_card_for(size: u64) -> Option<ID3D12Resource> { - let there = window_room_for(size); - if there.is_some() { - window_made(0, size); - } - if there.is_some() || !windows_own() || !cards() { - return there; +/// For a window of `size` bytes with no side in the card's memory +/// ([`window_room_for`]): with [`windows_own`], two sides all the same, the +/// card's in the PC's memory. +fn window_own_for(size: u64) -> Option<ID3D12Resource> { + if !windows_own() || !cards() { + return None; } - // Two sides all the same, the card's in the PC's memory. let host = host()?; if !host.card_ready() { return None; @@ -1071,6 +1613,340 @@ fn window_mapped_for(size: u64) -> Option<(ID3D12Resource, *mut u8)> { made } +/// The most bytes of small title buffers whose copy's card side lies in card +/// memory the CPU maps (`D3D12_HEAP_TYPE_GPU_UPLOAD`, a resizable BAR) and is +/// written there by the CPU (`LEONIDA_BAR_BUFFERS_MB`; 0, the default, none). +/// +/// A title buffer below the card's lower limit ([`card_limits`]: 4 MiB on +/// cards of 12-20 GiB) has one copy, a buffer in the PC's memory that every +/// shader load reads over the bus: 23-28 GB/s from write-back memory on the +/// RX 7900 XT of `docs/findings.md`'s last section, against 690-1,000 from +/// the card's own, and what many waves read many times is read over the bus +/// again past 1 MiB. With this number such a copy has two sides as a big one +/// has ([`cards`]), its card side in card memory the CPU maps: +/// +/// - the CPU's side is the buffer it had (`Card::staging`, write-back): every +/// CPU read of the copy reads it, never the card side. Compares, snapshots, +/// merges, the upcheck and the stale-page look read `Shadow::data`, which +/// is the CPU's side; what shaders wrote is found by the compare on the +/// card and fetched by a card copy (`Host::card_back`), as for any copy +/// with two sides. The CPU reads write-combined memory at 0.13-0.19 GB/s +/// (the same table), 150 times slower than write-back; +/// - what changed on the CPU's side goes up at the next submission +/// (`Host::card_before`); what the title's CPU wrote is written into the +/// card side by the CPU then, straight from the CPU's side (`send::take`, +/// with `LEONIDA_SEND_DIRECT`), with no card copy and no memory of the +/// submission's own; what we wrote at submission (the title's buffer copies +/// done on the CPU, [`copying`], [`send_copied`], noted for such a copy +/// whether a send was ever numbered or not) still goes through that +/// memory and a card copy behind the submissions in the air, and the CPU +/// writes no piece a card copy of ours is still to land on +/// (`direct::Direct::split_mapped`). +/// +/// What a submission in the air reads of it: the title's later CPU writes +/// where it reads them, as the single copy it replaces did (and as the title +/// does not do: it is told of a submission once the card has run it). The +/// card's memory holds the copies' bytes (counted in the frame line's card +/// bytes), up to this number and while the card's memory is under four +/// fifths of its budget, as [`window_mapped_for`]'s windows; the PC's memory +/// holds what it held. The CPU's write into the card side crosses the bus +/// (on the PCIe 4.0 x8 RTX 4060 Ti, sends filled that way took the +/// submitting thread 8-9 ms a frame against 3: `LEONIDA_SEND_BAR`). +/// +/// Which copies: those of small buffers shaders never write and that are +/// read many times. Neither is known when a copy is made, so a copy is made +/// with one side, as without the switch, and [`bar_sweep`] moves it later +/// ([`bar_move`]): to card memory the CPU maps once it was read in +/// [`BAR_READS`] submissions and never declared written, back to one side +/// (for good, for that buffer) once shaders are declared to write it. The +/// budget then goes to the buffers read in steady state, not to the first +/// small ones made at load. +/// +/// Off by default: nothing is measured with the title, and the one card +/// measured here has no resizable BAR (`crate::host::bar`'s line says so at +/// start). +fn bar_buffers_most() -> u64 { + static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("LEONIDA_BAR_BUFFERS_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0) << 20 + }) +} + +/// Bytes alive of title buffer copies' card sides in card memory the CPU maps. +static BAR_BYTES: AtomicU64 = AtomicU64::new(0); + +/// Whether a title buffer copy of `size` bytes gets its card side in card +/// memory the CPU maps ([`bar_buffers_most`]): smaller than the card's lower +/// limit `least` (from there on the side lies in device-local memory, +/// [`card_for`]), within `most` bytes with `alive` there already, and with +/// the card's memory (`used` of `budget`, if known) under four fifths of its +/// budget after it, as [`window_mapped_for`]. +fn bar_wanted(size: u64, least: u64, most: u64, alive: u64, video: Option<(u64, u64)>) -> bool { + size > 0 + && size < least + && alive.saturating_add(size) <= most + && video.is_none_or(|(budget, used)| used.saturating_add(size) <= budget / 10 * 8) +} + +/// A buffer in card memory the CPU maps for the card side of a title buffer +/// copy of `size` bytes, if it is to be there ([`bar_wanted`]); counted in +/// [`BAR_BYTES`] until the copy goes. +fn bar_for(size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let most = bar_buffers_most(); + if most == 0 || !cards() { + return None; + } + let host = host()?; + if !host.mapped_card_memory() || !host.card_ready() { + return None; + } + let video = host.video_memory().map(|[budget, used, ..]| (budget, used)); + // Counted before it is made, so that two made at once do not both fit. + let alive = BAR_BYTES.fetch_add(size, Ordering::Relaxed); + if !bar_wanted(size, card_limits().0, most, alive, video) { + BAR_BYTES.fetch_sub(size, Ordering::Relaxed); + return None; + } + let made = host.mapped_card_buffer(size, true); + if made.is_none() { + BAR_BYTES.fetch_sub(size, Ordering::Relaxed); + } + made +} + +/// [`Entry::bar`]: the next copy of the buffer is made with one side, as +/// without the switch. +const BAR_NOT_YET: u8 = 0; +/// [`Entry::bar`]: the last copy was read in [`BAR_READS`] submissions and +/// never written; the next one gets its card side in card memory the CPU +/// maps, if there is room then ([`bar_for`]). +const BAR_WANTED: u8 = 1; +/// [`Entry::bar`]: shaders were declared to write a copy of the buffer; +/// its copies keep one side from here on. +const BAR_NEVER: u8 = 2; + +/// The submissions a copy is read in ([`Shadow::read_in`]) before it is +/// moved to card memory the CPU maps: a buffer read once or twice at load +/// is not; one the title's frames read (some thirty submissions a frame +/// here) is, within its first frame or so. +const BAR_READS: u64 = 16; + +/// What [`bar_sweep`] does with a copy. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum BarMove { + /// The copy goes; the next one has its card side in card memory the + /// CPU maps. + There, + /// The copy, whose card side is there, goes; the next one has one side. + Back, +} + +/// Whether a small copy moves ([`bar_buffers_most`]), from what it is: +/// `barred`, its card side in card memory the CPU maps (else one side); +/// `written`, shaders were declared to write it; `reads`, the submissions it +/// was read in; `never`, a copy of the buffer was written before +/// ([`BAR_NEVER`]); and from the room [`bar_wanted`] asks about. A written +/// copy there goes back, and one never written that was read in +/// [`BAR_READS`] submissions goes there while there is room. +#[allow(clippy::too_many_arguments)] +fn bar_move( + barred: bool, + written: bool, + reads: u64, + never: bool, + size: u64, + least: u64, + most: u64, + alive: u64, + video: Option<(u64, u64)>, +) -> Option<BarMove> { + if barred { + return written.then_some(BarMove::Back); + } + (!written && !never && reads >= BAR_READS && bar_wanted(size, least, most, alive, video)).then_some(BarMove::There) +} + +/// Small copies moved to card memory the CPU maps since the start, and moved +/// back ([`bar_sweep`]). +static BAR_MOVES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// The copies of `map` that move ([`bar_move`]), with their buffers' keys; +/// those that go there counted against the room one after the other. +fn bar_moves_in( + map: &BTreeMap<(u64, usize), Entry>, + least: u64, + most: u64, + video: Option<(u64, u64)>, +) -> Vec<((u64, usize), BarMove)> { + let mut alive = BAR_BYTES.load(Ordering::Relaxed); + let mut moves = Vec::new(); + for (key, entry) in map { + let Some(shadow) = &entry.shadow else { + continue; + }; + let Some(barred) = shadow.bar_side() else { + continue; + }; + let size = shadow.len.next_multiple_of(1 << 16); + let reads = shadow.read_in[0].load(Ordering::Relaxed); + let Some(to) = bar_move(barred, shadow.written(), reads, entry.bar == BAR_NEVER, size, least, most, alive, video) else { + continue; + }; + if to == BarMove::There { + alive += size; + } + moves.push((*key, to)); + } + moves +} + +/// Whether nothing but the table holds `shadow`, as [`let_go_idle`] asks of +/// a window: no list not yet reset reads or writes it, no submission is +/// comparing or fetching it, and no descriptor slot views its buffer (a +/// slot keeps the buffer it views, `HostHeap::kept`). Such a copy may go and +/// another be made in its place: no slot shows the one that went, which the +/// pass that brings slots up to date would no longer find. +fn held_by_none(shadow: &Arc<Shadow>) -> bool { + Arc::strong_count(shadow) == 1 && crate::host::references(&shadow.buffer) == 1 +} + +/// Moves small copies between the PC's memory and card memory the CPU maps +/// ([`bar_buffers_most`], [`bar_move`]): a copy that moves goes, and the +/// next ask makes the buffer's copy anew, its card side where it was +/// decided ([`Entry::bar`]), and copies it whole from title memory. Only +/// copies nothing but the table holds ([`held_by_none`]) move: no list and +/// no slot is left with the one that went. Called by [`let_go_idle`], once a +/// second before a submission starts; with the switch off it does nothing. +/// +/// shortcut: a copy some list or descriptor slot always holds never moves +/// (a buffer every frame reads through a slot the title never writes +/// again). The sweep line in the trail says how many moved. +fn bar_sweep() { + let most = bar_buffers_most(); + if most == 0 || !cards() { + return; + } + let Some(host) = host() else { + return; + }; + if !host.mapped_card_memory() || !host.card_ready() { + return; + } + let least = card_limits().0; + let video = host.video_memory().map(|[budget, used, ..]| (budget, used)); + // Looked for under the shared lock first: the other one makes every + // thread's memory of the buffers' answers old ([`buffers`]). + let any = { + let map = buffers_read(); + bar_moves_in(&map, least, most, video) + .iter() + .any(|(key, _)| map.get(key).and_then(|e| e.shadow.as_ref()).is_some_and(held_by_none)) + }; + if !any { + return; + } + let mut gone: Vec<(Arc<Shadow>, BarMove)> = Vec::new(); + { + // Held from the look to the removal; taken, it makes what threads + // remember old before anything is looked at, so a copy one of them + // took out of its memory is held now or not handed out ([`found`]). + let mut map = buffers(); + for (key, to) in bar_moves_in(&map, least, most, video) { + let Some(entry) = map.get_mut(&key) else { + continue; + }; + if !entry.shadow.as_ref().is_some_and(held_by_none) { + continue; + } + entry.bar = match to { + BarMove::There => BAR_WANTED, + BarMove::Back => BAR_NEVER, + }; + gone.extend(entry.shadow.take().map(|s| (s, to))); + } + } + if gone.is_empty() { + return; + } + let there = gone.iter().filter(|(_, to)| *to == BarMove::There).count(); + let back = gone.len() - there; + BAR_MOVES[0].fetch_add(there as u64, Ordering::Relaxed); + BAR_MOVES[1].fetch_add(back as u64, Ordering::Relaxed); + crate::host::trail(|| { + format!( + "sweep: {there} small host copies made again in card memory the CPU maps (read in {BAR_READS} submissions, never written), \ + {back} back in the PC's memory (written by shaders); {} and {} since the start (LEONIDA_BAR_BUFFERS_MB)", + BAR_MOVES[0].load(Ordering::Relaxed), + BAR_MOVES[1].load(Ordering::Relaxed) + ) + }); + for (shadow, _) in gone { + // Nothing names it: freed once what runs now has run. + crate::host::retire(shadow); + } +} + +/// For tests: [`bar_sweep`] now. +#[cfg(test)] +pub(crate) fn bar_sweep_for_test() { + bar_sweep(); +} + +#[cfg(test)] +mod bar_tests { + use super::{BAR_READS, BarMove, bar_move, bar_wanted}; + + const MIB: u64 = 1 << 20; + + /// A small copy moves to card memory the CPU maps once it was read in + /// [`BAR_READS`] submissions and while it was never written, nor any + /// copy of its buffer before it, and while there is room; a copy there + /// goes back once it is written, whatever the room. Before, every + /// small copy got its side there when it was made, read once or + /// written or not, and kept it. + #[test] + fn copies_move_there_when_read_often_and_back_when_written() { + let least = 4 * MIB; + let video = Some((20_000 * MIB, 10_000 * MIB)); + let room = |barred, written, reads, never| bar_move(barred, written, reads, never, 256 << 10, least, 64 * MIB, 0, video); + assert_eq!(room(false, false, 0, false), None, "a new copy keeps one side"); + assert_eq!(room(false, false, BAR_READS - 1, false), None, "read in too few submissions"); + assert_eq!(room(false, false, BAR_READS, false), Some(BarMove::There)); + assert_eq!(room(false, true, 1000, false), None, "written by shaders"); + assert_eq!(room(false, false, 1000, true), None, "a copy of the buffer was written before"); + assert_eq!(room(true, false, 1000, false), None, "a copy there that is not written stays"); + assert_eq!(room(true, true, 0, false), Some(BarMove::Back)); + // The room as `bar_wanted` has it: none with the number at 0, the + // default; none for a big one; none past the number or the card's + // four fifths. + let read = BAR_READS; + assert_eq!(bar_move(false, false, read, false, 256 << 10, least, 0, 0, video), None, "off by default"); + assert_eq!(bar_move(false, false, read, false, least, least, 64 * MIB, 0, video), None); + assert_eq!(bar_move(false, false, read, false, MIB, least, 64 * MIB, 63 * MIB + 1, video), None); + assert_eq!(bar_move(false, false, read, false, MIB, least, 64 * MIB, 0, Some((20_000 * MIB, 16_000 * MIB))), None); + assert_eq!(bar_move(true, true, 0, false, MIB, least, 0, 64 * MIB, Some((20_000 * MIB, 19_000 * MIB))), Some(BarMove::Back)); + } + + /// A small title buffer's copy gets its card side in card memory the CPU + /// maps within the number asked for, below the card's lower limit, and + /// while the card's memory stays under four fifths of its budget; none + /// at all with the number at 0, the default. + #[test] + fn small_copies_go_to_mapped_card_memory_within_the_number() { + let least = 4 * MIB; + let video = Some((20_000 * MIB, 10_000 * MIB)); + assert!(bar_wanted(256 << 10, least, 64 * MIB, 0, video)); + assert!(!bar_wanted(256 << 10, least, 0, 0, video), "off by default"); + assert!(!bar_wanted(least, least, 64 * MIB, 0, video), "a big one's side is in device-local memory"); + assert!(bar_wanted(least - (64 << 10), least, 64 * MIB, 0, video)); + assert!(!bar_wanted(MIB, least, 64 * MIB, 63 * MIB + 1, video), "past the number"); + assert!(bar_wanted(MIB, least, 64 * MIB, 63 * MIB, video), "up to it"); + assert!(!bar_wanted(MIB, least, 64 * MIB, 0, Some((20_000 * MIB, 16_000 * MIB))), "the card's memory four fifths full"); + assert!(bar_wanted(MIB, least, 64 * MIB, 0, None), "a budget not known"); + assert!(!bar_wanted(0, least, 64 * MIB, 0, video)); + } +} + /// Whether windows outside buffers have two sides too, so that submissions /// in the air read the bytes they were prepared with (`LEONIDA_WINDOWS_OWN=1`; /// off by default: it takes the windows' bytes again, 3.3 GB in capture @@ -1081,7 +1957,8 @@ fn windows_own() -> bool { *ON.get_or_init(|| std::env::var_os("LEONIDA_WINDOWS_OWN").is_some_and(|v| v == "1")) } -/// [`window_card_for`] in the card's own memory. +/// A buffer in the card's own memory for a window of `size` bytes, if it is +/// to be there ([`window_card_most`]). fn window_room_for(size: u64) -> Option<ID3D12Resource> { let most = window_card_most(); if most == 0 || !cards() { @@ -1246,7 +2123,7 @@ pub(crate) fn stale_pages(most: usize, say: &mut dyn FnMut(&Shadow, usize, usize done += hi - lo; // SAFETY: inside the mapping; nothing is in the air and the // submission lock is held. - let held = unsafe { std::slice::from_raw_parts(shadow.data.add(lo - start).cast_const(), hi - lo) }; + let held = unsafe { std::slice::from_raw_parts(shadow.data().add(lo - start).cast_const(), hi - lo) }; if held == title { continue; } @@ -1333,21 +2210,93 @@ pub(crate) fn copy_all(copies: Vec<(usize, usize, usize)>) { /// goes up to the copies in the card's memory that hold it, whether their /// CPU side held the same before or not. Left out is what shaders in the air /// may be writing (such a copy waits for them, or is done on the card). +/// The copies are found by the memory they hold ([`carded_over`]). What the +/// card is still to copy out of those CPU sides for submissions in the air is +/// waited for first ([`copying`]). pub(crate) fn send_copied(dst: usize, len: usize) { - for shadow in carded_copies() { + // (Not the switch: sends that went straight may be in the air after it + // turned off, `crate::host::send_numbered`.) + let guarded = crate::host::send_numbered(); + for shadow in carded_over(dst, dst.saturating_add(len)) { + #[cfg(test)] + SEND_COPIED_LOOKED.with(|l| l.set(l.get() + 1)); let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize); let (from, to) = (dst.max(start), (dst + len).min(end)); if from >= to { continue; } - let busy: Vec<(usize, usize)> = - shadow.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().copied().filter(|&(a, b)| a < to && b > from).collect(); - for (a, b) in outside(from, to, busy) { + // (A side the CPU writes: always, numbered or not.) + if guarded || shadow.card_bar().is_some() { + shadow.card_copying(from - start, to - start); + } + let free = shadow.pending.lock().unwrap_or_else(|e| e.into_inner()).outside(from, to); + for (a, b) in free { shadow.copy(a, b); } } } +/// For tests: the copies in the card's memory [`send_copied`] looked at on +/// this thread. +#[cfg(test)] +thread_local! { + static SEND_COPIED_LOOKED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + +/// We are about to write title memory `[dst, dst + len)` at submission, for +/// a command the title's GPU would run after the submissions in the air (a +/// buffer copy at its place, `CopyMemoryToMemoryX` done on the CPU): the +/// copies in the card's memory that hold it ([`carded_over`]) note it, and +/// what the card is still to copy out of their CPU sides there is waited +/// for, as their CPU side takes the bytes now or at a refresh before the card +/// gets to it ([`direct`]; nothing once no send ever went straight, +/// `crate::host::send_numbered`, whatever `LEONIDA_SEND_DIRECT` says now). +/// +/// A copy whose card side the CPU writes ([`bar_buffers_most`]) notes it +/// whether a send was ever numbered or not: its next send may be the first, +/// and would write the piece into the side under the submissions in the air. +pub(crate) fn copying(dst: usize, len: usize) { + let guarded = crate::host::send_numbered(); + if !guarded && BAR_BYTES.load(Ordering::Relaxed) == 0 { + return; + } + for shadow in carded_over(dst, dst.saturating_add(len)) { + if !guarded && shadow.card_bar().is_none() { + continue; + } + let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize); + let (from, to) = (dst.max(start), dst.saturating_add(len).min(end)); + if from < to { + shadow.card_copying(from - start, to - start); + } + } +} + +/// [`copying`] for the copies whose CPU side is title memory +/// ([`from_title`]) alone: a title buffer copy done on the CPU +/// (`crate::host`'s `Step::Copy`) writes title memory first and then has +/// [`send_copied`] wait for the straight sends in the air before it writes +/// the CPU sides; such a copy's CPU side is written by the first, so the wait +/// comes before it. So for a copy whose CPU side *was* title memory +/// ([`Shadow::unsource`]): sends recorded out of title memory before it got a +/// side of its own may still be in the air, and read the write when the card +/// gets to them. Nothing while no such copy was ever made. +pub(crate) fn source_copying(dst: usize, len: usize) { + if SOURCED[2].load(Ordering::Relaxed) == 0 || !crate::host::send_numbered() { + return; + } + for shadow in carded_over(dst, dst.saturating_add(len)) { + if !shadow.sourced() && !shadow.card.as_ref().is_some_and(|c| c.unsourced.load(Ordering::Acquire)) { + continue; + } + let (start, end) = (shadow.start as usize, (shadow.start + shadow.len) as usize); + let (from, to) = (dst.max(start), dst.saturating_add(len).min(end)); + if from < to { + shadow.card_copying(from - start, to - start); + } + } +} + /// The copies in the card's memory (diagnostics: `crate::host::upcheck`). pub(crate) fn carded_copies() -> Vec<Arc<Shadow>> { CARDED.lock().unwrap_or_else(|e| e.into_inner()).values().filter_map(std::sync::Weak::upgrade).collect() @@ -1568,6 +2517,13 @@ pub(crate) fn relay_fetched(number: u64) { RELAY_FETCHED.fetch_max(number, Ordering::AcqRel); } +/// Up to which send the notes of sends may go ([`relay_fetched`]), as +/// [`card_dirty`] reads it. +#[cfg(test)] +pub(crate) fn relay_fetched_for_test() -> u64 { + RELAY_FETCHED.load(Ordering::Acquire) +} + /// With [`relay`]: how many submissions that are not copied back yet /// declared each range shaders may be writing (range, count, the last /// submission that declared it). @@ -1634,6 +2590,245 @@ fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { differs != 0 } +/// The ranges of title memory shaders of a submission not yet copied back +/// may be writing in a copy ([`Shadow::writing`]): each as declared +/// (`(address, end)`), once, in order, and their union, so that what holds +/// a range, what overlaps one and what lies outside them all is found by a +/// search and not by a walk of every range. An empty range holds no byte +/// and overlaps nothing (the walk took one strictly inside `[from, to)` for +/// an overlap). +/// +/// It was a `Vec` of the ranges: each declaration looked through all of them +/// (whether it was there, then its parts no range held, against every +/// range), and each copy-back looked each of its ranges up in a list of the +/// submission's, a walk of all for each: quadratic in the ranges of a copy, +/// at every submission (the world declares overlapping views of its heap +/// dozens of times). +#[derive(Default)] +struct Pending { + ranges: std::collections::BTreeSet<(usize, usize)>, + /// The union of `ranges`: apart (ranges that overlap or touch are one), + /// in order. Made again from `ranges` when it is next asked for after a + /// range went (`stale`). + union: Vec<(usize, usize)>, + stale: bool, +} + +/// For tests: the ranges and pieces of union [`Pending`] looked at on this +/// thread. +#[cfg(test)] +thread_local! { + static PENDING_STEPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + +/// [`PENDING_STEPS`] grows by `n`. +#[cfg_attr(not(test), allow(unused_variables))] +fn pending_steps(n: usize) { + #[cfg(test)] + PENDING_STEPS.with(|s| s.set(s.get() + n as u64)); +} + +impl Pending { + fn is_empty(&self) -> bool { + self.ranges.is_empty() + } + + fn contains(&self, range: &(usize, usize)) -> bool { + pending_steps(1); + self.ranges.contains(range) + } + + /// Adds `range`; whether it was not there yet. + fn insert(&mut self, range: (usize, usize)) -> bool { + pending_steps(1); + if !self.ranges.insert(range) { + return false; + } + if !self.stale && range.0 < range.1 { + // The pieces of the union it overlaps or touches become one. + let (a, b) = range; + let lo = self.union.partition_point(|u| u.1 < a); + let hi = self.union.partition_point(|u| u.0 <= b); + pending_steps(hi - lo + 1); + let joined = if lo < hi { (self.union[lo].0.min(a), self.union[hi - 1].1.max(b)) } else { range }; + self.union.splice(lo..hi, [joined]); + } + true + } + + /// Takes `range` out; whether it was there. + fn remove(&mut self, range: &(usize, usize)) -> bool { + pending_steps(1); + let gone = self.ranges.remove(range); + self.stale |= gone; + gone + } + + /// The union, made again if a range went since. + fn union(&mut self) -> &[(usize, usize)] { + if self.stale { + self.stale = false; + self.union.clear(); + pending_steps(self.ranges.len()); + for &(a, b) in &self.ranges { + if a >= b { + continue; + } + match self.union.last_mut() { + Some(last) if a <= last.1 => last.1 = last.1.max(b), + _ => self.union.push((a, b)), + } + } + } + &self.union + } + + /// The index of the first piece of the union that ends after `from`. + fn first_after(&mut self, from: usize) -> usize { + let union = self.union(); + pending_steps(union.len().max(1).ilog2() as usize + 1); + union.partition_point(|u| u.1 <= from) + } + + /// Whether a range overlaps `[from, to)`. (Empty, it is asked of the + /// ranges themselves, as the walk did: one that holds `from` strictly + /// inside overlaps it, two that only meet there do not.) + fn overlaps(&mut self, from: usize, to: usize) -> bool { + if from >= to { + return !self.over(from, to).is_empty(); + } + let i = self.first_after(from); + self.union.get(i).is_some_and(|u| u.0 < to) + } + + /// The ranges that overlap `[from, to)`, as declared, in order. + fn over(&mut self, from: usize, to: usize) -> Vec<(usize, usize)> { + let i = self.first_after(from); + let Some(&(first, _)) = self.union.get(i).filter(|u| u.0 < to) else { + return Vec::new(); + }; + // Each such range lies in a piece of the union that ends after + // `from`, so it begins at the first such piece or later. + let mut out = Vec::new(); + for &(a, b) in self.ranges.range((first, 0)..) { + pending_steps(1); + if a >= to { + break; + } + if b > from && a < b { + out.push((a, b)); + } + } + out + } + + /// `[from, to)` without the ranges, in order. + fn outside(&mut self, from: usize, to: usize) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + let mut at = from; + let i = self.first_after(from); + for &(a, b) in &self.union[i..] { + pending_steps(1); + if a >= to { + break; + } + if a > at { + out.push((at, a)); + } + at = at.max(b); + } + if at < to { + out.push((at, to)); + } + out + } +} + +#[cfg(test)] +mod pending_tests { + use super::{Pending, outside}; + + /// What holds, overlaps and lies outside the ranges, as ranges come and + /// go, is what a walk of all of them finds. + #[test] + fn pending_ranges_answer_as_a_walk_of_all_of_them() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut random = |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % n as u64) as usize + }; + let mut pending = Pending::default(); + let mut all: Vec<(usize, usize)> = Vec::new(); + for round in 0..3000 { + if random(3) > 0 || all.is_empty() { + let a = random(4000); + let range = (a, a + 1 + random(200)); + assert_eq!(pending.insert(range), !all.contains(&range), "round {round}"); + if !all.contains(&range) { + all.push(range); + } + } else { + let range = all.swap_remove(random(all.len())); + assert!(pending.remove(&range)); + assert!(!pending.remove(&range)); + } + let (from, to) = { + let a = random(4300); + (a, a + random(300)) + }; + let mut over: Vec<_> = all.iter().copied().filter(|&(a, b)| a < to && b > from).collect(); + over.sort_unstable(); + assert_eq!(pending.over(from, to), over, "round {round}: over {from}..{to}"); + assert_eq!(pending.overlaps(from, to), !over.is_empty(), "round {round}: overlaps {from}..{to}"); + assert_eq!(pending.outside(from, to), outside(from, to, all.clone()), "round {round}: outside {from}..{to}"); + assert_eq!(pending.is_empty(), all.is_empty()); + assert!(all.is_empty() || pending.contains(&all[0])); + } + // An empty range holds no byte: it overlaps nothing. + let mut pending = Pending::default(); + pending.insert((50, 50)); + assert!(!pending.is_empty()); + assert!(!pending.overlaps(0, 100)); + assert_eq!(pending.over(0, 100), []); + assert_eq!(pending.outside(0, 100), [(0, 100)]); + } + + /// A copy's ranges declared (each twice, as dispatches declare them), + /// asked about and copied back take steps in proportion to the ranges + /// and their logarithm: each declaration looked through every range + /// declared before it, and the copy-back looked each range up in the + /// submission's list, some 8 million steps for 4,000 ranges. + #[test] + fn a_copys_ranges_are_searched_not_walked() { + const N: usize = 4000; + const EACH: usize = 1024; + let mut side = vec![0u8; N * EACH]; + let start = 0x6300_0000usize; + let shadow = super::Shadow::unbacked(start as u64, side.as_mut_ptr(), side.len() as u64, true); + super::PENDING_STEPS.with(|s| s.set(0)); + for _ in 0..2 { + for i in 0..N { + shadow.writing(start + i * EACH, EACH / 2); + } + } + for i in 0..N { + let at = start + i * EACH; + assert!(shadow.writes_pending_in(at + 100, at + 108), "range {i}"); + assert!(!shadow.writes_pending_in(at + EACH / 2, at + EACH / 2 + 8), "after range {i}"); + } + let declared: Vec<_> = (0..N).map(|i| (start + i * EACH, start + i * EACH + EACH / 2)).collect(); + shadow.copy_back_done(&declared); + assert!(!shadow.writes_pending()); + assert!(!shadow.writes_pending_in(start, start + N * EACH)); + let steps = super::PENDING_STEPS.with(|s| s.get()) as usize; + let most = 4 * N * (N.ilog2() as usize + 1); + assert!(steps <= most, "{steps} steps for {N} ranges (at most {most})"); + drop(side); + } +} + /// `[from, to)` without the ranges of `skip`, in order. fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> { skip.sort_unstable(); @@ -1874,8 +3069,9 @@ mod relay_tests { } } -/// Snapshot memory kept for reuse (already touched, so no page faults). -static POOL: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new()); +/// Snapshot memory kept for reuse (already touched, so no page faults), +/// each buffer with when it was given back ([`crate::host::coarse_ms`]). +static POOL: Mutex<Vec<(Vec<u8>, u64)>> = Mutex::new(Vec::new()); /// An empty buffer with room for `n` bytes, from the pool if it has one /// of about that size: a small copy's snapshot took the 174 MB buffer kept @@ -1887,11 +3083,11 @@ fn pooled(n: usize) -> Vec<u8> { let fit = pool .iter() .enumerate() - .filter(|(_, v)| v.capacity() >= n && v.capacity() <= most) - .min_by_key(|(_, v)| v.capacity()) + .filter(|(_, (v, _))| v.capacity() >= n && v.capacity() <= most) + .min_by_key(|(_, (v, _))| v.capacity()) .map(|(i, _)| i); let mut v = match fit { - Some(i) => pool.swap_remove(i), + Some(i) => pool.swap_remove(i).0, None => Vec::with_capacity(n), }; v.clear(); @@ -1917,11 +3113,12 @@ fn snapshots_kept() -> usize { /// bytes in all. fn give_back(v: Vec<u8>) { const KEPT: usize = 512 << 20; + let now = crate::host::coarse_ms(); let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); - pool.push(v); - pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); + pool.push((v, now)); + pool.sort_by_key(|(v, _)| std::cmp::Reverse(v.capacity())); let (mut kept, mut total) = (0, 0usize); - for v in pool.iter().take(snapshots_kept()) { + for (v, _) in pool.iter().take(snapshots_kept()) { total = total.saturating_add(v.capacity()); if kept > 0 && total > KEPT { break; @@ -1934,6 +3131,310 @@ fn give_back(v: Vec<u8>) { drop(gone); } +/// Lets go of the snapshot buffers no snapshot took for `idle_ms` +/// ([`crate::host::ram_idle_ms`]). Nothing trimmed the pool: after a burst of +/// submissions whose shaders write copies in the PC's memory it kept up to +/// 512 MiB (or its largest buffer, a whole copy's size: 174 MB for the big +/// heap's, run 24) for the rest of the run. A buffer a snapshot takes and +/// gives back starts its idle time again. +fn let_go_idle_snapshots(idle_ms: u64) { + let now = crate::host::coarse_ms(); + let gone = idle_snapshots(&mut POOL.lock().unwrap_or_else(|e| e.into_inner()), now, idle_ms); + // Freed on the reaper thread, after the lock is released: the sweep + // runs on the submitting thread under the submission lock (behind + // flights in the air with `LEONIDA_SWEEP_NO_SETTLE`, with nothing in + // flight otherwise, when the card waits for it), and freeing the whole + // idle pool at once (up to 512 MiB of touched memory) took 22-58 ms on + // a Ryzen 7 5800X. The pool holds only buffers given back, which no + // submission names; `retire` keeps them past those running anyway. + if !gone.is_empty() { + crate::host::retire(gone); + } +} + +/// Takes out of `pool` the buffers given back `idle_ms` or more before +/// `now`; the others keep their order. +fn idle_snapshots(pool: &mut Vec<(Vec<u8>, u64)>, now: u64, idle_ms: u64) -> Vec<(Vec<u8>, u64)> { + pool.extract_if(.., |(_, at)| now.saturating_sub(*at) >= idle_ms).collect() +} + +/// Whether a copy's snapshot holds only the 64 KiB pieces its declared +/// ranges are in ([`Snapshot`]; `LEONIDA_SNAPSHOT_DECLARED=0`: room for the +/// whole copy, as before). Kept snapshots (`LEONIDA_KEEP_SNAPSHOTS`) take +/// the whole copy either way: they are kept for the next submission's +/// ranges, wherever those are. +fn snapshot_declared() -> bool { + crate::toggled!("LEONIDA_SNAPSHOT_DECLARED") && !keeps() +} + +/// A copy's snapshot ([`Shadow::writing`]): its bytes before a submission +/// ran, for the ranges the submission's shaders write, each byte at its +/// offset in the copy. Held in stretches (first offset, end, buffer from +/// [`pooled`]), apart and in order, that begin and end where 64 KiB pieces +/// of title memory do (or at the copy's ends): a range declared where no +/// stretch is gets one for the pieces it is in. A stretch never moves and +/// none goes before the whole snapshot is given back +/// ([`Shadow::copy_back_done`]): [`find_all`] and [`take_snapshots`] hold +/// addresses in it without the lock, as they did in the one buffer. +/// +/// It was one buffer the size of the copy whatever was declared: one 64 KiB +/// range of a 64 MiB copy took 64 MiB of commit (`Vec::with_capacity` +/// commits all of it), and from the pool a buffer some earlier snapshot had +/// touched whole, for as long as anything was declared. A piece is what +/// [`find_all`], [`Shadow::differing`], [`Shadow::relay_merge`] and +/// [`Shadow::land_back`] work in, so none of them meets a stretch's end +/// inside what it compares. +#[derive(Default)] +struct Snapshot(Vec<(usize, usize, Vec<u8>)>); + +impl Snapshot { + /// Offsets `[from, to)` of a copy of title memory `[start, start + len)` + /// are declared: a stretch is made for each part no stretch holds, from + /// the start of the piece it begins in to the end of the piece it ends in + /// (not into a neighbour). `whole`: one stretch for all of the copy, if + /// the snapshot has none yet; one that already has stretches of pieces + /// gets more of them, as without it. [`snapshot_declared`] may change + /// while a snapshot lives (`LEONIDA_AB` in a diagnostics build flips it + /// at a present, and with the relay a busy copy's snapshot outlives + /// one): when `whole` returned on any stretch, a part declared after the + /// flip got none, so [`Snapshot::spans`] gave nothing for it and what the + /// shaders wrote there was neither found nor put into title memory. + fn hold(&mut self, start: usize, len: usize, from: usize, to: usize, whole: bool) { + let to = to.min(len); + if from >= to { + return; + } + if whole && self.0.is_empty() { + self.0.push((0, len, pooled(len))); + return; + } + // (A stretch for all of the copy holds every part: nothing is made.) + let mut made = Vec::new(); + let mut i = self.0.partition_point(|s| s.1 <= from); + let mut at = from; + while at < to { + match self.0.get(i) { + Some(&(lo, hi, _)) if lo <= at => { + at = hi; + i += 1; + } + next => { + // (The stretch before ends at or before `at`.) + let before = if i == 0 { 0 } else { self.0[i - 1].1 }; + let gap = next.map_or(len, |s| s.0); + let end = to.min(gap); + let pieces = pieces_of(start, at, end); + let lo = piece_at(start, len, pieces.start).0.max(before); + let hi = piece_at(start, len, pieces.end - 1).1.min(gap); + made.push((lo, hi)); + at = end; + } + } + } + if made.is_empty() { + return; + } + self.0.extend(made.into_iter().map(|(lo, hi)| (lo, hi, pooled(hi - lo)))); + self.0.sort_unstable_by_key(|s| s.0); + } + + /// Where offset `at` is, if one stretch holds `[at, at + n)`. + fn at(&mut self, at: usize, n: usize) -> Option<*mut u8> { + let i = self.0.partition_point(|s| s.1 <= at); + let (lo, hi, bytes) = self.0.get_mut(i)?; + // SAFETY: `at - lo < hi - lo`, which the buffer has room for. + (*lo <= at && at + n <= *hi).then(|| unsafe { bytes.as_mut_ptr().add(at - *lo) }) + } + + /// The parts of offsets `[from, to)` it holds: (offset, where it is, + /// bytes), in order. + fn spans(&mut self, from: usize, to: usize) -> Vec<(usize, usize, usize)> { + let i = self.0.partition_point(|s| s.1 <= from); + self.0[i..] + .iter_mut() + .take_while(|s| s.0 < to) + .map(|(lo, hi, bytes)| { + let (a, b) = (from.max(*lo), to.min(*hi)); + (a, bytes.as_mut_ptr() as usize + (a - *lo), b - a) + }) + .filter(|s| s.2 > 0) + .collect() + } + + /// The bytes its buffers have room for (their capacity: what they hold + /// of the PC's memory). + #[cfg(test)] + fn bytes(&self) -> usize { + self.0.iter().map(|s| s.2.capacity()).sum() + } + + /// Its buffers go back to the pool. + fn give_back(self) { + for (_, _, bytes) in self.0 { + give_back(bytes); + } + } +} + +#[cfg(test)] +mod snapshot_tests { + use super::*; + + /// Stretches cover what is declared, begin and end where pieces of title + /// memory do (or at the copy's ends), never overlap, and are not made + /// again for what one holds already. + #[test] + fn stretches_hold_the_pieces_of_what_is_declared() { + // A copy that starts 32 KiB into a piece and ends inside one. + let (start, len) = (0x0012_3456_8000usize, 10 * PIECE + 100); + let mut snapshot = Snapshot::default(); + snapshot.hold(start, len, 100, 200, false); + assert_eq!(snapshot.0.iter().map(|s| (s.0, s.1)).collect::<Vec<_>>(), [(0, PIECE / 2)]); + // Across two pieces, and again inside what is held: nothing new. + snapshot.hold(start, len, 3 * PIECE, 4 * PIECE, false); + snapshot.hold(start, len, 3 * PIECE + 5, 3 * PIECE + 9, false); + snapshot.hold(start, len, 150, 160, false); + let held = |s: &Snapshot| s.0.iter().map(|s| (s.0, s.1)).collect::<Vec<_>>(); + assert_eq!(held(&snapshot), [(0, PIECE / 2), (5 * PIECE / 2, 9 * PIECE / 2)]); + // A range over both and the gap between: only the gap is made, up to + // its neighbours; then one that runs past the copy's end. + snapshot.hold(start, len, 10, 4 * PIECE, false); + snapshot.hold(start, len, 9 * PIECE, len + 4096, false); + assert_eq!( + held(&snapshot), + [(0, PIECE / 2), (PIECE / 2, 5 * PIECE / 2), (5 * PIECE / 2, 9 * PIECE / 2), (17 * PIECE / 2, len)] + ); + for s in &snapshot.0 { + assert!(s.2.capacity() >= s.1 - s.0); + } + // A piece is in one stretch; what spans two is told in two parts. + assert!(snapshot.at(PIECE / 2 + 7, PIECE).is_some()); + assert!(snapshot.at(PIECE / 2 - 1, 2).is_none()); + assert!(snapshot.at(5 * PIECE, 4).is_none()); + let parts: Vec<_> = snapshot.spans(PIECE / 4, 3 * PIECE).iter().map(|s| (s.0, s.2)).collect(); + assert_eq!(parts, [(PIECE / 4, PIECE / 4), (PIECE / 2, 2 * PIECE), (5 * PIECE / 2, PIECE / 2)]); + // With the switch off: one stretch for the whole copy. + let mut whole = Snapshot::default(); + whole.hold(start, len, 100, 200, true); + whole.hold(start, len, 9 * PIECE, 9 * PIECE + 1, true); + assert_eq!(held(&whole), [(0, len)]); + snapshot.give_back(); + whole.give_back(); + } + + /// The switch flips while a snapshot lives (`LEONIDA_AB` at a present, + /// with the relay keeping a busy copy's snapshot across it): every part + /// declared, in either phase, is held, so [`Snapshot::spans`] gives + /// [`find_all`] and [`Shadow::copy_back_with`] all of it. A part declared + /// with `whole` after stretches of pieces were made had none. + #[test] + fn a_flip_of_the_switch_leaves_no_declared_part_unheld() { + let (start, len) = (0x0012_3456_8000usize, 10 * PIECE + 100); + let covered = |s: &mut Snapshot, from: usize, to: usize| s.spans(from, to).iter().map(|p| p.2).sum::<usize>(); + // Pieces first, then the whole copy asked for. + let mut snapshot = Snapshot::default(); + snapshot.hold(start, len, 100, 200, false); + snapshot.hold(start, len, 3 * PIECE, 3 * PIECE + 64, true); + snapshot.hold(start, len, 9 * PIECE, len, true); + assert_eq!(covered(&mut snapshot, 100, 200), 100); + assert_eq!(covered(&mut snapshot, 3 * PIECE, 3 * PIECE + 64), 64, "a part declared after the flip is held"); + assert_eq!(covered(&mut snapshot, 9 * PIECE, len), len - 9 * PIECE); + // Still pieces, not the whole copy, and apart and in order. + assert!(snapshot.0.iter().map(|s| s.1 - s.0).sum::<usize>() < len); + assert!(snapshot.0.windows(2).all(|w| w[0].1 <= w[1].0)); + snapshot.give_back(); + // The whole copy first, then pieces: the one stretch holds them. + let mut whole = Snapshot::default(); + whole.hold(start, len, 100, 200, true); + whole.hold(start, len, 3 * PIECE, 4 * PIECE, false); + assert_eq!(whole.0.iter().map(|s| (s.0, s.1)).collect::<Vec<_>>(), [(0, len)]); + assert_eq!(covered(&mut whole, 3 * PIECE, 4 * PIECE), PIECE); + whole.give_back(); + } + + /// Four ranges of 64 KiB declared in a copy of 64 MiB: the snapshot holds + /// the pieces they are in, not the copy's 64 MiB (it held all of it, from + /// a buffer of that size, whatever was declared), and the shaders' + /// writes in them are still found ([`find_all`]) and put into title + /// memory ([`Shadow::copy_back_with`]), and nothing else is. + #[test] + fn a_snapshot_holds_what_is_declared_not_the_whole_copy() { + const LEN: usize = 64 << 20; + const RANGE: usize = 64 << 10; + let mut title = vec![1u8; LEN]; + let mut data = title.clone(); + let start = title.as_mut_ptr() as usize; + let shadow = Shadow::unbacked(start as u64, data.as_mut_ptr(), LEN as u64, false); + let offsets = [4096usize, 9 << 20, 33 << 20, LEN - RANGE]; + for &at in &offsets { + shadow.writing(start + at, RANGE); + } + // (With `wide_back` the bytes are taken here, as at a submission.) + take_snapshots(); + let (held, room) = { + let before = shadow.before.lock().unwrap(); + let snapshot = before.as_ref().expect("a snapshot"); + (snapshot.0.iter().map(|s| s.1 - s.0).sum::<usize>(), snapshot.bytes()) + }; + // A range not on a piece's line is in two pieces. (A kept snapshot, + // `LEONIDA_KEEP_SNAPSHOTS=1`, holds the whole copy by design.) + if !keeps() { + assert!(held <= offsets.len() * 2 * PIECE, "the snapshot holds {held:#x} bytes of the copy"); + // (The pool may hand a stretch a buffer up to 1 MiB.) + assert!(room <= offsets.len() << 20, "the snapshot's buffers have room for {room:#x} bytes"); + } + // What the card wrote: a byte in each range, and one outside them all. + for &at in &offsets { + data[at + 77] = 9; + } + data[20 << 20] = 9; + let work: Vec<_> = offsets.iter().map(|&at| (shadow.clone(), start + at, start + at + RANGE)).collect(); + let found = find_all(&work); + for (i, &at) in offsets.iter().enumerate() { + assert!(found[i].iter().any(|&(a, n)| (a..a + n).contains(&(at + 77))), "range {i}: {:x?}", found[i]); + let written = shadow.copy_back_with(start + at, RANGE, Some(found[i].clone())); + assert!(written > 0, "range {i}: nothing put into title memory"); + assert_eq!(title[at + 77], 9, "range {i}"); + } + assert_eq!(title[20 << 20], 1, "outside the declared ranges"); + let declared: Vec<_> = offsets.iter().map(|&at| (start + at, start + at + RANGE)).collect(); + shadow.copy_back_done(&declared); + // (A kept one stays for the next submission.) + assert!(keeps() || shadow.before.lock().unwrap().is_none(), "the snapshot is given back with the last range"); + assert!(!shadow.writes_pending()); + drop(data); + } +} + +#[cfg(test)] +mod snapshot_pool_tests { + use super::idle_snapshots; + + /// Buffers no snapshot took for the idle time leave the pool, and those + /// given back since stay: the pool kept up to 512 MiB (or its largest + /// buffer) of the PC's memory for the rest of the run once a burst of + /// submissions had filled it. + #[test] + fn buffers_the_pool_kept_for_the_idle_time_go() { + const IDLE_MS: u64 = 10_000; + // Eight buffers given back at 1 s, as a burst leaves them (the + // pool's 512 MiB are eight of 64 MiB; these are smaller), and one at + // 9 s. + let mut pool: Vec<(Vec<u8>, u64)> = (0..8).map(|_| (Vec::with_capacity(64 << 10), 1_000)).collect(); + pool.push((Vec::with_capacity(64 << 10), 9_000)); + // Under the idle time: all stay. + assert!(idle_snapshots(&mut pool, 10_999, IDLE_MS).is_empty()); + assert_eq!(pool.len(), 9); + // The idle time since the burst: its eight go, the newer one stays. + let gone = idle_snapshots(&mut pool, 11_000, IDLE_MS); + assert_eq!(gone.len(), 8, "{} of the eight idle buffers let go", gone.len()); + assert_eq!(pool.iter().map(|(_, at)| *at).collect::<Vec<_>>(), [9_000]); + // And it goes once it has been idle as long; nothing is reserved. + assert_eq!(idle_snapshots(&mut pool, 19_000, IDLE_MS).len(), 1); + assert!(pool.is_empty()); + } +} + const NOT_WATCHED: u8 = 2; /// Watched, not by the kernel but by the guards, when last asked about. const GUARDED: u8 = 3; @@ -2012,7 +3513,7 @@ mod difference_tests { } /// The unit shader writes are looked for and put back in. -const PIECE: usize = 64 << 10; +pub(crate) const PIECE: usize = 64 << 10; /// Calls `f` with `[from, to)` cut at multiples of [`PIECE`]. fn for_pieces_of(from: usize, to: usize, mut f: impl FnMut(usize, usize)) { @@ -2220,6 +3721,8 @@ fn wide(jobs: Vec<Job>) { } return; } + #[cfg(test)] + WIDE_IN_TEST.set(WIDE_IN_TEST.get() + 1); let workers = workers(); let _wide = crate::timeline::span("work spread over threads"); // The calling thread also drains the queue. Wake helpers only for the @@ -2229,6 +3732,13 @@ fn wide(jobs: Vec<Job>) { wide_help(workers, &left); } +#[cfg(test)] +thread_local! { + /// For tests: how many times this thread spread work over the kept + /// threads ([`wide`] with two jobs or more). + pub(crate) static WIDE_IN_TEST: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + /// What is left of jobs given to the kept threads ([`wide_queue`]): how /// many, and the word that none is. type Left = Arc<(Mutex<usize>, std::sync::Condvar)>; @@ -2372,19 +3882,27 @@ fn copy_jobs(copies: Vec<(usize, usize, usize)>) -> Vec<Job> { /// not yet done), the 64 KiB pieces that differ from the snapshot, as /// [`Shadow::copy_back_with`] takes them; found on several threads. pub(crate) fn find_all(work: &[(Arc<Shadow>, usize, usize)]) -> Vec<Vec<(usize, usize)>> { - let scans = work - .iter() - .map(|(shadow, address, end)| { - let (from, to) = shadow.inside(*address, end.saturating_sub(*address)); - // The snapshot's memory stays until the range is done with - // (`copy_back_done`), which comes after this. - match shadow.before.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { - Some(before) => (shadow.data as usize, before.as_ptr() as usize, shadow.start as usize, from, to), - None => (0, 0, 0, 0, 0), + // A scan per stretch of the snapshot a range is in (each holds whole + // pieces), and which of `work` it is for. + let (mut scans, mut of) = (Vec::with_capacity(work.len()), Vec::with_capacity(work.len())); + for (i, (shadow, address, end)) in work.iter().enumerate() { + let (from, to) = shadow.inside(*address, end.saturating_sub(*address)); + // The snapshot's memory stays until the range is done with + // (`copy_back_done`), which comes after this. + if let Some(before) = shadow.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + for (at, held, n) in before.spans(from, to) { + // (`held` less `at`: where offset 0 would be, as a number; + // only offsets inside the stretch are added to it.) + scans.push((shadow.data() as usize, held.wrapping_sub(at), shadow.start as usize, at, at + n)); + of.push(i); } - }) - .collect(); - find_pieces(scans) + } + } + let mut out = vec![Vec::new(); work.len()]; + for (i, pieces) in of.into_iter().zip(find_pieces(scans)) { + out[i].extend(pieces); + } + out } /// For each of `scans` (where a copy's bytes are, where its snapshot's @@ -2423,7 +3941,7 @@ fn find_pieces(scans: Vec<(usize, usize, usize, usize, usize)>) -> Vec<Vec<(usiz let (now, old) = unsafe { ( std::slice::from_raw_parts((data + at) as *const u8, n), - std::slice::from_raw_parts((before + at) as *const u8, n), + std::slice::from_raw_parts(before.wrapping_add(at) as *const u8, n), ) }; if now != old { @@ -3137,7 +4655,7 @@ unsafe fn word_runs_avx2_in<const PUT: bool>(at: usize, title: &[u8], held: *mut } /// [`word_runs`] of `title` and `held`, and `held` is `title` afterwards. -fn word_runs_put(at: usize, title: &[u8], held: &mut [u8]) -> Vec<(usize, usize)> { +pub(crate) fn word_runs_put(at: usize, title: &[u8], held: &mut [u8]) -> Vec<(usize, usize)> { #[cfg(target_arch = "x86_64")] if title.len() == held.len() && std::arch::is_x86_feature_detected!("avx2") { // SAFETY: the processor has AVX2, and the lengths are the same; `held` @@ -3482,6 +5000,12 @@ impl Drop for Shadow { crate::inplace::gone(self.window, self.len); return; } + if self.sourced() + && let Some(card) = &self.card + { + SOURCED[0].fetch_sub(1, Ordering::Relaxed); + SOURCED[1].fetch_sub(card.size, Ordering::Relaxed); + } LIVE[0].fetch_sub(1, Ordering::Relaxed); LIVE[1].fetch_sub(self.len, Ordering::Relaxed); if self.kept.get_mut().unwrap_or_else(|e| e.into_inner()).1 { @@ -3495,6 +5019,8 @@ impl Drop for Shadow { if let Some(card) = &mut self.card { if window { WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed); + } else if card.bar != 0 { + BAR_BYTES.fetch_sub(card.size, Ordering::Relaxed); } else { CARD_BYTES[0].fetch_sub(card.size, Ordering::Relaxed); } @@ -3878,6 +5404,18 @@ pub(crate) fn window_use() -> [u64; 8] { /// again. Called before a submission starts, by the thread that submits. pub(crate) fn let_go_idle() { const IDLE_FRAMES: u64 = 4; + // Asked once for the whole sweep: each ask is a GlobalMemoryStatusEx + // call and a look at the residency headroom. + let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + // Small copies to card memory the CPU maps and back, if asked for + // (`LEONIDA_BAR_BUFFERS_MB`). + bar_sweep(); + // The snapshot buffers no snapshot took for that long go too, whether + // or not there are windows. + let_go_idle_snapshots(idle_ms); + // The spare buffers of copies of views' own bytes that no copy took for + // that long go too, whether or not there are windows. + let_go_idle_spares(idle_ms); let gone: Vec<Arc<Shadow>> = { // Held from the look to the removal: `loose` hands a copy out // under the same lock, so none is handed out in between. @@ -3885,7 +5423,6 @@ pub(crate) fn let_go_idle() { if map.is_empty() { return; } - let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); let idle: Vec<(u64, u64)> = map .iter() .filter(|(_, s)| { @@ -3906,17 +5443,21 @@ pub(crate) fn let_go_idle() { for shadow in gone { LET_GO[0].fetch_add(1, Ordering::Relaxed); LET_GO[1].fetch_add(shadow.len, Ordering::Relaxed); - // Nothing runs now and nothing names it: freed at once unless a - // submission is running after all. + // Nothing names it (a strong count of 1, one COM reference: a list + // in a flight would hold a clone of each), but flights may be in + // the air (`LEONIDA_SWEEP_NO_SETTLE`): `retire` frees it once every + // submission running has finished, at once if none is. crate::host::retire(shadow); } } /// For the memory line: host copies alive and their bytes, of them the /// windows of memory outside buffers and their bytes, and the snapshot -/// buffers kept for reuse and the bytes they reserve. +/// buffers kept for reuse and the bytes they reserve; then the copies whose +/// CPU side is title memory ([`from_title`]) and the bytes of the CPU sides +/// not made for them, and since the start those given a side of their own. #[cfg(feature = "diagnostics")] -pub(crate) fn memory() -> [u64; 6] { +pub(crate) fn memory() -> [u64; 9] { let (windows, window_bytes) = { let loose = LOOSE.write().unwrap_or_else(|e| e.into_inner()); // Each copy once: a window may stand under several keys. @@ -3930,7 +5471,7 @@ pub(crate) fn memory() -> [u64; 6] { }; let (kept, kept_bytes) = { let pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); - (pool.len() as u64, pool.iter().map(|v| v.capacity() as u64).sum::<u64>()) + (pool.len() as u64, pool.iter().map(|(v, _)| v.capacity() as u64).sum::<u64>()) }; [ LIVE[0].load(Ordering::Relaxed), @@ -3939,6 +5480,9 @@ pub(crate) fn memory() -> [u64; 6] { window_bytes, kept, kept_bytes, + SOURCED[0].load(Ordering::Relaxed), + SOURCED[1].load(Ordering::Relaxed), + SOURCED[4].load(Ordering::Relaxed) + SOURCED[5].load(Ordering::Relaxed), ] } @@ -4019,9 +5563,27 @@ impl Shadow { /// and keeps the copy alive until the list is reset. pub(crate) fn refresh(self: &Arc<Self>, list: &HostList, address: u64, len: u64) { let len = len.min(self.start + self.len - address); + if bar_buffers_most() != 0 { + self.read_by(crate::host::submissions().0); + } list.defer_refresh(self, address as usize, len as usize); } + /// A list recorded while `submission` was the newest begun reads the copy + /// ([`Shadow::read_in`]): counted once per submission. + fn read_by(&self, submission: u64) { + // (Read first: the same copy is asked for draw after draw, on every + // recording thread, and a write each time would bounce its line.) + if self.read_in[1].load(Ordering::Relaxed) != submission && self.read_in[1].swap(submission, Ordering::Relaxed) != submission { + self.read_in[0].fetch_add(1, Ordering::Relaxed); + } + } + + /// Where the CPU's side is mapped: the copy's offset 0. + fn data(&self) -> *mut u8 { + self.data.load(Ordering::Acquire) + } + /// The bytes of the host buffer. pub(crate) fn width(&self) -> u64 { // SAFETY: a live buffer. @@ -4037,7 +5599,7 @@ impl Shadow { landing: Default::default(), width: Default::default(), buffer, - data, + data: std::sync::atomic::AtomicPtr::new(data), gpu, start, len, @@ -4053,6 +5615,7 @@ impl Shadow { asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)], unsized_asks: AtomicU64::new(0), written: Default::default(), + read_in: [AtomicU64::new(0), AtomicU64::new(u64::MAX)], id: { static NEXT: AtomicU64 = AtomicU64::new(1); NEXT.fetch_add(1, Ordering::Relaxed) @@ -4065,9 +5628,19 @@ impl Shadow { wc: AtomicU8::new(0), mapped: false, place: None, + opened: None, + numbered: Default::default(), + switched: Default::default(), + replaced: Default::default(), } } + /// The directory of memory by address numbered it (`crate::memory`): it + /// holds it for good ([`Shadow::numbered`]). + pub(crate) fn note_numbered(&self) { + self.numbered.store(true, Ordering::Release); + } + /// `[address, address + len)` cut to the buffer, as offsets in the copy. fn inside(&self, address: usize, len: usize) -> (usize, usize) { let (start, end) = (self.start as usize, (self.start + self.len) as usize); @@ -4084,6 +5657,10 @@ impl Shadow { /// shortcut: what shaders wrote is found by keeping the range's bytes /// before the submission (a copy per declared range and submission); /// a GPU-side dirty mask would save that if big ranges make it slow. + /// + /// Diagnostics: where the copy is watched (`LEONIDA_UNDECLARED_TRACE`), + /// the list notes the caller and what became of the declaration. + #[cfg_attr(feature = "diagnostics", track_caller)] pub(crate) fn gpu_writes(self: &Arc<Self>, list: &HostList, address: u64, len: u64) { // (For indirect batches that end by what was written, `LEONIDA_INDIRECT_BATCH=3` and `4`: // the list keeps every range its shaders may write, whatever is done about copying it back.) @@ -4096,8 +5673,16 @@ impl Shadow { // inside this one with a copy of its own, a texture in it) is not // told: the card's writes are not seen by write watching. if self.place.is_some() { + // (Read by lists recorded before through the copy it took the + // place of, if one still holds that: [`in_place_switch`].) + if self.replaced.get().is_some_and(|old| old.strong_count() > 0) { + crate::inplace::written_across_switch(self.start, self.len); + } return; } + if self.switched.load(Ordering::Relaxed) { + crate::inplace::written_across_switch(self.start, self.len); + } self.written.store(true, Ordering::Relaxed); let len = len.min(self.left(address)); // Write-combined title memory, which the title's CPU does not read @@ -4105,12 +5690,16 @@ impl Shadow { // what shaders write in a big copy with a card side stays on the card. if self.card.is_some() && self.len >= wc_no_back_min() && wc_no_back() && self.write_combined() { WC_LEFT.fetch_add(len, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::host::undeclared::declares(list, self, address, len, "kept on the card (LEONIDA_WC_NO_BACK)"); return; } // Ported from maren-halv/VIctory-DXR dd83629 (GPL-3.0): a copy nothing but shaders has written for a // while is not declared, so not compared, fetched or landed (`elide`, `LEONIDA_COPYBACK_ELIDE`). if self.elide_skip() { self.elide_skipped(len); + #[cfg(feature = "diagnostics")] + crate::host::undeclared::declares(list, self, address, len, "elided (LEONIDA_COPYBACK_ELIDE)"); return; } // Leonida: parts the console has the GPU read only cannot have been written there @@ -4121,6 +5710,8 @@ impl Shadow { GPU_RO_DECLARED[0].fetch_add(bytes, Ordering::Relaxed); if gpu_ro_no_back() { GPU_RO_DECLARED[1].fetch_add(bytes, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::host::undeclared::declares(list, self, address, len, "declared, less the parts the GPU only reads (LEONIDA_GPU_READ_ONLY_NO_BACK)"); let mut at = address; for (from, to) in read_only { if from > at { @@ -4134,6 +5725,8 @@ impl Shadow { return; } } + #[cfg(feature = "diagnostics")] + crate::host::undeclared::declares(list, self, address, len, "declared"); list.defer_gpu_write(self, address as usize, len as usize); } @@ -4170,6 +5763,11 @@ impl Shadow { if self.place.is_some() { return; } + // The merge compares what the card makes of the range with the CPU's + // side: title memory is not what the card side held ([`from_title`]). + if self.unsource("shaders are declared to write it") { + SOURCED[4].fetch_add(1, Ordering::Relaxed); + } let range = (address, address + len); let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); // With the copy-back on its own thread: counted for this submission @@ -4185,38 +5783,27 @@ impl Shadow { // the card (`Host::card_before` reads the declared ranges from the // lists). if self.card.is_some() { - pending.push(range); + pending.insert(range); self.has_pending.store(true, Ordering::Release); return; } - // The parts no declared range holds yet: their bytes are taken now, - // just after the range's refresh (a part declared earlier has not - // been refreshed since, and keeps the bytes taken then). - let mut parts = vec![self.inside(address, len)]; - for &(a, e) in pending.iter() { - let (a, e) = self.inside(a, e - a); - let mut rest = Vec::with_capacity(parts.len() + 1); - for (from, to) in parts { - if e <= from || a >= to { - rest.push((from, to)); - continue; - } - if from < a { - rest.push((from, a)); - } - if e < to { - rest.push((e, to)); - } - } - parts = rest; - } - pending.push(range); + // The parts no declared range holds yet, as offsets in the copy: + // their bytes are taken now, just after the range's refresh (a part + // declared earlier has not been refreshed since, and keeps the bytes + // taken then). + let parts: Vec<(usize, usize)> = + pending.outside(range.0, range.1).into_iter().map(|(a, e)| self.inside(a, e - a)).filter(|&(a, e)| a < e).collect(); + pending.insert(range); self.has_pending.store(true, Ordering::Release); let taken: usize = parts.iter().map(|&(from, to)| to.saturating_sub(from)).sum(); BACK_CLASS[usize::from(!self.window)].fetch_add(taken as u64, Ordering::Relaxed); let total = self.len as usize; let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); - let snapshot = before.get_or_insert_with(|| pooled(total)); + let snapshot = before.get_or_insert_with(Snapshot::default); + let whole = !snapshot_declared(); + for &(from, to) in &parts { + snapshot.hold(self.start as usize, total, from, to, whole); + } if keeps() { // Piece by piece, and only the pieces not known current. A // piece the part holds whole is current from now on; of a @@ -4239,9 +5826,13 @@ impl Shadow { let (lo, hi) = self.piece(piece); let whole = from <= lo && hi <= to; let (lo, hi) = (lo.max(from), hi.min(to)); + // (One stretch holds all of a kept snapshot.) + let Some(at) = snapshot.at(lo, hi - lo) else { + continue; + }; // SAFETY: as below; `hi <= total`. unsafe { - std::ptr::copy_nonoverlapping(self.data.add(lo), snapshot.as_mut_ptr().add(lo), hi - lo); + std::ptr::copy_nonoverlapping(self.data().add(lo), at, hi - lo); } kept.0[piece] = whole; } @@ -4255,16 +5846,19 @@ impl Shadow { // then. The snapshot's memory stays where it is until the // range is done with (`copy_back_done`). let mut snaps = SNAPS.lock().unwrap_or_else(|e| e.into_inner()); - let (data, snapshot) = (self.data as usize, snapshot.as_mut_ptr() as usize); - snaps.extend(parts.into_iter().filter(|&(from, to)| from < to).map(|(from, to)| (data + from, snapshot + from, to - from))); + let data = self.data() as usize; + for (from, to) in parts { + snaps.extend(snapshot.spans(from, to).into_iter().map(|(at, held, n)| (data + at, held, n))); + } return; } for (from, to) in parts { - if from < to { - // SAFETY: the copy's mapping and the snapshot's allocation - // (`pooled`) both hold `total` bytes, and `to <= total`. + for (at, held, n) in snapshot.spans(from, to) { + // SAFETY: inside the copy's mapping (`at + n <= total`) and + // inside a stretch of the snapshot, which holds the part + // (`Snapshot::hold` above). unsafe { - copy_wide(self.data.add(from), snapshot.as_mut_ptr().add(from), to - from); + copy_wide(self.data().add(at), held as *mut u8, n); } } } @@ -4290,17 +5884,23 @@ impl Shadow { if self.place.is_some() { return 0; } - let snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); let mut written = 0; let (from, to) = self.inside(address, len); let start = self.start as usize; self.compared(from, to); - if let Some(before) = &*snapshot + if let Some(before) = snapshot.as_mut() && from < to { - // SAFETY: `writing` set the snapshot's bytes of every declared - // range, at the copy's offsets. - let before = unsafe { std::slice::from_raw_parts(before.as_ptr().add(from), to - from) }; + // The stretches of the snapshot that hold the range: `writing` + // set their bytes of every declared range, at the copy's + // offsets, and each 64 KiB piece is in one of them. + let spans = before.spans(from, to); + let old = |at: usize, n: usize| -> Option<*const u8> { + let i = spans.partition_point(|s| s.0 + s.2 <= at); + let &(lo, held, len) = spans.get(i)?; + (lo <= at && at + n <= lo + len).then_some((held + (at - lo)) as *const u8) + }; // By 64 KiB piece: the copy compared with its bytes before the // submission (on several threads: gigabytes a frame, bound by // memory speed), title memory read only where the GPU wrote. @@ -4308,7 +5908,11 @@ impl Shadow { let scanning = std::time::Instant::now(); let differing = match found { Some(found) => found, - None => self.differing(from, to, before), + None => spans + .iter() + // SAFETY: a stretch's part, `n` bytes from `held`. + .flat_map(|&(at, held, n)| self.differing(at, at + n, unsafe { std::slice::from_raw_parts(held as *const u8, n) })) + .collect(), }; #[cfg(feature = "diagnostics")] let syncing = { @@ -4329,8 +5933,13 @@ impl Shadow { for (at, n) in differing { // SAFETY: inside the mapping; only the submitting thread // writes it. - let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; - let old = &before[at - from..at - from + n]; + let host = unsafe { std::slice::from_raw_parts_mut(self.data().add(at), n) }; + let Some(old) = old(at, n) else { + continue; + }; + // SAFETY: `n` bytes of a stretch of the snapshot, which only + // this thread touches under its lock. + let old = unsafe { std::slice::from_raw_parts(old, n) }; let read = |first: usize, title: &mut [u8]| crate::host::read_into((start + at + first) as *const u8, title); let Some((first, n)) = back_piece(host, old, &mut title, &mut mask, &mut runs, read) else { continue; @@ -4402,14 +6011,17 @@ impl Shadow { // room just reserved; the card may write the mapping meanwhile, and // each byte read is one it held at some moment. unsafe { - std::ptr::copy_nonoverlapping(self.data.add(at), now.as_mut_ptr(), n); + std::ptr::copy_nonoverlapping(self.data().add(at), now.as_mut_ptr(), n); now.set_len(n); } - // SAFETY: the snapshot's allocation holds the copy's length - // (`writing`), and these offsets are in a range declared and not - // done with, whose bytes it holds; nothing else touches them - // without the lock held here. - let held = unsafe { std::slice::from_raw_parts_mut(before.as_mut_ptr().add(at), n) }; + // (A piece is in one stretch of the snapshot.) + let Some(held) = before.at(at, n) else { + return 0; + }; + // SAFETY: a stretch of the snapshot holds these offsets (`writing`), + // which are in a range declared and not done with, whose bytes it + // holds; nothing else touches them without the lock held here. + let held = unsafe { std::slice::from_raw_parts_mut(held, n) }; let Some(first) = first_difference(now, held) else { return 0; }; @@ -4435,7 +6047,7 @@ impl Shadow { /// `from` on), as (offset, bytes) in order; compared on several threads /// when the range is big. fn differing(&self, from: usize, to: usize, before: &[u8]) -> Vec<(usize, usize)> { - let (start, data) = (self.start as usize, self.data as usize); + let (start, data) = (self.start as usize, self.data() as usize); let scan = |a: usize, b: usize| -> Vec<(usize, usize)> { let mut found = Vec::new(); let mut at = a; @@ -4499,9 +6111,13 @@ impl Shadow { let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); if relay() { let free = self.flights.lock().unwrap_or_else(|e| e.into_inner()).done(ranges); - pending.retain(|r| free.binary_search(r).is_err()); + for range in &free { + pending.remove(range); + } } else { - pending.retain(|r| !ranges.contains(r)); + for range in ranges { + pending.remove(range); + } } if pending.is_empty() { self.has_pending.store(false, Ordering::Release); @@ -4528,8 +6144,8 @@ impl Shadow { // the snapshot's.) kept.0.clear(); } - if let Some(bytes) = self.before.lock().unwrap_or_else(|e| e.into_inner()).take() { - give_back(bytes); + if let Some(snapshot) = self.before.lock().unwrap_or_else(|e| e.into_inner()).take() { + snapshot.give_back(); } } @@ -4578,7 +6194,7 @@ impl Shadow { /// Whether one of those submissions may be writing in title memory /// `[from, to)`. pub(crate) fn writes_pending_in(&self, from: usize, to: usize) -> bool { - self.may_pend() && self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) + self.may_pend() && self.pending.lock().unwrap_or_else(|e| e.into_inner()).overlaps(from, to) } /// Whether [`Shadow::update`] of `[address, address + len)` would leave @@ -4605,9 +6221,9 @@ impl Shadow { .pending .lock() .unwrap_or_else(|e| e.into_inner()) - .iter() - .filter(|&&(a, e)| a < to && e > from) - .map(|&(a, e)| (a.max(from), e.min(to))) + .over(from, to) + .into_iter() + .map(|(a, e)| (a.max(from), e.min(to))) .collect(); if busy.is_empty() { return false; @@ -4653,9 +6269,9 @@ impl Shadow { .pending .lock() .unwrap_or_else(|e| e.into_inner()) - .iter() - .filter(|&&(a, e)| a < to && e > from) - .map(|&(a, e)| (a.max(from), e.min(to))) + .over(from, to) + .into_iter() + .map(|(a, e)| (a.max(from), e.min(to))) .collect(); if busy.is_empty() { return false; @@ -4702,15 +6318,26 @@ impl Shadow { // bytes for the title's. let merging = self.merging.write().unwrap_or_else(|e| e.into_inner()); let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); - let held = if self.card.is_some() { - self.data as usize - } else { - before.as_mut().map_or(0, |snapshot| snapshot.as_mut_ptr() as usize) + // Where the reference's bytes of a page are: in the CPU's side, + // or in the stretch of the snapshot that holds it (a page is in + // one); none, and the flights are settled, for a page no stretch + // holds. + let spans = match before.as_mut() { + _ if self.card.is_some() => Vec::new(), + Some(snapshot) => snapshot.spans(a - start, e - start), + None => { + note_stale(3); + return true; + } + }; + let held_at = |at: usize, n: usize| -> Option<usize> { + if self.card.is_some() { + return Some(self.data() as usize + at); + } + let i = spans.partition_point(|s| s.0 + s.2 <= at); + let &(lo, held, len) = spans.get(i)?; + (lo <= at && at + n <= lo + len).then_some(held + (at - lo)) }; - if held == 0 { - note_stale(3); - return true; - } // A page's part in the range, compared and put in: the runs it // changed; none for a page that is not there (left as it is, and // looked at again next time) or that had too many. @@ -4722,10 +6349,14 @@ impl Shadow { let one = |i: usize| { let (lo, hi) = page_of(i); if lo < hi && !over.load(Ordering::Relaxed) { - // SAFETY: the reference holds the copy's bytes at the - // copy's offsets, and these are in a declared range; the - // locks held above keep out what else writes them, and - // no two pages are the same. + let Some(held) = held_at(lo - start, hi - lo) else { + over.store(true, Ordering::Relaxed); + return; + }; + // SAFETY: the reference holds the copy's bytes of the + // page from `held` on, and these are in a declared range; + // the locks held above keep out what else writes them, + // and no two pages are the same. let runs = unsafe { self.merge_page_under_writes(lo, hi - lo, held as *mut u8, &left) }; match runs { Ok(runs) => *done[i].lock().unwrap_or_else(|e| e.into_inner()) = runs, @@ -4774,13 +6405,13 @@ impl Shadow { } /// Of [`Shadow::merge_under_writes`]: title memory `[lo, lo + n)`, in one - /// page, compared with the reference, which begins at `held`, and put in. - /// The runs that changed, none if it cannot be read, and an error if - /// there were more to copy one by one than `left`. + /// page, compared with the reference, whose bytes of it are `n` from + /// `held` on, and put in. The runs that changed, none if it cannot be + /// read, and an error if there were more to copy one by one than `left`. /// /// # Safety - /// The reference holds the copy's length, and nothing else writes these - /// bytes of it during the call. + /// The reference holds `n` bytes at `held`, and nothing else writes + /// them during the call. unsafe fn merge_page_under_writes( &self, lo: usize, @@ -4800,7 +6431,7 @@ impl Shadow { MERGED[0].fetch_add(1, Ordering::Relaxed); let at = lo - self.start as usize; // SAFETY: the caller's. - let held = unsafe { std::slice::from_raw_parts_mut(held.add(at), n) }; + let held = unsafe { std::slice::from_raw_parts_mut(held, n) }; if self.card.is_some() { // Whole words go up as pairs, all of them in one // dispatch: only what is a copy of its own counts. @@ -4824,7 +6455,7 @@ impl Shadow { // SAFETY: inside the copy's mapping. The card may be // writing the copy beside these bytes; they are // written here and nothing around them. - unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) }; + unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data().add(at + r), m) }; held[r..r + m].copy_from_slice(&title[r..r + m]); } Ok(Some(runs)) @@ -4835,8 +6466,9 @@ impl Shadow { /// since it was last copied (all of it if the memory is not /// write-watched). Returns the bytes copied. pub(crate) fn update(&self, address: usize, len: usize) -> usize { - // In place: the card reads title memory itself. - if self.place.is_some() { + // In place: the card reads title memory itself. Opened: the CPU's + // side is the memory, and its writer said what goes up. + if self.place.is_some() || self.opened.is_some() { return 0; } let (start, end) = (self.start as usize, (self.start + self.len) as usize); @@ -4845,30 +6477,12 @@ impl Shadow { return 0; } if self.may_pend() { - let mut busy: Vec<(usize, usize)> = self - .pending - .lock() - .unwrap_or_else(|e| e.into_inner()) - .iter() - .copied() - .filter(|&(a, e)| a < to && e > from) - .collect(); - if !busy.is_empty() { + let gaps = self.pending.lock().unwrap_or_else(|e| e.into_inner()).outside(from, to); + if gaps != [(from, to)] { // Around ranges shaders are writing: the gaps, each as below // (in the world most submissions have such ranges; copying the // gaps whole cost ~1 s per frame). - busy.sort_unstable(); - let (mut at, mut bytes) = (from, 0); - for (a, e) in busy { - if a > at { - bytes += self.update_free(at, a); - } - at = at.max(e); - } - if at < to { - bytes += self.update_free(at, to); - } - return bytes; + return gaps.into_iter().map(|(a, e)| self.update_free(a, e)).sum(); } } self.update_free(from, to) @@ -4878,7 +6492,7 @@ impl Shadow { /// nothing, and knows it without asking anything /// (`crate::watch::nothing_new`). `false` if it would have to ask. pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool { - if self.place.is_some() { + if self.place.is_some() || self.opened.is_some() { return true; } let (start, end) = (self.start as usize, (self.start + self.len) as usize); @@ -4890,7 +6504,7 @@ impl Shadow { return false; } // Around ranges shaders are writing the refresh asks gap by gap. - if self.may_pend() && self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) { + if self.may_pend() && self.pending.lock().unwrap_or_else(|e| e.into_inner()).overlaps(from, to) { return false; } let copied = self.copied.read().unwrap_or_else(|e| e.into_inner()); @@ -4965,7 +6579,7 @@ impl Shadow { if crate::host::read_into(at as *const u8, &mut title[..n]) { // SAFETY: `[from, to)` lies inside the buffer (`update`), // so these bytes are inside the copy's mapping. - let copy = unsafe { std::slice::from_raw_parts(self.data.add(at - start).cast_const(), n) }; + let copy = unsafe { std::slice::from_raw_parts(self.data().add(at - start).cast_const(), n) }; let mut map = DIFFERING.lock().unwrap_or_else(|e| e.into_inner()); let map = map.get_or_insert_with(Default::default); if copy == &title[..n] { @@ -5169,11 +6783,14 @@ impl Shadow { // SAFETY: inside the mapping of the copy's CPU side, which // nothing else reads or writes there: no shader's range // holds it, and the parts of a refresh lie apart. - let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), next - at) }; + let held = unsafe { std::slice::from_raw_parts_mut(self.data().add(at - start), next - at) }; if title == held { ECHO[0].fetch_add((next - at) as u64, Ordering::Relaxed); } else { ECHO[1].fetch_add((next - at) as u64, Ordering::Relaxed); + if let Some(card) = &self.card { + card.taken.fetch_add((next - at) as u64, Ordering::Relaxed); + } held.copy_from_slice(title); self.changed(at - start, next - start); self.card_changed(at - start, next - start); @@ -5192,6 +6809,10 @@ impl Shadow { /// A page of title memory, as read. static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) }; } + // Nothing to compare with: the CPU's side is title memory itself. + if self.sourced() { + return self.copy(from, to); + } let Some(card) = self.card.as_ref().filter(|_| self.changes_only.load(Ordering::Relaxed) || send_changed()) else { if known && self.card.is_some() && self.landing.load(Ordering::Acquire) && land_echo() && !crate::host::upcheck::on() { return self.take_landed(from, to); @@ -5212,7 +6833,7 @@ impl Shadow { // nothing else reads or writes there (the card copies from // it): no shader's range holds it, and the parts of a // refresh lie apart. - let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), n) }; + let held = unsafe { std::slice::from_raw_parts_mut(self.data().add(at - start), n) }; let was = crate::host::upcheck::on().then(|| held.to_vec()); let runs = if refresh_dirty() { // Compared and put in one pass, with AVX2 from any address. @@ -5231,6 +6852,7 @@ impl Shadow { if let Some(was) = was { crate::host::upcheck::note(self.id, at - start, &was, held); } + card.taken.fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed); SEND[0].fetch_add(n as u64, Ordering::Relaxed); if runs.is_empty() { SEND[1].fetch_add(n as u64, Ordering::Relaxed); @@ -5247,13 +6869,26 @@ impl Shadow { fn copy(&self, from: usize, to: usize) -> usize { let (start, end) = (self.start as usize, (self.start + self.len) as usize); let (from, to) = (from.max(start), to.min(end)); + if from >= to { + return 0; + } + // The CPU's side is title memory itself ([`from_title`]): what + // changed there goes up as it is, and nothing is copied. + if self.sourced() { + self.changed(from - start, to - start); + self.card_changed(from - start, to - start); + return to - from; + } + if let Some(card) = &self.card { + card.taken.fetch_add((to - from) as u64, Ordering::Relaxed); + } // SAFETY: inside the mapping (`from` and `to` are within the buffer). - let at = unsafe { self.data.add(from - start) }; + let at = unsafe { self.data().add(from - start) }; if self.card.is_some() && from < to && crate::host::upcheck::on() { for_pieces_of(from - start, to - start, |a, b| { let was = self.card_held(a, b - a); // SAFETY: inside the mapping, as above. - crate::host::copy_mapped(unsafe { self.data.add(a) }, (start + a) as *const u8, b - a, false); + crate::host::copy_mapped(unsafe { self.data().add(a) }, (start + a) as *const u8, b - a, false); crate::host::upcheck::note(self.id, a, &was, &self.card_held(a, b - a)); }); } else { @@ -5274,6 +6909,11 @@ impl Shadow { /// Shaders store in it what is not declared: from here on only the dwords /// the title changes go up ([`by_address`]). pub(crate) fn keep_stores(&self) { + // Only the dwords that differ from the CPU's side go up from now on: + // title memory cannot be that side ([`from_title`]). + if self.unsource("its undeclared stores are kept") { + SOURCED[4].fetch_add(1, Ordering::Relaxed); + } self.changes_only.store(true, Ordering::Relaxed); } @@ -5282,6 +6922,86 @@ impl Shadow { self.card_changed(from, to); } + /// [`Shadow::resend`] of each of `runs` (offsets `[from, to)`). + pub(crate) fn resend_runs(&self, runs: impl Iterator<Item = (usize, usize)>) { + self.card_changed_runs(runs); + } + + /// Whether the CPU's side is the memory itself ([`by_address_opened`]): + /// then only what its writer resends goes up. + pub(crate) fn side_is_memory(&self) -> bool { + self.opened.is_some() + } + + /// Whether the CPU's side is the title memory itself ([`from_title`]): + /// a refresh notes what goes up and copies nothing. + pub(crate) fn sourced(&self) -> bool { + self.card.is_some() && self.opened.is_none() && self.data() as u64 == self.start + } + + /// Of a copy whose CPU side is title memory ([`from_title`]): gives it a + /// buffer of its own in the PC's memory, filled from title memory, and + /// sends all of it up again before the next submission (what the card + /// side holds is known no better). The buffer placed over title memory + /// goes once the card is done with what was recorded from it + /// ([`crate::host::retire`]), and with it the heap over the title's + /// pages. Whether it did now: `false` for a copy whose side is its own + /// already, or if no buffer could be made (then it goes on as it was, + /// said once). + /// + /// No refresh of the copy runs meanwhile (the page state's lock, which a + /// refresh holds from its plan to its note): one that noted pages taken + /// while the CPU's side was title memory noted bytes the fill reads after + /// it, and one after it fills the new side. + pub(crate) fn unsource(&self, why: &str) -> bool { + if !self.sourced() { + return false; + } + let (Some(card), Some(host)) = (self.card.as_ref(), host()) else { + return false; + }; + let copied = self.copied.write().unwrap_or_else(|e| e.into_inner()); + let mut staging = card.staging.write().unwrap_or_else(|e| e.into_inner()); + if !self.sourced() { + return false; + } + let Some((buffer, data)) = host.shared_buffer(card.size) else { + SOURCED[6].fetch_add(1, Ordering::Relaxed); + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!( + start = format_args!("{:#x}", self.start), + len = self.len, + why, + "a host copy whose CPU side is title memory got no side of its own: it goes on reading title memory (LEONIDA_CARD_FROM_TITLE)" + ); + }); + return false; + }; + crate::host::name(&buffer, || format!("title buffer {:#x}+{:#x}, the CPU's side", self.start, self.len)); + // (Pages that are not there read as zeros.) + crate::host::copy_mapped(data, self.start as *const u8, self.len as usize, false); + card.taken.fetch_add(self.len, Ordering::Relaxed); + // Before `data` moves: a `Step::Copy` that no longer finds the copy + // sourced finds this ([`source_copying`]). + card.unsourced.store(true, Ordering::Release); + let old = std::mem::replace(&mut *staging, buffer); + self.data.store(data, Ordering::Release); + drop(staging); + drop(copied); + SOURCED[0].fetch_sub(1, Ordering::Relaxed); + SOURCED[1].fetch_sub(card.size, Ordering::Relaxed); + self.card_changed(0, self.len as usize); + tracing::info!( + start = format_args!("{:#x}", self.start), + len = self.len, + why, + "a host copy whose CPU side was title memory has one of its own now, and goes up whole (LEONIDA_CARD_FROM_TITLE)" + ); + crate::host::retire(old); + true + } + /// The CPU side's bytes at offsets `[from, to)` changed: they go to the /// card's side before the next submission. fn card_changed(&self, from: usize, to: usize) { @@ -5341,11 +7061,149 @@ impl Shadow { ranges } + /// With `LEONIDA_SEND_DIRECT` (`crate::host::send`): send `number` takes + /// `ranges` of the copy (in order) and the card is past send `reached`. + /// Each range in parts, in order, each with whether the card copies it + /// straight out of the CPU side (noted as in the air until the card is + /// past `number`) or it goes through the submission's memory + /// ([`direct`]). `None` for a copy that sends nothing straight: none in + /// the card's memory, or one whose CPU side is memory of ours that + /// recording threads write ([`Shadow::side_is_memory`]). + pub(crate) fn card_split( + &self, + ranges: impl Iterator<Item = (usize, usize)>, + number: u64, + reached: u64, + ) -> Option<Vec<(usize, usize, bool)>> { + let card = self.card.as_ref().filter(|_| self.opened.is_none())?; + let mut direct = card.direct.lock().unwrap_or_else(|e| e.into_inner()); + direct.landed(reached); + let mut parts = Vec::new(); + for (from, to) in ranges { + let (straight, own) = direct.split(from, to, number); + let mut all: Vec<(usize, usize, bool)> = straight.into_iter().map(|(a, b)| (a, b, true)).collect(); + all.extend(own.into_iter().map(|(a, b)| (a, b, false))); + all.sort_unstable(); + parts.extend(all); + } + Some(parts) + } + + /// [`Shadow::card_split`] for a copy whose card side the CPU writes + /// ([`Shadow::card_bar`]): each range in parts, in order, each with + /// whether the CPU writes it into the card side now (`true`; nothing is + /// noted as in the air) or it goes through the submission's memory + /// (`direct::Direct::split_mapped`). Short runs too: they are no copy + /// command of their own either way. `None` for a copy without such a side. + pub(crate) fn card_split_mapped( + &self, + ranges: impl Iterator<Item = (usize, usize)>, + number: u64, + reached: u64, + ) -> Option<Vec<(usize, usize, bool)>> { + let card = self.card.as_ref().filter(|c| c.bar != 0 && self.opened.is_none())?; + let mut direct = card.direct.lock().unwrap_or_else(|e| e.into_inner()); + let mut parts = Vec::new(); + for (from, to) in ranges { + let (straight, own) = direct.split_mapped(from, to, number, reached); + let mut all: Vec<(usize, usize, bool)> = straight.into_iter().map(|(a, b)| (a, b, true)).collect(); + all.extend(own.into_iter().map(|(a, b)| (a, b, false))); + all.sort_unstable(); + parts.extend(all); + } + Some(parts) + } + + /// Of a copy whose card side lies in card memory the CPU maps + /// ([`bar_buffers_most`]): where that side is mapped. Only written, by + /// `crate::host::send` (a read of it crosses the bus a few bytes at a + /// time); every read of the copy reads the CPU's side + /// ([`Shadow::card_data`]). + pub(crate) fn card_bar(&self) -> Option<usize> { + self.card.as_ref().map(|c| c.bar).filter(|&bar| bar != 0) + } + + /// We write offsets `[from, to)` of the copy at submission (title memory + /// and, now or at a refresh, the CPU side; [`copying`]): noted, so that + /// the next sends take those pieces through the submission's memory, and + /// a send in the air that copies them straight out of the CPU side is + /// waited for ([`direct`]). + fn card_copying(&self, from: usize, to: usize) { + let Some(card) = self.card.as_ref().filter(|_| self.opened.is_none()) else { + return; + }; + let mut direct = card.direct.lock().unwrap_or_else(|e| e.into_inner()); + direct.copied(from, to, crate::host::send_number()); + if card.bar != 0 { + direct.copied_mapped(from, to, crate::host::send_number()); + } + if !direct.in_air() { + return; + } + let reached = crate::host::send_reached(); + direct.landed(reached); + let blocking = direct.blocking(from, to, reached); + if blocking != 0 { + direct.waits += 1; + } + drop(direct); + if blocking != 0 { + crate::host::send_wait(blocking); + } + } + + /// Of this copy ([`direct`]): bytes sent straight out of its CPU side, + /// bytes sent through the submissions' memory, and the sends in the air + /// waited for before a write of ours. Its own, whichever test's + /// submission took its changes (`card_dirty` takes every copy's). + #[cfg(test)] + pub(crate) fn direct_for_test(&self) -> (u64, u64, u64) { + let direct = self.card.as_ref().map(|c| c.direct.lock().unwrap_or_else(|e| e.into_inner())); + direct.map_or((0, 0, 0), |d| (d.sent[0], d.sent[1], d.waits)) + } + /// Whether shaders were ever declared to write it. pub(crate) fn written(&self) -> bool { self.written.load(Ordering::Relaxed) } + /// Of a title buffer's copy [`bar_sweep`] may move: whether its card side + /// lies in card memory the CPU maps (`true`) or it has one side + /// (`false`). `None` for the others: windows, what is in place, copies + /// over memory of ours, and those with a card side in device-local + /// memory ([`cards`]). + fn bar_side(&self) -> Option<bool> { + if self.window || self.mapped || self.place.is_some() || self.opened.is_some() { + return None; + } + match &self.card { + None => Some(false), + Some(card) => (card.bar != 0).then_some(true), + } + } + + /// For tests: the copy was read in `n` more submissions ([`Shadow::read_in`]). + #[cfg(test)] + pub(crate) fn read_in_for_test(&self, n: u64) { + let last = self.read_in[1].load(Ordering::Relaxed); + for i in 1..=n { + self.read_by(last.wrapping_add(i)); + } + } + + /// For tests: shaders were declared to write the copy. + #[cfg(test)] + pub(crate) fn written_for_test(&self) { + self.written.store(true, Ordering::Relaxed); + } + + /// For tests: put out of the tables for title memory in place while + /// something still held it ([`in_place_switch`]). + #[cfg(test)] + pub(crate) fn switched_for_test(&self) -> bool { + self.switched.load(Ordering::Relaxed) + } + /// `bytes` were put into title memory at `address`, and the submission /// being prepared copies the same to the copy at that copy's place in its /// list: the reference (the CPU's side of a copy in the card's memory, the @@ -5359,20 +7217,28 @@ impl Shadow { } let bytes = &bytes[self.start as usize + from - address..][..to - from]; let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner()); - if self.card.is_some() { + if self.sourced() { + // The CPU's side is the title memory they were put into + // ([`from_title`]): written again they could undo a write of the + // title's made since. + } else if self.card.is_some() { // SAFETY: inside the mapping of the CPU's side, in a range no // refresh writes; the lock keeps the landing out. - unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), self.data.add(from), bytes.len()) }; + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), self.data().add(from), bytes.len()) }; } else if let Some(snapshot) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { - // SAFETY: the snapshot's allocation holds the copy's length. - unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), snapshot.as_mut_ptr().add(from), bytes.len()) }; + // Where no stretch is, nothing was declared since the snapshot + // was made: a range declared later takes its bytes from the copy. + for (at, held, n) in snapshot.spans(from, to) { + // SAFETY: a stretch's part, `n` bytes from `held`. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr().add(at - from), held as *mut u8, n) }; + } } self.changed(from, to); } /// Of a copy in the card's memory: where its CPU side is. pub(crate) fn card_data(&self) -> *const u8 { - self.data + self.data() } /// Diagnostics: of a copy in the card's memory, what its CPU side holds @@ -5384,7 +7250,7 @@ impl Shadow { } // SAFETY: inside the mapping; the caller holds the submission lock, // under which it is written but for what is being landed. - unsafe { std::slice::from_raw_parts(self.data.add(at).cast_const(), to - at) }.to_vec() + unsafe { std::slice::from_raw_parts(self.data().add(at).cast_const(), to - at) }.to_vec() } /// Diagnostics: the offsets whose bytes have not gone to the card's side @@ -5400,10 +7266,11 @@ impl Shadow { /// Of a copy in the card's memory: the CPU's side (PC memory), the /// card side's bytes from before if made yet, and their size. - pub(crate) fn card_sides(&self) -> Option<(&ID3D12Resource, Option<ID3D12Resource>, u64)> { + pub(crate) fn card_sides(&self) -> Option<(ID3D12Resource, Option<ID3D12Resource>, u64)> { let card = self.card.as_ref()?; let before = card.before.lock().unwrap_or_else(|e| e.into_inner()).clone(); - Some((&card.staging, before, card.size)) + let staging = card.staging.read().unwrap_or_else(|e| e.into_inner()).clone(); + Some((staging, before, card.size)) } /// Shader writes are declared for a copy in the card's memory: makes @@ -5524,7 +7391,7 @@ impl Shadow { } // SAFETY: inside the mapping (checked above); only the submitting // thread writes it. - let old = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) }; + let old = unsafe { std::slice::from_raw_parts_mut(self.data().add(at), gpu.len()) }; let Some(first) = first_difference(gpu, old) else { return 0; }; @@ -5592,7 +7459,7 @@ impl Shadow { // range declared and not done with, which no refresh writes; what // does write it (the title's bytes put in under shader writes) // holds the lock held here. - let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) }; + let held = unsafe { std::slice::from_raw_parts_mut(self.data().add(at), gpu.len()) }; let Some(first) = first_difference(gpu, held) else { return 0; }; @@ -5628,22 +7495,99 @@ impl Shadow { let none = || unsafe { std::mem::transmute::<usize, ID3D12Resource>(8) }; let mut shadow = Shadow::new(none(), data, 0, start, len); if card { - shadow.card = Some(Card { - staging: none(), - before: Mutex::default(), - dirty: Mutex::default(), - sent: Mutex::default(), - touched: Default::default(), - has_dirty: Default::default(), - has_sent: Default::default(), - size: len.next_multiple_of(PIECE as u64), - }); + shadow.card = Some(Card::new(none(), 0, len.next_multiple_of(PIECE as u64))); } let shadow = Arc::new(shadow); std::mem::forget(shadow.clone()); shadow } + /// On the host's card: a copy in the card's memory of title memory + /// `[start, start + len)`, made as `lookup` makes one for a big title + /// buffer (a CPU side in the PC's memory, a buffer in the card's) and + /// counted with them, whatever the card's limits say. + pub(crate) fn carded_for_test(start: u64, len: u64) -> Option<Arc<Shadow>> { + let host = host()?; + if !host.card_ready() { + return None; + } + let size = len.next_multiple_of(PIECE as u64); + let (staging, data) = host.shared_buffer(size)?; + let buffer = host.uav_buffer(size)?; + CARD_BYTES[0].fetch_add(size, Ordering::Relaxed); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.card = Some(Card::new(staging, 0, size)); + let shadow = Arc::new(shadow); + note_carded(&shadow); + Some(shadow) + } + + /// As [`Shadow::carded_for_test`], its CPU side made as `lookup` makes a + /// big title buffer's: the title memory itself where [`from_title`] asks + /// for it (on this thread: [`TEST_FROM_TITLE`]) and the host opens it, + /// else a buffer of its own. + pub(crate) fn from_title_for_test(start: u64, len: u64) -> Option<Arc<Shadow>> { + let host = host()?; + if !host.card_ready() { + return None; + } + let size = len.next_multiple_of(PIECE as u64); + let buffer = host.uav_buffer(size)?; + let (staging, data) = match source_side(start, len, size) { + Some(side) => (side, start as *mut u8), + None => host.shared_buffer(size)?, + }; + CARD_BYTES[0].fetch_add(size, Ordering::Relaxed); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.card = Some(Card::new(staging, 0, size)); + let shadow = Arc::new(shadow); + note_carded(&shadow); + Some(shadow) + } + + /// Bytes refreshes copied from title memory into the CPU's side + /// (`Card::taken`). + pub(crate) fn taken_for_test(&self) -> u64 { + self.card.as_ref().map_or(0, |c| c.taken.load(Ordering::Relaxed)) + } + + /// As [`Shadow::carded_for_test`], the card side in card memory the CPU + /// maps, as `lookup` makes one for a small title buffer with + /// `LEONIDA_BAR_BUFFERS_MB` ([`bar_buffers_most`]), counted with those, + /// whatever that number says. `None` where there is no such memory. + pub(crate) fn barred_for_test(start: u64, len: u64) -> Option<Arc<Shadow>> { + let host = host()?; + if !host.card_ready() { + return None; + } + let size = len.next_multiple_of(PIECE as u64); + let (staging, data) = host.shared_buffer(size)?; + let (buffer, bar) = host.mapped_card_buffer(size, true)?; + BAR_BYTES.fetch_add(size, Ordering::Relaxed); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.card = Some(Card::new(staging, bar as usize, size)); + let shadow = Arc::new(shadow); + note_carded(&shadow); + Some(shadow) + } + + /// [`BAR_BYTES`], for tests. + pub(crate) fn bar_bytes_for_test() -> u64 { + BAR_BYTES.load(Ordering::Relaxed) + } + + /// The refresh of title memory `[from, to)` into the copy, as a + /// submission's would do it ([`Shadow::copy`]). + pub(crate) fn refresh_for_test(&self, from: usize, to: usize) { + self.copy(from, to); + } + /// What shaders wrote goes into title memory ([`put_changed`]). pub(crate) fn put(at: usize, title: &[u8], merged: &[u8]) { put_changed(at, title, merged); @@ -5669,6 +7613,19 @@ impl Shadow { ranges } + /// `ranges` noted as sent up with `number`, as [`card_dirty`] notes + /// them, after the notes of sends up to `merged` went; with no queue + /// and no dirty range (an unbacked copy must not reach a real send). + pub(crate) fn sent_for_test(&self, number: u64, ranges: Vec<(usize, usize)>, merged: u64) { + let card = self.card.as_ref().unwrap(); + let mut sent = card.sent.lock().unwrap(); + sent.forget(merged); + if !ranges.is_empty() { + sent.note(number, ranges); + } + card.has_sent.store(!sent.is_empty(), Ordering::Release); + } + /// What is to go up to the card, taken. pub(crate) fn take_dirty(&self) -> Vec<(usize, usize)> { let card = self.card.as_ref().unwrap(); @@ -5716,7 +7673,7 @@ impl Shadow { // Where title memory is not mapped the CPU's side keeps what // the card wrote, as before. let merged = - unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes, self) }; + unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data().add(lo), &parts, true, notes, self) }; self.walls_merged(hi - lo, merged as usize); if merged > 0 { self.note_landing(lo, hi); @@ -5739,17 +7696,17 @@ impl Shadow { crate::land::spent(crate::land::stat::LOCK, waiting); // The snapshot's memory stays where it is until the range is done // with (`copy_back_done`), which comes after this. - let Some(held) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut().map(Vec::as_mut_ptr) else { + // (A piece is in one stretch of the snapshot.) + let Some(held) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut().and_then(|s| s.at(at, n)) else { return 0; }; // SAFETY: inside the copy's mapping (checked above), which only the - // card writes there, and inside the snapshot's allocation, which - // holds the copy's length (`writing`): these offsets are in a range - // declared and not done with, whose bytes it holds, and the lock - // keeps out what else writes them. Title memory that is not there - // is looked at again when the next flight that declared the range - // lands. - unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes, self) } + // card writes there, and inside a stretch of the snapshot + // (`writing`): these offsets are in a range declared and not done + // with, whose bytes it holds, and the lock keeps out what else + // writes them. Title memory that is not there is looked at again + // when the next flight that declared the range lands. + unsafe { crate::land::piece(self.start as usize + at, self.data().add(at), held, &[(0, n)], false, notes, self) } } /// What shaders wrote in 64 KiB block `block` (of title memory) of this @@ -5782,7 +7739,6 @@ impl Shadow { #[cfg(test)] mod land_tests { use super::{Card, PIECE, Shadow}; - use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; /// A copy in the card's memory of title memory at `title` (its card side @@ -5792,16 +7748,7 @@ mod land_tests { // SAFETY: the mapping, `len` bytes. unsafe { std::ptr::write_bytes(data, 0, len) }; let mut shadow = Shadow::new(buffer.clone(), data, 0, title as u64, len as u64); - shadow.card = Some(Card { - staging: buffer, - before: Mutex::default(), - dirty: Mutex::default(), - sent: Mutex::default(), - touched: Default::default(), - has_dirty: Default::default(), - has_sent: Default::default(), - size: len as u64, - }); + shadow.card = Some(Card::new(buffer, 0, len as u64)); Some(shadow) } @@ -5872,7 +7819,7 @@ mod land_tests { for (shadow, at) in [(&one, a), (&many, b)] { crate::watch::writing(at, LEN); bytes(at).copy_from_slice(&title); - bytes(shadow.data as usize).copy_from_slice(&held); + bytes(shadow.data() as usize).copy_from_slice(&held); let card = shadow.card.as_ref().expect("made with one"); *card.dirty.lock().unwrap() = dirty.clone(); card.has_dirty.store(!dirty.is_empty(), Ordering::Release); @@ -5892,7 +7839,7 @@ mod land_tests { unsafe { many.land_card(&addressed, after, &mut notes) }; notes.flush(); assert!(bytes(a) == bytes(b), "title memory, round {round}"); - assert!(bytes(one.data as usize) == bytes(many.data as usize), "the CPU's side, round {round}"); + assert!(bytes(one.data() as usize) == bytes(many.data() as usize), "the CPU's side, round {round}"); } } } @@ -5911,7 +7858,7 @@ mod land_tests { let Some(shadow) = copy_of(title, LEN) else { return; // no host GPU }; - shadow.pending.lock().unwrap().push((title, title + LEN)); + shadow.pending.lock().unwrap().insert((title, title + LEN)); shadow.has_pending.store(true, Ordering::Release); // SAFETY: committed, aligned; touched as atomics or by the landing's // stores of whole dwords. @@ -5973,6 +7920,12 @@ mod land_tests { struct Entry { end: u64, shadow: Option<Arc<Shadow>>, + /// Memory of ours, not the title's ([`register_ours`]). + ours: bool, + /// With [`bar_buffers_most`]: where the next copy made of the buffer has + /// its card side ([`bar_sweep`]): [`BAR_NOT_YET`], [`BAR_WANTED`] or + /// [`BAR_NEVER`]. + bar: u8, } /// Title buffers by (start address, resource), with their copy once made. @@ -6149,6 +8102,23 @@ pub(crate) fn register(resource: usize, start: u64, len: u64) { Entry { end: start + len, shadow: None, + ours: false, + bar: BAR_NOT_YET, + }, + ); +} + +/// As [`register`], for memory of ours that the title's shaders read as a +/// title buffer (`crate::upload`'s arenas): with `crate::inplace::ours` its +/// copy is the memory itself in place. +pub(crate) fn register_ours(resource: usize, start: u64, len: u64) { + buffers().insert( + (start, resource), + Entry { + end: start + len, + shadow: None, + ours: true, + bar: BAR_NOT_YET, }, ); } @@ -6173,8 +8143,10 @@ pub(crate) fn extent(address: u64) -> Option<(u64, u64)> { /// Title memory `[at, at + len)` is about to show something else or be /// given up: what is in place there (`crate::inplace`) is taken out of the /// tables, so that the next ask makes a copy or opens the memory anew, and -/// goes when no list and no slot holds it any more. Returns how many. -pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 { +/// goes when no list and no slot holds it any more. Returns the buffers +/// taken out (for the descriptor slots that view them to let go of them: +/// `crate::inplace::title_memory_freeing`). +pub(crate) fn in_place_let_go(at: u64, len: u64) -> Vec<ID3D12Resource> { let end = at.saturating_add(len); let mut gone: Vec<Arc<Shadow>> = Vec::new(); { @@ -6195,11 +8167,254 @@ pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 { } } } - let n = gone.len() as u64; + let buffers = gone.iter().map(|shadow| shadow.buffer.clone()).collect(); + // Copies whose CPU side is that memory ([`from_title`]): a side of their + // own before the next submission ([`sources_going`]). They stay in the + // tables: the card side holds the buffer's bytes still, and the + // descriptor slots that show it are not stale. (A heap stands over + // whole 64 KiB pages.) Looked for after the tables' lock: a copy made + // over a section while the title mapped other pages there is in the + // index once that lock is free (`crate::inplace::place_source`). + if sourced_any() { + let going: Vec<Arc<Shadow>> = carded_over(at.saturating_sub(PIECE as u64) as usize, end as usize) + .into_iter() + .filter(|s| s.sourced() && s.start < end && s.start + s.len.next_multiple_of(PIECE as u64) > at) + .collect(); + if !going.is_empty() { + SOURCES_GOING.lock().unwrap_or_else(|e| e.into_inner()).extend(going); + SOURCES_WAITING.store(true, Ordering::Release); + } + } for shadow in gone { crate::host::retire(shadow); } - n + buffers +} + +/// The buffers of what is in place (`crate::inplace`) that the tables still +/// show over title memory `[at, end)`, found as [`in_place_let_go`] finds +/// them: raw interface pointers. A buffer they show is still the title's +/// memory to the runtime, and the slots that view it are not stale. +pub(crate) fn in_place_shown(at: u64, end: u64) -> Vec<usize> { + use windows::core::Interface; + let mut shown: Vec<usize> = LOOSE + .read() + .unwrap_or_else(|e| e.into_inner()) + .range((at.saturating_sub(WINDOW), 0)..(end, 0)) + .filter(|(key, shadow)| shadow.place.is_some() && key.0 + key.1 > at) + .map(|(_, shadow)| shadow.buffer.as_raw() as usize) + .collect(); + let map = buffers_read(); + for (_, entry) in map.range(..(end, 0)).rev().take(256) { + if entry.end > at + && let Some(shadow) = entry.shadow.as_ref().filter(|s| s.place.is_some()) + { + shown.push(shadow.buffer.as_raw() as usize); + } + } + shown +} + +/// `placed`, title memory `[start, start + len)` the opener opened in place +/// (`crate::inplace::asynchronous`), put in the tables in the place of the +/// copy made of that memory meanwhile (the window keyed so, or the title +/// buffer of that start and length), if the copy can go now without losing +/// anything: +/// +/// - a plain copy in the PC's memory: no card side (its bytes and its sends +/// are the card's), not in card memory the CPU maps, not memory of ours; +/// - shaders were never declared to write it ([`Shadow::gpu_writes`]): it +/// holds nothing title memory lacks, neither a write in flight to copy back +/// nor one kept out of title memory (`LEONIDA_WC_NO_BACK`, copy-back +/// elision); the title's own writes are in title memory either way; +/// - no submission's shaders may be writing it still, to be copied back, +/// and no landing of what they wrote waits for a refresh to look at it +/// (`pending`, `landing`: both follow from the above, asked all the same); +/// - no descriptor slot views its buffer (one COM reference: a slot would go +/// on reading a copy nobody brings up to date), and the directory of +/// memory by address has not numbered it ([`Shadow::numbered`]: it keeps +/// the copy for good and shows shaders that one); +/// - with `LEONIDA_INPLACE_SWITCH_HELD=0`, nothing but the table holds it +/// either (a strong count of 1, taken under the table's lock after the +/// count of changes went up, as [`let_go_idle`] does). +/// +/// Lists may still hold the copy (`crate::inplace::switch_held`): those +/// recorded and not yet reset, those in `runs` of the submission whose +/// sweep this is, a thread it was just handed out to ([`found`]). A copy read +/// every frame is always held so, and was never switched before. Each keeps +/// its own `Arc`: a list not yet sent brings the copy up to date from title +/// memory at its submission (its `Refresh` steps), one in flight reads what +/// was copied into it then, and the copy goes once the last of them lets +/// go of it ([`crate::host::retire`] keeps it for the submissions running). +/// Lists recorded from now on are given the title memory in place. Title +/// writes are in title memory either way. +/// +/// shortcut: for as long as lists hold the copy, two views of the same bytes +/// stand (as for a title buffer inside a window, which is not told of the +/// card's writes either): were shaders declared to write either while the +/// other is read, a list submitted after the writer could read the bytes +/// from before, until the copy-back. Shaders were never declared to write +/// this memory before; such writes are counted on the say line +/// (`crate::inplace::written_across_switch`). +/// +/// The copy goes once the submissions running have finished +/// ([`crate::host::retire`]). `Err` gives `placed` back. +pub(crate) fn in_place_switch(start: u64, len: u64, window: bool, placed: crate::inplace::Placed) -> Result<(), crate::inplace::Placed> { + let held = crate::inplace::switch_held(); + let free = |shadow: &Arc<Shadow>| { + shadow.place.is_none() + && shadow.card.is_none() + && !shadow.mapped + && shadow.opened.is_none() + && !shadow.written.load(Ordering::Relaxed) + && !shadow.has_pending.load(Ordering::Acquire) + && !shadow.landing.load(Ordering::Acquire) + && !shadow.numbered.load(Ordering::Acquire) + && (held || Arc::strong_count(shadow) == 1) + && crate::host::references(&shadow.buffer) == 1 + }; + // The copy, if anything but the table holds it (under the table's lock). + let still_held = |old: &Arc<Shadow>| { + (Arc::strong_count(old) > 1).then(|| { + old.switched.store(true, Ordering::Relaxed); + Arc::downgrade(old) + }) + }; + let placed_over = |placed: crate::inplace::Placed, old: Option<std::sync::Weak<Shadow>>, window: bool| { + let new = Shadow::placed(placed, start, len, window); + if let Some(old) = old { + let _ = new.replaced.set(old); + } + Arc::new(new) + }; + let (old, new) = if window { + let mut map = loose_taking(); + let Some(old) = map.get(&(start, len)).filter(|old| old.window && free(old)) else { + return Err(placed); + }; + let new = placed_over(placed, still_held(old), true); + new.used.store(old.used.load(Ordering::Relaxed), Ordering::Relaxed); + let old = map.insert((start, len), new.clone()); + (old, new) + } else { + let mut map = buffers(); + let Some(entry) = map + .range_mut((start, 0)..=(start, usize::MAX)) + .map(|(_, entry)| entry) + .find(|entry| entry.end == start + len && !entry.ours && entry.shadow.as_ref().is_some_and(|old| !old.window && free(old))) + else { + return Err(placed); + }; + let new = placed_over(placed, entry.shadow.as_ref().and_then(still_held), false); + let old = entry.shadow.replace(new.clone()); + (old, new) + }; + // (Not under the tables' locks.) + elide::made(&new); + if let Some(old) = old { + crate::host::retire(old); + } + Ok(()) +} + +/// The copies the tables have over title memory `[at, end)` that could be +/// title memory in place instead (`crate::inplace::again`), as (start, +/// bytes, window): plain copies in the PC's memory that shaders were never +/// declared to write (those [`in_place_switch`] could put the title memory +/// in the place of), windows and title buffers (not memory of ours, nor a +/// big one the card's memory is for by [`buffer_ways`]), found as +/// [`in_place_let_go`] finds what is in place. +pub(crate) fn copies_over(at: u64, end: u64) -> Vec<(u64, u64, bool)> { + let plain = |shadow: &Shadow| { + shadow.place.is_none() && shadow.card.is_none() && !shadow.mapped && shadow.opened.is_none() && !shadow.written.load(Ordering::Relaxed) + }; + let mut copies: Vec<(u64, u64, bool)> = LOOSE + .read() + .unwrap_or_else(|e| e.into_inner()) + .range((at.saturating_sub(WINDOW), 0)..(end, 0)) + .filter(|(key, shadow)| key.0 + key.1 > at && shadow.window && plain(shadow)) + .map(|(key, _)| (key.0, key.1, true)) + .collect(); + let map = buffers_read(); + for (key, entry) in map.range(..(end, 0)).rev().take(256) { + let size = (entry.end - key.0).next_multiple_of(1 << 16); + let big = cards() && (size >= card_limits().0 || card_all()); + if entry.end > at + && !entry.ours + && entry.shadow.as_ref().is_some_and(|shadow| !shadow.window && plain(shadow)) + && buffer_ways(crate::inplace::last(), big).contains(&Way::InPlace) + { + copies.push((key.0, entry.end - key.0, false)); + } + } + copies +} + +/// For the tests: a copy of title memory `[start, start + len)` in the +/// tables as a window, its buffer `buffer` (no CPU side: nothing is copied +/// into it), as [`loose`] makes one. +#[cfg(test)] +pub(crate) fn copy_window(buffer: ID3D12Resource, start: u64, len: u64) -> Arc<Shadow> { + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let mut shadow = Shadow::new(buffer, std::ptr::null_mut(), gpu, start, len); + shadow.window = true; + let shadow = Arc::new(shadow); + loose_taking().insert((start, len), shadow.clone()); + shadow +} + +/// For the tests: the window over `[start, start + len)` in the tables. +#[cfg(test)] +pub(crate) fn window_there(start: u64, len: u64) -> Option<Arc<Shadow>> { + LOOSE.read().unwrap_or_else(|e| e.into_inner()).get(&(start, len)).cloned() +} + +/// For the tests: `placed` as a window over `[start, start + len)` in the +/// tables, counted as `crate::inplace::place_for` counts what it gives. +#[cfg(test)] +pub(crate) fn in_place_window(placed: crate::inplace::Placed, start: u64, len: u64) -> Arc<Shadow> { + crate::inplace::counted(true, len); + let shadow = Arc::new(Shadow::placed(placed, start, len, true)); + loose_taking().insert((start, len), shadow.clone()); + shadow +} + +/// For the tests: whether the tables have a window over `[start, start + len)`. +#[cfg(test)] +pub(crate) fn in_place_window_there(start: u64, len: u64) -> bool { + LOOSE.read().unwrap_or_else(|e| e.into_inner()).contains_key(&(start, len)) +} + +/// For the tests: the window over `[start, start + len)` taken out of the +/// tables (memory the test gives back). +#[cfg(test)] +pub(crate) fn window_gone(start: u64, len: u64) -> Option<Arc<Shadow>> { + loose_taking().remove(&(start, len)) +} + +/// For the tests: the window [`loose`] makes for an ask of title memory +/// `[start, start + len)` (on the window grid), with room for windows in the +/// card's memory (`LEONIDA_CARD_WINDOWS_MB`), nothing in place, and +/// [`from_title`] as `from_title` says, on this thread. `None`, and nothing +/// left in the tables, if it got no side in the card's memory. The caller +/// takes it out of the tables when done ([`window_gone`]). +#[cfg(test)] +pub(crate) fn card_window_for_test(start: u64, len: u64, from_title: bool) -> Option<Arc<Shadow>> { + TEST_WINDOW_CARD_MOST.set(Some(len.max(64 << 20))); + TEST_FROM_TITLE.set(Some(from_title)); + crate::inplace::TEST_LEVEL.set(Some(0)); + let window = loose(start, start + len, false, false); + crate::inplace::TEST_LEVEL.set(None); + TEST_FROM_TITLE.set(None); + TEST_WINDOW_CARD_MOST.set(None); + let window = window?; + if window.window && window.card.is_some() && window.span() == (start, len) { + return Some(window); + } + let span = window.span(); + drop(window_gone(span.0, span.1)); + None } /// For the in-place census (`crate::inplace`): the title buffers (start, @@ -6301,7 +8516,7 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> { // In place, if asked for and the memory can be opened // (`crate::inplace::place_for`): the buffer is the title's own // memory. Not the big ones `cards` puts in the card's memory: those - // are read too often to stay in the PC's. + // are read too often to stay in the PC's ([`buffer_ways`]). let big = cards() && (size >= card_limits().0 || card_all()); // Renderer port 1 (`crate::port`, `LEONIDA_PORT_CONSTANTS=1`): the // title's 32-bit graphics heap in place, big or not. @@ -6309,32 +8524,93 @@ fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> { entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); return entry.shadow.clone(); } - if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) { + // Memory of ours (an upload arena) in place, big or not + // (`crate::inplace::ours`): the card reads it once, as a host upload + // heap is read. + if entry.ours + && let Some(placed) = crate::inplace::place_ours(key.0, len) + { entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); return entry.shadow.clone(); } - let (buffer, data) = host()?.shared_buffer(size)?; + let mut on_card = None; + for &way in buffer_ways(crate::inplace::last(), big) { + match way { + Way::InPlace => { + if let Some(placed) = crate::inplace::place_for(key.0, len, false) { + entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); + return entry.shadow.clone(); + } + } + Way::Card => { + let barred = (entry.bar == BAR_WANTED).then(|| bar_for(size)).flatten(); + if entry.bar == BAR_WANTED && barred.is_none() { + // (No room after all: asked again once this copy is read as much.) + entry.bar = BAR_NOT_YET; + } + on_card = match barred { + Some((mapped, at)) => Some((mapped, at as usize)), + None => card_for(size).map(|on_card| (on_card, 0)), + }; + if on_card.is_some() { + break; + } + } + Way::Mapped | Way::Copy => break, + } + } + // A big one's CPU side may be the title memory itself + // ([`from_title`]); not memory of ours, which recording threads write. + // Opened under the tables' lock, once per buffer: the opening locks + // the pages (70 ms for 256 MiB never touched, `crate::inplace`), and + // every `lookup` waits for it meanwhile, as for `place_for`. Not + // opened outside it: a let-go of the memory takes this lock before it + // looks for such copies in the index ([`in_place_let_go`]), and so + // finds a copy made over it, which a let-go between an opening + // outside the lock and the copy's note would miss, its heap kept and + // the title's free waiting on it. + let sourced = match on_card { + Some((_, 0)) if !entry.ours => source_side(key.0, len, size).map(|side| (side, key.0 as *mut u8)), + _ => None, + }; + let Some((buffer, data)) = sourced.or_else(|| host().and_then(|host| host.shared_buffer(size))) else { + // (Counted by `card_for`, or by `bar_for` for a side in card + // memory the CPU maps; the buffer goes with `on_card`.) + match on_card { + Some((_, 0)) => { + CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); + } + Some(_) => { + BAR_BYTES.fetch_sub(size, Ordering::Relaxed); + } + None => {} + } + return None; + }; crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0)); // A big one, with `cards`: shaders get a buffer in the card's own - // memory, and the one just made is the CPU's side. - let (buffer, card) = match card_for(size) { - Some(on_card) => { + // memory, and the one just made is the CPU's side. A small one, with + // `LEONIDA_BAR_BUFFERS_MB`, once `bar_sweep` found its copy read in + // many submissions and never written: the same, its card side in + // card memory the CPU maps and writes (`bar_buffers_most`), at offset + // `bar` of it (0: a buffer of its own in the card's memory). + let (buffer, card) = match on_card { + Some((on_card, bar)) => { crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", key.0)); - tracing::info!( - start = format_args!("{:#x}", key.0), - len, - "a buffer's host copy is in the card's memory" - ); - let card = Card { - staging: buffer, - before: Mutex::default(), - dirty: Mutex::default(), - sent: Mutex::default(), - touched: Default::default(), - has_dirty: Default::default(), - has_sent: Default::default(), - size, - }; + if bar != 0 { + tracing::debug!( + start = format_args!("{:#x}", key.0), + len, + "a buffer's host copy is in card memory the CPU writes (LEONIDA_BAR_BUFFERS_MB)" + ); + } else { + tracing::info!( + start = format_args!("{:#x}", key.0), + len, + "a buffer's host copy is in the card's memory" + ); + } + let card = Card::new(buffer, bar, size); (on_card, Some(card)) } None => (buffer, None), @@ -6528,6 +8804,25 @@ pub(crate) fn small_buffer_in(address: u64, len: u64, most: u64) -> bool { /// the only place that has it. The CPU's side holds the bytes as they were /// last taken, and only dwords that changed since go up. pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> { + by_address_with(start, len, false) +} + +/// [`by_address`] of memory of ours that one writer changes, and that writer +/// resends what it changed ([`Shadow::resend`]): an arena of +/// [`crate::memory`]'s, which takes only the dwords title memory changed. +/// The memory is opened as a heap of the host's and is itself the CPU's +/// side, so its bytes are in the PC's memory once. That side was a buffer +/// of the same size with the same bytes, which every refresh compared with +/// the arena: 64 MiB more commit per arena, and with the structure builder +/// (`LEONIDA_BVH_BUILDER=1`) up to 48 arenas. Its caller resends all of it +/// once it keeps the copy, as a new copy's first refresh sends it. If the +/// host does not open the memory, the copy is made as [`by_address`] makes +/// it. +pub(crate) fn by_address_opened(start: u64, len: u64) -> Option<Arc<Shadow>> { + by_address_with(start, len, true) +} + +fn by_address_with(start: u64, len: u64, open: bool) -> Option<Arc<Shadow>> { let host = host()?; if !cards() || !host.card_ready() { return None; @@ -6542,7 +8837,13 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> { mb.unwrap_or(4096) << 20 }); let room = host.video_memory().is_none_or(|[budget, used, ..]| used + len < budget / 100 * 97); - let (staging, data) = host.shared_buffer(len)?; + let (staging, data, opened) = match open.then(|| opened_side(host, start, len)).flatten() { + Some(placed) => (placed.buffer, start as *mut u8, Some(placed.heap)), + None => { + let (staging, data) = host.shared_buffer(len)?; + (staging, data, None) + } + }; let on_card = if room && USED.fetch_add(len, Ordering::Relaxed) + len <= most { host.uav_buffer(len) } else { @@ -6561,22 +8862,41 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> { let mut shadow = Shadow::new(buffer, data, gpu, start, len); shadow.window = true; shadow.changes_only.store(true, Ordering::Relaxed); - shadow.card = Some(Card { - staging, - before: Mutex::default(), - dirty: Mutex::default(), - sent: Mutex::default(), - touched: Default::default(), - has_dirty: Default::default(), - has_sent: Default::default(), - size: len, - }); + shadow.card = Some(Card::new(staging, 0, len)); + if opened.is_some() { + // Nothing asks the write watch about it (`Shadow::asked_ahead`): its + // writer tells. + *shadow.watched.get_mut() = NOT_WATCHED; + shadow.opened = opened; + } let shadow = Arc::new(shadow); note_carded(&shadow); elide::made(&shadow); Some(shadow) } +/// For [`by_address_opened`]: `[start, start + len)` opened as a heap, with +/// a buffer placed over it from its first byte, so that the buffer's offsets +/// are the copy's (the card's side is filled from it at the same offsets). +fn opened_side(host: &crate::host::Host, start: u64, len: u64) -> Option<crate::inplace::Placed> { + let why = match crate::inplace::place_part(&host.device, start, len) { + Ok(placed) if placed.bias == 0 => return Some(placed), + // (Not for an arena: `upload::reserve` gives 64 KiB lines.) + Ok(placed) => format!("it begins {:#x} bytes after a 64 KiB line", placed.bias), + Err(e) => format!("{e:?}"), + }; + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!( + start = format_args!("{start:#x}"), + len, + why = %why, + "memory by address not opened as its copy's CPU side: that side is a buffer of its own, as before" + ); + }); + None +} + /// Copies of title memory outside buffers, by (start, length). static LOOSE: std::sync::RwLock<BTreeMap<(u64, u64), Arc<Shadow>>> = std::sync::RwLock::new(BTreeMap::new()); @@ -6599,6 +8919,42 @@ fn note_ask(shadow: &Shadow, address: u64, end: u64, unsized_ask: bool) { } } +/// What a new window outside buffers or a title buffer's copy is made as. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Way { + /// The title memory itself, opened in place (`crate::inplace::place_for`, + /// which says whether `LEONIDA_INPLACE` asks for it). + InPlace, + /// One buffer in card memory the CPU maps ([`window_mapped_for`]). + Mapped, + /// A side in the card's memory and the CPU's in the PC's ([`window_room_for`], + /// [`card_for`]). + Card, + /// A copy in the PC's memory (with `LEONIDA_WINDOWS_OWN` two of them). + Copy, +} + +/// The ways a new window is tried in, the first that gives one taken; with +/// `last` ([`crate::inplace::last`]) in place only where a copy in the PC's +/// memory alone would be made: that copy is read over the bus as the title +/// memory itself would be, a side in the card's memory is not. +fn window_ways(last: bool) -> &'static [Way] { + if last { &[Way::Mapped, Way::Card, Way::InPlace, Way::Copy] } else { &[Way::InPlace, Way::Mapped, Way::Card, Way::Copy] } +} + +/// The ways a title buffer's copy is tried in; `big`: one `cards` puts in +/// the card's memory. With `last` a big one the card turned down +/// ([`card_for`] gave nothing) is opened in place rather than copied into +/// the PC's memory, where it is read over the bus all the same; before, a +/// big one never was. +fn buffer_ways(last: bool, big: bool) -> &'static [Way] { + match (last, big) { + (true, _) => &[Way::Card, Way::InPlace, Way::Copy], + (false, true) => &[Way::Card, Way::Copy], + (false, false) => &[Way::InPlace, Way::Card, Way::Copy], + } +} + fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Shadow>> { let (cell, _) = window_of(address, end, WINDOW); let named = window_of(address, end, if unsized_ask { WINDOW } else { window() }); @@ -6629,25 +8985,36 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Sha note(shadow); return Some(shadow.clone()); } - // In place, if asked for and the window's memory can be opened: the - // window is the title's own memory, with nothing to copy. - if let Some(placed) = crate::port::place_for(start, len, true).or_else(|| crate::inplace::place_for(start, len, true)) { - let shadow = Arc::new(Shadow::placed(placed, start, len, true)); - note(&shadow); - map.insert((start, len), shadow.clone()); - drop(map); - elide::made(&shadow); - return Some(shadow); + // Renderer port 1 (`crate::port`), then in the order [`window_ways`] + // gives: in place, if asked for and the window's memory can be opened + // (the window is the title's own memory, with nothing to copy); one + // buffer in the card's memory, filled by the CPU through the bus; a side + // in the card's memory; a copy in the PC's. + let mut made = crate::port::place_for(start, len, true).map(|placed| Shadow::placed(placed, start, len, true)); + let mut on_card = None; + for &way in window_ways(crate::inplace::last()) { + if made.is_some() || on_card.is_some() { + break; + } + match way { + Way::InPlace => made = crate::inplace::place_for(start, len, true).map(|placed| Shadow::placed(placed, start, len, true)), + Way::Mapped => { + made = window_mapped_for(len).map(|(buffer, data)| { + crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x} mapped on the card")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.window = true; + shadow.mapped = true; + window_made(1, len); + shadow + }) + } + Way::Card => on_card = window_room_for(len), + Way::Copy => break, + } } - // One buffer in the card's memory, filled by the CPU through the bus. - if let Some((buffer, data)) = window_mapped_for(len) { - crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x} mapped on the card")); - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - let mut shadow = Shadow::new(buffer, data, gpu, start, len); - shadow.window = true; - shadow.mapped = true; - window_made(1, len); + if let Some(shadow) = made { let shadow = Arc::new(shadow); note(&shadow); map.insert((start, len), shadow.clone()); @@ -6655,24 +9022,44 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Sha elide::made(&shadow); return Some(shadow); } - let (buffer, data) = host()?.shared_buffer(len)?; + // With a side in the card's memory, the CPU's may be the title memory + // itself ([`from_title`], [`from_title_windows`]). Opened under the + // table's lock (asks of windows on other threads wait for it each time + // a window is made, again after the idle sweep let it go: a few + // milliseconds at most for 4 MiB, `crate::inplace`'s opening costs), as + // `lookup` opens a big buffer's: [`in_place_let_go`] + // takes this lock before it looks for such copies in the index, so a + // let-go after the opening finds the window, noted before the lock is + // free. (A window of private memory lies in one allocation, the + // title's: the runtime's own memory it reads is registered whole as + // buffers, `register_ours`.) + let sourced = match on_card { + Some(_) if from_title_windows() => source_side(start, len, len).map(|side| (side, start as *mut u8)), + _ => None, + }; + let Some((buffer, data)) = sourced.or_else(|| host().and_then(|host| host.shared_buffer(len))) else { + // (Counted by `window_room_for`; the buffer goes with `on_card`.) + if on_card.is_some() { + WINDOW_CARD_BYTES.fetch_sub(len, Ordering::Relaxed); + } + return None; + }; crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}")); // With room for windows on the card (`window_card_most`): shaders get a - // buffer there, and the one just made is the CPU's side. - let (buffer, card) = match window_card_for(len) { + // buffer there, and the one just made is the CPU's side. Else, with + // `windows_own`, a second side in the PC's memory. + let on_card = match on_card { + Some(on_card) => { + window_made(0, len); + Some(on_card) + } + None => window_own_for(len), + }; + let (buffer, card) = match on_card { Some(on_card) => { crate::host::name(&on_card, || format!("title memory {start:#x}+{len:#x} on the card")); - let card = Card { - staging: buffer, - before: Mutex::default(), - dirty: Mutex::default(), - sent: Mutex::default(), - touched: Default::default(), - has_dirty: Default::default(), - has_sent: Default::default(), - size: len, - }; - // (Counted where it was made: `window_card_for`.) + let card = Card::new(buffer, 0, len); + // (Counted where it was made: above, or `window_own_for`.) (on_card, Some(card)) } None => { @@ -6776,17 +9163,27 @@ pub(crate) fn exact(address: u64, len: u64) -> Option<Arc<Shadow>> { // frame): making a buffer and letting one go are a call into the kernel // each, and were most of what these threads ran. let width = len.next_multiple_of(256); - let spare = { + // The copies let go are dropped here, before the spare list's lock is + // taken; their buffers live on in `let_go` (placed copies have none of + // their own). + let let_go: Vec<(u64, ID3D12Resource, usize)> = gone + .into_iter() + .filter(|shadow| shadow.place.is_none()) + .map(|shadow| (shadow.width(), shadow.buffer.clone(), shadow.data() as usize)) + .collect(); + let (spare, unparked) = { let mut spare = EXACT_SPARE.lock().unwrap_or_else(|e| e.into_inner()); - for shadow in gone.drain(..) { - if spare.len() < SPARE_MOST && shadow.place.is_none() { - spare.push((shadow.width(), shadow.buffer.clone(), shadow.data as usize)); - } - } - spare.iter().position(|(w, ..)| *w == width).map(|i| spare.swap_remove(i)) + let unparked = if let_go.is_empty() { Vec::new() } else { park(&mut spare, let_go, crate::host::coarse_ms()) }; + (spare.iter().position(|(w, ..)| *w == width).map(|i| spare.swap_remove(i)), unparked) }; + // Released after the lock, which the eight threads that translate lists + // queue on: a buffer is up to 64 MiB of committed memory. As idle spares + // and windows do, they go through `retire_resource`. + for buffer in unparked { + crate::host::retire_resource(buffer); + } let (buffer, data) = match spare { - Some((_, buffer, data)) => (buffer, data as *mut u8), + Some((_, buffer, data, _)) => (buffer, data as *mut u8), None => host()?.shared_buffer(width)?, }; crate::host::name(&buffer, || format!("title view {address:#x}+{len:#x}")); @@ -6807,11 +9204,76 @@ pub(crate) fn exact(address: u64, len: u64) -> Option<Arc<Shadow>> { Some(shadow) } -/// Leonida: buffers of copies [`exact`] let go, with their widths and where -/// they are mapped, for its next copies of the same width. -static EXACT_SPARE: Mutex<Vec<(u64, ID3D12Resource, usize)>> = Mutex::new(Vec::new()); -/// At most so many are kept (what comes after goes, as before). +/// Leonida: buffers of copies [`exact`] let go, for its next copies of the +/// same width. +static EXACT_SPARE: Mutex<Vec<Spare<ID3D12Resource>>> = Mutex::new(Vec::new()); +/// A spare buffer: its width, the buffer, where it is mapped, and when it +/// was parked ([`crate::host::coarse_ms`]). +type Spare<B> = (u64, B, usize, u64); +/// At most so many are kept (past that, the oldest goes for a newcomer, +/// [`park`]). const SPARE_MOST: usize = 1024; +/// And at most so many bytes of the PC's memory, each buffer counted in the +/// whole 64 KiB blocks a committed buffer takes. A spare is reused only for +/// a view of the same width, and with the count alone a spare of a width +/// that never came back stayed for the rest of the run: a full list was at +/// least 64 MiB, since no buffer takes less than a block, and could be up +/// to 64 MiB a buffer ([`exact`]'s largest view). +const SPARE_BYTES: u64 = 64 << 20; + +/// Parks the buffers `let_go` (width, buffer, where it is mapped) among +/// `spare` at `now`. Where the spares would then hold more than +/// [`SPARE_MOST`] buffers or [`SPARE_BYTES`], the spare parked longest ago +/// makes room: the widths the title's ring repeats are taken and parked +/// again all the time, so the oldest is of a width that did not come back. +/// Refusing the newcomer instead would let those keep a width that does +/// recur out of the list until they aged out. Returns the buffers that go, +/// for the caller to release once the lock is released. +fn park<B>(spare: &mut Vec<Spare<B>>, let_go: impl IntoIterator<Item = (u64, B, usize)>, now: u64) -> Vec<B> { + let committed = |width: u64| width.next_multiple_of(64 << 10); + let mut bytes: u64 = spare.iter().map(|&(width, ..)| committed(width)).sum(); + let mut gone = Vec::new(); + for (width, buffer, data) in let_go { + // (Larger than the list may hold at all; [`exact`]'s views are not.) + if committed(width) > SPARE_BYTES { + gone.push(buffer); + continue; + } + while spare.len() >= SPARE_MOST || bytes + committed(width) > SPARE_BYTES { + let Some(oldest) = spare.iter().enumerate().min_by_key(|(_, parked)| parked.3).map(|(i, _)| i) else { + break; + }; + let (old, buffer, ..) = spare.swap_remove(oldest); + bytes -= committed(old); + gone.push(buffer); + } + bytes += committed(width); + spare.push((width, buffer, data, now)); + } + gone +} + +/// Takes out of `spare` the buffers parked `idle_ms` or more before `now`. +fn idle_spares<B>(spare: &mut Vec<Spare<B>>, now: u64, idle_ms: u64) -> Vec<B> { + spare + .extract_if(.., |&mut (.., parked)| now.saturating_sub(parked) >= idle_ms) + .map(|(_, buffer, ..)| buffer) + .collect() +} + +/// Lets go of the spare buffers of [`exact`] that no copy took for +/// `idle_ms` ([`crate::host::ram_idle_ms`]). The title's ring gives the same +/// few widths every frame, so their spares are taken again long before +/// that; one that stays so long is of a width that did not come back. As +/// idle windows of title memory do, they go through +/// [`crate::host::retire_resource`]. +fn let_go_idle_spares(idle_ms: u64) { + let now = crate::host::coarse_ms(); + let gone = idle_spares(&mut EXACT_SPARE.lock().unwrap_or_else(|e| e.into_inner()), now, idle_ms); + for buffer in gone { + crate::host::retire_resource(buffer); + } +} /// Copies of single views' bytes made since the start. pub(crate) static OWN_MADE: AtomicU64 = AtomicU64::new(0); @@ -6833,6 +9295,61 @@ pub(crate) fn exact_line(frames: f64) { ); } +#[cfg(test)] +mod exact_spare_tests { + use super::{SPARE_MOST, Spare, idle_spares, park}; + + /// The memory a committed buffer of `width` bytes takes: whole 64 KiB + /// blocks. + fn committed(width: u64) -> u64 { + width.next_multiple_of(64 << 10) + } + + /// Spare buffers of views whose widths never come back hold at most + /// 64 MiB of the PC's memory, the oldest giving way to newcomers, and go + /// once they have been parked for the idle time: with the count alone + /// the list kept 1,024 of them (up to 64 MiB each) for the rest of the + /// run. + #[test] + fn spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle() { + const IDLE_MS: u64 = 10_000; + let mut spare: Vec<Spare<u32>> = Vec::new(); + let mut went = 0; + // 3,000 views of as many widths (256 bytes to 750 KiB), let go 30 + // at a sweep, one sweep every 0.1 s. + for sweep in 0..100u32 { + let let_go = (0..30).map(|i| { + let n = sweep * 30 + i; + (u64::from(n + 1) * 256, n, 0usize) + }); + went += park(&mut spare, let_go, u64::from(sweep) * 100).len(); + } + let bytes: u64 = spare.iter().map(|&(width, ..)| committed(width)).sum(); + assert!(spare.len() <= SPARE_MOST); + assert!(bytes <= 64 << 20, "{} spares hold {} MiB", spare.len(), bytes >> 20); + assert!(!spare.is_empty(), "spares are still kept"); + // Each buffer is either parked or handed back to be released. + assert_eq!(went + spare.len(), 3_000); + // Those that gave way were the oldest: the last sweep's are all kept. + assert_eq!(spare.iter().filter(|&&(.., at)| at == 9_900).count(), 30); + // A width that comes again still finds room in the full list: the + // oldest spare goes for it. + let width = 640 << 10; + assert!(bytes + committed(width) > 64 << 20, "the list has no room for it"); + let gone = park(&mut spare, [(width, 9_999, 0)], 10_000); + assert!(!gone.is_empty()); + assert!(spare.iter().any(|&(w, id, ..)| w == width && id == 9_999), "a newcomer is parked in a full list"); + // The idle time after the last sweep: all it and those before it + // parked goes, the newcomer stays. + let gone = idle_spares(&mut spare, 9_900 + IDLE_MS, IDLE_MS); + assert!(!gone.is_empty()); + assert_eq!(spare.iter().map(|&(_, id, ..)| id).collect::<Vec<_>>(), [9_999]); + // And at the idle time after it, none is left. + idle_spares(&mut spare, 10_000 + IDLE_MS, IDLE_MS); + assert!(spare.is_empty(), "{} spares left", spare.len()); + } +} + #[cfg(test)] mod window_tests { use super::{ @@ -7558,3 +10075,390 @@ mod window_memory_tests { assert_eq!(memory.get(0x1000, 8, (2, 1)).as_deref(), Some(&2)); } } + +#[cfg(test)] +pub(crate) mod in_place_tests { + use super::{Shadow, Way, buffer_ways, window_ways}; + use std::ffi::c_void; + use windows::Win32::Graphics::Direct3D12::ID3D12Device13; + use windows::core::Interface; + use windows_sys::Win32::System::Memory as mem; + + /// With `LEONIDA_INPLACE_LAST` (on), in place comes after a side in the + /// card's memory and card memory the CPU maps, and before a copy in the + /// PC's memory alone, for windows and title buffers, big or not; off, the + /// order is the one before. + #[test] + fn in_place_takes_the_place_of_a_copy_kept_in_the_pcs_memory_alone() { + let at = |ways: &[Way], way: Way| ways.iter().position(|&w| w == way).unwrap_or_else(|| panic!("{way:?} not in {ways:?}")); + for ways in [window_ways(true), buffer_ways(true, true), buffer_ways(true, false)] { + assert_eq!(ways.last(), Some(&Way::Copy), "{ways:?}"); + assert!(at(ways, Way::InPlace) > at(ways, Way::Card), "{ways:?}"); + } + assert!(at(window_ways(true), Way::InPlace) > at(window_ways(true), Way::Mapped)); + // `LEONIDA_INPLACE_LAST=0`. + assert_eq!(window_ways(false), [Way::InPlace, Way::Mapped, Way::Card, Way::Copy]); + assert_eq!(buffer_ways(false, true), [Way::Card, Way::Copy]); + assert_eq!(buffer_ways(false, false), [Way::InPlace, Way::Card, Way::Copy]); + } + + /// `LEONIDA_INPLACE` and the card's room for this thread's asks, as a + /// test sets them; as they were once dropped. + pub(crate) struct Asked; + + impl Asked { + pub(crate) fn new(level: u8, card_full: bool) -> Asked { + crate::inplace::TEST_LEVEL.set(Some(level)); + // Opened on the asking thread, as these tests look at what an ask + // gives at once (`LEONIDA_INPLACE_ASYNC=0`). + crate::inplace::TEST_ASYNC.set(Some(false)); + super::TEST_CARD_FULL.set(card_full); + Asked + } + } + + impl Drop for Asked { + fn drop(&mut self) { + crate::inplace::TEST_LEVEL.set(None); + crate::inplace::TEST_ASYNC.set(None); + super::TEST_CARD_FULL.set(false); + } + } + + /// The host, if its device opens memory as heaps (`ID3D12Device13`) and + /// copies go to the card's memory. + pub(crate) fn host_that_opens() -> Option<&'static crate::host::Host> { + let host = crate::host::host()?; + (super::cards() && host.card_ready() && host.device.cast::<ID3D12Device13>().is_ok()).then_some(host) + } + + /// Private memory of the test's own, committed whole: its base, and the + /// first multiple of `align` in it, from which `len` bytes are in it. + pub(crate) fn private(len: usize, align: usize) -> (usize, usize) { + // SAFETY: a fresh allocation of our own. + let base = unsafe { mem::VirtualAlloc(std::ptr::null(), len + align, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) } as usize; + assert_ne!(base, 0, "memory for the test"); + (base, base.next_multiple_of(align)) + } + + /// The title gives the allocation at `base` back, through the runtime's + /// path: a release a heap still refuses is done once the heap went. + pub(crate) fn give_back(base: usize) { + // SAFETY: the test's own allocation. + crate::inplace::title_memory_free(base, 0, mem::MEM_RELEASE, || unsafe { mem::VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE) }); + } + + /// Memory `[start, start + len)` gets bytes made from `seed`. + pub(crate) fn write(start: usize, len: usize, seed: u8) { + // SAFETY: the test's own memory. + let bytes = unsafe { std::slice::from_raw_parts_mut(start as *mut u8, len) }; + for (i, byte) in bytes.iter_mut().enumerate() { + *byte = seed.wrapping_add((i * 7 + i / 251) as u8); + } + } + + /// The card copies `[start, start + len)` out of `shadow`'s buffer and + /// finds the bytes the CPU sees at `start`. + pub(crate) fn card_reads(shadow: &Shadow, start: usize, len: usize) { + let host = crate::host::host().expect("the host"); + let mut rig = crate::inplace::Rig::new(&host.device).expect("a queue of the test's own"); + let got = rig.fetch(&shadow.buffer, shadow.offset(start as u64), len).expect("the card's copy"); + // SAFETY: the test's own memory. + let title = unsafe { std::slice::from_raw_parts(start as *const u8, len) }; + assert!(got == title, "the card reads the title's bytes at {start:#x}+{len:#x}"); + } + + /// A window of private title memory that would be a copy in the PC's + /// memory alone (no card side, no mapped card memory: neither switch is + /// set) is the title memory itself at level 1: the card reads what the + /// title wrote, and what it writes after, and nothing is copied at + /// submission. + #[test] + fn a_window_kept_only_in_the_pcs_memory_is_read_in_place() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(_host) = host_that_opens() else { return }; + if super::window() != super::WINDOW || super::window_card_most() != 0 || super::window_mapped_most() != 0 { + return; + } + let _asked = Asked::new(1, false); + let cell_bytes = super::WINDOW as usize; + let (base, cell) = private(cell_bytes, cell_bytes); + let (at, len) = (cell + 0x1_2340, 0x2_0000); + write(at, len, 1); + let shadow = super::find(at as u64, len as u64).expect("a window"); + assert!(shadow.in_place() && shadow.window, "the window is the title memory in place"); + assert_eq!(shadow.span(), (cell as u64, cell_bytes as u64)); + assert_eq!(shadow.update(at, len), 0, "nothing is copied at submission"); + card_reads(&shadow, at, len); + write(at, len, 99); + card_reads(&shadow, at, len); + assert_eq!(super::in_place_let_go(cell as u64, cell_bytes as u64).len(), 1); + drop(shadow); + give_back(base); + } + + /// (`LEONIDA_INPLACE_ASYNC`) The first ask of such a window gets a copy + /// and asks the opener; once the opener has opened the memory and nothing + /// holds the copy, a tick puts the title memory in place in the copy's + /// place, and the next ask gets it: the card reads what the title wrote, + /// and what it writes after. Before, the first ask opened the memory on + /// the asking thread. + #[test] + fn a_window_opened_in_the_background_takes_the_place_of_its_copy() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(host) = host_that_opens() else { return }; + if super::window() != super::WINDOW || super::window_card_most() != 0 || super::window_mapped_most() != 0 { + return; + } + let _asked = Asked::new(1, false); + crate::inplace::TEST_ASYNC.set(Some(true)); + let cell_bytes = super::WINDOW as usize; + let (base, cell) = private(cell_bytes, cell_bytes); + let (at, len) = (cell + 0x1_2340, 0x2_0000); + write(at, len, 1); + let copy = super::find(at as u64, len as u64).expect("a window"); + assert!(!copy.in_place(), "a copy at first"); + assert_eq!(copy.span(), (cell as u64, cell_bytes as u64)); + drop(copy); + assert!(crate::inplace::tests::open_window_now(&host.device, cell as u64, cell_bytes as u64), "the opener opens it"); + crate::inplace::tests::switch_ready_now(); + let shadow = super::find(at as u64, len as u64).expect("a window"); + assert!(shadow.in_place() && shadow.window, "the window is the title memory in place now"); + assert_eq!(shadow.update(at, len), 0, "nothing is copied at submission"); + card_reads(&shadow, at, len); + write(at, len, 99); + card_reads(&shadow, at, len); + assert_eq!(super::in_place_let_go(cell as u64, cell_bytes as u64).len(), 1); + drop(shadow); + give_back(base); + } + + /// (`LEONIDA_INPLACE_SWITCH_HELD`) A window a host list reads, which + /// holds its copy until it is reset (memory read every frame always is + /// held so), takes the title memory in place at the next tick all the + /// same: the next ask gets what is in place, and the list's copy stays + /// alive and is brought up to date from title memory at its submission, + /// as before; the list lets go of it at its reset. Before, the copy was + /// switched only once nothing but the table held it, which a window read + /// every frame never is: the heap waited beside it and was let go. + #[test] + fn a_window_a_list_holds_takes_the_title_memory_in_place_and_the_list_keeps_its_copy() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(host) = host_that_opens() else { return }; + if super::window() != super::WINDOW || super::window_card_most() != 0 || super::window_mapped_most() != 0 || !crate::inplace::switch_held() { + return; + } + let _asked = Asked::new(1, false); + crate::inplace::TEST_ASYNC.set(Some(true)); + let cell_bytes = super::WINDOW as usize; + let (base, cell) = private(cell_bytes, cell_bytes); + let (at, len) = (cell + 0x1_2340, 0x2_0000); + write(at, len, 1); + let list = host.new_list().expect("a host list"); + let copy = super::find(at as u64, len as u64).expect("a window"); + assert!(!copy.in_place(), "a copy at first"); + // The list reads it: it holds the copy until it is reset. + copy.refresh(&list, at as u64, len as u64); + let held = std::sync::Arc::downgrade(©); + drop(copy); + assert!(crate::inplace::tests::open_window_now(&host.device, cell as u64, cell_bytes as u64), "the opener opens it"); + crate::inplace::tests::switch_ready_now(); + let shadow = super::find(at as u64, len as u64).expect("a window"); + assert!(shadow.in_place() && shadow.window, "the next ask gets the title memory in place, though the list holds the copy"); + card_reads(&shadow, at, len); + let copy = held.upgrade().expect("the list holds its copy"); + assert!(!copy.in_place() && copy.switched_for_test()); + // Its submission's refresh: the title's bytes of now. + write(at, len, 99); + assert!(copy.update(at, len) > 0, "the list's copy is brought up to date at its submission"); + card_reads(©, at, len); + card_reads(&shadow, at, len); + drop(copy); + list.close(); + list.reset(); + assert_eq!(super::in_place_let_go(cell as u64, cell_bytes as u64).len(), 1); + drop(shadow); + give_back(base); + } + + /// With room for windows in the card's memory (`LEONIDA_CARD_WINDOWS_MB`) + /// a window at level 1 gets its side there, not the title memory in + /// place (`LEONIDA_INPLACE_LAST`): the card reads that side at its own + /// memory's speed, title memory over the bus. Before, in place came + /// first and took every window it could open. + #[test] + fn a_window_with_room_on_the_card_gets_its_side_there_not_in_place() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(_host) = host_that_opens() else { return }; + if !crate::inplace::last() || super::window() != super::WINDOW { + return; + } + let _asked = Asked::new(1, false); + super::TEST_WINDOW_CARD_MOST.set(Some(64 << 20)); + let cell_bytes = super::WINDOW as usize; + let (base, cell) = private(cell_bytes, cell_bytes); + let (at, len) = (cell + 0x1_2340, 0x2_0000); + write(at, len, 4); + let shadow = super::find(at as u64, len as u64); + super::TEST_WINDOW_CARD_MOST.set(None); + let shadow = shadow.expect("a window"); + let (in_place, carded, window) = (shadow.in_place(), shadow.carded(), shadow.window); + drop(super::window_gone(cell as u64, cell_bytes as u64)); + drop(shadow); + give_back(base); + assert!(window && !in_place, "a window, not the title memory in place"); + assert!(carded, "its side is in the card's memory"); + } + + /// A big title buffer the card's memory turns down is no copy in the PC's + /// memory at level 2 but the title memory in place: the card reads its + /// bytes, and nothing is copied at submission. Before, a big buffer was + /// never opened in place, and one the card turned down was a copy read + /// over the bus as the title's own memory would have been. + #[test] + fn a_big_title_buffer_the_card_turns_down_is_read_in_place() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(_host) = host_that_opens() else { return }; + let _asked = Asked::new(2, true); + // Big: its copy would be the card's least size or more. + let least = super::card_limits().0.max(1 << 16) as usize; + let (base, at) = private(least, 1 << 16); + let (start, len) = (at + 0x100, least - 0x100); + write(start, len, 5); + super::register(start, start as u64, len as u64); + let shadow = super::find(start as u64, len as u64); + super::unregister(start, start as u64); + let shadow = shadow.expect("a copy"); + assert!(shadow.in_place(), "the buffer is the title memory in place, not a copy in the PC's memory"); + assert!(!shadow.carded()); + assert_eq!(shadow.update(start, len), 0, "nothing is copied at submission"); + card_reads(&shadow, start, len); + write(start, len, 77); + card_reads(&shadow, start, len); + drop(shadow); + give_back(base); + } + + /// An upload arena (memory of ours the title's lists write and their + /// shaders read by address, `crate::upload`) is no copy at level 1 but + /// the memory itself in place, which nothing holds for the title's frees: + /// the card reads it, and nothing is copied at submission. Before, it was + /// copied as a title buffer (from the card's least size on, a card side + /// and a CPU side of its size). + #[test] + fn an_upload_arena_is_read_in_place() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(_host) = host_that_opens() else { return }; + let _asked = Asked::new(1, false); + // More than an arena's worth: an arena of its own, made now. + let mut upload = crate::upload::Upload::new((4 << 20) + 1).expect("upload memory"); + let (start, len) = (upload.start() as usize, 0x3_0000); + write(start, len, 3); + let shadow = super::find(start as u64, len as u64).expect("its copy"); + assert!(shadow.in_place(), "the arena is the memory itself in place"); + assert_eq!(shadow.update(start, len), 0, "nothing is copied at submission"); + card_reads(&shadow, start, len); + write(start, len, 33); + card_reads(&shadow, start, len); + assert_eq!(crate::inplace::tests::standing_over(start, start + len), 0, "nothing holds it for the title's frees"); + drop(shadow); + drop(upload); + } + + /// A title buffer in the page pool that is one run of a committed + /// section (`LEONIDA_SECTION_COMMIT=1` makes the pool's small sections + /// so) is the section's own pages in place at level 2: the card reads the + /// title's bytes, also those it writes after, and nothing is copied at + /// submission. When the title maps other pages there (as `crate::watch` + /// tells it) it is let go. Before, view memory was always a copy. + #[test] + fn a_title_buffer_in_a_committed_section_is_read_in_place() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(_host) = host_that_opens() else { return }; + let _asked = Asked::new(2, true); + const SIZE: usize = 4 << 16; + // SAFETY: a section and a view of the test's own. + let (handle, view) = unsafe { + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null()); + assert!(!handle.is_null(), "a committed section"); + let view = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, 0, SIZE).Value as usize; + assert_ne!(view, 0); + (handle, view) + }; + crate::inplace::title_memory_section(handle as usize, SIZE as u64, true); + crate::inplace::title_memory_view(view, SIZE, handle as usize, 0); + let (start, len) = (view + 0x100, 3 << 16); + write(start, len, 9); + super::register(start, start as u64, len as u64); + let shadow = super::find(start as u64, len as u64).expect("a copy"); + assert!(shadow.in_place(), "the buffer is the section's pages in place, not a copy"); + assert_eq!(shadow.update(start, len), 0, "nothing is copied at submission"); + card_reads(&shadow, start, len); + write(start, len, 90); + card_reads(&shadow, start, len); + // The title maps other pages there. + crate::inplace::views_gone(view, SIZE); + crate::inplace::title_memory_freeing(view, SIZE); + assert!(super::peek(start as u64, len as u64).is_none(), "let go once the title maps other pages there"); + super::unregister(start, start as u64); + drop(shadow); + // SAFETY: the test's own view and section. + unsafe { + mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut c_void }); + crate::inplace::title_memory_section_gone(handle as usize); + windows_sys::Win32::Foundation::CloseHandle(handle); + } + } + + /// A descriptor slot that views a title buffer in place in a committed + /// section lets go of it before the next submission once the title maps + /// other pages at its address (`crate::inplace::unheld_gone`): the slot + /// is made again from the record, from what the address shows then. + /// Before, the slot went on showing the section's old pages (a section's + /// heap is held by nothing that sees the title's frees, so nothing found + /// the slot), and kept the section's heap for as long. + #[test] + fn a_slot_over_a_title_buffer_in_a_section_lets_go_when_the_title_maps_other_pages_there() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(_host) = host_that_opens() else { return }; + let (title_heap, Some(heap)) = crate::descriptor::test_view_heap(8) else { return }; + let _asked = Asked::new(2, true); + const SIZE: usize = 4 << 16; + // SAFETY: a section and a view of the test's own. + let (handle, view) = unsafe { + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null()); + assert!(!handle.is_null(), "a committed section"); + let view = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, 0, SIZE).Value as usize; + assert_ne!(view, 0); + (handle, view) + }; + crate::inplace::title_memory_section(handle as usize, SIZE as u64, true); + crate::inplace::title_memory_view(view, SIZE, handle as usize, 0); + let (start, len) = (view + 0x100, 3 << 16); + write(start, len, 11); + super::register(start, start as u64, len as u64); + let shadow = super::find(start as u64, len as u64).expect("a copy"); + assert!(shadow.in_place(), "the buffer is the section's pages in place"); + // A title slot made of it, as a draw makes one from the title's + // descriptor. + heap.raw_at(3, &shadow.buffer, shadow.offset(start as u64), len as u64); + let raw = [shadow.buffer.as_raw() as usize]; + assert!(heap.keeps_one_of(3, &raw)); + drop(shadow); + // The title maps other pages there; then a submission starts. + crate::inplace::views_gone(view, SIZE); + crate::inplace::title_memory_freeing(view, SIZE); + crate::inplace::slots_let_go_of_unheld(); + assert!(!heap.keeps_one_of(3, &raw), "the slot let go of the section's old pages"); + super::unregister(start, start as u64); + crate::object::slot::<extern "system" fn(crate::object::This) -> u32>(title_heap, 0x10)(title_heap); + // SAFETY: the test's own view and section. + unsafe { + mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut c_void }); + crate::inplace::title_memory_section_gone(handle as usize); + windows_sys::Win32::Foundation::CloseHandle(handle); + } + } +} diff --git a/d3d12/crates/leonida-gpu/src/shadow/direct.rs b/d3d12/crates/leonida-gpu/src/shadow/direct.rs new file mode 100644 index 0000000000..cca241e513 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/shadow/direct.rs @@ -0,0 +1,372 @@ +//! Which bytes of a copy in the card's memory the card copies straight out +//! of its CPU side (`Card::staging`), and which go through memory of the +//! submission's own (`crate::host::send`, `LEONIDA_SEND_DIRECT`). +//! +//! Out of the CPU side a dirty byte is copied once on the CPU (title memory +//! into the side, by the refresh); through the submission's memory twice +//! (that memory too, on the submitting thread: 73-93 MB a frame, 3-7 ms in +//! `docs/findings.md`'s last section, where the card is measured to copy out +//! of write-back memory as fast as out of upload memory). What the memory +//! buys is that a submission's sends are its bytes as they were when it was +//! prepared, whatever later ones put into the side before the card gets to +//! it. For the title's own CPU writes that needs no help: the title is told +//! of a submission (fences, bottom-of-pipe writes) once the card has run +//! it, so it does not write what a submission in the air still reads, and +//! the opened arenas already send out of live memory on that ground. It does +//! for what *we* write into title memory when the next submission is +//! prepared: the title's buffer copies (`Step::Copy`, copies at their place, +//! `CopyMemoryToMemoryX` done on the CPU) are commands its GPU would run after +//! the earlier submission, and we do them at once. +//! +//! So per copy: +//! +//! - the pieces we wrote such a copy into in the last [`KEPT`] sends go up +//! through the submission's memory, as before: such writes come back at +//! the same places frame after frame, and there the side is rewritten +//! while the card may not have read it yet; +//! - the others go up straight out of the side, and their pieces are noted +//! as in the air with the number of their send until the card is past it +//! (a fence of [`crate::host::send`] behind the list that copies them); +//! - before we write such a copy into title memory at submission, its pieces +//! are noted ([`Direct::copied`]) and a send in the air that reads them is +//! waited for ([`Direct::blocking`], a look at those pieces whatever the +//! number of sends in the air). With the notes that is a write into +//! a piece nothing of ours wrote in the last [`KEPT`] sends but the title +//! sent straight in a send the card has not reached: once per new place, +//! not in a steady state (`a_steady_frame_never_waits`). +//! +//! A copy whose card side lies in card memory the CPU maps +//! (`LEONIDA_BAR_BUFFERS_MB`, `Shadow::card_bar`) has its straight parts +//! written into that side by the CPU when they are taken, not copied by the +//! card later: then nothing is in the air, but the side changes at once, +//! under submissions the card has not run. That is right for the title's own +//! CPU writes (as above), and for nothing of ours. So such a copy notes, per +//! piece, the value the sends' fence must have reached before the CPU may +//! write it ([`Direct::split_mapped`]): past every card copy of ours into +//! it (the sends that took it through the submission's memory), and past +//! the lists of the submissions that wrote it at submission (a copy at its +//! place runs in them, after their own send: two sends on). Exact, where +//! [`KEPT`] is a guess that costs a wait when it is wrong; a wrong guess +//! here would cost a byte. + +/// The bytes a note stands for: the card's pieces' size. +pub(super) const PIECE: usize = 64 << 10; + +/// For how many sends a piece we wrote at submission goes up through the +/// submission's memory: some 30 submissions a frame, so tens of frames +/// (a hypothesis: how far apart the title's copies to the same place are is +/// not measured; a longer gap costs one wait, not a wrong byte). +pub(super) const KEPT: u64 = 1024; + +/// Of one copy in the card's memory: where we wrote it at submission, and +/// what the card is still to copy out of its CPU side. +#[derive(Default)] +pub(super) struct Direct { + /// Per [`PIECE`] of the copy: the last send number when we wrote it at + /// submission, 0 never. Made at the first write. + copied: Vec<u64>, + /// Per [`PIECE`] of the copy: the last send number that copies (some of) + /// it straight out of the CPU side, 0 never. Made at the first such send. + /// A piece, not the bytes: a write of ours beside what a send in the air + /// reads in the same piece waits too, once (the piece is noted and goes + /// through the submission's memory from then on), and the look before a + /// write is the pieces it touches, not every run of the sends in the air + /// (some 60 sends with the relay, for each of the ~13,000 copies a frame + /// that touch a card copy, under the submission's lock). + air: Vec<u64>, + /// The highest number in `air`, and the highest send the card was told + /// to be past ([`Direct::landed`]). + top: u64, + reached: u64, + /// Bytes [`Direct::split`] gave out straight and through the + /// submission's memory, and the sends in the air waited for + /// (`Shadow::card_copying`): this copy's, for tests (the frame line's + /// counters are the process's). + pub(super) sent: [u64; 2], + pub(super) waits: u64, + /// Of a copy whose card side the CPU writes: per [`PIECE`], the value + /// the sends' fence must have reached before the CPU may write it there + /// ([`Direct::split_mapped`]); 0 any time. Made at the first need. + mapped: Vec<u64>, +} + +impl Direct { + /// We write offsets `[from, to)` at submission; `now` is the last send's + /// number (the next send is past it). + pub(super) fn copied(&mut self, from: usize, to: usize, now: u64) { + if from >= to { + return; + } + let last = (to - 1) / PIECE; + if self.copied.len() <= last { + self.copied.resize(last + 1, 0); + } + for piece in &mut self.copied[from / PIECE..=last] { + *piece = now.max(1); + } + } + + /// Of a copy whose card side the CPU writes: we write offsets `[from, + /// to)` at submission, `now` being the last send's number. A copy at its + /// place into the card side runs in this submission's lists, behind its + /// own send (`now + 1` at most): the CPU leaves the pieces alone until + /// the card is past the send after that one. + pub(super) fn copied_mapped(&mut self, from: usize, to: usize, now: u64) { + self.need(from, to, now + 2); + } + + /// The fence must reach `value` before the CPU writes the pieces of + /// `[from, to)`. + fn need(&mut self, from: usize, to: usize, value: u64) { + if from >= to { + return; + } + let last = (to - 1) / PIECE; + if self.mapped.len() <= last { + self.mapped.resize(last + 1, 0); + } + for piece in &mut self.mapped[from / PIECE..=last] { + *piece = (*piece).max(value); + } + } + + /// Of a copy whose card side the CPU writes: send `number` takes offsets + /// `[from, to)`, and the card is past send `reached`. The parts the CPU + /// writes into the side now (no card copy of ours is still to land on + /// them: [`Direct::copied_mapped`], and the sends that took them through + /// the submission's memory), then the parts that go through it, each in + /// order and joined. Nothing is noted as in the air: the CPU is done with + /// the first when this returns, and the card copies the second out of the + /// submission's memory. What goes through it holds its pieces until the + /// card is past `number`. + pub(super) fn split_mapped(&mut self, from: usize, to: usize, number: u64, reached: u64) -> (Vec<(usize, usize)>, Vec<(usize, usize)>) { + let (mut direct, mut own): (Vec<(usize, usize)>, Vec<(usize, usize)>) = (Vec::new(), Vec::new()); + let mut at = from; + while at < to { + let piece = at / PIECE; + let next = ((piece + 1) * PIECE).min(to); + let free = self.mapped.get(piece).is_none_or(|&need| need <= reached); + if !free { + self.need(at, next, number); + } + let out = if free { &mut direct } else { &mut own }; + match out.last_mut() { + Some(last) if last.1 == at => last.1 = next, + _ => out.push((at, next)), + } + at = next; + } + let bytes = |runs: &[(usize, usize)]| runs.iter().map(|&(a, b)| (b - a) as u64).sum::<u64>(); + self.sent[0] += bytes(&direct); + self.sent[1] += bytes(&own); + (direct, own) + } + + /// Whether piece `piece` was written by us in the [`KEPT`] sends before + /// send `number`. + fn kept(&self, piece: usize, number: u64) -> bool { + self.copied.get(piece).is_some_and(|&at| at != 0 && number.saturating_sub(at) <= KEPT) + } + + /// Send `number` takes offsets `[from, to)`: the parts the card copies + /// out of the CPU side, noted as in the air, then the parts that go + /// through the submission's memory, each in order and joined. + pub(super) fn split(&mut self, from: usize, to: usize, number: u64) -> (Vec<(usize, usize)>, Vec<(usize, usize)>) { + let (mut direct, mut own): (Vec<(usize, usize)>, Vec<(usize, usize)>) = (Vec::new(), Vec::new()); + let mut at = from; + while at < to { + let piece = at / PIECE; + let next = ((piece + 1) * PIECE).min(to); + let kept = self.kept(piece, number); + if !kept { + if self.air.len() <= piece { + self.air.resize(piece + 1, 0); + } + self.air[piece] = self.air[piece].max(number); + } + let out = if kept { &mut own } else { &mut direct }; + match out.last_mut() { + Some(last) if last.1 == at => last.1 = next, + _ => out.push((at, next)), + } + at = next; + } + let bytes = |runs: &[(usize, usize)]| runs.iter().map(|&(a, b)| (b - a) as u64).sum::<u64>(); + self.sent[0] += bytes(&direct); + self.sent[1] += bytes(&own); + if !direct.is_empty() { + self.top = self.top.max(number); + } + (direct, own) + } + + /// The card is past send `reached`: what those sends read is read. + pub(super) fn landed(&mut self, reached: u64) { + self.reached = self.reached.max(reached); + } + + /// The highest send the card has not reached (past `reached`, and past + /// what [`Direct::landed`] was told) that copies out of the pieces of + /// offsets `[from, to)` of the CPU side; 0 for none. + pub(super) fn blocking(&self, from: usize, to: usize, reached: u64) -> u64 { + let reached = reached.max(self.reached); + if from >= to || self.top <= reached { + return 0; + } + let last = ((to - 1) / PIECE + 1).min(self.air.len()); + let pieces = self.air.get(from / PIECE..last).unwrap_or_default(); + pieces.iter().copied().filter(|&n| n > reached).max().unwrap_or(0) + } + + /// Whether a send is noted as in the air. + pub(super) fn in_air(&self) -> bool { + self.top > self.reached + } +} + +#[cfg(test)] +mod tests { + use super::{Direct, KEPT, PIECE}; + + /// What nothing of ours wrote goes straight out of the CPU side, and is + /// in the air until the card is past its send; a piece we wrote goes + /// through the submission's memory for [`KEPT`] sends, then straight + /// again. + #[test] + fn written_pieces_go_through_own_memory_for_a_while() { + let mut d = Direct::default(); + let (direct, own) = d.split(100, 3 * PIECE + 5, 1); + assert_eq!((direct, own), (vec![(100, 3 * PIECE + 5)], vec![])); + assert_eq!(d.blocking(0, 200, 0), 1, "the send reads it until the card is past it"); + assert_eq!(d.blocking(0, 100, 0), 1, "bytes it does not read in a piece it reads: the piece is waited for"); + assert_eq!(d.blocking(4 * PIECE, 5 * PIECE, 0), 0, "a piece it does not read"); + assert_eq!(d.blocking(0, 200, 1), 0, "the card is past it"); + d.landed(1); + assert!(!d.in_air()); + // Piece 1 written by us after send 1. + d.copied(PIECE + 10, PIECE + 20, 1); + let (direct, own) = d.split(0, 3 * PIECE, 2); + assert_eq!(direct, vec![(0, PIECE), (2 * PIECE, 3 * PIECE)]); + assert_eq!(own, vec![(PIECE, 2 * PIECE)]); + assert_eq!(d.blocking(PIECE, 2 * PIECE, 0), 0, "what went through own memory is not in the air"); + assert_eq!(d.blocking(PIECE - 1, PIECE + 1, 0), 2); + // Still kept KEPT sends on; straight again past them. + assert_eq!(d.split(PIECE, PIECE + 1, 1 + KEPT).1, vec![(PIECE, PIECE + 1)]); + assert_eq!(d.split(PIECE, PIECE + 1, 2 + KEPT).0, vec![(PIECE, PIECE + 1)]); + } + + /// Several sends in the air: the one to wait for is the latest that + /// reads the pieces, and each goes once the card is past it. + #[test] + fn the_latest_send_in_the_air_that_reads_bytes_is_waited_for() { + let mut d = Direct::default(); + d.split(0, 10, 5); + d.split(5 * PIECE, 5 * PIECE + 1, 5); + d.split(PIECE + 20, PIECE + 30, 6); + d.split(2 * PIECE, 2 * PIECE + 1, 6); + d.split(5, PIECE + 25, 7); + d.split(4 * PIECE, 4 * PIECE + 10, 7); + assert_eq!(d.blocking(5 * PIECE, 6 * PIECE, 0), 5); + assert_eq!(d.blocking(0, 4, 0), 7, "send 7 is past send 5 there"); + assert_eq!(d.blocking(2 * PIECE + 9, 2 * PIECE + 10, 0), 6); + assert_eq!(d.blocking(3 * PIECE, 4 * PIECE, 0), 0, "nothing reads piece 3"); + assert_eq!(d.blocking(4 * PIECE + 5, 4 * PIECE + 6, 6), 7); + assert_eq!(d.blocking(2 * PIECE, 3 * PIECE, 6), 0); + d.landed(5); + assert_eq!(d.blocking(5 * PIECE, 6 * PIECE, 0), 0, "send 5 is gone"); + d.landed(6); + assert_eq!(d.blocking(2 * PIECE, 3 * PIECE, 0), 0, "send 6 is gone"); + assert_eq!(d.blocking(0, 100 * PIECE, 0), 7); + assert_eq!(d.blocking(0, 100 * PIECE, 3), 7, "an older reached is not taken back"); + d.landed(7); + assert!(!d.in_air()); + assert_eq!(d.blocking(0, 100 * PIECE, 0), 0); + // Thousands of sends in the air: a write looks at its pieces. + for n in 8..10_008u64 { + d.split(n as usize * PIECE, n as usize * PIECE + 4, n); + } + assert_eq!(d.blocking(9 * PIECE + 1, 11 * PIECE, 7), 10); + assert_eq!(d.blocking(9 * PIECE + 1, 11 * PIECE, 10), 0); + } + + /// A copy whose card side the CPU writes: what nothing of ours wrote is + /// written by the CPU at once, whatever the card has reached, and nothing + /// is noted as in the air; a piece we wrote at submission waits for the + /// card to be past the lists of that submission (two sends on), and one + /// that went through the submission's memory for the card to be past + /// that send, however long that takes ([`KEPT`] sends or more). With + /// [`Direct::split`] the piece went straight again after `KEPT` sends, + /// with the copy of ours still to run, and was noted in the air. + #[test] + fn a_card_side_the_cpu_writes_waits_for_every_copy_of_ours() { + let mut d = Direct::default(); + assert_eq!(d.split_mapped(100, 3 * PIECE + 5, 1, 0), (vec![(100, 3 * PIECE + 5)], vec![])); + assert!(!d.in_air(), "nothing the card is still to copy out of the CPU side"); + assert_eq!(d.blocking(0, 4 * PIECE, 0), 0); + // Piece 1 written by us when send 1 was the last given. + d.copied_mapped(PIECE + 10, PIECE + 20, 1); + let (direct, own) = d.split_mapped(0, 3 * PIECE, 2, 1); + assert_eq!(direct, vec![(0, PIECE), (2 * PIECE, 3 * PIECE)]); + assert_eq!(own, vec![(PIECE, 2 * PIECE)]); + // The card past send 2 (that submission's own send), not past its + // lists: still through the submission's memory, which holds it on + // until send 3 is reached. + assert_eq!(d.split_mapped(PIECE, PIECE + 1, 3, 2).1, vec![(PIECE, PIECE + 1)]); + // Thousands of sends later, the card still behind send 3: not yet. + assert_eq!(d.split_mapped(PIECE, PIECE + 1, 3 + 2 * KEPT, 2).1, vec![(PIECE, PIECE + 1)]); + assert_eq!(d.split_mapped(PIECE, PIECE + 1, 4 + 2 * KEPT, 3 + 2 * KEPT).0, vec![(PIECE, PIECE + 1)]); + assert!(!d.in_air()); + assert_eq!(d.sent, [(2 * PIECE + 3 * PIECE + 5 - 100 + 1) as u64, PIECE as u64 + 2]); + } + + /// A simulated run: 30 submissions a frame, the card three submissions + /// behind the CPU (a send is in the air until the CPU has prepared three + /// more), each submission sending pages the title writes on the CPU and + /// pages its buffer copies write, the same places every frame. With the + /// notes, the CPU waits for the card only in the first frame (places it + /// wrote nothing into yet); without them (every piece straight) it waits + /// in every frame. Every send's bytes are the bytes it was prepared with + /// either way: the waits are what keeps them. + #[test] + fn a_steady_frame_never_waits() { + const FRAMES: u64 = 40; + const EACH: u64 = 30; + const BEHIND: u64 = 3; + let run = |notes: bool| { + let mut d = Direct::default(); + let mut number = 0u64; + let (mut waits, mut late_waits) = (0u64, 0u64); + for frame in 0..FRAMES { + for s in 0..EACH { + let reached = number.saturating_sub(BEHIND); + d.landed(reached); + // A buffer copy of ours into this submission's place, + // which the title's CPU wrote for the submission before. + let copy = (((s + 1) % EACH) as usize * 4 * PIECE, ((s + 1) % EACH) as usize * 4 * PIECE + 4096); + if notes { + d.copied(copy.0, copy.1, number); + } + if d.blocking(copy.0, copy.1, reached) != 0 { + waits += 1; + if frame > 0 { + late_waits += 1; + } + // The wait: the card is past every send. + d.landed(number); + } + // The title's CPU wrote its own place for the next one. + let title = (((s + 2) % EACH) as usize * 4 * PIECE, ((s + 2) % EACH) as usize * 4 * PIECE + 8192); + number += 1; + let _ = d.split(copy.0, copy.1, number); + let _ = d.split(title.0, title.1, number); + } + } + (waits, late_waits) + }; + let (waits, late) = run(true); + let (without, late_without) = run(false); + eprintln!("waits in {FRAMES} frames: {waits} with the notes ({late} after the first), {without} without ({late_without})"); + assert_eq!(late, 0, "{waits} waits, {late} after the first frame"); + assert!(late_without >= FRAMES - 1, "{without} waits without the notes, {late_without} after the first frame"); + } +} diff --git a/d3d12/crates/leonida-gpu/src/smooth.rs b/d3d12/crates/leonida-gpu/src/smooth.rs index 15e86c712a..37de2dacb1 100644 --- a/d3d12/crates/leonida-gpu/src/smooth.rs +++ b/d3d12/crates/leonida-gpu/src/smooth.rs @@ -18,6 +18,29 @@ //! second, 11.1 -> 7.7 without one, 11.5 -> 7.8 and 10.1 -> 7.2 with `LEONIDA_FG_MARKERS=1`; //! their spread 12.3 -> 8.4, 10.4 -> 8.2, 11.5 -> 8.7 and 13.0 -> 7.6 ms; the median interval //! within 2 ms. Not measured here without frame generation (El1xr's numbers above are of that). +//! +//! `LEONIDA_SMOOTH_YIELD=1` (off unless set and not `0`; `LEONIDA_AB` may name it): no present is held while +//! submissions or presents other than itself stand in the line, not yet sent ([`waiting`], read +//! once when the hold begins: what reaches the line during a hold does not end it). The present +//! is sent by the line's own thread (`leonida-submit`, `queue::behind`'s present job), the one +//! thread that prepares and sends every submission, so a hold there stops the next frame's +//! submissions as well: the card idles while it sleeps, and the title's thread that waits for +//! one of our fences waits that much longer. In two traces standing (`LEONIDA_SUBMIT_FRAMES=1`, +//! 5 frames each, 2026-11-30) the host's present, nearly all of it this hold, took that thread +//! 3.6 and 2.1 ms a frame (the longest 11.5 ms) while the title's next frame stood behind it, +//! and the title's own present returned when the hold ended; a 30 s profile of the same scene +//! found 1.3 % of the run asleep in the hold. The count is of every queue's line, so a +//! submission stopped at a wait on another queue counts too and spares a hold that would not +//! have kept the thread from it. With nothing waiting (the line holds only this present, or +//! presents are not sent by a thread of ours: `queue::queued` is then 0) presents are held as +//! before; off (the default): held whether or not work waits, as before. Only when the host's present is +//! called moves; nothing of memory, fences or landings does. The frame-rate line says how many +//! presents were held and how long, and how many were not for the line with what they would +//! have slept (`line`, diagnostics builds), for the trade against how evenly presents come, +//! which the numbers above measure. Off by default: in the title (2026-11-30, RX 7900 XT, one +//! `LEONIDA_AB` run of 67 phases of 7 s in the world, four switches crossed) it moved the median +//! frame +0.6 % (s.e. 1.9 %), its 90th percentile +2.2 % (s.e. 3.6 %) and the submitting +//! thread's work +0.8 % (s.e. 1.2 %): the hold's sleep is not what keeps the card waiting there. use std::sync::{Mutex, OnceLock}; use std::time::{Duration, Instant}; @@ -77,22 +100,79 @@ fn hold_for(fraction: f64, mean_us: f64, since: Duration) -> Duration { Duration::from_micros((mean_us * fraction) as u64).saturating_sub(since) } +/// `LEONIDA_SMOOTH_YIELD`: whether a present with work waiting behind it is not held (module +/// notes). +#[cfg(windows)] +fn yields() -> bool { + crate::asked!("LEONIDA_SMOOTH_YIELD") +} + +#[cfg(not(windows))] +fn yields() -> bool { + false +} + +/// Whether work waits in the line for the present being sent, with `queued` from +/// `queue::queued`: submissions and presents in the line not yet given to the host, this present +/// among them (its job takes it off only after the host's present), so more than one. (0: no +/// thread of ours sends them.) +pub(crate) fn waiting(queued: u64) -> bool { + queued > 1 +} + +/// [`hold_for`], or none when `waiting` ([`waiting`]) and `yields` ([`yields`]). +fn hold_for_line(fraction: f64, mean_us: f64, since: Duration, waiting: bool, yields: bool) -> Duration { + if waiting && yields { Duration::ZERO } else { hold_for(fraction, mean_us, since) } +} + +/// Since the last frame-rate line: presents held, microseconds held; presents not held because +/// work waited behind them, microseconds they would have been. +#[cfg(feature = "diagnostics")] +static STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + /// Right before the host's present: held until the fraction of the mean has passed since the -/// last present returned. Returns how long it held. -pub(crate) fn hold() -> Duration { +/// last present returned, unless `waiting` ([`waiting`]) says other work stands in the line +/// ([`hold_for_line`]). Returns how long it held. +pub(crate) fn hold(waiting: bool) -> Duration { let Some(fraction) = fraction() else { return Duration::ZERO }; let (last, mean_us) = { let p = PACE.lock().unwrap_or_else(|e| e.into_inner()); (p.last, p.mean_us) }; let Some(last) = last else { return Duration::ZERO }; - let wait = hold_for(fraction, mean_us, last.elapsed()); + let since = last.elapsed(); + let wait = hold_for_line(fraction, mean_us, since, waiting, yields()); + #[cfg(feature = "diagnostics")] + { + use std::sync::atomic::Ordering::Relaxed; + let (at, us) = if wait.is_zero() && waiting { (2, hold_for(fraction, mean_us, since)) } else { (0, wait) }; + if !us.is_zero() { + STATS[at].fetch_add(1, Relaxed); + STATS[at + 1].fetch_add(us.as_micros() as u64, Relaxed); + } + } if !wait.is_zero() { std::thread::sleep(wait); } wait } +/// For the frame-rate line: [`STATS`] per frame, if any present was held or would have been. +#[cfg(feature = "diagnostics")] +pub(crate) fn line(frames: f64) { + use std::sync::atomic::Ordering::Relaxed; + let [held, held_us, yielded, yielded_us] = [0, 1, 2, 3].map(|i| STATS[i].swap(0, Relaxed) as f64 / frames); + if held + yielded > 0.0 { + tracing::info!( + "presents held to the recent mean interval (LEONIDA_PRESENT_SMOOTH), per frame: {held:.2} held, {:.2} ms \ + asleep; {yielded:.2} not held for submissions waiting behind them (LEONIDA_SMOOTH_YIELD), {:.2} ms they \ + would have slept", + held_us / 1000.0, + yielded_us / 1000.0 + ); + } +} + /// Right after the host's present returned: the interval since the last one goes into the mean /// (whether or not presents are held, so that a switch turned on finds it ready). pub(crate) fn presented() { @@ -126,4 +206,26 @@ mod tests { assert_eq!(hold_for(0.9, 70_000.0, Duration::from_millis(50)), Duration::from_millis(13)); assert_eq!(hold_for(0.9, 70_000.0, Duration::from_millis(70)), Duration::ZERO); } + + #[test] + fn a_present_with_submissions_behind_it_is_not_held() { + let since = Duration::from_millis(50); + // The title's next submissions wait behind the present: sent at once. + assert_eq!(hold_for_line(0.9, 70_000.0, since, true, true), Duration::ZERO); + // Nothing waits: held as before. + assert_eq!(hold_for_line(0.9, 70_000.0, since, false, true), Duration::from_millis(13)); + // `LEONIDA_SMOOTH_YIELD` off (the default): held whether or not work waits. + assert_eq!(hold_for_line(0.9, 70_000.0, since, true, false), Duration::from_millis(13)); + assert_eq!(hold_for_line(0.9, 70_000.0, Duration::from_millis(70), false, true), Duration::ZERO); + } + + #[test] + fn the_present_being_sent_is_not_work_waiting_behind_it() { + // No thread of ours sends presents: nothing is in its line. + assert!(!waiting(0)); + // Only the present being sent, which its job takes off after the host's present. + assert!(!waiting(1)); + // Something besides it. + assert!(waiting(2)); + } } diff --git a/d3d12/crates/leonida-gpu/src/texback.rs b/d3d12/crates/leonida-gpu/src/texback.rs index 92ee5afc44..f6cd374207 100644 --- a/d3d12/crates/leonida-gpu/src/texback.rs +++ b/d3d12/crates/leonida-gpu/src/texback.rs @@ -225,6 +225,12 @@ pub(crate) struct Back { mips: u32, layout: leonida_formats::texture::Layout, ticket: Arc<Ticket>, + /// How often the list was submitted ([`Back::submitted`]), and how often + /// a submission of it was landed ([`land`]): the card writes the buffer + /// again at each submission, so it is read in place only while every + /// submission so far has landed ([`mapped`]). + runs: Arc<AtomicU64>, + landed: Arc<AtomicU64>, /// The subresources it holds ([`Target::subs`]). subs: u64, } @@ -241,6 +247,12 @@ impl Back { pub(crate) fn range(&self) -> (usize, usize) { (self.ticket.at, self.ticket.end) } + + /// The list that copies into the buffer is submitted (before it goes to + /// the card): what the buffer holds may change from now on. + pub(crate) fn submitted(&self) { + self.runs.fetch_add(1, Ordering::SeqCst); + } } /// Records a host copy from a texture already in COPY_SOURCE. @@ -300,7 +312,17 @@ pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option // SAFETY: an open list; the texture is in the copy-source state. unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; } - Some(Back { buffer, footprints, rows, mips, layout: target.layout, ticket: target.ticket, subs: target.subs }) + Some(Back { + buffer, + footprints, + rows, + mips, + layout: target.layout, + ticket: target.ticket, + runs: Arc::new(AtomicU64::new(0)), + landed: Arc::new(AtomicU64::new(0)), + subs: target.subs, + }) } /// Whether texture read-backs are written into title memory by a thread of @@ -313,8 +335,8 @@ pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option /// (run 5 of the 16 GB machine, RTX 3060: "textures shaders wrote" in the /// read-backs line, two to ten 350 KB water maps a frame), and with it the /// landing of everything else. Here the landing thread only copies the -/// texels out of the read-back buffer; the waiting, tiling and writing go to -/// [`writer`]. Of several copies of one texture waiting there only the newest +/// texels out of the read-back buffer, or keeps it mapped for the writer +/// ([`mapped`]); the waiting, tiling and writing go to [`writer`]. Of several copies of one texture waiting there only the newest /// is written: the title reads the frame before at most, which it may on the /// console too. fn asynchronous() -> bool { @@ -363,7 +385,7 @@ pub(crate) fn land_many(backs: &[Back]) { } } -/// A read-back's texels taken out of its buffer, to be tiled into title memory. +/// A read-back's texels, to be tiled into title memory. struct Landing { footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>, rows: Vec<u32>, @@ -371,17 +393,133 @@ struct Landing { layout: leonida_formats::texture::Layout, ticket: Arc<Ticket>, /// The read-back buffer's bytes, from 0 to the end of its last subresource. - data: Vec<u8>, + data: Texels, /// The subresources it holds ([`Target::subs`]). subs: u64, } +/// Where a landing's texels are: taken out of the read-back buffer, or in it +/// ([`mapped`]). +enum Texels { + Copied(Vec<u8>), + Mapped(Mapped), +} + +/// A read-back buffer kept mapped for its landing: its first `len` bytes, +/// and the list's submission count ([`Back::runs`]) they were landed at. +/// Unmapped when it goes, and given back to the read-back pool if nothing +/// else holds it (`crate::host::give_read_back`): its reference moved out +/// to be asked about, not a second one beside it (which made the answer +/// always no, and a buffer whose list was reset before its landing was +/// written never went back to the pool). +struct Mapped { + buffer: std::mem::ManuallyDrop<ID3D12Resource>, + data: *const u8, + len: usize, + runs: Arc<AtomicU64>, + at: u64, +} + +// SAFETY: the mapping of a free-threaded buffer of ours, read only through +// `bytes`; the buffer is unmapped once, when this goes. +unsafe impl Send for Mapped {} + +impl Mapped { + fn bytes(&self) -> &[u8] { + // SAFETY: the buffer's mapping, of at least `len` bytes, while + // `self` holds it. + unsafe { std::slice::from_raw_parts(self.data, self.len) } + } + + /// Whether the list has not been submitted again since its texels were + /// landed: the card has not written the buffer since, so what was read + /// out of it before this was asked is the landing's. (A submission is + /// counted before it goes to the card.) + fn still(&self) -> bool { + std::sync::atomic::fence(Ordering::SeqCst); + self.runs.load(Ordering::SeqCst) == self.at + } +} + +impl Drop for Mapped { + fn drop(&mut self) { + // SAFETY: mapped once by `land` for this. + unsafe { self.buffer.Unmap(0, None) }; + // SAFETY: taken once, here, and not touched after. + let buffer = unsafe { std::mem::ManuallyDrop::take(&mut self.buffer) }; + crate::host::give_read_back(buffer); + } +} + +impl Landing { + fn texels(&self) -> &[u8] { + match &self.data { + Texels::Copied(data) => data, + Texels::Mapped(mapped) => mapped.bytes(), + } + } +} + +/// Whether a read-back is tiled into title memory straight out of its +/// buffer, kept mapped until it is written there (`LEONIDA_TEXBACK_MAPPED=0`: +/// its bytes are taken out into a vector of their own at the landing, as +/// before). +/// +/// Every landing allocated a vector of the read-back's size and copied the +/// buffer into it on the landing thread, so that the buffer could go back +/// to the list: a pass over each texture's bytes and an allocation, on top +/// of the card's copy, the tiling and the write into title memory (two to +/// ten water maps of 350 KB a frame, `asynchronous`). Read-back memory is +/// cached for the CPU, so it is tiled from where it is; the landing holds a +/// reference to the buffer, which keeps it out of the pool until the +/// landing is done (the pool takes only buffers nothing else holds). +/// +/// What the copy also guarded against: a list submitted again before its +/// landing is written has the card write the buffer again. So the texels +/// are read in place only when every submission of the list so far has +/// landed (`Back::runs` against `Back::landed`), and a landing whose list +/// was submitted again while it was tiled is not written (the next +/// landing of that list writes the newer texels); otherwise they are taken +/// out as before. +fn mapped() -> bool { + #[cfg(test)] + if let Some(on) = TEST_MAPPED.get() { + return on; + } + crate::toggled!("LEONIDA_TEXBACK_MAPPED") +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`mapped`], for its thread only. + static TEST_MAPPED: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; + /// For tests: bytes this thread took out of read-back buffers into + /// vectors, and landings it did not write because the list was + /// submitted again meanwhile. + static TAKEN_OUT: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; + static OVERTAKEN: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + /// Once the list has run, tile its texels back into the same title allocation /// (on [`writer`]'s thread when [`asynchronous`]). pub(crate) fn land(back: &Back) { + if let Some(landing) = landing(back) { + match asynchronous().then(writer).flatten() { + Some(writer) => writer.send(landing), + None => write(&landing), + } + } +} + +/// [`land`]'s landing of `back`: its texels kept in the mapped buffer when +/// every submission of the list has landed ([`mapped`]), else taken out. +fn landing(back: &Back) -> Option<Landing> { + // (Counted first: a landing that is not written still lands its + // submission.) + let landed = back.landed.fetch_add(1, Ordering::SeqCst) + 1; if !back.ticket.valid.load(Ordering::Acquire) { stale(); - return; + return None; } let len = back .footprints @@ -390,30 +528,33 @@ pub(crate) fn land(back: &Back) { .map(|(f, &rows)| f.Offset as usize + f.Footprint.RowPitch as usize * rows as usize * f.Footprint.Depth as usize) .max() .unwrap_or(0); - let mut mapped = std::ptr::null_mut(); + let mut data = std::ptr::null_mut(); // SAFETY: our read-back buffer, written by the list that has run; `len` // ends with its last subresource, which it holds. - let data = unsafe { - if back.buffer.Map(0, None, Some(&mut mapped)).is_err() || mapped.is_null() { - return; - } - let data = std::slice::from_raw_parts(mapped.cast::<u8>().cast_const(), len).to_vec(); - back.buffer.Unmap(0, None); - data + if unsafe { back.buffer.Map(0, None, Some(&mut data)) }.is_err() || data.is_null() { + return None; + } + let runs = back.runs.load(Ordering::SeqCst); + let texels = if mapped() && runs == landed { + Texels::Mapped(Mapped { buffer: std::mem::ManuallyDrop::new(back.buffer.clone()), data: data.cast::<u8>().cast_const(), len, runs: back.runs.clone(), at: runs }) + } else { + // SAFETY: as above. + let copied = unsafe { std::slice::from_raw_parts(data.cast::<u8>().cast_const(), len) }.to_vec(); + // SAFETY: mapped above. + unsafe { back.buffer.Unmap(0, None) }; + #[cfg(test)] + TAKEN_OUT.set(TAKEN_OUT.get() + len as u64); + Texels::Copied(copied) }; - let landing = Landing { + Some(Landing { footprints: back.footprints.clone(), rows: back.rows.clone(), mips: back.mips, layout: back.layout.clone(), ticket: back.ticket.clone(), - data, + data: texels, subs: back.subs, - }; - match asynchronous().then(writer).flatten() { - Some(writer) => writer.send(landing), - None => write(&landing), - } + }) } fn stale() { @@ -467,13 +608,23 @@ fn write(landing: &Landing) { let f = footprint.Footprint; let pitch = f.RowPitch as usize; let from = footprint.Offset as usize; - let linear = &landing.data[from..from + pitch * rows as usize * f.Depth as usize]; + let linear = &landing.texels()[from..from + pitch * rows as usize * f.Depth as usize]; if let Err(e) = landing.layout.tile(tiled, mip, slice, linear, pitch, pitch * rows as usize) { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!(?e, mip, slice, "a texture copied back could not be tiled")); return false; } } + // Read in place: not if the card may have written the buffer + // again meanwhile ([`mapped`]). + if let Texels::Mapped(mapped) = &landing.data + && !mapped.still() + { + crate::land::count(stat::TB_OVERTAKEN, 1); + #[cfg(test)] + OVERTAKEN.set(OVERTAKEN.get() + 1); + return false; + } true }; // Into title memory: all of it, or of a copy's the pages that change; @@ -741,7 +892,7 @@ mod tests { mips: 1, layout: layout.clone(), ticket: track(OWNER, at, at + size, false), - data: texels(seed), + data: Texels::Copied(texels(seed)), subs: u64::MAX, }; let expected = |seed: usize, before: &[u8]| { @@ -770,4 +921,214 @@ mod tests { assert_eq!(now(), second, "a read-back was written into an allocation that went"); drop(title); } + + /// On the host: a read-back whose list has landed every submission is + /// tiled into title memory straight out of its mapped buffer, nothing + /// taken out into a vector; one whose list is submitted again while it + /// is tiled is not written (the next landing is); one whose list has a + /// submission not landed yet, or with `LEONIDA_TEXBACK_MAPPED=0`, is + /// taken out first, as before. + #[test] + fn a_readback_is_tiled_from_its_mapped_buffer() { + use leonida_formats::texture::{Desc, Dimension, Layout, Swizzle}; + const OWNER: usize = 0x7e57_bac1; + let Some(host) = crate::host::host() else { return }; + let layout = Layout::new(&Desc { + dimension: Dimension::Tex2d, + width: 64, + height: 16, + depth: 1, + mips: 1, + element_bytes: 4, + block: 1, + samples: 1, + swizzle: Swizzle::SW_4KB_S, + }) + .unwrap(); + let size = layout.size as usize; + let mut title = vec![0u8; size]; + let at = title.as_mut_ptr() as usize; + let (pitch, rows) = (320usize, 16u32); + let len = pitch * rows as usize; + let buffer = host.read_back_buffer(len as u64).unwrap(); + let back = Back { + buffer: buffer.clone(), + footprints: vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Width: 64, Height: 16, Depth: 1, RowPitch: pitch as u32, ..Default::default() }, + }], + rows: vec![rows], + mips: 1, + layout: layout.clone(), + ticket: track(OWNER, at, at + size, false), + runs: Arc::new(AtomicU64::new(0)), + landed: Arc::new(AtomicU64::new(0)), + subs: u64::MAX, + }; + // What the card copied into the buffer; what the title then holds. + let texels = |seed: usize| -> Vec<u8> { (0..len).map(|i| (i * 13 + seed) as u8).collect() }; + let fill = |seed: usize| { + let mut data = std::ptr::null_mut(); + // SAFETY: our read-back buffer of `len` bytes or more, mapped + // and unmapped here (mappings are counted). + unsafe { + buffer.Map(0, None, Some(&mut data)).unwrap(); + std::ptr::copy_nonoverlapping(texels(seed).as_ptr(), data.cast::<u8>(), len); + buffer.Unmap(0, None); + } + }; + let expected = |seed: usize| { + let mut tiled = vec![0u8; size]; + layout.tile(&mut tiled, 0, 0, &texels(seed), pitch, len).unwrap(); + tiled + }; + // SAFETY: the vector's bytes, written behind its back. + let now = || unsafe { std::slice::from_raw_parts(at as *const u8, size) }.to_vec(); + TEST_MAPPED.set(Some(true)); + let taken = TAKEN_OUT.get(); + // Submitted once, landed: read where it is. + back.submitted(); + fill(1); + let first = landing(&back).unwrap(); + assert!(matches!(first.data, Texels::Mapped(_))); + write(&first); + drop(first); + assert_eq!(TAKEN_OUT.get(), taken, "nothing taken out"); + assert!(now() == expected(1), "the texels tiled into title memory"); + // Submitted again while the landing is tiled: not written; the + // landing of that submission is. + back.submitted(); + fill(2); + let second = landing(&back).unwrap(); + back.submitted(); + let overtaken = OVERTAKEN.get(); + write(&second); + drop(second); + assert_eq!(OVERTAKEN.get(), overtaken + 1); + assert!(now() == expected(1), "a landing the card may have written over is not written"); + fill(3); + let third = landing(&back).unwrap(); + assert!(matches!(third.data, Texels::Mapped(_))); + write(&third); + drop(third); + assert!(now() == expected(3)); + // Submitted twice, one landed: taken out at once, as before. + back.submitted(); + back.submitted(); + fill(4); + let fourth = landing(&back).unwrap(); + assert!(matches!(fourth.data, Texels::Copied(_))); + assert_eq!(TAKEN_OUT.get(), taken + len as u64); + write(&fourth); + assert!(now() == expected(4)); + // The switch off: taken out, as before. + TEST_MAPPED.set(Some(false)); + let fifth = landing(&back).unwrap(); + assert!(matches!(fifth.data, Texels::Copied(_))); + TEST_MAPPED.set(None); + released(OWNER); + drop(title); + } + + /// On the host: a list's submission counts for its read-backs before it + /// goes to the card, and its landing after it ran, so a list submitted + /// and landed once has its read-back read in place ([`mapped`]). + #[test] + fn a_submission_counts_before_its_landing() { + const OWNER: usize = 0x7e57_bac2; + let Some(host) = crate::host::host() else { return }; + let layout = leonida_formats::texture::Layout::new(&leonida_formats::texture::Desc { + dimension: leonida_formats::texture::Dimension::Tex2d, + width: 64, + height: 1, + depth: 1, + mips: 1, + element_bytes: 4, + block: 1, + samples: 1, + swizzle: leonida_formats::texture::Swizzle::LINEAR, + }) + .unwrap(); + let (runs, landed) = (Arc::new(AtomicU64::new(0)), Arc::new(AtomicU64::new(0))); + let back = Back { + buffer: host.read_back_buffer(256).unwrap(), + footprints: vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Width: 64, Height: 1, Depth: 1, RowPitch: 256, ..Default::default() }, + }], + rows: vec![1], + mips: 1, + layout, + // (No memory there: the ticket goes before the landing, which + // then writes nothing.) + ticket: track(OWNER, 0x7ffd_0000_0000, 0x7ffd_0000_0100, false), + runs: runs.clone(), + landed: landed.clone(), + subs: u64::MAX, + }; + released(OWNER); + let list = host.new_list().unwrap(); + list.add_texture_back(back); + list.close(); + host.execute(&[&list]); + assert_eq!((runs.load(Ordering::SeqCst), landed.load(Ordering::SeqCst)), (1, 1)); + host.execute(&[&list]); + assert_eq!((runs.load(Ordering::SeqCst), landed.load(Ordering::SeqCst)), (2, 2)); + } + + /// On the host, with the read-back pool on: a buffer a landing still + /// held in place when its list was reset (the writer behind the title, + /// which is told at the landing) goes to the pool when the landing goes, + /// its reference then the last (it was never pooled: the landing's own + /// reference still stood while it asked). + #[test] + fn a_buffer_read_in_place_goes_to_the_pool_after_its_landing() { + use windows::core::Interface; + const OWNER: usize = 0x7e57_bac3; + let Some(host) = crate::host::host() else { return }; + if !crate::toggled!("LEONIDA_READ_BACK_POOL") { + return; + } + let layout = leonida_formats::texture::Layout::new(&leonida_formats::texture::Desc { + dimension: leonida_formats::texture::Dimension::Tex2d, + width: 64, + height: 1, + depth: 1, + mips: 1, + element_bytes: 4, + block: 1, + samples: 1, + swizzle: leonida_formats::texture::Swizzle::LINEAR, + }) + .unwrap(); + // (A size no other test reads back, so none takes it from the pool.) + let buffer = host.read_back_buffer(23 << 16).unwrap(); + let raw = buffer.as_raw() as usize; + let back = Back { + buffer, + footprints: vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Width: 64, Height: 1, Depth: 1, RowPitch: 256, ..Default::default() }, + }], + rows: vec![1], + mips: 1, + layout, + ticket: track(OWNER, 0x7ffd_0001_0000, 0x7ffd_0001_0100, false), + runs: Arc::new(AtomicU64::new(0)), + landed: Arc::new(AtomicU64::new(0)), + subs: u64::MAX, + }; + TEST_MAPPED.set(Some(true)); + back.submitted(); + let landing = landing(&back).unwrap(); + assert!(matches!(landing.data, Texels::Mapped(_))); + TEST_MAPPED.set(None); + // The list's reset while the landing waits for the writer: its + // reference is not the last, so it is let go. + crate::host::give_read_back(back.into_buffer()); + assert!(!crate::host::read_back_kept(raw)); + drop(landing); + assert!(crate::host::read_back_kept(raw), "the landing's reference, the last, gave the buffer to the pool"); + released(OWNER); + } } diff --git a/d3d12/crates/leonida-gpu/src/texture.rs b/d3d12/crates/leonida-gpu/src/texture.rs index 8ad760157d..dfd9c3f294 100644 --- a/d3d12/crates/leonida-gpu/src/texture.rs +++ b/d3d12/crates/leonida-gpu/src/texture.rs @@ -3,19 +3,25 @@ //! atlases. Such a texture lives in console memory in its tiled layout; //! before a submission samples its host copy, the memory is detiled into a //! staging buffer when its content changed, and the staging buffer is -//! copied into the host texture. +//! copied into the host texture. What the texture was detiled from is kept; +//! the staging buffer goes once the copy of it is recorded, unless the +//! texture changes often ([`release_staging`]). //! //! "Changed" means a page of the memory was written since the last detiling //! ([`crate::watch`]), in write-watched memory; in physical-page views, //! which cannot be watched, a content hash of the whole memory at every //! submission that samples it. //! -//! shortcut: a change detiles the whole texture, not the pages written. +//! shortcut: a change detiles the whole texture, not the pages written, +//! but in write-watched memory, where the subresources the written pages +//! hold are detiled and copied alone once the texture keeps its staging +//! buffer ([`texture_parts`]); a hashed or guarded one is detiled whole. //! Only textures read through descriptor tables are brought up to date //! (directly indexed views are not known per draw); plane 0 is uploaded //! (every mip and array slice), depth and stencil planes are not. pub(crate) mod ahead; +mod table; use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -32,19 +38,58 @@ macro_rules! once { }}; } -/// A texture's upload state: the staging buffer laid out as the host -/// texture's subresources, and what was last detiled. -pub(crate) struct Staging { - /// A buffer of its own, or the block [`Staging::piece`] is part of. +/// A staging buffer's memory: write-combined upload memory laid out as the +/// host texture's subresources ([`Staging::footprints`]). Counted in +/// `STAGED` while it lives; the last of its texture and the lists that +/// copy from it to let go frees it (a piece of a pool block goes back to +/// the pool, which gives it out again only [`crate::pool`]'s rest later). +pub(crate) struct Staged { + /// A buffer of its own, or the block `_piece` is part of. buffer: ID3D12Resource, /// Where in `buffer` it begins (the footprints count from there). base: u64, - /// Back in the pool with the last list that names it. + /// Back in the pool with the last owner. _piece: Option<crate::pool::StagingPiece>, - /// Its bytes. + data: *mut u8, + /// Its bytes (the texture's [`Staging::bytes`]). + bytes: u64, +} + +// SAFETY: the mapping is written only by a texture's detiling, under its +// `last` lock, and read by the card; the buffer is free-threaded. +unsafe impl Send for Staged {} +// SAFETY: as above. +unsafe impl Sync for Staged {} + +impl Drop for Staged { + fn drop(&mut self) { + use std::sync::atomic::Ordering::Relaxed; + STAGED[0].fetch_sub(1, Relaxed); + STAGED[1].fetch_sub(self.bytes, Relaxed); + } +} + +/// A texture's upload state: what was last detiled and uploaded, kept while +/// the texture is sampled, and the staging buffer it is detiled into, kept +/// only from a detiling until the copy of it is recorded +/// ([`release_staging`]). +pub(crate) struct Staging { + /// The staging buffer, if the texture has one now: made with the + /// texture's staging state, let go once a list's prelude copied it + /// (that list holds it until it has run), and made again by the next + /// detiling ([`Staging::bytes_to_fill`]). + staged: Mutex<Option<Arc<Staged>>>, + /// The host texture's description and the title's resource, to name a + /// buffer made again. + desc: D3D12_RESOURCE_DESC, + resource: usize, + /// The staging buffer's bytes. #[cfg(feature = "diagnostics")] size: u64, - data: *mut u8, + /// When the last two detilings ran ([`crate::host::coarse_ms`]; 0: + /// none): a texture detiled again within [`HOT_STAGING_MS`] keeps its + /// staging buffer ([`keeps_staging`]). + detiled_ms: [std::sync::atomic::AtomicU64; 2], footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>, rows: Vec<u32>, layout: leonida_formats::texture::Layout, @@ -62,7 +107,7 @@ pub(crate) struct Staging { /// Made by the pass over textures picked by index, for one upload /// ([`once`]): read when the list is submitted, and never looked at again. once: std::sync::atomic::AtomicBool, - /// The staging buffer's bytes (counted in `STAGED` while it lives). + /// The staging buffer's bytes, whether it has one now or not. bytes: u64, memory: *const u8, /// Whether the guard may stand for a hash of this texture (LOCAL, @@ -77,6 +122,9 @@ pub(crate) struct Staging { /// of 1,120 textures in one frame of run 18.) dirty: std::sync::atomic::AtomicBool, uploaded: std::sync::atomic::AtomicBool, + /// Of the staging buffer's parts, those detiled since a list's prelude + /// last took them to copy ([`texture_parts`]; `None`: all of them). + parts_dirty: Mutex<Option<Parts>>, /// When a list last recorded a use of it (`crate::host::moment`). used: std::sync::atomic::AtomicU64, /// How many bytes of the texture's memory were mapped when a list last @@ -100,6 +148,10 @@ pub(crate) struct Staging { /// (`title_memory_reading`) instead of taking `no_wait()` / /// `refresh_unlocked()` or the 30-frame partial-read throttle. exact: std::sync::atomic::AtomicBool, + /// For a video's plane ([`Staging::movie_plane`], [`plane_same`]): the + /// digest of the plane a prelude last gave its host copy (`None`: none + /// yet, or a list's own copy came after it, not known here). + plane_on_card: Mutex<Option<Digest>>, } /// What a texture's staging buffer holds: the hash of the memory detiled @@ -171,11 +223,127 @@ fn blind_hot_frames() -> u64 { /// the start (the six-star screen of the first seconds, which the hash /// never caught changing). `LEONIDA_TEXTURE_HOT=0`: every eighth frame /// only, as before. +/// +/// Re-checked after `LEONIDA_VIEW_GUARD` (`crate::watch`'s header), which +/// opens every view of a page when the title writes through any of them: +/// the writes this was made for are seen by the guard now, but the start +/// stays hot, since writes the guard does not see remain and none of them +/// is counted apart. A page shown in more than `watch::MANY_VIEWS` places +/// is guarded at each address for itself. A plain read that finishes +/// (`watch::title_memory_written` without `pages`) opens no guard unless +/// `LEONIDA_PAGE_WRITES` has bit 4 (off by default): a block guarded again +/// while the read was in the air is found changed by the hash alone. With +/// `LEONIDA_PAGE_WRITES=0` or `slots`, DirectStorage's writes into physical +/// pages open none either (10,000 to 50,000 guarded blocks lay under them +/// in every run, `watch::page_writes`). Nothing measured says how many of +/// the changes found in a texture's first 64 frames came those ways; the +/// frame line's "changes the guard did not see" (`copystat::C::TexHot`) on +/// a streaming run with the default switches is the count to take first. +/// Near none would let a texture start cold, keeping the every-eighth-frame +/// turn and the hot frames after a change found. fn hot_textures() -> bool { static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_HOT").is_none_or(|v| v != "0")) } +/// Whether a texture's staging buffer is let go once a list's prelude has +/// recorded the copy of it, unless the texture is detiled often +/// ([`keeps_staging`]); `LEONIDA_STAGING_RELEASE=0`: kept with the texture's +/// staging state until the sweep lets go of both, as before. Only with +/// [`prelude_upload`]: a list that records the copy itself names the buffer +/// before the detiling at its submission fills it. +/// +/// Nothing on the CPU reads a staging buffer after the copy, and the next +/// copy follows a detiling that writes it whole: the buffer was a third copy +/// of every sampled texture's bytes (beside title memory and the card's), +/// kept up to five minutes with 12 GiB of the PC's memory free +/// (`crate::host::ram_idle_ms`): 2,246 buffers and 2.1 GB at the end of run +/// 24, 5.2 GB of staging blocks in run crash-1 (`crate::pool`). What tells +/// whether the texture changed (its hash, the write-watch asking, the +/// guard's turn) stays with the staging state, so an unchanged texture is +/// not detiled or uploaded again; a changed one gets a buffer at the +/// detiling (a cut from a pool block, or the allocation the first upload +/// made too). The list that copied it holds it until it is reset, after its +/// last submission ran; then it goes back to the pool. +fn release_staging() -> bool { + prelude_upload() && crate::toggled!("LEONIDA_STAGING_RELEASE") +} + +/// Milliseconds within which a texture detiled twice keeps its staging +/// buffer ([`keeps_staging`]): longer than a pool piece rests before it is +/// given out again (`crate::pool`, 2.5 s), so a texture that changes more +/// often than that (a glyph atlas, a texture still streaming in, a video's +/// ring) holds one buffer, not one resting piece per change. +const HOT_STAGING_MS: u64 = 3000; + +/// Whether a texture last detiled at `last` (and before that at `previous`; +/// 0: never) keeps its staging buffer at `now` (all [`crate::host::coarse_ms`]): +/// it was detiled twice within `keep_ms` and the last time within `keep_ms` +/// too. Else the buffer goes after the copy. +fn keeps_staging([last, previous]: [u64; 2], now: u64, keep_ms: u64) -> bool { + previous != 0 && last.saturating_sub(previous) < keep_ms && now.saturating_sub(last) < keep_ms +} + +#[cfg(test)] +thread_local! { + /// A test's [`HOT_STAGING_MS`], for the copies its thread's submissions + /// claim. + static TEST_HOT_STAGING_MS: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) }; +} + +fn hot_staging_ms() -> u64 { + #[cfg(test)] + if let Some(ms) = TEST_HOT_STAGING_MS.get() { + return ms; + } + HOT_STAGING_MS +} + +/// For tests: the title resources whose staging buffer cannot be had (as +/// with no room for one), on whichever thread it is asked for. +#[cfg(test)] +static TEST_NO_STAGED: Mutex<Vec<usize>> = Mutex::new(Vec::new()); + +/// The memory of a staging buffer of `total` bytes for host texture `d` of +/// title resource `resource`: a piece of a pool block, or a buffer of its +/// own (zeros, as new memory). Counted in `STAGED`. A piece the pool gives +/// out again holds what it held unless `zeroed` ([`crate::pool::staging`]). +fn new_staged( + host: &crate::host::Host, + resource: usize, + d: &D3D12_RESOURCE_DESC, + total: u64, + zeroed: bool, +) -> Option<Arc<Staged>> { + #[cfg(test)] + if TEST_NO_STAGED.lock().unwrap_or_else(|e| e.into_inner()).contains(&resource) { + return None; + } + let (piece, buffer, base, data) = match crate::pool::staging(host, total, zeroed) { + Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data), + None => { + let speculative = PICKING.get().is_some() && !BAKING.get(); + if crate::residency::upload_refused() + || (speculative && !crate::residency::allow_staging_growth(false)) + { + crate::residency::note_staging_deferred(); + return None; + } + let (buffer, data) = host.upload_buffer(total)?; + crate::host::name(&buffer, || { + format!( + "staging of {:#x} {}x{}x{} f{}", + resource, d.Width, d.Height, d.DepthOrArraySize, d.Format.0 + ) + }); + (None, buffer, 0, data) + } + }; + STAGED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + STAGED[1].fetch_add(total, std::sync::atomic::Ordering::Relaxed); + Some(Arc::new(Staged { buffer, base, _piece: piece, data, bytes: total })) +} + /// Whether a guarded texture the guard saw no write to, whose last /// [`backoff_after`] looks behind the guard found it as it was, takes only one /// of every [`backoff_every`] of its turns (`LEONIDA_TEXTURE_HASH_BACKOFF`, off @@ -224,7 +392,13 @@ unsafe impl Send for Staging {} // SAFETY: as above. unsafe impl Sync for Staging {} -static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None); +static STAGING: table::Table<Staging> = Mutex::new(None); + +/// Staging states taken out of [`STAGING`] by a texture's release or an +/// [`unstage`], counted under its lock: a state made meanwhile with the lock +/// let go ([`table::get_or_make`]) goes in only if its texture's host copy +/// is there yet. A release waits for a make of its texture's state. +static STAGING_GONE: table::Gone = table::Gone::new(); /// The buffer a texture the host writes is copied through into the texture /// of a view the title placed in its memory in another format @@ -1006,23 +1180,106 @@ fn waited<T>(slot: usize, f: impl FnOnce() -> T) -> T { thread_local! { /// Room to read a texture's memory into: one buffer per submitting - /// thread. Each texture kept its own, a second copy in memory of every - /// write-watched or partly mapped texture ever sampled, for the run. + /// thread, of up to [`read_kept`] bytes. Each texture kept its own, a + /// second copy in memory of every write-watched or partly mapped texture + /// ever sampled, for the run. static READ: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) }; } -/// Calls `f` with `size` bytes of this thread's read buffer (their -/// contents are whatever the last texture left). +/// Read buffers of textures larger than [`read_kept`], shared by the threads +/// that refresh textures, each with when it was given back +/// ([`crate::host::coarse_ms`]). A thread's own buffer only grew, so each of +/// those threads (the submitting one and the helpers of +/// `crate::shadow::wide_each`, which live for the run) kept the room of the +/// largest texture it ever read until the end: 22 MB for a 4096² BC7 texture +/// with its levels, 89 MB for one in RGBA8, on each of them (five on a PC of +/// 16 logical processors). Here such a buffer is still reused by the reads +/// that come one after another while the world streams in, and the sweep +/// lets it go once no read took it for a while ([`let_go_idle_reads`]). +static LARGE_READS: Mutex<Vec<(Vec<u8>, u64)>> = Mutex::new(Vec::new()); + +/// Calls `f` with `size` bytes of read buffer (their contents are whatever +/// the last texture left). fn with_read<R>(size: usize, f: impl FnOnce(&mut [u8]) -> R) -> R { + if size > read_kept() { + let mut read = take_read(&mut LARGE_READS.lock().unwrap_or_else(|e| e.into_inner()), size); + if read.len() < size { + // None there was large enough (or none was there): the largest + // goes before a new one is made, outside the lock. The new one + // is asked for zeroed, which lets the allocator skip writing + // pages that come fresh from the system. + drop(read); + read = vec![0u8; size]; + } + let out = f(&mut read[..size]); + let now = crate::host::coarse_ms(); + LARGE_READS.lock().unwrap_or_else(|e| e.into_inner()).push((read, now)); + return out; + } READ.with(|read| { let mut read = read.borrow_mut(); if read.len() < size { - read.resize(size, 0); + // Exactly the room asked for, which stays under [`read_kept`]: + // grown by doubling, it could be twice that. The old contents + // need no copy. + *read = vec![0u8; size]; } f(&mut read[..size]) }) } +/// A buffer for a read of `size` bytes from `pool`: the smallest there that +/// is large enough, or else the largest, which the caller makes again larger; +/// empty if the pool is. So the pool holds no more buffers than reads ran at +/// once, each at most the size of the largest texture read. +fn take_read(pool: &mut Vec<(Vec<u8>, u64)>, size: usize) -> Vec<u8> { + let fit = pool + .iter() + .enumerate() + .filter(|(_, (read, _))| read.len() >= size) + .min_by_key(|(_, (read, _))| read.len()) + .or_else(|| pool.iter().enumerate().max_by_key(|(_, (read, _))| read.len())) + .map(|(i, _)| i); + fit.map(|i| pool.swap_remove(i).0).unwrap_or_default() +} + +/// Takes out of `pool` the buffers given back `idle_ms` or more before +/// `now`. +fn idle_reads(pool: &mut Vec<(Vec<u8>, u64)>, now: u64, idle_ms: u64) -> Vec<(Vec<u8>, u64)> { + pool.extract_if(.., |(_, at)| now.saturating_sub(*at) >= idle_ms).collect() +} + +/// Lets go of the read buffers of large textures no read took for `idle_ms` +/// ([`crate::host::ram_idle_ms`]). They are freed on the reaper thread, not +/// on the submitting thread that runs the sweep under the submission lock: +/// freeing tens of MB of touched memory takes milliseconds, which the next +/// submission (and with nothing in flight, the card) would wait for. The +/// sweep may run behind flights in the air (`LEONIDA_SWEEP_NO_SETTLE`): the +/// pool holds only buffers given back, and `retire` keeps them past every +/// submission running. +fn let_go_idle_reads(idle_ms: u64) { + let now = crate::host::coarse_ms(); + let gone = idle_reads(&mut LARGE_READS.lock().unwrap_or_else(|e| e.into_inner()), now, idle_ms); + if !gone.is_empty() { + crate::host::retire(gone); + } +} + +/// The bytes of read buffer a thread keeps for itself from one texture to +/// the next (`LEONIDA_TEXTURE_READ_KEEP_MB`, 16); larger textures are read +/// into [`LARGE_READS`]. That holds a 4096² BC1 texture or a 2048² BC7 one +/// with their levels (11 and 5.6 MB) without a lock. +fn read_kept() -> usize { + static KEPT: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + *KEPT.get_or_init(|| { + std::env::var("LEONIDA_TEXTURE_READ_KEEP_MB") + .ok() + .and_then(|v| v.trim().parse::<usize>().ok()) + .unwrap_or(16) + .saturating_mul(1 << 20) + }) +} + /// Whether a texture all of whose memory is mapped is read through the /// kernel's copy instead of in place (`LEONIDA_TEXTURE_COPY=1`; off by /// default). Round 3 of the memory work read every such texture that way @@ -1037,6 +1294,128 @@ fn through_copy() -> bool { *ON.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_COPY").is_some_and(|v| v == "1")) } +/// Whether a write-watched texture whose memory is all there is detiled +/// straight out of title memory, not out of a copy of it in the thread's +/// read buffer (`LEONIDA_TEXTURE_WATCHED_IN_PLACE=1`; **off by default**). +/// +/// The copy was there because the title's own threads free, decommit and +/// protect write-watched memory whenever they like (the title's +/// `VirtualFree` and `VirtualProtect`, `crate::inplace::title_memory_free` +/// and `title_memory_protect`), without the lock the runtime takes to +/// change a mapping (`crate::watch::title_memory_reading`, which covers +/// views only): a read in place of a page taken away faults on the +/// submitting thread, where the kernel's copy, or the copy that takes the +/// fault, reads zeros (`title_memory_tests::an_uncommitted_tail_reads_as_zeros` +/// takes a page away between two reads). It cost one copy of every watched +/// byte detiled, through a buffer of up to 16 MiB that each refreshing +/// thread keeps for the run ([`read_kept`]). +/// +/// With the switch the read in place stands on three things: the range lock +/// against the runtime's mappings, its page check ([`committed`], after the +/// two below are held), and [`InPlaceRead`]: the title's frees and +/// protections that go through the runtime ([`title_memory_going`], from +/// `crate::inplace`) wait until no read in place of their pages is under +/// way, and a read does not begin while one of them is. Tearing is as with +/// the copy: the write watch was asked before the read, so a write during +/// it is the next refresh's either way. +/// +/// Off by default because what it costs and what it leaves are not +/// measured: a title thread's free or protection of memory a texture is +/// detiled from now waits for that detiling (a millisecond or so for a +/// large texture), and memory taken away by any route other than those +/// (none known) would fault instead of reading zeros. +fn watched_in_place() -> bool { + #[cfg(test)] + if let Some(on) = TEST_IN_PLACE.get() { + return on; + } + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_WATCHED_IN_PLACE").is_some_and(|v| v == "1")) +} + +/// Reads of title memory in place under way ([`InPlaceRead`]) and the +/// title's frees and protections under way ([`title_memory_going`]), each +/// as first and past the last byte. +struct InPlace { + reading: Vec<(usize, usize)>, + going: Vec<(usize, usize)>, +} + +static IN_PLACE: Mutex<InPlace> = Mutex::new(InPlace { reading: Vec::new(), going: Vec::new() }); +static IN_PLACE_DONE: std::sync::Condvar = std::sync::Condvar::new(); + +fn in_place() -> std::sync::MutexGuard<'static, InPlace> { + IN_PLACE.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn meet((a, b): (usize, usize), (c, d): (usize, usize)) -> bool { + a < d && c < b +} + +/// A read of title memory in place that the title's frees and protections +/// of its pages wait for ([`watched_in_place`]). +struct InPlaceRead(usize, usize); + +impl InPlaceRead { + /// For a read of `[at, at + len)`: `None` while a free or protection of + /// the title's of any of it is under way (the caller reads through the + /// copy then). One that comes later waits for the read. + fn begin(at: usize, len: usize) -> Option<InPlaceRead> { + let read = (at, at.saturating_add(len)); + let mut g = in_place(); + if g.going.iter().any(|&going| meet(going, read)) { + return None; + } + g.reading.push(read); + Some(InPlaceRead(read.0, read.1)) + } +} + +impl Drop for InPlaceRead { + fn drop(&mut self) { + let mut g = in_place(); + if let Some(i) = g.reading.iter().position(|&r| r == (self.0, self.1)) { + g.reading.swap_remove(i); + } + drop(g); + IN_PLACE_DONE.notify_all(); + } +} + +/// A free or protection of the title's under way ([`title_memory_going`]); +/// `None` with the switch off, where nothing was registered. +pub(crate) struct Going(Option<(usize, usize)>); + +impl Drop for Going { + fn drop(&mut self) { + let Some(going) = self.0 else { return }; + let mut g = in_place(); + if let Some(i) = g.going.iter().position(|&r| r == going) { + g.going.swap_remove(i); + } + } +} + +/// The title frees, decommits or protects `[at, at + len)` (`len` 0: the +/// whole allocation at `at`, of unknown end): once no read of those pages +/// in place is under way ([`InPlaceRead`]); none begins until what this +/// returns is dropped. While nothing reads in place, a lock not otherwise +/// contended, taken twice; with [`watched_in_place`] off (the default), +/// where no read in place begins, nothing at all, as before it (every +/// title free and protection took the lock twice and pushed to a list). +pub(crate) fn title_memory_going(at: usize, len: usize) -> Going { + if !watched_in_place() { + return Going(None); + } + let going = (at, if len == 0 { usize::MAX } else { at.saturating_add(len) }); + let mut g = in_place(); + g.going.push(going); + while g.reading.iter().any(|&read| meet(read, going)) { + g = IN_PLACE_DONE.wait(g).unwrap_or_else(|e| e.into_inner()); + } + Going(Some(going)) +} + /// Calls `f` with the `size` bytes of title memory at `memory`, read /// through the kernel into this thread's read buffer; pages that are not /// there read as zeros. The bytes are those a read in place would see. @@ -1048,21 +1427,13 @@ fn with_title<R>(memory: *const u8, size: usize, f: impl FnOnce(&[u8]) -> R) -> } /// Staging buffers alive (also those only a list still holds) and their -/// bytes. +/// bytes ([`Staged`]). static STAGED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; pub(crate) fn live_staging_bytes() -> u64 { STAGED[1].load(std::sync::atomic::Ordering::Relaxed) } -impl Drop for Staging { - fn drop(&mut self) { - use std::sync::atomic::Ordering::Relaxed; - STAGED[0].fetch_sub(1, Relaxed); - STAGED[1].fetch_sub(self.bytes, Relaxed); - } -} - /// For the memory line: staging buffers alive, their bytes, and how many /// of them their texture still has (the others wait for a list's reset). #[cfg(feature = "diagnostics")] @@ -1072,56 +1443,125 @@ pub(crate) fn memory() -> [u64; 3] { .lock() .unwrap_or_else(|e| e.into_inner()) .as_ref() - .map_or(0, |map| map.len() as u64); + .map_or(0, |map| map.values().filter(|s| s.staged().is_some()).count() as u64); [STAGED[0].load(Relaxed), STAGED[1].load(Relaxed), kept] } -/// Staging buffers let go as idle since the start, and their bytes. +/// Staging states let go as idle since the start (with their buffer or +/// without), and the bytes of the buffers that went with them. static LET_GO: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; -/// For the memory line: staging buffers let go as idle, and their bytes. +/// For the memory line: staging states let go as idle, and the bytes of the +/// buffers that went with them. #[cfg(feature = "diagnostics")] pub(crate) fn let_go() -> [u64; 2] { use std::sync::atomic::Ordering::Relaxed; [LET_GO[0].load(Relaxed), LET_GO[1].load(Relaxed)] } -/// Lets go of the staging buffers no list recorded a use of for `IDLE_MS` -/// and `IDLE_FRAMES` frames and no list holds: a staging buffer is system memory the size of its -/// texture, kept so that an unchanged texture is not uploaded again, and -/// those of textures no longer sampled were kept for the run (2,246 of -/// them, 2.1 GB, at the end of run 24). The next list that samples such a -/// texture makes a staging buffer anew, detiles and uploads once more. +/// Lets go of the staging states no list recorded a use of for `IDLE_MS` +/// and `IDLE_FRAMES` frames and no list holds, with the staging buffer of +/// one that still has it. A staging state is kept so that an unchanged +/// texture is not detiled and uploaded again; its buffer, system memory +/// the size of its texture, it keeps only while the texture changes often +/// (else it goes once its copy is recorded, [`release_staging`], and +/// [`let_go_cold`] here takes it when the texture stops changing). Those +/// of textures no longer sampled were kept for the run (2,246 buffers, +/// 2.1 GB, at the end of run 24). The next list that samples such a +/// texture makes a staging state anew, detiles and uploads once more. +/// Read buffers of large textures no read took for `idle_ms` go too +/// ([`let_go_idle_reads`]), whether or not there are staging states. /// Called before a submission starts, by the thread that submits. pub(crate) fn let_go_idle() { use std::sync::atomic::Ordering::Relaxed; const IDLE_FRAMES: u64 = 4; - let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); - let Some(map) = map.as_mut() else { - return; - }; - if map.is_empty() { - return; - } let idle_ms = crate::host::ram_idle_ms(crate::residency::headroom()); - // A list that recorded an upload or a check holds the staging until it - // is reset: one only the table holds is named by no list, recorded or - // running. + let_go_idle_reads(idle_ms); + // What goes, buffers and states, goes with the table's lock let go + // (`LEONIDA_STAGING_SHORT`, [`table::sweep`]). let (mut went, mut bytes) = (0u64, 0u64); - map.retain(|_, s| { - let keep = Arc::strong_count(s) > 1 - || !crate::host::long_ago(s.used.load(Relaxed), idle_ms, IDLE_FRAMES); - if !keep { - LET_GO[0].fetch_add(1, Relaxed); - LET_GO[1].fetch_add(s.bytes, Relaxed); + table::sweep( + &STAGING, + table::short(), + |map| { + let mut taken = Vec::new(); + let_go_cold(map.values(), crate::host::coarse_ms(), hot_staging_ms(), &mut taken); + taken + }, + // A list that recorded an upload or a check holds the staging until + // it is reset: one only the table holds is named by no list, recorded + // or running. + |s| { + let keep = Arc::strong_count(s) > 1 + || !crate::host::long_ago(s.used.load(Relaxed), idle_ms, IDLE_FRAMES); + if !keep { + // (Its staging buffer, if it still had one, goes with it.) + let had = if s.staged().is_some() { s.bytes } else { 0 }; + LET_GO[0].fetch_add(1, Relaxed); + LET_GO[1].fetch_add(had, Relaxed); + went += 1; + bytes += had; + } + keep + }, + ); + if went > 0 { + crate::host::trail(|| format!("sweep: {went} staging states of textures let go ({} KiB of buffers), held by no list", bytes >> 10)); + } +} + +/// Lets go of the staging buffers of textures that kept theirs as detiled +/// often ([`keeps_staging`]) and were not detiled within `keep_ms` of +/// `now` since ([`crate::host::coarse_ms`]), once a list copied what they +/// hold: the texture stopped changing (a video ended, a texture streamed +/// in). What a list still copies from such a buffer it holds itself. A +/// texture being detiled now (its `last` lock taken) is passed over; one +/// detiled between the look and the letting go is found without a buffer +/// at its copy and detiled again ([`PreludeUpload::claim`]). Returns how +/// many went; the buffers go into `taken`, for the caller to let go of +/// ([`let_go_idle`]: after the table's lock). +fn let_go_cold<'a>( + stagings: impl Iterator<Item = &'a Arc<Staging>>, + now: u64, + keep_ms: u64, + taken: &mut Vec<Arc<Staged>>, +) -> u64 { + use std::sync::atomic::Ordering::Relaxed; + if !release_staging() { + return 0; + } + let mut went = 0; + for s in stagings { + if s.staged().is_none() + || !s.uploaded.load(Relaxed) + || s.dirty.load(Relaxed) + || keeps_staging(s.detiled(), now, keep_ms) + { + continue; + } + let Ok(_last) = s.last.try_lock() else { + continue; + }; + if let Some(staged) = s.let_go_staged() { + taken.push(staged); went += 1; - bytes += s.bytes; + RELEASED[0].fetch_add(1, Relaxed); + RELEASED[1].fetch_add(s.bytes, Relaxed); } - keep - }); - if went > 0 { - crate::host::trail(|| format!("sweep: {went} staging buffers of textures let go ({} KiB), held by no list", bytes >> 10)); } + went +} + +/// Staging buffers let go once a list copied them ([`release_staging`]) since +/// the start, and their bytes; and the buffers made again by a detiling. +static RELEASED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// For the memory line: staging buffers let go once copied, their bytes, and +/// those made again ([`RELEASED`]). +#[cfg(feature = "diagnostics")] +pub(crate) fn released() -> [u64; 3] { + use std::sync::atomic::Ordering::Relaxed; + [RELEASED[0].load(Relaxed), RELEASED[1].load(Relaxed), RELEASED[2].load(Relaxed)] } /// Textures the host GPU wrote by a copy or resolve: their contents are on @@ -1149,11 +1589,125 @@ pub(crate) fn host_written(resource: This) { } } -/// The title memory of textures the host copied into, by address: bytes -/// and description words 4, 6, 7 and 8 (width, height, layers and levels, -/// format). -static HOST_WRITTEN_AT: Mutex<std::collections::BTreeMap<u64, (u64, u32, u32, u32, u32, usize)>> = - Mutex::new(std::collections::BTreeMap::new()); +/// The title memory of textures the host copied into ([`HostWrittenAt`]). +static HOST_WRITTEN_AT: Mutex<HostWrittenAt> = Mutex::new(HostWrittenAt::new()); + +/// What [`HostWrittenAt`] keeps of a texture the host copied into: bytes, +/// description words 4, 6, 7 and 8 (width, height, layers and levels, +/// format) and the resource. +type WrittenAt = (u64, u32, u32, u32, u32, usize); + +/// The title memory of textures the host copied into, by address +/// ([`placed_in_host_written`] looks a placed view up in it), and the +/// address of each resource there, for its release ([`forget`]). The +/// release looked at every entry (`BTreeMap::retain` under the global +/// lock) for every resource the title released, buffers too: O(n) in the +/// textures the host ever copied into that are still alive. Now one lookup +/// and at most one removal. +struct HostWrittenAt { + by_address: std::collections::BTreeMap<u64, WrittenAt>, + address_of: HashMap<usize, u64, std::hash::BuildHasherDefault<std::collections::hash_map::DefaultHasher>>, + /// Entries looked at by [`HostWrittenAt::forget`], for the test. + #[cfg(test)] + looked: u64, +} + +impl HostWrittenAt { + const fn new() -> HostWrittenAt { + HostWrittenAt { + by_address: std::collections::BTreeMap::new(), + address_of: HashMap::with_hasher(std::hash::BuildHasherDefault::new()), + #[cfg(test)] + looked: 0, + } + } + + /// The host copied into the texture `written.5`, whose memory is at + /// `at`. One noted at `at` before (another resource over the same + /// memory) is noted nowhere now, as the map always had it. + fn insert(&mut self, at: u64, written: WrittenAt) { + if let Some(before) = self.by_address.insert(at, written) + && before.5 != written.5 + && self.address_of.get(&before.5) == Some(&at) + { + self.address_of.remove(&before.5); + } + self.address_of.insert(written.5, at); + } + + /// The noted texture whose memory holds `address`, and where it starts. + fn holding(&self, address: u64) -> Option<(u64, WrittenAt)> { + self.by_address + .range(..=address) + .next_back() + .filter(|(at, d)| address < **at + d.0) + .map(|(at, d)| (*at, *d)) + } + + /// `resource` was released: its memory is no longer that of a texture + /// the host copied into. + fn forget(&mut self, resource: usize) { + let Some(at) = self.address_of.remove(&resource) else { + return; + }; + #[cfg(test)] + { + self.looked += 1; + } + if self.by_address.get(&at).is_some_and(|d| d.5 == resource) { + self.by_address.remove(&at); + } + } +} + +#[cfg(test)] +mod host_written_at_tests { + use super::HostWrittenAt; + + /// Releases look at the released resource's entry alone: a thousand + /// textures the host copied into, then a thousand other releases and the + /// thousand textures' own, are a thousand entries looked at (the retain + /// looked at every entry for each release: about 1.5 million here). + #[test] + fn a_release_looks_at_its_own_entry_only() { + let mut map = HostWrittenAt::new(); + const N: u64 = 1000; + let at = |i: u64| 0x10_0000_0000 + i * 0x1_0000; + for i in 0..N { + map.insert(at(i), (0x1_0000, 64, 64, 1, 28, 0x5000 + i as usize)); + } + // A view inside the fifth texture's memory finds it; one past the + // last does not. + assert_eq!(map.holding(at(5) + 0x100).map(|(a, d)| (a, d.5)), Some((at(5), 0x5005))); + assert!(map.holding(at(N)).is_none()); + // Releases of resources never noted (buffers, other textures). + for i in 0..N { + map.forget(0x9000_0000 + i as usize); + } + assert_eq!(map.by_address.len(), N as usize); + for i in 0..N { + map.forget(0x5000 + i as usize); + } + assert!(map.by_address.is_empty() && map.address_of.is_empty()); + assert!(map.looked <= N, "{} entries looked at for {} releases", map.looked, 2 * N); + } + + /// Another texture noted over the same memory takes the place: the one + /// before is noted nowhere, and its release leaves the new one. + #[test] + fn a_texture_over_the_same_memory_takes_the_place() { + let mut map = HostWrittenAt::new(); + map.insert(0x2000_0000, (0x4_0000, 256, 256, 1, 28, 1)); + map.insert(0x2000_0000, (0x2_0000, 128, 128, 1, 28, 2)); + assert_eq!(map.holding(0x2001_0000).map(|(_, d)| d.5), Some(2)); + assert!(map.holding(0x2003_0000).is_none(), "the new one's size counts"); + map.forget(1); + assert_eq!(map.holding(0x2000_0000).map(|(_, d)| d.5), Some(2)); + map.forget(2); + assert!(map.holding(0x2000_0000).is_none()); + assert!(map.address_of.is_empty()); + } +} /// A texture the title placed at `address` (description words `desc`) was /// made: says so once if it lies in the memory of a texture the host @@ -1166,13 +1720,7 @@ pub(crate) fn placed_in_host_written(address: u64, desc: &[u32; 14]) { if crate::texback::copies_back() { return; } - let hit = { - let map = HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()); - map.range(..=address) - .next_back() - .filter(|(at, d)| address < **at + d.0) - .map(|(at, d)| (*at, *d)) - }; + let hit = HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()).holding(address); if let Some((at, (bytes, width, height, layers_levels, format, _))) = hit { static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 200 { @@ -1263,12 +1811,19 @@ fn written_by_another(resource: usize, list: usize) -> bool { .is_some_and(|by| by != list) } -/// The title released a resource. +// Calls of `forget` on this thread, for the tests. +#[cfg(test)] +thread_local!(pub(crate) static FORGOTTEN: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }); + +/// The title released a texture (buffers are in none of these maps, and +/// their release does not come here). pub(crate) fn forget(resource: usize) { - let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(map) = map.as_mut() { - map.remove(&resource); - } + #[cfg(test)] + FORGOTTEN.with(|n| n.set(n.get() + 1)); + // A make of its staging state under way is waited for: it reads the + // texture, which goes when this returns. `LEONIDA_STAGING_SHORT=0`: the + // table's lock held to the end, as before. + let _held = table::take_out(&STAGING, resource, &STAGING_GONE, table::short(), true); let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); if let Some(set) = set.as_mut() { set.remove(&resource); @@ -1279,7 +1834,7 @@ pub(crate) fn forget(resource: usize) { } // Its memory may be given to other textures now (run 177: most of the // "HERO LEAD" lines were views in memory a released texture had held). - HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, d| d.5 != resource); + HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()).forget(resource); let mut through = THROUGH.lock().unwrap_or_else(|e| e.into_inner()); if let Some(through) = through.as_mut() { through.remove(&resource); @@ -1376,6 +1931,134 @@ pub(crate) fn digest(bytes: &[u8]) -> Digest { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Digest(u128); +/// Whether a write-watched texture a write touched only part of is detiled +/// and copied to the card only in the subresources the written pages hold +/// (`LEONIDA_TEXTURE_PARTS=0`: the whole texture, every level and array +/// slice, as before). +/// +/// The write watch says which 64 KiB pages of a texture were written since +/// its last detiling, but any write read all of its memory again, detiled +/// every level of every slice, and the prelude copied all of them to the +/// card: a texture array, a cube or an atlas whose title rewrites one slice +/// or one level paid for all of them. Now the pages written are mapped to +/// the subresources whose bytes they hold ([`parts_touched`], rounded +/// outwards: a page holds whole subresources and pieces of others, all +/// counted), only those are read and detiled, and the prelude copies the +/// subresources detiled since its last copy. The other subresources' bytes +/// stay in the staging buffer and on the card as the last detiling left +/// them, which is what title memory still holds there. +/// +/// Whole, as before: the first detiling and any after what was learnt of +/// the texture was forgotten, a staging buffer made anew (it holds what its +/// piece held), levels on demand (which levels are the title's is judged +/// at each detiling), a bake's exact refresh, 3D and multisampled layouts +/// (their parts are not told apart here), the first copy into a host copy, +/// textures read through the hash or the guard (no pages to go by), and a +/// subresource that could not be detiled (all of them are copied then). +/// Measured: nothing in the title yet; the share of watched bytes it saves +/// is that of untouched subresources in the textures written. +fn texture_parts() -> bool { + #[cfg(test)] + if let Some(on) = TEST_PARTS.get() { + return on; + } + crate::toggled!("LEONIDA_TEXTURE_PARTS") +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`texture_parts`], for its thread only. + static TEST_PARTS: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; + /// For tests: subresources this thread detiled into staging buffers, + /// and bytes of title memory it read for a write-watched texture. + static DETILED_PARTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; + static WATCHED_READ: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; + /// For tests: bytes of a write-watched texture it detiled in place + /// ([`watched_in_place`]). + static WATCHED_IN_PLACE: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; + /// A test's choice for [`watched_in_place`], for its thread only. + static TEST_IN_PLACE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; + /// For tests: subresource copies this thread's preludes recorded. + static COPIED_PARTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + +/// The bytes of tiled memory, from the texture's start, that hold the +/// subresource of level `mip` and array slice `slice`: every byte +/// [`leonida_formats::texture::Layout::detile`] reads for it lies inside. +/// A level in the mip tail is the tail block of its slice (which it shares +/// with the other levels there). `None` for layouts whose subresources are +/// not told apart here: 3D (a level spans every depth slab) and +/// multisampled ones. +fn part_span(layout: &leonida_formats::texture::Layout, mip: u32, slice: u32) -> Option<(u64, u64)> { + use leonida_formats::texture::Dimension; + if layout.desc.dimension == Dimension::Tex3d || layout.desc.samples != 1 || slice >= layout.slices { + return None; + } + let m = layout.mips.get(mip as usize)?; + let base = u64::from(slice) * layout.slice_size; + let span = if m.tail.is_some() { + (base, base + layout.alignment.min(layout.slice_size)) + } else { + let bytes = u64::from(m.pitch) * u64::from(m.rows) * u64::from(layout.desc.element_bytes); + (base + m.offset, base + m.offset + bytes) + }; + Some(span) +} + +/// A set of a staging buffer's parts (its footprints, in their order), a bit +/// a part. +type Parts = Vec<u64>; + +fn part_in(parts: &[u64], i: usize) -> bool { + parts.get(i / 64).is_some_and(|word| word >> (i % 64) & 1 != 0) +} + +/// Of a staging buffer's `count` parts, part `i` being level +/// `first + i % (mips - first)` of array slice `i / (mips - first)` (as +/// [`Staging::part`] has them), those whose bytes ([`part_span`]) meet any +/// of `ranges` (byte offsets from the texture's start, first and past the +/// last). `None`: all of them, for a layout whose parts are not told apart. +fn parts_touched( + layout: &leonida_formats::texture::Layout, + first: u32, + mips: u32, + count: usize, + ranges: &[(u64, u64)], +) -> Option<Parts> { + let levels = mips.checked_sub(first).filter(|&n| n != 0)? as usize; + let mut parts = vec![0u64; count.div_ceil(64)]; + for i in 0..count { + let (mip, slice) = (first + (i % levels) as u32, (i / levels) as u32); + let (from, to) = part_span(layout, mip, slice)?; + if ranges.iter().any(|&(a, b)| a < to && from < b) { + parts[i / 64] |= 1 << (i % 64); + } + } + Some(parts) +} + +/// The byte ranges of a texture of `size` bytes at `start` that the write +/// watch says were written after the asking `since`, from `written` (page +/// and the asking that last found it written, as [`crate::watch::writes`] +/// gives them): whole pages, cut to the texture, as offsets from its start. +fn written_since(start: usize, size: usize, written: &[(usize, u64)], since: u64) -> Vec<(u64, u64)> { + let page = crate::watch::PAGE; + let end = start.saturating_add(size); + let mut ranges: Vec<(u64, u64)> = Vec::new(); + for &(p, _) in written.iter().filter(|&&(_, w)| w > since) { + let (from, to) = ((p * page).max(start), (p * page).saturating_add(page).min(end)); + if from >= to { + continue; + } + let (from, to) = ((from - start) as u64, (to - start) as u64); + match ranges.last_mut() { + Some(last) if last.1 >= from => last.1 = last.1.max(to), + _ => ranges.push((from, to)), + } + } + ranges +} + /// [`upload`] of the levels from `first` on, the ones a view shows: of a /// texture the title placed there may be no memory of the larger ones, and /// what lies there is another texture's. (After leonida-amd 4436f8f1.) @@ -1433,12 +2116,17 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { // would record an upload again until the title writes the texture: the // level stayed empty, the texture blurred or black. Asked again about // once a second, and only when the card has room; the staging buffer - // still holds the level's bytes. + // still holds the level's bytes, or, let go after the copy + // ([`release_staging`]), the check at this list's submission detiles + // them again. if staging.on_demand { let since = staging.waiting.load(Relaxed); if since != 0 && crate::host::long_ago(since, 1000, 2) { if crate::resource::room_lately() { staging.waiting.store(0, Relaxed); + if staging.staged().is_none() { + staging.forget(); + } staging.dirty.store(true, Relaxed); crate::tiles::STATS[10].fetch_add(1, Relaxed); } else { @@ -1455,13 +2143,46 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { let pitch = footprint.RowPitch as usize; let bytes = pitch * staging.rows[0] as usize; let plane = staging.clone(); + if plane_same() { + // Filled at the list's submission only if the plane differs from + // what the host copy was last given, and then copied by the + // list's prelude ([`PreludeUpload::claim`]). + let found = Arc::new(Mutex::new(None)); + let found_by_fill = found.clone(); + let Some(source) = list.plane_upload(bytes as u64, (at, len), move |dst| { + let on_card = *plane.plane_on_card.lock().unwrap_or_else(|e| e.into_inner()); + let new = fill_plane_if_new(&plane.layout, at, len, dst, bytes, pitch, on_card); + *found_by_fill.lock().unwrap_or_else(|e| e.into_inner()) = new; + }) else { + once!("no upload buffer for a CPU-written movie plane"); + return; + }; + let plane = Some(PlaneCopy { source, found }); + list.upload_in_prelude(PreludeUpload { + staging, + copy, + on_demand: None, + held: Mutex::default(), + plane, + resource: resource as usize, + list: list_key(list), + }); + return; + } + // (Its copy follows, at its submission, the prelude copies of lists + // before it: what the host copy holds is not known to those after + // it, which copy theirs, with `plane_same` switched on at run time, + // `crate::ab`.) let Some(source) = list.plane_upload(bytes as u64, (at, len), move |dst| { fill_plane(&plane.layout, at, len, dst, bytes, pitch); + *plane.plane_on_card.lock().unwrap_or_else(|e| e.into_inner()) = None; }) else { once!("no upload buffer for a CPU-written movie plane"); return; }; record_upload(list, resource, texture, &staging, &source, 0); + #[cfg(test)] + PLANE_COPIES.set(PLANE_COPIES.get() + 1); staging.uploaded.store(true, Relaxed); return; } @@ -1484,6 +2205,8 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { staging, copy, on_demand, + held: Mutex::default(), + plane: None, resource: resource as usize, list: list_key(list), }); @@ -1518,13 +2241,23 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { }; staging.expected.store(there, Relaxed); } - record_upload(list, resource, texture, &staging, &staging.buffer, staging.base); + // (Not let go after copies recorded here, [`release_staging`]; one let go + // by the other way, `LEONIDA_AB`, is made again and detiled anew at the + // submission, and the list holds it.) + if staging.staged().is_none() { + staging.forget(); + } + let Some(staged) = staging.bytes_to_fill() else { + return; + }; + record_upload(list, resource, texture, &staging, &staged.buffer, staged.base); // When the list is submitted, its copy takes what the staging buffer // holds by then: noted before the check below, which sets `dirty` // again if it detiles (the next list then uploads once more). { let staging = staging.clone(); list.defer_host(move || { + let _held = &staged; staging.uploaded.store(true, Relaxed); staging.dirty.store(false, Relaxed); }); @@ -1579,7 +2312,8 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { /// the check found, ahead of its own commands. /// /// What stays as it was: a video's planes, each list's own copy of which is -/// read at its submission ([`Staging::movie_plane`]); the first uploads on the +/// read at its submission ([`Staging::movie_plane`]; copied by the prelude +/// too, and only when changed, with [`plane_same`]); the first uploads on the /// copy queue ([`ahead`]); textures the card wrote. What differs: the copies /// are not among the list's noted commands (diagnostics), and a texture found /// changed is copied once a submission, not by every list recorded while it @@ -1640,20 +2374,82 @@ pub(crate) struct PreludeUpload { copy: Arc<crate::resource::HostTexture>, /// Levels on demand (`crate::tiles`): the host copy, made without memory. on_demand: Option<crate::resource::OnDemand>, + /// The staging buffers the list's preludes copied from, by the number of + /// the submission that copied them ([`crate::host::submissions`]): the + /// texture may let go of its own as soon as the copy is recorded + /// ([`release_staging`]). Each is held until the list is reset, after its + /// last submission ran, or until a later copy finds its submission + /// finished: a list submitted again and again without a reset holds + /// those its submissions in the air copy, not one for each change. + held: Mutex<Vec<(u64, Arc<Staged>)>>, + /// For a video's plane ([`plane_same`]): copied from the list's own + /// upload buffer instead of a staging buffer. + plane: Option<PlaneCopy>, /// The title's texture ([`upload_guard`]). resource: usize, /// The list that reads it ([`list_key`]). list: usize, } -/// A copy of a staging buffer into its host copy that a list's prelude -/// records ([`PreludeUpload::claim`]). +/// A video's plane a list reads ([`plane_same`]): the list's own upload +/// buffer (held by the list until it is reset), and the digest of the plane +/// its fill at the list's submission put there if that differed from what +/// the host copy was last given (`None`: it filled nothing). +struct PlaneCopy { + source: ID3D12Resource, + found: Arc<Mutex<Option<Digest>>>, +} + +/// Whether a video's plane ([`Staging::movie_plane`]) is copied into its +/// host copy only when it changed, by the prelude of the first list of a +/// submission that reads it (`LEONIDA_PLANE_SAME=0`: every list that reads +/// it fills an upload buffer of its own and copies all of it, changed or +/// not, as before). Only with [`prelude_upload`]. +/// +/// The plane is read and hashed at each list's submission, as its fill read +/// it before; the fill and the copy are left out when the digest is the one +/// the host copy was last given. A video at 30 pictures a second in a title +/// at 60 changes every other frame, and any other linear one-level R8 +/// texture (the shape is all the rule goes by, see the info line in +/// [`staging`]) that stands still was copied whole by every list that +/// sampled it. The check runs where the copy is recorded, at the list's own +/// submission, so the picture is not a frame late (the ring of three of +/// `LOCAL` fx-flicker and r_avm23 above); a change between two lists' +/// submissions is the later one's. +fn plane_same() -> bool { + #[cfg(test)] + if let Some(on) = TEST_PLANE_SAME.get() { + return on && prelude_upload(); + } + prelude_upload() && crate::toggled!("LEONIDA_PLANE_SAME") +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`plane_same`], for its thread only. + static TEST_PLANE_SAME: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; + /// For tests: copies of video planes this thread's lists recorded or its + /// submissions gave to preludes. + static PLANE_COPIES: std::cell::Cell<u32> = const { std::cell::Cell::new(0) }; +} + +/// A copy into a host copy that a list's prelude records +/// ([`PreludeUpload::claim`]): of a staging buffer, or of a video's plane +/// from the list's own upload buffer. #[derive(Clone)] pub(crate) struct Upload { staging: Arc<Staging>, + /// The buffer copied from, and where in it the footprints count from. + source: ID3D12Resource, + base: u64, + /// The staging buffer it is part of, held while the copy is (`None`: the + /// list's own upload buffer, which the list holds). + _staged: Option<Arc<Staged>>, pub(crate) copy: Arc<crate::resource::HostTexture>, - /// The first copy from this staging buffer. + /// The first copy into the host copy. pub(crate) first: bool, + /// The parts it copies ([`texture_parts`]; `None`: all of them). + parts: Option<Parts>, } /// Whether a staging buffer is to be copied into its host copy now: it never @@ -1694,6 +2490,9 @@ impl PreludeUpload { pub(crate) fn claim(&self) -> Option<Upload> { use std::sync::atomic::Ordering::Relaxed; let staging = &self.staging; + if let Some(plane) = &self.plane { + return self.claim_plane(plane); + } let Some(first) = claim_upload(&staging.uploaded, &staging.dirty) else { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexSkipped, 1); @@ -1717,6 +2516,30 @@ impl PreludeUpload { crate::copystat::add(crate::copystat::C::TexSkipped, 1); return None; } + let staged = match staging.staged() { + Some(staged) => staged, + // Never copied and nothing detiled into it (none of its memory + // mapped yet): zeros, as from a new buffer. + None if first => match staging.bytes_to_fill() { + Some(staged) => staged, + None => { + staging.uploaded.store(false, Relaxed); + staging.dirty.store(true, Relaxed); + return None; + } + }, + // Let go after its last copy, and marked to be copied again with + // nothing detiled since (an on-demand level that waited for + // room, the sweep that let it go beside a detiling): the host + // copy still holds those bytes. Detiled anew at the next check + // (which marks it again) and copied then, not zeros now; if that + // check finds nothing to detile (no byte of it mapped), the host + // copy keeps what it has and nothing is asked again. + None => { + staging.forget(); + return None; + } + }; #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexUploads, 1); #[cfg(test)] @@ -1743,7 +2566,59 @@ impl PreludeUpload { // What the copy puts in the host copy is known. None => staging.note_held(), } - Some(Upload { staging: staging.clone(), copy: self.copy.clone(), first }) + // The list holds what its prelude copies from; the texture lets go + // of it unless it is detiled often. (This submission has begun and + // not finished: what it copies stays.) + { + let (begun, finished) = crate::host::submissions(); + let mut held = self.held.lock().unwrap_or_else(|e| e.into_inner()); + held.retain(|&(submission, _)| submission > finished); + held.push((begun, staged.clone())); + } + staging.copied(); + // What was detiled since the last copy; all of it into a host copy + // that never had any. A buffer marked to be copied with no part + // detiled since (levels on demand asked again for a level without + // tiles, [`upload_from`], which marks a kept buffer and detiles + // nothing) has all of it copied too: the set taken empty here said + // "none", and the level was given memory and left without its + // bytes. So does one with the switch off, whatever the set says. + let parts = { + let mut dirty = staging.parts_dirty.lock().unwrap_or_else(|e| e.into_inner()); + let taken = dirty.replace(Parts::new()); + taken.filter(|parts| !first && texture_parts() && parts.iter().any(|&word| word != 0)) + }; + Some(Upload { + staging: staging.clone(), + source: staged.buffer.clone(), + base: staged.base, + _staged: Some(staged), + copy: self.copy.clone(), + first, + parts, + }) + } + + /// [`PreludeUpload::claim`] of a video's plane: the copy from the list's + /// upload buffer if the list's fill found the plane changed and no list + /// before it in the submission brought the same picture. + fn claim_plane(&self, plane: &PlaneCopy) -> Option<Upload> { + let staging = &self.staging; + let found = plane.found.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut on_card = staging.plane_on_card.lock().unwrap_or_else(|e| e.into_inner()); + let Some(found) = found.filter(|found| *on_card != Some(*found)) else { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexSkipped, 1); + return None; + }; + let first = on_card.is_none(); + *on_card = Some(found); + staging.uploaded.store(true, std::sync::atomic::Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexUploads, 1); + #[cfg(test)] + PLANE_COPIES.set(PLANE_COPIES.get() + 1); + Some(Upload { staging: staging.clone(), source: plane.source.clone(), base: 0, _staged: None, copy: self.copy.clone(), first, parts: None }) } /// [`PreludeUpload::claim`] left the copy out over a host write: counted, @@ -1779,6 +2654,11 @@ impl Upload { pub(crate) unsafe fn record(&self, list: &ID3D12GraphicsCommandList) { let (staging, texture) = (&self.staging, &self.copy.texture); for (i, footprint) in staging.footprints.iter().enumerate() { + if self.parts.as_ref().is_some_and(|parts| !part_in(parts, i)) { + continue; + } + #[cfg(test)] + COPIED_PARTS.set(COPIED_PARTS.get() + 1); let to = D3D12_TEXTURE_COPY_LOCATION { // SAFETY: a borrowed pointer the location never releases. pResource: unsafe { std::mem::transmute_copy(texture) }, @@ -1789,11 +2669,11 @@ impl Upload { }; let from = D3D12_TEXTURE_COPY_LOCATION { // SAFETY: as above. - pResource: unsafe { std::mem::transmute_copy(&staging.buffer) }, + pResource: unsafe { std::mem::transmute_copy(&self.source) }, Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { - Offset: staging.base + footprint.Offset, + Offset: self.base + footprint.Offset, ..*footprint }, }, @@ -1885,6 +2765,36 @@ fn record_upload( } } +/// [`fill_plane`] if the plane differs from the one the host copy was last +/// given (digest `on_card`): its digest then, `None` if it is the same (and +/// `dst` is not written). Read through the copy, which stands unmapped pages +/// (zeros), as the fill's slow way; the fill then detiles from that read. +fn fill_plane_if_new( + layout: &leonida_formats::texture::Layout, + at: usize, + len: usize, + dst: usize, + bytes: usize, + pitch: usize, + on_card: Option<Digest>, +) -> Option<Digest> { + let _pin = crate::watch::title_memory_reading_range(at, len); + with_read(len, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), at as *const u8, len, false); + let found = digest(read); + if on_card == Some(found) { + return None; + } + // 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) }; + if let Err(error) = layout.detile(read, 0, 0, out, pitch, bytes) { + out.fill(0); + once!("could not copy the linear plane into the list's upload buffer: {error:?}"); + } + Some(found) + }) +} + fn fill_plane( layout: &leonida_formats::texture::Layout, at: usize, @@ -2130,11 +3040,92 @@ impl Staging { *self.last.lock().unwrap_or_else(|e| e.into_inner()) = Last::default(); } + /// The staging buffer, if the texture has one now. + fn staged(&self) -> Option<Arc<Staged>> { + self.staged.lock().unwrap_or_else(|e| e.into_inner()).clone() + } + + /// The staging buffer, made again if it was let go + /// ([`release_staging`]): all zeros then. `None`: none could be had. + fn bytes_to_fill(&self) -> Option<Arc<Staged>> { + self.staged_or_new(true).map(|(staged, _)| staged) + } + + /// [`Staging::bytes_to_fill`] for a detiling, which writes all the copy + /// reads: a buffer made again is not zeroed first (a piece of a pool + /// block given out again was written twice, write-combined memory, + /// zeros and then the texels), and says so (true: made now, holding + /// what its piece held). + fn bytes_to_detile(&self) -> Option<(Arc<Staged>, bool)> { + self.staged_or_new(false) + } + + fn staged_or_new(&self, zeroed: bool) -> Option<(Arc<Staged>, bool)> { + let mut slot = self.staged.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(staged) = slot.as_ref() { + return Some((staged.clone(), false)); + } + let staged = new_staged(host()?, self.resource, &self.desc, self.bytes, zeroed)?; + RELEASED[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + *slot = Some(staged.clone()); + Some((staged, !zeroed)) + } + + /// Lets go of the staging buffer (lists that copy from it hold it + /// themselves): the one there was, for the caller to drop. + fn let_go_staged(&self) -> Option<Arc<Staged>> { + self.staged.lock().unwrap_or_else(|e| e.into_inner()).take() + } + + /// The copy of the staging buffer into the host copy is recorded (and + /// whoever runs it holds the buffer): the texture lets go of it, unless + /// it is detiled often ([`release_staging`], [`keeps_staging`]). + fn copied(&self) { + use std::sync::atomic::Ordering::Relaxed; + if release_staging() + && !keeps_staging(self.detiled(), crate::host::coarse_ms(), hot_staging_ms()) + && self.let_go_staged().is_some() + { + RELEASED[0].fetch_add(1, Relaxed); + RELEASED[1].fetch_add(self.bytes, Relaxed); + } + } + + /// When the last two detilings ran ([`Staging::detiled_ms`]). + fn detiled(&self) -> [u64; 2] { + use std::sync::atomic::Ordering::Relaxed; + [self.detiled_ms[0].load(Relaxed), self.detiled_ms[1].load(Relaxed)] + } + /// The title memory the texture is read from: address and bytes. pub(crate) fn memory(&self) -> (usize, usize) { (self.memory as usize, self.read) } + /// The bytes of title memory the staging buffer's `parts` are detiled + /// from ([`part_span`]), cut to the first `size`, in address order and + /// joined where they meet. (A slice's levels lie from the smallest up, + /// level 0 last: the parts' order is not the addresses'.) + fn part_spans(&self, parts: &[u64], size: usize) -> Vec<(usize, usize)> { + let mut spans: Vec<(usize, usize)> = (0..self.footprints.len()) + .filter(|&i| part_in(parts, i)) + .filter_map(|i| { + let (mip, slice) = self.part(i); + let (from, to) = part_span(&self.layout, mip, slice)?; + Some(((from as usize).min(size), (to as usize).min(size))) + }) + .collect(); + spans.sort_unstable(); + let mut joined: Vec<(usize, usize)> = Vec::with_capacity(spans.len()); + for (from, to) in spans { + match joined.last_mut() { + Some(last) if last.1 >= from => last.1 = last.1.max(to), + _ => joined.push((from, to)), + } + } + joined + } + /// The title's level and the array slice of the staging buffer's part /// `i`. fn part(&self, i: usize) -> (u32, u32) { @@ -2197,16 +3188,76 @@ impl Staging { if !exact && last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { return 0; } + // Of a texture detiled before, only the subresources the pages + // written since hold ([`texture_parts`]). + let parts = (!exact && last.asked != 0 && !self.on_demand && texture_parts()) + .then(|| { + let ranges = written_since(start, size, &written, last.asked); + parts_touched(&self.layout, self.first, self.mips, self.footprints.len(), &ranges) + }) + .flatten(); + // The buffer it goes into, asked for first: one made anew holds + // what its piece held, and all of it is read and detiled then. + let target = parts.is_some().then(|| self.bytes_to_detile()).flatten(); + let parts = parts.filter(|_| target.as_ref().is_some_and(|&(_, made)| !made)); last.asked = now; // Read through the copy, which stands unmapped pages: memory of - // big pools is too slow to ask page by page. - with_read(size, |read| { - crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); - self.detile(read); + // big pools is too slow to ask page by page. Of some parts only, + // only their bytes: the detiling of those reads no other. + let spans = parts.as_ref().map(|parts| self.part_spans(parts, size)); + let read = spans.as_ref().map_or(size, |spans| spans.iter().map(|(a, b)| b - a).sum()); + // Detiled where it lies, if nothing can take a page of it away + // meanwhile ([`watched_in_place`]). + if watched_in_place() { + let mapped = if no_wait() && !exact { + crate::watch::title_memory_reading_now().map(crate::watch::RangeReading::Whole) + } else { + Some(waited(2, || crate::watch::title_memory_reading_range(start, size))) + }; + let whole = [(0, size)]; + let there = |spans: &[(usize, usize)]| { + spans.iter().all(|&(from, to)| committed(self.memory.wrapping_add(from), to - from)) + }; + if let Some(_mapped) = mapped + && let Some(_reading) = InPlaceRead::begin(start, size) + && there(spans.as_deref().unwrap_or(&whole)) + { + // SAFETY: committed memory of the texture's layout size + // (of the parts read, at least the pages those parts' + // bytes lie in, the only ones their detiling reads), and + // it stays so while `_mapped` and `_reading` are held: + // the runtime changes no mapping over it, the title's + // frees and protections of it wait for the read. + let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; + self.detile_parts(last, tiled, parts.as_deref(), target); + #[cfg(test)] + WATCHED_IN_PLACE.set(WATCHED_IN_PLACE.get() + read as u64); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexWatched, read as u64); + return read; + } + } + with_read(size, |buffer| { + match &spans { + Some(spans) => { + for &(from, to) in spans { + crate::host::copy_mapped( + buffer[from..].as_mut_ptr(), + self.memory.wrapping_add(from), + to - from, + false, + ); + } + } + None => crate::host::copy_mapped(buffer.as_mut_ptr(), self.memory, size, false), + } + self.detile_parts(last, buffer, parts.as_deref(), target); }); + #[cfg(test)] + WATCHED_READ.set(WATCHED_READ.get() + read as u64); #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::TexWatched, size as u64); - return size; + crate::copystat::add(crate::copystat::C::TexWatched, read as u64); + return read; } // View memory has no write-watch, and a texture there was hashed // whole at every check: 229 MB and 51 ms a frame in a gameplay view @@ -2314,7 +3365,7 @@ impl Staging { if read.iter().all(|&b| b == 0) { return false; } - self.detile(read); + self.detile(last, read); true }); #[cfg(feature = "diagnostics")] @@ -2339,7 +3390,7 @@ impl Staging { } last.hash = Some(hash); found_blind(last); - self.detile(tiled); + self.detile(last, tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); size @@ -2359,7 +3410,7 @@ impl Staging { } last.hash = Some(hash); found_blind(last); - self.detile(tiled); + self.detile(last, tiled); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexChanged, size as u64); size @@ -2381,7 +3432,7 @@ impl Staging { let hash = digest(read); if last.hash != Some(hash) { last.hash = Some(hash); - self.detile(read); + self.detile(last, read); } true }); @@ -2421,7 +3472,7 @@ impl Staging { } if got != 0 { last.hash = Some(digest(read)); - self.detile(read); + self.detile(last, read); } got }); @@ -2437,8 +3488,55 @@ impl Staging { size } - /// Detiles `tiled` (the texture's memory) into the staging buffer. - fn detile(&self, tiled: &[u8]) { + /// Detiles `tiled` (the texture's memory) into the staging buffer, made + /// again if it was let go after its last copy ([`release_staging`]), and + /// not zeroed first: every row the copy reads is written, those of levels + /// not the title's with zeros, and from a subresource that cannot be + /// detiled on all with zeros. If none can be had, what `last` says the buffer holds + /// is forgotten: the next check detiles anew, and the host copy keeps + /// what it has. + fn detile(&self, last: &mut Last, tiled: &[u8]) { + self.detile_parts(last, tiled, None, None); + } + + /// [`Staging::detile`] of the staging buffer's `parts` alone (`None`: + /// all; [`texture_parts`]): the others keep what the last detiling put + /// there, and `tiled` need hold only the bytes of those detiled + /// ([`part_span`]), into `target` if the caller asked for the buffer + /// before it read them ([`Staging::bytes_to_detile`]): parts are + /// detiled only into a buffer that was there before, since one made + /// again holds what its piece held. All of them of levels on demand. + /// Those detiled are noted for the prelude's copy + /// ([`Staging::parts_dirty`]). + fn detile_parts(&self, last: &mut Last, tiled: &[u8], parts: Option<&[u64]>, target: Option<(Arc<Staged>, bool)>) { + if parts.is_some_and(|parts| parts.iter().all(|&word| word == 0)) { + return; + } + let Some((staged, unzeroed)) = target.or_else(|| self.bytes_to_detile()) else { + once!("no staging buffer to detile a changed texture into: detiled at its next check"); + *last = Last { hot_until: last.hot_until, ..Last::default() }; + return; + }; + // (A caller that read some parts only asked for a buffer that was + // there: `unzeroed` is false with `parts`.) + debug_assert!(parts.is_none() || !unzeroed); + let parts = parts.filter(|_| !unzeroed && !self.on_demand); + { + let mut dirty = self.parts_dirty.lock().unwrap_or_else(|e| e.into_inner()); + match (dirty.as_mut(), parts) { + (Some(dirty), Some(parts)) => { + dirty.resize(dirty.len().max(parts.len()), 0); + dirty.iter_mut().zip(parts).for_each(|(d, p)| *d |= p); + } + _ => *dirty = None, + } + } + { + use std::sync::atomic::Ordering::Relaxed; + let now = crate::host::coarse_ms().max(1); + let previous = self.detiled_ms[0].swap(now, Relaxed); + self.detiled_ms[1].store(previous, Relaxed); + } self.dirty.store(true, std::sync::atomic::Ordering::Relaxed); // Levels on demand: which levels are the title's is judged here, // once, for what the staging buffer holds from now on. The step @@ -2471,10 +3569,16 @@ impl Staging { // block of the pool goes on with another texture's. let len = (pitch * rows as usize * f.Depth as usize) .min(self.bytes.saturating_sub(footprint.Offset) as usize); - // SAFETY: the subresource's part of the mapped staging buffer. + // SAFETY: the subresource's part of the mapped staging buffer, + // which `staged` holds; written under `last`'s lock alone. let linear = unsafe { - std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) + std::slice::from_raw_parts_mut(staged.data.add(footprint.Offset as usize), len) }; + if parts.is_some_and(|parts| !part_in(parts, i)) { + continue; + } + #[cfg(test)] + DETILED_PARTS.set(DETILED_PARTS.get() + 1); if mip < 32 && held & (1 << mip) == 0 { // Not the title's: zeros, not what lies in that memory. linear.fill(0); @@ -2485,20 +3589,29 @@ impl Staging { .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) { tracing::warn!(?e, mip, slice, "texture not detiled"); + // Every part is copied: what was not written here is as + // undefined as before. + *self.parts_dirty.lock().unwrap_or_else(|e| e.into_inner()) = None; + if unzeroed { + // From here on zeros, as from a buffer made zeroed, not + // what its piece held of another texture. + let rest = self.bytes.saturating_sub(footprint.Offset) as usize; + // SAFETY: the mapped staging buffer from this + // subresource to its end, as above. + unsafe { std::ptr::write_bytes(staged.data.add(footprint.Offset as usize), 0, rest) }; + } return; } } } } -/// Lets go of a title texture's staging buffer (lists that recorded an -/// upload from it hold it until they have run); the next upload makes one -/// anew. +/// Lets go of a title texture's staging state, and its staging buffer if it +/// still has one (lists that recorded an upload from it hold it until they +/// have run); the next upload makes them anew. pub(crate) fn unstage(resource: This) { - let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(map) = map.as_mut() { - map.remove(&(resource as usize)); - } + // (No wait for a make: callers hold the host side its `still` locks.) + drop(table::take_out(&STAGING, resource as usize, &STAGING_GONE, table::short(), false)); } /// Where a staged title texture's memory is: address and bytes. @@ -2862,20 +3975,50 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { there } -/// The staging state of a title texture, made on first use. +/// The staging state of a title texture, made on first use: with the +/// table's lock let go (`LEONIDA_STAGING_SHORT`, [`table::get_or_make`]), +/// or under it. fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> Option<Arc<Staging>> { - let texture = ©.texture; // Asked before the table is locked: the sweep lets go of a staging // buffer with its texture's host side locked, in that order. let on_demand = crate::resource::host_tiled(resource).is_some(); - let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); - let map = map.get_or_insert_with(HashMap::new); - if let Some(s) = map.get(&(resource as usize)) - && s.first <= first.max(copy.base) - && s.serial == copy.serial - { - return Some(s.clone()); - } + table::get_or_make( + &STAGING, + resource as usize, + &STAGING_GONE, + |s| s.first <= first.max(copy.base) && s.serial == copy.serial, + || { + #[cfg(test)] + if let Some(mut f) = WHILE_MADE.take() { + f(resource); + } + new_staging(resource, copy, first, on_demand) + }, + // A texture whose host copy went, or was replaced, while this was + // made ([`STAGING_GONE`], an [`unstage`]): none for it. One released + // meanwhile is still there to ask (its release waits for this, + // [`forget`]) and has no host copy left. + || crate::resource::made_copy(resource).is_some_and(|now| now.serial == copy.serial), + table::short(), + ) +} + +#[cfg(test)] +thread_local! { + /// Run once, on this thread, as [`staging`] begins to make a state + /// (tests). + static WHILE_MADE: std::cell::RefCell<Option<Box<dyn FnMut(This)>>> = const { std::cell::RefCell::new(None) }; +} + +/// A staging state of title texture `resource` for its host copy `copy`, +/// from level `first` on ([`staging`]). +fn new_staging( + resource: This, + copy: &crate::resource::HostTexture, + first: u32, + on_demand: bool, +) -> Option<Staging> { + let texture = ©.texture; let (memory, desc) = crate::resource::texture_memory(resource)?; let Some(layout) = crate::resource::texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else { @@ -2945,36 +4088,14 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O Some(&mut total), ); } - let (piece, buffer, base, data) = match crate::pool::staging(host, total) { - Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data), - None => { - let speculative = PICKING.get().is_some() && !BAKING.get(); - if crate::residency::upload_refused() - || (speculative && !crate::residency::allow_staging_growth(false)) - { - crate::residency::note_staging_deferred(); - return None; - } - let (buffer, data) = host.upload_buffer(total)?; - crate::host::name(&buffer, || { - format!( - "staging of {resource:?} {}x{}x{} f{}", - d.Width, d.Height, d.DepthOrArraySize, d.Format.0 - ) - }); - (None, buffer, 0, data) - } - }; tracing::debug!(?desc, total, "texture contents uploaded from title memory"); - STAGED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); - STAGED[1].fetch_add(total, std::sync::atomic::Ordering::Relaxed); - let s = Arc::new(Staging { - buffer, - base, - _piece: piece, + let mut s = Staging { + staged: Mutex::new(None), + desc: d, + resource: resource as usize, #[cfg(feature = "diagnostics")] size: total, - data, + detiled_ms: [const { std::sync::atomic::AtomicU64::new(0) }; 2], footprints, rows, layout, @@ -2991,6 +4112,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O last: Mutex::default(), dirty: std::sync::atomic::AtomicBool::new(true), uploaded: std::sync::atomic::AtomicBool::new(false), + parts_dirty: Mutex::new(None), used: std::sync::atomic::AtomicU64::new(crate::host::moment()), expected: std::sync::atomic::AtomicU64::new(0), on_demand, @@ -2998,8 +4120,16 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2], waiting: std::sync::atomic::AtomicU64::new(0), exact: std::sync::atomic::AtomicBool::new(BAKING.get()), - }); - map.insert(resource as usize, s.clone()); + plane_on_card: Mutex::new(None), + }; + // A video's plane is copied from an upload buffer of the list's own + // ([`upload_from`]), never from a staging buffer: each such texture held + // one of its size that nothing wrote or read, for as long as its staging + // state lived. A detiling makes one if one is wanted after all (the + // copy queue's first uploads, `ahead`). + if !s.movie_plane() { + *s.staged.get_mut().unwrap_or_else(|e| e.into_inner()) = Some(new_staged(host, resource as usize, &d, total, true)?); + } Some(s) } @@ -3371,6 +4501,1034 @@ mod prelude_upload_tests { } } +#[cfg(test)] +mod staging_release_tests { + use super::*; + use std::sync::atomic::Ordering::Relaxed; + + /// The bytes of `resource`'s staging buffer its texture holds now (lists + /// may hold more); 0: none, or no staging state. + fn held_staging_bytes(resource: This) -> u64 { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref() + .and_then(|map| map.get(&(resource as usize))) + .map_or(0, |s| if s.staged().is_some() { s.bytes } else { 0 }) + } + + fn staging_of(resource: This) -> Arc<Staging> { + STAGING.lock().unwrap_or_else(|e| e.into_inner()).as_ref().unwrap()[&(resource as usize)].clone() + } + + /// A texture detiled twice within the window keeps its staging buffer + /// while it goes on changing, and lets go of it once it has not changed + /// for the window; one detiled once, or seldom, does not keep it. + #[test] + fn only_a_texture_detiled_often_keeps_its_staging_buffer() { + const W: u64 = HOT_STAGING_MS; + // Never detiled, or once. + assert!(!keeps_staging([0, 0], 5, W)); + assert!(!keeps_staging([100, 0], 101, W)); + // Twice within the window, the last time just now: kept. + assert!(keeps_staging([2_100, 100], 2_200, W)); + // ...until it has not changed for the window. + assert!(!keeps_staging([2_100, 100], 2_100 + W, W)); + // Twice, further apart than the window: not kept. + assert!(!keeps_staging([100 + W, 100], 100 + W, W)); + // A window of 0 keeps none. + assert!(!keeps_staging([2_100, 2_100], 2_100, 0)); + } + + /// On the host: a title texture's staging buffer goes once a list's + /// prelude copied it, and the list holds it until it is reset; what the + /// texture was detiled from stays, so an unchanged texture is neither + /// detiled nor copied again, and the card keeps what it had (not zeros). + /// A change gets a buffer anew; a texture changing often keeps one until + /// it stops; one marked to be copied with nothing detiled and no buffer + /// is detiled anew first. + #[test] + fn a_copied_texture_keeps_its_change_tracking_but_not_its_staging_buffer() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const COPY_SOURCE: u32 = 0x800; + let Some(host) = crate::host::host() else { return }; + if !release_staging() { + return; + } + // 256x256 BC7, nine levels. + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = crate::resource::placed_bytes(&desc).unwrap() as usize; + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>(); + let paint = |seed: usize| { + // SAFETY: the memory above. + unsafe { (0..whole).for_each(|i| at.add(i).write((i * seed + i / 509 + seed) as u8)) }; + }; + paint(17); + let texture = crate::resource::texture_at(at as u64, &desc).unwrap(); + crate::resource::want_level(texture, 0); + let copy = crate::resource::host_copy(texture).unwrap(); + let layout = crate::resource::texture_memory(texture) + .and_then(|(_, d)| crate::resource::texture_layout(&d).map(|t| t.planes[0].layout.clone())) + .unwrap(); + let (pitch, rows) = (1024usize, 64usize); + let now = || { + let mut level = vec![0u8; pitch * rows]; + // SAFETY: the memory above. + let tiled = unsafe { std::slice::from_raw_parts(at, whole) }; + layout.detile(tiled, 0, 0, &mut level, pitch, pitch * rows).unwrap(); + level + }; + // A list that samples the texture and copies level 0 out of its host + // copy, submitted and waited for; what that copy saw. + let submit = || { + let back = host.read_back_buffer((pitch * rows) as u64).unwrap(); + let list = host.new_list().unwrap(); + upload_from(&list, texture, 0); + crate::list::ensure_state(&list, texture, COPY_SOURCE); + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(&back) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(98), + Width: 256, + Height: 256, + Depth: 1, + RowPitch: pitch as u32, + }, + }, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(©.texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + // SAFETY: an open list and live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + list.close(); + host.execute(&[&list]); + let mut data = std::ptr::null_mut(); + // SAFETY: a read-back buffer of that size, whose list has run. + let seen = unsafe { + back.Map(0, None, Some(&mut data)).unwrap(); + let seen = std::slice::from_raw_parts(data.cast::<u8>(), pitch * rows).to_vec(); + back.Unmap(0, None); + seen + }; + (list, seen) + }; + // The first upload: copied, and the texture lets go of the buffer; + // the list still holds it, until it goes. + let staging = super::staging(texture, ©, 0).unwrap(); + let first = Arc::downgrade(&staging.staged().unwrap()); + assert!(Arc::ptr_eq(&staging, &staging_of(texture))); + let claimed = CLAIMED.get(); + let (list, seen) = submit(); + assert_eq!(CLAIMED.get(), claimed + 1); + assert!(seen == now(), "what the memory held at the submission"); + assert_eq!(held_staging_bytes(texture), 0, "the staging buffer goes once its copy is recorded"); + assert!(first.upgrade().is_some(), "the list that copies it holds it"); + drop(list); + assert!(first.upgrade().is_none(), "and lets go of it when it is reset"); + // Unchanged: neither copied again nor zeros on the card, and no + // buffer made for it. + let (_list, seen) = submit(); + assert_eq!(CLAIMED.get(), claimed + 1, "nothing changed: nothing is copied"); + assert!(seen == now(), "the card keeps what it had"); + assert!(staging.staged().is_none(), "nothing detiled: no buffer made"); + // A change, the second detiling within the window: a buffer anew, + // copied, and kept while the texture changes often. + paint(29); + let (_list, seen) = submit(); + assert_eq!(CLAIMED.get(), claimed + 2); + assert!(seen == now(), "the change is on the card"); + assert!(held_staging_bytes(texture) > 0, "a texture detiled often keeps its buffer"); + // It stops changing: the sweep lets go of the buffer after the window. + assert_eq!(let_go_cold([&staging].into_iter(), crate::host::coarse_ms(), HOT_STAGING_MS, &mut Vec::new()), 0); + assert_eq!(let_go_cold([&staging].into_iter(), crate::host::coarse_ms() + HOT_STAGING_MS, HOT_STAGING_MS, &mut Vec::new()), 1); + assert_eq!(held_staging_bytes(texture), 0); + let (_list, seen) = submit(); + assert_eq!(CLAIMED.get(), claimed + 2); + assert!(seen == now()); + // Changes seldom (a window of 0 here): each one is detiled into a + // buffer made for it, copied, and the buffer goes again. + TEST_HOT_STAGING_MS.set(Some(0)); + for seed in [31, 37] { + paint(seed); + let (_list, seen) = submit(); + assert!(seen == now(), "change {seed} is on the card"); + assert_eq!(held_staging_bytes(texture), 0, "change {seed}: the buffer goes after its copy"); + } + assert_eq!(CLAIMED.get(), claimed + 4); + // Marked to be copied with nothing detiled and no buffer (a level on + // demand that waited for room, or the sweep beside a detiling): not + // zeros now, but detiled anew at the next check and copied then. + staging.dirty.store(true, Relaxed); + let (_list, seen) = submit(); + assert_eq!(CLAIMED.get(), claimed + 4, "nothing to copy: given up"); + assert!(seen == now(), "the card keeps what it had, not zeros"); + assert!(!staging.dirty.load(Relaxed), "the next check detiles it anew instead"); + let (_list, seen) = submit(); + assert_eq!(CLAIMED.get(), claimed + 5, "detiled anew and copied"); + assert!(seen == now()); + assert_eq!(held_staging_bytes(texture), 0); + TEST_HOT_STAGING_MS.set(None); + } + + /// A detiling writes every row the copy reads, of every level, whatever + /// the staging buffer held before: one made again for it needs no zeros + /// first ([`Staging::bytes_to_detile`]). + #[test] + fn a_detiling_writes_all_the_copy_reads() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const COPY_SOURCE: u32 = 0x800; + let Some(host) = crate::host::host() else { return }; + // 256x256 BC7, nine levels. + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = crate::resource::placed_bytes(&desc).unwrap() as usize; + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>(); + // SAFETY: as above. + unsafe { (0..whole).for_each(|i| at.add(i).write((i * 11 + i / 257 + 3) as u8)) }; + let texture = crate::resource::texture_at(at as u64, &desc).unwrap(); + crate::resource::want_level(texture, 0); + let copy = crate::resource::host_copy(texture).unwrap(); + let staging = super::staging(texture, ©, 0).unwrap(); + let Some(staged) = staging.staged() else { return }; + // What another texture left in it. + // SAFETY: the buffer's mapping, ours alone until the detiling. + unsafe { std::ptr::write_bytes(staged.data, 0xa5, staged.bytes as usize) }; + // What each level's rows hold, laid out as the staging buffer. + // SAFETY: the memory above. + let tiled = unsafe { std::slice::from_raw_parts(at, whole) }; + let mut expected = vec![0u8; staging.bytes as usize]; + for (i, (footprint, &rows)) in staging.footprints.iter().zip(&staging.rows).enumerate() { + let (mip, slice) = staging.part(i); + let pitch = footprint.Footprint.RowPitch as usize; + let len = (pitch * rows as usize).min(expected.len() - footprint.Offset as usize); + let linear = &mut expected[footprint.Offset as usize..][..len]; + staging.layout.detile(tiled, mip, slice, linear, pitch, pitch * rows as usize).unwrap(); + } + let back = host.read_back_buffer(staging.bytes.next_multiple_of(512)).unwrap(); + let list = host.new_list().unwrap(); + upload_from(&list, texture, 0); + crate::list::ensure_state(&list, texture, COPY_SOURCE); + for (i, footprint) in staging.footprints.iter().enumerate() { + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(&back) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(©.texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: i as u32 }, + }; + // SAFETY: an open list and live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + list.close(); + drop(staged); + host.execute(&[&list]); + let mut data = std::ptr::null_mut(); + // SAFETY: a read-back buffer of that size, whose list has run. + unsafe { back.Map(0, None, Some(&mut data)).unwrap() }; + // SAFETY: as above. + let seen = unsafe { std::slice::from_raw_parts(data.cast::<u8>(), staging.bytes as usize) }; + for (i, (footprint, &rows)) in staging.footprints.iter().zip(&staging.rows).enumerate() { + let f = footprint.Footprint; + // BC7: 16 bytes a block of 4x4. + let row = f.Width.div_ceil(4) as usize * 16; + for r in 0..rows as usize { + let at = footprint.Offset as usize + r * f.RowPitch as usize; + assert!(seen[at..at + row] == expected[at..at + row], "level {i}, row {r}"); + } + } + // SAFETY: mapped above. + unsafe { back.Unmap(0, None) }; + } + + /// A list submitted again and again without a reset holds the staging + /// buffers of its last submission, not one for every change its + /// submissions copied: those of a submission that has run go at the + /// next copy. + #[test] + fn a_list_submitted_again_holds_only_what_its_last_submission_copies() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + let Some(host) = crate::host::host() else { return }; + if !release_staging() { + return; + } + // 128x128 BC7, eight levels. + let desc = [3u32, 0, 0, 0, 128, 0, 128, 0x8_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = crate::resource::placed_bytes(&desc).unwrap() as usize; + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>(); + let paint = |seed: usize| { + // SAFETY: the memory above. + unsafe { (0..whole).for_each(|i| at.add(i).write((i * seed + i / 509 + seed) as u8)) }; + }; + paint(13); + let texture = crate::resource::texture_at(at as u64, &desc).unwrap(); + crate::resource::want_level(texture, 0); + let copy = crate::resource::host_copy(texture).unwrap(); + let staging = super::staging(texture, ©, 0).unwrap(); + TEST_HOT_STAGING_MS.set(Some(0)); + let list = host.new_list().unwrap(); + upload_from(&list, texture, 0); + list.close(); + let claimed = CLAIMED.get(); + let mut copied = Vec::new(); + for seed in [13, 19, 23, 29] { + paint(seed); + copied.push(Arc::downgrade(&staging.staged().unwrap_or_else(|| staging.bytes_to_fill().unwrap()))); + host.execute(&[&list]); + } + TEST_HOT_STAGING_MS.set(None); + assert_eq!(CLAIMED.get(), claimed + 4, "each submission copied the change"); + let alive = copied.iter().filter(|w| w.upgrade().is_some()).count(); + assert_eq!(alive, 1, "only the last submission's buffer is held"); + assert!(copied[3].upgrade().is_some()); + drop(list); + assert!(copied[3].upgrade().is_none(), "and it goes with the list's reset"); + } + + /// A 64x64 linear one-level R8 title texture (what the runtime takes + /// for a video's plane, [`Staging::movie_plane`]) in memory of our own, + /// painted by `paint(seed)`; lists that sample it and copy its host copy + /// out, and what those copies saw (row by row, 64 bytes each). + struct Plane { + at: *mut u8, + texture: This, + copy: Arc<crate::resource::HostTexture>, + } + + impl Plane { + const SIDE: usize = 64; + /// The rows of the title's memory and of the host copy's read-back, + /// 256 bytes apart (the console's linear pitch for this texture, as + /// its layout says, and `D3D12_TEXTURE_DATA_PITCH_ALIGNMENT`). + const PITCH: usize = 256; + + fn new() -> Plane { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + // 2D, 64x64, one level, R8_UNORM (61), linear (layout 1). + let desc = [3u32, 0, 0, 0, 64, 0, 64, 0x1_0001, 61, 1, 0, 1, 0, 0]; + let whole = crate::resource::placed_bytes(&desc).unwrap() as usize; + assert!(whole >= Self::SIDE * Self::PITCH); + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>(); + let texture = crate::resource::texture_at(at as u64, &desc).unwrap(); + crate::resource::want_level(texture, 0); + let copy = crate::resource::host_copy(texture).unwrap(); + let layout = crate::resource::texture_memory(texture) + .and_then(|(_, d)| crate::resource::texture_layout(&d).map(|t| t.planes[0].layout.clone())) + .unwrap(); + assert_eq!((layout.mips[0].offset, layout.mips[0].pitch as usize), (0, Self::PITCH)); + let plane = Plane { at, texture, copy }; + plane.paint(5); + plane + } + + /// Texel (x, y) is `x * seed + y`. + fn paint(&self, seed: usize) { + for y in 0..Self::SIDE { + for x in 0..Self::SIDE { + // SAFETY: the memory above. + unsafe { self.at.add(y * Self::PITCH + x).write((x * seed + y) as u8) }; + } + } + } + + fn now(&self) -> Vec<u8> { + // SAFETY: the memory above. + let rows = unsafe { std::slice::from_raw_parts(self.at, Self::SIDE * Self::PITCH) }; + rows.chunks(Self::PITCH).flat_map(|row| &row[..Self::SIDE]).copied().collect() + } + + /// A list that samples the plane, recorded (not closed). + fn record(&self, host: &crate::host::Host) -> (crate::host::HostList, ID3D12Resource) { + const COPY_SOURCE: u32 = 0x800; + let back = host.read_back_buffer((Self::PITCH * Self::SIDE) as u64).unwrap(); + let list = host.new_list().unwrap(); + upload_from(&list, self.texture, 0); + crate::list::ensure_state(&list, self.texture, COPY_SOURCE); + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(&back) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UNORM, + Width: Self::SIDE as u32, + Height: Self::SIDE as u32, + Depth: 1, + RowPitch: Self::PITCH as u32, + }, + }, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(&self.copy.texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + // SAFETY: an open list and live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + list.close(); + (list, back) + } + + /// What a list's copy out of the host copy saw, its list having run. + fn seen(back: &ID3D12Resource) -> Vec<u8> { + let mut data = std::ptr::null_mut(); + // SAFETY: a read-back buffer of that size, whose list has run. + unsafe { + back.Map(0, None, Some(&mut data)).unwrap(); + let rows = std::slice::from_raw_parts(data.cast::<u8>(), Self::PITCH * Self::SIDE); + let seen = rows.chunks(Self::PITCH).flat_map(|row| &row[..Self::SIDE]).copied().collect(); + back.Unmap(0, None); + seen + } + } + } + + /// A video's plane gets no staging buffer: it is copied from an upload + /// buffer of each list's own, filled at the list's submission. + #[test] + fn a_video_plane_has_no_staging_buffer() { + let Some(host) = crate::host::host() else { return }; + let plane = Plane::new(); + let (list, back) = plane.record(host); + assert!(is_staged(plane.texture), "it has its staging state"); + assert!(staging_of(plane.texture).movie_plane()); + assert_eq!(held_staging_bytes(plane.texture), 0, "and no staging buffer"); + host.execute(&[&list]); + assert!(Plane::seen(&back) == plane.now(), "the plane is on the card"); + assert_eq!(held_staging_bytes(plane.texture), 0); + } + + /// A video's plane is copied once a change, by the first list of a + /// submission that reads it, at that list's submission: lists recorded + /// before a change read it, a plane that stands still is not copied + /// again, and a picture the card had before is brought back when it + /// comes back (a ring of pictures). + #[test] + fn a_video_plane_is_copied_when_it_changed_not_by_every_list() { + let Some(host) = crate::host::host() else { return }; + if !plane_same() { + return; + } + let plane = Plane::new(); + let copies = PLANE_COPIES.get(); + // Two lists in one submission: the first brings it for both. + let (a, back_a) = plane.record(host); + let (b, back_b) = plane.record(host); + host.execute(&[&a, &b]); + assert_eq!(PLANE_COPIES.get(), copies + 1, "the first list of the submission copies it, the second finds it there"); + assert!(Plane::seen(&back_a) == plane.now() && Plane::seen(&back_b) == plane.now()); + // Unchanged: not copied again, and the card still has it. + let (c, back_c) = plane.record(host); + host.execute(&[&c]); + assert_eq!(PLANE_COPIES.get(), copies + 1, "a plane that stands still is not copied again"); + assert!(Plane::seen(&back_c) == plane.now()); + // Recorded before a change and submitted after it: the change. + let first = plane.now(); + let (d, back_d) = plane.record(host); + plane.paint(9); + host.execute(&[&d]); + assert_eq!(PLANE_COPIES.get(), copies + 2); + assert!(Plane::seen(&back_d) == plane.now() && plane.now() != first, "the list recorded before the change reads it"); + // The first picture again (a ring): the card has the second, so it + // is copied. + plane.paint(5); + assert!(plane.now() == first); + let (e, back_e) = plane.record(host); + host.execute(&[&e]); + assert_eq!(PLANE_COPIES.get(), copies + 3); + assert!(Plane::seen(&back_e) == first); + // A change between two submissions of one frame is the later one's. + let (f, back_f) = plane.record(host); + let (g, back_g) = plane.record(host); + host.execute(&[&f]); + plane.paint(11); + host.execute(&[&g]); + assert_eq!(PLANE_COPIES.get(), copies + 4); + assert!(Plane::seen(&back_f) == first && Plane::seen(&back_g) == plane.now()); + } + + /// A list that copies a video's plane itself (the prelude switched off + /// for it, as `crate::ab` does at run time in a diagnostics build) leaves + /// what the host copy holds unknown to the prelude's lists: a picture + /// the prelude gave before is brought again when it comes back, not + /// taken for the one on the card. + #[test] + fn a_plane_copied_by_its_list_is_not_taken_for_the_prelude_s() { + let Some(host) = crate::host::host() else { return }; + if !prelude_upload() { + return; + } + let plane = Plane::new(); + let first = plane.now(); + TEST_PLANE_SAME.set(Some(true)); + let (a, back_a) = plane.record(host); + host.execute(&[&a]); + assert!(Plane::seen(&back_a) == first, "the prelude brought the first picture"); + TEST_PLANE_SAME.set(Some(false)); + plane.paint(9); + let (b, back_b) = plane.record(host); + host.execute(&[&b]); + assert!(Plane::seen(&back_b) == plane.now(), "the list brought the second"); + TEST_PLANE_SAME.set(Some(true)); + plane.paint(5); + let (c, back_c) = plane.record(host); + host.execute(&[&c]); + TEST_PLANE_SAME.set(None); + assert!(Plane::seen(&back_c) == first, "the first again, not the second left on the card"); + } + + /// A list's prelude (here the plane's move to the copy source state and + /// its upload) is one made ahead on the pool's thread + /// (`crate::host::preludes`), not one made by the submitting thread, and + /// it still runs before the list. (Other tests take preludes at the same + /// time: a pool they emptied between the wait and the submission is + /// tried again.) + #[test] + fn a_list_s_prelude_is_made_ahead_not_by_the_submitting_thread() { + use crate::host::preludes::{MADE_HERE, PRELUDES, READY, on}; + let Some(host) = crate::host::host() else { + eprintln!("SKIP: no D3D12 device (LEONIDA_D3D12_WARP=1 makes one)"); + return; + }; + if !on() { + eprintln!("SKIP: LEONIDA_PRELUDE_POOL=0"); + return; + } + let plane = Plane::new(); + PRELUDES.warm(); + let mut made_here = Vec::new(); + for seed in [7, 11, 13] { + let began = std::time::Instant::now(); + while PRELUDES.len() < READY && began.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + plane.paint(seed); + let (list, back) = plane.record(host); + let before = MADE_HERE.get(); + host.execute(&[&list]); + made_here.push(MADE_HERE.get() - before); + assert!(Plane::seen(&back) == plane.now(), "the prelude ran first: the list copied the plane as it is now"); + if made_here.last() == Some(&0) { + return; + } + } + panic!("preludes made on the submitting thread, by submission: {made_here:?}"); + } +} + +#[cfg(test)] +mod staging_table_tests { + use super::*; + use std::sync::mpsc; + use std::time::Duration; + + /// As [`staging`] asks the table (`LEONIDA_STAGING_SHORT`): while one + /// texture's state is made, another thread finds another texture's; a + /// state made while its texture's host copy was replaced by one with + /// more levels (its state taken out) is not put in, and none comes back. + #[cfg(windows)] + #[test] + fn a_state_is_made_with_the_table_free_and_kept_only_for_its_copy() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + // (With the switch off the make holds the lock the hook asks for.) + if host().is_none() || !crate::resource::held_only() || !table::short() { + return; + } + // 256x256 BC7, nine levels, as in the other tests here. + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = crate::resource::placed_bytes(&desc).unwrap() as usize; + let texture = || { + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + crate::resource::texture_at(at as u64, &desc).unwrap() + }; + let (made, there) = (texture(), texture()); + crate::resource::want_level(there, 0); + let there_copy = crate::resource::host_copy(there).unwrap(); + assert!(staging(there, &there_copy, 0).is_some()); + // A host copy from level 2, then one from level 0 asked for while + // its state is made. + crate::resource::want_level(made, 2); + let copy = crate::resource::host_copy(made).unwrap(); + assert_eq!(copy.base, 2); + let (made_at, there_at) = (made as usize, there as usize); + WHILE_MADE.set(Some(Box::new(move |resource| { + assert_eq!(resource as usize, made_at); + let (tx, found) = mpsc::channel(); + std::thread::spawn(move || tx.send(is_staged(there_at as This)).ok()); + assert_eq!(found.recv_timeout(Duration::from_secs(1)), Ok(true), "the other state, found meanwhile"); + crate::resource::want_level(made_at as This, 0); + }))); + assert!(staging(made, ©, 0).is_none(), "made for a host copy that went: none"); + assert!(WHILE_MADE.take().is_none(), "the hook ran"); + assert!(!is_staged(made), "and none put in"); + // The new host copy gets one. + let grown = crate::resource::host_copy(made).unwrap(); + assert!(grown.serial != copy.serial); + assert!(staging(made, &grown, 0).is_some()); + assert!(is_staged(made)); + } +} + +#[cfg(test)] +mod parts_tests { + use super::*; + use leonida_formats::texture::{Desc, Dimension, Layout, Swizzle}; + + fn layout(swizzle: Swizzle, [width, height, depth, mips]: [u32; 4], element_bytes: u32, block: u32) -> Layout { + Layout::new(&Desc { + dimension: Dimension::Tex2d, + width, + height, + depth, + mips, + element_bytes, + block, + samples: 1, + swizzle, + }) + .unwrap() + } + + /// Level `mip` of slice `slice` of `tiled`, in rows of its own width. + fn detiled(layout: &Layout, tiled: &[u8], mip: u32, slice: u32) -> Vec<u8> { + let m = &layout.mips[mip as usize]; + let pitch = m.width as usize * layout.desc.element_bytes as usize; + let len = pitch * m.height as usize; + let mut out = vec![0u8; len]; + layout.detile(tiled, mip, slice, &mut out, pitch, len).unwrap(); + out + } + + /// Every byte the detiling of a subresource reads lies in its span: + /// with every byte outside it changed, the subresource detiles the + /// same; with the span's own changed, it does not. Linear and the + /// standard and display modes of each block size, block-compressed and + /// plain elements, sizes with and without a mip tail, odd ones. + #[test] + fn a_part_s_span_holds_every_byte_its_detiling_reads() { + let swizzles = [Swizzle::LINEAR, Swizzle::SW_256B_S, Swizzle::SW_4KB_S, Swizzle::SW_4KB_D, Swizzle::SW_64KB_S, Swizzle::SW_64KB_D]; + let shapes = [[256, 256, 3, 9], [100, 60, 2, 7], [64, 64, 6, 7], [512, 128, 1, 10], [40, 24, 4, 1]]; + let elements = [(8, 4), (16, 4), (4, 1), (1, 1)]; + let mut checked = 0; + for swizzle in swizzles { + for shape in shapes { + for (bytes, block) in elements { + let layout = layout(swizzle, shape, bytes, block); + let tiled: Vec<u8> = (0..layout.size as usize).map(|i| (i * 31 + i / 251 + 7) as u8).collect(); + for slice in 0..layout.slices { + for mip in 0..layout.desc.mips { + let (from, to) = part_span(&layout, mip, slice).unwrap(); + let (from, to) = (from as usize, to as usize); + assert!(from < to && to <= layout.size as usize, "{swizzle:?} {shape:?} {bytes}: mip {mip} slice {slice}"); + let expected = detiled(&layout, &tiled, mip, slice); + let mut outside: Vec<u8> = tiled.iter().map(|b| !b).collect(); + outside[from..to].copy_from_slice(&tiled[from..to]); + assert!( + detiled(&layout, &outside, mip, slice) == expected, + "{swizzle:?} {shape:?} {bytes}: mip {mip} slice {slice} reads outside {from:#x}..{to:#x}" + ); + let mut inside = tiled.clone(); + inside[from..to].iter_mut().for_each(|b| *b = !*b); + assert!(detiled(&layout, &inside, mip, slice) != expected, "{swizzle:?} {shape:?} {bytes}: mip {mip} slice {slice}"); + checked += 1; + } + } + } + } + } + assert!(checked > 1000); + // 3D and multisampled layouts are not told apart: all of them. + let three_d = Layout::new(&Desc { dimension: Dimension::Tex3d, ..layout(Swizzle::SW_64KB_S, [64, 64, 8, 4], 4, 1).desc }).unwrap(); + assert_eq!(part_span(&three_d, 0, 0), None); + assert_eq!(parts_touched(&three_d, 0, 4, 4, &[(0, 1)]), None); + } + + /// The parts of a 1024x1024 BC1 cube (`SW_64KB_S`, eleven levels) that + /// writes name: one inside level 0 of slice 3, one inside slice 3's mip + /// tail (the levels there together), and one across the end of slice 2 + /// (its level 0, the last of its chain) into the start of slice 3 (its + /// tail, the first). Of the levels from 1 on, as a host copy that + /// begins there has them. + #[test] + fn the_pages_written_name_the_parts_they_hold() { + let layout = layout(Swizzle::SW_64KB_S, [1024, 1024, 6, 11], 8, 4); + let tail = layout.first_tail_mip; + assert!((2..11).contains(&tail), "the layout has a mip tail, and levels 0 and 1 before it"); + let index = |first: u32, mip: u32, slice: u32| (slice * (11 - first) + mip - first) as usize; + let named = |first: u32, ranges: &[(u64, u64)]| { + let count = (11 - first) as usize * 6; + let parts = parts_touched(&layout, first, 11, count, ranges).unwrap(); + (0..count).filter(|&i| part_in(&parts, i)).collect::<Vec<_>>() + }; + let slice = layout.slice_size; + let level0 = 3 * slice + layout.mips[0].offset; + assert_eq!(named(0, &[(level0 + 4096, level0 + 8192)]), [index(0, 0, 3)]); + assert_eq!(named(0, &[(3 * slice + 100, 3 * slice + 200)]), (tail..11).map(|mip| index(0, mip, 3)).collect::<Vec<_>>()); + let mut across = vec![index(0, 0, 2)]; + across.extend((tail..11).map(|mip| index(0, mip, 3))); + assert_eq!(named(0, &[(3 * slice - 16, 3 * slice + 16)]), across); + // From level 1 on: the same parts, counted from there; a write in + // level 0 of slice 3 names none. + assert_eq!(named(1, &[(level0, level0 + 64)]), [0usize; 0]); + let level1 = 3 * slice + layout.mips[1].offset; + assert_eq!(named(1, &[(level1, level1 + 64)]), [index(1, 1, 3)]); + // Nothing written: nothing named. + assert_eq!(named(0, &[]), [0usize; 0]); + } + + /// The pages written after an asking, cut to the texture and joined + /// where they meet. + #[test] + fn the_pages_written_since_an_asking_are_cut_to_the_texture() { + let page = crate::watch::PAGE; + let start = 10 * page + 0x300; + let size = 3 * page; + // Pages 10 to 13 hold it; 9 and 14 do not. + let written = [(9, 5), (10, 7), (11, 3), (12, 8), (13, 9), (14, 9)]; + assert_eq!( + written_since(start, size, &written, 5), + [(0, (page - 0x300) as u64), ((2 * page - 0x300) as u64, size as u64)] + ); + assert_eq!(written_since(start, size, &written, 2), [(0, size as u64)]); + assert_eq!(written_since(start, size, &written, 9), []); + } + + /// A write-watched texture array, 256x256 BC7 with nine levels in six + /// slices, in memory of our own; what its host copy holds, every + /// subresource, after a list that samples it is submitted. + struct Watched { + at: *mut u8, + whole: usize, + texture: This, + copy: Arc<crate::resource::HostTexture>, + staging: Arc<Staging>, + } + + impl Watched { + fn new() -> Option<Watched> { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + crate::host::host()?; + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0006, 98, 1, 0, 0x105, 0, 0]; + let whole = crate::resource::placed_bytes(&desc)? as usize; + let room = whole.next_multiple_of(crate::watch::PAGE); + // SAFETY: memory of our own that stays for the test's run. + let at = unsafe { VirtualAlloc(std::ptr::null(), room, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }.cast::<u8>(); + assert!(!at.is_null()); + let texture = crate::resource::texture_at(at as u64, &desc)?; + crate::resource::want_level(texture, 0); + let copy = crate::resource::host_copy(texture)?; + let staging = super::staging(texture, ©, 0)?; + assert_eq!(staging.footprints.len(), 54); + let watched = Watched { at, whole, texture, copy, staging }; + watched.paint(0, whole, 13); + Some(watched) + } + + fn paint(&self, from: usize, to: usize, seed: usize) { + // SAFETY: the memory above. + unsafe { (from..to).for_each(|i| self.at.add(i).write((i * seed + i / 509 + seed) as u8)) }; + } + + /// Where level `mip` of slice `slice` begins in the memory. + fn part_at(&self, mip: u32, slice: u32) -> usize { + part_span(&self.staging.layout, mip, slice).unwrap().0 as usize + } + + /// Submits a list that samples the texture and copies every + /// subresource of its host copy out; whether each one holds what + /// the memory does. + fn submit(&self) -> Vec<bool> { + const COPY_SOURCE: u32 = 0x800; + let host = crate::host::host().unwrap(); + let staging = &self.staging; + let bytes = staging.bytes as usize; + // What the thread's read buffer holds is not this texture's: a + // part read through it sees only the bytes read for it. + with_read(staging.read, |read| read.fill(0x5a)); + let back = host.read_back_buffer(staging.bytes.next_multiple_of(512)).unwrap(); + let list = host.new_list().unwrap(); + upload_from(&list, self.texture, 0); + crate::list::ensure_state(&list, self.texture, COPY_SOURCE); + for (i, footprint) in staging.footprints.iter().enumerate() { + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(&back) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(&self.copy.texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: i as u32 }, + }; + // SAFETY: an open list and live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + list.close(); + host.execute(&[&list]); + // SAFETY: the memory above, not written meanwhile. + let tiled = unsafe { std::slice::from_raw_parts(self.at, self.whole) }; + let mut data = std::ptr::null_mut(); + // SAFETY: a read-back buffer of that size, whose list has run. + unsafe { back.Map(0, None, Some(&mut data)).unwrap() }; + // SAFETY: as above. + let seen = unsafe { std::slice::from_raw_parts(data.cast::<u8>(), bytes) }; + let same = staging + .footprints + .iter() + .zip(&staging.rows) + .enumerate() + .map(|(i, (footprint, &rows))| { + let (mip, slice) = staging.part(i); + let f = footprint.Footprint; + let pitch = f.RowPitch as usize; + let len = (pitch * rows as usize).min(bytes - footprint.Offset as usize); + let mut expected = vec![0u8; len]; + staging.layout.detile(tiled, mip, slice, &mut expected, pitch, pitch * rows as usize).unwrap(); + // BC7: 16 bytes a block of 4x4. + let row = f.Width.div_ceil(4) as usize * 16; + (0..rows as usize).all(|r| { + let at = footprint.Offset as usize + r * pitch; + seen[at..at + row] == expected[r * pitch..r * pitch + row] + }) + }) + .collect(); + // SAFETY: mapped above. + unsafe { back.Unmap(0, None) }; + same + } + } + + /// Of `f`'s run on this thread: the subresources detiled, those copied + /// to the card, and the bytes of watched memory read. + fn counted(f: impl FnOnce() -> Vec<bool>) -> (u64, u64, u64, Vec<bool>) { + let before = (DETILED_PARTS.get(), COPIED_PARTS.get(), WATCHED_READ.get()); + let same = f(); + (DETILED_PARTS.get() - before.0, COPIED_PARTS.get() - before.1, WATCHED_READ.get() - before.2, same) + } + + /// What a write to `[from, to)` of the texture's memory names: the parts + /// its 64 KiB pages hold ([`parts_touched`]), and the bytes of theirs + /// read. + fn named(watched: &Watched, from: usize, to: usize) -> (u64, u64) { + let page = crate::watch::PAGE as u64; + let (start, s) = (watched.at as u64, &watched.staging); + let pages = ((start + from as u64) / page * page, (start + to as u64).div_ceil(page) * page); + let range = (pages.0.max(start) - start, (pages.1 - start).min(s.read as u64)); + let parts = parts_touched(&s.layout, s.first, s.mips, s.footprints.len(), &[range]).unwrap(); + let read = s.part_spans(&parts, s.read); + (parts.iter().map(|w| u64::from(w.count_ones())).sum(), read.iter().map(|(a, b)| (b - a) as u64).sum()) + } + + /// On the host: of a write-watched texture array that changes often + /// (it keeps its staging buffer), a write inside level 0 of slice 3 + /// reads, detiles and copies only the subresources its page holds (the + /// layout here puts that level of slice 3, the other levels of slice 3 + /// and the end of slice 2 in it: 10 of 54), and every subresource on + /// the card holds what the memory does after it; so do writes in two + /// slices' mip tails. With `LEONIDA_TEXTURE_PARTS=0`, all 54 are read, + /// detiled and copied, as before. The first detiling and the one into + /// a staging buffer made anew take all of them. + #[test] + fn a_write_detiles_and_copies_only_the_subresources_its_page_holds() { + if !prelude_upload() { + return; + } + let Some(watched) = Watched::new() else { return }; + let all = vec![true; 54]; + TEST_PARTS.set(Some(true)); + TEST_HOT_STAGING_MS.set(Some(60_000)); + let whole = watched.staging.read as u64; + // The first upload, and the first change (its staging buffer went + // after that copy): all of it. + let (detiled, copied, read, same) = counted(|| watched.submit()); + assert_eq!((detiled, copied, read), (54, 54, whole)); + assert_eq!(same, all); + let level0 = watched.part_at(0, 3); + watched.paint(level0 + 4096, level0 + 8192, 29); + let (detiled, copied, read, same) = counted(|| watched.submit()); + assert_eq!((detiled, copied, read), (54, 54, whole), "into a buffer made anew: all of it"); + assert_eq!(same, all); + assert!(watched.staging.staged().is_some(), "detiled twice in the window: it keeps its buffer"); + // Changing often: the subresources the page written holds. + watched.paint(level0 + 4096, level0 + 8192, 31); + let (parts, bytes) = named(&watched, level0 + 4096, level0 + 8192); + assert_eq!(parts, 10); + assert!(bytes < whole / 2); + let (detiled, copied, read, same) = counted(|| watched.submit()); + assert_eq!((detiled, copied, read), (parts, parts, bytes), "those of the page written"); + assert_eq!(same, all, "and every subresource holds what the memory does"); + // Unchanged: nothing. + let (detiled, copied, read, same) = counted(|| watched.submit()); + assert_eq!((detiled, copied, read), (0, 0, 0)); + assert_eq!(same, all); + // Two writes, in the mip tails of slices 0 and 5. + let tail = watched.staging.layout.first_tail_mip; + assert!((1..9).contains(&tail), "the layout has a mip tail"); + let (tail0, tail5) = (watched.part_at(tail, 0), watched.part_at(8, 5)); + watched.paint(tail0, tail0 + 16, 37); + watched.paint(tail5 + 32, tail5 + 48, 41); + let (first, first_bytes) = named(&watched, tail0, tail0 + 16); + let (second, second_bytes) = named(&watched, tail5 + 32, tail5 + 48); + assert!(first + second < 54); + let (detiled, copied, read, same) = counted(|| watched.submit()); + assert_eq!((detiled, copied, read), (first + second, first + second, first_bytes + second_bytes)); + assert_eq!(same, all); + // The switch off: all of it, as before. + TEST_PARTS.set(Some(false)); + watched.paint(level0 + 4096, level0 + 8192, 43); + let (detiled, copied, read, same) = counted(|| watched.submit()); + assert_eq!((detiled, copied, read), (54, 54, whole)); + assert_eq!(same, all); + TEST_PARTS.set(None); + TEST_HOT_STAGING_MS.set(None); + } + + /// On the host: a staging buffer marked to be copied with nothing + /// detiled since (levels on demand asked again for a level the last + /// upload left without tiles, [`upload_from`], which keeps the buffer + /// and only marks it) has every subresource copied, after a copy of all + /// of them and after one of some, with `LEONIDA_TEXTURE_PARTS` on and + /// off: the empty set a copy leaves is not taken for "none of them" + /// (it was: nothing was copied, and the level stayed empty). + #[test] + fn a_buffer_marked_with_nothing_detiled_is_copied_whole() { + use std::sync::atomic::Ordering::Relaxed; + if !prelude_upload() { + return; + } + let Some(watched) = Watched::new() else { return }; + let all = vec![true; 54]; + TEST_PARTS.set(Some(true)); + TEST_HOT_STAGING_MS.set(Some(60_000)); + let level0 = watched.part_at(0, 3); + // The first upload, and a change into a buffer made anew: all of + // it; the buffer is kept from then on. + assert_eq!(counted(|| watched.submit()).3, all); + watched.paint(level0 + 4096, level0 + 8192, 29); + assert_eq!(counted(|| watched.submit()).1, 54); + assert!(watched.staging.staged().is_some()); + // Marked, nothing written: all of it copied, nothing detiled. + watched.staging.dirty.store(true, Relaxed); + let (detiled, copied, _, same) = counted(|| watched.submit()); + assert_eq!((detiled, copied), (0, 54), "a marked buffer is copied whole"); + assert_eq!(same, all); + // After a copy of some parts, as well. + watched.paint(level0 + 4096, level0 + 8192, 31); + let (parts, _) = named(&watched, level0 + 4096, level0 + 8192); + assert_eq!(counted(|| watched.submit()).1, parts); + watched.staging.dirty.store(true, Relaxed); + assert_eq!(counted(|| watched.submit()).1, 54); + // The switch off: all of it, as before. + TEST_PARTS.set(Some(false)); + watched.staging.dirty.store(true, Relaxed); + assert_eq!(counted(|| watched.submit()).1, 54); + TEST_PARTS.set(None); + TEST_HOT_STAGING_MS.set(None); + } + + /// A free or protection of pages a texture is detiled from in place + /// waits until that read is over, one of other pages does not, and no + /// read in place begins over pages whose free is under way. + #[test] + fn a_free_waits_for_a_read_in_place_of_its_pages() { + // Ranges only: nothing is read or freed there. + const AT: usize = 0x7ffe_0000_0000; + TEST_IN_PLACE.set(Some(true)); + let read = InPlaceRead::begin(AT, 0x1_0000).expect("nothing frees those pages"); + drop(title_memory_going(AT + 0x1_0000, 0x1000)); + let (sent, freed) = std::sync::mpsc::channel(); + let free = std::thread::spawn(move || { + TEST_IN_PLACE.set(Some(true)); + let _going = title_memory_going(AT + 0x8000, 0x1000); + sent.send(()).unwrap(); + }); + assert!(freed.recv_timeout(std::time::Duration::from_millis(300)).is_err(), "the free waits for the read"); + drop(read); + freed.recv_timeout(std::time::Duration::from_secs(10)).expect("and is done once the read is over"); + free.join().unwrap(); + // A free of a whole allocation (no length): nothing from its start on + // is read in place until it is done; what lies before it is. + let going = title_memory_going(AT, 0); + assert!(InPlaceRead::begin(AT + 0x10_0000, 16).is_none()); + assert!(InPlaceRead::begin(AT - 0x1_0000, 0x1000).is_some()); + drop(going); + assert!(InPlaceRead::begin(AT, 16).is_some()); + // The switch off (the default): nothing reads in place, and a free + // takes no lock and stops no read (none would begin). + TEST_IN_PLACE.set(Some(false)); + let going = title_memory_going(AT, 0); + assert!(!in_place().going.contains(&(AT, usize::MAX)), "a free with the switch off was registered"); + assert!(InPlaceRead::begin(AT, 16).is_some()); + drop(going); + TEST_IN_PLACE.set(None); + } + + /// On the host, with `LEONIDA_TEXTURE_WATCHED_IN_PLACE=1`: a + /// write-watched texture is detiled where it lies, whole and in parts, + /// nothing copied into the read buffer, and every subresource on the card + /// holds what the memory does; while a free of its pages is under way it + /// is read through the copy, as it is with the switch off (as before). + #[test] + fn a_watched_texture_is_detiled_where_it_lies() { + if !prelude_upload() { + return; + } + let Some(watched) = Watched::new() else { return }; + let all = vec![true; 54]; + TEST_PARTS.set(Some(true)); + TEST_IN_PLACE.set(Some(true)); + TEST_HOT_STAGING_MS.set(Some(60_000)); + // Bytes read through the copy, and detiled in place. + let run = || { + let before = (WATCHED_READ.get(), WATCHED_IN_PLACE.get()); + let same = watched.submit(); + (WATCHED_READ.get() - before.0, WATCHED_IN_PLACE.get() - before.1, same) + }; + let whole = watched.staging.read as u64; + assert_eq!(run(), (0, whole, all.clone())); + let level0 = watched.part_at(0, 3); + watched.paint(level0 + 4096, level0 + 8192, 29); + assert_eq!(run(), (0, whole, all.clone()), "into a buffer made anew: all of it"); + watched.paint(level0 + 4096, level0 + 8192, 31); + let (_, bytes) = named(&watched, level0 + 4096, level0 + 8192); + assert_eq!(run(), (0, bytes, all.clone()), "the parts written"); + // The title frees some of it meanwhile (here only said so). + let going = title_memory_going(watched.at as usize + watched.whole - 16, 16); + watched.paint(level0 + 4096, level0 + 8192, 37); + assert_eq!(run(), (bytes, 0, all.clone()), "through the copy"); + drop(going); + TEST_IN_PLACE.set(Some(false)); + watched.paint(level0 + 4096, level0 + 8192, 41); + assert_eq!(run(), (bytes, 0, all.clone()), "the switch off: through the copy, as before"); + TEST_IN_PLACE.set(None); + TEST_PARTS.set(None); + TEST_HOT_STAGING_MS.set(None); + } +} + #[cfg(test)] mod title_memory_tests { use super::with_title; @@ -3482,6 +5640,93 @@ mod title_memory_tests { } } +#[cfg(test)] +mod read_buffer_tests { + use super::{LARGE_READS, READ, idle_reads, read_kept, take_read, with_read}; + + /// The capacity of this thread's own read buffer. + fn room() -> usize { + READ.with(|read| read.borrow().capacity()) + } + + /// A thread that refreshes textures keeps a read buffer of up to the + /// kept bytes from one texture to the next, but not the room of a larger + /// texture once its read is over: those threads (the submitting one and + /// the helpers of `shadow::wide_each`) live for the run, and each held + /// the largest texture it ever read until the end. That room waits in + /// the shared pool for the next large read instead. The reads run on + /// threads of their own, as refreshes do, so that the buffer of the + /// thread the harness runs the test on (shared by the tests with + /// `--test-threads=1`) plays no part. No other test reads a texture + /// larger than the kept bytes, so the shared pool is this test's alone. + #[test] + fn a_large_read_gives_its_room_back_when_it_is_over() { + let kept = read_kept(); + // Larger than the kept bytes, whatever LEONIDA_TEXTURE_READ_KEEP_MB + // says. + let large = 2 * kept.max(1 << 20); + std::thread::scope(|threads| { + for _ in 0..2 { + threads.spawn(|| { + // Up to the kept bytes: kept for the next texture, also + // when the buffer grows from one under them. + with_read(kept * 5 / 8, |read| read.fill(1)); + with_read(kept * 3 / 4, |read| read.fill(1)); + assert!(room() >= kept * 3 / 4, "a read under the kept bytes keeps its room"); + // A larger texture is read whole, then the thread does + // not keep its room. + with_read(large, |read| { + assert_eq!(read.len(), large); + read[large - 1] = 2; + }); + assert!(room() <= kept, "{} MiB kept after a read of {} MiB", room() >> 20, large >> 20); + // And the next read is served as before. + with_read(4096, |read| assert_eq!(read.len(), 4096)); + }); + } + }); + // The pool holds a buffer for each of the large reads that ran at + // once (one or two, as the threads overlapped), each large enough. + let pooled: Vec<(usize, usize)> = LARGE_READS + .lock() + .unwrap() + .iter() + .map(|(read, _)| (read.as_ptr() as usize, read.len())) + .collect(); + assert!((1..=2).contains(&pooled.len()), "{} buffers pooled after two large reads", pooled.len()); + assert!(pooled.iter().all(|&(_, len)| len >= large)); + // The next large read, on another thread, takes one of them instead + // of making its room again. + let took = std::thread::spawn(move || with_read(large, |read| read.as_ptr() as usize)).join().unwrap(); + assert!(pooled.iter().any(|&(at, _)| at == took), "a large read reuses a pooled buffer"); + // (Their memory goes now, not at the end of the run of tests.) + LARGE_READS.lock().unwrap().clear(); + } + + /// The shared pool hands out the smallest buffer large enough for a + /// read, and the largest when none is (the reader makes it again + /// larger), so it holds no more buffers than reads ran at once; and it + /// lets go of those no read took for the idle time, while the ones given + /// back since stay. + #[test] + fn the_pool_of_large_reads_reuses_its_buffers_and_lets_the_idle_ones_go() { + const IDLE_MS: u64 = 10_000; + let mut pool: Vec<(Vec<u8>, u64)> = vec![(vec![0; 3000], 1_000), (vec![0; 9000], 1_000), (vec![0; 5000], 9_000)]; + assert_eq!(take_read(&mut pool, 4000).len(), 5000, "the smallest buffer large enough"); + assert_eq!(take_read(&mut pool, 20_000).len(), 9000, "the largest when none is large enough"); + assert_eq!(take_read(&mut pool, 1).len(), 3000); + assert!(take_read(&mut pool, 1).is_empty(), "an empty pool has none to give"); + // Two buffers given back at 1 s and one at 9 s. + let mut pool: Vec<(Vec<u8>, u64)> = vec![(vec![0; 3000], 1_000), (vec![0; 3000], 1_000), (vec![0; 3000], 9_000)]; + assert!(idle_reads(&mut pool, 10_999, IDLE_MS).is_empty(), "none goes under the idle time"); + let gone = idle_reads(&mut pool, 11_000, IDLE_MS); + assert_eq!(gone.len(), 2, "{} of the two idle buffers let go", gone.len()); + assert_eq!(pool.iter().map(|(_, at)| *at).collect::<Vec<_>>(), [9_000]); + assert_eq!(idle_reads(&mut pool, 19_000, IDLE_MS).len(), 1); + assert!(pool.is_empty()); + } +} + /// How long this PC's card takes to make the allocations a staged texture needs, for /// `cargo test -p leonida-gpu allocation_costs -- --ignored --nocapture`. #[cfg(test)] diff --git a/d3d12/crates/leonida-gpu/src/texture/ahead.rs b/d3d12/crates/leonida-gpu/src/texture/ahead.rs index ab082e4d87..48dc6c8d9e 100644 --- a/d3d12/crates/leonida-gpu/src/texture/ahead.rs +++ b/d3d12/crates/leonida-gpu/src/texture/ahead.rs @@ -149,6 +149,13 @@ pub(crate) fn send(job: &Arc<Job>) { QUEUE.1.notify_one(); } +/// Whether an upload is on its way here ([`drain`] would wait for it): a +/// decoration bake that finds none, and nothing else to do, passes without +/// the bake's lock (`crate::draw` `bake_can_skip`). +pub(crate) fn in_flight() -> bool { + IN_FLIGHT.load(std::sync::atomic::Ordering::Acquire) != 0 +} + /// Waits until every upload currently on its way here has finished copying /// and run its completion callbacks (queuing slot flips into `FLIPS`). /// Returns how many jobs were waited for. @@ -253,24 +260,43 @@ impl Worker { } } value += 1; - if let Err(e) = self.copy(&jobs, value) { + let mut copied = vec![false; jobs.len()]; + if let Err(e) = self.copy(&jobs, value, &mut copied) { tracing::warn!(error = %e, "uploads ahead did not run"); + copied.fill(false); } - finish(jobs); + finish(jobs, &copied); } } - fn copy(&self, jobs: &[Arc<Job>], value: u64) -> windows::core::Result<()> { - for job in jobs { - job.staging.refresh(); - } + /// Records and runs the jobs' copies; `copied[i]`: job `i`'s was recorded. + fn copy(&self, jobs: &[Arc<Job>], value: u64, copied: &mut [bool]) -> windows::core::Result<()> { + // What the copies read, held until after the wait: taken right after + // the detiling into it, as a list's submission may copy the buffer + // and let go of it ([`super::release_staging`]) once `listed` gave + // up waiting. A job without one records nothing (`finish` leaves its + // texture to the lists): its detiling had none (none could be had, + // or a video's plane, which has none of its own, found nothing to + // detile), or a list took it, which copied what it held. A buffer + // made here would copy zeros over the host copy. + let held: Vec<_> = jobs + .iter() + .map(|job| { + job.staging.refresh(); + job.staging.staged() + }) + .collect(); // SAFETY: this worker's allocator and list, whose last submission has - // run; the jobs hold what the list names until after the wait. + // run; the jobs and `held` hold what the list names until after the + // wait. unsafe { self.allocator.Reset()?; self.list.Reset(&self.allocator, None)?; - for job in jobs { - job.record(&self.list); + for ((job, staged), copied) in jobs.iter().zip(&held).zip(copied.iter_mut()) { + if let Some(staged) = staged { + job.record(&self.list, staged); + *copied = true; + } } self.list.Close()?; self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]); @@ -283,9 +309,12 @@ impl Worker { } impl Job { + /// Records the copies from `staged`, the job's staging buffer. + /// /// # Safety - /// `list` is an open copy list, and the job lives until it has run. - unsafe fn record(&self, list: &ID3D12GraphicsCommandList) { + /// `list` is an open copy list, and the job and `staged` live until it + /// has run. + unsafe fn record(&self, list: &ID3D12GraphicsCommandList, staged: &super::Staged) { let (s, texture) = (&self.staging, &self.copy.texture); for (i, footprint) in s.footprints.iter().enumerate() { let to = D3D12_TEXTURE_COPY_LOCATION { @@ -296,10 +325,10 @@ impl Job { }; let from = D3D12_TEXTURE_COPY_LOCATION { // SAFETY: as above. - pResource: unsafe { std::mem::transmute_copy(&s.buffer) }, + pResource: unsafe { std::mem::transmute_copy(&staged.buffer) }, Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: s.base + footprint.Offset, ..*footprint }, + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: staged.base + footprint.Offset, ..*footprint }, }, }; // SAFETY: the caller's. @@ -308,14 +337,25 @@ impl Job { } } -/// The jobs' copies have run. -fn finish(jobs: Vec<Arc<Job>>) { - for job in &jobs { +/// The jobs' copies have run, those `copied` says were recorded. A job +/// whose copy was not leaves its host copy as it was (never written, or +/// what a list brought) and to the lists, as one taken by a list +/// ([`LISTED`]): not [`there`], and not known to hold anything, so the next +/// list that samples it uploads it, the first upload (with its aliasing +/// barrier) if none has run. What waits for it is told all the same. +fn finish(jobs: Vec<Arc<Job>>, copied: &[bool]) { + for (job, &copied) in jobs.iter().zip(copied) { + BYTES.fetch_sub(job.staging.read as u64, Relaxed); + if !copied { + job.copy.ahead.store(LISTED, Relaxed); + continue; + } job.staging.uploaded.store(true, Relaxed); job.staging.dirty.store(false, Relaxed); job.staging.note_held(); + // The copy has run: its staging buffer goes, as after a prelude's. + job.staging.copied(); job.copy.ahead.store(DONE, Relaxed); - BYTES.fetch_sub(job.staging.read as u64, Relaxed); } for job in &jobs { let us = job.asked.elapsed().as_micros() as u64; @@ -444,6 +484,91 @@ mod tests { } } + /// A job that recorded no copy (no staging buffer could be had) does not + /// leave its texture taken for filled: the slots that wait for it are + /// still told, and the next list that samples it uploads it, as the first + /// upload (the host copy, cut from a block, was never written). + #[test] + fn a_job_that_copied_nothing_leaves_the_texture_to_the_lists() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const COPY_SOURCE: u32 = 0x800; + let Some(host) = crate::host::host() else { return }; + // 128x128 BC7, eight levels. + let desc = [3u32, 0, 0, 0, 128, 0, 128, 0x8_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = crate::resource::placed_bytes(&desc).unwrap() as usize; + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>(); + // SAFETY: as above. + unsafe { (0..whole).for_each(|i| at.add(i).write((i * 7 + i / 311 + 1) as u8)) }; + let texture = crate::resource::texture_at(at as u64, &desc).unwrap(); + crate::resource::want_level(texture, 0); + let copy = crate::resource::host_copy(texture).unwrap(); + if !crate::pool::fresh(©.texture) { + return; + } + let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") }; + // Its staging buffer went, and none can be had for its detiling or + // its copy. + job.staging.let_go_staged(); + super::super::TEST_NO_STAGED.lock().unwrap().push(texture as usize); + let (told, heard) = std::sync::mpsc::channel(); + job.then(move || told.send(()).unwrap()); + send(&job); + let told = heard.recv_timeout(std::time::Duration::from_secs(20)); + super::super::TEST_NO_STAGED.lock().unwrap().retain(|&r| r != texture as usize); + assert_eq!(told, Ok(()), "the slots that wait for it are told"); + assert!(!there(texture), "nothing was copied: not filled ahead"); + assert!(!job.staging.uploaded.load(Relaxed), "and not uploaded"); + assert!(copy.holds.lock().unwrap().is_none(), "the host copy holds nothing known"); + // A list that samples it uploads it. + let layout = crate::resource::texture_memory(texture) + .and_then(|(_, d)| crate::resource::texture_layout(&d).map(|t| t.planes[0].layout.clone())) + .unwrap(); + let (pitch, rows) = (512usize, 32usize); + let mut expected = vec![0u8; pitch * rows]; + // SAFETY: the memory above. + let tiled = unsafe { std::slice::from_raw_parts(at, whole) }; + layout.detile(tiled, 0, 0, &mut expected, pitch, pitch * rows).unwrap(); + let back = host.read_back_buffer((pitch * rows) as u64).unwrap(); + let list = host.new_list().unwrap(); + crate::texture::upload_from(&list, texture, 0); + crate::list::ensure_state(&list, texture, COPY_SOURCE); + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(&back) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(98), + Width: 128, + Height: 128, + Depth: 1, + RowPitch: pitch as u32, + }, + }, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(©.texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + // SAFETY: an open list, live resources; the mapping spans the buffer. + unsafe { + list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None); + list.close(); + host.execute(&[&list]); + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + let seen = std::slice::from_raw_parts(data.cast::<u8>(), pitch * rows); + assert!(seen == expected.as_slice(), "level 0's blocks, uploaded by the list"); + back.Unmap(0, None); + } + } + #[test] fn drain_waits_until_then_callbacks_have_run() { use std::sync::atomic::AtomicBool; diff --git a/d3d12/crates/leonida-gpu/src/texture/table.rs b/d3d12/crates/leonida-gpu/src/texture/table.rs new file mode 100644 index 0000000000..1283f7ecbc --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/texture/table.rs @@ -0,0 +1,464 @@ +//! The table of staging states ([`super::STAGING`]) held only to look an +//! entry up, put one in or take one out (`LEONIDA_STAGING_SHORT`; on). +//! +//! Every recording thread that samples a texture the title fills asks the +//! table for its staging state. A state was made under the table's lock: +//! the texture's layout and footprints, a log line, and the staging buffer, +//! a pool piece zeroed (megabytes written) or an upload buffer of its own +//! (a committed resource). The idle sweep let go of staging buffers and +//! states under it too, each a pool piece given back or a resource +//! released, and so did a texture's release ([`super::forget`]) and every +//! [`super::unstage`]. While a texture streamed in, the other recording +//! threads waited behind that work for a texture each of them already had a +//! state for, inside their draws and dispatches. +//! +//! Now a state is made with the lock let go ([`get_or_make`]); two threads +//! that make one for the same texture at once both make it, the first put +//! in stays and the other goes (its buffer back to the pool) with the lock +//! let go. What is taken out of the table goes after the lock too +//! ([`take_out`], [`sweep`]). A texture whose host copy went while its state +//! was made gets none ([`get_or_make`]'s `still`). A texture's release waits +//! for a make of its state ([`Gone`]), as it waited for the lock before: the +//! make reads the title texture, and so does `still`, until it is done. +//! `LEONIDA_STAGING_SHORT=0`: made and let go under the lock, as before. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard}; + +/// A table of title resources' states, by resource, as [`super::STAGING`]. +pub(super) type Table<V> = Mutex<Option<HashMap<usize, Arc<V>>>>; + +type Held<'a, V> = MutexGuard<'a, Option<HashMap<usize, Arc<V>>>>; + +/// Whether a staging state is made, and let go of, with the table's lock let +/// go (`LEONIDA_STAGING_SHORT`; on); `=0`: under it, as before. +pub(super) fn short() -> bool { + crate::toggled!("LEONIDA_STAGING_SHORT") +} + +fn lock<V>(table: &Table<V>) -> Held<'_, V> { + table.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// What takes entries out of a table ([`take_out`]) and what makes them with +/// its lock let go ([`get_or_make`]) tell each other: how many were taken +/// out, and the keys whose entries are being made, which a release waits for. +pub(super) struct Gone { + count: AtomicU64, + /// Keys being made now, once per make (few at a time). + making: Mutex<Vec<usize>>, + made: Condvar, +} + +impl Gone { + pub(super) const fn new() -> Self { + Self { count: AtomicU64::new(0), making: Mutex::new(Vec::new()), made: Condvar::new() } + } + + /// `key` noted as being made until what comes back goes. Under the + /// table's lock (taken before this one), so that a take-out sees it. + fn making(&self, key: usize) -> Making<'_> { + self.making.lock().unwrap_or_else(|e| e.into_inner()).push(key); + Making { gone: self, key } + } + + /// Waits until no make of `key` is under way (with no other lock held). + fn wait_made(&self, key: usize) { + let mut making = self.making.lock().unwrap_or_else(|e| e.into_inner()); + while making.contains(&key) { + making = self.made.wait(making).unwrap_or_else(|e| e.into_inner()); + } + } +} + +/// A make of `key` under way ([`Gone::making`]). +struct Making<'a> { + gone: &'a Gone, + key: usize, +} + +impl Drop for Making<'_> { + fn drop(&mut self) { + let mut making = self.gone.making.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(at) = making.iter().position(|&k| k == self.key) { + making.swap_remove(at); + } + drop(making); + self.gone.made.notify_all(); + } +} + +/// `key`'s entry of `table` if `is_current` takes it, else one `make` makes +/// (`None`: it made none, and the entry there stays) put in its place. +/// +/// With `short`, `make` runs with the lock let go. Put in afterwards, the +/// entry another thread put in meanwhile wins if `is_current` takes it; +/// else ours replaces what is there. If `gone` (counted under the lock by +/// whatever takes entries out, [`take_out`]) moved since the look, an entry +/// may have been taken out that `make` came before: ours goes in only if +/// `still` (asked with the lock let go) says what it was made for is there +/// yet; else `None`, as if none could be made. The entry that loses, or one +/// replaced, goes with the lock let go. A release of `key` waits from the +/// look until this returns, `still` included. Without `short`, all under +/// the lock, as before. +pub(super) fn get_or_make<V>( + table: &Table<V>, + key: usize, + gone: &Gone, + is_current: impl Fn(&V) -> bool, + make: impl FnOnce() -> Option<V>, + still: impl Fn() -> bool, + short: bool, +) -> Option<Arc<V>> { + let mut held = lock(table); + let entries = held.get_or_insert_with(HashMap::new); + if let Some(v) = entries.get(&key) + && is_current(v) + { + return Some(v.clone()); + } + if !short { + let v = Arc::new(make()?); + entries.insert(key, v.clone()); + return Some(v); + } + let mut seen = gone.count.load(Relaxed); + let _making = gone.making(key); + drop(held); + let ours = Arc::new(make()?); + loop { + let mut held = lock(table); + let entries = held.get_or_insert_with(HashMap::new); + if let Some(v) = entries.get(&key) + && is_current(v) + { + let theirs = v.clone(); + drop(held); + drop(ours); + return Some(theirs); + } + let now = gone.count.load(Relaxed); + if now == seen { + let old = entries.insert(key, ours.clone()); + drop(held); + drop(old); + return Some(ours); + } + // (Asked with the lock let go: the host side is locked before the + // table, `super::unstage`'s callers.) + seen = now; + drop(held); + if !still() { + return None; + } + } +} + +/// Takes `key`'s entry out of `table` and counts it in `gone` +/// ([`get_or_make`]). With `short` the entry goes with the lock let go and +/// `None` comes back; without, it goes under the lock, which comes back held +/// (for [`super::forget`] to hold over its other tables, as before). +/// +/// A `release` (the title let go of the texture, [`super::forget`]) then +/// waits for a make of `key` under way: the make, and its `still`, read the +/// texture, which goes when this returns. (Without `short` the lock waited +/// for it; a make begun with the lock let go before the switch turned, +/// `LEONIDA_AB`, is waited for before it is taken.) Not for an +/// [`super::unstage`]: its callers hold the texture's host side, which a +/// make's `still` locks. +pub(super) fn take_out<'a, V>( + table: &'a Table<V>, + key: usize, + gone: &Gone, + short: bool, + release: bool, +) -> Option<Held<'a, V>> { + if !short && release { + gone.wait_made(key); + } + let mut held = lock(table); + let out = held.as_mut().and_then(|entries| entries.remove(&key)); + gone.count.fetch_add(1, Relaxed); + if !short { + drop(out); + return Some(held); + } + drop(held); + drop(out); + if release { + gone.wait_made(key); + } + None +} + +/// Under `table`'s lock, unless it is empty: `first` over the entries (what +/// it gives back it took from them), then takes out those `keep` refuses. +/// With `short` both go with the lock let go; without, under it, as before. +pub(super) fn sweep<V, W>( + table: &Table<V>, + short: bool, + first: impl FnOnce(&HashMap<usize, Arc<V>>) -> W, + mut keep: impl FnMut(&Arc<V>) -> bool, +) { + let mut held = lock(table); + let Some(entries) = held.as_mut() else { + return; + }; + if entries.is_empty() { + return; + } + let taken = first(entries); + if !short { + drop(taken); + entries.retain(|_, v| keep(v)); + return; + } + let out: Vec<Arc<V>> = entries.extract_if(|_, v| !keep(v)).map(|(_, v)| v).collect(); + drop(held); + drop(taken); + drop(out); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::AtomicUsize; + use std::sync::mpsc; + use std::time::{Duration, Instant}; + + fn table_of(entries: &[(usize, u32)]) -> Table<u32> { + Mutex::new(Some(entries.iter().map(|&(k, v)| (k, Arc::new(v))).collect())) + } + + /// Asks `table` for key 2, there already, on another thread while this + /// one makes key 1's entry (which waits until told); whether that ask + /// came back within `within`. The make is let go afterwards either way. + fn other_key_answers_while_one_is_made(short: bool, within: Duration) -> bool { + let table = Arc::new(table_of(&[(2, 20)])); + let gone = Arc::new(Gone::new()); + let (entered_tx, entered) = mpsc::channel(); + let (go, go_rx) = mpsc::channel::<()>(); + let maker = { + let (table, gone) = (table.clone(), gone.clone()); + std::thread::spawn(move || { + get_or_make( + &table, + 1, + &gone, + |_| true, + || { + entered_tx.send(()).unwrap(); + go_rx.recv_timeout(Duration::from_secs(10)).ok(); + Some(10) + }, + || true, + short, + ) + }) + }; + entered.recv_timeout(Duration::from_secs(10)).expect("the make started"); + let (answer_tx, answer) = mpsc::channel(); + let asker = { + let (table, gone) = (table.clone(), gone.clone()); + std::thread::spawn(move || { + let v = get_or_make(&table, 2, &gone, |_| true, || Some(0), || true, short); + answer_tx.send(v.map(|v| *v)).ok(); + }) + }; + let answered = answer.recv_timeout(within); + go.send(()).ok(); + assert_eq!(*maker.join().unwrap().unwrap(), 10); + asker.join().unwrap(); + if let Ok(v) = answered { + assert_eq!(v, Some(20), "key 2's own entry, not one made"); + } + answered.is_ok() + } + + /// A thread asking for a texture it has a state for does not wait while + /// another thread makes the state of another texture. + #[test] + fn an_entry_there_is_found_while_another_is_made() { + assert!(other_key_answers_while_one_is_made(true, Duration::from_secs(1))); + } + + /// As before (`LEONIDA_STAGING_SHORT=0`): it waits behind the make. + #[test] + fn under_the_lock_the_ask_waits_behind_the_make() { + assert!(!other_key_answers_while_one_is_made(false, Duration::from_millis(300))); + } + + /// Counts its drops. + struct Counted(Arc<AtomicUsize>); + + impl Drop for Counted { + fn drop(&mut self) { + self.0.fetch_add(1, Relaxed); + } + } + + /// Two threads that make the same key's entry at once both make one; the + /// first put in is the one both get and the table keeps, the other goes, + /// once. + #[test] + fn two_makes_of_one_key_leave_one_entry() { + let table: Arc<Table<Counted>> = Arc::new(Mutex::new(None)); + let gone = Arc::new(Gone::new()); + let (made, dropped) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let makers: Vec<_> = (0..2) + .map(|_| { + let (table, gone, made, dropped) = (table.clone(), gone.clone(), made.clone(), dropped.clone()); + std::thread::spawn(move || { + get_or_make( + &table, + 7, + &gone, + |_| true, + || { + // Both inside their make before either puts in + // (given up after a while: under the lock only one + // ever is). + made.fetch_add(1, Relaxed); + let until = Instant::now() + Duration::from_secs(2); + while made.load(Relaxed) < 2 && Instant::now() < until { + std::thread::yield_now(); + } + Some(Counted(dropped.clone())) + }, + || true, + true, + ) + .unwrap() + }) + }) + .collect(); + let got: Vec<Arc<Counted>> = makers.into_iter().map(|t| t.join().unwrap()).collect(); + assert_eq!(made.load(Relaxed), 2, "both made one"); + assert!(Arc::ptr_eq(&got[0], &got[1]), "both got the one put in first"); + assert_eq!(dropped.load(Relaxed), 1, "the other went, once"); + let held = table.lock().unwrap(); + let entries = held.as_ref().unwrap(); + assert_eq!(entries.len(), 1); + assert!(Arc::ptr_eq(&entries[&7], &got[0])); + } + + /// An entry taken out while ours was made (a texture released) is not + /// put back if what it was made for is gone; if it is there yet, it is. + #[test] + fn an_entry_made_across_a_take_out_goes_in_only_if_still_wanted() { + for still in [false, true] { + let table = table_of(&[]); + let gone = Gone::new(); + let got = get_or_make( + &table, + 3, + &gone, + |_| true, + || { + drop(take_out(&table, 3, &gone, true, false)); + Some(30) + }, + || still, + true, + ); + assert_eq!(got.map(|v| *v), still.then_some(30)); + let held = table.lock().unwrap(); + assert_eq!(held.as_ref().unwrap().contains_key(&3), still); + } + } + + /// An entry that says, as it goes, whether its table's lock was free. + struct Probe { + table: &'static Table<Probe>, + free: &'static Mutex<Vec<bool>>, + } + + impl Drop for Probe { + fn drop(&mut self) { + let free = self.table.try_lock().is_ok(); + self.free.lock().unwrap().push(free); + } + } + + /// Fills `table` with `n` probes (keys 0..n) reporting into `free`. + fn fill(table: &'static Table<Probe>, free: &'static Mutex<Vec<bool>>, n: usize) { + *table.lock().unwrap() = Some((0..n).map(|k| (k, Arc::new(Probe { table, free }))).collect()); + } + + /// What a texture's release, the sweep and the sweep's taking of buffers + /// let go of goes with the table's lock free; under it as before. + #[test] + fn what_is_taken_out_goes_with_the_lock_free() { + static TABLE: Table<Probe> = Mutex::new(None); + static FREE: Mutex<Vec<bool>> = Mutex::new(Vec::new()); + for short in [true, false] { + let gone = Gone::new(); + fill(&TABLE, &FREE, 4); + FREE.lock().unwrap().clear(); + drop(take_out(&TABLE, 0, &gone, short, false)); + assert_eq!(gone.count.load(Relaxed), 1); + // The sweep: what it takes from the entries (a buffer: here a + // probe too), then the other three entries let go. + sweep(&TABLE, short, |_| Arc::new(Probe { table: &TABLE, free: &FREE }), |_| false); + let free = std::mem::take(&mut *FREE.lock().unwrap()); + assert_eq!(free.len(), 5, "short {short}: the one taken out, the one taken, the three swept"); + assert!(free.iter().all(|&f| f == short), "short {short}: lock free as they went: {free:?}"); + assert!(TABLE.lock().unwrap().as_ref().unwrap().is_empty()); + } + } + + /// A release of a texture whose state is being made with the lock let go + /// waits until the make, and its `still`, are done (both read the + /// texture, which goes when the release returns); the release of another + /// texture, and a take-out that is no release, do not wait. + #[test] + fn a_release_waits_for_the_make_of_its_key_only() { + use std::sync::atomic::AtomicBool; + let table = Arc::new(table_of(&[])); + let gone = Arc::new(Gone::new()); + let released = Arc::new(AtomicBool::new(false)); + let (entered_tx, entered) = mpsc::channel(); + let (go, go_rx) = mpsc::channel::<()>(); + let maker = { + let (table, gone, released) = (table.clone(), gone.clone(), released.clone()); + std::thread::spawn(move || { + get_or_make( + &table, + 1, + &gone, + |_| true, + || { + entered_tx.send(()).unwrap(); + go_rx.recv_timeout(Duration::from_secs(10)).ok(); + Some(10) + }, + || !released.load(Relaxed), + true, + ) + .map(|v| *v) + }) + }; + entered.recv_timeout(Duration::from_secs(10)).expect("the make started"); + // (A hang here would show as the test never ending: each returns at + // once.) + assert!(take_out(&table, 2, &gone, true, true).is_none()); + assert!(take_out(&table, 1, &gone, true, false).is_none()); + let (done_tx, done) = mpsc::channel(); + let releaser = { + let (table, gone) = (table.clone(), gone.clone()); + std::thread::spawn(move || { + // As a texture's release: its host copy goes first. + released.store(true, Relaxed); + drop(take_out(&table, 1, &gone, true, true)); + done_tx.send(()).ok(); + }) + }; + assert!(done.recv_timeout(Duration::from_millis(300)).is_err(), "the release waits for the make"); + go.send(()).ok(); + assert_eq!(maker.join().unwrap(), None, "made for a texture released meanwhile: none"); + done.recv_timeout(Duration::from_secs(10)).expect("then the release ends"); + releaser.join().unwrap(); + assert!(!table.lock().unwrap().as_ref().unwrap().contains_key(&1), "and none put in"); + } +} diff --git a/d3d12/crates/leonida-gpu/src/upload.rs b/d3d12/crates/leonida-gpu/src/upload.rs index 172d6928d3..da24907b4e 100644 --- a/d3d12/crates/leonida-gpu/src/upload.rs +++ b/d3d12/crates/leonida-gpu/src/upload.rs @@ -8,7 +8,8 @@ //! zeros. So this memory is taken in blocks of 64 KiB out of arenas in //! [4 GiB, 2^37), as upstream VIctory 0f637570 and 6d021fe3 place it (there //! an allocation of its own each). An arena is a title buffer to the host -//! copies ([`crate::shadow`]) and lives as long as the process: the directory +//! copies ([`crate::shadow`]; in place with `LEONIDA_INPLACE` on, +//! `crate::inplace::ours`) and lives as long as the process: the directory //! of memory by address ([`crate::memory`]) keeps the copy it found at an //! address for good, so the same addresses must stay the same copy. //! `LEONIDA_UPLOAD_LOW=0`: from the process heap, as before. @@ -100,7 +101,9 @@ impl Upload { None => { let blocks = n.max(ARENA / BLOCK); let at = reserve(blocks * BLOCK)?; - crate::shadow::register(at, at as u64, (blocks * BLOCK) as u64); + // Memory of ours: in place, not copied as the title's, with + // `LEONIDA_INPLACE` on (`crate::inplace::ours`). + crate::shadow::register_ours(at, at as u64, (blocks * BLOCK) as u64); tracing::info!(at = format_args!("{at:#x}"), bytes = blocks * BLOCK, "memory for lists' uploads, where shaders reach it by address"); arenas.push(Arena { at, taken: vec![false; blocks] }); (arenas.len() - 1, 0) @@ -122,8 +125,17 @@ impl Upload { } } +/// Where the uploads given back started, in order, so the tests can see +/// which were. +#[cfg(test)] +pub(crate) static GIVEN_BACK: Mutex<Vec<usize>> = Mutex::new(Vec::new()); + impl Drop for Upload { fn drop(&mut self) { + // Noted before the blocks are free, so that an upload made at the + // same place later is noted after this one. + #[cfg(test)] + GIVEN_BACK.lock().unwrap_or_else(|e| e.into_inner()).push(self.start() as usize); let Kind::Low(at, len) = self.0 else { return }; let mut arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner()); if let Some(arena) = arenas.iter_mut().find(|a| (a.at..a.at + a.taken.len() * BLOCK).contains(&at)) { diff --git a/d3d12/crates/leonida-gpu/src/watch.rs b/d3d12/crates/leonida-gpu/src/watch.rs index 02edd8e29d..69af153b7d 100644 --- a/d3d12/crates/leonida-gpu/src/watch.rs +++ b/d3d12/crates/leonida-gpu/src/watch.rs @@ -196,16 +196,18 @@ impl Notes { /// Whether `pred` holds for every note of pages `[first, last)` newer than /// `floor`, in no order: a part whose largest note is not newer is passed - /// over without a look. (maren-halv/VIctory-DXR 79a92c7, GPL-3.0.) - fn all_newer(&self, first: usize, last: usize, floor: u64, mut pred: impl FnMut(usize, u64) -> bool) -> bool { + /// over without a look. (maren-halv/VIctory-DXR 79a92c7, GPL-3.0.) `pred` + /// is given the part the note is in too, held (for the notes of the + /// page's parts: [`Shard::parts_since`]), then the page and the note. + fn all_newer(&self, first: usize, last: usize, floor: u64, mut pred: impl FnMut(&Shard, usize, u64) -> bool) -> bool { match pieces(first, last) { Some(mut pieces) => pieces.all(|(from, to)| { let s = self.read(shard_of(from)); - s.max_written <= floor || s.written.range(from..to).all(|(&p, &w)| w <= floor || pred(p, w)) + s.max_written <= floor || s.written.range(from..to).all(|(&p, &w)| w <= floor || pred(&s, p, w)) }), None => (0..SHARDS).all(|shard| { let s = self.read(shard); - s.max_written <= floor || s.written.range(first..last).all(|(&p, &w)| w <= floor || pred(p, w)) + s.max_written <= floor || s.written.range(first..last).all(|(&p, &w)| w <= floor || pred(&s, p, w)) }), } } @@ -764,6 +766,21 @@ thread_local! { static FOUND: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) }; } +#[cfg(test)] +thread_local! { + /// This thread's kernel askings ([`kernel_written`]): made, refused, and + /// the pages walked by those answered. + pub(crate) static KERNEL_ASKED: std::cell::Cell<[u64; 3]> = const { std::cell::Cell::new([0; 3]) }; + /// This thread's changes of protection of guarded blocks + /// ([`protect_here`], [`unguard`]), refused ones too. + pub(crate) static PROTECTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; + /// This thread's looks at allocations for a plan ([`Allocation::at`]). + pub(crate) static LOOKED_UP: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; + /// This thread's askings and guards as before ([`ask_by_allocation`], + /// [`views_unasked`] and [`protect_by_view`] off). + pub(crate) static ASK_AS_BEFORE_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + /// The pages of `[first, last)` the kernel says were written since it was /// last asked, in order, each once, with their written parts; `None` if the range is not write-watched /// memory of one reservation. The caller holds the range ([`Asking`]). @@ -795,6 +812,11 @@ fn kernel_written(first: usize, last: usize) -> Option<Vec<(usize, u16)>> { tally(10, u64::from(failed)); tally(11, started.elapsed().as_nanos() as u64); } + #[cfg(test)] + KERNEL_ASKED.with(|asked| { + let [made, refused, pages] = asked.get(); + asked.set([made + 1, refused + u64::from(failed), pages + if failed { 0 } else { (last - first) as u64 }]); + }); if failed { return None; } @@ -821,9 +843,18 @@ fn kernel_written(first: usize, last: usize) -> Option<Vec<(usize, u16)>> { } /// Ranges of one submission closer than this, in pages, are asked about -/// together: walking the pages between them costs less than another kernel -/// call (a call that resets written pages costs 30-70 microseconds whatever -/// the range). `LEONIDA_ASK_GAP_KB=<KiB>`, 8192 by default. +/// together. `LEONIDA_ASK_GAP_KB=<KiB>`, 8192 by default. +/// +/// It was chosen for a call that resets written pages costing 30-70 +/// microseconds whatever the range. On this PC (Windows 11, the answer's +/// room sized to the range as [`kernel_written`] sizes it) the call costs +/// what it walks: 0.5 microseconds for 64 KiB, 8.3 for 8 MiB, 52 for +/// 64 MiB, 860 for 1 GiB of committed memory nothing wrote (0.4 a MiB where +/// nothing is committed), some 20 nanoseconds more a 4 KiB page found +/// written; a refused call 0.3-1. By that alone a gap of 8 MiB costs some 8 +/// microseconds where another call costs half of one; yet the frame measured +/// by turns kept 8 MiB against 256 KiB (`docs/findings.md`, run d43), so +/// what the gap costs or saves in the game is more than the kernel's time. /// /// But the reset makes every written page between them clean again, the /// title's own pages among them, and the title's next write to each takes a @@ -854,6 +885,11 @@ const AHEAD_MAX: usize = (1 << 30) / PAGE; /// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are /// left to `writes`. pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { + ask_ahead_in(ranges, &mut planned()); +} + +/// [`ask_ahead`], the allocations found kept in `plan` ([`planned`]). +fn ask_ahead_in(ranges: &[(usize, usize)], plan: &mut Option<Allocations>) { let own = ask_ranges(); // The submission's one asking stands ([`ask_once`]): what it does not // hold is left to `writes`. (Looked at before the ranges are put in @@ -877,25 +913,8 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { } // The runs asked about together: their pieces (from, to) and pages // (first, last). A piece alone is left to `writes` ([`ask_run`]). - let mut runs: Vec<[usize; 4]> = Vec::new(); - let gap = ahead_gap(); - let mut i = 0; - while i < pieces.len() { - let first = pieces[i].0; - let mut last = pieces[i].1; - let mut k = i + 1; - while k < pieces.len() - && pieces[k].0 <= last + gap - && last.max(pieces[k].1) - first <= AHEAD_MAX - { - last = last.max(pieces[k].1); - k += 1; - } - if k - i >= 2 { - runs.push([i, k, first, last]); - } - i = k; - } + let mut runs = runs_of(&pieces, ahead_gap(), plan.as_mut()); + runs.retain(|r| r[1] - r[0] >= 2); // Held until the answers are noted: everything, or what is asked about. let _held = if own { Ok(AskingMany::hold(runs.iter().map(|r| (r[2], r[3])).collect())) } else { Err(Asking::hold_all()) }; let (mut asked, mut written) = (Vec::new(), Vec::new()); @@ -1138,13 +1157,21 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { return; } ask_once_end(); - ask_ahead(ranges); - ask_rest(ranges); + // (One look at each allocation for both parts.) + let mut plan = planned(); + ask_ahead_in(ranges, &mut plan); + ask_rest_in(ranges, &mut plan); } /// [`ask_once`] after its [`ask_ahead`]: what that left to `writes`, and the /// asking stands. +#[cfg(test)] fn ask_rest(ranges: &[(usize, usize)]) { + ask_rest_in(ranges, &mut planned()); +} + +/// [`ask_rest`], the allocations found kept in `plan` ([`planned`]). +fn ask_rest_in(ranges: &[(usize, usize)], plan: &mut Option<Allocations>) { let own = ask_ranges(); let _all = (!own).then(Asking::hold_all); let mut ahead = { @@ -1161,6 +1188,8 @@ fn ask_rest(ranges: &[(usize, usize)]) { .filter(|r| r.0 < r.1 && !published(r.0, r.1) && !refused_as_view(r.0, r.1)) .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE))) .filter(|&(first, last)| !ahead.holds(first, last)) + // (Not what the kernel would refuse, [`ask_by_allocation`].) + .filter(|&(first, last)| plan.as_mut().is_none_or(|plan| plan.answers(first, last) != Some(false))) .collect(); // Those are held, and no others ([`ask_ranges`]): a range the asking // ahead holds is not asked about here. (Until this asking stands such a @@ -1274,6 +1303,191 @@ fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: ask_run(b, asked, written); } +/// Whether a submission's askings ([`ask_ahead`], [`ask_rest`]) are planned +/// by allocation (`LEONIDA_ASK_BY_ALLOCATION=0`: by distance alone, as +/// before): a run asked about lies in one allocation, and a range the +/// kernel would refuse is not asked about (it is left to [`writes`], which +/// for view memory goes to the guards, as a refused range always went). +/// +/// What it was (run e_base1, ports 6 and 7 off): 259 kernel askings a +/// frame, and 274 more refused. A run of ranges closer than [`ahead_gap`] +/// was asked as one, across the ends of allocations (the title's +/// reservations lie side by side) and over view memory, which the kernel +/// keeps no written pages of; refused, it was asked again by halves down to +/// single ranges ([`ask_run`]), and each range left alone so was asked again +/// by [`ask_rest`], refused again if it was a view's. +/// +/// What it is: each allocation is looked up once per plan ([`region`], 0.4 +/// microseconds), and a refusal is still asked again by halves. Nothing is +/// left unasked that was asked before: what the kernel answers for is in a +/// run or asked alone, what it would refuse was refused before. Where the +/// kernel's region answers do not say which allocations are write-watched +/// ([`regions_say`]) a run still ends where its allocation ends; where they +/// cannot be had at all, the plan is as before. Tests: +/// `a_submission_asks_once_per_allocation_and_is_never_refused`. +fn ask_by_allocation() -> bool { + #[cfg(test)] + if ASK_AS_BEFORE_IN_TEST.get() { + return false; + } + crate::toggled!("LEONIDA_ASK_BY_ALLOCATION") && regions_say().is_some() +} + +/// The allocations of a plan, if askings are planned by them +/// ([`ask_by_allocation`]). +fn planned() -> Option<Allocations> { + ask_by_allocation().then(Allocations::default) +} + +/// The bit of [`Region::region_type`] the kernel sets for an allocation it +/// keeps the written pages of: seen on Windows 11 as 0x401 for a +/// write-watched private reservation, 0x1 for one without. +const WRITE_WATCHED: u32 = 1 << 10; + +/// What the kernel's region answers say ([`region`]), found once on two +/// reservations of our own of a page each, one write-watched: `None` if it +/// gives no answer to be trusted; `Some(true)` if [`WRITE_WATCHED`] tells +/// the one from the other, `Some(false)` if only where allocations begin +/// and end can be had. +fn regions_say() -> Option<bool> { + static SAY: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new(); + *SAY.get_or_init(|| { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree}; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + // SAFETY: reservations of our own, released below. + let made = [MEM_RESERVE | MEM_WRITE_WATCH, MEM_RESERVE] + .map(|kind| unsafe { VirtualAlloc(std::ptr::null(), PAGE, kind, PAGE_READWRITE) } as usize); + let said = made.map(|at| { + region(at) + .filter(|r| at != 0 && r.allocation_base == at && r.region_size == PAGE) + .map(|r| r.region_type & WRITE_WATCHED != 0) + }); + for at in made.into_iter().filter(|&at| at != 0) { + // SAFETY: as above; nothing of ours noted anything of them. + unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) }; + } + let say = match said { + [Some(watched), Some(plain)] => Some(watched && !plain), + _ => None, + }; + tracing::debug!(?say, "what the kernel's region answers say of write watching"); + say + }) +} + +/// An allocation, in pages: `[first, last)`, and whether the kernel keeps its +/// written pages (`None`: its answers do not say, [`regions_say`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Allocation { + first: usize, + last: usize, + watched: Option<bool>, +} + +impl Allocation { + /// The allocation `page` lies in; `None` if nothing is there or the + /// kernel does not say. One that does not begin and end on a page (sized + /// in 4 KiB steps) is the pages it lies in, and whether the kernel + /// answers for them is not said: it refuses the page reaching past its + /// end, and answers for the others or not, as before. A run still ends + /// there. + fn at(page: usize) -> Option<Allocation> { + let say = regions_say()?; + #[cfg(test)] + LOOKED_UP.set(LOOKED_UP.get() + 1); + #[cfg(feature = "diagnostics")] + tally(14, 1); + let found = (|| { + let r = region(page.checked_mul(PAGE)?)?; + let end = r.allocation_base.checked_add(r.region_size)?; + let whole = r.allocation_base.is_multiple_of(PAGE) && end.is_multiple_of(PAGE); + (r.region_size != 0 && (r.allocation_base..end).contains(&(page * PAGE))).then_some(Allocation { + first: r.allocation_base / PAGE, + last: end.div_ceil(PAGE), + watched: if whole { say.then_some(r.region_type & WRITE_WATCHED != 0) } else { None }, + }) + })(); + #[cfg(feature = "diagnostics")] + if found.is_none_or(|a| a.watched.is_none()) { + tally(15, 1); + } + found + } + + /// Whether the kernel answers for pages `[first, last)` (which begin in + /// this allocation): `Some(false)` if it refuses (they do not all lie in + /// it, or it is not write-watched), `None` if that cannot be said. + fn answers(&self, first: usize, last: usize) -> Option<bool> { + if first < self.first || last > self.last { + return Some(false); + } + self.watched + } +} + +/// The allocations a plan has looked up, and the pages it found none at, so +/// that each is looked up once (before, a page with none, or in an +/// allocation off the pages, was looked up again for each run and each +/// range left alone that began in it). +#[derive(Default)] +struct Allocations { + known: Vec<Allocation>, + none: Vec<usize>, +} + +impl Allocations { + fn of(&mut self, page: usize) -> Option<Allocation> { + if let Some(known) = self.known.iter().rev().find(|a| (a.first..a.last).contains(&page)) { + return Some(*known); + } + if self.none.contains(&page) { + return None; + } + let Some(found) = Allocation::at(page) else { + self.none.push(page); + return None; + }; + self.known.push(found); + Some(found) + } + + /// [`Allocation::answers`] for pages `[first, last)`; `None` where the + /// allocation is not known. + fn answers(&mut self, first: usize, last: usize) -> Option<bool> { + self.of(first)?.answers(first, last) + } +} + +/// The runs of `pieces` (page ranges in order) to ask about together, as +/// `[from, to, first, last]`: pieces `from..to`, pages `first..last`. Pieces +/// closer than `gap` pages are one run, of at most [`AHEAD_MAX`] pages. With +/// `plan` ([`ask_by_allocation`]) a run ends where its allocation does, and +/// a piece the kernel would refuse is in no run. +fn runs_of(pieces: &[(usize, usize)], gap: usize, mut plan: Option<&mut Allocations>) -> Vec<[usize; 4]> { + let mut runs = Vec::new(); + let mut i = 0; + while i < pieces.len() { + let (first, mut last) = pieces[i]; + let within = plan.as_deref_mut().and_then(|plan| plan.of(first)); + if within.is_some_and(|a| a.answers(first, last) == Some(false)) { + i += 1; + continue; + } + let mut k = i + 1; + while k < pieces.len() + && pieces[k].0 <= last + gap + && last.max(pieces[k].1) - first <= AHEAD_MAX + && within.is_none_or(|a| pieces[k].1 <= a.last) + { + last = last.max(pieces[k].1); + k += 1; + } + runs.push([i, k, first, last]); + i = k; + } + runs +} + /// What [`writes`] would say of `[start, end)` from the journal alone, if /// the range lies in one asked ahead ([`ask_ahead`], [`ask_once`]): the /// pages written since tracking began and the asking that last found each @@ -1330,11 +1544,18 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve } let mut guards_asked = false; // (View memory read-only by our hand: the kernel would refuse. With - // renderer port #6 also view memory known as such, [`VIEWS`].) + // renderer port #6, or [`views_unasked`], also view memory known as + // such, [`VIEWS`].) let protected = guarded && light() && PROTECTED.any(first, last); let viewed = guarded && !protected && known_views(first, last); if viewed { - port6_count(P6_NOT_ASKED, 1); + // (In the asking line; in the port's only with the port, whose line + // would otherwise show with it off, [`views_unasked`].) + #[cfg(feature = "diagnostics")] + tally(13, 1); + if port_guard() { + port6_count(P6_NOT_ASKED, 1); + } } let refused = protected || viewed; let pages = match if refused { None } else { kernel_written(first, last) } { @@ -1437,7 +1658,61 @@ pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], } oldest }; - j.notes.all_newer(first, last, floor, |page, write| write <= taken[page - first].max(ranged)) + let parts = look_parts(); + j.notes.all_newer(first, last, floor, |shard, page, write| { + let taken = taken[page - first].max(ranged); + // Written since only in parts the range does not hold: the refresh + // would take nothing of it (`Shadow::copy_stale` takes the parts + // written, `shadow::by_parts`). + write <= taken || parts && shard.parts_since(page, taken) & parts_in(page, start, end) == 0 + }) +} + +/// Whether [`nothing_new`] looks at the parts of a page a range holds only in +/// part, the pages at its ends (`LEONIDA_LOOK_PARTS=0`: at the page, as +/// before). +/// +/// A range that ends inside a 64 KiB page was not known to copy nothing once +/// the title wrote any 4 KiB of that page since the copy last took the range, +/// although the refresh then takes only the parts written that the range holds +/// ([`parts_written`], `shadow::by_parts`): none, when the title wrote beside +/// the range, as it does in memory where the views of many copies lie one +/// after the other. Such a refresh paid all of a refresh that copies (the +/// journal's notes of its range asked again and collected, the copy's page +/// notes held for writing, the runs planned, the parts asked for) and was +/// handed to the threads with those that copy: 1,000 copies of 160 KiB one +/// after the other, the title writing a byte beside each, 0.24 ms a flush in +/// front of the steps against 0.10 with the switch, 100 of them 0.029 against +/// 0.008 (test `refreshes_beside_writes`, release build, the RX 7900 XT PC; +/// how many such refreshes the game makes is not measured). The parts are the kernel's +/// (write-watched memory) and those of what we wrote ([`landed_beside`], in +/// view memory too); what the guards see is noted as the whole block, so a +/// title write in view memory still counts for the whole page, while the +/// parts our own landings note beside a range there are honoured, as the +/// refresh honours them. +fn look_parts() -> bool { + #[cfg(test)] + if let Some(on) = LOOK_PARTS_IN_TEST.get() { + return on; + } + crate::toggled!("LEONIDA_LOOK_PARTS") +} + +#[cfg(test)] +thread_local! { + /// [`look_parts`], for the looks of this thread. + pub(crate) static LOOK_PARTS_IN_TEST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; +} + +/// The parts of page `page` (a bit for each [`KERNEL_PAGE`]) that hold a byte +/// of `[start, end)`. +fn parts_in(page: usize, start: usize, end: usize) -> u16 { + let (a, b) = (start.max(page * PAGE), end.min((page + 1) * PAGE)); + if a >= b { + return 0; + } + let (lo, hi) = ((a - page * PAGE) / KERNEL_PAGE, (b - 1 - page * PAGE) / KERNEL_PAGE); + ((u32::MAX >> (31 - hi)) & (u32::MAX << lo)) as u16 } impl Tracked { @@ -1541,7 +1816,8 @@ pub(crate) fn light() -> bool { /// - a block the title writes again soon after each time it was taken rests /// longer ([`hot_rest`]; `LEONIDA_GUARD_HOT=0`: 3 ms as before); /// - view memory is not asked of the kernel, which refuses it -/// ([`VIEWS`]; ~300 refused askings a frame). +/// ([`VIEWS`]; ~300 refused askings a frame); a refresh's look at it is +/// not, port or not, by [`views_unasked`]. pub(crate) fn port_guard() -> bool { #[cfg(feature = "diagnostics")] if let Some(on) = crate::ab::pick("LEONIDA_PORT_GUARD") { @@ -1564,7 +1840,11 @@ pub(crate) fn port_guard() -> bool { /// /// A look walks the journal's every page ever written in the range; one /// submission a frame spent up to 6 ms in it alone, the six threads beside it -/// idle (runs lane-1, guard-3). +/// idle (runs lane-1, guard-3). With `LEONIDA_LOOK_FIRST` (on by default; +/// `crate::host`) the looks are made on the submitting thread whatever this +/// says, up to a time after which the rest go to the threads beside: 1.5 ms, +/// the clock asked every 64 looks, each 64 KiB page of a look's range counted +/// as one (so after every look of 4 MiB or more; `host::sift`). pub(crate) fn port_guard_plan() -> bool { if !port_guard() { return false; @@ -1664,6 +1944,18 @@ const P6_HOT: usize = 7; fn port6_count(what: usize, n: u64) { PORT6[what].fetch_add(n, std::sync::atomic::Ordering::Relaxed); + #[cfg(test)] + PORT6_HERE.with(|here| { + let mut counts = here.get(); + counts[what] += n; + here.set(counts); + }); +} + +#[cfg(test)] +thread_local! { + /// This thread's [`PORT6`] counts, never taken. + static PORT6_HERE: std::cell::Cell<[u64; 8]> = const { std::cell::Cell::new([0; 8]) }; } /// Renderer port #6's line of the frame lines, per frame. @@ -1687,18 +1979,41 @@ pub(crate) fn port_guard_line(frames: f64) { ); } -/// The blocks known to be view memory (renderer port #6): guarded by us -/// once, or found a view by [`guard`]. The kernel refuses to ask about them -/// (its write watch is not kept for views), and with the switch such a -/// range goes to the guards at once. Forgotten when the memory is unmapped -/// or freed; a block wrongly here is only looked at by the guards, which -/// find it no view ([`is_view`]) and say the range is not watched. +/// The blocks known to be view memory (renderer port #6, or +/// [`views_unasked`]): guarded by us once, or found a view by [`guard`]. +/// The kernel refuses to ask about them (its write watch is not kept for +/// views), and with the switch such a range goes to the guards at once. +/// Forgotten when the memory is unmapped, freed or allocated anew; a block +/// wrongly here is only looked at by the guards, which find it no view +/// ([`is_view`]) and say the range is not watched. static VIEWS: Bits = Bits::new(); /// Whether a block of `[first, last)` is known view memory and the kernel /// need not be asked ([`VIEWS`]). fn known_views(first: usize, last: usize) -> bool { - port_guard() && light() && VIEWS.any(first, last) + (port_guard() || views_unasked()) && light() && VIEWS.any(first, last) +} + +/// Whether a refresh's look at view memory it knows for such ([`VIEWS`]) +/// goes to the guards without asking the kernel first, renderer port #6 or +/// not (`LEONIDA_VIEWS_UNASKED=0`: only with the port, as before). +/// +/// With the port off (as it is by default) every look at view memory that +/// was not read-only by our hand right then, a block the title had opened +/// by writing it, a hole, asked the kernel, was refused and then went to +/// the guards ([`writes`]): part of the 274 refused askings a frame of run +/// e_base1, 75 of whose view ranges were guarded block by block. The answer +/// is the guards' either way. A block wrongly known for a view (other memory +/// there now, with nobody telling) is found no view by them, forgotten as +/// one and asked of the kernel, as before. Only [`writes`] for a caller that +/// asks the guards trusts the bits so; [`refused_as_view`] still needs the +/// port. +fn views_unasked() -> bool { + #[cfg(test)] + if ASK_AS_BEFORE_IN_TEST.get() { + return false; + } + crate::toggled!("LEONIDA_VIEWS_UNASKED") } /// A bit per block of the address space, in pieces made when first needed @@ -2086,18 +2401,33 @@ fn known_holes() -> bool { /// to be only by mapping a view (or an allocation) in its place, which an /// ordinary commit cannot do. fn placeholder(block: usize) -> bool { - /// `MEMORY_REGION_INFORMATION` (ntddk). - #[repr(C)] - #[derive(Default)] - struct Region { - allocation_base: usize, - allocation_protect: u32, - region_type: u32, - region_size: usize, - commit_size: usize, - partition_id: usize, - node_preference: usize, - } + const PLACEHOLDER_RESERVATION: u32 = 1 << 8; + region(block * BLOCK).is_some_and(|region| region.region_type & PLACEHOLDER_RESERVATION != 0) +} + +/// `MEMORY_REGION_INFORMATION` (ntddk): the allocation an address lies in, +/// whole (`region_size` is the allocation's, not a run of pages of one +/// state as `VirtualQuery`'s is). +#[repr(C)] +#[derive(Default, Debug)] +struct Region { + allocation_base: usize, + allocation_protect: u32, + region_type: u32, + region_size: usize, + commit_size: usize, + partition_id: usize, + node_preference: usize, +} + +/// The kernel's [`Region`] at `at`; `None` where nothing is allocated (or +/// the kernel does not answer this question, as older ones may not). +/// +/// One look in the tree of allocations: 0.4 microseconds whatever the size +/// (measured on this PC, Windows 11, 1 GiB committed and written), where +/// `VirtualQuery` walks the page tables to find where pages of one state +/// end: 16 ms for that GiB. +fn region(at: usize) -> Option<Region> { #[link(name = "ntdll", kind = "raw-dylib")] unsafe extern "system" { fn NtQueryVirtualMemory( @@ -2111,25 +2441,28 @@ fn placeholder(block: usize) -> bool { } // (Class 3 answers with the kind of memory in that word, not the flags.) const MEMORY_REGION_INFORMATION_EX: u32 = 7; - const PLACEHOLDER_RESERVATION: u32 = 1 << 8; let mut region = Region::default(); // SAFETY: the answer's room and its size. let status = unsafe { NtQueryVirtualMemory( windows_sys::Win32::System::Threading::GetCurrentProcess(), - (block * BLOCK) as *const _, + at as *const _, MEMORY_REGION_INFORMATION_EX, (&raw mut region).cast(), size_of::<Region>(), std::ptr::null_mut(), ) }; - status >= 0 && region.region_type & PLACEHOLDER_RESERVATION != 0 + (status >= 0).then_some(region) } /// The runtime gave the title memory at `[at, at + len)`, allocated or /// committed: what was known of holes there is asked again. pub fn title_memory_allocated(at: usize, len: usize) { + // Nor is it known for view memory any more ([`VIEWS`]). + if len != 0 { + forget_views(at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); + } if len == 0 || !known_holes() { return; } @@ -2202,9 +2535,13 @@ fn published(start: usize, end: usize) -> bool { /// opened by ourselves; nanoseconds waiting for the guards' lock and /// nanoseconds of changing protections (all threads); questions to Windows /// about holes; kernel askings refused; nanoseconds in kernel askings; the -/// 4 KiB pages they found written. +/// 4 KiB pages they found written; kernel askings left out for view memory +/// known as such ([`views_unasked`], renderer port #6); allocations a +/// submission's plan looked up ([`Allocation::at`]), and those of them it +/// cannot tell the kernel answers for or refuses (nothing there, not on +/// whole pages, or [`regions_say`] that it cannot be told). #[cfg(feature = "diagnostics")] -static ASKS: [std::sync::atomic::AtomicU64; 13] = [const { std::sync::atomic::AtomicU64::new(0) }; 13]; +static ASKS: [std::sync::atomic::AtomicU64; 16] = [const { std::sync::atomic::AtomicU64::new(0) }; 16]; #[cfg(feature = "diagnostics")] fn tally(what: usize, n: u64) { @@ -2213,7 +2550,7 @@ fn tally(what: usize, n: u64) { /// [`ASKS`], taken. #[cfg(feature = "diagnostics")] -pub(crate) fn asks() -> [u64; 13] { +pub(crate) fn asks() -> [u64; 16] { std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) } @@ -2617,20 +2954,39 @@ type CellsPiece = [PageCells; Landed::PAGES]; /// (a ring in the heap the skinning passes write), and by pages those looked written by shaders for as long as /// a neighbour 16 bytes away was: every copy of the title's into them at its place in a list waited for the /// flights, 50 to 65 ms of a 110 ms frame (2026-11-27). Pieces of 256 MiB as there, made (all zeros, which the -/// system commits page by page) when a page of theirs is first noted, and never let go. -struct LandedCells([std::sync::atomic::AtomicPtr<CellsPiece>; Landed::PIECES]); +/// system commits page by page) when a page of theirs is first noted, and never let go: 136 bytes a page, 8.5 MiB +/// for each 256 MiB of title addresses a landing touched (views of the same memory at other addresses +/// included). Kept only in a run that can ask for them ([`landed_cells_kept`]). +struct LandedCells { + pieces: [std::sync::atomic::AtomicPtr<CellsPiece>; Landed::PIECES], + /// Pieces made so far. + made: std::sync::atomic::AtomicUsize, +} impl LandedCells { /// Frames in a span: "lately" is this span and the one before it, 512 to 1,023 frames. const SPAN: u64 = 512; + const fn new() -> Self { + LandedCells { + pieces: [const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Landed::PIECES], + made: std::sync::atomic::AtomicUsize::new(0), + } + } + + /// Pieces of 256 MiB of addresses made so far. + #[cfg(test)] + fn made(&self) -> usize { + self.made.load(std::sync::atomic::Ordering::Relaxed) + } + fn span(frame: u64) -> u32 { ((frame / Self::SPAN) as u32 & 0x3fff_ffff) + 1 } fn page(&self, page: usize, make: bool) -> Option<&PageCells> { use std::sync::atomic::Ordering::{AcqRel, Acquire}; - let place = self.0.get(page / Landed::PAGES)?; + let place = self.pieces.get(page / Landed::PAGES)?; let mut piece = place.load(Acquire); if piece.is_null() { if !make { @@ -2643,7 +2999,10 @@ impl LandedCells { return None; } piece = match place.compare_exchange(std::ptr::null_mut(), made, AcqRel, Acquire) { - Ok(_) => made, + Ok(_) => { + self.made.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + made + } Err(there) => { // SAFETY: made just now with this layout, and another thread's is there. unsafe { std::alloc::dealloc(made.cast(), layout) }; @@ -2709,54 +3068,125 @@ impl LandedCells { } } -static LANDED_CELLS: LandedCells = LandedCells([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Landed::PIECES]); +static LANDED_CELLS: LandedCells = LandedCells::new(); + +/// Whether [`landed_lately_exact`] is what `crate::host` asks now: `LEONIDA_LANDED_EXACT=1`, or with +/// `LEONIDA_AB` naming it (diagnostics builds) in the phases it is on. +pub(crate) fn landed_exact() -> bool { + let on = landed_exact_asked(); + #[cfg(feature = "diagnostics")] + let on = crate::ab::pick("LEONIDA_LANDED_EXACT").unwrap_or(on); + on +} + +/// `LEONIDA_LANDED_EXACT=1`, read once. +fn landed_exact_asked() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_LANDED_EXACT").is_some_and(|v| v == "1")) +} + +/// Whether [`LandedCells`] are kept in this run: whether [`landed_exact`] can ever be on, which is +/// `LEONIDA_LANDED_EXACT=1` or `LEONIDA_AB` naming it (kept through its off phases too, so that an on phase +/// finds the spans before it). Otherwise no landing works out its cells ([`landing_cells`], `crate::land`) and +/// no piece is made: they were noted on every landing and copy-back with nothing reading them, 8.5 MiB of +/// commit per 256 MiB of title addresses touched, never let go. +pub(crate) fn landed_cells_kept() -> bool { + static KEPT: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *KEPT.get_or_init(|| { + let kept = landed_exact_asked(); + #[cfg(feature = "diagnostics")] + let kept = kept || crate::ab::bit("LEONIDA_LANDED_EXACT").is_some(); + kept + }) +} /// What shaders wrote went into title memory in these cells: for each, the 4 KiB page (its number) and the /// cells in it. Beside the pages' note ([`landing`], [`landed_beside`]), which says no more than the page. The -/// same pages at other addresses are noted as well, as there. +/// same pages at other addresses are noted as well, as there. Nothing in a run that does not keep the cells +/// ([`landed_cells_kept`]). pub(crate) fn landing_cells(pages: &[(usize, Cells)]) { + if !landed_cells_kept() { + return; + } let (Some(first), Some(last)) = (pages.iter().map(|p| p.0).min(), pages.iter().map(|p| p.0).max()) else { return; }; - let frame = crate::frame::current(); - for (page, cells) in pages { - LANDED_CELLS.note(*page, cells, frame); - } - for (block, others) in elsewhere(first * KERNEL_PAGE, (last - first + 1) * KERNEL_PAGE) { - let block = block / KERNEL_PAGE; - for (page, cells) in pages.iter().filter(|p| (block..block + BLOCK / KERNEL_PAGE).contains(&p.0)) { - for other in &others { - LANDED_CELLS.note(page - block + other / KERNEL_PAGE, cells, frame); - } - } - } + let between = |from: usize, to: usize| pages.iter().copied().filter(move |p| (from..=to).contains(&p.0)); + note_cells(&LANDED_CELLS, first, last, between, crate::frame::current()); } /// [`landing_cells`] for every byte of `[at, at + len)`: a caller that does not know which of them change. +/// Each page's cells are worked out as they are noted (a copy-back built a list of them, 72 bytes a page), and +/// those of a block shown elsewhere once more for it. pub(crate) fn landing_cells_whole(at: usize, len: usize) { + if !landed_cells_kept() { + return; + } + note_cells_whole(&LANDED_CELLS, at, len, crate::frame::current()); +} + +#[cfg(test)] +thread_local! { + /// Pages whose cells [`note_cells_whole`] worked out on this thread. + static WORKED_OUT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +/// [`landing_cells_whole`] into `into`, at `frame`. +fn note_cells_whole(into: &LandedCells, at: usize, len: usize, frame: u64) { if len == 0 { return; } - let pages: Vec<(usize, Cells)> = (at / KERNEL_PAGE..=(at + len - 1) / KERNEL_PAGE) - .map(|page| { + let (first, last) = (at / KERNEL_PAGE, (at + len - 1) / KERNEL_PAGE); + let pages = |from: usize, to: usize| { + (first.max(from)..=last.min(to)).map(move |page| { + #[cfg(test)] + WORKED_OUT.with(|n| n.set(n.get() + 1)); let base = page * KERNEL_PAGE; (page, cells_between(at.max(base) - base, (at + len).min(base + KERNEL_PAGE) - base)) }) - .collect(); - landing_cells(&pages); + }; + note_cells(into, first, last, pages, frame); +} + +/// Notes the pages from page `first` to page `last` into `into` at `frame`, and the same pages at the other +/// addresses that show them ([`elsewhere`]). `pages(from, to)` gives those of them from page `from` to page +/// `to` (both in), each with its cells: asked for all, then for each block shown elsewhere (a copy-back works +/// out only that block's cells again, not every page's of the stretch to keep the block's). +fn note_cells<I: Iterator<Item = (usize, Cells)>>( + into: &LandedCells, + first: usize, + last: usize, + pages: impl Fn(usize, usize) -> I, + frame: u64, +) { + for (page, cells) in pages(first, last) { + into.note(page, &cells, frame); + } + for (block, others) in elsewhere(first * KERNEL_PAGE, (last - first + 1) * KERNEL_PAGE) { + let block = block / KERNEL_PAGE; + for (page, cells) in pages(block, block + BLOCK / KERNEL_PAGE - 1) { + for other in &others { + into.note(page - block + other / KERNEL_PAGE, &cells, frame); + } + } + } } /// Whether shaders' writes went into bytes of `[at, at + len)` (by cells of 8) in the last 512 to 1,023 -/// frames. [`landed_lately`] asks by pages. +/// frames. [`landed_lately`] asks by pages. Only a run that keeps the cells ([`landed_cells_kept`]) has any. pub(crate) fn landed_lately_exact(at: usize, len: usize) -> bool { + lately_in(&LANDED_CELLS, at, len, crate::frame::current()) +} + +/// [`landed_lately_exact`] of `noted`, at `frame`. +fn lately_in(noted: &LandedCells, at: usize, len: usize, frame: u64) -> bool { if len == 0 { return false; } - let frame = crate::frame::current(); (at / KERNEL_PAGE..=(at + len - 1) / KERNEL_PAGE).any(|page| { let base = page * KERNEL_PAGE; let cells = cells_between(at.max(base) - base, (at + len).min(base + KERNEL_PAGE) - base); - LANDED_CELLS.lately(page, &cells, frame) + noted.lately(page, &cells, frame) }) } @@ -2777,7 +3207,7 @@ mod cells_tests { /// The case the cells are for: the title's constants end where a shader's small buffer begins. #[test] fn a_write_beside_other_bytes_of_the_page_is_not_one_into_them() { - static NOTED: LandedCells = LandedCells([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Landed::PIECES]); + static NOTED: LandedCells = LandedCells::new(); let page = 0xd66bb; NOTED.note(page, &cells_between(0xe30, 0xe88), 1000); // The constants at 0xc00..0xe30, and the shader's bytes. @@ -2798,6 +3228,98 @@ mod cells_tests { assert!(!NOTED.lately(page, &cells_between(0xe30, 0xe88), 1000 + 3 * LandedCells::SPAN)); assert!(NOTED.lately(page, &cells_between(0x200, 0x208), 1000 + 3 * LandedCells::SPAN)); } + + /// Where the tests note: far above the title's and the runtime's memory, at a piece's start. + const FAR: usize = 0x7e00_0000_0000; + const PIECE: usize = Landed::PAGES * KERNEL_PAGE; + + /// A run in which nothing can ask for the cells (no `LEONIDA_LANDED_EXACT=1`, no `LEONIDA_AB` naming it, as + /// in the tests) makes no piece of them, whatever lands: a copy-back of 1 GiB (four pieces of addresses) and + /// shaders' writes into pages of three pieces more. Each piece commits up to 8.5 MiB, never let go. + #[test] + fn cells_no_one_can_ask_for_are_not_kept() { + let whole = FAR + 16 * PIECE; + landing_cells_whole(whole, 4 * PIECE); + let pages: Vec<(usize, Cells)> = + (1..=3).map(|k| ((whole + (4 + k) * PIECE) / KERNEL_PAGE + 7, cells_between(0xe30, 0xe88))).collect(); + landing_cells(&pages); + if landed_cells_kept() { + // (Tests run with the switch on: kept, and read back.) + assert!(LANDED_CELLS.made() >= 7); + assert!(landed_lately_exact(whole + PIECE + 0x10, 8)); + return; + } + assert_eq!(LANDED_CELLS.made(), 0, "pieces of cells made with nothing to read them"); + assert!(!landed_lately_exact(whole + PIECE + 0x10, 8)); + } + + /// Kept, a copy-back's cells are worked out page by page as they are noted, and say what the list of them + /// said: every byte of the stretch, none beside it. + #[test] + fn a_copy_back_notes_every_cell_of_its_bytes_and_no_other() { + static NOTED: LandedCells = LandedCells::new(); + assert_eq!(std::mem::size_of::<CellsPiece>(), 136 * Landed::PAGES); + let frame = 1000; + note_cells_whole(&NOTED, FAR, 4 * PIECE, frame); + assert_eq!(NOTED.made(), 4); + assert!(lately_in(&NOTED, FAR, 1, frame)); + assert!(lately_in(&NOTED, FAR + 3 * PIECE + 0x1234, 64, frame)); + assert!(lately_in(&NOTED, FAR + 4 * PIECE - 8, 8, frame)); + assert!(!lately_in(&NOTED, FAR + 4 * PIECE, 8, frame)); + assert!(!lately_in(&NOTED, FAR - 8, 8, frame)); + // A stretch inside one page, as the case of the cells. + let page = FAR + 6 * PIECE + 0x5000; + note_cells_whole(&NOTED, page + 0xe30, 0x58, frame); + assert_eq!(NOTED.made(), 5); + assert!(lately_in(&NOTED, page + 0xe30, 1, frame)); + assert!(lately_in(&NOTED, page + 0xe80, 8, frame)); + assert!(!lately_in(&NOTED, page + 0xc00, 0x230, frame)); + assert!(!lately_in(&NOTED, page + 0xe88, 0x178, frame)); + // A stretch over a page's end. + let across = FAR + 7 * PIECE + 0x2000 - 0x10; + note_cells_whole(&NOTED, across, 0x20, frame); + assert!(lately_in(&NOTED, across, 0x10, frame)); + assert!(lately_in(&NOTED, across + 0x10, 0x10, frame)); + assert!(!lately_in(&NOTED, across - 8, 8, frame)); + assert!(!lately_in(&NOTED, across + 0x20, 8, frame)); + } + + /// A copy-back over a view the title shows at another address notes the same cells there, and works out + /// each page's cells once for it and once more for each block shown elsewhere, not once more per block for + /// every page of the stretch: 6 blocks of which 4 are shown twice, 96 pages and 64 again, where it was 96 + /// and 4 times 96. + #[test] + fn a_copy_back_notes_its_cells_at_the_other_view_working_each_out_once_more() { + static NOTED: LandedCells = LandedCells::new(); + let frame = 1000; + let (section, one, two) = (0xce11_5ec7_usize, FAR + 9 * PIECE, FAR + 10 * PIECE); + crate::inplace::title_memory_view(one, 4 * BLOCK, section, 0); + crate::inplace::title_memory_view(two, 4 * BLOCK, section, 0); + let from = one - 2 * BLOCK; + WORKED_OUT.with(|n| n.set(0)); + note_cells_whole(&NOTED, from, 6 * BLOCK, frame); + let worked_out = WORKED_OUT.with(|n| n.get()); + // Inside a page of the view, as the case of the cells. + static INSIDE: LandedCells = LandedCells::new(); + WORKED_OUT.with(|n| n.set(0)); + note_cells_whole(&INSIDE, one + 3 * BLOCK + 0x1e30, 0x58, frame); + let worked_out_inside = WORKED_OUT.with(|n| n.get()); + crate::inplace::views_gone(one, 4 * BLOCK); + crate::inplace::views_gone(two, 4 * BLOCK); + if view_guard() { + assert_eq!(worked_out, (6 + 4) * BLOCK / KERNEL_PAGE, "pages whose cells were worked out"); + assert_eq!(worked_out_inside, 2); + assert!(lately_in(&NOTED, two, 8, frame)); + assert!(lately_in(&NOTED, two + 4 * BLOCK - 8, 8, frame)); + let page = two + 3 * BLOCK + 0x1000; + assert!(lately_in(&INSIDE, page + 0xe30, 1, frame)); + assert!(lately_in(&INSIDE, page + 0xe80, 8, frame)); + assert!(!lately_in(&INSIDE, page + 0xc00, 0x230, frame)); + assert!(!lately_in(&INSIDE, page + 0xe88, 0x178, frame)); + } + assert!(!lately_in(&NOTED, two + 4 * BLOCK, 8, frame), "past the view"); + assert!(!lately_in(&NOTED, two - 8, 8, frame), "before the view"); + } } /// A page's number, spread. @@ -3012,11 +3534,11 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> { } } let rest = rest(); + // (Known for a view from now on: renderer port #6, [`views_unasked`].) + if (port_guard() || views_unasked()) && !VIEWS.all(first, last) { + (first..last).for_each(|block| VIEWS.set(block)); + } if port_guard() { - // (Renderer port #6: known for a view from now on.) - if !VIEWS.all(first, last) { - (first..last).for_each(|block| VIEWS.set(block)); - } return Some(guard_shared(first, last, &came, rest)); } let mut g = guards_timed(); @@ -3328,6 +3850,8 @@ fn protect_here(g: &Guards, from: usize, to: usize) { let mut old = 0; #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); + #[cfg(test)] + PROTECTS.with(|n| n.set(n.get() + 1)); // SAFETY: title view memory; only its protection changes. let mut done = unsafe { VirtualProtect( @@ -3361,11 +3885,24 @@ fn protect_here(g: &Guards, from: usize, to: usize) { note(g, from, to); return; } - let mut uncommitted_until = from; - for block in from..to { + let by_view = protect_by_view(); + let (mut uncommitted_until, mut tried_until) = (from, from); + let mut block = from; + while block < to { + // The run's blocks in this one's view, by one change ([`protect_by_view`]). + if by_view && block >= uncommitted_until && block >= tried_until && to - block >= 2 { + let end = view_end(block, to); + tried_until = end; + if end - block >= 2 && set(block, end) { + note(g, block, end); + block = end; + continue; + } + } // (Not one question a block of a region that is not there.) if block >= uncommitted_until && set(block, block + 1) { note(g, block, block + 1); + block += 1; continue; } PROTECTED.clear(block); @@ -3380,9 +3917,42 @@ fn protect_here(g: &Guards, from: usize, to: usize) { g.held.insert(block); } } + block += 1; } } +/// Whether a run of blocks whose protection cannot be changed by one call +/// (it is not of one view) is changed a view at a time, not a block at a +/// time (`LEONIDA_PROTECT_BY_VIEW=0`: a block at a time, as before), both +/// when guarded ([`protect_here`]) and when opened ([`unguard`]). +/// +/// The title maps runs of its physical pages as one view each (xmem's +/// `map`), so a run of guarded blocks across two views of sixteen blocks +/// took one refused change and 32 changes, each of which makes every core +/// that runs the title forget those pages; it takes the refused one and 2. +/// Where a view ends is one look in the kernel's tree of allocations +/// ([`region`], 0.4 microseconds). What it takes for granted is what one +/// change for a whole run took for granted already ([`unguard_runs`]): that +/// the first block's protection speaks for the rest of its view. A view's +/// part that one change cannot do (not all of it committed) is done a block +/// at a time, as before. +fn protect_by_view() -> bool { + #[cfg(test)] + if ASK_AS_BEFORE_IN_TEST.get() { + return false; + } + crate::toggled!("LEONIDA_PROTECT_BY_VIEW") +} + +/// The block past the last of `[block, to)` in the allocation that holds +/// `block` (its view, in view memory); `block + 1` where that cannot be said. +fn view_end(block: usize, to: usize) -> usize { + region(block * BLOCK) + .filter(|r| r.region_size != 0 && r.allocation_base <= block * BLOCK) + .and_then(|r| r.allocation_base.checked_add(r.region_size)) + .map_or(block + 1, |end| (end / BLOCK).clamp(block + 1, to.max(block + 1))) +} + /// The end (exclusive) of the whole uncommitted blocks starting at `block`. fn uncommitted_end(block: usize) -> usize { use windows_sys::Win32::System::Memory::{ @@ -3484,6 +4054,8 @@ fn unguard(g: &Guards, blocks: &[usize]) { } let one = |block: usize| { let mut old = 0; + #[cfg(test)] + PROTECTS.with(|n| n.set(n.get() + 1)); // SAFETY: a block we made read-only. unsafe { if VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) != 0 @@ -3496,9 +4068,28 @@ fn unguard(g: &Guards, blocks: &[usize]) { } PROTECTED.clear(block); }; + // Blocks `[from, to)` by one change; whether it was made. + let run = |from: usize, to: usize| { + let mut old = 0; + #[cfg(test)] + PROTECTS.with(|n| n.set(n.get() + 1)); + // SAFETY: blocks we made read-only. + let done = unsafe { VirtualProtect((from * BLOCK) as *const _, (to - from) * BLOCK, PAGE_READWRITE, &mut old) } != 0; + if !done { + return false; + } + if !matches!(old, PAGE_READONLY | PAGE_READWRITE) { + // The first is other memory's, and keeps its protection. + // SAFETY: as it was. + unsafe { VirtualProtect((from * BLOCK) as *const _, BLOCK, old, &mut old) }; + } + (from..to).for_each(|block| PROTECTED.clear(block)); + true + }; if blocks.len() < 2 || !unguard_runs() { blocks.iter().copied().for_each(one); } else { + let by_view = protect_by_view(); let mut sorted = blocks.to_vec(); sorted.sort_unstable(); sorted.dedup(); @@ -3515,22 +4106,31 @@ fn unguard(g: &Guards, blocks: &[usize]) { one(from); continue; } - let mut old = 0; - // SAFETY: blocks we made read-only. - let done = unsafe { VirtualProtect((from * BLOCK) as *const _, (to - from) * BLOCK, PAGE_READWRITE, &mut old) } != 0; + let done = run(from, to); #[cfg(any(test, feature = "diagnostics"))] UNGUARD_RUNS[usize::from(!done)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); - if !done { - // Not of one view, or not all there: each for itself. - (from..to).for_each(one); + if done { continue; } - if !matches!(old, PAGE_READONLY | PAGE_READWRITE) { - // The first is other memory's, and keeps its protection. - // SAFETY: as it was. - unsafe { VirtualProtect((from * BLOCK) as *const _, BLOCK, old, &mut old) }; + // Not of one view, or not all there: each view for itself + // ([`protect_by_view`]), each block where that fails too. + let mut block = from; + while block < to { + if by_view && to - block >= 2 { + let end = view_end(block, to); + if end - block >= 2 && run(block, end) { + block = end; + continue; + } + if end - block >= 2 { + (block..end).for_each(one); + block = end; + continue; + } + } + one(block); + block += 1; } - (from..to).for_each(|block| PROTECTED.clear(block)); } } #[cfg(feature = "diagnostics")] @@ -4237,6 +4837,8 @@ pub fn title_memory_remapped(at: usize, len: usize) { /// its bits ([`PUBLISHED`]) with no view behind it. pub fn title_memory_unmapping(at: usize, len: usize) { crate::texback::remapped(at, len); + // The host copies of placed textures there may go sooner. + crate::resource::title_memory_unmapped(at, len); forget_views(at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); let mut g = title_memory_changed(at, len); if CHANGING.get().0 && len != 0 { @@ -4260,14 +4862,38 @@ pub fn title_memory_unmapping(at: usize, len: usize) { /// `[at, at + len)`, or with no length the whole allocation at `at`: what /// was noted of its blocks (guarded, clean, absent) would be taken for true /// of the next memory at the address. +/// +/// What is in place over it (`crate::inplace`) is let go first: while its +/// heap stands the host refuses the free (error 87), and until it was let +/// go here it stood for as long as the tables kept it, the title's free +/// failed and the memory and the heap were both kept for good. The free +/// the heap still refuses after this is done once it is gone +/// (`crate::inplace::title_memory_free_held`). `LEONIDA_INPLACE_FREE=0`: +/// not let go, as before. pub fn title_memory_freed(at: usize, len: usize) { + // Where the whole allocation at `at` ends, asked once and only if needed: + // a walk of its regions, on the title's thread inside its free (one + // question about the title's 1.1 GB block took 8.8 ms, `crate::texture`). + let mut whole = None; + let mut whole_end = || *whole.get_or_insert_with(|| allocation_end(at, at)); + if crate::inplace::frees() && (crate::inplace::anything_placed() || crate::shadow::sourced_any()) { + let end = if len != 0 { at.saturating_add(len) } else { whole_end().max(at + 1) }; + crate::inplace::title_memory_freeing(at, end - at); + } + // The host copies of placed textures there may go sooner (the end of a + // whole allocation asked only once a placed texture was ever made). + if crate::resource::unmappings_noted() { + let end = if len != 0 { at.saturating_add(len) } else { whole_end().max(at + 1) }; + crate::resource::title_memory_unmapped(at, end - at); + } // (`LEONIDA_WC_NO_BACK`: write-combined regions in it are forgotten.) crate::shadow::write_combined_freed(at, len); if len != 0 { forget_views(at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); } else if VIEWS.any(at / BLOCK, at / BLOCK + 1) { - forget_views(at / BLOCK, allocation_end(at, at).div_ceil(BLOCK).max(at / BLOCK + 1)); + forget_views(at / BLOCK, whole_end().div_ceil(BLOCK).max(at / BLOCK + 1)); } + let whole = whole; let mut g = guards(); let first = at / BLOCK; let noted = [g.protected.range(first..).next(), g.absent.range(first..).next(), g.foreign.range(first..).next().copied()]; @@ -4276,6 +4902,10 @@ pub fn title_memory_freed(at: usize, len: usize) { }; let end = if len != 0 { at.saturating_add(len).div_ceil(BLOCK) + } else if let Some(whole) = whole { + // As `allocation_end(at, noted * BLOCK)`, without walking again: the + // allocation's end if the block lies before it, else `at`. + (if noted * BLOCK < whole { whole } else { at }).div_ceil(BLOCK) } else { allocation_end(at, noted * BLOCK).div_ceil(BLOCK) }; @@ -4298,9 +4928,20 @@ pub fn title_memory_freed(at: usize, len: usize) { open(&g, at, end * BLOCK); } +#[cfg(test)] +thread_local! { + /// Walks of a whole allocation's regions ([`allocation_end`] from its + /// start) on this thread. + static WHOLE_WALKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + /// The end of the allocation at `at`, if `inside` lies in it; else `at`. fn allocation_end(at: usize, inside: usize) -> usize { use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + #[cfg(test)] + if inside <= at { + WHOLE_WALKS.with(|n| n.set(n.get() + 1)); + } let ask = |address: usize| { // SAFETY: plain data filled in by the query. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; @@ -4614,6 +5255,19 @@ mod parts_tests { assert_eq!(j.parts_since(9, 5), 0b100); } + /// [`parts_in`]: the 4 KiB of a page a range holds a byte of. + #[test] + fn the_parts_of_a_page_a_range_holds() { + let (start, end) = (PAGE + KERNEL_PAGE + 500, 3 * PAGE + 3000); + assert_eq!(parts_in(0, start, end), 0); + assert_eq!(parts_in(1, start, end), 0xfffe); + assert_eq!(parts_in(2, start, end), WHOLE); + assert_eq!(parts_in(3, start, end), 1); + assert_eq!(parts_in(4, start, end), 0); + assert_eq!(parts_in(1, PAGE + 4 * KERNEL_PAGE, PAGE + 5 * KERNEL_PAGE + 1), 0b11_0000); + assert_eq!(parts_in(1, PAGE + 15 * KERNEL_PAGE + 4095, 2 * PAGE), 0x8000); + } + /// In order or as a list, the ranges asked ahead hold the same: what /// lies in one of them. (After TaynanGT/Vice-Tay 755dc92's test.) #[test] @@ -4952,6 +5606,99 @@ mod tests { } } + /// Views of `blocks` blocks each, one after the other in one placeholder + /// split for them: the first address. + fn views_in_a_row(blocks: &[usize]) -> usize { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, + PAGE_NOACCESS, VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let all: usize = blocks.iter().sum(); + // SAFETY (all): a fresh placeholder, split, and sections of their own + // in place of its pieces. + unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + all * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + let mut at = p; + for (k, &n) in blocks.iter().enumerate() { + if k + 1 < blocks.len() { + assert_ne!(VirtualFree(at as *mut _, n * BLOCK, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), 0); + } + let section = CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (n * BLOCK) as u32, std::ptr::null()); + assert!(!section.is_null()); + let got = MapViewOfFile3( + section, + GetCurrentProcess(), + at as *const _, + 0, + n * BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ); + assert_eq!(got.Value as usize, at); + at += n * BLOCK; + } + p + } + } + + /// A run of guarded blocks across views is made read-only, and opened, + /// by one change of protection a view, not one a block + /// ([`protect_by_view`]); every block is guarded and opened as before, + /// and a write is found. + #[test] + fn a_run_across_views_is_guarded_and_opened_a_view_at_a_time() { + use windows_sys::Win32::System::Memory::{MEMORY_MAPPED_VIEW_ADDRESS, PAGE_READONLY, UnmapViewOfFile}; + let mut changes = [[0; 2]; 2]; + for (before, changes) in [true, false].into_iter().zip(&mut changes) { + ASK_AS_BEFORE_IN_TEST.set(before); + // Seven blocks: a view of four, a view of two, and one of one. + let p = views_in_a_row(&[4, 2, 1]); + let all: Vec<usize> = (p / BLOCK..p / BLOCK + 7).collect(); + let guarded = |protect: u32| { + for b in 0..7 { + assert_eq!(protection(p + b * BLOCK), protect, "block {b}, as before: {before}"); + assert_eq!(PROTECTED.any(p / BLOCK + b, p / BLOCK + b + 1), protect == PAGE_READONLY, "block {b}"); + } + }; + let was = PROTECTS.get(); + assert_eq!(guard(p, p + 7 * BLOCK), Some(all.clone())); + changes[0] = PROTECTS.get() - was; + guarded(PAGE_READONLY); + let was = PROTECTS.get(); + writing(p, 7 * BLOCK); + changes[1] = PROTECTS.get() - was; + guarded(PAGE_READWRITE); + assert_eq!(guard(p, p + 7 * BLOCK), Some(all.clone()), "what was opened counts as written"); + guarded(PAGE_READONLY); + // The title writes the second view: the fault opens it, and the + // write is found. + // SAFETY: a byte of the second view. + unsafe { ((p + 5 * BLOCK) as *mut u8).add(8).write_volatile(1) }; + assert_eq!(guard(p, p + 7 * BLOCK), Some(vec![all[5]])); + title_memory_unmapping(p, 7 * BLOCK); + for at in [p, p + 4 * BLOCK, p + 6 * BLOCK] { + // SAFETY: our views. + unsafe { UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: at as *mut _ }) }; + } + } + ASK_AS_BEFORE_IN_TEST.set(false); + // Each way: one change for the run, refused; then a block at a time, + // seven, or a view at a time, three. + assert_eq!(changes, [[8, 8], [4, 4]], "changes of protection guarding and opening: before, now"); + } + /// A refresh between the opening of a kernel read's destination and the /// read itself leaves it open: the read lands, and is seen. #[test] @@ -5165,6 +5912,46 @@ mod tests { } } + /// The title's release of a whole allocation asks where it ends once, + /// however many of those it tells need it: the placed textures' notes + /// (`crate::resource::title_memory_unmapped`), the views known there and + /// the guards. Before, each asked again, a walk of the allocation's + /// regions on the title's thread inside its free. + #[test] + fn a_whole_release_walks_its_allocation_once() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, PAGE_READWRITE, VirtualAlloc}; + crate::resource::placed_any_for_test(); + if !crate::resource::unmappings_noted() { + return; + } + // Regions of two kinds, so that the walk takes more than one step. + // SAFETY: fresh memory of ours, released below through the runtime. + let at = unsafe { VirtualAlloc(std::ptr::null(), 8 * BLOCK, MEM_RESERVE, PAGE_READWRITE) } as usize; + assert_ne!(at, 0); + // SAFETY: the reservation above. + assert!(!unsafe { VirtualAlloc(at as *const _, 3 * BLOCK, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + assert_eq!(allocation_end(at, at), at + 8 * BLOCK); + // A view known there and a block noted in the reserved part: each of + // those wants the end. One noted just past the allocation stays. + VIEWS.set(at / BLOCK); + { + let mut g = guards(); + g.foreign.insert(at / BLOCK + 5); + g.foreign.insert(at / BLOCK + 8); + } + WHOLE_WALKS.with(|n| n.set(0)); + let freed = crate::inplace::title_memory_free(at, 0, MEM_RELEASE, || { + // SAFETY: our allocation, released whole. + unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) } + }); + assert_ne!(freed, 0); + assert_eq!(WHOLE_WALKS.with(|n| n.get()), 1, "the allocation was walked more than once"); + assert!(!VIEWS.any(at / BLOCK, at / BLOCK + 1)); + let mut g = guards(); + assert!(!g.foreign.contains(&(at / BLOCK + 5)), "a note in the allocation stayed"); + assert!(g.foreign.remove(&(at / BLOCK + 8)), "a note past the allocation went"); + } + /// A write between another thread's asking about a range and the second /// part of a submission's one asking is later than what that thread /// copied. @@ -5189,6 +5976,254 @@ mod tests { unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; } + /// Memory side by side as the title's lies, in pages: write-watched + /// reservations at `[0, 8)` and `[8, 16)`, plain memory at `[16, 17)` + /// and a view at `[17, 18)`. Their first address and the section. + fn side_by_side() -> (usize, usize) { + use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFileEx, PAGE_NOACCESS}; + // SAFETY: a pagefile section of one page, ours. + let section = unsafe { + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, PAGE as u32, std::ptr::null()) + } as usize; + assert_ne!(section, 0); + for _ in 0..64 { + // Address space free just now, taken piece by piece (another + // thread may take some of it first: then again elsewhere). + // SAFETY (all): reservations and a view of our own. + let p = unsafe { VirtualAlloc(std::ptr::null(), 18 * PAGE, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert_ne!(p, 0); + unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; + let mut made = Vec::new(); + for (at, kind) in [(0, MEM_WRITE_WATCH), (8, MEM_WRITE_WATCH), (16, 0)] { + let len = if at == 16 { PAGE } else { 8 * PAGE }; + let got = + unsafe { VirtualAlloc((p + at * PAGE) as *const _, len, MEM_RESERVE | MEM_COMMIT | kind, PAGE_READWRITE) } as usize; + if got != p + at * PAGE { + break; + } + crate::title_memory_allocated(got, len); + made.push(got); + } + let view = (made.len() == 3) + .then(|| unsafe { MapViewOfFileEx(section as _, FILE_MAP_WRITE, 0, 0, PAGE, (p + 17 * PAGE) as *const _) }.Value as usize); + if view == Some(p + 17 * PAGE) { + return (p, section); + } + for at in made { + free_title(at); + } + } + panic!("no 18 pages of address space stayed free long enough"); + } + + /// Releases title memory at `at` as the runtime does. + fn free_title(at: usize) { + // SAFETY: an allocation of the test's. + crate::inplace::title_memory_free(at, 0, MEM_RELEASE, || unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) }); + } + + /// A refresh's look at view memory it knows for such goes to the guards + /// with no kernel asking, which would be refused ([`views_unasked`]), + /// and finds what was written; a block wrongly known for a view (other + /// memory there now) is asked of the kernel, and memory allocated anew + /// is not known for a view. + #[test] + fn view_memory_known_as_such_is_not_asked_of_the_kernel() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, UnmapViewOfFile, + }; + // SAFETY: a pagefile section of one block. + let section = + unsafe { CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null()) }; + assert!(!section.is_null()); + let mut asked = [[0; 3]; 2]; + for (before, asked) in [true, false].into_iter().zip(&mut asked) { + ASK_AS_BEFORE_IN_TEST.set(before); + // SAFETY: a view of our own. + let view = unsafe { MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, BLOCK) }.Value as usize; + assert_ne!(view, 0); + title_memory_remapped(view, BLOCK); + // Guarded, as a refresh does before the title writes it; then + // written, which opens it. + assert!(writes(view, view + BLOCK, true).is_some()); + let numbered = ASKED.load(std::sync::atomic::Ordering::Relaxed); + // SAFETY: the view's own bytes. + unsafe { (view as *mut u8).add(8).write_volatile(1) }; + assert!(!PROTECTED.any(view / BLOCK, view / BLOCK + 1), "the write opened it"); + let was = KERNEL_ASKED.get(); + let port6 = PORT6_HERE.get(); + let (_, written) = writes(view, view + BLOCK, true).expect("a view"); + let now = KERNEL_ASKED.get(); + *asked = std::array::from_fn(|i| now[i] - was[i]); + assert!(written.iter().any(|w| w.0 == view / PAGE && w.1 > numbered), "planned as before: {before}: {written:?}"); + // Renderer port #6 is off: nothing in its counts, whose frame + // line would then show as if it were on. + assert_eq!(PORT6_HERE.get(), port6, "port 6's counts, the port off; planned as before: {before}"); + // As the runtime does: told before the view goes. + title_memory_unmapping(view, BLOCK); + // SAFETY: our view. + unsafe { UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) }; + } + ASK_AS_BEFORE_IN_TEST.set(false); + assert_eq!(asked, [[1, 1, 0], [0, 0, 0]], "kernel askings: before, now"); + // SAFETY: the section, ours. + unsafe { windows_sys::Win32::Foundation::CloseHandle(section) }; + // Write-watched memory wrongly known for a view: the guards say it is + // none, and the kernel is asked. + // SAFETY: a fresh write-watched reservation, released at the end. + let p = unsafe { VirtualAlloc(std::ptr::null(), PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as usize; + assert_ne!(p, 0); + crate::title_memory_allocated(p, PAGE); + let numbered = ASKED.load(std::sync::atomic::Ordering::Relaxed); + VIEWS.set(p / BLOCK); + // SAFETY: a committed page of ours. + unsafe { (p as *mut u8).write_volatile(1) }; + let (_, written) = writes(p, p + PAGE, true).expect("write-watched"); + assert!(written.iter().any(|w| w.0 == p / PAGE && w.1 > numbered), "{written:?}"); + assert!(!VIEWS.any(p / BLOCK, p / BLOCK + 1), "still known for a view"); + // Allocated anew there: not known for a view any more. + VIEWS.set(p / BLOCK); + crate::title_memory_allocated(p, PAGE); + assert!(!VIEWS.any(p / BLOCK, p / BLOCK + 1), "known for a view where memory was allocated"); + free_title(p); + } + + /// A submission's asking over ranges of memory side by side: one kernel + /// asking for the ranges of each write-watched allocation, none refused + /// (before: runs across the allocations' ends and over the view and the + /// plain memory, refused and asked again by halves, and each range left + /// alone asked again); and the writes are found as before. + #[test] + fn a_submission_asks_once_per_allocation_and_is_never_refused() { + use windows_sys::Win32::System::Memory::{MEMORY_MAPPED_VIEW_ADDRESS, UnmapViewOfFile}; + if regions_say() != Some(true) { + eprintln!("the kernel's region answers do not say which memory is write-watched here: nothing to test"); + return; + } + let (p, section) = side_by_side(); + let at = |page: usize| p + page * PAGE; + // In the first reservation, across both, in the second, the plain + // memory, the view. + let ranges = [ + (at(0), at(2)), + (at(4) + 100, at(5)), + (at(7), at(9)), + (at(10), at(11)), + (at(13), at(16)), + (at(16), at(16) + 4096), + (at(17), at(18)), + ]; + let first = p / PAGE; + assert_eq!(Allocations::default().of(first + 3), Some(Allocation { first, last: first + 8, watched: Some(true) })); + assert_eq!(Allocations::default().of(first + 16).map(|a| a.watched), Some(Some(false))); + assert_eq!(Allocations::default().of(first + 17).map(|a| a.watched), Some(Some(false))); + // (Guarded, as a refresh of it does before the title writes it.) + assert!(writes(at(17), at(18), true).is_some()); + let mut counts = [[0; 3]; 2]; + for (before, counts) in [true, false].into_iter().zip(&mut counts) { + ASK_AS_BEFORE_IN_TEST.set(before); + let numbered = ASKED.load(std::sync::atomic::Ordering::Relaxed); + for page in [1, 4, 13, 15, 17] { + // SAFETY: committed pages of ours. + unsafe { (at(page) as *mut u8).add(8).write_volatile(before as u8) }; + } + let was = KERNEL_ASKED.get(); + ask_once(&ranges); + let now = KERNEL_ASKED.get(); + *counts = std::array::from_fn(|i| now[i] - was[i]); + // What was written is found, what was not is not, whoever asked. + for (from, to, page) in [(0, 2, 1), (4, 5, 4), (13, 16, 13), (13, 16, 15), (17, 18, 17)] { + let (_, written) = writes(at(from), at(to), true).expect("watched, or a view"); + let newer: Vec<usize> = written.iter().filter(|w| w.1 > numbered).map(|w| w.0 - first).collect(); + let expected: Vec<usize> = [1, 4, 13, 15, 17].into_iter().filter(|q| (from..to).contains(q)).collect(); + assert_eq!(newer, expected, "pages {from}..{to}, planned as before: {before}; found written {page}"); + } + ask_once_end(); + } + ASK_AS_BEFORE_IN_TEST.set(false); + let [as_before, by_allocation] = counts; + // Two askings of 5 and 6 pages, and before 11, 8 refused. (Another + // test's asking may stand or end meanwhile: then some or all of the + // ranges are asked alone, four that the kernel answers for, and seven + // before.) + assert_eq!(by_allocation[1], 0, "askings refused: {by_allocation:?}"); + assert!(by_allocation[0] <= 6 && by_allocation[2] <= 18, "{by_allocation:?}"); + assert!(as_before[1] >= 3 && as_before[0] > by_allocation[0], "before: {as_before:?}, now: {by_allocation:?}"); + // As the runtime does: told before the memory goes. + title_memory_unmapping(at(17), PAGE); + // SAFETY: our view and section. + unsafe { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: at(17) as *mut _ }); + windows_sys::Win32::Foundation::CloseHandle(section as _); + } + for page in [0, 8, 16] { + free_title(at(page)); + } + } + + /// A submission's plan looks up an allocation it cannot plan by once, + /// however many of its ranges are asked about: one sized in 4 KiB steps + /// (its end on no page), or memory with nothing in it (before: once for + /// each run and again for each range left alone). A run still ends in the + /// page such an allocation ends in, and what was written is found. + #[test] + fn an_allocation_off_the_pages_is_looked_up_once_per_plan() { + use std::sync::atomic::Ordering::Relaxed; + if regions_say().is_none() { + eprintln!("the kernel gives no region answers to be trusted here: nothing to test"); + return; + } + // Write-watched, 271 pages and 4 KiB. + const LEN: usize = 271 * PAGE + 4096; + // SAFETY: a reservation of ours, released at the end. + let p = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as usize; + assert_ne!(p, 0); + crate::title_memory_allocated(p, LEN); + let first = p / PAGE; + // Farther apart than the gap of an asking ([`ahead_gap`], 128 pages): + // a run each, left alone to the second part of the asking. + let pages = [0, 135, 270]; + let ranges = pages.map(|page| (p + page * PAGE, p + (page + 1) * PAGE)); + let numbered = ASKED.load(Relaxed); + for page in [0, 135] { + // SAFETY: committed pages of ours. + unsafe { ((p + page * PAGE) as *mut u8).add(8).write_volatile(1) }; + } + let (looked, asked) = (LOOKED_UP.get(), KERNEL_ASKED.get()); + ask_once(&ranges); + let (looked, refused) = (LOOKED_UP.get() - looked, KERNEL_ASKED.get()[1] - asked[1]); + for page in pages { + let (_, written) = writes(p + page * PAGE, p + (page + 1) * PAGE, true).expect("write-watched"); + let newer: Vec<usize> = written.iter().filter(|w| w.1 > numbered).map(|w| w.0 - first).collect(); + assert_eq!(newer, [0, 135].into_iter().filter(|&q| q == page).collect::<Vec<_>>(), "page {page}"); + } + ask_once_end(); + assert_eq!((looked, refused), (1, 0), "looks at the allocation, askings refused"); + // A run ends in the page the allocation ends in (271), as the kernel + // would refuse one past it; a range across that end is not asked. + let mut plan = Allocations::default(); + let looked = LOOKED_UP.get(); + let runs = runs_of(&[(first + 270, first + 271), (first + 272, first + 273)], 128, Some(&mut plan)); + // (The second in a run of its own, or in none if another thread + // took memory there the kernel would refuse.) + assert_eq!(runs[0], [0, 1, first + 270, first + 271], "{runs:?}"); + assert_eq!(plan.answers(first + 270, first + 273), Some(false)); + assert_eq!(plan.answers(first + 1, first + 3), None); + // (The second run's page looked up too, whatever is there now.) + assert_eq!(LOOKED_UP.get() - looked, 2, "looks at allocations"); + free_title(p); + // Memory with nothing in it: looked up once. + // SAFETY: address space free just now, and so once more. + let free = unsafe { VirtualAlloc(std::ptr::null(), PAGE, MEM_RESERVE, PAGE_READWRITE) } as usize; + assert_ne!(free, 0); + // SAFETY: as above. + unsafe { VirtualFree(free as *mut _, 0, MEM_RELEASE) }; + let mut plan = Allocations::default(); + let looked = LOOKED_UP.get(); + assert_eq!(plan.answers(free / PAGE, free / PAGE + 1), plan.answers(free / PAGE, free / PAGE + 1)); + assert_eq!(LOOKED_UP.get() - looked, 1, "looks at free memory"); + } + /// The runtime maps a view and then tells us; a copy's refresh on another /// thread can guard it in between. Told, it is the title's to write: a /// block left read-only and forgotten would be an access violation in @@ -6722,15 +7757,15 @@ mod port7_tests { let mut notes = Notes::new(); notes.shard_mut(3).note(3, WHOLE, 9); let mut seen = Vec::new(); - assert!(notes.all_newer(0, 8, 9, |p, w| { + assert!(notes.all_newer(0, 8, 9, |_, p, w| { seen.push((p, w)); false })); assert!(seen.is_empty(), "nothing is newer than 9"); - assert!(!notes.all_newer(0, 8, 8, |_, _| false)); - assert!(notes.all_newer(0, usize::MAX / 2, 9, |_, _| false)); - assert!(!notes.all_newer(0, usize::MAX / 2, 8, |_, _| false)); - assert!(notes.all_newer(0, 8, 8, |p, w| (p, w) == (3, 9))); + assert!(!notes.all_newer(0, 8, 8, |_, _, _| false)); + assert!(notes.all_newer(0, usize::MAX / 2, 9, |_, _, _| false)); + assert!(!notes.all_newer(0, usize::MAX / 2, 8, |_, _, _| false)); + assert!(notes.all_newer(0, 8, 8, |_, p, w| (p, w) == (3, 9))); } #[test] diff --git a/d3d12/crates/leonida-hle/src/lib.rs b/d3d12/crates/leonida-hle/src/lib.rs index 57f66b38e6..9493d014f5 100644 --- a/d3d12/crates/leonida-hle/src/lib.rs +++ b/d3d12/crates/leonida-hle/src/lib.rs @@ -19,6 +19,8 @@ pub use leonida_gpu::frame_phase; pub mod modules; mod registry; pub mod runtime; +#[cfg(all(test, not(any(feature = "diagnostics", feature = "mimalloc"))))] +mod test_alloc; pub use host::HostPolicy; pub use registry::{HleExport, HleModule, registry}; diff --git a/d3d12/crates/leonida-hle/src/modules/apu.rs b/d3d12/crates/leonida-hle/src/modules/apu.rs index f56a64914e..6b322d5c04 100644 --- a/d3d12/crates/leonida-hle/src/modules/apu.rs +++ b/d3d12/crates/leonida-hle/src/modules/apu.rs @@ -138,6 +138,11 @@ struct State { results: VecDeque<ApuResult>, commands: u32, dequeued: u32, + /// What a packet decodes into before its frames are copied out: room for + /// the longest packet of two channels, made once. Each packet had its + /// own, 46 KB allocated and zeroed for each of the 50 packets a second + /// of every stream that plays. + pcm: Vec<f32>, } // SAFETY: `memory` and `event` are owned by `Connection` and freed only in @@ -282,6 +287,7 @@ pub extern "system" fn XApuConnect( results: VecDeque::new(), commands: 0, dequeued: 0, + pcm: vec![0.0; MAX_FRAMES * 2], }), }); let id = register(connection); @@ -318,6 +324,9 @@ pub extern "system" fn XApuEnqueueCommand( // SAFETY: checked non-null; every command starts with an id. let id = unsafe { command.read_unaligned() }; let mut state = lock(&connection); + // (Through a plain reference, so a decoder and the PCM memory can be + // borrowed at once.) + let state = &mut *state; let stream = id.stream as usize; if stream >= state.streams.len() { return INVALID_STREAM; @@ -369,7 +378,7 @@ pub extern "system" fn XApuEnqueueCommand( // SAFETY: a process command is this struct. let command = unsafe { command.cast::<Process>().read_unaligned() }; match decoder { - Some(d) => process(d, connection.options, &command, &mut result), + Some(d) => process(d, connection.options, &command, &mut state.pcm, &mut result), None => result.error = INVALID_STREAM, } } @@ -390,8 +399,15 @@ pub extern "system" fn XApuEnqueueCommand( } /// Decodes one packet into the command's output buffer, keeping the frames -/// from `first_frame` on, at most `frame_count` of them. -fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: &mut ApuResult) { +/// from `first_frame` on, at most `frame_count` of them; `pcm` is room for +/// the longest packet of two channels. +fn process( + decoder: &mut OpusDecoder, + options: u32, + command: &Process, + pcm: &mut [f32], + result: &mut ApuResult, +) { let channels = decoder.channels(); let (input, input_length) = (command.input, command.input_length); let (output, output_length) = (command.output, command.output_length); @@ -404,8 +420,10 @@ fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: & } // SAFETY: the title's packet in its connection memory. let packet = unsafe { std::slice::from_raw_parts(input, input_length as usize) }; - let mut pcm = vec![0f32; MAX_FRAMES * channels]; - let decoded = match decoder.decode(packet, MAX_FRAMES, &mut pcm) { + // Only what this packet decodes is read back, so what an earlier one + // left in it does not matter. + let pcm = &mut pcm[..MAX_FRAMES * channels]; + let decoded = match decoder.decode(packet, MAX_FRAMES, pcm) { Ok(n) => n, Err(_) => { result.error = BAD_PACKET; @@ -486,7 +504,7 @@ pub(crate) fn module() -> HleModule { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use opus_pure::{Application, OpusEncoder}; @@ -610,6 +628,106 @@ mod tests { assert_eq!(XApuDisconnect(handle), S_OK); } + /// Counts this thread's allocations of a stereo packet's PCM or larger, + /// for what a packet costs. The test binary's allocator (`test_alloc`) + /// tells it of each block. Not with the allocators the features bring. + #[cfg(not(any(feature = "diagnostics", feature = "mimalloc")))] + pub(crate) mod counting { + use std::cell::Cell; + + const LARGE: usize = super::MAX_FRAMES * 2 * size_of::<f32>(); + + std::thread_local! { + pub(crate) static COUNT: Cell<usize> = const { Cell::new(0) }; + } + + pub(crate) fn note(size: usize) { + if size >= LARGE { + let _ = COUNT.try_with(|n| n.set(n.get() + 1)); + } + } + } + + /// A packet decodes into memory the connection keeps: each of the 50 + /// packets a second of every stream that plays allocated and zeroed + /// 46 KB of its own. + #[cfg(not(any(feature = "diagnostics", feature = "mimalloc")))] + #[test] + fn packets_decode_without_memory_of_their_own() { + let input = ConnectInput { + process: DECODE_OPUS, + streams: 1, + commands_per_stream: 2, + memory: 0x2_0000, + frames_per_output: 0, + options: 0, + }; + let mut output = ConnectOutput { + memory: std::ptr::null_mut(), + result_event: std::ptr::null_mut(), + }; + let mut handle = std::ptr::null_mut(); + assert_eq!(XApuConnect(&input, &mut output, &mut handle), S_OK); + let base = output.memory.cast::<u8>(); + let activate = Activate { + id: id(ACTIVATE, 0), + channels: 2, + init_length: 0, + init: std::ptr::null(), + start_pitch: 1.0, + processing_length: 0, + processing: std::ptr::null_mut(), + }; + let mut result = std::mem::MaybeUninit::<ApuResult>::zeroed(); + assert_eq!( + XApuEnqueueCommand(handle, (&raw const activate).cast(), std::ptr::null_mut()), + S_OK + ); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + + let tone: Vec<f32> = (0..960 * 2) + .map(|i| ((i / 2) as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5) + .collect(); + let mut encoder = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); + let mut packet = [0u8; 1500]; + let n = encoder.encode(&tone, 960, &mut packet).unwrap(); + // SAFETY: inside the connection memory. + unsafe { std::ptr::copy_nonoverlapping(packet.as_ptr(), base, n) }; + let process = Process { + id: id(PROCESS, 0), + pitch_ramp: 0.0, + target_pitch: 1.0, + first_frame: 0, + frame_count: 960, + input_length: n as u32, + input: base, + output_length: 960 * 8, + output: base.wrapping_add(0x1_0000), + }; + let mut decode = || { + assert_eq!( + XApuEnqueueCommand(handle, (&raw const process).cast(), std::ptr::null_mut()), + S_OK + ); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + // SAFETY: written above. + let error = unsafe { result.assume_init() }.error; + assert_eq!(error, S_OK); + }; + // The first packet may set up the decoder's own memory. + decode(); + let before = counting::COUNT.with(|n| n.get()); + for _ in 0..10 { + decode(); + } + let large = counting::COUNT.with(|n| n.get()) - before; + assert_eq!( + large, 0, + "10 packets made {large} allocations of a packet's PCM or larger" + ); + assert_eq!(XApuDisconnect(handle), S_OK); + } + #[test] fn decodes_into_unaligned_output_interleaved_and_deinterleaved() { let tone: Vec<f32> = (0..960 * 2) diff --git a/d3d12/crates/leonida-hle/src/modules/d3d12x.rs b/d3d12/crates/leonida-hle/src/modules/d3d12x.rs index 56d88f4147..f16a41c5a3 100644 --- a/d3d12/crates/leonida-hle/src/modules/d3d12x.rs +++ b/d3d12/crates/leonida-hle/src/modules/d3d12x.rs @@ -10,7 +10,8 @@ use leonida_gpu::object::{HRESULT, Iid, Object}; use crate::{HleExport, HleModule}; /// Device creation; first hands the device the title's general allocator -/// (`XMemAlloc`, which honours the title's hooks) for resource memory. +/// (`XMemAlloc`, which honours the title's hooks) for resource memory, and +/// xmem's write-watched reservations for the heaps the title makes. extern "system" fn create_device( adapter: *const c_void, parameters: *const u32, @@ -18,6 +19,7 @@ extern "system" fn create_device( out: *mut *const Object, ) -> HRESULT { leonida_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree); + leonida_gpu::resource::use_heap_memory(super::xmem::heap_memory, super::xmem::heap_memory_free); leonida_gpu::resource::use_page_mapper(super::xmem::map_alias); leonida_gpu::resource::use_many_page_mapper(super::xmem::map_aliases); leonida_gpu::resource::use_later_page_mapper(super::xmem::map_aliases_later); diff --git a/d3d12/crates/leonida-hle/src/modules/dstorage.rs b/d3d12/crates/leonida-hle/src/modules/dstorage.rs index 427b75e40d..b2977d2e98 100644 --- a/d3d12/crates/leonida-hle/src/modules/dstorage.rs +++ b/d3d12/crates/leonida-hle/src/modules/dstorage.rs @@ -12,16 +12,16 @@ //! console's hardware runs them: in parallel, started in queue order, //! queues served by weighted round robin over their priorities (about 10x //! per level, counted in bytes), with at most the staging buffer's worth of -//! compressed source in flight. Each request reads its source (a file or -//! memory), inflates zlib data and/or unpacks BCPack data, and writes the -//! destination (an address, or physical pages). Completion is what stays -//! in order: a status entry is written once every request enqueued before -//! it on its queue has finished, with the first failure (in queue order) -//! since the previous status entry, or success. +//! buffered bytes in flight ([`staging_bytes`]). Each request reads its +//! source (a file or memory), inflates zlib data and/or unpacks BCPack data, +//! and writes the destination (an address, or physical pages), through +//! buffers its worker keeps from one request to the next ([`Scratch`]). +//! Completion is what stays in order: a status entry is written once every +//! request enqueued before it on its queue has finished, with the first +//! failure (in queue order) since the previous status entry, or success. #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; use std::ffi::{CStr, c_char, c_void}; use std::os::windows::fs::FileExt; @@ -154,7 +154,6 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out if stream_log::on() { stream_log::line(format_args!("F\t{:x}\t{kept}", file as usize)); } - WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept)); put(out, file) } @@ -229,7 +228,9 @@ extern "system" fn create_queue( /// The title asks for 32 MiB and stops if this fails. Give PC worker threads /// enough staging headroom (default 256 MiB) so multi-MB RPF chunks don't -/// starve the remaining cores. +/// starve the remaining cores. This is the largest bound on this module's +/// RAM: it caps the buffers of the requests running ([`staging_bytes`]); what +/// the workers keep between requests is apart from it ([`SCRATCH_KEPT`] each). extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT { static FLOOR_MB: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); let floor = *FLOOR_MB.get_or_init(|| { @@ -662,9 +663,22 @@ fn walls_trace() -> u8 { }) } -/// The files opened, by the address of our file object, with their paths -/// (for the walls trace: a request names its file by that address). -static WALLS_FILES: Mutex<Vec<(usize, String)>> = Mutex::new(Vec::new()); +/// The file a request reads, as the walls trace names it: the path its +/// file object was opened by ([`File::name`]). A list of every file opened, +/// by object address, used to give the names: it grew by a path per open +/// for the whole run, with the trace off too, and named a file object made +/// where a released one was by the first one opened there. +fn walls_file(request: &Request) -> String { + if request.options & MEMORY_SOURCE != 0 { + return "memory".to_string(); + } + if request.source.is_null() { + return "?".to_string(); + } + // SAFETY: a file object we created; the title keeps it open until the + // request is done ([`read_into`] read it the same way). + unsafe { &*request.source.cast::<Instance<File>>() }.state.name.clone() +} /// The walls trace's line for a request that is done. fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std::time::Instant) { @@ -672,13 +686,7 @@ fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std:: if level == 0 || (level == 1 && result.is_ok()) { return; } - let file = if request.options & MEMORY_SOURCE != 0 { - "memory".to_string() - } else { - let files = WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()); - let source = request.source as usize; - files.iter().find(|f| f.0 == source).map_or_else(|| "?".to_string(), |f| f.1.clone()) - }; + let file = walls_file(request); let hr = match result { Ok(()) => 0, Err(hr) => *hr as u32, @@ -776,6 +784,8 @@ pub(crate) mod stream_log { /// A worker: runs the next read of the most deserving queue. fn work(scheduler: &'static Scheduler) { + // This worker's buffers, in its own frame for as long as it runs. + let mut scratch = Scratch::default(); let mut lanes = scheduler.lock(); loop { let Some(job) = lanes.start() else { @@ -786,7 +796,8 @@ fn work(scheduler: &'static Scheduler) { let started = std::time::Instant::now(); let traced = Traced::start(&job); let reading = leonida_gpu::timeline::span("streaming: a request"); - let result = execute(&job.request); + let result = execute(&job.request, &mut scratch); + scratch.trim(); reading.end(); walls_request(&job.request, &result, started); stream_log::request(&job, started, &result); @@ -803,6 +814,58 @@ fn work(scheduler: &'static Scheduler) { } } +/// A worker's buffers between a request's source and its destination: a +/// compressed source read from its file, the zlib output that BCPack then +/// unpacks, and the bytes of a destination in pages that are not one +/// allocation's in order. They are kept from one request to the next: new +/// ones for every request cost an allocation each, and blocks of 1 MiB and +/// more come from the host's virtual memory, fresh and zero-filled each time +/// and given back at the end. +#[derive(Default)] +struct Scratch { + source: Vec<u8>, + packed: Vec<u8>, + pages: Vec<u8>, +} + +/// What a worker keeps of its buffers between requests. A request that needs +/// more has them for its own time, so at most this times the workers stays +/// allocated while nothing runs. +const SCRATCH_KEPT: usize = 16 << 20; + +impl Scratch { + /// Gives up buffers, largest first, until those kept hold at most + /// [`SCRATCH_KEPT`]. + fn trim(&mut self) { + let mut buffers = [&mut self.source, &mut self.packed, &mut self.pages]; + buffers.sort_unstable_by_key(|b| std::cmp::Reverse(b.capacity())); + let mut kept: usize = buffers.iter().map(|b| b.capacity()).sum(); + for buffer in buffers { + if kept <= SCRATCH_KEPT { + break; + } + kept -= buffer.capacity(); + *buffer = Vec::new(); + } + } +} + +/// `len` bytes of `buffer` for a request to overwrite. The buffer grows only +/// past what earlier requests left in it, so a reused one is neither +/// allocated nor cleared again; what those requests wrote stays in it, and +/// callers use only the bytes they write. One that is too small is replaced +/// rather than grown, since nothing in it needs copying. +fn room(buffer: &mut Vec<u8>, len: usize) -> &mut [u8] { + if buffer.capacity() < len { + // The old one goes first, so that both are never held at once. + *buffer = Vec::new(); + *buffer = vec![0; len]; + } else if buffer.len() < len { + buffer.resize(len, 0); + } + &mut buffer[..len] +} + impl Lanes { /// Counts a finished request; every 5 s a debug line sums them up. fn count(&mut self, job: &Job, started: std::time::Instant) { @@ -967,15 +1030,32 @@ impl Lane { } /// Staging bytes a request holds while it runs: what it buffers between -/// the file and the destination. Raw reads go straight to their -/// destination, memory sources need none (as on the console). +/// the source and the destination. That is a compressed source read from a +/// file, the zlib output that BCPack then unpacks, and for physical pages +/// the destination's bytes, which go through a buffer when the pages are +/// not one allocation's in order (rarely, but nothing tells beforehand). +/// Raw reads go straight to their destination, and memory sources are read +/// where they are (as on the console). fn staging_bytes(request: &Request) -> u64 { - let buffered = request.options & (ZLIB | BCPACK | PAGE_DESTINATION) != 0; - if buffered && request.options & MEMORY_SOURCE == 0 { - u64::from(request.source_size) + let options = request.options; + let compressed = options & (ZLIB | BCPACK) != 0; + let source = if compressed && options & MEMORY_SOURCE == 0 { + request.source_size } else { 0 - } + }; + let packed = if options & ZLIB != 0 && options & BCPACK != 0 { + request.intermediate_size + } else { + 0 + }; + // What `execute` writes: the decompressed bytes, or a raw copy's source. + let pages = match (options & PAGE_DESTINATION != 0, compressed) { + (false, _) => 0, + (true, true) => request.destination_size, + (true, false) => request.source_size, + }; + u64::from(source) + u64::from(packed) + u64::from(pages) } /// Ends a queue: what was not started is dropped, and this waits for the @@ -1018,7 +1098,8 @@ struct Request { source: *const c_void, offset: u64, source_size: u32, - /// Compressed size between two decompression stages; unused here. + /// Compressed size between two decompression stages: room for the zlib + /// output that BCPack then unpacks. intermediate_size: u32, /// Matched by cancellation; the title leaves it 0. tag: u64, @@ -1375,8 +1456,10 @@ extern "system" fn close(this: QueueRef) { close_lane(unsafe { &*this }.state.id); } -/// Reads, inflates and/or unpacks, and writes one request. -fn execute(request: &Request) -> Result<(), HRESULT> { +/// Reads, inflates and/or unpacks, and writes one request, through the +/// worker's buffers. +fn execute(request: &Request, scratch: &mut Scratch) -> Result<(), HRESULT> { + let Scratch { source: read, packed, pages } = scratch; let options = request.options; let fail = |hr: HRESULT, why: &str| { tracing::warn!( @@ -1404,7 +1487,7 @@ fn execute(request: &Request) -> Result<(), HRESULT> { if options & (ZLIB | BCPACK | MEMORY_SOURCE) == ZLIB && let Some(movie) = glyph_movie(request) { - return into_destination(request, size, |out| { + return into_destination(request, size, pages, |out| { let n = movie.len().min(out.len()); out[..n].copy_from_slice(&movie[..n]); out[n..].fill(0); @@ -1416,35 +1499,34 @@ fn execute(request: &Request) -> Result<(), HRESULT> { return Err(fail(E_INVALIDARG, "source larger than destination")); } let size = request.source_size as usize; - return into_destination(request, size, |out| read_into(request, out).map(|()| size)) + return into_destination(request, size, pages, |out| read_into(request, out).map(|()| size)) .map_err(|hr| fail(hr, "copying")); } let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; // (The parts of a request a timeline tells apart: `LEONIDA_TIMELINE`.) let reading = leonida_gpu::timeline::span("streaming: reading the source"); - let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; + let source = read_source(request, read).map_err(|hr| fail(hr, "reading the source"))?; drop(reading); // The console's order: zlib first, then BCPack. let source = if bc != 0 && options & ZLIB != 0 { let _inflating = leonida_gpu::timeline::span("streaming: inflating"); - let mut packed = vec![0; request.intermediate_size as usize]; - let n = inflate(&source, &mut packed).map_err(|hr| fail(hr, "zlib"))?; - packed.truncate(n); - Cow::Owned(packed) + let out = room(packed, request.intermediate_size as usize); + let n = inflate(source, out).map_err(|hr| fail(hr, "zlib"))?; + &packed[..n] } else { source }; - into_destination(request, size, |out| match tables { + into_destination(request, size, pages, |out| match tables { Some(tables) => { let _unpacking = leonida_gpu::timeline::span("streaming: unpacking BCPack"); - bcpack_dump(bc, &source, out.len()); - bcpack::decode(bc, &source, out, tables) + bcpack_dump(bc, source, out.len()); + bcpack::decode(bc, source, out, tables) .map(|()| out.len()) .map_err(|e| fail(INVALID_DATA, &e.to_string())) } None => { let _inflating = leonida_gpu::timeline::span("streaming: inflating"); - inflate(&source, out).map_err(|hr| fail(hr, "zlib")) + inflate(source, out).map_err(|hr| fail(hr, "zlib")) } })?; tracing::trace!( @@ -1572,18 +1654,19 @@ fn load_bcpack_tables() -> Result<Tables, String> { Tables::parse(&bytes).map_err(|e| e.to_string()) } -/// A compressed request's source: borrowed from memory, or read from the -/// file. -fn read_source(request: &Request) -> Result<Cow<'static, [u8]>, HRESULT> { +/// A compressed request's source: in memory where it is, or read from the +/// file into `buffer`. +fn read_source<'a>(request: &Request, buffer: &'a mut Vec<u8>) -> Result<&'a [u8], HRESULT> { let size = request.source_size as usize; if request.options & MEMORY_SOURCE != 0 { // SAFETY: the title's source holds `size` bytes until completion. - let bytes = unsafe { std::slice::from_raw_parts(request.source.cast(), size) }; - return Ok(Cow::Borrowed(bytes)); + return Ok(unsafe { std::slice::from_raw_parts(request.source.cast(), size) }); } - let mut bytes = vec![0; size]; - read_into(request, &mut bytes)?; - Ok(Cow::Owned(bytes)) + // `read_into` writes all of it or fails, so nothing an earlier request + // left in the buffer shows. + let bytes = room(buffer, size); + read_into(request, bytes)?; + Ok(bytes) } /// Nanoseconds workers spent reading files, for the debug summary. @@ -1644,10 +1727,11 @@ fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { /// many it produced. GPU-visible destinations are host memory like the /// rest (GPU address = CPU address), so an address is written in place; /// physical pages are too when they are consecutive pages of one -/// allocation, and otherwise go through a buffer. +/// allocation, and otherwise go through `buffer`. fn into_destination( request: &Request, len: usize, + buffer: &mut Vec<u8>, mut fill: impl FnMut(&mut [u8]) -> Result<usize, HRESULT>, ) -> Result<(), HRESULT> { if request.options & PAGE_DESTINATION == 0 { @@ -1677,7 +1761,7 @@ fn into_destination( // (Said aloud: by the title's protocol a submitted request's list stays // as it is.) for _ in 0..3 { - into_pages(&pages, offset, len, &mut fill)?; + into_pages(&pages, offset, len, buffer, &mut fill)?; let now = read_list(list, offset, len); if now == pages || !super::xmem::pages_known(&now, offset, len) { break; @@ -1695,11 +1779,13 @@ fn into_destination( Ok(()) } -/// Runs `fill` on `len` bytes of `pages`, from `offset` into the first. +/// Runs `fill` on `len` bytes of `pages`, from `offset` into the first; +/// through `buffer` when they are not one allocation's in order. fn into_pages( pages: &[usize], offset: usize, len: usize, + buffer: &mut Vec<u8>, mut fill: impl FnMut(&mut [u8]) -> Result<usize, HRESULT>, ) -> Result<(), HRESULT> { // Consecutive pages of one allocation (the usual case): written in @@ -1709,8 +1795,11 @@ fn into_pages( super::xmem::pages_written(pages, offset, len); return filled; } - let mut data = vec![0; len]; - let n = fill(&mut data)?; + let data = room(buffer, len); + // Zero as a new buffer would be, so that bytes a decoder leaves alone + // are not an earlier request's. + data.fill(0); + let n = fill(data)?; // A page the title has just made, or a view the host refuses for a moment (commit // or address space short while a load maps many at once), can come right a little // later: tried again before the request fails (`LEONIDA_DSTORAGE_RETRIES`, default 12, @@ -1816,7 +1905,7 @@ pub(crate) fn module() -> HleModule { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use std::os::windows::ffi::OsStrExt; use std::time::{Duration, Instant}; @@ -2130,7 +2219,7 @@ mod tests { let len = PAGE + 100; let r = request(PAGE_DESTINATION, at.cast(), len, std::ptr::null(), 0, len); let mut runs = 0; - let written = into_destination(&r, len, |out| { + let written = into_destination(&r, len, &mut Vec::new(), |out| { runs += 1; out.fill(0xa5); // SAFETY: our own list. @@ -2170,7 +2259,7 @@ mod tests { protect(PAGE_READWRITE) }); let r = request(0, at as *mut c_void, plain.len(), file, 0, plain.len()); - assert_eq!(execute(&r), Ok(())); + assert_eq!(execute(&r, &mut Scratch::default()), Ok(())); assert_ne!(opener.join().unwrap(), 0); // SAFETY: as above, all of it readable. assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, plain.len()) }, plain); @@ -2329,6 +2418,55 @@ mod tests { assert!(l.start().is_some()); } + /// What a request holds of the staging buffer is every buffer it fills + /// between the source and the destination. + #[test] + fn staging_counts_every_buffer_a_request_holds() { + let (to, from) = (std::ptr::null_mut(), std::ptr::null()); + // zlib then BCPack from a file: the source and the zlib output. + let mut both = request(ZLIB | 4 << 1, to, 4096, from, 0, 1000); + both.intermediate_size = 3000; + assert_eq!(staging_bytes(&both), 1000 + 3000); + // From memory the source is read where it is; the zlib output is not. + both.options |= MEMORY_SOURCE; + assert_eq!(staging_bytes(&both), 3000); + // Pages of several allocations take the destination's bytes through a + // buffer, so a request to pages holds that much too. + let to_pages = request(ZLIB | PAGE_DESTINATION, to, 4096, from, 0, 1000); + assert_eq!(staging_bytes(&to_pages), 1000 + 4096); + let raw_to_pages = request(PAGE_DESTINATION | MEMORY_SOURCE, to, 1000, from, 0, 1000); + assert_eq!(staging_bytes(&raw_to_pages), 1000); + // zlib alone and raw reads to an address hold what they did. + assert_eq!(staging_bytes(&request(ZLIB, to, 4096, from, 0, 1000)), 1000); + assert_eq!(staging_bytes(&request(0, to, 1000, from, 0, 1000)), 0); + } + + /// A worker's buffers are used again by smaller requests, and it keeps + /// at most `SCRATCH_KEPT` of them between requests, giving up the + /// largest first. + #[test] + fn a_worker_keeps_its_buffers_up_to_a_bound() { + let mut scratch = Scratch::default(); + room(&mut scratch.source, 1 << 20).fill(1); + room(&mut scratch.packed, 2 << 20); + scratch.trim(); + let (source, packed) = (scratch.source.as_ptr(), scratch.packed.as_ptr()); + // Smaller requests: the same buffers, and what they do not write + // stays as it was (nobody reads it). + assert_eq!(room(&mut scratch.source, 100).as_ptr(), source); + assert_eq!(room(&mut scratch.packed, 1 << 20).as_ptr(), packed); + assert_eq!(scratch.source.len(), 1 << 20); + room(&mut scratch.pages, SCRATCH_KEPT); + scratch.trim(); + assert_eq!(scratch.pages.capacity(), 0, "the largest goes"); + assert_eq!((scratch.source.as_ptr(), scratch.packed.as_ptr()), (source, packed)); + // A request larger than the bound has its buffer for its own time. + room(&mut scratch.source, SCRATCH_KEPT + 1); + scratch.trim(); + assert_eq!(scratch.source.capacity(), 0); + assert!(scratch.packed.capacity() >= 2 << 20); + } + #[test] fn a_status_waits_for_every_earlier_read() { let mut l = lanes(STAGING); @@ -2375,6 +2513,132 @@ mod tests { assert_eq!(out, bc4_blocks()); } + /// Counts the blocks of the sizes a test watches + /// (`compressed_requests_reuse_the_workers_buffers`). The test binary's + /// allocator (`test_alloc`) tells it of each block. Not with the features + /// under which leonida-gpu installs an allocator of its own. + #[cfg(not(any(feature = "diagnostics", feature = "mimalloc")))] + pub(crate) mod watched_blocks { + use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; + + /// The sizes watched (0: none), and how many blocks of each were + /// allocated since. + pub(super) static SIZES: [AtomicUsize; 3] = [const { AtomicUsize::new(0) }; 3]; + pub(super) static BLOCKS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + + pub(crate) fn note(size: usize) { + for (watched, blocks) in SIZES.iter().zip(&BLOCKS) { + if size != 0 && watched.load(Relaxed) == size { + blocks.fetch_add(1, Relaxed); + } + } + } + } + + /// Compressed requests run on buffers their worker keeps: the source + /// read from the file, the zlib output that BCPack unpacks, and the + /// bytes of a destination in pages that are not one allocation's in + /// order are each allocated at most once per worker, not once per + /// request (blocks of 1 MiB and more come from the host's virtual + /// memory, new and zero-filled each time). + #[cfg(not(any(feature = "diagnostics", feature = "mimalloc")))] + #[test] + fn compressed_requests_reuse_the_workers_buffers() { + use crate::modules::xmem; + use watched_blocks::{BLOCKS, SIZES}; + with_test_tables(); + const BATCH: usize = 8; + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()); + // More requests of each kind than there are workers, several times. + let batches = 4 * workers.div_ceil(BATCH) + 1; + + // zlib from the file, with about 1 MiB of source: bytes that do not + // compress (xorshift), so that the stream is about as long. + let mut x = 0x9e37_79b9_7f4a_7c15_u64; + let plain: Vec<u8> = (0..(1 << 20) + 1234) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x >> 32) as u8 + }) + .collect(); + let packed = compress_zlib(&plain); + // zlib then BCPack from the file, with room for a BCPack stream far + // longer than this one (a stream may end short of it). + let bc4 = compress_zlib(&BC4_STREAM); + let intermediate = (1 << 20) + 4099; + let mut contents = packed.clone(); + contents.extend_from_slice(&bc4); + let (_dir, file) = file_with(&contents); + // zlib from memory into three pages listed backwards: through a buffer. + let paged = pattern(2 * PAGE + 4093); + let paged_packed = compress_zlib(&paged); + let mut pages = vec![0usize; 3 * BATCH]; + let mut n = pages.len(); + assert_eq!(xmem::XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + let mut lists: Vec<[usize; 3]> = + pages.chunks_exact(3).map(|p| [p[2], p[1], p[0]]).collect(); + let mut inflated = vec![vec![0u8; plain.len()]; BATCH]; + let mut unpacked = [[0u8; 16]; BATCH]; + + let (queue, array) = (new_queue(0), status_array(1)); + // Sizes of their own: nothing else here allocates blocks of them. + let watch = [packed.len(), intermediate, paged.len()]; + assert!(watch.iter().all(|&size| size >= 2 * PAGE && size != plain.len())); + for ((watched, blocks), size) in SIZES.iter().zip(&BLOCKS).zip(watch) { + blocks.store(0, Ordering::Relaxed); + watched.store(size, Ordering::Relaxed); + } + // A page's bytes, from the start, and what of the destination it holds. + let pieces = |list: [usize; 3]| { + [(list[0], 0..PAGE), (list[1], PAGE..2 * PAGE), (list[2], 2 * PAGE..paged.len())] + }; + for _ in 0..batches { + for i in 0..BATCH { + inflated[i].fill(0); + unpacked[i] = [0; 16]; + for (page, _) in pieces(lists[i]) { + xmem::page_window(&[page], 0, PAGE).unwrap().bytes().fill(0); + } + let at = inflated[i].as_mut_ptr().cast(); + enqueue(queue, &request(ZLIB, at, plain.len(), file, 0, packed.len())); + let at = unpacked[i].as_mut_ptr().cast(); + let mut r = request(ZLIB | 4 << 1, at, 16, file, packed.len() as u64, bc4.len()); + r.intermediate_size = intermediate as u32; + enqueue(queue, &r); + let at = lists[i].as_mut_ptr().cast(); + let options = ZLIB | PAGE_DESTINATION | MEMORY_SOURCE; + let source = paged_packed.as_ptr().cast(); + enqueue(queue, &request(options, at, paged.len(), source, 0, paged_packed.len())); + } + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + for i in 0..BATCH { + assert!(inflated[i] == plain, "zlib request {i}"); + assert_eq!(unpacked[i], bc4_blocks(), "zlib then BCPack request {i}"); + for (page, bytes) in pieces(lists[i]) { + let mut window = xmem::page_window(&[page], 0, bytes.len()).unwrap(); + assert!(*window.bytes() == paged[bytes], "request {i} to pages"); + } + } + } + for watched in &SIZES { + watched.store(0, Ordering::Relaxed); + } + void(queue, 0x40); + assert_eq!(xmem::XMemFreePhysicalPages(pages.len(), pages.as_ptr()), 1); + let blocks = BLOCKS.each_ref().map(|b| b.load(Ordering::Relaxed)); + assert!( + blocks.iter().all(|&b| b <= workers as u64), + "buffers allocated for the source read from the file, the zlib output for BCPack \ + and the destination in pages: {blocks:?}, in {} requests of each kind on {workers} \ + workers", + batches * BATCH + ); + } + /// BCPack tables we made (uniform models; BC4 index pairs: low 3 bits, /// next 3 bits), in a folder kept for the test process. fn with_test_tables() { @@ -2605,4 +2869,39 @@ mod tests { assert_eq!(inflate(&packed, &mut out), Ok(plain.len())); assert_eq!(out, plain); } + + /// (`LEONIDA_WALLS_TRACE`) A request is traced by the name of the file + /// object it reads, also a file object made where another one was. + /// The trace kept every file opened, by address, for the whole run + /// (with the trace off too), and named a file at a reused address by + /// the first one opened there. The reuse is made here, not waited for + /// (the host's heap hands an address out again when it likes): the two + /// objects trade their files in place, so the object at the first one's + /// address is the second file, as a file opened where a released one + /// was would be, and both were opened through `open_file`. + #[test] + fn the_walls_trace_names_the_file_a_request_reads() { + let dir = tempfile::tempdir().unwrap(); + let first = dir.path().join("first.bin"); + let second = dir.path().join("second.bin"); + std::fs::write(&first, b"first").unwrap(); + std::fs::write(&second, b"second").unwrap(); + let name = |file: *mut c_void| walls_file(&request(0, std::ptr::null_mut(), 0, file, 0, 0)); + let a = open(&first); + let b = open(&second); + assert_eq!(name(a), first.to_string_lossy()); + assert_eq!(name(b), second.to_string_lossy()); + // SAFETY: two live file objects we created, each an `Instance<File>`; + // only their states trade places, and each is released once below. + unsafe { + std::ptr::swap( + &raw mut (*a.cast::<Instance<File>>()).state, + &raw mut (*b.cast::<Instance<File>>()).state, + ); + } + assert_eq!(name(a), second.to_string_lossy(), "the second file at the first one's address"); + assert_eq!(name(b), first.to_string_lossy(), "the first file at the second one's address"); + release::<File>(a.cast()); + release::<File>(b.cast()); + } } diff --git a/d3d12/crates/leonida-hle/src/modules/xasync.rs b/d3d12/crates/leonida-hle/src/modules/xasync.rs index d08d4f6bf1..d57945b97b 100644 --- a/d3d12/crates/leonida-hle/src/modules/xasync.rs +++ b/d3d12/crates/leonida-hle/src/modules/xasync.rs @@ -14,7 +14,7 @@ use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard}; -use std::time::Duration; +use std::time::{Duration, Instant}; use super::xgameruntime::{Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing}; @@ -147,45 +147,131 @@ impl Port { } } -/// The thread pool behind thread-pool ports: idle workers are reused, and a -/// new one starts whenever more tasks wait than workers idle, so a callback -/// that blocks on another never starves it. Workers stay for reuse. +/// The thread pool behind thread-pool ports. Idle workers are reused, and +/// while tasks wait there is always a worker coming to take them: a task +/// queued wakes an idle worker or, with none idle or coming, starts one, and +/// a worker that takes a task while others still wait, with none idle or +/// coming, starts the next before its task runs. So a callback that blocks +/// on another never starves it, while a burst of short tasks is run by a few +/// workers instead of a thread each. Each worker holds a stack and the +/// title's per-thread state, so one that has waited out `linger` with no +/// task leaves, down to `keep` idle ones. struct Pool { - /// Queued tasks and the number of idle workers. - state: Mutex<(VecDeque<Task>, usize)>, - ready: Condvar, -} - -static POOL: Pool = Pool { - state: Mutex::new((VecDeque::new(), 0)), - ready: Condvar::new(), -}; + state: Mutex<PoolState>, + linger: Duration, + keep: usize, +} + +struct PoolState { + tasks: VecDeque<Task>, + /// Idle workers, each waiting on a condition variable of its own, the + /// one that went idle last on top. A queued task takes the top one off + /// and wakes it. Waking them in turn instead would restart each one's + /// linger, so under a steady trickle of tasks none would ever leave. + idle: Vec<Arc<Condvar>>, + /// Workers started, or woken for a task, that have not looked for one + /// yet: each takes a task without waiting, so a task queued meanwhile + /// has a worker coming. + coming: usize, + /// Every worker that has not left: idle, coming or running a task. + workers: usize, +} + +/// Idle workers leave after 30 seconds without a task, down to four, so the +/// pool goes back to a few threads once a burst is over, even while a few +/// tasks keep coming. +static POOL: Pool = Pool::new(Duration::from_secs(30), 4); impl Pool { + const fn new(linger: Duration, keep: usize) -> Pool { + Pool { + state: Mutex::new(PoolState { + tasks: VecDeque::new(), + idle: Vec::new(), + coming: 0, + workers: 0, + }), + linger, + keep, + } + } + fn submit(&'static self, task: Task) { let mut state = lock(&self.state); - state.0.push_back(task); - if state.0.len() > state.1 { - std::thread::spawn(move || self.work()); - } else { - self.ready.notify_one(); + state.tasks.push_back(task); + // The worker that went idle last takes it, or one coming does (and + // starts the next if more wait); with neither, one starts. + if let Some(worker) = state.idle.pop() { + state.coming += 1; + worker.notify_one(); + } else if state.coming == 0 { + self.start(state); } } - fn work(&self) { + /// Starts a worker. The thread is created after the lock is let go, as + /// creating it takes a while and the other workers need the lock. + fn start(&'static self, mut state: MutexGuard<'_, PoolState>) { + state.coming += 1; + state.workers += 1; + drop(state); + if let Err(error) = std::thread::Builder::new().spawn(move || self.work()) { + // A worker that never came must not stay counted as coming, or no + // task queued later would start another. The tasks waiting now + // go to the next worker that finishes a task, or to the worker + // the next queued task tries to start. + let mut state = lock(&self.state); + state.coming -= 1; + state.workers -= 1; + tracing::warn!(%error, "task pool: a worker could not be started"); + } + } + + fn work(&'static self) { + let wake = Arc::new(Condvar::new()); let mut state = lock(&self.state); + state.coming -= 1; loop { - while state.0.is_empty() { - state.1 += 1; - state = self.ready.wait(state).unwrap_or_else(|e| e.into_inner()); - state.1 -= 1; - } - let task = state.0.pop_front(); - drop(state); - if let Some(task) = task { + if let Some(task) = state.tasks.pop_front() { + // This task may block on one still queued, so that one needs + // a worker of its own coming. + if !state.tasks.is_empty() && state.idle.is_empty() && state.coming == 0 { + self.start(state); + } else { + drop(state); + } task.run(false); + state = lock(&self.state); + continue; + } + state.idle.push(wake.clone()); + let mut deadline = Instant::now() + self.linger; + loop { + let left = deadline.saturating_duration_since(Instant::now()); + state = wake + .wait_timeout(state, left) + .unwrap_or_else(|e| e.into_inner()) + .0; + // Taken off the stack: a task was queued for this worker. + let Some(at) = state.idle.iter().position(|w| Arc::ptr_eq(w, &wake)) else { + state.coming -= 1; + break; + }; + if Instant::now() < deadline { + continue; + } + // A worker is on the stack only while the queue is empty (it + // goes idle when it finds no task, and each task queued takes + // one off), so leaving leaves no task without a worker. + if state.idle.len() > self.keep { + debug_assert!(state.tasks.is_empty()); + state.idle.remove(at); + state.workers -= 1; + tracing::debug!(workers = state.workers, "task pool: an idle worker leaves"); + return; + } + deadline = Instant::now() + self.linger; } - state = lock(&self.state); } } } @@ -1543,6 +1629,109 @@ mod tests { XTaskQueueCloseHandle(q); } + /// The workers `pool` has started that have not left. + fn workers(pool: &Pool) -> usize { + lock(&pool.state).workers + } + + /// Waits up to five seconds for `done`, and says whether it came. + fn within_seconds(done: impl Fn() -> bool) -> bool { + let start = std::time::Instant::now(); + while !done() && start.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(1)); + } + done() + } + + /// A burst of short callbacks (completions queued together, say) is run + /// by a few workers instead of a thread each. + #[test] + fn pool_workers_stay_few_in_a_burst_of_short_callbacks() { + static BURST: Pool = Pool::new(Duration::from_millis(200), 1); + static RAN: AtomicU32 = AtomicU32::new(0); + extern "system" fn ran(_: *mut c_void, _: bool) { + RAN.fetch_add(1, Ordering::SeqCst); + } + for _ in 0..256 { + BURST.submit(Task::new(std::ptr::null_mut(), ran)); + } + assert!(within_seconds(|| RAN.load(Ordering::SeqCst) == 256)); + let started = workers(&BURST); + assert!(started <= 32, "{started} workers for 256 short callbacks"); + } + + /// The workers a burst left idle leave once the pool's linger is over, + /// down to the ones it keeps, even while a trickle of short callbacks + /// keeps coming (the process queue's completions during play, say). + #[test] + fn pool_workers_left_idle_leave_under_a_trickle_of_callbacks() { + static TRICKLE: Pool = Pool::new(Duration::from_millis(200), 1); + static HELD: AtomicU32 = AtomicU32::new(0); + static HOLD: AtomicBool = AtomicBool::new(true); + static RAN: AtomicU32 = AtomicU32::new(0); + extern "system" fn held(_: *mut c_void, _: bool) { + HELD.fetch_add(1, Ordering::SeqCst); + while HOLD.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + } + extern "system" fn ran(_: *mut c_void, _: bool) { + RAN.fetch_add(1, Ordering::SeqCst); + } + // Sixteen callbacks that block until released take a worker each. + for _ in 0..16 { + TRICKLE.submit(Task::new(std::ptr::null_mut(), held)); + } + assert!(within_seconds(|| HELD.load(Ordering::SeqCst) == 16)); + assert_eq!(workers(&TRICKLE), 16); + HOLD.store(false, Ordering::SeqCst); + + // One short callback every 10 ms, for up to fifteen lingers. Two + // workers may stay a while longer: one that times out while another + // is running a callback is the only idle one, so it is kept. + let start = std::time::Instant::now(); + let mut sent = 0; + while workers(&TRICKLE) > 2 && start.elapsed() < Duration::from_secs(3) { + TRICKLE.submit(Task::new(std::ptr::null_mut(), ran)); + sent += 1; + std::thread::sleep(Duration::from_millis(10)); + } + assert!( + workers(&TRICKLE) <= 2, + "{} workers still there after {sent} callbacks 10 ms apart", + workers(&TRICKLE) + ); + assert!(within_seconds(|| RAN.load(Ordering::SeqCst) == sent)); + + // Once it is quiet, the one kept stays and still runs what comes. + assert!( + within_seconds(|| workers(&TRICKLE) == 1), + "{} workers still there", + workers(&TRICKLE) + ); + TRICKLE.submit(Task::new(std::ptr::null_mut(), ran)); + assert!(within_seconds(|| RAN.load(Ordering::SeqCst) == sent + 1)); + } + + /// Callbacks queued together that each wait for all of them to have + /// started still all run: a queued task always has a worker coming. + #[test] + fn pool_callbacks_queued_together_may_wait_for_each_other() { + static MEET: Pool = Pool::new(Duration::from_millis(200), 0); + static STARTED: AtomicU32 = AtomicU32::new(0); + static MET: AtomicU32 = AtomicU32::new(0); + extern "system" fn meet(_: *mut c_void, _: bool) { + STARTED.fetch_add(1, Ordering::SeqCst); + if within_seconds(|| STARTED.load(Ordering::SeqCst) == 8) { + MET.fetch_add(1, Ordering::SeqCst); + } + } + for _ in 0..8 { + MEET.submit(Task::new(std::ptr::null_mut(), meet)); + } + assert!(within_seconds(|| MET.load(Ordering::SeqCst) == 8)); + } + /// A dispatcher thread's loop, `while (XTaskQueueDispatch(queue, port, /// INFINITE));`, ends when its queue is terminated: nothing can be /// submitted to it any more, so nothing else would ever wake it. diff --git a/d3d12/crates/leonida-hle/src/modules/xmem.rs b/d3d12/crates/leonida-hle/src/modules/xmem.rs index 16e83c130f..1f6c064ac7 100644 --- a/d3d12/crates/leonida-hle/src/modules/xmem.rs +++ b/d3d12/crates/leonida-hle/src/modules/xmem.rs @@ -21,7 +21,8 @@ use windows_sys::Win32::System::Memory::{ MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, MEM_RESERVE_PLACEHOLDER, MEMORY_BASIC_INFORMATION, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile3, MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_COMMIT, - SEC_RESERVE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx, + SEC_RESERVE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualAllocEx, VirtualFree, + VirtualProtect, VirtualProtectEx, VirtualQueryEx, }; use windows_sys::Win32::System::ProcessStatus::{ K32GetPerformanceInfo, K32GetProcessMemoryInfo, PERFORMANCE_INFORMATION, @@ -101,15 +102,25 @@ pub extern "system" fn XMemVirtualAlloc( flags: u64, protect: u32, ) -> *mut c_void { + virtual_alloc(base, size, kind, flags, protect, 0, false) +} + +/// [`XMemVirtualAlloc`], a reservation of our choice also aligned to +/// `align` (a power of two; the host's 64 KiB and below go without saying). +/// +/// `ours`: a reservation the runtime makes for the title +/// ([`XMemAllocDefault`]'s blocks, the device's heaps), not one the title +/// asked for. It is left out of [`note_protection`], which says what the +/// title asks for, and a refusal of it is a warning: its caller falls back +/// to a heap, and the allocation may still succeed. +fn virtual_alloc(base: *mut c_void, size: usize, kind: u32, flags: u64, protect: u32, align: usize, ours: bool) -> *mut c_void { let (lowest, highest) = address_range(flags); + let pages = if kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M { 2 * MIB } else { 0 }; let mut requirements = MEM_ADDRESS_REQUIREMENTS { LowestStartingAddress: lowest as *mut c_void, HighestEndingAddress: highest as *mut c_void, - Alignment: if kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M { - 2 * MIB - } else { - 0 - }, + // (The host takes 0 or a multiple of its 64 KiB granularity.) + Alignment: if align > 64 << 10 { pages.max(align) } else { pages }, }; let asked = protect; let mut protect = match protect & HOST_PROTECTION { @@ -153,26 +164,31 @@ pub extern "system" fn XMemVirtualAlloc( kind |= MEM_WRITE_WATCH; } } + let parameters: *mut MEM_EXTENDED_PARAMETER = if constrained { + &raw mut parameter + } else { + std::ptr::null_mut() + }; // SAFETY: the title's own arguments, cleaned of console bits; the // parameter points at `requirements`, which outlives the call. - let at = unsafe { - VirtualAlloc2( - GetCurrentProcess(), - base, - size, - kind, - protect, - if constrained { - &mut parameter - } else { - std::ptr::null_mut() - }, - constrained.into(), - ) + let call = || unsafe { + VirtualAlloc2(GetCurrentProcess(), base, size, kind, protect, parameters, constrained.into()) + }; + // At an address of the title's: a release of its own there that the GPU + // side keeps for a heap opened in place is done first, if it can be + // (`leonida_gpu::title_memory_reserve`; else refused, as before), and + // pages it decommitted that the GPU side kept committed for such a heap + // are its again (`leonida_gpu::title_memory_alloc`). + let at = if constrained { + call() + } else { + leonida_gpu::title_memory_alloc(base as usize, size, kind, call) }; if at.is_null() { let error = std::io::Error::last_os_error(); - if kind & MEM_COMMIT != 0 { + if ours { + tracing::warn!(size, align, %error, "a reservation the runtime makes for the title refused: the memory comes from a heap"); + } else if kind & MEM_COMMIT != 0 { commit_refused(size, "virtual memory", error); } else { tracing::warn!( @@ -196,6 +212,10 @@ pub extern "system" fn XMemVirtualAlloc( if !at.is_null() && !placeholder { leonida_gpu::title_memory_allocated(at as usize, size); } + if !at.is_null() && kind & MEM_COMMIT != 0 { + let from = if base.is_null() { at as usize } else { base as usize }; + title_commit().add(at as usize & !(HOST_PAGE - 1), from.saturating_add(size).next_multiple_of(HOST_PAGE)); + } // Write-combined (the console's 0x400): memory the title's CPU writes and // does not read (`LEONIDA_WC_NO_BACK`; trustno1-coder/VIctory-NVIDIA // 50c15a1, GPL-3.0). @@ -213,7 +233,12 @@ pub extern "system" fn XMemVirtualAlloc( if !at.is_null() && constrained && kind & MEM_COMMIT == 0 && flags & ADDRESS_32BIT != 0 { LOW_RESERVATIONS.lock().unwrap_or_else(|e| e.into_inner()).push((at as usize, size)); } - note_protection(asked, kind, flags, at as usize, size); + if !at.is_null() && kind & MEM_RESERVE_PLACEHOLDER != 0 { + PLACEHOLDERS.lock().unwrap_or_else(|e| e.into_inner()).insert(at as usize, size); + } + if !ours { + note_protection(asked, kind, flags, at as usize, size); + } at } @@ -223,6 +248,8 @@ pub extern "system" fn XMemVirtualAlloc( /// each, with how much so far. (For placing it: memory the CPU reaches /// uncached or write-combined is memory it does not read.) fn note_protection(protect: u32, kind: u32, flags: u64, at: usize, size: usize) { + #[cfg(test)] + PROTECTIONS_NOTED.with(|n| n.set(n.get() + 1)); type Seen = std::collections::HashMap<(u32, u32, u64), (u64, usize)>; static SEEN: std::sync::Mutex<Option<Seen>> = std::sync::Mutex::new(None); let (n, bytes) = { @@ -239,6 +266,12 @@ fn note_protection(protect: u32, kind: u32, flags: u64, at: usize, size: usize) } } +#[cfg(test)] +thread_local! { + /// [`note_protection`]'s calls on this thread, for the tests. + static PROTECTIONS_NOTED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + /// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the /// same), then the XMem flags and tag. #[repr(C)] @@ -253,6 +286,13 @@ pub struct BasicInformation { // all of it is GPU-reachable here (the title's BVH builder, the // only caller, wants graphics memory); remember the flags of // `XMemVirtualAlloc` regions if a title tells CPU-only memory apart. +// +// What the host says is made what the title asked for where the GPU side +// does it later, for a heap it opened in place over the memory +// (`leonida_gpu::title_memory_as_asked`): a release it keeps reserved for +// the title is free memory, a protection that waits is made, a decommit +// it keeps committed and zeroed is reserved memory (not graphics memory). +// Of this process only: another's memory is the host's to tell. pub extern "system" fn XMemVirtualQuery( process: HANDLE, address: *const c_void, @@ -266,6 +306,9 @@ pub extern "system" fn XMemVirtualQuery( return 0; } let info = &mut *out; + if is_this_process(process) { + leonida_gpu::title_memory_as_asked(address as usize, &mut info.host); + } info.flags = if info.host.State == MEM_COMMIT { GRAPHICS } else { @@ -277,6 +320,14 @@ pub extern "system" fn XMemVirtualQuery( 1 } +/// Whether `process` names this process: its pseudo handle, or a handle of +/// it. +fn is_this_process(process: HANDLE) -> bool { + use windows_sys::Win32::System::Threading::{GetCurrentProcessId, GetProcessId}; + // SAFETY: plain queries; a handle that is no process's gives 0. + process as isize == -1 || unsafe { GetProcessId(process) == GetCurrentProcessId() } +} + // `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up // from 2), then the memory type, then bit 33: a 32-bit address. const ALIGNMENT_SHIFT: u64 = 24; @@ -349,7 +400,68 @@ pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) { } } +/// Blocks of [`XMemAllocDefault`] from this size or this alignment up get a +/// write-watched reservation of their own ([`watched_block`]). +const WATCHED_FROM: usize = 64 << 10; + +/// Whether a block of `size` bytes aligned to `align` is given a reservation +/// of its own ([`XMemAllocDefault`]) rather than a heap block. +/// +/// From 64 KiB the host's 4 KiB pages waste little of a block, its 64 KiB +/// alignment comes with the reservation, and the GPU side can ask the kernel +/// which pages of it were written. A block aligned to 64 KiB or more (the +/// executable's two constant `XMemAlloc` sites ask for 64 KiB, `0xf0814000`: +/// `docs/xmem_exe_calls.md`) costs a heap its alignment again in padding +/// ([`layout`]), more than the 4 KiB page a reservation commits for a small +/// one. +fn watched_block(size: usize, align: usize) -> bool { + size >= WATCHED_FROM || align >= WATCHED_FROM +} + +/// Whether [`watched_block`]s are made (`LEONIDA_XMEM_DEFAULT_WATCHED=0`: +/// every block from the heap, as before). +fn default_watched() -> bool { + static ON: LazyLock<bool> = LazyLock::new(|| std::env::var_os("LEONIDA_XMEM_DEFAULT_WATCHED").is_none_or(|v| v != "0")); + *ON +} + +/// The blocks [`XMemAllocDefault`] gave out as reservations of their own: +/// bytes asked for, by address. What [`XMemFreeDefault`] finds here it frees +/// as a reservation, anything else as a header-prefixed heap block; an +/// entry goes with its reservation ([`title_virtual_free`]), so it cannot +/// stand for a heap block given the same address later. +static WATCHED_BLOCKS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); + +fn watched_blocks() -> MutexGuard<'static, BTreeMap<usize, usize>> { + WATCHED_BLOCKS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// [`XMemAllocDefault`]'s blocks so far, count and bytes: from reservations +/// of their own, then from the heap. Said at the 1st, 2nd, 4th.. of each: +/// how much of the title's memory comes this way is not known otherwise. +static DEFAULT_BLOCKS: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +fn note_default_block(watched: bool, size: usize) { + let k = if watched { 0 } else { 2 }; + let n = DEFAULT_BLOCKS[k].fetch_add(1, Ordering::Relaxed) + 1; + let bytes = DEFAULT_BLOCKS[k + 1].fetch_add(size as u64, Ordering::Relaxed) + size as u64; + if n.is_power_of_two() { + let from = if watched { "write-watched reservations of their own" } else { "the heap" }; + tracing::info!("XMemAllocDefault: {n} blocks, {} MB in all, from {from}", bytes >> 20); + } +} + /// The system allocator behind [`XMemAlloc`]. +/// +/// A block of 64 KiB or aligned to 64 KiB is a reservation of its own +/// ([`watched_block`]; `LEONIDA_XMEM_DEFAULT_WATCHED=0`: not), made as +/// [`XMemVirtualAlloc`] makes the title's: write-watched, so a host copy of +/// it refreshes the pages the title wrote, not all of it (of a heap block +/// `leonida_gpu::watch` knows nothing, and its copies took it whole at every +/// refresh); below 2^40, where the console keeps title memory; and with no +/// padding for its alignment (a heap block aligned to 64 KiB cost 64 KiB +/// more). Committed resources come here when the title's hook passes them +/// on (`leonida_gpu::resource`, `Memory::for_resource`). pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_void { if attributes & ALLOC_32BIT != 0 { return XMemVirtualAlloc( @@ -363,16 +475,28 @@ pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_ let Some(layout) = layout(size, attributes) else { return std::ptr::null_mut(); }; + if size != 0 && default_watched() && watched_block(size, layout.align()) { + let at = virtual_alloc(std::ptr::null_mut(), size, MEM_RESERVE | MEM_COMMIT, GRAPHICS, PAGE_READWRITE, layout.align(), true); + if !at.is_null() { + watched_blocks().insert(at as usize, size); + note_default_block(true, size); + return at; + } + // (Refused, and said so: the heap may still have room.) + } // shortcut: the host heap's addresses lie above 2^40, unlike the // console's; nothing seen builds ray-tracing structures in this memory - // (the title uses its GPU heap). Sub-allocate from a - // reservation below 2^40 if one does. + // (the title uses its GPU heap), and no block from 64 KiB is here + // ([`watched_block`]). Sub-allocate from a reservation below 2^40 if + // one does. // SAFETY: the layout has a non-zero size. let block = unsafe { alloc(layout) }; if block.is_null() { tracing::warn!(size, "XMemAllocDefault: the host heap is out of memory"); return block.cast(); } + note_default_block(false, size); + HEAP_BLOCK_BYTES.fetch_add(size, Ordering::Relaxed); // SAFETY: the block holds the alignment (at least the header) and then // `size` bytes. unsafe { @@ -389,20 +513,27 @@ pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) { if address.is_null() { return; } + // (A reservation's base is 64 KiB-aligned: a heap block that is not + // needs no look at the table.) + let watched = attributes & ALLOC_32BIT == 0 + && (address as usize).is_multiple_of(64 << 10) + && watched_blocks().contains_key(&(address as usize)); // SAFETY: the address came from `XMemAlloc` with these attributes: a // whole reservation, or a header-prefixed block. unsafe { - if attributes & ALLOC_32BIT != 0 { - // A whole reservation: what the GPU side noted of it (guards, clean and absent - // blocks, views) goes first, as for the title's own `VirtualFree`, or it would be - // taken for true of the next memory at the address. (After ZigZagBoi1/ScarlettPort + if attributes & ALLOC_32BIT != 0 || watched { + // A whole reservation: `XMemVirtualAlloc` told the GPU side of + // this memory, so it is freed as the title's own `VirtualFree` + // frees: what the GPU side noted of it (guards, clean and absent + // blocks, views) goes first, or it would be taken for true of the + // next memory at the address. (After ZigZagBoi1/ScarlettPort // 745d6f3, as voidopcode/vilocity ed024d5 has it; GPL-3.0.) - leonida_gpu::title_memory_freed(address as usize, 0); - VirtualFree(address, 0, MEM_RELEASE); + title_virtual_free(address, 0, MEM_RELEASE); return; } let user = address.cast::<u8>(); let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read(); + HEAP_BLOCK_BYTES.fetch_sub(size - align, Ordering::Relaxed); dealloc( user.sub(align), Layout::from_size_align_unchecked(size, align), @@ -410,6 +541,22 @@ pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) { } } +/// Memory for a heap the title makes through the device (`CreateHeap`; +/// `leonida_gpu::resource::use_heap_memory`): `size` bytes aligned to +/// `align`, a reservation of its own made as [`XMemVirtualAlloc`] makes the +/// title's: write-watched, below 2^40, told to the GPU side, zeroed. On the +/// console a heap is title memory; from our allocator the GPU side knew +/// nothing of what the title wrote in it and took its copies whole. +pub(crate) fn heap_memory(size: usize, align: usize) -> *mut c_void { + virtual_alloc(std::ptr::null_mut(), size, MEM_RESERVE | MEM_COMMIT, GRAPHICS, PAGE_READWRITE, align, true) +} + +/// Frees what [`heap_memory`] gave, as the title's own `VirtualFree` frees +/// (the GPU side forgets what it noted there first). +pub(crate) fn heap_memory_free(at: *mut c_void) { + title_virtual_free(at, 0, MEM_RELEASE); +} + /// A retail console has no tools memory. pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL { 0 @@ -423,16 +570,107 @@ pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL { const PAGE: usize = 64 << 10; struct Section { - handle: HANDLE, + /// The host's section, its handle, and whether made with `SEC_COMMIT` + /// (no page of it needs a commit of its own): made with the + /// allocation, or, [`Section::lazy`], when a page of it is first + /// mapped or written ([`Section::handle`]). + host: std::sync::OnceLock<(usize, bool)>, + /// Made on first need, with `SEC_COMMIT` ([`lazy_commit`]). + lazy: bool, + /// Held while [`Section::handle`] makes the host's section: one + /// section, and one charge of commit, whichever thread comes first. + making: Mutex<()>, pages: usize, /// A view of the whole section, kept ([`Section::window`]); 0 if the /// host gave none. window: std::sync::OnceLock<usize>, - /// A bit per page: committed, as far as [`Section::window`] asked. + /// A bit per page: committed, as far as [`Section::window`] asked; in + /// a section made with `SEC_COMMIT`, handed out (mapped or written), + /// for [`arrange`]'s fresh pages. committed: Box<[std::sync::atomic::AtomicU64]>, } impl Section { + /// A section of `pages` pages; the host's made now unless `lazy` + /// ([`lazy_commit`]). `None` if the host refuses it. + fn new(pages: usize, lazy: bool) -> Option<Section> { + let section = Section { + host: std::sync::OnceLock::new(), + lazy, + making: Mutex::new(()), + pages, + window: std::sync::OnceLock::new(), + committed: (0..pages.div_ceil(64)).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), + }; + if !lazy { + // Under Wine a committed section is a sparse file, free until + // touched, and committing a reserved one page by page costs a + // wineserver request each that scans every range committed so + // far: commit it whole there. + let handle = host_section(pages * PAGE, on_wine()); + if handle.is_null() { + return None; + } + // For the GPU side's in-place census: only a committed section + // can be opened as a host heap. + leonida_gpu::title_memory_section(handle as usize, (pages * PAGE) as u64, on_wine()); + let _ = section.host.set((handle as usize, on_wine())); + } + Some(section) + } + + /// The host's section, made now if it is [`Section::lazy`] and not yet + /// made: with `SEC_COMMIT`, or, where the host will not charge that + /// much commit at once, with `SEC_RESERVE` (its pages then committed + /// as they are shown, as before). `None` if the host refuses both. + fn handle(&self) -> Option<HANDLE> { + if let Some(&(handle, _)) = self.host.get() { + return Some(handle as HANDLE); + } + let _making = self.making.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(&(handle, _)) = self.host.get() { + return Some(handle as HANDLE); + } + debug_assert!(self.lazy, "a section made with its allocation has its handle"); + let bytes = self.pages * PAGE; + let mut whole = true; + let mut handle = host_section(bytes, true); + if handle.is_null() { + let error = std::io::Error::last_os_error(); + static SAID: AtomicU64 = AtomicU64::new(0); + if SAID.fetch_add(1, Ordering::Relaxed) < 4 { + tracing::warn!( + bytes, + %error, + "a section of physical pages not made committed: made reserved, its pages committed as they are shown" + ); + } + whole = false; + handle = host_section(bytes, false); + if handle.is_null() { + commit_refused(bytes, "a section of physical pages", std::io::Error::last_os_error()); + return None; + } + } + // Told before any view of it is (`note_view`): the GPU side's + // census and `inplace::beside` look sections up by handle. + leonida_gpu::title_memory_section(handle as usize, bytes as u64, whole); + let _ = self.host.set((handle as usize, whole)); + Some(handle) + } + + /// The host's section's handle as a number, for the GPU side; 0 while + /// it is not made (no view shows the section then). + fn id(&self) -> usize { + self.host.get().map_or(0, |h| h.0) + } + + /// Made with `SEC_COMMIT`: every page is committed, none needs a + /// commit of its own. + fn whole(&self) -> bool { + self.host.get().is_some_and(|h| h.1) + } + /// Where bytes of `n` pages from page `index` on can be written, /// whether or not the pages are mapped anywhere, committed. /// @@ -451,9 +689,10 @@ impl Section { if !*ON || index + n > self.pages { return None; } + let handle = self.handle()?; let base = *self.window.get_or_init(|| { // SAFETY: the whole of a section we own. - unsafe { MapViewOfFile(self.handle, FILE_MAP_WRITE, 0, 0, self.pages * PAGE) }.Value as usize + unsafe { MapViewOfFile(handle, FILE_MAP_WRITE, 0, 0, self.pages * PAGE) }.Value as usize }); if base == 0 { return None; @@ -469,7 +708,7 @@ impl Section { if run == 0 { continue; // another worker committed it meanwhile } - if !commit(base + page * PAGE, run * PAGE) { + if !self.whole() && !commit(base + page * PAGE, run * PAGE) { return None; } for p in page..page + run { @@ -483,7 +722,9 @@ impl Section { impl Section { /// Commits the pages from `index` on that a view at `base` shows, unless - /// all of them are ([`lean`]): committed for one view is for all. + /// all of them are ([`lean`]): committed for one view is for all. In a + /// section made with `SEC_COMMIT` there is nothing to ask the host; the + /// pages are only noted handed out. fn commit_shown(&self, index: usize, base: usize, len: usize) -> bool { use std::sync::atomic::Ordering; let pages = index..(index + len / PAGE).min(self.pages); @@ -497,7 +738,7 @@ impl Section { if lean() && done() { return true; } - if !counted(Call::Commit, || commit(base, len)) { + if !self.whole() && !counted(Call::Commit, || commit(base, len)) { return false; } for p in pages { @@ -516,6 +757,9 @@ unsafe impl Sync for Section {} impl Drop for Section { fn drop(&mut self) { use windows_sys::Win32::System::Memory::UnmapViewOfFile; + let Some(&(handle, _)) = self.host.get() else { + return; // never made: nothing of the host's to let go + }; if let Some(&base) = self.window.get() && base != 0 { @@ -526,9 +770,9 @@ impl Drop for Section { }) }; } - leonida_gpu::title_memory_section_gone(self.handle as usize); + leonida_gpu::title_memory_section_gone(handle); // SAFETY: our handle; views keep the section alive on their own. - unsafe { CloseHandle(self.handle) }; + unsafe { CloseHandle(handle as HANDLE) }; } } @@ -563,10 +807,140 @@ impl Physical { } } +/// The page numbers the title can be given: [`FIRST_NUMBER`] to +/// [`END_NUMBER`]. +fn number_range() -> std::ops::Range<usize> { + #[cfg(test)] + if let Some((start, end)) = TEST_NUMBERS.get() { + return start..end; + } + FIRST_NUMBER..END_NUMBER +} + +#[cfg(test)] +thread_local! { + /// [`number_range`] for a test's thread only: numbers it took from the + /// counter and gave back, which no other thread takes (they draw from + /// the counter, far below [`END_NUMBER`]), so a space of a few numbers + /// stands for the title's 2^21 - 2^16. + static TEST_NUMBERS: std::cell::Cell<Option<(usize, usize)>> = const { std::cell::Cell::new(None) }; + /// Every host section made on a test's thread ([`host_section`]: with + /// its allocation, or a lazy one at its first page) fails, as + /// `CreateFileMappingW` does on a busy host (error 1450). + static TEST_NO_SECTION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + /// The title's pages by number. struct Pages { - next_page: usize, + numbers: Numbers, pages: HashMap<usize, Slice>, + spare: Spare, +} + +/// The first page number given out (0 stays unused; numbers are opaque to +/// titles). +const FIRST_NUMBER: usize = 0x10_0000; + +/// Past the last page number the title can keep: it keeps a number as 21 +/// bits of `number >> 4` ([`FRAMES`]), so every number must be below 2^25. +const END_NUMBER: usize = 1 << 25; + +/// Page numbers, given out from a counter and, once the counter reaches +/// [`END_NUMBER`], from those freed, lowest first. +/// +/// They were given out from the counter alone, never again, and the counter +/// passed 2^25 after (2^25 - 2^20) / 16 numbers of 64 KiB, 124 GiB of +/// allocations in a session, ever (the title frees pages and asks for them +/// again: four allocating calls and three freeing ones in +/// `docs/xmem_exe_calls.md`). Past it the title's 21 bits keep `number` as +/// `number - 2^25`: below [`FIRST_NUMBER`] (the next 4 GiB of allocations) +/// that is no page, and its mappings fail; above it, the number of a page +/// of another allocation, mapped in place of the title's own without a +/// word (`page_numbers_stay_in_the_titles_21_bits`). +/// +/// A number is only the key of [`Pages::pages`]: views, aliases and the GPU +/// side know a page by its section and index ([`Slice`]; the GPU side by the +/// section's handle and offset, `leonida_gpu::title_memory_view`), and the +/// GPU's page-mapping copies by the address the pool shows it at. Once +/// freed, nothing of the runtime's still names it; a DirectStorage request +/// that does finds whatever has the number then, as the console's DMA would +/// find whoever has the frame. Freed numbers wait as long as the counter +/// lasts, so in the first 124 GiB nothing changes: a stale number is still +/// "a physical page the title does not own (any more)". +/// +/// At most 2^21 - 2^16 numbers, so the freed ones are a bitmap of at most +/// 248 KiB, grown as the counter goes. +struct Numbers { + next: usize, + /// A bit per number below `next` that is freed and not given out again: + /// bit `(number - FIRST_NUMBER) / FRAMES`. + freed: Vec<u64>, + /// How many bits of `freed` are set. + spare: usize, + /// No word of `freed` below this one has a bit set. + lowest: usize, +} + +impl Numbers { + const fn new() -> Numbers { + Numbers { next: FIRST_NUMBER, freed: Vec::new(), spare: 0, lowest: 0 } + } + + /// `n` numbers in `range`, from the counter while it lasts, then freed + /// ones; `None` (and nothing taken) if fewer than `n` are left: more than + /// the range allows are live. The title's range is [`number_range`]: + /// every freed number is in it, so `spare` counts them all; a test's + /// narrower one counts its own. + fn take(&mut self, n: usize, range: std::ops::Range<usize>) -> Option<Vec<usize>> { + let fresh = if self.next < range.start { 0 } else { (range.end.saturating_sub(self.next) / FRAMES).min(n) }; + // Bits of `freed` in the range: [lo, hi). + let lo = range.start.saturating_sub(FIRST_NUMBER).div_ceil(FRAMES); + let hi = range.end.saturating_sub(FIRST_NUMBER) / FRAMES; + let mask = |w: usize| -> u64 { + let (from, to) = (lo.saturating_sub(w * 64).min(64), hi.saturating_sub(w * 64).min(64)); + if to <= from { 0 } else { (!0u64 >> (64 - (to - from))) << from } + }; + let whole = lo == 0 && hi >= self.freed.len() * 64; + let words = hi.div_ceil(64).min(self.freed.len()); + let left = if whole { + self.spare + } else { + (lo / 64..words).map(|w| (self.freed[w] & mask(w)).count_ones() as usize).sum() + }; + if n - fresh > left { + return None; + } + let mut out: Vec<usize> = (0..fresh).map(|k| self.next + k * FRAMES).collect(); + self.next += fresh * FRAMES; + let mut word = if lo == 0 { self.lowest } else { lo / 64 }; + while out.len() < n { + word = (word..words).find(|&w| self.freed[w] & mask(w) != 0)?; + if lo == 0 { + self.lowest = word; + } + let bit = (self.freed[word] & mask(word)).trailing_zeros() as usize; + self.freed[word] &= !(1 << bit); + self.spare -= 1; + out.push(FIRST_NUMBER + (word * 64 + bit) * FRAMES); + } + Some(out) + } + + /// `number`, which was given out, is free again. + fn give(&mut self, number: usize) { + if number < FIRST_NUMBER || number >= self.next || !number.is_multiple_of(FRAMES) { + return; + } + let k = (number - FIRST_NUMBER) / FRAMES; + if self.freed.len() <= k / 64 { + self.freed.resize(k / 64 + 1, 0); + } + if self.freed[k / 64] & 1 << (k % 64) == 0 { + self.freed[k / 64] |= 1 << (k % 64); + self.spare += 1; + self.lowest = self.lowest.min(k / 64); + } + } } /// Where the title sees its pages: [`Physical::views`] the other way. @@ -619,6 +993,13 @@ impl Shown { } } + /// Whether any view shows page `index` of `section` (an `Arc`'s + /// address, as the keys are). + fn shows(&self, section: usize, index: usize) -> bool { + self.pages.contains_key(&(section, index)) + || self.long.iter().any(|&(_, len, of, first)| of == section && (first..first + len / PAGE).contains(&index)) + } + /// Where the title sees the page at `slice`: addresses and bytes. fn at(&self, slice: &Slice) -> Vec<(usize, usize)> { let section = Arc::as_ptr(&slice.section) as usize; @@ -655,9 +1036,9 @@ fn physical() -> MutexGuard<'static, Physical> { /// where both are. static PAGES: LazyLock<RwLock<Pages>> = LazyLock::new(|| { RwLock::new(Pages { - // Page numbers are opaque to titles; 0 stays unused. - next_page: 0x10_0000, + numbers: Numbers::new(), pages: HashMap::new(), + spare: Spare::default(), }) }); @@ -670,8 +1051,9 @@ fn page_table_mut() -> RwLockWriteGuard<'static, Pages> { } /// The most pages of one section: `LEONIDA_SECTION_MB=<MiB>` makes an -/// allocation of sections of that many MiB at most (unset, 0 or not a -/// number: all its pages in one section, as before). +/// allocation of sections of that many MiB at most; unset, 16 +/// ([`DEFAULT_SECTION_MB`]); 0 or not a number: all its pages in one +/// section, as before. /// /// The title asks for its 6.1 GiB of pages in one call and maps them a /// 64 KiB page at a time: one section with views by the hundred thousand. @@ -685,8 +1067,16 @@ fn page_table_mut() -> RwLockWriteGuard<'static, Pages> { /// 3 us, 117 ms (as El1xr's notes give them); CGBJ, a kernel trace, 380 ms /// of every second, per call map 53 -> 3 us and unmap 99 -> 11 us in /// sections of 16 MiB (as OP-lite's notes give them). Here a page mapped -/// while the title streams costs 0.4 to 3 ms; whether this is why has not -/// been measured, so the switch is off until a run says. +/// while the title streams cost 0.4 to 3 ms. Measured here since +/// (docs/findings.md, the six-core PC's table, 2026-11-28; RTX 4060 Ti, one +/// run of 4 minutes walking and turning each, from one save): one section +/// an allocation 111.6 ms a frame on average, title memory held for +/// mapping changes 43.2 ms a frame, the mapping thread 46.2; 16 MiB 94.4, +/// 8.9 and 20.7; 2 MiB 91.7, 10.6 and 22.6. What it takes off is the +/// host's work per view of a section (the kernel's list of views, the +/// address-space lock), not the card's: nothing in it is the NVIDIA card's, +/// so it is the default for every card, and every way of starting the +/// runtime, not only the NVIDIA launcher, which set it. /// /// What goes by sections sees more of them, and nothing else changes: the /// bytes and every address are as before. A run of pages for a mapping or @@ -713,14 +1103,19 @@ fn section_pages() -> usize { return pages; } static PAGES: LazyLock<usize> = LazyLock::new(|| { - let pages = pages_per_section(std::env::var("LEONIDA_SECTION_MB").ok().as_deref()); + let asked = std::env::var("LEONIDA_SECTION_MB").ok(); + let pages = pages_per_section(asked.as_deref()); if pages == usize::MAX || on_wine() { return usize::MAX; } if port_on() { - tracing::warn!( - "LEONIDA_SECTION_MB is left out with LEONIDA_PORT_CONSTANTS=1: renderer port 1 needs its 32-bit heap in one section" - ); + // Warned of only when the user set it: unset is the default + // of 16 MiB, which port 1 leaves out as quietly. + if asked.is_some() { + tracing::warn!( + "LEONIDA_SECTION_MB is left out with LEONIDA_PORT_CONSTANTS=1: renderer port 1 needs its 32-bit heap in one section" + ); + } return usize::MAX; } tracing::info!( @@ -732,9 +1127,16 @@ fn section_pages() -> usize { *PAGES } +/// [`section_pages`] with `LEONIDA_SECTION_MB` unset, in MiB. +const DEFAULT_SECTION_MB: usize = 16; + /// [`section_pages`] for a value of `LEONIDA_SECTION_MB`: whole MiB. fn pages_per_section(mb: Option<&str>) -> usize { - match mb.and_then(|mb| mb.trim().parse::<usize>().ok()).map_or(0, |mb| mb.saturating_mul(MIB / PAGE)) { + let mb = match mb { + None => Some(DEFAULT_SECTION_MB), + Some(mb) => mb.trim().parse::<usize>().ok(), + }; + match mb.map_or(0, |mb| mb.saturating_mul(MIB / PAGE)) { 0 => usize::MAX, pages => pages, } @@ -746,6 +1148,413 @@ thread_local! { static TEST_SECTION_PAGES: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) }; } +/// Whether a section of physical pages of at most [`LAZY_SECTION_MOST`] +/// is made when one of its pages is first mapped or written, and made with +/// `SEC_COMMIT`: off unless `LEONIDA_SECTION_COMMIT=1` (off: every section +/// made with its allocation, reserved, each page committed on its own when +/// first shown; not under Wine, where sections are made committed whole +/// anyway). +/// +/// A reserved section has two costs. The host refuses to open it as a +/// heap (`OpenExistingHeapFromFileMapping`; `leonida_gpu`'s `inplace` +/// probe: "the pool must be made committed to be opened"), so no title +/// memory in the page pool can be read by the card in place except through +/// a view opened by address, which locks its pages. And every page's first +/// mapping, and every new run [`Section::window`] writes, asks the host to +/// commit it (`VirtualAlloc(MEM_COMMIT)` on a view), a call that waits for +/// the process's address-space lock, the mapping bottleneck of +/// [`lean`]: up to one call a page, some 100,000 for the title's 6.1 GiB +/// pool. A committed section asks for neither: its pages are committed with +/// it. +/// +/// Committed sections made with the allocation would charge all 6.1 GiB +/// of commit at once, which a busy host refuses (error 1450), the reason +/// they are reserved. Made at the first page of each that is shown, commit +/// is charged a section at a time, for the sections the title touches: +/// with sections of 16 MiB ([`section_pages`]), up to a section's worth +/// more than page by page for each section touched (16 MiB for one 64 KiB +/// page used), the same once the title has used all of a section's pages. +/// Where the host refuses the section's commit (the commit limit, 1455) +/// the section is made reserved and its pages committed as before +/// ([`Section::handle`]). That protects the pool only: once its sections +/// have taken commit early, what fails at the limit is everyone else's +/// (the host device's resources and upload buffers, the title's own +/// `MEM_COMMIT`), and runs of the title have had 1.8-2.0 GB of commit left +/// (findings.md, the `LEONIDA_SMALL_BUFFER_POOL` row of the six-core +/// switches). The whole of a section an allocation (`LEONIDA_SECTION_MB=0`, +/// renderer port 1) is larger than [`LAZY_SECTION_MOST`] and made reserved +/// either way. +/// +/// Off by default until a session with the title measures what it gains +/// and what it costs: the commit the pool charges over a session against +/// page by page, and the commit calls it saves the mapping thread (the +/// streaming log's `MAPPING` counts them, [`Call::Commit`]). Nothing places +/// title buffers in the sections it makes openable yet, so the heaps it +/// makes possible would be read by nothing today. +/// +/// Measured without the game (`a_committed_section_is_made_at_its_first_page`, +/// `a_committed_section_is_charged_when_first_touched`): no commit call for a +/// page mapped or written; commit charged by the section when it is first +/// touched and given back when its last page and view go; on the RX 7900 +/// XT the section behind a mapped page opens as a heap and the card reads +/// the title's bytes through a buffer placed in it, from the first address +/// and after the pages moved (`a_committed_section_opens_as_a_heap`; a +/// reserved section is refused with E_INVALIDARG there). Freed pages of +/// such a section are given out again before a section is made ([`Spare`]): +/// no section made and no commit charged for them, and those of a section +/// not made yet make it at their first touch +/// (`a_committed_sections_freed_pages_are_given_out_again_with_no_new_charge`). +fn lazy_commit() -> bool { + #[cfg(test)] + if let Some(on) = TEST_SECTION_COMMIT.get() { + return on; + } + static ON: LazyLock<bool> = + LazyLock::new(|| lazy_commit_asked(std::env::var_os("LEONIDA_SECTION_COMMIT").as_deref())); + *ON +} + +/// [`lazy_commit`] for a value of `LEONIDA_SECTION_COMMIT`: on for `1` +/// only. +fn lazy_commit_asked(value: Option<&std::ffi::OsStr>) -> bool { + value.is_some_and(|v| v == "1") +} + +/// The largest section [`lazy_commit`] makes committed: what one first +/// touch may charge. +const LAZY_SECTION_MOST: usize = 64 * MIB; + +/// A pagefile-backed section of `bytes`, made with `SEC_COMMIT` if +/// `committed`, else `SEC_RESERVE`; null if the host refuses. +fn host_section(bytes: usize, committed: bool) -> HANDLE { + #[cfg(test)] + if TEST_NO_SECTION.get() { + return std::ptr::null_mut(); + } + #[cfg(test)] + SECTIONS_MADE.set(SECTIONS_MADE.get() + 1); + // SAFETY: plain section creation. + unsafe { + CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE | if committed { SEC_COMMIT } else { SEC_RESERVE }, + (bytes as u64 >> 32) as u32, + bytes as u32, + std::ptr::null(), + ) + } +} + +/// Whether freed pages are given out again ([`Spare`]). +/// `LEONIDA_PHYSICAL_REUSE=0`: every allocation is sections of its own and +/// freed pages wait for the rest of their section, as before. +/// +/// Not with renderer port 1 (`LEONIDA_PORT_CONSTANTS=1`): [`arrange`] gives +/// numbers other slices of their section, any it finds without a number. +fn reuse() -> bool { + #[cfg(test)] + { + TEST_REUSE.get() && !port_on() + } + #[cfg(not(test))] + { + static ON: LazyLock<bool> = + LazyLock::new(|| std::env::var_os("LEONIDA_PHYSICAL_REUSE").is_none_or(|v| v != "0")); + *ON && !port_on() + } +} + +#[cfg(test)] +thread_local! { + /// A test's [`lazy_commit`], for its thread only. + static TEST_SECTION_COMMIT: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; + /// Host sections made on this thread ([`host_section`]). + static SECTIONS_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; + /// Commits asked of the host on this thread ([`commit`]). + static COMMITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; + /// [`reuse`] for a test's thread only (off: the other tests count on + /// fresh sections of their own). + static TEST_REUSE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// Pages the title freed, kept for the next allocations instead of new +/// sections ([`reuse`]). +/// +/// A section lives as long as any page of it has a number or a view, and the +/// host cannot decommit pages of a section (`VirtualFree(MEM_DECOMMIT)` on a +/// view of one fails with error 87; measured on Windows 11 26300, a section +/// of 256 MiB): what the title freed of a section it still uses part of +/// stayed committed, and resident, for as long as the rest, and every +/// allocation after it was new sections, committed anew as written. A title +/// that frees part of its pages and asks for pages again grew the commit by +/// what it freed, each time (`findings.md`: private bytes rising 30.0 -> +/// 31.4 GB in 11.5 minutes without a known cause; whether this is part of +/// it is a hypothesis). +/// +/// Now such pages wait here, by section, and an allocation takes them before +/// it makes a section: longest runs of consecutive pages first, so that a +/// mapping of them is few views and a DirectStorage write one window +/// ([`runs`], [`page_window`]). A page is taken only while no view shows it +/// ([`Shown`], read with [`PHYSICAL`] held, so every unmapping of it was told +/// to the GPU side, `leonida_gpu::title_memory_unmapping`, before it changes +/// hands): the GPU side knows a page only through its views and its +/// section's handle, never by number, and the section stays the same. One +/// written before is zeroed when given out again, as a new section's pages +/// read; one never written is left as it is (zero when first committed). +/// "Written" is the section's bits ([`Section::written`]), set only once the +/// host's section is made ([`Section::handle`]): a page of a section made at +/// its first page ([`lazy_commit`]) and not made yet has nothing to zero or +/// let go, and given out again it makes its section when first touched, as +/// a page that never waited does. +/// +/// Once the last page of a section with a number is freed, its pages leave +/// here and the section closes as before when its views go: the commit +/// returns to the host only then, with the handle. +/// +/// While they wait, freed pages that were written and that no view showed +/// when they were freed are let go by the host ([`discard`]). Pages still +/// shown are not: "pages still mapped stay readable through their views +/// until unmapped" ([`XMemFreePhysicalPages`]); nor later, when that view +/// goes (unmapping does not discard), so a page the title frees before it +/// unmaps it stays resident until given out again or its section closes. +#[derive(Default)] +struct Spare { + /// By section (its `Arc`'s address): those with a page with a number. + sections: HashMap<usize, Kept>, + /// Every run in a `Kept::freed`, longest first, then by section and + /// first page: (length, section, first page). [`Spare::take`] walks it + /// from the front and stops once nothing after can be given before what + /// it has, so an allocation looks at the pages of the runs it gives (and + /// of those views split), not at every page waiting (it still does when + /// fewer pages free of views wait than it asks for, since it gives them + /// all): before, it walked + /// all of them and sorted all their runs, under the page table lock, for + /// each allocation (`spare_take_looks_at_the_runs_it_gives`). + runs: std::collections::BTreeSet<(std::cmp::Reverse<usize>, usize, usize)>, + /// How many pages wait, in all `Kept::freed`: with none, an allocation + /// does not wait for [`PHYSICAL`] (mapping calls hold it 0.4 to 3 ms a + /// page while the title streams, [`section_pages`]), as before reuse. + waiting: usize, +} + +struct Kept { + section: Arc<Section>, + /// Its pages with a number, or on their way to one (taken here). + live: usize, + /// Its pages freed since and not given out again, as runs of + /// consecutive pages: first page -> length, no two touching. + freed: BTreeMap<usize, usize>, +} + +impl Kept { + /// How many pages wait in `freed`. + #[cfg(test)] + fn waiting(&self) -> usize { + self.freed.values().sum() + } +} + +impl Spare { + /// A section made for an allocation, all its pages with numbers. + fn made(&mut self, section: &Arc<Section>) { + let kept = Kept { section: section.clone(), live: section.pages, freed: Default::default() }; + self.sections.insert(Arc::as_ptr(section) as usize, kept); + } + + /// The page at `slice` lost its number: whether it is to wait here (its + /// section has other pages with numbers). Put it in with [`Spare::wait`]. + fn freed(&mut self, slice: &Slice) -> bool { + let key = Arc::as_ptr(&slice.section) as usize; + let Some(kept) = self.sections.get_mut(&key) else { + return false; + }; + kept.live -= 1; + if kept.live == 0 { + // The section's own pages are all freed: it goes when its views + // do, and those freed before with it. + for (&first, &len) in &kept.freed { + self.runs.remove(&(std::cmp::Reverse(len), key, first)); + self.waiting -= len; + } + self.sections.remove(&key); + return false; + } + true + } + + /// Pages [`Spare::freed`] kept, ready to be given out again. + fn wait(&mut self, slices: &[Slice]) { + use std::cmp::Reverse; + for slice in slices { + let key = Arc::as_ptr(&slice.section) as usize; + let Some(kept) = self.sections.get_mut(&key) else { + continue; + }; + let index = slice.index; + // Joined to the run that ends at it and to the one that starts + // after it, if any. + let (mut first, mut len) = (index, 1); + if let Some((&before, &k)) = kept.freed.range(..=index).next_back() { + if before + k > index { + continue; // waits already + } + if before + k == index { + kept.freed.remove(&before); + self.runs.remove(&(Reverse(k), key, before)); + (first, len) = (before, k + 1); + } + } + if let Some(k) = kept.freed.remove(&(index + 1)) { + self.runs.remove(&(Reverse(k), key, index + 1)); + len += k; + } + kept.freed.insert(first, len); + self.runs.insert((Reverse(len), key, first)); + self.waiting += 1; + } + } + + /// Up to `n` pages waiting that no view shows (`shown(section, index)`), + /// longest runs of consecutive pages first (then by section and first + /// page), each run in order. + fn take(&mut self, n: usize, shown: impl Fn(usize, usize) -> bool) -> Vec<Slice> { + use std::cmp::Reverse; + type Run = (Reverse<usize>, usize, usize); + // The runs of pages free to go found so far that are given, ordered + // as `runs`: the fewest first ones that hold `n` pages (the last + // maybe given in part), or all if they hold fewer; and their pages. + let mut given: std::collections::BTreeSet<Run> = Default::default(); + let mut found = 0; + let keep = |given: &mut std::collections::BTreeSet<Run>, found: &mut usize, run: Run| { + given.insert(run); + *found += run.0.0; + // Those past the first that hold `n` pages are not given, now or + // later: what is found later only goes before them. + while let Some(&last) = given.last() + && *found - last.0.0 >= n + { + given.pop_last(); + *found -= last.0.0; + } + }; + for &(Reverse(len), key, first) in &self.runs { + // Views split a run into runs no longer than it: once one is + // shorter than the last given, or as long and after it, neither + // it nor any after it goes before what is given. + if found >= n + && let Some(&(Reverse(least), at, from)) = given.last() + && (len < least || len == least && (key, first) > (at, from)) + { + break; + } + let mut run: Option<(usize, usize)> = None; + for index in first..first + len { + if !shown(key, index) { + run = Some(run.map_or((index, 1), |(from, k)| (from, k + 1))); + } else if let Some((from, k)) = run.take() { + keep(&mut given, &mut found, (Reverse(k), key, from)); + } + } + if let Some((from, k)) = run { + keep(&mut given, &mut found, (Reverse(k), key, from)); + } + } + let mut out: Vec<Slice> = Vec::with_capacity(n.min(found)); + for (Reverse(len), key, first) in given { + let Some(kept) = self.sections.get_mut(&key) else { + continue; + }; + let k = len.min(n - out.len()); + // Out of the waiting run that holds them: what is left of it + // either side waits on. + let (&at, &whole) = kept.freed.range(..=first).next_back().expect("a run found waits"); + kept.freed.remove(&at); + self.runs.remove(&(Reverse(whole), key, at)); + for (from, left) in [(at, first - at), (first + k, at + whole - first - k)] { + if left != 0 { + kept.freed.insert(from, left); + self.runs.insert((Reverse(left), key, from)); + } + } + out.extend((first..first + k).map(|index| Slice { section: kept.section.clone(), index })); + kept.live += k; + self.waiting -= k; + } + out + } + + /// Pages [`Spare::take`] gave and nobody got (the allocation failed). + fn put_back(&mut self, slices: &[Slice]) { + for slice in slices { + if self.freed(slice) { + self.wait(std::slice::from_ref(slice)); + } + } + } +} + +impl Section { + fn written(&self, page: usize) -> bool { + self.committed[page / 64].load(Ordering::Acquire) >> (page % 64) & 1 != 0 + } + + /// Runs `f` on the bytes of each run of written pages among `slices` (in + /// order): through [`Section::window`], or a view of our own if there is + /// none. + fn each_written(slices: &[Slice], mut f: impl FnMut(*mut u8, usize)) { + let mut i = 0; + while i < slices.len() { + let first = &slices[i]; + let run = 1 + slices[i + 1..] + .iter() + .zip(1..) + .take_while(|&(s, k)| Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + k) + .count(); + let mut page = first.index; + while page < first.index + run { + if !first.section.written(page) { + page += 1; + continue; + } + let len = (page..first.index + run).take_while(|&p| first.section.written(p)).count(); + if let Some(at) = first.section.window(page, len) { + f(at as *mut u8, len * PAGE); + } else if let Some(mut view) = View::map(&Slice { section: first.section.clone(), index: page }, len) { + f(view.bytes().as_mut_ptr(), len * PAGE); + } + page += len; + } + i += run; + } + } +} + +/// Whether freed pages that wait for another allocation ([`Spare`]), those +/// no view showed when freed, are given back to the host's memory while +/// they wait, with +/// `DiscardVirtualMemory` (`LEONIDA_PHYSICAL_DISCARD=0`: kept resident until +/// given out again or their section closes). +/// +/// Measured on this PC (Windows 11 26300, release build, a section of 256 +/// MiB committed and written through a view): `DiscardVirtualMemory` took +/// all 65,536 of its 4 KiB pages out of the working set, read back as zeros +/// after, and left the commit as it was until the section closed; it cost +/// 70-74 ms, about 18 us a 64 KiB page, and zeroing the pages after it +/// 71-77 ms (they come back as new pages) against 10 ms while resident. +/// `MEM_RESET` cost 8 ms and zeroing after it 55-57 ms, but the pages stayed +/// in the working set; `MEM_DECOMMIT` fails on a view of a section (error +/// 87). An unmapping and a mapping, which a page goes through before its +/// free and after its allocation, cost 60 to 300 us a page +/// (`leonida_gpu`'s `queue::alias_behind`), 0.4 to 3 ms while the title +/// streams ([`section_pages`]): the 18 us of each side is the smaller part. +/// Not under Wine, whose sections are sparse files. +fn discard() -> bool { + static ON: LazyLock<bool> = + LazyLock::new(|| std::env::var_os("LEONIDA_PHYSICAL_DISCARD").is_none_or(|v| v != "0") && !on_wine()); + *ON +} + /// `count` is in and out (pages wanted, pages given); all or nothing here. pub extern "system" fn XMemAllocatePhysicalPages( flags: u64, @@ -760,79 +1569,86 @@ pub extern "system" fn XMemAllocatePhysicalPages( if n.checked_mul(PAGE).is_none_or(|size| size == 0) { return 0; } - // Pagefile-backed sections of `n` pages in all ([`section_pages`] each - // at most), their pages committed when first mapped or written - // (`commit`): the title asks for 6.1 GiB at once, which a busy host - // often cannot commit (error 1450). - let per = section_pages().clamp(1, n); - let mut sections: Vec<Arc<Section>> = Vec::with_capacity(n.div_ceil(per)); - for first in (0..n).step_by(per) { - let here = per.min(n - first); - let size = here * PAGE; - // SAFETY: plain section creation. - let handle = unsafe { - CreateFileMappingW( - INVALID_HANDLE_VALUE, - std::ptr::null(), - // Under Wine a committed section is a sparse file, free until - // touched, and committing a reserved one page by page costs a - // wineserver request each that scans every range committed so - // far: commit it whole there. - PAGE_READWRITE | if on_wine() { SEC_COMMIT } else { SEC_RESERVE }, - (size as u64 >> 32) as u32, - size as u32, - std::ptr::null(), - ) + // The numbers first: with none left, no section is made for nothing. + // Then the pages freed before ([`Spare`]), with the views held still. + let (numbers, reused) = { + // PHYSICAL only if pages wait: what waits after the look stays for + // the next allocation, and nothing is taken without it. + let physical = (reuse() && page_table().spare.waiting != 0).then(physical); + let mut table = page_table_mut(); + let Some(numbers) = table.numbers.take(n, number_range()) else { + drop((table, physical)); + tracing::warn!(n, "XMemAllocatePhysicalPages failed: no page numbers left that the title can keep"); + // SAFETY: checked non-null. + unsafe { count.write(0) }; + return 0; }; - if handle.is_null() { + let reused = if physical.is_some() && table.spare.waiting != 0 { + let shown = SHOWN.read().unwrap_or_else(|e| e.into_inner()); + table.spare.take(n, |section, index| shown.shows(section, index)) + } else { + Vec::new() + }; + (numbers, reused) + }; + let fresh = n - reused.len(); + // Pagefile-backed sections of the other pages ([`section_pages`] each + // at most). Made reserved, their pages committed when first mapped or + // written (`commit`): the title asks for 6.1 GiB at once, which a busy + // host often cannot commit (error 1450). Or, small ones with + // `LEONIDA_SECTION_COMMIT=1` ([`lazy_commit`]), made committed when a + // page of theirs is first mapped or written. + let per = section_pages().clamp(1, fresh.max(1)); + let mut sections: Vec<Arc<Section>> = Vec::with_capacity(fresh.div_ceil(per)); + for first in (0..fresh).step_by(per) { + let here = per.min(fresh - first); + let lazy = lazy_commit() && !on_wine() && here * PAGE <= LAZY_SECTION_MOST; + let Some(section) = Section::new(here, lazy) else { // (Read before the sections made so far close, with `sections`.) let error = std::io::Error::last_os_error(); tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed"); + let mut table = page_table_mut(); + numbers.iter().for_each(|&number| table.numbers.give(number)); + table.spare.put_back(&reused); + drop(table); // SAFETY: checked non-null. unsafe { count.write(0) }; return 0; - } - sections.push(Arc::new(Section { - handle, - pages: here, - window: std::sync::OnceLock::new(), - committed: (0..here.div_ceil(64)).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(), - })); + }; + sections.push(Arc::new(section)); } tracing::debug!( n, + reused = reused.len(), sections = sections.len(), flags = format_args!("{flags:#x}"), "XMemAllocatePhysicalPages" ); - // For the GPU side's in-place census: only a committed section can be - // opened as a host heap. - for section in §ions { - leonida_gpu::title_memory_section(section.handle as usize, (section.pages * PAGE) as u64, on_wine()); - } + // Pages given out again read as new ones do. Theirs alone: no view shows + // them and the title has not seen their numbers yet. + Section::each_written(&reused, |at, len| { + // SAFETY: committed bytes of a view of the section, nobody else's. + unsafe { std::ptr::write_bytes(at, 0, len) } + }); let mut table = page_table_mut(); - let first = table.next_page; - table.next_page += n * FRAMES; - for index in 0..n { - let slice = Slice { - section: sections[index / per].clone(), - index: index % per, - }; - table.pages.insert(first + index * FRAMES, slice); + if reuse() { + sections.iter().for_each(|section| table.spare.made(section)); + } + let made = (0..fresh).map(|index| Slice { section: sections[index / per].clone(), index: index % per }); + for (&number, slice) in numbers.iter().zip(reused.into_iter().chain(made)) { + table.pages.insert(number, slice); } // Title memory is touched without our locks: a fault there may wait for // a mapping call, which takes them. drop(table); - for index in 0..n { - // SAFETY: the title passes room for `n` page numbers. - unsafe { pages.add(index).write(first + index * FRAMES) }; - } + // SAFETY: the title passes room for `n` page numbers. + unsafe { std::ptr::copy_nonoverlapping(numbers.as_ptr(), pages, n) }; 1 } /// Page numbers count 4 KiB frames, so a 64 KiB page's is a multiple of /// 16: the title keeps them as 21-bit `number >> 4` and rebuilds -/// them with `<< 4` (128 GiB of pages at most). +/// them with `<< 4` (128 GiB of pages at most; [`Numbers`]). const FRAMES: usize = PAGE >> 12; /// Pages still mapped stay readable through their views until unmapped. @@ -844,8 +1660,47 @@ pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> B let numbers = unsafe { std::slice::from_raw_parts(pages, n) }.to_vec(); let mut table = page_table_mut(); // Dropped without the lock: the last page of a section unmaps its window. - let gone: Vec<Slice> = numbers.iter().filter_map(|number| table.pages.remove(number)).collect(); + let mut gone: Vec<Slice> = Vec::with_capacity(numbers.len()); + // Those to wait for another allocation ([`Spare`]). + let mut kept: Vec<Slice> = Vec::new(); + for &number in &numbers { + if let Some(slice) = table.pages.remove(&number) { + table.numbers.give(number); + if table.spare.freed(&slice) { + kept.push(slice.clone()); + } + gone.push(slice); + } + } drop(table); + if kept.is_empty() { + return 1; + } + // Let go by the host before they can be given out again (so not under + // the lock that DirectStorage looks pages up with): those no view shows. + if discard() { + kept.sort_unstable_by_key(|s| (Arc::as_ptr(&s.section) as usize, s.index)); + let unseen: Vec<Slice> = { + // With PHYSICAL held, as `Spare::take` reads it: a mapping call + // takes a view out of SHOWN and notes again what stays of it + // only after its system calls ([`unmap`], [`change`]), under + // PHYSICAL, so read between the two SHOWN says no view shows a + // page one still does, and its bytes went (zeros through the + // title's view; `a_free_keeps_a_page_a_mapping_call_puts_back`). + // Past this no view can show them again: they have no number and + // are not in `Spare` yet, so the discard runs without locks. + let _physical = physical(); + let shown = SHOWN.read().unwrap_or_else(|e| e.into_inner()); + kept.iter().filter(|s| !shown.shows(Arc::as_ptr(&s.section) as usize, s.index)).cloned().collect() + }; + Section::each_written(&unseen, |at, len| { + use windows_sys::Win32::System::Memory::DiscardVirtualMemory; + // SAFETY: freed pages of a view of ours that no view of the + // title's shows; what they hold is nobody's any more. + unsafe { DiscardVirtualMemory(at.cast(), len) }; + }); + } + page_table_mut().spare.wait(&kept); drop(gone); 1 } @@ -862,10 +1717,11 @@ impl View { fn map(slice: &Slice, n: usize) -> Option<View> { use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile}; let (offset, len) = ((slice.index * PAGE) as u64, n * PAGE); + let handle = slice.section.handle()?; // SAFETY: slices of a section we own; the view is ours until dropped. let at = unsafe { MapViewOfFile( - slice.section.handle, + handle, FILE_MAP_WRITE, (offset >> 32) as u32, offset as u32, @@ -877,10 +1733,16 @@ impl View { return None; } let view = View { at, len }; - if !commit(at.Value as usize, len) { + if !slice.section.whole() && !commit(at.Value as usize, len) { tracing::warn!(error = %std::io::Error::last_os_error(), n, "physical pages not committed for a write"); return None; } + // Committed, and written next: said in the section's bits as every + // other commit is (what is given out again is zeroed by them, + // [`Spare`]; [`arrange`] moves only pages without one). + for p in slice.index..(slice.index + n).min(slice.section.pages) { + slice.section.committed[p / 64].fetch_or(1 << (p % 64), Ordering::AcqRel); + } Some(view) } @@ -1209,6 +2071,16 @@ fn port_on() -> bool { *ON } +/// The title's reservations the host made as placeholders, as the title +/// sees them: bytes by base. The runtime splits them as it maps and unmaps +/// 64 KiB pages (`change`, `unmap`), and each piece is then an allocation +/// of its own on the host, so the title's release of the base would take +/// the first piece only: [`title_virtual_free`] joins them first. The +/// title's own splits and joins (through the same call) change what it +/// sees, and so these; a join never reaches past what the title sees as +/// one reservation. +static PLACEHOLDERS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); + /// The title's reservations of 64 KiB pages for 32-bit graphics memory: /// base and bytes (one, of 185 MB, in Grand Theft Auto VI). static LOW_RESERVATIONS: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new()); @@ -1899,7 +2771,7 @@ fn change(physical: &mut Physical, mut ops: Vec<Op>) -> bool { // As in `map`. shown_mut().note(op.at, PAGE, &slice); leonida_gpu::title_memory_remapped(op.at, PAGE); - leonida_gpu::title_memory_view(op.at, PAGE, slice.section.handle as usize, (slice.index * PAGE) as u64); + leonida_gpu::title_memory_view(op.at, PAGE, slice.section.id(), (slice.index * PAGE) as u64); physical.views.insert(op.at, (PAGE, slice)); } None if op.had && done => { @@ -2094,7 +2966,7 @@ fn note_view(physical: &mut Physical, base: usize, len: usize, slice: Slice) { // New contents, read-write: the GPU side's copies no longer guard it. leonida_gpu::title_memory_remapped(base, len); // What the range shows now, for the GPU side's in-place census. - leonida_gpu::title_memory_view(base, len, slice.section.handle as usize, (slice.index * PAGE) as u64); + leonida_gpu::title_memory_view(base, len, slice.section.id(), (slice.index * PAGE) as u64); physical.views.insert(base, (len, slice)); } @@ -2115,11 +2987,14 @@ fn split(base: usize, len: usize) { /// long already; `loud`: a refusal is said (not where the caller tries /// another way). fn show(base: usize, len: usize, slice: &Slice, own: bool, loud: bool) -> bool { + let Some(handle) = slice.section.handle() else { + return false; + }; let map_view = || { // SAFETY: maps the section over a placeholder; acts only on one. counted(Call::Map, || unsafe { MapViewOfFile3( - slice.section.handle, + handle, GetCurrentProcess(), base as *const c_void, (slice.index * PAGE) as u64, @@ -2160,6 +3035,8 @@ fn commit(base: usize, len: usize) -> bool { if on_wine() { return true; // sections are committed whole there } + #[cfg(test)] + COMMITS.set(COMMITS.get() + 1); // SAFETY: `[base, base + len)` is a view of a reserved section. if !unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null() { return true; @@ -2289,15 +3166,127 @@ pub struct WorkingSet { pub kernel_pool_limit: u32, } -/// The title's budget and our process's commit as what it uses. No tools -/// memory: a retail console. -// shortcut: all fields are filled whatever the flags ask for, and use is -// not split by bandwidth class (GPU-optimal use reads 0); track -// allocations per class if a title budgets from that field. -pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut WorkingSet) -> BOOL { - if out.is_null() { - return 0; - } +/// The host's page, the unit it commits in. +const HOST_PAGE: usize = 4096; + +/// Private memory committed for the title through xmem ([`virtual_alloc`]: +/// its `XMemVirtualAlloc` calls, [`XMemAllocDefault`]'s reservations, the +/// device's heaps), as disjoint ranges `start -> end` of whole host pages, +/// and their bytes. A commit adds its pages, a decommit or release through +/// [`title_virtual_free`] takes them away; a range given twice counts once. +struct TitleCommit { + ranges: BTreeMap<usize, usize>, + bytes: usize, +} + +impl TitleCommit { + const fn new() -> TitleCommit { + TitleCommit { ranges: BTreeMap::new(), bytes: 0 } + } + + /// The ranges that meet or touch `[at, end]`, last first. + fn touching(&self, at: usize, end: usize) -> Vec<(usize, usize)> { + self.ranges.range(..=end).rev().take_while(|&(_, &e)| e >= at).map(|(&s, &e)| (s, e)).collect() + } + + fn add(&mut self, mut at: usize, mut end: usize) { + if at >= end { + return; + } + for (s, e) in self.touching(at, end) { + self.ranges.remove(&s); + self.bytes -= e - s; + (at, end) = (at.min(s), end.max(e)); + } + self.ranges.insert(at, end); + self.bytes += end - at; + } + + /// Takes `[at, end)` away; returns the ranges that were counted in it, + /// for [`TitleCommit::add`] to put back. + fn remove(&mut self, at: usize, end: usize) -> Vec<(usize, usize)> { + let mut taken = Vec::new(); + if at >= end { + return taken; + } + for (s, e) in self.touching(at, end) { + if e == at || s == end { + continue; + } + self.ranges.remove(&s); + self.bytes -= e - s; + taken.push((s.max(at), e.min(end))); + for (from, to) in [(s, at), (end, e)] { + if from < to { + self.ranges.insert(from, to); + self.bytes += to - from; + } + } + } + taken + } + + /// The bytes of `[at, end)` counted. + #[cfg(test)] + fn within(&self, at: usize, end: usize) -> usize { + self.touching(at, end).into_iter().map(|(s, e)| e.min(end).saturating_sub(s.max(at))).sum() + } +} + +static TITLE_COMMIT: Mutex<TitleCommit> = Mutex::new(TitleCommit::new()); + +fn title_commit() -> MutexGuard<'static, TitleCommit> { + TITLE_COMMIT.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The bytes of [`XMemAllocDefault`]'s heap blocks the title holds. +static HEAP_BLOCK_BYTES: AtomicUsize = AtomicUsize::new(0); + +/// What the title uses, as the console counts it: the memory it was given. +/// Its private commit through xmem ([`TitleCommit`]), its physical pages +/// (64 KiB each from allocation to free, mapped or not: on the console they +/// are its memory from `XMemAllocatePhysicalPages` on, though here a page +/// is committed only when first mapped or written, or with its whole +/// section ([`lazy_commit`]); a freed page waiting to be given out again, +/// [`Spare`], is no longer the title's) and [`XMemAllocDefault`]'s heap +/// blocks. +/// +/// shortcut: what the title takes from the host itself is not counted (its +/// image, its threads' stacks, its own heap through kernel32, which no shim +/// of ours sees): the figure is low by that much, where the process's commit +/// was high by the whole runtime. +fn title_used() -> usize { + let commit = title_commit().bytes; + commit + page_table().pages.len() * PAGE + HEAP_BLOCK_BYTES.load(Ordering::Relaxed) +} + +/// Whether the title is told its own use ([`title_used`]; +/// `LEONIDA_WS_TITLE=0`: the process's commit, as before). +fn ws_title() -> bool { + static ON: LazyLock<bool> = LazyLock::new(|| std::env::var_os("LEONIDA_WS_TITLE").is_none_or(|v| v != "0")); + *ON +} + +/// The title's budget and what it uses of it ([`title_used`]). No tools +/// memory: a retail console. +/// +/// It was our process's commit: the runtime's memory, the host copies of +/// title memory and the driver's included, 27 GB in run 60's gameplay +/// against a limit of 13.5 GB. A title that budgets its streaming from these +/// two figures believes it is twice over its limit, and may let go and +/// stream again what it would keep on the console. Whether it does is not +/// measured; what streaming costs here is (`d3d12/docs/findings.md`, +/// "Frame-rate switches measured on a six-core PC": 850 to 1,600 pages +/// mapped a second with the camera idle, which may or may not be what the +/// console would stream at rest). The console counts what the title was given, nothing of a +/// runtime it does not have, so that is what it is told now. +// shortcut: all fields are filled whatever the flags ask for, and use is +// not split by bandwidth class (GPU-optimal use reads 0); track +// allocations per class if a title budgets from that field. +pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut WorkingSet) -> BOOL { + if out.is_null() { + return 0; + } let mut counters = PROCESS_MEMORY_COUNTERS { cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, ..Default::default() @@ -2305,20 +3294,15 @@ pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut Workin // SAFETY: our own process and a sized structure. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) }; let (gpu_optimal, standard) = leonida_gpu::console::current().title_memory(); + let own = title_used(); let stats = WorkingSet { title_limit: gpu_optimal + standard - TRANSFERRED.load(Ordering::Relaxed), - title_used: counters.PagefileUsage, + title_used: if ws_title() { own } else { counters.PagefileUsage }, gpu_optimal_limit: gpu_optimal, ..Default::default() }; // What the title is told, logged at the first asking and at every - // 1,024th: "used" is all the process has committed, the layer's own - // memory and the card's included (27 GB in run 60's gameplay against a - // limit of 13.5 GB). A title that budgets its streaming from these two - // figures believes it is far over its limit. - // shortcut: the figure is not yet the title's own memory alone (its - // heaps and the pages it mapped); count those if this line shows the - // title asking. + // 1,024th, with both figures for comparing runs. static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let asked = ASKED.fetch_add(1, Ordering::Relaxed); if asked.is_multiple_of(1024) { @@ -2327,7 +3311,9 @@ pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut Workin which = _which, limit_mb = stats.title_limit >> 20, used_mb = stats.title_used >> 20, - "the title asks how much memory it uses" + title_mb = own >> 20, + process_mb = counters.PagefileUsage >> 20, + "the title asks how much memory it uses (LEONIDA_WS_TITLE=0: the process's commit)" ); } // SAFETY: checked non-null; the title passes room for the structure. @@ -2356,38 +3342,341 @@ pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL { moved.into() } -/// The title's own `VirtualFree`. What the GPU side noted of the memory goes -/// first: the address may be other memory's the moment it is free. +/// The title's own `VirtualFree`, through the GPU side's +/// (`leonida_gpu::title_memory_free`): what it noted of the memory goes +/// first, as the address may be other memory's the moment it is free. +/// +/// Memory the GPU side opened as a heap of its own (`LEONIDA_INPLACE`) is +/// let go there first, but the heap stands until nothing can use it any +/// more, and while it does the host refuses the free with error 87: the +/// GPU side then takes the free over and does it once the heap is gone, +/// and the title is told it is done, as the console would. extern "system" fn title_virtual_free(address: *mut c_void, size: usize, kind: u32) -> BOOL { const MEM_COALESCE_PLACEHOLDERS: u32 = 1; // Splitting and joining placeholders changes nothing they show. - if kind & (MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS) == 0 { - leonida_gpu::title_memory_freed(address as usize, size); + let freeing = kind & (MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS) == 0; + #[cfg(test)] + if freeing { + TOLD_FREED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(address as usize); + } + // A placeholder reservation the runtime split is one again, for the + // release to take all of it (and the GPU side to hear of all of it). + if freeing && kind & MEM_RELEASE != 0 && size == 0 { + join_placeholders(address as usize); + } + // What is noted of placeholders goes with what the host releases. + let released = (freeing && kind & MEM_RELEASE != 0).then(|| allocation_end(address as usize)).flatten(); + // What of the title's commit this takes, once the title is told it is + // done ([`TITLE_COMMIT`]): a release takes the allocation; a decommit + // its pages, or with no size the allocation's. + const MEM_DECOMMIT: u32 = 0x4000; + let at = address as usize; + let uncommits = match released { + Some(end) => Some((at, end)), + None if freeing && kind & MEM_DECOMMIT != 0 && size == 0 => allocation_end(at).map(|end| (at, end)), + None if freeing && kind & MEM_DECOMMIT != 0 => Some((at & !(HOST_PAGE - 1), at.saturating_add(size).next_multiple_of(HOST_PAGE))), + None => None, + }; + let block = released.is_some() && at.is_multiple_of(64 << 10); + // Both forgotten before the host's free, and no lock held over it (a + // decommit of a large range takes milliseconds, and every commit and + // `XMemGetWorkingSetStatistics` would wait behind it): the address is + // not given again before the free succeeds, so memory given there after + // it is noted after this, not lost. Put back if the host refuses and the + // GPU side does not take the free over. + let block_size = block.then(|| watched_blocks().remove(&at)).flatten(); + let uncommitted = uncommits.map(|(at, end)| title_commit().remove(at, end)).unwrap_or_default(); + let done = leonida_gpu::title_memory_free(address as usize, size, kind, || { + #[cfg(test)] + note_locks_at_free(); + // SAFETY: the title's own arguments. + let freed = unsafe { VirtualFree(address, size, kind) }; + if freed != 0 { + if let Some(end) = released { + reservation_gone(address as usize, end); + } else if kind & MEM_RELEASE != 0 && kind & MEM_PRESERVE_PLACEHOLDER != 0 { + placeholder_split(address as usize, size); + } else if kind & MEM_RELEASE != 0 && kind & MEM_COALESCE_PLACEHOLDERS != 0 { + placeholders_joined(address as usize, size); + } + } + freed + }); + // Refused, and not taken over by the GPU side (a heap of its standing + // there): the memory is still the title's. + if done == 0 { + if let Some(bytes) = block_size { + watched_blocks().insert(at, bytes); + } + if !uncommitted.is_empty() { + let mut commit = title_commit(); + for (from, to) in uncommitted { + commit.add(from, to); + } + } } + done +} + +#[cfg(test)] +thread_local! { + /// Whether, at the host's free in [`title_virtual_free`], this thread + /// held neither [`WATCHED_BLOCKS`]' lock nor [`TITLE_COMMIT`]'s (for + /// the tests; a lock another test's thread holds for a moment is tried + /// again). + static UNLOCKED_AT_FREE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +fn note_locks_at_free() { + use std::sync::TryLockError::WouldBlock; + let free = |busy: &dyn Fn() -> bool| { + (0..2000).any(|_| { + let b = busy(); + if b { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + !b + }) + }; + let unlocked = free(&|| matches!(WATCHED_BLOCKS.try_lock(), Err(WouldBlock))) && free(&|| matches!(TITLE_COMMIT.try_lock(), Err(WouldBlock))); + UNLOCKED_AT_FREE.with(|u| u.set(Some(unlocked))); +} + +/// The title's own `VirtualProtect`, through the GPU side's +/// (`leonida_gpu::title_memory_protect`). While a heap the GPU side opened +/// on the memory (`LEONIDA_INPLACE`) stands, the host refuses with error +/// 87: the GPU side then lets go of what is in place there, and the +/// protection is made at once if that was the last of the heap, else once +/// it is gone, the title told it is done, as the console would. Any other +/// call is the host's, unchanged (`LEONIDA_INPLACE_PROTECT=0`: all are). +extern "system" fn title_virtual_protect(address: *mut c_void, size: usize, new: u32, old: *mut u32) -> BOOL { + leonida_gpu::title_memory_protect(address as usize, size, new, old, || { + // SAFETY: the title's own arguments. + unsafe { VirtualProtect(address, size, new, old) } + }) +} + +/// `LEONIDA_INPLACE_TITLE_ALLOC`: on (unset), the title's own `VirtualAlloc`, +/// `VirtualAllocEx` and `VirtualProtectEx` (under `kernel32.dll`, +/// `kernelbase.dll` and the memory API sets, as [`title_virtual_free`]) are +/// the runtime's: [`title_virtual_alloc`], [`title_virtual_alloc_ex`], +/// [`title_virtual_protect_ex`]. `=0`: as before, the host's own, bound +/// directly. (Read once, when the table of exports is made.) +/// +/// With a timeline recording (`LEONIDA_TIMELINE`, diagnostics builds), the +/// title's `VirtualAlloc` is no longer bound to the timeline's wrapper as +/// one of its imports (`crate::host`, `leonida_gpu::timeline::import`), but +/// the host's call made here is still on the timeline as `VirtualAlloc`: +/// it goes through the runtime's own import table, whose entry the timeline +/// points at the same wrapper (`timeline::hooks::wrap_own`), as for +/// [`title_virtual_free`] and [`title_virtual_protect`]. What the glue does +/// before it (a release kept for a heap done first, waiting up to 50 ms for +/// the card to let go of its pages: `leonida_gpu::title_memory_reserve`) is +/// not inside that entry. `VirtualAllocEx` and `VirtualProtectEx` were never +/// on it (not wrapped). +fn title_allocs() -> bool { + static ON: LazyLock<bool> = LazyLock::new(|| std::env::var_os("LEONIDA_INPLACE_TITLE_ALLOC").is_none_or(|v| v != "0")); + *ON +} + +/// The title's own `VirtualAlloc`, through the GPU side's glue +/// (`leonida_gpu::title_memory_alloc`) as an `XMemVirtualAlloc` at an +/// address of the title's goes: an allocation at a fixed address that +/// touches a release the GPU side keeps for a heap it opened in place +/// (`LEONIDA_INPLACE`) does that release first, and is refused with error +/// 487 while the heap stands, as the console refuses a commit of memory that +/// is free. A commit of pages a heap stands over is the host's (they are +/// committed and read-write while it stands, and stay so), as is anything +/// else, unchanged, the thread's last error the host's; pages the title +/// decommitted under such a heap, kept committed and zeroed, are committed +/// to it again, and `XMemVirtualQuery` says so. +/// +/// Before, the title's import was the host's own, which the GPU side never +/// saw: a commit of pages the title had released was taken inside the +/// reservation kept for it, and those pages went with the release done +/// later, under a title told they were committed. +extern "system" fn title_virtual_alloc(address: *mut c_void, size: usize, kind: u32, protect: u32) -> *mut c_void { + leonida_gpu::title_memory_alloc(address as usize, size, kind, || { + // SAFETY: the title's own arguments. + unsafe { VirtualAlloc(address, size, kind, protect) } + }) +} + +/// The title's own `VirtualAllocEx`: of this process, [`title_virtual_alloc`] +/// (the host's `VirtualAllocEx` under the same glue); of another, the host's +/// alone. +extern "system" fn title_virtual_alloc_ex(process: HANDLE, address: *mut c_void, size: usize, kind: u32, protect: u32) -> *mut c_void { // SAFETY: the title's own arguments. - unsafe { VirtualFree(address, size, kind) } + let call = || unsafe { VirtualAllocEx(process, address, size, kind, protect) }; + if is_this_process(process) { + leonida_gpu::title_memory_alloc(address as usize, size, kind, call) + } else { + call() + } } +/// The title's own `VirtualProtectEx`: of this process, through the GPU +/// side's `leonida_gpu::title_memory_protect` as [`title_virtual_protect`] +/// (made once a heap opened in place over the memory is gone, the title told +/// it is done); of another, the host's alone. Before, it was the host's own, +/// which fails with error 87 while such a heap stands. +extern "system" fn title_virtual_protect_ex(process: HANDLE, address: *mut c_void, size: usize, new: u32, old: *mut u32) -> BOOL { + // SAFETY: the title's own arguments. + let call = || unsafe { VirtualProtectEx(process, address, size, new, old) }; + if is_this_process(process) { + leonida_gpu::title_memory_protect(address as usize, size, new, old, call) + } else { + call() + } +} + +/// Before the title's release of `at`: if it is a placeholder reservation +/// of the title's ([`PLACEHOLDERS`]) the runtime split into pieces, they +/// are joined into one (`MEM_COALESCE_PLACEHOLDERS`). The host refuses +/// while a view is still mapped in it: the release then takes the first +/// piece only, as before (said once). +fn join_placeholders(at: usize) { + const MEM_COALESCE_PLACEHOLDERS: u32 = 1; + let Some(bytes) = PLACEHOLDERS.lock().unwrap_or_else(|e| e.into_inner()).get(&at).copied() else { + return; + }; + if allocation_end(at).is_none_or(|end| end >= at + bytes) { + return; + } + // SAFETY: the title's reservation, about to be released by it; this + // acts only on placeholders. + if unsafe { VirtualFree(at as *mut c_void, bytes, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS) } == 0 { + static ONCE: std::sync::Once = std::sync::Once::new(); + let error = std::io::Error::last_os_error(); + ONCE.call_once(|| { + tracing::warn!( + at = format_args!("{at:#x}"), + bytes, + %error, + "the title releases a reservation whose pieces cannot be joined (a view still mapped in it?): the other pieces stay reserved" + ); + }); + } +} + +/// The title split `[at, at + len)` out of a placeholder reservation of its +/// (`MEM_PRESERVE_PLACEHOLDER`): it sees the pieces as reservations of +/// their own ([`PLACEHOLDERS`]). +fn placeholder_split(at: usize, len: usize) { + let mut placeholders = PLACEHOLDERS.lock().unwrap_or_else(|e| e.into_inner()); + let Some((base, bytes)) = placeholders.range(..=at).next_back().map(|(&b, &n)| (b, n)) else { + return; + }; + if base + bytes < at + len { + return; + } + placeholders.remove(&base); + for (from, to) in [(base, at), (at, at + len), (at + len, base + bytes)] { + if to > from { + placeholders.insert(from, to - from); + } + } +} + +/// The title joined the placeholders in `[at, at + len)` +/// (`MEM_COALESCE_PLACEHOLDERS`): one reservation of its ([`PLACEHOLDERS`]). +fn placeholders_joined(at: usize, len: usize) { + let mut placeholders = PLACEHOLDERS.lock().unwrap_or_else(|e| e.into_inner()); + let inside: Vec<usize> = placeholders.range(at..at.saturating_add(len)).map(|(&b, _)| b).collect(); + if inside.is_empty() { + return; + } + for base in inside { + placeholders.remove(&base); + } + placeholders.insert(at, len); +} + +/// The end of the host's allocation whose base is `at`, over all its +/// regions; `None` if `at` is not an allocation's base. (A placeholder the +/// runtime split, as `change` and `unmap` split the title's reservations of +/// 64 KiB pages, is an allocation of its own for each piece: a release of +/// the reservation's base takes the first piece only, unless they were +/// joined first, [`join_placeholders`].) +fn allocation_end(at: usize) -> Option<usize> { + // SAFETY: a pseudo handle needs no closing. + let process = unsafe { GetCurrentProcess() }; + let ask = |address: usize| { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQueryEx(process, address as *const c_void, &mut info, size_of_val(&info)) }; + (n != 0 && info.AllocationBase as usize == at).then(|| (info.BaseAddress as usize).saturating_add(info.RegionSize)) + }; + let mut end = ask(at)?; + while let Some(next) = ask(end) { + end = next; + } + Some(end) +} + +/// The title released the allocation `[at, end)`: the placeholders noted as +/// views' own there ([`Physical::holes`]), its record as a placeholder +/// reservation ([`PLACEHOLDERS`]) and as the 32-bit heap +/// ([`LOW_RESERVATIONS`]) go. Kept, a hole was taken for the next +/// reservation's own when the host gave the same address again (it gives +/// the lowest free one): `change` then skipped the serial split of that +/// placeholder and the pool's threads split it side by side, which can fail +/// (`XMemMapPhysicalPagesScatter` returns 0); and `arrange` looked through +/// stale reservations, the first match taken. +/// +/// shortcut: removed after the host's release, not with it: a reservation +/// made and mapped at the same address by another thread in between would +/// lose its own holes (which only costs it a split). +fn reservation_gone(at: usize, end: usize) { + { + let mut physical = physical(); + if !physical.holes.is_empty() { + physical.holes.retain(|&hole, _| hole < at || hole >= end); + } + } + PLACEHOLDERS.lock().unwrap_or_else(|e| e.into_inner()).remove(&at); + LOW_RESERVATIONS.lock().unwrap_or_else(|e| e.into_inner()).retain(|r| r.0 != at); +} + +/// The addresses [`title_virtual_free`] told the GPU side were freed, so the +/// tests can see which frees reach it. +#[cfg(test)] +static TOLD_FREED: Mutex<Vec<usize>> = Mutex::new(Vec::new()); + pub(crate) fn module() -> HleModule { + let mut exports = vec![ + crate::HleExport { name: "VirtualFree", address: title_virtual_free as *const () as usize }, + crate::HleExport { name: "VirtualProtect", address: title_virtual_protect as *const () as usize }, + hle_export!(XMemAlloc), + hle_export!(XMemFree), + hle_export!(XMemAllocDefault), + hle_export!(XMemFreeDefault), + hle_export!(XMemIsToolsMemAvailable), + hle_export!(XMemAllocatePhysicalPages), + hle_export!(XMemFreePhysicalPages), + hle_export!(XMemMapPhysicalPages), + hle_export!(XMemMapPhysicalPagesScatter), + hle_export!(XMemVirtualAlloc), + hle_export!(XMemVirtualQuery), + hle_export!(XMemGetWorkingSetStatistics), + hle_export!(XMemTransferMemory), + ]; + if title_allocs() { + exports.extend([ + crate::HleExport { name: "VirtualAlloc", address: title_virtual_alloc as *const () as usize }, + crate::HleExport { name: "VirtualAllocEx", address: title_virtual_alloc_ex as *const () as usize }, + crate::HleExport { name: "VirtualProtectEx", address: title_virtual_protect_ex as *const () as usize }, + ]); + } HleModule { name: "xmem", dlls: &["xmem.dll", "kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-*"], - exports: vec![ - crate::HleExport { name: "VirtualFree", address: title_virtual_free as *const () as usize }, - hle_export!(XMemAlloc), - hle_export!(XMemFree), - hle_export!(XMemAllocDefault), - hle_export!(XMemFreeDefault), - hle_export!(XMemIsToolsMemAvailable), - hle_export!(XMemAllocatePhysicalPages), - hle_export!(XMemFreePhysicalPages), - hle_export!(XMemMapPhysicalPages), - hle_export!(XMemMapPhysicalPagesScatter), - hle_export!(XMemVirtualAlloc), - hle_export!(XMemVirtualQuery), - hle_export!(XMemGetWorkingSetStatistics), - hle_export!(XMemTransferMemory), - ], + exports, } } @@ -2438,6 +3727,452 @@ mod tests { XMemFree(p, ALLOC_32BIT); } + /// A free the host refuses for a reason of its own (a release given a + /// size) goes through the GPU side's take-over + /// (`leonida_gpu::title_memory_free`, which no heap of its is in the way + /// of here) and comes back as the host refused it: 0, error 87 the + /// thread's last error. + #[test] + fn a_free_the_host_refuses_comes_back_refused_with_its_error() { + use windows_sys::Win32::Foundation::{ERROR_INVALID_PARAMETER, GetLastError, SetLastError}; + let at = XMemVirtualAlloc(std::ptr::null_mut(), PAGE, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE); + assert!(!at.is_null()); + // SAFETY: plain sets and reads of the thread's last error. + unsafe { + SetLastError(0); + assert_eq!(title_virtual_free(at, PAGE, MEM_RELEASE), 0); + assert_eq!(GetLastError(), ERROR_INVALID_PARAMETER); + } + assert_eq!(title_virtual_free(at, 0, MEM_RELEASE), 1); + } + + /// The title's `VirtualProtect` is the runtime's (through the GPU side's + /// `leonida_gpu::title_memory_protect`, which no heap of its is in the + /// way of here): made at once, the old protection given back, and a + /// call the host refuses comes back refused with its error. Before, the + /// title's import went to the host's own, which the GPU side never saw: + /// a protection of memory it had in place failed with error 87. + #[test] + fn the_title_protects_through_the_gpu_side() { + use windows_sys::Win32::Foundation::{ERROR_INVALID_PARAMETER, GetLastError, SetLastError}; + use windows_sys::Win32::System::Memory::PAGE_READONLY; + let exported = module().exports.iter().find(|e| e.name == "VirtualProtect").map(|e| e.address); + assert_eq!(exported, Some(title_virtual_protect as *const () as usize), "the title's VirtualProtect is the runtime's"); + let at = XMemVirtualAlloc(std::ptr::null_mut(), 2 * PAGE, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE); + assert!(!at.is_null()); + let mut old = 0; + assert_eq!(title_virtual_protect(at, PAGE, PAGE_READONLY, &mut old), 1); + assert_eq!(old, PAGE_READWRITE); + assert_eq!(query(at).host.Protect, PAGE_READONLY); + // SAFETY: plain sets and reads of the thread's last error. + unsafe { + SetLastError(0); + assert_eq!(title_virtual_protect(at, PAGE, 0x7f, &mut old), 0, "no such protection"); + assert_eq!(GetLastError(), ERROR_INVALID_PARAMETER); + } + assert_eq!(title_virtual_free(at, 0, MEM_RELEASE), 1); + } + + /// What the host says of the memory at `at`: its state and protection. + fn host_says(at: *const c_void) -> (u32, u32) { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a pseudo handle, a valid out pointer of the right size. + let n = unsafe { VirtualQueryEx(GetCurrentProcess(), at, &mut info, size_of_val(&info)) }; + assert_ne!(n, 0); + (info.State, info.Protect) + } + + /// (`LEONIDA_INPLACE_RELEASE_FIRST`) The title releases memory a heap + /// the GPU side opened in place stands over (the release is kept for it + /// until the heap is gone, `leonida_gpu::title_memory_free`), then + /// commits pages there without reserving them again, through + /// `XMemVirtualAlloc`: refused with error 487 while the heap stands, the + /// pages left as they were, as the console refuses a commit of memory + /// that is free; once the heap is gone the release is done first, the + /// commit refused all the same, and a reservation of the addresses made. + /// Before, the host was asked first and took the commit inside the + /// reservation kept for the title, whose release took the pages away + /// later. Skipped without a host device that opens memory in place. + #[test] + fn a_commit_into_a_release_kept_for_a_heap_is_refused() { + use windows_sys::Win32::Foundation::{ERROR_INVALID_ADDRESS, GetLastError}; + let base = XMemVirtualAlloc(std::ptr::null_mut(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE); + assert!(!base.is_null()); + let Some(held) = leonida_gpu::title_memory_held_in_place(base as usize + PAGE, PAGE) else { + eprintln!("no host device that opens memory in place: skipped"); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1); + return; + }; + let held = held.expect("opened in place"); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1, "the title is told its release is done"); + assert_eq!(host_says(base).0, MEM_COMMIT, "kept for it while the heap stands"); + + let page = base.wrapping_byte_add(2 * PAGE); + let got = XMemVirtualAlloc(page, PAGE, MEM_COMMIT, 0, PAGE_READWRITE); + // SAFETY: a plain read of the thread's last error. + let error = unsafe { GetLastError() }; + assert!(got.is_null(), "a commit of released pages is refused"); + assert_eq!(error, ERROR_INVALID_ADDRESS); + + drop(held); + // (The card's driver may let go of the heap's pages a moment later.) + let released = (0..500).any(|_| { + let got = XMemVirtualAlloc(page, PAGE, MEM_COMMIT, 0, PAGE_READWRITE); + // SAFETY: a plain read of the thread's last error. + let error = unsafe { GetLastError() }; + assert!(got.is_null(), "refused once the heap is gone too"); + assert_eq!(error, ERROR_INVALID_ADDRESS); + let free = host_says(base).0 == windows_sys::Win32::System::Memory::MEM_FREE; + if !free { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + free + }); + assert!(released, "the release was done first"); + let again = XMemVirtualAlloc(base, 4 * PAGE, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE); + assert_eq!(again, base, "the addresses are the title's to take again"); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1); + } + + /// (`LEONIDA_INPLACE_QUERY`) While a heap the GPU side opened in place + /// stands over the title's memory, its protection and its release are + /// done later (`leonida_gpu::title_memory_protect`, `title_memory_free`) + /// and the title is told they are done: `XMemVirtualQuery` then tells it + /// the protection it asked for, over the page it asked for, and free + /// memory once it released the allocation, though the host still has + /// the old protection and the allocation. Before, it told what the host + /// had. Skipped without a host device that opens memory in place. + #[test] + fn a_query_tells_what_the_gpu_side_does_later() { + use windows_sys::Win32::System::Memory::{MEM_FREE, PAGE_READONLY}; + let base = XMemVirtualAlloc(std::ptr::null_mut(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE); + assert!(!base.is_null()); + let Some(held) = leonida_gpu::title_memory_held_in_place(base as usize + PAGE, PAGE) else { + eprintln!("no host device that opens memory in place: skipped"); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1); + return; + }; + let held = held.expect("opened in place"); + let page = base.wrapping_byte_add(PAGE + 0x3000); + let mut old = 0; + assert_eq!(title_virtual_protect(page, 0x1000, PAGE_READONLY, &mut old), 1, "told done"); + assert_eq!(old, PAGE_READWRITE); + assert_eq!(host_says(page).1, PAGE_READWRITE, "the host keeps it while the heap stands"); + let info = query(page); + assert_eq!(info.host.Protect, PAGE_READONLY, "the protection the title asked for"); + assert_eq!((info.host.BaseAddress, info.host.RegionSize), (page, 0x1000)); + assert_eq!(info.host.State, MEM_COMMIT); + let before = query(base); + assert_eq!(before.host.Protect, PAGE_READWRITE); + assert_eq!(before.host.RegionSize, PAGE + 0x3000, "up to the page that waits"); + + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1, "told done"); + assert_eq!(host_says(base).0, MEM_COMMIT, "kept for the title while the heap stands"); + let info = query(page); + assert_eq!(info.host.State, MEM_FREE, "free memory to the title"); + assert!(info.host.RegionSize >= 3 * PAGE - 0x3000, "to the allocation's end at least"); + assert_eq!(info.flags, 0, "not graphics memory"); + + drop(held); + // The title takes the addresses again once the release is done + // (`leonida_gpu::title_memory_reserve` does it first). + let again = (0..500).any(|_| { + let again = XMemVirtualAlloc(base, 4 * PAGE, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE); + if again.is_null() { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + !again.is_null() + }); + assert!(again, "released once the heap is gone"); + assert_eq!(query(page).host.Protect, PAGE_READWRITE, "new memory: nothing waits over it"); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1); + } + + /// (`LEONIDA_INPLACE_TITLE_ALLOC`) The title's own `VirtualAlloc`, + /// `VirtualAllocEx` and `VirtualProtectEx` are the runtime's, under the + /// names it imports them by, and with no heap of the GPU side's in the + /// way they are the host's calls: memory reserved and committed where + /// asked, a protection made with the old one given back, and a call the + /// host refuses comes back refused with its error. + #[test] + fn the_titles_own_virtual_alloc_and_protect_ex_are_the_runtimes() { + use windows_sys::Win32::Foundation::{ERROR_INVALID_PARAMETER, GetLastError, SetLastError}; + use windows_sys::Win32::System::Memory::PAGE_READONLY; + let module = module(); + let exported = |name: &str| module.exports.iter().find(|e| e.name == name).map(|e| e.address); + assert_eq!(exported("VirtualAlloc"), Some(title_virtual_alloc as *const () as usize), "the title's VirtualAlloc is the runtime's"); + assert_eq!(exported("VirtualAllocEx"), Some(title_virtual_alloc_ex as *const () as usize)); + assert_eq!(exported("VirtualProtectEx"), Some(title_virtual_protect_ex as *const () as usize)); + assert!(module.serves("KERNEL32.dll") && module.serves("api-ms-win-core-memory-l1-1-0.dll")); + + // SAFETY: a pseudo handle needs no closing. + let process = unsafe { GetCurrentProcess() }; + let base = title_virtual_alloc(std::ptr::null_mut(), 2 * PAGE, MEM_RESERVE, PAGE_READWRITE); + assert!(!base.is_null()); + assert_eq!(title_virtual_alloc(base, PAGE, MEM_COMMIT, PAGE_READWRITE), base); + let second = base.wrapping_byte_add(PAGE); + assert_eq!(title_virtual_alloc_ex(process, second, PAGE, MEM_COMMIT, PAGE_READWRITE), second); + assert_eq!(host_says(second), (MEM_COMMIT, PAGE_READWRITE)); + let mut old = 0; + assert_eq!(title_virtual_protect_ex(process, second, 0x1000, PAGE_READONLY, &mut old), 1); + assert_eq!(old, PAGE_READWRITE); + assert_eq!(host_says(second).1, PAGE_READONLY); + // SAFETY: plain sets and reads of the thread's last error. + unsafe { + SetLastError(0); + assert!(title_virtual_alloc(base, 0, MEM_COMMIT, PAGE_READWRITE).is_null(), "no size"); + assert_eq!(GetLastError(), ERROR_INVALID_PARAMETER); + SetLastError(0); + assert_eq!(title_virtual_protect_ex(process, second, 0x1000, 0x7f, &mut old), 0, "no such protection"); + assert_eq!(GetLastError(), ERROR_INVALID_PARAMETER); + } + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1); + } + + /// (`LEONIDA_INPLACE_TITLE_ALLOC`) Through the title's own `VirtualAlloc` + /// and `VirtualProtectEx`, memory a heap the GPU side opened in place + /// stands over: a commit of pages under the heap is the host's (they + /// are committed); a protection is told done and made later + /// (`leonida_gpu::title_memory_protect`); once the title released the + /// allocation (kept for it while the heap stands), a commit of its pages + /// without a new reservation is refused with error 487, by either call, + /// while the heap stands and once it is gone, as the console refuses a + /// commit of free memory; and the addresses are the title's to reserve + /// again. Before, both went to the host: the protection failed with error + /// 87, and the commit was taken inside the reservation kept for the title, + /// whose release took the pages away later. Skipped without a host + /// device that opens memory in place. + #[test] + fn the_titles_own_virtual_alloc_and_protect_ex_meet_a_heap_in_place() { + use windows_sys::Win32::Foundation::{ERROR_INVALID_ADDRESS, GetLastError}; + use windows_sys::Win32::System::Memory::PAGE_READONLY; + // SAFETY: a pseudo handle needs no closing. + let process = unsafe { GetCurrentProcess() }; + let base = title_virtual_alloc(std::ptr::null_mut(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + assert!(!base.is_null()); + let Some(held) = leonida_gpu::title_memory_held_in_place(base as usize + PAGE, PAGE) else { + eprintln!("no host device that opens memory in place: skipped"); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1); + return; + }; + let held = held.expect("opened in place"); + let under = base.wrapping_byte_add(PAGE); + assert_eq!(title_virtual_alloc(under, 0x2000, MEM_COMMIT, PAGE_READWRITE), under, "a commit under the heap is the host's"); + let page = base.wrapping_byte_add(PAGE + 0x3000); + let mut old = 0; + assert_eq!(title_virtual_protect_ex(process, page, 0x1000, PAGE_READONLY, &mut old), 1, "told done"); + assert_eq!(old, PAGE_READWRITE); + assert_eq!(query(page).host.Protect, PAGE_READONLY, "the protection the title asked for"); + + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1, "the title is told its release is done"); + assert_eq!(host_says(base).0, MEM_COMMIT, "kept for it while the heap stands"); + let refused = |what: &str, got: *mut c_void| { + // SAFETY: a plain read of the thread's last error. + let error = unsafe { GetLastError() }; + assert!(got.is_null(), "{what}: a commit of released pages is refused"); + assert_eq!(error, ERROR_INVALID_ADDRESS, "{what}"); + }; + let released_page = base.wrapping_byte_add(2 * PAGE); + refused("VirtualAlloc", title_virtual_alloc(released_page, PAGE, MEM_COMMIT, PAGE_READWRITE)); + refused("VirtualAllocEx", title_virtual_alloc_ex(process, released_page, PAGE, MEM_COMMIT, PAGE_READWRITE)); + + drop(held); + // Once: the glue does the release first if the card's driver let go + // of the heap's pages, and the host refuses the commit of free memory; + // else the glue refuses it, as above. + refused("once the heap is gone", title_virtual_alloc(released_page, PAGE, MEM_COMMIT, PAGE_READWRITE)); + // The addresses taken back in one step (`title_memory_reserve` does the + // release and reserves at once; the driver may let go a moment later). + // Before, the commit above was asked again until the host said the + // memory was free and the reservation was made after: another test + // could take the addresses in between, and the next commit was made in + // its memory. + let again = (0..500).any(|_| { + let again = title_virtual_alloc(base, 4 * PAGE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if again.is_null() { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + again == base + }); + assert!(again, "the addresses are the title's to take again once the heap is gone"); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1); + } + + /// (`LEONIDA_INPLACE_QUERY_DECOMMITS`) The title decommits memory a heap + /// the GPU side opened in place stands over: the host keeps it committed + /// and zeroed (`leonida_gpu::title_memory_free`), and `XMemVirtualQuery` + /// tells it reserved memory, not graphics memory, as the title asked; + /// the committed memory before it ends there. Committed again by the + /// title's own `VirtualAlloc`, or by `XMemVirtualAlloc`, it is committed + /// graphics memory again; released, it is free memory. Before, it read as + /// committed until the title released the allocation. Skipped without a + /// host device that opens memory in place. + #[test] + fn a_query_tells_a_decommit_under_a_heap_as_reserved() { + use windows_sys::Win32::System::Memory::{MEM_DECOMMIT, MEM_FREE}; + let base = XMemVirtualAlloc(std::ptr::null_mut(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE); + assert!(!base.is_null()); + let Some(held) = leonida_gpu::title_memory_held_in_place(base as usize + PAGE, PAGE) else { + eprintln!("no host device that opens memory in place: skipped"); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1); + return; + }; + let held = held.expect("opened in place"); + let page = base.wrapping_byte_add(PAGE); + let decommitted = || { + assert_eq!(title_virtual_free(page, PAGE, MEM_DECOMMIT), 1, "the title's decommit is told done"); + assert_eq!(host_says(page).0, MEM_COMMIT, "kept committed under the heap"); + let info = query(page.wrapping_byte_add(0x10)); + assert_eq!((info.host.State, info.host.Protect, info.flags), (MEM_RESERVE, 0, 0), "reserved, as the title asked"); + assert_eq!((info.host.BaseAddress, info.host.RegionSize), (page, PAGE)); + let before = query(base); + assert_eq!((before.host.State, before.host.RegionSize, before.flags), (MEM_COMMIT, PAGE, GRAPHICS), "committed, to the decommit"); + }; + let committed = |how: &str| { + let info = query(page); + assert_eq!((info.host.State, info.host.Protect, info.flags), (MEM_COMMIT, PAGE_READWRITE, GRAPHICS), "{how}"); + assert_eq!(query(base).host.RegionSize, 4 * PAGE, "{how}: one committed region again"); + }; + decommitted(); + assert_eq!(title_virtual_alloc(page, PAGE, MEM_COMMIT, PAGE_READWRITE), page); + committed("committed again by VirtualAlloc"); + decommitted(); + assert_eq!(XMemVirtualAlloc(page, PAGE, MEM_COMMIT, 0, PAGE_READWRITE), page); + committed("committed again by XMemVirtualAlloc"); + + decommitted(); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1, "the title is told its release is done"); + assert_eq!(query(page).host.State, MEM_FREE, "free memory to the title, decommitted or not"); + + drop(held); + // The title takes the addresses again once the release is done + // (`leonida_gpu::title_memory_reserve` does it first). + let again = (0..500).any(|_| { + let again = XMemVirtualAlloc(base, 4 * PAGE, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE); + if again.is_null() { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + !again.is_null() + }); + assert!(again, "released once the heap is gone"); + assert_eq!(query(page).host.State, MEM_COMMIT, "new memory: nothing kept over it"); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1); + } + + #[test] + fn free_default_tells_the_gpu_side_of_32bit_memory() { + // `XMemAllocDefault` told the GPU side of this memory + // (`XMemVirtualAlloc`), so freeing it must say it is gone, or what + // was noted of it is taken for true of the next memory there. + let p = XMemAllocDefault(4096, ALLOC_32BIT); + assert!(!p.is_null()); + XMemFreeDefault(p, ALLOC_32BIT); + let told = TOLD_FREED.lock().unwrap_or_else(|e| e.into_inner()); + assert!( + told.contains(&(p as usize)), + "the free of {p:p} never reached the GPU side" + ); + } + + /// The pages of `[at, at + len)` written since the last asking, as the + /// GPU side asks (`leonida_gpu::watch`); `None` where the kernel keeps + /// no written pages. + fn written_pages(at: *mut c_void, len: usize) -> Option<Vec<usize>> { + const WRITE_WATCH_FLAG_RESET: u32 = 1; + let (mut found, mut count, mut granularity) = (vec![0usize; len / 4096], len / 4096, 0); + // SAFETY: room for `count` addresses. + let failed = unsafe { + windows_sys::Win32::System::Memory::GetWriteWatch( + WRITE_WATCH_FLAG_RESET, + at, + len, + found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + } != 0; + (!failed).then(|| found[..count].to_vec()) + } + + #[test] + fn default_blocks_from_64_kib_are_reservations_of_their_own() { + assert!(!watched_block(100, 16) && !watched_block(WATCHED_FROM - 1, 32 << 10)); + assert!(watched_block(WATCHED_FROM, 16) && watched_block(100, 64 << 10) && watched_block(100, 4 * MIB)); + } + + /// A block from 64 KiB, or aligned to 64 KiB, is a reservation of its + /// own: write-watched (a host copy of it refreshes the pages written, not + /// all of it), below 2^40, committed no further than its own pages, and + /// its free reaches the GPU side. + #[test] + fn large_default_blocks_are_write_watched_and_below_2_40() { + let attributes = 0x10 << ALIGNMENT_SHIFT | 1 << 29; // 64 KiB, a graphics type + let p = XMemAllocDefault(MIB, attributes); + assert!(!p.is_null()); + assert!(written_pages(p, MIB).is_some(), "the kernel keeps no written pages of {p:p}"); + assert_eq!(p as usize % (64 << 10), 0); + assert!((p as usize) >= 1 << 32 && (p as usize) + MIB <= 1 << 40, "{p:p}"); + // SAFETY: 1 MiB was allocated. + unsafe { p.cast::<u8>().add(5 * 4096 + 7).write(1) }; + assert_eq!(written_pages(p, MIB), Some(vec![p as usize + 5 * 4096])); + assert_eq!(written_pages(p, MIB), Some(vec![])); + // Small, 64 KiB-aligned: one 4 KiB page committed, where a heap block + // took 64 KiB more than it asked. + let small = XMemAllocDefault(0x80, attributes); + assert!(!small.is_null()); + assert_eq!(small as usize % (64 << 10), 0); + let info = query(small); + assert_eq!((info.host.AllocationBase, info.host.RegionSize, info.host.State), (small, 4096, MEM_COMMIT)); + // Aligned beyond the host's 64 KiB. + let wide_attributes = 22 << ALIGNMENT_SHIFT; + let wide = XMemAllocDefault(MIB, wide_attributes); + assert!(!wide.is_null() && (wide as usize).is_multiple_of(4 * MIB), "{wide:p}"); + for (at, attributes) in [(p, attributes), (small, attributes), (wide, wide_attributes)] { + XMemFreeDefault(at, attributes); + assert!(TOLD_FREED.lock().unwrap_or_else(|e| e.into_inner()).contains(&(at as usize)), "the free of {at:p} never reached the GPU side"); + assert!(!watched_blocks().contains_key(&(at as usize))); + } + } + + /// The device's heaps (`leonida_gpu::resource::use_heap_memory`): whole + /// write-watched reservations below 2^40, zeroed, at the alignment asked + /// for, freed as the title frees. + #[test] + fn heap_memory_is_a_write_watched_reservation_below_2_40() { + for align in [64 << 10, 4 * MIB] { + let p = heap_memory(4 * MIB, align); + assert!(!p.is_null()); + assert!(written_pages(p, 4 * MIB).is_some(), "the kernel keeps no written pages of {p:p}"); + assert!((p as usize).is_multiple_of(align) && (p as usize) >= 1 << 32 && (p as usize) + 4 * MIB <= 1 << 40, "{p:p}"); + let info = query(p); + assert_eq!((info.host.AllocationBase, info.host.RegionSize, info.host.Type), (p, 4 * MIB, windows_sys::Win32::System::Memory::MEM_PRIVATE)); + // SAFETY: 4 MiB were allocated. + assert!(unsafe { std::slice::from_raw_parts(p.cast::<u8>(), 4 * MIB) }.iter().all(|&b| b == 0)); + heap_memory_free(p); + assert!(TOLD_FREED.lock().unwrap_or_else(|e| e.into_inner()).contains(&(p as usize))); + } + } + + /// What the runtime reserves for the title (`XMemAllocDefault`'s + /// blocks, the device's heaps) is not logged as what the title asked + /// for; the title's own `XMemVirtualAlloc` is. + #[test] + fn only_the_titles_own_reservations_are_noted_as_asked_for() { + let noted = || PROTECTIONS_NOTED.with(|n| n.get()); + let before = noted(); + let block = XMemAllocDefault(MIB, 0); + let heap = heap_memory(MIB, 64 << 10); + assert!(!block.is_null() && !heap.is_null() && watched_blocks().contains_key(&(block as usize))); + assert_eq!(noted(), before, "a reservation of the runtime's noted as the title's"); + XMemFreeDefault(block, 0); + heap_memory_free(heap); + let own = XMemVirtualAlloc(std::ptr::null_mut(), MIB, MEM_RESERVE | MEM_COMMIT, GRAPHICS, PAGE_READWRITE); + assert!(!own.is_null()); + assert_eq!(noted(), before + 1); + assert_eq!(title_virtual_free(own, 0, MEM_RELEASE), 1); + } + #[test] fn virtual_alloc_meets_console_constraints() { const GPU_READ_WRITE: u32 = 0x2000; @@ -2469,8 +4204,9 @@ mod tests { ) }; assert_eq!(watched, 0); - // SAFETY: our own reservation. - assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0); + // As the title frees (a host free alone would leave its commit + // counted, [`TITLE_COMMIT`], for the next memory there). + assert_ne!(title_virtual_free(p, 0, MEM_RELEASE), 0); assert_eq!(query(p).flags, 0); // No address field: above the 32-bit range and below 2^40, where // the console keeps it. @@ -2491,7 +4227,6 @@ mod tests { fn transfers_shrink_the_title_budget() { let mut before = WorkingSet::default(); assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut before), 1); - assert!(before.title_used > 0); assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1); assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory"); let standard = leonida_gpu::console::current().title_memory().1; @@ -2501,6 +4236,127 @@ mod tests { assert_eq!(before.title_limit - after.title_limit, 128 * MIB); } + /// The title's `VirtualFree` holds no lock of the tables over the + /// host's free (a decommit of a large range takes milliseconds, and + /// every commit would wait behind it); a free the host refuses leaves + /// both tables as they were. + #[test] + fn title_free_holds_no_lock_over_the_host_free() { + let p = XMemAllocDefault(MIB, 0); + assert!(!p.is_null() && watched_blocks().contains_key(&(p as usize))); + let (at, end) = (p as usize, p as usize + MIB); + assert_eq!(title_commit().within(at, end), MIB); + // A release with a size: the host refuses it. + UNLOCKED_AT_FREE.with(|u| u.set(None)); + assert_eq!(title_virtual_free(p, 4096, MEM_RELEASE), 0); + assert_eq!(UNLOCKED_AT_FREE.with(|u| u.get()), Some(true), "a table's lock held over the host's free"); + assert_eq!(watched_blocks().get(&at), Some(&MIB), "a refused free forgot the block"); + assert_eq!(title_commit().within(at, end), MIB, "a refused free forgot the commit"); + UNLOCKED_AT_FREE.with(|u| u.set(None)); + XMemFreeDefault(p, 0); + assert_eq!(UNLOCKED_AT_FREE.with(|u| u.get()), Some(true), "a table's lock held over the host's free"); + assert!(!watched_blocks().contains_key(&at) || query(p).host.State != windows_sys::Win32::System::Memory::MEM_FREE); + assert_eq!(counted_after_free(at, end), 0); + } + + #[test] + fn title_commit_counts_each_page_once() { + let mut c = TitleCommit::new(); + c.add(0x10_0000, 0x20_0000); + c.add(0x18_0000, 0x28_0000); // over the end + c.add(0x28_0000, 0x30_0000); // beside: one range + c.add(0x40_0000, 0x41_0000); + assert_eq!((c.bytes, c.ranges.len()), (0x21_0000, 2)); + assert_eq!(c.remove(0x14_0000, 0x15_0000), [(0x14_0000, 0x15_0000)]); // a hole + assert_eq!(c.remove(0x30_0000, 0x40_0000), []); // between: nothing + assert_eq!((c.bytes, c.ranges.len()), (0x20_0000, 3)); + assert_eq!(c.within(0x12_0000, 0x16_0000), 0x3_0000); + // What a remove takes, added back, is what was there. + let taken = c.remove(0x12_0000, 0x40_8000); + assert_eq!(taken, [(0x40_0000, 0x40_8000), (0x15_0000, 0x30_0000), (0x12_0000, 0x14_0000)]); + for (from, to) in taken { + c.add(from, to); + } + assert_eq!((c.bytes, c.ranges.len()), (0x20_0000, 3)); + c.remove(0, usize::MAX); + assert_eq!((c.bytes, c.ranges.len()), (0, 0)); + } + + /// Committed through `XMemVirtualAlloc`, counted to the page; decommitted + /// and released through the title's `VirtualFree`, no more. + #[test] + fn the_titles_commit_is_counted_until_it_is_freed() { + const MEM_DECOMMIT: u32 = 0x4000; + let p = XMemVirtualAlloc(std::ptr::null_mut(), 16 * MIB - 100, MEM_RESERVE | MEM_COMMIT, GRAPHICS, PAGE_READWRITE); + assert!(!p.is_null()); + let (at, end) = (p as usize, p as usize + 16 * MIB); + assert_eq!(title_commit().within(at, end), 16 * MIB); + assert_eq!(title_virtual_free(p.wrapping_byte_add(MIB + 5), 4 * MIB, MEM_DECOMMIT), 1); + assert_eq!(title_commit().within(at, end), 16 * MIB - 4 * MIB - HOST_PAGE); + // Committed again, and once more over itself. + for _ in 0..2 { + assert_eq!(XMemVirtualAlloc(p, 8 * MIB, MEM_COMMIT, GRAPHICS, PAGE_READWRITE), p); + } + assert_eq!(title_commit().within(at, end), 16 * MIB); + assert_eq!(title_virtual_free(p, 0, MEM_RELEASE), 1); + assert_eq!(counted_after_free(at, end), 0); + // A block of `XMemAllocDefault`'s too. + let block = XMemAllocDefault(MIB, 0); + assert_eq!(title_commit().within(block as usize, block as usize + MIB), MIB); + XMemFreeDefault(block, 0); + assert_eq!(counted_after_free(block as usize, block as usize + MIB), 0); + } + + /// What of the freed `[at, end)` [`TITLE_COMMIT`] counts, but 0 if + /// memory stands there again: another test's thread may be given the + /// address the moment it is free, and its commit is counted rightly + /// (asked again a while, as that thread may free it between the count + /// and the look). + fn counted_after_free(at: usize, end: usize) -> usize { + let reused = || { + let mut from = at; + while from < end { + let info = query(from as *const c_void); + if info.host.State != windows_sys::Win32::System::Memory::MEM_FREE { + return true; + } + from = (info.host.BaseAddress as usize).saturating_add(info.host.RegionSize); + } + false + }; + let mut counted = 0; + for _ in 0..100 { + counted = title_commit().within(at, end); + if counted == 0 || reused() { + return 0; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + counted + } + + /// The title is told what it was given, not what the process holds: + /// memory of the runtime's own leaves its figure as it was. + #[test] + fn the_title_is_told_its_own_use_not_the_processes() { + let used = || { + let mut stats = WorkingSet::default(); + assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut stats), 1); + stats.title_used + }; + let p = XMemVirtualAlloc(std::ptr::null_mut(), 16 * MIB, MEM_RESERVE | MEM_COMMIT, GRAPHICS, PAGE_READWRITE); + assert!(!p.is_null()); + assert!(used() >= 16 * MIB); + let before = used(); + let ours = vec![1u8; 512 * MIB]; + let after = used(); + assert!(ours.iter().step_by(4096).all(|&b| b == 1)); + drop(ours); + // (Other tests allocate title memory meanwhile, 64 MiB at most at once.) + assert!(after < before + 256 * MIB, "the title is told it uses {} MB more for 512 MB of the runtime's", (after - before) >> 20); + assert_eq!(title_virtual_free(p, 0, MEM_RELEASE), 1); + } + #[test] fn statistics_have_the_console_layout() { assert_eq!(size_of::<WorkingSet>(), 0x50); @@ -3007,6 +4863,164 @@ mod tests { View::map(&slice, 1).expect("mapped").bytes().to_vec() } + /// (`LEONIDA_SECTION_COMMIT`) A small section is made when a page of it + /// is first shown, committed: mapping a page, mapping it again + /// elsewhere, a page beside it and a DirectStorage write into a page + /// mapped nowhere ask the host to commit nothing, and a section none + /// of whose pages is shown is never made. The bytes are where their + /// page numbers say. + #[test] + fn a_committed_section_is_made_at_its_first_page() { + let was = (TEST_SECTION_PAGES.replace(Some(16)), TEST_SECTION_COMMIT.replace(Some(true))); + let (made, commits) = (SECTIONS_MADE.get(), COMMITS.get()); + let pages = allocate(48); + let base = XMemVirtualAlloc(std::ptr::null_mut(), 2 * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + let other = XMemVirtualAlloc(std::ptr::null_mut(), PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!base.is_null() && !other.is_null()); + assert_eq!(XMemMapPhysicalPages(base, 1, pages[3..].as_ptr()), base); + // SAFETY: mapped read-write. + unsafe { base.cast::<u8>().write(5) }; + assert_eq!(COMMITS.get() - commits, 0, "a page mapped: no commit of its own"); + assert_eq!(SECTIONS_MADE.get() - made, 1, "only the section of the page shown is made"); + assert_eq!(XMemMapPhysicalPages(other, 1, pages[3..].as_ptr()), other); + // SAFETY: mapped read-write. + assert_eq!(unsafe { other.cast::<u8>().read() }, 5, "the same page at a second address"); + let next = base.wrapping_byte_add(PAGE); + assert_eq!(XMemMapPhysicalPages(next, 1, pages[4..].as_ptr()), next); + assert!(write_physical(&pages[20..], 7, &[9]), "a write into a page mapped nowhere"); + assert_eq!(COMMITS.get() - commits, 0, "no page asked to be committed on its own"); + assert_eq!(SECTIONS_MADE.get() - made, 2, "the second section, made by the write"); + assert_eq!(page_bytes(pages[20])[7], 9); + assert_eq!(page_bytes(pages[3])[0], 5); + assert!(page_table().pages.get(&pages[40]).is_some_and(|s| s.section.host.get().is_none()), "the third section untouched, not made"); + assert_eq!(XMemMapPhysicalPages(base, 2, std::ptr::null()), base); + assert_eq!(XMemMapPhysicalPages(other, 1, std::ptr::null()), other); + assert_eq!(XMemFreePhysicalPages(48, pages.as_ptr()), 1); + TEST_SECTION_PAGES.set(was.0); + TEST_SECTION_COMMIT.set(was.1); + } + + /// (`LEONIDA_SECTION_COMMIT`) The section behind two pages the title + /// mapped opens as a heap on the host device (`OpenExistingHeapFromFileMapping`, + /// which refuses a section made reserved), and a buffer placed in it at + /// the pages' offset gives the card the bytes the CPU wrote through the + /// title's view; still, with new bytes, once the view is gone and the + /// pages are mapped at another address. Skipped without a host device. + #[test] + fn a_committed_section_opens_as_a_heap() { + let was = (TEST_SECTION_PAGES.replace(Some(16)), TEST_SECTION_COMMIT.replace(Some(true))); + let pages = allocate(32); + let reserve = || XMemVirtualAlloc(std::ptr::null_mut(), 2 * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + let (base, other) = (reserve(), reserve()); + assert!(!base.is_null() && !other.is_null()); + let fill = |at: *mut c_void, seed: u8| { + for k in (0..2 * PAGE).step_by(4093) { + // SAFETY: mapped read-write. + unsafe { at.cast::<u8>().add(k).write(seed ^ (k / 4093) as u8) }; + } + }; + assert_eq!(XMemMapPhysicalPages(base, 2, pages[5..].as_ptr()), base); + fill(base, 0x5a); + let first = leonida_gpu::title_memory_reads_in_place(base as usize, 2 * PAGE); + assert_eq!(XMemMapPhysicalPages(base, 2, std::ptr::null()), base); + assert_eq!(XMemMapPhysicalPages(other, 2, pages[5..].as_ptr()), other); + fill(other, 0xc3); + let moved = leonida_gpu::title_memory_reads_in_place(other.wrapping_byte_add(100) as usize, 2 * PAGE - 200); + assert_eq!(XMemMapPhysicalPages(other, 2, std::ptr::null()), other); + assert_eq!(XMemFreePhysicalPages(32, pages.as_ptr()), 1); + TEST_SECTION_PAGES.set(was.0); + TEST_SECTION_COMMIT.set(was.1); + let (Some(first), Some(moved)) = (first, moved) else { + return; // no host device + }; + assert_eq!(first, Ok(true), "the section opened and the card read the title's bytes"); + assert_eq!(moved, Ok(true), "and from its new address"); + } + + /// The process's shared commit (`SharedCommitUsage`, which a + /// pagefile-backed section's commit is charged to), in bytes. + fn shared_commit() -> u64 { + use windows_sys::Win32::System::ProcessStatus::PROCESS_MEMORY_COUNTERS_EX2; + let mut counters = PROCESS_MEMORY_COUNTERS_EX2 { cb: size_of::<PROCESS_MEMORY_COUNTERS_EX2>() as u32, ..Default::default() }; + // SAFETY: the buffer and size describe a writable + // PROCESS_MEMORY_COUNTERS_EX2, which begins as the smaller one. + let asked = unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), (&raw mut counters).cast(), counters.cb) }; + assert_ne!(asked, 0); + counters.SharedCommitUsage + } + + /// Runs the test `name` (its path in this binary) alone in a child + /// process of this test binary, and checks that it passed there: true in + /// the parent, which has nothing left to do, false in the child, which + /// runs the test's body. For the tests that read [`shared_commit`], the + /// whole process's counter, which the other tests of this module move + /// on other threads as they make and drop sections of their own. + fn in_a_child(name: &str) -> bool { + const CHILD: &str = "LEONIDA_TEST_COMMIT_CHILD"; + if std::env::var_os(CHILD).is_some() { + return false; + } + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", name, "--test-threads=1", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let said = String::from_utf8_lossy(&out.stdout) + String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "the child failed:\n{said}"); + assert!(said.contains("1 passed"), "the child ran no test:\n{said}"); + true + } + + /// (`LEONIDA_SECTION_COMMIT`) Commit is charged by the section, when a + /// page of it is first shown, not for the allocation: allocating two + /// sections of 32 MiB charges nothing, mapping a page of one charges + /// that section, a second page of it nothing more, and the free of the + /// pages and the end of their views give it back. + /// + /// Measured in a child process of this test binary, this test alone in + /// it: the counter is the whole process's, and the other tests of this + /// module on other threads make and drop sections of their own, charged + /// by the section or page by page as they ask (one maps 12.5 MiB at + /// once), which in the same process moved it by 15-50 MiB between two + /// readings (`cargo test -p leonida-hle --lib modules::xmem`: failed 6 + /// runs of 10 so; the whole lib suite happened to keep them apart). + #[test] + fn a_committed_section_is_charged_when_first_touched() { + if in_a_child("modules::xmem::tests::a_committed_section_is_charged_when_first_touched") { + return; + } + const SECTION: u64 = 32 << 20; + const SLACK: u64 = 8 << 20; + let was = (TEST_SECTION_PAGES.replace(Some(SECTION as usize / PAGE)), TEST_SECTION_COMMIT.replace(Some(true))); + let before = shared_commit(); + let pages = allocate(2 * SECTION as usize / PAGE); + let allocated = shared_commit(); + let base = XMemVirtualAlloc(std::ptr::null_mut(), 2 * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!base.is_null()); + assert_eq!(XMemMapPhysicalPages(base, 1, pages[1..].as_ptr()), base); + let touched = shared_commit(); + let next = base.wrapping_byte_add(PAGE); + assert_eq!(XMemMapPhysicalPages(next, 1, pages[2..].as_ptr()), next); + let again = shared_commit(); + assert_eq!(XMemMapPhysicalPages(base, 2, std::ptr::null()), base); + assert_eq!(XMemFreePhysicalPages(pages.len(), pages.as_ptr()), 1); + let freed = shared_commit(); + TEST_SECTION_PAGES.set(was.0); + TEST_SECTION_COMMIT.set(was.1); + let mb = |a: u64, b: u64| (b as i64 - a as i64) >> 20; + let said = format!( + "MiB of shared commit since the start: allocated {}, a page shown {}, another {}, freed {}", + mb(before, allocated), + mb(before, touched), + mb(before, again), + mb(before, freed) + ); + assert!(allocated < before + SLACK, "nothing charged for the allocation: {said}"); + assert!(touched >= before + SECTION - SLACK / 2 && touched < before + SECTION + SLACK, "one section charged: {said}"); + assert!(again < touched + SLACK, "nothing more for a second page of it: {said}"); + assert!(freed < before + SLACK, "given back: {said}"); + } + /// Four pages mapped one by one, then at one stretch: one view in place /// of the four placeholders their views left (joined first). #[test] @@ -3030,15 +5044,669 @@ mod tests { assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); } + /// The host's reservation from the top of the range (not in windows-sys' + /// memory module). + const MEM_TOP_DOWN: u32 = 0x10_0000; + + /// One test at a time reserves from the top ([`MEM_TOP_DOWN`]): each + /// would take what another just released, before that one looked. + fn top_down_turn() -> MutexGuard<'static, ()> { + static TURN: Mutex<()> = Mutex::new(()); + TURN.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// The title releases a reservation of 64 KiB pages it mapped and + /// unmapped page by page: the placeholders those left (`holes`) go + /// with it; nothing stale is left to be taken for the next + /// reservation's own (`change`, `map`). A 32-bit reservation released + /// leaves the record of the 32-bit heap. + #[test] + fn a_released_reservation_leaves_no_holes_behind() { + use windows_sys::Win32::System::Memory::MEM_FREE; + let _turn = top_down_turn(); + let pages = allocate(4); + // (From the top: the other tests take the lowest free addresses, + // and would take these the moment they are free.) + let base = XMemVirtualAlloc(std::ptr::null_mut(), 4 * PAGE, MEM_RESERVE | MEM_TOP_DOWN | PAGES_64K, 0, PAGE_READWRITE); + assert!(!base.is_null()); + let at = |page: usize| base as usize + page * PAGE; + for (index, page) in pages.iter().enumerate() { + assert_eq!(XMemMapPhysicalPages(at(index) as *mut c_void, 1, page), at(index) as *mut c_void); + } + for index in 0..4 { + assert_eq!(XMemMapPhysicalPages(at(index) as *mut c_void, 1, std::ptr::null()), at(index) as *mut c_void); + } + let holes = || (0..4).filter(|&k| physical().holes.contains_key(&at(k))).collect::<Vec<_>>(); + assert_eq!(holes(), [0, 1, 2, 3], "each page left a placeholder of its own"); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1); + let kept: Vec<usize> = (0..4).filter(|&k| query(at(k) as *const c_void).host.State != MEM_FREE).collect(); + assert_eq!(kept, [], "all of the reservation is released"); + assert!(holes().is_empty(), "no hole is left"); + assert!(!PLACEHOLDERS.lock().unwrap().contains_key(&(base as usize))); + assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); + + let low = XMemVirtualAlloc(std::ptr::null_mut(), 4 * PAGE, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, GRAPHICS | ADDRESS_32BIT, PAGE_NOACCESS); + assert!(!low.is_null()); + assert!(LOW_RESERVATIONS.lock().unwrap().iter().any(|r| r.0 == low as usize)); + assert_eq!(title_virtual_free(low, 0, MEM_RELEASE), 1); + assert!(!LOW_RESERVATIONS.lock().unwrap().iter().any(|r| r.0 == low as usize), "the 32-bit heap's record goes with it"); + } + + /// The runtime's splits of a placeholder reservation (each piece an + /// allocation of its own on the host) are joined for the title's + /// release, but not past the title's own split: what it split off it + /// sees as a reservation of its own, released by its own call; and + /// what it joins again is one again. + #[test] + fn a_release_joins_the_runtimes_pieces_and_not_the_titles() { + use windows_sys::Win32::System::Memory::MEM_FREE; + let _turn = top_down_turn(); + let pages = allocate(1); + // (From the top, as in the test above.) + let base = XMemVirtualAlloc(std::ptr::null_mut(), 4 * PAGE, MEM_RESERVE | MEM_TOP_DOWN | PAGES_64K, 0, PAGE_READWRITE); + assert!(!base.is_null()); + let at = |page: usize| base as usize + page * PAGE; + let free = |page: usize| query(at(page) as *const c_void).host.State == MEM_FREE; + // The title splits off its last two pages. + assert_eq!(title_virtual_free(at(2) as *mut c_void, 2 * PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), 1); + // The runtime splits the first two as it maps and unmaps. + assert_eq!(XMemMapPhysicalPages(at(1) as *mut c_void, 1, pages.as_ptr()), at(1) as *mut c_void); + assert_eq!(XMemMapPhysicalPages(at(1) as *mut c_void, 1, std::ptr::null()), at(1) as *mut c_void); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1); + assert_eq!([free(0), free(1), free(2), free(3)], [true, true, false, false], "the title's first piece, all of it"); + assert_eq!(title_virtual_free(at(2) as *mut c_void, 0, MEM_RELEASE), 1); + assert!(free(2) && free(3)); + + // What the title split and joined again is one reservation again. + let base = XMemVirtualAlloc(std::ptr::null_mut(), 4 * PAGE, MEM_RESERVE | MEM_TOP_DOWN | PAGES_64K, 0, PAGE_READWRITE); + assert!(!base.is_null()); + let at = |page: usize| base as usize + page * PAGE; + let free = |page: usize| query(at(page) as *const c_void).host.State == MEM_FREE; + assert_eq!(title_virtual_free(at(2) as *mut c_void, 2 * PAGE, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), 1); + assert_eq!(title_virtual_free(base, 4 * PAGE, MEM_RELEASE | 1 /* MEM_COALESCE_PLACEHOLDERS */), 1); + assert_eq!(XMemMapPhysicalPages(at(1) as *mut c_void, 1, pages.as_ptr()), at(1) as *mut c_void); + assert_eq!(XMemMapPhysicalPages(at(1) as *mut c_void, 1, std::ptr::null()), at(1) as *mut c_void); + assert_eq!(title_virtual_free(base, 0, MEM_RELEASE), 1); + assert_eq!([free(0), free(1), free(2), free(3)], [true; 4], "all of it"); + assert_eq!(XMemFreePhysicalPages(1, pages.as_ptr()), 1); + } + + /// A number as the title gives it back: kept as 21 bits of + /// `number >> 4` and rebuilt with `<< 4`. + fn kept(number: usize) -> usize { + (number >> 4 & 0x1f_ffff) << 4 + } + + /// (`Numbers`) Past 124 GiB of allocations the counter reaches 2^25: the + /// numbers given out then must still be ones the title keeps whole, so + /// they are freed ones. Given from the counter, `2^25 + n` came back from + /// the title as `n`, no page below 2^20 and another allocation's above. + #[test] + fn page_numbers_stay_in_the_titles_21_bits() { + assert_eq!(kept(END_NUMBER + FIRST_NUMBER), FIRST_NUMBER, "what the counter gave past 2^25 came back as another page"); + let mut numbers = Numbers::new(); + // A long session: all but two numbers given out, the first four freed. + numbers.next = END_NUMBER - 2 * FRAMES; + for k in 0..4 { + numbers.give(FIRST_NUMBER + k * FRAMES); + } + let given = numbers.take(4, FIRST_NUMBER..END_NUMBER).expect("numbers left"); + for &number in &given { + assert_eq!(kept(number), number, "the title keeps {number:#x} as {:#x}", kept(number)); + } + assert_eq!(given, [END_NUMBER - 32, END_NUMBER - 16, FIRST_NUMBER, FIRST_NUMBER + 16], "the counter's last, then the lowest freed"); + // Two freed numbers left: three are refused, and none is taken for it. + assert_eq!(numbers.take(3, FIRST_NUMBER..END_NUMBER), None); + assert_eq!(numbers.take(2, FIRST_NUMBER..END_NUMBER), Some(vec![FIRST_NUMBER + 32, FIRST_NUMBER + 48])); + assert_eq!(numbers.take(1, FIRST_NUMBER..END_NUMBER), None, "every number is live"); + // A number given twice, or never given out, is not two numbers. + numbers.give(FIRST_NUMBER); + numbers.give(FIRST_NUMBER); + numbers.give(END_NUMBER); + numbers.give(FIRST_NUMBER + 1); + assert_eq!(numbers.take(2, FIRST_NUMBER..END_NUMBER), None); + assert_eq!(numbers.take(1, FIRST_NUMBER..END_NUMBER), Some(vec![FIRST_NUMBER])); + } + + /// (`Numbers`) Allocating and freeing in a loop, far past the numbers + /// there are (a space of 64 here, 2^21 - 2^16 for the title): every + /// number stays in the space, none is live twice, and freed ones are + /// given out again. + #[test] + fn page_numbers_come_back_round_after_round() { + const SPACE: usize = 64; + let end = FIRST_NUMBER + SPACE * FRAMES; + let mut numbers = Numbers::new(); + let mut live: Vec<Vec<usize>> = Vec::new(); + let (mut given, mut seed) = (0usize, 12345u32); + for _ in 0..10_000 { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + let n = 1 + (seed >> 16) as usize % 12; + let held: usize = live.iter().map(Vec::len).sum(); + match numbers.take(n, FIRST_NUMBER..end) { + Some(got) => { + assert!(held + n <= SPACE); + given += n; + live.push(got); + } + None => assert!(held + n > SPACE, "{n} refused with {held} of {SPACE} live"), + } + if live.len() > 3 || seed & 0x100 != 0 { + let k = (seed >> 9) as usize % live.len().max(1); + if k < live.len() { + live.swap_remove(k).into_iter().for_each(|number| numbers.give(number)); + } + } + let mut all: Vec<usize> = live.iter().flatten().copied().collect(); + assert!(all.iter().all(|&number| (FIRST_NUMBER..end).contains(&number) && number % FRAMES == 0)); + all.sort_unstable(); + let before = all.len(); + all.dedup(); + assert_eq!(all.len(), before, "a number live twice"); + } + assert!(given > 100 * SPACE, "only {given} numbers given out"); + } + + /// (`Numbers` through `XMemAllocatePhysicalPages` and + /// `XMemFreePhysicalPages`) A title allocating and freeing in a loop, far + /// round the numbers there are (a space of 8 numbers, `TEST_NUMBERS`, in + /// place of the title's 2^21 - 2^16): every number given is in the space + /// and has its page, none is live twice, and an allocation that fits in + /// what is not live is given; one that does not is count 0 and FALSE, + /// with nothing taken; a section that cannot be made gives its numbers + /// back. With the free not giving its numbers back, the space ran dry + /// with none live. + #[test] + fn page_numbers_come_back_through_the_calls() { + const SPACE: usize = 8; + let space = { + let mut table = page_table_mut(); + let got = table.numbers.take(SPACE, FIRST_NUMBER..END_NUMBER).expect("numbers left"); + got.iter().for_each(|&number| table.numbers.give(number)); + got[0]..got[SPACE - 1] + FRAMES + }; + assert_eq!(space.len(), SPACE * FRAMES, "consecutive numbers"); + let was = TEST_NUMBERS.replace(Some((space.start, space.end))); + let try_allocate = |n: usize| -> Option<Vec<usize>> { + let (mut pages, mut given) = (vec![0; n], n); + let ok = XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()); + assert_eq!(given, if ok == 1 { n } else { 0 }, "count says what was given"); + (ok == 1).then_some(pages) + }; + let mut live: Vec<Vec<usize>> = Vec::new(); + let (mut given, mut seed) = (0usize, 777u32); + for round in 0..400 { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + let n = 1 + (seed >> 16) as usize % 3; + let held: usize = live.iter().map(Vec::len).sum(); + match try_allocate(n) { + Some(got) => { + assert!(held + n <= SPACE, "round {round}"); + given += n; + live.push(got); + } + None => assert!(held + n > SPACE, "round {round}: {n} refused with {held} of {SPACE} live"), + } + if live.len() > 2 || seed & 0x100 != 0 { + let k = (seed >> 9) as usize % live.len().max(1); + if k < live.len() { + let gone = live.swap_remove(k); + assert_eq!(XMemFreePhysicalPages(gone.len(), gone.as_ptr()), 1); + } + } + let mut all: Vec<usize> = live.iter().flatten().copied().collect(); + assert!(all.iter().all(|&number| space.contains(&number)), "round {round}: a number out of the space"); + assert!(all.iter().all(|number| page_table().pages.contains_key(number)), "round {round}: a number with no page"); + all.sort_unstable(); + let before = all.len(); + all.dedup(); + assert_eq!(all.len(), before, "round {round}: a number live twice"); + } + assert!(given > 20 * SPACE, "only {given} numbers given out"); + for gone in live.drain(..) { + assert_eq!(XMemFreePhysicalPages(gone.len(), gone.as_ptr()), 1); + } + // All live: the next is refused; one freed is the one given. + let all = try_allocate(SPACE).expect("the whole space"); + assert_eq!(try_allocate(1), None, "every number is live"); + assert_eq!(XMemFreePhysicalPages(1, all[3..].as_ptr()), 1); + assert_eq!(try_allocate(1), Some(vec![all[3]])); + assert_eq!(XMemFreePhysicalPages(SPACE, all.as_ptr()), 1); + // A section refused: the numbers are free again. + TEST_NO_SECTION.set(true); + assert_eq!(try_allocate(SPACE), None); + TEST_NO_SECTION.set(false); + let all = try_allocate(SPACE).expect("the numbers came back"); + assert_eq!(XMemFreePhysicalPages(SPACE, all.as_ptr()), 1); + TEST_NUMBERS.set(was); + // A narrower range leaves out what is freed outside it. + let mut numbers = Numbers::new(); + numbers.next = FIRST_NUMBER + 200 * FRAMES; + [5, 70, 71, 130].iter().for_each(|&k| numbers.give(FIRST_NUMBER + k * FRAMES)); + let range = FIRST_NUMBER + 64 * FRAMES..FIRST_NUMBER + 128 * FRAMES; + assert_eq!(numbers.take(3, range.clone()), None); + assert_eq!(numbers.take(2, range), Some(vec![FIRST_NUMBER + 70 * FRAMES, FIRST_NUMBER + 71 * FRAMES])); + assert_eq!(numbers.take(3, FIRST_NUMBER..numbers.next), None); + assert_eq!(numbers.take(2, FIRST_NUMBER..numbers.next), Some(vec![FIRST_NUMBER + 5 * FRAMES, FIRST_NUMBER + 130 * FRAMES])); + } + + /// Whether the host has `len` bytes from `at` in our working set, page by + /// 4 KiB page: how many are. + fn resident(at: usize, len: usize) -> usize { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + let mut info: Vec<PSAPI_WORKING_SET_EX_INFORMATION> = (0..len / 4096) + .map(|k| PSAPI_WORKING_SET_EX_INFORMATION { + VirtualAddress: (at + k * 4096) as *mut c_void, + // SAFETY: plain data, filled by the host. + VirtualAttributes: unsafe { std::mem::zeroed() }, + }) + .collect(); + let bytes = (info.len() * size_of::<PSAPI_WORKING_SET_EX_INFORMATION>()) as u32; + // SAFETY: `info` holds `bytes` bytes of entries. + assert_ne!(unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), info.as_mut_ptr().cast(), bytes) }, 0); + // SAFETY: the host filled every entry; bit 0 is "valid". + info.iter().filter(|i| unsafe { i.VirtualAttributes.Flags } & 1 != 0).count() + } + + /// `Spare::waiting`, which spares an allocation [`PHYSICAL`] when it is + /// 0, counts the pages in every `Kept::freed` (read under one lock, so + /// whatever the other tests do). + fn waiting_is_counted() { + let table = page_table(); + let freed: usize = table.spare.sections.values().map(Kept::waiting).sum(); + assert_eq!(table.spare.waiting, freed, "Spare::waiting"); + } + + /// What [`Spare::take`] gave before it kept its runs by length: every + /// run of waiting pages no view shows, all sorted longest first (then + /// by section and first page), and the first `n` pages of them in that + /// order. `waiting` is by section key. + fn every_run_sorted( + waiting: &BTreeMap<usize, std::collections::BTreeSet<usize>>, + n: usize, + shown: impl Fn(usize, usize) -> bool, + ) -> Vec<(usize, usize)> { + let mut runs: Vec<(usize, usize, usize)> = Vec::new(); + for (&key, pages) in waiting { + let mut run: Option<(usize, usize)> = None; + for &index in pages.iter().filter(|&&index| !shown(key, index)) { + match &mut run { + Some((first, len)) if *first + *len == index => *len += 1, + _ => { + runs.extend(run.map(|(first, len)| (len, key, first))); + run = Some((index, 1)); + } + } + } + runs.extend(run.map(|(first, len)| (len, key, first))); + } + runs.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)).then(a.2.cmp(&b.2))); + let mut out = Vec::new(); + for (len, key, first) in runs { + let k = len.min(n - out.len()); + out.extend((first..first + k).map(|index| (key, index))); + } + out + } + + /// (`Spare::take`) An allocation looks at the waiting pages it needs to + /// find the longest runs, not at every page waiting. A streaming title + /// keeps a few pages of many sections and frees the rest a page here and + /// there: 64 sections of 64 pages with every other page waiting (2,048 + /// runs of one), and one run of 16 in another. Asked for 4 pages, the + /// allocation looks at the 16 of the long run and gives the first 4 of + /// them; then a page at a time, 11 of the 12 left of it and then single + /// pages (its last among them, by section), each looking at the run it + /// gives from and no other. (Before, each looked at all 2,064 and sorted + /// the 2,049 runs, under the page table lock.) The pages given are those + /// the old walk gave ([`every_run_sorted`]). + #[test] + fn spare_take_looks_at_the_runs_it_gives() { + let key = |section: &Arc<Section>| Arc::as_ptr(section) as usize; + let mut spare = Spare::default(); + // Sections never made by the host (lazy): nothing of its to let go. + let sections: Vec<Arc<Section>> = (0..65).map(|_| Arc::new(Section::new(64, true).expect("lazy"))).collect(); + let mut waiting: BTreeMap<usize, std::collections::BTreeSet<usize>> = BTreeMap::new(); + for (s, section) in sections.iter().enumerate() { + spare.made(section); + let freed: Vec<usize> = if s == 64 { (8..24).collect() } else { (0..64).step_by(2).collect() }; + for &index in &freed { + let slice = Slice { section: section.clone(), index }; + assert!(spare.freed(&slice), "the section has other pages with numbers"); + spare.wait(&[slice]); + waiting.entry(key(section)).or_default().insert(index); + } + } + assert_eq!(spare.waiting, 64 * 32 + 16); + let long = key(§ions[64]); + let looked = std::cell::Cell::new(0); + let shown = |_: usize, _: usize| { + looked.set(looked.get() + 1); + false + }; + let mut take = |n: usize, waiting: &mut BTreeMap<usize, std::collections::BTreeSet<usize>>| { + let before = every_run_sorted(waiting, n, |_, _| false); + looked.set(0); + let given: Vec<(usize, usize)> = spare.take(n, shown).iter().map(|s| (key(&s.section), s.index)).collect(); + assert_eq!(given, before, "the pages the old walk gave"); + for &(section, index) in &given { + waiting.get_mut(§ion).expect("waits").remove(&index); + } + (given, looked.get()) + }; + let (given, looked_at) = take(4, &mut waiting); + assert_eq!(given, (8..12).map(|index| (long, index)).collect::<Vec<_>>()); + assert_eq!(looked_at, 16, "the long run's pages"); + for index in 12..23 { + let (given, looked_at) = take(1, &mut waiting); + assert_eq!(given, [(long, index)]); + assert_eq!(looked_at, 24 - index, "what is left of the long run"); + } + for _ in 0..101 { + let (given, looked_at) = take(1, &mut waiting); + assert_eq!(given.len(), 1); + assert_eq!(looked_at, 1, "one run of one page"); + } + assert_eq!(spare.waiting, 64 * 32 - 100); + } + + /// (`Spare::take`) Whatever waits and whatever views show, the pages + /// given are those the old walk gave ([`every_run_sorted`]): rounds of + /// pseudo-random frees, sections closing when their last page goes, + /// allocations with some pages shown, and failed ones put back. + #[test] + fn spare_take_gives_what_every_run_sorted_gave() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |below: usize| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 33) as usize % below + }; + let key = |section: &Arc<Section>| Arc::as_ptr(section) as usize; + let mut spare = Spare::default(); + let sections: Vec<Arc<Section>> = (0..8).map(|_| Arc::new(Section::new(96, true).expect("lazy"))).collect(); + sections.iter().for_each(|section| spare.made(section)); + let by_key: HashMap<usize, Arc<Section>> = sections.iter().map(|s| (key(s), s.clone())).collect(); + // Pages with a number, and pages waiting, by section key. + let mut live: BTreeMap<usize, std::collections::BTreeSet<usize>> = + sections.iter().map(|s| (key(s), (0..96).collect())).collect(); + let mut waiting: BTreeMap<usize, std::collections::BTreeSet<usize>> = BTreeMap::new(); + for round in 0..2_000 { + // Some pages freed, a section's last closing it. + for _ in 0..next(24) { + let Some((§ion, pages)) = live.iter().nth(next(live.len().max(1))) else { break }; + let Some(&index) = pages.iter().nth(next(pages.len())) else { continue }; + let slice = Slice { section: by_key[§ion].clone(), index }; + live.get_mut(§ion).expect("live").remove(&index); + if spare.freed(&slice) { + spare.wait(&[slice]); + waiting.entry(section).or_default().insert(index); + } else { + assert!(live[§ion].is_empty(), "round {round}: closed with its last page"); + live.remove(§ion); + waiting.remove(§ion); + } + } + assert_eq!(spare.waiting, waiting.values().map(|pages| pages.len()).sum::<usize>(), "round {round}"); + // An allocation, with a few pages shown. + let picked: std::collections::BTreeSet<(usize, usize)> = (0..next(12)) + .filter_map(|_| { + let (§ion, pages) = waiting.iter().nth(next(waiting.len().max(1)))?; + Some((section, *pages.iter().nth(next(pages.len().max(1)))?)) + }) + .collect(); + let shown = |section: usize, index: usize| picked.contains(&(section, index)); + let n = 1 + next(40); + let before = every_run_sorted(&waiting, n, shown); + let given = spare.take(n, shown); + let pages: Vec<(usize, usize)> = given.iter().map(|s| (key(&s.section), s.index)).collect(); + assert_eq!(pages, before, "round {round}: n {n}"); + if next(4) == 0 { + spare.put_back(&given); + } else { + for &(section, index) in &pages { + waiting.get_mut(§ion).expect("waits").remove(&index); + live.get_mut(§ion).expect("open").insert(index); + } + } + waiting.retain(|_, pages| !pages.is_empty()); + if live.is_empty() { + break; + } + } + } + + /// (`Spare`, `LEONIDA_PHYSICAL_REUSE`) A title that keeps one page of an + /// allocation and frees the rest, then asks for pages again, round after + /// round: the freed pages are given out again, read as zeros, and no + /// section is made for them; what a view still shows is not given out + /// until unmapped, and pages that go out together are one run (one + /// view). While they wait, the written ones are not resident. The last + /// page of the section freed, the section closes: its commit goes back to + /// the host. (As before, every round was a new section, and the four of + /// the first stayed committed for as long as its one page lived.) + #[test] + fn freed_pages_are_given_out_again_until_their_section_goes() { + let was = TEST_REUSE.replace(true); + let first = allocate(4); + let slice = |page: usize| page_table().pages.get(&page).cloned().expect("known page"); + let section = Arc::downgrade(&slice(first[0]).section); + let ours = |page: usize| section.upgrade().is_some_and(|s| Arc::ptr_eq(&slice(page).section, &s)); + assert!(write_physical(&first, 0, &vec![0xcd; 4 * PAGE]), "written: committed"); + // The last page stays mapped after its free. + let base = XMemVirtualAlloc(std::ptr::null_mut(), 4 * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!base.is_null()); + assert_eq!(XMemMapPhysicalPages(base, 1, &first[3]), base); + assert_eq!(XMemFreePhysicalPages(3, first[1..].as_ptr()), 1); + waiting_is_counted(); + let window = slice(first[0]).section.window.get().copied().expect("the section's own view"); + assert_eq!(resident(window + PAGE, 2 * PAGE), 0, "freed pages no view shows are let go"); + assert_eq!(resident(window + 3 * PAGE, PAGE), PAGE / 4096, "the page still shown is not"); + for round in 0..50 { + let again = allocate(2); + waiting_is_counted(); + assert!(again.iter().all(|&page| ours(page)), "round {round}: the freed pages, not a new section"); + assert_eq!(again.iter().map(|&page| slice(page).index).collect::<Vec<_>>(), [1, 2], "round {round}"); + assert!(again.iter().all(|&page| page_bytes(page).iter().all(|&b| b == 0)), "round {round}: zeros"); + assert!(write_physical(&again, 0, &vec![round as u8 + 1; 2 * PAGE])); + assert_eq!(XMemFreePhysicalPages(2, again.as_ptr()), 1); + waiting_is_counted(); + } + // SAFETY: still mapped: what it showed, as the title left it. + assert_eq!(unsafe { base.cast::<u8>().read() }, 0xcd); + assert_eq!(XMemMapPhysicalPages(base, 1, std::ptr::null()), base); + let again = allocate(3); + assert!(again.iter().all(|&page| ours(page))); + let lengths: Vec<usize> = runs(&again, 0, 3 * PAGE).expect("known pages").iter().map(|&(_, n)| n).collect(); + assert_eq!(lengths, [3], "one run"); + assert_eq!(XMemFreePhysicalPages(3, again.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, first.as_ptr()), 1); + assert!(section.upgrade().is_none(), "the section is closed"); + waiting_is_counted(); + // Nothing of it waits any more: a new allocation is a new section. + let other = allocate(2); + assert_eq!(slice(other[0]).index, 0); + // A page written only through a view of our own (DirectStorage's, + // with no window in place) is zeroed too. + View::map(&slice(other[1]), 1).expect("mapped").bytes().fill(0xab); + assert_eq!(XMemFreePhysicalPages(1, other[1..].as_ptr()), 1); + let again = allocate(1); + assert_eq!(slice(again[0]).index, 1); + assert!(page_bytes(again[0]).iter().all(|&b| b == 0), "zeros"); + assert_eq!(XMemFreePhysicalPages(1, again.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, other.as_ptr()), 1); + TEST_REUSE.set(was); + } + + /// (`Spare` with `LEONIDA_SECTION_COMMIT`) Freed pages of sections made + /// at their first page are given out again as those of sections made + /// with their allocation are. A title writes half of a committed section + /// of 32 MiB, frees that half and asks for as many pages again: it gets + /// the same pages, zeroed, with no section made and no commit charged + /// for them (made anew, they would be a section charged 16 MiB when written), + /// and no page asks for a commit of its own; while they wait they are + /// not resident. Freed pages of a section none of whose pages was + /// touched have nothing to zero or let go: the free and their giving out + /// again leave the section unmade, and the first page written makes it, + /// and charges it, as for pages that never waited. The last pages freed, + /// both sections close and give their commit back. + /// + /// Measured in a child process ([`in_a_child`]), as + /// `a_committed_section_is_charged_when_first_touched` is. + #[test] + fn a_committed_sections_freed_pages_are_given_out_again_with_no_new_charge() { + if in_a_child("modules::xmem::tests::a_committed_sections_freed_pages_are_given_out_again_with_no_new_charge") { + return; + } + const SECTION: u64 = 32 << 20; + const SLACK: u64 = 8 << 20; + const PER: usize = SECTION as usize / PAGE; + const HALF: usize = PER / 2; + let was = (TEST_SECTION_PAGES.replace(Some(PER)), TEST_SECTION_COMMIT.replace(Some(true)), TEST_REUSE.replace(true)); + let (made, commits) = (SECTIONS_MADE.get(), COMMITS.get()); + let slice = |page: usize| page_table().pages.get(&page).cloned().expect("known page"); + let before = shared_commit(); + let pages = allocate(2 * PER); + let allocated = shared_commit(); + let (first, second) = (slice(pages[0]).section, slice(pages[PER]).section); + assert!(first.lazy && second.lazy, "sections of 32 MiB made at their first page"); + assert_eq!(SECTIONS_MADE.get() - made, 0, "none made with the allocation"); + // Half of the first section written (as DirectStorage writes, through + // its window), the page after it mapped and kept. + assert!(write_physical(&pages[..HALF], 0, &vec![0xcd; HALF * PAGE])); + let base = XMemVirtualAlloc(std::ptr::null_mut(), PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!base.is_null()); + assert_eq!(XMemMapPhysicalPages(base, 1, &pages[HALF]), base); + assert_eq!(SECTIONS_MADE.get() - made, 1, "the first section made at its first page"); + let touched = shared_commit(); + // The written half freed, and three pages of the second section. + assert_eq!(XMemFreePhysicalPages(HALF, pages.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(3, pages[PER + 1..].as_ptr()), 1); + waiting_is_counted(); + assert!(second.host.get().is_none(), "nothing of a section never made to zero or let go: still not made"); + let window = first.window.get().copied().expect("the first section's own view"); + assert_eq!(resident(window, HALF * PAGE), 0, "the written pages freed are let go"); + let freed = shared_commit(); + // As many pages asked for again: those waiting, the longest run first. + let again = allocate(HALF + 3); + waiting_is_counted(); + assert_eq!(SECTIONS_MADE.get() - made, 1, "no section made for them"); + let key = |section: &Arc<Section>| Arc::as_ptr(section) as usize; + let given: Vec<(usize, usize)> = again.iter().map(|&page| slice(page)).map(|s| (key(&s.section), s.index)).collect(); + let freed_pages = (0..HALF).map(|index| (key(&first), index)).chain((1..4).map(|index| (key(&second), index))); + assert_eq!(given, freed_pages.collect::<Vec<_>>(), "the freed pages are given out again"); + // SAFETY: the first section's own view; its first HALF pages are + // committed, and ours until the title has their numbers. + let bytes = unsafe { std::slice::from_raw_parts(window as *const u8, HALF * PAGE) }; + assert!(bytes.iter().all(|&b| b == 0), "the written pages given out again read zeros"); + assert!(second.host.get().is_none(), "nothing written in the second section to zero: still not made"); + assert!(write_physical(&again[..HALF], 0, &vec![0xab; HALF * PAGE])); + let rewritten = shared_commit(); + // A page given out again of the section never made: made, and + // charged, when first written; the rest of the page reads zeros. + assert!(write_physical(&again[HALF..HALF + 1], 0, &[7])); + assert_eq!(SECTIONS_MADE.get() - made, 2, "the second section made at its first page written"); + let page = page_bytes(again[HALF]); + assert!(page[0] == 7 && page[1..].iter().all(|&b| b == 0), "the page written, the rest zeros"); + let second_touched = shared_commit(); + assert_eq!(COMMITS.get() - commits, 0, "no page asked to be committed on its own"); + // Everything freed: both sections close. + assert_eq!(XMemMapPhysicalPages(base, 1, std::ptr::null()), base); + let live: Vec<usize> = + pages[HALF..PER].iter().chain(&pages[PER..PER + 1]).chain(&pages[PER + 4..]).chain(&again).copied().collect(); + assert_eq!(live.len(), 2 * PER); + assert_eq!(XMemFreePhysicalPages(live.len(), live.as_ptr()), 1); + let sections = (Arc::downgrade(&first), Arc::downgrade(&second)); + drop((first, second)); + assert!(sections.0.upgrade().is_none() && sections.1.upgrade().is_none(), "both sections closed"); + waiting_is_counted(); + let gone = shared_commit(); + TEST_SECTION_PAGES.set(was.0); + TEST_SECTION_COMMIT.set(was.1); + TEST_REUSE.set(was.2); + let mb = |a: u64, b: u64| (b as i64 - a as i64) >> 20; + let said = format!( + "MiB of shared commit since the start: allocated {}, half written {}, freed {}, given out again and written {}, \ + the second section written {}, all freed {}", + mb(before, allocated), + mb(before, touched), + mb(before, freed), + mb(before, rewritten), + mb(before, second_touched), + mb(before, gone) + ); + assert!(allocated < before + SLACK, "nothing charged for the allocation: {said}"); + assert!(touched >= before + SECTION - SLACK / 2 && touched < before + SECTION + SLACK, "one section charged: {said}"); + assert!(freed + SLACK > touched && freed < touched + SLACK, "the section lives, its commit with it: {said}"); + assert!(rewritten < touched + SLACK, "nothing more for the pages given out again: {said}"); + assert!( + second_touched >= rewritten + SECTION - SLACK / 2 && second_touched < rewritten + SECTION + SLACK, + "the second section charged at its first page written: {said}" + ); + assert!(gone < before + SLACK, "given back: {said}"); + } + + /// (`XMemFreePhysicalPages`, `LEONIDA_PHYSICAL_DISCARD`) A free while a + /// mapping call of another thread is between taking a view out of + /// `Shown` and noting again what stays of it ([`unmap`] when the title + /// maps over part of a larger view, [`change`]; done here by hand with + /// PHYSICAL held, as they do it): the page still mapped keeps its bytes, + /// as `XMemFreePhysicalPages` promises. With `Shown` read without + /// PHYSICAL the free saw no view, let the page go, and the title's view + /// read zeros. + #[test] + fn a_free_keeps_a_page_a_mapping_call_puts_back() { + let was = TEST_REUSE.replace(true); + let pages = allocate(2); + assert!(write_physical(&pages, 0, &vec![0xcd; 2 * PAGE])); + let base = XMemVirtualAlloc(std::ptr::null_mut(), PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!base.is_null()); + assert_eq!(XMemMapPhysicalPages(base, 1, &pages[1]), base); + let slice = page_table().pages.get(&pages[1]).cloned().expect("known page"); + let free = { + let physical = physical(); + shown_mut().forget(base as usize, PAGE, &slice); + let numbers = pages[1..].to_vec(); + let free = std::thread::spawn(move || XMemFreePhysicalPages(1, numbers.as_ptr())); + // As far as it gets without PHYSICAL. + let until = std::time::Instant::now() + std::time::Duration::from_millis(500); + while !free.is_finished() && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + shown_mut().note(base as usize, PAGE, &slice); + drop(physical); + free + }; + assert_eq!(free.join().expect("freed"), 1); + // SAFETY: still mapped. + assert_eq!(unsafe { base.cast::<u8>().read() }, 0xcd, "the page still mapped keeps its bytes"); + assert_eq!(XMemMapPhysicalPages(base, 1, std::ptr::null()), base); + assert_eq!(XMemFreePhysicalPages(1, pages.as_ptr()), 1); + TEST_REUSE.set(was); + } + #[test] fn section_sizes_come_from_the_switch() { - assert_eq!(pages_per_section(None), usize::MAX); + // Unset: sections of 16 MiB (docs/findings.md, `LEONIDA_SECTION_MB`). + assert_eq!(pages_per_section(None), 256); assert_eq!(pages_per_section(Some("0")), usize::MAX); assert_eq!(pages_per_section(Some("off")), usize::MAX); assert_eq!(pages_per_section(Some("2")), 32); assert_eq!(pages_per_section(Some(" 16 ")), 256); } + /// (`LEONIDA_SECTION_COMMIT`) Sections are made committed only when + /// asked: unset, the pool's sections are reserved and committed page by + /// page, whose commit charge runs of the title have been measured with; + /// a whole section's charge for each touched is not measured yet. + #[test] + fn committed_sections_are_asked_for() { + use std::ffi::OsStr; + assert!(!lazy_commit_asked(None), "unset: reserved sections, as measured"); + assert!(!lazy_commit_asked(Some(OsStr::new("0")))); + assert!(!lazy_commit_asked(Some(OsStr::new("")))); + assert!(lazy_commit_asked(Some(OsStr::new("1")))); + } + /// (`LEONIDA_SECTION_MB`) An allocation of more pages than a section /// holds is several sections: mapped at one stretch it is a view a /// section, and the bytes are in the pages their numbers say, whichever diff --git a/d3d12/crates/leonida-hle/src/test_alloc.rs b/d3d12/crates/leonida-hle/src/test_alloc.rs new file mode 100644 index 0000000000..dc0036f1ad --- /dev/null +++ b/d3d12/crates/leonida-hle/src/test_alloc.rs @@ -0,0 +1,46 @@ +//! The test binary's allocator: the system's, telling the tests that count +//! allocations of each block (`modules::apu`'s packet test and +//! `modules::dstorage`'s worker buffer test). A process has one allocator, so +//! they share it. Not with the features under which leonida-gpu installs an +//! allocator of its own. + +use std::alloc::{GlobalAlloc, Layout, System}; + +use crate::modules::{apu, dstorage}; + +fn note(size: usize) { + apu::tests::counting::note(size); + dstorage::tests::watched_blocks::note(size); +} + +struct Counting; + +// SAFETY: every call goes to the system's allocator unchanged; only counters +// are kept beside it. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + note(layout.size()); + // SAFETY: the caller's contract, passed on. + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + note(layout.size()); + // SAFETY: the caller's contract, passed on. + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn realloc(&self, at: *mut u8, layout: Layout, size: usize) -> *mut u8 { + note(size); + // SAFETY: the caller's contract, passed on. + unsafe { System.realloc(at, layout, size) } + } + + unsafe fn dealloc(&self, at: *mut u8, layout: Layout) { + // SAFETY: the caller's contract, passed on. + unsafe { System.dealloc(at, layout) } + } +} + +#[global_allocator] +static HEAP: Counting = Counting; diff --git a/d3d12/crates/leonida-loader/src/crash.rs b/d3d12/crates/leonida-loader/src/crash.rs index 6eeebaf10e..e5218a1680 100644 --- a/d3d12/crates/leonida-loader/src/crash.rs +++ b/d3d12/crates/leonida-loader/src/crash.rs @@ -17,8 +17,8 @@ use windows_sys::Win32::Foundation::{ }; use windows_sys::Win32::System::Diagnostics::Debug::{ - AddVectoredExceptionHandler, CONTEXT, EXCEPTION_POINTERS, M128A, RtlLookupFunctionEntry, - RtlVirtualUnwind, SetUnhandledExceptionFilter, UNW_FLAG_NHANDLER, + AddVectoredExceptionHandler, CONTEXT, EXCEPTION_POINTERS, IMAGE_RUNTIME_FUNCTION_ENTRY, M128A, + RtlLookupFunctionEntry, RtlVirtualUnwind, SetUnhandledExceptionFilter, UNW_FLAG_NHANDLER, }; use windows_sys::Win32::System::LibraryLoader::{ GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, @@ -646,7 +646,7 @@ fn unwind(context: CONTEXT) -> Vec<u64> { // SAFETY: writes the current thread's stack bounds. unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) }; let mut frames = Vec::with_capacity(MAX_FRAMES); - unwind_into(context, low, high, &mut frames); + unwind_into(context, low, high, &mut frames, None); frames } @@ -654,10 +654,26 @@ fn unwind(context: CONTEXT) -> Vec<u64> { #[repr(C, align(16))] pub(crate) struct Aligned16(pub(crate) CONTEXT); +/// One step of a walk in place of the plain [`virtual_unwind`]: unwinds the +/// context by the function table entry of the image at the given base, or +/// returns `false` to end the walk there with the frames found so far. +pub(crate) type Step<'a> = + &'a mut dyn FnMut(&mut CONTEXT, u64, *const IMAGE_RUNTIME_FUNCTION_ENTRY) -> bool; + /// [`unwind`] for any thread of the process, its stack being `low..high`; /// pushes no more than `MAX_FRAMES`, so it does not allocate when `frames` /// has that capacity (another thread may be suspended holding the heap). -pub(crate) fn unwind_into(context: CONTEXT, low: usize, high: usize, frames: &mut Vec<u64>) { +/// The system unwinder reads wherever the unwind data and the registers +/// point, inside the stack or not: a walk of another thread passes `step` +/// to unwind each frame with those reads bounded or checked first, and to +/// stop where one would fault. +pub(crate) fn unwind_into( + context: CONTEXT, + low: usize, + high: usize, + frames: &mut Vec<u64>, + mut step: Option<Step>, +) { // `RtlVirtualUnwind` writes the context with 16-byte aligned stores, and // windows-sys declares `CONTEXT` without that alignment: a by-value copy on // the stack can land 8 bytes off and fault (seen in a debug build). @@ -678,20 +694,16 @@ pub(crate) fn unwind_into(context: CONTEXT, low: usize, high: usize, frames: &mu context.Rip = unsafe { (rsp as *const u64).read() }; context.Rsp += 8; } else { - let (mut data, mut frame) = (null_mut(), 0); - // SAFETY: `entry` belongs to `image`; the context is our copy. - unsafe { - RtlVirtualUnwind( - UNW_FLAG_NHANDLER, - image, - context.Rip, - entry, - context, - &mut data, - &mut frame, - null_mut(), - ) + let unwound = match step.as_mut() { + Some(step) => step(context, image, entry), + None => { + virtual_unwind(context, image, entry); + true + } }; + if !unwound { + break; + } } if context.Rip == 0 { break; @@ -700,6 +712,30 @@ pub(crate) fn unwind_into(context: CONTEXT, low: usize, high: usize, frames: &mu } } +/// Unwinds `context` one frame by `entry` of the image at `image` with +/// `RtlVirtualUnwind`, which reads wherever the unwind data and the +/// registers point. `context` must be 16-byte aligned, as an [`Aligned16`]'s. +pub(crate) fn virtual_unwind( + context: &mut CONTEXT, + image: u64, + entry: *const IMAGE_RUNTIME_FUNCTION_ENTRY, +) { + let (mut data, mut frame) = (null_mut(), 0); + // SAFETY: `entry` belongs to `image`; the context is the caller's copy. + unsafe { + RtlVirtualUnwind( + UNW_FLAG_NHANDLER, + image, + context.Rip, + entry, + context, + &mut data, + &mut frame, + null_mut(), + ) + }; +} + /// `module+rva`, or the bare address. pub fn locate(address: usize) -> String { module_of(address).unwrap_or_else(|| format!("{address:#x}")) diff --git a/d3d12/crates/leonida-loader/src/profile.rs b/d3d12/crates/leonida-loader/src/profile.rs index 62e2a16878..9167bd40d0 100644 --- a/d3d12/crates/leonida-loader/src/profile.rs +++ b/d3d12/crates/leonida-loader/src/profile.rs @@ -21,7 +21,7 @@ use windows_sys::Win32::System::Threading::{ }; use crate::crash::locate; -use crate::stacks::{frames_of, name_of, other_threads, start_of}; +use crate::stacks::{Unwinder, frames_of, name_of, other_threads, start_of}; /// The threads sampled: those that ran most since they were last chosen. const BUSIEST: usize = 28; @@ -68,13 +68,19 @@ pub fn profile_on_schedule(phase: fn() -> u32) { let start = Instant::now(); let all: Vec<_> = list.split(';').filter_map(asked).collect(); std::thread::spawn(move || { + let mut unwinder = Unwinder::new(); for one in all { - profile(one, start, phase); + profile(one, start, phase, &mut unwinder); } }); } -fn profile((from, to, every, file): (Duration, Duration, Duration, String), start: Instant, phase: fn() -> u32) { +fn profile( + (from, to, every, file): (Duration, Duration, Duration, String), + start: Instant, + phase: fn() -> u32, + unwinder: &mut Unwinder, +) { std::thread::sleep(from.saturating_sub(start.elapsed())); eprintln!("Leonida: the profile begins"); let mut threads: HashMap<u32, Thread> = HashMap::new(); @@ -93,7 +99,7 @@ fn profile((from, to, every, file): (Duration, Duration, Duration, String), star *phases.entry(phase).or_default() += 1; for id in &chosen { if let Some(t) = threads.get_mut(id) { - let (frames, _) = frames_of(t.handle); + let (frames, _) = frames_of(t.handle, unwinder); t.samples += 1; if !frames.is_empty() { *counts.entry((*id, phase, frames)).or_default() += 1; diff --git a/d3d12/crates/leonida-loader/src/stacks.rs b/d3d12/crates/leonida-loader/src/stacks.rs index dcfd1eb5bc..acfc67c8df 100644 --- a/d3d12/crates/leonida-loader/src/stacks.rs +++ b/d3d12/crates/leonida-loader/src/stacks.rs @@ -3,23 +3,28 @@ //! [`dump_stacks_on_schedule`], to find what a title waits on. use std::ffi::c_void; +use std::ptr::null_mut; use windows_sys::Wdk::System::Threading::{ NtQueryInformationThread, ThreadBasicInformation, ThreadQuerySetWin32StartAddress, }; use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, LocalFree}; use windows_sys::Win32::System::Diagnostics::Debug::{ - CONTEXT, CONTEXT_FULL_AMD64, GetThreadContext, + CONTEXT, CONTEXT_FULL_AMD64, GetThreadContext, IMAGE_RUNTIME_FUNCTION_ENTRY, UNW_FLAG_NHANDLER, }; use windows_sys::Win32::System::Diagnostics::ToolHelp::{ CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, }; +use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress}; use windows_sys::Win32::System::Threading::{ GetCurrentProcessId, GetCurrentThreadId, GetThreadDescription, OpenThread, ResumeThread, SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME, }; -use crate::crash::{MAX_FRAMES, locate, unwind_into}; +use crate::crash::{MAX_FRAMES, locate, unwind_into, virtual_unwind}; + +mod unwind_check; +use unwind_check::{Check, Images}; /// Reads `LEONIDA_STACKS` and, if set, starts a thread that prints every /// thread's stack at each listed time (seconds from now). @@ -30,13 +35,124 @@ pub fn dump_stacks_on_schedule() { let times = schedule(&list); let start = std::time::Instant::now(); std::thread::spawn(move || { + let mut unwinder = Unwinder::new(); for at in times { std::thread::sleep(at.saturating_sub(start.elapsed())); - dump_stacks(); + dump_stacks_with(&mut unwinder); } }); } +/// `RtlVirtualUnwind2` (ntdll, exported from Windows 10 build 20348 and in +/// Windows 11; windows-sys does not declare it). It is `RtlVirtualUnwind` +/// with the stack's bounds: every read of the stack (the prologue's saved +/// registers, `rsp` taken from the frame register, an epilogue's pops, the +/// return address) must be within `*low_limit..=*high_limit - 8` (`- 16` for +/// a saved xmm register), or it returns `STATUS_BAD_STACK` instead of +/// reading. With a null `machine_frame_unwound` it tells an epilogue at +/// every frame, as `RtlVirtualUnwind` does; `unwind_flags` must be 0. +type VirtualUnwind2 = unsafe extern "system" fn( + handler_type: u32, + image_base: u64, + control_pc: u64, + function_entry: *const IMAGE_RUNTIME_FUNCTION_ENTRY, + context: *mut CONTEXT, + machine_frame_unwound: *mut u8, + handler_data: *mut *mut c_void, + establisher_frame: *mut u64, + context_pointers: *mut c_void, + low_limit: *const u64, + high_limit: *const u64, + handler_routine: *mut *mut c_void, + unwind_flags: u32, +) -> i32; + +/// How a walk of another thread unwinds a frame that has unwind data: +/// `RtlVirtualUnwind2` limited to the thread's stack where ntdll exports it, +/// after [`Check::tables`]; else `RtlVirtualUnwind` after the whole replay +/// of [`Check::step`]. It keeps the regions of loaded images the checks +/// found readable for the next walks, so each thread that walks has its own. +pub(crate) struct Unwinder { + unwind: Option<VirtualUnwind2>, + images: Images, +} + +impl Unwinder { + /// Looks `RtlVirtualUnwind2` up and asks for the loader's notice of + /// unloads. `GetProcAddress` may take the loader's lock, which a + /// suspended thread may hold, so this runs before any thread is + /// suspended: once, as the thread that walks starts. + pub(crate) fn new() -> Self { + let ntdll: Vec<u16> = "ntdll.dll\0".encode_utf16().collect(); + // SAFETY: ntdll is in every process and stays; both names end in + // NUL; the export has the signature of `VirtualUnwind2`. + let unwind = unsafe { + let module = GetModuleHandleW(ntdll.as_ptr()); + if module.is_null() { + None + } else { + GetProcAddress(module, c"RtlVirtualUnwind2".as_ptr().cast()) + .map(|f| std::mem::transmute::<_, VirtualUnwind2>(f)) + } + }; + Unwinder { + unwind, + images: Images::new(), + } + } + + /// Unwinds `context` of a thread whose stack is `low..high` one frame + /// by `entry` of the image at `image` with `unwind` (see [`Unwinder`]); + /// `false` ends the walk there. + fn step( + unwind: Option<VirtualUnwind2>, + check: &mut Check, + context: &mut CONTEXT, + image: u64, + entry: *const IMAGE_RUNTIME_FUNCTION_ENTRY, + (low, high): (usize, usize), + ) -> bool { + let Some(unwind) = unwind else { + if !check.step(context, image, entry) { + return false; + } + virtual_unwind(context, image, entry); + return true; + }; + // The limits cover only the stack. The entry, the unwind info, the + // code at `rip` and, for a jump there, the entry and unwind info + // where it goes are read unchecked (any of them that runs into an + // unreadable page faults it), and an unknown unwind code is taken + // for another one. + if !check.tables(context, image, entry) { + return false; + } + let (low, high) = (low as u64, high as u64); + let (mut data, mut frame, mut routine) = (null_mut(), 0, null_mut()); + // SAFETY: `entry` belongs to `image` and what it leads to outside + // the stack is readable (checked above); `context` is 16-byte + // aligned (`unwind_into`'s); the limits bound its stack reads. + let status = unsafe { + unwind( + UNW_FLAG_NHANDLER, + image, + context.Rip, + entry, + context, + null_mut(), + &mut data, + &mut frame, + null_mut(), + &low, + &high, + &mut routine, + 0, + ) + }; + status >= 0 + } +} + /// The times in a `LEONIDA_STACKS` list (seconds, comma-separated), in /// order. Negative times are now; times no `Duration` holds (`inf`, `NaN`, /// `1e20`) are left out instead of panicking the dump thread. @@ -101,6 +217,10 @@ pub(crate) fn other_threads() -> Vec<u32> { /// only while its context is read and unwound into a buffer allocated /// beforehand (it may hold the heap lock). pub fn dump_stacks() { + dump_stacks_with(&mut Unwinder::new()); +} + +fn dump_stacks_with(unwinder: &mut Unwinder) { let ids = other_threads(); eprintln!("Leonida: stacks of {} threads", ids.len()); for id in ids { @@ -115,7 +235,7 @@ pub fn dump_stacks() { if thread.is_null() { continue; } - let (frames, (priority, base, affinity)) = frames_of(thread); + let (frames, (priority, base, affinity)) = frames_of(thread, unwinder); eprintln!( " thread {id} \"{}\" start {} priority {priority} (base {base}) affinity {affinity:#x}", name_of(thread), @@ -129,9 +249,10 @@ pub fn dump_stacks() { } } -/// The thread's frames and its current and base scheduling priority (0-31). -pub(crate) fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32, usize)) { - let mut frames = Vec::with_capacity(MAX_FRAMES); +/// The basic information of a thread the caller has suspended and its +/// committed stack, `low..high`; `None` without its TEB. It allocates +/// nothing. +fn stack_of(thread: HANDLE) -> Option<(BasicInfo, usize, usize)> { let mut info: BasicInfo = BasicInfo { exit_status: 0, teb: std::ptr::null(), @@ -140,12 +261,6 @@ pub(crate) fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32, usize)) { priority: 0, base_priority: 0, }; - // Suspended first: a running thread may exit and free its TEB between - // the query and the read below. - // SAFETY: a thread of this process that is not this one. - if unsafe { SuspendThread(thread) } == u32::MAX { - return (frames, (0, 0, 0)); - } // SAFETY: writes `info`, whose layout and size are the system's. let status = unsafe { NtQueryInformationThread( @@ -157,13 +272,29 @@ pub(crate) fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32, usize)) { ) }; if status != 0 || info.teb.is_null() { - // SAFETY: suspended above. - unsafe { ResumeThread(thread) }; - return (frames, (0, 0, 0)); + return None; } // SAFETY: the TEB of a suspended thread of this process: its NT_TIB // holds the stack base at +8 and the stack limit at +0x10. let (high, low) = unsafe { (info.teb.add(1).read(), info.teb.add(2).read()) }; + Some((info, low, high)) +} + +/// The thread's frames, unwound by `unwinder`, and its current and base +/// scheduling priority (0-31). +pub(crate) fn frames_of(thread: HANDLE, unwinder: &mut Unwinder) -> (Vec<u64>, (i32, i32, usize)) { + let mut frames = Vec::with_capacity(MAX_FRAMES); + // Suspended first: a running thread may exit and free its TEB between + // the query and the read in `stack_of`. + // SAFETY: a thread of this process that is not this one. + if unsafe { SuspendThread(thread) } == u32::MAX { + return (frames, (0, 0, 0)); + } + let Some((info, low, high)) = stack_of(thread) else { + // SAFETY: suspended above. + unsafe { ResumeThread(thread) }; + return (frames, (0, 0, 0)); + }; // SAFETY: zeroed is a valid CONTEXT. let mut context = Aligned(unsafe { std::mem::zeroed() }); context.0.ContextFlags = CONTEXT_FULL_AMD64; @@ -172,13 +303,26 @@ pub(crate) fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32, usize)) { // the unwinder's own. unsafe { if GetThreadContext(thread, &mut context.0) != 0 { - unwind_into(context.0, low, high, &mut frames); + walk(context.0, low, high, unwinder, &mut frames); } ResumeThread(thread); } (frames, (info.priority, info.base_priority, info.affinity)) } +/// Unwinds `context` of another thread, whose stack is `low..high`, into +/// `frames`. The thread may be anywhere: each step's reads are bounded or +/// checked before the system unwinder makes them. It allocates nothing +/// when `frames` has room for `MAX_FRAMES`. +fn walk(context: CONTEXT, low: usize, high: usize, unwinder: &mut Unwinder, frames: &mut Vec<u64>) { + let unwind = unwinder.unwind; + let mut check = Check::new(low, high, &mut unwinder.images); + let mut step = |context: &mut CONTEXT, image, entry| { + Unwinder::step(unwind, &mut check, context, image, entry, (low, high)) + }; + unwind_into(context, low, high, frames, Some(&mut step)); +} + pub(crate) fn start_of(thread: HANDLE) -> usize { let mut start = 0usize; // SAFETY: writes one pointer-sized start address. @@ -211,6 +355,482 @@ pub(crate) fn name_of(thread: HANDLE) -> String { #[cfg(test)] mod tests { use super::*; + use std::sync::atomic::{AtomicU8, Ordering}; + use std::time::{Duration, Instant}; + use windows_sys::Win32::System::Diagnostics::Debug::{ + FlushInstructionCache, IMAGE_RUNTIME_FUNCTION_ENTRY, IMAGE_RUNTIME_FUNCTION_ENTRY_0, + RtlAddFunctionTable, RtlCaptureContext, RtlDeleteFunctionTable, + }; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_NOACCESS, PAGE_READWRITE, + VirtualAlloc, VirtualFree, VirtualProtect, + }; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetCurrentThreadStackLimits}; + + /// Set in the child processes of + /// `walks_stop_where_a_wrong_function_table_would_fault` to the case run. + const WRONG_TABLE: &str = "LEONIDA_TEST_WRONG_TABLE"; + /// Set beside `WRONG_TABLE` to how the child walks: `limits` + /// (`RtlVirtualUnwind2`) or `replay`. + const UNWINDER: &str = "LEONIDA_TEST_UNWINDER"; + + /// Sets up `rbp` as the frame register, then loads a small odd number + /// into it (no stack address: nothing is mapped below 64 KiB), keeping + /// the frame in `r11`. Code whose function table entry is wrong about it + /// looks like this to the unwinder. + const PROLOGUE: [&[u8]; 4] = [ + &[0x55], // push rbp + &[0x48, 0x89, 0xe5], // mov rbp, rsp + &[0x49, 0x89, 0xeb], // mov r11, rbp + &[0xbd, 0x01, 0x80, 0x00, 0x00], // mov ebp, 0x8001 + ]; + + /// At 0x00: waits in the body, `rbp` still wrong, for the byte at `rcx`. + const FRAMED: [&[u8]; 5] = [ + &[0x80, 0x39, 0x00], // 0x0c: cmp byte [rcx], 0 + &[0x74, 0xfb], // je 0x0c + &[0x4c, 0x89, 0xdd], // mov rbp, r11 + &[0x5d], // pop rbp + &[0xc3], // ret + ]; + + /// At 0x20: calls `WAIT`, which returns to an epilogue that restores + /// `rsp` from the frame register. + const CALLER: [&[u8]; 4] = [ + &[0xe8, 0x0f, 0x00, 0x00, 0x00], // 0x2c: call 0x40 + &[0x48, 0x8d, 0x65, 0x00], // 0x31: lea rsp, [rbp] + &[0x5d], // pop rbp + &[0xc3], // ret + ]; + + /// At 0x40, without a function table entry: waits for the byte at + /// `rcx`, then puts the caller's frame back in `rbp`. + const WAIT: [&[u8]; 4] = [ + &[0x80, 0x39, 0x00], // 0x40: cmp byte [rcx], 0 + &[0x74, 0xfb], // je 0x40 + &[0x4c, 0x89, 0xdd], // mov rbp, r11 + &[0xc3], // ret + ]; + + /// The unwind info of `FRAMED` and `CALLER`: version 1, a 4-byte + /// prologue, 2 codes, `rbp` the frame register at offset 0; `SET_FPREG` + /// at 4, `PUSH_NONVOL rbp` at 1. + const INFO: [u8; 8] = [0x01, 4, 2, 0x05, 4, 0x03, 1, 0x50]; + + /// `INFO` with code 7 in place of `SET_FPREG`, which no unwind info of + /// version 1 has. + const UNKNOWN: [u8; 8] = [0x01, 4, 2, 0x05, 4, 0x07, 1, 0x50]; + + /// `INFO` as version 2, without epilogue codes. + const INFO_V2: [u8; 8] = [0x02, 4, 2, 0x05, 4, 0x03, 1, 0x50]; + + /// Version 1, a 1-byte prologue, no frame register: `PUSH_NONVOL rbp` + /// at 1. + const PUSHED: [u8; 8] = [0x01, 1, 1, 0x00, 1, 0x50, 0, 0]; + + /// At 0x180, without a function table entry: waits for the byte at + /// `rcx`, then returns for its caller as well, so the code the caller's + /// call returns to is never run: drops its own return address and pops + /// the `rbp` the caller pushed. + const WAIT_POP: [&[u8]; 5] = [ + &[0x80, 0x39, 0x00], // 0x180: cmp byte [rcx], 0 + &[0x74, 0xfb], // je 0x180 + &[0x58], // pop rax + &[0x5d], // pop rbp + &[0xc3], // ret + ]; + + /// The cases whose caller calls `WAIT_POP`: the caller's prologue, the + /// code its call returns to and the offset of its unwind info. The + /// caller ends where the code page does. In each the unwinder unwinds + /// the caller through its prologue, where the bytes alone would read as + /// an epilogue, or reads past the page. + fn returns_to(case: &str) -> Option<(&'static [&'static [u8]], &'static [u8], usize)> { + Some(match case { + // `pop rbp; ret` in a function with version 2 unwind info, whose + // epilogues the unwinder finds from their codes. + "v2" => (&PROLOGUE[..], &[0x5d, 0xc3][..], 0x140), + // `add r12, 8` before `pop rbp; ret`: the unwinder takes only + // `add rsp` there. + "add" => ( + &PROLOGUE[..], + &[0x49, 0x83, 0xc4, 0x08, 0x5d, 0xc3][..], + 0x80, + ), + // `jmp r11`: an indirect jump ends an epilogue only with REX.W. + "jmp" => (&PROLOGUE[..], &[0x41, 0xff, 0xe3][..], 0x80), + // A sound frame whose `pop rbp; jmp rel32` has its displacement + // on the page that cannot be read. + "jump" => (&PROLOGUE[..1], &[0x5d, 0xe9][..], 0x160), + // A sound frame whose `pop rbp` is followed by a jump (rel32 or + // rel8) to `TARGET`, another function whose unwind info cannot + // be read: the unwinder reads it to tell whether the jump leaves + // the function. + "tail" => ( + &PROLOGUE[..1], + &[0x5d, 0xe9, 0x80, 0xff, 0xff, 0xff][..], + 0x160, + ), + "tail8" => (&PROLOGUE[..1], &[0x5d, 0xeb, 0x80][..], 0x160), + _ => return None, + }) + } + + /// Where the jumps of the `tail` cases go, 0x80 below the end of the + /// code page they end. + const TARGET: u32 = 0xf80; + + fn entry(begin: u32, end: u32, unwind: u32) -> IMAGE_RUNTIME_FUNCTION_ENTRY { + IMAGE_RUNTIME_FUNCTION_ENTRY { + BeginAddress: begin, + EndAddress: end, + Anonymous: IMAGE_RUNTIME_FUNCTION_ENTRY_0 { UnwindData: unwind }, + } + } + + /// Runs one case of `walks_stop_where_a_wrong_function_table_would_fault` + /// in this (child) process: a thread waits in the code above while its + /// stack is walked again and again by `unwinder`, and every walk must + /// end at the expected frames. A walk that lets the unwinder read where + /// `rbp` points (or at the unwind info, in the `info` case) faults the + /// process. + fn walk_wrong_table(case: &str, mut unwinder: Unwinder) { + // SAFETY: a fresh two-page allocation of our own. + let page = unsafe { + VirtualAlloc( + std::ptr::null(), + 0x2000, + MEM_COMMIT | MEM_RESERVE, + PAGE_READWRITE, + ) + } + .cast::<u8>(); + assert!(!page.is_null()); + let base = page as u64; + let mut code = vec![0xcc; 0x1000]; + let mut put = |at: usize, bytes: &[u8]| code[at..at + bytes.len()].copy_from_slice(bytes); + put(0x00, &[&PROLOGUE[..], &FRAMED[..]].concat().concat()); + put(0x20, &[&PROLOGUE[..], &CALLER[..]].concat().concat()); + put(0x40, &WAIT.concat()); + put(0x80, &INFO); + put(0x100, &UNKNOWN); + put(0x140, &INFO_V2); + put(0x160, &PUSHED); + put(0x180, &WAIT_POP.concat()); + // In the `info` case the entries' unwind info is on a page that + // cannot be read; in the `code` case it has a code the unwinder + // does not know. + let unwind = match case { + "info" => 0x1080, + "code" => 0x100, + _ => 0x80, + }; + let mut table = vec![entry(0x00, 0x16, unwind), entry(0x20, 0x37, unwind)]; + if case.starts_with("tail") { + table.push(entry(TARGET, TARGET + 0x10, 0x1080)); + } + let returns = returns_to(case).map(|(prologue, after, info)| { + let prologue = prologue.concat(); + let start = 0x1000 - prologue.len() - 5 - after.len(); + let call = start + prologue.len(); + let to = (0x180 - (call + 5) as i32).to_le_bytes(); + put(start, &[&prologue[..], &[0xe8], &to, after].concat()); + table.push(entry(start as u32, 0x1000, info as u32)); + (start as u64, 0x1000 - after.len() as u64) + }); + let mut old = 0; + // SAFETY: writes and protects the pages allocated above, then + // registers `table`, which outlives its registration. + unsafe { + std::ptr::copy_nonoverlapping(code.as_ptr(), page, code.len()); + std::ptr::copy_nonoverlapping(INFO.as_ptr(), page.add(0x1080), INFO.len()); + assert!(VirtualProtect(page.cast(), 0x1000, PAGE_EXECUTE_READ, &mut old) != 0); + assert!(VirtualProtect(page.add(0x1000).cast(), 0x1000, PAGE_NOACCESS, &mut old) != 0); + FlushInstructionCache(GetCurrentProcess(), page.cast(), 0x1000); + assert!(RtlAddFunctionTable( + table.as_ptr(), + table.len() as u32, + base + )); + } + // Where the thread is called, where it waits, and the frames above + // the one it waits in. + let (start, waits, callers) = match (case, returns) { + (_, Some((start, returns))) => (start, 0x180..0x185, vec![base + returns]), + ("frame" | "info" | "code", _) => (0x00, 0x0c..0x11, vec![]), + ("epilogue", _) => (0x20, 0x40..0x45, vec![base + 0x31]), + _ => panic!("no case {case}"), + }; + let flag = std::sync::Arc::new(AtomicU8::new(0)); + let (tx, rx) = std::sync::mpsc::channel(); + let waiter = { + let flag = flag.clone(); + std::thread::spawn(move || { + // SAFETY: plain query. + tx.send(unsafe { GetCurrentThreadId() }).unwrap(); + // SAFETY: the code written above, which returns once the + // flag is set and keeps the registers the ABI asks it to. + let code: extern "system" fn(*const AtomicU8) = + unsafe { std::mem::transmute((base + start) as usize) }; + code(&*flag); + }) + }; + let id = rx.recv().unwrap(); + // SAFETY: a thread of this process. + let thread = unsafe { + OpenThread( + THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, + 0, + id, + ) + }; + assert!(!thread.is_null()); + let since = Instant::now(); + let mut seen = 0; + while seen < 200 && since.elapsed() < Duration::from_secs(10) { + let (frames, _) = frames_of(thread, &mut unwinder); + if frames + .first() + .is_some_and(|pc| waits.contains(&pc.wrapping_sub(base))) + { + seen += 1; + assert_eq!(frames[1..], callers[..], "{case}: {frames:#x?}"); + } + } + flag.store(1, Ordering::SeqCst); + waiter.join().unwrap(); + // SAFETY: opened, registered and allocated above; the thread is gone. + unsafe { + CloseHandle(thread); + RtlDeleteFunctionTable(table.as_ptr()); + VirtualFree(page.cast(), 0, MEM_RELEASE); + } + assert!(seen > 0, "{case}: the thread was never seen waiting"); + } + + /// Walking a thread whose registers its unwind data does not describe + /// stops at the frames found so far instead of faulting: in the body of + /// a function with the frame register, in an epilogue that restores + /// `rsp` from it, with unwind info that cannot be read and with an + /// unwind code the unwinder does not know; at code that reads as an + /// epilogue to the bytes alone but is unwound through the prologue + /// (`returns_to`); and at a jump whose displacement, or whose target's + /// unwind info, cannot be read. Each case runs in a child process, since + /// without the check the walk faults it, once with `RtlVirtualUnwind2` + /// and its limits (where ntdll has it) and once with the replay that + /// stands in for them where it does not. + #[test] + fn walks_stop_where_a_wrong_function_table_would_fault() { + if let Ok(case) = std::env::var(WRONG_TABLE) { + let unwinder = match std::env::var(UNWINDER).as_deref() { + Ok("limits") => Unwinder::new(), + _ => replay(), + }; + walk_wrong_table(&case, unwinder); + return; + } + let name = "stacks::tests::walks_stop_where_a_wrong_function_table_would_fault"; + let cases = [ + "frame", "epilogue", "info", "code", "v2", "add", "jmp", "jump", "tail", "tail8", + ]; + let mut unwinders = vec!["replay"]; + if limits().is_some() { + unwinders.push("limits"); + } + for unwinder in unwinders { + for case in cases { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", name, "--test-threads=1"]) + .env(WRONG_TABLE, case) + .env(UNWINDER, unwinder) + .output() + .unwrap(); + let said = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success() && said.contains("1 passed"), + "{case} ({unwinder}): the child ended with {:#x}\n{said}{}", + out.status.code().unwrap_or(0) as u32, + String::from_utf8_lossy(&out.stderr) + ); + } + } + } + + /// `context` walked by plain `RtlVirtualUnwind` and by `unwinders`, the + /// replay's and `RtlVirtualUnwind2`'s with the limits (both made + /// beforehand), each into a buffer of `MAX_FRAMES` allocated beforehand: + /// nothing here allocates or looks anything up. + fn walk_three_ways( + context: CONTEXT, + (low, high): (usize, usize), + [replayed, limited]: &mut [Unwinder; 2], + walks: &mut [Vec<u64>; 3], + ) { + let [plain, replay, limits] = walks; + unwind_into(context, low, high, plain, None); + walk(context, low, high, replayed, replay); + walk(context, low, high, limited, limits); + } + + /// An unwinder that replays every step, as where ntdll has no + /// `RtlVirtualUnwind2`. + fn replay() -> Unwinder { + Unwinder { + unwind: None, + ..Unwinder::new() + } + } + + /// `Unwinder::new()`, which these tests need to have found + /// `RtlVirtualUnwind2` unless ntdll has no such export (before Windows 10 + /// build 20348). + fn limits() -> Option<Unwinder> { + let unwinder = Unwinder::new(); + if unwinder.unwind.is_none() { + eprintln!("no RtlVirtualUnwind2 in ntdll: only the replay is tested"); + } + unwinder.unwind.map(|_| unwinder) + } + + /// The check keeps every frame of a stack the unwinder walks soundly: + /// this thread's, through the test harness and the system's thread start. + #[test] + fn the_check_keeps_every_frame_of_a_sound_stack() { + // SAFETY: zeroed is a valid CONTEXT; it is captured here, and the + // frames above stay put while the walks below read them. + let mut context = Aligned(unsafe { std::mem::zeroed() }); + unsafe { RtlCaptureContext(&mut context.0) }; + let (mut low, mut high) = (0, 0); + // SAFETY: writes this thread's stack bounds. + unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) }; + let mut unwinders = [replay(), limits().unwrap_or_else(replay)]; + let mut walks = std::array::from_fn(|_| Vec::with_capacity(MAX_FRAMES)); + walk_three_ways(context.0, (low, high), &mut unwinders, &mut walks); + let [plain, replay, bounded] = walks; + assert!(plain.len() >= 4, "{plain:#x?}"); + assert_eq!(replay, plain); + assert_eq!(bounded, plain); + } + + /// A walk through loaded images asks `VirtualQuery` nothing once the + /// regions it reads are known, with the replay and with + /// `RtlVirtualUnwind2`: the profile walks a thread every few + /// milliseconds while it is suspended, and each query costs about a + /// microsecond. An unload elsewhere in the test process forgets the + /// regions, so a walk it overlaps is tried again. + #[test] + fn a_warm_walk_asks_the_system_nothing() { + use unwind_check::{QUERIES, UNLOADS}; + // SAFETY: zeroed is a valid CONTEXT; it is captured here, and the + // frames above stay put while the walks below read them. + let mut context = Aligned(unsafe { std::mem::zeroed() }); + unsafe { RtlCaptureContext(&mut context.0) }; + let (mut low, mut high) = (0, 0); + // SAFETY: writes this thread's stack bounds. + unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) }; + for mut unwinder in [Some(replay()), limits()].into_iter().flatten() { + let mut frames = Vec::with_capacity(MAX_FRAMES); + let asked = (0..5).find_map(|_| { + frames.clear(); + walk(context.0, low, high, &mut unwinder, &mut frames); + let (unloads, before) = (UNLOADS.load(Ordering::SeqCst), QUERIES.get()); + frames.clear(); + walk(context.0, low, high, &mut unwinder, &mut frames); + (UNLOADS.load(Ordering::SeqCst) == unloads).then(|| QUERIES.get() - before) + }); + assert!(frames.len() >= 4, "{frames:#x?}"); + assert_eq!(asked, Some(0)); + } + } + + /// The check keeps every frame of other threads walked as the profile + /// walks them: suspended, from their context, inside the stack their + /// TEB gives. Each sample is walked without the check, with the replay + /// and with `RtlVirtualUnwind2`'s limits under one suspension, for + /// threads in recursive Rust code that allocates and formats, sleeping, + /// allocating and yielding, and in file system calls. + #[test] + fn the_check_keeps_every_frame_of_other_threads() { + let mut unwinders = [replay(), limits().unwrap_or_else(replay)]; + fn deep(n: u32) -> String { + if n == 0 { + return format!("{:08x}", std::hint::black_box(n)); + } + let below = deep(n - 1); + format!("{below}{}", n % 10) + } + let works: [fn(); 4] = [ + || drop(std::hint::black_box(deep(40))), + || std::thread::sleep(Duration::from_millis(1)), + || { + drop(std::hint::black_box(vec![0u8; 4096])); + std::thread::yield_now(); + }, + || drop(std::fs::metadata(std::env::current_exe().unwrap())), + ]; + let stop = std::sync::Arc::new(AtomicU8::new(0)); + let (tx, rx) = std::sync::mpsc::channel(); + let workers: Vec<_> = works + .into_iter() + .map(|work| { + let (stop, tx) = (stop.clone(), tx.clone()); + std::thread::spawn(move || { + // SAFETY: plain query. + tx.send(unsafe { GetCurrentThreadId() }).unwrap(); + while stop.load(Ordering::Relaxed) == 0 { + work(); + } + }) + }) + .collect(); + let threads: Vec<HANDLE> = (0..works.len()) + .map(|_| { + let id = rx.recv().unwrap(); + // SAFETY: a thread of this process. + unsafe { + OpenThread( + THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, + 0, + id, + ) + } + }) + .collect(); + assert!(threads.iter().all(|thread| !thread.is_null())); + for _ in 0..250 { + for &thread in &threads { + // Allocated before the suspension: the thread may hold the + // heap's lock. + let mut walks = std::array::from_fn(|_| Vec::with_capacity(MAX_FRAMES)); + // SAFETY: zeroed is a valid CONTEXT. + let mut context = Aligned(unsafe { std::mem::zeroed() }); + context.0.ContextFlags = CONTEXT_FULL_AMD64; + // SAFETY: suspends, reads and resumes a thread of this + // process; nothing in between allocates. + unsafe { + assert!(SuspendThread(thread) != u32::MAX); + if let Some((_, low, high)) = stack_of(thread) + && GetThreadContext(thread, &mut context.0) != 0 + { + walk_three_ways(context.0, (low, high), &mut unwinders, &mut walks); + } + ResumeThread(thread); + } + let [plain, replay, bounded] = walks; + assert!(plain.len() >= 4, "{plain:#x?}"); + assert_eq!(replay, plain); + assert_eq!(bounded, plain); + } + } + stop.store(1, Ordering::Relaxed); + for worker in workers { + worker.join().unwrap(); + } + for thread in threads { + // SAFETY: opened above. + unsafe { CloseHandle(thread) }; + } + } #[test] fn another_threads_stack_unwinds_to_its_start() { @@ -231,7 +851,7 @@ mod tests { ) }; assert!(!thread.is_null()); - let (frames, _) = frames_of(thread); + let (frames, _) = frames_of(thread, &mut Unwinder::new()); // Waiting in the kernel, several frames down from the thread start. assert!(frames.len() >= 3, "{frames:?}"); assert!(start_of(thread) != 0); diff --git a/d3d12/crates/leonida-loader/src/stacks/unwind_check.rs b/d3d12/crates/leonida-loader/src/stacks/unwind_check.rs new file mode 100644 index 0000000000..5a880e9296 --- /dev/null +++ b/d3d12/crates/leonida-loader/src/stacks/unwind_check.rs @@ -0,0 +1,989 @@ +//! Whether `RtlVirtualUnwind` can take one step of another thread's stack +//! without faulting. +//! +//! The system unwinder believes the unwind data and the registers it is +//! given. It reads the stack at the frame register, at the saved-register +//! slots and at the return address without bounds, and raises on an unwind +//! code it does not know. A sampled thread suspended where its registers and +//! its unwind data do not agree (code that keeps something other than the +//! frame in the frame register, a return address taken from a stale stack +//! slot, a function table entry that is wrong) then faults the thread doing +//! the walk, which ends the process. [`Check::step`] replays what the +//! unwinder will read for one frame, on a copy of the registers, and says no +//! when any of it is outside that thread's stack or outside committed +//! readable memory, so the walk ends there with the frames found so far. +//! +//! Where ntdll has `RtlVirtualUnwind2`, the walk uses it instead with the +//! thread's stack as its limits, and it checks every read of the stack +//! itself. What it reads outside the stack it does not check, and it still +//! raises on what it does not know: [`Check::tables`] is the part of the +//! replay that covers those, the function table entry, the unwind info and +//! its chain, the code at `rip` read to tell an epilogue and, for a jump +//! there, the function table entry and unwind info of where it goes. +//! +//! Whether memory outside the stack is readable is asked of the system +//! (`VirtualQuery`, about a microsecond each). The regions of loaded images +//! found readable are kept in [`Images`] from walk to walk until an image is +//! unloaded, so walks through the images' own tables ask nothing once warm. +//! +//! The replay follows the unwinder's rules. An epilogue is told by its bytes +//! (`add rsp` or `lea rsp` from the frame register, pops, then `ret` or a +//! jump) and emulated forward. Otherwise the unwind codes whose prologue +//! offset has been reached are applied in order, through chained unwind +//! info, and the return address is read at the final `rsp`. Where the rule +//! cannot be told from what is read (a jump may or may not leave the +//! function, version 2 unwind info finds its epilogues from its own codes), +//! both ways are checked. + +use std::ffi::c_void; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU64, Ordering}; + +use windows_sys::Win32::System::Diagnostics::Debug::{ + CONTEXT, IMAGE_RUNTIME_FUNCTION_ENTRY, RtlLookupFunctionEntry, +}; +use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress}; +use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_IMAGE, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, + PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, + VirtualQuery, +}; + +/// Readable regions outside loaded images remembered during one walk. +const SPANS: usize = 16; +/// Readable regions of loaded images remembered from walk to walk: a few +/// per module on the stacks walked (code, read-only data, `.pdata`). +const IMAGE_SPANS: usize = 128; +/// Chained unwind info followed at most; the system raises past its own +/// limit, and real chains are one or two deep. +const CHAIN: usize = 16; +const UNW_FLAG_CHAININFO: u8 = 4; +/// `rsp` among the integer registers, in `CONTEXT` order. +const RSP: usize = 4; + +// The unwind codes (`UWOP_*`). +const PUSH_NONVOL: u8 = 0; +const ALLOC_LARGE: u8 = 1; +const ALLOC_SMALL: u8 = 2; +const SET_FPREG: u8 = 3; +const SAVE_NONVOL: u8 = 4; +const SAVE_NONVOL_FAR: u8 = 5; +/// Version 2 only: where an epilogue is, read by the unwinder itself. +const EPILOG: u8 = 6; +const SAVE_XMM128: u8 = 8; +const SAVE_XMM128_FAR: u8 = 9; +const PUSH_MACHFRAME: u8 = 10; + +/// Image unloads the loader has told of (`LdrRegisterDllNotification`). +pub(super) static UNLOADS: AtomicU64 = AtomicU64::new(0); + +#[cfg(test)] +thread_local! { + /// The `VirtualQuery` calls the checks on this thread have made. + pub(super) static QUERIES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +/// `LDR_DLL_NOTIFICATION_REASON_UNLOADED`. +const UNLOADED: u32 = 2; + +/// The loader's notice of a module loaded or unloaded. +type DllNotification = + unsafe extern "system" fn(reason: u32, data: *const c_void, context: *mut c_void); + +/// What `GetProcAddress` gives for an export. +type Export = unsafe extern "system" fn() -> isize; + +/// `LdrRegisterDllNotification` (ntdll; windows-sys does not declare it). +type RegisterDllNotification = unsafe extern "system" fn( + flags: u32, + notification: DllNotification, + context: *mut c_void, + cookie: *mut *mut c_void, +) -> i32; + +/// Counts an unload. The loader calls it on the thread that unloads, +/// holding its lock, while the image is still mapped +/// (`the_loader_tells_of_an_unload_before_it_unmaps_the_image`). +unsafe extern "system" fn unloaded(reason: u32, _: *const c_void, _: *mut c_void) { + if reason == UNLOADED { + UNLOADS.fetch_add(1, Ordering::SeqCst); + } +} + +/// Whether [`UNLOADS`] counts every unload: asks the loader for its notice +/// once. `GetProcAddress` and the registration take the loader's lock, so +/// this runs before any thread is suspended. +fn watch_unloads() -> bool { + static WATCHING: OnceLock<bool> = OnceLock::new(); + *WATCHING.get_or_init(|| { + let ntdll: Vec<u16> = "ntdll.dll\0".encode_utf16().collect(); + // SAFETY: ntdll is in every process and stays; both names end in + // NUL; the export has the signature of `RegisterDllNotification`, + // and `unloaded` stays for the life of the process. + unsafe { + let module = GetModuleHandleW(ntdll.as_ptr()); + if module.is_null() { + return false; + } + let name = c"LdrRegisterDllNotification"; + let Some(register) = GetProcAddress(module, name.as_ptr().cast()) else { + return false; + }; + let register = std::mem::transmute::<Export, RegisterDllNotification>(register); + let mut cookie = std::ptr::null_mut(); + register(0, unloaded, std::ptr::null_mut(), &mut cookie) >= 0 + } + }) +} + +/// Committed readable regions, `start..end`, filled in turn; empty ones +/// match nothing. `VirtualQuery` gives a region from the page asked about +/// to its end, so a lower page of a region already known widens it. +#[derive(Clone, Copy)] +struct Spans<const N: usize> { + spans: [(u64, u64); N], + next: usize, + /// The span found last, asked first. + last: usize, +} + +impl<const N: usize> Spans<N> { + const EMPTY: Self = Spans { + spans: [(0, 0); N], + next: 0, + last: 0, + }; + + /// The end of the span holding `at`. + fn find(&mut self, at: u64) -> Option<u64> { + let (start, end) = self.spans[self.last]; + if start <= at && at < end { + return Some(end); + } + let i = self.spans.iter().position(|&(s, e)| s <= at && at < e)?; + self.last = i; + Some(self.spans[i].1) + } + + fn add(&mut self, (start, end): (u64, u64)) { + if let Some(i) = self.spans.iter().position(|&(s, e)| e == end && s < e) { + let span = &mut self.spans[i]; + span.0 = span.0.min(start); + self.last = i; + return; + } + self.last = self.next % N; + self.spans[self.last] = (start, end); + self.next += 1; + } +} + +/// The regions of loaded images (`MEM_IMAGE`) found readable, kept by the +/// thread that walks from one walk to the next while the loader's notice +/// counts unloads, else for one walk. An unload ends them all, so a region +/// kept is never one the loader had unmapped when the walk began; one that +/// unmaps it while the walk runs is the race a query has with the read +/// after it. An image mapped as data is unmapped without the notice, but no +/// function table entry or unwind info leads into one. +pub(crate) struct Images { + spans: Spans<IMAGE_SPANS>, + /// [`UNLOADS`] when `spans` began; `None` without the notice. + unloads: Option<u64>, +} + +impl Images { + /// Asks for the loader's notice of unloads: before any thread is + /// suspended. + pub(crate) fn new() -> Self { + Images { + spans: Spans::EMPTY, + unloads: watch_unloads().then_some(u64::MAX), + } + } + + /// Forgets the regions if an image may have been unmapped since they + /// were found. + fn refresh(&mut self) { + let Some(seen) = self.unloads.as_mut() else { + self.spans = Spans::EMPTY; + return; + }; + let now = UNLOADS.load(Ordering::SeqCst); + if *seen != now { + *seen = now; + self.spans = Spans::EMPTY; + } + } +} + +/// One walk's check: the walked thread's stack and the readable memory +/// found so far. It allocates nothing and takes no lock, since the walked +/// thread is suspended and may hold the heap's. +pub(super) struct Check<'a> { + low: u64, + high: u64, + /// Readable regions outside loaded images, for this walk. + spans: Spans<SPANS>, + images: &'a mut Images, +} + +/// A function table entry, copied. +#[derive(Clone, Copy)] +struct Function { + begin: u32, + unwind: u32, +} + +/// An `UNWIND_INFO` found readable, its codes and chained entry included. +struct Info { + version: u8, + flags: u8, + prolog: u8, + count: usize, + frame_register: usize, + frame_offset: u64, + /// The address of the first unwind code. + codes: u64, + chained: Option<Function>, +} + +impl Info { + fn slot(&self, i: usize) -> u16 { + // SAFETY: `Check::info` found the `count` slots from `codes` + // readable; callers pass `i < count`. + unsafe { ((self.codes + 2 * i as u64) as *const u16).read_unaligned() } + } + + /// Slot `i`: its prologue offset, unwind code and operation info. + fn code(&self, i: usize) -> (u8, u8, u8) { + let slot = self.slot(i); + (slot as u8, (slot >> 8) as u8 & 0xf, (slot >> 12) as u8) + } + + /// The 32-bit operand in slots `i` and `i + 1`. + fn far(&self, i: usize) -> u64 { + u64::from(self.slot(i)) | u64::from(self.slot(i + 1)) << 16 + } + + /// Whether the `SET_FPREG` has run at `offset` into the prologue, the + /// codes walked one slot at a time when `by_slot`, else by their sizes + /// (`None` with no such code). + fn frame_set(&self, offset: u32, by_slot: bool) -> Option<bool> { + let mut i = 0; + while i < self.count { + let (at, op, op_info) = self.code(i); + if op == SET_FPREG { + return Some(offset >= u32::from(at)); + } + i += if by_slot { + 1 + } else { + slots(self.version, op, op_info)? + }; + } + None + } +} + +/// How the unwinder takes the code at `pc`. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Epilogue { + No, + Yes, + /// Pops then a jump: an epilogue when the jump leaves the function, a + /// rule this check does not follow, so both ways are checked. + Either, +} + +/// What an epilogue does to `rsp` before its pops. +#[derive(Clone, Copy)] +enum Unwound { + Nothing, + /// `add rsp, n`. + Add(i64), + /// `lea rsp, [frame register + n]`. + Lea(i64), +} + +/// The slots unwind code `op` takes, or `None` for one the unwinder does +/// not know (it raises on those). +fn slots(version: u8, op: u8, op_info: u8) -> Option<usize> { + match op { + PUSH_NONVOL | ALLOC_SMALL | SET_FPREG => Some(1), + PUSH_MACHFRAME if op_info <= 1 => Some(1), + ALLOC_LARGE if op_info == 0 => Some(2), + ALLOC_LARGE if op_info == 1 => Some(3), + SAVE_NONVOL | SAVE_XMM128 => Some(2), + SAVE_NONVOL_FAR | SAVE_XMM128_FAR => Some(3), + EPILOG if version == 2 => Some(1), + _ => None, + } +} + +/// The integer registers in `CONTEXT` order (`rax` = 0 ... `r15` = 15). +fn registers(context: &CONTEXT) -> [u64; 16] { + let c = context; + [ + c.Rax, c.Rcx, c.Rdx, c.Rbx, c.Rsp, c.Rbp, c.Rsi, c.Rdi, c.R8, c.R9, c.R10, c.R11, c.R12, + c.R13, c.R14, c.R15, + ] +} + +/// `pc`'s offset from the start of `function`, as the unwinder computes it. +fn prolog_offset(pc: u64, image: u64, function: Function) -> u32 { + pc.wrapping_sub(image) + .wrapping_sub(u64::from(function.begin)) as u32 +} + +impl<'a> Check<'a> { + /// A check for a thread whose stack is `low..high`, with the regions of + /// loaded images found readable before. + pub(super) fn new(low: usize, high: usize, images: &'a mut Images) -> Self { + images.refresh(); + Check { + low: low as u64, + high: high as u64, + spans: Spans::EMPTY, + images, + } + } + + /// Whether `RtlVirtualUnwind` can unwind `context` by `entry` of the + /// image at `image` reading only the thread's stack and readable memory. + pub(super) fn step( + &mut self, + context: &CONTEXT, + image: u64, + entry: *const IMAGE_RUNTIME_FUNCTION_ENTRY, + ) -> bool { + self.replay(context, image, entry as u64).is_some() + } + + /// Whether what the unwinder reads for one step outside the stack is + /// committed readable memory of a form it takes without raising: the + /// entry, the unwind info and its chain with known codes, and the code + /// at `rip` it reads to tell an epilogue. The stack reads are left to + /// `RtlVirtualUnwind2`'s limits. + pub(super) fn tables( + &mut self, + context: &CONTEXT, + image: u64, + entry: *const IMAGE_RUNTIME_FUNCTION_ENTRY, + ) -> bool { + self.off_stack(context.Rip, image, entry as u64).is_some() + } + + fn off_stack(&mut self, pc: u64, image: u64, entry: u64) -> Option<()> { + let function = self.function(entry)?; + let info = self.info(image, function.unwind)?; + self.epilogue(pc, info.frame_register)?; + self.chain(image, info) + } + + /// Whether the chain from `info` is readable unwind info with known + /// codes, no deeper than the unwinder follows. + fn chain(&mut self, image: u64, mut info: Info) -> Option<()> { + for depth in 0.. { + let mut i = 0; + while i < info.count { + let (_, op, op_info) = info.code(i); + i += slots(info.version, op, op_info)?; + } + if i > info.count { + return None; + } + let Some(chained) = info.chained else { break }; + if depth + 1 >= CHAIN { + return None; + } + info = self.info(image, chained.unwind)?; + } + Some(()) + } + + fn replay(&mut self, context: &CONTEXT, image: u64, entry: u64) -> Option<()> { + let function = self.function(entry)?; + let info = self.info(image, function.unwind)?; + let pc = context.Rip; + let regs = registers(context); + let (epilogue, unwound, pops) = self.epilogue(pc, info.frame_register)?; + if epilogue != Epilogue::No { + self.leave(regs, info.frame_register, unwound, pops)?; + // A version 2 epilogue is not told by its bytes: where its own + // codes do not cover `pc`, the unwinder takes the prologue even + // at a `ret`. + if epilogue == Epilogue::Yes && info.version == 1 { + return Some(()); + } + } + if info.version == 2 { + // A version 2 epilogue is found from its own codes, not by its + // bytes, and unwound from `rsp` up: at most the whole frame. + self.frame_fits(&info, regs[RSP])?; + } + self.prologue(pc, image, function, info, regs) + } + + /// The prologue's unwind codes reached at `pc`, applied in order through + /// the chain, then the return address. + fn prologue( + &mut self, + pc: u64, + image: u64, + mut function: Function, + mut info: Info, + mut regs: [u64; 16], + ) -> Option<()> { + let bases = self.bases(pc, image, function, &info, ®s); + let mut machine = false; + for depth in 0.. { + let offset = prolog_offset(pc, image, function); + let mut i = 0; + while i < info.count && !machine { + let (at, op, op_info) = info.code(i); + let n = slots(info.version, op, op_info)?; + if i + n > info.count { + return None; + } + if offset >= u32::from(at) { + let register = usize::from(op_info); + match op { + PUSH_NONVOL => { + let value = self.word(regs[RSP])?; + regs[register] = value; + regs[RSP] = regs[RSP].wrapping_add(8); + } + ALLOC_LARGE => { + let size = match op_info { + 0 => u64::from(info.slot(i + 1)) * 8, + _ => info.far(i + 1), + }; + regs[RSP] = regs[RSP].wrapping_add(size); + } + ALLOC_SMALL => { + regs[RSP] = regs[RSP].wrapping_add(u64::from(op_info) * 8 + 8) + } + SET_FPREG => { + if info.frame_register == 0 { + return None; + } + regs[RSP] = + regs[info.frame_register].wrapping_sub(16 * info.frame_offset); + } + SAVE_NONVOL | SAVE_NONVOL_FAR => { + let offset = match op { + SAVE_NONVOL => u64::from(info.slot(i + 1)) * 8, + _ => info.far(i + 1), + }; + let mut value = None; + for base in bases.into_iter().flatten() { + let read = self.word(base.wrapping_add(offset))?; + value.get_or_insert(read); + } + regs[register] = value?; + } + SAVE_XMM128 | SAVE_XMM128_FAR => { + let offset = match op { + SAVE_XMM128 => u64::from(info.slot(i + 1)) * 16, + _ => info.far(i + 1), + }; + for base in bases.into_iter().flatten() { + self.on_stack(base.wrapping_add(offset), 16)?; + } + } + PUSH_MACHFRAME => { + let rsp = regs[RSP].wrapping_add(8 * u64::from(op_info)); + self.word(rsp)?; + regs[RSP] = self.word(rsp.wrapping_add(24))?; + machine = true; + } + _ => {} + } + } + i += n; + } + let Some(chained) = info.chained else { break }; + if depth + 1 >= CHAIN { + return None; + } + function = chained; + info = self.info(image, chained.unwind)?; + } + if !machine { + self.word(regs[RSP])?; + } + Some(()) + } + + /// The establisher frame the save codes are relative to, as the + /// unwinder takes it: `rsp` without a frame register, the frame register + /// once its `SET_FPREG` has run. Inside the prologue the unwinder finds + /// that code stepping one slot at a time; where that and a walk by code + /// sizes disagree, both frames are checked (the first is the one used). + fn bases( + &self, + pc: u64, + image: u64, + function: Function, + info: &Info, + regs: &[u64; 16], + ) -> [Option<u64>; 2] { + let rsp = regs[RSP]; + if info.frame_register == 0 { + return [Some(rsp), None]; + } + let frame = regs[info.frame_register].wrapping_sub(16 * info.frame_offset); + let offset = prolog_offset(pc, image, function); + if offset >= u32::from(info.prolog) || info.flags & UNW_FLAG_CHAININFO != 0 { + return [Some(frame), None]; + } + match (info.frame_set(offset, false), info.frame_set(offset, true)) { + (Some(set), Some(by_slot)) if set == by_slot => { + [Some(if set { frame } else { rsp }), None] + } + _ => [Some(rsp), Some(frame)], + } + } + + /// Whether the code at `pc` reads as an epilogue to the unwinder, what + /// it does to `rsp` first, and where its pops begin. The prefixes are + /// the unwinder's exactly: `add rsp` with REX.W alone, `lea rsp` with + /// REX.W and at most REX.B, an indirect jump with REX.W. + fn epilogue(&mut self, pc: u64, frame_register: usize) -> Option<(Epilogue, Unwound, u64)> { + let mut at = pc; + let mut unwound = Unwound::Nothing; + let rex = self.byte(at)?; + if rex & 0xfe == 0x48 { + let op = self.byte(at + 1)?; + if rex == 0x48 && op == 0x83 && self.byte(at + 2)? == 0xc4 { + unwound = Unwound::Add(i64::from(self.byte(at + 3)? as i8)); + at += 4; + } else if rex == 0x48 && op == 0x81 && self.byte(at + 2)? == 0xc4 { + unwound = Unwound::Add(i64::from(self.dword(at + 3)?)); + at += 7; + } else if op == 0x8d { + let modrm = self.byte(at + 2)?; + let register = usize::from((rex & 1) << 3 | modrm & 7); + if register != 0 && register == frame_register { + if modrm & 0xf8 == 0x60 { + unwound = Unwound::Lea(i64::from(self.byte(at + 3)? as i8)); + at += 4; + } else if modrm & 0xf8 == 0xa0 { + unwound = Unwound::Lea(i64::from(self.dword(at + 3)?)); + at += 7; + } + } + } + } + let pops = at; + while let Some((_, n)) = self.pop(at)? { + at += n; + } + let next = self.byte(at)?; + let epilogue = match next { + 0xc3 | 0xc2 => Epilogue::Yes, + 0xf3 if self.byte(at + 1)? == 0xc3 => Epilogue::Yes, + // The unwinder reads the displacement to find where the jump + // goes, then what is there. + 0xeb => { + let to = (at + 2).wrapping_add_signed(i64::from(self.byte(at + 1)? as i8)); + self.jump(to)?; + Epilogue::Either + } + 0xe9 => { + let to = (at + 5).wrapping_add_signed(i64::from(self.dword(at + 1)?)); + self.jump(to)?; + Epilogue::Either + } + 0xff if self.byte(at + 1)? == 0x25 => Epilogue::Yes, + _ if next & 0xf8 == 0x48 + && self.byte(at + 1)? == 0xff + && self.byte(at + 2)? & 0x38 == 0x20 => + { + Epilogue::Yes + } + _ => Epilogue::No, + }; + Some((epilogue, unwound, pops)) + } + + /// Whether what the unwinder reads at a jump's target `to` is readable + /// and of a form it takes. Where `to` is outside the function, it looks + /// up the function table entry there and follows its unwind info's + /// chain to the primary entry, to tell whether the jump leaves the + /// function. Which bounds it compares with (the entry's or its primary + /// one's) is not checked here, so the target is looked up wherever it + /// is: one more lookup at such a jump, as the walk makes at every frame. + fn jump(&mut self, to: u64) -> Option<()> { + let mut image = 0; + // SAFETY: looks up the function table entry covering `to`, if any. + let entry = unsafe { RtlLookupFunctionEntry(to, &mut image, std::ptr::null_mut()) } as u64; + if entry == 0 { + return Some(()); + } + let function = self.function(entry)?; + let info = self.info(image, function.unwind)?; + self.chain(image, info) + } + + /// The register a `pop` at `at` restores and its length, or `None` for + /// another instruction. + fn pop(&mut self, at: u64) -> Option<Option<(usize, u64)>> { + let first = self.byte(at)?; + if first & 0xf8 == 0x58 { + return Some(Some((usize::from(first & 7), 1))); + } + if first & 0xf0 == 0x40 { + let second = self.byte(at + 1)?; + if second & 0xf8 == 0x58 { + return Some(Some((usize::from((first & 1) << 3 | second & 7), 2))); + } + } + Some(None) + } + + /// The epilogue emulated forward from `pops`: `rsp` set, the pops and + /// the return. + fn leave( + &mut self, + mut regs: [u64; 16], + frame_register: usize, + unwound: Unwound, + mut at: u64, + ) -> Option<()> { + match unwound { + Unwound::Nothing => {} + Unwound::Add(n) => regs[RSP] = regs[RSP].wrapping_add_signed(n), + Unwound::Lea(n) => regs[RSP] = regs[frame_register].wrapping_add_signed(n), + } + while let Some((register, n)) = self.pop(at)? { + let value = self.word(regs[RSP])?; + regs[register] = value; + regs[RSP] = regs[RSP].wrapping_add(8); + at += n; + } + self.word(regs[RSP]).map(drop) + } + + /// Whether the whole fixed frame `info` describes, and the return + /// address above it, fit on the stack from `rsp`. + fn frame_fits(&self, info: &Info, rsp: u64) -> Option<()> { + let mut size = 8u64; + let mut i = 0; + while i < info.count { + let (_, op, op_info) = info.code(i); + let n = slots(info.version, op, op_info)?; + if i + n > info.count { + return None; + } + size = size.saturating_add(match op { + PUSH_NONVOL => 8, + ALLOC_SMALL => u64::from(op_info) * 8 + 8, + ALLOC_LARGE if op_info == 0 => u64::from(info.slot(i + 1)) * 8, + ALLOC_LARGE => info.far(i + 1), + _ => 0, + }); + i += n; + } + self.on_stack(rsp, size) + } + + /// The function table entry at `entry`, if readable. An entry that + /// points at another (the low bit of its unwind data) is not followed. + fn function(&mut self, entry: u64) -> Option<Function> { + if !self.readable(entry, 12) { + return None; + } + // SAFETY: the 12 bytes of the entry are readable. + let read = |i: u64| unsafe { ((entry + 4 * i) as *const u32).read_unaligned() }; + let function = Function { + begin: read(0), + unwind: read(2), + }; + (function.unwind & 1 == 0).then_some(function) + } + + /// The `UNWIND_INFO` at `image + unwind`, if all of it is readable and + /// of a version the unwinder takes. + fn info(&mut self, image: u64, unwind: u32) -> Option<Info> { + let at = image.checked_add(u64::from(unwind))?; + if !self.readable(at, 4) { + return None; + } + // SAFETY: the 4 header bytes are readable. + let [first, prolog, count, frame] = unsafe { (at as *const [u8; 4]).read_unaligned() }; + let version = first & 7; + if version != 1 && version != 2 { + return None; + } + let flags = first >> 3; + let count = usize::from(count); + let codes = at + 4; + if !self.readable(codes, 2 * count as u64) { + return None; + } + let chained = if flags & UNW_FLAG_CHAININFO != 0 { + Some(self.function(codes + 2 * ((count as u64 + 1) & !1))?) + } else { + None + }; + Some(Info { + version, + flags, + prolog, + count, + frame_register: usize::from(frame & 0xf), + frame_offset: u64::from(frame >> 4), + codes, + chained, + }) + } + + /// Whether `[at, at + len)` is inside the walked thread's stack. + fn on_stack(&self, at: u64, len: u64) -> Option<()> { + (at >= self.low && at.checked_add(len).is_some_and(|end| end <= self.high)).then_some(()) + } + + /// The stack word at `at`, if it is inside the walked thread's stack. + fn word(&self, at: u64) -> Option<u64> { + self.on_stack(at, 8)?; + // SAFETY: inside the committed stack of a thread of this process + // (`low` is its committed limit), which is suspended. + Some(unsafe { (at as *const u64).read_unaligned() }) + } + + /// The code byte at `at`, if readable. + fn byte(&mut self, at: u64) -> Option<u8> { + // SAFETY: readable, as just checked. + self.readable(at, 1) + .then(|| unsafe { (at as *const u8).read() }) + } + + /// The little-endian 32-bit displacement at `at`, if readable. + fn dword(&mut self, at: u64) -> Option<i32> { + // SAFETY: readable, as just checked. + self.readable(at, 4) + .then(|| unsafe { (at as *const i32).read_unaligned() }) + } + + /// Whether `[at, at + len)` is committed readable memory (no guard page). + fn readable(&mut self, at: u64, len: u64) -> bool { + let Some(end) = at.checked_add(len) else { + return false; + }; + let mut at = at; + while at < end { + if let Some(span_end) = self.spans.find(at).or_else(|| self.images.spans.find(at)) { + at = span_end; + continue; + } + #[cfg(test)] + QUERIES.set(QUERIES.get() + 1); + // SAFETY: a zeroed MEMORY_BASIC_INFORMATION is valid. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: reads the address space's bookkeeping, not `at` itself. + let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + let readable = [ + PAGE_READONLY, + PAGE_READWRITE, + PAGE_WRITECOPY, + PAGE_EXECUTE_READ, + PAGE_EXECUTE_READWRITE, + PAGE_EXECUTE_WRITECOPY, + ] + .contains(&(info.Protect & 0xff)); + if n == 0 || info.State != MEM_COMMIT || info.Protect & PAGE_GUARD != 0 || !readable { + return false; + } + let start = info.BaseAddress as u64; + let span_end = start + info.RegionSize as u64; + if info.Type == MEM_IMAGE { + self.images.spans.add((start, span_end)); + } else { + self.spans.add((start, span_end)); + } + at = span_end; + } + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE, VirtualAlloc, VirtualFree}; + + /// How `code` reads to [`Check::epilogue`] with `frame_register`, + /// followed by `int3`s. + fn reads(code: &[u8], frame_register: usize) -> Option<Epilogue> { + let bytes = [code, &[0xcc; 8]].concat(); + let mut images = Images::new(); + let mut check = Check::new(0, 0, &mut images); + check + .epilogue(bytes.as_ptr() as u64, frame_register) + .map(|(epilogue, _, _)| epilogue) + } + + /// An epilogue is told with the unwinder's prefixes only: code that + /// differs from one by the prefix is unwound through the prologue, so + /// taking it as an epilogue would skip what the unwinder reads there. + #[test] + fn epilogues_are_told_by_the_unwinders_prefixes() { + use Epilogue::{Either, No, Yes}; + let rbp = 5; + for (code, frame, is) in [ + // add rsp, 8; pop rbp; ret + (&[0x48, 0x83, 0xc4, 0x08, 0x5d, 0xc3][..], 0, Yes), + // add rsp, 0x100; ret + ( + &[0x48, 0x81, 0xc4, 0x00, 0x01, 0x00, 0x00, 0xc3][..], + 0, + Yes, + ), + // add r12, 8; pop rbp; ret + (&[0x49, 0x83, 0xc4, 0x08, 0x5d, 0xc3][..], 0, No), + // lea rsp, [rbp]; pop rbp; ret + (&[0x48, 0x8d, 0x65, 0x00, 0x5d, 0xc3][..], rbp, Yes), + // lea rsp, [r13 + 0x10]; ret + (&[0x49, 0x8d, 0x65, 0x10, 0xc3][..], 13, Yes), + // lea r12, [rbp]; pop rbp; ret + (&[0x4c, 0x8d, 0x65, 0x00, 0x5d, 0xc3][..], rbp, No), + // pop r12; jmp rax (REX.W) or jmp r11 (REX.B) + (&[0x41, 0x5c, 0x48, 0xff, 0xe0][..], 0, Yes), + (&[0x41, 0x5c, 0x49, 0xff, 0xe3][..], 0, Yes), + (&[0x41, 0x5c, 0x41, 0xff, 0xe3][..], 0, No), + // pop rbp; jmp rel8 + (&[0x5d, 0xeb, 0x10][..], 0, Either), + ] { + assert_eq!(reads(code, frame), Some(is), "{code:02x?}"); + } + } + + /// The displacement of a jump after the pops is read by the unwinder, + /// so one past the end of readable memory ends the check. + #[test] + fn a_jump_whose_displacement_cannot_be_read_is_refused() { + // SAFETY: reserves two pages and commits the first, of our own. + let page = unsafe { + let page = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE, PAGE_READWRITE); + VirtualAlloc(page, 0x1000, MEM_COMMIT, PAGE_READWRITE).cast::<u8>() + }; + assert!(!page.is_null()); + let mut images = Images::new(); + let mut check = Check::new(0, 0, &mut images); + for (code, is) in [ + (&[0x5d, 0xc3][..], Some(Epilogue::Yes)), + (&[0x5d, 0xeb][..], None), + (&[0x5d, 0xe9][..], None), + (&[0xe9, 0, 0, 0][..], None), + ] { + // SAFETY: the end of the committed page. + let at = unsafe { + let at = page.add(0x1000 - code.len()); + std::ptr::copy_nonoverlapping(code.as_ptr(), at, code.len()); + at + }; + let read = check + .epilogue(at as u64, 0) + .map(|(epilogue, _, _)| epilogue); + assert_eq!(read, is, "{code:02x?}"); + } + // SAFETY: allocated above. + unsafe { VirtualFree(page.cast(), 0, MEM_RELEASE) }; + } + + /// `LDR_DLL_UNLOADED_NOTIFICATION_DATA`. + #[repr(C)] + struct Unloaded { + flags: u32, + full_name: *const c_void, + base_name: *const c_void, + base: *const c_void, + size: u32, + } + + /// The module the test unloads, and what its notice found there: + /// 0 none yet, 1 the image still mapped, 2 something else. + struct Seen { + base: u64, + mapped: std::sync::atomic::AtomicU8, + } + + unsafe extern "system" fn look(reason: u32, data: *const c_void, context: *mut c_void) { + // SAFETY: the loader passes its notification data, and `context` + // is the `Seen` registered with this callback. + let (data, seen) = unsafe { (&*data.cast::<Unloaded>(), &*context.cast::<Seen>()) }; + if reason != UNLOADED || data.base as u64 != seen.base { + return; + } + // SAFETY: a zeroed MEMORY_BASIC_INFORMATION is valid; the query + // reads bookkeeping only. + let mapped = unsafe { + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(data.base, &mut info, size_of_val(&info)) != 0 + && info.Type == MEM_IMAGE + && info.AllocationBase as u64 == seen.base + }; + seen.mapped + .store(if mapped { 1 } else { 2 }, Ordering::SeqCst); + } + + /// What [`Images`] rests on: the loader's notice of an unload comes + /// while the image is still mapped, so the count has moved before a + /// region kept can be unmapped. + #[test] + fn the_loader_tells_of_an_unload_before_it_unmaps_the_image() { + use windows_sys::Win32::Foundation::FreeLibrary; + use windows_sys::Win32::System::LibraryLoader::LoadLibraryW; + assert!(watch_unloads(), "no LdrRegisterDllNotification"); + let wide = |name: &str| name.encode_utf16().chain([0]).collect::<Vec<u16>>(); + // A system module this process has not loaded. + let Some(module) = ["msimg32.dll", "version.dll", "winmm.dll"] + .into_iter() + .map(wide) + // SAFETY: NUL-terminated names of system modules, whose + // loading runs only their own initialisation. + .find_map(|name| unsafe { + if !GetModuleHandleW(name.as_ptr()).is_null() { + return None; + } + let module = LoadLibraryW(name.as_ptr()); + (!module.is_null()).then_some(module) + }) + else { + eprintln!("every candidate module is loaded already: nothing to unload"); + return; + }; + let seen = Box::new(Seen { + base: module as u64, + mapped: 0.into(), + }); + let ntdll = wide("ntdll.dll"); + // SAFETY: as in `watch_unloads`; `seen` outlives the registration, + // which is undone before it is dropped. + unsafe { + let ntdll = GetModuleHandleW(ntdll.as_ptr()); + let register = GetProcAddress(ntdll, c"LdrRegisterDllNotification".as_ptr().cast()); + let unregister = GetProcAddress(ntdll, c"LdrUnregisterDllNotification".as_ptr().cast()); + let register = + std::mem::transmute::<Export, RegisterDllNotification>(register.unwrap()); + let unregister = std::mem::transmute::< + Export, + unsafe extern "system" fn(*mut c_void) -> i32, + >(unregister.unwrap()); + let mut cookie = std::ptr::null_mut(); + let context = (&raw const *seen).cast_mut().cast(); + assert!(register(0, look, context, &mut cookie) >= 0); + let before = UNLOADS.load(Ordering::SeqCst); + assert!(FreeLibrary(module) != 0); + let after = UNLOADS.load(Ordering::SeqCst); + assert!(unregister(cookie) >= 0); + assert!(after > before, "the unload was not counted"); + } + assert_eq!( + seen.mapped.load(Ordering::SeqCst), + 1, + "told after the unmap, or never" + ); + } +} diff --git a/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs b/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs index d0e205663c..17ba664162 100644 --- a/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs +++ b/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs @@ -21,11 +21,12 @@ //! condition was made of (both terms of an `and` that held, the opposite //! comparison). The lowering branches on a lane's condition and then //! guards each instruction behind the branch with the same condition. -//! - [`LOADS`]: within a block, a read of the same place as an earlier read -//! gives that one's result while no store, atomic, barrier or other call -//! with an effect stands between them (another thread's unsynchronised -//! store may fall between any two reads or before both: the title's code -//! cannot tell which). +//! - [`LOADS`]: a read of the same place as an earlier dominating read gives +//! that one's result while no store, atomic, barrier or other call with an +//! effect can occur between them (including across blocks along the +//! dominator tree when no path from the immediate dominator writes; wave +//! and quad operations stay block-local because active lanes can change +//! across branches). //! //! - [`GUARDS`]: a value kept for the lanes a guard leaves out (`select(g, new, old)`, //! what a console instruction under EXEC writes) that is read only where `g` holds, or by @@ -815,22 +816,72 @@ impl Module { } } } + // Precompute per-block write presence and immediate dominators so `LOADS` + // can reuse dominating `Effect::Reads` across blocks whenever no path + // from the immediate dominator can execute an `Effect::Writes`. + let (has_write, idom) = if passes & LOADS != 0 { + let has_write: Vec<bool> = self + .blocks + .iter() + .map(|blk| { + blk.body + .iter() + .any(|&i| self.class(&effects, i) == Effect::Writes) + }) + .collect(); + let mut idom = vec![None; self.blocks.len()]; + for (p, children) in tree.children.iter().enumerate() { + for &c in children { + idom[c] = Some(p); + } + } + (has_write, idom) + } else { + (Vec::new(), Vec::new()) + }; + let path_has_write = |b: usize, dom: usize| -> bool { + if tree.preds[b].as_slice() == [dom] { + return false; + } + let mut visited = vec![false; has_write.len()]; + let mut stack = Vec::new(); + for &p in &tree.preds[b] { + if p != dom && !visited[p] { + visited[p] = true; + stack.push(p); + } + } + while let Some(u) = stack.pop() { + if has_write[u] { + return true; + } + for &p in &tree.preds[u] { + if p != dom && !visited[p] { + visited[p] = true; + stack.push(p); + } + } + } + false + }; // The values every path to the block being walked has computed // (those of the blocks above it in the tree, and its own so far). let mut known: HashMap<Key, V> = HashMap::new(); - // The reads of the block being walked since its last store. - let mut read: HashMap<Key, V> = HashMap::new(); + // Dominating memory reads still valid (no `Effect::Writes` since). + let mut dom_reads: HashMap<Key, V> = HashMap::new(); + // Wave/quad operations in the current block (active lanes stay fixed within a block). + let mut lane_reads: HashMap<Key, V> = HashMap::new(); let mut facts = Facts::default(); let (yes, no) = (self.bool(true), self.bool(false)); enum Step { Enter(usize), - Leave(Vec<Key>, Learned), + Leave(Vec<Key>, Learned, Vec<Key>, Option<HashMap<Key, V>>), } let mut steps = vec![Step::Enter(0)]; while let Some(step) = steps.pop() { let b = match step { Step::Enter(b) => b, - Step::Leave(keys, learned) => { + Step::Leave(keys, learned, added_reads, saved_reads) => { for k in keys { known.remove(&k); } @@ -840,10 +891,19 @@ impl Module { for k in learned.compares { facts.compares.remove(&k); } + if let Some(prev) = saved_reads { + dom_reads = prev; + } else { + for k in added_reads { + dom_reads.remove(&k); + } + } continue; } }; let mut added = Vec::new(); + let mut added_reads = Vec::new(); + let mut saved_reads = None; // Reached from one block alone, by one side of its branch: the // condition is that side's, here and in every block below. let mut learned = Learned::default(); @@ -859,7 +919,13 @@ impl Module { Some(false) => no, None => v, }; - read.clear(); + lane_reads.clear(); + if passes & LOADS != 0 + && b != 0 + && idom[b].is_none_or(|dom| path_has_write(b, dom)) + { + saved_reads = Some(std::mem::take(&mut dom_reads)); + } // Two joins of the same values from the same blocks are one. if passes & REUSE != 0 && self.blocks[b].phis.len() > 1 { let mut joins: HashMap<Vec<(usize, V)>, V> = HashMap::new(); @@ -926,21 +992,46 @@ impl Module { known.insert(key.clone(), V::Inst(i)); added.push(key); } - // Reads of memory, and wave operations (the same lanes run - // the whole block): the block's own earlier one. + // Reads of memory (valid across blocks along the dominator tree + // while no `Effect::Writes` intervenes), and wave operations + // (block-local: the same lanes run the whole block). if passes & LOADS != 0 && matches!(class, Effect::Reads | Effect::Lanes) && let Some(key) = self.key(i) { - if let Some(&first) = read.get(&key) { - repl[i as usize] = Some(first); - changed = true; - continue; + match class { + Effect::Reads => { + if let Some(&first) = dom_reads.get(&key) { + repl[i as usize] = Some(first); + changed = true; + continue; + } + if saved_reads.is_none() { + added_reads.push(key.clone()); + } + dom_reads.insert(key, V::Inst(i)); + } + Effect::Lanes => { + if let Some(&first) = lane_reads.get(&key) { + repl[i as usize] = Some(first); + changed = true; + continue; + } + lane_reads.insert(key, V::Inst(i)); + } + _ => {} } - read.insert(key, V::Inst(i)); } if class == Effect::Writes { - read.clear(); + lane_reads.clear(); + if saved_reads.is_none() { + for k in added_reads.drain(..) { + dom_reads.remove(&k); + } + saved_reads = Some(std::mem::take(&mut dom_reads)); + } else { + dom_reads.clear(); + } } kept.push(i); } @@ -949,7 +1040,7 @@ impl Module { let c = known_bit(&facts, resolve(&repl, c)); self.blocks[b].term = Some(Term::CondBr(c, t, f)); } - steps.push(Step::Leave(added, learned)); + steps.push(Step::Leave(added, learned, added_reads, saved_reads)); for &c in tree.children[b].iter().rev() { steps.push(Step::Enter(c)); } @@ -2621,6 +2712,121 @@ mod tests { g.k.m } + #[test] + fn cross_block_reads_reuse_dominating_load_without_writes() { + let Diamond { + k: Kit { mut m, b: entry, reads, writes, .. }, + then, + other, + join, + .. + } = diamond(); + let seven = m.i32(7); + let i32t = m.int(32); + let top = m.call(entry, reads, vec![seven, seven]); + let in_then = m.call(then, reads, vec![seven, seven]); + let in_other = m.call(other, reads, vec![seven, seven]); + let joined = m.phi(join, i32t); + m.set_phi(joined, vec![(in_then, then), (in_other, other)]); + let in_join = m.call(join, reads, vec![seven, seven]); + let sum = m.bin(join, Bin::Add, joined, in_join); + m.call(join, writes, vec![sum, top]); + m.optimise(LOADS | DEAD); + let stores = super::tests::stores(&m, join); + assert_eq!(stores.len(), 1); + let V::Inst(sum_id) = stores[0][0] else { panic!() }; + assert!( + matches!(m.insts[sum_id as usize].op, Op::Bin(Bin::Add, _, z) if z == top), + "join should reuse entry's dominating read when neither branch writes" + ); + assert!( + m.blocks[then].body.is_empty() && m.blocks[other].body.is_empty(), + "redundant reads in both branches should be eliminated" + ); + assert_eq!( + m.blocks[join].body.len(), + 2, + "join should keep only sum and the store (redundant read eliminated)" + ); + m.write(); + } + + #[test] + fn cross_block_reads_invalidated_when_branch_writes() { + let Diamond { + k: Kit { mut m, b: entry, reads, writes, .. }, + then, + other, + join, + .. + } = diamond(); + let seven = m.i32(7); + let top = m.call(entry, reads, vec![seven, seven]); + // `then` writes, so a read after the write in `then` and any read in `join` must stay fresh. + m.call(then, writes, vec![top, seven]); + let after_write = m.call(then, reads, vec![seven, seven]); + m.call(then, writes, vec![after_write, seven]); + // `other` is a sibling of `then` and has no write before its read: it can still reuse `top`. + let in_other = m.call(other, reads, vec![seven, seven]); + m.call(other, writes, vec![in_other, seven]); + // `join` is reachable from `then` (which wrote), so it must NOT reuse `top`. + let in_join = m.call(join, reads, vec![seven, seven]); + m.call(join, writes, vec![in_join, seven]); + m.optimise(LOADS | DEAD); + assert_eq!(super::tests::stores(&m, then)[1][0], after_write); + assert_eq!(super::tests::stores(&m, other)[0][0], top, "sibling branch without prior write reuses entry read"); + assert_eq!(super::tests::stores(&m, join)[0][0], in_join, "merge after writing branch must not reuse entry read"); + m.write(); + } + + #[test] + fn cross_block_reads_in_loop_respect_backedge_writes() { + // Loop WITH a write in the latch: header must NOT reuse preheader read. + let Kit { mut m, b: entry, reads, writes, .. } = kit(); + let header = m.new_block(); + let latch = m.new_block(); + let exit = m.new_block(); + let one = m.i32(1); + let pre = m.call(entry, reads, vec![one, one]); + m.terminate(entry, Term::Br(header)); + let in_header = m.call(header, reads, vec![one, one]); + let cond = m.cmp(header, pred::NE, in_header, one); + m.terminate(header, Term::CondBr(cond, latch, exit)); + m.call(latch, writes, vec![in_header, pre]); + m.terminate(latch, Term::Br(header)); + m.call(exit, writes, vec![in_header, pre]); + m.terminate(exit, Term::Ret); + m.optimise(LOADS | DEAD); + assert_eq!( + super::tests::stores(&m, exit)[0][0], + in_header, + "loop header must re-read when backedge writes" + ); + m.write(); + + // Loop WITHOUT any write: header reuses preheader read. + let Kit { mut m, b: entry, reads, writes, .. } = kit(); + let header = m.new_block(); + let latch = m.new_block(); + let exit = m.new_block(); + let one = m.i32(1); + let pre = m.call(entry, reads, vec![one, one]); + m.terminate(entry, Term::Br(header)); + let in_header = m.call(header, reads, vec![one, one]); + let cond = m.cmp(header, pred::NE, in_header, one); + m.terminate(header, Term::CondBr(cond, latch, exit)); + m.terminate(latch, Term::Br(header)); + m.call(exit, writes, vec![in_header, pre]); + m.terminate(exit, Term::Ret); + m.optimise(LOADS | DEAD); + assert_eq!( + super::tests::stores(&m, exit)[0][0], + pre, + "write-free loop header should reuse preheader read" + ); + m.write(); + } + #[test] fn every_pass_leaves_what_random_programs_store() { let mut removed = 0; diff --git a/d3d12/crates/leonida-shader/src/emit/lower.rs b/d3d12/crates/leonida-shader/src/emit/lower.rs index 773af41197..d7780caaae 100644 --- a/d3d12/crates/leonida-shader/src/emit/lower.rs +++ b/d3d12/crates/leonida-shader/src/emit/lower.rs @@ -2434,8 +2434,9 @@ impl<'a> Lower<'a> { s.threads = Some([32 * waves, 1, 1]); s.lds_dwords = cs.lds_bytes() / 4; if waves > 1 { - halves = Some(s.lds_dwords); - s.lds_dwords += 1; + // Paired host groups are always 1-D (`[32 * waves, 1, 1]`), so host + // wave `k` already holds flat ids `32*k..32*k+31` (console base `64*k`). + halves = Some(NO_COUNTER); } console_lanes = true; s.wave_size = Some(32); @@ -2588,20 +2589,20 @@ impl<'a> Lower<'a> { eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", ")); } } - // A group of one dimension whose LDS leaves no dword for a counter (all of D3D12's - // 32 KiB: the title's culling program of 1,024 threads) takes its console threads - // from the flat id, as a host does that gives each wave a run of consecutive ids (it - // is only the other shapes, whose waves are tiles, that the counter is for). - let no_room = s.lds_dwords >= 8192 && cs.threads[1] == 1 && cs.threads[2] == 1; + // A 1-D group gives each host wave a consecutive run of flat ids, so it + // takes its console threads from the flat id without an LDS counter, + // entry barrier, or atomic (2-D/3-D shapes, whose waves may be tiled, + // keep the counter). + let one_d = cs.threads[1] == 1 && cs.threads[2] == 1; if wave == 32 && x.native.wave64 { // console threads go to host waves in the order the waves take them (`wave_base`) - if no_room { + if one_d { halves = Some(NO_COUNTER); } else { halves = Some(s.lds_dwords); s.lds_dwords += 1; } - } else if console_lanes && group > wave && ticket_on() && !no_room { + } else if console_lanes && group > wave && ticket_on() && !one_d { // the flat id rounded down is not a host wave's base on every host (#1243) ticket = Some(s.lds_dwords); s.lds_dwords += 1; @@ -5853,10 +5854,20 @@ impl<'a> Lower<'a> { let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let half = self.s.m.i32(if self.upper { 32 } else { 0 }); let t = self.s.m.bin(e, Bin::Add, lane, half); - return match self.wave_base() { - Some(base) => self.s.m.bin(e, Bin::Add, base, t), - None => t, - }; + self.s.flags |= flags::WAVE_OPS; + if let Some(base) = self.wave_base() { + return self.s.m.bin(e, Bin::Add, base, t); + } + if self.halves == Some(NO_COUNTER) { + let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]); + let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]); + let mask = self.s.m.i32(!31u32); + let host_base = self.s.m.bin(e, Bin::And, first, mask); + let one = self.s.m.i32(1); + let base = self.s.m.bin(e, Bin::Shl, host_base, one); + return self.s.m.bin(e, Bin::Add, base, t); + } + return t; } if let Some(base) = self.wave_base() { let rank = self.wave_rank.expect("made with the base"); @@ -5868,6 +5879,7 @@ impl<'a> Lower<'a> { let wave = self.s.wave_size.unwrap_or(32); let mask = self.s.m.i32(!(wave - 1)); let base = self.s.m.bin(e, Bin::And, first, mask); + self.s.flags |= flags::WAVE_OPS; self.s.m.bin(e, Bin::Add, base, lane) } @@ -9700,11 +9712,23 @@ impl<'a> Lower<'a> { h } + /// `offset` plus `bias` in `block`, keeping 32-bit sentinel and negative + /// offsets (`u32::MAX * stride + field`, `x - 4` at `x = 0`) out of bounds + /// instead of wrapping modulo 2^32 into `[0, 16)`, the bytes before the + /// view (including across a 4-dword vector load or store). + fn add_bias(&mut self, block: usize, offset: V, bias: V) -> V { + let sum = self.s.m.bin(block, Bin::Add, offset, bias); + let ceiling = self.s.m.i32(0xFFFF_FFD0); + let oob = self.s.m.i32(0xFFFF_FFE0); + let wraps = self.s.m.cmp(block, pred::IUGT, offset, ceiling); + self.s.m.select(block, wraps, oob, sum) + } + /// `offset` plus the bias of the raw twin `h` is, if it is one /// ([`Lower::twin_handle`]), in the current block. fn biased(&mut self, h: V, offset: V) -> V { - match self.twin_bias.get(&h) { - Some(&bias) => self.s.m.bin(self.cur, Bin::Add, offset, bias), + match self.twin_bias.get(&h).copied() { + Some(bias) => self.add_bias(self.cur, offset, bias), None => offset, } } @@ -9726,7 +9750,7 @@ impl<'a> Lower<'a> { match (args.first().and_then(|h| self.twin_bias.get(h)).copied(), args.get(at)) { (Some(bias), Some(&offset)) => { let mut moved = args.to_vec(); - moved[at] = self.s.m.bin(block, Bin::Add, offset, bias); + moved[at] = self.add_bias(block, offset, bias); self.s.op(block, name, attr, ret, opcode, &moved) } _ => self.s.op(block, name, attr, ret, opcode, args), @@ -14293,7 +14317,10 @@ impl<'a> Lower<'a> { let aligned = self.s.m.bin(c, Bin::Sub, byte, within); let shift = self.s.m.bin(c, Bin::Shl, within, k3); let four = self.s.m.i32(4); + let at_end = self.s.m.i32(0xFFFF_FFFC); + let wraps = self.s.m.cmp(c, pred::EQ, aligned, at_end); let next = self.s.m.bin(c, Bin::Add, aligned, four); + let next = self.s.m.select(c, wraps, at_end, next); let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff }); let zero = self.s.m.i32(0); let k8 = self.s.m.i32(8); diff --git a/d3d12/crates/leonida-shader/src/emit/twin_bias_tests.rs b/d3d12/crates/leonida-shader/src/emit/twin_bias_tests.rs index 1e75c8eeac..9756ca4f91 100644 --- a/d3d12/crates/leonida-shader/src/emit/twin_bias_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/twin_bias_tests.rs @@ -157,3 +157,318 @@ fn accesses_through_twins_begin_where_the_view_does() { eprintln!("no D3D12 device; the dispatch is skipped"); } } + +fn mubuf(op: u32, vdata: u32, vaddr: u32, srsrc: u32, idxen: bool, offen: bool, offset: u32) -> [u32; 2] { + [ + 0x38 << 26 | op << 18 | u32::from(idxen) << 13 | u32::from(offen) << 12 | (offset & 0xFFF), + 0x80 << 24 | (srsrc >> 2) << 16 | vdata << 8 | vaddr, + ] +} + +fn v_mov_lit(vdst: u32, literal: u32) -> [u32; 2] { + [0x7E00_02FF | (vdst << 17), literal] +} + +/// 32-bit sentinel (`u32::MAX` / `-1`) and negative (`x - 4` at `x = 0`) offsets must stay out of +/// bounds when biased: wrapping `0xFFFF_FFF8 + 8` or `0xFFFF_FFFC + 8` modulo `2^32` would land in +/// the 16-byte prefix before the view and read or corrupt the preceding suballocation. +#[test] +fn sentinel_and_wrapped_offsets_stay_out_of_bounds_on_biased_twins() { + let mut code = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 (structured SRV, stride 8) + 0xF408_0302, + 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20 (raw SRV, stride 4) + 0xF408_0402, + 0xFA00_0040, // s_load_dwordx4 s[16:19], s[4:5], 0x40 (raw UAV, stride 4) + ]; + // Control: element 0 of structured SRV (stride 8) -> dwords 0 and 1 at UAV +0 and +4. + code.extend_from_slice(&v_mov_lit(1, 0)); + code.extend_from_slice(&mubuf(0x0C, 2, 1, 8, true, false, 0)); + code.extend_from_slice(&mubuf(0x0C, 3, 1, 8, true, false, 4)); + code.extend_from_slice(&mubuf(0x1C, 2, 0, 16, false, false, 0)); + code.extend_from_slice(&mubuf(0x1C, 3, 0, 16, false, false, 4)); + + // Sentinel element = 0xFFFF_FFFF (-1) on structured SRV (stride 8): + // (-1 * 8 + 0) = 0xFFFF_FFF8 and (-1 * 8 + 4) = 0xFFFF_FFFC must both read 0, never twin[0..3]. + code.extend_from_slice(&v_mov_lit(1, u32::MAX)); + code.extend_from_slice(&mubuf(0x0C, 2, 1, 8, true, false, 0)); + code.extend_from_slice(&mubuf(0x0C, 3, 1, 8, true, false, 4)); + code.extend_from_slice(&mubuf(0x1C, 2, 0, 16, false, false, 8)); + code.extend_from_slice(&mubuf(0x1C, 3, 0, 16, false, false, 12)); + + // Raw neighbor lookbehind `x - 4` at `x = 0` (`0xFFFF_FFFC`) and multi-dword `dwordx4` at + // `0xFFFF_FFF0` must read 0 for every component. + code.extend_from_slice(&v_mov_lit(1, 0xFFFF_FFFC)); + code.extend_from_slice(&mubuf(0x0C, 2, 1, 12, false, true, 0)); + code.extend_from_slice(&mubuf(0x1C, 2, 0, 16, false, false, 16)); + code.extend_from_slice(&v_mov_lit(1, 0xFFFF_FFF0)); + code.extend_from_slice(&mubuf(0x0E, 4, 1, 12, false, true, 0)); // buffer_load_dwordx4 v[4:7] + for k in 0..4u32 { + code.extend_from_slice(&mubuf(0x1C, 4 + k, 0, 16, false, false, 20 + 4 * k)); + } + // Straddling sub-dword load `buffer_load_ushort` at `0xFFFF_FFFF` (`within = 3`, + // `aligned = 0xFFFF_FFFC`, `next` clamped instead of wrapping to `0`) must also read 0. + code.extend_from_slice(&v_mov_lit(1, u32::MAX)); + code.extend_from_slice(&mubuf(0x0A, 2, 1, 12, false, true, 0)); + code.extend_from_slice(&mubuf(0x1C, 2, 0, 16, false, false, 40)); + + // Scalar load at soffset = 0xFFFF_FFFC (-4): s_mov_b32 s20, -4; s_buffer_load_dword s21, s[12:15], s20 + code.extend_from_slice(&[ + 0xBE94_03FF, + 0xFFFF_FFFC, + 0xF420_0546, + 0x14 << 25, + ]); + code.push(0x7E04_0215); // v_mov_b32 v2, s21 + code.extend_from_slice(&mubuf(0x1C, 2, 0, 16, false, false, 36)); + + // Out-of-bounds UAV store (`0xFFFF_FFF8`) and UAV atomic add (`0xFFFF_FFFC`) must drop, never + // writing into the pre-view bytes `[0..target_bias)` of the target twin. + code.extend_from_slice(&v_mov_lit(2, 0xBAD0_CAFE)); + code.extend_from_slice(&v_mov_lit(1, 0xFFFF_FFF8)); + code.extend_from_slice(&mubuf(0x1C, 2, 1, 16, false, true, 0)); + code.extend_from_slice(&v_mov_lit(2, 7)); + code.extend_from_slice(&v_mov_lit(1, 0xFFFF_FFFC)); + code.extend_from_slice(&mubuf(0x32, 2, 1, 16, false, true, 0)); + code.push(0xBF81_0000); // s_endpgm + + let entry = |kind, at, stride| crate::UsedResource { + kind, + root: crate::RootType::Table, + table_offset_dwords: at, + lower_bound: at / 8, + stride, + dwords: 4, + user_data: 4, + slot: 1, + }; + let native = super::NativeProgram { + stage: super::HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + crate::RootParam { root: crate::RootType::Constants, table_offset_dwords: 0, sgprs: 4, base_register: 0, user_data: 0, slot: 0 }, + crate::RootParam { root: crate::RootType::Table, table_offset_dwords: 0, sgprs: 1, base_register: 0, user_data: 4, slot: 1 }, + ], + used: vec![ + entry(crate::ResourceType::Srv, 0, 8), + entry(crate::ResourceType::Srv, 8, 4), + entry(crate::ResourceType::Uav, 16, 4), + ], + io: crate::native::StageIo::Cs(crate::native::ComputeIo { rsrc2: 5 << 1, threads: [1, 1, 1] }), + code: code.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + // `RAW_VIEWS` is a power-of-two bit (`index | first`), so 4 slots + 4 twins. + const LOCAL_TWINS: u32 = 4; + super::shader::RAW_VIEWS_HERE.set(Some(LOCAL_TWINS)); + let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let l = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + super::shader::RAW_VIEWS_HERE.set(None); + let l = l.unwrap(); + let mut dxil = l.dxil.clone(); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut dxil).unwrap(); + } + let cs = HostShader { + stage: super::HwStage::Cs, + dxil, + user_data: l.user_data.clone(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs.clone(), + root_srvs: l.root_srvs.clone(), + root_uavs: l.root_uavs.clone(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), + }; + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for (backend, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { continue }; + let (root, pso) = host.compute_pipeline(&cs).unwrap_or_else(|e| panic!("{backend}: {e}")); + for (source_bias, target_bias) in [(0u32, 0u32), (4, 8), (8, 12), (12, 8)] { + let s = (source_bias / 4) as usize; + let t = (target_bias / 4) as usize; + // Fill the pre-view prefix `[0..s]` with non-zero poison floats/ints (`0x7f7f_7f7f`) + // and the view's own dwords `[s..]` with known payload. + let mut src_words = vec![0x7f7f_7f7fu32; 32]; + for (offset, slot) in src_words.iter_mut().skip(s).enumerate() { + *slot = 0x6200_0000 | (offset as u32 * 0x0101); + } + let title_dummy = vec![0xdead_beefu32; 32]; + let strides = vec![ + 8 | source_bias << super::VIEW_BIAS_SHIFT, + 4 | source_bias << super::VIEW_BIAS_SHIFT, + 4 | target_bias << super::VIEW_BIAS_SHIFT, + 0, + ]; + let views = [ + View::Buffer { data: &title_dummy, stride: Stride::Raw }, + View::Buffer { data: &title_dummy, stride: Stride::Raw }, + View::RawUav(32), + View::Buffer { data: &title_dummy, stride: Stride::Raw }, + View::Buffer { data: &src_words, stride: Stride::Raw }, + View::Buffer { data: &src_words, stride: Stride::Raw }, + View::RawUav(32), + View::Buffer { data: &title_dummy, stride: Stride::Raw }, + ]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(vec![0; 5])), (1, Root::View { srv: true, data: strides })], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{backend}: {e}")); + let mut want = vec![0u32; 32]; + want[t] = src_words[s]; + want[t + 1] = src_words[s + 1]; + // Slots t + 2 .. t + 9 are all OOB reads and must be 0; pre-view `[0..t]` must stay 0. + let label = format!("{backend}, source_bias={source_bias}, target_bias={target_bias}"); + assert_eq!(out[1], want, "{label}: wrapped OOB accesses touched pre-view twin bytes"); + } + } +} + +/// A program picking structured buffers from `ResourceHeap` (`SLOT_STRIDES`) alongside biased raw +/// twins (`SLOT_TABLE_STRIDES`) validates cleanly and keeps `element = u32::MAX` out of bounds. +#[test] +fn resource_heap_structured_twins_validate_and_guard_wrapped_elements() { + let mut code = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x8F06_8500, // s_lshl_b32 s6, s0, 5 (slot 0 * 32) + 0x8F07_8501, // s_lshl_b32 s7, s1, 5 (slot 1 * 32) + 0xF408_0202, + 0x06 << 25, // s_load_dwordx4 s[8:11], s[4:5], s6 + 0xF408_0302, + 0x07 << 25, // s_load_dwordx4 s[12:15], s[4:5], s7 + ]; + // Read element `lane` (v0) at offset 4, and sentinel element `-1` at offset 4. + code.extend_from_slice(&mubuf(0x0C, 2, 0, 8, true, false, 4)); + code.extend_from_slice(&v_mov_lit(1, u32::MAX)); + code.extend_from_slice(&mubuf(0x0C, 3, 1, 8, true, false, 4)); + code.push(0x3408_0083); // v_lshlrev_b32 v4, 3, v0 (8 bytes per lane) + code.extend_from_slice(&mubuf(0x1C, 2, 4, 12, false, true, 0)); + code.extend_from_slice(&mubuf(0x1C, 3, 4, 12, false, true, 4)); + code.push(0xBF81_0000); // s_endpgm + + let native = super::NativeProgram { + stage: super::HwStage::Cs, + wave64: false, + vgprs: 6, + layout: vec![ + crate::RootParam { root: crate::RootType::Constants, table_offset_dwords: 0, sgprs: 4, base_register: 0, user_data: 0, slot: 0 }, + crate::RootParam { root: crate::RootType::ResourceHeap, table_offset_dwords: 0, sgprs: 1, base_register: 4, user_data: 4, slot: 1 }, + ], + used: Vec::new(), + io: crate::native::StageIo::Cs(crate::native::ComputeIo { rsrc2: 5 << 1, threads: [2, 1, 1] }), + code: code.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + super::shader::RAW_VIEWS_HERE.set(Some(TWINS)); + let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let l = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + super::shader::RAW_VIEWS_HERE.set(None); + let l = l.unwrap(); + assert!( + l.root_srvs.contains(&super::SLOT_STRIDES) + && l.root_srvs.contains(&super::SLOT_TABLE_STRIDES), + "ResourceHeap structured twin program declares both stride SRVs: {:?}", + l.root_srvs + ); + let mut dxil = l.dxil.clone(); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut dxil).unwrap(); + } + let cs = HostShader { + stage: super::HwStage::Cs, + dxil, + user_data: l.user_data.clone(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs.clone(), + root_srvs: l.root_srvs.clone(), + root_uavs: l.root_uavs.clone(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), + }; + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for (backend, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { continue }; + let (root, pso) = host.compute_pipeline(&cs).unwrap_or_else(|e| panic!("{backend}: {e}")); + for bias in [8u32, 12] { + let s = (bias / 4) as usize; + let mut src_words = vec![0x7f80_0001u32; 24]; + for k in s..24 { + src_words[k] = 0x3300_0000 + (k - s) as u32; + } + let dummy = vec![0xdead_beefu32; 24]; + let strides = vec![8 | bias << super::VIEW_BIAS_SHIFT, 1]; + let views = [ + View::Buffer { data: &dummy, stride: Stride::Raw }, + View::RawUav(16), + View::Buffer { data: &src_words, stride: Stride::Raw }, + View::RawUav(16), + ]; + // User data: s0 = 0 (slot 0), s1 = 1 (slot 1), heap base = 0. + let mut user = vec![0u32; cs.user_data_dwords() as usize]; + for u in &cs.user_data { + if u.root == crate::RootType::Constants && u.dword == 1 { + user[u.index as usize] = 1; + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(user)), + (1, Root::View { srv: true, data: strides.clone() }), + (2, Root::View { srv: true, data: strides }), + ], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{backend}: {e}")); + let mut want = vec![0u32; 16]; + want[0] = src_words[s + 1]; // lane 0: element 0, +4 bytes + want[1] = 0; // lane 0: element -1, +4 bytes -> OOB 0 + want[2] = src_words[s + 3]; // lane 1: element 1, +4 bytes (stride 8 -> +12 bytes) + want[3] = 0; // lane 1: element -1, +4 bytes -> OOB 0 + assert_eq!(out[1], want, "{backend}, bias={bias}"); + } + } +} diff --git a/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs b/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs index bf9cb76ec7..93443cd7fa 100644 --- a/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs @@ -1923,3 +1923,79 @@ fn a_loop_the_lanes_leave_one_by_one_is_left_by_each_host_wave_together_when_ask Err(_) => eprintln!("no dxil.dll: neither form validated"), } } + +/// A 1-D wave64 group (`[128, 1, 1]`) on a 32-lane host needs no entry ticket +/// barrier or LDS atomic: each host wave already has a consecutive run of flat +/// thread IDs, and every console thread 0..127 writes its own slot. +#[test] +fn one_d_wave64_group_skips_entry_ticket_barrier_and_keeps_thread_ids() { + // v_mbcnt_lo_u32_b32 v3, exec_lo, 0 (triggers console_lanes on a 32-lane host) + // v_add_nc_u32 v5, 1, v0 + // v_lshlrev_b32 v4, 2, v0 + // buffer_store_dword v5, v4, s[8:11], 0 offen + let words = [ + 0xD765_0003, + 0x0001_007E, + 0x4A0A_0081, // v_add_nc_u32 v5, 1, v0 + 0x3408_0082, // v_lshlrev_b32 v4, 2, v0 + 0x38 << 26 | 0x1C << 18 | 1 << 12, + 0x80 << 24 | 2 << 16 | 5 << 8 | 4, // buffer_store_dword v5, v4, s[8:11], 0 offen + ]; + let mut native = native_of(&words, true, 128); + native.io = StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, // 5 user SGPRs, thread id x in v0 + threads: [128, 1, 1], + }); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let bytes = crate::dxbc::build(&[]); + let c = crate::dxbc::Container::parse(&bytes).expect("container"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + lower::TEST_GROUP_SYNCS.set(0); + let shader = lowered(&native, &p, &HashSet::new()).expect("lower 1D halves"); + let halves_syncs = lower::TEST_GROUP_SYNCS.get(); + lower::TEST_GROUP_SYNCS.set(0); + let (paired_shader, _) = super::paired(&c, &native, &p, false).expect("lower 1D paired"); + let paired_syncs = lower::TEST_GROUP_SYNCS.get(); + lower::TEST_HOST_WAVE.set(was); + + assert_eq!( + halves_syncs, 1, + "1-D halves lowering should emit only the v_mbcnt exchange barrier (no entry ticket barrier)" + ); + assert_eq!( + paired_syncs, 0, + "1-D paired lowering should emit zero group barriers (no entry ticket barrier)" + ); + + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + for s in [&shader, &paired_shader] { + let mut copy = s.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + } + + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + return; + }; + let want: Vec<u32> = (1..=128).collect(); + for (label, s) in [("halves", &shader), ("paired", &paired_shader)] { + let Ok((root, pso)) = host.compute_pipeline(s) else { + continue; + }; + let ud = vec![0u32; s.user_data_dwords().max(1) as usize]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(128)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .expect("dispatch"); + assert_eq!(out[0], want, "{label}: every 1-D console thread 0..127 must write its own slot"); + } +} diff --git a/d3d12/docs/README-fxceless.md b/d3d12/docs/README-fxceless.md index bca384781e..d639c05735 100644 --- a/d3d12/docs/README-fxceless.md +++ b/d3d12/docs/README-fxceless.md @@ -116,6 +116,55 @@ Tools and diagnostics: a copy-back is about to put back to older values: none found in 138,000 copy-backs), `LEONIDA_WALLS_TRACE`, `LEONIDA_CARD_ACCOUNTING`, and a census of the copies the texture sweep never lets go. +- `LEONIDA_UNDECLARED_TRACE=1` (diagnostics builds, with + `LEONIDA_UPCOPY_CHECK=1`; off by default) tells, in the run where the + up-copy check flags a copy, what wrote its card side (`host/undeclared.rs`). + A copy flagged at a send or at rest in two frames is watched: 256 KiB of it + from the piece flagged, 16 copies at most. Every submission from then on + gets two looks of ours, one ahead of its lists (behind its sends, in a call + of its own) and one behind them (ahead of its compare), each comparing the + watched bytes on the card with a snapshot the card keeps and taking it + anew: the line `undeclared trace: <copy> at +a..b: submission N (frame F): + its lists changed W words in ...` (or `what went up ahead of its lists ... + changed`) names the submission, whether its lists or its sends changed the + bytes, their span and one word before and after (with "the sign flipped", + "from zero", "to zero"). A submission not looked at (the switch off for a + while under `LEONIDA_AB`, too many in the air) has the snapshot taken anew + at the next, which then says nothing of what changed in between. A change + by the lists lists what they told of those bytes while recorded: first + every write declared over them, by list, bind (the n-th draw or dispatch + since the watch began, with its program's shaders), the source line that + declared it (root view, view in a table, address stored by, copy at its + place) and what became of it (declared, kept on the card by + `LEONIDA_WC_NO_BACK`, elided, less the GPU read-only parts), kept apart + from the rest so that no number of other binds hides one; views picked + from the heap for the copy; the programs whose binds store past what their + bind declared, with how many binds and why (views picked from the heap, + stores by address, a table its bind did not go through, ...); and whether + what changed lies in a declared write at all. A change by the sends says + how many of its words the lists of an earlier submission had changed, and + which ("N of the W words were last changed by the lists of submission M": + the card keeps per watched word the submission whose lists last changed + it; a send undoing a shader's write), or "none of them", with the + refreshes the lists asked there, the title's copies done on the CPU into + the bytes in that submission, and the last submission whose lists wrote + values there at the bottom of the pipe or read texels back. A title that + rewrites what a shader then changes in place shows as sends over the + lists' words too, often with the same value each time; only a run with + `LEONIDA_WC_NO_BACK=0` tells the two apart. For that run, + `LEONIDA_UNDECLARED_WATCH=<hex address>,...` watches the copies that hold + those addresses from the first look at rest, flagged or not. A copy flagged again although nothing changed its watched + bytes on the card is said once (its CPU side moved). Two compare passes + over at most 4 MiB per submission; what the lists told is gathered only + for copies with lines left, 24 lines per copy, then sums every 4 s. Tests + on the card: a store through a view nobody declared is traced to its + submission and bind, and the send that undoes it to the next submission; + a send beside the lists' words is not said over them; a declaration in the + window is named ahead of more binds that store past their views than a + list keeps; a submission not looked at lays its change on no other; title + copies are said with the sends; both looks of the check have a copy + watched; declarations are noted with what became of them; off, nothing is + watched, noted or looked at. ### What this fork changed (summary) @@ -131,12 +180,56 @@ Rendering: Speed and memory: - Waits for memory values, write-watch queries and page queries no longer walk page tables per call. +- A submission's write-watch askings are planned by allocation: the ranges of one write-watched reservation are asked in one call that stops where the reservation ends, and a range the kernel would refuse (view memory, memory that is not write-watched, a range across two reservations) is left to the copy's own refresh, which goes to the guards for view memory as a refused range always did (`LEONIDA_ASK_BY_ALLOCATION=0`: by distance alone, as before). Before, runs crossed the ends of reservations and the views between them, were refused and asked again by halves: 259 askings a frame and 274 more refused in one run. Each allocation is looked up once per submission in the kernel's tree of allocations (0.4 microseconds on this PC; `VirtualQuery` walks the page tables, 16 ms for a written GiB); a page with nothing there, and an allocation sized in 4 KiB steps (whose last page reaches past it), are looked up once too, and runs end where such an allocation does. The frame line of asking about title memory counts the allocations looked up and those of them it cannot plan by (diagnostics builds). In a test of two reservations, plain memory and a view side by side: 2 askings and none refused, against 11 with 8 refused. +- A copy's refresh that looks at view memory it already knows for view memory goes straight to the guards, without first asking the kernel, which refuses view memory (`LEONIDA_VIEWS_UNASKED=0`: only with renderer port 6, as before). With the port off every such look at a block the title had opened by writing it was a refused asking first; the answer is the guards' either way. A block wrongly known for a view (other memory there now) is found no view by the guards and asked of the kernel, as before, and memory the title allocates is no longer known for a view. The askings so left out are counted in the frame line of asking about title memory (diagnostics builds), and in renderer port 6's line only with the port on, so that line no longer shows with the port off. +- A run of guarded view blocks that one change of protection cannot do (it lies across several views; the title maps runs of its pages as one view each) is made read-only, and opened again, a view at a time instead of a block at a time (`LEONIDA_PROTECT_BY_VIEW=0`: a block at a time, as before). Each change makes every core that runs the title forget those pages; a run across two views of sixteen blocks took 32 changes after the refused one, now 2. Where a view ends is one look in the kernel's tree of allocations (0.4 microseconds). It takes for granted what one change for a whole run already did: that the first block's protection speaks for the rest of its view. In a test of views of four, two and one blocks: 4 changes to guard the seven blocks and 4 to open them, against 8 and 8. - Large title buffers get a copy in card memory, with shader writes found by hashing on the card. +- The hash pass after a submission's lists hashes a 64 KiB piece once when several declared ranges of one copy lie in it (views a few bytes apart, which stay apart because only ranges that overlap or touch are joined), instead of once for each range (`LEONIDA_CARD_COMPARE_SHARE=0`: once for each, as before). Each range still reads its own flag for every piece and lands only its own bytes, and with the relay the second hash of a piece no longer races the first one's stored hash. On the RX 7900 XT (`host::comparecost`, [findings.md](findings.md)) a copy declared as four views in every piece is hashed in a quarter of the pieces and one pass instead of 12,289 (256 MiB): 0.57 -> 0.45 ms on the card; ranges that share no piece are hashed as before. The frame line gives the pieces the compare hashed and those it shared. +- Our own lists over these copies are timed on the card in diagnostics builds (`LEONIDA_CARD_OWN_TIMES=1`, **off by default**: in a `LEONIDA_AB` run in the world the stamps cost +2.8 % on the frame median, s.e. 1.9 %; `host::owntimes`): the list ahead of a submission (the ranges sent up, then the hash passes over them) and the compare behind it (from after its barrier on the title's shader writes, so the drain of the title's lists is not counted). Neither is in the timing run's table of commands (`LEONIDA_GPU_TIMING`, which notes commands inside the title's lists only), and the timeline shows the first as idle between submissions, so their cost was only estimated from trace gaps (about 0.4-0.5 ms a frame for the first and 0.6-1.1 ms for the compare in the world scene). Five timestamps per submission, read when its plan is given back: the card-passes frame line ends with `on the card per frame: sends up X ms in N lists, rehash Y ms, compare Z ms in M lists`, and a timing run lists them as `ours sends`, `ours rehash` and `ours compare`. A timestamp orders nothing; the stamp between the sends and the hash passes is written when the card has got that far, not necessarily when the sends ended, so the sum of the two is the surer number. Measured so on an RX 7900 XT in the world: sends up 1.2-1.3 ms a frame in about 13 lists, rehash 0.07 ms, compare 0.6 ms in about 15 lists. Builds without diagnostics record nothing. +- That compare can go to the queue in the same `ExecuteCommandLists` call as its submission's last lists, **off by default** (`LEONIDA_COMPARE_JOIN=1`), instead of in a call of its own before the submission's signal: a list of ours with one global barrier (every earlier access done and seen, copies' too) stands between the lists and the compare, which still runs after all of them and before the signal. The call of its own was for the state a title list can leave a host copy's buffer in (`COPY_DEST`, after a copy at its place; a buffer decays only at the end of a call), not for order: so the compare keeps its call where a list of that call copied into a host copy, and on a card without enhanced barriers. Each call more cost the RX 7900 XT 18-26 us of card time with everything already queued, for some 18 submissions a frame with a compare (0.3-0.45 ms a frame while the card is the frame). Off until the title has run with it under the debug layer and GPU-based validation, which must also judge host copies a title list wrote as unordered access (a write state too, read by the joined compare in the same call; the copy flag does not keep those apart); tests on the card and WARP cover the flags and that a copy keeps the call, and say whether the debug layer was there to check the states (without the SDK layers it is not, and they say so). In a `LEONIDA_AB` run of 68 phases in the world on that card it moved the card's busy time -1.2 % (s.e. 0.9 %) and the frame median -1.4 % (s.e. 1.9 %): within the noise, in line with the 0.3-0.45 ms. The frame line of submissions sent ahead counts the compares sent in their lists' call and apart, and why (`host/compare_ecl.rs`). +- What the title's CPU wrote into such a copy goes up to the card straight out of the copy's CPU side, copied once on the CPU instead of twice (`LEONIDA_SEND_DIRECT=0`: through each submission's own memory, as before). The title's buffer copies that the runtime does at submission still go through that memory, and before one is written where a submission in the air has yet to read, the runtime waits for the card; the frame line counts those waits, with or without the relay. +- Each submission's own memory for what it sends up is carved out of a ring of mapped upload buffers (usually one open buffer; closed ones go once their carves have landed) instead of being a buffer of its own from a pool of spares (`LEONIDA_SEND_RING=0`: the spares, as before). A carve is free again once its submission has landed and so has every carve made before it, so nothing is reused while the card may still read it, even when submissions land out of order. A new, larger buffer is made when a carve does not fit (sized from the bytes in flight, an eighth over them plus twice the largest carve); the buffer it replaces goes once its last carve lands; the once-a-second sweep closes a buffer more than twice what recent submissions needed and lets every buffer go after the idle time with no submission. A send of more than 64 MiB gets a buffer of its own and does not count in the sizing of the ring. On by default: the bytes on the card are the same, and the reuse hazard is covered by tests (20,000 carves landing out of order; six submissions in flight on the card each reading its own bytes from one buffer). In a simulation of 30 sends of 1 to 5 MiB a frame, the spares made 121 buffers (a committed resource each, made resident) and the ring 6, none after warm-up, and once warm the ring held 352 MiB against 391; while it grows it briefly holds the old buffer too (640 MiB at most in the first frames). Not measured in the game; the frame line counts the buffers made for sends. +- A large title buffer's card copy can have the title memory itself as its CPU side, **off by default** (`LEONIDA_CARD_FROM_TITLE=1`): where the memory opens as a graphics heap (private memory committed whole, or one run of a committed section, from a 64 KiB line on), the copy's second buffer in the PC's memory is not made, the refresh notes the pages the title wrote without copying them, and the card copies them out of title memory into its side (with `LEONIDA_SEND_DIRECT`, no CPU copy of the title's writes at all; the card reads opened title memory as fast as upload memory, 23-28 GB/s on the RX 7900 XT). The memory line counts such copies and the RAM not taken. Title writes after a submission was prepared are taken as with `LEONIDA_SEND_DIRECT`; the runtime's own writes at submission (buffer copies done on the CPU, copies at their place, `CopyMemoryToMemoryX`) wait for the straight sends in the air first. The first declared shader write (or a kept undeclared store) gives the copy a PC-memory side of its own, filled from title memory and sent up whole once, since the merge needs what the card held before the shaders ran; the title's frees, decommits and protections of the memory, and remaps of a section, do the same before the next submission, and the title's call is made once the card is done with the old heap. Off until a game run measures it: tests on the card cover the zero-copy refresh, the ordering of the runtime's writes, the late declared write and the free through the runtime's path; but a buffer shaders write early pays for opening its pages (which locks them in memory) and a full copy right after, the opening is a one-time hitch per buffer for every recording thread (it is done under the buffer table's lock, which the title's frees of the memory rely on), and the title's free of such memory now waits for a submission. Not with `LEONIDA_SEND_CHANGED=1`, nor with `LEONIDA_INPLACE_FREE=0` or `LEONIDA_INPLACE_PROTECT=0` (nothing would let go of the heap, and the title's frees and protections of the memory would fail while the copy lives). With the switch on, windows of title memory outside buffers that get a side in the card's memory (`LEONIDA_CARD_WINDOWS_MB`) have title memory as their CPU side the same way, with the same hazards handled (tests on the card for each but a section's remap, which no test covers for windows or buffers, and for a protection of the memory through the runtime's path); `LEONIDA_CARD_FROM_TITLE_WINDOWS=0` keeps them on a side of their own, as before. The window is opened under the window table's lock each time it is made, and a window the idle sweep let go of is made again at its next ask: a hitch for every recording thread that asks for a window then, of a few milliseconds at most for 4 MiB (openings took 1 ms for 1 MiB and 2 to 6 ms for 16 MiB on the RX 7900 XT; not measured for windows in the game). Not for memory by address (its copy sends only the dwords that differ from its CPU side) nor for windows with two sides in the PC's memory (`LEONIDA_WINDOWS_OWN=1`). A send of a window still in the air may read some of the bytes a copy-back of shaders' writes to a title buffer inside it puts into title memory, where a side of its own took none of them until its next refresh. +- The log's first lines say whether the card's memory is open to the CPU (a resizable BAR, Smart Access Memory): Direct3D's `GPUUploadHeapSupported` and the size of the card's memory window, 256 MiB when the BAR is off in the firmware. Without it every option that puts memory the CPU writes in the card's memory falls back to the PC's memory. The placement benchmark (`host::placement`) ends with the GPU upload rows beside the others, or says why there are none. +- Small title buffers (below the card-copy size) can have their copy's card side in card memory the CPU maps and writes, **off by default** (`LEONIDA_BAR_BUFFERS_MB=<MiB>`, a budget; needs a resizable BAR). Only buffers that are read often and never written by shaders get this: a copy starts in the PC's memory as before, and the once-a-second sweep makes it again in card memory after 16 submissions have read it and no shader was declared to write it. If shaders later write it, the sweep moves it back to the PC's memory for good. The sweep only moves a copy that no list and no descriptor slot holds, so a buffer that is always held stays where it is (the sweep line in the trail counts the moves). For the buffers that move, shaders then read them from the card's memory instead of over the bus, and what the title's CPU wrote goes up by the CPU writing it there at the next submission, with no card copy. The copy keeps its side in the PC's memory, which every CPU read of it uses: the card side is never read by the CPU (write-combined memory reads about 150 times slower). The runtime's own buffer copies at submission still go through the submission's memory behind what the card has yet to run, and shader writes are found on the card as for large buffers. Tested on the software adapter; not measured with the game, and the test PC has the BAR off. - Submissions can be sent ahead of the wait for the card (`LEONIDA_LATE_WAIT`), with a relay thread that lands results as the card finishes (`LEONIDA_RELAY`): in a first five-minute run the card's idle time behind the submitting thread fell from about 136 to 30 ms per frame. +- With the relay, a queue's wait for a memory value that flights in the air may write waits only until the last of those flights has landed, not until all of them have, and the game's blocking wait for a fence only until the fence is set (`LEONIDA_EXACT_WAIT=0`: until all of them, as before). How often they waited, and how long, is in the frame line ("a memory value", "a blocking fence wait"); the saving in the game is not measured yet. +- With the present sent ahead (`LEONIDA_LATE_WAIT=3`, the relay's default), the once-a-second sweep that lets idle host objects go runs behind the submissions in the air instead of making one submission every 1.5 s wait for the card to run dry first (`LEONIDA_SWEEP_NO_SETTLE=0`: that wait, as before). Everything the sweep frees is either held by the submissions that use it or freed only after they have run. The wait stays for the diagnostic up-copy check and for `LEONIDA_COMPARE_RING=0`. Its cost was never measured on its own (the frame line counts it with the presents' waits). +- With the relay, a submission waiting for submissions in the air to land before it reads title memory they may write checks whether it can go on without holding the lock that the landing thread and the game's fence signals also need (`LEONIDA_LINE_APART=0`: it looked through all of its steps after each landing with that lock held, as before); so does one that waits before refreshing memory they write. The time saved is not measured. +- With the relay, the thread that lands flights (`leonida-relay`) can run above normal, as the submitting thread and the helpers it waits for do (`LEONIDA_RELAY_PRIORITY=1`; off by default: at normal, as before; `LEONIDA_AB` can flip it while the title runs). It sets the title's fences once a flight's bytes are in title memory, and the title's busiest thread spins on such a fence's value (about 72 % of its samples in a 30-second profile in the world); at normal, among some twenty busy title threads on twelve logical processors, its landings had gaps of 3 to 5 ms with no wait in them, and the tails of its gathers, fetches' sends and wakes came to 0.8 to 3.3 ms a frame in two timelines, while 894 of its 975 profile samples were waits. Above normal only: the pools of `land` it hands pieces to run there too. Nothing it does, nor its order, changes, so no fence is set before its flight's bytes. Tests: a priority that follows the switch is above normal while it is on, normal while it is off, and asked of the system only when it changes; the relay's start leaves it as the switch says. In the game (one `LEONIDA_AB` run of 67 phases of 7 s, four switches crossed) it gained nothing: the median frame +1.6 % (s.e. 1.9 %), the submitting thread's work +1.4 % (s.e. 1.2 %), hence off. +- With submissions sent ahead, the list of title memory they may write is kept up to date as each one is sent and lands, in one pass, instead of being sorted again from all of them each time, under the same lock (`LEONIDA_LINE_COVER=0`: sorted again, as before; read once at start, so it cannot be one of the switches `LEONIDA_AB` turns on and off: compare two runs). In a test with 16 submissions of 1,024 ranges each it does about an eighth of the work; the time saved in the game is not measured. +- With the relay, what shaders wrote to copies in card memory can come down in the submission that wrote it, **off by default** (`LEONIDA_LAND_IN_SUBMISSION=1`, which `LEONIDA_AB` can flip): two passes after the card's compare number the changed 64 KiB pieces and copy them into a buffer in PC memory, so the landing thread merges them once the submission's own fence is reached, instead of sending a fetch of its own and waiting for it behind whatever was sent meanwhile (before: 48 ms of a 120 ms frame waiting for seven fetches of 94 MB). Pieces past a plan's room (sized by the last plans, `LEONIDA_LAND_IN_SUBMISSION_MB`, 256, in all), ranges not compared and pieces an earlier fetch may hold newer (noted by the sends known to have gone to the queue ahead of it: on the drawing queue the count it went there under) still come down with a fetch, merged after them; a piece held whole by an earlier fetch that ran after its flight is left out, neither merged nor fetched (before, with fetches noted by the last send after their wait and nothing left out, a piece flights kept writing was fetched again by every landing on the drawing queue, for good). Tests on the card cover the landed bytes, title writes in between, flights landed together, the room running out, an earlier fetch newer than a capture, and with the relay's order of sends the notes later captures need and flights sent after a fetch landing with no further fetch; but every flight's changed pieces cross the bus, where one fetch brought a piece several flights changed once. The frame line counts what it landed and fetched, and how many plans landed were made to capture and how many to fetch. The switch is read once per plan, when it is made, and kept in it (`landsame::Capturing`): `LEONIDA_AB` can flip it per phase in diagnostics builds, and a plan in the air lands as it was made whatever the switch says by then; what a landing keeps for later captures (the notes of sends they are merged against, and fetches noted as maybe newer than them) is kept while any plan alive was made to capture, not by the switch at the landing (tests on the card: flights made on, off, on, off, and a flip between a plan's making and its landing). In a first run in the world on the RX 7900 XT (270 s, one run per configuration) it landed 1,392 pieces (49.7 MB) a frame in their own submission with none past a plan's room, the relay's landing went from 10.2 to 6.8 ms a frame and its waits for fetches from 3.9 to 0.0 ms, the frame 49.5 ms against 49-52 ms without, and nothing failed; `LEONIDA_AB` phases then weighed it in the same scene (67 phases of 7 s, about 1,410 pieces, 50 MB, a frame landed in their own submission): frame median +0.6 % (s.e. 2.5 %), the card's busy time +1.1 % (s.e. 1.5 %), the submitting thread +1.3 % (s.e. 1.5 %). The relay is not what the frame waits for, so it stays off. Not with the relay off, and not straight into title memory opened in place (`host/landsame.rs` says why). +- The pass over the heap's buffer views that the list ahead of each frame records can be looked ahead of, **off by default** (`LEONIDA_HEAP_PRELOOK=1`, every `LEONIDA_HEAP_PRELOOK_MS`, 3): while the thread that records that list waits for the present, it looks every few milliseconds at the slots the title wrote since its last look and, once a pass, at the coming pass's sixteenth of the others, making their host descriptors and finding their copies; the pass then looks only at slots written since, and at those whose look no longer holds (another record in the slot, written by a call or as bytes; its host slot let go of or made again; a draw's table has it; the view's resource released), and keeps the rest as found; slots that showed nothing at the look (a draw's table had them then, their memory had no copy yet) it looks at again, and a panic in a look gives it back the written slots and its part. It works only with the list ahead recorded by a thread of its own (`LEONIDA_PASSES_AHEAD` on, not `=2`) and with `LEONIDA_HEAP_SPREAD` on; without, no look is made and the switch changes nothing (the frame line counts none, and with the passes ahead off is not printed). The list took 13.8 ms to record in the title's world and the submitting thread stood 13.3 ms a frame waiting for it at the frame's first submission (4.9 ms of the list looking at some 29,000 slots); not measured with the switch. What changes: a written slot shows its buffer from the look on, where it showed none until the pass; lists sent in between that read it by index (which the title, having written the record, does not do) read the copy as its last refresh left it instead of zeros. Tests: the pass looks at 5 slots where it looked at 10 (the written ones, the ones changed under the look, the tables'), and keeps for each slot the copy and range a pass of its own finds, its host slot made from the record it holds; a slot a draw's table had at the look but not at the pass shows its buffer after the pass, and after a look that panicked the pass shows the written slots and its part as a pass of its own does. The frame line counts the looks and what the passes kept and looked at again. +- The spans of host copies that the pass over the heap's buffer views keeps for each sixteenth of the slots are made again, for every sixteenth whose slots changed so that its spans cannot be put right in place, in one walk over the slots taken 4,096 slots at a time, instead of one walk over all of them for each such sixteenth (`LEONIDA_SPANS_ONE_WALK=0`: a walk for each, as before; one sixteenth alone keeps its own walk). A slot's range is 24 bytes, so each of those walks read a line of memory for every slot it looked at, 384 bytes apart; in a sampling profile of the title's world 729 of the 2,717 samples of the thread that records the list ahead of each frame, between the present and the first submission, were on the one load of that walk, while the submitting thread waited for that list 5 to 7 ms a frame. In the benchmark `spans_of_a_pass` (a Ryzen 7 5800X, slots out of the caches) 72,000 of 1,152,000 slots showing something with 8 or 16 sixteenths to make again took 1.42 and 1.98 ms instead of 1.91 and 3.26; with every one of 72,000 slots showing something and all sixteen to make again, 1.64 ms instead of 1.46, the tables of the sixteenths being taken in turn block by block. The spans are the same either way (`heap_range_tests`). The heap pass's line in the frame-rate lines (diagnostics builds) says how many sixteenths a pass made again, in how many walks over the slots, and how many of its slots show something; the one walk was slower only with every slot showing something, so a run whose line shows the slots mostly showing something is the one to compare `LEONIDA_SPANS_ONE_WALK=0` on (`LEONIDA_AB` can name it) before the default is relied on there. The one sixteenth that keeps its own walk is seldom the pass's own, which it forgets before setting its slots again and so does not make stale; it is mostly one the title wrote to. - Independent host-copy refreshes run in parallel by default on systems with at least four logical CPUs (`LEONIDA_WIDE_REFRESH=0` disables this; `=1` forces it). This targets the serial memory reads that previously cost about 45–50 ms per frame on the test run. -- Title memory can be opened as a graphics heap so that buffers are used in place instead of copied (`LEONIDA_INPLACE`, first stage only; a probe confirmed the approach on the test GPU). +- Which of a submission's refreshes copy nothing (nothing was written since the copy last took its range) is looked at on the submitting thread, one after the other, before any thread is woken, however many there are, and only the refreshes that may copy are spread over the threads; none is woken for a flush that ends up with fewer than two (`LEONIDA_LOOK_FIRST=0`: a flush of more than 256 refreshes, or the copies a submission's shaders write, looked at on the threads, as before). A look takes the write watch's locks for a moment: about 30 ns on one thread, but on eight at once each look takes those locks' memory from the others. 4,400 copies nothing wrote: 0.65 -> 0.24 ms a flush in front of the steps, 0.47 -> 0.17 ms in flushes between them (test `refreshes_of_nothing_written`, release build, RX 7900 XT PC of 8 cores); in a five-minute game run some 5,750 of a frame's 6,590 refreshes were of that kind. The looks and the refreshes are the same, and all looks still come before the first refresh, as they always did for 256 or fewer; looks that take longer than 1.5 ms leave the rest to the threads (the clock is asked every 64 looks, each 64 KiB page of a look's range counted as one, so after every look of 4 MiB or more, whatever the number of refreshes; with `LEONIDA_PORT_GUARD=1` this is how long a submission's looks stay on the submitting thread). On by default; the saving in the game is not measured yet. +- A refresh whose range ends inside a 64 KiB page that the title wrote since only in 4 KiB pieces beside the range is known to copy nothing, as the refresh would take none of it (`LEONIDA_LOOK_PARTS=0`: any write in the page made it a refresh like one that copies, handed to the threads with those, as before). In view memory what the guards see is noted as the whole block, so a title write there still counts for the whole page; the 4 KiB pieces our own landings write beside a range there are honoured, as the refresh honours them. 1,000 copies of 160 KiB one after the other, written beside: 0.24 -> 0.10 ms a flush, 100 of them 0.029 -> 0.008 ms (test `refreshes_beside_writes`, release build, RX 7900 XT PC); how many of the game's refreshes are of that kind is not measured. +- Title memory can be opened as a graphics heap so that buffers are used in place instead of copied (`LEONIDA_INPLACE`, first stage only; a probe confirmed the approach on the test GPU). The title can free such memory: what is in place there is let go first and the free is done once the heap is gone (`LEONIDA_INPLACE_FREE=0`: as before, the free fails with error 87 and both stay). Descriptor slots that view a buffer over memory the title frees let go of it then, instead of when the title next writes them (`LEONIDA_INPLACE_SLOTS=0`: as before, and the free can wait for good). The title's `VirtualProtect` of such memory lets go of what is in place in its 64 KiB pages and is made once the heap is gone, the title told it is done; the slots that view those buffers let go of them only once the submissions sent before have run, since the card may still read protected memory (`LEONIDA_INPLACE_PROTECT=0`: as before, it fails with error 87). A 64 KiB page with mixed protections is never opened, so what the title reads there meanwhile is copied; once it gives read-write back to all of the pages such a heap stood over, those copies are opened in place again in the background and take their place once no descriptor slot views them (`LEONIDA_INPLACE_AGAIN=0`: as before, they stay copies for as long as they are used). A reservation at a fixed address where such a free still waits does the free first if the heap has gone (`LEONIDA_INPLACE_RESERVE=0`: as before, refused until the next check, every 100 ms). A commit there without a new reservation is refused while the heap stands, as the console refuses a commit of free memory, instead of being taken inside the reservation kept for the title and taken away with the free later (`LEONIDA_INPLACE_RELEASE_FIRST=0`: as before). The title's own `VirtualAlloc`, `VirtualAllocEx` and `VirtualProtectEx` (kernel32, kernelbase and the memory API sets) go through the same glue as `XMemVirtualAlloc` at an address of the title's and its `VirtualProtect` (`LEONIDA_INPLACE_TITLE_ALLOC=0`: as before, bound to the host's own, which took such a commit inside the reservation kept for the title and refused such a protection with error 87). On a timeline (`LEONIDA_TIMELINE`) the title's `VirtualAlloc`, `VirtualFree` and `VirtualProtect` show only the host's call inside that glue, through the runtime's own wrapped imports, not the glue's own waits around it (for an opening in progress, or up to 50 ms for a heap's pages before a reservation). The title's `XMemVirtualQuery` is told what it asked for where the runtime does it later for such a heap: a protection that waits reads as made, a release that waits as free memory (`LEONIDA_INPLACE_QUERY=0`: as before, what the host has until the heap is gone). A decommit such a heap is in the way of, kept committed and zeroed, reads as reserved memory, as the title asked, until the title commits those pages again through `XMemVirtualAlloc` or its own `VirtualAlloc`, or frees them (`LEONIDA_INPLACE_QUERY_DECOMMITS=0`: as before, committed graphics memory until the title releases the allocation). In place now takes the place only of a copy kept in PC memory alone, which the card read over the bus as fast as the title memory itself (measured on the RX 7900 XT): a window that gets a side in card memory (`LEONIDA_CARD_WINDOWS_MB`) or mapped card memory (`LEONIDA_WINDOWS_BAR_MB`) keeps it, and at level 2 a big title buffer the card's memory turned down is opened in place instead of copied (`LEONIDA_INPLACE_LAST=0`: as before, in place first, and never for a big buffer). With it on, memory the runtime owns is no longer copied as if it were the title's: the 4 MiB upload arenas of the lists are read in place, and the 16 MiB directory of memory by address is its own copy's CPU side, sending the entries written instead of being compared with a second 16 MiB buffer at every list (`LEONIDA_INPLACE_OURS=0`: copied as before). Private title memory is opened by a thread of its own, not by the list thread that asks for it under the tables' lock (1 to 6 ms a part on the RX 7900 XT): the ask gets a copy, and what was opened goes in place at the next ask of it, or in the place of that copy before a submission once no descriptor slot views the copy and shaders were never declared to write it (`LEONIDA_INPLACE_ASYNC=0`: opened by the ask, as before). The title's frees and protections, on any thread, wait for an opening in progress: about 1 ms for 1 MiB and 2 to 6 ms for 16 MiB on the RX 7900 XT, but 36 ms for a title buffer of 256 MiB at level 2, which is opened whole (70 ms on the software adapter), and those that come while the opener waits for its turn wait behind it; how long the game waits so is not measured. Lists that still hold the copy keep it, bring it up to date at their submission as before and let go of it at their reset, while lists recorded after get the title memory in place: memory read every frame is always held by some list, and was never switched before (`LEONIDA_INPLACE_SWITCH_HELD=0`: as before, only a copy no list holds, so such memory stayed a copy). Until those lists let go, shaders declared to write either the copy or what is in place could leave a later list reading the bytes from before until the copy-back; only memory shaders were never declared to write is switched, and such writes are counted on the in-place say line (none seen in the tests; not measured with the game). +- The snapshot a host copy in PC memory keeps to find what shaders wrote holds only the 64 KiB pieces of the declared ranges, not the whole copy (`LEONIDA_SNAPSHOT_DECLARED=0`: the whole copy, as before). +- A buffer copy done on the CPU finds the card-memory copies it writes by address instead of going through all of them (`LEONIDA_CARDED_INDEX=0`: through all, as before). +- What a command list's recorded steps say that does not depend on what title memory holds is found once, when the list is closed, by the thread that records it (`LEONIDA_CLOSE_SUMMARY=0`: as before; `check`: both, compared, counted on the frame line). The submitting thread went over every step of every list again for each question it asks at submission (whether submissions in the air stop it, asked again after every landing the relay waits through; which refreshed copies they may be writing; what the write watch is asked about; what shaders may write), with each list's lock held for the walk. Now it asks the same of each list's summary: the title memory its steps read up to its first step of ours, the copies done at their place, per copy the span of its refreshes, and its declared writes. What changes between the close and a submission (what is in the air, which copies shaders are writing) is still asked at submission, and nothing takes a summary out, so a list submitted twice has it both times. With `LEONIDA_FILL_TITLE`, when a copy at its place waits only for its readers, and once a submission is stopped by a read (for the frame line's count and name of what stopped it), the steps are walked as before. Tests compare every answer with the steps' over random lists of every kind of step but textures (a texture's step needs a title texture); not measured with the game. With `check`, what stops a submission can differ by a landing's timing alone when `LEONIDA_PLACED_TITLE=1` (both answers ask what landed lately, one after the other); the other answers are compared by one answer per copy. +- An indirect execution's host command signature is found in a table with a slot for each kind of argument and stride, filled once and lent for the process's life, with no lock taken and no reference of its own (`LEONIDA_SIG_TABLE=0`: out of one list under one lock, with an `AddRef` and a `Release` of the shared object, as before). About 13,000 executions a frame on up to eight recording threads queued on that lock: 0.1 to 4.8 ms of waiting a frame in three scenes, once six threads standing still for 3 ms together because the one holding it had been taken off its core. A packed dispatch's signature, which also depends on its root signature, is looked up under a shared lock and made outside it. A kind or stride past the table (not of dwords, or 128 bytes or more) goes to the list as before; a refused signature is kept as refused (a packed one with its root signature, so that address is not reused for another root while the refusal is kept). Tests: eight threads asking 100,000 times each make each signature once and are lent the same one, and a thread looking up one made before does not wait while another is being made (with the list it does), both without a GPU (`draw::sigtable`); with one, the host signature is one object on every thread either way. Not yet measured with the game. +- Bookkeeping off the hot paths, with nothing reported changed and no switch (nothing drawn or paced depends on it): releasing a resource no longer goes through every texture the card copied into (a buffer's release skips those tables altogether), and in the diagnostics build that is played the per-range counts of copies and comparisons take a lock per set of threads instead of one for all, which every parallel host-copy refresh waited for. Whether a new texture still needs hashing at every check for its first 64 frames, now that the guard sees writes through the title's other views, was looked at and left as it is: writes the guard does not see remain, uncounted (see `hot_textures` in `texture.rs`). +- The title's physical pages come in sections of 16 MiB by default, not one section for each allocation of gigabytes (`LEONIDA_SECTION_MB=0`: one section, as before): measured on an RTX 4060 Ti, 111.6 -> 94.4 ms a frame on average and title memory held for mapping changes 43.2 -> 8.9 ms a frame; what it saves is Windows' work per view of a section, so it applies on every card, not only through the NVIDIA launcher that set it. +- Sections of physical pages of up to 64 MiB can be made when a page of theirs is first mapped or written, committed whole (`SEC_COMMIT`), instead of reserved with the allocation, **off by default** (`LEONIDA_SECTION_COMMIT=1`): no commit call for each page the title maps, and the host opens such a section as a graphics heap (it refuses a reserved one), the first step to reading the page pool in place. It charges a whole section of commit (16 MiB) for each section touched, against 64 KiB for each page used; the commit a session charges and the calls it saves are not measured with the title yet. With `LEONIDA_INPLACE` on as well, a window or title buffer that is one run of such a section is read by the card in place in its section, a buffer placed in a heap opened on the section, instead of copied; opening a section locks nothing, so the title's frees and protections of those pages are not held up, and what is in place there is let go when the title maps other pages at the address, and by the descriptor slots that view it before the next submission, so that they are made again from what the address shows then (`LEONIDA_INPLACE_SLOTS=0`: a slot keeps the old pages until the title writes it again; `LEONIDA_INPLACE_SECTIONS=0`: copied as before). Where Windows refuses a section's commit, that section is made reserved as before, but commit taken early by the pool can make other allocations fail with error 1455. +- Whether a window of title memory made of scattered 64 KiB pages of the page pool could be read in place through tiles (a reserved buffer whose tiles are mapped onto the pool's section opened as a heap, the console's own page table) is asked of the card with `LEONIDA_INPLACE_PROBE=1 LEONIDA_INPLACE_PROBE_TILES=1` (**off by default**), after the in-place probe, on a device of its own made by the device factory so that a refusal removes that one and not the title's (`inplace/tiled.rs`; the ignored test `card_tiles_over_a_committed_section` runs it on the card beside a device made as the host makes the title's). On the RX 7900 XT that device reports no removal and still copies after the probe's four removals; other cards and drivers are not shown, nor the title's process, hence asked for rather than on with every `LEONIDA_INPLACE_PROBE=1`. On the RX 7900 XT (tiled resources tier 4) and the software adapter Direct3D refuses it: the mapping removes the device (`DXGI_ERROR_INVALID_CALL`) on the section's heap, on private memory opened in part, and on a heap of ours made shared and cross-adapter, while one made shared alone takes the tile; every heap opened on memory the process has is cross-adapter, so no tiled window over title memory on Windows (VKD3D-Proton not asked). The same steps on a heap of ours hold and give the costs: `UpdateTileMappings` of 1, 64 and 1024 tiles a range each, 15 to 19, 23 to 30 and 2,021 to 2,197 us of CPU and 0.2, 1.1 to 1.3 and 20 to 26 ms until a fence after it (two runs); reads through scattered tiles as fast as through one placed buffer (27.5 against 26.9 GB/s). In diagnostics builds with `LEONIDA_INPLACE` on, a line every ten seconds counts the asks turned down as view memory not one run of a committed section: how many tiles could hold (every page in a view of a committed section), their pages and sections, and how often the title maps or unmaps pages under those still alive; only counted, no switch (a walk over the views of each such ask, one relaxed load per mapping while none is alive, the list of copies every ten seconds). Not run with the title yet. +- Physical pages the title frees are given out again by its next allocations instead of new sections, zeroed, once no view shows them; while they wait, the host takes back the memory of those no view showed when they were freed (one freed while still mapped stays resident until given out again; `LEONIDA_PHYSICAL_REUSE=0`: as before, freed pages stay committed for as long as the rest of their section; `LEONIDA_PHYSICAL_DISCARD=0`: reused, but kept resident while they wait). With `LEONIDA_SECTION_COMMIT=1` the same holds for sections made at their first page: the pages given out again charge no new commit. Page numbers no longer run past the 21 bits the title keeps them in after 124 GiB of allocations. An allocation looks only at the waiting runs it gives (longest first, as before, and the same pages; at all of them, every page, when fewer wait free of views than it asks for, and at every page of a run that views split), not at every page waiting with all their runs sorted under the page table lock; no switch, since only the time taken changes. +- Blocks of 64 KiB or more, or aligned to 64 KiB, that the title's allocator passes on to `XMemAllocDefault` are write-watched reservations below 2^40 of their own instead of heap blocks, so their host copies refresh only the pages written (they were copied whole every time) and a 64 KiB-aligned block no longer costs 64 KiB more than it asks (`LEONIDA_XMEM_DEFAULT_WATCHED=0`: all from the heap, as before). +- The heaps the title makes through the device (`CreateHeap`) are write-watched reservations below 2^40 from xmem, as console heaps are title memory, instead of our allocator's memory: the host copies of resources placed in them refresh only the pages written, the GPU side forgets what it noted there when a heap goes, and a heap can be opened in place (`LEONIDA_HEAP_WATCHED=0`: our allocator, as before). +- `XMemGetWorkingSetStatistics` tells the title the memory it was given (its commit through xmem, its physical pages, its default-allocator blocks) instead of the whole process's commit, which counted the runtime, the host copies and the driver (27 GB against a limit of 13.5 GB in one run), so the title no longer believes it is twice over its budget; the log line gives both figures (`LEONIDA_WS_TITLE=0`: the process's commit, as before). +- A write-watched texture the title writes part of is read, detiled and copied to the card only in the subresources the written 64 KiB pages hold, once it changes often enough to keep its staging buffer (`LEONIDA_TEXTURE_PARTS=0`: the whole texture, every level and slice, as before). Textures read through the hash or the guard, levels on demand, 3D and multisampled ones are still done whole; the saving in the game is not measured yet. +- A write-watched texture can be detiled straight out of title memory instead of out of a copy of it in a read buffer of up to 16 MiB per refreshing thread, **off by default** (`LEONIDA_TEXTURE_WATCHED_IN_PLACE=1`): the title's own frees and protections of such memory (its `VirtualFree` and `VirtualProtect`, and the ones the runtime makes for it later) then wait until no texture is detiled from those pages, and a detiling does not begin while one is under way (it reads through the copy then). Off because a title thread's free can now wait for a detiling and memory taken away by any other route would fault instead of reading zeros; neither is measured. Off, those frees and protections take no lock for it, as before. +- A texture's staging state is made, and staging buffers and states are let go of, with the table of staging states unlocked (`LEONIDA_STAGING_SHORT=0`: under its lock, as before). Making one lays out the texture, asks the host for its copy footprints and takes a staging buffer (a pool piece zeroed, megabytes written, or an upload buffer of its own); letting go gives pieces back to the pool or releases buffers. Every recording thread that samples a texture the title fills asks that table, so while textures streamed in, draws and dispatches on the other recording threads waited behind that work for textures they already had a state for, and the card idled between submissions. Now the table's lock is held only to look up, put in or take out an entry: two threads that make the state of one texture at once both make it, the first put in stays and the other's buffer goes back to the pool; a state made while its host copy went or was replaced is not put in (a count of the states taken out, and its host copy asked again), and a texture's release waits for a make of its state under way, as it waited for the lock before (the make reads the title texture). Tested on the CPU with tables of the same kind (a look-up does not wait behind a make; two makes leave one entry; what goes, goes with the lock free; a release waits for its own texture's make only) and on the host through `staging` (another texture's state is found during a make; a state made across a host copy's replacement is not put in); not measured in the game yet. +- A texture read back for the title's CPU (the water maps) is tiled into title memory straight out of its mapped read-back buffer instead of a copy of it allocated at each landing, as long as every submission of its list has landed; one whose list is submitted again while it is tiled is left to that submission's landing (`LEONIDA_TEXBACK_MAPPED=0`: copied out at the landing, as before). +- Samplers in the view table are let go as the views carrying an address are, once the table holds `LEONIDA_VIEW_ADDRESSED_MOST` (1,048,576) of the two kinds: one that no record in a view or sampler heap names (CPU-only heaps too) and that nothing looked up for a round of the clock (`LEONIDA_VIEW_SAMPLERS_BOUND=0`: every sampler kept for the run, as before). A title that writes samplers with ever new values (a mip bias that follows a dynamic resolution, say: whether this title does is not measured) added one entry each for the run; below the most nothing changes. A sampler record the title keeps outside every heap for a whole round, unread, and copies back finds its sampler gone (the point stand-in), as a view's does. +- The card copies of textures the title placed in its own memory go within seconds once the title unmaps or frees that memory, instead of after the card's idle time (ten minutes while it has room; `LEONIDA_PLACED_UNMAPPED=0`: kept until then, as before). The runtime notes where the title unmaps; the once-a-second sweep then lets go of the copy of each placed texture whose first page lies there and is still not mapped, on the same terms as any copy it lets go: out of use for 2.5 s and 60 frames, held by no command list not yet reset and no descriptor slot, never written by the card. The runtime is told of an unmapping before the memory goes, so a texture whose first page the sweep finds still mapped is looked at again at its next looks, and given up as the title's again only once found mapped for 5 s; a free the host refuses until one of our heaps goes and that is done later than that (up to 30 s) still leaves its copies to the idle time. A texture the title maps memory under again is made again from title memory at its next use. In a world run on the RX 7900 XT before this, the memory line estimated 1,443 MB of such copies over memory no longer mapped, none shown by a slot; not measured in the game since. On by default: only when a copy goes changes, and tests cover a copy a list holds, one a slot holds, one used lately, memory mapped again before the sweep looks, and the copy made again reading the new bytes. The memory line counts the copies let go this way. +- A draw of the title's decoration bake waits for uploads on their way and settles what is in the air before it takes the lock the bakes share, and goes on without the lock when the holder would find nothing to do for it: not the frame's first bake, nothing on its way, no settle or flip pending for its heap, and no pass due (no milliseconds left, or nothing new since a pass served all there was) (`LEONIDA_BAKE_QUICK=0`: all of it under the lock, as before). Before, every list thread with a bake draw queued behind the one holding the lock while that one waited for the card, even when its own draw needed nothing; under the lock the flush still runs whole and finds little left. While another draw is at work under the lock (its pass, or flips it took from lists and has not shown yet), no draw goes on, milliseconds left or not, and a draw that goes on still waits for the gate its list is behind. In a test with the lock held on another thread for 400 ms, such a draw went on at once; without the switch it waited the 400 ms. - The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory. - An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed. +- The recording threads no longer wait for a heap's queue of textures picked by index when nothing would change: its marks of which slots it holds now spare its lock by default (`LEONIDA_QUEUE_MARKS=0`: every note takes it, as before), and so does a slot write past the lock of placed texture views (`LEONIDA_SPANS_QUICK=0`: every write takes it). A table read of a slot the queue does hold, when another thread holds the lock, leaves the slot to the lock's next holder, who takes it out before anything else, and the draw goes on (`LEONIDA_TABLED_INBOX=0`: it waits, as before); a reader of the marks asks the queue while such a slot waits. Both were off while only the submitting thread was weighed, which did not wait for these locks; in timelines of three scenes the recording threads waited 23 to 72 ms a frame for the locks of the host heaps, 3.3 to 18.9 ms of it for this queue in table reads, and not one note was spared. The frame line counts the table reads left to the next holder (diagnostics builds). +- A host list's prelude (the allocator and list that move its textures into the states it starts with, copy depth twins and upload changed textures before it) is taken from 16 made ahead by a thread of its own, `leonida-preludes`, which makes more when fewer than half are left (`LEONIDA_PRELUDE_POOL=0`: made by the thread that submits the list, the first time it needs one, as before). Preludes are made when a list first needs one, and host lists are made anew in steady play (idle ones go once a second), so the submitting thread kept making them in the middle of submissions, while the card stood idle for it: in a 30 s sampling profile in play, 297 samples of it (3.8 %, about 1.9 ms a frame) were in `CreateCommandAllocator`, mostly in the kernel. With none ready a prelude is still made where it is taken, and the thread is woken. A prelude is reset and recorded only at a submission, under its list's lock, as before; its age for `LEONIDA_ALLOCATOR_TRIM` counts from when a list took it. The 16 kept cost a few MB of host objects. The memory line counts the preludes taken made ahead and those made where they were taken (diagnostics builds); not measured with the game yet. +- With `LEONIDA_SMOOTH_YIELD=1` (off by default), a present is not held to the recent mean interval (`LEONIDA_PRESENT_SMOOTH`) while other submissions or presents stand in the line, not yet sent, when the hold begins (off: held whether or not work waits, as before; work that comes during a hold does not end it). With submissions sent by a thread of ours, that thread also sends the present, so the hold stopped the next frame's submissions too and the card idled while it slept: in two traces standing the host's present, nearly all of it the hold, took that thread 3.6 and 2.1 ms a frame while the next frame stood behind it. With nothing waiting, or without that thread, presents are held as before. The frame line says how many presents were held and how long, and how many were not for the line with what they would have slept (diagnostics builds); the evenness of presents with frame generation, which the hold was measured for, is the other side of the trade. In the game (the same `LEONIDA_AB` run) it gained nothing: the median frame +0.6 % (s.e. 1.9 %), its 90th percentile +2.2 % (s.e. 3.6 %), hence off. +- A pass of the batched indirect-argument clamp reads its table of jobs from the card's memory instead of upload memory in the PC (`LEONIDA_BATCH_TABLE_CARD=0`: from upload memory, as before; not where the list's scratch memory is already in the card's memory, `LEONIDA_SCRATCH_CARD` with a resizable BAR). The CPU fills the tables as before, into an upload buffer beside each scratch buffer of the batches, and the list's prelude copies them, once per buffer, into a buffer in the card's memory, ahead of the list in the same submission; the pass, its wait for every earlier shader write and its transitions are unchanged. Each pass read its count and then its jobs across the bus before it could start: in the timing run of the world scene on the RX 7900 XT, 4.9 ms a frame in 653 passes; a standalone test there measured 4.8-5.0 us a pass against 3.4-3.5 us with the table in the card's memory, the copy counted, which is some 0.9 ms of the card's time a frame. In the title it gives less: a timing run in the world flipping the switch every 20 s gave 4.2 ms a frame for the clamps with it on against 4.7 ms off (about 660 passes either way), and in a `LEONIDA_AB` run of 68 phases the card's busy time moved -0.6 % (s.e. 0.9 %), the frame median +0.0 % (s.e. 1.9 %) and the submitting thread +1.7 % (s.e. 1.2 %; about 114 table copies a frame in the preludes, 2.9 MB). It stays on: the card holds the frame and the clamps take 0.5 ms less there. Which batches read where is decided as each is opened, so `LEONIDA_AB` can flip it while lists are recorded. The frame line of batch scratch buffers is followed by one that gives the passes reading each way, the copies and their KB. - Translated shaders get clean-up passes over the finished module (dead code, constant folding, reuse of values, branch facts); the pack's host instruction count falls by about 43 %, worth about 20 ms of GPU time per frame on the test machine (`LEONIDA_SHADER_OPT=0` turns them off). diff --git a/d3d12/docs/findings.md b/d3d12/docs/findings.md index ce64f3609f..d562f8a67f 100644 --- a/d3d12/docs/findings.md +++ b/d3d12/docs/findings.md @@ -644,7 +644,7 @@ found; the frame replay (`replay/`) is where to ask. |---|---|---| | `LEONIDA_REMAP_SPANS` (a texture refresh waits only for a change of mapping that touches its own memory) | A/B of 15 s phases while walking and turning, 25 phases | mean 153.3 -> 129.5 ms, median 117.2 -> 103.1, p90 305.1 -> 230.5. Of 130 to 320 named reads a frame, 6 to 128 went on beside a change and none waited. Standing: no change (the lock is held 5 to 13 ms a frame there). On by default. | | `LEONIDA_BATCH_SCRATCH_POOL` (lists share the scratch buffers of their batched clamps) | one standing run each way, 4.5 minutes in the world | the card's memory in use that no line counted 3,587 MB and rising -> 1,347 MB and level; "card buffers" made 7,165 -> 5,592 MB; host textures made again after being let go 1,700 -> 357; 150 buffers a frame taken from 170 to 200 kept, none made. In the 13-minute session before it the uncounted memory reached 5.0 GB and the card stayed at its budget of 14.3 GB. On by default. | -| `LEONIDA_SECTION_MB` (the title's physical pages in sections of a few MiB instead of one section an allocation) | one run each of 4 minutes walking and turning, every run from the same copy of the autosave | none: mean 111.6 ms, median 105.1, p90 139.3, title memory held for mapping changes 43.2 ms a frame, the mapping thread 46.2. 2 MiB: 91.7, 91.8, 111.4, held 10.6, thread 22.6. 16 MiB: 94.4, 91.7, 113.9, held 8.9, thread 20.7. The card is then busy 90 % of the time (78 % without). The launcher sets 16. | +| `LEONIDA_SECTION_MB` (the title's physical pages in sections of a few MiB instead of one section an allocation) | one run each of 4 minutes walking and turning, every run from the same copy of the autosave | none: mean 111.6 ms, median 105.1, p90 139.3, title memory held for mapping changes 43.2 ms a frame, the mapping thread 46.2. 2 MiB: 91.7, 91.8, 111.4, held 10.6, thread 22.6. 16 MiB: 94.4, 91.7, 113.9, held 8.9, thread 20.7. The card is then busy 90 % of the time (78 % without). The launcher sets 16; the code's default since 2026-11-29 (`0`: one section). | | `LEONIDA_WINDOWS_BAR_MB` (windows of title memory in card memory the CPU maps) | one standing run each from the same save, with timelines of 20 frames | 0 (all 1,105 windows in the PC's memory): 93.4 ms median, the card running 68 to 73 ms a frame. 3072, the launcher's (759 windows on the card, 797 not): 94.1 ms, 59 to 74 ms. No difference: what the card reads of windows over the bus is not where its time goes. 6144 is not comparable (its view had 4,800 draws). | | `LEONIDA_ALLOCATOR_TRIM=1` (host command allocators taken anew when 30 s old, idle host lists let go) | one standing run from the same save as the run above, 5.5 minutes | private bytes 30.1 GB against 30.7; 1,624 host lists alive against 1,514, 2,448 made against 1,514; 60 to 70 allocators replaced a second. No memory worth the churn on this driver; off. | | `LEONIDA_LATE_WAIT=2` (a present settles its frame's flights; asked because El1xr 8fa2de5 counts fewer tile flashes with presents kept behind their frame) | every frame of the standard moves saved and scanned, one run each way from the same save at night | 2 of 481 frames with a one-frame dip or spike as it is, 2 of 462 with the switch, the same early frames in both: there are no flashes at this place to count, so it is not judged. | @@ -809,6 +809,143 @@ formats (`CreateCommittedResource3`) can be read through the view itself, which under 5 us each (463 of them `CS_ComputeImposterTransform`, 0.5 us each) are 0.9 ms together, 15 kinds over 200 us each are 6.6 ms and 42 kinds of 50 to 200 us 4.2 ms: the screen-sized passes. +## Where memory the CPU fills and the card reads is put, on an RX 7900 XT (2026-11-29) + +Every decision that leaves card memory the CPU maps and title memory in place off was measured on an NVIDIA card +(the RTX 4060 Ti above, PCIe 4.0 x8) or on the software adapter (`inplace.rs`). This is the same question asked of +an AMD card, without the game: `host::placement` (`cargo test -p leonida-gpu --release --lib host::placement -- +--ignored --nocapture`) fills buffers of 1, 16 and 256 MiB in each placement from cached memory of its own, has the +card copy each into a device-local buffer and a compute shader read every byte of it (in a second submission, twice +in a row; the XOR it folds is checked against the CPU's), and reads the mapping back on the CPU. + +The PC: Ryzen 7 5800X (8 cores), 32 GB DDR4-3600, Radeon RX 7900 XT 20 GB on PCIe 4.0 x16 (the device's own link +properties), Windows 11 build 26300, driver 32.0.32029.2010 (the user-mode driver version DXGI gives). Direct3D 12 +is Windows' own: the test binary exports no `D3D12SDKVersion`, and the `D3D12Core.dll` it loads is +`C:\Windows\System32`'s (10.0.26100.9818), `D3D12SDKVersion` 616, newer than the Agility SDK 1.614.1 that +`Get-D3D12.cmd` fetches, so `leonida.exe` runs on the same one here (Windows takes its own where it is newer). +`ARCHITECTURE1`: not UMA. **Resizable BAR is off in this PC's firmware**: the card's memory window is 256 MiB +(`Win32_DeviceMemoryAddress`, D0000000-E01FFFFF) and `GPUUploadHeapSupported` is false, so there is no GPU upload +row; `D3D12_HEAP_TYPE_GPU_UPLOAD` is refused with E_INVALIDARG. + +One run of 15 (CPU reads: 3), medians, GB/s (10^9 bytes a second). Other programs were compiling during the runs: +over three runs the card's reads over the bus stayed between 22 and 28 GB/s, the CPU's columns moved a lot (fills at 16 MiB 11 to 27 GB/s, plain +reads of write-back memory 13 to 30), so the run with the least else on the CPU is the one shown. + +| Placement | Size | CPU fill, memcpy | CPU fill, NT stores | Card copy to DEFAULT | Card shader read | Card shader read again | CPU read, plain | CPU read, streaming | +|---|---|---|---|---|---|---|---|---| +| default via upload | 1 MiB | 28.57 | 28.65 | 26.37 | 214.87 | 291.27 | - | - | +| upload | 1 MiB | 27.38 | 27.89 | 26.43 | 25.55 | 288.07 | 0.19 | 8.40 | +| custom L0 write-back | 1 MiB | 28.73 | 28.42 | 26.56 | 25.70 | 291.27 | 32.77 | 95.33 | +| opened (FromAddress), opening 0.7 ms | 1 MiB | 28.49 | 28.11 | 26.69 | 25.80 | 288.07 | 34.61 | 95.33 | +| default via upload | 16 MiB | 26.30 | 27.30 | 28.29 | 907.86 | 1018.03 | - | - | +| upload | 16 MiB | 23.33 | 24.58 | 28.29 | 28.21 | 28.20 | 0.18 | 8.13 | +| custom L0 write-back | 16 MiB | 25.36 | 26.88 | 28.32 | 28.25 | 28.27 | 26.90 | 45.44 | +| opened (FromAddress), opening 2.1 ms | 16 MiB | 24.39 | 26.40 | 28.13 | 28.24 | 28.27 | 29.95 | 35.78 | +| default via upload | 256 MiB | 17.61 | 16.53 | 27.98 | 686.61 | 760.61 | - | - | +| upload | 256 MiB | 13.43 | 13.31 | 24.80 | 23.29 | 21.81 | 0.16 | 5.36 | +| custom L0 write-back | 256 MiB | 13.21 | 13.75 | 25.07 | 23.09 | 22.35 | 14.52 | 14.07 | +| opened (FromAddress), opening 36.2 ms | 256 MiB | 14.15 | 14.72 | 26.59 | 24.50 | 24.15 | 19.42 | 21.07 | + +Default via upload: the fills are of its upload staging, the card copy is that staging into the device-local +buffer, and the shader reads the device-local buffer. "Again" is a second read in the same submission. Opening: +`OpenExistingHeapFromAddress` and placing the buffer (30 to 40 ms for 256 MiB over three runs, 70 on the software +adapter). + +What it says: + +- **The card reads the PC's memory at the bus's rate, 23 to 28 GB/s, in every placement and by copy or shader + alike.** Write-back memory (custom L0, which host copies of title buffers and windows are, and title memory + opened in place) costs the card nothing over write-combined upload memory here. Device-local memory reads at + 690 to 1,000 GB/s, 25 to 40 times as fast. A 1 MiB buffer in the PC's memory read twice in one submission is + read from the card's L2 the second time (290 GB/s); at 16 MiB it is not, and the 80 MB last-level cache does not + keep what came over the bus either ("again" equals the first read): what many waves read many times belongs in + the card's memory, what is read once costs the same wherever it is in the PC's. +- **Write-combined memory is not to be read by the CPU**: 0.13 to 0.19 GB/s with ordinary loads (about 150 times + slower than write-back), 3 to 8 GB/s with streaming loads (`movntdqa`). That holds for upload memory and would + for GPU upload memory: the CPU sides of card copies (`Card::staging`, a shared buffer) are rightly write-back, + since compares and snapshots read them. +- **Filling costs the same into upload and into write-back memory** (13 to 28 GB/s on one thread; the C runtime's + `memcpy` already streams large copies, so non-temporal stores gain nothing past 1 MiB). The CPU's memory is the + limit, not the placement. +- **`LEONIDA_SEND_BAR` and `LEONIDA_WINDOWS_BAR_MB` do nothing on this PC as it is set up**: `mapped_card_buffer` + answers `None` and both fall back (send.rs `memory`, shadow.rs `window_mapped_for`). Measuring them needs + "Above 4G decoding" and "Re-Size BAR" (Smart Access Memory) on in the firmware, then this test again. What the + table bounds without it: the sends' card copies out of upload memory run at 25 to 28 GB/s on the drawing queue, + 2.6 to 3.7 ms of it for the 73 to 93 MB a frame of send.rs's run, which is what the BAR would take off the card; + and the CPU's fill is already bound by its own memory (13 to 28 GB/s), so on an x16 link a fill through the BAR + may cost the submitting thread little more than one into upload memory, unlike the x8 card's 8-9 ms against 3 + (a hypothesis until measured). +- **Card copies' staging**: the card copies out of write-back staging or opened title memory as fast as out of the + upload ring (24 to 28 GB/s), so sending straight from the CPU side, or from title memory opened in place, would + cost the card's copies nothing and save the CPU the copy into the ring (90 MB at 13 to 28 GB/s: 3 to 7 ms of the + submitting thread). Texture staging in upload memory is no faster for the card than write-back would be. +- **In place**: on this card a window opened in place is read as fast as its host copy in a shared buffer (both + cross the bus), and the CPU writes and reads it as plain cached memory, so `LEONIDA_INPLACE=1` takes away the + copy and its refresh at no cost to the card's reads that this table shows. Opening costs about 1 ms for a part + of 1 MiB and 2 to 6 ms for 16 MiB, and locks the pages. The 290 ms a frame of `LEONIDA_PORT_CONSTANTS=1` on the + RTX 4060 Ti is not explained by what the card pays to read the PC's memory here; it was not measured on this + card. + +## What the card's compare after a submission costs, on an RX 7900 XT (2026-11-29) + +Every submission that declares shader writes over a copy in the card's memory has a pass of ours hash every 64 KiB +piece of every declared range on the drawing queue after its lists (`CARD_COMPARE`, the check list of +`Host::card_before`), whatever the shaders wrote; nothing had timed it. `host::comparecost` (`cargo test -p +leonida-gpu --release --lib host::comparecost -- --ignored --nocapture`) runs the runtime's own compare, its passes +planned as `card_before` plans them, over a device-local copy of each size between timestamps on a direct queue of +its own, mode 2 as the relay's flights have it. "Cold" follows a 192 MiB copy that sweeps the card's caches (6 MB of +L2, 80 MB of last-level cache), "again" is the same passes right after in the same list. Same PC as the section +above; medians of 9 runs, three runs within 0.003 ms of each other up to 16 MiB and 0.025 ms above. + +| Declared | Pieces | Cold, ms | GB/s | Again, ms | GB/s | +|---|---|---|---|---|---| +| 64 KiB as one range | 1 | 0.010 | 7 | 0.008 | 8 | +| 1 MiB as one range | 16 | 0.008 | 139 | 0.005 | 205 | +| 4 MiB as one range | 64 | 0.018 | 236 | 0.004 | 1059 | +| 16 MiB as one range | 256 | 0.043 | 391 | 0.009 | 1792 | +| 64 MiB as one range | 1024 | 0.159 | 421 | 0.033 | 2039 | +| 256 MiB as one range | 4096 | 0.447 | 601 | 0.353 | 761 | + +The same copies declared as views of 256 bytes every 16 KiB (four in each piece, ranges that do not touch), cold: + +| Copy | Views | `LEONIDA_CARD_COMPARE_SHARE` | Passes | Pieces hashed | Cold, ms | +|---|---|---|---|---|---| +| 64 KiB | 4 | 0 | 4 | 4 | 0.008 | +| 64 KiB | 4 | 1 | 1 | 1 | 0.007 | +| 1 MiB | 64 | 0 | 49 | 64 | 0.009 | +| 1 MiB | 64 | 1 | 1 | 16 | 0.007 | +| 4 MiB | 256 | 0 | 193 | 256 | 0.018 | +| 4 MiB | 256 | 1 | 1 | 64 | 0.018 | +| 16 MiB | 1,024 | 0 | 769 | 1,024 | 0.049 | +| 16 MiB | 1,024 | 1 | 1 | 256 | 0.043 | +| 64 MiB | 4,096 | 0 | 3,073 | 4,096 | 0.174 | +| 64 MiB | 4,096 | 1 | 1 | 1,024 | 0.159 | +| 256 MiB | 16,384 | 0 | 12,289 | 16,384 | 0.569 | +| 256 MiB | 16,384 | 1 | 1 | 4,096 | 0.448 | + +What it says: + +- **The compare reads the card's memory at its own rate once a range is large**: 600 GB/s cold at 256 MiB, 1.7 us a + declared MiB (2.4 to 2.6 us at 16 to 64 MiB). A frame's worth is small beside the card's 56 ms: the 375 MB a frame + of run 86's declared ranges would be 0.6 to 1 ms, 1 GB about 1.6 to 2.5 ms. That it costs the drawing queue + gigabytes of reads a frame holds only for that many declared bytes; the frame line now gives the pieces the + compare hashed a frame, which times 64 KiB over these rates is its share of the card (not measured in a game run). +- **A pass of a few pieces costs its latency, 5 to 10 us, not its bytes** (64 KiB at 7 GB/s). Passes of one list + with no barrier between them overlap, so those of one submission share it: four views in one piece hashed four + times cost what one hash does (0.008 against 0.007 ms), since the repeats come from the cache. +- **Hashing a shared piece once (`LEONIDA_CARD_COMPARE_SHARE`, on) saves pieces and passes more than time**: a + quarter of the pieces and one pass instead of 12,289, but 0.57 -> 0.45 ms at 256 MiB and 0.049 -> 0.043 at 16 + MiB. Besides, the check list records one root-constant set and dispatch where it recorded 12,289, and with the + relay two hashes of one piece no longer race (the second compared with the hash the first had just stored). +- **A wider form of the shader is not worth its hash.** Four times the threads per piece (256, each 16 loads 4 KiB + apart, a tree of folds; `LEONIDA_BENCH_CS`) made the one-piece pass 0.004 ms instead of 0.010 and changed nothing + from 16 MiB on (0.042, 0.156, 0.443 ms): the large ranges are bound by memory, not by the loads in flight, and the + small ones save 5 us a submission. It would change the hash the CPU mirrors (`host::torn`), so it was not taken. +- **What else would narrow it is outside this crate**: the declared range of a view is already its bounds, and a + shader that cannot store declares nothing (`LEONIDA_WRITE_SKIP`); which bound views a shader stores through is not + among the facts the translator gives (`UsedResource`), and a root unordered access view has no size, so it declares + all that is left of its buffer (`LEONIDA_ROOT_UAV_MB` bounds it by hand). + ## Where the frame goes at the launcher's default, and what a "native" runtime would change (2026-11-29) The same PC and save, the launcher's default since e4973b5db: Series X, a 2560x1440 output, the title's own dynamic @@ -1047,7 +1184,10 @@ the card's own 55 ms. locks were not what anyone waited for on this six-core PC. With the quick way counting itself per thread in batches instead of in one shared counter, two more runs by turns (d43) gave the submitting thread +0.12 +-0.50 and +0.30 +-0.31 ms again. Both are off by default now (`=1` turns each on; the marks and the set of slots are kept either - way), kept for a PC whose threads do wait there. + way), kept for a PC whose threads do wait there. They are on by default again (`=0` restores the lock on every + write and every note): the recording threads, not the submitting thread, wait for these locks. In timelines of + three scenes they waited 23 to 72 ms a frame for the locks of the host heaps, 3.3 to 18.9 ms of it for the texture + queue in table reads, with not one note spared and not one slot write past the lock of placed views. - **Measured by turns and kept as they were (runs d43, two runs, 154 phases):** 8 parts of submissions joined against 2 (`LEONIDA_JOIN_PARTS_AB=2`, the value ReZOnGithub/VIctory-lap f2c7109 found 0.87 ms better there): with 8 the frame's median -3.09 +-0.51 and -3.03 +-0.26 ms, the submitting thread -4.66 +-0.33 and -4.60 +-0.18, so the @@ -1471,3 +1611,304 @@ tour that made its pipelines): the card 49.8 -> 51.5 ms a frame, the indirect dr 1.17 (114 -> 125 draws a frame), 89a622617919c92a 1.43 -> 1.44, 321d411b20a35ef9 0.48 -> 0.47. No gain on this card: the primitive stage that takes every slot costs NVIDIA less than the counts' barrier and group-shared word cost the programs. Left off. (The tour with it on, d157, drew as without.) + +## The memory switches in the running title, on an RX 7900 XT (2026-11-29) + +The switches the memory work of 2026-11-29 left off by default, measured in the running title: Series X profile, +2560x1440 output, the launcher's defaults (`scripts\play-d3d12.ps1 -Log`, which sets `LEONIDA_RELAY=2` and +`LEONIDA_RELAY_COPY=1`), the same scene each time (the save folder restored before each start, so that the title +loads the same scene and does not go on from where the last run saved), measured for 5 minutes from the moment the +title leaves its start screen. Frame time is the median over the last 4 minutes of the frame line's "the card's +clock per frame" (the time nothing of ours was queued over the share of the frame the card was idle); private +memory and the card's memory are the process's and the system's figures at the end. Ryzen 7 5800X, 32 GB, Radeon RX +7900 XT 20 GB (driver 32.0.32029.2010), Windows 11 26300, resizable BAR off. + +| Switches | Frame (ms) | Private (MB) | Card memory (MB) | PC memory the card uses (MB) | +|---|---|---|---|---| +| none (two starts) | 50.0, 50.8 | 29,381, 29,187 | 11,738, 11,526 | 7,851, 8,015 | +| `LEONIDA_CARD_FROM_TITLE=1` | 48.6 | 27,961 | 11,219 | 7,337 | +| `LEONIDA_INPLACE=2` | 47.8 | 28,455 | 11,689 | 7,174 | +| `LEONIDA_LAND_IN_SUBMISSION=1` | 55.2 | 29,456 | 11,669 | 8,021 | +| the three together | 51.4 | 28,442 | 11,047 | 7,987 | +| `LEONIDA_CARD_WINDOWS_MB=3072` | 52.7 | 31,747 | 14,236 | 7,756 | + +What it says: + +- **Nothing here is far from the two starts without switches** (about 1 ms apart) except `LEONIDA_LAND_IN_SUBMISSION`, + which is 5 ms slower: with `LEONIDA_RELAY_COPY=1` the fetches it replaces already run on the copy queue (the relay + waited 0.0 ms for them a frame), so it only adds its landing traffic (53 MB a frame). It stays off. +- `LEONIDA_CARD_FROM_TITLE` worked through the whole run with no error: 25 copies had title memory as their CPU side + and 162 MB of the PC's memory were not taken; 32 others were declared written and got a side of their own. +- **In place reaches almost nothing of this title's memory**: with `LEONIDA_INPLACE=1` or `=2` 4 to 8 windows + (16 to 40 MB) were in place; 1,926 asks were turned down as view memory, and with `LEONIDA_SECTION_COMMIT=1` too, + 1,990 as "not one run of a committed section": the title maps physical pages of many sections into one stretch of + address space, so a 4 MiB window lies over pages of several sections and cannot be one heap. The 3.6 GB of windows + stay copies. +- Windows on the card (`LEONIDA_CARD_WINDOWS_MB`) put 934 windows (3.9 GB) in the card's memory but keep their CPU + side, so the process holds more, not less, and the frame does not improve. +- **What holds the frame is the submitting thread, not where memory lies**: it worked 52.5 ms a frame, the card was + idle behind it 17 ms. Of its time, 11.7 ms were refreshes (6,590 a frame, 5,753 of them known to copy nothing), + 13.3 ms waiting for the pass over the heap's views, 8.0 ms waiting for the heaps' records and 4.1 ms asking the + write watch (259 askings over 1.7 GB a frame, 274 refused). +- The memory line estimates 1.4 GB of host copies of placed textures whose title memory is no longer mapped, which + no descriptor slot shows, kept in the card's memory. + +## The recording threads' locks in the running title, on an RX 7900 XT (2026-11-30) + +A timeline of the same scene (`LEONIDA_TIMELINE`, three captures of five frames) put about 600 list calls of 50 us +or more a frame on the recording threads. Most of them hold no nested event at all; the waits inside the rest were +behind four locks shared by all eight recording threads: the staging table (`texture.rs`), the bake upload lock +(`draw.rs` `early_textures`), a heap's texture queue (`descriptor/host.rs`) and the list of host command signatures +(`draw.rs` `host_signature`). Each now has a switch, on by default, with `=0` the lock as before: +`LEONIDA_STAGING_SHORT`, `LEONIDA_BAKE_QUICK`, `LEONIDA_QUEUE_MARKS` with `LEONIDA_SPANS_QUICK` and +`LEONIDA_TABLED_INBOX`, and `LEONIDA_SIG_TABLE`. + +Measured with all six in one `LEONIDA_AB` run (phases of 7 s, the 64 combinations once each after the title was in +game, the save restored before the start), each switch's effect taken by least squares over all 64 phases with a +linear trend for the scene's drift: + +| Switch on vs off | Frame median | Frame p90 | Submitting thread | Card idle | +|---|---|---|---|---| +| `LEONIDA_STAGING_SHORT` | +0.3 % | -3.5 % | -0.6 % | -1.4 % | +| `LEONIDA_BAKE_QUICK` | -1.1 % | -5.8 % | -2.9 % | -5.3 % | +| `LEONIDA_QUEUE_MARKS` | -0.6 % | -1.2 % | -0.8 % | -4.6 % | +| `LEONIDA_SPANS_QUICK` | +2.1 % | +0.8 % | -1.1 % | -0.1 % | +| `LEONIDA_TABLED_INBOX` | -1.9 % | -4.6 % | -1.9 % | -7.9 % | +| `LEONIDA_SIG_TABLE` | -0.4 % | -1.2 % | +1.7 % | -2.9 % | +| standard error | 1.9 % | 4.2 % | 1.8 % | 5.6 % | + +None is beyond two standard errors (frame median 47.3 ms over the run, about 7.6 % between phases), so no frame time +change is claimed. The waits they remove are on the recording threads, which are not what holds the frame here: the +submitting thread still worked about 33 ms of a 47 ms frame. + +## What the title's busiest thread waits for, and four cuts on the submitting thread (2026-11-30) + +With the sampling profiler working again (`LEONIDA_PROFILE`, 30 s in the world), the title's busiest thread turned +out to be waiting, not working: about 45 % of its samples in a `monitorx`/`mwaitx` loop on the value at a fence's GPU +address (`fence.rs` `gpu_address`) and 27 % in `Sleep` inside the same loop. The timeline report had counted that +spin as the title's own time ("outside our spans"). + +Read against two timelines (`LEONIDA_TIMELINE`, five frames each), the time from the title's `Signal` to +`fence::set` is short: +- The fence the spin waits for is set 0.19 to 0.64 ms after the card ends the flight before it. That breaks down into: + - the relay's wake, 16 to 112 us; + - the copy-queue fetch of the landing, 73 to 444 us; + - the merge, 20 to 64 us; + - telling the title, 13 to 49 us. +- The title leaves its loop 9 to 90 us after the set. +- The relay thread spends 68 % of its samples waiting for the card. + +The title waits for the card itself. Inside each wait the card is busy 17 to 34 ms and idle about 5 ms, and while it +is idle the submitting thread is still preparing the next submission. + +Four cuts on the submitting thread and the threads it waits for, each behind a switch, measured in one `LEONIDA_AB` +run. The run used phases of 7 s, the 16 combinations about four times each after the title was in game (67 phases), +and the save restored before the start: + +| Switch on vs off | Frame median | Frame p90 | Submitting thread | Card idle | +|---|---|---|---|---| +| `LEONIDA_SPANS_ONE_WALK` | -1.0 % | -0.8 % | +0.6 % | -5.6 % | +| `LEONIDA_PRELUDE_POOL` | -1.2 % | -0.8 % | **-3.1 %** | -1.0 % | +| `LEONIDA_SMOOTH_YIELD` | +0.6 % | +2.2 % | +0.8 % | +1.2 % | +| `LEONIDA_RELAY_PRIORITY` | +1.6 % | +2.9 % | +1.4 % | +6.4 % | +| standard error | 1.9 % | 3.6 % | 1.2 % | 6.2 % | + +What each switch did: +- `LEONIDA_PRELUDE_POOL`: the submitting thread did 3.1 % less work, about 1 ms a frame, beyond two standard errors. + - About half of the preludes were still made where they were taken, because the 16 made ahead run out in bursts. + - The frame did not move. +- `LEONIDA_SPANS_ONE_WALK`: + - The heap pass's line shows 15 stale parts a pass made again in 1 walk over the slots instead of 15. About 100,000 + of 1,245,182 slots show something. + - The time spent making spans fell from about 5.5 to 4.1-4.5 ms a frame. That pass runs beside the recording + (`LEONIDA_HEAP_PASS_ASIDE`), so the frame does not see it. + - Both stay on by default. +- `LEONIDA_SMOOTH_YIELD` and `LEONIDA_RELAY_PRIORITY` gained nothing, and every reading of the relay's priority was on + the side of a loss. Both are now off by default (`=1` turns them on). + +Over the run the frame median was 46.4 ms, with the card busy about 35 ms a frame and idle about 12 ms. The +submitting thread worked about 32 ms. What holds the frame now is the card's own work, plus the idle time while the +title records the next frame. Shaving the submitting thread further does not show in the frame. + +## The runtime's own work on the card, measured there, and three changes (2026-11-30) + +The card holds the frame (busy about 35 ms of 46). A timing run in the world (`LEONIDA_GPU_TIMING=1`, every +command between two stamps, so the frame there is slower) put the card's time a frame at about 41 ms by command: + +| Commands | ms a frame | Commands a frame | +|---|---|---| +| title `ExecuteIndirect` | 16.0 | 5161 | +| title dispatches | 15.7 | 3834 | +| our batched clamps of indirect arguments | 4.9 | 653 | +| title mesh, draw, alias and indexed commands | 5.0 | 843 | + +Our lists over the card copies of title memory are not in that table, as they are not inside the title's lists. Timed +on the card now (`LEONIDA_CARD_OWN_TIMES=1`, diagnostics builds), in the world: +- the ranges sent up ahead of submissions: 1.2-1.3 ms a frame in about 13 lists; +- the hash passes after them: 0.07 ms; +- the compare after the submissions' lists: 0.6 ms in about 15 lists. + +So the runtime's own card work is some 5-7 ms of the 35, the clamps the largest part. The rest is the title's +translated shaders. + +Three changes, measured in one `LEONIDA_AB` run (phases of 7 s, 68 in game, the save restored before the start): + +| Switch on vs off | Frame median | Card busy | Submitting thread | Card idle | +|---|---|---|---|---| +| `LEONIDA_BATCH_TABLE_CARD` | +0.0 % | -0.6 % | +1.7 % | +2.7 % | +| `LEONIDA_COMPARE_JOIN` | -1.4 % | -1.2 % | -0.8 % | -0.1 % | +| `LEONIDA_CARD_OWN_TIMES` | +2.8 % | +0.9 % | +2.2 % | +9.4 % | +| standard error | 1.9 % | 0.9 % | 1.2 % | 5.4 % | + +What each switch did: +- `LEONIDA_BATCH_TABLE_CARD`: each clamp pass read its table of jobs over the bus from upload memory, the count and + then the jobs, before it could start. The tables now go to the card's memory in the list's prelude. + - A standalone test measured 4.8-5.0 us a pass against 3.4-3.5 us. + - In the title it gives less. A second timing run, flipping the switch every 20 s, gave the clamps 4.2 ms a frame + on against 4.7 ms off, about 660 passes either way. The card's busy time moved -0.6 %, within its noise. + - The cost is about 114 table copies a frame in the preludes (2.9 MB), +1.7 % on the submitting thread, which is not + the limit. + - It stays on. +- `LEONIDA_COMPARE_JOIN` sends the compare in the same call as the submission's last lists, behind one global barrier + list. It saved about 0.4 ms of card time a frame, within the noise, as expected from 18-26 us a call. It stays off + until the title has run with it under the debug layer: a host copy a title list wrote as unordered access is read + in the same call, and this machine has no SDK layers to judge that. +- `LEONIDA_CARD_OWN_TIMES`: its stamps and read-backs cost a little on the frame and the submitting thread. It is now + off by default (`=1` turns it on) so that it does not shift other measurements. + +None of the three moves the frame beyond the noise (median 46.4 ms). Cutting our own card work further has a ceiling +of the 5-7 ms above: the clamps, which need knowing what the title's culling programs write (the translator), and the +ranges sent up, which are the title's CPU writes the card has to see. + +## Tiles over the page pool, asked of an RX 7900 XT (2026-11-30) + +With `LEONIDA_INPLACE=1 LEONIDA_SECTION_COMMIT=1` the title had 32 MB in place in its sections and 1,838 asks turned +down as view memory that is not one run of a committed section: `xmem` maps physical pages one 64 KiB view at a time, +so a window is scattered pages, and one placed buffer shows one run. A reserved (tiled) buffer whose tiles are mapped +onto the section opened as a heap would be the console's own page table. The probe (`inplace/tiled.rs`, with +`LEONIDA_INPLACE_PROBE=1`, and the ignored test `card_tiles_over_a_committed_section`) asks, on a device of its own: + +- Tiled resources tier 4. On a heap of ours (`CreateHeap`, the PC's memory, write-back) everything holds: sixteen tiles + over fifteen scattered pages read what the CPU wrote, also afterwards with no call in between; a shader reads them + and its unordered-access writes show at the pages' address after the fence, two tiles on one page alike; a remap and + an unmap (zero, and the write lost) work. +- On the section's heap the first `UpdateTileMappings` removes the device (`DXGI_ERROR_INVALID_CALL`), with a + cross-adapter reserved buffer or a plain one, and so on private memory opened in part. A heap of ours made shared and + cross-adapter does the same; one made shared alone takes the tile. Direct3D takes no tiles in a cross-adapter heap, + and every heap opened on memory the process has is one (flags 0x421). The software adapter answers the same. + No tiled window over title memory on Windows; VKD3D-Proton is not asked yet. +- What tiles would cost (on the heap of ours, best of 3): `UpdateTileMappings` of 1, 64 and 1024 tiles, a range each, + 19, 23 and 2,021 us of CPU and 0.2, 1.1 and 20 ms until a fence after it; 1024 as one run of pages, 32 us and 9 ms. + The card reads 64 MB through tiles in a scattered order at 27.5 GB/s, through one placed buffer at 26.9 and out of + an upload buffer at 27.3: tiles cost the reads nothing. + +## The paths that read title memory where it is, in the title (2026-11-30) + +The runtime's paths that read title memory in place instead of keeping a copy of it were all off by default and had +never run in the title. One run per configuration in the world on an RX 7900 XT (Windows, ReBAR off), 270 s each, the +save restored before each start; the frame is the card's clock line over the last two minutes. A first base run had +GPU tests beside it, so the base is the repeated one. + +| Configuration | Frame | Private | Card memory | Shared memory | What it did in the title | +|---|---|---|---|---|---| +| base | 48.6 ms | 27.4 GB | 9.8 GB | 8.0 GB | | +| `LEONIDA_CARD_FROM_TITLE=1` | 49.0 ms | 27.1 GB | 9.8 GB | 7.8 GB | 13 copies with title memory as their CPU side, 13 MB not made | +| `LEONIDA_INPLACE=1` | 49.0 ms | 27.4 GB | 9.8 GB | 8.1 GB | 7 windows in place, 36 MB; 1,872 asks turned down | +| `LEONIDA_INPLACE=1 LEONIDA_SECTION_COMMIT=1` | 51.6 ms | 27.5 GB | 10.0 GB | 8.2 GB | 18 opened in their section, all let go when their memory changed; 1,838 turned down | +| `LEONIDA_LAND_IN_SUBMISSION=1` | 49.5 ms | 27.6 GB | 9.9 GB | 8.1 GB | 1,392 pieces (49.7 MB) a frame landed in their own submission | +| `LEONIDA_TEXTURE_WATCHED_IN_PLACE=1` | 50.9 ms | 27.4 GB | 9.9 GB | 7.8 GB | no fault | + +No configuration faulted, and none moved the frame beyond what two starts of the same build differ by. + +- **In place:** the title's GPU memory outside buffers is its page pool: `xmem` maps physical pages one 64 KiB view at a + time, so a window that is contiguous to the title is scattered pages of a section, and one placed buffer cannot show + it. The tiles that would (the section above) are refused by Direct3D on any opened heap. Private memory committed + whole, the only other kind that opens, holds little of what the card reads. +- **Landing in the submission:** made a per-plan decision so `LEONIDA_AB` can flip it, and weighed in one run of 67 + phases: frame median +0.6 % (s.e. 2.5 %), card busy +1.1 % (s.e. 1.5 %). The relay lands in 6.8 ms a frame instead + of 10.2 and waits for no fetch, but the frame does not wait for the relay. It stays off. + +**Where the process's memory goes** (the base run, read from its memory lines and the code). Private memory is flat at +27.3-27.5 GB from about two minutes in the world to the end; nothing grows without bound. On this driver the card's +own memory and the PC memory shared with it are charged to private bytes about one for one: private minus both stays at +9.3-10.4 GB whatever the configuration, and a run that put 2.5 GB more of copies in card memory had 2.4 GB more private. +So moving a copy to the card saves no commit; only removing a duplicate does. +- Card memory, 9.8 GB: texture blocks 4.4 GB (2.7 GB used, about 1.7 GB free inside blocks that hold some live + texture, which the pool lets go only whole), textures the host draws into 2.0 GB, card buffers 1.6 GB (of them 210 MB + of 64 KiB buffers holding about 100 bytes of hashes each, and 57 MB of 256-byte budgets in 64 KiB each), 1.7 GB not + in the census (swap chain, descriptor heaps, pipelines, the driver). +- Shared memory, 8.0 GB: windows 3.8 GB over 3.6 GB of title memory, of which only 2.5 GB was ever copied; the CPU + sides of card copies 1.1 GB; small-buffer blocks 0.4 GB; about 2.5 GB not in the census. +- The rest, about 9.6 GB: the title's committed memory through `xmem` (at least 4.1 GB), our own heap 1.5 GB (0.3 GB + of it shader caches), and about 4 GB with no owner named (the driver's user-mode part, the title's image and stacks, + what the allocator keeps). The physical page pool's sections are charged to commit but not to private, and nothing + counts them yet. +- The line "private bytes grew N MB while lists were made" adds up the whole process's changes around each list made, + on any thread; it rose by 4.8 GB with private flat, and is no measure of what lists cost. + +**A finer grid for windows** (`LEONIDA_WINDOW_KB=256 LEONIDA_WINDOW_TAILS=1`, one run): windows 3,820 -> 2,219 MB, +private 27.4 -> 26.1 GB, commit left 1.3 -> 1.9 GB. It stays off: a reading of the code found that where two windows +hold the same bytes, a shader's write through one does not reliably reach the other before it is read or sent up (a +read through the other while the flight is in the air, with `LEONIDA_RELAY_CROSS` off; a write and a read through +the two in one submission; the order in which two written copies land; the late merge keeping a value the card +overwrote later). The 4 MiB grid has the same exposure where asks cross a cell line, only rarer. (An earlier reading +of the up-copy check said it found no send putting an older value over a card write in either run: wrong, see the +next section. Its sends-over-card lines were nonzero once in the world, at both grids, and come from the copies +below, not from the window grid.) + +**What the up-copy check did find, at either grid:** (read again in the next section) about nine title buffers (2 MiB and 1.1 MiB ones, the +same addresses every few seconds, 239 checks each) whose card copy differs from its CPU side, written by shaders through +a view no flight declared. A later send of a title write there would put the older bytes back over the shaders'. + +## Shader writes that a send undoes, in write-combined title memory (2026-11-30) + +The up-copy check (`LEONIDA_UPCOPY_CHECK=1`) has two looks. The lines "older values sent up to <range>: ... (card X, +sent Y)" come from the look **at a send**, not the one at rest: once in the world every one of its summaries is +nonzero (about 20 M words over 240 summaries in one run, 17 M in another; zero only before the world loads). The look +at rest prints "are not the CPU side's" and names other, larger copies. The label "no shader was declared to write the +buffer" means only that no card-back plan ever held the copy: a write kept on the card by `LEONIDA_WC_NO_BACK` is never +planned, so it reads the same as a write nobody declared. + +All nine ranges, and the larger ones at rest, are copies of write-combined title memory (protection 0x2404) of 1 MiB +or more. The launcher sets `LEONIDA_WC_NO_BACK=1` (`d3d12/scripts/play-nvidia.ps1`), so what shaders write there stays +on the card and is never compared, fetched or landed. When the title then writes anywhere in the same page, the page +goes up whole from title memory, which still holds what was there before the shaders wrote. + +What wrote them was traced with `LEONIDA_UNDECLARED_TRACE=1` (`host/undeclared.rs`), which says per submission whether +its lists or its sends changed the watched bytes, and which declarations the lists made there. Three runs from the same +save on an RX 7900 XT, diagnostics build, about 40 s in the world each: + +| run | `WC_NO_BACK` | watched | frame | +|---|---|---|---| +| b11_trace | 1 (the launcher's) | flagged copies | 66.7 ms | +| b11_trace_wcback | 0 | flagged copies | 89.9 ms | +| b11_trace_wcback_watch | 0 | the nine, asked for by address (`LEONIDA_UNDECLARED_WATCH`) | 87.9 ms | + +(Frames are slow because both checks run on every submission. Only the difference between the runs counts.) + +- **Every write into them is declared.** It comes from a view in a descriptor table (`draw::readable`), and with + `WC_NO_BACK=1` it is "kept on the card". Writes that no flight declares (views picked from the heap, stores past + their views) are near them in the same binds, but they are not what the check flagged. +- **Two buffers lose what their shaders write, every frame, with the launcher's setting.** + - 0xd624f2660+0x177000: a compute pass sets 1,203 words (0 -> 0x80) each frame. The next submission's sends put all + 1,203 back to 0: 12 of 12 frames traced. + - 0xd94cd7430+0x280000: the same in 9 of 15 frames. + - With `WC_NO_BACK=0` their lists change the words in 24 of 24 frames and no send touches them again. The title does + not write those words. Only the page around them is sent, and it carries the words the shader wrote, because they + were landed. + - So `WC_NO_BACK=1` turns state that a shader keeps from frame to frame into state that resets every frame. The + console keeps it. +- **The rings are the title's own writes.** In 0xdb5047000, 0xdb515e500 and 0xdb5275a00 (+0x117500, three apart), in + 0xdba8a9c00 and 0xdbaaa9c00 (+0x200000), and in 0xdb9b30000 and 0xd5c6c7500, the sends still put values back over + the shaders' words with `WC_NO_BACK=0`. Often it is the same value each time (0x3f800016, where the shader leaves + 1.0f). The title rewrites each record when it reuses the slot, and the console would hold its value too. + - The check cannot tell this apart from an undone write, because the value sent equals the one before. That a sent + value stays the same from send to send does not tell the two apart either: only a run with the write-back on does. +- **Elsewhere with `WC_NO_BACK=0`** the check flags four other copies: 0xfb1450000+0x3200000, 0xfeb510000+0xbf4000, + 0x1000710000+0x473100 and 0xfe3110000. There, sends go over words that lists changed even though the writes are + declared and landed. Most are the same value each time (0xfffe03ff), so they read as title rewrites too. Not + followed further. +- **What would keep both the frame and the two buffers:** take back, as declared writes, only those write-combined + copies whose shader-written pages the title also writes. Leaving all of them on the card saves about 21 ms here + (66.7 against 88-90). Not built yet. + diff --git a/d3d12/scripts/play-nvidia.ps1 b/d3d12/scripts/play-nvidia.ps1 index b22bd07384..b2efe7ec79 100644 --- a/d3d12/scripts/play-nvidia.ps1 +++ b/d3d12/scripts/play-nvidia.ps1 @@ -338,7 +338,8 @@ $settings = @{ # e5e7120 and El1xr's section_mb.rs, GPL-3.0, which measured the unmap at 99-182 -> 3-11 us). Walking and turning # from one save, 4 minutes each (2026-11-28, RTX 4060 Ti): mean 111.6 -> 94.4 ms a frame, median 105.1 -> 91.7, # p90 139.3 -> 113.9; title memory held for mapping changes 43.2 -> 8.9 ms a frame, the mapping thread 46.2 -> - # 20.7. Sections of 2 MiB measured the same (91.7, 91.8, 111.4). '0' in -More: one section, as before. + # 20.7. Sections of 2 MiB measured the same (91.7, 91.8, 111.4). The code's default since 2026-11-29 (play.ps1 and + # cargo run get it too); kept here so that the measured value stays written. '0' in -More: one section, as before. LEONIDA_SECTION_MB = '16' } # The card's own memory, from its driver's key (HardwareInformation.qwMemorySize, 64-bit; Win32_VideoController's diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index 92653e2ea5..1a5b1edc95 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -488,7 +488,9 @@ Slot 148 matters beyond the builder: the address it returns is written by the CP as a root SRV address, so console upload memory has the same address for the CPU and the GPU. On a PC the two address spaces differ, so `d3d12_xs_device.cpp` carves a bump arena out of persistently-mapped UPLOAD-heap buffers: the title writes the mapped memory and the six root descriptor setters and the IA/SO view setters -translate the CPU pointer to the chunk's buffer device address before forwarding. +translate the CPU pointer to the chunk's buffer device address before forwarding. The buffers belong to the command +allocator the list records into: that allocator's Reset, which D3D12 allows only once the GPU has finished its +lists, carves them from the front again, and its release frees them (`LEONIDA_UPLOAD_REWIND`, runtime/README.md). The function at `0xd580` uses the 71/73 pair instead of the slot-146 barrier when the byte at RVA `0xd773c` is set. That byte is one of seven bools at `0xd7738`–`0xd773e` in zero-initialised `.bss`. The only accesses to them in diff --git a/docs/d3d12_xs_console_abi.md b/docs/d3d12_xs_console_abi.md index fc3c75a17b..2e9784eca0 100644 --- a/docs/d3d12_xs_console_abi.md +++ b/docs/d3d12_xs_console_abi.md @@ -252,6 +252,11 @@ The runtime's model: state set so far (heaps, root signatures and arguments, pipeline, viewports, scissors, targets, vertex and index buffers, blend factor, stencil reference, predication; what an executed bundle set, and nothing from before a `ClearState`) is set on it again. A cut that would split an open query waits for the query's `EndQuery`. + At the title's next `Reset` the parts' real lists become spares for later cuts, the newest reused first. Nothing + executes a spare again before a cut resets it, so it drops its recording then (`rt::d3d12::drop_recording`): an + idle spare keeps no commands, no pipeline states, root signatures or scratch they held, and no command-list epoch + that would keep a retired title window from being freed (`src/command_list_epochs.h`). `xbox_list_cut_spares` + covers it. Bundles record neither method (`ExecuteBundle` names one real list, so a bundle cannot be cut). - At submission each part's waits are checked: met ones cost nothing; one that a write still in flight will meet becomes a queue `Wait` on that write's fence (the GPU orders the two queues); any other makes the queue `Wait` on diff --git a/docs/directstorage.md b/docs/directstorage.md index 10b9390cb8..0e7bd2e17a 100644 --- a/docs/directstorage.md +++ b/docs/directstorage.md @@ -226,10 +226,14 @@ shim beyond the size check it already does. The last one is behaviour the first - Two adjacent file-backed transforms can read and decode concurrently into private buffers. A queue has one ordered publisher. Mutable memory inputs, page-list resolution, status slots, events, fences, and overlapping destinations retain their enqueue order. At most two helpers run across all queues and each - assisted request has a 16 MiB eligibility limit. A shared 64 MiB window covers private source, - intermediate, output and page-number buffers across queues. Each transform releases its previous input - and each request releases the final buffer at retirement. A valid request larger than the window runs - alone, bounded by the ABI maximum of two 1 GiB payloads. Raw buffer reads use no private staging. + assisted request has a 16 MiB eligibility limit. A shared 64 MiB window covers the private source, + intermediate, output and page-number buffers of the requests running across queues. A valid request + larger than the window runs alone, bounded by the ABI maximum of two 1 GiB payloads. Raw buffer reads + use no private staging. + Each queue's worker keeps its staging buffers from one request to the next (its own and its helper's), + so streaming does not allocate and zero-fill them per request. Between requests it keeps at most + 16 MiB of them, dropping the largest first; a larger request has its buffers for its own time. What the + workers keep is outside the 64 MiB window: idle queues hold up to 16 MiB each until they close. With tracing enabled, `ds-staging` reports the process peak reservation and return to zero. The figure excludes title destinations, allocator overhead and fixed decoder stacks. `LEONIDA_DSTORAGE_WORKERS=1` restores serial execution. diff --git a/docs/ultrawide.md b/docs/ultrawide.md index 6570401511..7f7e2be162 100644 --- a/docs/ultrawide.md +++ b/docs/ultrawide.md @@ -89,7 +89,7 @@ The same two settings, read by the D3D12 runtime's own code. Nothing of this sec | variable | where | what it does | |---|---|---| | `LEONIDA_ASPECT` | `d3d12/crates/leonida-hle/src/modules/lifecycle.rs` (`fit`), `leonida-gpu/src/aspect.rs` | the window the title asks for (3840x2160) is made in that shape at the same height (5040x2160 for `21:9`, 7680x2160 for `32:9`), then fitted to the screen as before. `auto`: the primary monitor's shape. | -| `LEONIDA_PRESENT_SCALE` | `leonida-gpu/src/host.rs` (`present_planes`), `aspect.rs` (`frame`) | `fit`: in a window of another shape the swap chain becomes a frame of the window's shape at the picture's height (or width), cleared to black, with the picture copied unscaled into its middle. `stretch`: the swap chain is the picture and the window stretches it, as before. Unset: `fit` with `LEONIDA_ASPECT`, else `stretch`. | +| `LEONIDA_PRESENT_SCALE` | `leonida-gpu/src/host/present.rs` (`present_planes`), `aspect.rs` (`frame`) | `fit`: in a window of another shape the swap chain becomes a frame of the window's shape at the picture's height (or width), cleared to black, with the picture copied unscaled into its middle. `stretch`: the swap chain is the picture and the window stretches it, as before. Unset: `fit` with `LEONIDA_ASPECT`, else `stretch`. | `scripts/play-d3d12.ps1 -Aspect 21:9 [-PresentScale fit|stretch]` sets them; the F1 menu has WINDOW SHAPE (next start) and PICTURE IN ANOTHER SHAPE (live). With neither set nothing changes: the frame of a 16:9 window is the picture itself