diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 3cc3b12..0d05390 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -196,6 +196,7 @@ pub fn run( #[cfg(all(windows, feature = "diagnostics"))] fn diagnostics(image: &victory_loader::LoadedImage, cfg: &victory_core::Config) { victory_loader::dump_stacks_on_schedule(); + victory_loader::profile_on_schedule(victory_hle::frame_phase); victory_hle::modules::audio::capture::start(); watch(image.base(), image.info().size_of_image as usize); poke(image.base(), image.info().size_of_image as usize); diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs index dbcf277..e52d639 100644 --- a/crates/victory-formats/src/texture.rs +++ b/crates/victory-formats/src/texture.rs @@ -599,8 +599,35 @@ impl Layout { self.mips.get(mip as usize).map_or(0, |m| m.depth) } + /// The bytes from the texture's start that mip `first` and the smaller + /// ones take: the smaller a mip, the nearer the start it lies, so a + /// title that streams textures has memory for the smaller mips only and + /// another texture right behind them. All of the layout where slices + /// follow each other (each holds its whole chain). + pub fn bytes_from(&self, first: u32) -> u64 { + let whole = first == 0 + || self.slices != 1 + || self.thick + || self.desc.dimension == Dimension::Tex3d + || self.desc.samples != 1 + || first >= self.desc.mips; + if whole { + return self.size; + } + self.mips[first as usize..] + .iter() + .map(|m| match m.tail { + Some(_) => self.alignment, + None => m.offset + u64::from(m.pitch) * u64::from(m.rows) * u64::from(self.desc.element_bytes), + }) + .max() + .unwrap_or(self.size) + .min(self.size) + } + /// Copies one subresource out of tiled memory (the whole texture, - /// [`Layout::size`] bytes) into linear rows: mip `mip` of array slice + /// [`Layout::size`] bytes, or the [`Layout::bytes_from`] of the mip) + /// into linear rows: mip `mip` of array slice /// `slice` (3D: every depth slice of the mip, `slice` 0). Rows are /// `row_pitch` bytes apart, depth slices `depth_pitch`. pub fn detile( @@ -676,7 +703,8 @@ impl Layout { } else { (dst.len(), src.len()) }; - if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes { + let tiled_need = if DETILE { self.bytes_from(mip) } else { self.size }; + if tiled_len < tiled_need as usize || linear_len < need || row_pitch < bytes { return Err(Error::TooSmall); } let linear = self.desc.swizzle == Swizzle::LINEAR; @@ -1305,6 +1333,34 @@ mod tests { } } + /// The smaller mips lie first: they are read from the memory that holds + /// them alone, as from the whole texture's. + #[test] + fn smaller_mips_need_only_the_start_of_the_texture() { + for swizzle in [Swizzle::SW_4KB_S, Swizzle(9)] { + let l = Layout::new(&Desc { block: 4, ..desc(1024, 1024, 9, 8, swizzle) }).unwrap(); + assert_eq!(l.bytes_from(0), l.size); + let needs: Vec = (0..9).map(|mip| l.bytes_from(mip)).collect(); + assert!(needs.windows(2).all(|w| w[0] >= w[1]), "{needs:?}"); + assert!(needs[3] * 4 < l.size, "{needs:?}"); + let tiled: Vec = (0..l.size).map(|i| (i * 7 >> 3) as u8).collect(); + for mip in 1..9 { + let m = l.mips[mip as usize]; + let pitch = m.width as usize * 8; + let read = |tiled: &[u8]| { + let mut linear = vec![0; pitch * m.height as usize]; + l.detile(tiled, mip, 0, &mut linear, pitch, pitch * m.height as usize).map(|()| linear) + }; + let len = l.bytes_from(mip) as usize; + assert_eq!(read(&tiled[..len]), read(&tiled)); + assert_eq!(read(&tiled[..len - 1]), Err(Error::TooSmall)); + } + } + // Slices each hold their chain: the whole texture. + let l = Layout::new(&Desc { depth: 2, block: 4, ..desc(1024, 1024, 9, 8, Swizzle::SW_4KB_S) }).unwrap(); + assert_eq!(l.bytes_from(4), l.size); + } + #[test] fn depth_stencil_is_two_planes() { let t = Texture::new(&TextureDesc { diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 1fdd273..c43d1af 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -1009,6 +1009,7 @@ pub(crate) fn recorded(started: std::time::Instant) { /// submission lock). pub(crate) fn submission_begins() { let now = now_us(); + INSIDE.fetch_add(1, Relaxed); if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) { add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed))); } @@ -1029,6 +1030,7 @@ pub(crate) fn submission_begins() { /// submission lock. pub(crate) fn submission_ends(lock: u64) { let now = now_us(); + INSIDE.fetch_sub(1, Relaxed); SUBMITTED_AT.store(now, Relaxed); let (user, kernel) = thread_times(); let (u, k) = ENTERED.with(|e| e.get()); @@ -1042,6 +1044,22 @@ pub(crate) fn submission_ends(lock: u64) { s.inside_kernel += kernel.saturating_sub(k); } +/// The submissions being prepared now. +static INSIDE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// What the frame is at, for the sampling profiler (`VICTORY_PROFILE`): 3 +/// in a submission, else 0 after a present until the first list call, 1 until +/// the first submission, 2 behind it. +pub(crate) fn phase() -> u32 { + if INSIDE.load(Relaxed) > 0 { + 3 + } else if SUBMITTED_SINCE.load(Relaxed) { + 2 + } else { + u32::from(RECORDED_SINCE.load(Relaxed)) + } +} + /// The title calls its present (before our own copy to the window runs). pub(crate) fn present_begins() { add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed))); diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 39e8b68..2652ad4 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -286,6 +286,15 @@ pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 6] = [const { std::sync /// Nothing while no heap page changed. #[cfg(windows)] pub(crate) fn sync_line(frames: f64) { + let [twins, moved, lost] = [0, 1, 2].map(|i| host::TWINS[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + if twins > 0 { + tracing::info!( + "raw twins of buffer views made per frame (VICTORY_RAW_VIEWS=0: none): {:.0}, of them {:.1} that do not begin on 16 bytes ({:.1} null)", + twins as f64 / frames, + moved as f64 / frames, + lost as f64 / frames + ); + } let [pages, looked, mirrored, micros, tabled, later] = [0, 1, 2, 3, 4, 5].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); if pages == 0 { return; @@ -333,17 +342,38 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { } } +/// Runs `f` with the host heap of the title's largest view heap, if there is +/// one (reports: nothing is waited for). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn with_view_heap(f: impl FnOnce(&host::HostHeap) -> T) -> Option { + let heaps = SHADER_HEAPS.try_read().ok()?; + let host = heaps + .iter() + // SAFETY: registered heaps are live (removed when dropped). + .map(|&(_, _, at)| unsafe { &*(at as *const Heap) }) + .filter(|heap| !heap.samplers()) + .filter_map(|heap| heap.host.get()?.as_ref()) + .max_by_key(|host| host.count())?; + Some(f(host)) +} + /// Makes dynamic slot `index` of the host heap behind the title heap at /// `heap`, if that heap still exists, the constant buffer view of `size` -/// bytes at `gpu`. +/// bytes of `buffer` at `gpu`. #[cfg(windows)] -pub(crate) fn constant_slot(heap: usize, index: u32, gpu: u64, size: u32) { +pub(crate) fn constant_slot( + heap: usize, + index: u32, + buffer: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, + gpu: u64, + size: u32, +) { let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); if heaps.iter().any(|&(_, _, h)| h == heap) // SAFETY: registered heaps are live (removed when dropped). && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() { - host.constant_at(index, gpu, size); + host.constant_at(index, buffer, gpu, size); } } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 5aac724..2a6372f 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -24,6 +24,11 @@ pub(crate) struct HostHeap { /// ours keeps 2^18 there: 2^16 and 2^17 both ran out in this title.) dynamic: u32, sampler: bool, + /// Where the raw twins of the title's slots start + /// (`victory_shader::emit::raw_views`; 0: there are none), and which of + /// them are not null. + raw: u32, + twins: Vec, /// The record (view index and generation) each slot was last made from. made: Mutex>, /// The records of the title's heap as the pass over records copied in @@ -140,6 +145,42 @@ pub(crate) fn levels_changed(start: u64) { RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).push(start); } +/// [`levels_changed`] once the submissions begun so far (that of the list +/// whose step calls this among them) have run. +pub(crate) fn levels_changed_after(start: u64) { + let after = crate::host::submissions().0; + RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner()).push((after, start)); +} + +static RESHOWN_AFTER: Mutex> = Mutex::new(Vec::new()); + +/// Slots that show a placed texture from another level than the title's view +/// in them says now, and are made from that view when the upload it needs +/// has run ([`HostHeap::texture_slot_flip`]). +struct Flip { + /// The submission to wait for. + after: u64, + /// The heap (its address), the slot, where its record is and which + /// record it was. + heap: usize, + index: u32, + handle: u64, + key: u64, +} + +static FLIPS: Mutex> = Mutex::new(Vec::new()); + +/// Since the start: slots made from their new view after its upload had run, +/// and those the title had written again by then. +pub(crate) static FLIPPED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The key of the record at `handle`, a view's descriptor slot; 0: none. +fn record_key(handle: u64) -> u64 { + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + if tag == VIEW_TAG { u64::from(generation) << 32 | u64::from(i) } else { 0 } +} + /// Levels on demand (`crate::tiles`): where the placed textures start /// whose last upload left a held level without tiles (the card had no /// room, or no heap could be had), and when (`crate::host::moment`). A @@ -210,8 +251,9 @@ pub(crate) struct Spans { rule: Rule, by_start: std::collections::BTreeMap)>, by_slot: std::collections::HashMap, - /// The level each slot's view starts at ([`Spans::shows`]). - first: std::collections::HashMap, + /// The level each slot's view starts at, and where what it is read from + /// ends ([`Spans::shows`]). + first: std::collections::HashMap, /// The bytes a placed texture takes, by resource description: worked /// out once for each (a title writes the views of a few thousand /// descriptions, thousands of times a frame). @@ -329,14 +371,20 @@ impl Spans { stale } - /// The view in slot `index` starts at level `first` of its texture. - fn shows(&mut self, index: u32, first: u32) { - self.first.insert(index, first); + /// The view in slot `index` starts at level `first` of its texture; the + /// memory of that and the smaller levels ends at `end`. + fn shows(&mut self, index: u32, first: u32, end: u64) { + self.first.insert(index, (first, end)); + } + + /// Whether slot `index`'s view is read from memory at or past `start`. + fn reaches(&self, index: u32, start: u64) -> bool { + self.first.get(&index).is_none_or(|&(_, end)| end > start) } /// The lowest level a view of the texture at `start` starts at. fn first_viewed(&self, start: u64) -> Option { - self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).min().copied() + self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).map(|&(first, _)| first).min() } /// The first span that starts inside `[start, end)` past the first @@ -370,6 +418,7 @@ impl Spans { .iter() .filter_map(|at| self.by_start.get(at)) .flat_map(|span| span.1.iter().copied()) + .filter(|&slot| self.reaches(slot, start)) .collect() } @@ -391,6 +440,7 @@ impl Spans { .into_iter() .chain(self.by_start.range(start..end).map(|(_, span)| span)) .flat_map(|span| span.1.iter().copied()) + .filter(|&slot| self.reaches(slot, start)) .collect() } } @@ -838,6 +888,12 @@ fn off_elements(offset: u64, stride: u32, raw: bool, element: u64) -> bool { } } +/// Whether `view` has a raw twin when its host slot is made ([`raw_twins`]): +/// a buffer view or a constant buffer's. +fn twinned(view: &View) -> bool { + matches!(view, View::Constant(..)) || view_elements(view).is_some() +} + /// Whether views off their copy's elements get a copy of their own bytes. On by /// default; `VICTORY_VIEW_BYTES=0` leaves them null, as before. fn view_bytes() -> bool { @@ -866,6 +922,20 @@ fn view_home( crate::shadow::exact(start, len).unwrap_or(shadow) } +/// For device-removed reports: what the slots of the title's view heap that +/// the words of user data may name hold now ([`crate::host::indirects`]). +#[cfg(feature = "diagnostics")] +pub(crate) fn describe_slots(words: &[u32]) -> Vec<(usize, u32, String)> { + super::with_view_heap(|host| { + crate::host::indirects::slots(words, host.count, 6) + .into_iter() + .take(24) + .map(|(word, slot)| (word, slot, host.describe_slot(slot).unwrap_or_default())) + .collect() + }) + .unwrap_or_default() +} + /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for /// device-removed reports: a shader indexing a heap past its end faults. static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); @@ -899,6 +969,20 @@ const PORTABLE_VIEWS: u32 = 1_000_000; /// the last slot is the null slot every view index at or past it reads. const UNCAPPED_VIEWS: u32 = 1 << 21; +/// Where the raw twins of the title's slots start in a heap that has them +/// ([`raw_twins`]): past every slot a title's heap and the dynamic ones take. +const RAW_TWINS: u32 = 1 << 21; + +/// Whether view heaps keep a raw twin of every buffer view of the title's +/// slots, which shaders read that pick buffers by an index they compute +/// (`victory_shader::emit::raw_views` says why; `VICTORY_RAW_VIEWS=0`: they +/// read the title's slots themselves, as before). Needs a host that takes +/// heaps of 2^22 views. +fn raw_twins() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_RAW_VIEWS").is_none_or(|v| v != "0")) +} + /// Picks, once, the null slot at the end of every host view heap and tells /// the translator now (`set_view_heap_limit`) instead of when the title's /// heap is made: a shader keeps the limit it was translated with, and the @@ -929,13 +1013,21 @@ pub(crate) fn probe_view_limit() { }; made.is_ok() }; - let views = if fits(UNCAPPED_VIEWS) { + let twins = raw_twins() && fits(2 * RAW_TWINS); + if twins { + victory_shader::emit::set_raw_views(RAW_TWINS); + } + // (The twins lie past the null slot.) + let views = if twins { + RAW_TWINS + } else if fits(UNCAPPED_VIEWS) { UNCAPPED_VIEWS } else { PORTABLE_VIEWS }; tracing::info!( views, + raw_twins = twins, "host view heaps hold {views} views; view indices are clamped to the null slot at the end from the first shader on" ); victory_shader::emit::set_view_heap_limit(views - 1); @@ -1006,6 +1098,7 @@ impl HostHeap { } else { victory_shader::emit::view_heap_limit() }; + let raw = if sampler { 0 } else { victory_shader::emit::raw_views() }; let extra = if sampler { 0 } else { dynamic_slots(count, null) }; let (heap, count, size) = if null == 0 { match make(count + extra) { @@ -1016,7 +1109,7 @@ impl HostHeap { } } } else { - let size = null + 1; + let size = if raw == 0 { null + 1 } else { 2 * raw }; let fitted = if count + extra <= null { count } else { @@ -1069,6 +1162,8 @@ impl HostHeap { count, dynamic: extra, sampler, + raw, + twins: (0..if raw == 0 { 0 } else { count }).map(|_| std::sync::atomic::AtomicBool::new(false)).collect(), made: Mutex::new(vec![0; count as usize]), copied: Mutex::new(Vec::new()), waiting: Mutex::default(), @@ -1124,22 +1219,31 @@ impl HostHeap { let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + (i * self.step) as usize, }; - if self.sampler { - null_sampler(start); - } else { - null_view(start); - } - let mut filled = 1; - while filled < BLOCK { - let n = filled.min(BLOCK - filled); - host.device.CopyDescriptorsSimple(n, at(filled), start, kind); - filled += n; - } + // (The twins are null buffer views.) + let ends = if self.raw == 0 { [total, total] } else { [self.raw.min(total), total] }; let mut done = 0; - while done < total { - let n = BLOCK.min(total - done); - host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); - done += n; + for (twin, end) in ends.into_iter().enumerate() { + if done == end { + continue; + } + if self.sampler { + null_sampler(start); + } else if twin == 1 { + null_buffer_view(start); + } else { + null_view(start); + } + let mut filled = 1; + while filled < BLOCK { + let n = filled.min(BLOCK - filled); + host.device.CopyDescriptorsSimple(n, at(filled), start, kind); + filled += n; + } + while done < end { + let n = BLOCK.min(end - done); + host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); + done += n; + } } } Ok(()) @@ -1148,7 +1252,8 @@ impl HostHeap { /// A plain point sampler at slot `index`, for sampler slots without a /// view. fn null_sampler(&self, index: u32) { - null_sampler(self.cpu(index)); + null_sampler(self.at(index)); + self.put(index); } } @@ -1525,6 +1630,19 @@ impl HostHeap { if self.sampler { return 0; } + { + let mut after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner()); + if !after.is_empty() { + let finished = crate::host::submissions().1; + let mut now = RESHOWN.lock().unwrap_or_else(|e| e.into_inner()); + after.retain(|&(at, start)| { + if at <= finished { + now.push(start); + } + at > finished + }); + } + } let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner())); if starts.is_empty() { return 0; @@ -1545,7 +1663,8 @@ impl HostHeap { let Some(view) = view_at(key as u32, (key >> 32) as u32) else { continue; }; - if let Some(kept) = make(&view, self.cpu(slot)) { + if let Some(kept) = make(&view, self.at(slot)) { + self.put(slot); self.keep(slot, kept); remade += 1; } @@ -1594,6 +1713,76 @@ impl HostHeap { true } + /// Whether host slot `index` shows the placed texture the title's record + /// at `handle` views, by an earlier view of it. + pub(crate) fn texture_slot_shows_other(&self, index: u32, handle: u64) -> bool { + let key = record_key(handle); + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + let Some(&shown) = made.get(index as usize) else { + return false; + }; + if key == 0 || shown == 0 || shown == key { + return false; + } + let view = |key: u64| view_at(key as u32, (key >> 32) as u32); + matches!((view(shown), view(key)), (Some(a), Some(b)) if same_placed_texture(&a, &b)) + } + + /// Slot `index` is made from the record at `handle` (what it is now) + /// when `list`, which holds the upload of what that view shows, has run: + /// until then it shows what it showed. (Made at once, the frames on the + /// card read the new view before its levels were filled.) + pub(crate) fn texture_slot_flip(&self, list: &crate::host::HostList, index: u32, handle: u64) { + let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); + list.defer_host(move || { + let after = crate::host::submissions().0; + let flip = Flip { after, heap, index, handle, key }; + FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip); + }); + } + + /// Makes the slots whose new view's upload has run + /// ([`HostHeap::texture_slot_flip`]); returns how many. + pub(crate) fn texture_slots_flip(&self) -> usize { + use std::sync::atomic::Ordering::Relaxed; + let finished = crate::host::submissions().1; + let ready: Vec = { + let mut flips = FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + if flips.is_empty() { + return 0; + } + let own = std::ptr::from_ref(self) as usize; + let (ready, wait): (Vec, Vec) = + flips.drain(..).partition(|f| f.after <= finished && f.heap == own); + *flips = wait; + ready + }; + let mut flipped = 0; + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + for f in ready { + let Some(shown) = made.get_mut(f.index as usize) else { + continue; + }; + if *shown == f.key { + continue; + } + // Written again since, or made null: that write is in the queue. + let view = view_at(f.key as u32, (f.key >> 32) as u32); + let (true, true, Some(view)) = (f.key != 0 && record_key(f.handle) == f.key, *shown != 0, view) else { + FLIPPED[1].fetch_add(1, Relaxed); + continue; + }; + if let Some(kept) = make(&view, self.at(f.index)) { + self.put(f.index); + *shown = f.key; + self.keep(f.index, kept); + flipped += 1; + } + } + FLIPPED[0].fetch_add(flipped as u64, Relaxed); + flipped + } + /// The memory of the texture title slot `index` views is there (again): /// see [`HostHeap::texture_slot_gone`]. pub(crate) fn texture_slot_here(&self, index: u32) { @@ -1613,9 +1802,11 @@ impl HostHeap { return; } match view_at(key as u32, (key >> 32) as u32) { - Some(view) => null_for(&view, self.cpu(index)), - None => null_view(self.cpu(index)), + Some(view) => null_for(&view, self.at(index)), + None => null_view(self.at(index)), } + self.put(index); + self.clear_twin(index); self.keep(index, None); } @@ -1761,23 +1952,25 @@ impl HostHeap { // (And the level the view starts at: word 4 of a texture // view's description, after format, dimension, mapping // and a pad.) - Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32, desc[4])) + let at = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let held = crate::resource::placed_bytes_from(resource, crate::resource::first_mip(desc)); + Some((resource, at, desc[4], held.map_or(u64::MAX, |held| at.saturating_add(held)))) } _ => None, }; let stale = { use std::sync::atomic::Ordering::Relaxed; let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); - let span = placed_view.and_then(|(resource, start, first)| { - Some((start, start.saturating_add(placed.bytes(resource)?), first)) + let span = placed_view.and_then(|(resource, start, first, held)| { + Some((start, start.saturating_add(placed.bytes(resource)?), first, held)) }); match span { - Some((start, end, first)) => { + Some((start, end, first, held)) => { SPANNED[0].fetch_min(start, Relaxed); SPANNED[1].fetch_max(end, Relaxed); placed.rule = stale_rule(); let stale = placed.note(index, start, end, !seen); - placed.shows(index, first); + placed.shows(index, first, held); stale } None => { @@ -1838,10 +2031,11 @@ impl HostHeap { /// Makes slot `index` (a dynamic one) from `view`; a null view if the /// host cannot. pub(crate) fn make_at(&self, index: u32, view: &View) { - let kept = make(view, self.cpu(index)); + let kept = make(view, self.at(index)); if kept.is_none() { - null_for(view, self.cpu(index)); + null_for(view, self.at(index)); } + self.put(index); self.keep(index, kept.flatten()); } @@ -1850,15 +2044,36 @@ impl HostHeap { if self.sampler { self.null_sampler(index); } else { - null_view(self.cpu(index)); + null_view(self.at(index)); + self.put(index); } self.keep(index, None); } + /// Where the raw twin of title slot `index` is. + fn twin(&self, index: u32) -> Option { + (index < self.twins.len() as u32).then(|| staged(self.sampler, 1).unwrap_or_else(|| self.cpu(self.raw + index))) + } + + /// The raw twin of title slot `index` is a null view again. + fn clear_twin(&self, index: u32) { + if let Some(made) = self.twins.get(index as usize) + && made.swap(false, std::sync::atomic::Ordering::Relaxed) + { + null_buffer_view(self.at(self.raw + index)); + self.put(self.raw + index); + } + } + /// Slot `index` now views `resource` (or nothing of the host's). fn keep(&self, index: u32, resource: Option) { let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); if let Some(slot) = kept.get_mut(index as usize) { + use windows::core::Interface; + // The same again: nothing to retire. + if slot.as_ref().map(Interface::as_raw) == resource.as_ref().map(Interface::as_raw) { + return; + } // A running submission may still read the old resource through // this slot. if let Some(old) = std::mem::replace(slot, resource) { @@ -1890,15 +2105,17 @@ impl HostHeap { // SAFETY: a slot of our heap and a live buffer covering the range. unsafe { host.device - .CreateShaderResourceView(buffer, Some(&desc), self.cpu(index)) + .CreateShaderResourceView(buffer, Some(&desc), self.at(index)) }; + self.put(index); self.keep(index, Some(buffer.clone())); } /// Makes slot `index` (a dynamic one) a raw buffer view that reads /// zeros. pub(crate) fn null_raw_at(&self, index: u32) { - null_buffer_view(self.cpu(index)); + null_buffer_view(self.at(index)); + self.put(index); self.keep(index, None); } @@ -1928,16 +2145,16 @@ impl HostHeap { buffer, None::<&ID3D12Resource>, Some(&desc), - self.cpu(index), + self.at(index), ) }; + self.put(index); self.keep(index, Some(buffer.clone())); } /// Makes slot `index` (a dynamic one) a raw unordered access view of /// nothing: reads give zeros, writes are dropped. pub(crate) fn null_raw_uav_at(&self, index: u32) { - self.keep(index, None); let Some(host) = host() else { return }; let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_TYPELESS, @@ -1956,9 +2173,11 @@ impl HostHeap { None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&desc), - self.cpu(index), + self.at(index), ) }; + self.put(index); + self.keep(index, None); } /// The shader-visible handle of slot `index`. @@ -1971,9 +2190,17 @@ impl HostHeap { } /// Makes slot `index` (a dynamic one) a constant buffer view of host - /// memory (the list's own, which it holds). - pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { - self.keep(index, None); + /// memory, `size` bytes at `gpu` of `buffer`, which the slot holds. + /// + /// The list holds it too, until it is reset; the slot shows it until it + /// is made again, and a shader that picks the slot by an index it + /// computes from wrong data reads it through there. The list's scratch + /// chunks go back to the pool and are freed past its limit: session n02 + /// lost the device to a page fault in the memory of three freed ones. + /// `VICTORY_SLOT_HOLDS=0`: only the list holds it, as before. + pub(crate) fn constant_at(&self, index: u32, buffer: &ID3D12Resource, gpu: u64, size: u32) { + static HOLDS: std::sync::OnceLock = std::sync::OnceLock::new(); + let holds = *HOLDS.get_or_init(|| std::env::var_os("VICTORY_SLOT_HOLDS").is_none_or(|v| v != "0")); let Some(host) = host() else { return }; let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, @@ -1982,8 +2209,45 @@ impl HostHeap { // SAFETY: a slot of our heap; the memory is the caller's. unsafe { host.device - .CreateConstantBufferView(Some(&desc), self.cpu(index)) + .CreateConstantBufferView(Some(&desc), self.at(index)) }; + self.put(index); + // After the descriptor: what it showed is let go when nothing shows + // it any more. + self.keep(index, holds.then(|| buffer.clone())); + } + + /// Where a descriptor for slot `index` is made, then [`HostHeap::put`]: + /// a slot of this thread's in a heap the card does not see + /// ([`staged`]), or the slot itself. + fn at(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { + staged(self.sampler, 0).unwrap_or_else(|| self.cpu(index)) + } + + /// The descriptor this thread made last ([`HostHeap::at`]) goes to slot + /// `index`. + fn put(&self, index: u32) { + self.copy_to(index, 0); + } + + /// The raw twin this thread made last goes to that of slot `index`. + fn put_twin(&self, index: u32) { + if self.twin(index).is_some() { + self.copy_to(self.raw + index, 1); + } + } + + fn copy_to(&self, to: u32, which: u32) { + let (Some(from), Some(host)) = (staged(self.sampler, which), host()) else { + return; // made in place + }; + let kind = if self.sampler { + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER + } else { + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV + }; + // SAFETY: a slot of our heap, and one of this thread's heap slots. + unsafe { host.device.CopyDescriptorsSimple(1, self.cpu(to), from, kind) }; } fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { @@ -2106,6 +2370,7 @@ impl HostHeap { // title released): nothing to read. if made[index as usize] != 0 { made[index as usize] = 0; + self.clear_twin(index); self.make_null(index); let _ = self.note_buffer(index, None, false); } else if for_draw { @@ -2151,10 +2416,21 @@ impl HostHeap { let kept = if later { None } else { - make(&view, self.cpu(index)) + make_twinned(&view, self.at(index), self.twin(index)) }; if kept.is_none() && !self.sampler { - null_for(&view, self.cpu(index)); + null_for(&view, self.at(index)); + } + if kept.is_some() || !self.sampler { + self.put(index); + } + if kept.is_some() && twinned(&view) { + self.put_twin(index); + if let Some(made) = self.twins.get(index as usize) { + made.store(true, std::sync::atomic::Ordering::Relaxed); + } + } else { + self.clear_twin(index); } self.keep(index, kept.flatten()); } @@ -2218,6 +2494,90 @@ impl HostHeap { } } +/// Slots of this thread's own in heaps the card does not see, two of views +/// and two of samplers (`which` 0 or 1): descriptors are made there and +/// copied whole into the heaps it does see. Made in place they are seen half +/// written: an RX 7900 XTX saw a texture of no size in 4 % of its reads of +/// slots whose views a thread made over and over (the driver clears the +/// descriptor and fills it step by step), and none in 8,500 million with the +/// same descriptors copied, three times as fast +/// (`indirect::tests::descriptors_written_under_readers`). Title threads and +/// our passes rewrite slots while submissions run whose shaders pick them; +/// three device losses of 2026-11-25 (play-1125-0203, n02, n03) were reads of +/// memory no view names. `VICTORY_VIEW_COPY=0`: made in place, as before. +fn staged(sampler: bool, which: u32) -> Option { + /// Threads at a time that have slots; more make views in place. + const THREADS: u32 = 4096; + struct Stage { + starts: [usize; 2], + steps: [usize; 2], + _heaps: [ID3D12DescriptorHeap; 2], + } + // SAFETY: descriptor heaps are free-threaded; each thread has slots of + // its own. + unsafe impl Send for Stage {} + // SAFETY: as above. + unsafe impl Sync for Stage {} + static STAGE: std::sync::OnceLock> = std::sync::OnceLock::new(); + /// Places given back, and how many were ever given out. + static PLACES: Mutex<(Vec, u32)> = Mutex::new((Vec::new(), 0)); + struct Place(Option); + impl Drop for Place { + fn drop(&mut self) { + if let Some(place) = self.0 { + PLACES.lock().unwrap_or_else(|e| e.into_inner()).0.push(place); + } + } + } + thread_local! { + static PLACE: Place = { + let mut places = PLACES.lock().unwrap_or_else(|e| e.into_inner()); + Place(places.0.pop().or_else(|| { + (places.1 < THREADS).then(|| { + places.1 += 1; + places.1 - 1 + }) + })) + }; + } + let stage = STAGE + .get_or_init(|| { + if std::env::var_os("VICTORY_VIEW_COPY").is_some_and(|v| v == "0") { + return None; + } + let host = host()?; + let make = |kind: D3D12_DESCRIPTOR_HEAP_TYPE| -> Option { + // SAFETY: plain heap creation. + unsafe { + host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: 2 * THREADS, + ..Default::default() + }) + } + .inspect_err(|e| tracing::warn!(error = %e, "no heap to make views in: they are made in place")) + .ok() + }; + let kinds = [D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER]; + let heaps = [make(kinds[0])?, make(kinds[1])?]; + // SAFETY: live heaps, plain queries. + let (starts, steps) = unsafe { + ( + [0, 1].map(|i: usize| heaps[i].GetCPUDescriptorHandleForHeapStart().ptr), + kinds.map(|kind| host.device.GetDescriptorHandleIncrementSize(kind) as usize), + ) + }; + Some(Stage { starts, steps, _heaps: heaps }) + }) + .as_ref()?; + // (A thread that is ending has none any more.) + let place = PLACE.try_with(|p| p.0).ok().flatten()?; + let kind = usize::from(sampler); + Some(D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: stage.starts[kind] + (2 * place + which) as usize * stage.steps[kind], + }) +} + /// Logs `what` the first time it happens. macro_rules! once { ($($arg:tt)*) => {{ @@ -2444,11 +2804,74 @@ fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: .is_some_and(|end| end <= width) } +/// Raw twins ([`raw_twins`]) made since the last frame line, and those of them that +/// do not begin on 16 bytes, as a raw view must ([`move_raw`]), and those of +/// these that could not be moved there (null). +pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Moves the raw view at `at`, a slot of our heaps the card does not see, +/// which shows `bytes` from `start` on (GPU address), `by` bytes on: for a +/// twin whose view begins between two multiples of 16, where the host makes +/// no raw view. An AMD descriptor of a raw buffer is its address (48 bits), +/// its bytes and flags; only one that says just that is changed, and only +/// where what the handle points at is the descriptor. False: not moved. +fn move_raw(at: D3D12_CPU_DESCRIPTOR_HANDLE, start: u64, bytes: u32, by: u32) -> bool { + if !by.is_multiple_of(4) || by >= bytes { + return false; + } + let mut words = [0u8; 16]; + if !crate::host::read_into(at.ptr as *const u8, &mut words) { + return false; + } + let word = |i: usize| u32::from_le_bytes([words[4 * i], words[4 * i + 1], words[4 * i + 2], words[4 * i + 3]]); + let address = u64::from(word(0)) | u64::from(word(1)) << 32; + if address != start || word(2) != bytes || start >> 48 != 0 { + return false; + } + let moved = start + u64::from(by); + // SAFETY: this thread's own slot (it has slots of its own: the caller + // asks only for those), read just now. + unsafe { + let words = at.ptr as *mut u32; + words.write(moved as u32); + words.add(1).write((moved >> 32) as u32); + words.add(2).write(bytes - by); + } + true +} + +/// The bytes a buffer view the host takes ([`buffer_view_ok`]) shows as a raw +/// view (first dword, dwords, and the bytes past that dword it begins: a raw +/// view begins on 16 bytes); of a buffer of `width` bytes. +fn twin_window(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> Option<(u64, u32, u32)> { + use std::sync::atomic::Ordering::Relaxed; + TWINS[0].fetch_add(1, Relaxed); + let element = if raw { + 4 + } else if stride > 0 { + u64::from(stride) + } else { + crate::resource::element(format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + let (start, end) = (first * element, ((first + u64::from(count)) * element).next_multiple_of(4)); + let end = end.min(width & !3); + let from = start & !15; + if end <= start { + return None; + } + let dwords = u32::try_from((end - from) / 4).ok()?; + if from != start { + TWINS[1].fetch_add(1, Relaxed); + } + Some((from / 4, dwords, (start - from) as u32)) +} + fn buffer_srv( address: u64, len: u64, mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE, + twin: Option, ) -> Option { let mut shadow = crate::shadow::find(address, len)?; let mut offset = shadow.offset(address); @@ -2519,6 +2942,30 @@ fn buffer_srv( host.device .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) }; + if let Some(twin) = twin { + let window = twin_window(desc.Format, first, count, stride, raw, width); + if let Some((first, count, by)) = window { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer = D3D12_BUFFER_SRV { + FirstElement: first, + NumElements: count, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }; + // SAFETY: a live buffer and a slot of our heap. + let start = unsafe { + host.device + .CreateShaderResourceView(&shadow.buffer, Some(&desc), twin); + shadow.buffer.GetGPUVirtualAddress() + first * 4 + }; + if by > 0 && !(staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, count.saturating_mul(4), by)) { + TWINS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + null_buffer_view(twin); + } + } else { + null_buffer_view(twin); + } + } Some(Some(shadow.buffer.clone())) } @@ -2532,6 +2979,7 @@ fn buffer_uav( len: u64, mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE, + twin: Option, ) -> Option { let mut shadow = crate::shadow::find(address, len)?; let unit = { @@ -2617,6 +3065,31 @@ fn buffer_uav( host.device .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) }; + if let Some(twin) = twin { + let window = twin_window(desc.Format, first, count, stride, raw, width); + if let Some((first, count, by)) = window { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer = D3D12_BUFFER_UAV { + FirstElement: first, + NumElements: count, + StructureByteStride: 0, + CounterOffsetInBytes: 0, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + }; + // SAFETY: a live buffer and a slot of our heap. + let start = unsafe { + host.device + .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), twin); + shadow.buffer.GetGPUVirtualAddress() + first * 4 + }; + if by > 0 && !(staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, count.saturating_mul(4), by)) { + TWINS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + null_buffer_view(twin); + } + } else { + null_buffer_view(twin); + } + } Some(Some(shadow.buffer.clone())) } @@ -2763,6 +3236,17 @@ fn constant_bytes(size: u32) -> u32 { /// Makes the host descriptor for `view` at `at`: the host resource it /// views, or `None` if it cannot. fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { + make_twinned(view, at, None) +} + +/// [`make`]; `twin`: where the raw twin of a buffer view goes +/// ([`raw_twins`]; a constant buffer's is the same view again, other views +/// have none). +fn make_twinned( + view: &View, + at: D3D12_CPU_DESCRIPTOR_HANDLE, + twin: Option, +) -> Option { let host = host()?; let device = &host.device; match view { @@ -2780,13 +3264,19 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { BufferLocation: gpu, SizeInBytes: constant_bytes(size), }; - // SAFETY: a slot of our heap; the range lies in the host copy. - unsafe { device.CreateConstantBufferView(Some(&desc), at) }; + // SAFETY: slots of our heap; the range lies in the host copy. + unsafe { + device.CreateConstantBufferView(Some(&desc), at); + if let Some(twin) = twin { + device.CreateConstantBufferView(Some(&desc), twin); + } + } Some(Some(shadow.buffer.clone())) } View::Shader(resource, desc) => { let resource = *resource as crate::object::This; - if let Some(texture) = crate::resource::host_resource(resource) { + if let Some(copy) = crate::resource::host_copy(resource) { + let texture = ©.texture; // The title's views of textures with a stencil plane, as it // describes them (format, dimension, component mapping, a // pad, then first level, levels, plane): each distinct one @@ -2841,6 +3331,11 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { }; crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels)); } + if copy.base > 0 + && let Some(desc) = &mut desc + { + from_base(desc, copy.base); + } // SAFETY: a live texture and a slot of our heap. unsafe { device.CreateShaderResourceView( @@ -2853,7 +3348,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { } else if let (Some((data, len)), Some(desc)) = (crate::resource::buffer_bytes(resource), desc) { - buffer_srv(data as u64, len, srv_desc(desc), at) + buffer_srv(data as u64, len, srv_desc(desc), at, twin) } else { None } @@ -2863,7 +3358,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { let Some(texture) = crate::resource::host_resource(resource) else { return match (crate::resource::buffer_bytes(resource), desc) { (Some((data, len)), Some(desc)) => { - buffer_uav(data as u64, len, uav_desc(desc), at) + buffer_uav(data as u64, len, uav_desc(desc), at, twin) } _ => None, }; @@ -2967,14 +3462,31 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { return None; } if *unordered { - buffer_uav(address, len, uav_desc(words), at) + buffer_uav(address, len, uav_desc(words), at, twin) } else { - buffer_srv(address, len, srv_desc(words), at) + buffer_srv(address, len, srv_desc(words), at, twin) } } } } +/// The view `desc` of a texture, of a host copy of its levels from `base` +/// on (`crate::resource::held_only`). What it shows of larger ones, if any, +/// is left out. +fn from_base(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, base: u32) { + if desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D { + return; + } + // SAFETY: the member its dimension says. + let t = unsafe { &mut desc.Anonymous.Texture2D }; + let lost = base.saturating_sub(t.MostDetailedMip); + t.MostDetailedMip = t.MostDetailedMip.saturating_sub(base); + if t.MipLevels != u32::MAX { + t.MipLevels = t.MipLevels.saturating_sub(lost).max(1); + } + t.ResourceMinLODClamp = (t.ResourceMinLODClamp - base as f32).max(0.0); +} + /// Writes of a slot with another view of the placed texture it showed, /// since the start: the slot kept showing the old view. pub(crate) static KEPT_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -2993,7 +3505,10 @@ fn keep_views() -> bool { fn same_placed_texture(a: &View, b: &View) -> bool { match (a, b) { (View::Placed(false, resource, desc), View::Placed(false, other, other_desc)) => { - resource[0] != 1 && resource == other && desc[10..12] == other_desc[10..12] + // (Words 1 and 13 are the filler of the description's layout, not + // part of what a texture is: `crate::resource::texture_at`.) + let same = |from: usize, to: usize| resource[from..to] == other[from..to]; + resource[0] != 1 && resource[0] == other[0] && same(2, 13) && desc[10..12] == other_desc[10..12] } _ => false, } @@ -3011,6 +3526,7 @@ pub(crate) fn placed_texture(view: &View) -> Option { } let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let texture = crate::resource::texture_at(address, resource)?; + crate::resource::want_level(texture, crate::resource::first_mip(desc)); Some(View::Shader(texture as usize, desc[..10].try_into().ok())) } @@ -3186,6 +3702,40 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { mod tests { use super::*; + /// A view of a host copy that begins at a later level shows the same + /// levels of it. + #[test] + fn views_count_from_the_first_level_of_the_host_copy() { + let view = |first, levels, clamp| { + let mut desc = srv_desc(&[98, 4, 5768, 0, first, levels, 0, 0, 0, 0]); + desc.Anonymous.Texture2D.ResourceMinLODClamp = clamp; + from_base(&mut desc, 3); + // SAFETY: the member its dimension says. + let t = unsafe { desc.Anonymous.Texture2D }; + (t.MostDetailedMip, t.MipLevels, t.ResourceMinLODClamp) + }; + assert_eq!(view(3, 4, 0.0), (0, 4, 0.0)); + assert_eq!(view(5, u32::MAX, 5.5), (2, u32::MAX, 2.5)); + // (Two levels the copy has not.) + assert_eq!(view(1, 4, 0.0), (0, 2, 0.0)); + } + + /// Memory past the levels a slot's view shows is not its texture's. + #[test] + fn a_view_of_smaller_levels_is_not_told_of_memory_past_them() { + let mut spans = Spans::default(); + spans.note(1, 0x10000, 0x50000, true); + spans.shows(1, 3, 0x12000); + spans.note(2, 0x10000, 0x50000, true); + spans.shows(2, 0, 0x50000); + assert_eq!(spans.slots_holding(0x11000, 0x11800), vec![1, 2]); + assert_eq!(spans.slots_holding(0x20000, 0x21000), vec![2]); + assert_eq!(spans.slots_in(0x20000, 0x21000), vec![2]); + spans.forget(2); + assert!(spans.slots_in(0x20000, 0x21000).is_empty()); + assert_eq!(spans.slots_in(0x0, 0x10001), vec![1]); + } + /// A texture filled with less than was mapped is looked at again, but /// not for ever: memory that is shown and cannot be read ends it, and a /// filling that got everything starts the count anew. @@ -3235,9 +3785,9 @@ mod tests { // A 512x512 texture of 0x56000 bytes viewed from levels 3 and 1, // and the next one 0x6000 after it (run 188). spans.note(1, 0x1_0000, 0x1_0000 + 0x5_6000, true); - spans.shows(1, 3); + spans.shows(1, 3, u64::MAX); spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true); - spans.shows(2, 1); + spans.shows(2, 1, u64::MAX); spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true); assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000)); assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None); @@ -3297,7 +3847,7 @@ mod tests { assert!(alive(), "a view of {size} bytes"); } // SAFETY: a live upload buffer. - heap.constant_at(1, unsafe { buffer.GetGPUVirtualAddress() }, 969_472); + heap.constant_at(1, &buffer, unsafe { buffer.GetGPUVirtualAddress() }, 969_472); assert!(alive(), "a view of the list's own memory"); assert_eq!(constant_bytes(480), 512); assert_eq!(constant_bytes(64 << 10), 64 << 10); @@ -3337,6 +3887,101 @@ mod tests { assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096)); } + /// The raw twin of a view shows the same bytes: typed and structured ones + /// that begin on 16 bytes, whole dwords, none past the buffer. + #[test] + fn raw_twins_show_the_views_bytes() { + let (u16s, u32s, none) = (DXGI_FORMAT(57), DXGI_FORMAT(42), DXGI_FORMAT_UNKNOWN); + assert_eq!(twin_window(u32s, 4, 10, 0, false, 4096), Some((4, 10, 0))); + assert_eq!(twin_window(u16s, 8, 7, 0, false, 4096), Some((4, 4, 0))); + // the last dword would reach past the buffer + assert_eq!(twin_window(u16s, 8, 7, 0, false, 30), Some((4, 3, 0))); + assert_eq!(twin_window(none, 2, 3, 24, false, 4096), Some((12, 18, 0))); + assert_eq!(twin_window(DXGI_FORMAT_R32_TYPELESS, 8, 5, 0, true, 4096), Some((8, 5, 0))); + // where no raw view begins: from the 16 bytes below + assert_eq!(twin_window(none, 1, 3, 24, false, 4096), Some((4, 20, 8))); + assert_eq!(twin_window(u32s, 1, 10, 0, false, 4096), Some((0, 11, 4))); + assert_eq!(twin_window(u32s, 1, 10, 0, false, 4), None); + } + + /// What a slot is made as is made beside the heap and copied in whole: the + /// slot's descriptor is the one the view has, and each thread makes its + /// own. + #[test] + fn views_are_made_beside_the_heap_and_copied_in() { + let Some(host) = host() else { + return; // no host GPU here + }; + let Some(heap) = HostHeap::new(false, 4) else { + return; + }; + let (Some(a), Some(b)) = (staged(false, 0), staged(false, 1)) else { + return; + }; + assert_ne!(a.ptr, b.ptr); + assert_ne!(Some(a.ptr), std::thread::spawn(|| staged(false, 0).map(|h| h.ptr)).join().unwrap()); + let (buffer, _) = host.shared_buffer(1 << 16).unwrap(); + let index = heap.dynamic(1).unwrap(); + let bytes = |at: D3D12_CPU_DESCRIPTOR_HANDLE| { + let mut bytes = [0u8; 32]; + crate::host::read_into(at.ptr as *const u8, &mut bytes).then_some(bytes) + }; + heap.raw_at(index, &buffer, 64, 1024); + let (slot, beside) = (bytes(heap.cpu(index)), bytes(staged(false, 0).unwrap())); + assert_eq!(slot, beside, "copied as it was made"); + heap.null_raw_at(index); + assert_ne!(bytes(heap.cpu(index)), slot, "another view since"); + // SAFETY: a plain query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + } + + /// A raw view moved on by some dwords says so in its descriptor, on a + /// card whose descriptors are what we take them for; on another nothing + /// is changed. + #[test] + fn a_raw_view_is_moved_only_where_its_descriptor_says_where_it_is() { + let (Some(host), Some(at)) = (host(), staged(false, 1)) else { + return; // no host GPU here + }; + let (buffer, _) = host.shared_buffer(1 << 16).unwrap(); + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: 8, + NumElements: 100, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + // SAFETY: this thread's slot, a live buffer. + let start = unsafe { + host.device.CreateShaderResourceView(&buffer, Some(&desc), at); + buffer.GetGPUVirtualAddress() + 32 + }; + let words = || { + let mut bytes = [0u8; 32]; + assert!(crate::host::read_into(at.ptr as *const u8, &mut bytes)); + bytes + }; + let before = words(); + assert!(!move_raw(at, start + 16, 400, 8), "another address"); + assert!(!move_raw(at, start, 404, 8), "another size"); + assert!(!move_raw(at, start, 400, 2), "not a dword"); + assert_eq!(words(), before); + if move_raw(at, start, 400, 8) { + let moved = words(); + assert_eq!(moved[..8], (start + 8).to_le_bytes()); + assert_eq!(moved[8..12], 392u32.to_le_bytes()); + assert_eq!(moved[12..], before[12..]); + } else { + assert_eq!(words(), before); + } + } + /// Views that begin where no host view can: raw ones off 16 bytes, /// structured ones off their elements (and off 16 bytes, where they are /// made raw), typed ones off theirs. diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 8454580..6885c8c 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -95,6 +95,34 @@ fn early_budgets() -> (u64, u64) { }) } +/// Whether a draw of the title's bake finds the textures it picks by index +/// as title memory has them at that moment (`VICTORY_BAKE_EXACT=0`: as the +/// pass leaves them, as before). The pass looks at a slot whose memory was +/// written or mapped a frame or two later, by when the rest of it has +/// landed, and at one uploaded whole a few frames later again, for a title +/// that fills memory unnoticed: a bake in between took the bytes from before +/// (another texture's), and what it bakes stays: coloured specks all over +/// the waitress's face for the whole diner scene (run n01), none in other +/// runs. So the pass ahead of a bake takes those slots too, and its uploads +/// wait for title memory that is being remapped (`crate::texture` `BAKING`). +fn bake_exact() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_BAKE_EXACT").is_none_or(|v| v != "0")) +} + +/// Whether a texture found changed with nothing to tell of it is looked at +/// again in the next frame (`VICTORY_RECHECK_SOON=0`: after four, as +/// before). +fn recheck_soon() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_RECHECK_SOON").is_none_or(|v| v != "0")) +} + +/// Frames ahead the pass before a bake takes slots from that are due only +/// then ([`bake_exact`]): those of notices (1 and 2), and the first looks +/// again ([`RECHECK_FRAMES`]). +const BAKE_AHEAD: u64 = 12; + /// The pixel shaders of the title's decoration bake (the title: /// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the /// frame listings print it. They draw into a 256x256 corner of 2048x2048 @@ -283,6 +311,10 @@ pub(crate) struct State { /// The records clamped in a batch, if later executions may still read /// them ([`batches`]). batch: Option, + /// The user data bound last, of the last stage that has some (for the + /// report of a removed device, `crate::host::indirects`). + #[cfg(feature = "diagnostics")] + user: Vec, /// What the host list has: pipeline, root signature, heaps. host_pipeline: usize, /// Graphics, compute. @@ -601,6 +633,7 @@ fn heap_recheck() -> bool { } /// Times a placed texture's slot was passed over because its memory is not /// mapped. +pub(crate) static HEAP_TEXTURES_SAME: AtomicU64 = AtomicU64::new(0); pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0); /// Slots the pass found up to date already: their texture is uploaded by /// the draws that read it through a table (it has a staging buffer). @@ -1250,6 +1283,11 @@ impl State { None => self.user_value(compute, u.slot, u.root, u.dword), }; } + #[cfg(feature = "diagnostics")] + { + self.user.clear(); + self.user.extend_from_slice(&values); + } // SAFETY: an open list; `values` covers the parameter. unsafe { if compute { @@ -1824,7 +1862,9 @@ impl State { } let began = std::time::Instant::now(); PASS_BUDGET.set(Some(budget)); + crate::texture::BAKING.set(bake && bake_exact()); self.heap_textures(list, heap, host); + crate::texture::BAKING.set(false); PASS_BUDGET.set(None); if bake { BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); @@ -1974,15 +2014,26 @@ impl State { // wrote since the last pass are due again. host.texture_slots_remapped(frame); host.texture_slots_short(frame); - // Levels on demand: the slots of textures whose first level with - // memory changed since the last pass are made again from it. + // The slots of textures whose first level with memory (levels on + // demand), or whose host copy for one with more levels, changed since + // the last pass are made again from it; those whose new view's upload + // has run are made from that. host.texture_views_remade(); + host.texture_slots_flip(); // And with room, the textures whose upload left a held level // without the card's memory are uploaded again. if room { host.texture_slots_waiting(frame); } - let (due, census) = host.texture_slots_due(frame, 4096); + let baking = crate::texture::BAKING.get(); + let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 }); + // (Those that are due later after all that are due.) + let on_time = due.len(); + if baking { + let known: std::collections::HashSet = due.iter().map(|&(index, _)| index).collect(); + let (ahead, _) = host.texture_slots_due(frame + BAKE_AHEAD, 1 << 16); + due.extend(ahead.into_iter().filter(|(index, _)| !known.contains(index))); + } HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { count.store(now, Ordering::Relaxed); @@ -2025,7 +2076,7 @@ impl State { // drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget. static CATCHUP: std::sync::OnceLock = std::sync::OnceLock::new(); let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0")); - let (per_frame, span) = if catchup && due.len() >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) }; + let (per_frame, span) = if catchup && on_time >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) }; // A run made early (`State::early_textures`) has a budget of its // own: its bytes on top of what the frame has spent so far. // (Not `most`: that is the longest wait between looks, used below.) @@ -2059,6 +2110,12 @@ impl State { // first look for the rest of the run. The look reads 48 KiB; // only a changed texture is uploaded again. // `VICTORY_HEAP_RECHECK=0`: uploaded once, as before. + // One found changed by such a look is looked at in the next frame + // again: the textures left that change unnoticed are ones the + // title paints all the time through another view of their pages + // (all their blocks are shown at other addresses too), and each + // was shown four frames late, over and over. + let mut again_in = RECHECK_FRAMES[0]; if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) { if crate::texture::fingerprint(at, len) == print { HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed); @@ -2070,9 +2127,21 @@ impl State { } continue; } + if recheck_soon() { + again_in = 1; + } let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed); if n < 200 || n.is_multiple_of(1000) { + // Whether its pages are the title's at other addresses + // too: what is written there is told of there alone. + let elsewhere = crate::inplace::shown_elsewhere(at as usize & !0xffff, (at + len) as usize); + let first = heap.handle(index).and_then(crate::descriptor::view).map_or(0, |view| match view { + View::Placed(false, _, desc) => crate::resource::first_mip(&desc), + _ => 0, + }); tracing::warn!( + first_level = first, + blocks_shown_elsewhere = elsewhere.len(), slot = index, address = format_args!("{at:#x}"), bytes = len, @@ -2086,7 +2155,8 @@ impl State { let mut partly = None; if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; - let len = crate::resource::placed_bytes(&resource).unwrap_or(1); + let first = crate::resource::first_mip(&desc); + let len = crate::resource::placed_bytes_from(&resource, first).unwrap_or(1); let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize); if mapped == 0 { HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed); @@ -2159,7 +2229,15 @@ impl State { ); } } - let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true)); + // A slot that shows the texture by an earlier view of it (one + // from another level) goes on doing so until the upload of what + // the new one shows has run. + let shows_other = !baking + && crate::resource::held_only() + && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle)); + let view = heap.handle(index).and_then(|handle| { + if shows_other { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) } + }); let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); let resource = match placed.as_ref().or(view.as_ref()) { Some(&View::Shader(resource, _)) => resource as This, @@ -2178,9 +2256,34 @@ impl State { // through a table: they upload it, and check it at every // submission that samples it. let tabled = crate::texture::is_staged(resource); + // The host copy holds these very bytes: nothing to upload. + let first = match (&placed, &view) { + (Some(_), Some(View::Placed(_, _, desc))) => crate::resource::first_mip(desc), + _ => 0, + }; + let same = !tabled && crate::texture::unchanged(resource, first); + if same { + HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed); + if shows_other && let Some(handle) = heap.handle(index) { + let _ = host.mirror(index, handle, true); + } + let again = partly.map(|mapped| (frame + 1, mapped)); + let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None }; + match memory { + Some((at, len)) => { + let print = crate::texture::fingerprint(at, len); + host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame); + } + None => host.texture_slot_done(index, write, again), + } + continue; + } if let Some(view) = &view { readable(list, sampled.kind, view); } + if shows_other && let Some(handle) = heap.handle(index) { + host.texture_slot_flip(list, index, handle); + } // A texture view the host refuses removes the device: name it. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !GONE.load(Ordering::Relaxed) @@ -2236,7 +2339,7 @@ impl State { // Whole and uploaded: looked at again (see above). Some((at, len)) => { let print = crate::texture::fingerprint(at, len); - host.texture_slot_recheck(index, write, frame + RECHECK_FRAMES[0], (at, len), print, 0, frame); + host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame); } None => host.texture_slot_done(index, write, again), } @@ -2873,13 +2976,13 @@ impl State { let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k); match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { - let Some((gpu, to)) = list.scratch(u64::from(size)) else { + let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else { host.make_null(index); continue; }; let slot = (std::ptr::from_ref(heap) as usize, index); list.defer_constants(to, address as *const u8, size as usize, slot); - host.constant_at(index, gpu, size); + host.constant_at(index, &buffer, gpu, size); } Some(view) => { host.make_at(index, &view); @@ -3387,6 +3490,8 @@ impl State { list.note_op(|| { self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) }); + #[cfg(feature = "diagnostics")] + list.ran_indirect(p.pso.as_raw() as usize, &p.name, kind, max, &self.user); if kind == MESH { self.mesh_scissor(list, true); } @@ -3533,7 +3638,12 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { && let Some(t) = crate::resource::host_resource(*resource as This) && crate::texture::title_written(t) { - crate::texture::upload(list, *resource as This, t); + // Of a texture the title placed, the levels the view shows. + let first = match (&placed, view) { + (Some(_), View::Shader(_, Some(desc))) => crate::resource::first_mip(desc), + _ => 0, + }; + crate::texture::upload_from(list, *resource as This, first); } // A depth texture shaders also write: what they wrote, first. list.twin_use(*resource as This, false, false); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4e46127..c051cb8 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -117,6 +117,34 @@ pub(crate) fn available_physical_ram() -> Option { ok.then_some(m.ullAvailPhys) } +/// How long host copies of textures the title fills must have been idle to +/// be let go, in milliseconds, and how many bytes of them go at most (the +/// longest idle first): none but those of ten minutes while what is in use +/// of the card (`used`: without what our own blocks have free, with what is +/// kept free for others) is under 88 % of its budget, else enough to come +/// down to 85 %. `VICTORY_TEXTURE_KEEP=0`: [`vram_idle_ms`]' older rule, +/// all that are idle; `=1`: that rule with its two longer times. +/// +/// (By those times everything idle for 2.5 s went from 75 % of the budget +/// on: 61,000 of them in the first 300 s of session play-1125-0203, at 78 to +/// 80 %, of which 13,000 were made and uploaded again.) +pub(crate) fn vram_keep(budget: u64, used: u64) -> (u64, u64) { + const KEPT_MS: u64 = 600_000; + const IDLE_MS: u64 = 5_000; + const SHORT_MS: u64 = 1_500; + if budget == 0 { + return (IDLE_MS, u64::MAX); + } + let share = |percent: u64| budget / 100 * percent; + if used < share(88) { + (KEPT_MS, u64::MAX) + } else if used < share(95) { + (IDLE_MS, used - share(85)) + } else { + (SHORT_MS, used - share(85)) + } +} + /// Effective idle timeout (in milliseconds) for VRAM-backed host textures, /// scaled down under VRAM pressure. Never returns less than 1,000 ms so /// handles not yet recorded into a list or slot remain protected. @@ -157,11 +185,37 @@ fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 { } } +/// Whether memory the card was given stays with it while there is room (on +/// by default; `VICTORY_KEEP_FREED=0`: it is given back as before). A shader +/// that reads past a view (a raw load through a typed, structured or +/// constant buffer view has no end on AMD: `indirect::tests::raw_loads_past_views`) +/// or through a slot that shows wrong data reads whatever lies there, and +/// nothing happens; where memory was given back it is a page fault, and the +/// device is lost. Both losses of 2026-11-25 were reads in memory given back +/// seconds before (a block of textures; a list's scratch and a window of +/// title memory). Kept are: empty blocks of textures ([`crate::pool`]) below +/// 85 % of the card's budget, windows of title memory and staging buffers +/// for five minutes with 12 GiB of the PC's memory free, and 1 GiB of +/// scratch chunks. +pub(crate) fn keep_freed() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_FREED").is_none_or(|v| v != "0")) +} + /// Effective idle timeout (in milliseconds) for system-RAM caches (staging /// buffers, loose shadows, and the mapped pipeline library), scaled down /// when free physical RAM is low. Never returns less than 2,000 ms. +/// With plenty of it five minutes ([`keep_freed`]). pub(crate) fn ram_idle_ms(avail_phys: Option) -> u64 { + ram_idle_for(avail_phys, keep_freed()) +} + +fn ram_idle_for(avail_phys: Option, keep: bool) -> u64 { const GIB: u64 = 1024 * 1024 * 1024; + const KEPT_MS: u64 = 300_000; + if keep && avail_phys.is_some_and(|avail| avail >= 12 * GIB) { + return KEPT_MS; + } const NORMAL_MS: u64 = 10_000; const MODERATE_MS: u64 = 5_000; const HIGH_MS: u64 = 2_000; @@ -215,12 +269,19 @@ fn sweep() { { return; } + crate::pool::room(host().and_then(|h| h.video_memory())); crate::pipeline::trim_library(); crate::shadow::let_go_idle(); crate::texture::let_go_idle(); crate::resource::let_go_idle(); } +/// The number of the newest submission begun, and of the newest of which all +/// before it have finished too. +pub(crate) fn submissions() -> (u64, u64) { + (STARTED.load(Ordering::Acquire), FINISHED.load(Ordering::Acquire)) +} + /// Drops `object` once every submission running now has finished: at once /// if none is. pub(crate) fn retire(object: T) { @@ -889,6 +950,9 @@ pub(crate) struct HostList { prelude: OnceLock>, /// The pipelines the list binds, for reports of slow submissions. pipelines: std::sync::Arc>>, + /// What its indirect executions ran, for the report of a removed device. + #[cfg(feature = "diagnostics")] + indirects: indirects::Shared, /// The work its indirect executions may still do (`indirect`): a /// shader-writable word, zeroed when the list is submitted, and after /// it what the clamp notes about mesh records. In memory the CPU maps. @@ -1404,7 +1468,14 @@ pub(crate) fn dred_faults() -> bool { #[cfg(feature = "diagnostics")] #[allow(clippy::type_complexity)] static LIST_NOTES: Mutex< - std::collections::BTreeMap>>, std::sync::Weak>>)>, + std::collections::BTreeMap< + u32, + ( + std::sync::Weak>>, + std::sync::Weak>>, + std::sync::Weak>, + ), + >, > = Mutex::new(std::collections::BTreeMap::new()); /// The number in the name of a list of ours ("victory host list 7", which the @@ -1531,6 +1602,8 @@ const SCRATCH_CHUNK: u64 = 4 << 20; const SCRATCH_FIRST: u64 = 256 << 10; /// The most bytes of chunks kept while no list holds them. const SPARE_MOST: u64 = 128 << 20; +/// The same with [`keep_freed`]. +const SPARE_KEPT: u64 = 1 << 30; /// Whether lists share their scratch chunks: a list takes a chunk when it /// first needs one, a small one first, and gives all of them back when it @@ -1611,7 +1684,7 @@ fn give_chunks(chunks: Vec<(Chunk, u64)>) { let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); for (chunk, size) in chunks { let back = if scratch_pool() { - spare.give(chunk, size, SPARE_MOST) + spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST }) } else { Some(chunk) }; @@ -3156,6 +3229,7 @@ fn late_line(frames: f64) { pub(crate) mod awake; mod card_steps; +pub(crate) mod indirects; mod place; mod send; #[cfg(feature = "diagnostics")] @@ -3525,6 +3599,8 @@ impl Host { let notes = std::sync::Arc::>>::default(); let pipelines = std::sync::Arc::>>::default(); #[cfg(feature = "diagnostics")] + let indirects = indirects::Shared::default(); + #[cfg(feature = "diagnostics")] if dred_on() || dred_light() { static NUMBER: AtomicU32 = AtomicU32::new(0); let number = NUMBER.fetch_add(1, Ordering::Relaxed); @@ -3533,7 +3609,14 @@ impl Host { if number.is_multiple_of(256) { all.retain(|_, l| l.0.strong_count() > 0); } - all.insert(number, (std::sync::Arc::downgrade(¬es), std::sync::Arc::downgrade(&pipelines))); + all.insert( + number, + ( + std::sync::Arc::downgrade(¬es), + std::sync::Arc::downgrade(&pipelines), + std::sync::Arc::downgrade(&indirects), + ), + ); } Ok(HostList { allocator, @@ -3544,6 +3627,8 @@ impl Host { twins: Mutex::default(), prelude, pipelines, + #[cfg(feature = "diagnostics")] + indirects, budget: OnceLock::new(), card_budget: OnceLock::new(), indirect_args: Mutex::default(), @@ -5280,7 +5365,12 @@ impl Host { #[cfg(feature = "diagnostics")] let by_name = list_number(&named).and_then(|n| { let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()); - all.get(&n).map(|(notes, pipelines)| (notes.upgrade(), pipelines.upgrade())) + all.get(&n).map(|(notes, pipelines, _)| (notes.upgrade(), pipelines.upgrade())) + }); + #[cfg(feature = "diagnostics")] + let indirects = run.map(|r| r.indirects.clone()).or_else(|| { + let n = list_number(&named)?; + LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()).get(&n)?.2.upgrade() }); #[cfg(not(feature = "diagnostics"))] #[allow(clippy::type_complexity)] @@ -5310,6 +5400,10 @@ impl Host { if done > 0 { text.push_str(&in_flight(history, &markers, done as usize)); } + #[cfg(feature = "diagnostics")] + if let Some(indirects) = indirects { + text.push_str(&indirects_around(history, done as usize, &indirects)); + } // (Without markers a list that stopped midway says what // it may have been at only by what it binds.) if (done == 0 || markers.is_empty()) @@ -5507,6 +5601,8 @@ impl HostList { self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); #[cfg(feature = "diagnostics")] + self.indirects.lock().unwrap_or_else(|e| e.into_inner()).clear(); + #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); { let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); @@ -5539,8 +5635,10 @@ impl HostList { resource: crate::object::This, wanted: u32, ) -> Option<(&'static ID3D12Resource, u32)> { - let texture = crate::resource::host_resource(resource)?; let copy = crate::resource::host_copy(resource)?; + // SAFETY: as in `crate::resource::host_resource`; the list's states + // hold the copy from here on. + let texture: &'static ID3D12Resource = unsafe { &*std::ptr::from_ref(©.texture) }; let wanted = legal_state(texture, wanted); let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); match states.entry(std::sync::Arc::as_ptr(©) as usize) { @@ -5913,6 +6011,15 @@ impl HostList { && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty() } + /// Notes an indirect execution, while device-removed data is kept + /// ([`indirects`]). + #[cfg(feature = "diagnostics")] + pub(crate) fn ran_indirect(&self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) { + if dred_on() || dred_light() { + self.indirects.lock().unwrap_or_else(|e| e.into_inner()).note(pipeline, name, kind, count, user); + } + } + /// Notes a pipeline the list binds. pub(crate) fn used_pipeline(&self, name: &str) { let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); @@ -6034,6 +6141,15 @@ impl HostList { Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data)) } + /// [`HostList::scratch`] and the buffer it lies in, for a descriptor + /// slot to hold: the slot outlives the list's use of it. + pub(crate) fn scratch_held(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> { + let (buffer, at, data) = self.scratch_at(len)?; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() } + at; + Some((buffer, gpu, data)) + } + /// [`HostList::scratch`]: the buffer, the offset in it and the CPU /// pointer. fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> { @@ -7419,6 +7535,20 @@ impl Meter { crate::descriptor::host::STALE[4].load(Ordering::Relaxed) ); } + if crate::resource::held_only() { + let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed)); + let [flipped, missed] = [0, 1].map(|i| crate::descriptor::host::FLIPPED[i].load(Ordering::Relaxed)); + tracing::info!( + "textures from the first level viewed (VICTORY_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \ + levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \ + {flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \ + out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free", + bytes >> 20, + whole >> 20, + crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed), + crate::pool::texture_room() >> 20 + ); + } { let mode = crate::watch::page_writes(); let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed)); @@ -8069,6 +8199,34 @@ fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String { /// barriers overlaps on the GPU), by kind, and what the markers just /// before them say (`HostList::note_op`: diagnostics builds with /// device-removed data on). +/// For a list that stopped at command `done`: what the indirect executions +/// there ran, from the one before it to the next barrier (four at most), and +/// what the heap slots their user data names hold now. +#[cfg(feature = "diagnostics")] +fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &indirects::Shared) -> String { + let indirect = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT; + let all = all.lock().unwrap_or_else(|e| e.into_inner()); + let mut text = String::new(); + let mut shown = 0; + for (at, op) in history.iter().enumerate().skip(done.saturating_sub(1)) { + if shown == 4 || (at > done && *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER) { + break; + } + if !indirect(op) { + continue; + } + shown += 1; + let Some((what, words)) = all.nth(indirects::before(history, at, indirect)) else { + continue; + }; + text.push_str(&format!("; command {at} ran {what}")); + for (word, slot, what) in crate::descriptor::host::describe_slots(words) { + text.push_str(&format!(", word {word} slot {slot}: {what}")); + } + } + text +} + fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String { let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER; let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1); @@ -8996,9 +9154,24 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000); } + #[test] + fn textures_are_kept_while_the_card_has_room() { + use super::vram_keep; + let gib = 1 << 30; + assert_eq!(vram_keep(100 * gib, 87 * gib).0, 600_000); + // Past it: the longest idle ones, enough to come down to 85 %. + let (ms, bytes) = vram_keep(100 * gib, 90 * gib); + assert_eq!((ms, bytes), (5_000, 5 * gib)); + assert_eq!(vram_keep(100 * gib, 120 * gib), (1_500, 35 * gib)); + assert_eq!(vram_keep(0, 7).0, 5_000); + } + #[test] fn ram_idle_ms_scales_with_pressure() { - use super::ram_idle_ms; + let ram_idle_ms = |avail| super::ram_idle_for(avail, false); + assert_eq!(super::ram_idle_for(Some(12 << 30), true), 300_000); + assert_eq!(super::ram_idle_for(Some((12 << 30) - 1), true), 10_000); + assert_eq!(super::ram_idle_for(None, true), 10_000); let gib = 1024 * 1024 * 1024; // Normal (>= 4 GiB) assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000); diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 881d1b2..84641cd 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -715,7 +715,7 @@ impl Host { To::Slot(heap, index) => { DONE[0].fetch_add(1, Ordering::Relaxed); // (A heap that is gone: nothing can read the slot.) - crate::descriptor::constant_slot(*heap, *index, gpu + op.at, op.len as u32); + crate::descriptor::constant_slot(*heap, *index, &own.between, gpu + op.at, op.len as u32); } To::Buffer(_) => { DONE[0].fetch_add(1, Ordering::Relaxed); diff --git a/crates/victory-gpu/src/host/indirects.rs b/crates/victory-gpu/src/host/indirects.rs new file mode 100644 index 0000000..cc34bff --- /dev/null +++ b/crates/victory-gpu/src/host/indirects.rs @@ -0,0 +1,127 @@ +//! What the indirect executions of a list ran, for the report of a removed +//! device: with `VICTORY_D3D12_DRED=light` the lists carry no markers, and +//! the two device losses of 2026-11-25 (sessions play-1125-0203 and n02) +//! said only that a list of 814 (954) commands stopped at an indirect +//! execution. The pipeline of each was found hours later by finding the +//! same run of commands in a capture. +//! +//! Per list, in the order recorded: the pipeline (by its host object, whose +//! name is kept once) and the first root constants (user data) it had. The +//! report finds an indirect execution by how many the breadcrumbs' history +//! has before it. Nothing is kept without device-removed data. +//! `VICTORY_D3D12_DRED=faults` and no data at all: nothing is noted. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +/// Words of user data kept of each execution. +pub(crate) const WORDS: usize = 16; + +/// One indirect execution. +#[derive(Clone, Copy)] +pub(crate) struct Ran { + pipeline: usize, + kind: u32, + count: u32, + words: [u32; WORDS], + used: u8, +} + +#[derive(Default)] +pub(crate) struct Indirects { + names: HashMap, + ran: Vec, +} + +/// A list's, shared with the report's table of lists. +pub(crate) type Shared = Arc>; + +impl Indirects { + /// An indirect execution of `kind` (the argument's type) of at most + /// `count` records with `pipeline` (a host object) and user data. + pub(crate) fn note(&mut self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) { + self.names.entry(pipeline).or_insert_with(|| name.to_owned()); + let used = user.len().min(WORDS); + let mut words = [0; WORDS]; + words[..used].copy_from_slice(&user[..used]); + self.ran.push(Ran { pipeline, kind, count, words, used: used as u8 }); + } + + pub(crate) fn clear(&mut self) { + self.ran.clear(); + if self.names.len() > 512 { + self.names.clear(); + } + } + + /// The `nth` execution (from 0): its text and its user data. + pub(crate) fn nth(&self, nth: usize) -> Option<(String, &[u32])> { + let ran = self.ran.get(nth)?; + let name = self.names.get(&ran.pipeline).map_or("a pipeline", String::as_str); + let words = &ran.words[..usize::from(ran.used)]; + Some(( + format!("{name} (indirect kind {} max {}, the list's indirect execution {nth}, user data {words:x?})", ran.kind, ran.count), + words, + )) + } +} + +/// How many indirect executions come before command `at` of a history of +/// breadcrumb operations (`is` tells them): which of a list's it is. +pub(crate) fn before(history: &[T], at: usize, is: impl Fn(&T) -> bool) -> usize { + history[..at.min(history.len())].iter().filter(|op| is(op)).count() +} + +/// The heap slots the user data may name, for the report to describe: the +/// words that are slots as they are, and the slots from where a word is a +/// table's byte offset (32 bytes a descriptor), `table` of them. +pub(crate) fn slots(words: &[u32], count: u32, table: u32) -> Vec<(usize, u32)> { + let mut out = Vec::new(); + for (i, &word) in words.iter().enumerate() { + if word > 0 && word < count && word % 32 != 0 { + out.push((i, word)); + } + if word % 32 == 0 && word / 32 > 16 && word / 32 < count { + out.extend((0..table).map(|k| (i, word / 32 + k)).filter(|s| s.1 < count)); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The execution a breadcrumb history stops at is found by the ones + /// before it, and its pipeline and user data are told. + #[test] + fn an_indirect_execution_is_found_by_its_place_in_the_history() { + let mut all = Indirects::default(); + all.note(1, "[compute a]", 2, 1, &[0x2549f40, 0x20, 0x11]); + all.note(2, "[compute b]", 2, 1, &[7; 20]); + all.note(1, "another name of the same is not taken", 10, 4, &[]); + // dispatch, indirect, barrier, indirect, indirect + let history = [6, 5, 15, 5, 5]; + let nth = before(&history, 3, |op| *op == 5); + assert_eq!(nth, 1); + let (text, words) = all.nth(nth).unwrap(); + assert!(text.starts_with("[compute b] (indirect kind 2 max 1"), "{text}"); + assert_eq!(words, [7; WORDS]); + let (text, words) = all.nth(2).unwrap(); + assert!(text.starts_with("[compute a] (indirect kind 10 max 4"), "{text}"); + assert!(words.is_empty()); + assert!(all.nth(3).is_none()); + assert_eq!(before(&history, 99, |op| *op == 5), 3); + all.clear(); + assert!(all.nth(0).is_none()); + } + + /// A table's byte offset names the slots from it on; a small word that + /// is no multiple of a descriptor's bytes names its own slot. + #[test] + fn user_data_names_slots() { + let words = [0, 0x2549f40, 0x20, 0x11, 0x26f1, 0xffff_ffff]; + let slots = slots(&words, 1_245_184, 2); + assert_eq!(slots, [(1, 0x2549f40 / 32), (1, 0x2549f40 / 32 + 1), (3, 0x11), (4, 0x26f1)]); + } +} diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 7d044ab..60b645c 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -600,7 +600,7 @@ pub(crate) mod tests { use super::*; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; - use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; use windows::Win32::Graphics::Dxgi::*; use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; use windows::core::Interface; @@ -984,6 +984,543 @@ void main() { } } + /// What raw loads through views that are not raw give past the view's + /// end (ignored: a measurement of the card). A buffer view of 4 KiB in a + /// buffer of 1 MiB whose every dword says where it lies: zeros past the + /// view, or the bytes there (whatever the card has in that place). + #[test] + #[ignore] + fn raw_loads_past_views() { + let Some(mut gpu) = WarpHarness::on(std::env::var_os("VICTORY_BENCH_WARP").is_some()) else { + return; + }; + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=4,b0), DescriptorTable(SRV(t0,numDescriptors=8)), UAV(u0), DescriptorTable(CBV(b1,numDescriptors=8))" +cbuffer C : register(b0) { uint which; uint first; uint step; uint at; } +ByteAddressBuffer v[8] : register(t0); +struct Block { uint4 d[4096]; }; +ConstantBuffer c[8] : register(b1); +RWByteAddressBuffer o : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) { + if (step == 0) { if (id.x == 0) o.Store(at, v[which].Load(first)); } + else if (step == 1) { if (id.x == 0) o.Store(at, c[which].d[first / 16][(first / 4) & 3]); } + else { o.Store(at + id.x * 4, v[which].Load(first + id.x * step)); } +} +"#; + let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile"); + let (buffer, data, _) = gpu.shared_buffer(1 << 20); + for i in 0..(1usize << 18) { + // SAFETY: inside the mapping. + unsafe { data.cast::().add(i).write(0xA000_0000 | i as u32) }; + } + let (_out, out_ptr, out_gpu) = gpu.shared_buffer(1 << 16); + // SAFETY: plain heap creation, views of a live buffer. + let heap: ID3D12DescriptorHeap = unsafe { + gpu.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 16, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + } + .unwrap(); + // SAFETY: as above. + let (cpu, table, step) = unsafe { + ( + heap.GetCPUDescriptorHandleForHeapStart().ptr, + heap.GetGPUDescriptorHandleForHeapStart(), + gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize, + ) + }; + let names = ["raw", "structured 24 at 24", "structured 16", "typed u32", "typed u16", "typed 4 x u32", "constant buffer", "null raw"]; + let view = |i: usize, format: i32, first: u64, count: u32, stride: u32, raw: bool, null: bool| { + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(format), + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: first, + NumElements: count, + StructureByteStride: stride, + Flags: if raw { D3D12_BUFFER_SRV_FLAG_RAW } else { D3D12_BUFFER_SRV_FLAG_NONE }, + }, + }, + }; + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu + i * step }; + // SAFETY: a slot of our heap, a live buffer. + unsafe { gpu.device.CreateShaderResourceView(if null { None } else { Some(&buffer) }, Some(&desc), at) }; + }; + for base in [0, 8] { + view(base, 39, 0, 1024, 0, true, false); + view(base + 1, 0, 1, 170, 24, false, false); + view(base + 2, 0, 0, 256, 16, false, false); + view(base + 3, 42, 0, 1024, 0, false, false); + view(base + 4, 57, 0, 2048, 0, false, false); + view(base + 5, 3, 0, 256, 0, false, false); + view(base + 7, 39, 0, 1, 0, true, true); + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { + // SAFETY: a live buffer. + BufferLocation: unsafe { buffer.GetGPUVirtualAddress() }, + SizeInBytes: 4096, + }; + // SAFETY: a slot of our heap. + unsafe { gpu.device.CreateConstantBufferView(Some(&desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu + (base + 6) * step }) }; + } + let table2 = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: table.ptr + 8 * step as u64 }; + let offsets = [0u32, 4092, 4096, 4104, 8192, 65536, 524_288, (1 << 20) - 4]; + for mode in ["one load (uniform)", "a load a thread", "constant buffer load"] { + println!("{mode}:"); + for (which, name) in names.iter().enumerate() { + // SAFETY: our open list, live buffers. + unsafe { + std::ptr::write_bytes(out_ptr, 0x77, 1 << 16); + gpu.list.SetDescriptorHeaps(&[Some(heap.clone())]); + gpu.list.SetComputeRootSignature(&pass.root); + gpu.list.SetPipelineState(&pass.pso); + gpu.list.SetComputeRootDescriptorTable(1, table); + gpu.list.SetComputeRootUnorderedAccessView(2, out_gpu); + gpu.list.SetComputeRootDescriptorTable(3, table2); + for (k, &offset) in offsets.iter().enumerate() { + let step = match mode.as_bytes()[0] { + b'o' => 0u32, + b'c' => 1, + _ => 4, + }; + // (A thread's loads end at the offset.) + let first = if step == 4 { offset.saturating_sub(63 * 4) } else { offset }; + let constants = [which as u32, first, step, k as u32 * 256]; + gpu.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + gpu.list.Dispatch(1, 1, 1); + } + } + gpu.submit_and_wait(); + let found: Vec = offsets + .iter() + .enumerate() + .map(|(k, &offset)| { + let thread = if mode.as_bytes()[0] == b'a' { (offset.min(63 * 4) / 4) as usize } else { 0 }; + // SAFETY: inside the mapping. + let word = unsafe { out_ptr.cast::().add(k * 64 + thread).read_volatile() }; + format!("{offset}: {word:#x}") + }) + .collect(); + println!(" {name:20} {}", found.join(" ")); + } + } + // SAFETY: a plain query. + println!("device: {:?}", unsafe { gpu.device.GetDeviceRemovedReason() }); + } + + /// Whether the card can read a texture's descriptor half written + /// (ignored: a measurement of the card, `VICTORY_BENCH_S` seconds a way, + /// 5). Two slots change between a texture of 64x64 and one of 2048x2048 + /// as fast as a thread can write them, while groups that each load the + /// descriptor anew ask its size and read its last texel: size and texel + /// of two textures are one descriptor half written. (Both lie in one heap + /// that is there as a whole: a read past the small one finds memory.) + #[test] + #[ignore] + fn descriptors_written_under_readers() { + let Some(mut gpu) = WarpHarness::on(std::env::var_os("VICTORY_BENCH_WARP").is_some()) else { + return; + }; + let seconds = std::env::var("VICTORY_BENCH_S").ok().and_then(|v| v.parse().ok()).unwrap_or(5u64); + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=1,b0), DescriptorTable(SRV(t0,numDescriptors=2,flags=DESCRIPTORS_VOLATILE)), UAV(u0)" +cbuffer C : register(b0) { uint odd; } +Texture2D t[2] : register(t0); +RWByteAddressBuffer o : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { + uint w, h, n; + uint which = (g.x + odd) & 1; + t[which].GetDimensions(0, w, h, n); + uint r = (uint)(t[which].Load(int3(w - 1, h - 1, 0)).x * 255.0 + 0.5); + // 0: small, 1: large, 2: no size of the two, 3: small with another texel, 4: large with another + uint kind = (w == 64 && h == 64) ? (r == 17 ? 0 : 3) : (w == 2048 && h == 2048) ? (r == 34 ? 1 : 4) : 2; + if (i == 0) { + uint was; + o.InterlockedAdd(kind * 4, 1, was); + if (kind > 1) { o.Store(32, w); o.Store(36, h); o.Store(40, r); } + } +} +"#; + let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile"); + let texture = |size: u64| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: size, + Height: size as u32, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(28), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + // SAFETY: plain creation; each texture in its own half of the heap. + let (heap, textures) = unsafe { + let mut heap: Option = None; + gpu.device + .CreateHeap( + &D3D12_HEAP_DESC { + SizeInBytes: 64 << 20, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }, + &mut heap, + ) + .unwrap(); + let heap = heap.unwrap(); + let textures = [(0u64, 64u64), (32 << 20, 2048)].map(|(at, size)| { + let mut made: Option = None; + gpu.device + .CreatePlacedResource(&heap, at, &texture(size), D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + .unwrap(); + made.unwrap() + }); + (heap, textures) + }; + // Fill them: 17 and 34 in every byte. + for (texture, (size, byte)) in textures.iter().zip([(64u32, 17u8), (2048, 34)]) { + let pitch = size * 4; + let (from, data, _) = gpu.shared_buffer(u64::from(pitch) * u64::from(size)); + // SAFETY: the mapping holds the bytes; an open list, live resources. + unsafe { + std::ptr::write_bytes(data, byte, (pitch * size) as usize); + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&from), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(28), + Width: size, + Height: size, + Depth: 1, + RowPitch: pitch, + }, + }, + }, + }; + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(texture), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + gpu.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + gpu.list.ResourceBarrier(&[crate::host::transition( + texture, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + gpu.submit_and_wait(); + } + let view_heap = |visible: bool| -> ID3D12DescriptorHeap { + // SAFETY: plain heap creation. + unsafe { + gpu.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 4, + Flags: if visible { D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE } else { D3D12_DESCRIPTOR_HEAP_FLAG_NONE }, + NodeMask: 0, + }) + } + .unwrap() + }; + let (shown, kept) = (view_heap(true), view_heap(false)); + // SAFETY: live heaps. + let (to, from, step) = unsafe { + ( + shown.GetCPUDescriptorHandleForHeapStart().ptr, + kept.GetCPUDescriptorHandleForHeapStart().ptr, + gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize, + ) + }; + let at = |base: usize, i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: base + i * step }; + for (i, texture) in textures.iter().enumerate() { + // SAFETY: slots of our heaps, live textures. + unsafe { + gpu.device.CreateShaderResourceView(texture, None, at(from, i)); + gpu.device.CreateShaderResourceView(texture, None, at(to, i)); + } + } + let bytes = |base: usize, i: usize| { + // SAFETY: a heap's handle; what it points at is read if it is memory. + let mut out = vec![0u8; step]; + crate::host::read_into((base + i * step) as *const u8, &mut out).then_some(out) + }; + println!("step {step}, the heaps' handles point at {:#x} and {:#x} (shown, kept)", to, from); + for i in 0..2 { + println!(" shown {i}: {:02x?}", bytes(to, i)); + println!(" kept {i}: {:02x?}", bytes(from, i)); + } + let same = bytes(to, 0).is_some() && bytes(to, 0) == bytes(from, 0) && bytes(to, 1) == bytes(from, 1); + println!("the shown heap's memory is the descriptors' own bytes: {same}"); + let images = [bytes(from, 0), bytes(from, 1)]; + // SAFETY: a live heap. + let table = unsafe { shown.GetGPUDescriptorHandleForHeapStart() }; + for way in ["view creation", "copies from a CPU heap", "one 32 byte store"] { + if way.starts_with("one") && !(same && step == 32) { + continue; + } + let (_out, out_ptr, out_gpu) = gpu.shared_buffer(1 << 12); + // SAFETY: the mapping. + unsafe { std::ptr::write_bytes(out_ptr, 0, 1 << 12) }; + let stop = std::sync::atomic::AtomicBool::new(false); + let writes = std::sync::atomic::AtomicU64::new(0); + std::thread::scope(|scope| { + let device = gpu.device.clone(); + let (stop, writes, textures, images) = (&stop, &writes, &textures, &images); + scope.spawn(move || { + let mut k = 0usize; + while !stop.load(std::sync::atomic::Ordering::Relaxed) { + for slot in 0..2 { + let which = (k + slot) & 1; + // SAFETY: slots of our heaps, live textures. + unsafe { + match way.as_bytes()[0] { + b'v' => device.CreateShaderResourceView(&textures[which], None, at(to, slot)), + b'c' => device.CopyDescriptorsSimple( + 1, + at(to, slot), + at(from, which), + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ), + _ => store32(to + slot * step, images[which].as_deref().unwrap()), + } + } + } + k += 1; + writes.fetch_add(2, std::sync::atomic::Ordering::Relaxed); + } + }); + let started = std::time::Instant::now(); + let mut odd = 0u32; + while started.elapsed().as_secs() < seconds { + // SAFETY: our open list, live objects. + unsafe { + gpu.list.SetDescriptorHeaps(&[Some(shown.clone())]); + gpu.list.SetComputeRootSignature(&pass.root); + gpu.list.SetPipelineState(&pass.pso); + gpu.list.SetComputeRootDescriptorTable(1, table); + gpu.list.SetComputeRootUnorderedAccessView(2, out_gpu); + for _ in 0..8 { + gpu.list.SetComputeRoot32BitConstants(0, 1, (&raw const odd).cast(), 0); + gpu.list.Dispatch(65_535, 1, 1); + odd += 1; + } + } + gpu.submit_and_wait(); + } + stop.store(true, std::sync::atomic::Ordering::Relaxed); + }); + // SAFETY: the mapping, the card is done. + let found: Vec = (0..11).map(|i| unsafe { out_ptr.cast::().add(i).read_volatile() }).collect(); + println!( + "{way}: {} writes; groups that saw the small texture {}, the large {}; no size of the two {}, the small size with another texel {}, the large size with another texel {}; the last such: {}x{} texel {}", + writes.load(std::sync::atomic::Ordering::Relaxed), + found[0], + found[1], + found[2], + found[3], + found[4], + found[8], + found[9], + found[10] + ); + // SAFETY: a plain query. + println!(" device: {:?}", unsafe { gpu.device.GetDeviceRemovedReason() }); + } + drop(heap); + } + + /// 32 bytes to `to` (32 byte aligned) in one store, then a fence. + /// + /// # Safety + /// `to` is 32 bytes of memory that may be written. + unsafe fn store32(to: usize, bytes: &[u8]) { + #[target_feature(enable = "avx")] + unsafe fn store(to: usize, bytes: *const u8) { + use std::arch::x86_64::*; + // SAFETY: the caller's. + unsafe { + _mm256_stream_si256(to as *mut __m256i, _mm256_loadu_si256(bytes.cast())); + _mm_sfence(); + } + } + assert!(std::is_x86_feature_detected!("avx") && bytes.len() == 32 && to.is_multiple_of(32)); + // SAFETY: asked for above; the caller's memory. + unsafe { store(to, bytes.as_ptr()) } + } + + /// What a texture read in another dimension than its view's gives + /// (ignored: a measurement of the card): a view of a small 2D texture + /// read as an array, a volume and a cube, and a small volume read as 2D, + /// far out. The texture lies at the start of a heap whose other megabytes + /// hold other bytes: a texel of those is a read past the texture. + #[test] + #[ignore] + fn textures_read_in_another_dimension() { + let Some(mut gpu) = WarpHarness::on(std::env::var_os("VICTORY_BENCH_WARP").is_some()) else { + return; + }; + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=2,b0), DescriptorTable(SRV(t0,numDescriptors=4,flags=DESCRIPTORS_VOLATILE)), UAV(u0), StaticSampler(s0,filter=FILTER_MIN_MAG_MIP_POINT,addressU=TEXTURE_ADDRESS_WRAP,addressV=TEXTURE_ADDRESS_WRAP,addressW=TEXTURE_ADDRESS_WRAP)" +cbuffer C : register(b0) { uint how; uint far; } +Texture2D flat_ : register(t0); +Texture2DArray layers : register(t1); +Texture3D volume : register(t2); +TextureCubeArray cube : register(t3); +SamplerState s : register(s0); +RWByteAddressBuffer o : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 t : SV_DispatchThreadID) { + uint2 at = uint2(t.x & 7, t.x >> 3); + float4 c = 0; + if (how == 0) c = flat_.Load(int3(at, 0)); + if (how == 1) c = layers.Load(int4(at, far, 0)); + if (how == 2) c = volume.Load(int4(at, far, 0)); + if (how == 3) c = layers.SampleLevel(s, float3((at + 0.5) / 64, far), 0); + if (how == 4) c = volume.SampleLevel(s, float3((at + 0.5) / 64, (far + 0.5) / 4096.0), 0); + if (how == 5) c = cube.SampleLevel(s, float4(1, (at + 0.5) / 64, far), 0); + if (how == 6) c = flat_.Load(int3(at, far)); + uint r = (uint)(c.x * 255.0 + 0.5), was; + // the texture's own bytes, zeros, anything else + o.InterlockedAdd(r == 17 ? 0 : r == 0 ? 4 : 8, 1, was); + if (r != 17 && r != 0) o.Store(12, r); +} +"#; + let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile"); + // SAFETY: plain creation, each thing in its own part of the heap. + let (_heap, small) = unsafe { + let mut heap: Option = None; + gpu.device + .CreateHeap( + &D3D12_HEAP_DESC { + SizeInBytes: 256 << 20, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }, + &mut heap, + ) + .unwrap(); + let heap = heap.unwrap(); + let place = |at: u64, size: u64| { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: size, + Height: size as u32, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(28), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let mut made: Option = None; + gpu.device + .CreatePlacedResource(&heap, at, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + .unwrap(); + made.unwrap() + }; + let small = place(0, 64); + // The rest: 34 in every byte. + let mut fill: Vec<(ID3D12Resource, u32, u8)> = vec![(small.clone(), 64, 17)]; + for k in 0..15u64 { + fill.push((place((1 + k) << 24, 2048), 2048, 34)); + } + for k in 1..16u64 { + fill.push((place(k << 20, 512), 512, 34)); + } + for (texture, size, byte) in fill { + let pitch = size * 4; + let (from, data, _) = gpu.shared_buffer(u64::from(pitch) * u64::from(size)); + std::ptr::write_bytes(data, byte, (pitch * size) as usize); + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&from), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(28), + Width: size, + Height: size, + Depth: 1, + RowPitch: pitch, + }, + }, + }, + }; + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&texture), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + gpu.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + gpu.list.ResourceBarrier(&[crate::host::transition( + &texture, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + gpu.submit_and_wait(); + } + (heap, small) + }; + // SAFETY: plain heap creation; slots of it, a live texture. + let heap: ID3D12DescriptorHeap = unsafe { + let heap: ID3D12DescriptorHeap = gpu + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 4, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .unwrap(); + let step = gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + for i in 0..4 { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: heap.GetCPUDescriptorHandleForHeapStart().ptr + i * step }; + // A 2D view of the small texture in every slot. + gpu.device.CreateShaderResourceView(&small, None, at); + } + heap + }; + for (how, name) in + ["2D", "array, loaded", "volume, loaded", "array, sampled", "volume, sampled", "cube array", "2D, a level it has not"] + .iter() + .enumerate() + { + for far in [0u32, 1, 7, 63, 1000, 4000] { + let (_out, out_ptr, out_gpu) = gpu.shared_buffer(1 << 12); + // SAFETY: the mapping; our open list, live objects. + unsafe { + std::ptr::write_bytes(out_ptr, 0, 1 << 12); + gpu.list.SetDescriptorHeaps(&[Some(heap.clone())]); + gpu.list.SetComputeRootSignature(&pass.root); + gpu.list.SetPipelineState(&pass.pso); + gpu.list.SetComputeRoot32BitConstants(0, 2, [how as u32, far].as_ptr().cast(), 0); + gpu.list.SetComputeRootDescriptorTable(1, heap.GetGPUDescriptorHandleForHeapStart()); + gpu.list.SetComputeRootUnorderedAccessView(2, out_gpu); + gpu.list.Dispatch(1, 1, 1); + } + gpu.submit_and_wait(); + // SAFETY: the mapping, the card is done. + let found: Vec = (0..4).map(|i| unsafe { out_ptr.cast::().add(i).read_volatile() }).collect(); + println!("{name} at {far}: its own texels {}, zeros {}, others {} (the last {})", found[0], found[1], found[2], found[3]); + } + } + // SAFETY: a plain query. + println!("device: {:?}", unsafe { gpu.device.GetDeviceRemovedReason() }); + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 532cf78..a0199ae 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -73,6 +73,12 @@ mod watch; #[cfg(windows)] pub use host::on_failure; + +/// What the frame is at (`copystat::phase`), for the sampling profiler. +#[cfg(all(windows, feature = "diagnostics"))] +pub fn frame_phase() -> u32 { + copystat::phase() +} #[cfg(windows)] pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 140b755..84aa3a3 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1023,6 +1023,25 @@ extern "system" fn copy_texture_region( // A depth texture shaders also write: what they wrote, first (the // source above too). list.twin_use(dst.resource, false, true); + // The first copy into a texture of the title's: what it does not + // write is what title memory holds, as on the console. (The host + // copy is cut from a block and held whatever lay there, and no + // upload is made once a copy wrote it: the atlas the title copies + // its baked decorations into, a 2048x2048 BC3 texture of which a + // bake writes 256x256 at most, was drawn over a character's face + // with other textures' bytes wherever nothing was baked, runs n01 and + // textures-1.) + static OVER: std::sync::OnceLock = std::sync::OnceLock::new(); + if *OVER.get_or_init(|| std::env::var_os("VICTORY_COPY_OVER_TITLE").is_none_or(|v| v != "0")) + && crate::texture::title_written(to) + && !crate::texture::host_wrote(dst.resource as usize) + { + crate::texture::upload(list, dst.resource, to); + // (Done before the title's copy writes over it.) + if list.used(dst.resource as usize) { + ensure_state(list, dst.resource, COPY_SOURCE); + } + } // A destination made level by level gets the level's memory ahead // of this list (`crate::tiles`): the title's bake copies each level // of its result into a block-compressed texture of that kind, and diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 138fb2b..02bb959 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -318,11 +318,15 @@ fn workers() -> bool { let spawned = std::thread::Builder::new() .name(format!("victory-pipelines-{i}")) .spawn(|| { - // Below the title's own threads (loading, recording). + // Below the title's own threads (loading, recording), + // and the streaming one, which is below normal itself + // (`VICTORY_PIPELINE_LOWEST=0`: level with it, as before). + let lowest = std::env::var_os("VICTORY_PIPELINE_LOWEST").is_none_or(|v| v != "0"); // SAFETY: a plain call on our own thread. unsafe { use windows::Win32::System::Threading::*; - let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + let priority = if lowest { THREAD_PRIORITY_LOWEST } else { THREAD_PRIORITY_BELOW_NORMAL }; + let _ = SetThreadPriority(GetCurrentThread(), priority); } loop { next().make(); diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 32b3bfb..e3da7ac 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -20,7 +20,7 @@ use std::collections::{BTreeMap, VecDeque}; use std::ffi::c_void; use std::sync::Mutex; -use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering}; use windows::Win32::Graphics::Direct3D12::*; use windows::core::{GUID, HRESULT, IUnknown, Interface}; @@ -29,6 +29,28 @@ use windows::core::{GUID, HRESULT, IUnknown, Interface}; const BLOCK: u64 = 64 << 20; /// Blocks with nothing in them that are kept. const SPARE: usize = 2; +/// The same while the card has room ([`room`]): 4 GiB of them. +const SPARE_KEPT: usize = 64; +/// The same of blocks of staging buffers, which are the PC's memory: run +/// crash-1 held 5.2 GB of them. +const STAGING_KEPT: usize = 8; +/// How many are kept now. +static SPARES: AtomicUsize = AtomicUsize::new(SPARE); + +/// Sets how many empty blocks stay, by the card's memory (budget and use): +/// [`SPARE_KEPT`] below 85 % ([`crate::host::keep_freed`]), else [`SPARE`]. +/// Asked once a second. +pub(crate) fn room(memory: Option<[u64; 4]>) { + SPARES.store(spares(memory, crate::host::keep_freed()), Ordering::Relaxed); +} + +fn spares(memory: Option<[u64; 4]>, keep: bool) -> usize { + match memory { + Some([budget, used, ..]) if keep && u128::from(used) * 100 < u128::from(budget) * 85 => SPARE_KEPT, + _ => SPARE, + } +} + /// Milliseconds until a piece given back is used again. (It was three /// frames, a tenth of a second while the title shows a loading screen at 30 /// a second, with up to 18 submissions in the air.) @@ -106,11 +128,14 @@ struct Pool { blocks: Vec>>, /// Pieces given back, and when each may be used again. resting: VecDeque<(u64, Piece)>, + /// The empty blocks it was last told to keep, and the most it keeps. + spare: usize, + most: usize, } impl Pool { - const fn new() -> Pool { - Pool { blocks: Vec::new(), resting: VecDeque::new() } + const fn new(most: usize) -> Pool { + Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most } } /// A piece of `len` bytes and the memory it lies in, and whether that @@ -168,12 +193,15 @@ impl Pool { any |= block.free.whole(BLOCK); } } - if any { + // (Without a piece given back too, once there is less room.) + let most = SPARES.load(Ordering::Relaxed).min(self.most); + if any || most < self.spare { + self.spare = most; let mut spare = 0; for block in &mut self.blocks { if block.as_ref().is_some_and(|b| b.free.whole(BLOCK)) { spare += 1; - if spare > SPARE { + if spare > most { *block = None; } } @@ -192,13 +220,22 @@ struct Upload(ID3D12Resource, *mut u8); // SAFETY: the mapping is written by the owners of its pieces, each its own. unsafe impl Send for Upload {} -static TEXTURES: Mutex> = Mutex::new(Pool::new()); -static STAGING: Mutex> = Mutex::new(Pool::new()); +static TEXTURES: Mutex> = Mutex::new(Pool::new(SPARE_KEPT)); +static STAGING: Mutex> = Mutex::new(Pool::new(STAGING_KEPT)); fn lock(m: &'static Mutex) -> std::sync::MutexGuard<'static, T> { m.lock().unwrap_or_else(|e| e.into_inner()) } +/// Bytes of the pieces textures hold now. +static HELD: AtomicU64 = AtomicU64::new(0); + +/// Bytes of the texture blocks no texture holds: the card's memory in use +/// by us that new textures take first. +pub(crate) fn texture_room() -> u64 { + (lock(&TEXTURES).blocks() as u64 * BLOCK).saturating_sub(HELD.load(Ordering::Relaxed)) +} + /// For the memory line: blocks of textures and of staging buffers, in MiB. #[cfg(feature = "diagnostics")] pub(crate) fn memory() -> [u64; 2] { @@ -282,6 +319,7 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { let left = (*this.cast::()).references.fetch_sub(1, Ordering::AcqRel) - 1; if left == 0 { let gone = Box::from_raw(this.cast::()); + HELD.fetch_sub(gone.piece.len, Ordering::Relaxed); lock(&TEXTURES).give(gone.piece, now()); } left @@ -351,6 +389,7 @@ pub(crate) unsafe fn texture( let result = unsafe { device.CreatePlacedResource(&heap, piece.start, &d, state, None, &mut made) }; match (result, made) { (Ok(()), Some(made)) => { + HELD.fetch_add(piece.len, Ordering::Relaxed); give_back_with(&made, piece); Some(made) } @@ -379,9 +418,17 @@ mod tests { assert!(r.whole(1024)); } + #[test] + fn empty_blocks_stay_while_the_card_has_room() { + assert_eq!(spares(Some([100, 84, 0, 0]), true), SPARE_KEPT); + assert_eq!(spares(Some([100, 85, 0, 0]), true), SPARE); + assert_eq!(spares(Some([100, 10, 0, 0]), false), SPARE); + assert_eq!(spares(None, true), SPARE); + } + #[test] fn pieces_never_overlap_and_rest_before_they_are_used_again() { - let mut pool: Pool = Pool::new(); + let mut pool: Pool = Pool::new(SPARE); let made = std::cell::Cell::new(0); let make = || { made.set(made.get() + 1); @@ -411,7 +458,7 @@ mod tests { assert_eq!(pool.blocks(), blocks.min(SPARE)); // Too big for a block, and a block that cannot be made. assert!(pool.take(BLOCK, 65536, 30, make).is_none()); - let mut none: Pool = Pool::new(); + let mut none: Pool = Pool::new(SPARE); assert!(none.take(65536, 65536, 0, || None).is_none()); } diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 884fbf0..826eb00 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -947,6 +947,15 @@ extern "system" fn copy_page_mappings( unsafe { std::slice::from_raw_parts(batches, count as usize) } }); let mut ok = true; + let many = crate::resource::many_page_mapper(); + let mut gathered: Vec<(u64, u64, u64)> = Vec::new(); + let mut map = |to: u64, from: u64, len: u64| match many { + Some(_) => { + gathered.push((to, from, len)); + true + } + None => map(to, from, len), + }; for b in batches.into_iter().flatten() { if b.ranges.is_null() { continue; @@ -968,6 +977,9 @@ extern "system" fn copy_page_mappings( at += len; } } + if let Some(many) = many { + ok &= many(&gathered); + } if !ok { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed")); diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index db3621e..b44ba86 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -98,6 +98,20 @@ pub(crate) struct ResourceDesc { flags: u32, } +#[cfg(windows)] +impl ResourceDesc { + /// The texture of this one's levels from `base` on. + fn from_level(&self, base: u32) -> ResourceDesc { + let mut d = *self; + if base > 0 { + d.width = (d.width >> base).max(1); + d.height = (d.height >> base).max(1); + d.mip_levels -= base as u16; + } + d + } +} + #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct AllocationInfo { @@ -947,6 +961,20 @@ pub fn use_page_mapper(mapper: PageMapper) { let _ = PAGE_MAPPER.set(mapper); } +/// As a [`PageMapper`], many at once: `(to, from, len)` each, in order. +pub type ManyPageMapper = fn(&[(u64, u64, u64)]) -> bool; + +static MANY_PAGE_MAPPER: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// The runtime's mapper of many pages at once. +pub fn use_many_page_mapper(mapper: ManyPageMapper) { + let _ = MANY_PAGE_MAPPER.set(mapper); +} + +pub(crate) fn many_page_mapper() -> Option { + MANY_PAGE_MAPPER.get().copied() +} + pub(crate) fn page_mapper() -> Option { PAGE_MAPPER.get().copied() } @@ -1137,8 +1165,27 @@ pub(crate) struct HostTexture { /// levels have been given. Its `bytes` are 0: what it holds of the card /// is counted there. pub(crate) tiled: Option, + /// The title's level its level 0 is ([`held_only`]): larger levels have + /// no place in it. + pub(crate) base: u32, + /// Tells host copies apart that one texture had one after the other. + pub(crate) serial: u64, + /// Made in place of one with fewer levels: the slots that show that one + /// are made again once this one was filled whole. + pub(crate) grown: std::sync::atomic::AtomicBool, + /// What the last submitted upload put in it. + pub(crate) holds: std::sync::Arc, } +/// What a host copy was filled with last: the first level of it and the +/// hash of the title memory it was read from. +#[cfg(windows)] +pub(crate) type Holds = std::sync::Mutex>; + +/// [`HostTexture::serial`] of the last one made. +#[cfg(windows)] +static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// What a title texture has on the host: its host copy and, for a depth /// texture shaders also write, the colour twin. #[cfg(windows)] @@ -1167,6 +1214,149 @@ struct Hosted { gone: std::sync::atomic::AtomicBool, /// A texture of [`PLACED_TEXTURES`]. placed: std::sync::atomic::AtomicBool, + /// The lowest level a view asked for since it had no host copy + /// ([`want_level`]; `u32::MAX`: none said). + wanted: std::sync::atomic::AtomicU32, + /// The next host copy takes the place of one with fewer levels. + grown: std::sync::atomic::AtomicBool, +} + +/// Whether a texture the title places in memory is read, kept and uploaded +/// from the first level its views show on (`VICTORY_HELD_LEVELS=0`: whole, +/// as before). Such a title describes every level of a texture and views it +/// from the first one it holds; the memory of the larger ones is the next +/// texture's, or nothing. Of two recorded world frames the levels some slot +/// shows are 1.2 and 1.6 GB of the 6.3 and 6.7 GB of such host copies, and +/// most of what was found "changed" and uploaded again was other textures' +/// bytes. +#[cfg(windows)] +pub(crate) fn held_only() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + std::env::var_os("VICTORY_HELD_LEVELS").is_none_or(|v| v != "0") && !crate::tiles::wanted() + }) +} + +/// The first level a placed texture's view shows: of views of one 2D +/// texture (the others show whole textures). After victory-amd 4436f8f1. +pub(crate) fn first_mip(view: &[u32]) -> u32 { + const TEXTURE_2D_VIEW: u32 = 4; + match *view { + [_, TEXTURE_2D_VIEW, _, _, first, ..] => first.min(15), + _ => 0, + } +} + +/// The level from which on a texture of layout `layout` is read for a view +/// that starts at `first`: the smallest levels share a block and are read +/// together; 0 where the larger ones lie between the smaller ones. +pub(crate) fn read_from(layout: &victory_formats::texture::Layout, first: u32) -> u32 { + if layout.slices != 1 || layout.mips.is_empty() { + return 0; + } + let first = first.min(layout.first_tail_mip).min(layout.mips.len() as u32 - 1); + if layout.bytes_from(first) < layout.size { first } else { 0 } +} + +/// The level a host copy begins at for views that start at `first`: one the +/// host can have as a texture's level 0 ([`read_from`]; block-compressed +/// formats in whole blocks). +#[cfg(windows)] +fn base_level(desc: &ResourceDesc, first: u32) -> u32 { + const TEXTURE_2D: u32 = 3; + if first == 0 + || !fills(desc) + || desc.dimension != TEXTURE_2D + || desc.depth_or_array_size != 1 + || desc.mip_levels <= 1 + || desc.sample_count > 1 + { + return 0; + } + let Some(t) = texture_layout(desc).filter(|t| t.planes.len() == 1) else { + return 0; + }; + let layout = &t.planes[0].layout; + if layout.desc.swizzle.xor() { + return 0; + } + let block = u64::from(layout.desc.block.max(1)); + let mut base = read_from(layout, first).min(u32::from(desc.mip_levels) - 1); + let whole = |side: u64| side != 0 && side.is_multiple_of(block); + while base > 0 && !(whole(desc.width >> base) && whole(u64::from(desc.height) >> base)) { + base -= 1; + } + base +} + +/// The bytes of title memory a placed texture with the resource description +/// `desc` is read from for a view that starts at level `first`; `None` as +/// [`placed_bytes`]. Remembered: asked for every slot that is looked at. +#[cfg(windows)] +pub(crate) fn placed_bytes_from(desc: &[u32; 14], first: u32) -> Option { + if first == 0 || !held_only() { + return placed_bytes(desc); + } + type Known = std::collections::HashMap<([u32; 14], u32), Option>; + thread_local! { + static KNOWN: std::cell::RefCell = std::cell::RefCell::default(); + } + KNOWN.with(|known| { + *known.borrow_mut().entry((*desc, first)).or_insert_with(|| { + let whole = placed_bytes(desc)?; + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::().read_unaligned() }; + let Some(t) = texture_layout(&d).filter(|t| t.planes.len() == 1) else { + return Some(whole); + }; + let layout = &t.planes[0].layout; + Some(layout.bytes_from(read_from(layout, first)).min(whole)) + }) + }) +} + +/// Host copies replaced by ones with more levels, for as long as a thread +/// that asked for one may still be about to record its use +/// ([`host_resource`]): when, and the copy. +#[cfg(windows)] +static REPLACED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Since the start: host copies made with a first level other than the +/// title's, and their bytes; host copies replaced by one with more levels; +/// bytes of title memory such copies' textures take whole. +#[cfg(windows)] +pub(crate) static HELD: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// A view of the placed texture `this` that starts at level `first` is made +/// or brought up to date: a host copy without that level is replaced by one +/// with it (made and filled at the next use; the slots that show the old +/// one go on showing it until that is done). +#[cfg(windows)] +pub(crate) fn want_level(this: This, first: u32) { + use std::sync::atomic::Ordering::Relaxed; + if this.is_null() || !held_only() { + return; + } + let r = resource(this); + if r.desc.dimension == BUFFER || !r.host.placed.load(Relaxed) { + return; + } + let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + let Some((host, _)) = made.as_ref() else { + r.host.wanted.fetch_min(first, Relaxed); + return; + }; + if host.base == 0 || host.base <= base_level(&r.desc, first) { + return; + } + r.host.wanted.store(first, Relaxed); + // Under the lock, as in `let_go_idle`. + crate::texture::unstage(this); + r.host.grown.store(true, Relaxed); + HELD[2].fetch_add(1, Relaxed); + if let Some(old) = made.take() { + REPLACED.lock().unwrap_or_else(|e| e.into_inner()).push((crate::host::moment(), old)); + } } /// Counts for the memory line: host copies of textures the title fills @@ -1254,6 +1444,30 @@ pub(crate) fn alias_of(this: This) -> Option { && o.desc.flags & DEPTH == 0 && target_format(o.desc.format) == o.desc.format && element(o.desc.format).is_some_and(|e| e.1 == 1 && Some(e) == element(r.desc.format)); + if !same && r.desc.sample_count <= 1 { + // What shaders wrote there is on the card in the other texture; this + // one is filled from title memory, which they never reached. Each + // kind of pair is said once. + static SAID: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); + let pair = [ + r.desc.width as u32, + r.desc.height, + r.desc.format, + o.desc.width as u32, + o.desc.height, + o.desc.format, + ]; + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + if said.len() < 64 && said.insert(pair) { + tracing::warn!( + view = ?this, + texture = ?other, + "a placed texture lies where a texture the host writes does, and is not like it (width, height, format of each): {pair:?}, levels {} and {}, layers {} and {}", + r.desc.mip_levels, o.desc.mip_levels, r.desc.depth_or_array_size, o.desc.depth_or_array_size + ); + } + } same.then_some(other) } @@ -1353,9 +1567,20 @@ fn hosted(this: This, make: bool) -> Option { texture = reserved; } } + // The levels views show ([`held_only`]), those of the slots shaders + // pick by index among them. + let mut base = 0; + if shape_fits && r.host.placed.load(Relaxed) && held_only() && alias_of(this).is_none() { + let wanted = r.host.wanted.load(Relaxed); + let viewed = crate::descriptor::host::first_viewed(r.data() as u64).unwrap_or(u32::MAX); + let first = wanted.min(viewed); + if first != u32::MAX { + base = base_level(&r.desc, first); + } + } let texture = match texture { Some(texture) => Some(texture), - None => host_texture(&r.desc, r.host.state, clear), + None => host_texture(&r.desc.from_level(base), r.host.state, clear), }; let Some(texture) = texture else { r.host.refused.store(true, Relaxed); @@ -1378,6 +1603,13 @@ fn hosted(this: This, make: bool) -> Option { Some(tiled) => HostTexture::new_tiled(texture, state, tiled), None => HostTexture::new(texture, state), }; + host.base = base; + host.grown.store(r.host.grown.swap(false, Relaxed), Relaxed); + if base > 0 { + HELD[0].fetch_add(1, Relaxed); + HELD[1].fetch_add(host.bytes, Relaxed); + HELD[3].fetch_add(footprint(&r.desc).map_or(0, |f| f.size), Relaxed); + } host.filled = fills(&r.desc); if host.filled { KINDS[0].fetch_add(1, Relaxed); @@ -1455,7 +1687,8 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { // world makes in its first frame ([`targets_room_kept`]) counts as // used. Some([budget, used, ..]) => { - used + crate::shadow::card_room_kept() + targets_room_kept() < budget / 100 * room_percent() + used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() + targets_room_kept() + < budget / 100 * room_percent() } None => filled < WITHOUT_BUDGET, } @@ -1777,12 +2010,52 @@ pub(crate) fn let_go_idle() { if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { return; } - let idle_ms = crate::host::vram_idle_ms(crate::host::host().and_then(|h| h.video_memory())); + // Copies replaced by ones with more levels, as any let go. + { + let mut replaced = REPLACED.lock().unwrap_or_else(|e| e.into_inner()); + let (gone, keep): (Vec<_>, Vec<_>) = + replaced.drain(..).partition(|(at, _)| crate::host::long_ago(*at, 1000, IDLE_FRAMES)); + *replaced = keep; + drop(replaced); + for (_, made) in gone { + crate::host::retire(made); + } + } + let memory = crate::host::host().and_then(|h| h.video_memory()); + static KEEP: std::sync::OnceLock = std::sync::OnceLock::new(); + let keep = *KEEP + .get_or_init(|| !matches!(std::env::var("VICTORY_TEXTURE_KEEP").as_deref(), Ok("0") | Ok("1"))); + let (idle_ms, most) = match memory { + Some([budget, used, ..]) if keep => { + let used = used.saturating_sub(crate::pool::texture_room()) + + crate::shadow::card_room_kept() + + targets_room_kept(); + crate::host::vram_keep(budget, used) + } + _ => (crate::host::vram_idle_ms(memory), u64::MAX), + }; // For the trail (`crate::host::trail`): how many went, their bytes, // and the first one. let (mut went, mut bytes, mut first) = (0u64, 0u64, None); let all = textures(); - for &at in all.iter() { + // With a limit, the longest idle first. + let mut by_age: Vec<(u64, usize)> = Vec::new(); + if most != u64::MAX { + for &at in all.iter() { + // SAFETY: as below. + let r = unsafe { &*(at as *const Resource) }; + let used = r.host.used.load(Relaxed); + if used != 0 && fills(&r.desc) && crate::host::long_ago(used, idle_ms, IDLE_FRAMES) { + by_age.push((used & 0xffff_ffff, at)); + } + } + by_age.sort_unstable(); + } + let every = all.iter().copied().filter(|_| most == u64::MAX); + for at in every.chain(by_age.iter().map(|&(_, at)| at)) { + if bytes >= most { + break; + } // SAFETY: a texture leaves the table before it is freed, under the // lock held here (`Drop for Resource`). let r = unsafe { &*(at as *const Resource) }; @@ -1800,6 +2073,7 @@ pub(crate) fn let_go_idle() { // Under the lock: the next use must not find the staging // state of the texture let go (it says "uploaded"). crate::texture::unstage(at as This); + r.host.wanted.store(u32::MAX, Relaxed); made.take() } else { None @@ -1973,6 +2247,10 @@ impl HostTexture { bytes, filled: false, tiled: None, + base: 0, + serial: SERIAL.fetch_add(1, Relaxed) + 1, + grown: Default::default(), + holds: Default::default(), } } @@ -1990,6 +2268,10 @@ impl HostTexture { bytes: 0, filled: false, tiled: Some(tiled), + base: 0, + serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1, + grown: Default::default(), + holds: Default::default(), } } } @@ -2054,6 +2336,15 @@ pub(crate) fn host_copy(this: This) -> Option> { hosted(this, true).map(|made| made.0) } +/// A title texture's host copy if it is made; not made here. +#[cfg(windows)] +pub(crate) fn made_copy(this: This) -> Option> { + if this.is_null() { + return None; + } + hosted(this, false).map(|made| made.0) +} + /// A host texture like the title's: same description, in GPU memory, /// without the console's layout and flags. #[cfg(windows)] @@ -2330,6 +2621,8 @@ fn hand_out_resource( refused: std::sync::atomic::AtomicBool::new(false), gone: std::sync::atomic::AtomicBool::new(false), placed: std::sync::atomic::AtomicBool::new(false), + wanted: std::sync::atomic::AtomicU32::new(u32::MAX), + grown: std::sync::atomic::AtomicBool::new(false), }, }); // The host copy waits for the texture's first use ([`Hosted`]). @@ -4140,4 +4433,37 @@ float4 lit() : SV_Target { return 1.0; } assert_eq!(texture_floor_bytes(Some(24 * GIB)), 2 * GIB); assert_eq!(texture_floor_bytes(Some(32 * GIB)), 2 * GIB); } + + /// A placed texture viewed from a later level has a host copy of that + /// and the smaller levels; a view from an earlier one gets another. + #[cfg(windows)] + #[test] + fn a_placed_texture_is_kept_from_the_level_viewed() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + if crate::host::host().is_none() || !held_only() { + return; + } + // 256x256 BC7, nine levels, 4 KiB blocks. + let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = placed_bytes(&desc).unwrap(); + let part = placed_bytes_from(&desc, 2).unwrap(); + assert!(part * 8 < whole, "{part} of {whole}"); + assert_eq!(placed_bytes_from(&desc, 0), Some(whole)); + // SAFETY: memory of our own that stays. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + let texture = texture_at(at as u64, &desc).unwrap(); + want_level(texture, 2); + let copy = host_copy(texture).unwrap(); + // SAFETY: a live texture. + let d = unsafe { copy.texture.GetDesc() }; + assert_eq!((copy.base, d.Width, d.Height, d.MipLevels), (2, 64, 64, 7)); + want_level(texture, 5); + assert_eq!(host_copy(texture).unwrap().serial, copy.serial); + want_level(texture, 0); + let more = host_copy(texture).unwrap(); + // SAFETY: as above. + let d = unsafe { more.texture.GetDesc() }; + assert_eq!((more.base, d.Width, d.MipLevels), (0, 256, 9)); + assert!(more.serial != copy.serial && more.grown.load(std::sync::atomic::Ordering::Relaxed)); + } } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index f3c2a8d..f970f70 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -46,8 +46,20 @@ pub(crate) struct Staging { footprints: Vec, rows: Vec, layout: victory_formats::texture::Layout, - /// Mips per array slice. + /// Mips per array slice, of the title's texture. mips: u32, + /// The first of them that is read and uploaded + /// (`crate::resource::held_only`), the one the host copy begins at, and + /// the bytes of title memory read. + first: u32, + level0: u32, + read: usize, + /// Which host copy it uploads into, and what that is told to hold. + serial: u64, + holds: Arc, + /// Title memory being remapped is waited for whatever [`no_wait`] says: + /// a list that bakes from the texture now recorded the upload. + waits: std::sync::atomic::AtomicBool, /// The staging buffer's bytes (counted in `STAGED` while it lives). bytes: u64, memory: *const u8, @@ -160,6 +172,8 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { const TARGET_OR_UNORDERED: u32 = 0x4 | 0x8; const COPY_DEST: u32 = 0x400; const COPY_SOURCE: u32 = 0x800; + // (All of its levels: the copy is level by level.) + crate::resource::want_level(placed, 0); let (Some(to), Some(from)) = ( crate::resource::host_resource(placed), crate::resource::host_resource(source), @@ -629,7 +643,21 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { /// its host copy, and the detiling that refreshes the staging buffer at /// submission if the memory changed. Leaves the texture in the copy /// destination state. -pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { +pub(crate) fn upload(list: &HostList, resource: This, _texture: &ID3D12Resource) { + upload_from(list, resource, 0); +} + +thread_local! { + /// The thread records uploads for a draw that bakes from them + /// ([`Staging::waits`]). + pub(crate) static BAKING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// [`upload`] of the levels from `first` on, the ones a view shows: of a +/// texture the title placed there may be no memory of the larger ones, and +/// what lies there is another texture's. (After victory-amd 4436f8f1.) +pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { + let first = if crate::resource::held_only() { first } else { 0 }; let host_written = HOST_WRITTEN .lock() .unwrap_or_else(|e| e.into_inner()) @@ -637,13 +665,28 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) .is_some_and(|set| set.contains(&(resource as usize))); // shortcut: a texture the host copied into keeps the host's contents // even if the title later writes its memory too. - if host_written || !list.first_use(resource as usize) { + if host_written { return; } - let Some(staging) = staging(resource, texture) else { + // Once a list for each first level; not again for one that the list's + // upload of larger ones held too. + if !list.first_use(1 << 63 | (resource as usize) << 4 | first as usize & 15) { + return; + } + if !list.first_use(resource as usize) && staged_from(resource) <= first { + return; + } + let Some(copy) = crate::resource::host_copy(resource) else { + return; + }; + let texture = ©.texture; + let Some(staging) = staging(resource, ©, first) else { return; }; use std::sync::atomic::Ordering::Relaxed; + if BAKING.get() { + staging.waits.store(true, Relaxed); + } staging.used.store(crate::host::moment(), Relaxed); // Levels on demand: a view of the texture now starts at another // level, or another texture now starts inside its span, with no byte @@ -684,7 +727,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexUploads, 1); if no_wait() && fill_unlocked() { - let there = mapped_bytes(staging.memory, staging.layout.size as usize); + let there = mapped_bytes(staging.memory, staging.read); staging.expected.store(there, Relaxed); } const COPY_DEST: u32 = 0x400; @@ -741,7 +784,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) pResource: unsafe { std::mem::transmute_copy(texture) }, Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: i as u32, + SubresourceIndex: staging.first - staging.level0 + i as u32, }, }; let from = D3D12_TEXTURE_COPY_LOCATION { @@ -768,6 +811,13 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) staging.dirty.store(false, Relaxed); }); } + // A host copy that took the place of one with fewer levels: the slots + // that show that one are made again once this upload has run. + if staging.first == staging.level0 && copy.grown.swap(false, Relaxed) { + let start = staging.memory as u64; + list.defer_host(move || crate::descriptor::host::levels_changed_after(start)); + } + let noted = staging.clone(); // Levels on demand (`crate::tiles`): after the check below, in the // order of this list's steps, and before the list is executed, the // levels the staging buffer holds as the title's are given the card's @@ -778,6 +828,8 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) let Some(on_demand) = on_demand else { // Once per submission however many of its lists sample the texture. list.defer_texture(staging); + // Then what the list's copy puts in the host copy is known. + list.defer_host(move || noted.note_held()); return; }; list.defer_texture(staging.clone()); @@ -971,7 +1023,21 @@ impl Staging { /// The title memory the texture is read from: address and bytes. pub(crate) fn memory(&self) -> (usize, usize) { - (self.memory as usize, self.layout.size as usize) + (self.memory as usize, self.read) + } + + /// The title's level and the array slice of the staging buffer's part + /// `i`. + fn part(&self, i: usize) -> (u32, u32) { + let mips = self.mips - self.first; + (self.first + i as u32 % mips, i as u32 / mips) + } + + /// The host copy holds what the staging buffer was filled from + /// ([`unchanged`]). + fn note_held(&self) { + let hash = self.last.lock().unwrap_or_else(|e| e.into_inner()).hash; + *self.holds.lock().unwrap_or_else(|e| e.into_inner()) = hash.map(|hash| (self.first, hash)); } /// Detiles the texture memory into the staging buffer if it changed @@ -994,7 +1060,7 @@ impl Staging { } fn refresh_timed(&self) -> usize { - let size = self.layout.size as usize; + let size = self.read; let start = self.memory as usize; let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); let last = &mut *last; @@ -1061,7 +1127,7 @@ impl Staging { // stays mapped (see `crate::watch::title_memory_reading`; without // it a page went between the asking and the read in runs 71 and // 74). - let _mapped = if no_wait() { + let _mapped = if no_wait() && !self.waits.load(std::sync::atomic::Ordering::Relaxed) { // Not waited for: while the runtime remaps title memory the // texture is read through the kernel instead, whole or not at // all (`no_wait`). @@ -1240,7 +1306,7 @@ impl Staging { ); } for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { - let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); + let (mip, slice) = self.part(i); let f = footprint.Footprint; let pitch = f.RowPitch as usize; // The last row of the last subresource is not padded to its pitch @@ -1330,6 +1396,59 @@ pub(crate) fn staged_state(resource: This) -> Option<(bool, bool)> { Some((staging.uploaded.load(Relaxed), staging.dirty.load(Relaxed))) } +/// The first level a title texture's staging buffer holds; `u32::MAX` +/// without one. +fn staged_from(resource: This) -> u32 { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref() + .and_then(|map| map.get(&(resource as usize))) + .map_or(u32::MAX, |s| s.first) +} + +/// Whether the levels from `first` on of `resource`'s host copy were filled +/// from the bytes title memory holds now: an upload would bring nothing new. +/// (Of 787 repeated uploads of a frame that streams 398 were equal in every +/// byte, and a texture uploaded again costs a staging buffer, a detiling and +/// a copy more than this look.) `VICTORY_TEXTURE_SAME=0`: not asked. +pub(crate) fn unchanged(resource: This, first: u32) -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SAME").is_none_or(|v| v != "0")) { + return false; + } + let Some(copy) = crate::resource::made_copy(resource) else { + return false; + }; + let Some((from, held)) = *copy.holds.lock().unwrap_or_else(|e| e.into_inner()) else { + return false; + }; + let Some((memory, desc)) = crate::resource::texture_memory(resource) else { + return false; + }; + let Some(layout) = crate::resource::texture_layout(&desc) else { + return false; + }; + let layout = &layout.planes[0].layout; + if from > crate::resource::read_from(layout, first).max(copy.base) { + return false; + } + let size = layout.bytes_from(from) as usize; + with_read(size, |read| { + if crate::host::read_there(memory, read) == 0 { + return false; + } + blake3::hash(read) == held + }) +} + +/// Where the levels from `first` on of a title texture are: address and +/// bytes. +pub(crate) fn title_span(resource: This, first: u32) -> Option<(u64, u64)> { + let (memory, desc) = crate::resource::texture_memory(resource)?; + let layout = crate::resource::texture_layout(&desc)?; + let layout = &layout.planes[0].layout; + Some((memory as u64, layout.bytes_from(crate::resource::read_from(layout, first)))) +} + pub(crate) fn is_staged(resource: This) -> bool { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize))) @@ -1342,8 +1461,7 @@ pub(crate) fn staged(resource: This) -> Option<(u64, bool)> { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref()?.get(&(resource as usize))?.clone() }; - let size = s.layout.size as usize; - Some((size as u64, committed(s.memory, size))) + Some((s.read as u64, committed(s.memory, s.read))) } /// Whether `[at, at + len)` is committed memory (streamed textures may be @@ -1509,13 +1627,17 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { } /// The staging state of a title texture, made on first use. -fn staging(resource: This, texture: &ID3D12Resource) -> Option> { +fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> Option> { + let texture = ©.texture; // Asked before the table is locked: the sweep lets go of a staging // buffer with its texture's host side locked, in that order. let on_demand = crate::resource::host_tiled(resource).is_some(); let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); let map = map.get_or_insert_with(HashMap::new); - if let Some(s) = map.get(&(resource as usize)) { + if let Some(s) = map.get(&(resource as usize)) + && s.first <= first.max(copy.base) + && s.serial == copy.serial + { return Some(s.clone()); } let (memory, desc) = crate::resource::texture_memory(resource)?; @@ -1534,10 +1656,14 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { let host = host()?; // SAFETY: a live resource. let d = unsafe { texture.GetDesc() }; + let level0 = copy.base; + let mips = level0 + u32::from(d.MipLevels); + let first = crate::resource::read_from(&layout, first).max(level0).min(mips - 1); + let read = layout.bytes_from(first) as usize; let count = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { - u32::from(d.MipLevels) + mips - first } else { - u32::from(d.MipLevels) * u32::from(d.DepthOrArraySize) + (mips - first) * u32::from(d.DepthOrArraySize) }; let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; let mut rows = vec![0u32; count as usize]; @@ -1546,7 +1672,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { unsafe { host.device.GetCopyableFootprints( &d, - 0, + first - level0, count, 0, Some(footprints.as_mut_ptr()), @@ -1581,7 +1707,13 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option> { footprints, rows, layout, - mips: u32::from(d.MipLevels), + mips, + first, + level0, + read, + serial: copy.serial, + holds: copy.holds.clone(), + waits: std::sync::atomic::AtomicBool::new(false), bytes: total, memory, last: Mutex::default(), @@ -1800,6 +1932,65 @@ mod allocation_costs { } } + /// What a texture met for the first time costs, by step, in + /// milliseconds a megabyte on one thread: for whether a store of + /// detiled copies on disk could be worth it (its key is a hash of the + /// title's bytes, so reading and hashing them stay; `VICTORY_BENCH_FILE` + /// is a big file to read past the system's cache). + #[test] + #[ignore = "a measurement, not a check"] + fn cold_texture_costs() { + let Some(host) = crate::host::host() else { return }; + let desc = [3u32, 0, 0, 0, 1024, 0, 1024, 0xb_0001, 98, 1, 0, 0x105, 0, 0]; + // SAFETY: 56 bytes in the description's layout. + let desc = unsafe { desc.as_ptr().cast::().read_unaligned() }; + let layout = crate::resource::texture_layout(&desc).unwrap().planes[0].layout.clone(); + let size = layout.size as usize; + let title: Vec = (0..size).map(|i| (i.wrapping_mul(2654435761) >> 13) as u8).collect(); + let (_buffer, up) = host.upload_buffer(2 * layout.size).unwrap(); + // SAFETY: the mapping. + let up = unsafe { std::slice::from_raw_parts_mut(up, 2 * size) }; + let mut read = vec![0u8; size]; + const N: u32 = 200; + let per_mb = |t: std::time::Duration| t.as_secs_f64() * 1e3 / (f64::from(N) * size as f64 / 1e6); + let timed = |what: &str, f: &mut dyn FnMut()| { + f(); + let started = std::time::Instant::now(); + (0..N).for_each(|_| f()); + println!("{what}: {:.3} ms/MB", per_mb(started.elapsed())); + }; + timed("read through the kernel or a safe copy", &mut || { + std::hint::black_box(crate::host::read_into(title.as_ptr(), &mut read)); + }); + timed("blake3", &mut || { + std::hint::black_box(blake3::hash(&title)); + }); + timed("detiled into upload memory", &mut || { + let mut at = 0; + for (mip, m) in layout.mips.iter().enumerate() { + let pitch = (m.width as usize * 16).next_multiple_of(256); + let len = pitch * m.height as usize; + layout.detile(&title, mip as u32, 0, &mut up[at..at + len], pitch, len).unwrap(); + at += len.next_multiple_of(512); + } + }); + timed("copied into upload memory", &mut || up[..size].copy_from_slice(&title)); + if let Some(file) = std::env::var_os("VICTORY_BENCH_FILE") { + use std::os::windows::fs::{FileExt, OpenOptionsExt}; + const NO_BUFFERING: u32 = 0x2000_0000; + let file = std::fs::OpenOptions::new().read(true).custom_flags(NO_BUFFERING).open(file).unwrap(); + let len = file.metadata().unwrap().len(); + let mut block = vec![0u8; size + 4096]; + let skew = block.as_ptr().align_offset(4096); + let n = size / 4096 * 4096; + let mut at = 0u64; + timed("read from the disk, one request at a time", &mut || { + at = (at + 7919 * 4096 * 64) % (len - n as u64) / 4096 * 4096; + file.seek_read(&mut block[skew..skew + n], at).unwrap(); + }); + } + } + #[test] #[ignore = "a measurement, not a check"] fn allocation_costs() { diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index f9b9a86..0ad25ff 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -13,6 +13,9 @@ mod host; mod image_watch; +#[cfg(all(windows, feature = "diagnostics"))] +pub use victory_gpu::frame_phase; + pub mod modules; mod registry; pub mod runtime; diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index 4b9bd25..a5de7c4 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -19,6 +19,7 @@ extern "system" fn create_device( ) -> HRESULT { victory_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree); victory_gpu::resource::use_page_mapper(super::xmem::map_alias); + victory_gpu::resource::use_many_page_mapper(super::xmem::map_aliases); #[cfg(windows)] victory_gpu::on_failure(host_gpu_failed); device::create(adapter, parameters, iid, out) diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index f74ddfc..5d0a5f2 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -151,6 +151,9 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out let file = unsafe { std::fs::File::from_raw_handle(handle) }; let files = Files::new(file, Io::chosen()); let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { files }); + if stream_log::on() { + stream_log::line(format_args!("F\t{:x}\t{kept}", file as usize)); + } WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept)); put(out, file) } @@ -170,9 +173,10 @@ extern "system" fn create_status_array( "dstorage: status array" ); let entries = (0..capacity).map(|_| AtomicI32::new(S_OK)).collect(); + let written = (0..capacity).map(|_| AtomicU64::new(0)).collect(); let array = Instance::create( Object::new("dstorage status array", &STATUS_VTABLE), - StatusArray { entries }, + StatusArray { entries, written }, ); put(out, array) } @@ -459,6 +463,9 @@ static FILE_VTABLE: Methods<8> = Methods([ struct StatusArray { entries: Box<[AtomicI32]>, + /// For the log: when each entry was written ([`stream_log::now`]); 0 + /// once the title has seen it. + written: Box<[AtomicU64]>, } type Array = *mut Instance; @@ -476,7 +483,15 @@ extern "system" fn status_result(this: Array, index: u32) -> HRESULT { /// The title polls this (entry 0, a `Sleep(1)` loop) and never /// reads the result itself. extern "system" fn is_complete(this: Array, index: u32) -> bool { - status_result(this, index) != E_PENDING + let done = status_result(this, index) != E_PENDING; + if done && stream_log::on() { + // SAFETY: as above. + let written = &unsafe { &*this }.state.written; + if let Some(at) = written.get(index as usize).map(|w| w.swap(0, Ordering::Relaxed)).filter(|&at| at != 0) { + stream_log::line(format_args!("P\t{:x}\t{at}\t{}", this as usize, stream_log::now())); + } + } + done } static STATUS_VTABLE: Methods<5> = Methods([ @@ -671,6 +686,83 @@ fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std:: ); } +/// The streaming log (`VICTORY_DSTORAGE_LOG=`): a line for every +/// request (`R`: queue, number, file, offset, source bytes, destination +/// bytes, options, when enqueued, submitted, started, done, result), every +/// status entry written (`S`: array, number, when enqueued, when written), +/// the title's first look at it after (`P`: array, when written, when +/// seen), every file opened (`F`), and each second what the title's mapping +/// calls cost (`M`, `xmem::map_costs`). Times are milliseconds since the +/// Unix epoch. +pub(crate) mod stream_log { + use super::*; + use std::io::Write; + + type Log = Mutex>; + + fn log() -> Option<&'static Log> { + static LOG: OnceLock> = OnceLock::new(); + LOG.get_or_init(|| { + let path = std::env::var_os("VICTORY_DSTORAGE_LOG")?; + let file = std::fs::File::create(&path).ok()?; + std::thread::spawn(|| { + loop { + std::thread::sleep(std::time::Duration::from_secs(1)); + if let Some(costs) = super::super::xmem::map_costs() { + line(format_args!("M\t{}\t{costs}", now())); + } + if let Some(log) = log() { + let _ = log.lock().unwrap_or_else(|e| e.into_inner()).flush(); + } + } + }); + Some(Mutex::new(std::io::BufWriter::with_capacity(1 << 20, file))) + }) + .as_ref() + } + + pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_DSTORAGE_LOG").is_some()) + } + + /// Milliseconds since the Unix epoch. + pub(super) fn now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |t| t.as_millis() as u64) + } + + pub(super) fn line(text: std::fmt::Arguments) { + if let Some(log) = log() { + let _ = writeln!(log.lock().unwrap_or_else(|e| e.into_inner()), "{text}"); + } + } + + pub(super) fn request(job: &Job, started: std::time::Instant, result: &Result<(), HRESULT>) { + if !on() { + return; + } + let now = now(); + let ago = |t: Option| now - t.map_or(0, |t| t.elapsed().as_millis() as u64); + let r = &job.request; + line(format_args!( + "R\t{}\t{}\t{:x}\t{}\t{}\t{}\t{:x}\t{}\t{}\t{}\t{now}\t{:x}", + job.lane, + job.seq, + r.source as usize, + r.offset, + r.source_size, + r.destination_size, + r.options, + ago(job.note.enqueued), + ago(job.note.submitted), + ago(Some(started)), + result.err().unwrap_or(0) + )); + } +} + /// A worker: runs the next read of the most deserving queue. fn work(scheduler: &'static Scheduler) { let mut lanes = scheduler.lock(); @@ -684,6 +776,7 @@ fn work(scheduler: &'static Scheduler) { let traced = Traced::start(&job); let result = execute(&job.request); walls_request(&job.request, &result, started); + stream_log::request(&job, started, &result); if let Some(traced) = traced { traced.end(&job, &result); } @@ -848,6 +941,11 @@ impl Lane { let first = std::mem::replace(&mut self.failures, later) .into_values() .next(); + if stream_log::on() { + let at = stream_log::now(); + stream_log::line(format_args!("S\t{:x}\t{seq}\t{}\t{at}", status.array as usize, status.enqueued)); + status.written().store(at, Ordering::Relaxed); + } status .entry() .store(first.unwrap_or(S_OK), Ordering::Release); @@ -965,6 +1063,7 @@ struct Note { impl Note { fn enqueued(request: &Request) -> Note { match trace() { + 0 if stream_log::on() => Note { enqueued: Some(std::time::Instant::now()), ..Note::default() }, 0 => Note::default(), _ => Note { enqueued: Some(std::time::Instant::now()), @@ -976,8 +1075,10 @@ impl Note { fn submitted(&mut self, request: &Request, early: bool) { self.early = early; - if trace() > 0 { + if trace() > 0 || stream_log::on() { self.submitted = Some(std::time::Instant::now()); + } + if trace() > 0 { self.at_submit = list_hash(request); } } @@ -1131,6 +1232,8 @@ impl Traced { struct Status { array: Array, index: u32, + /// For the log. + enqueued: u64, } impl Drop for Status { @@ -1144,6 +1247,11 @@ impl Status { // SAFETY: we hold a reference; the index was checked when enqueued. &unsafe { &*self.array }.state.entries[self.index as usize] } + + fn written(&self) -> &AtomicU64 { + // SAFETY: as above. + &unsafe { &*self.array }.state.written[self.index as usize] + } } extern "system" fn enqueue_request(this: QueueRef, request: *const Request) { @@ -1166,7 +1274,8 @@ extern "system" fn enqueue_status(this: QueueRef, array: Array, index: u32) { }; entry.store(E_PENDING, Ordering::Release); add_ref_instance(array); - queue(this, Command::Status(Status { array, index })); + let enqueued = stream_log::now(); + queue(this, Command::Status(Status { array, index, enqueued })); } /// Whether a queue submits itself once half of it is enqueued @@ -2162,7 +2271,7 @@ mod tests { let array = status_array(2).cast::>(); let status = |index| { add_ref_instance(array); - Command::Status(Status { array, index }) + Command::Status(Status { array, index, enqueued: 0 }) }; read(&mut l, 0, 0, 16); read(&mut l, 0, 0, 16); diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index 83ce323..5b8fb20 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -406,6 +406,34 @@ pub extern "C" fn __p___argv() -> *mut *mut *mut c_char { argv().list.get() } +/// The title's thread priorities, but for the lowest two, which become +/// "below normal". Six of the title's threads run at "idle", the streaming +/// pager's among them; on the console they have what the rest of the title +/// leaves of its cores. A PC's processors are also wanted by other programs +/// and by our own workers (sixteen when pipelines are made): with every +/// one of them busy such a thread ran once in four seconds or so, when the +/// host's scheduler took pity, and the loading that waits for it with it +/// (run stream-3: loads seen to be done 1.1 s late on average, 4.8 s at +/// worst). `VICTORY_TITLE_PRIORITIES=0`: as the title sets them. +fn title_priority(asked: i32) -> i32 { + const IDLE: i32 = -15; + const LOWEST: i32 = -2; + const BELOW_NORMAL: i32 = -1; + match asked { + IDLE..=LOWEST => BELOW_NORMAL, + other => other, + } +} + +/// [`title_priority`]. +pub extern "system" fn SetThreadPriority(thread: *mut c_void, priority: i32) -> i32 { + static AS_SET: std::sync::OnceLock = std::sync::OnceLock::new(); + let as_set = *AS_SET.get_or_init(|| std::env::var_os("VICTORY_TITLE_PRIORITIES").is_some_and(|v| v == "0")); + let priority = if as_set { priority } else { title_priority(priority) }; + // SAFETY: the title passes a thread handle. + unsafe { windows_sys::Win32::System::Threading::SetThreadPriority(thread, priority) } +} + pub(crate) fn module() -> HleModule { HleModule { name: "kernel", @@ -440,6 +468,7 @@ pub(crate) fn module() -> HleModule { hle_export!(_invalid_parameter_noinfo_noreturn), hle_export!(TerminateProcess), hle_export!(SetUnhandledExceptionFilter), + hle_export!(SetThreadPriority), ], } } @@ -654,6 +683,24 @@ mod host { mod tests { use super::*; + /// The title's idle and lowest threads run below normal; the others as + /// it sets them. + #[test] + fn no_title_thread_waits_for_idle_processors() { + let given: Vec = [-15, -2, -1, 0, 1, 2, 15].into_iter().map(title_priority).collect(); + assert_eq!(given, [-1, -1, -1, 0, 1, 2, 15]); + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadPriority}; + std::thread::spawn(|| { + // SAFETY: plain calls on this thread. + let thread = unsafe { GetCurrentThread() }; + assert_eq!(SetThreadPriority(thread, -15), 1); + // SAFETY: as above. + assert_eq!(unsafe { GetThreadPriority(thread) }, -1); + }) + .join() + .unwrap(); + } + #[test] fn title_images_report_their_original_path() { let base = 0x7000_0000_0000; diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 02ba024..4181edb 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -419,6 +419,33 @@ impl Section { } } +impl Section { + /// Commits the pages from `index` on that a view at `base` shows, unless + /// all of them are ([`lean`]): committed for one view is for all. + fn commit_shown(&self, index: usize, base: usize, len: usize) -> bool { + use std::sync::atomic::Ordering; + let pages = index..(index + len / PAGE).min(self.pages); + let bit = |p: usize| (&self.committed[p / 64], 1 << (p % 64)); + let done = || { + pages.clone().all(|p| { + let (word, bit) = bit(p); + word.load(Ordering::Acquire) & bit != 0 + }) + }; + if lean() && done() { + return true; + } + if !counted(Call::Commit, || commit(base, len)) { + return false; + } + for p in pages { + let (word, bit) = bit(p); + word.fetch_or(bit, Ordering::AcqRel); + } + true + } +} + // SAFETY: a section handle may be used from any thread. unsafe impl Send for Section {} // SAFETY: as above. @@ -455,6 +482,23 @@ struct Slice { struct Physical { /// Mapped views by address: their length and what they show. views: BTreeMap, + /// Placeholders that are some view's own, left by its unmapping: address + /// and length. The title may have joined one with others since. + holes: HashMap, +} + +impl Physical { + /// What the page at `at` shows. + fn slice_at(&self, at: usize) -> Option { + self.views + .range(..=at) + .next_back() + .filter(|(base, (size, _))| at < *base + size) + .map(|(base, (_, s))| Slice { + index: s.index + (at - base) / PAGE, + section: s.section.clone(), + }) + } } /// The title's pages by number. @@ -893,6 +937,121 @@ pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) { } } +/// What the title's mapping calls cost since the last asking, for the +/// streaming log, counted only while that log is on: calls, pages, +/// milliseconds in all, the longest one's and waiting for the lock; the same +/// of the GPU's page-mapping copies ([`map_alias`]; calls and milliseconds); +/// and by system call (unmap, split, map, commit) how many and their +/// milliseconds. +static MAPPING: [std::sync::atomic::AtomicU64; 15] = [const { std::sync::atomic::AtomicU64::new(0) }; 15]; + +pub(crate) fn map_costs() -> Option { + let n: [u64; 15] = std::array::from_fn(|i| MAPPING[i].swap(0, Ordering::Relaxed)); + let time = |i: usize| matches!(i, 2 | 3 | 4 | 6 | 8 | 10 | 12 | 14); + (n[0] + n[5] > 0).then(|| { + let all: Vec = n + .iter() + .enumerate() + .map(|(i, &n)| if time(i) { n / 1_000_000 } else { n }) + .map(|n| n.to_string()) + .collect(); + all.join("\t") + }) +} + +/// The system calls that change a mapping, as [`MAPPING`] counts them. +#[derive(Clone, Copy)] +enum Call { + Unmap = 7, + Split = 9, + Map = 11, + Commit = 13, +} + +/// Runs `f`, a system call, and counts it while the streaming log is on. +fn counted(call: Call, f: impl FnOnce() -> T) -> T { + if !super::dstorage::stream_log::on() { + return f(); + } + let started = std::time::Instant::now(); + let done = f(); + MAPPING[call as usize].fetch_add(1, Ordering::Relaxed); + MAPPING[call as usize + 1].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + done +} + +/// Counts a mapping call when dropped. +struct Costed { + started: std::time::Instant, + /// `None`: a copy of mappings. + pages: Option, + waited: u64, +} + +impl Costed { + fn begin(pages: Option) -> Option { + super::dstorage::stream_log::on().then(|| Costed { started: std::time::Instant::now(), pages, waited: 0 }) + } +} + +impl Drop for Costed { + fn drop(&mut self) { + let ns = self.started.elapsed().as_nanos() as u64; + let Some(pages) = self.pages else { + MAPPING[5].fetch_add(1, Ordering::Relaxed); + MAPPING[6].fetch_add(ns, Ordering::Relaxed); + return; + }; + for (i, n) in [1, pages as u64, ns].into_iter().enumerate() { + MAPPING[i].fetch_add(n, Ordering::Relaxed); + } + MAPPING[3].fetch_max(ns, Ordering::Relaxed); + MAPPING[4].fetch_add(self.waited, Ordering::Relaxed); + } +} + +/// Whether a mapping change asks the host only for what it needs: no split +/// of a placeholder that is already the view's own, no commit of section +/// pages that are committed (`VICTORY_MAP_LEAN=0`: both every time, as +/// before). +/// +/// All of the title's streaming goes through one thread, which maps the +/// pages of a batch and then submits it. Each call waits for the process's +/// one address-space lock, behind the guards' and the driver's: 200 to 400 +/// us a page in the world against 10 in a menu, 2 to 4 s of every 5 s of +/// that thread (runs stream-1 and -2; all six stacks taken of it in the +/// opening were in these calls), so that models came as fast as their pages +/// could be mapped. A page took up to four calls (unmap, split, map, +/// commit), twice: the title maps a page into its pool and then has the GPU +/// map it into its tiled heap. +fn lean() -> bool { + static ON: LazyLock = LazyLock::new(|| std::env::var_os("VICTORY_MAP_LEAN").is_none_or(|v| v != "0")); + *ON +} + +/// The title's streaming thread runs below normal priority, as do sixteen +/// workers of ours when pipelines are made; on the console nothing else +/// wants its core. Called where that thread maps and submits: lifts a +/// thread that is below normal to above it (`VICTORY_STREAM_PRIORITY=0`: +/// left as the title set it). +pub(crate) fn lift_thread() { + use windows_sys::Win32::System::Threading::{ + GetCurrentThread, GetThreadPriority, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL, + }; + static ON: LazyLock = + LazyLock::new(|| std::env::var_os("VICTORY_STREAM_PRIORITY").is_none_or(|v| v != "0")); + if !*ON { + return; + } + // SAFETY: plain calls on this thread. + unsafe { + let thread = GetCurrentThread(); + if matches!(GetThreadPriority(thread), -2..0) { + SetThreadPriority(thread, THREAD_PRIORITY_ABOVE_NORMAL); + } + } +} + /// Maps `n` pages at `address`, in place of what is mapped there; null /// `pages` unmaps. Returns `address`, or null if a page or the host fails. pub extern "system" fn XMemMapPhysicalPages( @@ -905,7 +1064,11 @@ pub extern "system" fn XMemMapPhysicalPages( // the mapping call that holds them. // SAFETY: the title passes `n` page numbers, or null. let pages = (!pages.is_null()).then(|| unsafe { std::slice::from_raw_parts(pages, n) }.to_vec()); + let mut costed = Costed::begin(Some(n)); let mut physical = physical(); + if let Some(costed) = &mut costed { + costed.waited = costed.started.elapsed().as_nanos() as u64; + } // Until the pages are mapped again: `unmap` takes whole views away and // maps what stays of them again, and a mapped view is a reservation // until it is committed. A read of title memory in place must not fall @@ -953,6 +1116,17 @@ pub extern "system" fn XMemMapPhysicalPagesScatter( if addresses.is_null() { return 0; } + lift_thread(); + if side_by_side() > 1 && n > 1 { + // Read before any lock is taken, as in `XMemMapPhysicalPages`. + let wanted: Vec<(usize, usize)> = (0..n) + // SAFETY: the title passes `n` addresses and, unless null, `n` pages. + .map(|i| unsafe { (*addresses.add(i) as usize, if pages.is_null() { 0 } else { *pages.add(i) }) }) + .collect(); + if wanted.iter().all(|w| w.0 % PAGE == 0) { + return scatter(&wanted).into(); + } + } for i in 0..n { // SAFETY: the title passes `n` addresses and, unless null, `n` pages. let (address, page) = unsafe { @@ -979,6 +1153,7 @@ pub extern "system" fn XMemMapPhysicalPagesScatter( /// heap. Page by page; false if a source page is not mapped physical memory. pub fn map_alias(to: u64, from: u64, len: u64) -> bool { let (to, from, len) = (to as usize, from as usize, len as usize); + let _costed = Costed::begin(None); let mut physical = physical(); // As in `XMemMapPhysicalPages`: no read in place meets the gap. let _changing = victory_gpu::title_memory_remapping(); @@ -988,16 +1163,7 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool { break; } let at = from + k; - let Some(slice) = physical - .views - .range(..=at) - .next_back() - .filter(|(base, (size, _))| at < *base + size) - .map(|(base, (_, s))| Slice { - index: s.index + (at - base) / PAGE, - section: s.section.clone(), - }) - else { + let Some(slice) = physical.slice_at(at) else { return false; }; if !map(&mut physical, to + k, PAGE, slice) { @@ -1007,42 +1173,323 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool { true } +/// [`map_alias`] of many ranges, in order. +pub fn map_aliases(ranges: &[(u64, u64, u64)]) -> bool { + let _costed = Costed::begin(None); + lift_thread(); + if side_by_side() <= 1 { + return ranges.iter().all(|&(to, from, len)| map_alias(to, from, len)); + } + // By the page: the address, and the one whose page it is to show. + let pages: Vec<(usize, Option)> = ranges + .iter() + .flat_map(|&(to, from, len)| { + (0..len as usize).step_by(PAGE).map(move |k| (to as usize + k, (from != 0).then_some(from as usize + k))) + }) + .collect(); + if pages.iter().any(|p| p.0 % PAGE != 0 || p.1.is_some_and(|from| from % PAGE != 0)) { + return ranges.iter().all(|&(to, from, len)| map_alias(to, from, len)); + } + let mut ok = true; + let mut at = 0; + while at < pages.len() { + let mut physical = physical(); + let mut ops: Vec = Vec::new(); + let mut touched = std::collections::HashSet::new(); + for &(to, from) in &pages[at..] { + // A page the group changes already, or one it would be mapped + // from: after it. + if ops.len() == GROUP || touched.contains(&to) || from.is_some_and(|from| touched.contains(&from)) { + break; + } + let slice = from.map(|from| physical.slice_at(from)); + ok &= !matches!(slice, Some(None)); + touched.insert(to); + ops.push(Op::new(to, slice.flatten())); + at += 1; + } + let _changing = victory_gpu::title_memory_remapping(); + ok &= change(&mut physical, ops); + } + ok +} + +/// Maps (page number not 0) or unmaps each address; false if a page is not +/// the title's or the host refuses one. +fn scatter(wanted: &[(usize, usize)]) -> bool { + let mut ok = true; + let mut at = 0; + while at < wanted.len() { + let mut costed = Costed::begin(None); + let mut ops: Vec = Vec::new(); + let mut physical = physical(); + if let Some(costed) = &mut costed { + costed.waited = costed.started.elapsed().as_nanos() as u64; + } + { + let table = page_table(); + let mut touched = std::collections::HashSet::new(); + for &(to, page) in &wanted[at..] { + if ops.len() == GROUP || !touched.insert(to) { + break; + } + let slice = table.pages.get(&page).cloned(); + if page != 0 && slice.is_none() { + tracing::warn!(page, "XMemMapPhysicalPagesScatter: unknown page"); + ok = false; + } + ops.push(Op::new(to, slice)); + at += 1; + } + } + if let Some(costed) = &mut costed { + costed.pages = Some(ops.len()); + } + let _changing = victory_gpu::title_memory_remapping(); + ok &= change(&mut physical, ops); + } + ok +} + +/// Pages changed under the locks at once. +const GROUP: usize = 64; + +/// How many threads map a group of pages side by side (`VICTORY_MAP_THREADS`; +/// 1: the caller alone, a page after the other, as before). +/// +/// Mapping and unmapping a view wait for a lock that every protection change +/// of a view takes too, and our guards make 100,000 of those a second, from +/// many threads, in the world: 0.2 to 4 ms a page. One thread stands in that +/// queue once at a time. In a bench (60,000 views, five threads changing +/// protections) one thread mapped 1,500 pages a second, eight 30,000. +fn side_by_side() -> usize { + static THREADS: LazyLock = LazyLock::new(|| { + std::env::var("VICTORY_MAP_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8).clamp(1, 32) + }); + *THREADS +} + +/// A page of address space to unmap and, with a slice, map anew. +struct Op { + at: usize, + slice: Option, + /// A view of this page alone is there, to be unmapped. + had: bool, + /// The placeholder is the page's own (or will be, after the unmapping). + own: bool, +} + +impl Op { + fn new(at: usize, slice: Option) -> Op { + Op { at, slice, had: false, own: false } + } + + /// The system calls; whether the host did as asked. + fn run(&self) -> bool { + if self.had { + // SAFETY: a view we mapped; it becomes a placeholder again. + let gone = counted(Call::Unmap, || unsafe { + UnmapViewOfFile2( + GetCurrentProcess(), + MEMORY_MAPPED_VIEW_ADDRESS { Value: self.at as *mut c_void }, + MEM_PRESERVE_PLACEHOLDER, + ) + }); + if gone == 0 { + return false; + } + } + let Some(slice) = &self.slice else { + return true; + }; + show(self.at, PAGE, slice, self.own) + } +} + +/// Does `ops`, each of another page, side by side: first what is noted of +/// the pages goes, then the system calls, then what is there now is noted. +/// With [`PHYSICAL`] and the change of mapping (`title_memory_remapping`) +/// held. +fn change(physical: &mut Physical, mut ops: Vec) -> bool { + for op in &mut ops { + let there = physical + .views + .range(..=op.at) + .next_back() + .filter(|(base, view)| op.at < **base + view.0) + .map(|(base, view)| (*base, view.0)); + match there { + Some((base, PAGE)) if base == op.at => { + if let Some((size, slice)) = physical.views.remove(&op.at) { + shown_mut().forget(op.at, size, &slice); + } + victory_gpu::title_memory_unmapping(op.at, PAGE); + physical.holes.remove(&op.at); + (op.had, op.own) = (true, lean()); + } + // Part of a larger view. + Some(_) => { + unmap(physical, op.at, PAGE); + } + None => {} + } + if op.had { + continue; + } + op.own = physical.holes.remove(&op.at) == Some(PAGE) && lean(); + if op.slice.is_some() && !op.own { + // Cut out of a larger placeholder here, not side by side: a + // thread that maps a piece while others cut the same one can + // fail. + split(op.at, PAGE); + op.own = true; + } + } + let done = pool::all(ops); + let mut ok = true; + for (op, done) in done { + match op.slice { + Some(slice) if done => { + // As in `map`. + shown_mut().note(op.at, PAGE, &slice); + victory_gpu::title_memory_remapped(op.at, PAGE); + victory_gpu::title_memory_view(op.at, PAGE, slice.section.handle as usize, (slice.index * PAGE) as u64); + physical.views.insert(op.at, (PAGE, slice)); + } + None if op.had && done => { + physical.holes.insert(op.at, PAGE); + } + _ => ok &= done, + } + } + ok +} + +/// The threads that do the system calls of [`change`]. +mod pool { + use std::collections::VecDeque; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::{Arc, Condvar, Mutex, OnceLock}; + + use super::{Op, side_by_side}; + + struct Batch { + ops: Vec<(Op, AtomicBool)>, + next: AtomicUsize, + /// Ops not done yet. + left: AtomicUsize, + over: (Mutex, Condvar), + } + + impl Batch { + /// Does ops until none is left to begin. + fn work(&self) { + loop { + let i = self.next.fetch_add(1, Ordering::Relaxed); + let Some((op, done)) = self.ops.get(i) else { + return; + }; + done.store(op.run(), Ordering::Release); + if self.left.fetch_sub(1, Ordering::AcqRel) == 1 { + *self.over.0.lock().unwrap_or_else(|e| e.into_inner()) = true; + self.over.1.notify_all(); + } + } + } + } + + struct Pool { + batches: Mutex>>, + more: Condvar, + } + + fn pool() -> &'static Pool { + static POOL: OnceLock = OnceLock::new(); + static STARTED: std::sync::Once = std::sync::Once::new(); + let pool = POOL.get_or_init(|| Pool { batches: Mutex::default(), more: Condvar::new() }); + STARTED.call_once(|| { + let started = (1..side_by_side()) + .filter(|i| std::thread::Builder::new().name(format!("mapping {i}")).spawn(|| serve(pool)).is_ok()) + .count(); + tracing::info!(started, "threads that map pages side by side (VICTORY_MAP_THREADS=1: none)"); + }); + pool + } + + fn serve(pool: &Pool) { + use windows_sys::Win32::System::Threading::{ + GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL, + }; + // SAFETY: a plain call on our own thread. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) }; + let mut batches = pool.batches.lock().unwrap_or_else(|e| e.into_inner()); + loop { + let Some(batch) = batches.front().cloned() else { + batches = pool.more.wait(batches).unwrap_or_else(|e| e.into_inner()); + continue; + }; + if batch.next.load(Ordering::Relaxed) >= batch.ops.len() { + // All begun: nobody needs to see it any more. + if batches.front().is_some_and(|b| Arc::ptr_eq(b, &batch)) { + batches.pop_front(); + } + continue; + } + drop(batches); + batch.work(); + batches = pool.batches.lock().unwrap_or_else(|e| e.into_inner()); + } + } + + /// Runs `ops`; each with whether the host did it. + pub(super) fn all(ops: Vec) -> Vec<(Op, bool)> { + // Waking the others takes longer than a few quick calls. + if ops.len() < 3 { + return ops + .into_iter() + .map(|op| { + let done = op.run(); + (op, done) + }) + .collect(); + } + let n = ops.len(); + let batch = Arc::new(Batch { + ops: ops.into_iter().map(|op| (op, AtomicBool::new(false))).collect(), + next: AtomicUsize::new(0), + left: AtomicUsize::new(n), + over: Default::default(), + }); + let pool = pool(); + pool.batches.lock().unwrap_or_else(|e| e.into_inner()).push_back(batch.clone()); + if n > side_by_side() { + pool.more.notify_all(); + } else { + (1..n).for_each(|_| pool.more.notify_one()); + } + batch.work(); + let mut over = batch.over.0.lock().unwrap_or_else(|e| e.into_inner()); + while !*over { + over = batch.over.1.wait(over).unwrap_or_else(|e| e.into_inner()); + } + drop(over); + // No worker changes it any more (one may still hold it for a moment). + batch + .ops + .iter() + .map(|(op, done)| { + let op = Op { at: op.at, slice: op.slice.clone(), had: op.had, own: op.own }; + (op, done.load(Ordering::Acquire)) + }) + .collect() + } +} + /// Maps `slice` and the slices after it over `[base, base + len)`, which /// must lie in one placeholder. fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { - // SAFETY: splits the placeholder around the range (failing harmlessly - // when the range is the whole placeholder), then maps the section - // there; both act only on placeholders. - let view = unsafe { - VirtualFree( - base as *mut c_void, - len, - MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, - ); - MapViewOfFile3( - slice.section.handle, - GetCurrentProcess(), - base as *const c_void, - (slice.index * PAGE) as u64, - len, - MEM_REPLACE_PLACEHOLDER, - PAGE_READWRITE, - std::ptr::null_mut(), - 0, - ) - }; - if view.Value as usize != base { - tracing::warn!( - address = format_args!("{base:#x}"), - len, - error = %std::io::Error::last_os_error(), - "mapping physical pages failed (not a placeholder?)" - ); - return false; - } - if !commit(base, len) { - // SAFETY: the view just mapped, back to a placeholder. - unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }; + let own = physical.holes.remove(&base) == Some(len) && lean(); + if !show(base, len, &slice, own) { return false; } // Noted before the GPU side is told: bytes DirectStorage put in earlier, @@ -1057,6 +1504,60 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { true } +/// Cuts `[base, base + len)` out of the placeholder it is in (which fails +/// harmlessly when the range is the whole placeholder). +fn split(base: usize, len: usize) { + // SAFETY: acts only on a placeholder. + counted(Call::Split, || unsafe { + VirtualFree( + base as *mut c_void, + len, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ) + }); +} + +/// The system calls of [`map`]; `own`: the placeholder at `base` is `len` +/// long already. +fn show(base: usize, len: usize, slice: &Slice, own: bool) -> bool { + let map_view = || { + // SAFETY: maps the section over a placeholder; acts only on one. + counted(Call::Map, || unsafe { + MapViewOfFile3( + slice.section.handle, + GetCurrentProcess(), + base as *const c_void, + (slice.index * PAGE) as u64, + len, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }) + }; + let mut view = if own { map_view() } else { MEMORY_MAPPED_VIEW_ADDRESS { Value: std::ptr::null_mut() } }; + if view.Value as usize != base { + split(base, len); + view = map_view(); + } + if view.Value as usize != base { + tracing::warn!( + address = format_args!("{base:#x}"), + len, + error = %std::io::Error::last_os_error(), + "mapping physical pages failed (not a placeholder?)" + ); + return false; + } + if !slice.section.commit_shown(slice.index, base, len) { + // SAFETY: the view just mapped, back to a placeholder. + unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }; + return false; + } + true +} + /// Commits the section pages a view shows (once per page, whichever view). fn commit(base: usize, len: usize) -> bool { if on_wine() { @@ -1150,7 +1651,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { } victory_gpu::title_memory_unmapping(at, size); // SAFETY: a view we mapped; it becomes a placeholder again. - unsafe { + let gone = counted(Call::Unmap, || unsafe { UnmapViewOfFile2( GetCurrentProcess(), MEMORY_MAPPED_VIEW_ADDRESS { @@ -1158,7 +1659,10 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { }, MEM_PRESERVE_PLACEHOLDER, ) - }; + }); + if gone != 0 && at >= base && at + size <= end { + physical.holes.insert(at, size); + } if at < base { map(physical, at, base - at, slice.clone()); } @@ -1591,6 +2095,106 @@ mod tests { assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1); } + /// Many pages in one call: mapped, moved over each other's addresses, + /// given twice in one list, copied by the GPU's mappings and unmapped. + #[test] + fn a_scatter_of_many_pages_is_what_one_after_the_other_is() { + const N: usize = 200; + let pages = allocate(N); + let a = XMemVirtualAlloc(std::ptr::null_mut(), 2 * N * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE) as usize; + let at = |k: usize| (a + k * PAGE) as *mut c_void; + let first = |k: usize| at(k).cast::(); + for round in 0..4_usize { + // Every address shows another page each round. + let to: Vec<*mut c_void> = (0..N).map(|i| at((i + 7 * round) % N)).collect(); + assert_eq!(XMemMapPhysicalPagesScatter(to.as_ptr(), N, pages.as_ptr()), 1); + for i in 0..N { + // SAFETY: mapped read-write. + unsafe { + if round > 0 { + assert_eq!(first((i + 7 * round) % N).read(), (1000 * (round - 1) + i) as u64); + } + first((i + 7 * round) % N).write((1000 * round + i) as u64); + } + } + } + // The GPU's copies of the mappings, in ranges and one by one; a page + // mapped from one the same call has mapped shows the same. + let half = (N / 2 * PAGE) as u64; + let (from, to) = (a as u64, at(N) as u64); + assert!(map_aliases(&[(to, from, half), (to + half, to, half)])); + for k in 0..N / 2 { + // SAFETY: mapped read-write. + unsafe { + assert_eq!(first(N + k).read(), first(k).read()); + assert_eq!(first(N + N / 2 + k).read(), first(k).read()); + first(N + k).write(5); + assert_eq!(first(k).read(), 5); + } + } + // An address twice: the last one counts; page 0 unmaps. + let to = [at(0), at(1), at(0), at(2), at(3), at(0)]; + let what = [pages[5], pages[6], 0, 0, pages[7], pages[8]]; + assert_eq!(XMemMapPhysicalPagesScatter(to.as_ptr(), 6, what.as_ptr()), 1); + assert_eq!(query(at(2)).host.State, MEM_RESERVE); + // SAFETY: mapped read-write; the same page at both. + unsafe { + first(0).write(77); + assert_eq!(XMemMapPhysicalPagesScatter([at(2), at(4), at(6)].as_ptr(), 3, [pages[8]; 3].as_ptr()), 1); + assert_eq!((first(2).read(), first(4).read(), first(6).read()), (77, 77, 77)); + } + // A page the title does not own. + assert_eq!(XMemMapPhysicalPagesScatter([at(0), at(1)].as_ptr(), 2, [pages[0], 1].as_ptr()), 0); + // All gone, also parts of a larger view. + assert_eq!(XMemMapPhysicalPages(at(0), 4, std::ptr::null()), at(0)); + // SAFETY: placeholders of ours, nothing mapped in them. + unsafe { VirtualFree(at(0), 4 * PAGE, MEM_RELEASE | 1 /* MEM_COALESCE_PLACEHOLDERS */) }; + assert_eq!(XMemMapPhysicalPages(at(0), 4, pages.as_ptr()), at(0)); + assert!(map_aliases(&[(a as u64, 0, (2 * N * PAGE) as u64)])); + assert!((0..2 * N).all(|k| query(at(k)).host.State == MEM_RESERVE)); + assert!(physical().views.range(a..a + 2 * N * PAGE).next().is_none()); + assert_eq!(XMemFreePhysicalPages(N, pages.as_ptr()), 1); + } + + /// Pages keep what they hold however often they are mapped, moved and + /// unmapped without a commit or a split of their own. + #[test] + fn pages_mapped_again_hold_what_they_held() { + let pages = allocate(3); + let a = XMemVirtualAlloc(std::ptr::null_mut(), 8 * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!a.is_null()); + let at = |k: usize| a.wrapping_byte_add(k * PAGE); + for round in 0..6_usize { + for (k, page) in pages.iter().enumerate() { + let to = at((round + 2 * k) % 8); + assert_eq!(XMemMapPhysicalPages(to, 1, page), to); + let first = to.cast::(); + // SAFETY: mapped read-write; the far end of the page too. + unsafe { + if round > 0 { + assert_eq!(first.read(), (round * 16 + k - 16) as u64); + assert_eq!(first.add(PAGE / 8 - 1).read(), k as u64); + } + first.write((round * 16 + k) as u64); + first.add(PAGE / 8 - 1).write(k as u64); + } + } + for k in 0..pages.len() { + let to = at((round + 2 * k) % 8); + assert_eq!(XMemMapPhysicalPages(to, 1, std::ptr::null()), to); + assert_eq!(query(to).host.State, MEM_RESERVE); + } + // The title joins what it unmapped: the next view splits it anew. + if round == 3 { + // SAFETY: placeholders of ours, nothing mapped in them. + unsafe { + VirtualFree(a, 8 * PAGE, MEM_RELEASE | 1 /* MEM_COALESCE_PLACEHOLDERS */) + }; + } + } + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); + } + #[test] fn mapping_no_pages_changes_nothing() { let pages = allocate(2); diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index f26b96f..a42c89f 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -258,6 +258,25 @@ pub fn use_console_timers() { ); timeBeginPeriod(1); } + ahead_of_other_programs(); +} + +/// The title's streaming thread runs below normal priority (on the console +/// nobody else wants its core) and does all of the title's loading: a +/// program that keeps the processors busy at normal priority (a build, a +/// virus scan) starved it, loading took 40 to 60 s instead of 28 to 33, and +/// the opening ran without the models that were to be there (runs cpu-1, +/// play-1125-0203). The process runs above normal, as long as it runs. +/// `VICTORY_PROCESS_PRIORITY=normal`: as it was started. +#[cfg(windows)] +fn ahead_of_other_programs() { + use windows_sys::Win32::System::Threading::{ABOVE_NORMAL_PRIORITY_CLASS, GetCurrentProcess, SetPriorityClass}; + if std::env::var_os("VICTORY_PROCESS_PRIORITY").is_some_and(|v| v == "normal" || v == "0") { + return; + } + // SAFETY: a plain process setting. + let set = unsafe { SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS) } != 0; + tracing::info!(set, "the process runs above normal priority (VICTORY_PROCESS_PRIORITY=normal: not)"); } #[cfg(test)] diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 5a65fa6..9ae6730 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -28,6 +28,8 @@ pub mod prepare; pub(crate) mod publish; pub mod resolve; #[cfg(all(windows, feature = "diagnostics"))] +mod profile; +#[cfg(all(windows, feature = "diagnostics"))] mod stacks; #[cfg(windows)] mod threads; @@ -48,6 +50,8 @@ pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; #[cfg(all(windows, feature = "diagnostics"))] pub use stacks::{dump_stacks, dump_stacks_on_schedule}; +#[cfg(all(windows, feature = "diagnostics"))] +pub use profile::profile_on_schedule; #[cfg(windows)] pub use threads::disable_thread_calls; #[cfg(windows)] diff --git a/crates/victory-loader/src/profile.rs b/crates/victory-loader/src/profile.rs new file mode 100644 index 0000000..d9142db --- /dev/null +++ b/crates/victory-loader/src/profile.rs @@ -0,0 +1,195 @@ +//! Where the process's time goes: `VICTORY_PROFILE=,,,` +//! samples the stacks of the busiest threads every `` milliseconds +//! between two times (seconds, as `VICTORY_STACKS`), and writes them counted +//! to `` at the end (several of them, one after another, with `;` +//! between). A thread that waits is sampled like one that +//! runs: its top frame says which (`ntdll`'s system calls). +//! +//! The file: `thread `, then +//! `stack ;;...` (innermost first, as +//! `module+rva`), where the phase is what the caller's function says of the +//! frame at that moment. + +use std::collections::HashMap; +use std::io::Write; +use std::time::{Duration, Instant}; + +use windows_sys::Win32::Foundation::{CloseHandle, FILETIME, HANDLE}; +use windows_sys::Win32::System::Threading::{ + GetThreadTimes, OpenThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME, +}; + +use crate::crash::locate; +use crate::stacks::{frames_of, name_of, other_threads, start_of}; + +/// The threads sampled: those that ran most since they were last chosen. +const BUSIEST: usize = 28; +/// How often they are chosen anew. +const CHOOSE: Duration = Duration::from_secs(1); + +/// What `VICTORY_PROFILE` says: from, to, every, the file. +fn asked(list: &str) -> Option<(Duration, Duration, Duration, String)> { + let mut parts = list.splitn(4, ','); + let mut seconds = || parts.next()?.trim().parse::().ok(); + let (from, to, ms) = (seconds()?, seconds()?, seconds()?); + let of = |s: f64| Duration::try_from_secs_f64(s).ok(); + let file = parts.next()?.trim().to_string(); + Some((of(from)?, of(to)?, of(ms / 1000.0)?, file)).filter(|(a, b, ms, f)| a < b && !ms.is_zero() && !f.is_empty()) +} + +struct Thread { + handle: HANDLE, + start: String, + name: String, + /// Its processor time, 100 ns: at first, when last chosen, now. + first: u64, + last: u64, + now: u64, + samples: u64, +} + +fn cpu(thread: HANDLE) -> u64 { + // SAFETY: zeroed is a valid FILETIME, and the calls write them. + let mut t: [FILETIME; 4] = unsafe { std::mem::zeroed() }; + let [a, b, c, d] = &mut t; + // SAFETY: an open thread; the pointers are to the structures above. + unsafe { GetThreadTimes(thread, a, b, c, d) }; + let of = |f: &FILETIME| u64::from(f.dwHighDateTime) << 32 | u64::from(f.dwLowDateTime); + of(&t[2]) + of(&t[3]) +} + +/// Reads `VICTORY_PROFILE` and, if set, starts the thread that samples. +/// `phase` is asked at each round. +pub fn profile_on_schedule(phase: fn() -> u32) { + let Ok(list) = std::env::var("VICTORY_PROFILE") else { + return; + }; + let start = Instant::now(); + let all: Vec<_> = list.split(';').filter_map(asked).collect(); + std::thread::spawn(move || { + for one in all { + profile(one, start, phase); + } + }); +} + +fn profile((from, to, every, file): (Duration, Duration, Duration, String), start: Instant, phase: fn() -> u32) { + std::thread::sleep(from.saturating_sub(start.elapsed())); + eprintln!("VIctory: the profile begins"); + let mut threads: HashMap = HashMap::new(); + let mut chosen: Vec = Vec::new(); + let mut counts: HashMap<(u32, u32, Vec), u64> = HashMap::new(); + let mut phases: HashMap = HashMap::new(); + let mut choose_at = Instant::now(); + let mut rounds = 0u64; + while start.elapsed() < to { + let round = Instant::now(); + if round >= choose_at { + choose_at = round + CHOOSE; + choose(&mut threads, &mut chosen); + } + let phase = phase(); + *phases.entry(phase).or_default() += 1; + for id in &chosen { + if let Some(t) = threads.get_mut(id) { + let (frames, _) = frames_of(t.handle); + t.samples += 1; + if !frames.is_empty() { + *counts.entry((*id, phase, frames)).or_default() += 1; + } + } + } + rounds += 1; + std::thread::sleep(every.saturating_sub(round.elapsed())); + } + choose(&mut threads, &mut chosen); + if let Err(e) = write(&file, &threads, &counts, &phases, rounds) { + eprintln!("VIctory: the profile was not written: {e}"); + } else { + eprintln!("VIctory: the profile is in {file}"); + } +} + +/// Opens the threads that are new, and chooses the ones to sample. +fn choose(threads: &mut HashMap, chosen: &mut Vec) { + for id in other_threads() { + threads.entry(id).or_insert_with(|| { + // SAFETY: opens a thread of our own process; kept open for the + // profile's life, so the id stays its own. + let handle = + unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, id) }; + let first = if handle.is_null() { 0 } else { cpu(handle) }; + Thread { + handle, + start: if handle.is_null() { String::new() } else { locate(start_of(handle)) }, + name: if handle.is_null() { String::new() } else { name_of(handle) }, + first, + last: first, + now: first, + samples: 0, + } + }); + } + let mut ran: Vec<(u64, u32)> = Vec::new(); + for (&id, t) in threads.iter_mut().filter(|(_, t)| !t.handle.is_null()) { + t.now = cpu(t.handle); + ran.push((t.now - t.last, id)); + t.last = t.now; + } + ran.sort_unstable_by(|a, b| b.cmp(a)); + *chosen = ran.into_iter().take(BUSIEST).map(|(_, id)| id).collect(); +} + +fn write( + file: &str, + threads: &HashMap, + counts: &HashMap<(u32, u32, Vec), u64>, + phases: &HashMap, + rounds: u64, +) -> std::io::Result<()> { + let mut out = std::io::BufWriter::new(std::fs::File::create(file)?); + writeln!(out, "rounds {rounds}")?; + for (phase, n) in phases { + writeln!(out, "phase {phase} {n}")?; + } + let mut names: HashMap = HashMap::new(); + for (id, t) in threads { + writeln!(out, "thread {id} {} {} {} {}", t.start, (t.now - t.first) / 10_000, t.samples, t.name)?; + if !t.handle.is_null() { + // SAFETY: opened by `choose`. + unsafe { CloseHandle(t.handle) }; + } + } + for ((id, phase, frames), n) in counts { + write!(out, "stack {id} {phase} {n} ")?; + for f in frames { + let name = names.entry(*f).or_insert_with(|| locate(*f as usize)); + write!(out, "{name};")?; + } + writeln!(out)?; + } + out.flush() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn what_is_asked_is_read_whole_or_not_at_all() { + assert_eq!( + asked("150, 160.5,5,D:\\a b,c.txt"), + Some(( + Duration::from_secs(150), + Duration::from_millis(160_500), + Duration::from_millis(5), + "D:\\a b,c.txt".to_string() + )) + ); + assert_eq!(asked("150,160,5"), None); + assert_eq!(asked("160,150,5,x"), None); + assert_eq!(asked("a,160,5,x"), None); + assert_eq!(asked("-1,160,5,x"), None); + assert_eq!(asked("1,160,0,x"), None); + } +} diff --git a/crates/victory-loader/src/stacks.rs b/crates/victory-loader/src/stacks.rs index 214dda9..2e2b727 100644 --- a/crates/victory-loader/src/stacks.rs +++ b/crates/victory-loader/src/stacks.rs @@ -66,10 +66,8 @@ struct BasicInfo { #[repr(C, align(16))] struct Aligned(CONTEXT); -/// Prints every other thread's stack to stderr. Each thread is suspended -/// only while its context is read and unwound into a buffer allocated -/// beforehand (it may hold the heap lock). -pub fn dump_stacks() { +/// The ids of this process's threads but the caller's. +pub(crate) fn other_threads() -> Vec { // SAFETY: plain queries and a snapshot of this process's threads. let (me, process, snapshot) = unsafe { ( @@ -79,7 +77,7 @@ pub fn dump_stacks() { ) }; if snapshot == INVALID_HANDLE_VALUE { - return; + return Vec::new(); } let mut ids = Vec::new(); // SAFETY: zeroed is a valid THREADENTRY32; its size is set before use. @@ -96,6 +94,14 @@ pub fn dump_stacks() { } // SAFETY: we opened it. unsafe { CloseHandle(snapshot) }; + ids +} + +/// Prints every other thread's stack to stderr. Each thread is suspended +/// only while its context is read and unwound into a buffer allocated +/// beforehand (it may hold the heap lock). +pub fn dump_stacks() { + let ids = other_threads(); eprintln!("VIctory: stacks of {} threads", ids.len()); for id in ids { // SAFETY: opens a thread of our own process. @@ -109,9 +115,9 @@ pub fn dump_stacks() { if thread.is_null() { continue; } - let (frames, (priority, base)) = frames_of(thread); + let (frames, (priority, base, affinity)) = frames_of(thread); eprintln!( - " thread {id} \"{}\" start {} priority {priority} (base {base})", + " thread {id} \"{}\" start {} priority {priority} (base {base}) affinity {affinity:#x}", name_of(thread), locate(start_of(thread)) ); @@ -124,7 +130,7 @@ pub fn dump_stacks() { } /// The thread's frames and its current and base scheduling priority (0-31). -fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { +pub(crate) fn frames_of(thread: HANDLE) -> (Vec, (i32, i32, usize)) { let mut frames = Vec::with_capacity(MAX_FRAMES); let mut info: BasicInfo = BasicInfo { exit_status: 0, @@ -138,7 +144,7 @@ fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { // the query and the read below. // SAFETY: a thread of this process that is not this one. if unsafe { SuspendThread(thread) } == u32::MAX { - return (frames, (0, 0)); + return (frames, (0, 0, 0)); } // SAFETY: writes `info`, whose layout and size are the system's. let status = unsafe { @@ -153,7 +159,7 @@ fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { if status != 0 || info.teb.is_null() { // SAFETY: suspended above. unsafe { ResumeThread(thread) }; - return (frames, (0, 0)); + return (frames, (0, 0, 0)); } // SAFETY: the TEB of a suspended thread of this process: its NT_TIB // holds the stack base at +8 and the stack limit at +0x10. @@ -170,10 +176,10 @@ fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { } ResumeThread(thread); } - (frames, (info.priority, info.base_priority)) + (frames, (info.priority, info.base_priority, info.affinity)) } -fn start_of(thread: HANDLE) -> usize { +pub(crate) fn start_of(thread: HANDLE) -> usize { let mut start = 0usize; // SAFETY: writes one pointer-sized start address. unsafe { @@ -188,7 +194,7 @@ fn start_of(thread: HANDLE) -> usize { start } -fn name_of(thread: HANDLE) -> String { +pub(crate) fn name_of(thread: HANDLE) -> String { let mut name = std::ptr::null_mut(); // SAFETY: the system allocates the string; we free it with LocalFree. unsafe { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 6a86f71..86ceff9 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1082,9 +1082,9 @@ fn own_bits_on() -> bool { } /// What the translator was told of the host, for a cache's key: the widest -/// wave and the view heap's limit. -pub fn host_settings() -> [u32; 2] { - [host_max_wave(), super::shader::view_heap_limit()] +/// wave, the view heap's limit and where the raw twins of its views start. +pub fn host_settings() -> [u32; 3] { + [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views()] } /// The refusal of a first half of an interpolation whose result is read @@ -6724,12 +6724,13 @@ impl<'a> Lower<'a> { return Ok(h); } let index = self.heap_index(*load, *first, sampler)?; + let (index, bounded) = self.raw_twin(src, index, sampler, props); // A waterfall loop's load at the first lane's offset reads // each lane's own entry (see `resource::Waterfall`). let per_lane = self.x.res.waterfall.loads.contains(load); let h = self .s - .heap_handle(self.cur, index, sampler, per_lane, props); + .heap_handle_at(self.cur, index, sampler, per_lane, props, bounded); self.handles.insert(key, h); Ok(h) } @@ -6775,7 +6776,8 @@ impl<'a> Lower<'a> { Source::Phi { block, args } => { let _ = site; let phi = self.descriptor_phi(*block, args, sampler, 8)?; - Ok(self.s.heap_handle(self.cur, phi, sampler, false, props)) + let (index, bounded) = self.raw_twin(src, phi, sampler, props); + Ok(self.s.heap_handle_at(self.cur, index, sampler, false, props, bounded)) } Source::Select { scc, args } => { // The heap index of each choice, picked by SCC (uniform). @@ -6793,18 +6795,52 @@ impl<'a> Lower<'a> { let set = self.heap_index(a, fa, sampler)?; let clear = self.heap_index(b, fb, sampler)?; let index = self.s.m.select(self.cur, cond, set, clear); - Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) + let (index, bounded) = self.raw_twin(src, index, sampler, props); + Ok(self.s.heap_handle_at(self.cur, index, sampler, false, props, bounded)) } Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => { // A descriptor each lane has its own of (a waterfall loop // reads it from the first active lane): each lane's heap // index, non-uniform. let index = self.lane_heap_index(src, sampler)?; - Ok(self.s.heap_handle(self.cur, index, sampler, true, props)) + let (index, bounded) = self.raw_twin(src, index, sampler, props); + Ok(self.s.heap_handle_at(self.cur, index, sampler, true, props, bounded)) } } } + /// The heap index to read descriptor `src` at, `index` being the title's: + /// for a buffer picked from the heap itself and read as raw bytes (or as + /// a constant buffer), the host's raw twin of that slot + /// ([`super::shader::raw_views`]), whose reads end where the view does. + /// Everything else (tables, textures, typed buffers) stays in place. + /// And whether it is a twin's (inside the host's heap). + fn raw_twin(&mut self, src: &Source, index: V, sampler: bool, props: (u32, u32)) -> (V, bool) { + // Raw and constant buffers (DXIL resource kinds 11 and 13). + const RAW: u32 = 11; + const CONSTANT: u32 = 13; + let first = super::shader::raw_views(); + let picked = |leaf: &&Source| { + let (Source::Loaded { load, .. } | Source::Fetched { load, .. }) = leaf else { + return false; + }; + self.scalar + .get(load) + .and_then(|a| self.x.native.layout.get(a.param)) + .is_some_and(|p| p.root == RootType::ResourceHeap) + }; + if first == 0 || sampler || !matches!(props.0 & 0xFF, RAW | CONSTANT) || !src.leaves().iter().all(picked) { + return (index, false); + } + let c = self.cur; + let (last, first) = (self.s.m.i32(first - 1), self.s.m.i32(first)); + let i32t = self.s.t.i32; + // (As `dx.op.binary` UMin, see `heap_handle`.) + let index = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]); + self.s.m.tag(index, Tag::Clamp); + (self.s.m.bin(c, Bin::Or, index, first), true) + } + /// The heap index a descriptor phi picks. Each predecessor computes its /// heap index at its end and the join picks one with a phi; a /// predecessor whose descriptor is itself chosen by control flow (a diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index c9c727e..46de147 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -119,7 +119,7 @@ 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, - set_view_heap_limit, view_heap_limit, + raw_views, set_raw_views, set_view_heap_limit, view_heap_limit, }; /// The loop limit without an override: 2^20. @@ -221,6 +221,7 @@ pub fn translation_fingerprint() -> Vec { } out.extend_from_slice(&lower::host_max_wave().to_le_bytes()); out.extend_from_slice(&shader::view_heap_limit().to_le_bytes()); + out.extend_from_slice(&shader::raw_views().to_le_bytes()); out.extend_from_slice(&loop_limit().to_le_bytes()); out.push(group_sync()); out.extend_from_slice(&shader_opt().to_le_bytes()); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index eb6d589..c545294 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -131,6 +131,40 @@ pub fn view_heap_limit() -> u32 { VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed) } +/// Where the host's raw twins of its buffer views start in its view heaps (0: there are none). +/// +/// A buffer a shader picks from the heap by an index it computes is read as raw bytes whatever +/// view the title has there, and the index comes from data: a record of a mesh long gone, a list +/// entry nothing wrote. On AMD a raw load through a view that is not raw (typed, structured, a +/// constant buffer's) has no end: it reads whatever lies there, up to 4 GiB on, and loses the +/// device where nothing does; and a texture's descriptor read as a buffer's is a wild address. +/// So the host keeps, for title slot `i`, a raw view of the same bytes at this place + `i` +/// (a constant buffer view of a constant buffer, a null raw view of everything else and of every +/// slot past the title's), and shaders translated while this is set read picked buffers there. +/// A power of two above every slot index. +static RAW_VIEWS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +#[cfg(test)] +thread_local! { + /// For a test's thread alone. + pub(crate) static RAW_VIEWS_HERE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// See [`RAW_VIEWS`]. +pub fn set_raw_views(first: u32) { + debug_assert!(first == 0 || first.is_power_of_two()); + RAW_VIEWS.store(first, std::sync::atomic::Ordering::Relaxed); +} + +/// See [`RAW_VIEWS`]: where shaders translated now read the buffers they pick (0: in place). +pub fn raw_views() -> u32 { + #[cfg(test)] + if let Some(first) = RAW_VIEWS_HERE.get() { + return first; + } + RAW_VIEWS.load(std::sync::atomic::Ordering::Relaxed) +} + pub(crate) struct Shader { pub m: Module, pub t: Types, @@ -402,9 +436,24 @@ impl Shader { sampler: bool, nonuniform: bool, props: (u32, u32), + ) -> V { + self.heap_handle_at(block, index, sampler, nonuniform, props, false) + } + + /// [`Shader::heap_handle`]; `bounded`: the index is inside the host's heap already + /// ([`raw_views`]). + pub fn heap_handle_at( + &mut self, + block: usize, + index: V, + sampler: bool, + nonuniform: bool, + props: (u32, u32), + bounded: bool, ) -> V { // a view index past the host heap (`set_view_heap_limit`) reads its null slot instead - let limit = VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed); + // (the raw twins of buffer views lie past it: such an index comes bounded) + let limit = if bounded { 0 } else { VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed) }; // (as `dx.op.binary` UMin: a compare and select emitted here made the bitcode invalid) let index = if !sampler && limit != 0 { let null = self.m.i32(limit); diff --git a/crates/victory-shader/src/emit/size_tests.rs b/crates/victory-shader/src/emit/size_tests.rs index 086587b..0cb8696 100644 --- a/crates/victory-shader/src/emit/size_tests.rs +++ b/crates/victory-shader/src/emit/size_tests.rs @@ -299,3 +299,47 @@ fn a_buffer_loaded_past_the_cache_is_coherent() { } } } + +/// A buffer picked from the view heap and read as raw bytes is read at the +/// host's raw twin of its slot, when the host keeps some; an index past the +/// title's slots reads the last twin, not a slot of something else. +#[test] +fn a_picked_buffer_is_read_at_its_raw_twin() { + let program = |at: u32| { + let words = [ + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xBE8C_03FF, // s_mov_b32 s12, at + at, + 0xF408_0203, // s_load_dwordx4 s[8:11], s[6:7], s12 + 0x1800_0000, + 0xE030_0004, // buffer_load_dword v5, off, s[8:11], 0 offset:4 + 0x8002_0500, + 0x7E0A_0505, // v_readfirstlane_b32 s5, v5 + 0xBE84_0380, // s_mov_b32 s4, 0 + ]; + [TABLE, &words, STORE].concat() + }; + let (title, twin, last, texel) = ([1u32, 2, 3, 4], [5u32, 6, 7, 8], [9u32, 10, 11, 12], [[0.0; 4]; 1]); + let raw = |data| View::Buffer { data, stride: Stride::Raw }; + let views = || { + [ + View::Texture(1, 1, &texel), + raw(&title), + View::RawUav(2), + View::Texture(1, 1, &texel), + View::Texture(1, 1, &texel), + raw(&twin), + View::Texture(1, 1, &texel), + raw(&last), + ] + }; + for (first, at, expected) in [(0, 32, 2), (4, 32, 6), (4, 32 * 1000, 10)] { + super::shader::RAW_VIEWS_HERE.set(Some(first)); + let shader = build(&program(at), (8, 0)).expect("translates"); + super::shader::RAW_VIEWS_HERE.set(None); + for (label, got) in run(&shader, &views()) { + assert_eq!(got[..2], [0, expected], "{label}: twins from {first}, byte {at}"); + } + } +}