From b558934d7b3c02f03e7dd393a62ea701413c2c63 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:11:24 -0600 Subject: [PATCH 1/9] Structure builder: root views as memory by address, windows of its own on the card, upload memory below 2^37 The ray-tracing structure builder's 52 programs translate, validate and make host pipelines on the 7900 XTX (its waves have 32-64 lanes). What kept it from working, from a first run (light-1, VICTORY_BVH_QUARANTINE=1) and the code: - a root view ends with the host copy (a 4 MiB window); structures of megabytes cross it. Programs with a spilled user-data table now reach what their root views name by address (USER_ROOT_ADDRESS), as upstream VIctory 0f637570 does. - the list's upload memory (instance descriptions) came from the process heap, above 2^40, where shaders' addresses do not reach (upstream 0f637570, 6d021fe3). - the 1,023 numbered copies of 4 MiB ran out in the first frame: pages come in windows of 256 KiB (4 MiB around what a dispatch names), 16,383 at most. - what the builder stores came back to title memory; now only what it stores in small title buffers it names (sizes the title reads). - the directory lay in the PC's memory and every access stored a fault note. - a list without a view heap gets the title's; a dropped stage rests the builder for a frame, not for the run. Off unless VICTORY_BVH_BUILDER=1, as before. VICTORY_UPLOAD_LOW=0, VICTORY_LENT_HEAP=0, VICTORY_MEMORY_WINDOW_KB, VICTORY_MEMORY_CARD_MB. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 21 ++ crates/victory-gpu/src/draw.rs | 39 +- crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/list.rs | 28 +- crates/victory-gpu/src/memory.rs | 389 +++++++++++++------- crates/victory-gpu/src/pipeline.rs | 40 +- crates/victory-gpu/src/pipeline/make.rs | 6 + crates/victory-gpu/src/shadow.rs | 71 +++- crates/victory-gpu/src/upload.rs | 168 +++++++++ crates/victory-shader/src/emit/intersect.rs | 6 +- crates/victory-shader/src/emit/lower.rs | 121 +++++- crates/victory-shader/src/emit/mod.rs | 2 +- crates/victory-shader/src/emit/shader.rs | 11 +- 13 files changed, 727 insertions(+), 177 deletions(-) create mode 100644 crates/victory-gpu/src/upload.rs diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 39e8b68..8d0a6fe 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -320,6 +320,27 @@ fn changed_slots( first.min(last)..last } +/// The title's view heap that shaders of a list without one get their views +/// from (`draw.rs`, `bind`): the title's structure builder binds root views +/// only, and the host shows those, and memory by address, through heap slots. +/// The biggest there is. `VICTORY_LENT_HEAP=0`: none, such a dispatch is +/// dropped, as before. +#[cfg(windows)] +pub(crate) fn lent_heap() -> Option { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_LENT_HEAP").is_none_or(|v| v != "0")) { + return None; + } + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + // SAFETY: registered heaps are live (removed when dropped). + .map(|&(_, _, h)| (h, unsafe { &*(h as *const Heap) })) + .filter(|(_, heap)| !heap.samplers() && matches!(heap.host.get(), Some(Some(_)))) + .max_by_key(|(_, heap)| heap.desc.count) + .map(|(h, _)| h) +} + /// Gives back dynamic slots of the host heap behind the title heap at /// `heap`, if that heap still exists. #[cfg(windows)] diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2b6f8a0..b4174c9 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -953,10 +953,17 @@ impl State { dword: u32, memory: Option<&crate::memory::Ready>, ) -> u32 { - use victory_shader::emit::{USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS}; + use victory_shader::emit::{USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS}; if kind == USER_MEMORY_BASE { return memory.map_or(0, |m| m.base); } + if kind == USER_ROOT_ADDRESS || kind == USER_ROOT_ADDRESS + 1 { + return match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::View(address)) if kind == USER_ROOT_ADDRESS => address as u32, + Some(&Root::View(address)) => (address >> 32) as u32, + _ => 0, + }; + } if kind == USER_VIEW_BIAS { // The view begins on 16 bytes of the copy the address finds // (`root_uav`, `root_srv_table`). @@ -1014,7 +1021,7 @@ impl State { list: &HostList, t: &crate::pipeline::Translated, compute: bool, - writes: bool, + use_: crate::memory::Use, ) -> Option { let heap = match self.heaps[0] { 0 => None, @@ -1033,7 +1040,7 @@ impl State { addresses.push(self.view_address(compute, u.slot, u.dword)); } } - crate::memory::ready(list, heap, &addresses, &constants, writes) + crate::memory::ready(list, heap, &addresses, &constants, use_) } /// The bound heap holding `handle`. @@ -1154,6 +1161,15 @@ impl State { if crate::host::walls_trace() { self.walls_census(p, compute); } + // A list without a view heap: one of the title's for the views the + // host itself puts into heap slots. + if self.heaps[0] == 0 + && p.stages.iter().any(|s| !s.root_uavs.is_empty() || !s.root_srvs.is_empty()) + && let Some(heap) = crate::descriptor::lent_heap() + { + once!("a dispatch without a view heap that needs one gets the title's"); + self.heaps[0] = heap; + } // Heaps first: a root signature with directly indexed heaps must be // set after them. if self.host_heaps != self.heaps { @@ -1221,8 +1237,14 @@ impl State { let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) { // Only through a store by address: what it stores through // views is declared with them. - let writes = writes && t.stores_by_address; - let Some(ready) = self.memory_ready(list, &t, compute, writes) else { + let use_ = if crate::pipeline::is_builder(self.pipeline as This) { + crate::memory::Use::Builder { back: writes } + } else if writes && t.stores_by_address { + crate::memory::Use::Writes + } else { + crate::memory::Use::Reads + }; + let Some(ready) = self.memory_ready(list, &t, compute, use_) else { once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped"); return false; }; @@ -2317,12 +2339,17 @@ impl State { // A stage of the structure builder that cannot be bound is a // dropped stage: the others stop too. if crate::pipeline::is_builder(self.pipeline as This) { - crate::pipeline::builder_off("one of its dispatches could not be bound"); + crate::pipeline::builder_rests("one of its dispatches could not be bound"); } return; } #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_builder(self.pipeline as This) { + crate::capture::op(list as *const _ as usize, || format!("builder {}", p.name)); + self.list_dropped_roots([x, y, z]); + } // SAFETY: an open list with everything set. unsafe { list.list.Dispatch(x, y, z) }; self.buffers_written(); diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 532cf78..a54b4fb 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -69,6 +69,8 @@ mod tdr; #[cfg(windows)] mod texture; #[cfg(windows)] +mod upload; +#[cfg(windows)] mod watch; #[cfg(windows)] diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 140b755..e58f019 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -114,7 +114,7 @@ struct List { /// Ours, after the console layout: memory handed out by /// [`allocate_upload`], kept until the list is reset; the host list the /// calls record into (decision 0007), and the draw state the title set. - uploads: std::sync::Mutex>>, + uploads: std::sync::Mutex>, #[cfg(windows)] host: Option, #[cfg(windows)] @@ -187,7 +187,7 @@ pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { #[cfg(windows)] pub(crate) struct Detached { host: crate::host::HostList, - _uploads: Vec>, + _uploads: Vec, _state: crate::draw::State, } @@ -1481,6 +1481,23 @@ extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: reset(this, allocator, pipeline) } +#[cfg(windows)] +use crate::upload::Upload; + +/// The memory of [`allocate_upload`] where no host GPU reads it by address. +#[cfg(not(windows))] +struct Upload(Vec); + +#[cfg(not(windows))] +impl Upload { + fn new(len: usize) -> Option { + Some(Upload(vec![0; len])) + } + fn start(&mut self) -> *mut u8 { + self.0.as_mut_ptr() + } +} + /// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list /// owns until it is reset, which the CPU writes and the GPU reads at the /// same address; null on failure. The title's BVH builder puts @@ -1494,13 +1511,14 @@ extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mu if this.is_null() || !align.is_power_of_two() { return std::ptr::null_mut(); } - let mut block = vec![0u8; len]; - let start = block.as_mut_ptr(); + let Some(mut block) = Upload::new(len) else { + return std::ptr::null_mut(); + }; + let start = block.start(); // SAFETY: the offset is below `align`, so `size` bytes fit after it. let at = unsafe { start.add(start.align_offset(align)) }; // SAFETY: the title passes one of our lists. let uploads = unsafe { &(*this.cast::()).uploads }; - // Moving the vector keeps its heap block where it is. uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block); at } diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index a85ee02..da67877 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -4,15 +4,22 @@ //! structures; the structures themselves lie in plain title memory, in no //! buffer object). //! -//! The copies are the ones every other access uses ([`crate::shadow`]: a -//! title buffer's copy, or the 4 MiB window of memory outside buffers), so -//! a root view and a raw address reach the same host bytes. This module -//! keeps what a shader needs to find them: +//! A page in a title buffer that holds all of it is in that buffer's copy +//! ([`crate::shadow`]), which every other access uses. A page outside +//! buffers is in a window of this module's own, on the card +//! ([`crate::shadow::by_address`]): 4 MiB around what a dispatch names (the +//! title's pool of dynamic structures), 256 KiB around a page a shader came +//! to by a pointer (the streamed structures lie anywhere between other +//! data; `VICTORY_MEMORY_WINDOW_KB`). +//! +//! This module keeps what a shader needs to find the copies: //! //! - the **directory**: per 64 KiB page of title address space the number //! of the copy that holds the page (0: none) and the page's byte offset -//! in it; one buffer for all lists, entries only ever go from empty to -//! filled; +//! in it; one for all lists, entries only ever go from empty to filled. +//! The CPU writes it in memory of its own and shaders read a copy of that +//! on the card, brought up to date as title memory is (over the bus, every +//! step of every ray waited for it); //! - per view heap a run of slots with a raw unordered access view of each //! numbered copy (slot 0 of the run: a null view, for pages without a //! copy); @@ -25,27 +32,26 @@ //! the read gives 0, the store is dropped, and the fault note only helps //! the next frame. For the structure builder that is the same as a dropped //! stage, so before a dispatch the host makes ready everything it can see -//! the dispatch name: the whole copy around each root view, around each +//! the dispatch name: the window around each root view, around each //! pair of root constants that is a title address and around each root //! constant that is one in 256-byte units (the builder passes structures -//! all three ways), and the 4 MiB after each (a structure may cross a +//! all three ways), and the one after each (a structure may cross a //! window's end). //! shortcut: what a stage reaches only through pointers it reads out of -//! memory (InitHeaders' table of structure addresses, LoadInstances' -//! instance records) is not made ready unless something else named it; -//! the fault count in the log says whether that happens. The whole answer -//! is the extent of the title's allocation around an address, which the -//! memory module of the layer knows and this one does not ask yet. +//! memory (the structures a top-level build's instances name) is there from +//! the second frame on; the fault count in the log says how often that +//! happens. The top level is built anew every frame. +//! +//! **What comes back to title memory**: what the builder stores in title +//! buffers of at most [`BACK`] bytes it names (the sizes the title reads to +//! make a structure smaller). Structures and scratch memory stay on the card. +//! Other programs that store by address declare the copies they name. //! //! shortcut: a copy that is numbered is kept for the rest of the run, and -//! there are at most [`COPIES`] of them (4 MiB windows mostly: 4 GiB at -//! most). Every list with such a shader brings all numbered copies up to -//! date. A dispatch that can store through raw addresses declares the -//! copies it names as written (the bytes are compared afterwards, as for -//! any unordered access view); what a stage stores through pointers it -//! reads out of memory is declared if a stage of the same list names the -//! copy, and otherwise stays in the host's copy until one does. A -//! dirty-page mask written by the shader would bound both. +//! there are at most [`COPIES`] of them. +//! shortcut: the windows a list does not name are brought up to date once a +//! frame, by the first list that reads by address: bytes the title writes +//! there later in the frame are seen a frame late. use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -58,29 +64,54 @@ use crate::host::{HostList, host}; use crate::shadow::Shadow; /// Copies that can be numbered (the run of heap slots is one longer). A -/// listed frame of the opening cutscene names about 50 windows. -const COPIES: u32 = 1023; -/// A window of memory outside buffers (`shadow.rs`). +/// frame of the dorm names 1,100 pages outside the named windows. +const COPIES: u32 = (1 << 14) - 1; +/// A window around memory a dispatch names. const CELL: u64 = 4 << 20; /// A directory page. const PAGE: u64 = 1 << 16; +/// The biggest title buffer whose builder results come back. +const BACK: u64 = 256 << 10; + +/// What a draw or dispatch does with title memory by address. +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum Use { + Reads, + Writes, + /// A stage of the structure builder; `back`: its results come back. + Builder { back: bool }, +} struct Memory { - /// Buffer, its mapping, its GPU address. - directory: (ID3D12Resource, *mut u32, u64), + /// The CPU's entries (number, offset), and the copy shaders read. + directory: (*mut u32, Arc), faults: (ID3D12Resource, *mut u32, u64), - /// Copy `n` is `copies[n - 1]`. - copies: Vec>, + /// Copy `n` is `copies[n - 1]`; whether it is a window of ours. + copies: Vec<(Arc, bool)>, + /// Places of title buffers' copies among `copies`. + numbers: HashMap, /// Per host view heap (by address): the first slot of its run, and how /// many copies have their view there. heaps: HashMap, /// The frame the faults were last read in. frame: u64, + /// The frame our windows were last brought up to date in. + swept: u64, /// Pages asked for this frame that are not the title's memory. refused: std::collections::HashSet, + stats: Stats, } -// SAFETY: the mappings are of buffers the struct owns; all access is under +/// Since the last report (diagnostics). +#[derive(Default)] +struct Stats { + from: Option<(std::time::Instant, u64)>, + uses: [u64; 3], + faults: u64, + back: u64, +} + +// SAFETY: the mappings are of memory the struct owns; all access is under // the mutex. unsafe impl Send for Memory {} @@ -94,54 +125,70 @@ pub(crate) struct Ready { pub(crate) base: u32, } +/// A window around a page a shader came to by a pointer. +fn far_window() -> u64 { + static BYTES: std::sync::OnceLock = std::sync::OnceLock::new(); + *BYTES.get_or_init(|| { + let kb = std::env::var("VICTORY_MEMORY_WINDOW_KB").ok().and_then(|v| v.trim().parse::().ok()); + kb.map(|kb| kb << 10).filter(|b| b.is_power_of_two() && (PAGE..=CELL).contains(b)).unwrap_or(256 << 10) + }) +} + impl Memory { fn new() -> Option { let host = host()?; - let make = |dwords: u64, what: &str| { - let (buffer, data) = host.shared_buffer(dwords * 4)?; - crate::host::name(&buffer, || format!("title memory by address: {what}")); - // SAFETY: a fresh mapping of at least that many bytes. - unsafe { std::ptr::write_bytes(data, 0, (dwords * 4) as usize) }; - // SAFETY: a live buffer. - let gpu = unsafe { buffer.GetGPUVirtualAddress() }; - Some((buffer, data.cast::(), gpu)) - }; + let bytes = u64::from(MEMORY_PAGES) * 8; + // Zeroed, and watched for writes as the title's memory is. + let entries = crate::upload::reserve(bytes as usize)?; + let directory = crate::shadow::by_address(entries as u64, bytes)?; + crate::host::name(&directory.buffer, || "title memory by address: directory".into()); + let (faults, data) = host.shared_buffer(u64::from(MEMORY_FAULTS) * 4)?; + crate::host::name(&faults, || "title memory by address: faults".into()); + // SAFETY: a fresh mapping of at least that many bytes. + unsafe { std::ptr::write_bytes(data, 0, MEMORY_FAULTS as usize * 4) }; + // SAFETY: a live buffer. + let gpu = unsafe { faults.GetGPUVirtualAddress() }; tracing::info!("title memory by address: a shader reads or writes through raw addresses"); Some(Memory { - directory: make(u64::from(MEMORY_PAGES) * 2, "directory")?, - faults: make(u64::from(MEMORY_FAULTS), "faults")?, + directory: (entries as *mut u32, directory), + faults: (faults, data.cast::(), gpu), copies: Vec::new(), + numbers: HashMap::new(), heaps: HashMap::new(), frame: u64::MAX, + swept: u64::MAX, refused: Default::default(), + stats: Stats::default(), }) } - /// Gives the page of `address` its copy, if it has none and the memory - /// is the title's; the place of its copy in `copies`. - fn map(&mut self, address: u64) -> Option { - self.make(address); - let page = address / PAGE; - if page >= u64::from(MEMORY_PAGES) - 1 { - return None; - } - // SAFETY: inside the directory's mapping. - let number = unsafe { self.directory.1.add(page as usize * 2).read() }; - (number as usize).checked_sub(1) + /// The directory's entry of `page`. + fn entry(&self, page: u64) -> *mut u32 { + debug_assert!(page < u64::from(MEMORY_PAGES)); + // SAFETY: inside the directory. + unsafe { self.directory.0.add(page as usize * 2) } } - fn make(&mut self, address: u64) { + /// Gives the page of `address` its copy, if it has none and the memory + /// is the title's (a window of `window` bytes outside buffers); the place + /// of its copy in `copies`. + fn map(&mut self, address: u64, window: u64) -> Option { let page = address / PAGE; // The last entry stays empty: addresses past the directory read it. if page >= u64::from(MEMORY_PAGES) - 1 { - return; + return None; } - // SAFETY: inside the directory's mapping. - let entry = unsafe { self.directory.1.add(page as usize * 2) }; - // SAFETY: as above. - if unsafe { entry.read() } != 0 { - return; + // SAFETY: an entry of the directory. + let mut number = unsafe { self.entry(page).read() }; + if number == 0 { + self.make(page, window); + // SAFETY: as above. + number = unsafe { self.entry(page).read() }; } + (number as usize).checked_sub(1) + } + + fn make(&mut self, page: u64, window: u64) { let start = page * PAGE; // A shader's pointer, or a constant taken for an address, may be // anything: only memory the title has. @@ -152,60 +199,57 @@ impl Memory { self.refused.insert(page); return; } - // The copy a root view at that address would get; a buffer that - // ends inside the page is passed over for what holds all of it. - let whole = |s: &Arc| s.offset_in(start).is_some_and(|_| s.left(start) >= PAGE); - let Some(shadow) = crate::shadow::find(start, 1) - .filter(whole) - .or_else(|| crate::shadow::find(start, PAGE).filter(whole)) - else { - return; + // The copy of a title buffer that holds all of the page, the + // innermost first; else a window of our own. + let whole = |s: &Arc| s.offset_in(start).is_some() && s.left(start) >= PAGE; + let buffer = crate::shadow::in_buffer(start, PAGE).and_then(|_| crate::shadow::find(start, PAGE)).filter(whole); + let own = buffer.is_none(); + let shadow = match buffer { + Some(s) => s, + None => { + if self.copies.len() >= COPIES as usize { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros") + }); + return; + } + let Some(s) = crate::shadow::by_address(start & !(window - 1), window) else { + return; + }; + s + } }; // SAFETY: a live buffer. let flags = unsafe { shadow.buffer.GetDesc() }.Flags; if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { return; } - let n = match self.copies.iter().position(|c| Arc::ptr_eq(c, &shadow)) { - Some(n) => n, + let key = Arc::as_ptr(&shadow) as usize; + let n = match self.numbers.get(&key) { + Some(&n) => n, None if self.copies.len() < COPIES as usize => { - self.copies.push(shadow.clone()); + self.copies.push((shadow.clone(), own)); let n = self.copies.len() - 1; + self.numbers.insert(key, n); // Every page the copy holds whole, not only the one asked - // for: a structure is more than 64 KiB. - // shortcut: a page of a title buffer inside this one that - // has a copy of its own is given this copy too. + // for: a structure is more than 64 KiB. (Not those of title + // buffers inside a window: they have copies of their own.) let (first, len) = shadow.span(); let mut at = first.next_multiple_of(PAGE); while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 { - // SAFETY: inside the directory's mapping. - let other = unsafe { self.directory.1.add((at / PAGE) as usize * 2) }; - // SAFETY: as above; the offset first, as below. - unsafe { - if other.read() == 0 { - other.add(1).write_volatile((at - first) as u32); - other.write_volatile(n as u32 + 1); - } + let entry = self.entry(at / PAGE); + // SAFETY: an entry of the directory. + if unsafe { entry.read() } == 0 && (!own || crate::shadow::in_buffer(at, PAGE).is_none()) { + fill(entry, n, at - first); } at += PAGE; } n } - None => { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros") - }); - return; - } + None => return, }; - let offset = shadow.offset_in(start).unwrap_or(0); - // The offset first: a shader that sees the number sees it too. - // SAFETY: inside the directory's mapping. - unsafe { - entry.add(1).write_volatile(offset as u32); - entry.write_volatile(n as u32 + 1); - } + fill(self.entry(page), n, shadow.offset_in(start).unwrap_or(0)); } /// The pages shaders found empty since the last frame. @@ -223,48 +267,90 @@ impl Memory { unsafe { at.write_volatile(0) }; } } - if !pages.is_empty() { - // Each is an access that read 0 or was dropped. - static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 50 { - tracing::warn!( - pages = pages.len(), - first = format_args!("{:#x}", u64::from(pages[0]) * PAGE), - "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now" - ); - } + if pages.is_empty() { + return; } - for page in pages { - self.map(u64::from(page) * PAGE); + let mut made = 0; + for &page in &pages { + made += usize::from(self.map(u64::from(page) * PAGE, far_window()).is_some()); + } + self.stats.faults += pages.len() as u64; + // Each is an access that read 0 or was dropped. + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 100 { + pages.sort_unstable(); + let first: Vec = pages.iter().take(8).map(|&p| format!("{:#x}", u64::from(p) * PAGE)).collect(); + tracing::warn!( + frame = self.frame, + pages = pages.len(), + made, + copies = self.copies.len(), + ?first, + "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now, of those that are the title's" + ); } } - /// What a dispatch names: the copy around `address` and the 4 MiB - /// after it; their places in `copies`. + /// What a dispatch names: the copy around `address` and the one after it; + /// their places in `copies`. fn name(&mut self, address: u64, named: &mut Vec) { for at in [address, (address & !(CELL - 1)) + CELL] { - if let Some(n) = self.map(at) + if let Some(n) = self.map(at, CELL) && !named.contains(&n) { named.push(n); } } } + + /// Every ten seconds or so, what was used (with the frame's line). + fn report(&mut self) { + let now = std::time::Instant::now(); + let (since, frame) = *self.stats.from.get_or_insert((now, self.frame)); + let seconds = now.duration_since(since).as_secs_f64(); + if seconds < 10.0 { + return; + } + let frames = self.frame.wrapping_sub(frame).max(1) as f64; + let (mut ours, mut bytes) = (0, 0); + for (s, own) in &self.copies { + if *own { + ours += 1; + bytes += s.span().1; + } + } + let s = std::mem::take(&mut self.stats); + tracing::info!( + "title memory by address: {ours} windows ({} MB) and {} title buffers; per frame {:.0} dispatches that read, {:.0} that write, \ + {:.0} of the structure builder, {:.1} pages that had no copy, {:.1} results brought back", + bytes >> 20, + self.copies.len() - ours, + s.uses[0] as f64 / frames, + s.uses[1] as f64 / frames, + s.uses[2] as f64 / frames, + s.faults as f64 / frames, + s.back as f64 / frames + ); + self.stats.from = Some((now, self.frame)); + } +} + +/// The offset first: a shader that sees the number sees it too. +fn fill(entry: *mut u32, n: usize, offset: u64) { + // SAFETY: an entry of the directory, under the mutex. + unsafe { + entry.add(1).write_volatile(offset as u32); + entry.write_volatile(n as u32 + 1); + } } /// Before a draw whose shader reads title memory by address: what its /// root arguments name gets its copies (`addresses`: its root views; /// `constants`: its root constants, see the module), every numbered copy /// has its view in `heap`'s run and is brought up to date when `list` is -/// submitted (and, with `writes`, the named ones copied back after). None if the host -/// cannot hold it; the draw is then dropped. -pub(crate) fn ready( - list: &HostList, - heap: &HostHeap, - addresses: &[u64], - constants: &[u32], - writes: bool, -) -> Option { +/// submitted (what `use_` writes is copied back after, see the module). +/// None if the host cannot hold it; the draw is then dropped. +pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constants: &[u32], use_: Use) -> Option { let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); if guard.is_none() { *guard = Memory::new(); @@ -275,7 +361,13 @@ pub(crate) fn ready( m.frame = frame; m.refused.clear(); m.take_faults(); + m.report(); } + m.stats.uses[match use_ { + Use::Reads => 0, + Use::Writes => 1, + Use::Builder { .. } => 2, + }] += 1; let numbered = m.copies.len(); let mut named = Vec::new(); for &address in addresses { @@ -305,7 +397,7 @@ pub(crate) fn ready( (base, 0) } }; - for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) { + for (n, (shadow, _)) in m.copies.iter().enumerate().skip(made as usize) { let (_, len) = shadow.span(); heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len); } @@ -315,25 +407,68 @@ pub(crate) fn ready( // shortcut: a copy another list numbers meanwhile is brought up to date // by that list's submission, which may run after this one's. const READ: usize = usize::MAX - 0x6d; - const WRITE: usize = usize::MAX - 0x1_0000; + const NAMED: usize = usize::MAX - 0x1_0000; + const WRITE: usize = usize::MAX - 0x2_0000; + const RESULT: usize = usize::MAX / 2; let first_read = list.first_use(READ); - for (n, shadow) in m.copies.iter().enumerate() { + if first_read { + let (start, len) = m.directory.1.span(); + m.directory.1.refresh(list, start, len); + let sweep = m.swept != frame; + m.swept = frame; + for (shadow, own) in &m.copies { + if sweep || !own { + let (start, len) = shadow.span(); + shadow.refresh(list, start, len); + } + } + list.keep(&m.faults.0); + } else if m.copies.len() > numbered { + let (start, len) = m.directory.1.span(); + m.directory.1.refresh(list, start, len); + } + for (shadow, _) in &m.copies[numbered..] { let (start, len) = shadow.span(); - if first_read || n >= numbered { + shadow.refresh(list, start, len); + } + for &n in &named { + let (shadow, own) = &m.copies[n]; + let (start, len) = shadow.span(); + if *own && list.first_use(NAMED - n) { shadow.refresh(list, start, len); } - if writes && named.contains(&n) && list.first_use(WRITE - n) { + if use_ == Use::Writes && list.first_use(WRITE - n) { #[cfg(feature = "diagnostics")] crate::host::wide_write(start, len, 1); shadow.gpu_writes(list, start, len); } } - if first_read { - list.keep(&m.directory.0); - list.keep(&m.faults.0); + if use_ == (Use::Builder { back: true }) { + for &address in addresses { + let Some((start, len)) = crate::shadow::in_buffer(address, 1).filter(|b| b.1 <= BACK) else { + continue; + }; + if !list.first_use(RESULT + start as usize) { + continue; + } + // The copy or copies its pages are in (it need not fill one). + let mut at = start; + while at < start + len { + let end = (at / PAGE + 1) * PAGE; + let n = end.min(start + len) - at; + if let Some(k) = m.map(at, CELL) { + let shadow = &m.copies[k].0; + shadow.refresh(list, at, n); + shadow.gpu_writes(list, at, n); + m.stats.back += 1; + } + at = end; + } + } } + let directory = &m.directory.1; Some(Ready { - directory: m.directory.2, + directory: directory.gpu(directory.span().0), faults: m.faults.2, base, }) diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 971a351..e94d740 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -233,8 +233,11 @@ fn translate(container: &[u8]) -> Result { /// So a builder dispatch runs only while every builder pipeline the title /// has created has a host pipeline; the first builder dispatch makes them /// all on the spot instead of over the next frames (a stage "still being -/// made" would be a dropped stage). One that cannot be made turns the -/// builder off for the rest of the run. +/// made" would be a dropped stage). While one cannot be made the builder +/// is off; it is looked at again when the title creates another. A stage +/// that could not be bound stops the stages after it for the rest of that +/// frame and the next ([`builder_rests`]); it turned the builder off for the +/// rest of the run at first. /// /// shortcut: and only with `VICTORY_BVH_BUILDER=1`, until a run has shown /// the whole builder and the host side of title memory by address @@ -245,15 +248,18 @@ struct Builder { pipelines: Vec>, /// Every one of `pipelines` has a host pipeline. whole: bool, - /// One could not be made. - off: bool, + /// One could not be made, of so many (0: none). + off: usize, + /// No stage runs before this frame. + rests: u64, } #[cfg(windows)] static BUILDER: Mutex = Mutex::new(Builder { pipelines: Vec::new(), whole: false, - off: false, + off: 0, + rests: 0, }); /// Whether `shaders` are a pipeline of the structure builder. @@ -292,13 +298,15 @@ pub(crate) fn is_builder(this: This) -> bool { !this.is_null() && pipeline(this).builder } -/// A stage of the builder was dropped after all: none runs from here on. +/// A stage of the builder was dropped after all: none runs for the rest of +/// this frame and the next (what it fed is not there). #[cfg(windows)] -pub(crate) fn builder_off(why: &'static str) { +pub(crate) fn builder_rests(why: &'static str) { let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); - if !b.off { - b.off = true; - tracing::warn!(why, "the ray-tracing structure builder is turned off for the rest of the run: its stages run all or none"); + b.rests = crate::frame::current() + 2; + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 20 { + tracing::warn!(why, "the ray-tracing structure builder rests for this frame and the next: its stages run all or none"); } } @@ -311,22 +319,24 @@ pub(crate) fn builder_runs() -> bool { return false; } let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); - if b.off { + if b.off == b.pipelines.len() || crate::frame::current() < b.rests { return false; } if b.whole { return true; } - let missing = b.pipelines.iter().filter(|p| !make::now(p)).count(); - if missing > 0 { - b.off = true; + let missing: Vec = b.pipelines.iter().filter(|p| !make::now(p)).map(|p| make::hashes(p)).collect(); + if !missing.is_empty() { + b.off = b.pipelines.len(); tracing::warn!( - missing, + missing = missing.len(), of = b.pipelines.len(), + which = ?missing, "the ray-tracing structure builder stays off: not all of its programs have a host pipeline, and its stages run all or none" ); return false; } + b.off = 0; tracing::info!( pipelines = b.pipelines.len(), "the ray-tracing structure builder runs: all of its programs have host pipelines" diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 138fb2b..39d67b5 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -91,6 +91,12 @@ pub(crate) fn missing(p: &Pending) -> Option { } } +/// The hashes of the shaders `p` is made of. +pub(crate) fn hashes(p: &Pending) -> String { + let hashes: Vec<&str> = p.shaders.iter().map(|s| s.hash.as_str()).collect(); + hashes.join("+") +} + /// Signalled whenever a worker has made a pipeline. static DONE: (Mutex<()>, Condvar) = (Mutex::new(()), Condvar::new()); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 8b127df..93242b7 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -83,6 +83,9 @@ pub(crate) struct Shadow { card: Option, /// A window of title memory outside buffers, not a title buffer's copy. window: bool, + /// Of a copy with two sides: only the dwords the title changed go up, + /// as with [`send_changed`] ([`by_address`]). + changes_only: bool, /// With `crate::inplace`: not a copy at all. `buffer` is placed in a /// heap opened on the title memory itself, so shaders read and write /// the title's own bytes and nothing is copied either way. The heap, @@ -2631,6 +2634,7 @@ impl Shadow { }, card: None, window: false, + changes_only: false, place: None, } } @@ -3515,7 +3519,7 @@ impl Shadow { /// A page of title memory, as read. static TITLE: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } - let Some(card) = self.card.as_ref().filter(|_| send_changed()) else { + let Some(card) = self.card.as_ref().filter(|_| self.changes_only || send_changed()) else { return self.copy(from, to); }; let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none(); @@ -4554,6 +4558,71 @@ fn longest_tail(windows: impl Iterator, address: u64, end: u6 .min() } +/// Whether `[address, address + len)` lies in one title buffer. +pub(crate) fn in_buffer(address: u64, len: u64) -> Option<(u64, u64)> { + let end = address.checked_add(len)?; + let map = buffers_read(); + let found = map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end); + found.map(|(k, e)| (k.0, e.end - k.0)) +} + +/// A copy of the title memory `[start, start + len)` outside buffers for the +/// programs that find memory by address ([`crate::memory`]), on the card: the +/// structures rays are traced through, read with every step of every ray. +/// +/// What shaders write there by address is not brought back to title memory +/// (nothing else reads a structure; the first whole run of the builder wrote +/// garbage over the title's objects), so the copy is the only place that has +/// it. The CPU's side holds the title's bytes as they were last taken, and +/// only dwords the title changed since go up: a page the title writes a part +/// of keeps what shaders wrote in the rest. +pub(crate) fn by_address(start: u64, len: u64) -> Option> { + let host = host()?; + if !cards() || !host.card_ready() { + return None; + } + // At most so much on the card's own memory (2 GiB unless + // `VICTORY_MEMORY_CARD_MB` says otherwise), and while it has room; past + // that the side shaders see is in the PC's memory. + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + static USED: AtomicU64 = AtomicU64::new(0); + let most = *MOST.get_or_init(|| { + let mb = std::env::var("VICTORY_MEMORY_CARD_MB").ok().and_then(|v| v.trim().parse::().ok()); + mb.unwrap_or(2048) << 20 + }); + let room = host.video_memory().is_none_or(|[budget, used, ..]| used + len < budget / 100 * 97); + let (staging, data) = host.shared_buffer(len)?; + let on_card = if room && USED.fetch_add(len, Ordering::Relaxed) + len <= most { + host.uav_buffer(len) + } else { + None + }; + let buffer = match on_card { + Some(buffer) => buffer, + None => host.shared_buffer(len)?.0, + }; + crate::host::name(&staging, || format!("title memory {start:#x}+{len:#x} by address, the CPU's side")); + crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x} by address")); + // (Counted down with the windows' on the card when it goes.) + WINDOW_CARD_BYTES.fetch_add(len, Ordering::Relaxed); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.window = true; + shadow.changes_only = true; + shadow.card = Some(Card { + staging, + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + touched: Default::default(), + size: len, + }); + let shadow = Arc::new(shadow); + CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + Some(shadow) +} + /// Copies of title memory outside buffers, by (start, length). static LOOSE: std::sync::RwLock>> = std::sync::RwLock::new(BTreeMap::new()); diff --git a/crates/victory-gpu/src/upload.rs b/crates/victory-gpu/src/upload.rs new file mode 100644 index 0000000..7ea3776 --- /dev/null +++ b/crates/victory-gpu/src/upload.rs @@ -0,0 +1,168 @@ +//! Memory `allocate_upload` (`list.rs`) hands out: the title's CPU writes +//! it and its shaders read it at the same address (the structure builder's +//! instance descriptions lie there). +//! +//! The console's GPU addresses have 40 bits, and a translated shader that +//! reads by address has no more (`victory_shader`'s `Lower::memory`): memory +//! from the process heap lies above 2^40 and was read at another address, as +//! zeros. So this memory is taken in blocks of 64 KiB out of arenas in +//! [4 GiB, 2^37), as upstream VIctory 0f637570 and 6d021fe3 place it (there +//! an allocation of its own each). An arena is a title buffer to the host +//! copies ([`crate::shadow`]) and lives as long as the process: the directory +//! of memory by address ([`crate::memory`]) keeps the copy it found at an +//! address for good, so the same addresses must stay the same copy. +//! `VICTORY_UPLOAD_LOW=0`: from the process heap, as before. + +use std::sync::{Mutex, OnceLock}; + +/// What blocks are cut on: a page of the directory of memory by address. +const BLOCK: usize = 64 << 10; +/// An arena's size, if one request does not need more. +const ARENA: usize = 4 << 20; + +struct Arena { + at: usize, + /// Per block whether it is handed out. + taken: Vec, +} + +static ARENAS: Mutex> = Mutex::new(Vec::new()); + +/// Upload memory of one request, zeroed, given back when dropped. +pub(crate) struct Upload(Kind); + +enum Kind { + /// Address, bytes. + Low(usize, usize), + Heap(Vec), +} + +fn low() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_UPLOAD_LOW").is_none_or(|v| v != "0")) +} + +/// The first place of `n` free blocks side by side. +fn gap(taken: &[bool], n: usize) -> Option { + let mut free = 0; + for (i, &t) in taken.iter().enumerate() { + free = if t { 0 } else { free + 1 }; + if free == n { + return Some(i + 1 - n); + } + } + None +} + +/// Fresh zeroed memory in [4 GiB, 2^37) (where the directory of memory by +/// address reaches, `MEMORY_PAGES`), write-watched as the title's own +/// pools are (copies then take only written pages). +pub(crate) fn reserve(len: usize) -> Option { + use windows_sys::Win32::System::Memory::{ + MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_RESERVE, MemExtendedParameterAddressRequirements, + PAGE_READWRITE, VirtualAlloc2, + }; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + let mut requirements = MEM_ADDRESS_REQUIREMENTS { + LowestStartingAddress: (1usize << 32) as *mut _, + HighestEndingAddress: ((1usize << 37) - 1) as *mut _, + Alignment: 0, + }; + let mut parameter = MEM_EXTENDED_PARAMETER::default(); + parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64; + parameter.Anonymous2.Pointer = (&raw mut requirements).cast(); + // SAFETY: a fresh allocation; the parameter points at `requirements`, + // which outlives the call. + let at = unsafe { + VirtualAlloc2( + std::ptr::null_mut(), + std::ptr::null(), + len, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + &mut parameter, + 1, + ) + } as usize; + (at != 0).then_some(at) +} + +impl Upload { + pub(crate) fn new(len: usize) -> Option { + if !low() { + return Some(Upload(Kind::Heap(vec![0; len]))); + } + let n = len.max(1).div_ceil(BLOCK); + let mut arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner()); + let found = arenas.iter().enumerate().find_map(|(a, arena)| Some((a, gap(&arena.taken, n)?))); + let (a, first) = match found { + Some(place) => place, + None => { + let blocks = n.max(ARENA / BLOCK); + let at = reserve(blocks * BLOCK)?; + crate::shadow::register(at, at as u64, (blocks * BLOCK) as u64); + tracing::info!(at = format_args!("{at:#x}"), bytes = blocks * BLOCK, "memory for lists' uploads, where shaders reach it by address"); + arenas.push(Arena { at, taken: vec![false; blocks] }); + (arenas.len() - 1, 0) + } + }; + let arena = &mut arenas[a]; + arena.taken[first..first + n].fill(true); + let at = arena.at + first * BLOCK; + // SAFETY: the blocks are the arena's and nobody else's now. + unsafe { std::ptr::write_bytes(at as *mut u8, 0, len) }; + Some(Upload(Kind::Low(at, len))) + } + + pub(crate) fn start(&mut self) -> *mut u8 { + match &mut self.0 { + Kind::Low(at, _) => *at as *mut u8, + Kind::Heap(block) => block.as_mut_ptr(), + } + } +} + +impl Drop for Upload { + fn drop(&mut self) { + 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)) { + let first = (at - arena.at) / BLOCK; + arena.taken[first..first + len.max(1).div_ceil(BLOCK)].fill(false); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blocks_lie_below_40_bits_and_are_used_again_zeroed() { + let mut a = Upload::new(100).unwrap(); + let mut b = Upload::new(BLOCK + 1).unwrap(); + let (pa, pb) = (a.start(), b.start()); + assert!((pa as usize) >= 1 << 32 && (pb as usize) + 2 * BLOCK <= 1 << 40); + assert!((pa as usize).is_multiple_of(BLOCK) && pa != pb); + // SAFETY: 100 bytes were handed out. + unsafe { pa.write_bytes(0xab, 100) }; + drop(a); + // The lowest free place (another test may have taken it meanwhile; + // zeroed either way). + let mut c = Upload::new(100).unwrap(); + // SAFETY: as above. + assert!(unsafe { std::slice::from_raw_parts(c.start(), 100) }.iter().all(|&x| x == 0)); + // More than an arena. + let mut d = Upload::new(ARENA + 1).unwrap(); + // SAFETY: the bytes were handed out. + unsafe { d.start().add(ARENA).write(1) }; + drop(b); + } + + #[test] + fn a_gap_is_blocks_side_by_side() { + assert_eq!(gap(&[true, false, true, false, false, true], 1), Some(1)); + assert_eq!(gap(&[true, false, true, false, false, true], 2), Some(3)); + assert_eq!(gap(&[true, false, true, false, false, true], 3), None); + } +} diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index 78a1d99..e1043f3 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -251,7 +251,6 @@ impl<'a> Lower<'a> { /// computed, `offset` fixed; none of the node's bytes past 127), read /// four at a time. fn bvh_node_words(&mut self, at: NodeAt, base: Option, offset: u32, count: u32) -> Vec { - let c = self.cur; let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); // The second half of a 128-byte node may lie in the next 64 KiB // page, which may be in another copy: its own look, made once. @@ -267,10 +266,11 @@ impl<'a> Lower<'a> { let (low, high) = self.address_plus(low, high, 64); // Every lane in this block runs the instruction. let (handle, byte) = self.bvh_memory(low, high, None); - let k64 = self.s.m.i32(64); + let (k64, c) = (self.s.m.i32(64), self.cur); (handle, self.s.m.bin(c, Bin::Sub, byte, k64)) }), }; + let c = self.cur; if let Some(b) = base { byte = self.s.m.bin(c, Bin::Add, byte, b); } @@ -330,6 +330,8 @@ impl<'a> Lower<'a> { let k16 = self.s.m.i32(16); let words = self.bvh_node_words(at, None, 16, 24); let floats: Vec = words.iter().map(|&w| self.as_float(w)).collect(); + // (The look for the second half goes on in another block.) + let wide_block = self.cur; self.s.m.terminate(wide_block, Term::Br(join)); // 16-bit floats: 24 halves in 12 dwords from byte 16, the low half // of a dword first. diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 6a86f71..44bee8c 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -259,6 +259,9 @@ struct Lower<'a> { /// they are globally coherent; a load in a loop that only waits would /// be made once otherwise. coherent: HashSet<(usize, u32)>, + /// In the instruction being lowered: the host copy its root view's bytes + /// are in ([`Lower::root_memory`]). + root_copy: Option, mask_phis: HashMap, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, @@ -1572,6 +1575,7 @@ impl<'a> Lower<'a> { read_phis: HashSet::new(), stale: HashSet::new(), coherent: HashSet::new(), + root_copy: None, ordered: if x.native.stage == HwStage::Ps { ordered_section(p) } else { @@ -1735,6 +1739,7 @@ impl<'a> Lower<'a> { let Fields::Flat { dst, .. } = &inst.fields else { unreachable!() }; + self.root_copy = None; let name = inst.name(); if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) { return self.memory_flat(inst, b, i); @@ -1778,8 +1783,15 @@ impl<'a> Lower<'a> { if let Some(bias) = self.root_bias(a.param) { off = self.s.m.bin(c, Bin::Add, off, bias); } - Some(self.handle((b, i), &src, false, (11, 0))?) + match self.root_memory(&src, off, guard) { + Some((h, byte)) => { + off = byte; + Some(h) + } + None => Some(self.handle((b, i), &src, false, (11, 0))?), + } }; + let c = self.cur; let dword = |l: &mut Self, byte: V| -> Result { match h { None => l.code_dword(byte), @@ -2999,7 +3011,8 @@ impl<'a> Lower<'a> { /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding /// it and the byte in that view. A page without a copy reads zeros /// (and drops writes) through the null view at the first slot, and its - /// number is left for the host, for lanes that run (`guard`). + /// number is left for the host, for lanes that run (`guard`). Goes on in + /// another block. fn memory(&mut self, lo: V, hi: V, guard: Option) -> (V, V) { use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE}; let c = self.cur; @@ -3031,21 +3044,23 @@ impl<'a> Lower<'a> { ); let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1)); let (copy, start) = (self.as_int(copy), self.as_int(start)); - // A page without a copy: its number, at a place by the number, or - // at the sink for lanes that do not run and pages that have one. + // A page without a copy: its number, at a place by the number. In a + // branch: the notes lie in the PC's memory, and a store there with + // every node of every ray would be most of what a trace does. let zero = k(self, 0); let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero); if let Some(g) = guard { missing = self.s.m.bin(c, Bin::And, missing, g); } let places = k(self, MEMORY_FAULTS - 1); + let faults = self.s.root_uav_handle(SLOT_FAULTS); + let noting = self.begin_guarded(Some(missing)); + let c = self.cur; let place = self.s.m.bin(c, Bin::URem, page, places); let one = k(self, 1); let place = self.s.m.bin(c, Bin::Add, place, one); let k2 = k(self, 2); let place = self.s.m.bin(c, Bin::Shl, place, k2); - let place = self.s.m.select(c, missing, place, zero); - let faults = self.s.root_uav_handle(SLOT_FAULTS); let void = self.s.t.void; let mask = self.s.m.i8(1); self.s.op( @@ -3056,15 +3071,63 @@ impl<'a> Lower<'a> { 140, &[faults, place, iu, page, iu, iu, iu, mask, align], ); + self.end_guarded(noting, &[]); + let c = self.cur; let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0); let slot = self.s.m.bin(c, Bin::Add, base, copy); - let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0)); + // The builder's threads read what others of the dispatch wrote (a + // refit climbs from children to parents): globally coherent. + let coherent = if crate::spill::is_spilled(self.x.native) { 0x4000 } else { 0 }; + let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000 | coherent, 0)); let k64k = k(self, 0xFFFF); let within = self.s.m.bin(c, Bin::And, lo, k64k); let byte = self.s.m.bin(c, Bin::Add, start, within); (h, byte) } + /// The title address in the root view `src` is built around, in a program + /// with a spilled user-data table (`shader.rs` `USER_ROOT_ADDRESS`). + fn root_address(&mut self, src: &Source) -> Option<(V, V)> { + use super::shader::USER_ROOT_ADDRESS; + let Source::Built { address, .. } = src else { + return None; + }; + let rp = *self.x.native.layout.get(address.param)?; + if rp.root != RootType::Descriptor || !crate::spill::is_spilled(self.x.native) { + return None; + } + let used = self.x.native.used.iter().find(|u| u.user_data == rp.user_data)?; + if !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) { + return None; + } + let lo = self.host_word(RootType::Other(USER_ROOT_ADDRESS), rp.slot, 0); + let hi = self.host_word(RootType::Other(USER_ROOT_ADDRESS + 1), rp.slot, 0); + Some((lo, hi)) + } + + /// For an access through such a root view: the raw view of the host copy + /// and the byte in it of the view's byte `off` (signed: an offset below + /// the address stays below it). [`Lower::handle`] gives the same view for + /// the rest of the instruction. None for any other source. Goes on in + /// another block. + /// shortcut: an access of several dwords is taken not to cross the end + /// of a host copy (the builder's records lie on their size). + fn root_memory(&mut self, src: &Source, off: V, guard: Option) -> Option<(V, V)> { + let (lo, hi) = self.root_address(src)?; + let c = self.cur; + let i32t = self.s.t.i32; + let sum = self.s.m.bin(c, Bin::Add, lo, off); + let wrapped = self.s.m.cmp(c, pred::IULT, sum, lo); + let carry = self.s.m.cast(c, Cast::ZExt, wrapped, i32t); + let k31 = self.s.m.i32(31); + let sign = self.s.m.bin(c, Bin::AShr, off, k31); + let hi = self.s.m.bin(c, Bin::Add, hi, carry); + let hi = self.s.m.bin(c, Bin::Add, hi, sign); + let (h, byte) = self.memory(sum, hi, guard); + self.root_copy = Some(h); + Some((h, byte)) + } + /// `global_load_*`, `global_store_*` and `global_atomic_*` on title /// memory by address (`resource::MEMORY`): the address is the VGPR /// pair, each lane its own. @@ -3094,7 +3157,6 @@ impl<'a> Lower<'a> { let (lo, hi) = (word(self, 0)?, word(self, 1)?); let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset)); let guard = self.guard(b, i)?; - let c = self.cur; let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void); let iu = self.s.m.undef(i32t); let align = self.s.m.i32(4); @@ -3112,6 +3174,7 @@ impl<'a> Lower<'a> { return Err("a global load result"); }; let (h, byte) = self.memory(lo, hi, guard); + let c = self.cur; let mask = self.s.m.i8((1u8 << n) - 1); let r = self.s.op( c, @@ -3160,6 +3223,7 @@ impl<'a> Lower<'a> { None => self.s.m.i32(0), }; let (h, byte) = self.memory(lo, hi, guard); + let c = self.cur; // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8. let simple = match op { @@ -3294,6 +3358,7 @@ impl<'a> Lower<'a> { let n = (count - first).min(4); let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first)); let (h, byte) = self.memory(lo, hi, None); + let c = self.cur; let mask = self.s.m.i8((1u8 << n) - 1); let r = self.s.op( c, @@ -5830,6 +5895,7 @@ impl<'a> Lower<'a> { else { unreachable!() }; + self.root_copy = None; let name = inst.name(); if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) { return self.code_smem(inst, a); @@ -5938,7 +6004,14 @@ impl<'a> Lower<'a> { return Ok(()); } if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { - let h = self.handle(site, src, false, (11, 0))?; + let h = match self.root_memory(src, addr, None) { + Some((h, byte)) => { + addr = byte; + h + } + None => self.handle(site, src, false, (11, 0))?, + }; + let c = self.cur; for k in 0..count { let off = self.s.m.i32(4 * k); let a = self.s.m.bin(c, Bin::Add, addr, off); @@ -6645,13 +6718,14 @@ impl<'a> Lower<'a> { /// For a root view the host binds as a raw view that may begin before /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add - /// to offsets through it. Every root UAV, and the root SRVs of programs - /// with a spilled user-data table (the others keep the views they + /// to offsets through it. Every root UAV (root SRVs keep the views they /// have). fn root_bias(&mut self, param: usize) -> Option { use super::shader::USER_VIEW_BIAS; let rp = *self.x.native.layout.get(param)?; - if rp.root != RootType::Descriptor { + // (Title memory by address where the user-data table is spilled: + // [`Lower::root_memory`].) + if rp.root != RootType::Descriptor || crate::spill::is_spilled(self.x.native) { return None; } let kind = self @@ -6661,12 +6735,7 @@ impl<'a> Lower<'a> { .iter() .find(|u| u.user_data == rp.user_data) .map(|u| u.kind); - let biased = match kind { - Some(ResourceType::Uav) => true, - Some(ResourceType::Srv) => crate::spill::is_spilled(self.x.native), - _ => false, - }; - biased.then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0)) + (kind == Some(ResourceType::Uav)).then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0)) } /// The used-resource entry a descriptor loaded from a table falls in. @@ -6738,6 +6807,7 @@ impl<'a> Lower<'a> { Ok(self.s.sampler_handle(self.cur, n)) } Source::Constant(_) => Err("a constant resource descriptor"), + Source::Built { .. } if self.root_copy.is_some() => self.root_copy.ok_or("no copy"), Source::Built { address, .. } => { let rp = *self .x @@ -11001,6 +11071,7 @@ impl<'a> Lower<'a> { } fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + self.root_copy = None; let Fields::Buffer { data, addr, @@ -11163,6 +11234,20 @@ impl<'a> Lower<'a> { } return Ok(()); } + if self.root_address(src).is_some() { + // Title memory by address: the byte in the host copy from here on. + if let Some(element) = index { + if used.is_none_or(|u| u.stride != 1) { + return Err("an indexed access through a root view by address"); + } + off = self.s.m.bin(c, Bin::Add, element, off); + index = None; + } + if let Some((_, byte)) = self.root_memory(src, off, guard) { + off = byte; + } + } + let c = self.cur; let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav); let mut u = if uav { 0x1000 } else { 0 }; if uav && !typed && self.entry(src).is_some_and(|e| self.coherent.contains(&e)) { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index c9c727e..bd453bc 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -118,7 +118,7 @@ pub use lower::{host_settings, set_host_max_wave}; pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, - SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, + SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, set_view_heap_limit, view_heap_limit, }; diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index eb6d589..c73baf6 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -66,9 +66,16 @@ pub const USER_VIEW_ADDRESS: u32 = 0x101; /// begins on 16 bytes of its host buffer; the console's root views begin /// anywhere (the structure builder's counters sit at addresses ending in /// 4 and c). The shader adds the dword to every byte offset through that -/// view. Asked for every root UAV, and for the root SRVs of programs with -/// a spilled user-data table. +/// view. Asked for every root UAV. pub const USER_VIEW_BIAS: u32 = 0x103; +/// `RootType::Other` code of a user-data dword the host computes: the low +/// 32 bits of the title address in the root view of root parameter `slot`; +/// [`USER_ROOT_ADDRESS`] + 1: its bits from 32 up. Programs with a spilled +/// user-data table (the ray-tracing structure builder's) reach what their +/// root views name as title memory by address ([`SLOT_MEMORY`]): a root view +/// has no size, and the host's copy of what it names may end in the middle of +/// it (a structure of megabytes crosses the 4 MiB windows). +pub const USER_ROOT_ADDRESS: u32 = 0x104; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { From bde604e72589022d4e6b84b3fe6c26f334f65427 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:03:24 -0600 Subject: [PATCH 2/9] Title memory by address: pages in arenas, structures' pages made ready ahead Windows of title memory around every page took 8 GB (run light-2, 0.5-1 s a frame): structures are streamed in anywhere between other data. A 64 KiB page outside title buffers now has a page of its own in an arena on the card; only the title's GPU memory is taken; what instances in a list's upload memory name is there before the top level is built, 1 MiB from each root view before the rehydration stages unpack it in place. VICTORY_MEMORY_DUMP= writes the arenas out (diagnostics). Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 10 +- crates/victory-gpu/src/memory.rs | 703 +++++++++++++++++++++---------- crates/victory-gpu/src/shadow.rs | 21 +- crates/victory-gpu/src/upload.rs | 10 + 4 files changed, 516 insertions(+), 228 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b4174c9..f286375 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1030,7 +1030,9 @@ impl State { let (mut addresses, mut constants) = (Vec::new(), Vec::new()); for root in self.roots_ref(compute) { match root { - Root::View(address) => addresses.push(*address), + // (Of a program that only walks structures, the structures' + // views below: its root views are constants and tables.) + Root::View(address) if use_ != crate::memory::Use::Reads => addresses.push(*address), Root::Constants(values) => constants.extend_from_slice(values), _ => {} } @@ -1237,10 +1239,8 @@ impl State { let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) { // Only through a store by address: what it stores through // views is declared with them. - let use_ = if crate::pipeline::is_builder(self.pipeline as This) { - crate::memory::Use::Builder { back: writes } - } else if writes && t.stores_by_address { - crate::memory::Use::Writes + let use_ = if crate::pipeline::is_builder(self.pipeline as This) || writes && t.stores_by_address { + crate::memory::Use::Builds { back: writes } } else { crate::memory::Use::Reads }; diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index da67877..034c244 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -4,15 +4,14 @@ //! structures; the structures themselves lie in plain title memory, in no //! buffer object). //! -//! A page in a title buffer that holds all of it is in that buffer's copy -//! ([`crate::shadow`]), which every other access uses. A page outside -//! buffers is in a window of this module's own, on the card -//! ([`crate::shadow::by_address`]): 4 MiB around what a dispatch names (the -//! title's pool of dynamic structures), 256 KiB around a page a shader came -//! to by a pointer (the streamed structures lie anywhere between other -//! data; `VICTORY_MEMORY_WINDOW_KB`). +//! A 64 KiB page in a title buffer that holds all of it is in that buffer's +//! copy ([`crate::shadow`]), which every other access uses. A page outside +//! buffers has a page of its own in an **arena**: memory of ours with a copy +//! on the card ([`crate::shadow::by_address`]). The streamed structures lie +//! anywhere between other data (6.6 GB of title memory in 4 MiB windows, run +//! light-1; 8 GB in windows of 256 KiB, light-2), so a page is what is kept. //! -//! This module keeps what a shader needs to find the copies: +//! This module keeps what a shader needs to find the pages: //! //! - the **directory**: per 64 KiB page of title address space the number //! of the copy that holds the page (0: none) and the page's byte offset @@ -24,34 +23,35 @@ //! numbered copy (slot 0 of the run: a null view, for pages without a //! copy); //! - the **faults**: the page numbers shaders found empty, read back here -//! once a frame, so the copies exist from the next frame on. A pointer a -//! shader takes out of memory cannot be known before it runs; the -//! addresses a dispatch is given as root views are made ready before it. +//! once a frame, so the pages are there from the next frame on. A pointer a +//! shader takes out of memory cannot be known before it runs. //! //! **A page that is not there when a shader touches it is a lost access**: //! the read gives 0, the store is dropped, and the fault note only helps //! the next frame. For the structure builder that is the same as a dropped -//! stage, so before a dispatch the host makes ready everything it can see -//! the dispatch name: the window around each root view, around each -//! pair of root constants that is a title address and around each root -//! constant that is one in 256-byte units (the builder passes structures -//! all three ways), and the one after each (a structure may cross a -//! window's end). -//! shortcut: what a stage reaches only through pointers it reads out of -//! memory (the structures a top-level build's instances name) is there from -//! the second frame on; the fault count in the log says how often that -//! happens. The top level is built anew every frame. +//! stage, so before one of its dispatches the host makes ready what it can +//! see the dispatch name: +//! +//! - 1 MiB from each root view outside buffers (structures unpacked in place: +//! the title ships them packed and the builder's rehydration stages unpack +//! each once, when it is streamed in); +//! - 4 MiB from each pair of root constants that is a title address and from +//! each root constant that is one in 256-byte units (structures built); +//! - the first page of every structure a list's upload memory names +//! (a top-level build's instances). //! //! **What comes back to title memory**: what the builder stores in title //! buffers of at most [`BACK`] bytes it names (the sizes the title reads to -//! make a structure smaller). Structures and scratch memory stay on the card. -//! Other programs that store by address declare the copies they name. +//! make a structure smaller). Structures and scratch memory stay on the card +//! (the first whole run of the builder wrote garbage over the title's +//! objects). So an arena's page is the only place a structure is whole, and +//! title memory must not go over it: of a page the title wrote only the +//! dwords that changed since they were last taken go up, unless a quarter of +//! a 4 KiB piece changed, which is other data streamed in: then all of it. //! -//! shortcut: a copy that is numbered is kept for the rest of the run, and -//! there are at most [`COPIES`] of them. -//! shortcut: the windows a list does not name are brought up to date once a -//! frame, by the first list that reads by address: bytes the title writes -//! there later in the frame are seen a frame late. +//! shortcut: a page is kept for the rest of the run. +//! shortcut: pages a list does not name are looked at again in turn, over +//! [`SWEEP`] frames. use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -63,52 +63,83 @@ use crate::descriptor::host::HostHeap; use crate::host::{HostList, host}; use crate::shadow::Shadow; -/// Copies that can be numbered (the run of heap slots is one longer). A -/// frame of the dorm names 1,100 pages outside the named windows. -const COPIES: u32 = (1 << 14) - 1; -/// A window around memory a dispatch names. -const CELL: u64 = 4 << 20; +/// Copies that can be numbered (the run of heap slots is one longer). +const COPIES: u32 = (1 << 12) - 1; /// A directory page. const PAGE: u64 = 1 << 16; +/// An arena's bytes. +const ARENA: u64 = 64 << 20; +/// The kernel's page: what is sent whole when much of it changed. +const PIECE: usize = 4096; +/// From a root view; from an address in constants. +const VIEW: u64 = 1 << 20; +const BUILT: u64 = 4 << 20; /// The biggest title buffer whose builder results come back. const BACK: u64 = 256 << 10; +/// Pages taken from the faults of one frame, at most. +const FAULTS: usize = 2048; +/// Frames over which every page is looked at once. +const SWEEP: usize = 32; /// What a draw or dispatch does with title memory by address. #[derive(Clone, Copy, PartialEq)] pub(crate) enum Use { Reads, - Writes, - /// A stage of the structure builder; `back`: its results come back. - Builder { back: bool }, + /// Stores by address, as the structure builder; `back`: its results in + /// small title buffers come back. + Builds { back: bool }, +} + +/// A page of title memory in an arena. +struct Held { + /// Where in the arena's memory, and the arena's place in `copies`. + at: usize, + copy: usize, + /// The write-watch asking after which it was last taken (0: never). + taken: u64, } struct Memory { /// The CPU's entries (number, offset), and the copy shaders read. directory: (*mut u32, Arc), faults: (ID3D12Resource, *mut u32, u64), - /// Copy `n` is `copies[n - 1]`; whether it is a window of ours. - copies: Vec<(Arc, bool)>, + /// Copy `n` is `copies[n - 1]`. + copies: Vec>, /// Places of title buffers' copies among `copies`. numbers: HashMap, + /// Arenas: place in `copies`, address; pages of the last one handed out. + arenas: Vec<(usize, usize)>, + used: u64, + /// By title page. + pages: HashMap, + /// Their numbers in the order they came, and where the sweep is. + order: Vec, + sweep: usize, /// Per host view heap (by address): the first slot of its run, and how /// many copies have their view there. heaps: HashMap, /// The frame the faults were last read in. frame: u64, - /// The frame our windows were last brought up to date in. - swept: u64, /// Pages asked for this frame that are not the title's memory. refused: std::collections::HashSet, stats: Stats, + #[cfg(feature = "diagnostics")] + dump: dump::Dump, } -/// Since the last report (diagnostics). +/// Since the last report. #[derive(Default)] struct Stats { from: Option<(std::time::Instant, u64)>, - uses: [u64; 3], + uses: [u64; 2], faults: u64, + unknown: u64, back: u64, + /// Pages looked at, bytes that changed, pieces sent whole. + looked: u64, + changed: u64, + whole: u64, + micros: u64, } // SAFETY: the mappings are of memory the struct owns; all access is under @@ -125,15 +156,6 @@ pub(crate) struct Ready { pub(crate) base: u32, } -/// A window around a page a shader came to by a pointer. -fn far_window() -> u64 { - static BYTES: std::sync::OnceLock = std::sync::OnceLock::new(); - *BYTES.get_or_init(|| { - let kb = std::env::var("VICTORY_MEMORY_WINDOW_KB").ok().and_then(|v| v.trim().parse::().ok()); - kb.map(|kb| kb << 10).filter(|b| b.is_power_of_two() && (PAGE..=CELL).contains(b)).unwrap_or(256 << 10) - }) -} - impl Memory { fn new() -> Option { let host = host()?; @@ -154,11 +176,17 @@ impl Memory { faults: (faults, data.cast::(), gpu), copies: Vec::new(), numbers: HashMap::new(), + arenas: Vec::new(), + used: ARENA / PAGE, + pages: HashMap::new(), + order: Vec::new(), + sweep: 0, heaps: HashMap::new(), frame: u64::MAX, - swept: u64::MAX, refused: Default::default(), stats: Stats::default(), + #[cfg(feature = "diagnostics")] + dump: Default::default(), }) } @@ -169,87 +197,168 @@ impl Memory { unsafe { self.directory.0.add(page as usize * 2) } } - /// Gives the page of `address` its copy, if it has none and the memory - /// is the title's (a window of `window` bytes outside buffers); the place - /// of its copy in `copies`. - fn map(&mut self, address: u64, window: u64) -> Option { - let page = address / PAGE; - // The last entry stays empty: addresses past the directory read it. - if page >= u64::from(MEMORY_PAGES) - 1 { + /// The place in `copies` of the copy that holds `page`, if one does. + fn copy_of(&self, page: u64) -> Option { + if page >= u64::from(MEMORY_PAGES) { return None; } // SAFETY: an entry of the directory. - let mut number = unsafe { self.entry(page).read() }; - if number == 0 { - self.make(page, window); - // SAFETY: as above. - number = unsafe { self.entry(page).read() }; - } - (number as usize).checked_sub(1) + (unsafe { self.entry(page).read() } as usize).checked_sub(1) } - fn make(&mut self, page: u64, window: u64) { - let start = page * PAGE; - // A shader's pointer, or a constant taken for an address, may be - // anything: only memory the title has. - if self.refused.contains(&page) { - return; + /// Whether `page` can be given a place: in the directory, not turned down + /// this frame, and the title's GPU memory. (A shader's pointer, or a + /// constant taken for an address, may be anything.) + fn possible(&mut self, page: u64) -> bool { + // Not the last entry: addresses past the directory read it, and it + // stays empty. + if page < 0x1_0000 || page >= u64::from(MEMORY_PAGES) - 1 || self.refused.contains(&page) { + return false; } - if !crate::texture::committed(start as *const u8, PAGE as usize) { + let at = (page * PAGE) as usize; + let ours = crate::texture::committed(at as *const u8, PAGE as usize) + && crate::watch::writes(at, at + PAGE as usize, true).is_some(); + if !ours { self.refused.insert(page); - return; + self.stats.unknown += 1; + } + ours + } + + /// Gives a copy a number, if one is left. + fn number(&mut self, shadow: Arc) -> Option { + let key = Arc::as_ptr(&shadow) as usize; + if let Some(&n) = self.numbers.get(&key) { + return Some(n); + } + if self.copies.len() >= COPIES as usize { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros")); + return None; } - // The copy of a title buffer that holds all of the page, the - // innermost first; else a window of our own. - let whole = |s: &Arc| s.offset_in(start).is_some() && s.left(start) >= PAGE; - let buffer = crate::shadow::in_buffer(start, PAGE).and_then(|_| crate::shadow::find(start, PAGE)).filter(whole); - let own = buffer.is_none(); - let shadow = match buffer { - Some(s) => s, - None => { - if self.copies.len() >= COPIES as usize { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros") - }); - return; - } - let Some(s) = crate::shadow::by_address(start & !(window - 1), window) else { - return; - }; - s - } - }; // SAFETY: a live buffer. let flags = unsafe { shadow.buffer.GetDesc() }.Flags; if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { - return; + return None; } - let key = Arc::as_ptr(&shadow) as usize; - let n = match self.numbers.get(&key) { - Some(&n) => n, - None if self.copies.len() < COPIES as usize => { - self.copies.push((shadow.clone(), own)); - let n = self.copies.len() - 1; - self.numbers.insert(key, n); - // Every page the copy holds whole, not only the one asked - // for: a structure is more than 64 KiB. (Not those of title - // buffers inside a window: they have copies of their own.) + self.copies.push(shadow); + let n = self.copies.len() - 1; + self.numbers.insert(key, n); + Some(n) + } + + /// Gives `page` a place, if it has none and the memory is the title's; + /// whether it has one then. + fn map(&mut self, page: u64) -> bool { + if self.copy_of(page).is_some() { + return true; + } + if !self.possible(page) { + return false; + } + let start = page * PAGE; + if crate::shadow::in_buffer(start, PAGE).is_some() { + let Some(shadow) = crate::shadow::find(start, PAGE) else { + return false; + }; + let fresh = !self.numbers.contains_key(&(Arc::as_ptr(&shadow) as usize)); + let Some(n) = self.number(shadow.clone()) else { + return false; + }; + // Every page the copy holds whole, not only the one asked for. + // shortcut: a page of a title buffer inside this one that has a + // copy of its own is given this copy too. + if fresh { let (first, len) = shadow.span(); let mut at = first.next_multiple_of(PAGE); while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 { let entry = self.entry(at / PAGE); // SAFETY: an entry of the directory. - if unsafe { entry.read() } == 0 && (!own || crate::shadow::in_buffer(at, PAGE).is_none()) { + if unsafe { entry.read() } == 0 { fill(entry, n, at - first); } at += PAGE; } - n } - None => return, + fill(self.entry(page), n, start - shadow.span().0); + return true; + } + if self.used == ARENA / PAGE { + let Some(at) = crate::upload::reserve(ARENA as usize) else { + return false; + }; + let Some(shadow) = crate::shadow::by_address(at as u64, ARENA) else { + return false; + }; + let Some(n) = self.number(shadow) else { + return false; + }; + self.arenas.push((n, at)); + self.used = 0; + } + let Some(&(copy, arena)) = self.arenas.last() else { + return false; }; - fill(self.entry(page), n, shadow.offset_in(start).unwrap_or(0)); + let offset = self.used * PAGE; + self.used += 1; + self.pages.insert(page, Held { at: arena + offset as usize, copy, taken: 0 }); + self.order.push(page); + fill(self.entry(page), copy, offset); + true + } + + /// [`Memory::map`] of the pages of `[address, address + len)`, up to the + /// first that is not the title's, and what the title wrote there since + /// they were taken goes into the arenas. + fn ready(&mut self, address: u64, len: u64) { + let first = address / PAGE; + let mut end = first; + while end * PAGE < address + len && self.map(end) { + end += 1; + } + self.bring(first, end); + } + + /// Takes the pages `[first, end)` that are in arenas from title memory + /// where it wrote them. + fn bring(&mut self, first: u64, end: u64) { + if first >= end { + return; + } + let started = std::time::Instant::now(); + let answer = crate::watch::writes((first * PAGE) as usize, (end * PAGE) as usize, true); + for page in first..end { + let Some(held) = self.pages.get_mut(&page) else { + continue; + }; + self.stats.looked += 1; + let wrote = answer + .as_ref() + .map(|(_, w)| w.binary_search_by_key(&(page as usize), |w| w.0).map_or(0, |i| w[i].1)); + let now = answer.as_ref().map_or(1, |a| a.0); + let stale = held.taken == 0 || wrote.is_none_or(|w| w > held.taken); + if !stale { + continue; + } + 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; + let mut title = [0u8; PIECE]; + for piece in (0..PAGE as usize).step_by(PIECE) { + let from = (page * PAGE) as usize + piece; + // (Pages that are not there read as zeros.) + 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) }; + let (changed, whole) = merge(&title, ours, never); + self.stats.changed += changed as u64 * 4; + if whole { + self.stats.whole += 1; + shadow.resend(base + piece, base + piece + PIECE); + } + } + } + self.stats.micros += started.elapsed().as_micros() as u64; } /// The pages shaders found empty since the last frame. @@ -262,7 +371,7 @@ impl Memory { // SAFETY: as above. let page = unsafe { at.read_volatile() }; if page != 0 { - pages.push(page); + pages.push(u64::from(page)); // SAFETY: as above. unsafe { at.write_volatile(0) }; } @@ -270,66 +379,105 @@ impl Memory { if pages.is_empty() { return; } + pages.sort_unstable(); let mut made = 0; for &page in &pages { - made += usize::from(self.map(u64::from(page) * PAGE, far_window()).is_some()); + if made < FAULTS && self.copy_of(page).is_none() && self.map(page) { + made += 1; + self.bring(page, page + 1); + } } self.stats.faults += pages.len() as u64; // Each is an access that read 0 or was dropped. static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 100 { - pages.sort_unstable(); - let first: Vec = pages.iter().take(8).map(|&p| format!("{:#x}", u64::from(p) * PAGE)).collect(); + let said = SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if said < 40 || said.is_multiple_of(100) { + let some: Vec = pages + .iter() + .step_by(pages.len().div_ceil(12)) + .map(|&p| format!("{:#x}", p * PAGE)) + .collect(); tracing::warn!( frame = self.frame, pages = pages.len(), made, - copies = self.copies.len(), - ?first, - "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now, of those that are the title's" + held = self.pages.len(), + ?some, + "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); those that are the title's are there now" ); } } - /// What a dispatch names: the copy around `address` and the one after it; - /// their places in `copies`. - fn name(&mut self, address: u64, named: &mut Vec) { - for at in [address, (address & !(CELL - 1)) + CELL] { - if let Some(n) = self.map(at, CELL) - && !named.contains(&n) - { - named.push(n); + /// The structures named in a list's upload memory around `address` + /// (instances of a top-level build: a structure's address is their last + /// 8 bytes): the first page of each. + fn named_in_upload(&mut self, address: u64) { + let Some((from, len)) = crate::upload::block(address as usize) else { + return; + }; + // SAFETY: the block is handed out and stays mapped; the title wrote + // it before it recorded the dispatch. + let words = unsafe { std::slice::from_raw_parts(from as *const u64, len / 8) }; + let mut seen = std::collections::HashSet::new(); + for &word in words { + if word & 0xFF == 0 && (1 << 32..1 << 37).contains(&word) && seen.insert(word / PAGE) && self.map(word / PAGE) { + let page = word / PAGE; + self.bring(page, page + 1); } } } - /// Every ten seconds or so, what was used (with the frame's line). + /// A title buffer too small to fill its pages, whose results come back: + /// windows of title memory itself around its pages, which go back. + fn small(&mut self, list: &HostList, start: u64, len: u64) { + let mut at = start; + while at < start + len { + let page = at / PAGE; + let n = ((page + 1) * PAGE).min(start + len) - at; + if self.copy_of(page).is_none() + && self.possible(page) + && let Some(shadow) = crate::shadow::by_address(page * PAGE, PAGE) + && let Some(k) = self.number(shadow) + { + fill(self.entry(page), k, 0); + } + if let Some(k) = self.copy_of(page) + && !self.pages.contains_key(&page) + { + self.copies[k].refresh(list, at, n); + self.copies[k].gpu_writes(list, at, n); + self.stats.back += 1; + } + at += n; + } + } + + /// Every ten seconds or so, what was used. fn report(&mut self) { let now = std::time::Instant::now(); let (since, frame) = *self.stats.from.get_or_insert((now, self.frame)); - let seconds = now.duration_since(since).as_secs_f64(); - if seconds < 10.0 { + if now.duration_since(since).as_secs_f64() < 10.0 { return; } let frames = self.frame.wrapping_sub(frame).max(1) as f64; - let (mut ours, mut bytes) = (0, 0); - for (s, own) in &self.copies { - if *own { - ours += 1; - bytes += s.span().1; - } - } let s = std::mem::take(&mut self.stats); tracing::info!( - "title memory by address: {ours} windows ({} MB) and {} title buffers; per frame {:.0} dispatches that read, {:.0} that write, \ - {:.0} of the structure builder, {:.1} pages that had no copy, {:.1} results brought back", - bytes >> 20, - self.copies.len() - ours, + "title memory by address: {} pages ({} MB) in {} arenas, {} copies in all; per frame {:.0} dispatches that read, {:.0} that build, \ + {:.1} pages that had no copy, {:.1} pages turned down, {:.1} results brought back; {:.0} pages looked at, {:.1} KB changed, \ + {:.1} pieces sent whole, {:.2} ms", + self.pages.len(), + (self.pages.len() as u64 * PAGE) >> 20, + self.arenas.len(), + self.copies.len(), s.uses[0] as f64 / frames, s.uses[1] as f64 / frames, - s.uses[2] as f64 / frames, s.faults as f64 / frames, - s.back as f64 / frames + s.unknown as f64 / frames, + s.back as f64 / frames, + s.looked as f64 / frames, + s.changed as f64 / 1024.0 / frames, + s.whole as f64 / frames, + s.micros as f64 / 1000.0 / frames ); self.stats.from = Some((now, self.frame)); } @@ -344,12 +492,32 @@ fn fill(entry: *mut u32, n: usize, offset: u64) { } } +/// Puts what `title` holds into `ours` (what was last taken): the dwords that +/// differ. How many, and whether the whole piece is to be sent again because +/// so many did (or it was never taken). +fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> (usize, bool) { + if never { + ours.copy_from_slice(title); + return (PIECE / 4, true); + } + if ours == title { + return (0, false); + } + let mut changed = 0; + for (t, o) in title.chunks_exact(4).zip(ours.chunks_exact_mut(4)) { + if t != o { + o.copy_from_slice(t); + changed += 1; + } + } + (changed, changed > PIECE / 16) +} + /// Before a draw whose shader reads title memory by address: what its -/// root arguments name gets its copies (`addresses`: its root views; +/// root arguments name is made ready (`addresses`: its root views; /// `constants`: its root constants, see the module), every numbered copy /// has its view in `heap`'s run and is brought up to date when `list` is -/// submitted (what `use_` writes is copied back after, see the module). -/// None if the host cannot hold it; the draw is then dropped. +/// submitted. None if the host cannot hold it; the draw is then dropped. pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constants: &[u32], use_: Use) -> Option { let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); if guard.is_none() { @@ -361,30 +529,60 @@ pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constan m.frame = frame; m.refused.clear(); m.take_faults(); + let n = m.order.len().div_ceil(SWEEP); + for _ in 0..n { + m.sweep = (m.sweep + 1) % m.order.len(); + let page = m.order[m.sweep]; + m.bring(page, page + 1); + } m.report(); } - m.stats.uses[match use_ { - Use::Reads => 0, - Use::Writes => 1, - Use::Builder { .. } => 2, - }] += 1; + let builds = use_ != Use::Reads; + m.stats.uses[usize::from(builds)] += 1; let numbered = m.copies.len(); - let mut named = Vec::new(); - for &address in addresses { - m.name(address, &mut named); - } + // Once per list and page named: the builder dispatches hundreds of times + // a frame with the same arguments. + const READ: usize = usize::MAX - 0x6d; + let named = |kind: usize, at: u64| list.first_use(usize::MAX - (kind << 26) - (at / PAGE) as usize); // A title address in two constants (low dword, then bits 32 to 39), or - // in one in 256-byte units. A constant that only looks like one names - // memory nothing reads; one that is not the title's memory is refused. + // in one in 256-byte units (the builder's alone). A constant that only + // looks like one names memory nothing reads; one that is not the title's + // memory is refused. + let built = if builds { BUILT } else { PAGE }; for (i, &c) in constants.iter().enumerate() { if let Some(&high) = constants.get(i + 1) - && (1..=0xFF).contains(&high) + && (1..=0x1F).contains(&high) && c >= 0x1_0000 { - m.name(u64::from(c) | u64::from(high) << 32, &mut named); + let at = u64::from(c) | u64::from(high) << 32; + if named(1, at) { + m.ready(at, built); + } } - if c >= 0x0100_0000 { - m.name(u64::from(c) << 8, &mut named); + if builds && (0x0100_0000..0x2000_0000).contains(&c) { + let at = u64::from(c) << 8; + if named(1, at) { + m.ready(at, built); + } + } + } + for &at in addresses.iter().filter(|&&a| a >= 1 << 32) { + if !named(2, at) { + continue; + } + match crate::shadow::in_buffer(at, 1) { + Some((start, len)) if builds && len <= BACK => { + if use_ == (Use::Builds { back: true }) { + m.small(list, start, len); + } + m.ready(at, 1); + m.named_in_upload(at); + } + Some(_) => { + m.ready(at, 1); + m.named_in_upload(at); + } + None => m.ready(at, if builds { VIEW } else { PAGE }), } } let key = std::ptr::from_ref(heap) as usize; @@ -397,74 +595,31 @@ pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constan (base, 0) } }; - for (n, (shadow, _)) in m.copies.iter().enumerate().skip(made as usize) { + for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) { let (_, len) = shadow.span(); heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len); } m.heaps.insert(key, (base, m.copies.len() as u32)); - // Once per list, and for copies numbered since: the builder alone - // dispatches hundreds of times a frame. // shortcut: a copy another list numbers meanwhile is brought up to date // by that list's submission, which may run after this one's. - const READ: usize = usize::MAX - 0x6d; - const NAMED: usize = usize::MAX - 0x1_0000; - const WRITE: usize = usize::MAX - 0x2_0000; - const RESULT: usize = usize::MAX / 2; let first_read = list.first_use(READ); - if first_read { - let (start, len) = m.directory.1.span(); - m.directory.1.refresh(list, start, len); - let sweep = m.swept != frame; - m.swept = frame; - for (shadow, own) in &m.copies { - if sweep || !own { - let (start, len) = shadow.span(); - shadow.refresh(list, start, len); - } - } - list.keep(&m.faults.0); - } else if m.copies.len() > numbered { + let from = if first_read { 0 } else { numbered }; + if first_read || m.copies.len() > numbered { let (start, len) = m.directory.1.span(); m.directory.1.refresh(list, start, len); } - for (shadow, _) in &m.copies[numbered..] { + for shadow in &m.copies[from..] { let (start, len) = shadow.span(); shadow.refresh(list, start, len); } - for &n in &named { - let (shadow, own) = &m.copies[n]; - let (start, len) = shadow.span(); - if *own && list.first_use(NAMED - n) { - shadow.refresh(list, start, len); - } - if use_ == Use::Writes && list.first_use(WRITE - n) { - #[cfg(feature = "diagnostics")] - crate::host::wide_write(start, len, 1); - shadow.gpu_writes(list, start, len); - } + if first_read { + list.keep(&m.faults.0); + #[cfg(feature = "diagnostics")] + m.dump(list, addresses); } - if use_ == (Use::Builder { back: true }) { - for &address in addresses { - let Some((start, len)) = crate::shadow::in_buffer(address, 1).filter(|b| b.1 <= BACK) else { - continue; - }; - if !list.first_use(RESULT + start as usize) { - continue; - } - // The copy or copies its pages are in (it need not fill one). - let mut at = start; - while at < start + len { - let end = (at / PAGE + 1) * PAGE; - let n = end.min(start + len) - at; - if let Some(k) = m.map(at, CELL) { - let shadow = &m.copies[k].0; - shadow.refresh(list, at, n); - shadow.gpu_writes(list, at, n); - m.stats.back += 1; - } - at = end; - } - } + #[cfg(feature = "diagnostics")] + if use_ == Use::Reads { + m.dump.walked(addresses); } let directory = &m.directory.1; Some(Ready { @@ -473,3 +628,123 @@ pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constan base, }) } + +/// `VICTORY_MEMORY_DUMP=`: when a file `go` appears there, the arenas +/// as the card holds them are copied out and written (`arena-.bin`), with +/// `pages.txt` (title page, arena, offset) and the structures the walking +/// programs were given: to look at the structures offline. +#[cfg(feature = "diagnostics")] +mod dump { + use super::*; + + #[derive(Default)] + pub(super) struct Dump { + walked: std::collections::BTreeSet, + /// The frame it is written at, and the copies. + due: Option<(u64, Vec<(ID3D12Resource, usize)>)>, + done: bool, + } + + impl Dump { + pub(super) fn walked(&mut self, addresses: &[u64]) { + if !self.done && self.walked.len() < 64 { + self.walked.extend(addresses); + } + } + } + + fn folder() -> Option<&'static std::path::PathBuf> { + static FOLDER: std::sync::OnceLock> = std::sync::OnceLock::new(); + FOLDER.get_or_init(|| std::env::var_os("VICTORY_MEMORY_DUMP").map(Into::into)).as_ref() + } + + fn turn(buffer: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: the same pointer, not counted; the barrier is + // used while the buffer lives. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } + } + + impl Memory { + /// At a list's first use: the copies are recorded into it. + pub(super) fn dump(&mut self, list: &HostList, _: &[u64]) { + let Some(folder) = folder() else { return }; + if let Some((due, _)) = &self.dump.due { + if self.frame < *due { + return; + } + let copies = self.dump.due.take().map(|d| d.1).unwrap_or_default(); + let mut text = String::new(); + for a in &self.dump.walked { + text += &format!("walked {a:#x}\n"); + } + for (page, held) in &self.pages { + let arena = self.arenas.iter().position(|a| a.0 == held.copy).unwrap_or(usize::MAX); + let at = held.at - self.arenas[arena].1; + text += &format!("{:#x} {arena} {at:#x}\n", page * PAGE); + } + let _ = std::fs::write(folder.join("pages.txt"), text); + for (n, (_, data)) in copies.iter().enumerate() { + // SAFETY: a mapping of an arena's bytes; the copies ran + // frames ago. + let bytes = unsafe { std::slice::from_raw_parts(*data as *const u8, ARENA as usize) }; + let _ = std::fs::write(folder.join(format!("arena-{n}.bin")), bytes); + } + tracing::info!(arenas = copies.len(), "title memory by address: the arenas are written out"); + return; + } + if self.dump.done || !folder.join("go").exists() { + return; + } + self.dump.done = true; + let Some(host) = host() else { return }; + let mut copies = Vec::new(); + for &(n, _) in &self.arenas { + let buffer = &self.copies[n].buffer; + let Some((to, data)) = host.shared_buffer(ARENA) else { break }; + // SAFETY: an open list; live buffers of those sizes. The list + // has not used the arena yet. + unsafe { + list.list.ResourceBarrier(&[turn(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.list.CopyBufferRegion(&to, 0, buffer, 0, ARENA); + list.list.ResourceBarrier(&[turn(buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); + } + list.keep(&to); + copies.push((to, data as usize)); + } + self.dump.due = Some((self.frame + 12, copies)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_piece_takes_what_changed_and_is_sent_whole_when_much_did() { + let mut title = [7u8; PIECE]; + let mut ours = vec![0u8; PIECE]; + assert_eq!(merge(&title, &mut ours, true), (PIECE / 4, true)); + assert_eq!(ours, title); + assert_eq!(merge(&title, &mut ours, false), (0, false)); + // A dword of it. + title[41] = 8; + assert_eq!(merge(&title, &mut ours, false), (1, false)); + assert_eq!(ours, title); + // Other data. + title[..PIECE / 2].fill(9); + assert_eq!(merge(&title, &mut ours, false), (PIECE / 8, true)); + assert_eq!(ours, title); + } +} diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 93242b7..9f4a90c 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -3587,6 +3587,11 @@ impl Shadow { self.card.is_some() } + /// Offsets `[from, to)` go up again whole, as the CPU's side has them. + pub(crate) fn resend(&self, from: usize, to: usize) { + self.card_changed(from, to); + } + /// 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) { @@ -4566,16 +4571,14 @@ pub(crate) fn in_buffer(address: u64, len: u64) -> Option<(u64, u64)> { found.map(|(k, e)| (k.0, e.end - k.0)) } -/// A copy of the title memory `[start, start + len)` outside buffers for the -/// programs that find memory by address ([`crate::memory`]), on the card: the -/// structures rays are traced through, read with every step of every ray. +/// A copy of the memory `[start, start + len)` (an arena of +/// [`crate::memory`]'s, its directory, title memory around a small buffer) +/// for the programs that find memory by address, on the card: the structures +/// rays are traced through, read with every step of every ray. /// -/// What shaders write there by address is not brought back to title memory -/// (nothing else reads a structure; the first whole run of the builder wrote -/// garbage over the title's objects), so the copy is the only place that has -/// it. The CPU's side holds the title's bytes as they were last taken, and -/// only dwords the title changed since go up: a page the title writes a part -/// of keeps what shaders wrote in the rest. +/// What shaders write there by address is not brought back, so the copy is +/// 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> { let host = host()?; if !cards() || !host.card_ready() { diff --git a/crates/victory-gpu/src/upload.rs b/crates/victory-gpu/src/upload.rs index 7ea3776..d6f60e5 100644 --- a/crates/victory-gpu/src/upload.rs +++ b/crates/victory-gpu/src/upload.rs @@ -133,6 +133,16 @@ impl Drop for Upload { } } +/// The block handed out that holds `address`: its start and bytes (whole +/// [`BLOCK`]s). +pub(crate) fn block(address: usize) -> Option<(usize, usize)> { + let arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner()); + let arena = arenas.iter().find(|a| (a.at..a.at + a.taken.len() * BLOCK).contains(&address))?; + let first = (address - arena.at) / BLOCK; + let n = arena.taken[first..].iter().take_while(|t| **t).count(); + (n > 0).then_some((arena.at + first * BLOCK, n * BLOCK)) +} + #[cfg(test)] mod tests { use super::*; From 773b403171e31ae96aa61651f7d92aca60f09a65 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:15:29 -0600 Subject: [PATCH 3/9] Title memory by address: packed structures go up whole when the builder unpacks them; small buffers' pages stay title memory The arenas of run light-3, read offline: 2,833 instances, valid top levels and dynamic structures, three quarters of the streamed ones unpacked right. The rest were unpacked a second time (the same bytes streamed in again do not differ from those last taken), into garbage over their neighbours. And the sizes the title reads of a structure (compaction) never came back where their small buffer lay in an arena's page. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/memory.rs | 163 +++++++++++++++++++++++-------- crates/victory-gpu/src/shadow.rs | 8 ++ 2 files changed, 131 insertions(+), 40 deletions(-) diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 034c244..1e4a952 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -32,9 +32,10 @@ //! stage, so before one of its dispatches the host makes ready what it can //! see the dispatch name: //! -//! - 1 MiB from each root view outside buffers (structures unpacked in place: -//! the title ships them packed and the builder's rehydration stages unpack -//! each once, when it is streamed in); +//! - 1 MiB from each root view outside buffers, and where title memory has a +//! packed ("dehydrated") structure there, all of it: the title ships its +//! structures packed, and the builder's rehydration stages unpack each in +//! place once it is streamed in; //! - 4 MiB from each pair of root constants that is a title address and from //! each root constant that is one in 256-byte units (structures built); //! - the first page of every structure a list's upload memory names @@ -46,8 +47,11 @@ //! (the first whole run of the builder wrote garbage over the title's //! objects). So an arena's page is the only place a structure is whole, and //! title memory must not go over it: of a page the title wrote only the -//! dwords that changed since they were last taken go up, unless a quarter of -//! a 4 KiB piece changed, which is other data streamed in: then all of it. +//! dwords that changed since they were last taken go up. A packed structure +//! goes up whole when the builder comes to it, whatever is known of it: the +//! same bytes streamed in again do not differ from those last taken, and the +//! card holds them unpacked (run light-3: a quarter of the structures +//! unpacked a second time, into garbage all over their neighbours). //! //! shortcut: a page is kept for the rest of the run. //! shortcut: pages a list does not name are looked at again in turn, over @@ -69,8 +73,16 @@ const COPIES: u32 = (1 << 12) - 1; const PAGE: u64 = 1 << 16; /// An arena's bytes. const ARENA: u64 = 64 << 20; -/// The kernel's page: what is sent whole when much of it changed. +/// What is compared at a time. const PIECE: usize = 4096; +/// Pages held, at most (2 GiB). +const MOST: usize = 1 << 15; +/// Pages of title memory with small title buffers in them, at most. +const WINDOWS: usize = 512; +/// The biggest packed structure taken for one. +const PACKED: u64 = 64 << 20; +/// A packed structure not named for so many frames is another one. +const AGAIN: u64 = 8; /// From a root view; from an address in constants. const VIEW: u64 = 1 << 20; const BUILT: u64 = 4 << 20; @@ -115,6 +127,10 @@ struct Memory { /// Their numbers in the order they came, and where the sweep is. order: Vec, sweep: usize, + /// Windows of title memory itself ([`Memory::map`]). + windows: usize, + /// Packed structures the builder came to: the frame it last did. + packed: HashMap, /// Per host view heap (by address): the first slot of its run, and how /// many copies have their view there. heaps: HashMap, @@ -135,10 +151,10 @@ struct Stats { faults: u64, unknown: u64, back: u64, - /// Pages looked at, bytes that changed, pieces sent whole. + /// Pages looked at, bytes that changed, packed structures sent. looked: u64, changed: u64, - whole: u64, + packed: u64, micros: u64, } @@ -181,6 +197,8 @@ impl Memory { pages: HashMap::new(), order: Vec::new(), sweep: 0, + windows: 0, + packed: HashMap::new(), heaps: HashMap::new(), frame: u64::MAX, refused: Default::default(), @@ -283,6 +301,23 @@ impl Memory { fill(self.entry(page), n, start - shadow.span().0); return true; } + // Small title buffers in it: what the builder stores in them comes + // back, so title memory itself. + if self.windows < WINDOWS && crate::shadow::small_buffer_in(start, PAGE, BACK) { + if let Some(shadow) = crate::shadow::by_address(start, PAGE) + && let Some(n) = self.number(shadow) + { + self.windows += 1; + fill(self.entry(page), n, 0); + return true; + } + return false; + } + if self.pages.len() >= MOST { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(MOST, "title memory by address: no more pages are taken; others read zeros")); + return false; + } if self.used == ARENA / PAGE { let Some(at) = crate::upload::reserve(ARENA as usize) else { return false; @@ -350,17 +385,49 @@ 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) }; - let (changed, whole) = merge(&title, ours, never); - self.stats.changed += changed as u64 * 4; - if whole { - self.stats.whole += 1; - shadow.resend(base + piece, base + piece + PIECE); - } + self.stats.changed += merge(&title, ours, never) as u64 * 4; + } + if never { + shadow.resend(base, base + PAGE as usize); } } self.stats.micros += started.elapsed().as_micros() as u64; } + /// If title memory has a packed structure at `address` that the builder + /// comes to anew: all of it has its pages, and goes up as it is there. + fn unpacks(&mut self, address: u64) { + if address & 0xFF != 0 || !self.possible(address / PAGE) { + return; + } + let mut header = [0u8; 8]; + crate::host::copy_mapped(header.as_mut_ptr(), address as *const u8, 8, false); + let Some(len) = packed_len(u64::from_le_bytes(header)) else { + return; + }; + let last = self.packed.insert(address, self.frame); + if last.is_some_and(|f| f + AGAIN >= self.frame) { + return; + } + self.ready(address, len); + let mut title = [0u8; PIECE]; + let mut at = address; + while at < address + len { + let n = (PAGE - at % PAGE).min(address + len - at).min(PIECE as u64) as usize; + if let Some(held) = self.pages.get(&(at / PAGE)) { + let place = held.at + (at % PAGE) as usize; + crate::host::copy_mapped(title.as_mut_ptr(), at as *const u8, n, false); + // SAFETY: a page of an arena of ours, under the mutex. + unsafe { std::slice::from_raw_parts_mut(place as *mut u8, n) }.copy_from_slice(&title[..n]); + let shadow = &self.copies[held.copy]; + let base = place - shadow.span().0 as usize; + shadow.resend(base, base + n); + } + at += n as u64; + } + self.stats.packed += 1; + } + /// The pages shaders found empty since the last frame. fn take_faults(&mut self) { let mut pages = Vec::new(); @@ -427,20 +494,14 @@ impl Memory { } } - /// A title buffer too small to fill its pages, whose results come back: - /// windows of title memory itself around its pages, which go back. + /// A small title buffer whose results come back, if its pages are + /// windows of title memory itself (or a copy of the buffer's own). fn small(&mut self, list: &HostList, start: u64, len: u64) { let mut at = start; while at < start + len { let page = at / PAGE; let n = ((page + 1) * PAGE).min(start + len) - at; - if self.copy_of(page).is_none() - && self.possible(page) - && let Some(shadow) = crate::shadow::by_address(page * PAGE, PAGE) - && let Some(k) = self.number(shadow) - { - fill(self.entry(page), k, 0); - } + self.map(page); if let Some(k) = self.copy_of(page) && !self.pages.contains_key(&page) { @@ -464,7 +525,7 @@ impl Memory { tracing::info!( "title memory by address: {} pages ({} MB) in {} arenas, {} copies in all; per frame {:.0} dispatches that read, {:.0} that build, \ {:.1} pages that had no copy, {:.1} pages turned down, {:.1} results brought back; {:.0} pages looked at, {:.1} KB changed, \ - {:.1} pieces sent whole, {:.2} ms", + {:.1} packed structures ({} seen), {:.2} ms; {} windows", self.pages.len(), (self.pages.len() as u64 * PAGE) >> 20, self.arenas.len(), @@ -476,8 +537,10 @@ impl Memory { s.back as f64 / frames, s.looked as f64 / frames, s.changed as f64 / 1024.0 / frames, - s.whole as f64 / frames, - s.micros as f64 / 1000.0 / frames + s.packed as f64 / frames, + self.packed.len(), + s.micros as f64 / 1000.0 / frames, + self.windows ); self.stats.from = Some((now, self.frame)); } @@ -492,16 +555,24 @@ fn fill(entry: *mut u32, n: usize, offset: u64) { } } +/// The bytes of a packed structure whose first two dwords these are: the +/// version (6) with the marks of a bottom level and of one that is packed, +/// and its size unpacked in 64-byte nodes. +fn packed_len(header: u64) -> Option { + let (version, nodes) = (header as u32, header >> 32); + let marks = version >> 16; + (version & 0xFFFF == 6 && marks & 0x8100 == 0x8100 && nodes > 0 && nodes * 64 <= PACKED).then_some(nodes * 64) +} + /// Puts what `title` holds into `ours` (what was last taken): the dwords that -/// differ. How many, and whether the whole piece is to be sent again because -/// so many did (or it was never taken). -fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> (usize, bool) { +/// differ. How many. +fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> usize { if never { ours.copy_from_slice(title); - return (PIECE / 4, true); + return PIECE / 4; } if ours == title { - return (0, false); + return 0; } let mut changed = 0; for (t, o) in title.chunks_exact(4).zip(ours.chunks_exact_mut(4)) { @@ -510,7 +581,7 @@ fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> (usize, bool) { changed += 1; } } - (changed, changed > PIECE / 16) + changed } /// Before a draw whose shader reads title memory by address: what its @@ -567,6 +638,10 @@ pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constan } } for &at in addresses.iter().filter(|&&a| a >= 1 << 32) { + // (Several structures to a page.) + if builds && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) { + m.unpacks(at); + } if !named(2, at) { continue; } @@ -732,19 +807,27 @@ mod tests { use super::*; #[test] - fn a_piece_takes_what_changed_and_is_sent_whole_when_much_did() { + 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, true)); + assert_eq!(merge(&title, &mut ours, true), PIECE / 4); assert_eq!(ours, title); - assert_eq!(merge(&title, &mut ours, false), (0, false)); + assert_eq!(merge(&title, &mut ours, false), 0); // A dword of it. title[41] = 8; - assert_eq!(merge(&title, &mut ours, false), (1, false)); - assert_eq!(ours, title); - // Other data. - title[..PIECE / 2].fill(9); - assert_eq!(merge(&title, &mut ours, false), (PIECE / 8, true)); + assert_eq!(merge(&title, &mut ours, false), 1); assert_eq!(ours, title); } + + #[test] + fn a_packed_structure_is_known_by_its_header() { + let header = |version: u32, nodes: u32| u64::from(version) | u64::from(nodes) << 32; + assert_eq!(packed_len(header(0x8102_0006, 0x9a1a)), Some(0x9a1a * 64)); + // Unpacked, a top level, another version, no size, too big. + assert_eq!(packed_len(header(0x8002_0006, 0x9a1a)), None); + assert_eq!(packed_len(header(0x0000_0006, 5)), None); + assert_eq!(packed_len(header(0x8102_0007, 5)), None); + assert_eq!(packed_len(header(0x8102_0006, 0)), None); + assert_eq!(packed_len(header(0x8102_0006, 1 << 21)), None); + } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 9f4a90c..3f2b89d 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -4571,6 +4571,14 @@ pub(crate) fn in_buffer(address: u64, len: u64) -> Option<(u64, u64)> { found.map(|(k, e)| (k.0, e.end - k.0)) } +/// Whether a title buffer of at most `most` bytes lies in `[address, address +/// + len)`, all of it or in part. +pub(crate) fn small_buffer_in(address: u64, len: u64, most: u64) -> bool { + let map = buffers_read(); + map.range((address.saturating_sub(most), 0)..(address + len, 0)) + .any(|(key, entry)| entry.end > address && entry.end - key.0 <= most) +} + /// A copy of the memory `[start, start + len)` (an arena of /// [`crate::memory`]'s, its directory, title memory around a small buffer) /// for the programs that find memory by address, on the card: the structures From 96bfd0ebecae7f48ad2e1e4f4a3c7c928952c005 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 04:53:33 -0600 Subject: [PATCH 4/9] Stores by address are bounded: title buffers take the builder's only where it was given them to write A directory entry says whether stores by address reach its page (translator and host). Faults take at most 128 pages a frame and 8,192 in all; every slot of the copies' run holds a null view until its copy is there; a page is looked at once a frame. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/draw.rs | 12 +- crates/victory-gpu/src/memory.rs | 126 +++++++++++++++----- crates/victory-shader/src/emit/intersect.rs | 2 +- crates/victory-shader/src/emit/lower.rs | 34 ++++-- crates/victory-shader/src/emit/mod.rs | 2 +- crates/victory-shader/src/emit/shader.rs | 6 +- 6 files changed, 136 insertions(+), 46 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b075c97..7efd5ac 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1061,6 +1061,16 @@ impl State { h => crate::descriptor::heap(h as This).host(), }?; let (mut addresses, mut constants) = (Vec::new(), Vec::new()); + // (What it may write: its root views of unordered access.) + let written: Vec = t + .used + .iter() + .filter(|u| u.kind == ResourceType::Uav && u.root == RootType::Descriptor) + .filter_map(|u| match self.roots_ref(compute).get(usize::from(u.slot)) { + Some(&Root::View(address)) => Some(address), + _ => None, + }) + .collect(); for root in self.roots_ref(compute) { match root { // (Of a program that only walks structures, the structures' @@ -1075,7 +1085,7 @@ impl State { addresses.push(self.view_address(compute, u.slot, u.dword)); } } - crate::memory::ready(list, heap, &addresses, &constants, use_) + crate::memory::ready(list, heap, &addresses, &written, &constants, use_) } /// The bound heap holding `handle`. diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 1e4a952..a1168c5 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -32,7 +32,7 @@ //! stage, so before one of its dispatches the host makes ready what it can //! see the dispatch name: //! -//! - 1 MiB from each root view outside buffers, and where title memory has a +//! - 256 KiB from each root view outside buffers, and where title memory has a //! packed ("dehydrated") structure there, all of it: the title ships its //! structures packed, and the builder's rehydration stages unpack each in //! place once it is streamed in; @@ -53,6 +53,11 @@ //! card holds them unpacked (run light-3: a quarter of the structures //! unpacked a second time, into garbage all over their neighbours). //! +//! **Stores are bounded**: a structure the builder misreads makes it store +//! anywhere. Pages of title buffers take its stores only once one of its +//! dispatches was given that buffer as an unordered access view (its scratch +//! memory, its results); what else a store reaches is an arena's. +//! //! shortcut: a page is kept for the rest of the run. //! shortcut: pages a list does not name are looked at again in turn, over //! [`SWEEP`] frames. @@ -60,7 +65,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; -use victory_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES}; +use victory_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY}; use windows::Win32::Graphics::Direct3D12::*; use crate::descriptor::host::HostHeap; @@ -84,14 +89,17 @@ const PACKED: u64 = 64 << 20; /// A packed structure not named for so many frames is another one. const AGAIN: u64 = 8; /// From a root view; from an address in constants. -const VIEW: u64 = 1 << 20; +const VIEW: u64 = 256 << 10; const BUILT: u64 = 4 << 20; /// The biggest title buffer whose builder results come back. const BACK: u64 = 256 << 10; -/// Pages taken from the faults of one frame, at most. -const FAULTS: usize = 2048; +/// Pages taken from the faults, of one frame and in all, at most: a ray in a +/// structure that is not right goes anywhere, and 2,048 a frame took all the +/// pages there are in the first seconds (run light-4). +const FAULTS: usize = 128; +const FAULTS_ALL: usize = 8192; /// Frames over which every page is looked at once. -const SWEEP: usize = 32; +const SWEEP: usize = 128; /// What a draw or dispatch does with title memory by address. #[derive(Clone, Copy, PartialEq)] @@ -109,6 +117,8 @@ struct Held { copy: usize, /// The write-watch asking after which it was last taken (0: never). taken: u64, + /// The frame it was last looked at in. + looked: u64, } struct Memory { @@ -131,6 +141,10 @@ struct Memory { windows: usize, /// Packed structures the builder came to: the frame it last did. packed: HashMap, + /// Copies of title buffers the builder may store in. + open: std::collections::HashSet, + /// Pages taken from faults. + faulted: usize, /// Per host view heap (by address): the first slot of its run, and how /// many copies have their view there. heaps: HashMap, @@ -199,6 +213,8 @@ impl Memory { sweep: 0, windows: 0, packed: HashMap::new(), + open: Default::default(), + faulted: 0, heaps: HashMap::new(), frame: u64::MAX, refused: Default::default(), @@ -221,7 +237,7 @@ impl Memory { return None; } // SAFETY: an entry of the directory. - (unsafe { self.entry(page).read() } as usize).checked_sub(1) + ((unsafe { self.entry(page).read() } & !MEMORY_READ_ONLY) as usize).checked_sub(1) } /// Whether `page` can be given a place: in the directory, not turned down @@ -293,12 +309,15 @@ impl Memory { let entry = self.entry(at / PAGE); // SAFETY: an entry of the directory. if unsafe { entry.read() } == 0 { - fill(entry, n, at - first); + close(entry, n, at - first); } at += PAGE; } } - fill(self.entry(page), n, start - shadow.span().0); + // SAFETY: as above. + if unsafe { self.entry(page).read() } == 0 { + close(self.entry(page), n, start - shadow.span().0); + } return true; } // Small title buffers in it: what the builder stores in them comes @@ -336,12 +355,34 @@ impl Memory { }; let offset = self.used * PAGE; self.used += 1; - self.pages.insert(page, Held { at: arena + offset as usize, copy, taken: 0 }); + self.pages.insert(page, Held { at: arena + offset as usize, copy, taken: 0, looked: u64::MAX }); self.order.push(page); fill(self.entry(page), copy, offset); true } + /// A dispatch of the builder was given `address` to write: if it is in a + /// title buffer's copy, stores by address reach that from here on. + fn opens(&mut self, address: u64) { + let Some(n) = self.map(address / PAGE).then(|| self.copy_of(address / PAGE)).flatten() else { + return; + }; + if self.pages.contains_key(&(address / PAGE)) || !self.open.insert(n) { + return; + } + let (first, len) = self.copies[n].span(); + tracing::info!( + start = format_args!("{first:#x}"), + len, + "title memory by address: the structure builder may store in a title buffer" + ); + for page in first.div_ceil(PAGE)..(first + len) / PAGE { + if self.copy_of(page) == Some(n) { + fill(self.entry(page), n, page * PAGE - first); + } + } + } + /// [`Memory::map`] of the pages of `[address, address + len)`, up to the /// first that is not the title's, and what the title wrote there since /// they were taken goes into the arenas. @@ -357,7 +398,9 @@ impl Memory { /// Takes the pages `[first, end)` that are in arenas from title memory /// where it wrote them. fn bring(&mut self, first: u64, end: u64) { - if first >= end { + // Once a frame: the builder names the same pages list after list. + let frame = self.frame; + if !(first..end).any(|page| self.pages.get(&page).is_some_and(|h| h.looked != frame)) { return; } let started = std::time::Instant::now(); @@ -366,6 +409,10 @@ impl Memory { let Some(held) = self.pages.get_mut(&page) else { continue; }; + if held.looked == frame { + continue; + } + held.looked = frame; self.stats.looked += 1; let wrote = answer .as_ref() @@ -396,18 +443,19 @@ impl Memory { /// If title memory has a packed structure at `address` that the builder /// comes to anew: all of it has its pages, and goes up as it is there. - fn unpacks(&mut self, address: u64) { + /// Whether there is a packed structure. + fn unpacks(&mut self, address: u64) -> bool { if address & 0xFF != 0 || !self.possible(address / PAGE) { - return; + return false; } let mut header = [0u8; 8]; crate::host::copy_mapped(header.as_mut_ptr(), address as *const u8, 8, false); let Some(len) = packed_len(u64::from_le_bytes(header)) else { - return; + return false; }; let last = self.packed.insert(address, self.frame); if last.is_some_and(|f| f + AGAIN >= self.frame) { - return; + return true; } self.ready(address, len); let mut title = [0u8; PIECE]; @@ -426,6 +474,7 @@ impl Memory { at += n as u64; } self.stats.packed += 1; + true } /// The pages shaders found empty since the last frame. @@ -449,8 +498,9 @@ impl Memory { pages.sort_unstable(); let mut made = 0; for &page in &pages { - if made < FAULTS && self.copy_of(page).is_none() && self.map(page) { + if made < FAULTS && self.faulted < FAULTS_ALL && self.copy_of(page).is_none() && self.map(page) { made += 1; + self.faulted += 1; self.bring(page, page + 1); } } @@ -546,6 +596,11 @@ impl Memory { } } +/// [`fill`] of a page stores by address do not reach. +fn close(entry: *mut u32, n: usize, offset: u64) { + fill(entry, n | MEMORY_READ_ONLY as usize, offset); +} + /// The offset first: a shader that sees the number sees it too. fn fill(entry: *mut u32, n: usize, offset: u64) { // SAFETY: an entry of the directory, under the mutex. @@ -585,11 +640,19 @@ fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> usize { } /// Before a draw whose shader reads title memory by address: what its -/// root arguments name is made ready (`addresses`: its root views; -/// `constants`: its root constants, see the module), every numbered copy +/// root arguments name is made ready (`addresses`: its root views, of them +/// `written` those it writes; `constants`: its root constants, see the +/// module), every numbered copy /// has its view in `heap`'s run and is brought up to date when `list` is /// submitted. None if the host cannot hold it; the draw is then dropped. -pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constants: &[u32], use_: Use) -> Option { +pub(crate) fn ready( + list: &HostList, + heap: &HostHeap, + addresses: &[u64], + written: &[u64], + constants: &[u32], + use_: Use, +) -> Option { let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); if guard.is_none() { *guard = Memory::new(); @@ -639,20 +702,20 @@ pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constan } for &at in addresses.iter().filter(|&&a| a >= 1 << 32) { // (Several structures to a page.) - if builds && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) { - m.unpacks(at); + let packed = builds && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) && m.unpacks(at); + if builds && written.contains(&at) && named(4, at) { + if let Some((start, len)) = crate::shadow::in_buffer(at, 1) + && len <= BACK + && use_ == (Use::Builds { back: true }) + { + m.small(list, start, len); + } + m.opens(at); } - if !named(2, at) { + if packed || !named(2, at) { continue; } match crate::shadow::in_buffer(at, 1) { - Some((start, len)) if builds && len <= BACK => { - if use_ == (Use::Builds { back: true }) { - m.small(list, start, len); - } - m.ready(at, 1); - m.named_in_upload(at); - } Some(_) => { m.ready(at, 1); m.named_in_upload(at); @@ -666,7 +729,10 @@ pub(crate) fn ready(list: &HostList, heap: &HostHeap, addresses: &[u64], constan None => { // Held for the heap's life: not given back with a list's slots. let base = heap.dynamic(COPIES + 1)?; - heap.null_raw_uav_at(base); + // Every slot of the run: a number shows no view of another kind. + for n in 0..=COPIES { + heap.null_raw_uav_at(base + n); + } (base, 0) } }; diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index e1043f3..b5335cb 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -244,7 +244,7 @@ impl<'a> Lower<'a> { let at = self.s.m.select(c, inside, at, outside); return (handle, at); } - self.memory(low, high, guard) + self.memory(low, high, guard, false) } /// `count` dwords of the node from its byte `base` + `offset` (`base` diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 319b20e..38fab3b 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1783,7 +1783,7 @@ impl<'a> Lower<'a> { if let Some(bias) = self.root_bias(a.param) { off = self.s.m.bin(c, Bin::Add, off, bias); } - match self.root_memory(&src, off, guard) { + match self.root_memory(&src, off, guard, false) { Some((h, byte)) => { off = byte; Some(h) @@ -3013,8 +3013,10 @@ impl<'a> Lower<'a> { /// (and drops writes) through the null view at the first slot, and its /// number is left for the host, for lanes that run (`guard`). Goes on in /// another block. - fn memory(&mut self, lo: V, hi: V, guard: Option) -> (V, V) { - use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE}; + /// With `store`, a page that is not to be written ([`super::shader::MEMORY_READ_ONLY`]) + /// is the null view. + fn memory(&mut self, lo: V, hi: V, guard: Option, store: bool) -> (V, V) { + use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE}; let c = self.cur; let (i32t, res) = (self.s.t.i32, self.s.t.res_ret); let k = |l: &mut Self, v: u32| l.s.m.i32(v); @@ -3043,7 +3045,9 @@ impl<'a> Lower<'a> { &[directory, at, iu, both, align], ); let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1)); - let (copy, start) = (self.as_int(copy), self.as_int(start)); + let (number, start) = (self.as_int(copy), self.as_int(start)); + let mask = k(self, !MEMORY_READ_ONLY); + let copy = self.s.m.bin(c, Bin::And, number, mask); // A page without a copy: its number, at a place by the number. In a // branch: the notes lie in the PC's memory, and a store there with // every node of every ray would be most of what a trace does. @@ -3073,6 +3077,12 @@ impl<'a> Lower<'a> { ); self.end_guarded(noting, &[]); let c = self.cur; + let copy = if store { + let closed = self.s.m.cmp(c, pred::SLT, number, zero); + self.s.m.select(c, closed, zero, copy) + } else { + copy + }; let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0); let slot = self.s.m.bin(c, Bin::Add, base, copy); // The builder's threads read what others of the dispatch wrote (a @@ -3112,7 +3122,7 @@ impl<'a> Lower<'a> { /// another block. /// shortcut: an access of several dwords is taken not to cross the end /// of a host copy (the builder's records lie on their size). - fn root_memory(&mut self, src: &Source, off: V, guard: Option) -> Option<(V, V)> { + fn root_memory(&mut self, src: &Source, off: V, guard: Option, store: bool) -> Option<(V, V)> { let (lo, hi) = self.root_address(src)?; let c = self.cur; let i32t = self.s.t.i32; @@ -3123,7 +3133,7 @@ impl<'a> Lower<'a> { let sign = self.s.m.bin(c, Bin::AShr, off, k31); let hi = self.s.m.bin(c, Bin::Add, hi, carry); let hi = self.s.m.bin(c, Bin::Add, hi, sign); - let (h, byte) = self.memory(sum, hi, guard); + let (h, byte) = self.memory(sum, hi, guard, store); self.root_copy = Some(h); Some((h, byte)) } @@ -3173,7 +3183,7 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = *dst else { return Err("a global load result"); }; - let (h, byte) = self.memory(lo, hi, guard); + let (h, byte) = self.memory(lo, hi, guard, false); let c = self.cur; let mask = self.s.m.i8((1u8 << n) - 1); let r = self.s.op( @@ -3195,7 +3205,7 @@ impl<'a> Lower<'a> { let n = count(rest)?; let d = data.as_ref().ok_or("global store data")?; let vals = self.vgprs(inst, d, n)?; - let (h, byte) = self.memory(lo, hi, guard); + let (h, byte) = self.memory(lo, hi, guard, true); let mut args = vec![h, byte, iu]; args.extend(&vals); args.resize(3 + 4, iu); @@ -3222,7 +3232,7 @@ impl<'a> Lower<'a> { Some(x) => self.i32_of(x)?, None => self.s.m.i32(0), }; - let (h, byte) = self.memory(lo, hi, guard); + let (h, byte) = self.memory(lo, hi, guard, true); let c = self.cur; // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8. @@ -3357,7 +3367,7 @@ impl<'a> Lower<'a> { for first in (0..count).step_by(4) { let n = (count - first).min(4); let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first)); - let (h, byte) = self.memory(lo, hi, None); + let (h, byte) = self.memory(lo, hi, None, false); let c = self.cur; let mask = self.s.m.i8((1u8 << n) - 1); let r = self.s.op( @@ -6004,7 +6014,7 @@ impl<'a> Lower<'a> { return Ok(()); } if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { - let h = match self.root_memory(src, addr, None) { + let h = match self.root_memory(src, addr, None, false) { Some((h, byte)) => { addr = byte; h @@ -11279,7 +11289,7 @@ impl<'a> Lower<'a> { off = self.s.m.bin(c, Bin::Add, element, off); index = None; } - if let Some((_, byte)) = self.root_memory(src, off, guard) { + if let Some((_, byte)) = self.root_memory(src, off, guard, store || atomic.is_some()) { off = byte; } } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index e23971f..2f06eac 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -117,7 +117,7 @@ pub use sampler::StaticSampler; pub use lower::{host_settings, set_host_max_wave}; pub use rect::rect_list_gs; pub use shader::{ - MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, + MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit, }; diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 7ae8baf..d2605dc 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -37,7 +37,8 @@ pub const SLOT_STRIDES_COUNT: u32 = 1 << 21; /// - the root SRV `t` in [`ROOT_CBV_SPACE`] is a directory of /// [`MEMORY_PAGES`] entries of two dwords, one per 64 KiB of title /// address space: the number of the host copy holding that page (0: none -/// yet) and the page's byte offset in that copy; +/// yet; with [`MEMORY_READ_ONLY`]: stores there are dropped) and the page's +/// byte offset in that copy; /// - copy `n` is the raw buffer view at view-heap slot `base + n`, `base` /// the user-data dword of kind [`USER_MEMORY_BASE`]; slot `base` itself /// reads zeros and drops writes; @@ -49,6 +50,9 @@ pub const SLOT_MEMORY: u8 = 254; pub const SLOT_FAULTS: u8 = 253; /// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB. pub const MEMORY_PAGES: u32 = 1 << 21; +/// In a directory entry's first dword: shaders do not store there by address +/// (a title buffer the structure builder has not been given to write). +pub const MEMORY_READ_ONLY: u32 = 1 << 31; /// Dwords of the [`SLOT_FAULTS`] buffer. pub const MEMORY_FAULTS: u32 = 4096; /// `RootType::Other` code of a user-data dword the host computes: the view From e1561288e7b7d0c072ca23148e10e70211a20618 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:29:50 -0600 Subject: [PATCH 5/9] Title memory by address: packed structures that are gone give their pages back; ranges only for views written 4 MiB for every constant that looked like an address took a third of the pages (run light-5). Which pages came for what is in the ten-second line. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/memory.rs | 185 ++++++++++++++++++++++++++----- crates/victory-gpu/src/shadow.rs | 4 +- 2 files changed, 161 insertions(+), 28 deletions(-) diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index a1168c5..2daab6f 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -36,8 +36,9 @@ //! packed ("dehydrated") structure there, all of it: the title ships its //! structures packed, and the builder's rehydration stages unpack each in //! place once it is streamed in; -//! - 4 MiB from each pair of root constants that is a title address and from -//! each root constant that is one in 256-byte units (structures built); +//! - 4 MiB from each unordered access view outside buffers (structures built); +//! - the page of each pair of root constants that is a title address and of +//! each root constant that is one in 256-byte units; //! - the first page of every structure a list's upload memory names //! (a top-level build's instances). //! @@ -58,7 +59,10 @@ //! dispatches was given that buffer as an unordered access view (its scratch //! memory, its results); what else a store reaches is an arena's. //! -//! shortcut: a page is kept for the rest of the run. +//! A packed structure is gone when title memory has no header of it any more +//! (looked at over [`SWEEP`] frames); the pages it alone has are given back. +//! +//! shortcut: a page held for anything else is kept for the rest of the run. //! shortcut: pages a list does not name are looked at again in turn, over //! [`SWEEP`] frames. @@ -80,15 +84,15 @@ const PAGE: u64 = 1 << 16; const ARENA: u64 = 64 << 20; /// What is compared at a time. const PIECE: usize = 4096; -/// Pages held, at most (2 GiB). -const MOST: usize = 1 << 15; +/// Pages held, at most (3 GiB). +const MOST: usize = 3 << 14; /// Pages of title memory with small title buffers in them, at most. const WINDOWS: usize = 512; /// The biggest packed structure taken for one. const PACKED: u64 = 64 << 20; /// A packed structure not named for so many frames is another one. const AGAIN: u64 = 8; -/// From a root view; from an address in constants. +/// From a root view; from one that is written (a structure being built). const VIEW: u64 = 256 << 10; const BUILT: u64 = 4 << 20; /// The biggest title buffer whose builder results come back. @@ -97,7 +101,7 @@ const BACK: u64 = 256 << 10; /// structure that is not right goes anywhere, and 2,048 a frame took all the /// pages there are in the first seconds (run light-4). const FAULTS: usize = 128; -const FAULTS_ALL: usize = 8192; +const FAULTS_ALL: usize = 2048; /// Frames over which every page is looked at once. const SWEEP: usize = 128; @@ -119,6 +123,19 @@ struct Held { taken: u64, /// The frame it was last looked at in. looked: u64, + /// Packed structures that have bytes in it, and whether it is held for + /// them alone. + owners: u32, + theirs: bool, +} + +/// A packed structure the builder came to. +struct Packed { + /// The frame it last did. + frame: u64, + len: u64, + /// Its first two dwords in title memory. + header: u64, } struct Memory { @@ -140,7 +157,12 @@ struct Memory { /// Windows of title memory itself ([`Memory::map`]). windows: usize, /// Packed structures the builder came to: the frame it last did. - packed: HashMap, + packed: HashMap, + /// Their addresses in the order they came, and where the sweep is. + packed_order: Vec, + packed_sweep: usize, + /// Places of pages given back: the copy, the address in the arena. + free: Vec<(usize, usize)>, /// Copies of title buffers the builder may store in. open: std::collections::HashSet, /// Pages taken from faults. @@ -169,6 +191,11 @@ struct Stats { looked: u64, changed: u64, packed: u64, + packed_bytes: u64, + gone: u64, + /// Pages that came for an address in constants, a written view, another + /// view, a structure named in upload memory. + came: [u64; 4], micros: u64, } @@ -213,6 +240,9 @@ impl Memory { sweep: 0, windows: 0, packed: HashMap::new(), + packed_order: Vec::new(), + packed_sweep: 0, + free: Vec::new(), open: Default::default(), faulted: 0, heaps: HashMap::new(), @@ -337,6 +367,10 @@ impl Memory { ONCE.call_once(|| tracing::warn!(MOST, "title memory by address: no more pages are taken; others read zeros")); return false; } + if let Some((copy, at)) = self.free.pop() { + self.hold(page, at, copy); + return true; + } if self.used == ARENA / PAGE { let Some(at) = crate::upload::reserve(ARENA as usize) else { return false; @@ -355,12 +389,71 @@ impl Memory { }; let offset = self.used * PAGE; self.used += 1; - self.pages.insert(page, Held { at: arena + offset as usize, copy, taken: 0, looked: u64::MAX }); - self.order.push(page); - fill(self.entry(page), copy, offset); + self.hold(page, arena + offset as usize, copy); true } + /// `page` is held at `at` in the arena that is `copy`. + fn hold(&mut self, page: u64, at: usize, copy: usize) { + self.pages.insert(page, Held { at, copy, taken: 0, looked: u64::MAX, owners: 0, theirs: false }); + self.order.push(page); + fill(self.entry(page), copy, at as u64 - self.copies[copy].span().0); + } + + /// The packed structure at `address` is gone: the pages it alone had are + /// given back. + fn gone(&mut self, address: u64) { + let Some(packed) = self.packed.remove(&address) else { return }; + for page in address / PAGE..=(address + packed.len - 1) / PAGE { + let Some(held) = self.pages.get_mut(&page) else { continue }; + held.owners = held.owners.saturating_sub(1); + if held.owners == 0 && held.theirs { + self.free.push((held.copy, held.at)); + self.pages.remove(&page); + // SAFETY: an entry of the directory, under the mutex. + unsafe { self.entry(page).write_volatile(0) }; + } + } + self.stats.gone += 1; + } + + /// Whether the packed structure at `address` is still in title memory. + fn there(&self, address: u64) -> bool { + let mut header = [0u8; 8]; + crate::texture::committed(address as *const u8, 8) && { + crate::host::copy_mapped(header.as_mut_ptr(), address as *const u8, 8, false); + self.packed.get(&address).is_some_and(|p| p.header == u64::from_le_bytes(header)) + } + } + + /// Looks at some of the pages and packed structures again. + fn look_again(&mut self) { + for _ in 0..self.order.len().div_ceil(SWEEP) { + self.sweep = (self.sweep + 1) % self.order.len(); + let page = self.order[self.sweep]; + if self.pages.contains_key(&page) { + self.bring(page, page + 1); + } else { + self.order.swap_remove(self.sweep); + if self.order.is_empty() { + break; + } + } + } + for _ in 0..self.packed_order.len().div_ceil(SWEEP) { + self.packed_sweep = (self.packed_sweep + 1) % self.packed_order.len(); + let address = self.packed_order[self.packed_sweep]; + if !self.packed.contains_key(&address) { + self.packed_order.swap_remove(self.packed_sweep); + if self.packed_order.is_empty() { + break; + } + } else if !self.there(address) { + self.gone(address); + } + } + } + /// A dispatch of the builder was given `address` to write: if it is in a /// title buffer's copy, stores by address reach that from here on. fn opens(&mut self, address: u64) { @@ -453,9 +546,31 @@ impl Memory { let Some(len) = packed_len(u64::from_le_bytes(header)) else { return false; }; - let last = self.packed.insert(address, self.frame); - if last.is_some_and(|f| f + AGAIN >= self.frame) { - return true; + let header = u64::from_le_bytes(header); + if let Some(known) = self.packed.get_mut(&address) { + let soon = known.frame + AGAIN >= self.frame; + known.frame = self.frame; + if known.header == header && soon { + return true; + } + if known.header != header { + self.gone(address); + } + } + if !self.packed.contains_key(&address) { + self.packed.insert(address, Packed { frame: self.frame, len, header }); + self.packed_order.push(address); + for page in address / PAGE..=(address + len - 1) / PAGE { + let new = !self.pages.contains_key(&page); + if !self.map(page) { + continue; + } + if let Some(held) = self.pages.get_mut(&page) { + held.owners += 1; + held.theirs |= new; + } + } + self.stats.packed_bytes += len; } self.ready(address, len); let mut title = [0u8; PIECE]; @@ -575,7 +690,8 @@ impl Memory { tracing::info!( "title memory by address: {} pages ({} MB) in {} arenas, {} copies in all; per frame {:.0} dispatches that read, {:.0} that build, \ {:.1} pages that had no copy, {:.1} pages turned down, {:.1} results brought back; {:.0} pages looked at, {:.1} KB changed, \ - {:.1} packed structures ({} seen), {:.2} ms; {} windows", + {:.1} packed structures ({} there), {:.2} ms; {} windows; since the last line {} KB of packed structures came and {} of them went, \ + and pages for constants {}, views written {}, others {}, upload memory {}, faults in all {}", self.pages.len(), (self.pages.len() as u64 * PAGE) >> 20, self.arenas.len(), @@ -590,7 +706,14 @@ impl Memory { s.packed as f64 / frames, self.packed.len(), s.micros as f64 / 1000.0 / frames, - self.windows + self.windows, + s.packed_bytes >> 10, + s.gone, + s.came[0], + s.came[1], + s.came[2], + s.came[3], + self.faulted ); self.stats.from = Some((now, self.frame)); } @@ -663,12 +786,7 @@ pub(crate) fn ready( m.frame = frame; m.refused.clear(); m.take_faults(); - let n = m.order.len().div_ceil(SWEEP); - for _ in 0..n { - m.sweep = (m.sweep + 1) % m.order.len(); - let page = m.order[m.sweep]; - m.bring(page, page + 1); - } + m.look_again(); m.report(); } let builds = use_ != Use::Reads; @@ -682,7 +800,8 @@ pub(crate) fn ready( // in one in 256-byte units (the builder's alone). A constant that only // looks like one names memory nothing reads; one that is not the title's // memory is refused. - let built = if builds { BUILT } else { PAGE }; + let held = |m: &Memory| m.pages.len() as u64; + let before = held(m); for (i, &c) in constants.iter().enumerate() { if let Some(&high) = constants.get(i + 1) && (1..=0x1F).contains(&high) @@ -690,16 +809,17 @@ pub(crate) fn ready( { let at = u64::from(c) | u64::from(high) << 32; if named(1, at) { - m.ready(at, built); + m.ready(at, 1); } } if builds && (0x0100_0000..0x2000_0000).contains(&c) { let at = u64::from(c) << 8; if named(1, at) { - m.ready(at, built); + m.ready(at, 1); } } } + let mut came = [held(m) - before, 0, 0, 0]; for &at in addresses.iter().filter(|&&a| a >= 1 << 32) { // (Several structures to a page.) let packed = builds && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) && m.unpacks(at); @@ -711,18 +831,31 @@ pub(crate) fn ready( m.small(list, start, len); } m.opens(at); + if !packed && crate::shadow::in_buffer(at, 1).is_none() { + let before = held(m); + m.ready(at, BUILT); + came[1] += held(m).saturating_sub(before); + } } if packed || !named(2, at) { continue; } + let before = held(m); match crate::shadow::in_buffer(at, 1) { Some(_) => { m.ready(at, 1); m.named_in_upload(at); + came[3] += held(m).saturating_sub(before); + } + None => { + m.ready(at, if builds { VIEW } else { PAGE }); + came[2] += held(m).saturating_sub(before); } - None => m.ready(at, if builds { VIEW } else { PAGE }), } } + for (sum, n) in m.stats.came.iter_mut().zip(came) { + *sum += n; + } let key = std::ptr::from_ref(heap) as usize; let (base, made) = match m.heaps.get(&key) { Some(&run) => run, diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 3f2b89d..e3c8fc1 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -4592,14 +4592,14 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option> { if !cards() || !host.card_ready() { return None; } - // At most so much on the card's own memory (2 GiB unless + // At most so much on the card's own memory (4 GiB unless // `VICTORY_MEMORY_CARD_MB` says otherwise), and while it has room; past // that the side shaders see is in the PC's memory. static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); static USED: AtomicU64 = AtomicU64::new(0); let most = *MOST.get_or_init(|| { let mb = std::env::var("VICTORY_MEMORY_CARD_MB").ok().and_then(|v| v.trim().parse::().ok()); - mb.unwrap_or(2048) << 20 + 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)?; From c51ca571ee4b024c16292f019932b4a829ed6981 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:48:04 -0600 Subject: [PATCH 6/9] Title memory by address: the dump names what was built and unpacked; a small buffer's results once a list Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/memory.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 2daab6f..41ba575 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -823,15 +823,21 @@ pub(crate) fn ready( for &at in addresses.iter().filter(|&&a| a >= 1 << 32) { // (Several structures to a page.) let packed = builds && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) && m.unpacks(at); - if builds && written.contains(&at) && named(4, at) { + if builds && written.contains(&at) && list.first_use(usize::MAX - (4 << 33) - (at >> 2 & 0x7FFF_FFFF) as usize) { if let Some((start, len)) = crate::shadow::in_buffer(at, 1) && len <= BACK && use_ == (Use::Builds { back: true }) + && list.first_use(usize::MAX - (5 << 33) - (start >> 2 & 0x7FFF_FFFF) as usize) { m.small(list, start, len); } m.opens(at); if !packed && crate::shadow::in_buffer(at, 1).is_none() { + #[cfg(feature = "diagnostics")] + { + let built = m.dump.built.entry(at).or_insert((frame, frame, 0)); + (built.1, built.2) = (frame, built.2 + 1); + } let before = held(m); m.ready(at, BUILT); came[1] += held(m).saturating_sub(before); @@ -914,6 +920,9 @@ mod dump { #[derive(Default)] pub(super) struct Dump { walked: std::collections::BTreeSet, + /// Views the builder was given to write outside buffers: the first + /// and the last frame, how often. + pub(super) built: std::collections::BTreeMap, /// The frame it is written at, and the copies. due: Option<(u64, Vec<(ID3D12Resource, usize)>)>, done: bool, @@ -962,6 +971,13 @@ mod dump { for a in &self.dump.walked { text += &format!("walked {a:#x}\n"); } + for (a, (first, last, n)) in &self.dump.built { + text += &format!("built {a:#x} {first} {last} {n}\n"); + } + for (a, p) in &self.packed { + text += &format!("packed {a:#x} {} {}\n", p.len, p.frame); + } + text += &format!("frame {}\n", self.frame); for (page, held) in &self.pages { let arena = self.arenas.iter().position(|a| a.0 == held.copy).unwrap_or(usize::MAX); let at = held.at - self.arenas[arena].1; From 3c0721033b7af9fecfb19dcfb19a21bd96687ab2 Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 05:48:49 -0600 Subject: [PATCH 7/9] docs: ray tracing, the state after the first runs Co-Authored-By: Claude Opus 5.5 --- docs/fork-ray-tracing.md | 66 ++++++++++++++++++++++++++++++++-------- 1 file changed, 54 insertions(+), 12 deletions(-) diff --git a/docs/fork-ray-tracing.md b/docs/fork-ray-tracing.md index dee0281..6c05d8d 100644 --- a/docs/fork-ray-tracing.md +++ b/docs/fork-ray-tracing.md @@ -1,8 +1,10 @@ # Ray tracing in this fork: what the title does and what has been built -Status, 2026-11-25: **nothing is lit by ray tracing yet.** Most of the -machinery translates and is unit-tested; it has not yet run end to end in the -game. Everything here is off by default. +Status, 2026-11-25, 06:00: **with `VICTORY_BVH_BUILDER=1` the builder runs on +the RX 7900 XTX and rooms get their indirect light** (run light-6, the dorm: +bunk, locker, window frame, posters; 100-116 ms a frame against 84-95 without). +Some structures are still wrong; one run of four with it lost the device early, +in a list without a builder stage. Off by default. ## What the title does @@ -35,8 +37,8 @@ shaders and emulates the one instruction. ## What this fork adds -1. **The builder programs translate** (49 of 52; all that the title creates in - the scenes tested). They pass buffer addresses in a spilled parameter table +1. **The builder programs translate** (all 52, with host pipelines on the RX + 7900 XTX; the title creates 53 such pipelines). They pass buffer addresses in a spilled parameter table rather than in descriptors. Added: the spilled user-data table, root unordered-access views (translator and host binding), byte and 16-bit buffer accesses, and several control-flow shapes. @@ -61,18 +63,58 @@ shaders and emulates the one instruction. partly working builder wrote garbage bounds into title memory and crashed the title. +## The structures (from dumps of the arenas, `VICTORY_MEMORY_DUMP`) + +- Header, 64 bytes: dword 0 the version 6 in the low half and marks in the high + (0x8000 bottom level, 0x4 compacted, 0x2 rehydrated, 0x100 still packed), + dword 1 the size in 64-byte nodes, 3 the number of elements, 4-9 the bounds, + 10 the offset of the box nodes, 12 the root's node pointer, 13 the offset of + the elements, 14 the offset of the parent table (from the header; the static + ones' index counts the leaves too, so it is negative). +- An instance is 128 bytes at the top level's offset 13: a 3x4 matrix in dwords + 0-11, id and mask, flags, the root pointer (bit 30 set for static ones), the + bottom level's address in 256-byte units. +- The static world's structures are shipped **packed ("dehydrated")** and + unpacked in place, once, by DecompressHeader, Box32/Box16Rehydration and + LeafRehydration when they have been streamed in (3,000 in the opening). +- Dynamic ones are built, their compacted size read back by the title from a + small buffer, and copied to a place of that size. + +## How title memory by address is held (`memory.rs`) + +Pages of 64 KiB in arenas on the card, whole title buffers in their own copies, +pages with small title buffers as windows of title memory. The module's +comment has the rules. In short: what the builder stores stays on the card +(only small title buffers it was given to write come back); a packed structure +goes up whole when the builder comes to it; title buffers take its stores only +after it was given them as an unordered access view. + +| variable | does | +|---|---| +| `VICTORY_BVH_BUILDER=1` | the builder's stages run | +| `VICTORY_BVH_QUARANTINE=1` | nothing it stores comes back to title memory | +| `VICTORY_MEMORY_CARD_MB` | the most of it on the card (4096) | +| `VICTORY_MEMORY_DUMP=` | a file `go` there writes the arenas out (diagnostics) | +| `VICTORY_UPLOAD_LOW=0`, `VICTORY_LENT_HEAP=0` | lists' upload memory above 2^40, no view heap for lists without one, as before | + +Every ten seconds the log has a line "title memory by address: ..." with pages, +dispatches, faults and what came. + ## Known gaps -- With `VICTORY_BVH_BUILDER=1` the builder still stays off in a real run: a few - of its pipelines are refused by the host (they still ask for 64-lane waves on - a 32-lane GPU) or do not translate. -- Five shadow-mask trace programs do not translate yet. -- An access to a title page that has no host copy is lost (a read gives zero, a - store is dropped). +- About 4,000 pages a frame that are not there are still touched (the notes' + limit): some structures are wrong and rays go anywhere in them. Guess: sizes + that came back late or not (fixed after light-6, not seen working), so places + overlap. +- Five shadow-mask trace programs do not translate (a structure's address out + of a descriptor picked from the heap by a computed index: the host would have + to give a table of addresses by slot). The title did not create them in any + run so far. +- An access to a page that is not there is lost (a read gives zero, a store is + dropped). - Not publicly documented, and assumed: the instruction's rounding, the order of two boxes entered at the same distance, and the result for a ray exactly through an edge. -- Cost on the GPU is unmeasured. ## Where to look From 28fbbfdcbce4eeb6c3b6337f2010fd1f50cf858b Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 06:09:43 -0600 Subject: [PATCH 8/9] Title memory by address: every list brings up every copy, whoever made it An arena another list made while this one was being recorded was brought up by that list's submission alone: structures unpacked from zeros, then written over by the arena's first upload. In run light-8 half of the 470 structures unpacked in the frame with the most (1381) were wrong, 5-15 % in frames with few. A title buffer the builder stores in sends up only the dwords the title changed. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/memory.rs | 24 +++++++++++++++--------- crates/victory-gpu/src/shadow.rs | 14 ++++++++++---- 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 41ba575..5a7112f 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -463,6 +463,8 @@ impl Memory { if self.pages.contains_key(&(address / PAGE)) || !self.open.insert(n) { return; } + // (Its pages hold what the CPU writes beside the builder's scratch.) + self.copies[n].keep_stores(); let (first, len) = self.copies[n].span(); tracing::info!( start = format_args!("{first:#x}"), @@ -791,7 +793,6 @@ pub(crate) fn ready( } let builds = use_ != Use::Reads; m.stats.uses[usize::from(builds)] += 1; - let numbered = m.copies.len(); // Once per list and page named: the builder dispatches hundreds of times // a frame with the same arguments. const READ: usize = usize::MAX - 0x6d; @@ -880,17 +881,22 @@ pub(crate) fn ready( heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len); } m.heaps.insert(key, (base, m.copies.len() as u32)); - // shortcut: a copy another list numbers meanwhile is brought up to date - // by that list's submission, which may run after this one's. + // Every copy by every list that has come to by-address memory, whoever + // numbered it: an arena another list made while this one was being + // recorded was brought up to date by that list's submission alone, which + // may run after this one's (structures unpacked from zeros, and then + // written over by the arena's first upload: in frames that stream much in + // half of them, run light-8). let first_read = list.first_use(READ); - let from = if first_read { 0 } else { numbered }; - if first_read || m.copies.len() > numbered { + if list.first_use(usize::MAX - (6 << 33) - m.copies.len()) { let (start, len) = m.directory.1.span(); m.directory.1.refresh(list, start, len); - } - for shadow in &m.copies[from..] { - let (start, len) = shadow.span(); - shadow.refresh(list, start, len); + for (n, shadow) in m.copies.iter().enumerate() { + if list.first_use(usize::MAX - (7 << 33) - n) { + let (start, len) = shadow.span(); + shadow.refresh(list, start, len); + } + } } if first_read { list.keep(&m.faults.0); diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 124ecd5..0690506 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -85,7 +85,7 @@ pub(crate) struct Shadow { window: bool, /// Of a copy with two sides: only the dwords the title changed go up, /// as with [`send_changed`] ([`by_address`]). - changes_only: bool, + changes_only: std::sync::atomic::AtomicBool, /// A window in card memory the CPU maps ([`window_mapped_for`]). mapped: bool, /// With `crate::inplace`: not a copy at all. `buffer` is placed in a @@ -2686,7 +2686,7 @@ impl Shadow { }, card: None, window: false, - changes_only: false, + changes_only: Default::default(), mapped: false, place: None, } @@ -3572,7 +3572,7 @@ impl Shadow { /// A page of title memory, as read. static TITLE: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } - let Some(card) = self.card.as_ref().filter(|_| self.changes_only || send_changed()) else { + let Some(card) = self.card.as_ref().filter(|_| self.changes_only.load(Ordering::Relaxed) || send_changed()) else { return self.copy(from, to); }; let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none(); @@ -3640,6 +3640,12 @@ impl Shadow { self.card.is_some() } + /// Shaders store in it what is not declared: from here on only the dwords + /// the title changes go up ([`by_address`]). + pub(crate) fn keep_stores(&self) { + self.changes_only.store(true, Ordering::Relaxed); + } + /// Offsets `[from, to)` go up again whole, as the CPU's side has them. pub(crate) fn resend(&self, from: usize, to: usize) { self.card_changed(from, to); @@ -4673,7 +4679,7 @@ pub(crate) fn by_address(start: u64, len: u64) -> Option> { let gpu = unsafe { buffer.GetGPUVirtualAddress() }; let mut shadow = Shadow::new(buffer, data, gpu, start, len); shadow.window = true; - shadow.changes_only = true; + shadow.changes_only.store(true, Ordering::Relaxed); shadow.card = Some(Card { staging, before: Mutex::default(), From d2a8f03b6d73b753316c5b4f6e0576cbc18dcd5b Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 06:20:48 -0600 Subject: [PATCH 9/9] Title memory by address: what streaming brings is taken when the list is submitted, not when it is recorded Dumps of runs light-8 and light-9: of structures of the same size some are unpacked right and some not, more of them in frames that stream much. The title's queue waits for its streaming, so a packed structure's bytes may come after the dispatch that unpacks it is recorded. Not run in the game yet. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/memory.rs | 207 ++++++++++++++++++++++--------- 1 file changed, 148 insertions(+), 59 deletions(-) diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 5a7112f..65a2cd7 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -90,6 +90,10 @@ const MOST: usize = 3 << 14; const WINDOWS: usize = 512; /// The biggest packed structure taken for one. const PACKED: u64 = 64 << 20; +/// For so many frames what a page holds may still be on its way. +const YOUNG: u64 = 4; +/// Free pages there are, at least, when a list is recorded. +const SPARE: usize = 1024; /// A packed structure not named for so many frames is another one. const AGAIN: u64 = 8; /// From a root view; from one that is written (a structure being built). @@ -121,8 +125,9 @@ struct Held { copy: usize, /// The write-watch asking after which it was last taken (0: never). taken: u64, - /// The frame it was last looked at in. + /// The frame it was last looked at in, and the one it came in. looked: u64, + born: u64, /// Packed structures that have bytes in it, and whether it is held for /// them alone. owners: u32, @@ -146,9 +151,8 @@ struct Memory { copies: Vec>, /// Places of title buffers' copies among `copies`. numbers: HashMap, - /// Arenas: place in `copies`, address; pages of the last one handed out. + /// Arenas: place in `copies`, address. arenas: Vec<(usize, usize)>, - used: u64, /// By title page. pages: HashMap, /// Their numbers in the order they came, and where the sweep is. @@ -161,7 +165,7 @@ struct Memory { /// Their addresses in the order they came, and where the sweep is. packed_order: Vec, packed_sweep: usize, - /// Places of pages given back: the copy, the address in the arena. + /// Places of pages that are free: the copy, the address in the arena. free: Vec<(usize, usize)>, /// Copies of title buffers the builder may store in. open: std::collections::HashSet, @@ -234,7 +238,6 @@ impl Memory { copies: Vec::new(), numbers: HashMap::new(), arenas: Vec::new(), - used: ARENA / PAGE, pages: HashMap::new(), order: Vec::new(), sweep: 0, @@ -371,31 +374,33 @@ impl Memory { self.hold(page, at, copy); return true; } - if self.used == ARENA / PAGE { - let Some(at) = crate::upload::reserve(ARENA as usize) else { - return false; - }; - let Some(shadow) = crate::shadow::by_address(at as u64, ARENA) else { - return false; - }; - let Some(n) = self.number(shadow) else { - return false; - }; - self.arenas.push((n, at)); - self.used = 0; + if !self.another() { + return false; } - let Some(&(copy, arena)) = self.arenas.last() else { + let Some((copy, at)) = self.free.pop() else { return false; }; - let offset = self.used * PAGE; - self.used += 1; - self.hold(page, arena + offset as usize, copy); + self.hold(page, at, copy); + true + } + + /// Another arena's pages. + fn another(&mut self) -> bool { + 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 { + return false; + }; + 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))); true } /// `page` is held at `at` in the arena that is `copy`. fn hold(&mut self, page: u64, at: usize, copy: usize) { - self.pages.insert(page, Held { at, copy, taken: 0, looked: u64::MAX, owners: 0, theirs: false }); + self.pages.insert(page, Held { at, copy, taken: 0, looked: u64::MAX, born: self.frame, owners: 0, theirs: false }); self.order.push(page); fill(self.entry(page), copy, at as u64 - self.copies[copy].span().0); } @@ -536,35 +541,54 @@ impl Memory { self.stats.micros += started.elapsed().as_micros() as u64; } - /// If title memory has a packed structure at `address` that the builder - /// comes to anew: all of it has its pages, and goes up as it is there. - /// Whether there is a packed structure. - fn unpacks(&mut self, address: u64) -> bool { - if address & 0xFF != 0 || !self.possible(address / PAGE) { - return false; + /// The bytes of a packed structure title memory has at `address` by now, + /// and its first two dwords. + fn packed_at(&self, address: u64) -> Option<(u64, u64)> { + if address & 0xFF != 0 { + return None; } let mut header = [0u8; 8]; crate::host::copy_mapped(header.as_mut_ptr(), address as *const u8, 8, false); - let Some(len) = packed_len(u64::from_le_bytes(header)) else { - return false; - }; let header = u64::from_le_bytes(header); + Some((packed_len(header)?, header)) + } + + /// At the submission of a list whose builder dispatch was given `address` + /// outside buffers, in the order of its copies: what title memory has + /// there now goes up. When the dispatch is recorded it may not be there + /// yet: the title's queue waits for its streaming. (Nothing is asked of + /// the write watch here: the submission's asking stands.) + fn land(&mut self, address: u64) { + let page = address / PAGE; + if !crate::texture::committed((page * PAGE) as *const u8, PAGE as usize) { + return; + } + let Some((len, header)) = self.packed_at(address) else { + // Anything else: what came since its page was first taken. + for page in page..=(address + VIEW - 1) / PAGE { + if self.pages.get(&page).is_some_and(|h| h.born + YOUNG >= self.frame) { + self.take(page, 0, PAGE as usize, false); + } + } + return; + }; if let Some(known) = self.packed.get_mut(&address) { let soon = known.frame + AGAIN >= self.frame; known.frame = self.frame; if known.header == header && soon { - return true; + return; } if known.header != header { self.gone(address); } } + let last = (address + len - 1) / PAGE; if !self.packed.contains_key(&address) { self.packed.insert(address, Packed { frame: self.frame, len, header }); self.packed_order.push(address); - for page in address / PAGE..=(address + len - 1) / PAGE { - let new = !self.pages.contains_key(&page); - if !self.map(page) { + for page in page..=last { + let new = self.copy_of(page).is_none(); + if new && !self.place(page) { continue; } if let Some(held) = self.pages.get_mut(&page) { @@ -574,26 +598,59 @@ impl Memory { } self.stats.packed_bytes += len; } - self.ready(address, len); - let mut title = [0u8; PIECE]; - let mut at = address; - while at < address + len { - let n = (PAGE - at % PAGE).min(address + len - at).min(PIECE as u64) as usize; - if let Some(held) = self.pages.get(&(at / PAGE)) { - let place = held.at + (at % PAGE) as usize; - crate::host::copy_mapped(title.as_mut_ptr(), at as *const u8, n, false); - // SAFETY: a page of an arena of ours, under the mutex. - unsafe { std::slice::from_raw_parts_mut(place as *mut u8, n) }.copy_from_slice(&title[..n]); - let shadow = &self.copies[held.copy]; - let base = place - shadow.span().0 as usize; - shadow.resend(base, base + n); - } - at += n as u64; + for page in page..=last { + let from = address.max(page * PAGE) - page * PAGE; + let to = (address + len).min((page + 1) * PAGE) - page * PAGE; + self.take(page, from as usize, to as usize, true); } self.stats.packed += 1; + } + + /// A place in an arena for a page of committed title memory, at a + /// submission: only one there is already (the list brings up the arenas + /// it knew when it was recorded). + fn place(&mut self, page: u64) -> bool { + if page < 0x1_0000 + || page >= u64::from(MEMORY_PAGES) - 1 + || !crate::texture::committed((page * PAGE) as *const u8, PAGE as usize) + || crate::shadow::in_buffer(page * PAGE, PAGE).is_some() + { + return false; + } + let Some((copy, at)) = self.free.pop() else { + return false; + }; + self.hold(page, at, copy); + crate::watch::wrote(self.entry(page) as usize, 8); + self.take(page, 0, PAGE as usize, true); true } + /// Bytes `from..to` of `page` from title memory into its arena's page, at + /// a submission; `whole`: sent whether they differ from those last taken + /// or not. + fn take(&mut self, page: u64, from: usize, to: usize, whole: bool) { + let Some(held) = self.pages.get(&page) else { return }; + let shadow = &self.copies[held.copy]; + let base = held.at - shadow.span().0 as usize; + let mut title = [0u8; PIECE]; + let mut at = from; + while at < to { + let n = (PIECE - at % PIECE).min(to - at); + 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] { + ours.copy_from_slice(&title[..n]); + crate::watch::wrote(held.at + at, n); + } + at += n; + } + if whole { + shadow.resend(base + from, base + to); + } + } + /// The pages shaders found empty since the last frame. fn take_faults(&mut self) { let mut pages = Vec::new(); @@ -680,6 +737,17 @@ impl Memory { } } + /// Every copy is brought up to date when `list` is submitted, after what + /// it deferred so far (once until a copy of the title's intervenes). + fn bring_up(&self, list: &HostList) { + let (start, len) = self.directory.1.span(); + self.directory.1.refresh(list, start, len); + for shadow in &self.copies { + let (start, len) = shadow.span(); + shadow.refresh(list, start, len); + } + } + /// Every ten seconds or so, what was used. fn report(&mut self) { let now = std::time::Instant::now(); @@ -792,6 +860,7 @@ pub(crate) fn ready( m.report(); } let builds = use_ != Use::Reads; + while builds && m.free.len() < SPARE && m.pages.len() + m.free.len() < MOST && m.another() {} m.stats.uses[usize::from(builds)] += 1; // Once per list and page named: the builder dispatches hundreds of times // a frame with the same arguments. @@ -823,7 +892,34 @@ pub(crate) fn ready( let mut came = [held(m) - before, 0, 0, 0]; for &at in addresses.iter().filter(|&&a| a >= 1 << 32) { // (Several structures to a page.) - let packed = builds && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) && m.unpacks(at); + let mut packed = false; + if builds + && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize) + && crate::shadow::in_buffer(at, 1).is_none() + && m.possible(at / PAGE) + { + // What it needs, as far as it is known now; the rest when the + // list is submitted ([`Memory::land`]). + if let Some((len, _)) = m.packed_at(at) { + packed = true; + for page in at / PAGE..=(at + len - 1) / PAGE { + let new = m.copy_of(page).is_none(); + if m.map(page) + && new + && let Some(held) = m.pages.get_mut(&page) + { + held.theirs = true; + } + } + m.bring(at / PAGE, (at + len - 1) / PAGE + 1); + } + list.defer_host(move || { + if let Some(m) = MEMORY.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + m.land(at); + } + }); + m.bring_up(list); + } if builds && written.contains(&at) && list.first_use(usize::MAX - (4 << 33) - (at >> 2 & 0x7FFF_FFFF) as usize) { if let Some((start, len)) = crate::shadow::in_buffer(at, 1) && len <= BACK @@ -889,14 +985,7 @@ pub(crate) fn ready( // half of them, run light-8). let first_read = list.first_use(READ); if list.first_use(usize::MAX - (6 << 33) - m.copies.len()) { - let (start, len) = m.directory.1.span(); - m.directory.1.refresh(list, start, len); - for (n, shadow) in m.copies.iter().enumerate() { - if list.first_use(usize::MAX - (7 << 33) - n) { - let (start, len) = shadow.span(); - shadow.refresh(list, start, len); - } - } + m.bring_up(list); } if first_read { list.keep(&m.faults.0);