diff --git a/d3d12/apps/leonida/src/warm.rs b/d3d12/apps/leonida/src/warm.rs index 60d7b050a1..aa8a4aad5e 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/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index ceffbdf114..d4b8baeb01 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -419,7 +419,7 @@ 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). /// `LEONIDA_SWEEP=0` keeps everything, as before. fn sweep() { // The in-place probe and census, if asked for (`LEONIDA_INPLACE_PROBE`). @@ -446,6 +446,7 @@ fn sweep() { trim_spare_backs(); } 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(); diff --git a/d3d12/crates/leonida-gpu/src/host/send.rs b/d3d12/crates/leonida-gpu/src/host/send.rs index 32cb70473a..d454f7b082 100644 --- a/d3d12/crates/leonida-gpu/src/host/send.rs +++ b/d3d12/crates/leonida-gpu/src/host/send.rs @@ -232,10 +232,20 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc, Vec<(usize, us let mut to = to as *mut [u32; 2]; for &(a, b) in ranges.iter().filter(|r| short(r)) { 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]); diff --git a/d3d12/crates/leonida-gpu/src/list.rs b/d3d12/crates/leonida-gpu/src/list.rs index 48a898b925..683e389d1e 100644 --- a/d3d12/crates/leonida-gpu/src/list.rs +++ b/d3d12/crates/leonida-gpu/src/list.rs @@ -218,25 +218,73 @@ impl Detached { } } -/// A host list that has run and waits to be used again, and the bytes of -/// upload memory it keeps. +/// A host list that has run and waits to be used again. #[cfg(windows)] -struct Idle(crate::host::HostList, u64); +struct Idle(crate::host::HostList); // 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 { + 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 Pool { + const fn new() -> Self { + Pool { kept: Vec::new(), bytes: 0, low: 0 } + } + + /// The thing given last. + fn take(&mut self) -> Option { + 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 { + 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 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::(); + 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, u64)> = std::sync::Mutex::new((Vec::new(), 0)); +static IDLE: std::sync::Mutex> = 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 @@ -259,20 +307,30 @@ fn pools() -> bool { /// after its reset, or a new one. #[cfg(windows)] fn fresh_list() -> Option { - 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 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 @@ -286,18 +344,16 @@ pub(crate) fn recycle(lists: Vec, ran: &[usize]) { // The descriptor slots and the upload memory its commands named. drop(_state); drop(_uploads); - 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(); let bytes = host.scratch_kept(); - 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 { - idle.0.push(Idle(host, bytes)); - idle.1 += bytes; - } + let refused = IDLE.lock().unwrap_or_else(|e| e.into_inner()).give(Idle(host), bytes, IDLE_MOST); + // (Dropped outside the lock.) + drop(refused); } } @@ -379,8 +435,8 @@ pub(crate) fn cut_list(this: This) -> bool { pub(crate) type Parts = Vec<(Vec, Vec, Vec)>; /// 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 @@ -410,16 +466,11 @@ pub(crate) fn detach_parts(lists: &[This]) -> Parts { } continue; } - let Some(fresh) = fresh_list() else { - continue; - }; - // A new host list is open; the title's next call on its list is a - // reset, which wants it closed. - fresh.close(); // 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::() }; - 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); @@ -488,8 +539,8 @@ pub(crate) fn ahead_of_frame() -> Option { } /// 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, Vec) { let mut taken: Vec<(This, Detached)> = Vec::new(); @@ -502,17 +553,11 @@ pub(crate) fn detach(lists: &[This]) -> (Vec, Vec) { order.push(i); continue; } - let Some(fresh) = fresh_list() else { - continue; - }; - // A new host list is open; the title's next call on its list is a - // reset, which wants it closed. - fresh.close(); let list = this.cast_mut().cast::(); // 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 = @@ -711,6 +756,18 @@ extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT let list = unsafe { &mut *this.cast_mut().cast::() }; 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. + if list.host.is_none() + && let Some(fresh) = fresh_list() + { + fresh.close(); + list.host = Some(fresh); + } } #[cfg(windows)] with_state(this, |host, state| { @@ -2690,6 +2747,94 @@ 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 = (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:: 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 = 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 = (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); + } + /// 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 f262325444..f4600d2e88 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(); } @@ -690,6 +695,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) { @@ -929,4 +949,28 @@ mod tests { assert_eq!(kept[1], 2); 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"); + } + } } diff --git a/d3d12/crates/leonida-gpu/src/memory.rs b/d3d12/crates/leonida-gpu/src/memory.rs index 223f760ce3..d660c61cf5 100644 --- a/d3d12/crates/leonida-gpu/src/memory.rs +++ b/d3d12/crates/leonida-gpu/src/memory.rs @@ -402,9 +402,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))); @@ -538,6 +545,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 +555,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::(); + 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 +679,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 +689,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()); } } @@ -894,24 +927,28 @@ fn packed_len(header: u64) -> Option { (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 @@ -1307,13 +1344,173 @@ 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::() 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 + ); + } + + /// 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::().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::().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::().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::().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); } #[test] diff --git a/d3d12/crates/leonida-gpu/src/picked.rs b/d3d12/crates/leonida-gpu/src/picked.rs index 54985b813f..aedff1596a 100644 --- a/d3d12/crates/leonida-gpu/src/picked.rs +++ b/d3d12/crates/leonida-gpu/src/picked.rs @@ -129,6 +129,8 @@ fn ask(shader: Arc) { 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 709a4cc98a..26333e8b91 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,14 +60,40 @@ pub(crate) struct Shader { pub(crate) stage: &'static str, /// The first 8 bytes of its BLAKE3, as logged. pub(crate) hash: String, - container: Vec, + /// 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>>, /// Its part in the stand-in for the indirect light. #[cfg(windows)] pub(crate) ambient: Option, #[cfg(windows)] + facts: OnceLock, + #[cfg(windows)] translated: OnceLock>, } +/// 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) @@ -78,7 +104,8 @@ impl std::fmt::Debug for Shader { static SHADERS: Mutex>>> = 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: @@ -130,16 +157,57 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc { 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(), }) }) .clone() } +impl Shader { + /// The container, while the shader keeps it. + #[cfg_attr(not(windows), allow(dead_code))] + fn container(&self) -> Option> { + 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()); + if kept.take().is_some() { + 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 { @@ -161,6 +229,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, + /// 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, + /// 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, @@ -171,18 +244,21 @@ 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); + // Still here: it goes below, once, after the translation. + let container = self.container()?; + let done = translate(&container, &self.hash); // `LEONIDA_SHADER_SAVE=`: 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") { let dir = std::path::PathBuf::from(dir); let _ = std::fs::create_dir_all(&dir); let stem = format!("{}.{}", 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); } @@ -206,6 +282,16 @@ 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. + if let Ok(t) = &done { + self.facts(); + if !(t.stores && crate::picked::on()) { + self.let_container_go(); + } + } done.ok() }) .as_ref() @@ -214,17 +300,20 @@ impl Shader { #[cfg(windows)] impl Shader { - /// 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> { 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]) -> Result { +fn translate(container: &[u8], hash: &str) -> Result { use leonida_shader::{Container, FourCC, HwStage}; // The translation depends on it (a view index past a capped heap). crate::descriptor::host::probe_view_limit(); @@ -267,6 +356,8 @@ fn translate(container: &[u8]) -> Result { stores_by_address, writes, pack, + program: program_name(container), + linear_samplers: crate::pipeline::host::linear_samplers(hash, container), pack_logged: Default::default(), picks: Default::default(), }) @@ -317,12 +408,16 @@ static BUILDER: Mutex = Mutex::new(Builder { /// Whether `shaders` are a pipeline of the structure builder. #[cfg(windows)] fn of_builder(shaders: &[Arc]) -> 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) @@ -499,7 +594,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"); } } @@ -959,7 +1054,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() } @@ -1005,13 +1100,113 @@ mod tests { assert_eq!(slot:: 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 { + fn put(out: &mut Vec, 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::(); + 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> = (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 = containers.iter().map(|c| create(c)).collect(); + let shaders: Vec<&Arc> = + pipelines.iter().map(|&p| &pipeline(p).shaders[0]).collect(); + let all_held = || shaders.iter().map(|s| held(s)).sum::(); + 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:: 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 [ @@ -1036,8 +1231,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 { @@ -1047,6 +1241,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)] { @@ -1058,4 +1260,23 @@ 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); + } } diff --git a/d3d12/crates/leonida-gpu/src/pipeline/host.rs b/d3d12/crates/leonida-gpu/src/pipeline/host.rs index 6776eab8e1..464bd55719 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 = 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 { @@ -829,7 +836,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(); @@ -997,7 +1004,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], 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 feae4a5a2c..4bcd198fdc 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/library.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/library.rs @@ -12,7 +12,8 @@ //! 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 +50,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}; @@ -680,7 +681,7 @@ pub(crate) fn save(now: bool) { }; // Through `used`: a process that asked for none yet (`leonida shaders`) // must not write the earlier runs' list over with nothing. - let used: Vec = used().iter().flatten().cloned().collect(); + let used: Vec = 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. @@ -803,25 +804,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>> = Mutex::new(None); +/// Title pipeline keys requested by draws or dispatches (this run and the +/// last, [`early_runs`]). +static USED: Mutex> = Mutex::new(None); static USED_CHANGED: AtomicBool = AtomicBool::new(false); -fn used() -> std::sync::MutexGuard<'static, Option>> { +/// 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 runs; 0: every run's, as before. +fn early_runs() -> u64 { + static RUNS: OnceLock = 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, +} + +impl Early { + fn read(text: &str) -> Early { + let mut keys: HashMap = 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 { + 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> { 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 = 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 @@ -831,14 +904,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); } } @@ -987,6 +1058,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 70588b4e20..9d264bb8ec 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>, - pub(crate) graphics: Option>, + /// Shared with every pipeline of the same state ([`shared_state`]). + pub(crate) graphics: Option>, queue_state: AtomicU8, /// Taken by a worker from [`Queue::slow`]. was_slow: AtomicBool, @@ -58,10 +59,24 @@ pub(crate) struct Pending { variant: OnceLock>, } -fn named(shaders: &[Arc], 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], 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]) -> Option<&'static str> { @@ -116,17 +131,19 @@ unsafe impl Sync for Pending {} impl Pending { pub(crate) fn new(shaders: Vec>, graphics: Option>) -> 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()); key.update(s.hash.as_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, @@ -188,6 +205,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, described: &str) -> Arc { + struct Held(Weak); + // 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, 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 = 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/resource.rs b/d3d12/crates/leonida-gpu/src/resource.rs index 2fc331a1ef..4c8483e4d9 100644 --- a/d3d12/crates/leonida-gpu/src/resource.rs +++ b/d3d12/crates/leonida-gpu/src/resource.rs @@ -2153,16 +2153,16 @@ fn sweep_batch(all: &std::collections::BTreeSet, from: usize, limit: usiz /// 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 = 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<_>) = @@ -2173,6 +2173,10 @@ pub(crate) fn let_go_idle() { crate::host::retire(made); } } + static ON: std::sync::OnceLock = 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 = std::sync::OnceLock::new(); let keep = *KEEP @@ -5062,4 +5066,55 @@ 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"); + } } diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 8415889fac..010ccd352c 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -401,6 +401,15 @@ 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, } /// What a copy in the card's memory ([`cards`]) has beside the buffer @@ -1785,8 +1794,9 @@ mod relay_tests { } } -/// Snapshot memory kept for reuse (already touched, so no page faults). -static POOL: Mutex>> = 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, 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 @@ -1798,11 +1808,11 @@ fn pooled(n: usize) -> Vec { 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(); @@ -1828,11 +1838,12 @@ fn snapshots_kept() -> usize { /// bytes in all. fn give_back(v: Vec) { 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; @@ -1845,6 +1856,59 @@ fn give_back(v: Vec) { 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 while nothing is in flight, so 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. + 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, u64)>, now: u64, idle_ms: u64) -> Vec<(Vec, u64)> { + pool.extract_if(.., |(_, at)| now.saturating_sub(*at) >= idle_ms).collect() +} + +#[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, 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::>(), [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; @@ -2948,7 +3012,7 @@ unsafe fn word_runs_avx2_in(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` @@ -3672,6 +3736,15 @@ 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()); + // 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> = { // Held from the look to the removal: `loose` hands a copy out // under the same lock, so none is handed out in between. @@ -3679,7 +3752,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)| { @@ -3724,7 +3796,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::()) + (pool.len() as u64, pool.iter().map(|(v, _)| v.capacity() as u64).sum::()) }; [ LIVE[0].load(Ordering::Relaxed), @@ -3859,6 +3931,7 @@ impl Shadow { wc: AtomicU8::new(0), mapped: false, place: None, + opened: None, } } @@ -4603,8 +4676,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); @@ -4646,7 +4720,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); @@ -5050,6 +5124,17 @@ 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) { + 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() + } + /// 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) { @@ -6296,6 +6381,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> { + 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> { + by_address_with(start, len, true) +} + +fn by_address_with(start: u64, len: u64, open: bool) -> Option> { let host = host()?; if !cards() || !host.card_ready() { return None; @@ -6310,7 +6414,13 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option> { 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 { @@ -6339,12 +6449,40 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option> { has_sent: Default::default(), size: 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 { + 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>> = std::sync::RwLock::new(BTreeMap::new()); @@ -6544,17 +6682,27 @@ pub(crate) fn exact(address: u64, len: u64) -> Option> { // 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}")); @@ -6575,11 +6723,76 @@ pub(crate) fn exact(address: u64, len: u64) -> Option> { 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> = 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>> = 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 = (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(spare: &mut Vec>, let_go: impl IntoIterator, now: u64) -> Vec { + 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(spare: &mut Vec>, now: u64, idle_ms: u64) -> Vec { + 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); @@ -6601,6 +6814,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> = 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::>(), [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::{ diff --git a/d3d12/crates/leonida-gpu/src/texture.rs b/d3d12/crates/leonida-gpu/src/texture.rs index 6282633d9f..4e2d2d5ac2 100644 --- a/d3d12/crates/leonida-gpu/src/texture.rs +++ b/d3d12/crates/leonida-gpu/src/texture.rs @@ -448,23 +448,103 @@ fn waited(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> = 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, u64)>> = Mutex::new(Vec::new()); + +/// Calls `f` with `size` bytes of read buffer (their contents are whatever +/// the last texture left). fn with_read(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, u64)>, size: usize) -> Vec { + 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, u64)>, now: u64, idle_ms: u64) -> Vec<(Vec, 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: freeing tens of MB of +/// touched memory takes milliseconds, and nothing is in flight while the +/// sweep runs, so the card would wait for it. +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 = std::sync::OnceLock::new(); + *KEPT.get_or_init(|| { + std::env::var("LEONIDA_TEXTURE_READ_KEEP_MB") + .ok() + .and_then(|v| v.trim().parse::().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 @@ -534,10 +614,14 @@ pub(crate) fn let_go() -> [u64; 2] { /// 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. +/// Read buffers of large textures no read took for `idle_ms` go too +/// ([`let_go_idle_reads`]), whether or not there are staging buffers. /// 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 idle_ms = crate::host::ram_idle_ms(crate::residency::headroom()); + let_go_idle_reads(idle_ms); let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); let Some(map) = map.as_mut() else { return; @@ -545,7 +629,6 @@ pub(crate) fn let_go_idle() { 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. @@ -2560,6 +2643,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, 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, 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::>(), [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/upload.rs b/d3d12/crates/leonida-gpu/src/upload.rs index 172d6928d3..b148fac7d6 100644 --- a/d3d12/crates/leonida-gpu/src/upload.rs +++ b/d3d12/crates/leonida-gpu/src/upload.rs @@ -122,8 +122,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> = 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-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 9027da0a45..6462444385 100644 --- a/d3d12/crates/leonida-hle/src/modules/apu.rs +++ b/d3d12/crates/leonida-hle/src/modules/apu.rs @@ -137,6 +137,11 @@ struct State { results: VecDeque, 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, } fn lock(c: &Connection) -> std::sync::MutexGuard<'_, State> { @@ -210,6 +215,7 @@ pub extern "system" fn XApuConnect( results: VecDeque::new(), commands: 0, dequeued: 0, + pcm: vec![0.0; MAX_FRAMES * 2], }), }); // SAFETY: checked non-null. @@ -249,6 +255,9 @@ pub extern "system" fn XApuEnqueueCommand( // SAFETY: a connection from `XApuConnect`; every command starts with an id. let (connection, id) = unsafe { (&*handle, 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; @@ -300,7 +309,7 @@ pub extern "system" fn XApuEnqueueCommand( // SAFETY: a process command is this struct. let command = unsafe { command.cast::().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, } } @@ -321,8 +330,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); @@ -335,8 +351,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; @@ -416,7 +434,7 @@ pub(crate) fn module() -> HleModule { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use opus_pure::{Application, OpusEncoder}; @@ -540,6 +558,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::(); + + std::thread_local! { + pub(crate) static COUNT: Cell = 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::(); + 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::::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 = (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 = (0..960 * 2) diff --git a/d3d12/crates/leonida-hle/src/modules/dstorage.rs b/d3d12/crates/leonida-hle/src/modules/dstorage.rs index 202d94e0bb..38e3a3bd6e 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; @@ -229,7 +229,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 = std::sync::OnceLock::new(); let floor = *FLOOR_MB.get_or_init(|| { @@ -776,6 +778,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 +790,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 +808,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, + packed: Vec, + pages: Vec, +} + +/// 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, 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 +1024,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 +1092,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 +1450,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 +1481,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,25 +1493,24 @@ 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 }; - 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"))?; // The console's order: zlib first, then BCPack. let source = if bc != 0 && options & ZLIB != 0 { - 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 { - Some(tables) => bcpack::decode(bc, &source, out, tables) + into_destination(request, size, pages, |out| match tables { + Some(tables) => bcpack::decode(bc, source, out, tables) .map(|()| out.len()) .map_err(|e| fail(INVALID_DATA, &e.to_string())), - None => inflate(&source, out).map_err(|hr| fail(hr, "zlib")), + None => inflate(source, out).map_err(|hr| fail(hr, "zlib")), })?; tracing::trace!( options = format_args!("{options:#x}"), @@ -1539,18 +1615,19 @@ fn load_bcpack_tables() -> Result { 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, 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) -> 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. @@ -1611,10 +1688,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, mut fill: impl FnMut(&mut [u8]) -> Result, ) -> Result<(), HRESULT> { if request.options & PAGE_DESTINATION == 0 { @@ -1644,7 +1722,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; @@ -1662,11 +1740,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, mut fill: impl FnMut(&mut [u8]) -> Result, ) -> Result<(), HRESULT> { // Consecutive pages of one allocation (the usual case): written in @@ -1676,8 +1756,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, @@ -1783,7 +1866,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}; @@ -2097,7 +2180,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. @@ -2137,7 +2220,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); @@ -2296,6 +2379,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); @@ -2342,6 +2474,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 = (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() { 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, usize)>, - ready: Condvar, -} - -static POOL: Pool = Pool { - state: Mutex::new((VecDeque::new(), 0)), - ready: Condvar::new(), -}; + state: Mutex, + linger: Duration, + keep: usize, +} + +struct PoolState { + tasks: VecDeque, + /// 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>, + /// 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 dcc3d5e88f..dec4b2e3ca 100644 --- a/d3d12/crates/leonida-hle/src/modules/xmem.rs +++ b/d3d12/crates/leonida-hle/src/modules/xmem.rs @@ -372,7 +372,10 @@ pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) { // whole reservation, or a header-prefixed block. unsafe { if attributes & ALLOC_32BIT != 0 { - VirtualFree(address, 0, MEM_RELEASE); + // `XMemVirtualAlloc` told the GPU side of this memory, so it is + // freed as the title's own `VirtualFree` frees: what was noted of + // it must not be taken for true of the next memory there. + title_virtual_free(address, 0, MEM_RELEASE); return; } let user = address.cast::(); @@ -2182,11 +2185,21 @@ extern "system" fn title_virtual_free(address: *mut c_void, size: usize, kind: u // 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); + #[cfg(test)] + TOLD_FREED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(address as usize); } // SAFETY: the title's own arguments. unsafe { VirtualFree(address, size, kind) } } +/// 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> = Mutex::new(Vec::new()); + pub(crate) fn module() -> HleModule { HleModule { name: "xmem", @@ -2239,6 +2252,21 @@ mod tests { XMemFree(p, ALLOC_32BIT); } + #[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" + ); + } + #[test] fn virtual_alloc_meets_console_constraints() { const GPU_READ_WRITE: u32 = 0x2000; 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/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index eea693c701..7746144618 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -411,7 +411,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_vulkan.md b/docs/d3d12_vulkan.md index 3084bf06b8..ca5e548102 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -92,7 +92,8 @@ enough for the bundled middleware's `d3d12_xs` calls, not for the game. The laye start handles returned in RAX at heap slots 9/10. Implement the public chain plus those measured overrides explicitly; do not assume every slot. On the retail executable's higher device slots (`runtime/shims/d3d12_xs_device.cpp`), slot 86 routes `CreatePipelineState(desc, riid, out)` to PC slot 47 (`ID3D12Device2::CreatePipelineState`) and keeps - a deep copy of the stream on the PSO it returns; slot 55 (`CreateDerivedPipelineState(pBasePSO, n, pRecords, riid, + a deep copy of the stream on the PSO it returns (its shader bytecode once per content for the process, shared by + every PSO whose stream carries the same bytes); slot 55 (`CreateDerivedPipelineState(pBasePSO, n, pRecords, riid, out)`, `n` = 1..4 records of 0x14c bytes: a u32 tag, then the payload at +4) patches a copy of that stream and creates the PSO through the same path. Tags 0 (`D3D12_DEPTH_STENCIL_DESC`, on DEPTH_STENCIL or DEPTH_STENCIL1), 1 (`D3D12_RASTERIZER_DESC`), 2 (`D3D12_BLEND_DESC`) and 3 (sample mask) are the TomBox layout (GPL-3.0, @@ -916,7 +917,8 @@ The compute path, end to end: - Shader-visible descriptor heaps also live in it: the CPU handle is its host mapping and the GPU handle is the VA, so descriptor bytes the application writes itself are what shaders load. - Upload and readback buffers keep their own memory, and their VA is their device address minus the heap base. - - Shader programs (FSSM blobs) are copied in as the code base. + - Shader programs (FSSM blobs) are copied in as the code base, once per program: the PSOs made from one program + share its copy, which goes back to the arena with the last of them (`LEONIDA_SHARE_CODE_BASE`). - **`CreateRootSignature`** parses the blob with `parse_rts0` and keeps each parameter's place in two layouts, both the console's (one dword per table; section 3.5, D3D-448): `pack_stage(Stage::Pixel)` for the graphics bind point (from s8; a signature past s31 there keeps `pack()`'s s0 layout, logged) and `pack_stage(Stage::Compute)` for the @@ -1719,7 +1721,10 @@ The copies: began before the retirement is gone (reset, released, or a held batch's or the async worker's copy of it run), and the submissions recorded by then have completed: a list resolves its root views when they are recorded, so one recorded before the retirement and executed, or executed again, after it still names the window - (`src/command_list_epochs.h`). Until then its copy stays a target of its pages' tracker, refreshed like the others, + (`src/command_list_epochs.h`). A list-value cut's spare drops its recording when it becomes one + ([d3d12_xs_console_abi.md](d3d12_xs_console_abi.md)); a list the title closes and then neither resets nor releases + keeps every window retired after its recording began, and a retired window still waiting after 30 s is logged once. + Until it is freed its copy stays a target of its pages' tracker, refreshed like the others, and what the GPU wrote in it goes back to the title's pages: with its submissions' write-back, and once more when it is freed (a range noted when a list was recorded can be copied back before a held batch has run). A retired copy goes back only on the bytes no live copy over them changed, byte by byte (the window and the buffer that replaced it can @@ -1780,10 +1785,16 @@ The copies: whole gets a copy of its whole range, so the BVH builder's commands are recorded. - `LEONIDA_GEOMETRY_MB` sets the device-local memory cap for streamed buffer views. The default is 0. A positive cap enables persistent copies of placed buffer SRVs and buffer descriptors in title memory. - A GPU-only reservation uses its paired CPU mapping. Matching source ranges share one copy. + A GPU-only reservation uses its paired CPU mapping. Matching source ranges share one copy, and a range inside a + live, filled copy is answered from that copy at its offset instead of being copied again + (`LEONIDA_GEOMETRY_CONTAINED=0`: a copy of its own, as before). The copy of an acceleration structure's whole + range (`copy_title_range`: a destination, scratch or input no other range holds whole) is never answered that way, + so a release elsewhere in a larger copy cannot take a structure the GPU wrote with it. The resource descriptor heap keeps its console indices and original CPU bytes. Its shader-visible copy encodes each resolved buffer's offset from the arena base. CPU writes through either physical mapping, - file reads and XMem remaps invalidate the affected copies before their next submission. + file reads and XMem remaps invalidate the affected copies before their next submission. A filled copy over a + 64 KiB tile that a file read is still writing (it cannot be guarded yet) takes its other written tiles at once, + and that tile once the read has ended (`geometry_views_test` case 18). During an untyped heap scan, an extent above 16 MiB with no format or an unrecognized descriptor encoding reuses only an independently established geometry view. An explicit table or placed SRV can establish that view. The Vulkan memory probe reports populated views, payload and reserved bytes, @@ -1799,8 +1810,12 @@ The copies: extent is forgotten, and its memory is freed only after every ExecuteCommandLists replay in progress at the retirement has recorded its submissions and those have completed (`kAfterExecutes`). Before it leaves the refresh it is copied once more from its pages if they are still readable (a heap block freed in memory that - stays committed). The next view of the range makes a new copy. - `geometry_views_test` cases 14-16 cover this without a GPU. + stays committed). The ranges answered from inside it go with it, each invalidated by its own address; when the + release did not touch one of them, the view's memory also waits until no command list is left whose recording + began before those invalidations had run. Unlike a retired title window, the view is not refreshed meanwhile: a + list recorded before the retirement and executed after it reads such a range as the last copy left it. The + `geometry buffers` line counts the retired views waiting for command lists. The next view of the range makes a + new copy. `geometry_views_test` cases 14-17 cover this without a GPU. - **Which pages changed** since the last refresh: where xmem reserved the title's memory with `MEM_WRITE_WATCH` (`XMemVirtualAlloc`'s ordinary regions and the title's `VirtualAlloc` reservations, not placeholders or physical-page windows), the kernel says (`GetWriteWatch` with reset, its answers kept for every copy over the page: @@ -1903,8 +1918,8 @@ texture coverage and the game's use of tile streaming remain open. lookups a summary by format, type and tiling. - `LEONIDA_UNBACKED_VSHARP=1`: the buffer V#s `fix_vsharp` writes empty because nothing backs their base; one line for each of the first 120 distinct bases and every 8192 a summary by 4 GiB range of the base. -- `LEONIDA_UPLOAD_LOG=1` (`d3d12_xs_device.cpp`): each upload chunk (CPU base, device address, size) and the first 96, - then every 8192nd, `AllocateUploadMemory` result as an offset into its chunk. +- `LEONIDA_UPLOAD_LOG=1` (`d3d12_xs_device.cpp`): each upload chunk (CPU base, device address, size), made and given + back, and the first 96, then every 8192nd, `AllocateUploadMemory` result as an offset into its chunk. - `LEONIDA_UPLOAD_ALIAS=1` (an experiment, changes behaviour): enters each upload chunk's CPU range in the title VA table, so a V# the title wrote with the CPU pointer `AllocateUploadMemory` handed it is rewritten to the chunk instead of left empty. A chunk below the arena needs `LEONIDA_IMPORT_BELOW_ARENA=1` as well. @@ -2146,9 +2161,11 @@ The game can use D3D12 descriptors in three ways, and the layer must handle all (a backing, an alias range, title memory) go on an unbounded per-device list; at the next submission each heap fixes again exactly the slots whose records a change touches: a release or removal every half naming it, an addition the waiting halves over it. Nothing walks the heap or reads the copy for this. A zeroed range, a slot - the title rewrote and a heap destroyed drop their records. `console_heap_slot_records_test` checks that a release - of a buffer 10 of 60,010 slots name looks at those 10, and compares the copy with a full re-resolution through - random writes, releases, additions and alias changes. + the title rewrote and a heap destroyed drop their records, and an index bucket goes with the last half it holds: + the indexes hold the granules of the live halves, not every granule the session wrote a V# into. + `console_heap_slot_records_test` checks that a release of a buffer 10 of 60,010 slots name looks at those 10, + compares the copy with a full re-resolution and each lookup with a walk of every half through random writes, + releases, additions and alias changes, and that two halves moved 200,001 times hold 3 buckets (600,003 before). Console resource heap copies and shader-visible CBV/SRV/UAV heaps with at least 65,536 slots request 64 MiB of zeroed padding after their last descriptor. `LEONIDA_HEAP_GUARD_MB` sets the padding in MiB (0 disables it). When arena space is tight, allocation can fall back to the heap alone. Only indices @@ -3628,6 +3645,32 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv complete CPU read. Copies of descriptors written earlier resolve to the fallback until that upload succeeds. `LEONIDA_TITLE_IMAGE_DEFER=0` allocates these textures eagerly. The memory probe reports the live unbound image count and its Vulkan memory requirements in MiB. +- **When a slot-70 image goes**: an image made for slot-70 views was retired only when its address got another + description or a slot-133 texture. A title that streams places its textures at ever new addresses of its memory, + so each address named kept an image, its bindless index (65,536 per dimension) and its turn in every refresh + pass for the device's life. Now an image is also retired once a texture made or registered after its last view + covers some of its bytes, or once none of its pages has been committed (freed, decommitted or unmapped: a + `title_memory_map` change over it, then a look at its pages) for `LEONIDA_TITLE_IMAGE_IDLE_MS` (2000), in both + cases when no slot-70 view has named it for that long. An image over exactly the same bytes (the other view of a + stream pool) does not cover it; one never filled (the view of a texture whose pages have not come) does not go + with its pages; two textures over the same bytes that views keep naming both stay. Its T# keys go at once and the + image 3 s later, as for an address given another description. A later view of the address makes it again: a T# + names the title address, so descriptors the title kept find the new image once it is filled; until then, and for + an address no view names again, they sample the fallback. A slot-133 texture covers an image with the layout of + the title's XG computer of its shape, or with the one its first slot-70 view gives it; the guess from its + description (Layout 0) can be larger than what the title placed, and covers nothing. A view that names an image + whose pages went keeps it, until a later change over its pages finds them still gone. Pages are looked at only + after a change with a range: xmem records a change anywhere for each run of pages it commits for a DirectStorage + transfer on Windows, and it names no image's pages. A whole release (`VirtualFree` with `MEM_RELEASE` and no size) + records the range of the reservation. A look walks the pages with VirtualQuery on the title's submitting thread, + so a pass visits at most `LEONIDA_TITLE_IMAGE_CHECKS` (128) of the images that may go, from where the last one + stopped. The title textures census line counts the retirements under a newer texture and with their pages gone, + and the images a view named again after a newer texture covered them (overlapping textures both in use). + It is off by default (`LEONIDA_TITLE_IMAGE_RETIRE=1` turns it on) until a game session has measured it: a title + that samples an image through a descriptor it wrote once (a heap it copies from, a table it keeps), with no later + slot-70 view of the address, would sample the fallback once the image goes, and the census cannot see that. The + range a whole release records is there for every reader of the map, whatever the switch. + `d3d12_title_image_retire` and `d3d12_title_image_idle` cover it without game files, with the switch on. - With `LEONIDA_TITLE_PARTIAL_MIPS=1`, such a texture can be filled before all its pages are readable. The XG layout of a 2D texture of one slice stores its mips from the smallest to the largest, so the mips from `m` on are the first `mip_chain_bytes(layout, m)` bytes from its base (`xg_xs_layout.h`; checked in `xg_xs_test` for tiled, @@ -3649,6 +3692,11 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv over the map itself would step into a freed node (measured: an access violation reading the nil flag of a null child, 0x19, in `Device::refresh_title_textures`). The snapshot also holds a reference to each entry, so an entry retired during the pass is still alive when its turn comes. +- An image made for slot-70 views (`make_title_texture`) is held by the registry and holds no reference to the device; + a retired one is released by the first refresh pass 3 s later, and `~Device` releases the rest after the GPU is idle + (`release_title_images`). With a device reference, a device released before those passes never went: it kept every + Vulkan object it had (`d3d12_existing_heap`'s device without host image copies: 93 at `vkDestroyDevice` on an + RX 7900 XT, VUID-vkDestroyDevice-device-05137). - Sampled title images can use device-local memory even when Vulkan host image copies require a host-visible memory type. The runtime queries the same image with and without host-transfer usage. When only the latter permits plain device-local backing, it detiles the complete image into a reusable diff --git a/docs/d3d12_xs_console_abi.md b/docs/d3d12_xs_console_abi.md index 986acf6802..2418aa380f 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/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 5b875bbd73..d15089245c 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1528,6 +1528,8 @@ if(BUILD_TESTING) add_test(NAME xs_proxy_mock_env_slots_74 COMMAND xs_proxy_mock_test --env-slots-74) # LEONIDA_SLOT133_LAYOUT_WORD=1 (set by the test itself): the slot 133 stand-in reads its fourth word as a layout. add_test(NAME xs_proxy_mock_slot133_layout COMMAND xs_proxy_mock_test --slot133-layout) + # LEONIDA_UPLOAD_REWIND=0 (set by the test itself): the upload arena only advances, as before the rewind. + add_test(NAME xs_proxy_mock_upload_rewind_off COMMAND xs_proxy_mock_test --upload-rewind-off) endif() # Reads d3d12.h and takes MSVC options, so only where the Windows runtime is built. if(TARGET gta6rt) @@ -2303,6 +2305,23 @@ if(TARGET Vulkan::Headers) add_test(NAME vk_fence_lost_by_counter COMMAND vk_fence_lost_by_counter_test) set_tests_properties(vk_fence_lost_by_counter PROPERTIES SKIP_RETURN_CODE 77) endif() + # The deferred deletion queue after a device loss: what was queued and what is released later is destroyed while + # the context lives, not at its teardown (driver vkDestroyBuffer interposed). + add_executable(vk_deferred_destroy_lost_test test/vk_deferred_destroy_lost_test.cpp) + target_link_libraries(vk_deferred_destroy_lost_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_deferred_destroy_lost_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + else() + find_package(Threads REQUIRED) + target_link_libraries(vk_deferred_destroy_lost_test PRIVATE Threads::Threads) + endif() + if(MSVC) + target_compile_options(vk_deferred_destroy_lost_test PRIVATE /W4 /permissive- /utf-8) + endif() + if(BUILD_TESTING) + add_test(NAME vk_deferred_destroy_lost COMMAND vk_deferred_destroy_lost_test) + set_tests_properties(vk_deferred_destroy_lost PROPERTIES SKIP_RETURN_CODE 77) + endif() # The bindless set under view churn (bounded table, spare generations) and failed allocations (host table, in-place # rewrite, a degraded flush instead of a refused submission). add_executable(vk_bindless_grow_test test/vk_bindless_grow_test.cpp) @@ -2897,6 +2916,18 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_placed_heap_lifetime PROPERTIES SKIP_RETURN_CODE 77 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # LEONIDA_SHADOW_GPU=1 alone keeps no released arena range or removed alias range for the console heap pass, + # which never runs then; with LEONIDA_CONSOLE_HEAP_GPU=1 an arena release is one range, taken by the next + # submission (RT-SHADOW-GPU-RELEASED-RANGES). The test sets both variables itself. + add_executable(d3d12_shadow_gpu_releases_test test/d3d12_shadow_gpu_releases_test.cpp) + target_link_libraries(d3d12_shadow_gpu_releases_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_shadow_gpu_releases_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_shadow_gpu_releases_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_shadow_gpu_releases COMMAND d3d12_shadow_gpu_releases_test) + add_test(NAME d3d12_console_heap_gpu_releases COMMAND d3d12_shadow_gpu_releases_test --console-heap-gpu) + set_tests_properties(d3d12_shadow_gpu_releases d3d12_console_heap_gpu_releases PROPERTIES SKIP_RETURN_CODE 77 + FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # ClearUnorderedAccessViewUint/Float on buffers and textures, read back through D3D12. add_executable(d3d12_uav_clear_test test/d3d12_uav_clear_test.cpp) target_link_libraries(d3d12_uav_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) @@ -2979,9 +3010,21 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_host_prefix COMMAND d3d12_existing_heap_test --host-prefix-only) set_tests_properties(d3d12_host_prefix PROPERTIES SKIP_RETURN_CODE 77) set_tests_properties(d3d12_existing_heap PROPERTIES SKIP_RETURN_CODE 77) - # LEONIDA_TEXTURE_REFRESH_ASYNC=1 (set by the test itself): a mapped plane's first submission reads its bytes. + # LEONIDA_TEXTURE_REFRESH_ASYNC=1 (set by the test itself): a mapped plane's first submission reads its bytes, and + # a mapped plane destroyed inside the registry leaves nothing for the refresh worker (RT-TITLE-TEXTURE-GONE-RANGES). add_test(NAME d3d12_mapped_plane_async COMMAND d3d12_existing_heap_test --mapped-plane-async) set_tests_properties(d3d12_mapped_plane_async PROPERTIES SKIP_RETURN_CODE 77) + # LEONIDA_TITLE_IMAGE_RETIRE=1, with LEONIDA_TITLE_IMAGE_IDLE_MS=0 and LEONIDA_TITLE_IMAGE_CHECKS=4 (set by the test + # itself): the images made for + # slot-70 views of textures a streaming title places at ever new addresses of the same memory stay at the textures + # still there, and a pass looks at the pages of a few of them, only of those under a change it knows the range of. + add_test(NAME d3d12_title_image_retire COMMAND d3d12_existing_heap_test --title-image-retire) + set_tests_properties(d3d12_title_image_retire PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "LEONIDA_TITLE_IMAGE_RETIRE=1") + # LEONIDA_TITLE_IMAGE_IDLE_MS=500 (set by the test itself): such an image goes only after that long unnamed. + add_test(NAME d3d12_title_image_idle COMMAND d3d12_existing_heap_test --title-image-idle) + set_tests_properties(d3d12_title_image_idle PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "LEONIDA_TITLE_IMAGE_RETIRE=1") # The same with write watching off: the guarded cases only, the concurrent writers among them. add_test(NAME d3d12_existing_heap_no_write_watch COMMAND d3d12_existing_heap_test) set_tests_properties(d3d12_existing_heap_no_write_watch PROPERTIES SKIP_RETURN_CODE 77 @@ -2990,6 +3033,14 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_existing_heap_write_watch COMMAND d3d12_existing_heap_test) set_tests_properties(d3d12_existing_heap_write_watch PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_WRITE_WATCH=1") + # A placed BC texture's shape whose shared zero image could not be made gets one at a later placement, after a wait + # that doubles at each failure. + add_executable(d3d12_zero_image_retry_test test/d3d12_zero_image_retry_test.cpp) + target_link_libraries(d3d12_zero_image_retry_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_zero_image_retry_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_zero_image_retry_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_zero_image_retry COMMAND d3d12_zero_image_retry_test) + set_tests_properties(d3d12_zero_image_retry PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) # Slot 133 on untouched xmem physical pages: committed through the pages hook, then imported. xmem.cpp and # registry.cpp are compiled in, as xmem_test does, to reach the registered XMem* exports. add_executable(d3d12_xmem_placed_test test/d3d12_xmem_placed_test.cpp shims/xmem.cpp shims/registry.cpp) @@ -3006,6 +3057,15 @@ if(TARGET Vulkan::Headers) set_tests_properties(xbox_linear_texture_map PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30 ENVIRONMENT "LEONIDA_LINEAR_MAP_FIRST=1") set_tests_properties(d3d12_xmem_placed PROPERTIES SKIP_RETURN_CODE 77) + # A vertex or index view of title memory that can be neither imported nor shadowed gets no stand-in buffer and is + # tried again after a delay, not at every bind; after a refusal no other view is tried for that second either. + add_executable(d3d12_title_buffer_fallback_test test/d3d12_title_buffer_fallback_test.cpp) + target_link_libraries(d3d12_title_buffer_fallback_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_title_buffer_fallback_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_title_buffer_fallback_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_title_buffer_fallback COMMAND d3d12_title_buffer_fallback_test) + set_tests_properties(d3d12_title_buffer_fallback PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 + ENVIRONMENT "LEONIDA_SLOT133_IMPORT=0;LEONIDA_ARENA_MB=16") # Fences and timing (D3D-30): multiple-fence waits, clock calibration, adapter LUID, custom heap properties. add_executable(d3d12_fence_timing_test test/d3d12_fence_timing_test.cpp) @@ -3490,6 +3550,14 @@ if(TARGET Vulkan::Headers) target_link_options(xbox_list_value_fallback_test PRIVATE /OPT:NOREF) add_test(NAME xbox_list_value_fallback COMMAND xbox_list_value_fallback_test) set_tests_properties(xbox_list_value_fallback PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + # The spare real lists a list-value cut leaves: an idle one drops its recording, so it holds back no retired title + # window (src/command_list_epochs.h) and holds nothing its recording used. + add_executable(xbox_list_cut_spares_test test/xbox_list_cut_spares_test.cpp shims/d3d12_xs_device.cpp + shims/d3d12_xs_pso_stream.cpp) + target_link_libraries(xbox_list_cut_spares_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_list_cut_spares_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) + add_test(NAME xbox_list_cut_spares COMMAND xbox_list_cut_spares_test) + set_tests_properties(xbox_list_cut_spares PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) add_executable(d3d12_present_test test/d3d12_present_test.cpp) target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi) target_compile_definitions(d3d12_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -4099,6 +4167,7 @@ if(TARGET Vulkan::Headers) VERBATIM) endforeach() add_executable(d3d12_draw_test test/d3d12_draw_test.cpp test/d3d12_stateful_indirect_pixels.cpp + test/d3d12_draw_views_sharing.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_VS_INT}) target_link_libraries(d3d12_draw_test PRIVATE gta6rt_d3d12_com) @@ -4123,6 +4192,8 @@ if(TARGET Vulkan::Headers) d3d12_stateful_indirect_nonindexed_counted_pixels PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) add_test(NAME d3d12_title_index_window COMMAND d3d12_draw_test --title-index-window) add_test(NAME d3d12_title_vertex_window COMMAND d3d12_draw_test --title-vertex-window) + # Draws that keep the same render targets and vertex buffers share one views block (recording only). + add_test(NAME d3d12_draw_views_sharing COMMAND d3d12_draw_test --draw-views-sharing) # LEONIDA_STUB_PIPELINES: a pipeline with no translated shader is a stub when the switch is on. add_executable(d3d12_stub_pipelines_test test/d3d12_stub_pipelines_test.cpp) target_link_libraries(d3d12_stub_pipelines_test PRIVATE gta6rt_d3d12_com) @@ -4138,7 +4209,8 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_stub_draw_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_stub_draw COMMAND d3d12_stub_draw_test) set_tests_properties(d3d12_stub_draw PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) - set_tests_properties(d3d12_draw d3d12_title_index_window d3d12_title_vertex_window PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(d3d12_draw d3d12_title_index_window d3d12_title_vertex_window d3d12_draw_views_sharing + PROPERTIES SKIP_RETURN_CODE 77) # Graphics & compute PSO descriptor validation parity against live Windows D3D12 (WARP and HW). add_executable(d3d12_pso_validation_test test/d3d12_pso_validation_test.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_CS}) @@ -4155,6 +4227,19 @@ if(TARGET Vulkan::Headers) # the thread (d3d12_compile_teardown_test). set_tests_properties(d3d12_pso_validation PROPERTIES SKIP_RETURN_CODE 77 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") + # The arena copy of a program that shaders read their code base from: one per program, shared by its PSOs. + add_executable(d3d12_code_base_share_test test/d3d12_code_base_share_test.cpp ${LEONIDA_TEST_CS} + ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_PS}) + target_link_libraries(d3d12_code_base_share_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_code_base_share_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" + LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}") + target_compile_options(d3d12_code_base_share_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_code_base_share COMMAND d3d12_code_base_share_test) + # LEONIDA_SHARE_CODE_BASE=0: a copy for every PSO, as before. + add_test(NAME d3d12_code_base_per_pso COMMAND d3d12_code_base_share_test --per-pso) + set_tests_properties(d3d12_code_base_per_pso PROPERTIES ENVIRONMENT "LEONIDA_SHARE_CODE_BASE=0") + set_tests_properties(d3d12_code_base_share d3d12_code_base_per_pso PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) # Conservative raster Tier 1, with geometric coverage bounds and host D3D12 references. set(LEONIDA_CONSERVATIVE_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_conservative.spv) set(LEONIDA_CONSERVATIVE_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative.spv) @@ -4858,6 +4943,17 @@ if(TARGET Vulkan::Headers) target_compile_options(memory_breakdown_test PRIVATE /W4 /permissive- /utf-8) endif() add_test(NAME memory_breakdown COMMAND memory_breakdown_test) + # The mem probe's vmmap line, its reading of the process on native Windows (src/mem_probe.h): the classifier over + # synthetic regions and ranges, and walks of this process around memory it commits and maps. + if(WIN32) + add_executable(mem_probe_vmmap_test test/mem_probe_vmmap_test.cpp) + target_link_libraries(mem_probe_vmmap_test PRIVATE Vulkan::Headers psapi) + target_compile_definitions(mem_probe_vmmap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + if(MSVC) + target_compile_options(mem_probe_vmmap_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME mem_probe_vmmap COMMAND mem_probe_vmmap_test) + endif() # The address guard's page table (src/address_guard.h; docs/d3d12_vulkan.md, "Address guard"). add_executable(address_guard_test test/address_guard_test.cpp) if(WIN32 AND MSVC) diff --git a/runtime/README.md b/runtime/README.md index 1a3d18f429..426f1d8cbf 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -341,6 +341,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w |---|---|---| | `LEONIDA_LAZY_PIPELINES` | on | Graphics pipelines are built at their first draw. `0` builds each at `CreatePipelineState`, as before; the title creates far more pipelines at startup than it draws with. | | `LEONIDA_LAZY_COMPUTE` | on | Compute pipelines are built at the first dispatch that names them, or earlier by the warm-up thread. `0` builds each at `CreateComputePipelineState`. | +| `LEONIDA_SHARE_CODE_BASE` | on | The copy of a shader program that shaders read their code base from (`s_getpc_b64` and the constant tables in the program) is made once in the GPU address arena for all the PSOs of that program, compute and graphics, and goes back to the arena when the last of them is released. `0` gives every PSO a copy of its own, as before. | | `LEONIDA_ASYNC_MIN_BYTES` | unset | ``, with `LEONIDA_ASYNC_PIPELINES=1`: only a pipeline of n bytes of SPIR-V or more (compute: its module; graphics: all its stages) is built asynchronously, its draws or dispatches skipped until the compile worker has it; a smaller one is built where it is needed, as with asynchronous builds off, so small lighting and post programs are not skipped while the large ray-tracing ones compile. Unset or `0`: every pipeline is asynchronous. Text that is not a decimal number is ignored, with a log line. ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md), "Only the large ones asynchronous") | | `LEONIDA_ASYNC_MIN_BYTES_GRAPHICS` | unset | ``, with `LEONIDA_ASYNC_PIPELINES=1`: the threshold of `LEONIDA_ASYNC_MIN_BYTES` for graphics and mesh pipelines only (all their stages), so a draw can wait for a different size than a dispatch. `0`: every graphics pipeline is asynchronous (its draws skipped until built) while compute keeps `LEONIDA_ASYNC_MIN_BYTES`. Unset: graphics take `LEONIDA_ASYNC_MIN_BYTES`, as before the variable. Text that is not a decimal number is ignored, with a log line. ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md), "Only the large ones asynchronous") | | `LEONIDA_COMPUTE_WARMUP_MAX_BYTES` | `1048576` | The largest SPIR-V module, in bytes, the background warm-up thread (`LEONIDA_COMPUTE_WARMUP`) builds ahead of its first dispatch. Larger modules wait for that dispatch. | @@ -364,7 +365,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TITLE_TEXTURE_FILL_MB` | `32` | How many MiB of changed textures one pass fills again; the rest waits for the next pass. | | `LEONIDA_TEXTURE_HASH_BUDGET_US` | `400` | Microseconds a pass may spend hashing before it stops at a texture boundary. `0` leaves the byte budget alone to bound it. | | `LEONIDA_TEXTURE_SWEEP_BUDGET_US` | `400` | Microseconds a pass may spend on residency checks and uploads between textures. | -| `LEONIDA_TITLE_BUFFERS_MB` | `512` | The most memory, in MiB, of buffers made over the title's own memory for vertex and index views that name it. | +| `LEONIDA_TITLE_BUFFERS_MB` | `512` | The most memory, in MiB, of buffers made over the title's own memory for vertex and index views that name it. Only a buffer that covers its view (the pages imported or shadowed) is made, kept and counted. After a view whose pages got neither, no view is tried for a second, and a view refused again waits twice as long as the last time, up to 64 s. | | `LEONIDA_TITLE_BUFFER_COVERAGE` | on | Such a view counts as covered only when a known buffer spans all its bytes. `0` asks for the first byte only. | | `LEONIDA_SHADOW_FULL_WALK` | unset | *Diagnostic.* `1` queries every page of the title-memory shadows at every refresh, as before unchanged generations were skipped. | | `LEONIDA_STRICT_REPLAY` | unset | *Diagnostic.* `1` makes a draw or dispatch with an unresolvable resource fail its command list (`src/vulkan_replay.h`); by default it is dropped and logged. | @@ -379,7 +380,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_INPUT_TRACE` | unset | `1` (diagnostic, the GameInput shim built without SDL3) logs the title's reading calls on the scripted pad: the first 128, then each one with a button down and every 1000th. Details in [docs/gameinput.md](../docs/gameinput.md#scripted-input-without-sdl3). | | `LEONIDA_LOG_ALLOCINFO` | unset | *Diagnostic.* `1` logs every device slot 25 call (`GetResourceAllocationInfo`) with its thread, description and sizes (`shims/d3d12_xs_device.cpp`). | | `LEONIDA_LOG_EXE_PIPELINES` | unset | *Diagnostic.* When set, one line per distinct graphics pipeline that uses a program translated from the executable's inline containers. | -| `LEONIDA_MEM_PROBE` | unset | *Diagnostic.* ``: every that many seconds the memory probe (`src/mem_probe.h`) logs `[rt] mem-probe t=` (live pipelines, shader modules and `VkDeviceMemory` per memory type), `[rt] mem-probe breakdown t=` (the same allocated bytes by consumer: the arena with its reserved, bound and in-use MiB, geometry copies, title windows and shadows, upload heaps, staging, texture blocks, sampled textures, render targets and depth, and `other`, which add up to the allocated total; `src/memory_breakdown.h`) and `[rt] mem-probe smaps` (the process's resident memory by kind). | +| `LEONIDA_MEM_PROBE` | unset | *Diagnostic.* ``: every that many seconds the memory probe (`src/mem_probe.h`) logs `[rt] mem-probe t=` (live pipelines, shader modules and `VkDeviceMemory` per memory type), `[rt] mem-probe breakdown t=` (the same allocated bytes by consumer: the arena with its reserved, bound and in-use MiB, geometry copies, title windows and shadows, upload heaps, staging, texture blocks, sampled textures, render targets and depth, and `other`, which add up to the allocated total; `src/memory_breakdown.h`) and `[rt] mem-probe smaps` (the process's resident memory by kind, read from `/proc` under Wine). On native Windows, which has no `/proc`, `[rt] mem-probe vmmap` takes the smaps line's place: the private commit, working set (and private working set where Windows reports it) and their peaks, then the committed MiB of a `VirtualQuery` walk over the address space by the same kinds (title memory, other PE private memory, PE images, PE sections, memory the Vulkan driver mapped for `vkMapMemory`) with their region counts, the reserved MiB and the four largest private allocations; the walk's time is in the line. | | `LEONIDA_MEM_PROBE_CACHE` | unset | *Diagnostic.* `1` adds the pipeline cache's size to the memory probe's report; the driver serializes the whole cache to answer. | | `LEONIDA_TEXTURE_PROBE` | unset | *Diagnostic.* Logs a `[rt] texture-probe` line for every shader resource view of a texture in the title's memory. | | `LEONIDA_LOCAL_DIAGNOSTICS` | unset | *Diagnostic.* `1` turns on the boot diagnostics that write to stderr from the draw, clear, present and descriptor paths (the lines tagged `present-probe`, `fsdraw`, `heap-probe`, `desc-probe` and `PresentX diag`; `src/local_diagnostics.h`). They follow a frame of the title from its draws to the window and cost a lock and a line per draw, so they are off by default. The full-screen draw targets that `LEONIDA_CAPTURE_SOURCE` reads back are only collected with it. | @@ -406,6 +407,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_REFRESH_PER_FRAME` | `0` | Trades correctness for speed. `1`: the slot-133 shadows, title windows and geometry copies are brought up to date only by the first submission after each present, not by every submission; `2`: the console descriptor heaps too. A GPU read of them can then be a frame behind the title's writes (wrong pixels). `0` refreshes all of them at every submission. | | `LEONIDA_GEOMETRY_ASYNC` | unset | Trades correctness for speed. `1` refreshes the geometry copies (`shims/d3d12_geometry_views.h`) on a worker thread of the layer, started at submission and not waited for, instead of on the title's submitting thread. A draw may read a copy the worker is still writing: wrong vertices for a frame. | | `LEONIDA_GEOMETRY_WHOLE_VIEWS` | unset | A geometry copy that is already filled copies only the 64 KiB tiles of title memory written since the last refresh (`shims/d3d12_geometry_views.h`). Any value other than `0` copies every view over a written tile whole, as before. | +| `LEONIDA_GEOMETRY_CONTAINED` | on | A range of title memory inside a live, filled geometry copy (`shims/d3d12_geometry_views.h`, under `LEONIDA_GEOMETRY_MB`) is answered from that copy at its offset, refreshed with it and retired with it, instead of being copied again. The copy of an acceleration structure's whole range (`copy_title_range`) always gets its own. `0` gives every range a copy of its own, as before: the same title bytes can then be held several times against the cap. The `geometry buffers` line counts the ranges answered this way, and the retired copies that wait for older command lists because a range inside them was still the title's. | | `LEONIDA_GEOMETRY_HOST` | unset | Where the geometry copies (`shims/d3d12_geometry_views.h`, under `LEONIDA_GEOMETRY_MB`) live. Unset or `0`: device-local memory through the BAR while the driver gives it (several GB of VRAM in a world run). `1`: system memory outside VRAM, write-back where the device offers a cached host type; `2`: system memory, write-combined. The GPU then reads every vertex and index of a copy over the bus, which can cost frame time in geometry-heavy passes. A device whose host-visible memory is all device-local (an integrated GPU) keeps its types. The choice is logged once and in the `geometry buffers` line. | | `LEONIDA_TITLE_FILL_ASYNC` | unset | Trades correctness for speed. `1` stops device slot 70 views from hashing and filling the texture they name on the title's thread: a texture never filled or known stale is queued for a worker thread that fills one texture at a time. Until then a shader samples the image as it is, empty or a frame behind. | | `LEONIDA_TITLE_VIEW_REFRESH_MS` | `0` | The shortest time, in milliseconds, between two checks of a title texture's bytes when a device slot 70 view of it is written. `0` checks at every view. The periodic pass still checks the texture on its own period, and a texture known stale is checked at once. Has no effect with `LEONIDA_TITLE_FILL_ASYNC=1`. | @@ -413,6 +415,9 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TITLE_TEXTURE_FILL_MS` | `8` | Milliseconds one pass over the textures filled from the title's memory may spend filling; a texture already started is finished. `0` removes the time limit and leaves `LEONIDA_TITLE_TEXTURE_FILL_MB` to bound the pass. | | `LEONIDA_TITLE_PARTIAL_MIPS` | unset | `1`: a 2D texture of one slice the title keeps in its own memory, whose larger mips are not readable, is filled from the first mip that is when its last slot-70 view starts there or later. Views that start above keep the fallback until a later fill has their mips. Unset, a texture waits for all its mips. | | `LEONIDA_TITLE_PARTIAL_MIPS_MB` | `2048` | With `LEONIDA_TITLE_PARTIAL_MIPS=1`, the image memory the textures filled in part may hold, in MiB: each has memory for all its mips. A texture past it keeps the fallback. | +| `LEONIDA_TITLE_IMAGE_RETIRE` | off | `1`: an image the layer made for device slot 70 views of a texture in the title's memory is retired, with its bindless index, once a texture made or placed (slot 133, with the layout of the title's XG computer or of a slot 70 view) after its last view covers some of its bytes, or once none of its pages has been committed for `LEONIDA_TITLE_IMAGE_IDLE_MS`, and no slot 70 view has named it for that long. A title that streams places its textures at ever new addresses, and each such image stayed for the device's life. A later view of the address makes the image again, with the same T#. The title textures census line counts the retirements by reason. Unset or `0` keeps an image until its address gets another description or a slot-133 texture, as before. Off by default until a game session has measured it: a title that samples such an image through a descriptor it wrote once, without a later slot 70 view of the address, would get the fallback texture once the image goes. ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md), "When a slot-70 image goes") | +| `LEONIDA_TITLE_IMAGE_IDLE_MS` | `2000` | With `LEONIDA_TITLE_IMAGE_RETIRE=1`: how long, in milliseconds, an image a newer texture covers must have gone without a slot 70 view, and one whose pages went must have stayed without them, before it is retired. `0` retires it at the next submission. | +| `LEONIDA_TITLE_IMAGE_CHECKS` | `128` | With `LEONIDA_TITLE_IMAGE_RETIRE=1`: how many of the images that may be retired one pass over the title's textures visits, from where the last pass stopped. A visit looks at the pages of an image under a map change with a range (a VirtualQuery walk, about a microsecond a call, on the title's submitting thread), so a change over a large pool that the title unloads is looked at over several passes. `0` visits all of them every pass. | | `LEONIDA_MAP_READBACK` | unset | `1` writes the GPU's texels of a small render or unordered-access target the title placed into the title's pages when the title maps it, so a CPU read of the target sees what the GPU rendered (the title reads its exposure statistics that way). Only a single-row, single-mip, single-layer, single-sample 2D target of at most 4 KiB a row; the copy waits for the GPU's work already submitted, and a page that is not writable is left as it is. Unset, the title reads its own pages, which the GPU never writes. | | `LEONIDA_SLOT133_IMPORT` | on | *Diagnostic.* `0` imports no title-placed buffer (device slot 133) as host memory: each takes the shadow-buffer fallback, so no GPU store can reach the title's memory through an import. | | `LEONIDA_ARENA_NULL_MB` | `0` | `n` (MiB) keeps the first `n` MiB of the descriptor arena, at `heap_base + 0`, zeroed and never allocated, and moves the zero page and the quad indices above it. A translated shader whose address arithmetic starts from a null base then reads or writes there instead of in a title buffer or the shared zero page. Ignored when it would take half of the arena or more; the device logs the region it made. | @@ -462,6 +467,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_STRAY_RO_HEAL` | unset | `1`: a title write into a read-only page of title memory that no guard of ours owns (a guard left behind) makes the page writable again and retries the write, so the title goes on; a shadow may then miss that page's next writes for a frame. Unset: the first 32 such pages are logged. | | `LEONIDA_PRELUDE_QUEUE_WAIT` | on | The prelude pass of a submission (the console-heap pass) waits for the last submission of another queue that recorded one (`src/vulkan_backend.h`). `0` (an experiment): no wait, so the queues do not serialise on each other's submissions; a list may read what the other pass has not written yet. | | `LEONIDA_DEPTH_BOUNDS_SLOT70` | on | Slot 70 of the console command list is forwarded to `OMSetDepthBounds` (`shims/d3d12_xs_device.cpp`). `0` leaves the slot to the default thunk. | +| `LEONIDA_UPLOAD_REWIND` | on | The memory console list slot 148 (`AllocateUploadMemory`) hands out belongs to the command allocator the list records into (`shims/d3d12_xs_device.cpp`): the allocator's Reset carves its upload buffers from the front again, gives back the ones it has not used for 8 Resets, and its release frees them. A list's own Reset gives nothing back. `0` keeps the one arena all lists share, which only grows until the device goes, as before: one more 8 MiB buffer each time the newest is full, in VRAM with Resizable BAR and in host memory without. | | `LEONIDA_DESCRIPTOR_RING` | unset | *Diagnostic.* `1` records the descriptor-table slots each list binds (`shims/d3d12_com.cpp`), as `LEONIDA_DEVICE_FAULT=1` does; it takes a global lock on almost every table bind. | | `LEONIDA_DESC_PROBE` | unset | *Diagnostic.* `1` logs which console-heap slots the API wrote and which the title wrote itself, what the title's records decode to and whether the GPU can see them. It hashes every slot of every bound table at each submission. The log quotes title data: keep it local. | | `LEONIDA_DRAW_DIAG` | on with the local diagnostics or `LEONIDA_FSDRAW_PROBE` | *Diagnostic.* Logs the first 8 draws and one in 1,200 after them, with whether each was skipped for having no viewport, its pipeline, render target, viewport and scissor (`shims/d3d12_com.cpp`). `0` turns it off, any other value on. | diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 472e2c62f0..14d0e38931 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -225,8 +225,24 @@ class GraphicsCommandList final // The pipeline states and root signatures the recording names (it holds a reference to each until Reset), and // the objects a shim handed it with hold_until_reset. const std::vector& pinned() const { return held_; } + // The objects a shim handed it with hold_until_reset (also in pinned()), which ExecuteCommandLists keeps until + // the submission has completed: the application may Reset or release the list as soon as the call returns. + const std::vector& kept() const { return kept_; } // rt::d3d12::hold_until_reset: an object the recording uses that its caller does not keep (a shim's own scratch). - void hold_for_recording(IUnknown* object) { hold(object); } + void hold_for_recording(IUnknown* object) { + if (std::find(kept_.begin(), kept_.end(), object) == kept_.end()) kept_.push_back(object); + hold(object); + } + // rt::d3d12::drop_recording: what Reset lets go of, now, without a new recording; the list stays closed. + bool drop_recording() { + if (!list_.drop_recording()) return false; + calls_.clear(); + tables_.clear(); + directly_indexed_ = false; + release_held(); + reset_state(nullptr); + return true; + } bool needs_all_sampled_views() const { if (directly_indexed_) return true; for (const auto& command : list_.commands()) { @@ -497,12 +513,17 @@ class GraphicsCommandList final const D3D12_CPU_DESCRIPTOR_HANDLE* depth) override { if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); if (count > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return check(false); - render_targets_.fill({}); - render_target_count_ = count; - draw_views_stale_ = true; + std::array bound{}; for (UINT i = 0; i < count && targets; ++i) { const SIZE_T handle = single_range ? targets[0].ptr + SIZE_T(i) * descriptor_size : targets[i].ptr; - if (handle) render_targets_[i] = *reinterpret_cast(handle); + if (handle) bound[i] = *reinterpret_cast(handle); + } + // The same targets bound again keep the current views block (draw_views), so the draws after them do not + // each allocate a new one. + if (count != render_target_count_ || bound != render_targets_) { + render_targets_ = bound; + render_target_count_ = count; + draw_views_stale_ = true; } depth_ = depth && depth->ptr ? *reinterpret_cast(depth->ptr) : leonida::TargetView{}; } @@ -1623,6 +1644,9 @@ class GraphicsCommandList final // layout it reads and the pipeline ExecuteCommandLists looks up still exist. (Keeping them alive while the GPU // runs the submission stays the application's job, as in D3D12.) std::vector held_; + // The part of held_ a shim handed the list (hold_until_reset). Nothing else keeps those alive while the GPU runs + // the submission (CommandQueue::keep_lists). No references of its own: held_ has them. + std::vector kept_; // A bundle keeps its state calls and draws instead of applying them: it has no render targets, viewport or root // signature of its own to resolve them against, and what it sets belongs to the list that executes it. @@ -1658,6 +1682,7 @@ class GraphicsCommandList final void release_held() { for (IUnknown* object : held_) object->Release(); held_.clear(); + kept_.clear(); } void set_pipeline(ID3D12PipelineState* state) { @@ -1857,8 +1882,10 @@ class GraphicsCommandList final } } + // Only a slot whose view changes marks the views block stale (draw_views). Titles bind the same vertex buffer + // again before many of their draws, and a new block for each would be one allocation of about 700 bytes per + // draw, kept until the list's Reset. void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) { - if (count) draw_views_stale_ = true; for (UINT i = 0; i < count; ++i) { // A stream pool's GPU-only alias becomes the CPU view of the same pages (rule B, gfxgeom section 6): the // buffer made for it, and every other view naming that range, then use one host-readable address. @@ -1868,9 +1895,12 @@ class GraphicsCommandList final : 0; if (views) leonida::title_va_aliases().note(va, leonida::TitleVaAliases::vertex_view); if (views) leonida::title_va_aliases().want_buffer(va, views[i].SizeInBytes); - vertex_buffers_[start + i] = views ? leonida::VertexBufferView{va, views[i].SizeInBytes, - views[i].StrideInBytes} - : leonida::VertexBufferView{}; + const leonida::VertexBufferView view = + views ? leonida::VertexBufferView{va, views[i].SizeInBytes, views[i].StrideInBytes} + : leonida::VertexBufferView{}; + if (view == vertex_buffers_[start + i]) continue; + vertex_buffers_[start + i] = view; + draw_views_stale_ = true; } } @@ -2358,16 +2388,34 @@ class CommandQueue final // are not held (a D3D12 application keeps them until the fence it signals; the docs, section 4.4, list this), // except a shim's own the recording uses (hold_until_reset), which are pinned with them. static std::shared_ptr pin_lists(const std::vector& lists) { - auto objects = std::shared_ptr>(new std::vector, [](auto* held) { + return reference_lists(lists, &GraphicsCommandList::pinned); + } + + // What a batch submitted at once keeps alive until its submission has completed on the GPU: the shim's own + // objects its lists use (hold_until_reset). The lists release them at their Reset or release, which D3D12 allows + // as soon as ExecuteCommandLists returns, and a default-heap buffer's arena range is free again the moment the + // buffer is destroyed. Null when no list has any, which is every list without a shim's scratch. + static std::shared_ptr keep_lists(const std::vector& lists) { + for (const GraphicsCommandList* list : lists) + if (!list->kept().empty()) return reference_lists(lists, &GraphicsCommandList::kept); + return nullptr; + } + + // Takes a reference to each object that `objects` returns for each list. They are released when the last copy of + // the result goes. + static std::shared_ptr reference_lists( + const std::vector& lists, + const std::vector& (GraphicsCommandList::*objects)() const) { + auto references = std::shared_ptr>(new std::vector, [](auto* held) { for (IUnknown* object : *held) object->Release(); delete held; }); for (const GraphicsCommandList* list : lists) - for (IUnknown* object : list->pinned()) { + for (IUnknown* object : (list->*objects)()) { object->AddRef(); - objects->push_back(object); + references->push_back(object); } - return objects; + return references; } // A D3D12 queue holds the fences it waits on and signals until the work has been submitted. @@ -2548,7 +2596,8 @@ class CommandQueue final return; } } - last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); + last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }, + [&graphics] { return keep_lists(graphics); }); d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); if (last_result_ != leonida::ReplayResult::success) std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists failed: %s; nothing was submitted\n", @@ -3044,6 +3093,11 @@ bool hold_until_reset(ID3D12GraphicsCommandList* list, IUnknown* object) { return true; } +bool drop_recording(ID3D12GraphicsCommandList* list) { + GraphicsCommandList* l = GraphicsCommandList::from(list); + return l && l->drop_recording(); +} + bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector& commands) { const GraphicsCommandList* l = GraphicsCommandList::from(list); if (!l) return false; diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index eaea4f648e..689236a2f4 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -347,6 +347,29 @@ struct TitleShadowWatch { std::uint64_t asks = 0, written = 0, faults = 0, watched_bytes = 0, hot_bytes = 0; }; TitleShadowWatch title_shadow_watch(ID3D12Device* device); +// What waits for the console heaps' GPU pass (LEONIDA_CONSOLE_HEAP_GPU, src/console_heap_gpu.h) to drop from its key +// table at the next submission that runs it: the arena ranges `device` released since the last one, and the alias +// ranges removed since (the alias table's list, one for the process). `made`: the device made the pass's object at +// all (LEONIDA_CONSOLE_HEAP_GPU=1 or LEONIDA_SHADOW_GPU=1). For tests. +struct ConsoleHeapGpuPending { + bool made = false; + std::uint64_t released = 0, removed = 0; +}; +ConsoleHeapGpuPending console_heap_gpu_pending(ID3D12Device* device); +// The device's registry of textures in the title's own memory now (write_placed_texture_view): the images it made for +// slot-70 texture views and their image memory, the slot-133 textures in it, the made images retired since the device +// was created (of them, those a newer texture over their bytes retired and those whose pages went), and how many +// retired images still wait for the GPU before their memory is freed. Then the made images that may be retired now, +// and, since the device was created, the looks at their pages and the images a view named again after a newer texture +// covered them. For tests. +struct OwnedTitleImages { + std::uint64_t owned = 0, owned_bytes = 0, slot133 = 0, retired = 0, superseded = 0, gone = 0, waiting = 0; + std::uint64_t candidates = 0, looks = 0, named_again = 0; +}; +OwnedTitleImages owned_title_images(ID3D12Device* device); +// The image made for slot-70 texture views at `address`, with a reference added for the caller; null when the +// registry holds none there. For tests. +ID3D12Resource* owned_title_image(ID3D12Device* device, std::uint64_t address); // True when `device` has VK_KHR_acceleration_structure + VK_KHR_ray_query enabled. bool device_supports_ray_tracing(ID3D12Device* device); @@ -393,6 +416,9 @@ bool device_sparse_buffer_tiles(ID3D12Device* device); // The size in bytes of the device's GPU address arena, or 0 without one. For tests. std::uint64_t device_arena_size(ID3D12Device* device); +// The bytes of the device's GPU address arena that hold shader programs now: the copies pipelines read their code +// base from. 0 without an arena. For tests. +std::uint64_t arena_shader_bytes(ID3D12Device* device); // Copies `bytes` of the device's GPU address arena at console VA `va` (what shaders read there: a heap's GPU copy, // the null slots after it) into `out`. False without an arena or when the range is not inside it. For tests. bool read_arena(ID3D12Device* device, std::uint64_t va, void* out, std::size_t bytes); @@ -460,6 +486,18 @@ void note_refused_tsharp_for_test(std::uint64_t heap_va, std::size_t offset, // or TitleImage::unknown / TitleImage::not_tsharp. TitleImage test_bind_title_image(ID3D12Device* device, const std::array& words, const char** why = nullptr); +// The title texture registry of `device` (the slot-133 textures and the images made for slot-70 views): its entries, +// the keys of the async refresh's range index and the mapped textures that refresh visits every pass. Read under the +// registry's lock, so a refresh pass on the worker (LEONIDA_TEXTURE_REFRESH_ASYNC=1) is over when it returns. For +// tests. +struct TitleTextureRegistry { + std::uint64_t textures = 0, ranges = 0, mapped = 0; +}; +TitleTextureRegistry title_texture_registry(ID3D12Device* device); +// Releases the caller's reference to `resource` with the registry's lock held on this thread, as a slot-70 view that +// overwrites the descriptor holding a texture's last reference does (title_texture_gone inside the registry), then +// lets drain_titles_gone remove what went. False when `device` is not a Vulkan device of this module. For tests. +bool release_in_title_registry(ID3D12Device* device, ID3D12Resource* resource); // Returns the internal image address registered for a resource in the device's image table. std::uint64_t resource_image_address(ID3D12Resource* resource); @@ -611,6 +649,9 @@ bool pipeline_stage_words(ID3D12PipelineState* pipeline, std::vector& commands); diff --git a/runtime/shims/d3d12_geometry_views.h b/runtime/shims/d3d12_geometry_views.h index 58649a29c2..e19abb5c10 100644 --- a/runtime/shims/d3d12_geometry_views.h +++ b/runtime/shims/d3d12_geometry_views.h @@ -1,8 +1,10 @@ #pragma once #include "d3d12_title_buffer_windows.h" +#include "../src/command_list_epochs.h" #include "../src/memory_breakdown.h" #include "../src/title_geometry_watch.h" +#include #include #include #include @@ -21,7 +23,7 @@ namespace rt::d3d12 { // Every CPU mapping of a source tile is watched; a physical remap changes which aliases must be watched. // Views whose title range is released are retired immediately and their backing storage is reclaimed once // in-flight GPU submissions up to their retire ticket have completed; previously cap-refused ranges retry -// once budget has been freed. +// once budget has been freed. A range inside a live view is answered from that view's bytes, not copied again. enum class GeometryCopy { copied, unreadable, interrupted }; class GeometryViews { @@ -51,13 +53,18 @@ class GeometryViews { struct FastEntry { VkDeviceSize va{}; std::uint64_t refused_at{}; // free_generation_ when refused (only meaningful when va == 0) + bool inside{}; // answered from inside a live view (contained_) }; struct Retired { VkDeviceSize va{}; std::size_t size{}; std::uint64_t ticket{}; // kAfterExecutes until execute_end() stamps it std::uint64_t epoch{}; // the last execute begun when it was retired (kAfterExecutes only) + std::uint64_t lists{}; // the command-list epoch it waits for (retire_range), 0 for none }; + // Retired::lists until retire_range has taken the epoch, once nothing answers the ranges inside the view: until + // then execute_end does not stamp the view. + static constexpr std::uint64_t kListsPending = UINT64_MAX; std::uint64_t cap_override_{}; mutable std::mutex mutex_; std::mutex refresh_mutex_; // refresh() only, held for its whole run, before mutex_ @@ -84,9 +91,9 @@ class GeometryViews { mutable std::shared_mutex structure_mutex_; mutable std::shared_mutex fast_mutex_; std::unordered_map fast_; - void publish(const Key& key, VkDeviceSize va, std::uint64_t refused_at = 0) { // mutex_ held + void publish(const Key& key, VkDeviceSize va, std::uint64_t refused_at = 0, bool inside = false) { // mutex_ held std::unique_lock lock(fast_mutex_); - fast_[key] = {va, refused_at}; + fast_[key] = {va, refused_at, inside}; } bool fast_find(const Key& key, VkDeviceSize& va) const { std::shared_lock lock(fast_mutex_); @@ -95,12 +102,13 @@ class GeometryViews { va = it->second.va; return true; } - bool fast_find_resolve(const Key& key, VkDeviceSize& va) const { + bool fast_find_resolve(const Key& key, VkDeviceSize& va, bool contain) const { std::shared_lock lock(fast_mutex_); const auto it = fast_.find(key); if (it == fast_.end()) return false; if (it->second.va == 0 && it->second.refused_at != free_generation_.load(std::memory_order_acquire)) return false; + if (it->second.inside && !contain) return false; va = it->second.va; return true; } @@ -109,6 +117,16 @@ class GeometryViews { std::size_t live_views_{}; bool refreshing_{}; std::map by_address_; + // The live views that no other live view holds, by their first byte: source -> {end, id}. As none holds another, + // their ends rise with their sources, so the last one starting at or before an address reaches furthest past it, + // and a range is inside some live view exactly when it is inside that one (outer_view_locked). A view held by one + // that is retired takes its place (retire_range). Under mutex_. + std::map> outer_; + // The keys resolve() answered from inside a live view instead of with a view of their own, with that view's id. + // They are its bytes at their offsets, watched and refreshed with it, and they leave with it (retire_range). + // Under mutex_. + std::map contained_; + std::uint64_t contained_hits_{}; std::map tiles_; std::vector retired_; std::atomic retired_count_{0}; @@ -154,6 +172,24 @@ class GeometryViews { } } + static constexpr std::size_t kNoView = SIZE_MAX; + // The live view that holds all of [cpu, cpu + bytes), or kNoView. mutex_ held; cpu + bytes does not wrap. + std::size_t outer_view_locked(Address cpu, std::size_t bytes) const { + auto it = outer_.upper_bound(cpu); + if (it == outer_.begin()) return kNoView; + --it; + return it->second.first >= cpu + bytes ? it->second.second : kNoView; + } + // A live view enters outer_ unless one there holds it, and the ones there that it holds leave. mutex_ held. + void enter_outer_locked(Address source, std::size_t size, std::size_t id) { + const Address end = source + size; + auto it = outer_.upper_bound(source); + if (it != outer_.begin() && std::prev(it)->second.first >= end) return; + // The ones it holds start at or after it, their ends rising: they leave until one reaches past its end. + for (it = outer_.lower_bound(source); it != outer_.end() && it->second.first <= end;) it = outer_.erase(it); + outer_.emplace(source, std::make_pair(end, id)); + } + bool update(Address va, Tile& t) { namespace watch = leonida::geometry_writes; if (!t.primary) t.primary = watch::acquire(va); @@ -245,6 +281,15 @@ class GeometryViews { } int system_memory() const { return pool_.system_memory(); } + // LEONIDA_GEOMETRY_CONTAINED=0: a range inside a live view gets a copy of its own, as before. + static bool contain_setting() { + static const bool value = [] { + const char* v = std::getenv("LEONIDA_GEOMETRY_CONTAINED"); + return !v || std::strcmp(v, "0") != 0; + }(); + return value; + } + bool has_released() const { return leonida::geometry_writes::has_released(releases_); } bool has_retired() const { return retired_count_.load(std::memory_order_acquire) != 0; } bool has_pending_reclaim() const { return has_released() || has_retired(); } @@ -296,19 +341,35 @@ class GeometryViews { return it == keys_.end() || !views_[it->second].alive ? 0 : views_[it->second].va; } + // `contain` false: a range inside a live view gets a view of its own all the same. A structure the GPU writes + // (copy_title_range) needs one: in another view's bytes it would leave with that view when a release elsewhere in + // it retires it, and its next copy would be made from the title's pages. template - std::uint64_t resolve(Device& device, Address cpu, std::size_t bytes, Copy copy) { + std::uint64_t resolve(Device& device, Address cpu, std::size_t bytes, Copy copy, bool contain = true) { if (!bytes || bytes > UINTPTR_MAX - cpu) return 0; const std::uint64_t limit = effective_cap(); if (!limit) return 0; const Key key = std::make_pair(cpu, bytes); - if (VkDeviceSize known = 0; fast_find_resolve(key, known)) return known; + if (VkDeviceSize known = 0; fast_find_resolve(key, known, contain)) return known; std::lock_guard lock(mutex_); if (const auto it = keys_.find(key); it != keys_.end()) { const VkDeviceSize known = views_[it->second].va; publish(key, known, 0); return known; } + // A range inside a live view is that view's bytes at its offset: the view's tiles already watch it and its + // refresh copies it, so a copy of its own would hold the same title bytes again, against the same cap. The + // view must be filled: one made over pages not all readable then is zeroed, also where the range is readable. + if (contain && contain_setting()) { + if (const std::size_t id = outer_view_locked(cpu, bytes); id != kNoView && views_[id].ready) { + const VkDeviceSize at = views_[id].va + (cpu - views_[id].source); + // Two threads that missed the lock-free answer for the same key both come here, one after the other. + if (contained_.insert_or_assign(key, id).second) ++contained_hits_; + refused_.erase(key); + publish(key, at, 0, true); + return at; + } + } const std::uint64_t gen = free_generation_.load(std::memory_order_acquire); const auto refused_it = refused_.find(key); if (refused_it != refused_.end() && refused_it->second == gen) { @@ -352,6 +413,7 @@ class GeometryViews { keys_[key] = id; by_address_.emplace(bda, id); } + if (contain_setting()) enter_outer_locked(cpu, bytes, id); if (bytes > max_view_bytes_) max_view_bytes_ = bytes; ++live_views_; bytes_ += bytes; @@ -411,11 +473,13 @@ class GeometryViews { std::lock_guard execute(execute_mutex_); for (const auto s : executing_) oldest = (std::min)(oldest, s); } + // Before the ticket: a list released after this read has had its submissions counted in it. + const std::uint64_t oldest_list = leonida::command_list_epochs::oldest(); const std::uint64_t ticket = submitted(); bool left = false; for (auto& r : retired_) { if (r.ticket != kAfterExecutes) continue; - if (r.epoch < oldest) r.ticket = ticket; + if (r.epoch < oldest && r.lists != kListsPending && r.lists <= oldest_list) r.ticket = ticket; else left = true; } unstamped_.store(left, std::memory_order_release); @@ -429,6 +493,8 @@ class GeometryViews { // committed) may hold new bytes, and a list recorded before the release that runs in a submission the view waits // for reads those, as it would have read them in the console's memory. Decommitted or unmapped memory is not // readable, so such a view keeps what it held. + // The ranges resolve() answered from inside a retired view go with it, each told to `on_retire` with the address + // it was answered with. Returns the number of views retired. template std::size_t retire_range(Address begin, Address end, std::uint64_t retire_ticket = 0, OnRetire&& on_retire = {}, Copy&& final_copy = {}) { @@ -439,6 +505,8 @@ class GeometryViews { VkDeviceSize va; }; std::vector callbacks; + std::vector pending; // the retired views at kListsPending, by address + std::size_t retired_views = 0; { std::lock_guard lock(mutex_); std::vector ids; @@ -456,6 +524,7 @@ class GeometryViews { if (begin < key.first + key.second) stale_refused.push_back(key); } if (ids.empty() && stale_refused.empty()) return 0; + retired_views = ids.size(); if (retire_ticket == kAfterExecutes && !ids.empty()) unstamped_.store(true, std::memory_order_release); callbacks.reserve(ids.size()); const std::size_t first_retired = retired_.size(); @@ -476,6 +545,40 @@ class GeometryViews { callbacks.push_back({v.source, v.size, v.va}); retired_.push_back({v.va, v.size, retire_ticket, 0}); } + // The ranges answered from inside these views are their bytes and leave with them. A view that was in + // outer_ leaves it; the live views it held take its place below, once the retired ones are out of keys_. + std::vector inner; + std::vector> vacated; + for (std::size_t i = 0; i < ids.size(); ++i) { + const std::size_t id = ids[i]; + const View& v = views_[id]; + bool untouched = false; + for (auto it = contained_.lower_bound({v.source, 0}); + it != contained_.end() && it->first.first < v.source + v.size;) { + if (it->second != id) { + ++it; + continue; + } + const auto [source, size] = it->first; + untouched |= source >= end || source + size <= begin; + callbacks.push_back({source, size, v.va + (source - v.source)}); + inner.push_back(it->first); + it = contained_.erase(it); + } + // A range inside it that the release did not touch is still the title's, and a command list recorded + // while it is still answered may name it and be executed after: the view's memory also waits until no + // such list is left (src/command_list_epochs.h). It is answered until fast_ forgets it below and the + // aliases and heap slots that hold its address are dropped (on_retire, after the lock), so the epoch is + // taken after on_retire. + if (untouched && retire_ticket == kAfterExecutes) { + retired_[first_retired + i].lists = kListsPending; + pending.push_back(v.va); + } + if (const auto it = outer_.find(v.source); it != outer_.end() && it->second.second == id) { + vacated.emplace_back(v.source, v.source + v.size); + outer_.erase(it); + } + } if (!ids.empty()) { std::unique_lock structure(structure_mutex_); for (const auto id : ids) { @@ -485,9 +588,13 @@ class GeometryViews { v.alive = false; } } + for (const auto& [from, to] : vacated) + for (auto it = keys_.lower_bound({from, 0}); it != keys_.end() && it->first.first < to; ++it) + enter_outer_locked(it->first.first, it->first.second, it->second); { std::unique_lock fast(fast_mutex_); for (const auto id : ids) fast_.erase({views_[id].source, views_[id].size}); + for (const auto& k : inner) fast_.erase(k); for (const auto& k : stale_refused) fast_.erase(k); } // No resolve() or find() answers these views from here on, so a replay that begins now cannot name them: @@ -509,7 +616,17 @@ class GeometryViews { retired_count_.store(retired_.size(), std::memory_order_release); } for (const auto& item : callbacks) on_retire(item.source, item.size, item.va); - return callbacks.size(); + // Nothing answers the ranges inside those views now, so a list whose recording begins from here on cannot name + // them. reap() may have compacted retired_ meanwhile, but it cannot have freed these entries, which execute_end + // leaves unstamped while they are pending: their addresses find them. + if (!pending.empty()) { + const std::uint64_t lists = leonida::command_list_epochs::advance(); + std::lock_guard lock(mutex_); + for (auto& r : retired_) + if (r.lists == kListsPending && std::find(pending.begin(), pending.end(), r.va) != pending.end()) + r.lists = lists; + } + return retired_views; } // Frees backing storage for retired views whose GPU retire_ticket <= completed_ticket, returning their budget @@ -584,8 +701,11 @@ class GeometryViews { }(); // One pass over the tiles: each written tile is read once and copied into every view over it, not view by // view (speed-16: up to 63 written tiles under 918 views a refresh, ~58,000 per-view lookups and copies, - // 30-80 ms). A view over a tile that cannot be guarded yet (retry) is left as it is this time; a view not - // filled yet is filled whole, once. + // 30-80 ms). A view over a tile that cannot be guarded yet (retry) is not filled whole this time, as that + // would read the tile; a view not filled yet is filled whole, once. A filled view over such a tile still takes + // its other written tiles: update() has taken their versions, so a tile skipped now would not be copied again + // until it is written again, and every range inside the view would keep the old bytes. The retry tile itself + // is not among the written ones, and is copied once it can be guarded. marks_.assign(views_.size(), 0); written_vas_.clear(); // The pass over the watched tiles makes a VirtualQuery and a VirtualProtect for each written one (tens of @@ -628,7 +748,7 @@ class GeometryViews { View& v = views_[id]; if (!v.alive) continue; std::uint8_t& mark = marks_[id]; - if (mark & (kPinned | kWhole)) continue; + if (mark & kWhole) continue; if (!(mark & kTouched)) { mark |= kTouched; ++changed_views; @@ -647,7 +767,7 @@ class GeometryViews { std::memcpy(v.dst + (from - v.source), read + (from - va), to - from); } else if (copy(v.dst + (from - v.source), reinterpret_cast(from), to - from) != GeometryCopy::copied) { - mark |= kWhole; // filled whole below, which zeroes it if that fails too + mark |= kWhole; // filled whole below (unless pinned), which zeroes it if that fails too continue; } uploaded_ += to - from; @@ -708,18 +828,29 @@ class GeometryViews { void report() const { if (!effective_cap()) return; std::lock_guard lock(mutex_); + // A command list kept for long (an idle one, or a bundle) holds these, and keeps execute_end walking retired_. + std::size_t waiting = 0; + std::uint64_t waiting_bytes = 0; + for (const auto& r : retired_) + if (r.ticket == kAfterExecutes && r.lists) { + ++waiting; + waiting_bytes += r.size; + } std::fprintf(stderr, "[rt] geometry buffers: seen %zu, backed %zu (%llu bytes), populated %llu, cap %llu MiB, " "cap refused %llu, retried ok %llu, evicted %llu (reaped %llu, retired %zu, copied at " "retirement %llu), allocation failures %llu, uploads %llu (%llu bytes), watched tiles %zu, " - "reserved %llu bytes (%s)\n", - keys_.size() + refused_.size(), live_views_, (unsigned long long)bytes_, (unsigned long long)ready_, + "reserved %llu bytes (%s), ranges inside a live view %zu (%llu so far), retired views " + "waiting for older command lists %zu (%llu bytes)\n", + keys_.size() + refused_.size() + contained_.size(), live_views_, (unsigned long long)bytes_, + (unsigned long long)ready_, (unsigned long long)(effective_cap() >> 20), (unsigned long long)cap_refusals_, (unsigned long long)retries_succeeded_, (unsigned long long)evicted_, (unsigned long long)reaped_, retired_.size(), (unsigned long long)final_copies_, (unsigned long long)allocation_failures_, (unsigned long long)uploads_, (unsigned long long)uploaded_, tiles_.size(), static_cast(pool_.reserved()), - pool_.system_memory() ? "system memory" : "device-local"); + pool_.system_memory() ? "system memory" : "device-local", contained_.size(), + (unsigned long long)contained_hits_, waiting, (unsigned long long)waiting_bytes); std::fprintf(stderr, "[rt] geometry refresh: %llu/%llu submissions uploaded dirty views, %llu bytes (%llu views by " "their written tiles only); %.3f s checking and refreshing sources, %llu bytes cleared\n", static_cast(dirty_refreshes_), static_cast(submissions_), @@ -740,6 +871,8 @@ class GeometryViews { by_address_.clear(); views_.clear(); } + outer_.clear(); + contained_.clear(); { std::unique_lock fast(fast_mutex_); fast_.clear(); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index de623b6040..3d21edc57c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -3377,7 +3377,12 @@ struct DeviceState { std::uint64_t start, shader_va, size, ticket, epoch; std::uint8_t* mapped; std::uint64_t lists; // the command-list epoch of the retirement + std::chrono::steady_clock::time_point retired_at; // for the warning in stamp_retired_windows }; + // A retired window still without a ticket this long after its retirement is reported once: a replay that does + // not end, or a command list recorded before the retirement that is closed and never reset or released. + static constexpr std::chrono::seconds kRetiredWindowWait{30}; + std::atomic retired_window_wait_reported{false}; static constexpr std::size_t kWindowAliasRemovals = 4096; // kept before every window is looked at instead std::mutex window_alias_removal_mutex; // a leaf: taken in alias_changed, under the alias table's lock std::vector> window_alias_removals; // (shader VA, bytes) @@ -3489,12 +3494,13 @@ struct DeviceState { std::vector retiring; const std::uint64_t epoch = geometry.execute_epoch(); const std::uint64_t lists = leonida::command_list_epochs::advance(); + const auto now = std::chrono::steady_clock::now(); std::uint64_t bytes = 0; std::erase_if(title_windows, [&](const TitleWindow& window) { if (!is_gone(window.shader_va)) return false; retire_shadow(window.mapped); retiring.push_back({window.start, window.shader_va, window.size, rt::d3d12::GeometryViews::kAfterExecutes, - epoch, window.mapped, lists}); + epoch, window.mapped, lists, now}); title_window_bytes -= window.size; bytes += window.size; return true; @@ -3553,12 +3559,34 @@ struct DeviceState { const std::uint64_t oldest_list = leonida::command_list_epochs::oldest(); const std::uint64_t ticket = context->submitted_retire_ticket(); bool left = false; + const RetiredWindow* longest = nullptr; // the earliest retired of those left without a ticket + std::size_t waiting = 0; + std::uint64_t waiting_bytes = 0; for (RetiredWindow& window : retired_windows) { if (window.ticket != rt::d3d12::GeometryViews::kAfterExecutes) continue; - if (window.epoch < oldest && window.lists <= oldest_list) window.ticket = ticket; - else left = true; + if (window.epoch < oldest && window.lists <= oldest_list) { + window.ticket = ticket; + continue; + } + left = true; + ++waiting; + waiting_bytes += window.size; + if (!longest || window.retired_at < longest->retired_at) longest = &window; } retired_windows_unstamped.store(left, std::memory_order_release); + if (!longest || retired_window_wait_reported.load(std::memory_order_relaxed)) return; + const auto waited = std::chrono::steady_clock::now() - longest->retired_at; + if (waited < kRetiredWindowWait || retired_window_wait_reported.exchange(true, std::memory_order_relaxed)) + return; + const std::uint64_t latest = leonida::command_list_epochs::current(); + std::fprintf(stderr, "[rt] d3d12: a title window retired %lld s ago still waits for %s; %zu retired windows " + "(%llu KiB) wait for a ticket, and the oldest command list alive began %llu command-list " + "epochs ago (logged once)\n", + static_cast(std::chrono::duration_cast(waited).count()), + longest->epoch >= oldest ? "a replay in progress at its retirement" + : "a command list recorded before its retirement", + waiting, static_cast(waiting_bytes >> 10), + static_cast(latest - std::min(oldest_list, latest))); } // ExecuteCommandLists replays in progress, for GeometryViews::kAfterExecutes (see drain_geometry_releases). // A plain aggregate on purpose: a C++ thread_local with a destructor in gta6rt.exe adds TLS callbacks to the image @@ -4100,8 +4128,9 @@ struct DeviceState { // or a build reaches the whole range by one address. A GPU-written structure (a BVH destination or its scratch) // keeps the GPU's writes in the copy: that is the only place the structure is read from afterwards, so the copy // is the structure. It is made even when a shorter range already maps the start: spreading a window's address over - // bytes it does not cover would be a lie. 0 when geometry copies are off (LEONIDA_GEOMETRY_MB), their cap refuses - // it, or the range is not the title's memory. + // bytes it does not cover would be a lie. It is not answered from inside a larger copy either (resolve's + // `contain`): a release elsewhere in that copy would retire the structure with it. 0 when geometry copies are off + // (LEONIDA_GEOMETRY_MB), their cap refuses it, or the range is not the title's memory. std::uint64_t copy_title_range(std::uint64_t va, std::uint64_t bytes) { const std::uint64_t span = std::max(bytes, 1); auto& aliases = leonida::title_va_aliases(); @@ -4110,7 +4139,7 @@ struct DeviceState { const auto cpu = leonida::title_gpu_views::to_host_view(static_cast(va), static_cast(span)); if (context->knows_buffer_va(cpu, span)) return 0; - const std::uint64_t copy = geometry.resolve(*this, cpu, span, copy_geometry); + const std::uint64_t copy = geometry.resolve(*this, cpu, span, copy_geometry, false); if (!copy) return 0; std::lock_guard lock(title_window_mutex); aliases.add(va, span, copy); @@ -4584,7 +4613,7 @@ struct DeviceState { std::lock_guard lock(backing_mutex); backing_generation.fetch_add(1, std::memory_order_relaxed); note_slot_change(leonida::SlotChange::target_gone, address, bytes); - if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); + if (heap_pass_enabled()) released_ranges.emplace_back(address - arena.address, bytes); } void backing(VkDeviceAddress address, uint64_t bytes, uint64_t id, bool add) { std::lock_guard lock(backing_mutex); @@ -4599,7 +4628,7 @@ struct DeviceState { // The heap slots whose copy names it are fixed again at the next refresh. note_slot_change(leonida::SlotChange::target_gone, address, bytes); // LEONIDA_CONSOLE_HEAP_GPU: the key entries answering into it go at the next refresh. - if (heap_gpu) released_ranges.emplace_back(address - arena.address, bytes); + if (heap_pass_enabled()) released_ranges.emplace_back(address - arena.address, bytes); } } @@ -4967,6 +4996,27 @@ struct DeviceState { static_cast(pool_span_bytes >> 10), static_cast(geometry_spans), static_cast(pool_spans_retired), static_cast(unbacked_requests)); + // The retired windows whose memory is not freed yet, and of those the ones still without a ticket, which + // wait for a replay in progress at their retirement or for a command list recorded before it + // (stamp_retired_windows); and how many command-list epochs ago the oldest list alive began. + std::lock_guard retired(retired_window_mutex); + std::size_t unstamped = 0; + std::uint64_t retired_bytes = 0, unstamped_bytes = 0; + for (const RetiredWindow& window : retired_windows) { + retired_bytes += window.size; + if (window.ticket != rt::d3d12::GeometryViews::kAfterExecutes) continue; + ++unstamped; + unstamped_bytes += window.size; + } + const std::uint64_t latest = leonida::command_list_epochs::current(); + const std::uint64_t oldest_list = leonida::command_list_epochs::oldest(); + std::fprintf(stderr, + "[rt] d3d12: title memory: %zu retired windows (%llu KiB) not freed yet, %zu of them " + "(%llu KiB) without a ticket; the oldest command list alive began %llu command-list epochs " + "ago\n", + retired_windows.size(), static_cast(retired_bytes >> 10), unstamped, + static_cast(unstamped_bytes >> 10), + static_cast(latest - std::min(oldest_list, latest))); } } @@ -4977,11 +5027,10 @@ struct DeviceState { // had must not change them, and a double free must not count the bytes twice. const auto fault = arena.blocks.release(offset, bytes); if (fault != leonida::ArenaBlocks::Fault::outside_arena) { + // A heap copy re-fixes the slots that named a backing that has gone (slot_changes): the range is no view's. backing(arena.address + offset, bytes, offset, false); arena.in_use -= bytes; arena.use_in_use[use] -= bytes; - // A heap copy re-fixes the slots that named a backing that has gone (slot_changes): the range is no view's. - backing(arena.address + offset, bytes, offset, false); } if (fault != leonida::ArenaBlocks::Fault::none && arena_report_due()) { std::fprintf(stderr, @@ -4998,6 +5047,66 @@ struct DeviceState { check_arena("a release"); } + // The arena copies of the programs shaders read their code base from (s_getpc_b64 and the constant tables in the + // program's own bytes; PipelineState::create_compute and create_graphics). A copy belongs to a program, not to a + // PSO: every PSO made from a program used to get a copy of the same bytes, so N PSOs of one program held N copies + // of the fixed-size arena. The first PSO of a program makes the copy and the others take a reference to it; the + // last one returns it to the arena when that PSO is deleted, which is when a PSO's own copy was returned. The key + // is the SHA-256 the PSO found the program's translation by, which is that of the bytes copied. + // LEONIDA_SHARE_CODE_BASE=0, or an empty key, gives the PSO a copy of its own, as before. + struct CodeCopy { + VkDeviceSize offset = 0; + VkDeviceSize bytes = 0; + std::uint64_t users = 0; + }; + std::mutex code_copy_mutex; // taken before arena.mutex + std::unordered_map code_copies; // by the program's SHA-256, guarded by code_copy_mutex + + static bool share_code_copies() { + static const bool share = [] { + wchar_t v[2]{}; + return !(GetEnvironmentVariableW(L"LEONIDA_SHARE_CODE_BASE", v, 2) == 1 && v[0] == L'0'); + }(); + return share; + } + + // Gives `offset` the console VA of a copy of `code`; false when the arena has no room for one. `key` is cleared + // when the copy is the PSO's own; code_copy_release takes the key as this left it. + bool code_copy_acquire(std::string& key, std::span code, VkDeviceSize& offset) { + if (!share_code_copies()) key.clear(); + if (key.empty()) { + if (!arena_allocate(code.size(), 256, offset, arena_shader)) return false; + std::memcpy(arena.mapped + offset, code.data(), code.size()); + return true; + } + std::lock_guard lock(code_copy_mutex); + const auto [it, made] = code_copies.try_emplace(key); + CodeCopy& copy = it->second; + if (made) { + if (!arena_allocate(code.size(), 256, copy.offset, arena_shader)) { + code_copies.erase(it); + return false; + } + std::memcpy(arena.mapped + copy.offset, code.data(), code.size()); + copy.bytes = code.size(); + } + ++copy.users; + offset = copy.offset; + return true; + } + + void code_copy_release(const std::string& key, VkDeviceSize offset, VkDeviceSize bytes) { + if (key.empty()) { + arena_release(offset, bytes, arena_shader); + return; + } + std::lock_guard lock(code_copy_mutex); + const auto it = code_copies.find(key); + if (it == code_copies.end() || --it->second.users) return; + arena_release(it->second.offset, it->second.bytes, arena_shader); + code_copies.erase(it); + } + // Console descriptor heaps (Xbox slot 14, docs/d3d12_vulkan.md section 3.4). The title gives the heap's address // itself: memory of its own, at a console VA the shaders would reach as heap_base + VA, past the arena. It fills // the heap through Create*View and CopyDescriptors, and also by writing 32-byte descriptor records into that @@ -5483,10 +5592,11 @@ struct DeviceState { // entries looked at to find their slots, and the slots fixed again (apply_slot_changes). std::fprintf(stderr, "[rt] d3d12: console descriptor heap 0x%llx slot records per submission: %.1f changes, " - "%.1f slots looked at, %.1f fixed again, %.3f ms; %zu V# halves recorded\n", + "%.1f slots looked at, %.1f fixed again, %.3f ms; %zu V# halves recorded, %zu index " + "buckets\n", static_cast(heap->console_va), double(heap->record_changes) / count, double(heap->record_looked) / count, double(heap->record_refixed) / count, - heap->record_ms / count, heap->records.recorded()); + heap->record_ms / count, heap->records.recorded(), heap->records.buckets()); for (auto& n : heap->changed) n = 0; heap->vsharp_halves = heap->vsharp_repeats = 0; heap->record_changes = heap->record_looked = heap->record_refixed = 0; @@ -5796,6 +5906,9 @@ struct DeviceState { std::unique_ptr heap_gpu; std::array gpu_heaps{}; // console_heap_mutex std::vector> released_ranges; // (shader VA, bytes); backing_mutex + // Whether the pass runs: only it takes released_ranges and the alias table's removals (console_heap_gpu_begin). + // LEONIDA_SHADOW_GPU=1 alone makes heap_gpu for the shadows' page copies, and a range kept for it is never taken. + bool heap_pass_enabled() const { return heap_gpu && console_heap_gpu_enabled(); } struct GpuKeyHash { std::size_t operator()(const leonida::ConsoleHeapKeys::Key& k) const { return leonida::ConsoleHeapKeys::hash(k); @@ -6088,7 +6201,8 @@ struct DeviceState { } heap_gpu = std::move(gpu); heap_gpu->set_signed_offsets(signed_vsharp_offsets()); - leonida::title_va_aliases().record_removals(true); + // Only the pass takes what the alias table records (heap_pass_enabled). + if (console_heap_gpu_enabled()) leonida::title_va_aliases().record_removals(true); context->set_prelude([this](VkCommandBuffer cb) { return heap_gpu->record(cb); }, [this](bool submitted, std::uint64_t ticket) { heap_gpu->commit(submitted, ticket); }); gpu_resolver = std::make_unique(); @@ -7726,7 +7840,14 @@ struct DeviceState { std::unordered_map pending_image_keys; using ZeroShape = std::tuple; std::mutex zero_image_mutex; - std::map zero_images; + std::map zero_images; // null: past the 256 MiB the shared images may take + // Shapes whose image could not be made, with when to try again and how long they waited last + // (zero_sampled_image). Under zero_image_mutex. + struct ZeroImageRetry { + std::chrono::steady_clock::time_point at; + std::chrono::steady_clock::duration delay; + }; + std::map zero_image_retry; std::atomic zero_image_bytes{0}; VkImage zero_sampled_image(const D3D12_RESOURCE_DESC&, const Format&, VkDeviceSize); std::multimap image_keys; // by the texture's address @@ -10758,13 +10879,31 @@ VkImage DeviceState::zero_sampled_image(const D3D12_RESOURCE_DESC& d, const Form const ZeroShape key{d.Format, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels}; std::lock_guard lock(zero_image_mutex); if (auto it = zero_images.find(key); it != zero_images.end()) return it->second ? it->second->image() : VK_NULL_HANDLE; + // A shape whose image could not be made is tried again later. Under VRAM pressure create_texture fails, or its + // image loses host-transfer usage: a shape left without an image for good would have every later placement of it + // take memory of its own for the rest of the session, and one tried at every placement would make an image and ask + // for its memory each time. The wait is a second and doubles at each failure, up to 64 s, so a shape that fails + // every time (where the driver allows no memory type for host-transfer images, that usage is dropped at every try) + // is tried about once a minute, not once a second. + const auto now = std::chrono::steady_clock::now(); + const auto retry = zero_image_retry.find(key); + if (retry != zero_image_retry.end() && now < retry->second.at) return VK_NULL_HANDLE; constexpr VkDeviceSize limit = 256ull << 20; const auto used = zero_image_bytes.load(std::memory_order_relaxed); if (used >= limit || bytes > limit - used) return VK_NULL_HANDLE; const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_CUSTOM, D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0, 1, 1}; auto* zero = new Resource(*this, d, heap, D3D12_HEAP_FLAG_NONE); - if (FAILED(zero->create_texture(format)) || (copy_memory_to_image && !zero->host_initialized_image()) || - zero->image_backing_bytes() > limit - used) { + if (FAILED(zero->create_texture(format)) || (copy_memory_to_image && !zero->host_initialized_image())) { + zero->Release(); + constexpr std::chrono::steady_clock::duration first = std::chrono::seconds(1), + longest = std::chrono::seconds(64); + const auto delay = retry != zero_image_retry.end() ? std::min(retry->second.delay * 2, longest) : first; + zero_image_retry[key] = {now + delay, delay}; + return VK_NULL_HANDLE; + } + if (retry != zero_image_retry.end()) zero_image_retry.erase(retry); + // The shared images are never released, so a shape past the limit stays past it. + if (zero->image_backing_bytes() > limit - used) { zero->Release(); zero_images.emplace(key, nullptr); return VK_NULL_HANDLE; @@ -12006,7 +12145,7 @@ class PipelineState final for (const auto& [unbound, built] : variants_) vk.vkDestroyPipeline(dev, built, nullptr); if (graphics_.layout) vk.vkDestroyPipelineLayout(dev, graphics_.layout, nullptr); modules_.clear(); - if (code_bytes_) device_.arena_release(code_base_, code_bytes_, DeviceState::arena_shader); + if (code_bytes_) device_.code_copy_release(code_key_, code_base_, code_bytes_); --live_pipeline_state_count; } @@ -12167,6 +12306,12 @@ class PipelineState final const std::vector& subgroup_requests() const { return native_owner_ ? native_owner_->subgroup_requests() : subgroup_requests_; } + // The program copy its shaders read their code base from: the console VA replay pushes, and its bytes (0: none). + std::uint64_t code_copy_va() const { + if (native_owner_) return native_owner_->code_copy_va(); + return is_graphics_ ? graphics_.code_base : pipeline_.code_base; + } + VkDeviceSize code_copy_bytes() const { return native_owner_ ? native_owner_->code_copy_bytes() : code_bytes_; } // A VS (+ GS) (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the // VS's input signature by semantic name and index: location = the element's register, the translator's rule @@ -13058,9 +13203,11 @@ class PipelineState final graphics_.estimate = leonida::large_module_estimate(spirv_bytes); if (code_stage) { + // One copy per program, shared with the other PSOs of it (DeviceState::code_copy_acquire): the entry's + // key is the SHA-256 of these bytes, which the lookup above matched. + code_key_ = code_stage->entry->fssm_sha256; VkDeviceSize offset = 0; - if (!device_.arena_allocate(code_stage->fssm.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY; - std::memcpy(device_.arena.mapped + offset, code_stage->fssm.data(), code_stage->fssm.size()); + if (!device_.code_copy_acquire(code_key_, code_stage->fssm, offset)) return E_OUTOFMEMORY; code_bytes_ = code_stage->fssm.size(); code_base_ = offset; graphics_.code_base = offset; @@ -13231,8 +13378,11 @@ class PipelineState final // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). if (entry->uses_code_base || !entry->code_base_known) { const auto& code = program.bytes; - if (!device_.arena_allocate(code.size(), 256, code_base_, DeviceState::arena_shader)) return E_OUTOFMEMORY; - std::memcpy(device_.arena.mapped + code_base_, code.data(), code.size()); + // One copy per program, shared with the other PSOs of it (DeviceState::code_copy_acquire): the entry's + // key is the SHA-256 of these bytes, which program_candidates matched. + code_key_ = program.kind == leonida::ComputeProgram::Kind::fssm ? entry->fssm_sha256 + : entry->fspx_code_sha256; + if (!device_.code_copy_acquire(code_key_, code, code_base_)) return E_OUTOFMEMORY; code_bytes_ = code.size(); pipeline_.code_base = code_base_; } @@ -13912,6 +14062,7 @@ class PipelineState final } VkDeviceSize code_base_ = 0; VkDeviceSize code_bytes_ = 0; + std::string code_key_; // the program's key in DeviceState::code_copies; empty when the copy is this PSO's own bool registered_ = false; bool unregistered_ = false; // taken out of the context's registry (unregister) bool is_graphics_ = false; @@ -14432,6 +14583,12 @@ struct TitleTexture { device_local = (r->memory_flags() & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; } bool owned = false; // made here for slot-70 views (a reference is held); else slot 133's + // Owned, for its retirement (Device::retire_idle_owned_images): when a slot-70 view last named it, whether a + // texture made or registered since then covers some of its bytes, and since when no page of it has been committed + // (time_point{}: some were at the last look after a map change, or a view has named it since). + std::chrono::steady_clock::time_point named{}; + bool superseded = false; + std::chrono::steady_clock::time_point gone_since{}; bool attachment_4k = false; // slot 133: 3840x2160 color or depth attachment bool gpu_written = false; // render target, depth or unordered access: never filled bool mapped = false; // a slot-133 texture the title mapped: checked before submissions @@ -14564,8 +14721,15 @@ void DeviceState::drain_titles_gone() { if (!titles_gone_pending.load(std::memory_order_acquire)) return; std::lock_guard lock(title_texture_mutex); for (const auto& [resource, address] : titles_gone) { + // As title_texture_gone outside the registry: LEONIDA_TEXTURE_REFRESH_ASYNC's range index and mapped list + // name the entry too. A texture made at the address since has a resource and keeps all three. const auto it = title_textures.find(address); - if (it != title_textures.end() && !it->second->resource) title_textures.erase(it); + if (it != title_textures.end() && !it->second->resource) { + texture_ranges.erase(address); + title_textures.erase(it); + } + const auto mapped = mapped_title_textures.find(address); + if (mapped != mapped_title_textures.end() && !mapped->second->resource) mapped_title_textures.erase(mapped); } titles_gone.clear(); titles_gone_pending.store(false, std::memory_order_release); @@ -16143,6 +16307,7 @@ class Device final state_.context->observe_result(state_.context->vk.vkDeviceWaitIdle(state_.info.device), "vkDeviceWaitIdle"); } + release_title_images(); // their Vulkan objects go to the deferred queue drained next state_.context->drain_deleted_resources(UINT64_MAX); state_.context->set_pipeline_workers(nullptr); // before the pipeline cache is written and destroyed state_.context->set_bindless_release(nullptr, nullptr); @@ -16151,6 +16316,10 @@ class Device final if (state_.context) { if (state_.gpu_resolver) state_.gpu_resolver->halt(); // it calls into the geometry copies ShadowPages::gpu_copy = nullptr; + // The console heap pass's pipeline and buffers (LEONIDA_CONSOLE_HEAP_GPU, LEONIDA_SHADOW_GPU) are the + // VkDevice's, and a device that owns its VkDevice destroys it below, before ~DeviceState: they go now. + state_.context->set_prelude(nullptr, nullptr); + state_.heap_gpu.reset(); state_.geometry.release(state_); state_.external_windows.release(state_); std::lock_guard upload(state_.title_upload_mutex); @@ -16475,6 +16644,14 @@ class Device final state_.index_texture(*entry); slot = std::move(entry); ++title_stats_.registered; + if (owned_image_retirement_on()) { + forget_owned_range(address); + // What it covers is known from the title's XG computer of its shape. A texture the GPU writes has no + // layout here, and a guessed one (Layout 0 of the description) may be larger than what the title + // placed, over its neighbours: those cover what a slot-70 view gives them (place_title_view). + if (slot->layout_from_xg && !slot->gpu_written) + supersede_owned_images(address, slot->cpu, slot->layout.layout.size); + } } } @@ -16628,16 +16805,32 @@ class Device final // journal lost some changes, all are probed again, for whatever no change reports. constexpr auto kRetryAll = std::chrono::seconds(30); title_map_changes_.clear(); + owned_map_changes_.clear(); + const bool retire = owned_image_retirement_on(); std::uint64_t map_now = 0; bool map_all = !leonida::title_memory_map::changes_since( - title_map_generation_, map_now, 0, UINTPTR_MAX, - [&](std::uintptr_t from, std::uintptr_t to) { title_map_changes_.emplace_back(from, to); }); + title_map_generation_, map_now, 0, UINTPTR_MAX, [&](std::uintptr_t from, std::uintptr_t to) { + title_map_changes_.emplace_back(from, to); + // A change anywhere (title_memory_map::changed() with no range) says that something changed, not + // where: xmem records one for each run of pages it commits for a DirectStorage transfer on Windows. + // It names no owned image's pages. Taken for all of them, it would have nearly every pass of a + // streaming load look at the pages of every image. + if (retire && (from || to != UINTPTR_MAX)) owned_map_changes_.emplace_back(from, to); + }); title_map_generation_ = map_now; if (now - title_retry_all_ >= kRetryAll) map_all = true; if (map_all) title_retry_all_ = now; leonida::merge_title_writes(title_map_changes_); stats.map_ranges += title_map_changes_.size(); stats.map_all += map_all; + // The owned images over these changes may have lost their pages (retire_idle_owned_images looks). Changes the + // journal lost, and changes anywhere, are not looked for: such an image goes with the next change over its + // pages or a texture over its bytes. + if (retire) { + leonida::merge_title_writes(owned_map_changes_); + for (const auto& [from, to] : owned_map_changes_) + owned_ranges_.overlapping(from, to, [&](std::uint64_t key) { retire_candidates_[key] = true; }); + } if (!written.empty() || overflow || map_all || !title_map_changes_.empty()) { stats.written_ranges += written.size(); leonida::merge_title_writes(written); @@ -16666,7 +16859,10 @@ class Device final const auto apply = [&](const auto& ranges, bool write) { for (const auto& [from, to] : ranges) state_.texture_ranges.overlapping(from, to, [&](auto key) { - auto& t = *state_.title_textures.at(key); + // A key without an entry is skipped: an exception here would end the process. + const auto it = state_.title_textures.find(key); + if (it == state_.title_textures.end()) return; + auto& t = *it->second; invalidate(t, write, !write); if (t.stale) queue_title_fill(key); }); @@ -16744,6 +16940,7 @@ class Device final stats.hashed += checked; stats.filled_bytes += filled; stats.max_pass_bytes = std::max(stats.max_pass_bytes, filled); + if (!retire_candidates_.empty()) retire_idle_owned_images(now); std::vector release; std::erase_if(retired_title_textures_, [&](const auto& r) { if (now - r.first < std::chrono::seconds(3)) return false; // descriptors may still be in flight @@ -16772,6 +16969,36 @@ class Device final for (Resource* r : release) r->Release(); } + // For tests (rt::d3d12::owned_title_images, owned_title_image). + OwnedTitleImages owned_title_images() { + std::lock_guard lock(state_.title_texture_mutex); + OwnedTitleImages out; + for (const auto& [address, t] : state_.title_textures) { + if (!t->resource) continue; + if (!t->owned) { + ++out.slot133; + continue; + } + ++out.owned; + out.owned_bytes += t->resource->image_backing_bytes(); + } + out.retired = title_stats_.retired; + out.superseded = title_stats_.retired_superseded; + out.gone = title_stats_.retired_gone; + out.waiting = retired_title_textures_.size(); + out.candidates = retire_candidates_.size(); + out.looks = title_stats_.retire_looks; + out.named_again = title_stats_.superseded_named; + return out; + } + ID3D12Resource* owned_title_image(std::uint64_t address) { + std::lock_guard lock(state_.title_texture_mutex); + const auto it = state_.title_textures.find(address); + if (it == state_.title_textures.end() || !it->second->owned || !it->second->resource) return nullptr; + it->second->resource->AddRef(); + return it->second->resource; + } + private: struct TitleTextureStats { std::uint64_t mapped_checks = 0, mapped_changed = 0, mapped_fills = 0; @@ -16780,6 +17007,9 @@ class Device final std::map refused; // why a view is a null view -> views std::uint64_t views = 0, null_views = 0, of_slot133 = 0, of_cache = 0, made = 0, retired = 0, registered = 0, refusals = 0, written_ranges = 0, unmaps = 0, unreadable = 0, pending_views = 0; + // Of the retired: under a newer texture, with their pages gone (retire_idle_owned_images). Looks at the pages + // of owned images there; owned images a view named again after a newer texture covered them. + std::uint64_t retired_superseded = 0, retired_gone = 0, retire_looks = 0, superseded_named = 0; std::uint64_t fills = 0, fill_bytes = 0, fill_failures = 0; // Fills of some mips only; textures whose first fill was one; those that got larger mips later; first fills // refused by LEONIDA_TITLE_PARTIAL_MIPS_MB. @@ -17058,6 +17288,12 @@ class Device final VkDeviceSize retired_backing_ = 0; VkDeviceSize title_partial_bytes_ = 0; // likewise: image memory of the textures filled in part, as of this pass std::vector> retired_title_textures_; // likewise + // LEONIDA_TITLE_IMAGE_RETIRE, likewise: the owned images by the CPU bytes they are filled from, and those that may + // be retired (a newer texture covers them, or their pages may have gone: true until a pass has looked at them). + leonida::TitleTextureRangeIndex owned_ranges_; + std::map retire_candidates_; + std::uint64_t retire_cursor_ = 0; // the candidate the next pass starts from + leonida::TitleWriteRanges owned_map_changes_; // scratch: this pass's map changes with a range std::vector title_tiled_, title_linear_; // scratch, under title_texture_mutex std::vector title_columns_; @@ -17152,6 +17388,7 @@ class Device final state_.index_texture(*t); t->layout_guessed = t->layout_from_xg = false; t->hashed = false; + if (owned_image_retirement_on()) supersede_owned_images(address, t->cpu, t->layout.layout.size); } else { refuse_title_view(why, d, address); // counted; the view of its image is still written } @@ -17169,10 +17406,16 @@ class Device final }(); retire_title_texture(*t); state_.texture_ranges.erase(address); + forget_owned_range(address); textures.erase(address); t = make_title_texture(d, words, srv, address, view_mip, same_shape ? formats : std::vector{}); } else if (t) { ++title_stats_.of_cache; + // Named again: in use, whatever covers its bytes now, and a view of a texture whose pages may come back. + title_stats_.superseded_named += t->superseded; + t->named = std::chrono::steady_clock::now(); + t->superseded = false; + t->gone_since = {}; if (t->view_mip != view_mip) { t->view_mip = view_mip; if (!t->fills) t->memory.retry(); // what is readable may do for this view @@ -17253,6 +17496,11 @@ class Device final log_once("an image for a slot-70 texture view could not be made; HRESULT", int(hr)); return refuse_title_view("image not created", d, address), nullptr; } + // The registry's reference keeps the image and the device keeps the registry, so the image holds no device + // reference: with one, a device its title (or a test) released stayed alive, with all its Vulkan objects, + // while an image made here was in the registry or retired and not yet released (3 s on, at a refresh pass a + // released device never runs). ~Device releases what is left (release_title_images). + r->attach_device(nullptr); if (!title_layout_fits(entry->layout, d, *r, why)) { r->Release(); return refuse_title_view(why, d, address), nullptr; @@ -17275,8 +17523,13 @@ class Device final } ++title_stats_.made; TitleTexture* t = entry.get(); + t->named = std::chrono::steady_clock::now(); state_.index_texture(*entry); state_.title_textures[address] = std::move(entry); + if (owned_image_retirement_on()) { + owned_ranges_.set(address, t->cpu, t->layout.layout.size); + supersede_owned_images(address, t->cpu, t->layout.layout.size); + } if (title_fill_async() && readable) queue_title_fill(address); return t; } @@ -17292,6 +17545,130 @@ class Device final ++title_stats_.retired; } + // Device teardown, after the GPU is idle: the last release of the images made for slot-70 views, those in the + // registry and those retired. Each destructor reaches the device state, so this comes before the context goes. + void release_title_images() { + std::vector release; + { + std::lock_guard lock(state_.title_texture_mutex); + for (auto& [address, t] : state_.title_textures) + if (t && t->owned && t->resource) release.push_back(std::exchange(t->resource, nullptr)); + for (const auto& [when, r] : retired_title_textures_) release.push_back(r); + retired_title_textures_.clear(); + retired_backing_ = 0; + } + for (Resource* r : release) r->Release(); + } + + // LEONIDA_TITLE_IMAGE_RETIRE=1 (off by default). An image made for slot-70 views was retired only when + // its own address got another description or a slot-133 texture, and a title that streams places its textures at + // ever new addresses: each kept its image (in VRAM, then in system memory), its bindless index and its turn in the + // refresh passes for the device's life. Now one is also retired once a texture made or registered after the last + // view of it covers some of its bytes, or once no page of it has been committed for a while, when no slot-70 view + // has named it for LEONIDA_TITLE_IMAGE_IDLE_MS (2000 by default): the bytes now hold another texture, or nothing, + // as they would for its T# on the console. Two textures over the same bytes that views keep naming both stay. + // A slot-133 texture covers with its XG layout, or with the one a slot-70 view gives it, never with the guess from + // its description. Its pages are looked at after a title_memory_map change over them, not after a change anywhere. + // A view that names an image whose pages went keeps it, until a later change over them finds them still gone. + // A view of a retired image's address makes it again (place_title_view): its T# names the title address + // (Resource::place_at_title_address), so the copies of its descriptors the title kept find the new image once it + // is filled. Until then, and for a T# whose address no view names again, a shader samples the fallback. + static bool owned_image_retirement_on() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_TITLE_IMAGE_RETIRE"); + return v && *v && std::strcmp(v, "0") != 0; + }(); + return on; + } + static std::chrono::milliseconds owned_image_idle() { + static const std::chrono::milliseconds idle([] { + const char* v = std::getenv("LEONIDA_TITLE_IMAGE_IDLE_MS"); + return v && *v ? (std::max)(0ll, std::strtoll(v, nullptr, 10)) : 2000ll; + }()); + return idle; + } + static std::size_t owned_image_checks() { + static const std::size_t checks = [] { + const char* v = std::getenv("LEONIDA_TITLE_IMAGE_CHECKS"); + return v && *v ? std::size_t(std::strtoull(v, nullptr, 10)) : std::size_t(128); + }(); + return checks; + } + + // A texture at `key` now holds the title's bytes [cpu, cpu + size): the owned images at other keys over some of + // them are superseded. One over exactly these bytes is the same texture named through the other view of a + // stream pool (title_gpu_views::other_view), or the same bytes in another shape, and is left alone. + void supersede_owned_images(std::uint64_t key, std::uint64_t cpu, std::uint64_t size) { + if (!size) return; + owned_ranges_.overlapping(cpu, cpu + size, [&](std::uint64_t other) { + const auto it = state_.title_textures.find(other); + if (other == key || it == state_.title_textures.end() || !it->second->owned || !it->second->resource) + return; + TitleTexture& t = *it->second; + if (t.cpu == cpu && t.layout.layout.size == size) return; + t.superseded = true; + retire_candidates_.try_emplace(other, false); + }); + } + + // The registry no longer holds an owned image at `key` (retired, or replaced by another texture). + void forget_owned_range(std::uint64_t key) { + owned_ranges_.erase(key); + retire_candidates_.erase(key); + } + + // Once a pass, after its visits: the candidates of LEONIDA_TITLE_IMAGE_RETIRE. One over a map change since the + // last pass is looked at first (a filled image none of whose pages is committed has gone; an image never filled + // is the view of a texture whose pages have not come yet, and stays). A superseded image goes once no view has + // named it for the idle time, one whose pages went once they have been gone that long; the others stay + // candidates. Its Release waits as every retired image's does (retired_title_textures_). + // A pass visits at most LEONIDA_TITLE_IMAGE_CHECKS of them (128 by default; 0: all), from where the last pass + // stopped. A look walks the pages with VirtualQuery, about a microsecond a call, and this runs under the registry + // lock on the title's submitting thread: a change over a large unloaded pool marks tens of thousands of images at + // once, and they are looked at over the following passes, a candidate not reached keeping its mark. + void retire_idle_owned_images(std::chrono::steady_clock::time_point now) { + const auto idle = owned_image_idle(); + const std::size_t limit = owned_image_checks(); + std::size_t visits = limit ? std::min(limit, retire_candidates_.size()) : retire_candidates_.size(); + auto it = retire_candidates_.lower_bound(retire_cursor_); + for (; visits; --visits) { + if (it == retire_candidates_.end()) it = retire_candidates_.begin(); + const std::uint64_t key = it->first; + const auto entry = state_.title_textures.find(key); + TitleTexture* t = entry == state_.title_textures.end() || !entry->second->owned || !entry->second->resource + ? nullptr + : entry->second.get(); + if (t && std::exchange(it->second, false)) { + bool committed = !t->fills; + if (!committed) { + ++title_stats_.retire_looks; + committed = leonida::texture_memory_committed(std::uintptr_t(t->cpu), t->layout.layout.size); + } + if (committed) + t->gone_since = {}; + else if (t->gone_since == std::chrono::steady_clock::time_point{}) + t->gone_since = now; + } + const bool gone = t && t->gone_since != std::chrono::steady_clock::time_point{}; + if (!t || (!t->superseded && !gone)) { + it = retire_candidates_.erase(it); + continue; + } + const bool covered = t->superseded && now - t->named >= idle; + if (!covered && !(gone && now - t->gone_since >= idle)) { + ++it; + continue; + } + ++(covered ? title_stats_.retired_superseded : title_stats_.retired_gone); + retire_title_texture(*t); + it = retire_candidates_.erase(it); + owned_ranges_.erase(key); + state_.texture_ranges.erase(key); + state_.title_textures.erase(entry); + } + retire_cursor_ = it == retire_candidates_.end() ? 0 : it->first; + } + // LEONIDA_TITLE_PARTIAL_MIPS=1 (off by default). A slot-70 2D texture whose larger mips are not readable is filled from the // first mip that is, with every smaller one, when its last view starts there or later. The T#s of views that start // above stay on the fallback (PendingImage::first_mip), so no shader samples a mip that was not filled. Larger @@ -17591,14 +17968,17 @@ class Device final double(s.staged_ns) / 1e9, double(state_.title_upload.capacity()) / 1048576.0); std::fprintf(stderr, "[rt] d3d12: title textures (%s): %llu slot-70 texture views (%zu kinds), %llu of slot-133 textures, " - "%llu of images made for them (%llu made, %llu over memory not readable yet, %llu retired), %llu " + "%llu of images made for them (%llu made, %llu over memory not readable yet, %llu retired: %llu " + "under a newer texture, %llu with their pages gone; %llu named again under a newer texture), %llu " "null views; registry %zu images " "(%zu made, %zu slot 133 of %llu registered, %zu mapped, %zu filled); %llu fills %.1f MiB, %llu " "failed\n", when, static_cast(s.views), s.asked.size(), static_cast(s.of_slot133), static_cast(s.of_cache), static_cast(s.made), static_cast(s.unreadable), - static_cast(s.retired), + static_cast(s.retired), static_cast(s.retired_superseded), + static_cast(s.retired_gone), + static_cast(s.superseded_named), static_cast(s.null_views), state_.title_textures.size(), owned, slot133, static_cast(s.registered), mapped, filled, static_cast(s.fills), double(s.fill_bytes) / 1048576.0, @@ -19713,7 +20093,9 @@ class Device final // TitleVaAliases::want_buffer: a vertex or index view names `va` in the title's own memory and no buffer covers // it. A buffer over the 64 KiB-aligned committed pages around it is made the way slot 133 makes one (the pages // imported, or a shadow copied from them before every submission) and kept until the device goes, up to - // LEONIDA_TITLE_BUFFERS_MB (512 by default). + // LEONIDA_TITLE_BUFFERS_MB (512 by default). Only a buffer that covers the view is made and kept. After a range + // got none, no range is tried for a second (title_buffer_retry_), and a range refused again waits twice as long + // as the last time, up to 64 s (refused_title_ranges_). void make_title_buffer(std::uint64_t va, std::uint64_t bytes) { if (!&context()) return; static const bool check_size = [] { @@ -19739,9 +20121,23 @@ class Device final const bool set = getenv_s(&length, text, "LEONIDA_TITLE_BUFFERS_MB") == 0 && length > 1; return (set ? std::strtoull(text, nullptr, 10) : 512ull) << 20; }(); + // The title binds the same views draw after draw, and many views of one pool when its pages are refused. Each + // try asks for an import and a shadow, and their memory, under memory_mutex(), where the title's own + // allocations wait. So after a refusal no range is tried for a second, whichever range it is, and a range + // refused before waits its own time too, which doubles at each refusal: one that keeps failing (its pages + // cannot be imported, and no shadow of its size fits) does not take every second's try from ranges that + // could get a buffer. Both are checked before the page walk below (its VirtualQuery calls), which only + // shortens `asked`. + const auto now = std::chrono::steady_clock::now(); + if (now < title_buffer_retry_) return; constexpr std::uint64_t align = 65536, most = 64ull << 20; const std::uint64_t start = std::max(va & ~(align - 1), lo); - std::uint64_t end = std::min(hi, (va + std::clamp(bytes, 1, most) + align - 1) & ~(align - 1)); + const std::uint64_t asked = + std::min(hi, (va + std::clamp(bytes, 1, most) + align - 1) & ~(align - 1)); + const auto refused = refused_title_ranges_.find(start); + if (refused != refused_title_ranges_.end() && asked <= refused->second.end && now < refused->second.retry) + return; + std::uint64_t end = asked; for (std::uint64_t at = start; at < end;) { // the committed, readable part only MEMORY_BASIC_INFORMATION region{}; if (!VirtualQuery(reinterpret_cast(static_cast(at)), ®ion, sizeof(region)) || @@ -19767,13 +20163,35 @@ class Device final desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; ID3D12Resource* made = nullptr; + // When the pages can be neither imported nor shadowed, slot 133 answers with an ordinary DEFAULT buffer that + // has neither the title's VA nor its bytes. It would not cover the view: kept, it would hold its memory until + // the device goes, and another would be made at the next bind of the same view, until + // LEONIDA_TITLE_BUFFERS_MB is used up. So it is not asked for (the shadow's failure comes back instead), and + // a buffer that still does not cover the view is let go. const HRESULT hr = create_at_host_address(reinterpret_cast(static_cast(start)), desc, 0xFFFFFFFFu, __uuidof(ID3D12Resource), - reinterpret_cast(&made), nullptr); - if (FAILED(hr) || !made) { - log_once("a buffer over the title's memory for a vertex or index view could not be made; HRESULT", int(hr)); + reinterpret_cast(&made), nullptr, false); + const bool kept = SUCCEEDED(hr) && made && state_.context->knows_buffer_va(va, check_size ? end - va : 1); + if (!kept) { + if (SUCCEEDED(hr) && made) + log_once("a buffer over the title's memory for a vertex or index view does not cover it, so it is not " + "kept; KiB", + int((end - start) >> 10)); + else + log_once("a buffer over the title's memory for a vertex or index view could not be made; HRESULT", + int(hr)); + if (made) made->Release(); + constexpr std::chrono::steady_clock::duration first = std::chrono::seconds(1), + longest = std::chrono::seconds(64); + const auto delay = + refused != refused_title_ranges_.end() ? std::min(refused->second.delay * 2, longest) : first; + if (refused_title_ranges_.size() >= 256) + std::erase_if(refused_title_ranges_, [&](const auto& range) { return range.second.retry <= now; }); + refused_title_ranges_[start] = {asked, now + delay, delay}; + title_buffer_retry_ = now + first; return; } + if (refused != refused_title_ranges_.end()) refused_title_ranges_.erase(refused); title_buffers_.push_back(made); title_buffer_bytes_ += end - start; if (title_buffers_.size() <= 8 || !(title_buffers_.size() & (title_buffers_.size() - 1))) @@ -19787,9 +20205,21 @@ class Device final std::mutex title_buffer_mutex_; std::vector title_buffers_; // kept: the title's views name their addresses frame after frame std::uint64_t title_buffer_bytes_ = 0; + // Ranges [start, end) that got no buffer, by start (`end` as asked, before the page walk), with when they may be + // tried again and how long they waited last. Under title_buffer_mutex_; the entries past their time are dropped + // once there are 256. + struct RefusedTitleRange { + std::uint64_t end; + std::chrono::steady_clock::time_point retry; + std::chrono::steady_clock::duration delay; + }; + std::map refused_title_ranges_; + std::chrono::steady_clock::time_point title_buffer_retry_{}; // no range is tried before then (a refusal's second) + // `ordinary_fallback` false: a buffer whose pages can be neither imported nor shadowed fails with the shadow's + // HRESULT instead of being an ordinary DEFAULT buffer (make_title_buffer). HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, - void** out, const D3D12_CLEAR_VALUE* clear) { + void** out, const D3D12_CLEAR_VALUE* clear, bool ordinary_fallback = true) { constexpr auto method = "Xbox CreatePlacedResourceX (device slot 133)"; if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { // A texture cannot be placed on the title's pages (the PC GPU does not sample the console layout): it gets @@ -19909,8 +20339,11 @@ class Device final } // No memory for the shadow either: the boot goes on with an ordinary DEFAULT buffer of the same // description, as #6915's stand-in did. The title gets a resource, but neither its VA nor its writes at - // `address` reach it. + // `address` reach it. make_title_buffer asks for no such buffer: it would not cover the view it is made + // for, and making it would only take device-local memory, under the pressure that refused the shadow, + // to be let go at once. resource->Release(); + if (!ordinary_fallback) return d3d12_trace::result(method, shadow); log_once("a title-placed buffer (device slot 133) could neither import its pages nor get a shadow, so it " "is an ordinary buffer the title's writes do not reach; HRESULT", int(shadow)); @@ -21949,6 +22382,14 @@ bool pipeline_stage_words(ID3D12PipelineState* pipeline, std::vector(pipeline); + if (!p || !p->code_copy_bytes()) return false; + va = p->code_copy_va(); + bytes = p->code_copy_bytes(); + return true; +} + bool write_placed_buffer_view(ID3D12Device* device, bool unordered, const void* view, std::uint64_t address, std::uint64_t width, D3D12_CPU_DESCRIPTOR_HANDLE destination) { Device* d = Device::from(device); @@ -22095,6 +22536,14 @@ TitleWindows title_windows(ID3D12Device* device) { windows.waiting = state.retired_windows.size(); return windows; } +OwnedTitleImages owned_title_images(ID3D12Device* device) { + auto* d = Device::from(device); + return d ? d->owned_title_images() : OwnedTitleImages{}; +} +ID3D12Resource* owned_title_image(ID3D12Device* device, std::uint64_t address) { + auto* d = Device::from(device); + return d ? d->owned_title_image(address) : nullptr; +} std::uint64_t title_shadow_trackers(ID3D12Device* device) { auto* d = Device::from(device); if (!d) return 0; @@ -22117,6 +22566,21 @@ TitleShadowWatch title_shadow_watch(ID3D12Device* device) { } return watch; } +ConsoleHeapGpuPending console_heap_gpu_pending(ID3D12Device* device) { + ConsoleHeapGpuPending pending; + if (!device) return pending; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + auto* d = Device::from(real ? real : device); + if (!d) return pending; + auto& state = d->state(); + pending.made = state.heap_gpu != nullptr; + { + std::lock_guard lock(state.backing_mutex); + pending.released = state.released_ranges.size(); + } + pending.removed = leonida::title_va_aliases().removals_pending(); + return pending; +} HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear) { @@ -22242,6 +22706,16 @@ std::uint64_t device_arena_size(ID3D12Device* device) { return d ? d->state().arena.size : 0; } +std::uint64_t arena_shader_bytes(ID3D12Device* device) { + if (!device) return 0; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + if (!real) real = device; + Device* d = Device::from(real); + if (!d) return 0; + std::lock_guard lock(d->state().arena.mutex); + return d->state().arena.use_in_use[DeviceState::arena_shader]; +} + ImageMemoryStats image_memory_stats(ID3D12Device* device) { if (!device) return {}; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); @@ -24051,6 +24525,35 @@ TitleImage test_bind_title_image(ID3D12Device* device, const std::arraystate(), w, why); } +TitleTextureRegistry title_texture_registry(ID3D12Device* device) { + TitleTextureRegistry registry; + if (!device) return registry; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + Device* d = Device::from(real ? real : device); + if (!d) return registry; + DeviceState& state = d->state(); + std::lock_guard lock(state.title_texture_mutex); + registry.textures = state.title_textures.size(); + registry.ranges = state.texture_ranges.size(); + registry.mapped = state.mapped_title_textures.size(); + return registry; +} + +bool release_in_title_registry(ID3D12Device* device, ID3D12Resource* resource) { + if (!device || !resource) return false; + ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); + Device* d = Device::from(real ? real : device); + if (!d) return false; + DeviceState& state = d->state(); + { + std::lock_guard lock(state.title_texture_mutex); + const InTitleTextures inside; + resource->Release(); + } + state.drain_titles_gone(); + return true; +} + std::uint64_t resource_image_address(ID3D12Resource* resource) { if (!resource) return 0; const Resource* r = Resource::from(resource); diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 26dd5e7f70..dd65ff3036 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -76,6 +76,7 @@ #include #include #include +#include #include #include #include @@ -186,6 +187,10 @@ bool call_presentation(DeviceProxy* self, F&& f) { // Freed in proxy_release; defined where the states are complete. void destroy_present_state(void* present_state); void destroy_upload_state(void* upload_state); +// The upload memory console list slot 148 handed out under an allocator (the real one, as ListProxy::allocator names +// it): rewound at the allocator proxy's Reset and freed with the proxy. Defined with the upload arena. +void upload_allocator_reset(DeviceProxy* device, const void* allocator); +void upload_allocator_gone(DeviceProxy* device, const void* allocator); constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles @@ -1616,7 +1621,12 @@ void destroy_child(ChildProxy* self) { unsigned long release_child_reference(ChildProxy* self) { const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; - if (refs == 0) destroy_child(self); + if (refs == 0) { + // The last reference to an allocator: the upload memory handed out under it goes with it. D3D12 asks the same + // of a release as of a Reset, that the GPU has finished the allocator's lists. + if (self->kind == ChildKind::allocator) upload_allocator_gone(self->device, self->real); + destroy_child(self); + } return refs; } @@ -2788,6 +2798,14 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); auto fn = reinterpret_cast(self->real_vtable[Slot]); + if constexpr (K == ChildKind::allocator && Slot == 8) { + // Reset. D3D12 allows it only once the GPU has finished every list recorded into the allocator, so the + // upload memory handed out under it is free again and upload_allocator_reset rewinds it. A refused Reset + // (the Vulkan layer's while a list still records into the allocator) gives nothing back. + const std::uint64_t result = fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); + if (SUCCEEDED(static_cast(result))) upload_allocator_reset(self->device, self->real); + return result; + } if constexpr (K == ChildKind::fence && Slot == kFenceSignal) { const std::uint64_t result = fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); if (FenceMirror* m = self->mirror.load(std::memory_order_acquire)) refresh_mirror(m); @@ -2918,22 +2936,56 @@ constexpr unsigned kListSlots = 160; // address (the same backing memory) before forwarding. Translation covers the six root VA setters (console // 41-46); VAs inside view structs (IASetVertexBuffers/IASetIndexBuffer) and ExecuteIndirect arguments are not // rewritten yet and stay title addresses. +// +// The memory belongs to the command allocator the list records into, as the list's commands do. Each allocator has +// its own chunks, carved from front to back; its Reset (allocator slot 8), which D3D12 allows only once the GPU has +// finished every list recorded into it, starts them from the front again, and its release frees them. A list's own +// Reset gives nothing back: the allocator's earlier lists may still be pending. The arena used to only advance, so +// for as long as the title ran it grew by one 8 MiB buffer each time the newest was full, in VRAM with Resizable BAR +// and in host memory without. An allocator the device hands out unwrapped (a PC runtime's, see +// resolves_allocator_proxies) never reaches its Reset here: its chunks only advance, as before, until the device goes. +// LEONIDA_UPLOAD_REWIND=0 keeps the one arena all lists share, which only advances, as before. struct UploadChunk { - UploadChunk* next; + UploadChunk* next; // the allocator's next older chunk ID3D12Resource* resource; // the mapped buffer; released with the chunk std::uint8_t* cpu_base; D3D12_GPU_VIRTUAL_ADDRESS gpu_base; std::size_t size; std::size_t used; + unsigned idle_resets; // how many of its allocator's Resets in a row found it unused }; struct UploadArena { - UploadChunk* chunks = nullptr; + // Each allocator's chunks, newest first, by the real allocator (ListProxy::allocator). The null key holds the + // chunks of a list whose allocator is not known and, with LEONIDA_UPLOAD_REWIND=0, every chunk: nothing rewinds it. + std::map owners; + std::map by_cpu; // every chunk by its CPU base, for upload_translate std::mutex lock; }; constexpr std::size_t kUploadChunkMin = 8 << 20; // one chunk serves a title's whole frame of uploads +// A chunk that served nothing for this many Resets of its allocator in a row goes back, so an allocator keeps what its +// recent frames needed rather than the most they ever did. More than one, so that a load which comes and goes every +// other frame does not make and free a buffer each time. +constexpr unsigned kUploadIdleResets = 8; + +inline bool upload_rewind() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_UPLOAD_REWIND"); + return !(v && v[0] == '0' && v[1] == '\0'); + }(); + return on; +} + +// LEONIDA_UPLOAD_ALIAS=1 (experiment): see upload_chunk_new. +inline bool upload_alias() { + static const bool on = [] { + const char* v = std::getenv("LEONIDA_UPLOAD_ALIAS"); + return v && *v == '1'; + }(); + return on; +} // LEONIDA_UPLOAD_LOG=1 (diagnostic): each upload chunk (its CPU base, device address and size), and the first 96 and // then every 8192nd AllocateUploadMemory result as an offset into its chunk, so the addresses the title builds @@ -2991,11 +3043,7 @@ UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { // the title VA table, the chunk's CPU range answers with the chunk's console VA (its device address minus // heap_base), so a V# the title wrote with such a pointer is rewritten to the chunk instead of left empty. A // chunk below the arena has a negative console VA, usable in a V# only with LEONIDA_IMPORT_BELOW_ARENA=1. - static const bool alias = [] { - const char* v = std::getenv("LEONIDA_UPLOAD_ALIAS"); - return v && *v == '1'; - }(); - if (alias) { + if (upload_alias()) { const bool added = leonida::title_va_aliases().add(reinterpret_cast(chunk->cpu_base), chunk->size, chunk->gpu_base); std::fprintf(stderr, "[rt] d3d12_xs: upload chunk 0x%llx (%llu bytes) entered as an alias of console VA " @@ -3020,7 +3068,34 @@ UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { return chunk; } -std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_t alignment) { +// Unmaps and releases (or frees) a chunk that is out of its arena, so that no list is handed it again. +void upload_chunk_free(UploadChunk* chunk) { + if (chunk->resource) { + if (upload_alias()) + leonida::title_va_aliases().remove(reinterpret_cast(chunk->cpu_base), chunk->gpu_base); + chunk->resource->Unmap(0, nullptr); + chunk->resource->Release(); + } else { + VirtualFree(chunk->cpu_base, 0, MEM_RELEASE); + } + delete chunk; +} + +// Frees a list of chunks (linked by `next`) taken out of their arena; `why` names the reason in the upload log. +void upload_chunks_free(UploadChunk* chunk, const char* why) { + while (chunk) { + UploadChunk* next = chunk->next; + if (upload_log()) + std::fprintf(stderr, "[rt] upload-log: chunk at 0x%llx, %llu bytes, given back (%s)\n", + static_cast(reinterpret_cast(chunk->cpu_base)), + static_cast(chunk->size), why); + upload_chunk_free(chunk); + chunk = next; + } +} + +// `allocator` is the real allocator the list records into (ListProxy::allocator), the owner of what it hands out. +std::uint64_t upload_alloc(DeviceProxy* device, const void* allocator, std::uint64_t size, std::uint64_t alignment) { if (!device || !size) return 0; alignment = alignment < 16 ? 16 : alignment; // every measured call asked for 16 // Refuse what cannot be served before any arithmetic runs: only power-of-two alignments are measured, @@ -3045,9 +3120,11 @@ std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_ arena = static_cast(expected); } } + const void* const owner = upload_rewind() ? allocator : nullptr; std::lock_guard lock(arena->lock); const std::size_t need = static_cast(size); - for (UploadChunk* chunk = arena->chunks; chunk; chunk = chunk->next) { + const auto owned = arena->owners.find(owner); + for (UploadChunk* chunk = owned != arena->owners.end() ? owned->second : nullptr; chunk; chunk = chunk->next) { const std::size_t aligned = (chunk->used + (alignment - 1)) & ~(static_cast(alignment) - 1); if (aligned >= chunk->used && aligned <= chunk->size && need <= chunk->size - aligned) { chunk->used = aligned + need; @@ -3058,13 +3135,22 @@ std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_ } const std::size_t chunk_size = need + alignment > kUploadChunkMin ? need + alignment : kUploadChunkMin; UploadChunk* chunk = upload_chunk_new(device, chunk_size); + if (chunk) { + try { + UploadChunk*& newest = arena->owners[owner]; + arena->by_cpu.emplace(reinterpret_cast(chunk->cpu_base), chunk); + chunk->next = newest; + newest = chunk; + } catch (const std::bad_alloc&) { // no exception may leave a thunk for the title's code + upload_chunk_free(chunk); + chunk = nullptr; + } + } if (!chunk) { std::fprintf(stderr, "[rt] d3d12_xs: AllocateUploadMemory(%llu, %llu) failed\n", static_cast(size), static_cast(alignment)); return 0; } - chunk->next = arena->chunks; - arena->chunks = chunk; const std::size_t aligned = (alignment - 1) & ~(static_cast(alignment) - 1); // 0-based chunk->used = aligned + need; if (upload_log()) @@ -3078,36 +3164,70 @@ std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_ } // An address inside an upload chunk becomes the chunk's device address plus the offset; anything else โ€” a -// real resource VA the title already holds โ€” passes through. +// real resource VA the title already holds โ€” passes through. Every root CBV/SRV/UAV and IA/SO view asks, so the +// chunk is found by its CPU base rather than by walking them all. std::uint64_t upload_translate(DeviceProxy* device, std::uint64_t va) { auto* arena = static_cast( device ? device->upload_state.load(std::memory_order_acquire) : nullptr); if (!arena) return va; std::lock_guard lock(arena->lock); - for (UploadChunk* chunk = arena->chunks; chunk; chunk = chunk->next) { - const std::uint64_t base = reinterpret_cast(chunk->cpu_base); - if (va >= base && va < base + chunk->size) return chunk->gpu_base + (va - base); + auto above = arena->by_cpu.upper_bound(va); // the first chunk starting past va + if (above == arena->by_cpu.begin()) return va; + const auto& [base, chunk] = *--above; + return va - base < chunk->size ? chunk->gpu_base + (va - base) : va; +} + +// The allocator proxy's Reset succeeded: the GPU is done with every list recorded into `allocator`, so its chunks are +// carved from the front again. One that served nothing for kUploadIdleResets of these in a row is given back. +void upload_allocator_reset(DeviceProxy* device, const void* allocator) { + auto* arena = static_cast( + device ? device->upload_state.load(std::memory_order_acquire) : nullptr); + if (!arena || !allocator) return; + UploadChunk* idle = nullptr; // taken out under the lock, freed after it + { + std::lock_guard lock(arena->lock); + const auto owned = arena->owners.find(allocator); + if (owned == arena->owners.end()) return; + UploadChunk** link = &owned->second; + while (UploadChunk* chunk = *link) { + chunk->idle_resets = chunk->used ? 0 : chunk->idle_resets + 1; + chunk->used = 0; + if (chunk->idle_resets < kUploadIdleResets) { + link = &chunk->next; + continue; + } + *link = chunk->next; + arena->by_cpu.erase(reinterpret_cast(chunk->cpu_base)); + chunk->next = idle; + idle = chunk; + } + if (!owned->second) arena->owners.erase(owned); } - return va; + upload_chunks_free(idle, "idle at its allocator's Resets"); +} + +// The allocator proxy's last reference went: its chunks go with it. +void upload_allocator_gone(DeviceProxy* device, const void* allocator) { + auto* arena = static_cast( + device ? device->upload_state.load(std::memory_order_acquire) : nullptr); + if (!arena || !allocator) return; + UploadChunk* gone = nullptr; + { + std::lock_guard lock(arena->lock); + const auto owned = arena->owners.find(allocator); + if (owned == arena->owners.end()) return; + gone = owned->second; + for (const UploadChunk* chunk = gone; chunk; chunk = chunk->next) + arena->by_cpu.erase(reinterpret_cast(chunk->cpu_base)); + arena->owners.erase(owned); + } + upload_chunks_free(gone, "its allocator was released"); } void destroy_upload_state(void* upload_state) { auto* arena = static_cast(upload_state); if (!arena) return; - for (UploadChunk* chunk = arena->chunks; chunk;) { - UploadChunk* next = chunk->next; - if (chunk->resource) { - const char* alias = std::getenv("LEONIDA_UPLOAD_ALIAS"); - if (alias && *alias == '1') - leonida::title_va_aliases().remove(reinterpret_cast(chunk->cpu_base), chunk->gpu_base); - chunk->resource->Unmap(0, nullptr); - chunk->resource->Release(); - } else { - VirtualFree(chunk->cpu_base, 0, MEM_RELEASE); - } - delete chunk; - chunk = next; - } + for (const auto& entry : arena->by_cpu) upload_chunk_free(entry.second); delete arena; } @@ -3376,17 +3496,30 @@ void note_list_state(ListProxy* self, std::uint64_t a1, std::uint64_t a2, std::u (void)self, (void)a1, (void)a2, (void)a3, (void)a4; } +// A closed real list of the last recording becomes a spare. Nothing executes it again before a cut resets it: a +// submission names the proxy's parts and `real`, and the title's Reset ended the recording they were. So it drops +// that recording now: an idle spare would otherwise keep its commands and the pipeline states, root signatures and +// scratch they hold, and its command-list epoch would hold back every title window retired after that recording +// began (src/command_list_epochs.h) until a cut reset it, which never comes for a spare past the cuts later +// recordings make (cut_list takes the newest spare first). +void keep_spare(ListProxy* self, ID3D12GraphicsCommandList* list) { +#ifdef LEONIDA_VULKAN_DEVICE + rt::d3d12::drop_recording(list); +#endif + self->spares.push_back(list); +} + // A new recording (Reset): the primary list records again; the other real lists of the last recording are closed and // wait with the spares for later cuts. void restart_recording(ListProxy* self) { for (const ListProxy::Part& part : self->parts) - if (part.list != self->primary) self->spares.push_back(part.list); + if (part.list != self->primary) keep_spare(self, part.list); self->parts.clear(); if (self->real != self->primary) { // A title resets a list it closed; one still open (a D3D12 error, which the real Reset reports) is closed // here so that a later cut can Reset it. if (!self->real_closed) self->real->Close(); - self->spares.push_back(self->real); + keep_spare(self, self->real); self->real = self->primary; } self->pre_writes.clear(); @@ -3699,7 +3832,8 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t } #endif if constexpr (Slot == kConsoleAllocateUpload) { - return upload_alloc(self->device, a1, a2); // (size, alignment); the comment at UploadChunk + // (size, alignment), under the allocator the list records into; the comment at UploadChunk + return upload_alloc(self->device, self->allocator, a1, a2); } if constexpr (Slot >= 69 && Slot <= 74) { // memory writes and waits, by the layout (console_value_op) const ConsoleValueOp op = console_value_op(Slot, layout); diff --git a/runtime/shims/d3d12_xs_pso_stream.cpp b/runtime/shims/d3d12_xs_pso_stream.cpp index 34a5d9f0a8..01eb1c9166 100644 --- a/runtime/shims/d3d12_xs_pso_stream.cpp +++ b/runtime/shims/d3d12_xs_pso_stream.cpp @@ -3,9 +3,12 @@ #include "../src/shader_library.h" +#include #include #include #include +#include +#include namespace rt::d3d12_xs { namespace { @@ -112,6 +115,68 @@ const unsigned char* own_blob(std::vector>& blobs, co return blobs.back().data(); } +// Shader bytecode kept once per content for every record in the process. The title makes some 50 000 slot 86 calls +// in its first boot from about 26 500 shaders (docs/embedded_shaders.md; the carved containers average 9.6 KB), so a +// copy of each stage per record kept most containers many times over. A record holds a reference to the shared +// bytes and the table holds weak references only, so a container is freed with the last record that uses it. The +// bytes are never written after they are copied, so every stream that points at them reads what its own source held. +class ShaderTable { +public: + using ShaderData = PsoStreamRecord::ShaderData; + + ShaderData acquire(const void* source, std::size_t size) { + const auto* bytes = static_cast(source); + const std::uint64_t key = content_key(bytes, size); + { + std::lock_guard lock(mutex_); + if (auto found = find_locked(key, bytes, size)) return found; + } + // Copied outside the lock: another thread may have added the same bytes meanwhile, and then its copy is used. + auto made = std::make_shared>(bytes, bytes + size); + std::lock_guard lock(mutex_); + if (auto found = find_locked(key, bytes, size)) return found; + if (++added_ % 1024 == 0) std::erase_if(shaders_, [](const auto& entry) { return entry.second.expired(); }); + shaders_.emplace(key, made); + return made; + } + +private: + // A DXBC container carries a checksum of its contents in bytes 4..19, so that and the size pick the candidates + // without reading the whole program (as key_shader does in d3d12_vulkan_device.cpp). A container without one (all + // zero, as hand-built test containers have) or other bytecode is hashed with FNV-1a. A candidate is only taken + // when all its bytes are equal: hand-built containers can share a checksum. + static std::uint64_t content_key(const std::uint8_t* bytes, std::size_t size) { + std::uint64_t h = 0xcbf29ce484222325ull; + const auto mix = [&h](const std::uint8_t* data, std::size_t count) { + for (std::size_t i = 0; i < count; ++i) h = (h ^ data[i]) * 0x100000001b3ull; + }; + mix(reinterpret_cast(&size), sizeof(size)); + if (size >= 20 && std::memcmp(bytes, "DXBC", 4) == 0 && + std::any_of(bytes + 4, bytes + 20, [](std::uint8_t b) { return b != 0; })) + mix(bytes + 4, 16); + else + mix(bytes, size); + return h; + } + ShaderData find_locked(std::uint64_t key, const std::uint8_t* bytes, std::size_t size) { + const auto [first, last] = shaders_.equal_range(key); + for (auto it = first; it != last; ++it) + if (auto live = it->second.lock(); + live && live->size() == size && std::memcmp(live->data(), bytes, size) == 0) + return live; + return {}; + } + + std::mutex mutex_; + std::unordered_multimap>> shaders_; + std::uint64_t added_ = 0; +}; + +ShaderTable& shader_table() { + static auto* table = new ShaderTable; // never destroyed: a PSO may still be created during teardown + return *table; +} + // Holds a PsoStreamRecord as an IUnknown: the object keeps one reference, the creation code drops its own. class RecordOwner final : public IUnknown { public: @@ -309,7 +374,10 @@ bool PsoStreamRecord::copy_pointed_data(std::size_t type, std::size_t payload_of if (code.pShaderBytecode && code.BytecodeLength) { for (const auto& shader : payloads_->shaders) if (shader->data() == code.pShaderBytecode && shader->size() == code.BytecodeLength) return true; - code.pShaderBytecode = own_blob(payloads_->blobs, code.pShaderBytecode, code.BytecodeLength); + // Equal bytecode from any stream is kept once (ShaderTable); this record holds a reference to it. + ShaderData shared = shader_table().acquire(code.pShaderBytecode, code.BytecodeLength); + code.pShaderBytecode = shared->data(); + payloads_->shaders.push_back(std::move(shared)); std::memcpy(payload, &code, sizeof(code)); } return true; diff --git a/runtime/shims/d3d12_xs_pso_stream.h b/runtime/shims/d3d12_xs_pso_stream.h index bfeaf29b31..0d42397f99 100644 --- a/runtime/shims/d3d12_xs_pso_stream.h +++ b/runtime/shims/d3d12_xs_pso_stream.h @@ -42,7 +42,8 @@ inline constexpr unsigned kDerivedMaxRecords = 4; // An owned deep copy of one pipeline state stream. The root signature references are held until destruction; shader // bytecode, stream-output and input-layout arrays and strings, and cached blobs are copied, and their pointers in the -// copy point at the copies. +// copy point at the copies. Shader bytecode is copied once per content for the whole process: records whose streams +// carry equal bytecode, from any buffer, share one read-only copy, which lives as long as the last of them. class PsoStreamRecord { public: // Null when the stream is malformed, holds a subobject type this module does not walk, or is too large. @@ -74,7 +75,7 @@ class PsoStreamRecord { std::vector bytes_; struct Payloads { std::vector> blobs; // owned copies; their buffers do not move when this grows - std::vector shaders; + std::vector shaders; // the caller's containers and the shared bytecode copies std::vector roots; // AddRef'd ~Payloads(); }; diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index fca6f6f474..85fa6042ed 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -2260,6 +2260,13 @@ BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) { const uintptr_t start = reinterpret_cast(address); uintptr_t release_end = 0; if (releases && address) allocation_extent(address, release_end); + // Whether [start, release_end) is all the release frees: allocation_extent stops after 4096 regions. + bool release_known = false; + if (release_end > start) { + MEMORY_BASIC_INFORMATION next{}; + release_known = !VirtualQuery(reinterpret_cast(release_end), &next, sizeof(next)) || + next.State == MEM_FREE || next.AllocationBase != address; + } uintptr_t decommit_end = 0; if ((free_type & MEM_DECOMMIT) && address) { decommit_end = size ? start + size : leonida::title_write_watch::end_of(start); @@ -2276,8 +2283,11 @@ BOOL title_free_impl(LPVOID address, SIZE_T size, DWORD free_type) { } else { result = VirtualFree(address, size, free_type); } - // A release of size 0 frees the whole reservation, whose extent is not known here: a change anywhere. + // A release of size 0 frees the whole reservation: the range allocation_extent found before the free, so a reader + // whose pages are elsewhere (the D3D12 layer's textures and shadows) does not take every page for changed. Where + // that range is not known, a change anywhere. if (result && size) leonida::title_memory_map::changed(address, size); + else if (result && release_known) leonida::title_memory_map::changed(start, release_end); else if (result) leonida::title_memory_map::changed(); if (result && (free_type & MEM_DECOMMIT)) note_unwatched_change(address, size, 0, true); if (result && (free_type & MEM_RELEASE) && !(free_type & MEM_PRESERVE_PLACEHOLDER)) diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 8b79c987e9..92c6969d68 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -229,6 +229,8 @@ struct TargetView { std::uint32_t first_layer; std::uint32_t layer_count; ColorViewFormat format = ColorViewFormat::resource; + + bool operator==(const TargetView&) const = default; }; // D3D12_RECT: right and bottom are exclusive. @@ -399,6 +401,8 @@ struct VertexBufferView { std::uint64_t va; std::uint32_t size; std::uint32_t stride; + + bool operator==(const VertexBufferView&) const = default; }; struct IndexBufferView { @@ -988,6 +992,17 @@ class CommandList { return true; } + // The recording is dropped and no new one begins, for a closed list its owner will not execute again before its + // next Reset (a list-value cut's spare, d3d12_xs_device.cpp restart_recording): it keeps no commands and no + // stamp, so it holds back no copy the layer retires (command_list_epochs.h). Executed anyway, it replays nothing. + bool drop_recording() { + if (!closed_) return false; + commands_.clear(); + active_.clear(); + stamp_.drop(); + return true; + } + bool closed() const { return closed_; } std::span commands() const { return commands_; } diff --git a/runtime/src/command_list_epochs.h b/runtime/src/command_list_epochs.h index 61c73565db..1df5d16d95 100644 --- a/runtime/src/command_list_epochs.h +++ b/runtime/src/command_list_epochs.h @@ -4,7 +4,8 @@ // retires (a title window, DeviceState::retire_orphan_windows) may still be named by a list recorded before the // retirement and executed, or executed again, after it; a held batch and the async worker keep copies of the lists // too. Each list, and each copy of it, carries the epoch its recording began in (Stamp, a CommandList member): -// whatever was retired at epoch E is named by no list once the oldest live stamp is E or later. +// whatever was retired at epoch E is named by no list once the oldest live stamp is E or later. A list whose recording +// was dropped (CommandList::drop_recording) names nothing and carries no stamp until its next Reset. #include #include #include @@ -24,6 +25,8 @@ inline Registry& registry() { // A new epoch: lists whose recording began before it carry a smaller stamp. inline std::uint64_t advance() { return registry().epoch.fetch_add(1, std::memory_order_acq_rel) + 1; } +// The epoch a recording begun now carries. +inline std::uint64_t current() { return registry().epoch.load(std::memory_order_acquire); } // The oldest stamp alive (UINT64_MAX with no list at all). inline std::uint64_t oldest() { @@ -49,16 +52,25 @@ class Stamp { leave(epoch_); epoch_ = enter(registry().epoch.load(std::memory_order_acquire)); } + // The recording was dropped (CommandList::drop_recording): no stamp until restamp(), and a copy made meanwhile + // has none either. epoch() is 0 then; the epochs begin at 1. + void drop() { + leave(epoch_); + epoch_ = kNone; + } std::uint64_t epoch() const { return epoch_; } private: + static constexpr std::uint64_t kNone = 0; static std::uint64_t enter(std::uint64_t epoch) { + if (epoch == kNone) return kNone; Registry& r = registry(); std::lock_guard lock(r.mutex); r.live.insert(epoch); return epoch; } static void leave(std::uint64_t epoch) { + if (epoch == kNone) return; Registry& r = registry(); std::lock_guard lock(r.mutex); if (const auto it = r.live.find(epoch); it != r.live.end()) r.live.erase(it); diff --git a/runtime/src/console_heap_slot_records.h b/runtime/src/console_heap_slot_records.h index 4ab3c3b9d9..476c544ccc 100644 --- a/runtime/src/console_heap_slot_records.h +++ b/runtime/src/console_heap_slot_records.h @@ -16,6 +16,10 @@ // so a range [lo, hi) is answered by visiting, per class in use, the granules from lo - 2^class to hi: the cost is the // halves near the range, never the heap. An entry is checked against the record when visited (a half that moved // leaves a stale entry behind; a bucket drops its stale entries whenever it has doubled since it was last cleaned). +// A bucket counts the halves it holds and goes when the last one leaves it, so the buckets held are those of the live +// halves: without that, every granule a session ever wrote a V# into kept its bucket until the heap was destroyed, and +// the main heap lives as long as the session (many of its V#s are data the title keeps in a slot, with a new base +// whenever the data changes). // Portable, standard library only: console_heap_slot_records_test exercises it without a GPU. #include #include @@ -58,6 +62,14 @@ class ConsoleHeapSlotRecords { std::size_t recorded() const { return recorded_; } // halves in state resolved or waiting std::size_t waiting_count() const { return waiting_; } // halves in state waiting std::uint64_t looked_at() const { return looked_at_; } // index entries visited by touched(), all calls + // The buckets both indexes hold, counted over their maps: a diagnostic (the heap log line and + // console_heap_slot_records_test, which bounds it by the live halves). + std::size_t buckets() const { + std::size_t n = 0; + for (const auto& index : indexes_) + for (const auto& buckets : index.classes) n += buckets.size(); + return n; + } // Half `half` (0: the buffer V#, 1: the UAV counter V#) of `slot` now names [base, base + span) and resolved as // `state` says, its copy at `target` (see above). span 0 counts as 1. @@ -75,18 +87,15 @@ class ConsoleHeapSlotRecords { h.target = target; h.span_state = span | (std::uint64_t(state) << 56); count(state, +1); - if (state == none) return; // entries left behind are stale now - const auto add = [&](int which, std::uint64_t start, std::uint64_t old_start) { - const unsigned c = span_class(span); - const std::uint64_t granule = start >> granule_shift(c); + for (const int which : {kSource, kTarget}) { + unsigned was_c = 0, is_c = 0; + std::uint64_t was_granule = 0, is_granule = 0; + const bool was = held(which, old, was_c, was_granule), is = held(which, h, is_c, is_granule); // Unchanged key: the entry already there stands for it. - if (old.state() != none && (which == kSource || old.target) && span_class(old.span()) == c && - (old_start >> granule_shift(c)) == granule) - return; - push(which, c, granule, std::uint32_t(key)); - }; - add(kSource, base, old.base); - if (target) add(kTarget, target, old.target); + if (was && is && was_c == is_c && was_granule == is_granule) continue; + if (was) leave(which, was_c, was_granule); // the entry left behind is stale now + if (is) push(which, is_c, is_granule, std::uint32_t(key)); + } } void clear(std::size_t slot) { @@ -141,6 +150,7 @@ class ConsoleHeapSlotRecords { struct Bucket { std::vector keys; std::size_t clean = 0; // its size when it was last cleaned + std::size_t live = 0; // the halves held here now: each has a current entry in keys }; struct Index { std::array, kClasses> classes; @@ -158,18 +168,34 @@ class ConsoleHeapSlotRecords { if (state == waiting) waiting_ += std::size_t(std::ptrdiff_t(delta)); } + // Whether index `which` holds a half recorded as `h`, and if so under which class and granule. + static bool held(int which, const Half& h, unsigned& c, std::uint64_t& granule) { + if (h.state() == none || (which == kTarget && !h.target)) return false; + c = span_class(h.span()); + granule = (which == kSource ? h.base : h.target) >> granule_shift(c); + return true; + } + // Whether index `which` still holds `key` under (c, granule). bool current(int which, std::uint32_t key, unsigned c, std::uint64_t granule) const { - const Half& h = halves_[key]; - if (h.state() == none || span_class(h.span()) != c) return false; - if (which == kTarget && !h.target) return false; - return ((which == kSource ? h.base : h.target) >> granule_shift(c)) == granule; + unsigned hc = 0; + std::uint64_t hg = 0; + return held(which, halves_[key], hc, hg) && hc == c && hg == granule; + } + + // A half no longer held under (c, granule): its entry there is stale, and with the last live half the bucket + // goes, its stale entries with it (a lookup skips them, so it answers the same without them). + void leave(int which, unsigned c, std::uint64_t granule) { + auto& buckets = indexes_[which].classes[c]; + const auto it = buckets.find(granule); + if (it != buckets.end() && !--it->second.live) buckets.erase(it); } void push(int which, unsigned c, std::uint64_t granule, std::uint32_t key) { Index& index = indexes_[which]; index.used |= std::uint64_t(1) << c; Bucket& bucket = index.classes[c][granule]; + ++bucket.live; bucket.keys.push_back(key); if (bucket.keys.size() < 32 || bucket.keys.size() < 2 * bucket.clean) return; auto& keys = bucket.keys; diff --git a/runtime/src/mem_probe.h b/runtime/src/mem_probe.h index f8c573da49..4821b2f3ec 100644 --- a/runtime/src/mem_probe.h +++ b/runtime/src/mem_probe.h @@ -13,11 +13,20 @@ // bound and in-use bytes, geometry copies, title windows and shadows, upload heaps, staging, // texture blocks, sampled textures, render targets and depth, and other, which add up to the // allocated bytes of the t= line. +// [rt] mem-probe vmmap: in place of the smaps line where there is no /proc (native Windows): the commit charge and +// working set (GetProcessMemoryInfo), and the committed bytes of a VirtualQuery walk over the +// user address space by the smaps line's kinds (title memory, other PE private memory, PE +// images, PE sections, memory the Vulkan driver mapped for us), with the reserved bytes and +// the largest private allocations. // The Vulkan counts come from wrapping the runtime's own function table (install()); helpers that load their own // pointers (depth24, predicate, xdxr, swapchain) are not counted: they create a handful of objects. #include +#include #include +#ifdef _MSC_VER +#pragma comment(lib, "psapi.lib") +#endif #include "memory_breakdown.h" @@ -30,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -501,6 +511,211 @@ inline std::string read_rollup() { return out; } +// ---- native Windows: the address space by VirtualQuery, classified ---- +// One committed region as VirtualQuery reports it. +struct VmRegion { + std::uint64_t base = 0, size = 0; + std::uint64_t allocation = 0; // AllocationBase: the VirtualAlloc or the view the region belongs to + std::uint32_t type = 0; // MEM_IMAGE, MEM_MAPPED or MEM_PRIVATE +}; + +// Sorted, with overlapping and touching ranges joined, so that a region can be cut at the ranges' edges. +inline Ranges joined(Ranges ranges) { + std::sort(ranges.begin(), ranges.end()); + Ranges out; + for (const auto& range : ranges) { + if (range.second <= range.first) continue; + if (!out.empty() && range.first <= out.back().second) + out.back().second = (std::max)(out.back().second, range.second); + else + out.push_back(range); + } + return out; +} + +// The committed bytes by the smaps line's kinds, with the same title and vk_mapped ranges: the part of a region inside +// a title range is title memory, the part inside a vk_mapped range is memory the Vulkan driver mapped for us, and the +// rest is named by the region's type. The smaps line names a mapping by its first address; here a region is cut at +// the ranges' edges instead, so a reservation the title commits only part of counts once in each kind it reaches. +class VmTally { +public: + VmTally(Ranges title, Ranges vk_mapped) : title_(joined(std::move(title))), vk_mapped_(joined(std::move(vk_mapped))) {} + + void add(const VmRegion& region) { + bool counted[b_count] = {}; + const std::uint64_t end = region.size > UINT64_MAX - region.base ? UINT64_MAX : region.base + region.size; + for (std::uint64_t at = region.base; at < end;) { + bool inside = false; + std::uint64_t next = piece(title_, at, end, inside); + int bucket = b_title; + if (!inside) { + next = piece(vk_mapped_, at, next, inside); + bucket = inside ? b_vk_mapped : type_bucket(region.type); + } + committed[bucket] += next - at; + if (!counted[bucket]) { + counted[bucket] = true; + ++regions[bucket]; + } + if (bucket == b_pe_private) private_by_allocation_[region.allocation] += next - at; + at = next; + } + } + + std::uint64_t total() const { + std::uint64_t sum = 0; + for (const std::uint64_t bytes : committed) sum += bytes; + return sum; + } + + // The n allocations with the most committed private bytes outside the title and vk_mapped ranges, largest first: + // (bytes, allocation base). + std::vector> largest_private(std::size_t n) const { + std::vector> ranked; + ranked.reserve(private_by_allocation_.size()); + for (const auto& [allocation, bytes] : private_by_allocation_) ranked.push_back({bytes, allocation}); + const std::size_t keep = (std::min)(n, ranked.size()); + std::partial_sort(ranked.begin(), ranked.begin() + std::ptrdiff_t(keep), ranked.end(), + [](const auto& a, const auto& b) { return a.first > b.first; }); + ranked.resize(keep); + return ranked; + } + + std::uint64_t committed[b_count] = {}; + std::uint64_t regions[b_count] = {}; // the regions that put bytes into each kind + +private: + static int type_bucket(std::uint32_t type) { + if (type == MEM_IMAGE) return b_pe_image; + if (type == MEM_MAPPED) return b_pe_mapped; + return b_pe_private; + } + // From `at`, the end (at most `end`) of the piece that lies wholly inside one of `ranges` or wholly outside them. + static std::uint64_t piece(const Ranges& ranges, std::uint64_t at, std::uint64_t end, bool& inside) { + const auto it = std::upper_bound(ranges.begin(), ranges.end(), std::make_pair(at, UINT64_MAX)); + if (it != ranges.begin() && at < std::prev(it)->second) { + inside = true; + return (std::min)(end, std::prev(it)->second); + } + inside = false; + return it == ranges.end() ? end : (std::min)(end, it->first); + } + + Ranges title_, vk_mapped_; + std::map private_by_allocation_; +}; + +// The process's commit charge and working set. PrivateUsage and PagefileUsage are the same figure on Windows 8 and +// later; Wine fills only PagefileUsage (src/memory_figures.h), so the larger of the two is the charge. +struct ProcessCounters { + bool read = false; // GetProcessMemoryInfo answered + bool private_working_set_reported = false; // it took the PROCESS_MEMORY_COUNTERS_EX2 size + std::uint64_t private_commit = 0, peak_commit = 0, working_set = 0, peak_working_set = 0; + std::uint64_t private_working_set = 0; // 0 where the system does not report it +}; + +// PROCESS_MEMORY_COUNTERS_EX2's layout. The SDK declares it only for NTDDI_WIN10_CU and later, and MinGW's headers may +// not at all; Windows 10 21H2 and later fill it, an older system refuses its size. +struct MemoryCountersEx2 { + PROCESS_MEMORY_COUNTERS_EX ex; + SIZE_T private_working_set; + ULONG64 shared_commit; +}; +static_assert(sizeof(MemoryCountersEx2) == sizeof(PROCESS_MEMORY_COUNTERS_EX) + 2 * sizeof(ULONG64), + "PROCESS_MEMORY_COUNTERS_EX2 is PROCESS_MEMORY_COUNTERS_EX and two more 64-bit fields"); + +inline ProcessCounters process_counters() { + MemoryCountersEx2 counters{}; + counters.ex.cb = sizeof counters; + ProcessCounters out; + out.private_working_set_reported = GetProcessMemoryInfo( + GetCurrentProcess(), reinterpret_cast(&counters), sizeof counters) != FALSE; + if (!out.private_working_set_reported) { + counters = {}; + counters.ex.cb = sizeof counters.ex; + if (!GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&counters.ex), + sizeof counters.ex)) + return out; + } + out.read = true; + out.private_commit = (std::max)(std::uint64_t(counters.ex.PrivateUsage), std::uint64_t(counters.ex.PagefileUsage)); + out.peak_commit = counters.ex.PeakPagefileUsage; + out.working_set = counters.ex.WorkingSetSize; + out.peak_working_set = counters.ex.PeakWorkingSetSize; + out.private_working_set = counters.private_working_set; + return out; +} + +// Walks the user address space (GetSystemInfo's bounds) with VirtualQuery: every committed region goes to the tally, +// and the reserved bytes are summed. Returns how many regions it walked, free ones included. +inline std::uint64_t walk_address_space(VmTally& tally, std::uint64_t& reserved) { + SYSTEM_INFO system{}; + GetSystemInfo(&system); + const auto last = reinterpret_cast(system.lpMaximumApplicationAddress); + std::uint64_t walked = 0; + for (auto at = reinterpret_cast(system.lpMinimumApplicationAddress); at <= last;) { + MEMORY_BASIC_INFORMATION region{}; + if (!VirtualQuery(reinterpret_cast(at), ®ion, sizeof region)) break; + const auto base = reinterpret_cast(region.BaseAddress); + ++walked; + if (region.State == MEM_COMMIT) + tally.add({base, region.RegionSize, reinterpret_cast(region.AllocationBase), region.Type}); + else if (region.State == MEM_RESERVE) + reserved += region.RegionSize; + if (base + region.RegionSize <= at) break; // no progress: stop rather than loop + at = base + region.RegionSize; + } + return walked; +} + +inline std::string vmmap_text(double t, double ms, std::uint64_t walked, const ProcessCounters& counters, + const VmTally& tally, std::uint64_t reserved) { + char item[256]; + std::snprintf(item, sizeof item, "[rt] mem-probe vmmap t=%.0fs (%.0f ms, %llu regions): ", t, ms, + (unsigned long long)walked); + std::string text = item; + if (counters.read) { + char private_ws[32] = "n/a"; + if (counters.private_working_set) + std::snprintf(private_ws, sizeof private_ws, "%.0f", mib(counters.private_working_set)); + std::snprintf(item, sizeof item, + "private commit %.0f MiB (peak %.0f), working set %.0f MiB (private %s, peak %.0f); ", + mib(counters.private_commit), mib(counters.peak_commit), mib(counters.working_set), private_ws, + mib(counters.peak_working_set)); + text += item; + } else { + text += "process counters n/a; "; + } + std::snprintf(item, sizeof item, "committed %.0f MiB by kind:", mib(tally.total())); + text += item; + const int kinds[] = {b_title, b_pe_private, b_pe_image, b_pe_mapped, b_vk_mapped}; + for (const int b : kinds) { + std::snprintf(item, sizeof item, "%s %s %.0f (%llu regions)", b == kinds[0] ? "" : ",", bucket_name(b), + mib(tally.committed[b]), (unsigned long long)tally.regions[b]); + text += item; + } + std::snprintf(item, sizeof item, "; reserved %.0f MiB; largest private allocations MiB:", mib(reserved)); + text += item; + const auto largest = tally.largest_private(4); + for (std::size_t i = 0; i < largest.size(); ++i) { + std::snprintf(item, sizeof item, "%s 0x%llx %.0f", i ? "," : "", (unsigned long long)largest[i].second, + mib(largest[i].first)); + text += item; + } + if (largest.empty()) text += " none"; + return text; +} + +// The vmmap line of this process now. It takes the title and vk_mapped ranges the smaps line would use. +inline std::string sample_vmmap(double t, const Ranges& title, const Ranges& vk_mapped) { + const std::uint64_t t0 = now_ns(); + const ProcessCounters counters = process_counters(); + VmTally tally(title, vk_mapped); + std::uint64_t reserved = 0; + const std::uint64_t walked = walk_address_space(tally, reserved); + return vmmap_text(t, double(now_ns() - t0) / 1e6, walked, counters, tally, reserved); +} + // What the device adds to the line: pipeline cache bytes, arena use, title memory ranges. struct DeviceFacts { std::function describe; // one text fragment @@ -590,6 +805,11 @@ inline void sample(const DeviceFacts& facts) { .c_str()); Ranges title = facts.title_ranges ? facts.title_ranges() : Ranges{}; std::sort(title.begin(), title.end()); + // Native Windows has no /proc to read: the vmmap line takes the same kinds from the Win32 API there. + if (proc_dir().empty()) { + std::fprintf(stderr, "%s\n", sample_vmmap(t, title, vk_mapped).c_str()); + return; + } Usage usage[b_count]; std::string top_files, error; const std::uint64_t t0 = now_ns(); diff --git a/runtime/src/title_texture_memory.h b/runtime/src/title_texture_memory.h index d2c512cecc..ee106f4297 100644 --- a/runtime/src/title_texture_memory.h +++ b/runtime/src/title_texture_memory.h @@ -89,4 +89,22 @@ inline bool texture_memory_readable(std::uintptr_t base, std::uint64_t size, Tex return size && texture_memory_readable_bytes(base, size, commit) == size; } +// Whether any page of [base, base + size) is committed, whatever its protection. False when the title has freed, +// decommitted or unmapped every page of the footprint: a texture there has gone whole, where one whose larger mips +// went (texture_memory_readable_bytes stops at the first missing page) still has its smaller ones. A page the layer +// write-protects to watch it stays committed. +inline bool texture_memory_committed(std::uintptr_t base, std::uint64_t size) { + if (!base || !size || size > (std::numeric_limits::max)() - base) return false; + const auto end = base + size; + for (auto at = base; at < end;) { + MEMORY_BASIC_INFORMATION region{}; + if (!VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region))) return false; + if (region.State == MEM_COMMIT) return true; + const auto next = reinterpret_cast(region.BaseAddress) + region.RegionSize; + if (next <= at) return false; + at = next; + } + return false; +} + } // namespace leonida diff --git a/runtime/src/title_texture_refresh.h b/runtime/src/title_texture_refresh.h index b39defdcda..a1058faae2 100644 --- a/runtime/src/title_texture_refresh.h +++ b/runtime/src/title_texture_refresh.h @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -39,6 +40,7 @@ class TitleTextureRangeIndex { pages_[shift][{number, key}] = {first, last}; location_[key] = {shift, number}; } + std::size_t size() const { return location_.size(); } // the keys with a range template void overlapping(Address from, Address to, Visit visit) const { if (from >= to) return; diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 8ed315ecf1..46a37016d4 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -511,6 +511,11 @@ class TitleVaAliases { std::unique_lock lock(mutex_); out.swap(removed_); } + // The removals recorded and not taken yet. For tests. + std::size_t removals_pending() const { + std::shared_lock lock(mutex_); + return removed_.size(); + } void note_translation(Kind kind) { translated_[kind].fetch_add(1, std::memory_order_relaxed); } std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); } std::uint64_t untranslated(Kind kind) const { return untranslated_[kind].load(std::memory_order_relaxed); } diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 858ba46bec..1db8193028 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -529,45 +529,83 @@ class DeferredDeletionQueue { } } - for (const Item& item : to_destroy) { - switch (item.kind) { - case Kind::bindless_slot: - if (release_fn) { - release_fn(release_user, static_cast(item.handle >> 32), - static_cast(item.handle & 0xFFFFFFFFu)); + for (const Item& item : to_destroy) destroy(item, device, vk, release_fn, release_user); + } + + // What still waits for a drain after a device loss, in its order, instead of being destroyed at once. Releasing a + // bindless slot takes the device's descriptor lock, which the caller that defers it holds (DeviceState::release in + // d3d12_vulkan_device.cpp). An image view is deferred right after its slot, and until the slot is released the + // set's pending writes and shadow copy may still name the view; a flush hands those to vkUpdateDescriptorSets, + // which must not see a destroyed view. So views go at teardown too, after their slot. Both stay bounded: the set + // never hands out more slots than it has (a slot comes back only through its release), a slot has at most four + // views, and the context's own view cache grows only while batches replay, which stops at the loss. + static bool kept_after_loss(Kind kind) { return kind == Kind::bindless_slot || kind == Kind::image_view; } + + // After a device loss: destroys every item now, whatever its ticket, except those kept_after_loss(), which stay + // queued in their order. + void drain_lost(VkDevice device, const VulkanDeviceFunctions& vk) { + std::vector to_destroy; + { + std::lock_guard lock(mutex_); + const std::size_t mask = pending_.size() - 1; + std::size_t kept = 0; + for (std::size_t i = 0; i < count_; ++i) { + const Item& item = pending_[(head_ + i) & mask]; + if (kept_after_loss(item.kind)) { + // Kept items move towards the front only, so this never overwrites one not yet read. + pending_[(head_ + kept) & mask] = item; + ++kept; + } else { + to_destroy.push_back(item); } - break; - case Kind::image_view: - vk.vkDestroyImageView(device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::image: - vk.vkDestroyImage(device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::pooled_title_image: - delete reinterpret_cast(item.handle); - break; - case Kind::sparse_resource: - // Releases the resource and its page backing together after outstanding submissions. - delete reinterpret_cast*>(item.handle); - break; - case Kind::buffer: - vk.vkDestroyBuffer(device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::device_memory: - vk.vkFreeMemory(device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::image_memory: - delete reinterpret_cast(item.handle); - break; - case Kind::acceleration_structure: - if (vk.vkDestroyAccelerationStructureKHR) - vk.vkDestroyAccelerationStructureKHR( - device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::framebuffer: - vk.vkDestroyFramebuffer(device, reinterpret_cast(item.handle), nullptr); - break; } + count_ = kept; + tail_ = (head_ + kept) & mask; + } + for (const Item& item : to_destroy) destroy(item, device, vk, nullptr, nullptr); + } + + // Destroys one item now. A bindless slot is handed to release_fn. + static void destroy(const Item& item, VkDevice device, const VulkanDeviceFunctions& vk, + BindlessReleaseFn release_fn, void* release_user) { + switch (item.kind) { + case Kind::bindless_slot: + if (release_fn) { + release_fn(release_user, static_cast(item.handle >> 32), + static_cast(item.handle & 0xFFFFFFFFu)); + } + break; + case Kind::image_view: + vk.vkDestroyImageView(device, reinterpret_cast(item.handle), nullptr); + break; + case Kind::image: + vk.vkDestroyImage(device, reinterpret_cast(item.handle), nullptr); + break; + case Kind::pooled_title_image: + delete reinterpret_cast(item.handle); + break; + case Kind::sparse_resource: + // Releases the resource and its page backing together: after outstanding submissions, or at once after a + // device loss. + delete reinterpret_cast*>(item.handle); + break; + case Kind::buffer: + vk.vkDestroyBuffer(device, reinterpret_cast(item.handle), nullptr); + break; + case Kind::device_memory: + vk.vkFreeMemory(device, reinterpret_cast(item.handle), nullptr); + break; + case Kind::image_memory: + delete reinterpret_cast(item.handle); + break; + case Kind::acceleration_structure: + if (vk.vkDestroyAccelerationStructureKHR) + vk.vkDestroyAccelerationStructureKHR(device, reinterpret_cast(item.handle), + nullptr); + break; + case Kind::framebuffer: + vk.vkDestroyFramebuffer(device, reinterpret_cast(item.handle), nullptr); + break; } } @@ -1971,13 +2009,21 @@ class VulkanContext { void defer_destroy(DeferredDeletionQueue::Kind kind, VkHandle handle) { const auto raw = static_cast(reinterpret_cast(handle)); if (!raw) return; - std::lock_guard lock(submit_mutex_); - const std::uint64_t safe_ticket = submitted_ticket_.load(std::memory_order_acquire) + 1; - deletion_queue_.push(safe_ticket, kind, raw); + defer_destroy(kind, raw); } void defer_destroy(DeferredDeletionQueue::Kind kind, std::uint64_t raw_handle) { if (!raw_handle && kind != DeferredDeletionQueue::Kind::bindless_slot) return; + // Once the device is lost no retire ticket completes again (completed_retire_ticket() answers 0 and acquire() + // returns before its drain), so a queued object would stay until the context goes and the queue would grow + // with everything the title releases. The lost device runs nothing more, and vkDestroy* and vkFreeMemory are + // valid on it: the object goes now, and the first time also everything queued before the loss. Bindless slots + // and image views still wait, in their order (DeferredDeletionQueue::kept_after_loss says why). + if (is_device_lost() && !DeferredDeletionQueue::kept_after_loss(kind)) { + if (!lost_queue_drained_.exchange(true, std::memory_order_acq_rel)) deletion_queue_.drain_lost(device_, vk); + DeferredDeletionQueue::destroy({0, raw_handle, kind}, device_, vk, nullptr, nullptr); + return; + } std::lock_guard lock(submit_mutex_); const std::uint64_t safe_ticket = submitted_ticket_.load(std::memory_order_acquire) + 1; deletion_queue_.push(safe_ticket, kind, raw_handle); @@ -2372,6 +2418,7 @@ class VulkanContext { RetireTickets retire_tickets_; std::atomic submitted_ticket_{0}; DeferredDeletionQueue deletion_queue_; + std::atomic lost_queue_drained_{false}; // defer_destroy emptied the queue once after the loss std::unique_ptr device_fault_; std::jthread progress_watch_; std::unique_ptr fence_dispatcher_; @@ -2747,12 +2794,15 @@ class VulkanQueue : private QueueHolds::Holder { // held instead, and the call succeeds: the batch is replayed by the thread that submits the Signal (or the CPU // Signal), which is also where its errors are reported (stderr, and take_held_failure()). // - // `pin`, called only when the batch is held, returns what has to stay alive until the batch has run: the COM layer - // passes the pipeline states and root signatures the lists named (the application may release them and Reset - // the lists as soon as the call returns). + // `pin`, called only when the batch is held (or queued for the worker, LEONIDA_SUBMIT_ASYNC), returns what has to + // stay alive until the batch has run: the COM layer passes the pipeline states and root signatures the lists + // named (the application may release them and Reset the lists as soon as the call returns). `keep`, called when + // the batch is submitted at once, returns what has to stay alive until that submission has completed on the GPU, + // or null: the COM layer passes the objects a shim gave the lists for their recording alone (a scratch buffer). + // A held or queued batch has those in what `pin` returned, which is kept until its submission has completed too. using PinFn = std::function()>; - ReplayResult execute(std::span lists, const PinFn& pin = {}) { + ReplayResult execute(std::span lists, const PinFn& pin = {}, const PinFn& keep = {}) { pipeline_wait::note_submission(); // big compute warm-ups are left to their first use while the title submits auto* diagnostics = context_.device_fault(); const auto execute_call = diagnostics ? diagnostics->next_execute_call() : 0; @@ -2766,10 +2816,11 @@ class VulkanQueue : private QueueHolds::Holder { enqueue(std::move(call)); return ReplayResult::success; } - return execute_sync(lists, pin, execute_call); + return execute_sync(lists, pin, execute_call, keep); } - ReplayResult execute_sync(std::span lists, const PinFn& pin, std::uint64_t execute_call) { + ReplayResult execute_sync(std::span lists, const PinFn& pin, std::uint64_t execute_call, + const PinFn& keep = {}) { ReplayResult result = ReplayResult::success; bool held = false; std::vector> retired; // destroyed after state_mutex_ is released @@ -2777,6 +2828,12 @@ class VulkanQueue : private QueueHolds::Holder { std::lock_guard state(state_mutex_); if (!must_hold()) { result = execute_now(lists, execute_call); + // A failed call submitted nothing of the lists, so there is nothing to keep them for. + std::shared_ptr kept = result == ReplayResult::success && keep ? keep() : nullptr; + if (kept) { + std::vector> pins{std::move(kept)}; + retire_pins(pins, submitted_); // released by drain_pins once this submission has completed + } } else if (context_.is_device_lost()) { result = queue_unsupported(__LINE__); } else { @@ -3634,6 +3691,16 @@ class VulkanQueue : private QueueHolds::Holder { VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &full, 0, nullptr, 0, nullptr); } if (!tracker_lock.owns_lock()) tracker_lock.lock(); + // Another queue holds tracker_mutex_ through its vkQueueSubmit, so it can find the device lost while this batch + // waits here, past its own checks above. Once the device is lost, defer_destroy destroys released objects at + // once rather than after the next submission, and also what was queued before the loss. An image may then be + // gone whose view the bindless set's pending writes or shadow copy still name until its slot is released, and + // the flush below would hand that view to vkUpdateDescriptorSets. Nothing this batch records would reach the + // queue anyway: submit() refuses a lost device. + if (context_.is_device_lost()) { + discard(); + return queue_unsupported(__LINE__); + } if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { const bool ended = context_.observe_result(context_.vk.vkEndCommandBuffer(command_buffer), "vkEndCommandBuffer") == VK_SUCCESS; diff --git a/runtime/test/command_list_test.cpp b/runtime/test/command_list_test.cpp index ea81503e6e..de57ed91ba 100644 --- a/runtime/test/command_list_test.cpp +++ b/runtime/test/command_list_test.cpp @@ -9,9 +9,46 @@ } \ } while (0) +// Command-list epochs (src/command_list_epochs.h), checked before main records any list. A list closed and never +// reset may be executed again, so it holds back every copy the layer retires after its recording began; one whose +// recording was dropped (drop_recording: its owner does not execute it again before its next Reset) holds back +// nothing, nor does a copy of it, until a Reset begins a new recording. Only a closed list drops its recording. +static int check_epochs() { + using namespace leonida; + namespace epochs = command_list_epochs; + CHECK(epochs::oldest() == UINT64_MAX); // no list yet + { + CommandList idle, busy; + const std::uint64_t first = epochs::oldest(); + CHECK(idle.uav_barrier({0}) && idle.close() && busy.close()); + const std::uint64_t retirement = epochs::advance(); + CHECK(busy.reset() && !busy.drop_recording() && busy.close()); // a list still recording keeps its recording + CHECK(first < retirement && epochs::oldest() == first); // the idle list, closed and never reset + { + const CommandList held = idle; // a held batch's copy, made before the drop + CHECK(idle.drop_recording() && idle.closed() && idle.commands().empty()); + CHECK(held.commands().size() == 1 && epochs::oldest() == first); // the copy still names the recording + } + CHECK(epochs::oldest() == retirement); // only the busy list, reset after the retirement + const std::uint64_t later = epochs::advance(); + CHECK(busy.drop_recording() && epochs::oldest() == UINT64_MAX); + { + const CommandList copy = idle; // copies of a dropped recording name nothing either + CommandList assigned; // a new list's recording begins at once + CHECK(epochs::oldest() == later); + assigned = busy; + CHECK(epochs::oldest() == UINT64_MAX); + } + CHECK(idle.reset() && epochs::oldest() == later); // a new recording counts again, from its Reset + } + CHECK(epochs::oldest() == UINT64_MAX); + return 0; +} + int main() { using namespace leonida; namespace s = d3d12_state; + if (check_epochs()) return 1; CommandList list; TargetView descriptor{12, 1, 2, 3}; ClearColor color{1, 0, 0, 1}; diff --git a/runtime/test/console_heap_slot_records_test.cpp b/runtime/test/console_heap_slot_records_test.cpp index c5fcfbe9ab..a721d6b5a3 100644 --- a/runtime/test/console_heap_slot_records_test.cpp +++ b/runtime/test/console_heap_slot_records_test.cpp @@ -127,18 +127,57 @@ struct Model { changes.push_back({SlotChange::source_gone, title, a.end}); changes.push_back({SlotChange::target_gone, kArena + a.shader, kArena + a.shader + (a.end - title)}); } - // apply_slot_changes: the slots looked at (index entries) and fixed again. + // touched() as a walk of every recorded half answers it: the slots whose target (target changes, halves with one) + // or base range (source changes) overlaps a change, waiting halves only for an addition. + std::vector walk(const std::vector& list) const { + std::vector out; + for (std::size_t slot = 0; slot < slots.size(); ++slot) { + bool hit = false; + for (unsigned half = 0; half < 2 && !hit; ++half) { + const auto state = records.state(slot, half); + if (state == ConsoleHeapSlotRecords::none) continue; + const Words& w = slots[slot][half]; + const std::uint64_t target = records.target(slot, half); + for (const SlotChange& change : list) { + const bool on_target = + change.kind == SlotChange::target_gone || change.kind == SlotChange::target_added; + const bool waiting_only = + change.kind == SlotChange::target_added || change.kind == SlotChange::source_added; + if (change.hi <= change.lo || (on_target && !target)) continue; + if (waiting_only && state != ConsoleHeapSlotRecords::waiting) continue; + const std::uint64_t start = on_target ? target : w.base; + if (start < change.hi && start + w.span > change.lo) { + hit = true; + break; + } + } + } + if (hit) out.push_back(std::uint32_t(slot)); + } + return out; + } + // apply_slot_changes: the slots looked at (index entries) and fixed again. Each answer is also compared with the + // walk; a difference is kept until consistent() reports it. std::uint64_t looked = 0; std::vector touched; + std::size_t walk_differs = 0; // touched() answers that differed from the walk void apply() { + const std::vector walked = walk(changes); const std::uint64_t before = records.looked_at(); records.touched(changes.data(), changes.size(), touched); looked = records.looked_at() - before; + if (touched != walked) { + if (!walk_differs) + std::fprintf(stderr, "touched() names %zu slots, a walk of every half %zu\n", touched.size(), + walked.size()); + ++walk_differs; + } changes.clear(); for (const std::uint32_t slot : touched) fix(slot); } // Every slot as a full re-resolution would leave it: the copy the walk this replaced would have produced. bool consistent() const { + if (walk_differs) return false; for (std::size_t slot = 0; slot < slots.size(); ++slot) for (unsigned half = 0; half < 2; ++half) { const Words& w = slots[slot][half]; @@ -326,13 +365,56 @@ int differential() { std::fprintf(stderr, "round %d\n", round); return 1; } + // A half is held at most once in each index, so the buckets held are at most twice the halves recorded. + if (m.records.buckets() > 2 * m.records.recorded()) { + std::fprintf(stderr, "round %d: %zu index buckets held for %zu halves recorded\n", round, + m.records.buckets(), m.records.recorded()); + return 1; + } } EXPECT(m.records.recorded() > 0); // The model's address space is a few MiB, so most changes touch most of it: this case checks results, not cost. - std::printf("differential: 400 rounds, copy equal to a full re-resolution after each; %llu entries looked at, " - "%llu slots fixed again, %zu halves recorded at the end\n", + std::printf("differential: 400 rounds, copy equal to a full re-resolution and touched() to a walk of every half " + "after each; %llu entries looked at, %llu slots fixed again, %zu halves recorded and %zu index " + "buckets held at the end\n", static_cast(looked), static_cast(touched), - m.records.recorded()); + m.records.recorded(), m.records.buckets()); + return 0; +} + +// A half that moves to another granule leaves its old bucket. Slot 0's counter half waits at a new 1 MiB step 200,001 +// times (data the title keeps in a slot reads as a V# with a new base whenever it changes), and slot 1's buffer half +// resolves into a new step as often, so both indexes see it: the buckets held stay those of the two live halves, and +// none is left once both slots are cleared. The lookups give what they gave before. +int buckets_follow_live_halves() { + ConsoleHeapSlotRecords records; + records.reset(16); + constexpr std::uint64_t kMoves = 200001; + for (std::uint64_t i = 0; i < kMoves; ++i) { + records.set(0, 1, ConsoleHeapSlotRecords::waiting, i << 20, 4096, 0); + records.set(1, 0, ConsoleHeapSlotRecords::resolved, (i << 20) + 0x800, 0x100, kArena + (i << 20)); + } + const std::size_t held = records.buckets(); + // The last ranges are found, every earlier one names nothing. + constexpr std::uint64_t last = (kMoves - 1) << 20; + std::vector out; + const SlotChange now[] = {{SlotChange::source_gone, last, last + 0x1000}, + {SlotChange::target_gone, kArena + last, kArena + last + 0x100}}; + records.touched(now, 1, out); + EXPECT(out.size() == 2 && out[0] == 0 && out[1] == 1); + records.touched(now + 1, 1, out); + EXPECT(out.size() == 1 && out[0] == 1); + const SlotChange before[] = {{SlotChange::source_gone, 0, last}, {SlotChange::target_gone, kArena, kArena + last}, + {SlotChange::source_added, 0, last}}; + records.touched(before, 3, out); + EXPECT(out.empty()); + records.clear(0); + records.clear(1); + std::printf("buckets: %llu moves of two halves: %zu index buckets held for the 2 live halves, %zu once both slots " + "are cleared\n", + static_cast(kMoves), held, records.buckets()); + EXPECT(held <= 2 * 2); + EXPECT(records.recorded() == 0 && records.buckets() == 0); return 0; } @@ -341,6 +423,7 @@ int differential() { int main() { if (release_looks_at_its_slots_only()) return 1; if (cases()) return 1; + if (buckets_follow_live_halves()) return 1; if (differential()) return 1; std::printf("console_heap_slot_records_test: ok\n"); return 0; diff --git a/runtime/test/d3d12_code_base_share_test.cpp b/runtime/test/d3d12_code_base_share_test.cpp new file mode 100644 index 0000000000..2f9298b5af --- /dev/null +++ b/runtime/test/d3d12_code_base_share_test.cpp @@ -0,0 +1,282 @@ +// The arena copies of the programs shaders read their code base from (s_getpc_b64 and the constant tables in the +// shader's own FSSM program, docs/design.md): the PSOs made from one program share one copy, which lives while any of +// them does. Through the Vulkan device alone, with hand-built programs and GLSL modules written to the translator's +// contract: +// - four compute PSOs of program A (uses_code_base: true) take A's bytes of the arena once, and all four read their +// code base at the same console VA, where A's bytes are; +// - a PSO of program B takes B's bytes at another VA; one of program C, whose index entry has no uses_code_base key +// (an index from before the key, whose shader may read its code base), takes C's; one of program D +// (uses_code_base: false) takes none; +// - two graphics PSOs whose pixel shader is program E (uses_code_base: true), with different blend states, take E's +// bytes once; +// - releasing three of the four A PSOs keeps A's copy, its bytes intact, for the fourth; releasing that one returns +// A's bytes, and a new A PSO makes a new copy. +// With --per-pso (LEONIDA_SHARE_CODE_BASE=0) every PSO has a copy of its own, as before the copies were shared. +// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_CS_SPV +#error "LEONIDA_TEST_CS_SPV must name the compiled compute test shader" +#endif +#if !defined(LEONIDA_TEST_VS_FULLSCREEN_SPV) || !defined(LEONIDA_TEST_PS_SPV) +#error "LEONIDA_TEST_VS_FULLSCREEN_SPV and LEONIDA_TEST_PS_SPV must name the compiled draw test shaders" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; + +namespace { + +// An FSSM program of `words` dwords after the magic, each distinct, so two programs of one seed and size are equal +// and any other two differ. +std::vector program(std::uint32_t seed, std::uint32_t words) { + std::vector out = {'F', 'S', 'S', 'M'}; + for (std::uint32_t i = 0; i < words; ++i) put32(out, seed + i); + return out; +} + +// A copy's console VA and bytes, or {0, 0} when the PSO has none. +struct Copy { + std::uint64_t va = 0, bytes = 0; +}; +Copy copy_of(ID3D12PipelineState* pso) { + Copy c; + if (!rt::d3d12::pipeline_code_base(pso, c.va, c.bytes)) return {}; + return c; +} + +// True when the arena holds `expected` at `va`. +bool arena_holds(ID3D12Device* device, std::uint64_t va, const std::vector& expected) { + std::vector got(expected.size()); + return rt::d3d12::read_arena(device, va, got.data(), got.size()) && got == expected; +} + +// A released PSO whose pipeline a compile worker is building (the warm-up thread builds compute ones ahead of their +// first dispatch) is deleted when that build returns (PipelineState::last_release), and its copy goes with it. Waits +// up to 60 s for the PSOs not yet deleted to be `live`. +bool settle(long live) { + for (int i = 0; i < 6000 && rt::d3d12::live_pipeline_states() != live; ++i) Sleep(10); + return rt::d3d12::live_pipeline_states() == live; +} + +std::string entry(const char* name, const char* stage, const std::vector& fssm, const char* extra) { + return std::string("\"") + name + "\": {\"stage\": \"" + stage + "\", \"fssm_sha256\": \"" + + leonida::sha256_hex(fssm) + "\", \"bindings\": [], \"push_constant_bytes\": 144" + extra + "}"; +} + +} // namespace + +int main(int argc, char** argv) { + const bool per_pso = argc == 2 && std::strcmp(argv[1], "--per-pso") == 0; + if (argc != 1 && !per_pso) { + std::fputs("usage: d3d12_code_base_share_test [--per-pso]\n", stderr); + return 2; + } + if (per_pso) { + char value[4] = {}; + if (GetEnvironmentVariableA("LEONIDA_SHARE_CODE_BASE", value, sizeof value) != 1 || value[0] != '0') { + std::fputs("--per-pso needs LEONIDA_SHARE_CODE_BASE=0\n", stderr); + return 2; + } + } + + // The programs, of distinct sizes so each count below has one reading, and the index that maps them to modules. + const auto a = program(0x41000000u, 1000), b = program(0x42000000u, 600), c = program(0x43000000u, 300), + d = program(0x44000000u, 200), e = program(0x45000000u, 500), vs = program(0x56000000u, 8); + const testfiles::ScratchDir scratch("leonida_code_base_share_test"); + const auto& library = scratch.path(); + // The pipeline cache and journal of the warm-up's builds go to the scratch folder, not the working directory. + if (!GetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", nullptr, 0)) + EXPECT(SetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", (library / "cache").c_str())); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_a.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_b.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_c.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_d.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_VS_FULLSCREEN_SPV), library / "vs_e.spv")); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_PS_SPV), library / "ps_e.spv")); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{" << entry("cs_a", "cs", a, ", \"local_size\": [64, 1, 1], \"uses_code_base\": true") << ",\n " + << entry("cs_b", "cs", b, ", \"local_size\": [64, 1, 1], \"uses_code_base\": true") << ",\n " + << entry("cs_c", "cs", c, ", \"local_size\": [64, 1, 1]") << ",\n " + << entry("cs_d", "cs", d, ", \"local_size\": [64, 1, 1], \"uses_code_base\": false") << ",\n " + << entry("vs_e", "vs", vs, ", \"input_signature\": []") << ",\n " + << entry("ps_e", "ps", e, ", \"outputs\": [0], \"uses_code_base\": true") << "}"; + index.close(); + EXPECT(index); + } + // The index as the runtime reads it: C's entry has no uses_code_base key, so its use is not known. + { + leonida::ShaderLibrary check; + EXPECT(check.load(library.string())); + const auto* entry_c = check.find("cs", leonida::sha256_hex(c)); + EXPECT(entry_c && !entry_c->code_base_known && !entry_c->uses_code_base); + const auto* entry_d = check.find("cs", leonida::sha256_hex(d)); + EXPECT(entry_d && entry_d->code_base_known && !entry_d->uses_code_base); + } + + { + vktest::Device vk; + vk.request_buffer_device_address = true; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + EXPECT(status == vktest::DeviceStatus::ready); + if (!vk.buffer_device_address) { + std::puts("SKIP: the device lacks bufferDeviceAddress, which the GPU address arena needs"); + return 77; + } + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.buffer_device_address = vk.buffer_device_address; + info.subgroup = vk.subgroup; + info.shader_dir = library.string(); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + if (rt::d3d12::device_push_constants_need_fallback(device.p)) { + std::printf("SKIP: the PSOs need 144 push-constant bytes and this GPU has %u\n", + rt::d3d12::device_max_push_constants_size(device.p)); + return 77; + } + EXPECT(rt::d3d12::device_arena_size(device.p) > 0); + EXPECT(rt::d3d12::live_pipeline_states() == 0); // settle() counts this test's PSOs only + const std::uint64_t before = rt::d3d12::arena_shader_bytes(device.p); + const auto used = [&] { return rt::d3d12::arena_shader_bytes(device.p) - before; }; + + // Root signatures: one root UAV for compute; two constants and a root CBV for the draw shaders. + D3D12_ROOT_PARAMETER uav{}; + uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC compute_root_desc{}; + compute_root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + compute_root_desc.Desc_1_0 = {1, &uav, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + D3D12_ROOT_PARAMETER draw_params[2] = {}; + draw_params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + draw_params[0].Constants = {0, 0, 2}; + draw_params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + draw_params[1].Descriptor = {1, 0}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC draw_root_desc{}; + draw_root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + draw_root_desc.Desc_1_0 = {2, draw_params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + Ref compute_root, draw_root; + for (auto [desc, root] : {std::pair{&compute_root_desc, &compute_root}, std::pair{&draw_root_desc, &draw_root}}) { + const auto blob = serialize_root_signature(*desc); + EXPECT(!blob.empty()); + EXPECT(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root->p)))); + } + + const auto container_a = shader_container(a), container_b = shader_container(b), + container_c = shader_container(c), container_d = shader_container(d), + container_e = shader_container(e), container_vs = shader_container(vs); + const auto make_compute = [&](const std::vector& container, Ref& pso) { + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = compute_root.p; + desc.CS = {container.data(), container.size()}; + return SUCCEEDED(device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso.p))) && pso.p; + }; + const auto make_graphics = [&](bool blend, Ref& pso) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = draw_root.p; + desc.VS = {container_vs.data(), container_vs.size()}; + desc.PS = {container_e.data(), container_e.size()}; + auto& target = desc.BlendState.RenderTarget[0]; + target.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + if (blend) { + target.BlendEnable = TRUE; + target.SrcBlend = target.SrcBlendAlpha = D3D12_BLEND_ONE; + target.DestBlend = target.DestBlendAlpha = D3D12_BLEND_ONE; + target.BlendOp = target.BlendOpAlpha = D3D12_BLEND_OP_ADD; + } + desc.SampleMask = 0xffffffff; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + return SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p))) && pso.p; + }; + const std::uint64_t copies = per_pso ? 4 : 1; // of A while four PSOs of it live + const std::uint64_t draw_copies = per_pso ? 2 : 1; + + // Four PSOs of A: one copy of A's bytes, at one VA, which all four push as their code base. + Ref pso_a[4]; + for (auto& pso : pso_a) EXPECT(make_compute(container_a, pso)); + std::printf("4 compute PSOs of one %zu-byte program: %llu bytes of the arena hold program copies\n", a.size(), + static_cast(used())); + EXPECT(used() == copies * a.size()); + const Copy first = copy_of(pso_a[0].p); + EXPECT(first.bytes == a.size()); + for (const auto& pso : pso_a) { + const Copy copy = copy_of(pso.p); + EXPECT(copy.bytes == a.size() && arena_holds(device.p, copy.va, a)); + EXPECT(per_pso ? (&pso == &pso_a[0] || copy.va != first.va) : copy.va == first.va); + } + + // B: a copy of its own, elsewhere. C: copied too, since its entry does not say. D: no copy. + Ref pso_b, pso_c, pso_d; + EXPECT(make_compute(container_b, pso_b) && make_compute(container_c, pso_c) && make_compute(container_d, pso_d)); + const Copy copy_b = copy_of(pso_b.p), copy_c = copy_of(pso_c.p); + EXPECT(copy_b.bytes == b.size() && copy_b.va != first.va && arena_holds(device.p, copy_b.va, b)); + EXPECT(copy_c.bytes == c.size() && arena_holds(device.p, copy_c.va, c)); + EXPECT(copy_of(pso_d.p).bytes == 0); + EXPECT(used() == copies * a.size() + b.size() + c.size()); + + // Two graphics PSOs whose pixel shader reads its code base: one copy of E's bytes (one per PSO with --per-pso), + // none of the VS's. + Ref draw[2]; + EXPECT(make_graphics(false, draw[0]) && make_graphics(true, draw[1])); + const Copy draw_copy = copy_of(draw[0].p), draw_copy2 = copy_of(draw[1].p); + EXPECT(draw_copy.bytes == e.size() && arena_holds(device.p, draw_copy.va, e)); + EXPECT(draw_copy2.bytes == e.size() && arena_holds(device.p, draw_copy2.va, e)); + EXPECT(per_pso ? draw_copy2.va != draw_copy.va : draw_copy2.va == draw_copy.va); + EXPECT(used() == copies * a.size() + b.size() + c.size() + draw_copies * e.size()); + draw[0].reset(); + EXPECT(settle(8) && arena_holds(device.p, draw_copy2.va, e)); + draw[1].reset(); + EXPECT(settle(7) && used() == copies * a.size() + b.size() + c.size()); + + // Three of A's PSOs go: the fourth keeps its copy, A's bytes still where it reads them. + const Copy last = copy_of(pso_a[3].p); + for (int i = 0; i < 3; ++i) pso_a[i].reset(); + EXPECT(settle(4) && used() == a.size() + b.size() + c.size()); + EXPECT(copy_of(pso_a[3].p).va == last.va && arena_holds(device.p, last.va, a)); + // The last one goes: A's bytes are returned to the arena. + pso_a[3].reset(); + EXPECT(settle(3) && used() == b.size() + c.size()); + // A new PSO of A makes a new copy, which holds A's bytes. + Ref again; + EXPECT(make_compute(container_a, again)); + EXPECT(used() == a.size() + b.size() + c.size() && arena_holds(device.p, copy_of(again.p).va, a)); + again.reset(); + pso_b.reset(); + pso_c.reset(); + pso_d.reset(); + EXPECT(settle(0) && used() == 0); + std::printf("%s: 4 PSOs of one program held %llu copies, 2 graphics PSOs %llu; all bytes returned\n", + per_pso ? "per PSO (LEONIDA_SHARE_CODE_BASE=0)" : "shared", static_cast(copies), + static_cast(draw_copies)); + } + EXPECT(vktest::validation_error_count() == 0); // includes device teardown + std::puts("d3d12_code_base_share_test: PASS"); + return 0; +} diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp index ffbfbf718d..bbf0426f93 100644 --- a/runtime/test/d3d12_draw_test.cpp +++ b/runtime/test/d3d12_draw_test.cpp @@ -80,6 +80,9 @@ static_assert(offsetof(Vertex, wrong_color) == 16); // Positive-only offscreen variant, sharing the translated-shader fixture, root signature and PSO description. int check_stateful_indirect_pixels(ID3D12Device* device, ID3D12RootSignature* root, D3D12_GRAPHICS_PIPELINE_STATE_DESC desc, bool multi, bool counted, bool nonindexed_only); +// Recording only, on the same root signature and PSO description: which draws share a views block (DrawViews). +int check_draw_views_sharing(ID3D12Device* device, ID3D12RootSignature* root, + const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc); int main(int argc, char** argv) { const bool nonindexed_only = argc == 3 && std::strcmp(argv[2], "--nonindexed-only") == 0; @@ -92,6 +95,7 @@ int main(int argc, char** argv) { const bool title_index = argc == 2 && std::strcmp(argv[1], "--title-index-window") == 0; const bool title_vertex = argc == 2 && std::strcmp(argv[1], "--title-vertex-window") == 0; const bool title_window = title_index || title_vertex; + const bool views_sharing = argc == 2 && std::strcmp(argv[1], "--draw-views-sharing") == 0; vktest::Device d; d.request_draw_indirect_first_instance = indirect_pixels; d.request_robust_index_view = indirect_pixels && !nonindexed_only; @@ -243,6 +247,11 @@ int main(int argc, char** argv) { pso_desc.NumRenderTargets = 1; pso_desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; pso_desc.SampleDesc.Count = 1; + if (views_sharing) { + const int result = check_draw_views_sharing(device.p, root.p, pso_desc); + EXPECT(d.validation_errors() == 0); + return result; + } if (indirect_pixels) { const int result = check_stateful_indirect_pixels(device.p, root.p, pso_desc, multi_pixels || count_pixels, count_pixels, nonindexed_only); diff --git a/runtime/test/d3d12_draw_views_sharing.cpp b/runtime/test/d3d12_draw_views_sharing.cpp new file mode 100644 index 0000000000..8f0678f7f4 --- /dev/null +++ b/runtime/test/d3d12_draw_views_sharing.cpp @@ -0,0 +1,128 @@ +// The views block a list records with each draw (leonida::DrawViews: 8 render targets and 32 vertex buffer views, +// about 700 bytes, kept until the list's Reset) is shared by the draws that keep the same render targets and vertex +// buffers. A title that binds the same vertex buffer, or the same render targets, again before every draw gets one +// block, not one per draw. A changed vertex buffer slot, a different render target, or a new descriptor behind the +// same RTV handle still starts a new block that holds the new views. Recording only: nothing is submitted. +// Run by d3d12_draw_test --draw-views-sharing, on its device, root signature and PSO description. No game data. +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" + +#include +#include +#include +#include + +using namespace d3d12test; + +#define CHECK(x) \ + do { \ + if (!(x)) { \ + std::fprintf(stderr, "draw views line %d: %s\n", __LINE__, #x); \ + return 1; \ + } \ + } while (0) + +int check_draw_views_sharing(ID3D12Device* device, ID3D12RootSignature* root, + const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { + Ref pso; + CHECK(SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)))); + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto upload_desc = buffer_desc(2048); + Ref vertices; + CHECK(SUCCEEDED(device->CreateCommittedResource(&upload_heap, {}, &upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&vertices.p)))); + const auto va = vertices->GetGPUVirtualAddress(); + const D3D12_VERTEX_BUFFER_VIEW first{va, 1024, 12}, second{va + 1024, 1024, 12}; + + // Two render targets, each named by the RTV of a heap of its own. + D3D12_RESOURCE_DESC tex{}; + tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + tex.Width = tex.Height = 64; + tex.DepthOrArraySize = tex.MipLevels = 1; + tex.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + tex.SampleDesc.Count = 1; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void*); // heap slot 9: the CPU handle in RAX + Ref targets[2]; + Ref heaps[2]; + D3D12_CPU_DESCRIPTOR_HANDLE rtvs[2]{}; + for (int i = 0; i < 2; ++i) { + CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, {}, &tex, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&targets[i].p)))); + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heaps[i].p)))); + rtvs[i].ptr = SIZE_T(reinterpret_cast(slot(heaps[i].p, 9))(heaps[i].p)); + device->CreateRenderTargetView(targets[i].p, nullptr, rtvs[i]); + } + const D3D12_VIEWPORT viewport{0, 0, 64, 64, 0, 1}; + + Ref allocator; + Ref list; + CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p, + IID_PPV_ARGS(&list.p)))); + list->SetGraphicsRootSignature(root); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->RSSetViewports(1, &viewport); + list->OMSetRenderTargets(1, &rtvs[0], FALSE, nullptr); + constexpr std::size_t repeats = 1000; + for (std::size_t i = 0; i < repeats; ++i) { + list->IASetVertexBuffers(0, 1, &first); // the view slot 0 already holds after the first pass + list->DrawInstanced(3, 1, 0, 0); + } + list->IASetVertexBuffers(0, 1, &second); // [0] slot 0 changes + list->DrawInstanced(3, 1, 0, 0); + list->IASetVertexBuffers(0, 0, nullptr); // [1] no slot written, and the same render target bound again + list->OMSetRenderTargets(1, &rtvs[0], FALSE, nullptr); + list->DrawInstanced(3, 1, 0, 0); + list->IASetVertexBuffers(1, 1, &first); // [2] another slot is bound + list->DrawInstanced(3, 1, 0, 0); + list->IASetVertexBuffers(1, 1, nullptr); // [3] and unbound again + list->DrawInstanced(3, 1, 0, 0); + list->OMSetRenderTargets(1, &rtvs[1], FALSE, nullptr); // [4] another render target + list->DrawInstanced(3, 1, 0, 0); + // [5] The same handle, whose descriptor now names the first target. D3D12 reads the descriptor at + // OMSetRenderTargets, so this is a change as well. + device->CreateRenderTargetView(targets[0].p, nullptr, rtvs[1]); + list->OMSetRenderTargets(1, &rtvs[1], FALSE, nullptr); + list->DrawInstanced(3, 1, 0, 0); + CHECK(list->Close() == S_OK); + + std::vector recorded; + CHECK(rt::d3d12::recorded_commands(list.p, recorded) && recorded.size() == repeats + 6); + std::vector views; + for (const auto& command : recorded) { + const auto* draw = std::get_if(&command); + CHECK(draw && draw->views); + views.push_back(draw->views.get()); + } + const std::set repeated(views.begin(), views.begin() + repeats); + if (repeated.size() != 1) + std::fprintf(stderr, "draw views: %zu blocks for %zu draws that bind the same vertex buffer again\n", + repeated.size(), repeats); + CHECK(repeated.size() == 1); + + const leonida::DrawViews& base = *views[0]; + CHECK(base.render_target_count == 1 && base.render_targets[0].resource); + CHECK(base.vertex_buffers[0].va == va && base.vertex_buffers[0].size == 1024 && + base.vertex_buffers[0].stride == 12); + CHECK(!base.vertex_buffers[1].va); + const leonida::DrawViews* const* changed = views.data() + repeats; + CHECK(changed[0] != &base && changed[0]->vertex_buffers[0].va == va + 1024); + CHECK(changed[0]->render_targets[0].resource == base.render_targets[0].resource); + CHECK(changed[1] == changed[0]); + CHECK(changed[2] != changed[1] && changed[2]->vertex_buffers[1].va == va && + changed[2]->vertex_buffers[0].va == va + 1024); + CHECK(changed[3] != changed[2] && !changed[3]->vertex_buffers[1].va && + changed[3]->vertex_buffers[0].va == va + 1024); + CHECK(changed[4] != changed[3] && changed[4]->render_targets[0].resource && + changed[4]->render_targets[0].resource != base.render_targets[0].resource); + CHECK(changed[4]->render_target_count == 1 && changed[4]->vertex_buffers[0].va == va + 1024); + CHECK(changed[5] != changed[4] && changed[5]->render_targets[0].resource == base.render_targets[0].resource); + const std::set all(views.begin(), views.end()); + CHECK(all.size() == 6); + std::printf("draw views: %zu draws that bind the same vertex buffer again share 1 block; a changed slot, render " + "target or RTV descriptor starts a new one (%zu blocks for %zu draws)\n", + repeats, all.size(), views.size()); + return 0; +} diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 1d940a7e48..dcfc14835b 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -4,7 +4,8 @@ // on the host devices too. With VK_EXT_external_memory_host, OpenExistingHeapFromAddress on real host memory is // compared case by case with the host devices (open_cases: RTX 4090 and WARP agree), and a heap is opened on a // committed range; without it, the device reports EXISTING_HEAPS unsupported and answers an accepted range E_NOTIMPL. -// No shaders or game data. +// Each Vulkan-backed device goes with the test's last reference to it (release_device), and under +// LEONIDA_VK_VALIDATION=1 vkDestroyDevice must find nothing left over. No shaders or game data. // https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromaddress #include "../shims/title_gpu_placements.h" #include "../shims/xg_xs_layout.h" @@ -20,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -1658,6 +1660,324 @@ int check_placed_view_map_changes(ID3D12Device* device) { return 0; } +// What the slot-70 image checks below share: textures of 64 KiB the title writes into its memory and names through +// slot-70 views, submissions (the registry's refresh pass runs before each) and what the registry holds. +struct TitleImageBench { + static constexpr UINT width = 256, height = 256; + static constexpr SIZE_T texture_bytes = width * height; + const char* who = nullptr; + ID3D12Device* device = nullptr; + GpuReader gpu; + D3D12_RESOURCE_DESC desc{}; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + rt::d3d12::OwnedTitleImages start{}; + + int init(ID3D12Device* d, const char* name) { + device = d; + who = name; + EXPECT(!gpu.init(device, 4096)); + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + srv.Format = desc.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Texture2D.MipLevels = 1; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + start = images(); + return 0; + } + // The title writes the bytes of the texture at `at` (unless `write` is false: it wrote them already, or the pages + // are not there), then names it. + bool name(std::uint8_t* at, unsigned seed, leonida::gfx10::ImageWords& slot, bool write = true) { + if (write) + for (SIZE_T i = 0; i < texture_bytes; ++i) at[i] = pattern_byte(i, seed); + std::array resource{}; + std::array words{}; + std::memcpy(resource.data(), &desc, sizeof(desc)); + std::memcpy(words.data(), &srv, sizeof(srv)); + return rt::d3d12::write_placed_texture_view(device, false, resource.data(), words.data(), + reinterpret_cast(at), + {reinterpret_cast(slot.data())}); + } + bool index(const leonida::gfx10::ImageWords& descriptor) const { + std::uint32_t key[8]; + std::memcpy(key, descriptor.data(), sizeof(key)); + return rt::d3d12::bindless_hash_lookup(device, key); + } + int submit() { + ID3D12CommandList* lists[]{gpu.list.p}; + gpu.queue->ExecuteCommandLists(1, lists); + EXPECT_HR(gpu.queue->Signal(gpu.fence.p, ++gpu.fence_value), S_OK); + EXPECT_HR(gpu.fence->SetEventOnCompletion(gpu.fence_value, gpu.done), S_OK); + EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); + return 0; + } + // The image at `at` holds the texels of `seed`. + int texels(std::uint8_t* at, unsigned seed) const { + Ref image; + image.p = rt::d3d12::owned_title_image(device, reinterpret_cast(at)); + EXPECT(image.p); + std::vector got(texture_bytes); + EXPECT_HR(image->ReadFromSubresource(got.data(), width, UINT(texture_bytes), 0, nullptr), S_OK); + for (SIZE_T i = 0; i < texture_bytes; ++i) + if (got[i] != pattern_byte(i, seed)) { + std::fprintf(stderr, "%s: texel %zu of the image at %p is %u, expected %u\n", who, i, + static_cast(at), unsigned(got[i]), unsigned(pattern_byte(i, seed))); + return 1; + } + return 0; + } + rt::d3d12::OwnedTitleImages images() const { return rt::d3d12::owned_title_images(device); } + std::uint64_t owned() const { return images().owned - start.owned; } + std::uint64_t looks() const { return images().looks - start.looks; } + std::uint64_t gone() const { return images().gone - start.gone; } +}; + +// The images the layer makes for slot-70 texture views of the title's memory have a lifetime (the +// d3d12_title_image_retire test, with LEONIDA_TITLE_IMAGE_IDLE_MS=0 and LEONIDA_TITLE_IMAGE_CHECKS=4). A streaming +// title places its textures at ever new addresses of the same memory: here 16 textures of 64 KiB, each 4 KiB after +// the one before, in one committed range. An image a newer texture covers, or whose pages have all gone, and that no +// view named since, is retired at the next submission; before, each address named kept its image, and its bindless +// index, for the device's life. An image a view names again after a newer texture covered it is kept (two views of +// the same bytes in use). A texture named again after its image was retired gets a new one with its texels, and the +// T# its first view wrote finds it again. A slot-133 texture the title places over an image's bytes retires it once +// a slot-70 view gives it its layout, not with the guess from its description. An image never filled stays when its +// pages go. A change anywhere in the address space (title_memory_map::changed() with no range, which DirectStorage +// transfers record) does not make the pass look at every image's pages, and a change over many images has them +// looked at a few a pass. +int check_title_image_retirement(ID3D12Device* device) { + TitleImageBench b; + const char* who = "slot-70 image retirement"; + EXPECT(!b.init(device, who)); + constexpr SIZE_T texture_bytes = TitleImageBench::texture_bytes, step = 4096, bytes = 1 << 20; + constexpr unsigned count = 16, checks = 4; // LEONIDA_TITLE_IMAGE_CHECKS, set by main + auto* pages = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(pages); + const auto room = rt::d3d12::bindless_room(device).images_2d; + + // 1. Sixteen textures over the same memory, one after the other: one image is left, the last one. + leonida::gfx10::ImageWords first{}, slot{}; + for (unsigned i = 0; i < count; ++i) { + EXPECT(b.name(pages + i * step, i, i ? slot : first)); + if (!i) EXPECT(b.index(first)); // published at its fill... + EXPECT(!b.submit()); + } + EXPECT(!b.submit() && !b.submit()); + const auto streamed = b.images(); + std::printf("%s: %u textures named over the same memory: %llu images (%llu KiB), %llu retired, %llu of them under " + "a newer texture; %u bindless 2D indices taken\n", + who, count, static_cast(streamed.owned - b.start.owned), + static_cast((streamed.owned_bytes - b.start.owned_bytes) >> 10), + static_cast(streamed.retired - b.start.retired), + static_cast(streamed.superseded - b.start.superseded), + room - rt::d3d12::bindless_room(device).images_2d); + EXPECT(streamed.owned - b.start.owned == 1); + EXPECT(streamed.owned_bytes - b.start.owned_bytes <= 2 * texture_bytes); + EXPECT(streamed.superseded - b.start.superseded == count - 1); + EXPECT(room - rt::d3d12::bindless_room(device).images_2d <= 1); + EXPECT(!b.index(first)); // ...so its T# finds nothing + EXPECT(!b.texels(pages + (count - 1) * step, count - 1)); + + // 2. The first texture named again: a new image with its texels, which the T# of its first view finds again. + EXPECT(b.name(pages, 0, slot)); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && !b.texels(pages, 0)); + EXPECT(slot == first && b.index(first)); + + // 3. A view names it again after a newer texture covered half of it: both stay, at every submission. + leonida::gfx10::ImageWords newer{}; + const auto named_again = b.images().named_again; + EXPECT(b.name(pages + 8 * step, 8, newer)); + EXPECT(b.name(pages, 0, slot)); + EXPECT(!b.submit() && !b.submit()); + EXPECT(b.owned() == 2 && b.index(first) && b.index(newer)); + EXPECT(b.images().named_again - named_again == 1); + + // 4. A third texture over both, named alone: it is the one image left. + EXPECT(b.name(pages + 12 * step, 12, slot)); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && !b.index(first) && !b.index(newer) && b.index(slot) && !b.texels(pages + 12 * step, 12)); + + // 5. Its pages decommitted: no image is left. + EXPECT(VirtualFree(pages, bytes, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(pages, bytes); + EXPECT(!b.submit()); + EXPECT(b.owned() == 0 && b.gone() == 1); + + // 6. The pages back, and a texture named there again: it has an image and its texels. + EXPECT(VirtualAlloc(pages, bytes, MEM_COMMIT, PAGE_READWRITE) == pages); + leonida::title_memory_map::changed(pages, bytes); + EXPECT(b.name(pages, 0, slot)); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && !b.texels(pages, 0) && b.index(first)); + + // 7. A slot-133 texture the title places over its bytes: the Layout 0 of its description is a guess, which may be + // larger than what the title placed, and covers nothing. A slot-70 view of it gives it its layout, and the image + // under it is retired. + { + Ref placed; + D3D12_RESOURCE_DESC placed_desc = b.desc; + placed_desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + std::uint8_t* const at = pages + 65536 - 2 * step; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, at, placed_desc, 0, IID_PPV_ARGS(&placed.p)), S_OK); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && b.index(first)); + leonida::gfx10::ImageWords placed_view{}; + EXPECT(b.name(at, 7, placed_view)); + EXPECT(!b.submit()); + EXPECT(b.owned() == 0 && !b.index(first)); + } + + // 8. A texture named before its pages came has an image never filled: it stays when a change over its pages + // finds none, and is filled once they come and a view names it again. + auto* hold = static_cast(VirtualAlloc(nullptr, texture_bytes, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(hold); + leonida::gfx10::ImageWords pending{}; + EXPECT(b.name(hold, 0, pending, false)); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1); + leonida::title_memory_map::changed(hold, texture_bytes); + EXPECT(!b.submit() && !b.submit()); + EXPECT(b.owned() == 1 && b.gone() == 1); + EXPECT(VirtualAlloc(hold, texture_bytes, MEM_COMMIT, PAGE_READWRITE) == hold); + for (SIZE_T i = 0; i < texture_bytes; ++i) hold[i] = pattern_byte(i, 3); + leonida::title_memory_map::changed(hold, texture_bytes); + EXPECT(!b.submit()); + EXPECT(b.name(hold, 3, pending, false)); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && !b.texels(hold, 3)); + + // 9. Twelve textures side by side, none over another, filled. + constexpr unsigned side = 12; + constexpr SIZE_T apart = 80 << 10; + auto* spread = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(spread); + std::vector views(side); + for (unsigned i = 0; i < side; ++i) EXPECT(b.name(spread + i * apart, 20 + i, views[i])); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 + side && b.images().candidates == 0); + // A change anywhere: no image is looked at, as no page of theirs is known to have changed. + const auto looks = b.looks(); + leonida::title_memory_map::changed(); + EXPECT(!b.submit()); + std::printf("%s: a change anywhere with %u images in the registry: %llu looks at their pages, %llu left to look " + "at\n", + who, 1 + side, static_cast(b.looks() - looks), + static_cast(b.images().candidates)); + EXPECT(b.looks() == looks && b.images().candidates == 0 && b.owned() == 1 + side); + // A change over all twelve: their pages are looked at, at most `checks` a pass, and all are still there. + leonida::title_memory_map::changed(spread, bytes); + for (unsigned pass = 0; pass * checks < side; ++pass) { + EXPECT(!b.submit()); + const auto seen = b.looks() - looks; + std::printf("%s: a change over %u images, pass %u: %llu looks at their pages\n", who, side, pass + 1, + static_cast(seen)); + EXPECT(seen == std::min(side, (pass + 1) * checks)); + } + EXPECT(b.owned() == 1 + side && b.images().candidates == 0 && b.gone() == 1); + // Their pages decommitted: they go, a few a pass. + EXPECT(VirtualFree(spread, bytes, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(spread, bytes); + EXPECT(!b.submit()); + EXPECT(b.gone() == 1 + checks); + EXPECT(!b.submit() && !b.submit()); + EXPECT(b.owned() == 1 && b.gone() == 1 + side); + EXPECT(VirtualFree(hold, texture_bytes, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(hold, texture_bytes); + EXPECT(!b.submit()); + EXPECT(b.owned() == 0); + + // The retired images' memory is freed once no submission can still read them (3 s after their retirement). + Sleep(3100); + EXPECT(!b.submit()); + const auto end = b.images(); + std::printf("%s: %llu images retired in all (%llu under a newer texture, %llu with their pages gone), %llu still " + "waiting for the GPU\n", + who, static_cast(end.retired - b.start.retired), + static_cast(end.superseded - b.start.superseded), + static_cast(end.gone - b.start.gone), + static_cast(end.waiting)); + EXPECT(end.waiting == 0 && end.owned == b.start.owned); + VirtualFree(spread, 0, MEM_RELEASE); + VirtualFree(hold, 0, MEM_RELEASE); + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + +// The idle time of the slot-70 images (the d3d12_title_image_idle test, LEONIDA_TITLE_IMAGE_IDLE_MS=500). An image a +// newer texture covers stays while a view named it less than that long ago, and goes after; one a view names again in +// that time is no longer covered. An image whose pages went stays that long after the look that found them gone. A +// view that names it meanwhile keeps it, until a later change over its pages finds them still gone. +int check_title_image_idle(ID3D12Device* device) { + TitleImageBench b; + const char* who = "slot-70 image idle time"; + EXPECT(!b.init(device, who)); + using clock = std::chrono::steady_clock; + constexpr auto idle = std::chrono::milliseconds(500); // LEONIDA_TITLE_IMAGE_IDLE_MS, set by main + constexpr SIZE_T half = 32 << 10, bytes = 1 << 20, upper = bytes / 2; + auto* pages = static_cast(VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(pages); + const auto superseded = [&] { return b.images().superseded - b.start.superseded; }; + + // x and y, then a newer texture over the second half of each. + leonida::gfx10::ImageWords x{}, x2{}, y{}, y2{}; + const auto named = clock::now(); + EXPECT(b.name(pages, 1, x) && b.name(pages + half, 2, x2)); + EXPECT(b.name(pages + upper, 3, y) && b.name(pages + upper + half, 4, y2)); + EXPECT(!b.submit()); + if (clock::now() - named < idle) + EXPECT(b.owned() == 4 && superseded() == 0); + else + std::printf("%s: the first submission came after the idle time; its check is skipped\n", who); + // x named again: no longer covered. y, not named for longer than the idle time, goes. + Sleep(250); + EXPECT(b.name(pages, 1, x, false)); + Sleep(400); + EXPECT(!b.submit()); + EXPECT(b.owned() == 3 && superseded() == 1 && b.index(x) && !b.index(y)); + Sleep(600); + EXPECT(!b.submit()); + EXPECT(b.owned() == 3 && b.index(x) && b.index(x2) && b.index(y2)); + + // The pages of x and x2 decommitted: they stay for the idle time, then go. + EXPECT(VirtualFree(pages, upper, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(pages, upper); + const auto gone = clock::now(); + EXPECT(!b.submit()); + if (clock::now() - gone < idle) EXPECT(b.owned() == 3 && b.gone() == 0); + Sleep(700); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && b.gone() == 2 && b.index(y2)); + + // Those of y2 decommitted, and y2 named again before the idle time: it stays, while no change over its pages + // comes. A later one finds them still gone, and it goes the idle time after. + EXPECT(VirtualFree(pages + upper, upper, MEM_DECOMMIT) != FALSE); + leonida::title_memory_map::changed(pages + upper, upper); + EXPECT(!b.submit()); + EXPECT(b.name(pages + upper + half, 4, y2, false)); + Sleep(700); + EXPECT(!b.submit()); + EXPECT(b.owned() == 1 && b.gone() == 2); + leonida::title_memory_map::changed(pages + upper, upper); + EXPECT(!b.submit()); + Sleep(700); + EXPECT(!b.submit()); + EXPECT(b.owned() == 0 && b.gone() == 3); + std::printf("%s: %llu images retired under a newer texture and %llu with their pages gone, each after the idle " + "time\n", + who, static_cast(superseded()), static_cast(b.gone())); + // Their memory is freed 3 s after their retirement; an image still waiting at the end would keep the device. + Sleep(3100); + EXPECT(!b.submit()); + EXPECT(b.images().waiting == 0); + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + // A persistent Map can become readable without notifying xmem or calling Map a second time. int check_mapped_plane(ID3D12Device* device) { const char* who = "persistent slot-133 plane"; @@ -1753,6 +2073,73 @@ int check_mapped_plane_first_use(ID3D12Device* device) { return 0; } +// The refresh worker's pass after the texel writes noted so far (LEONIDA_TEXTURE_REFRESH_ASYNC=1): submissions wake the +// worker (a busy one can miss a request) until a pass has taken the writes, and title_texture_registry, read under the +// registry's lock, returns once that pass is over. +int wait_async_refresh(ID3D12Device* device, GpuReader& gpu) { + const char* who = "async texture refresh"; + auto& writes = leonida::title_texel_writes::state(); + ID3D12CommandList* lists[]{gpu.list.p}; + for (int i = 0; i < 2000 && writes.pending.load(std::memory_order_acquire); ++i) { + gpu.queue->ExecuteCommandLists(1, lists); + EXPECT_HR(gpu.queue->Signal(gpu.fence.p, ++gpu.fence_value), S_OK); + EXPECT_HR(gpu.fence->SetEventOnCompletion(gpu.fence_value, gpu.done), S_OK); + EXPECT(WaitForSingleObject(gpu.done, 30000) == WAIT_OBJECT_0); + Sleep(1); + } + EXPECT(!writes.pending.load(std::memory_order_acquire)); + rt::d3d12::title_texture_registry(device); + return 0; +} + +// LEONIDA_TEXTURE_REFRESH_ASYNC=1 (the d3d12_mapped_plane_async test): a mapped slot-133 texture destroyed while its +// thread held the registry's lock (a slot-70 view overwrote the descriptor that held its last reference) leaves +// nothing in the async refresh's range index or mapped list once drain_titles_gone removes its entry. A key left in +// the index made the next pass that saw a write over the texture's memory look the gone entry up with +// title_textures.at(), and the std::out_of_range ended the process on the refresh worker +// (RT-TITLE-TEXTURE-GONE-RANGES). +int check_mapped_plane_gone_in_registry(ID3D12Device* device) { + const char* who = "mapped slot-133 plane destroyed inside the registry"; + constexpr UINT width = 256, height = 8, size = width * height; + void* pages = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + EXPECT(pages); + std::memset(pages, 29, size); + GpuReader gpu; + EXPECT(!gpu.init(device, size)); + const auto before = rt::d3d12::title_texture_registry(device); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.Format = DXGI_FORMAT_R8_UNORM; + desc.SampleDesc.Count = desc.DepthOrArraySize = desc.MipLevels = 1; + leonida::title_xg_layouts::note({UINT(desc.Dimension), UINT(desc.Format), height, 1, 1, width}, 1); + ID3D12Resource* texture = nullptr; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 6, IID_PPV_ARGS(&texture)), S_OK); + void* mapped = nullptr; + EXPECT_HR(texture->Map(0, nullptr, &mapped), S_OK); + EXPECT(mapped == pages); + const auto registered = rt::d3d12::title_texture_registry(device); + EXPECT(registered.textures == before.textures + 1 && registered.ranges == before.ranges + 1 && + registered.mapped == before.mapped + 1); + // One pass first: the worker's first pass looks at every texture, a later one only at those a write overlaps. + leonida::title_texel_writes::note(pages, size); + EXPECT(!wait_async_refresh(device, gpu)); + EXPECT(rt::d3d12::release_in_title_registry(device, texture)); + // The title writes those pages again, and submits. + std::memset(pages, 41, size); + leonida::title_texel_writes::note(pages, size); + EXPECT(!wait_async_refresh(device, gpu)); + const auto after = rt::d3d12::title_texture_registry(device); + std::printf("%s: %llu textures, %llu range keys, %llu mapped after it went (%llu, %llu, %llu before it)\n", who, + static_cast(after.textures), static_cast(after.ranges), + static_cast(after.mapped), static_cast(before.textures), + static_cast(before.ranges), static_cast(before.mapped)); + EXPECT(after.textures == before.textures && after.ranges == before.ranges && after.mapped == before.mapped); + VirtualFree(pages, 0, MEM_RELEASE); + return 0; +} + // Several threads write the same watched pages while submissions keep making them read-only again. Two threads that // fault on one page race: the first fault reopens it, a submission can protect it again before the second fault is // handled, and the second write must still be retried, not refused (refused, the process ends: seen natively). After @@ -2387,13 +2774,32 @@ void print_cases(const std::vector& cases, const char* who) { int(c.desc.Properties.CPUPageProperty), int(c.desc.Properties.MemoryPoolPreference), unsigned(c.desc.Flags)); } -} // namespace -int main(int argc, char** argv) { +// The test's last reference to a device destroys it: nothing the layer made for it keeps it alive, such as the images +// made for slot-70 views, live or retired (a retired one is released at the first refresh pass 3 s later, which a +// device released before then never reaches). Otherwise the device and all its Vulkan objects outlive the test and +// vkDestroyDevice reports them (VUID-vkDestroyDevice-device-05137). +int release_device(Ref& device, const char* who) { + const ULONG left = device.p->Release(); + device.p = nullptr; + EXPECT(left == 0); + return 0; +} + +int run(int argc, char** argv) { const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0; const bool async_plane = argc == 2 && std::strcmp(argv[1], "--mapped-plane-async") == 0; - if (argc != 1 && !prefix_only && !async_plane) return 2; + const bool image_retire = argc == 2 && std::strcmp(argv[1], "--title-image-retire") == 0; + const bool image_idle = argc == 2 && std::strcmp(argv[1], "--title-image-idle") == 0; + if (argc != 1 && !prefix_only && !async_plane && !image_retire && !image_idle) return 2; if (async_plane) _putenv_s("LEONIDA_TEXTURE_REFRESH_ASYNC", "1"); // read once, at the device's first refresh + // An image no view named since a newer texture covered it, or since its pages went, goes at the next pass; a pass + // visits at most 4 of those that may go. + if (image_retire) { + _putenv_s("LEONIDA_TITLE_IMAGE_IDLE_MS", "0"); + _putenv_s("LEONIDA_TITLE_IMAGE_CHECKS", "4"); + } + if (image_idle) _putenv_s("LEONIDA_TITLE_IMAGE_IDLE_MS", "500"); _putenv_s("LEONIDA_TITLE_TEXTURE_PERIOD_MS", "0"); _putenv_s("LEONIDA_TITLE_TEXTURE_CHECK_KB", "0"); vktest::Device vk; @@ -2418,16 +2824,34 @@ int main(int argc, char** argv) { if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; if (prefix_only) { if (!vk.host_pointer_alignment) return 77; - const int result = check_host_prefix_buffers(ours.p); + int result = check_host_prefix_buffers(ours.p); + result += release_device(ours, "vulkan device"); return result || vk.validation_errors() ? 1 : 0; } if (async_plane) { int result = vk.host_image_copy ? check_mapped_plane_first_use(ours.p) : 0; + result += check_mapped_plane_gone_in_registry(ours.p); auto no_host_copy = info; // the staged upload too no_host_copy.host_image_copy = false; Ref staged; if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; result += check_mapped_plane_first_use(staged.p); + result += release_device(staged, "staged device"); + result += release_device(ours, "vulkan device"); + return result || vk.validation_errors() ? 1 : 0; + } + if ((image_retire || image_idle) && !rt::d3d12::bindless_set_layout(ours.p)) return 77; + if (image_idle) { + const int result = check_title_image_idle(ours.p); + return result || vk.validation_errors() ? 1 : 0; + } + if (image_retire) { + int result = check_title_image_retirement(ours.p); + auto no_host_copy = info; // the staged upload too + no_host_copy.host_image_copy = false; + Ref staged; + if (FAILED(rt::d3d12::create_vulkan_device(no_host_copy, IID_PPV_ARGS(&staged.p)))) return 1; + result += check_title_image_retirement(staged.p); return result || vk.validation_errors() ? 1 : 0; } failures += check(ours.p, "vulkan"); @@ -2455,6 +2879,7 @@ int main(int argc, char** argv) { failures += check_shared_bc_placements(staged.p, true); failures += check_mapped_plane(staged.p); failures += check_mapped_bc_array(staged.p); + failures += release_device(staged, "staged device"); } failures += check_written_pages_all(ours.p); { @@ -2468,6 +2893,7 @@ int main(int argc, char** argv) { failures += check_write_watched(ours.p, second.p, modifier); failures += check_rereserved(ours.p); } + if (second.p) failures += release_device(second, "second device"); } failures += check_heap_lock_faults(ours.p); Ref factory; @@ -2485,6 +2911,7 @@ int main(int argc, char** argv) { if (vk.host_pointer_alignment) failures += compare_cases(vulkan_cases, host_cases, who.c_str()); } } + failures += release_device(ours, "vulkan device"); } if (vk.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", vk.validation_errors()); @@ -2492,3 +2919,16 @@ int main(int argc, char** argv) { } return failures ? 1 : 0; } +} // namespace + +int main(int argc, char** argv) { + // run's vktest::Device destroys the Vulkan device on return, so what vkDestroyDevice finds left over + // (VUID-vkDestroyDevice-device-05137 under LEONIDA_VK_VALIDATION=1) is counted here. + const int result = run(argc, argv); + if (result) return result; + if (const unsigned errors = vktest::validation_error_count()) { + std::fprintf(stderr, "%u validation errors at teardown\n", errors); + return 1; + } + return 0; +} diff --git a/runtime/test/d3d12_shadow_gpu_releases_test.cpp b/runtime/test/d3d12_shadow_gpu_releases_test.cpp new file mode 100644 index 0000000000..ea463dd98a --- /dev/null +++ b/runtime/test/d3d12_shadow_gpu_releases_test.cpp @@ -0,0 +1,168 @@ +// LEONIDA_SHADOW_GPU=1 without LEONIDA_CONSOLE_HEAP_GPU (RT-SHADOW-GPU-RELEASED-RANGES): the device makes the +// console heaps' GPU pass object for the shadows' copies alone, and the pass itself never runs, so nothing may keep +// the arena ranges released and the alias ranges removed for it: only the pass takes those lists, at the start of a +// submission that runs it. Before, every arena release added two entries (backing() ran twice for it), a slot-133 +// import added one for its backing and one for its alias range, and both lists grew for as long as the process ran. +// Checked on the Vulkan-backed device: committed buffers and slot-133 buffers made and released, with submissions +// between, leave nothing waiting. With --console-heap-gpu (LEONIDA_CONSOLE_HEAP_GPU=1) the pass still gets one entry +// per arena release, and the next submission takes them all. Both release the device at the end, which owns its +// VkDevice here: the pass's pipeline and buffers were destroyed after it before, a fault in ~ConsoleHeapGpu. No game +// data. LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation. +#include "../shims/d3d12_com.h" + +#include +#include +#include +#include + +namespace { +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + T* operator->() const { return p; } + void reset() { + if (p) p->Release(); + p = nullptr; + } +}; + +D3D12_RESOURCE_DESC buffer(UINT64 bytes) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return desc; +} + +// An empty command list, executed and waited for: what runs before every submission runs (refresh_console_heaps). +struct Submitter { + Ref queue; + Ref allocator; + Ref list; + Ref fence; + HANDLE done = nullptr; + UINT64 value = 0; + ~Submitter() { + if (done) CloseHandle(done); + } + bool init(ID3D12Device* device) { + D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + return done && SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue.p))) && + SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) && + SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p))) && + SUCCEEDED(list->Close()) && + SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))); + } + bool submit() { + ID3D12CommandList* lists[]{list.p}; + queue->ExecuteCommandLists(1, lists); + return SUCCEEDED(queue->Signal(fence.p, ++value)) && SUCCEEDED(fence->SetEventOnCompletion(value, done)) && + WaitForSingleObject(done, 30000) == WAIT_OBJECT_0; + } +}; + +// `count` committed buffers made and released: as many arena releases. +bool churn_committed(ID3D12Device* device, unsigned count) { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC desc = buffer(64 << 10); + for (unsigned i = 0; i < count; ++i) { + Ref made; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&made.p)))) + return false; + } + return true; +} +} // namespace + +int main(int argc, char** argv) { + const bool heap_pass = argc == 2 && std::strcmp(argv[1], "--console-heap-gpu") == 0; + if (argc != 1 && !heap_pass) return 2; + // Both are read once, when the device is made. An empty value removes the variable. + _putenv_s("LEONIDA_SHADOW_GPU", "1"); + _putenv_s("LEONIDA_CONSOLE_HEAP_GPU", heap_pass ? "1" : ""); + Ref device; + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p))) || !device.p) { + std::printf("SKIP: no Vulkan device\n"); + return 77; // ctest skips + } + if (!rt::d3d12::device_arena_size(device.p) || !rt::d3d12::console_heap_gpu_pending(device.p).made) { + std::printf("SKIP: no GPU address arena, or the console heap pass could not be made on this device\n"); + return 77; + } + Submitter gpu; + if (!gpu.init(device.p) || !gpu.submit()) { + std::printf("FAIL: a queue and an empty command list\n"); + return 1; + } + constexpr unsigned kRounds = 16, kBuffers = 64; + int failures = 0; + + if (heap_pass) { + // The pass runs at every submission: one entry per release (not two), all taken by the next submission. + const auto before = rt::d3d12::console_heap_gpu_pending(device.p); + if (!churn_committed(device.p, kBuffers)) { + std::printf("FAIL: CreateCommittedResource\n"); + return 1; + } + const auto released = rt::d3d12::console_heap_gpu_pending(device.p); + std::printf("LEONIDA_CONSOLE_HEAP_GPU=1: %u buffers released: %llu ranges waiting (%llu before)\n", kBuffers, + static_cast(released.released), + static_cast(before.released)); + if (released.released - before.released != kBuffers) { + std::printf("FAIL: an arena release is not one range for the pass\n"); + ++failures; + } + if (!gpu.submit()) { + std::printf("FAIL: a submission\n"); + return 1; + } + const auto after = rt::d3d12::console_heap_gpu_pending(device.p); + std::printf("after a submission: %llu released ranges, %llu removed alias ranges waiting\n", + static_cast(after.released), static_cast(after.removed)); + if (after.released || after.removed) { + std::printf("FAIL: the pass did not take what was released\n"); + ++failures; + } + if (!failures) std::printf("console heap pass: the released ranges are taken at the next submission\n"); + return failures ? 1 : 0; + } + + // Slot-133 buffers on pages of our own (an import and its alias range each, where the driver imports them). + constexpr SIZE_T kPages = 64 << 10; + void* pages = VirtualAlloc(nullptr, kPages, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!pages) return 1; + unsigned placed = 0; + for (unsigned round = 0; round < kRounds && !failures; ++round) { + if (!churn_committed(device.p, kBuffers)) { + std::printf("FAIL: CreateCommittedResource\n"); + ++failures; + } + Ref title; + if (SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, pages, buffer(kPages), 0xFFFFFFFFu, + IID_PPV_ARGS(&title.p)))) + ++placed; + title.reset(); + if (!gpu.submit()) { + std::printf("FAIL: a submission\n"); + ++failures; + } + } + VirtualFree(pages, 0, MEM_RELEASE); + const auto pending = rt::d3d12::console_heap_gpu_pending(device.p); + std::printf("LEONIDA_SHADOW_GPU=1 alone: %u committed and %u slot-133 buffers released over %u submissions: %llu " + "released ranges and %llu removed alias ranges waiting\n", + kRounds * kBuffers, placed, kRounds, static_cast(pending.released), + static_cast(pending.removed)); + if (pending.released || pending.removed) { + std::printf("FAIL: ranges are kept for a console heap pass that never runs\n"); + ++failures; + } + if (!failures) std::printf("shadow GPU copies: nothing is kept for the console heap pass\n"); + return failures ? 1 : 0; +} diff --git a/runtime/test/d3d12_title_buffer_fallback_test.cpp b/runtime/test/d3d12_title_buffer_fallback_test.cpp new file mode 100644 index 0000000000..4c5571109d --- /dev/null +++ b/runtime/test/d3d12_title_buffer_fallback_test.cpp @@ -0,0 +1,268 @@ +// A vertex or index view that names the title's own memory gets a buffer made over those pages (make_title_buffer, +// TitleVaAliases::want_buffer), the way slot 133 makes one: the pages imported, or a shadow copied from them. When +// neither can be made, slot 133's last resort is an ordinary DEFAULT buffer, which has neither the title's VA nor its +// bytes. A view must not keep such a buffer: it does not cover the view, so the next IASetVertexBuffers of the same +// view would make another, each holding device memory and a device reference until the device goes, until +// LEONIDA_TITLE_BUFFERS_MB is used up and no new title view is resolved for the rest of the session. Nor is such a +// buffer made only to be let go: it would take device-local memory at every try, under the pressure that refused the +// shadow. +// - The arena is filled first (LEONIDA_ARENA_MB=16, filled with 64 KiB buffers, so no slice is left for a shadow) +// and host-visible allocations are refused (the test wraps vkAllocateMemory behind the instance-proc pointer it +// hands the layer), with LEONIDA_SLOT133_IMPORT=0: no import and no shadow can be made, but a device-local DEFAULT +// buffer could. +// - The same 2 MiB view of title memory bound 16 times, as vertex and index views, keeps no buffer (every buffer +// made over title memory holds a device reference, and the device's count does not grow) and is tried once: one +// buffer of its size is created, the shadow's, and no device-local memory of its size is allocated. +// - A second, 512 KiB view bound right after that refusal is not tried: after a refusal no range is tried for a +// second, whichever range it is. +// - After that second the first view is tried again, once, and refused again. 1.5 s later the second view is tried, +// but the first is not: a range refused again waits twice as long. After that it is tried once more. +// Needs a device-local memory type that is not host-visible (skipped otherwise). Synthetic data only. Set +// LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../src/title_va_alias.h" + +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +template +struct Ref { + T* p = nullptr; + Ref() = default; + Ref(const Ref&) = delete; // a copy would release the same interface twice + Ref& operator=(const Ref&) = delete; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +constexpr UINT large_bytes = 2u << 20, small_bytes = 512u << 10; // the two views; no other buffer has these sizes + +// The Vulkan calls the layer makes, seen through the function pointers it loads. +PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; +PFN_vkGetDeviceProcAddr real_device_proc = nullptr; +PFN_vkAllocateMemory real_allocate = nullptr; +PFN_vkCreateBuffer real_create_buffer = nullptr; +VkPhysicalDeviceMemoryProperties memory{}; +std::atomic refuse_host_visible{false}; +std::atomic large_buffers{0}, small_buffers{0}; // buffers of each view's size created +std::atomic device_allocations{0}; // device-local allocations of at least the smaller view's size, made + // while host-visible ones are refused + +VKAPI_ATTR VkResult VKAPI_CALL allocate(VkDevice device, const VkMemoryAllocateInfo* info, + const VkAllocationCallbacks* allocator, VkDeviceMemory* out) { + if (refuse_host_visible.load() && info->memoryTypeIndex < memory.memoryTypeCount) { + const VkMemoryPropertyFlags flags = memory.memoryTypes[info->memoryTypeIndex].propertyFlags; + if (flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) return VK_ERROR_OUT_OF_DEVICE_MEMORY; + if ((flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && info->allocationSize >= small_bytes) ++device_allocations; + } + return real_allocate(device, info, allocator, out); +} + +VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice device, const VkBufferCreateInfo* info, + const VkAllocationCallbacks* allocator, VkBuffer* buffer) { + if (info->size == large_bytes) ++large_buffers; + if (info->size == small_bytes) ++small_buffers; + return real_create_buffer(device, info, allocator, buffer); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) { + if (std::strcmp(name, "vkAllocateMemory") == 0) { + real_allocate = reinterpret_cast(real_device_proc(device, name)); + return real_allocate ? reinterpret_cast(&allocate) : nullptr; + } + if (std::strcmp(name, "vkCreateBuffer") == 0) { + real_create_buffer = reinterpret_cast(real_device_proc(device, name)); + return real_create_buffer ? reinterpret_cast(&create_buffer) : nullptr; + } + return real_device_proc(device, name); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) { + if (std::strcmp(name, "vkGetDeviceProcAddr") == 0) { + real_device_proc = reinterpret_cast(real_instance_proc(instance, name)); + return real_device_proc ? reinterpret_cast(&device_proc) : nullptr; + } + return real_instance_proc(instance, name); +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return desc; +} + +// The device's reference count: every buffer the device keeps over title memory holds one. +ULONG references(ID3D12Device* device) { + device->AddRef(); + return device->Release(); +} + +} // namespace + +int main() { + vktest::Device vk; + if (!vk.create()) return 77; + real_instance_proc = vk.instance_proc; + reinterpret_cast( + vk.instance_proc(vk.instance, "vkGetPhysicalDeviceMemoryProperties"))(vk.physical, &memory); + bool device_only = false; + for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) + device_only |= (memory.memoryTypes[i].propertyFlags & + (VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) == + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + if (!device_only) { + std::fprintf(stderr, "SKIP: every device-local memory type is host-visible\n"); + return 77; + } + + // Title memory of 4 MiB: the large view is its first 2 MiB, the small one starts 3 MiB in (another range). + constexpr UINT title_bytes = 4u << 20; + auto& aliases = leonida::title_va_aliases(); + void* pages = VirtualAlloc(nullptr, title_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + EXPECT(pages); + const auto title_va = reinterpret_cast(pages); + const auto small_va = title_va + (3u << 20); + aliases.add_title_memory(title_va, title_bytes); + int result = 0; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = &instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.buffer_device_address = true; + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + const std::uint64_t arena = rt::d3d12::device_arena_size(device.p); + if (!arena) { + std::fprintf(stderr, "SKIP: the device has no GPU address arena\n"); + result = 77; + } else { + // Fill the arena: a 64 KiB buffer (its placement alignment) that is not given an arena VA found no room + // there, so no shadow will find any either. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC filler_desc = buffer_desc(64u << 10); + std::vector> fillers(arena >> 16); + bool full = false; + for (auto& filler : fillers) { + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &filler_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&filler.p)))); + if ((full = filler->GetGPUVirtualAddress() >= arena)) break; + } + EXPECT(full); + + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + const D3D12_VERTEX_BUFFER_VIEW large_vertices{title_va, large_bytes, 16}; + const D3D12_INDEX_BUFFER_VIEW large_indices{title_va, large_bytes, DXGI_FORMAT_R16_UINT}; + const D3D12_VERTEX_BUFFER_VIEW small_vertices{small_va, small_bytes, 16}; + const D3D12_INDEX_BUFFER_VIEW small_indices{small_va, small_bytes, DXGI_FORMAT_R16_UINT}; + const auto bind_large = [&](unsigned times) { + for (unsigned i = 0; i < times; ++i) { + if (i & 1) list->IASetIndexBuffer(&large_indices); + else list->IASetVertexBuffers(0, 1, &large_vertices); + } + return large_buffers.load(); + }; + const auto bind_small = [&](unsigned times) { + for (unsigned i = 0; i < times; ++i) { + if (i & 1) list->IASetIndexBuffer(&small_indices); + else list->IASetVertexBuffers(0, 1, &small_vertices); + } + return small_buffers.load(); + }; + + // No import, no shadow: nothing over the title's pages is kept, and the view is tried once, with no + // device-local stand-in made for it. The other view, bound right after, is not tried. + const ULONG before = references(device.p); + refuse_host_visible = true; + const unsigned first = bind_large(1); + const unsigned tried = bind_large(15); + const unsigned small_held = bind_small(8); + const ULONG refused = references(device.p); + std::printf("16 binds with no import or shadow: %lu buffers kept, %u buffers of the view's size created " + "(%u by the first bind), %u device-local allocations of its size; 8 binds of another view " + "right after: %u buffers of its size created\n", + refused - before, tried, first, device_allocations.load(), small_held); + EXPECT(refused == before); + EXPECT(device_allocations == 0); + EXPECT(first == 1); + EXPECT(tried == first); + EXPECT(small_held == 0); + EXPECT(aliases.shader_va(title_va) == title_va); + + // After the second, the large view is tried again, once, and refused again. Host-visible memory is still + // refused here and below: a buffer the device keeps over title memory holds a reference to it, so the + // device would never be destroyed, and its Vulkan objects would be reported as leaked under the + // validation layer. + Sleep(1500); + const unsigned retried = bind_large(1); + const unsigned again = bind_large(7); + std::printf("after a second: %u buffers of the view's size created by the next bind, %u by 7 further " + "binds\n", + retried - tried, again - retried); + EXPECT(retried == tried + 1); + EXPECT(again == retried); + + // 1.5 s after that second refusal the other view is tried (no range waits for the device any more), but + // the large view is not: refused twice, it waits 2 s. + Sleep(1500); + const unsigned waited = bind_large(8); + const unsigned small_tried = bind_small(8); + std::printf("1.5 s later: %u buffers of the large view's size created by 8 binds, %u of the other " + "view's by 8 binds\n", + waited - again, small_tried - small_held); + EXPECT(waited == again); + EXPECT(small_tried == small_held + 1); + + // Once its 2 s have passed (and the other view's refusal is a second old), the large view is tried again. + Sleep(1500); + const unsigned third = bind_large(8); + refuse_host_visible = false; + const ULONG after = references(device.p); + std::printf("1.5 s later: %u buffers of the large view's size created by 8 binds; %lu buffers kept, %u " + "device-local allocations of a view's size in all\n", + third - waited, after - before, device_allocations.load()); + EXPECT(third == waited + 1); + EXPECT(after == before); + EXPECT(device_allocations == 0); + EXPECT(aliases.shader_va(title_va) == title_va); + EXPECT(aliases.shader_va(small_va) == small_va); + EXPECT(SUCCEEDED(list->Close())); + } + } + aliases.remove_title_memory(title_va); + VirtualFree(pages, 0, MEM_RELEASE); + if (vk.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", vk.validation_errors()); + return 1; + } + if (!result) std::printf("ok\n"); + return result; +} diff --git a/runtime/test/d3d12_zero_image_retry_test.cpp b/runtime/test/d3d12_zero_image_retry_test.cpp new file mode 100644 index 0000000000..c6001acea8 --- /dev/null +++ b/runtime/test/d3d12_zero_image_retry_test.cpp @@ -0,0 +1,185 @@ +// A sampled BC texture the title places on its own memory (Xbox device slot 133) waits for memory of its own until +// the title writes it or a command uses it; until then its views name one shared, zeroed image of its exact shape +// (DeviceState::zero_sampled_image), kept for the device's life. Under VRAM pressure that image cannot always be made +// (vkCreateImage or its memory refused). Such a shape must get its shared image at a later placement once the memory is +// back, not stay without one for the whole session, every placement of it taking memory of its own at once. +// - A control shape gets its shared image (the placement has no memory of its own), or the test is skipped. +// - The test wraps vkCreateImage behind the instance-proc pointer it hands the layer and refuses the next image of +// the shape under test: that is the shared image, made before the placement's own. That placement, and one right +// after it, have memory of their own: the shape is not tried again at every placement. +// - After the retry delay (a second), a third placement of the shape tries again, and that image is refused too. +// - The delay doubles at each refusal: 1.5 s later a fourth placement does not try (memory of its own, one image of +// the shape made for it), and 1.5 s after that (past the 2 s) a fifth gets its shared image (no memory of its +// own): two images of the shape are made for it, the shared one and the placement's. +// The device has no host image copies, so a placement takes the shared image whatever its driver allows for host-copy +// images (d3d12_existing_heap's shared slot-133 BC images do the same). Needs the bindless set (skipped otherwise). +// Synthetic data only. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" + +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +template +struct Ref { + T* p = nullptr; + Ref() = default; + Ref(const Ref&) = delete; // a copy would release the same interface twice + Ref& operator=(const Ref&) = delete; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +constexpr UINT width = 64, height = 48; // the shape under test; no other image of the test has this extent + +// The Vulkan calls the layer makes, seen through the function pointers it loads. +PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; +PFN_vkGetDeviceProcAddr real_device_proc = nullptr; +PFN_vkCreateImage real_create_image = nullptr; +std::atomic refuse_next{false}; +std::atomic shape_images{0}, refused{0}; // vkCreateImage calls for the shape under test, and refusals + +VKAPI_ATTR VkResult VKAPI_CALL create_image(VkDevice device, const VkImageCreateInfo* info, + const VkAllocationCallbacks* allocator, VkImage* image) { + if (info->extent.width == width && info->extent.height == height) { + ++shape_images; + if (refuse_next.exchange(false)) { + ++refused; + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + } + return real_create_image(device, info, allocator, image); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) { + if (std::strcmp(name, "vkCreateImage") == 0) { + real_create_image = reinterpret_cast(real_device_proc(device, name)); + return real_create_image ? reinterpret_cast(&create_image) : nullptr; + } + return real_device_proc(device, name); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) { + if (std::strcmp(name, "vkGetDeviceProcAddr") == 0) { + real_device_proc = reinterpret_cast(real_instance_proc(instance, name)); + return real_device_proc ? reinterpret_cast(&device_proc) : nullptr; + } + return real_instance_proc(instance, name); +} + +D3D12_RESOURCE_DESC bc1(UINT w, UINT h) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = w; + desc.Height = h; + desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_BC1_UNORM; + return desc; +} + +// A placement waiting on the shared zero image has no memory of its own yet. +bool shared(ID3D12Resource* texture) { return !rt::d3d12::vulkan_memory_flags(texture); } + +} // namespace + +int main() { + vktest::Device vk; + if (!vk.create()) return 77; + real_instance_proc = vk.instance_proc; + void* pages = VirtualAlloc(nullptr, 6 * 65536, MEM_RESERVE, PAGE_NOACCESS); + EXPECT(pages); + const auto at = [&](unsigned i) { return static_cast(pages) + i * 65536; }; + int result = 0; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = &instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.bindless = vk.bindless; + info.bindless_partially_bound = vk.partially_bound; + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + Ref control, first, second, third, fourth, fifth; + const D3D12_RESOURCE_DESC control_desc = bc1(32, 32), desc = bc1(width, height); + if (!rt::d3d12::bindless_set_layout(device.p)) { + std::fprintf(stderr, "SKIP: the device has no bindless set\n"); + result = 77; + } else if (FAILED(rt::d3d12::create_buffer_at_host_address(device.p, at(0), control_desc, 0, + IID_PPV_ARGS(&control.p))) || + !shared(control.p)) { + std::fprintf(stderr, "SKIP: a placed BC texture does not take a shared zero image on this device\n"); + result = 77; + } else { + // The shared image of the shape is refused: the first placement, and the next one, get memory of their own. + refuse_next = true; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, at(1), desc, 0, + IID_PPV_ARGS(&first.p)))); + EXPECT(refused == 1); + const unsigned by_first = shape_images.load(); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, at(2), desc, 0, + IID_PPV_ARGS(&second.p)))); + const unsigned by_second = shape_images.load() - by_first; + std::printf("shared image refused: placements %s and %s; %u and %u images of the shape made for them\n", + shared(first.p) ? "shared" : "with memory of their own", + shared(second.p) ? "shared" : "with memory of their own", by_first, by_second); + EXPECT(!shared(first.p)); + EXPECT(!shared(second.p)); + EXPECT(by_second == 1); + + // After the retry delay the shape is tried again, and its image is refused again. + Sleep(1500); + refuse_next = true; + const unsigned before_third = shape_images.load(); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, at(3), desc, 0, + IID_PPV_ARGS(&third.p)))); + const unsigned by_third = shape_images.load() - before_third; + std::printf("after the retry delay, refused again: placement %s; %u images of the shape made for it\n", + shared(third.p) ? "shared" : "with memory of their own", by_third); + EXPECT(refused == 2); + EXPECT(!shared(third.p)); + EXPECT(by_third == 2); + + // Refused twice, the shape waits 2 s: 1.5 s later it is not tried, and after the 2 s it gets its image. + Sleep(1500); + const unsigned before_fourth = shape_images.load(); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, at(4), desc, 0, + IID_PPV_ARGS(&fourth.p)))); + const unsigned by_fourth = shape_images.load() - before_fourth; + std::printf("1.5 s later: placement %s; %u images of the shape made for it\n", + shared(fourth.p) ? "shared" : "with memory of their own", by_fourth); + EXPECT(!shared(fourth.p)); + EXPECT(by_fourth == 1); + Sleep(1500); + const unsigned before_fifth = shape_images.load(); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(device.p, at(5), desc, 0, + IID_PPV_ARGS(&fifth.p)))); + const unsigned by_fifth = shape_images.load() - before_fifth; + std::printf("1.5 s later: placement %s; %u images of the shape made for it\n", + shared(fifth.p) ? "shared" : "with memory of their own", by_fifth); + EXPECT(refused == 2); + EXPECT(shared(fifth.p)); + EXPECT(by_fifth == 2); + } + } + VirtualFree(pages, 0, MEM_RELEASE); + if (vk.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", vk.validation_errors()); + return 1; + } + if (!result) std::printf("ok\n"); + return result; +} diff --git a/runtime/test/geometry_views_test.cpp b/runtime/test/geometry_views_test.cpp index 37a1bd391d..ce4c3917ca 100644 --- a/runtime/test/geometry_views_test.cpp +++ b/runtime/test/geometry_views_test.cpp @@ -19,9 +19,18 @@ // (forget_copy); its destroyed block leaves the lock-free block list and is reported to the device; // 14. LEONIDA_GEOMETRY_HOST picks a system-memory type (write-back for 1, write-combined for 2), never the BAR; // 15. a retired view is copied once more from its pages when they are readable, not when they are not; -// 16. a full release queue joins touching ranges before it collapses to one covering range. +// 16. a full release queue joins touching ranges before it collapses to one covering range; +// 17. a range inside a live view is answered from that view (its address plus the offset), not copied again, unless +// the caller asks for a copy of its own; it is refreshed with that view and leaves with it, and a view it was +// inside before keeps answering after the outer one goes; a retired view with a range inside it the release did +// not touch also waits for the command lists whose recording began before that range stopped being answered, +// on_retire included (LEONIDA_GEOMETRY_CONTAINED=0, a copy of its own as before, fails 17); +// 18. a filled view over a tile that cannot be guarded yet (a file read into it in flight) still takes the writes to +// its other tiles, and so does a range inside it (with whole views such a view waits for the read to end and is +// then copied whole, so its first check fails). #include +#include #include #include #include @@ -31,6 +40,7 @@ #include #include "../shims/d3d12_geometry_views.h" +#include "../src/command_list_epochs.h" #include "../src/title_va_alias.h" namespace { @@ -138,6 +148,10 @@ void title_write(std::uintptr_t at, std::uint8_t value) { *reinterpret_cast(at) = value; } +// kernel_writes::begin_write pins a range only once the layer has an opener; the test's pages are opened by +// title_write already. +void open_nothing(std::uintptr_t, std::uintptr_t) {} + } // namespace int main() { @@ -620,6 +634,162 @@ int main() { VirtualFree(host_title, 0, MEM_RELEASE); } + // 17. Ranges inside a live view: (A, 128 KiB), then (A, 64 KiB) and (A + 4 KiB, 64 KiB), are 132 KiB of the + // title's bytes. Each with a copy of its own they were three views and 256 KiB of copies; the two inside the first + // are its bytes at their offsets, so one view of 128 KiB. Asked for smallest first, (B, 64 KiB) is no view's bytes + // yet and (B, 128 KiB) is not inside it: two views, and (B + 4 KiB, 64 KiB) is inside the second. + { + auto* nest_title = + static_cast(VirtualAlloc(nullptr, 8 * kTile, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!nest_title) return 1; + for (std::size_t i = 0; i < 8 * kTile; ++i) nest_title[i] = std::uint8_t((i * 11) ^ 0x6e); + const auto a = reinterpret_cast(nest_title); + const auto b = a + 4 * kTile; + rt::d3d12::GeometryViews nest; + const auto host_of = [&](std::uint64_t at) -> const std::uint8_t* { + std::uint64_t host = 0, room = 0; + return at && nest.lookup(device.arena.address + at, host, room) ? reinterpret_cast(host) + : nullptr; + }; + const std::uint64_t outer = nest.resolve(device, a, 2 * kTile, copy); + const std::uint64_t head = nest.resolve(device, a, kTile, copy); + const std::uint64_t inner = nest.resolve(device, a + 4096, kTile, copy); + check(outer != 0 && head == outer && inner == outer + 4096 && nest.live_views() == 1 && + nest.bytes() == 2 * kTile, + "two ranges inside a live 128 KiB view are its bytes at their offsets: one view, 128 KiB"); + check(nest.resolve(device, a + 4096, kTile, copy) == inner && nest.find(a + 4096, kTile) == inner && + nest.find(a, kTile) == head && host_of(inner) && !std::memcmp(host_of(inner), nest_title + 4096, kTile), + "asked again or found, the inner range has the same address, which holds the title's bytes"); + title_write(a + 4096 + 77, 0xe1); + nest.refresh(copy); + check(host_of(inner) && host_of(inner)[77] == 0xe1, "a write inside the inner range reaches it with the view"); + + const std::uint64_t small = nest.resolve(device, b, kTile, copy); + const std::uint64_t large = nest.resolve(device, b, 2 * kTile, copy); + const std::uint64_t inside = nest.resolve(device, b + 4096, kTile, copy); + check(small != 0 && large != 0 && large != small && inside == large + 4096 && nest.live_views() == 3 && + nest.bytes() == 5 * kTile, + "smallest first: (B, 64 KiB) and (B, 128 KiB) are two views, (B + 4 KiB, 64 KiB) is inside the second"); + + // Retiring a range at the outer view's tail, which neither inner range touches, retires them with it: they + // were its bytes. Each is told by the address it was answered with. + std::vector> told; + const auto tell = [&](std::uintptr_t source, std::size_t, VkDeviceSize at) { told.emplace_back(source, at); }; + const std::size_t retired = nest.retire_range(a + 100 * 1024, a + 104 * 1024, 1, tell); + const auto was_told = [&](std::uintptr_t source, VkDeviceSize at) { + return std::find(told.begin(), told.end(), std::make_pair(source, at)) != told.end(); + }; + check(retired == 1 && told.size() == 3 && was_told(a, outer) && was_told(a, head) && + was_told(a + 4096, inner) && nest.live_views() == 2, + "retiring the outer view retires the ranges inside it, each told with its own address"); + check(nest.find(a, kTile) == 0 && nest.find(a + 4096, kTile) == 0 && nest.find(a, 2 * kTile) == 0, + "no range inside the retired view is found any more"); + check(nest.reap(device, 1) == 1 && nest.bytes() == 3 * kTile, "the outer view's 128 KiB are freed once"); + const std::uint64_t again = nest.resolve(device, a + 4096, kTile, copy); + check(again != 0 && nest.live_views() == 3 && nest.bytes() == 4 * kTile && host_of(again) && + !std::memcmp(host_of(again), nest_title + 4096, kTile), + "asked for after its view went, the inner range gets a view of its own with the title's bytes"); + + // The view (B, 128 KiB) goes by its tail; (B, 64 KiB), which it held inside, answers what is inside it again. + told.clear(); + check(nest.retire_range(b + 100 * 1024, b + 104 * 1024, 2, tell) == 1 && told.size() == 2 && + was_told(b, large) && was_told(b + 4096, large + 4096) && nest.find(b, kTile) == small, + "the outer view of B retires with its inner range; the smaller view of B stays"); + const std::uint64_t quarter = nest.resolve(device, b + 8192, kTile / 4, copy); + check(nest.reap(device, 2) == 1 && quarter == small + 8192 && nest.live_views() == 2, + "a range inside the smaller view of B is answered from it once the larger one has gone (and is freed)"); + + // A command list recorded before a retirement (its command_list_epochs stamp) may name a range inside the + // retired view that the release did not touch, which is still the title's: that view's memory waits for the + // list as well as for the replays. A view with nothing inside it, retired in the same replay, does not. + const auto c = a + 6 * kTile; + const std::uint64_t outer_c = nest.resolve(device, c, 2 * kTile, copy); + check(outer_c != 0 && nest.resolve(device, c + 4096, kTile, copy) == outer_c + 4096, + "a third outer view with a range inside it"); + auto list = std::make_unique(); + const std::uint64_t replay = nest.execute_begin(); + nest.retire_range(c + 100 * 1024, c + 104 * 1024, rt::d3d12::GeometryViews::kAfterExecutes); + nest.retire_range(a + 4096, a + 8192, rt::d3d12::GeometryViews::kAfterExecutes); // `again`: nothing inside + nest.execute_end(replay, [] { return std::uint64_t(3); }); + check(nest.reap(device, 3) == 1 && nest.retired_count() == 1, + "while a list recorded before the retirement lives, only the view with nothing inside it is freed"); + list.reset(); + const std::uint64_t next = nest.execute_begin(); + nest.execute_end(next, [] { return std::uint64_t(4); }); + check(nest.reap(device, 3) == 0 && nest.reap(device, 4) == 1 && nest.retired_count() == 0, + "once that list is gone, the outer view waits only for the next replay's submissions"); + + // The range inside answers until on_retire has dropped what still names it (aliases, heap slots), after the + // views' lock is let go: a list whose recording begins in on_retire can still take its address, so the view + // waits for that list too. + const auto d = a + 2 * kTile; + const std::uint64_t outer_d = nest.resolve(device, d, 2 * kTile, copy); + check(outer_d != 0 && nest.resolve(device, d + 4096, kTile, copy) == outer_d + 4096, + "a fourth outer view with a range inside it"); + std::unique_ptr late; + nest.retire_range(d + 100 * 1024, d + 104 * 1024, rt::d3d12::GeometryViews::kAfterExecutes, + [&](std::uintptr_t, std::size_t, VkDeviceSize) { + if (!late) late = std::make_unique(); + }); + const std::uint64_t after = nest.execute_begin(); + nest.execute_end(after, [] { return std::uint64_t(5); }); + check(late && nest.reap(device, 5) == 0 && nest.retired_count() == 1, + "a list whose recording began in on_retire, while the range inside still answered, holds the view"); + late.reset(); + const std::uint64_t last_replay = nest.execute_begin(); + nest.execute_end(last_replay, [] { return std::uint64_t(6); }); + check(nest.reap(device, 6) == 1 && nest.retired_count() == 0, "once that list is gone, the view is freed"); + + // A caller that asks for a copy of its own (a structure the GPU writes, copy_title_range) gets one, even + // inside a live view: a release elsewhere in that view must not take the structure with it. + const std::uint64_t holder = nest.resolve(device, d, 2 * kTile, copy); + const std::uint64_t own = nest.resolve(device, d + 4096, kTile, copy, false); + check(holder != 0 && own != 0 && own != holder + 4096 && nest.find(d + 4096, kTile) == own && + nest.retire_range(d + 100 * 1024, d + 104 * 1024, 7) == 1 && nest.find(d + 4096, kTile) == own, + "asked for a copy of its own, a range inside a live view gets one, which outlives that view"); + nest.release(device); + VirtualFree(nest_title, 0, MEM_RELEASE); + } + + // 18. V = (P, 128 KiB) over tiles 0 and 1, and K = (P + 4 KiB, 4 KiB) inside tile 0. The title writes K and tile + // 1, and a file read into tile 1 is in flight at the next refresh, so tile 1 cannot be guarded yet. The refresh + // takes tile 0's version all the same, so a write to it that is not copied then is never copied: tile 0 goes to + // V (and K) now, and tile 1 once the read has ended. + { + auto* pin_title = + static_cast(VirtualAlloc(nullptr, 2 * kTile, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!pin_title) return 1; + for (std::size_t i = 0; i < 2 * kTile; ++i) pin_title[i] = std::uint8_t((i * 5) ^ 0x0f); + const auto p = reinterpret_cast(pin_title); + rt::d3d12::GeometryViews pinned; + const auto host_of = [&](std::uint64_t at) -> const std::uint8_t* { + std::uint64_t host = 0, room = 0; + return at && pinned.lookup(device.arena.address + at, host, room) + ? reinterpret_cast(host) + : nullptr; + }; + const std::uint64_t whole = pinned.resolve(device, p, 2 * kTile, copy); + const std::uint64_t part = pinned.resolve(device, p + 4096, 4096, copy); + pinned.refresh(copy); + const std::uint8_t before = pin_title[kTile + 10]; + leonida::kernel_writes::set_opener(open_nothing); + title_write(p + kTile + 10, 0x11); + title_write(p + 4096 + 5, 0x5a); + const std::uint64_t pin = leonida::kernel_writes::begin_write(pin_title + kTile + 100, 16, nullptr); + pinned.refresh(copy); + check(pin != 0 && host_of(whole) && host_of(part) && host_of(whole)[4096 + 5] == 0x5a && + host_of(part)[5] == 0x5a && host_of(whole)[kTile + 10] == before, + "while a file read into tile 1 is in flight, the write to tile 0 reaches V and K; tile 1 waits"); + leonida::kernel_writes::end_write(pin, false); + pinned.refresh(copy); + check(host_of(whole) && host_of(part) && host_of(whole)[kTile + 10] == 0x11 && + host_of(whole)[4096 + 5] == 0x5a && host_of(part)[5] == 0x5a, + "once the read has ended, tile 1 reaches V too, and tile 0 keeps the write"); + leonida::kernel_writes::set_opener(nullptr); + pinned.release(device); + VirtualFree(pin_title, 0, MEM_RELEASE); + } + std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/runtime/test/mem_probe_vmmap_test.cpp b/runtime/test/mem_probe_vmmap_test.cpp new file mode 100644 index 0000000000..f9cac8af57 --- /dev/null +++ b/runtime/test/mem_probe_vmmap_test.cpp @@ -0,0 +1,188 @@ +// leonida::mem_probe's vmmap line (src/mem_probe.h, LEONIDA_MEM_PROBE=): on native Windows there is no +// /proc//smaps to read, so the probe walks the address space with VirtualQuery and sums the committed bytes by the +// smaps line's kinds. The classifier cuts synthetic regions at the title and vk_mapped ranges and names the rest by +// their type; a walk of this process sees 64 MiB it commits as PE private memory, or as title memory inside a title +// range, and a mapped view as a PE section, or as memory the Vulkan driver mapped inside a vk_mapped range. A walk +// over a 4 GiB reservation with 65 536 committed pages prints how long it takes. No GPU, no device. +#include "../src/mem_probe.h" + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +namespace mp = leonida::mem_probe; +constexpr std::uint64_t kMiB = 1 << 20; +constexpr std::uint64_t kKiB = 1 << 10; + +bool contains(const std::string& text, const char* part) { return text.find(part) != std::string::npos; } + +std::uint64_t walk(mp::VmTally& tally) { + std::uint64_t reserved = 0; + return mp::walk_address_space(tally, reserved); +} + +// Synthetic regions: the part inside a title range is title memory, the part inside a vk_mapped range is the driver's, +// the rest goes by the region's type, and a region cut by a range counts once in each kind it reaches. The title ranges +// come unsorted and overlapping, as a caller may hand them. +int classifier() { + const mp::Ranges title = {{0x30000000, 0x30100000}, {0x10000000, 0x18000000}, {0x17000000, 0x20000000}}; + const mp::Ranges vk_mapped = {{0x40000000, 0x40200000}}; + mp::VmTally t(title, vk_mapped); + t.add({0x10000000, 64 * kMiB, 0x10000000, MEM_PRIVATE}); // all title + t.add({0x1FF00000, 2 * kMiB, 0x1FF00000, MEM_PRIVATE}); // 1 MiB title, then 1 MiB private + t.add({0x2FF00000, 3 * kMiB, 0x2FF00000, MEM_MAPPED}); // 1 MiB section, 1 MiB title, 1 MiB section + t.add({0x40000000, 2 * kMiB, 0x40000000, MEM_MAPPED}); // all vk_mapped + t.add({0x401F0000, 128 * kKiB, 0x401F0000, MEM_PRIVATE}); // 64 KiB vk_mapped, then 64 KiB private + t.add({0x140000000, 3 * kMiB, 0x140000000, MEM_IMAGE}); + t.add({0x50000000, 5 * kMiB, 0x50000000, MEM_MAPPED}); + t.add({0x60000000, 1 * kMiB, 0x60000000, MEM_PRIVATE}); // one allocation in two regions + t.add({0x60100000, 7 * kMiB, 0x60000000, MEM_PRIVATE}); + EXPECT(t.committed[mp::b_title] == 66 * kMiB && t.regions[mp::b_title] == 3); + EXPECT(t.committed[mp::b_pe_private] == 9 * kMiB + 64 * kKiB && t.regions[mp::b_pe_private] == 4); + EXPECT(t.committed[mp::b_pe_mapped] == 7 * kMiB && t.regions[mp::b_pe_mapped] == 2); + EXPECT(t.committed[mp::b_vk_mapped] == 2 * kMiB + 64 * kKiB && t.regions[mp::b_vk_mapped] == 2); + EXPECT(t.committed[mp::b_pe_image] == 3 * kMiB && t.regions[mp::b_pe_image] == 1); + std::uint64_t sum = 0; + for (int b = 0; b < mp::b_count; ++b) sum += t.committed[b]; + EXPECT(sum == 87 * kMiB + 128 * kKiB); // every byte of every region, once + EXPECT(t.total() == sum); + const auto largest = t.largest_private(2); + EXPECT(largest.size() == 2); + EXPECT(largest[0].first == 8 * kMiB && largest[0].second == 0x60000000); + EXPECT(largest[1].first == 1 * kMiB && largest[1].second == 0x1FF00000); + // Without ranges every byte goes by its type. + mp::VmTally bare({}, {}); + bare.add({0x10000000, 64 * kMiB, 0x10000000, MEM_PRIVATE}); + bare.add({0x40000000, 2 * kMiB, 0x40000000, MEM_MAPPED}); + EXPECT(bare.committed[mp::b_pe_private] == 64 * kMiB && bare.committed[mp::b_pe_mapped] == 2 * kMiB); + EXPECT(bare.committed[mp::b_title] == 0 && bare.committed[mp::b_vk_mapped] == 0); + return 0; +} + +// The text: the walk's time and size, the process counters, the committed MiB of every kind with its regions, the +// reserved bytes and the largest private allocations; "n/a" where the system did not report the private working set. +int text() { + mp::VmTally t({{0x10000000, 0x20000000}}, {{0x40000000, 0x40200000}}); + t.add({0x10000000, 64 * kMiB, 0x10000000, MEM_PRIVATE}); + t.add({0x40000000, 2 * kMiB, 0x40000000, MEM_MAPPED}); + t.add({0x60000000, 8 * kMiB, 0x60000000, MEM_PRIVATE}); + t.add({0x140000000, 3 * kMiB, 0x140000000, MEM_IMAGE}); + t.add({0x50000000, 5 * kMiB, 0x50000000, MEM_MAPPED}); + mp::ProcessCounters counters; + counters.read = true; + counters.private_commit = 2048 * kMiB; + counters.peak_commit = 4096 * kMiB; + counters.working_set = 1024 * kMiB; + counters.peak_working_set = 1536 * kMiB; + counters.private_working_set = 512 * kMiB; + const std::string line = mp::vmmap_text(12.0, 3.0, 100, counters, t, 640 * kMiB); + std::fprintf(stderr, "%s\n", line.c_str()); + EXPECT(line.rfind("[rt] mem-probe vmmap t=12s (3 ms, 100 regions): private commit 2048 MiB (peak 4096), working " + "set 1024 MiB (private 512, peak 1536); committed 82 MiB by kind: title 64 (1 regions), " + "pe-private 8 (1 regions), pe-image 3 (1 regions), pe-section 5 (1 regions), vk-mapped 2 (1 " + "regions); reserved 640 MiB; largest private allocations MiB: 0x60000000 8", + 0) == 0); + counters.private_working_set = 0; + EXPECT(contains(mp::vmmap_text(12.0, 3.0, 100, counters, t, 0), "(private n/a, peak 1536)")); + EXPECT(contains(mp::vmmap_text(12.0, 3.0, 100, mp::ProcessCounters{}, t, 0), + "(3 ms, 100 regions): process counters n/a; committed 82 MiB")); + return 0; +} + +// This process: 64 MiB it commits shows up as PE private memory and in the commit charge, as title memory when a +// title range covers it, and a 16 MiB view of a pagefile-backed section as a PE section, or as vk-mapped memory when a +// vk_mapped range covers it. +int live() { + const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr; + const mp::ProcessCounters counters_before = mp::process_counters(); + mp::VmTally before({}, {}); + EXPECT(walk(before) > 0); + EXPECT(before.committed[mp::b_pe_image] > 0); // this executable and its DLLs + + auto* block = static_cast(VirtualAlloc(nullptr, 64 * kMiB, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(block); + std::memset(block, 1, 64 * kMiB); // in the working set too + const std::uint64_t base = reinterpret_cast(block); + mp::VmTally after({}, {}); + walk(after); + const mp::ProcessCounters counters_after = mp::process_counters(); + std::fprintf(stderr, "pe-private %.0f -> %.0f MiB, private commit %.0f -> %.0f MiB, private working set %.0f MiB\n", + mp::mib(before.committed[mp::b_pe_private]), mp::mib(after.committed[mp::b_pe_private]), + mp::mib(counters_before.private_commit), mp::mib(counters_after.private_commit), + mp::mib(counters_after.private_working_set)); + EXPECT(after.committed[mp::b_pe_private] >= before.committed[mp::b_pe_private] + 64 * kMiB); + EXPECT(counters_before.read && counters_after.read); + EXPECT(counters_after.private_commit >= counters_before.private_commit + 64 * kMiB); + EXPECT(counters_after.working_set > 0 && counters_after.peak_working_set >= counters_after.working_set); + if (!wine && counters_after.private_working_set_reported) EXPECT(counters_after.private_working_set > 0); + bool listed = false; + for (const auto& [bytes, allocation] : after.largest_private(4)) + if (allocation == base && bytes == 64 * kMiB) listed = true; + EXPECT(listed); + + mp::VmTally titled({{base, base + 64 * kMiB}}, {}); + walk(titled); + EXPECT(titled.committed[mp::b_title] == 64 * kMiB && titled.regions[mp::b_title] == 1); + + HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(16 * kMiB), nullptr); + EXPECT(section); + void* view = MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, 0); + EXPECT(view); + const std::uint64_t view_base = reinterpret_cast(view); + mp::VmTally mapped({}, {}); + walk(mapped); + EXPECT(mapped.committed[mp::b_pe_mapped] >= after.committed[mp::b_pe_mapped] + 16 * kMiB); + mp::VmTally driver({}, {{view_base, view_base + 16 * kMiB}}); + walk(driver); + EXPECT(driver.committed[mp::b_vk_mapped] == 16 * kMiB && driver.regions[mp::b_vk_mapped] == 1); + + UnmapViewOfFile(view); + CloseHandle(section); + VirtualFree(block, 0, MEM_RELEASE); + return 0; +} + +// A big, fragmented address space: 4 GiB reserved with one page committed every 64 KiB gives 65 536 committed regions +// between as many reserved ones. The walk counts them all and prints how long it took, then the whole line. +int big_address_space() { + const std::uint64_t span = 4ull << 30, step = 64 * kKiB, page = 4 * kKiB; + auto* base = static_cast(VirtualAlloc(nullptr, span, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(base); + for (std::uint64_t offset = 0; offset < span; offset += step) + EXPECT(VirtualAlloc(base + offset, page, MEM_COMMIT, PAGE_READWRITE)); + mp::VmTally tally({}, {}); + std::uint64_t reserved = 0; + const auto t0 = std::chrono::steady_clock::now(); + const std::uint64_t walked = mp::walk_address_space(tally, reserved); + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + std::fprintf(stderr, "walk: %llu regions in %.1f ms, %llu private regions, %.0f MiB reserved\n", + (unsigned long long)walked, ms, (unsigned long long)tally.regions[mp::b_pe_private], mp::mib(reserved)); + EXPECT(walked >= 2 * (span / step)); + EXPECT(tally.regions[mp::b_pe_private] >= span / step); + EXPECT(reserved >= span - (span / step) * page); + const auto largest = tally.largest_private(1); + EXPECT(!largest.empty() && largest[0].second == reinterpret_cast(base) && + largest[0].first == (span / step) * page); + std::fprintf(stderr, "%s\n", mp::sample_vmmap(0.0, {}, {}).c_str()); + VirtualFree(base, 0, MEM_RELEASE); + return 0; +} + +} // namespace + +int main() { + if (int r = classifier()) return r; + if (int r = text()) return r; + if (int r = live()) return r; + if (int r = big_address_space()) return r; + std::fprintf(stderr, "mem_probe_vmmap: ok\n"); + return 0; +} diff --git a/runtime/test/pso_stream_test.cpp b/runtime/test/pso_stream_test.cpp index 01eaa54aa4..62a10fbfa3 100644 --- a/runtime/test/pso_stream_test.cpp +++ b/runtime/test/pso_stream_test.cpp @@ -1,9 +1,15 @@ // Pipeline state stream copies and the derived-state patch (device slot 55) with synthetic streams only: no D3D12 // device, no game data. The layout rule is the one measured on the console's slot 86 stream (see the offsets check). #include +#include +#include +#include #include #include +#include +#include +#include #include #include "d3d12_xs_pso_stream.h" @@ -285,6 +291,194 @@ void test_refusals() { "a stream with an unmodelled subobject type is not captured"); } +// A hand-built container of `size` bytes: the DXBC magic, 16 checksum bytes made from `checksum` (all zero when it is +// 0, as a container without a checksum has) and a body filled from `seed`. The record parses none of it. +std::vector container(std::size_t size, unsigned char checksum, unsigned seed) { + std::vector bytes(size); + std::memcpy(bytes.data(), "DXBC", 4); + for (std::size_t i = 4; i < 20; ++i) bytes[i] = static_cast(checksum ? checksum + i : 0); + for (std::size_t i = 20; i < size; ++i) bytes[i] = static_cast(seed * 131 + i * 7 + (i >> 8)); + return bytes; +} + +// Root signature (null), VS and PS, as the title's slot 86 streams start. +std::vector shader_stream(const std::vector& vs, const std::vector& ps) { + StreamBuilder s; + ID3D12RootSignature* root = nullptr; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &root, 8, 8); + D3D12_SHADER_BYTECODE code{vs.data(), vs.size()}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &code, sizeof(code), 8); + code = {ps.data(), ps.size()}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, &code, sizeof(code), 8); + return s.bytes; +} + +// Captures a stream the test built; the record reads the stream and never writes it. +std::unique_ptr keep(const std::vector& stream) { + return rt::d3d12_xs::PsoStreamRecord::capture({stream.size(), const_cast(stream.data())}); +} + +D3D12_SHADER_BYTECODE stage_of(const rt::d3d12_xs::PsoStreamRecord& record, unsigned type) { + D3D12_SHADER_BYTECODE code{}; + std::memcpy(&code, record.bytes().data() + payload_of_type(record.bytes(), type), sizeof(code)); + return code; +} + +bool holds(const D3D12_SHADER_BYTECODE& code, const std::vector& bytes) { + return code.pShaderBytecode && code.BytecodeLength == bytes.size() && + std::memcmp(code.pShaderBytecode, bytes.data(), bytes.size()) == 0; +} + +std::uint64_t private_bytes() { + PROCESS_MEMORY_COUNTERS_EX counters{}; + counters.cb = sizeof(counters); + if (!GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&counters), + sizeof(counters))) + return 0; + return counters.PrivateUsage; +} + +void test_equal_bytecode_is_kept_once() { + // The title creates tens of thousands of PSOs from far fewer shaders, and every slot 86 stream points at the + // bytecode it was made from. Equal bytecode in many streams, from different source buffers, is kept once. + constexpr std::size_t kMeanContainer = 9800; // the corpus mean is about 9.6 KB per container + const auto vs_a = container(kMeanContainer, 0x40, 1); + const auto vs_a_again = vs_a; // another buffer with the same bytes, as a second load of the shader would be + const auto ps = container(kMeanContainer + 512, 0x80, 2); + const auto ps_again = ps; + const auto first_stream = shader_stream(vs_a, ps); + const auto second_stream = shader_stream(vs_a_again, ps_again); + + auto first = keep(first_stream); + auto second = keep(second_stream); + if (!first || !second) { check(false, "shader streams captured"); return; } + const auto vs1 = stage_of(*first, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + const auto vs2 = stage_of(*second, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + const auto ps1 = stage_of(*first, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS); + const auto ps2 = stage_of(*second, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS); + check(holds(vs1, vs_a) && holds(vs2, vs_a) && holds(ps1, ps) && holds(ps2, ps), + "every stage of the kept streams holds the source bytes"); + check(vs1.pShaderBytecode != vs_a.data() && vs2.pShaderBytecode != vs_a_again.data(), + "the kept bytecode is not the caller's buffer"); + check(vs1.pShaderBytecode == vs2.pShaderBytecode && ps1.pShaderBytecode == ps2.pShaderBytecode, + "two streams with equal bytecode in different buffers share one copy of each stage"); + check(vs1.pShaderBytecode != ps1.pShaderBytecode, "stages with different bytecode keep different copies"); + + // Bytecode with the same DXBC checksum and size but other bytes (hand-built containers can share one) stays apart. + auto vs_b = vs_a; + vs_b[kMeanContainer / 2] ^= 0xff; + const auto third_stream = shader_stream(vs_b, ps); + auto third = keep(third_stream); + if (!third) { check(false, "the equal-checksum stream is captured"); return; } + const auto vs3 = stage_of(*third, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + check(vs3.pShaderBytecode != vs1.pShaderBytecode && holds(vs3, vs_b) && holds(vs1, vs_a), + "equal checksums with different bytes are not merged, and each keeps its own bytes"); + check(stage_of(*third, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS).pShaderBytecode == ps1.pShaderBytecode, + "the third stream's PS, equal to the others, is still shared"); + + // Containers without a checksum (all zero, as hand-built ones have) are told apart by their bytes too. + const auto bare = container(4096, 0, 3); + const auto bare_again = bare; + auto bare_other = bare; + bare_other.back() ^= 0x01; + const auto s4 = shader_stream(bare, ps), s5 = shader_stream(bare_again, ps), s6 = shader_stream(bare_other, ps); + auto r4 = keep(s4); + auto r5 = keep(s5); + auto r6 = keep(s6); + if (!r4 || !r5 || !r6) { check(false, "the checksum-less streams are captured"); return; } + const auto b4 = stage_of(*r4, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + const auto b5 = stage_of(*r5, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + const auto b6 = stage_of(*r6, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + check(b4.pShaderBytecode == b5.pShaderBytecode && holds(b4, bare), "equal checksum-less bytecode is shared"); + check(b6.pShaderBytecode != b4.pShaderBytecode && holds(b6, bare_other), + "checksum-less bytecode that differs in its last byte is not merged"); + + // A derived PSO keeps the base's copies, and a record keeps the shared bytes alive after the others are gone. + std::vector patched = first->bytes(); + auto derived = rt::d3d12_xs::PsoStreamRecord::derived(*first, std::move(patched)); + first.reset(); + second.reset(); + const auto vs_derived = stage_of(*derived, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + check(vs_derived.pShaderBytecode == vs1.pShaderBytecode && holds(vs_derived, vs_a), + "a derived record shares the base's bytecode and keeps it after the base records are freed"); + derived.reset(); + auto again = keep(first_stream); + check(again && holds(stage_of(*again, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS), vs_a) && + holds(stage_of(*again, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS), ps), + "bytecode captured again after every record that held it was freed holds the source bytes"); +} + +void test_many_streams_share_their_bytecode() { + // N records of one VS and one PS: the streams' bytes are each record's own, the bytecode is kept once. + constexpr unsigned kRecords = 10000; + const auto vs = container(9800, 0x11, 4); + const auto ps = container(9400, 0x22, 5); + const auto stream = shader_stream(vs, ps); + std::vector> records; + records.reserve(kRecords); + const std::uint64_t before = private_bytes(); + for (unsigned i = 0; i < kRecords; ++i) + if (auto record = keep(stream)) + records.push_back(std::move(record)); + const std::uint64_t after = private_bytes(); + check(records.size() == kRecords, "10000 streams are captured"); + if (records.size() != kRecords) return; + const void* vs_kept = stage_of(*records[0], D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS).pShaderBytecode; + const void* ps_kept = stage_of(*records[0], D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS).pShaderBytecode; + std::size_t vs_shared = 0, ps_shared = 0, intact = 0; + for (const auto& record : records) { + const auto v = stage_of(*record, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + const auto p = stage_of(*record, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS); + vs_shared += v.pShaderBytecode == vs_kept; + ps_shared += p.pShaderBytecode == ps_kept; + intact += holds(v, vs) && holds(p, ps) && record->bytes().size() == stream.size(); + } + check(intact == kRecords, "every one of the 10000 records holds the source bytecode and stream size"); + check(vs_shared == kRecords && ps_shared == kRecords, "the 10000 records share one copy of each stage"); + std::printf("INFO 10000 records of a %zu + %zu byte VS/PS: private bytes %+.1f MiB (%.1f MiB if each record kept " + "its own bytecode)\n", + vs.size(), ps.size(), (double(after) - double(before)) / (1024.0 * 1024.0), + double(kRecords) * double(vs.size() + ps.size()) / (1024.0 * 1024.0)); +} + +void test_streams_from_many_threads() { + // PSOs are created on many threads. Records made and freed side by side from the same three containers each hold + // their own source bytes, and the ones still alive at the end share one copy per content. + const std::vector shaders[3] = {container(6000, 0x31, 6), container(7000, 0x32, 7), + container(8000, 0x33, 8)}; + const std::vector streams[3] = {shader_stream(shaders[0], shaders[1]), + shader_stream(shaders[1], shaders[2]), + shader_stream(shaders[2], shaders[0])}; + constexpr unsigned kThreads = 8, kRounds = 2000; + std::vector>> kept(kThreads); + std::atomic wrong{0}; + std::vector threads; + for (unsigned t = 0; t < kThreads; ++t) + threads.emplace_back([&, t] { + for (unsigned i = 0; i < kRounds; ++i) { + const unsigned which = (t + i) % 3; + auto record = keep(streams[which]); + if (!record || !holds(stage_of(*record, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS), shaders[which]) || + !holds(stage_of(*record, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS), shaders[(which + 1) % 3])) + ++wrong; + if (i % 16 == t % 16) kept[t].push_back(std::move(record)); // the others are freed at once + } + }); + for (auto& thread : threads) thread.join(); + std::set copies; + bool intact = true; + for (const auto& list : kept) + for (const auto& record : list) { + const auto v = stage_of(*record, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS); + const auto p = stage_of(*record, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS); + copies.insert(v.pShaderBytecode); + copies.insert(p.pShaderBytecode); + intact = intact && (holds(v, shaders[0]) || holds(v, shaders[1]) || holds(v, shaders[2])); + } + check(wrong.load() == 0 && intact, "records made and freed on 8 threads each hold their source bytecode"); + check(copies.size() == 3, "the records alive after 8 threads share one copy per container (3 in all)"); +} + } // namespace int main() { @@ -295,6 +489,9 @@ int main() { test_stencil_mask_record(); test_view_instancing_is_captured(); test_refusals(); + test_equal_bytecode_is_kept_once(); + test_many_streams_share_their_bytecode(); + test_streams_from_many_threads(); std::printf("%s: %d failure(s)\n", g_failures ? "FAILED" : "OK", g_failures); return g_failures ? 1 : 0; } diff --git a/runtime/test/vk_deferred_destroy_lost_test.cpp b/runtime/test/vk_deferred_destroy_lost_test.cpp new file mode 100644 index 0000000000..daa9ad7685 --- /dev/null +++ b/runtime/test/vk_deferred_destroy_lost_test.cpp @@ -0,0 +1,245 @@ +// The context's deferred deletion queue after a device loss (runtime/src/vulkan_backend.h, +// VulkanContext::defer_destroy). Once the device is lost no retire ticket completes again and acquire() returns before +// its drain, so an object queued then would stay until the context goes, and the queue would grow with every object +// the title releases. +// 1. Buffers deferred before the loss wait for a submission that never comes. +// 2. After the loss, the next deferred destruction frees them and every later one is freed at once: all 1000 buffers +// are gone while the context lives, and the context's own teardown destroys none of them twice. +// 3. A bindless slot and the image view released with it (DeviceState::release in d3d12_vulkan_device.cpp defers +// the slot, then its views), queued before the loss or after it, both wait in the queue. Releasing the slot +// takes the device's descriptor lock, which the caller holds; and until the slot is released the set's pending +// writes and shadow copy may still name the view, which a flush hands to vkUpdateDescriptorSets. At teardown the +// slot is released first, then its view is destroyed. +// 4. A batch that takes the tracker lock after the loss (another queue's vkQueueSubmit found it while this one +// waited for that lock) stops before it flushes the bindless set or records its lists: the loss is marked from +// the interposed vkBeginCommandBuffer, after the batch's first check of it. +// vkDestroyBuffer, vkDestroyImageView and vkBeginCommandBuffer are interposed on a real device's table; only the +// buffers and views the test made are counted. Skips with exit code 77 when no Vulkan 1.3 device is available; +// LEONIDA_VK_VALIDATION=1 runs it under the validation layer. No game data. +#include "vk_test_device.h" +#include "../src/vulkan_backend.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); std::_Exit(1); } \ +} while (0) + +namespace { + +template +std::uint64_t key(Handle handle) { + return static_cast(reinterpret_cast(handle)); +} + +namespace driver { +PFN_vkGetDeviceProcAddr real_get_device = nullptr; +PFN_vkDestroyBuffer real_destroy_buffer = nullptr; +PFN_vkDestroyImageView real_destroy_view = nullptr; +PFN_vkBeginCommandBuffer real_begin = nullptr; + +std::mutex mutex; +std::set ours; // the buffers and views the test made +unsigned destroyed_buffers = 0; // of ours +unsigned destroyed_views = 0; // of ours +std::vector events; // bindless slot releases and destructions of our views, in order +std::atomic lose_at_begin{nullptr}; + +void adopt(std::uint64_t handle) { + std::lock_guard lock(mutex); + ours.insert(handle); +} + +unsigned buffers() { + std::lock_guard lock(mutex); + return destroyed_buffers; +} + +unsigned views() { + std::lock_guard lock(mutex); + return destroyed_views; +} + +VKAPI_ATTR void VKAPI_CALL destroy_buffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks* allocator) { + { + std::lock_guard lock(mutex); + if (ours.erase(key(buffer))) ++destroyed_buffers; + } + real_destroy_buffer(device, buffer, allocator); +} + +VKAPI_ATTR void VKAPI_CALL destroy_view(VkDevice device, VkImageView view, const VkAllocationCallbacks* allocator) { + { + std::lock_guard lock(mutex); + if (ours.erase(key(view))) { + ++destroyed_views; + events.push_back(key(view)); + } + } + real_destroy_view(device, view, allocator); +} + +// As another queue's vkQueueSubmit returning VK_ERROR_DEVICE_LOST would, while this batch is past its own checks. +VKAPI_ATTR VkResult VKAPI_CALL begin(VkCommandBuffer command_buffer, const VkCommandBufferBeginInfo* info) { + const VkResult result = real_begin(command_buffer, info); + if (auto* context = lose_at_begin.exchange(nullptr)) context->mark_device_lost("the test marks the device lost"); + return result; +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { + const std::string_view n(name); + if (n == "vkDestroyBuffer") return reinterpret_cast(destroy_buffer); + if (n == "vkDestroyImageView") return reinterpret_cast(destroy_view); + if (n == "vkBeginCommandBuffer") return reinterpret_cast(begin); + return real_get_device(device, name); +} + +void install(PFN_vkGetDeviceProcAddr device_proc, VkDevice device) { + real_get_device = device_proc; + real_destroy_buffer = reinterpret_cast(device_proc(device, "vkDestroyBuffer")); + real_destroy_view = reinterpret_cast(device_proc(device, "vkDestroyImageView")); + real_begin = reinterpret_cast(device_proc(device, "vkBeginCommandBuffer")); +} +} // namespace driver + +} // namespace + +int main() { + using namespace leonida; + + vktest::Device d; + if (!d.create(false)) { + std::fprintf(stderr, "vk_deferred_destroy_lost_test: no Vulkan 1.3 device, skipped\n"); + return 77; + } + driver::install(d.device_proc, d.device); + const auto create_buffer = d.fn("vkCreateBuffer"); + const auto create_view = d.fn("vkCreateImageView"); + EXPECT(create_buffer && create_view); + const auto make_buffer = [&] { + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = 256; + info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; + info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + VkBuffer buffer = VK_NULL_HANDLE; + EXPECT(create_buffer(d.device, &info, nullptr, &buffer) == VK_SUCCESS && buffer); + driver::adopt(key(buffer)); + return buffer; + }; + const VkImage image = d.image(VK_FORMAT_R8G8B8A8_UNORM, 4, 4, 1, VK_IMAGE_USAGE_SAMPLED_BIT); // d destroys it + EXPECT(image); + const auto make_view = [&] { + VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + info.image = image; + info.viewType = VK_IMAGE_VIEW_TYPE_2D; + info.format = VK_FORMAT_R8G8B8A8_UNORM; + info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + VkImageView view = VK_NULL_HANDLE; + EXPECT(create_view(d.device, &info, nullptr, &view) == VK_SUCCESS && view); + driver::adopt(key(view)); + return view; + }; + + constexpr unsigned before_loss = 500; + constexpr unsigned total = 1000; + constexpr std::uint64_t slot_before = (std::uint64_t(1) << 32) | 3u; + constexpr std::uint64_t slot_after = (std::uint64_t(1) << 32) | 7u; + const VkImageView view_before = make_view(), view_after = make_view(); + { + VulkanContext context(driver::get_device, d.device, true); + EXPECT(context.loaded()); + context.set_bindless_release( + [](void*, std::uint32_t dimension, std::uint32_t index) { + std::lock_guard lock(driver::mutex); + driver::events.push_back((std::uint64_t(dimension) << 32) | index); + }, + nullptr); + + // 1, with a bindless slot and its view among the buffers + for (unsigned i = 0; i < before_loss; ++i) { + context.defer_destroy(DeferredDeletionQueue::Kind::buffer, make_buffer()); + if (i == before_loss / 2) { + context.defer_destroy(DeferredDeletionQueue::Kind::bindless_slot, slot_before); + context.defer_destroy(DeferredDeletionQueue::Kind::image_view, view_before); + } + } + EXPECT(driver::buffers() == 0); + EXPECT(driver::views() == 0); + + // 2 + context.mark_device_lost("the test marks the device lost"); + for (unsigned i = before_loss; i < total; ++i) + context.defer_destroy(DeferredDeletionQueue::Kind::buffer, make_buffer()); + EXPECT(driver::buffers() == total); + EXPECT(driver::views() == 0); // the view queued before the loss still waits behind its slot + + // 3 + context.defer_destroy(DeferredDeletionQueue::Kind::bindless_slot, slot_after); + context.defer_destroy(DeferredDeletionQueue::Kind::image_view, view_after); + context.defer_destroy(DeferredDeletionQueue::Kind::buffer, make_buffer()); // still freed at once + EXPECT(driver::buffers() == total + 1); + EXPECT(driver::views() == 0); + std::lock_guard lock(driver::mutex); + EXPECT(driver::events.empty()); + } + EXPECT(driver::buffers() == total + 1); + EXPECT(driver::views() == 2); + { + std::lock_guard lock(driver::mutex); + const std::vector expected{slot_before, key(view_before), slot_after, key(view_after)}; + EXPECT(driver::events == expected); + } + std::puts("deferred deletion after a loss: buffers freed at once; bindless slots and their views kept, in order"); + + // 4 + { + VulkanContext context(driver::get_device, d.device, true); + EXPECT(context.loaded()); + unsigned prepared = 0; + context.set_bindless_prepare([&](VkCommandBuffer) { + ++prepared; + return true; + }); + constexpr VkDeviceSize size = 4096; + const VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + void* map = nullptr; + const VkBuffer a = d.buffer(size, usage, &map), b = d.buffer(size, usage, &map); // d destroys them + EXPECT(a && b); + ResourceBinding binding; + binding.size = size; + binding.buffer = a; + context.add_resource(1, binding); + binding.buffer = b; + context.add_resource(2, binding); + CommandList copy; + EXPECT(copy.copy_buffer({2, 0, 1, 0, size})); + EXPECT(copy.close()); + const CommandList* lists[] = {©}; + auto queue = std::make_unique(context, d.queue, d.family); + EXPECT(queue->ok()); + EXPECT(queue->execute(lists) == ReplayResult::success); + EXPECT(prepared == 1); // a batch on a live device flushes the set + + driver::lose_at_begin = &context; + EXPECT(queue->execute(lists) == ReplayResult::unsupported); + EXPECT(driver::lose_at_begin.load() == nullptr); // the interposer marked the loss, past the first check + EXPECT(context.is_device_lost()); + EXPECT(prepared == 1); + queue.reset(); + context.remove_resource(1); + context.remove_resource(2); + } + std::puts("a batch that takes the tracker lock after the loss stops before the bindless flush"); + + EXPECT(d.validation_errors() == 0); + std::puts("vk_deferred_destroy_lost: ok"); + return 0; +} diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp index 8334143fd7..6ad7662fda 100644 --- a/runtime/test/xbox_bvh_builder_test.cpp +++ b/runtime/test/xbox_bvh_builder_test.cpp @@ -7,7 +7,9 @@ // an element asking for offline statistics is skipped and leaves its destination untouched, a non-empty XDXR stream // is accepted, rehydration rebuilds from geometry with S_OK (with the title's scratch, with none, and two elements of // one batch without scratch, which the shim gives regions of their own; their structures go to check-build too) and -// refuses a source-only element, and builders are released. +// refuses a source-only element, the scratch the shim makes (and an object a list holds through hold_until_reset) +// outlives a Reset or release of the list right after ExecuteCommandLists until that submission has completed, and +// builders are released. // // xbox_bvh_builder_test the shim // xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered @@ -18,6 +20,7 @@ #include "../shims/shims.h" #include "../src/xdxr_descs.h" +#include #include #include #include @@ -26,6 +29,7 @@ #include #include #include +#include #include namespace rt::shims { @@ -52,6 +56,22 @@ template struct Ref { T** put() { return &p; } }; +// An object only a recording uses, as a shim's own scratch is, handed to a list with hold_until_reset. It counts its +// references and is never freed, so a check can read when the layer let it go. +struct Sentinel final : IUnknown { + std::atomic refs{1}; + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override { + if (!out) return E_POINTER; + *out = nullptr; + if (iid != __uuidof(IUnknown)) return E_NOINTERFACE; + AddRef(); + *out = this; + return S_OK; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; } + ULONG STDMETHODCALLTYPE Release() override { return --refs; } +}; + int fail(const char* what, HRESULT hr = S_OK) { std::fprintf(stderr, "FAIL: %s (hr 0x%08lx)\n", what, static_cast(hr)); return 1; @@ -522,6 +542,88 @@ int main(int argc, char** argv) { : "the batch's first element (its own scratch region) is written for check-build"); } + // ---- the shim's scratch outlives a Reset of the list until the submission that used it has completed ---- + // D3D12 lets the title Reset a list as soon as ExecuteCommandLists returns (only its allocator waits for the GPU), + // and the title rehydrates with ScratchAccelerationStructureData = 0. The scratch the shim made for the build must + // not go back to the arena before the build has run: the next DEFAULT buffer of its size would get its range and + // be zeroed by the CPU while the GPU still uses it. A list released right after the call makes the same promise. + { + Ref next_allocator, other_allocator; + Ref other_list; + Ref kept_as, kept_rb; + if (FAILED(hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(next_allocator.put()))) || + FAILED(hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(other_allocator.put()))) || + FAILED(hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, other_allocator.p, nullptr, + IID_PPV_ARGS(other_list.put()))) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, + kept_as.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, kept_rb.put()))) + return fail("kept-scratch lists or buffers", hr); + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for kept scratch"); + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC kept_desc = zero_scratch_desc; + kept_desc.DestAccelerationStructureData = kept_as->GetGPUVirtualAddress(); + check(rehydrate(builder, list.p, 1, &kept_desc, &source) == S_OK, + "a rehydrate without the title's scratch is recorded for the Reset check"); + // The build's scratch is the one buffer the shim made for this call (one element: its region starts there). + UINT64 scratch_va = 0; + std::vector commands; + if (rt::d3d12::recorded_commands(list.p, commands)) + for (const auto& command : commands) + if (const auto* build = std::get_if(&command)) + scratch_va = build->scratch_va; + const UINT64 scratch_bytes = (blas_info.ScratchDataSizeInBytes + 255) / 256 * 256; + // Static, so a release that comes after this block (the queue's worker, or the teardown after a failed step + // returns early) still finds the object. + static Sentinel reset_sentinel, release_sentinel; + check(scratch_va && rt::d3d12::hold_until_reset(list.p, &reset_sentinel) && + rt::d3d12::hold_until_reset(other_list.p, &release_sentinel), + "the build has the shim's scratch, and both lists hold a sentinel"); + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(kept_rb.p, 0, kept_as.p, 0, blas_info.ResultDataMaxSizeInBytes); + if (FAILED(list->Close()) || FAILED(other_list->Close())) return fail("Close for kept scratch"); + ID3D12CommandList* lists[] = {list.p, other_list.p}; + queue->ExecuteCommandLists(2, lists); + // At once, before any Signal: the one list is Reset on another allocator, the other released. + if (FAILED(list->Reset(next_allocator.p, nullptr))) return fail("Reset right after ExecuteCommandLists"); + other_list->Release(); + other_list.p = nullptr; + Ref probe; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_bytes, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + uav, probe.put()))) + return fail("probe buffer", hr); + const UINT64 probe_va = probe->GetGPUVirtualAddress(); + std::printf("scratch VA 0x%llx, a DEFAULT buffer of its 0x%llx bytes made after the Reset at VA 0x%llx\n", + static_cast(scratch_va), static_cast(scratch_bytes), + static_cast(probe_va)); + check(probe_va + scratch_bytes <= scratch_va || scratch_va + scratch_bytes <= probe_va, + "a DEFAULT buffer made right after the Reset does not get the range of the scratch the submission uses"); + check(reset_sentinel.refs.load() > 1, "an object a list holds outlives the list's Reset after the call"); + check(release_sentinel.refs.load() > 1, "and the list's release after the call"); + // The queue lets go of what a submission kept in the first of its calls that finds the submission completed, + // after that call's own submission. On the queue's worker (LEONIDA_SUBMIT_ASYNC) the release can therefore + // still be running when the fence of that call's Signal is reached. The worker runs the calls in order, so it + // has finished by the time the fence of the next Signal is reached. After the Signal the build needs, the + // loop signals and waits until both objects are released, a few Signals at most. + const auto signal_and_wait = [&] { + if (FAILED(queue->Signal(fence.p, ++fence_value))) return false; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(fence_value, event)) && + WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + return done; + }; + const auto released = [] { return reset_sentinel.refs.load() == 1 && release_sentinel.refs.load() == 1; }; + bool settled = SUCCEEDED(list->Close()) && signal_and_wait(); + for (int i = 0; settled && !released() && i < 8; ++i) settled = signal_and_wait(); + if (!settled || FAILED(device->GetDeviceRemovedReason())) + return fail("the kept-scratch submission did not complete"); + check(header_units(kept_rb.p) > 0, "the structure rehydrated with the kept scratch was built"); + check(released(), "both objects are released once the submission has completed"); + } + // ---- the destructor releases the builder ---- destruct(builder); destruct(builder); // a second destruction of the same storage is ignored diff --git a/runtime/test/xbox_list_cut_spares_test.cpp b/runtime/test/xbox_list_cut_spares_test.cpp new file mode 100644 index 0000000000..e9f6a86f1e --- /dev/null +++ b/runtime/test/xbox_list_cut_spares_test.cpp @@ -0,0 +1,160 @@ +// The spare real lists a list-value cut leaves behind (d3d12_xs_device.cpp restart_recording), on a Vulkan device +// and the queue and list proxies. No game data. +// A recording cut three times leaves three spare real lists when the title resets its list; later recordings cut at +// most once reuse only the last of them, and the other two stay closed and idle until the list is released. A title +// window the layer retires is freed only once every command list whose recording began before the retirement is gone +// (src/command_list_epochs.h), and a list holds the root signatures and pipeline states its recording set until its +// next Reset. The idle spares must therefore drop their recordings when they become spares: they can never be +// executed again before a cut resets them. Without that, the oldest live recording stays the first one's, and the +// root signature it set stays referenced by the two idle spares. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/command_list_epochs.h" + +#include +#include + +#define CHECK(x) \ + do { \ + if (!(x)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); \ + return 1; \ + } \ + } while (0) + +using namespace d3d12test; +namespace xs = rt::d3d12_xs; +namespace epochs = leonida::command_list_epochs; + +namespace { +using Create = HRESULT(WINAPI *)(void *, const void *, ID3D12CommandAllocator *, ID3D12PipelineState *, const IID *, + void **); +// Console list slots on the newer layout (an undetected one reads the same): wait64(address, comparison, reference, +// flags) and SetComputeRootSignature (PC slot 29). +using WaitFn = std::uint64_t(WINAPI *)(void *, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); +using RootSignatureFn = std::uint64_t(WINAPI *)(void *, std::uint64_t); +constexpr unsigned kConsoleWait64 = 74, kConsoleSetComputeRootSignature = 33; +constexpr std::uint64_t kGreaterEqual = 7; // memory >= reference, in D3D12_COMPARISON_FUNC order + +ULONG references(IUnknown *object) { + object->AddRef(); + return object->Release(); +} +} // namespace + +int main() { + xs::set_list_values_enabled(true); + vktest::Device gpu; + auto status = gpu.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + CHECK(status == vktest::DeviceStatus::ready); + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = gpu.instance_proc; + info.instance = gpu.instance; + info.physical = gpu.physical; + info.device = gpu.device; + info.queue = gpu.queue; + info.queue_family = gpu.family; + info.buffer_device_address = true; + ID3D12Device *inner = nullptr; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + CHECK( + SUCCEEDED(xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(&device.p), true))); + rt::d3d12::set_device_outer(inner, device.p); + { + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + Ref allocator; + CHECK(SUCCEEDED(inner->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + Ref fence; + CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + // The work each wait follows: a copy between two buffers. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto desc = buffer_desc(4096); + Ref source, destination; + CHECK(SUCCEEDED(inner->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&source.p)))); + CHECK(SUCCEEDED(inner->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&destination.p)))); + // An empty root signature: the first recording sets it before its first cut, so every cut sets it again on + // the spare that records the next part, which holds it until its next Reset. + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + const auto blob = serialize_root_signature(root_desc); + CHECK(!blob.empty()); + Ref root; + CHECK(SUCCEEDED(inner->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p)))); + // What every wait reads: already met, so no submission is held at a gate. + auto *cell = static_cast(VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE)); + CHECK(cell); + *cell = 1; + + // No other command list is alive in this process: the oldest recording is one of the lists below. + CHECK(epochs::oldest() == UINT64_MAX); + std::uint64_t create_desc[4]{}; + Ref list; + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p, 73))(device.p, create_desc, allocator.p, nullptr, + &__uuidof(ID3D12GraphicsCommandList), + reinterpret_cast(&list.p)))); + CHECK(xs::is_list_proxy(list.p)); + CHECK(SUCCEEDED(list->Close())); + const auto wait = reinterpret_cast(slot(list.p, kConsoleWait64)); + const auto set_root = reinterpret_cast(slot(list.p, kConsoleSetComputeRootSignature)); + UINT64 submitted = 0; + // One recording, executed and waited for: `cuts` waits for a memory value, each after a copy, and a copy + // after the last. + const auto record = [&](unsigned cuts, bool with_root) { + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return false; + if (with_root) set_root(list.p, reinterpret_cast(root.p)); + for (unsigned i = 0; i < cuts; ++i) { + list->CopyBufferRegion(destination.p, 0, source.p, 0, 256); + wait(list.p, reinterpret_cast(cell), kGreaterEqual, 1, 0); + } + list->CopyBufferRegion(destination.p, 0, source.p, 0, 256); + if (FAILED(list->Close()) || xs::list_proxy_part_count(list.p) != cuts + 1) return false; + ID3D12CommandList *lists[1] = {list.p}; + queue->ExecuteCommandLists(1, lists); + return SUCCEEDED(queue->Signal(fence.p, ++submitted)) && + SUCCEEDED(fence->SetEventOnCompletion(submitted, nullptr)); + }; + + xs::reset_list_value_stats(); + // 1. Three cuts: the list has three spare real lists from the next Reset on, each of which set the root + // signature again (the test's reference, the primary list's and the three spares'). + CHECK(record(3, true)); + const ULONG held_by_cuts = references(root.p); + // 2. A title window retired now is freed only once no list recorded before this point is alive. + const std::uint64_t retirement = epochs::advance(); + // 3. Recordings cut at most once: only the last spare records again; the other two stay idle. + constexpr unsigned kRecordings = 8; + for (unsigned i = 0; i < kRecordings; ++i) CHECK(record(i % 2, false)); + const std::uint64_t oldest = epochs::oldest(); + const ULONG held_after = references(root.p); + const auto stats = xs::list_value_stats(); + std::printf("list cut spares: %llu cuts; after %u recordings cut at most once, the oldest live recording " + "began in epoch %llu (the retirement: %llu); the root signature the three-cut recording set has " + "%lu references (%lu after that recording)\n", + static_cast(stats.cuts), kRecordings, + static_cast(oldest), static_cast(retirement), held_after, + held_by_cuts); + CHECK(stats.cuts == 3 + kRecordings / 2 && stats.cut_failures == 0); + CHECK(held_by_cuts == 5); + // Every recording alive began after the retirement: a window retired there would get its ticket now. + CHECK(oldest != UINT64_MAX && oldest >= retirement); + // Nothing but the test holds the root signature: the idle spares let go of what their recordings used. + CHECK(held_after == 1); + VirtualFree(const_cast(cell), 0, MEM_RELEASE); + } + // The list and its spares are gone: no recording is alive. + CHECK(epochs::oldest() == UINT64_MAX); + CHECK(gpu.validation_errors() == 0); + std::puts("list cut spares: idle spare lists hold back no retired title window and hold no root signature"); + return 0; +} diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 79f6554128..122b396c2a 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -2271,7 +2271,20 @@ void test_title_virtual_alloc() { generation = leonida::title_memory_map::generation(); check(free(gfx, 0x1000, MEM_DECOMMIT), "title VirtualFree decommits a page"); check(leonida::title_memory_map::generation() != generation, "title VirtualFree invalidates shadows"); + // A release takes no size: the map change it records is the reservation's own two regions (one page + // decommitted, the rest committed), not the whole address space, so a reader whose pages are elsewhere + // need not look at them again. + generation = leonida::title_memory_map::generation(); check(free(gfx, 0, MEM_RELEASE), "release the graphics allocation"); + const auto base = reinterpret_cast(gfx); + std::uint64_t now = 0; + bool released = false, elsewhere = false; + const auto note = [&](std::uintptr_t from, std::uintptr_t to) { + (from == base && to == base + 0x10000 ? released : elsewhere) = true; + }; + check(leonida::title_memory_map::changes_since(generation, now, 0, UINTPTR_MAX, note) && released && + !elsewhere, + "title VirtualFree of a whole reservation records the reservation's range as the map change"); } for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) { void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 7735c4112c..3ffeeda3e1 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -117,6 +117,13 @@ struct Mock { Mock* completes_with; // fence: once its completed value reaches completes_at, a GetCompletedValue first std::uint64_t completes_at, completes_value; // signals that fence to completes_value (GPU order across queues) bool signals_complete; // queue: a Signal (slot 14) completes the fence at once, as an idle GPU would + // device: an UPLOAD-heap committed resource it makes is a mapped buffer of its own (`mapped`, freed with the last + // reference) with a device address of its own (`gpu_va`, outside the CPU's user range), as the upload chunks of + // console list slot 148 are on a real device. Off, Map hands out g_mock_mapped and the address is 0. + bool mapped_uploads; + std::uint8_t* mapped; // resource: what Map (slot 8) hands out, when set + std::uint64_t gpu_va; // resource: what GetGPUVirtualAddress (slot 11) returns, when set + HRESULT reset_result; // allocator: what Reset (slot 8) returns const void* observed_queue; // optional proxy pair to sample during a forwarded fence call const void* observed_fence; unsigned long observed_queue_refs, observed_fence_refs; @@ -552,8 +559,10 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { *reinterpret_cast(a2) = mock_cpu_origin(); } if (m->kind == Kind::resource && slot == 8 && a3) { // Map(subresource, range, data): the test's readback - *reinterpret_cast(a3) = g_mock_mapped; + *reinterpret_cast(a3) = m->mapped ? m->mapped : g_mock_mapped; } + if (m->kind == Kind::resource && slot == 11 && m->gpu_va) return m->gpu_va; // GetGPUVirtualAddress + if (m->kind == Kind::allocator && slot == 8) return static_cast(m->reset_result); // Reset if (m->kind == Kind::heap && slot == 9) { if (a1) reinterpret_cast(a1)->ptr = kMockHeapCpuStart; return kMockHeapCpuStart; @@ -606,6 +615,10 @@ std::uint64_t WINAPI mock_slot(Mock* self, std::uint64_t a1, std::uint64_t a2, s self->held = nullptr; held->Release(); } + if (left == 0 && self->mapped) { // a mapped upload buffer's memory goes with it (gpu_va stays, for checks) + VirtualFree(self->mapped, 0, MEM_RELEASE); + self->mapped = nullptr; + } return static_cast(left); } else if constexpr (Slot == 5) { // SetPrivateDataInterface(guid, object): keeps one reference ++self->calls[5]; @@ -699,6 +712,13 @@ HRESULT WINAPI mock_create_committed_resource(Mock* self, const D3D12_HEAP_PROPE if (self->create_null || FAILED(self->create_result)) return self->create_result; Mock* child = new_mock(Kind::resource); self->last_child = child; + if (self->mapped_uploads && heap && heap->Type == D3D12_HEAP_TYPE_UPLOAD && desc && desc->Width) { + static std::uint64_t made = 0; + child->mapped = static_cast( + VirtualAlloc(nullptr, static_cast(desc->Width), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!child->mapped) return E_OUTOFMEMORY; + child->gpu_va = 0x0001000000000000ull + (++made << 32); + } return mock_query(child, riid, out); } @@ -2510,6 +2530,199 @@ int check_lists() { return 0; } +// ---- 9a. Upload memory comes back at its allocator's Reset ---- +// AllocateUploadMemory (console list slot 148) is asked every frame (the XDXR builder takes count * 40 bytes per +// build, docs/d3d12_command_objects.md ยง3.3a). The arena only ever advanced: 200 frames of 1 MiB made 25 chunks of +// 8 MiB, and kept them. D3D12 allows an allocator Reset only once the GPU has finished the lists recorded into it, so +// the memory handed out under that allocator is free again then. A list Reset gives nothing back (the allocator's +// other lists may still be pending), and one allocator's Reset leaves another's memory alone. + +constexpr std::uint64_t kUploadMiB = 1 << 20; + +// The resource of the one upload chunk made on `mock` since `seen` CreateCommittedResource calls, or null when there +// was not exactly one; `seen` moves on. +Mock* new_upload_chunk(const Mock* mock, unsigned& seen) { + const unsigned made = mock->calls[27] - seen; + seen = mock->calls[27]; + Mock* const chunk = mock->last_child; + return made == 1 && chunk && chunk->kind == Kind::resource && chunk->mapped ? chunk : nullptr; +} + +// 200 frames on one allocator: list Reset, 1 MiB at alignment 16, Close, allocator Reset. `moved` counts the frames +// whose pointer was not the first frame's, `chunks` the chunks they made. +int upload_frames(const Mock* mock, void* list, void* allocator, unsigned& moved, unsigned& chunks) { + const unsigned before = mock->calls[27]; + std::uint64_t first = 0; + moved = 0; + for (int frame = 0; frame < 200; ++frame) { + EXPECT(hr_of(raw(list, 139, word(allocator), 0)) == S_OK); + const std::uint64_t p = raw(list, 148, kUploadMiB, 16); + EXPECT(p && (p & 15) == 0); + std::memset(reinterpret_cast(p), frame & 0xff, 64); // the title writes what it was handed + if (!first) first = p; + if (p != first) ++moved; + EXPECT(hr_of(raw(list, 9)) == S_OK); // Close + EXPECT(hr_of(raw(allocator, 8)) == S_OK); // the allocator's Reset, once the GPU is done with it + } + chunks = mock->calls[27] - before; + std::printf("%s: 200 frames of 1 MiB on one allocator: the pointer moved in %u, %u upload chunks made\n", g_label, + moved, chunks); + return 0; +} + +// A device whose upload chunks are mapped buffers with their own device addresses, two allocator proxies and a +// closed list on each. +struct UploadSetup { + Mock* mock = nullptr; + void* device = nullptr; + void* allocator[2] = {}; + Mock* real_allocator[2] = {}; + void* list[2] = {}; + Mock* real_list[2] = {}; +}; + +int make_upload_setup(UploadSetup& s) { + const IID allocator_iid = __uuidof(ID3D12CommandAllocator); + const IID gcl_iid = __uuidof(ID3D12GraphicsCommandList); + s.device = make_device(s.mock, 9, true, true, true); + EXPECT(s.device); + s.mock->mapped_uploads = true; + for (int i = 0; i < 2; ++i) { + EXPECT(hr_of(raw(s.device, 9, 0, word(&allocator_iid), word(&s.allocator[i]))) == S_OK); + s.real_allocator[i] = s.mock->last_child; + EXPECT(xs::is_allocator_proxy(s.allocator[i])); + EXPECT(hr_of(raw(s.device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(s.allocator[i]), 0, word(&gcl_iid), + word(&s.list[i]))) == S_OK); + s.real_list[i] = s.mock->last_child; + EXPECT(hr_of(raw(s.list[i], 9)) == S_OK); // closed, as a title's list is between frames + } + return 0; +} + +bool upload_ranges_apart(std::uint64_t a, std::uint64_t b, std::uint64_t bytes) { + return a + bytes <= b || b + bytes <= a; +} + +int check_upload_rewind() { + UploadSetup s; + if (make_upload_setup(s)) return 1; + void* const list_a = s.list[0]; + void* const list_b = s.list[1]; + void* const allocator_a = s.allocator[0]; + void* const allocator_b = s.allocator[1]; + unsigned seen = s.mock->calls[27]; + + // One chunk serves every frame, and the pointer is the same each time. + unsigned moved = 0, made = 0; + if (upload_frames(s.mock, list_a, allocator_a, moved, made)) return 1; + EXPECT(moved == 0 && made == 1); + Mock* const chunk_a1 = new_upload_chunk(s.mock, seen); + EXPECT(chunk_a1 && chunk_a1->refs == 1); + const std::uint64_t a1 = word(chunk_a1->mapped); + + // The root SRV setter (console 43 -> PC 39) gets the chunk's device address for a pointer into it. + EXPECT(hr_of(raw(list_a, 139, word(allocator_a), 0)) == S_OK); + EXPECT(raw(list_a, 148, kUploadMiB, 16) == a1); + EXPECT(hr_of(raw(list_a, 43, 0, a1 + 0x123)) == S_OK && s.real_list[0]->args[39][1] == chunk_a1->gpu_va + 0x123); + EXPECT(hr_of(raw(list_a, 9)) == S_OK); + + // A failed allocator Reset (the Vulkan layer refuses one while a list records into it) gives nothing back. + s.real_allocator[0]->reset_result = E_FAIL; + EXPECT(hr_of(raw(allocator_a, 8)) == E_FAIL); + s.real_allocator[0]->reset_result = S_OK; + EXPECT(hr_of(raw(list_a, 139, word(allocator_a), 0)) == S_OK); + EXPECT(raw(list_a, 148, kUploadMiB, 16) == a1 + kUploadMiB); + EXPECT(hr_of(raw(list_a, 9)) == S_OK); + EXPECT(hr_of(raw(allocator_a, 8)) == S_OK); + + // Allocator B's memory is its own: A's Resets do not hand it out again. + EXPECT(hr_of(raw(list_b, 139, word(allocator_b), 0)) == S_OK); + const std::uint64_t b1 = raw(list_b, 148, kUploadMiB, 16); + EXPECT(b1 && upload_ranges_apart(b1, a1, 8 * kUploadMiB)); + std::memset(reinterpret_cast(b1), 0xb1, kUploadMiB); + EXPECT(hr_of(raw(list_b, 9)) == S_OK); + Mock* const chunk_b = new_upload_chunk(s.mock, seen); + EXPECT(chunk_b && b1 == word(chunk_b->mapped)); + // Two frames of 16 MiB on A meanwhile: a second chunk for A, then both again. + for (int frame = 0; frame < 2; ++frame) { + EXPECT(hr_of(raw(list_a, 139, word(allocator_a), 0)) == S_OK); + for (int i = 0; i < 16; ++i) { + const std::uint64_t p = raw(list_a, 148, kUploadMiB, 16); + EXPECT(p && upload_ranges_apart(p, b1, kUploadMiB)); + std::memset(reinterpret_cast(p), 0xa0, kUploadMiB); + } + EXPECT(hr_of(raw(list_a, 9)) == S_OK); + EXPECT(hr_of(raw(allocator_a, 8)) == S_OK); + } + Mock* const chunk_a2 = new_upload_chunk(s.mock, seen); + EXPECT(chunk_a2); + const auto* b_bytes = reinterpret_cast(b1); + EXPECT(std::all_of(b_bytes, b_bytes + kUploadMiB, [](std::uint8_t v) { return v == 0xb1; })); + + // A list Reset gives nothing back: B's next pointer is new memory, and B's own Reset brings b1 back. + EXPECT(hr_of(raw(list_b, 139, word(allocator_b), 0)) == S_OK); + const std::uint64_t b2 = raw(list_b, 148, kUploadMiB, 16); + EXPECT(b2 && upload_ranges_apart(b2, b1, kUploadMiB)); + EXPECT(hr_of(raw(list_b, 9)) == S_OK); + EXPECT(hr_of(raw(allocator_b, 8)) == S_OK); + EXPECT(hr_of(raw(list_b, 139, word(allocator_b), 0)) == S_OK); + EXPECT(raw(list_b, 148, kUploadMiB, 16) == b1); + EXPECT(hr_of(raw(list_b, 9)) == S_OK); + // A list records into the allocator of its last Reset: list A on allocator B takes B's memory. + EXPECT(hr_of(raw(allocator_b, 8)) == S_OK); + EXPECT(hr_of(raw(list_a, 139, word(allocator_b), 0)) == S_OK); + EXPECT(raw(list_a, 148, kUploadMiB, 16) == b1); + EXPECT(hr_of(raw(list_a, 9)) == S_OK); + + // A chunk its allocator has not used for a while goes back; the one in use stays. A's frames now fit in its + // newest chunk, so its first one is idle. + EXPECT(chunk_a1->refs == 1 && chunk_a2->refs == 1); + std::uint64_t kept = 0; + for (int frame = 0; frame < 32; ++frame) { + EXPECT(hr_of(raw(list_a, 139, word(allocator_a), 0)) == S_OK); + const std::uint64_t p = raw(list_a, 148, kUploadMiB, 16); + EXPECT(p && (!kept || p == kept)); + kept = p; + EXPECT(hr_of(raw(list_a, 9)) == S_OK); + EXPECT(hr_of(raw(allocator_a, 8)) == S_OK); + } + EXPECT(chunk_a1->refs == 0 && chunk_a1->calls[9] == 1 && chunk_a2->refs == 1 && kept == word(chunk_a2->mapped)); + EXPECT(s.mock->calls[27] == seen); // no chunk made since A's second one + // A pointer into a chunk that went back is no longer translated: it passes through as any other address. + EXPECT(hr_of(raw(list_a, 139, word(allocator_a), 0)) == S_OK); + EXPECT(hr_of(raw(list_a, 43, 0, a1)) == S_OK && s.real_list[0]->args[39][1] == a1); + EXPECT(hr_of(raw(list_a, 9)) == S_OK); + + // An allocator's chunks go with it, and another allocator's stay. + EXPECT(release(list_b) == 0 && release(allocator_b) == 0); + EXPECT(chunk_b->refs == 0 && chunk_b->calls[9] == 1 && chunk_a2->refs == 1); + EXPECT(release(list_a) == 0 && release(allocator_a) == 0); + EXPECT(chunk_a2->refs == 0); + EXPECT(release(s.device) == 0 && s.mock->refs == 0); + std::printf("%s: upload memory comes back at its own allocator's Reset (not a list's), idle chunks go back, an " + "allocator's chunks go with it\n", g_label); + return 0; +} + +// --upload-rewind-off: LEONIDA_UPLOAD_REWIND=0 (set here, before the device's first upload) keeps one arena that +// only advances, as before the rewind: the 200 frames make 25 chunks, and an allocator's release frees none of them. +int run_upload_rewind_off() { + g_label = "xs_proxy_mock --upload-rewind-off"; + EXPECT(_putenv_s("LEONIDA_UPLOAD_REWIND", "0") == 0); + UploadSetup s; + if (make_upload_setup(s)) return 1; + unsigned moved = 0, made = 0; + if (upload_frames(s.mock, s.list[0], s.allocator[0], moved, made)) return 1; + EXPECT(moved == 199 && made == 25); + Mock* const last_chunk = s.mock->last_child; + EXPECT(last_chunk->kind == Kind::resource && last_chunk->refs == 1); + for (int i = 0; i < 2; ++i) EXPECT(release(s.list[i]) == 0 && release(s.allocator[i]) == 0); + EXPECT(last_chunk->refs == 1); + EXPECT(release(s.device) == 0 && s.mock->refs == 0 && last_chunk->refs == 0); + std::printf("%s: PASS (one arena, never rewound)\n", g_label); + return 0; +} + // ---- 10. SignalX layout detection ------------------------------------------------------------ // A fence at queue slot 25 while the layout is still unknown is itself the newer-layout evidence: a title that // signals only through SignalX never reaches Signal/Wait at 16/17, so an unanswered SignalX used to return @@ -5403,12 +5616,13 @@ int main(int argc, char** argv) { if (std::strcmp(argv[1], "--env-slots-74") == 0) return run_env_slots(true, true); if (std::strcmp(argv[1], "--env-slots-70") == 0) return run_env_slots(true, false, true); if (std::strcmp(argv[1], "--slot133-layout") == 0) return run_slot133_layout_word(); + if (std::strcmp(argv[1], "--upload-rewind-off") == 0) return run_upload_rewind_off(); return run_fault_mode(argv[1]); } if (argc != 1) return 2; if (check_tail(true) || check_host_device_floor() || check_levels() || check_slot48() || check_fence1() || check_fence_completed_value() || check_create_failures() || check_open_shared() || - check_alloc_failures() || check_allocators() || check_xbox_slots() || check_lists() || + check_alloc_failures() || check_allocators() || check_xbox_slots() || check_lists() || check_upload_rewind() || check_signalx_detection() || check_list_tail_names() || check_console_command_list() || check_custom_heap_properties() || check_resource_allocation_info() || check_slot70() || check_slot70_raw_buffer() ||