Merge fork main 310c6eb

Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	crates/victory-gpu/src/indirect.rs
This commit is contained in:
local committed 2026-11-24 21:41:28 -06:00
commit 9213e3fdf8
9 files changed
+1807 -32

No files matched your search

+5
View File
@@ -692,6 +692,11 @@ fn log_memory() {
let card = crate::host::host()
.and_then(|h| h.video_memory())
.unwrap_or_default();
// Everything the system says of the two memory groups, beside the
// budget and use the lines below print.
if let Some(h) = crate::host::host() {
h.log_video_memory("with the memory line");
}
// What else holds memory: the map, on a thread of its own, with every
// sixth line; and what the shader table and the pipeline library keep.
static LINES: AtomicU64 = AtomicU64::new(0);
+262 -24
View File
@@ -89,16 +89,25 @@ pub(crate) struct HostHeap {
}
/// Title memory by the placed texture views that describe it: per span of
/// memory (its start, its end) the title slots holding a view of a
/// texture that takes exactly that span. Spans never overlap: a console
/// title need not clear a descriptor when it streams a texture out, so a
/// view written over memory that older views describe otherwise (another
/// start or another length: another texture) is all that says the older
/// ones are stale. Views of one span with different descriptions (the
/// formats of one family, say) are one texture's.
/// memory (its start, its end at full size) the title slots holding a
/// view of a texture that takes exactly that span. A console title need
/// not clear a descriptor when it streams a texture out, so a newer view
/// that cannot be there together with an older one is all that says the
/// older one is stale ([`Rule`] says when that is). Views of one span with
/// different descriptions (the formats of one family, say) are one
/// texture's.
///
/// Spans may overlap: a texture's smallest levels lie at the start of its
/// memory, and a title that holds only those puts the next texture where
/// the larger ones would be (the title: three 512x256 textures
/// of 0x2c000 bytes each whose starts are 0x2000 and 0x4000 apart, all
/// three read by the same frame's draws, run 188). What is there of a
/// texture ends where the next one starts.
/// No host heap is needed, so it is tested without one.
#[derive(Default)]
pub(crate) struct Spans {
/// When a newer view makes an older one stale.
rule: Rule,
by_start: std::collections::BTreeMap<u64, (u64, std::collections::BTreeSet<u32>)>,
by_slot: std::collections::HashMap<u32, u64>,
/// The bytes a placed texture takes, by resource description: worked
@@ -107,6 +116,32 @@ pub(crate) struct Spans {
sizes: std::collections::HashMap<[u32; 14], Option<u64>>,
}
/// When a view the title writes makes an older view of other memory stale.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Rule {
/// When it starts where the older one starts: at the same address
/// with another length, or within the older one's first [`HEAD`]
/// bytes (or the older within its own). No two textures share the
/// block of their smallest levels. A view that only reaches into the
/// address range of an older texture's larger levels says nothing.
#[default]
Start,
/// Whenever their spans at full size overlap (the rule until run
/// 188, where it made null the slots of textures packed as above:
/// each view written took its neighbours out of the queue and off the
/// card, for good). `VICTORY_STALE_TEXTURES=overlap`.
Overlap,
/// Never; a view that would be stale under [`Rule::Overlap`] is left
/// out of the spans instead. `VICTORY_STALE_TEXTURES=0`, as before.
Never,
}
/// The first bytes of a placed texture that are its own under
/// [`Rule::Start`]: the 4 KiB block its smallest levels share. (Of 129
/// pairs of overlapping neighbours in the listings of runs 188 and 189,
/// none starts closer than 0x2000 to the one before it.)
const HEAD: u64 = 4096;
impl Spans {
/// The bytes of title memory a placed texture with the resource
/// description `desc` takes (`crate::resource::placed_bytes`).
@@ -119,7 +154,10 @@ impl Spans {
bytes
}
/// The starts of the spans that overlap `[start, end)`.
/// The starts of the spans that overlap `[start, end)`, each taken to
/// end where the next one starts: the last span that starts before
/// `start`, if it reaches past it at full size, and every span that
/// starts inside.
fn overlapping(&self, start: u64, end: u64) -> Vec<u64> {
let before = self
.by_start
@@ -131,10 +169,10 @@ impl Spans {
}
/// Slot `index` holds a view of a texture in `[start, end)`. `newer`:
/// the title wrote it now, so the slots whose views describe that
/// memory otherwise are stale: they are returned, and forgotten.
/// Otherwise (a draw made the slot from what it held) a view that
/// overlaps other spans is left out.
/// the title wrote it now, so the slots whose views cannot be there
/// with it ([`Rule`]) are stale: they are returned, and forgotten.
/// Otherwise (a draw made the slot from what it held), and under
/// [`Rule::Never`], a view that clashes with other spans is left out.
fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec<u32> {
let same = |span: Option<&(u64, std::collections::BTreeSet<u32>)>| span.is_some_and(|s| s.0 == end);
if self.by_slot.get(&index) == Some(&start) && same(self.by_start.get(&start)) {
@@ -144,15 +182,40 @@ impl Spans {
if end <= start {
return Vec::new();
}
let rule = self.rule;
// The spans the view cannot be there with.
let clashing: Vec<u64> = match rule {
Rule::Start => self
.by_start
.range(start.saturating_sub(HEAD - 1)..start.saturating_add(HEAD))
.map(|(at, _)| *at)
.collect(),
Rule::Overlap | Rule::Never => self.overlapping(start, end),
};
let mut stale = Vec::new();
for at in self.overlapping(start, end) {
for at in clashing {
if at == start && same(self.by_start.get(&at)) {
continue;
}
if !newer {
if !newer || rule == Rule::Never {
return stale;
}
if let Some((_, slots)) = self.by_start.remove(&at) {
if let Some((old_end, slots)) = self.by_start.remove(&at) {
// The first of them are said with both spans, to tell a
// replacement from a neighbour in one launch's log.
static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 48 {
tracing::info!(
slot = index,
start = format_args!("{start:#x}"),
end = format_args!("{end:#x}"),
stale_start = format_args!("{at:#x}"),
stale_end = format_args!("{old_end:#x}"),
stale_slots = slots.len(),
rule = ?rule,
"a placed texture view makes older views of other memory stale"
);
}
for slot in slots {
self.by_slot.remove(&slot);
stale.push(slot);
@@ -206,11 +269,18 @@ static SPANNED: [std::sync::atomic::AtomicU64; 2] = [
pub(crate) static STALE: [std::sync::atomic::AtomicU64; 5] =
[const { std::sync::atomic::AtomicU64::new(0) }; 5];
/// Whether a view written over memory that older views describe otherwise
/// makes those stale; `VICTORY_STALE_TEXTURES=0` leaves them as they are.
fn stale_out() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_STALE_TEXTURES").is_none_or(|v| v != "0"))
/// When a view the title writes makes older views of other memory stale
/// ([`Rule`]): where it starts in the block of their smallest levels, by
/// default; `VICTORY_STALE_TEXTURES=0`: never, as before;
/// `VICTORY_STALE_TEXTURES=overlap`: wherever their spans overlap, the rule
/// until run 188.
fn stale_rule() -> Rule {
static RULE: std::sync::OnceLock<Rule> = std::sync::OnceLock::new();
*RULE.get_or_init(|| match std::env::var("VICTORY_STALE_TEXTURES").as_deref() {
Ok("0") => Rule::Never,
Ok("overlap") => Rule::Overlap,
_ => Rule::Start,
})
}
/// The runtime mapped or unmapped title memory `[at, at + len)`, or is
@@ -856,6 +926,20 @@ impl HostHeap {
(if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame))
}
/// Every title slot of the queue that is due at `frame`, and whether
/// it was uploaded before (in part, or whole and waiting for another
/// look): for the card accounting line
/// (`crate::resource::card_accounting`).
pub(crate) fn texture_slots_all_due(&self, frame: u64) -> Vec<(u32, bool)> {
let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
textures
.slots
.iter()
.filter(|(_, w)| w.due <= frame)
.map(|(&index, w)| (index, w.mapped > 0 || w.checked.2 != 0))
.collect()
}
/// The texture view of title slot `index` (as handed out with `write`)
/// was brought up to date: due again from frame `again` (uploaded with
/// that many bytes of its memory there, not all), or not until the
@@ -934,6 +1018,36 @@ impl HostHeap {
slots.len()
}
/// Whether host slot `index` is made from the very record the title
/// has at `handle` now. Its host texture then exists (a slot keeps what
/// it views), so bringing that texture up to date takes no memory of
/// the card.
pub(crate) fn texture_slot_made_from(&self, index: u32, handle: u64) -> bool {
if index >= self.count {
return false;
}
// SAFETY: the handle is a descriptor slot in title memory.
let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
let key = u64::from(generation) << 32 | u64::from(i);
if tag != VIEW_TAG {
return false;
}
// And the slot holds a host resource: a slot is also noted as made
// from a view the host could not make (`make` gave nothing, the
// slot is null and keeps nothing). The host copy of such a
// texture is held by no slot, may have been let go, and would be
// made anew here, with the card full. `made` first, then `kept`,
// as `mirror` takes them.
let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
made.get(index as usize).is_some_and(|&made| made != 0 && made == key)
&& self
.kept
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(index as usize)
.is_some_and(Option::is_some)
}
/// The memory of the texture title slot `index` views is not mapped
/// (any more): a host slot made from it becomes null again, so that
/// the host copy can be let go (`crate::resource::let_go_idle`; a slot
@@ -1103,7 +1217,8 @@ impl HostHeap {
Some((start, end)) => {
SPANNED[0].fetch_min(start, Relaxed);
SPANNED[1].fetch_max(end, Relaxed);
placed.note(index, start, end, !seen && stale_out())
placed.rule = stale_rule();
placed.note(index, start, end, !seen)
}
None => {
placed.forget(index);
@@ -1412,6 +1527,24 @@ impl HostHeap {
Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer))
}
/// What the queue of textures picked by index knows of title slot
/// `index` at `frame`, in a few words (diagnostics).
#[cfg(feature = "diagnostics")]
pub(crate) fn texture_slot_state(&self, index: u32, frame: u64) -> String {
let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
match textures.slots.get(&index) {
None => "not queued".into(),
Some(w) => format!(
"queued due={} written@{} looks={} part_mapped={} recheck={}",
if w.due <= frame { "now".to_string() } else { format!("@{}", w.due) },
w.written,
w.looks,
w.mapped,
w.checked.2 != 0
),
}
}
/// The view host slot `index` was made from, in a few words, with the
/// title and host addresses of a buffer view (diagnostics). "null" for
/// a slot never made or left null.
@@ -2471,11 +2604,116 @@ mod tests {
assert!(q.due(16, 100).iter().any(|d| d.0 == 98));
}
/// A view written over memory that older views describe otherwise
/// makes those stale; views of the same span are one texture's.
/// Textures of which only the smallest levels are held, packed into
/// one another's address range (the three of run 188: 0x2c000 bytes
/// each at full size, their starts 0x2000 and 0x4000 apart): writing
/// any of them, in any order and again, leaves the others.
#[test]
fn packed_neighbours_stay() {
let mut spans = Spans::default();
assert_eq!(spans.rule, Rule::Start);
let at = 0xb_86bf_8000u64;
let (a, b, c) = (at, at + 0x2000, at + 0x6000);
assert!(spans.note(105_998, a, a + 0x2c000, true).is_empty());
assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty());
assert!(spans.note(108_521, c, c + 0x2c000, true).is_empty());
// The first written again (as a title does when levels arrive),
// from another slot too: its span reaches over the other two.
assert!(spans.note(7, a, a + 0x2c000, true).is_empty());
assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty());
let mut all = spans.slots_in(0, u64::MAX);
all.sort_unstable();
assert_eq!(all, [7, 105_998, 106_004, 108_521]);
// A draw makes a slot of the second texture: it is one of them.
assert!(spans.note(9, b, b + 0x2c000, false).is_empty());
assert_eq!(spans.by_slot.get(&9), Some(&b));
}
/// A texture written where another starts replaces it: at the same
/// address with another length, or inside the block of its smallest
/// levels. The packed neighbours of the one replaced stay.
#[test]
fn a_texture_written_at_the_start_of_another_replaces_it() {
let mut spans = Spans::default();
let at = 0x7_0000_0000u64;
assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
// Another length from the same start: slot 1 is stale, slot 2 not.
assert_eq!(spans.note(3, at, at + 0xb000, true), [1]);
// A start inside the first 4 KiB of slot 3's texture: stale too.
assert_eq!(spans.note(4, at + 0x800, at + 0x1800, true), [3]);
// And the other way: a texture that starts just before one.
assert_eq!(spans.note(5, at + 0x1800, at + 0x4800, true), [2]);
let mut left = spans.slots_in(0, u64::MAX);
left.sort_unstable();
assert_eq!(left, [4, 5]);
// Exactly 4 KiB apart: both there.
assert!(spans.note(6, at + 0x2800, at + 0x3800, true).is_empty());
// A draw's view that clashes is left out, and nothing is stale.
assert!(spans.note(8, at + 0x900, at + 0x2900, false).is_empty());
assert_eq!(spans.by_slot.get(&8), None);
assert_eq!(spans.by_slot.len(), 3);
}
/// A slot written with another texture leaves its old span; the same
/// view written again changes nothing.
#[test]
fn a_slot_rewritten_moves_to_its_new_span() {
let mut spans = Spans::default();
assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty());
assert!(spans.note(2, 0x12000, 0x3e000, true).is_empty());
assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty());
assert_eq!(spans.slots_in(0x10000, 0x10001), [1]);
// Slot 1 now views a texture far away.
assert!(spans.note(1, 0x90000, 0x91000, true).is_empty());
assert_eq!(spans.slots_in(0x10000, 0x10001), [] as [u32; 0]);
assert_eq!(spans.slots_in(0x12000, 0x12001), [2]);
assert_eq!(spans.slots_in(0x90000, 0x90001), [1]);
spans.forget(1);
spans.forget(2);
assert!(spans.by_start.is_empty() && spans.by_slot.is_empty());
}
/// Memory the runtime maps, unmaps or writes names the textures that
/// are there: among packed neighbours the one whose held levels the
/// range lies in (it ends where the next one starts), and the ones
/// that start inside the range.
#[test]
fn memory_changed_under_packed_neighbours_names_the_ones_there() {
let mut spans = Spans::default();
let at = 0x7_0000_0000u64;
assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty());
// Inside the first one's held levels.
assert_eq!(spans.slots_in(at + 0x1000, at + 0x2000), [1]);
// Inside the second's: not the first, which ends where it starts.
assert_eq!(spans.slots_in(at + 0x3000, at + 0x4000), [2]);
// Past the last start: the last one.
assert_eq!(spans.slots_in(at + 0x20000, at + 0x21000), [3]);
// A range over all of them.
assert_eq!(spans.slots_in(at, at + 0x8000), [1, 2, 3]);
// Past the end of all: none.
assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]);
}
/// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that
/// overlaps others is left out of the spans, as before.
#[test]
fn never_stale_leaves_overlapping_views_out() {
let mut spans = Spans { rule: Rule::Never, ..Default::default() };
assert!(spans.note(1, 0x1000, 0x3000, true).is_empty());
assert!(spans.note(2, 0x2000, 0x4000, true).is_empty());
assert!(spans.note(3, 0x1000, 0x2000, true).is_empty());
assert_eq!(spans.slots_in(0, u64::MAX), [1]);
}
/// The rule until run 188 (`VICTORY_STALE_TEXTURES=overlap`): a view
/// written over memory that older views describe otherwise makes
/// those stale; views of the same span are one texture's.
#[test]
fn a_newer_view_of_other_memory_makes_the_older_stale() {
let mut spans = Spans::default();
let mut spans = Spans { rule: Rule::Overlap, ..Default::default() };
// Three textures side by side, the first in two slots.
assert!(spans.note(1, 0x1000, 0x3000, true).is_empty());
assert!(spans.note(2, 0x1000, 0x3000, true).is_empty());
+459 -4
View File
@@ -383,6 +383,18 @@ const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400];
/// was, and that found it changed (uploaded again), since the start.
pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)];
/// Uploads of textures already on the card made while it had no room for
/// new ones, since the start.
pub(crate) static HEAP_TEXTURES_REUPLOADED_FULL: AtomicU64 = AtomicU64::new(0);
/// Whether a texture that has its host copy is still brought up to date
/// while the card has no room for new ones (`VICTORY_REUPLOAD_WHEN_FULL=0`:
/// no).
fn reupload_when_full() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_REUPLOAD_WHEN_FULL").is_none_or(|v| v != "0"))
}
/// Whether textures picked by index are looked at again after their upload
/// (`VICTORY_HEAP_RECHECK=0`: no).
fn heap_recheck() -> bool {
@@ -915,6 +927,9 @@ impl State {
let l = &list.list;
// Textures picked by index, before anything asks for them.
self.early_textures(list, p, compute);
if crate::host::walls_trace() {
self.walls_census(p, compute);
}
// Heaps first: a root signature with directly indexed heaps must be
// set after them.
if self.host_heaps != self.heaps {
@@ -1552,6 +1567,77 @@ impl State {
}
}
/// The queue's side of the card accounting line
/// (`crate::resource::card_accounting`, which says what the line
/// holds): the slots that are due, by what their texture has on the
/// card. Off unless `VICTORY_CARD_ACCOUNTING=1`; then at the first pass
/// that finds the card without room, and every five seconds after it.
/// Nothing is made, uploaded or counted as used here. For 18,000 due
/// slots: 18,000 looks at a title slot and at the texture it views, a
/// lock each, some milliseconds of the thread that records the frame.
fn card_accounting(
heap: &crate::descriptor::Heap,
host: &crate::descriptor::host::HostHeap,
frame: u64,
room: bool,
) {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ACCOUNTING").is_some_and(|v| v == "1")) {
return;
}
// When the next line is due (0: none yet, the card has had room).
static NEXT: AtomicU64 = AtomicU64::new(0);
let now = crate::host::now_ms().max(1);
let next = NEXT.load(Ordering::Relaxed);
let due_now = if next == 0 { !room } else { now >= next };
if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() {
return;
}
// Due slots; of them uploaded before; of them viewing nothing the
// title fills; and the textures (each once) whose host copy is
// alive, with their bytes on the card.
let mut due = [0u64; 5];
// Textures (each once) that never had a host copy, and ones whose
// host copy was let go: where their memory is, and its bytes.
let (mut never, mut gone) = (Vec::new(), Vec::new());
let mut seen = std::collections::BTreeSet::new();
for (index, uploaded) in host.texture_slots_all_due(frame) {
due[0] += 1;
due[1] += u64::from(uploaded);
let state = match heap.handle(index).and_then(crate::descriptor::view) {
Some(View::Placed(false, resource, desc)) if resource[0] != 1 => {
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
match crate::resource::placed_known(address, &resource) {
Some(texture) => crate::resource::copy_state(texture),
// No title texture was made for it: the pass never
// got as far as making one.
None => Some((0, crate::resource::placed_bytes(&resource).unwrap_or(0), address)),
}
}
Some(View::Shader(object, _)) if crate::resource::title_fills(object as This) => {
crate::resource::copy_state(object as This)
}
_ => None,
};
let Some((state, bytes, memory)) = state else {
due[2] += 1;
continue;
};
if !seen.insert(memory) {
continue;
}
match state {
2 => {
due[3] += 1;
due[4] += bytes;
}
1 => gone.push((memory, bytes)),
_ => never.push((memory, bytes)),
}
}
crate::resource::card_accounting(room, due, never, gone);
}
/// The texture side of [`State::heap_buffers`]: textures the title fills
/// itself (streamed pages, layout-library copies) whose views sit in the
/// view heap are created (placed textures have no host texture until
@@ -1615,6 +1701,10 @@ impl State {
for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) {
count.store(now, Ordering::Relaxed);
}
// Where the card's memory is, and what the due slots would need
// (`VICTORY_CARD_ACCOUNTING=1`; a line when the card first has no
// room, and every five seconds after it).
Self::card_accounting(heap, host, frame, room);
// The frames in about four seconds, between 16 and 256: how long a
// slot with nothing to upload waits at most for its next look. In
// frames alone it was 120: four minutes at the opening cutscene's
@@ -1744,12 +1834,35 @@ impl State {
}
// From here on a host texture is made: not without room. The
// slot stays due.
// Not so a slot already made from this very view: its host
// texture exists, and uploading it again takes none of the
// card's memory. It was refused all the same, so a texture the
// title filled after its first upload kept its empty host copy
// from the moment the card reached the line, which is the first
// world frame in eight launches of nine: the same slots were
// found changed again at every pass and never uploaded (run
// 179: 33,000 such findings), and the main character's face
// had its colour only in the launches that entered the world
// under the line. `VICTORY_REUPLOAD_WHEN_FULL=0`: refused, as
// before.
if !room {
refused += 1;
if refused > 256 {
break;
let has_its_texture = reupload_when_full()
&& heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle));
if !has_its_texture {
refused += 1;
if refused > 256 {
break;
}
continue;
}
let n = HEAP_TEXTURES_REUPLOADED_FULL.fetch_add(1, Ordering::Relaxed) + 1;
if n == 1 || n.is_multiple_of(500) {
tracing::info!(
so_far = n,
slot = index,
"a texture already on the card is brought up to date although the card has no room for new ones"
);
}
continue;
}
let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true));
let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture);
@@ -1982,9 +2095,180 @@ impl State {
}
}
let _ = write!(text, " tables {:?}", self.reads(compute));
if !compute && !list_slots().is_empty() {
text.push_str(&self.slots_text());
}
text
}
/// For the frame listing, after a draw whose shader `VICTORY_LIST_SLOTS`
/// names: the heap slots it will pick textures from by index, and what
/// the title and the host hold there (one `~slot` line each), with the
/// words they were read from (`~raw` lines, to decode offline what is
/// not decoded here).
///
/// Where the slots are, for the title's character shaders
/// (`PS_DeferredPedTexturedNC`, from their native code): in the small
/// buffers and constants of the draw's own table (every word of those
/// that names a texture view gets a line); in the material record, at
/// the byte offset the draw's constants (table 1, dword 56) hold at
/// 0x1c, of the buffer at table 0, dword 160; and in the record at the
/// byte offset the second root constant holds of the buffer at table 0,
/// dword 688. A word that is a small number by chance and names a
/// texture gets a line too.
#[cfg(feature = "diagnostics")]
fn slots_text(&self) -> String {
use std::fmt::Write;
const MATERIALS: u32 = 160;
const GLOBAL: u32 = 688;
const DRAW_CONSTANTS: u32 = 56;
let wanted = list_slots();
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
return String::new();
};
let Some(stage) = p.stages.iter().find(|s| wanted.iter().any(|w| s.shader.hash.starts_with(w.as_str())))
else {
return String::new();
};
let Some(heap) = self
.heaps
.iter()
.filter(|&&h| h != 0)
.map(|&h| crate::descriptor::heap(h as This))
.find(|h| !h.samplers())
else {
return String::new();
};
let t = stage.translated();
let mut text = String::new();
let entry = |slot: u8, dwords: u32| -> Option<View> {
let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(slot)) else {
return None;
};
crate::descriptor::view(table + u64::from(dwords) * 4)
};
let mut material = None;
for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind != ResourceType::Sampler) {
let label = format!("s{}+{}", u.slot, u.table_offset_dwords);
let Some(view) = entry(u.slot, u.table_offset_dwords) else {
let _ = write!(text, "\n ~table {label} no view");
continue;
};
let range = match &view {
View::Constant(address, size) => Some((*address, u64::from(*size))),
other => crate::descriptor::host::buffer_range(other),
};
match range {
// A small buffer or constants: its words.
Some((address, len)) if len <= 2048 => {
Self::slot_words(&mut text, heap, &label, address, len as usize);
if u.slot == 1 && u.table_offset_dwords == DRAW_CONSTANTS && len >= 0x20 {
let mut word = [0u8; 4];
if crate::host::read_into((address + 0x1c) as *const u8, &mut word) {
material = Some(u32::from_le_bytes(word));
}
}
}
Some(_) => {}
// A texture read through the table: the title slot it sits in.
None => {
let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(u.slot)) else {
continue;
};
match heap.index(table + u64::from(u.table_offset_dwords) * 4) {
Some(index) => text.push_str(&Self::slot_line(heap, &format!("table:{label}"), 0, index)),
None => {
let _ = write!(text, "\n ~table {label} title=[{}]", view_state(Some(&view)));
}
}
}
}
}
let uses = |slot: u8, dwords: u32| {
t.used.iter().any(|u| u.root == RootType::Table && u.slot == slot && u.table_offset_dwords == dwords)
};
if let Some(at) = material
&& uses(0, MATERIALS)
&& let Some((base, len)) = entry(0, MATERIALS).as_ref().and_then(crate::descriptor::host::buffer_range)
{
let at = u64::from(at);
let _ = write!(text, "\n ~material record at {at:#x} of the buffer at {base:#x} bytes {len}");
if at + 64 <= len {
Self::slot_words(&mut text, heap, "M", base + at, 64);
}
if at + 1936 + 512 <= len {
Self::slot_words(&mut text, heap, "M+1936", base + at + 1936, 512);
}
}
if uses(0, GLOBAL)
&& let Some(slot) = t.used.iter().find(|u| u.root == RootType::Constants).map(|u| u.slot)
&& let Some(Root::Constants(words)) = self.roots_ref(false).get(usize::from(slot))
&& let Some(&at) = words.get(1)
&& let Some((base, len)) = entry(0, GLOBAL).as_ref().and_then(crate::descriptor::host::buffer_range)
{
let at = u64::from(at);
let _ = write!(text, "\n ~root constants {words:08x?}: record at {at:#x} of the buffer at {base:#x} bytes {len}");
if at + 64 <= len {
Self::slot_words(&mut text, heap, "G", base + at, 64);
}
}
text
}
/// Up to 512 bytes of title memory at `address` as hex words (a `~raw`
/// line), and a `~slot` line for every word of them that names a
/// texture view in `heap`.
#[cfg(feature = "diagnostics")]
fn slot_words(text: &mut String, heap: &crate::descriptor::Heap, label: &str, address: u64, len: usize) {
use std::fmt::Write;
let mut bytes = vec![0u8; len.min(512) & !3];
if bytes.is_empty() || !crate::host::read_into(address as *const u8, &mut bytes) {
let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}: unreadable");
return;
}
let words: Vec<u32> =
bytes.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect();
let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}:");
for w in &words {
let _ = write!(text, " {w:08x}");
}
for (i, &index) in words.iter().enumerate() {
let names = index != 0
&& heap
.handle(index)
.and_then(crate::descriptor::view)
.as_ref()
.is_some_and(crate::descriptor::host::is_texture_view);
if names {
text.push_str(&Self::slot_line(heap, label, i * 4, index));
}
}
}
/// One `~slot` line: where the slot number was read (`from`, byte
/// `at`), what the title's heap holds in slot `index` with the state
/// of that texture ([`view_state`]), what the host slot was made from,
/// and what the queue of textures picked by index knows of it.
#[cfg(feature = "diagnostics")]
fn slot_line(heap: &crate::descriptor::Heap, from: &str, at: usize, index: u32) -> String {
let title = heap.handle(index).and_then(crate::descriptor::view);
let host: String = heap
.host()
.and_then(|h| h.describe_slot(index))
.unwrap_or_else(|| "none".into())
.chars()
.take(90)
.collect();
let queue = match heap.host() {
Some(h) => h.texture_slot_state(index, crate::frame::current()),
None => "no host heap".into(),
};
format!(
"\n ~slot from={from}+{at:#x} slot={index} title=[{}] host=[{host}] queue=[{queue}]",
view_state(title.as_ref())
)
}
/// A mesh draw under `VICTORY_MESH_TEST=scissor` rasterises one pixel:
/// the scissors before it (`on`), the title's after it.
fn mesh_scissor(&self, list: &HostList, on: bool) {
@@ -2028,6 +2312,74 @@ impl State {
}
}
/// The walls trace (`crate::host::walls_trace`): one log line per
/// frame with the draws of its main pass (four or more colour targets)
/// by scissor rectangle, and how often each of the title's culling
/// programs was dispatched. The title clips what it draws
/// through a window or door to that opening's rectangle while it holds
/// the camera to be in a room (run 182, frame 1529: 1,386 draws under
/// `531 0 1789 1337`); in a launch without the room's walls the same
/// shot has no such rectangle (run 187, frame 1414). The line shows
/// the frame in which that changes.
fn walls_census(&self, p: &HostPipeline, compute: bool) {
const CULL: [(&str, &str); 9] = [
("55679a0547649d0b", "tree"),
("89d08e561897d4e5", "tree_imposter"),
("9209777e8face9dd", "grass"),
("17af15c4015cb4b6", "prop"),
("fdd56d97a806bcca", "prop_nocull"),
("42f717f1b4d18e94", "simple"),
("1c4b3c0547e3e6fa", "slod"),
("9146291b38ea9ce1", "meshlet_args"),
("42683eebec081520", "depth_pyramid_cpu_occlusion"),
];
type Census = (u64, std::collections::BTreeMap<[i32; 4], u32>, [u32; 9]);
static CENSUS: std::sync::Mutex<Census> =
std::sync::Mutex::new((u64::MAX, std::collections::BTreeMap::new(), [0; 9]));
let frame = crate::frame::current();
let mut census = CENSUS.lock().unwrap_or_else(|e| e.into_inner());
if census.0 != frame {
let draws: u32 = census.1.values().sum();
if draws > 0 {
let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect();
rects.sort_unstable_by(|a, b| b.1.cmp(&a.1));
let scissors: Vec<String> = rects
.iter()
.take(5)
.map(|(r, n)| format!("{} {} {} {} x{n}", r[0], r[1], r[2], r[3]))
.collect();
let counts = census.2;
let culling: Vec<String> = CULL
.iter()
.zip(counts)
.filter(|(_, n)| *n > 0)
.map(|(c, n)| format!("{}={n}", c.1))
.collect();
tracing::info!(
frame = census.0,
main_pass_draws = draws,
rectangles = rects.len(),
scissors = ?scissors,
culling = ?culling,
"walls trace: the frame's main pass by scissor rectangle, and its culling dispatches"
);
}
census.0 = frame;
census.1.clear();
census.2 = [0; 9];
}
if compute {
for (i, c) in CULL.iter().enumerate() {
if p.stages.iter().any(|s| s.shader.hash.as_str() == c.0) {
census.2[i] += 1;
}
}
} else if self.targets.iter().filter(|&&t| t != 0).count() >= 4 {
let r = self.scissors.first().map_or([0; 4], |r| [r.left, r.top, r.right, r.bottom]);
*census.1.entry(r).or_insert(0) += 1;
}
}
fn roots_ref(&self, compute: bool) -> &Vec<Root> {
if compute {
&self.compute
@@ -2823,6 +3175,109 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) {
}
}
/// The pixel shaders whose draws get their slots listed
/// ([`State::slots_text`]): `VICTORY_LIST_SLOTS`, hash prefixes separated
/// by commas. None by default.
#[cfg(feature = "diagnostics")]
fn list_slots() -> &'static [String] {
static LIST: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
LIST.get_or_init(|| {
std::env::var("VICTORY_LIST_SLOTS")
.unwrap_or_default()
.split(',')
.map(|s| s.trim().to_ascii_lowercase())
.filter(|s| !s.is_empty())
.collect()
})
}
/// A fingerprint of the 4 KiB of title memory at `at` (FNV-1a, 64 bits; of
/// 4 KiB of zeros it is always the same value, which `slots.py` knows), or
/// "unreadable".
#[cfg(feature = "diagnostics")]
fn print_4k(at: u64) -> String {
let mut bytes = [0u8; 4096];
if at == 0 || !crate::host::read_into(at as *const u8, &mut bytes) {
return "unreadable".into();
}
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
for b in bytes {
hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
}
format!("{hash:016x}")
}
/// The `bytes` of title memory at `at`: how many are mapped, and the
/// fingerprints of the first and the last 4 KiB (a texture's smallest
/// levels lie first, its largest last).
#[cfg(feature = "diagnostics")]
fn memory_state(at: u64, bytes: u64) -> String {
let mapped = crate::texture::mapped_bytes(at as *const u8, bytes as usize);
let last = at + bytes.saturating_sub(4096);
format!("memory={at:#x} mapped={mapped}/{bytes} first4k={} last4k={}", print_4k(at), print_4k(last))
}
/// Title texture `this` for the frame listing: its size, whether it has a
/// host copy (not made here), its staging buffer's state, whether the host
/// copied into it, and its memory ([`memory_state`]).
#[cfg(feature = "diagnostics")]
fn texture_state(this: This) -> String {
let Some((at, desc)) = crate::resource::texture_memory(this) else {
return "not a texture".into();
};
// SAFETY: 56 bytes in the description's layout.
let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() };
let bytes = crate::resource::placed_bytes(&words).unwrap_or(0);
let staged = match crate::texture::staged_state(this) {
Some((uploaded, dirty)) => format!("staged=yes uploaded={uploaded} dirty={dirty}"),
None => "staged=no".into(),
};
format!(
"{}x{} f{} levels={} host_copy={} {staged} host_written={} title_fills={} {}",
u64::from(words[4]) | u64::from(words[5]) << 32,
words[6],
words[8],
words[7] >> 16,
crate::resource::host_made(this).is_some(),
crate::texture::host_wrote(this as usize),
crate::resource::title_fills(this),
memory_state(at as u64, bytes)
)
}
/// A view of the title's heap for the frame listing: a texture with its
/// state ([`texture_state`]; a placed one that has no resource yet with
/// its memory alone), anything else in a few words.
#[cfg(feature = "diagnostics")]
fn view_state(view: Option<&View>) -> String {
match view {
None => "no view".into(),
Some(View::Placed(false, r, d)) if r[0] != 1 => {
let address = u64::from(d[10]) | u64::from(d[11]) << 32;
let state = match crate::resource::texture_at_made(address, r) {
Some(this) => texture_state(this),
None => format!(
"{}x{} f{} levels={} resource=none {}",
u64::from(r[4]) | u64::from(r[5]) << 32,
r[6],
r[8],
r[7] >> 16,
memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0))
),
};
format!("placed texture view_format={} {state}", d[0])
}
Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => {
format!(
"texture object {r:#x} view_format={} {}",
d.as_ref().map_or(0, |d| d[0]),
texture_state(*r as This)
)
}
Some(v) => format!("{v:?}").chars().take(80).collect(),
}
}
/// A view in a few words (diagnostics builds).
#[cfg(feature = "diagnostics")]
fn describe(view: Option<&View>) -> String {
+110 -4
View File
@@ -2871,6 +2871,19 @@ fn declared_writes(runs: &[&HostList]) -> Vec<Declared> {
back
}
/// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log
/// lines that say what the title's CPU was given while it decided whether
/// the camera is in a room. The values of the small read-backs
/// ([`read_backs`]), the frame's main pass by scissor rectangle with its
/// culling dispatches (`draw.rs`, `walls_census`), the shader-written
/// buffers merged into title memory (`shadow.rs`, `walls_merged`), host
/// copies found stale after their refresh (`shadow.rs`), and, in the
/// runtime, the read requests that fail (with 2: every request).
pub(crate) fn walls_trace() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2"))
}
/// After `list` has run: the texels its read-backs copied into host
/// buffers of ours go to the title's memory (`HostList::defer_read_back`).
///
@@ -2890,6 +2903,19 @@ fn read_backs(list: &HostList) {
for line in 0..*rows {
std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row);
}
// The walls trace: what the title is handed (one row of at
// most 24 values: its 5x1 and 1x1 float targets).
if walls_trace() && *rows == 1 && *row <= 96 {
let mut values = [0f32; 24];
std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::<u8>(), *row & !3);
tracing::info!(
frame = crate::frame::current(),
to = format_args!("{:#x}", *at),
bytes = *row,
values = ?&values[..*row / 4],
"walls trace: a read-back lands in title memory"
);
}
buffer.Unmap(0, None);
}
}
@@ -3651,7 +3677,9 @@ impl Host {
// SAFETY: the mapping of the fetched bytes, `total` of them;
// the copy into it has run.
let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) };
written += shadow.card_merge_relay(*lo, gpu, after, &mut title);
let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title);
shadow.walls_merged(gpu.len(), merged);
written += merged;
}
COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
// Sends up to `after` are of no use to any later merge.
@@ -3880,7 +3908,9 @@ impl Host {
// the copy into it has run, and the caller
// waits for this job.
let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) };
counts[i].fetch_add(shadow.card_merge(lo, gpu, &mut title), Ordering::Relaxed);
let merged = shadow.card_merge(lo, gpu, &mut title);
shadow.walls_merged(gpu.len(), merged);
counts[i].fetch_add(merged, Ordering::Relaxed);
}
}) as Box<dyn FnOnce() + Send>
})
@@ -3895,7 +3925,9 @@ impl Host {
// SAFETY: the mapping of the fetched bytes, `total` of
// them; the copy into it has run.
let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) };
written[i] += plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title);
plan.ranges[i].shadow.walls_merged(gpu.len(), merged);
written[i] += merged;
}
}
}
@@ -6381,7 +6413,17 @@ impl Host {
.ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
};
match resized {
Ok(()) => (p.width, p.height, p.format) = (width, height, format),
Ok(()) => {
(p.width, p.height, p.format) = (width, height, format);
tracing::info!(
width,
height,
format = format.0,
frame,
"the swap chain's buffers were made again for another size or format"
);
self.log_video_memory("right after the swap chain's buffers were made again");
}
Err(e) => {
tracing::warn!(error = %e, width, height, "swap chain not resized");
return None;
@@ -6477,6 +6519,7 @@ impl Host {
Some(hwnd) => hwnd,
None => window(width, height)?,
};
self.log_video_memory("right before the swap chain is made");
// SAFETY: plain object creation for our window.
unsafe {
let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
@@ -6499,6 +6542,7 @@ impl Host {
let copy = self.new_list()?;
copy.close();
tracing::info!(width, height, format = format.0, "presenting to a window");
self.log_video_memory("right after the swap chain is made");
Ok(Presenter {
swap_chain,
width,
@@ -6578,9 +6622,71 @@ impl Host {
.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
.ok()?;
}
// The card's budget moved by 256 MB or more since the last look:
// said at once, with what was in use at the last look, so the log
// has the moment. (It fell from 11,242 MB to some 10,300 MB with
// the first world frame in runs 179 to 185, and the memory line,
// seconds later, was the first to show it. We reserve nothing
// and make the swap chain once, at the start.)
static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage];
let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed));
if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) {
tracing::info!(
"the system changed the budget of the card's memory from {} MB to {} MB (frame {}); at the last look {} MB of the card's and {} MB of the PC's shared memory were in use",
last[0] >> 20,
own.Budget >> 20,
crate::frame::current(),
last[1] >> 20,
last[2] >> 20
);
self.log_video_memory("right after that change");
}
Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage])
}
/// Both of the system's memory groups for this process, in bytes: for
/// the card's own memory and then for the PC's memory shared with the
/// card, the budget, the use, what could still be reserved and what
/// is reserved (the layer reserves none).
pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> {
let adapter = self.adapter.as_ref()?;
let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
// SAFETY: plain queries that fill our structures.
unsafe {
adapter
.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
.ok()?;
adapter
.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared)
.ok()?;
}
let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| {
[m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation]
};
Some([all(&own), all(&shared)])
}
/// Logs [`Self::video_memory_groups`], with `when` it is said.
pub(crate) fn log_video_memory(&self, when: &str) {
let Some([own, shared]) = self.video_memory_groups() else {
return;
};
tracing::info!(
"video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved; the PC's shared with the card: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved (the layer reserves none)",
when,
own[0] >> 20,
own[1] >> 20,
own[2] >> 20,
own[3] >> 20,
shared[0] >> 20,
shared[1] >> 20,
shared[2] >> 20,
shared[3] >> 20
);
}
/// A buffer in system memory that the CPU maps (write-back, so reading
/// it is fast too) and shaders read and write: for host copies of title
/// memory that shaders write, which upload memory cannot be. Starts in
+601
View File
@@ -1721,3 +1721,604 @@ void main() {
/// The benchmark of the clamp and its barriers (ignored by default).
#[cfg(test)]
mod bench;
/// What one small draw costs this card, bare and with one thing changed
/// between every two draws: a measurement, not a check (it asserts only
/// that the card answered). The timing run of the lit scene (run 187) has
/// some 11,000 small commands a frame at 5 to 16 microseconds each, and no
/// log says whether that is what we put around a command or what the card
/// takes for one. Each variant here is 10,000 one-triangle draws into a
/// 2560x1440 target, timed on the card by one pair of timestamps around
/// the whole batch (not one per command, which would time the stamps).
///
/// Run by name, no game needed:
/// `cargo test -p victory-gpu --release -- --ignored bare_command_cost --nocapture`
#[cfg(test)]
mod bare_cost {
use windows::Win32::Foundation::{HANDLE, RECT};
use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY};
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::Win32::Graphics::Dxgi::*;
use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
use windows::core::{Interface, s};
use crate::host::{compile, transition};
/// Draws in a batch.
const DRAWS: u32 = 10_000;
const WIDTH: u32 = 2560;
const HEIGHT: u32 = 1440;
/// One small triangle in the middle of the target (about 180 pixels),
/// and two pixel programs that read one texel of a texture through a
/// table, so that the view heap set is in use.
const DRAW: &str = r#"
#define RS "DescriptorTable(SRV(t0))"
Texture2D<float4> image : register(t0);
[RootSignature(RS)]
float4 corner(uint i : SV_VertexID) : SV_Position {
float2 p = float2((i << 1) & 2, i & 2);
return float4(p * 0.02 - 0.01, 0.5, 1.0);
}
[RootSignature(RS)]
float4 first(float4 at : SV_Position) : SV_Target {
return image.Load(int3(0, 0, 0));
}
[RootSignature(RS)]
float4 second(float4 at : SV_Position) : SV_Target {
return 1.0 - image.Load(int3(0, 0, 0));
}
"#;
/// A compute pass of next to nothing, as our clamp of an indirect
/// record is: one group of one thread that writes one word.
const WORK: &str = r#"
#define RS "UAV(u0)"
RWByteAddressBuffer words : register(u0);
[RootSignature(RS)]
[numthreads(1, 1, 1)]
void work() {
words.Store(0, words.Load(0) + 1);
}
"#;
/// What changes between every two draws of a batch.
#[derive(Clone, Copy, PartialEq)]
enum Between {
/// Nothing.
Nothing,
/// The pipeline: two alternate.
Pipeline,
/// A second texture goes from target to shader read and back.
BarrierPair,
/// The depth texture bound for testing goes from write to read or
/// back.
DepthMove,
/// The pair of descriptor heaps: two pairs alternate.
Heaps,
/// The colour target: two alternate.
Targets,
/// A compute pass of ours of one group, and the pipeline back.
Compute,
/// The same between two waits for every earlier shader write, as
/// the clamp records them.
ComputeWithWaits,
}
struct Rig {
queue: ID3D12CommandQueue,
allocator: ID3D12CommandAllocator,
list: ID3D12GraphicsCommandList,
fence: ID3D12Fence,
submitted: u64,
event: HANDLE,
root: ID3D12RootSignature,
pipelines: [ID3D12PipelineState; 2],
work_root: ID3D12RootSignature,
work: ID3D12PipelineState,
words: ID3D12Resource,
other: ID3D12Resource,
depth: ID3D12Resource,
/// Kept alive: the views below name them.
_kept: Vec<ID3D12Resource>,
_target_heaps: [ID3D12DescriptorHeap; 2],
heap_pairs: [[Option<ID3D12DescriptorHeap>; 2]; 2],
tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2],
targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2],
depth_written: D3D12_CPU_DESCRIPTOR_HANDLE,
depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE,
stamps: ID3D12QueryHeap,
back: ID3D12Resource,
card: String,
}
fn texture(
device: &ID3D12Device,
(width, height): (u32, u32),
format: DXGI_FORMAT,
flags: D3D12_RESOURCE_FLAGS,
state: D3D12_RESOURCE_STATES,
) -> ID3D12Resource {
let heap = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_DEFAULT,
..Default::default()
};
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: u64::from(width),
Height: height,
DepthOrArraySize: 1,
MipLevels: 1,
Format: format,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Flags: flags,
..Default::default()
};
let mut out: Option<ID3D12Resource> = None;
// SAFETY: plain texture creation.
unsafe {
device
.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out)
.unwrap();
}
out.unwrap()
}
fn buffer(
device: &ID3D12Device,
size: u64,
kind: D3D12_HEAP_TYPE,
flags: D3D12_RESOURCE_FLAGS,
state: D3D12_RESOURCE_STATES,
) -> ID3D12Resource {
let heap = D3D12_HEAP_PROPERTIES {
Type: kind,
..Default::default()
};
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: flags,
..Default::default()
};
let mut out: Option<ID3D12Resource> = None;
// SAFETY: plain buffer creation.
unsafe {
device
.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out)
.unwrap();
}
out.unwrap()
}
fn heap(device: &ID3D12Device, kind: D3D12_DESCRIPTOR_HEAP_TYPE, count: u32, visible: bool) -> ID3D12DescriptorHeap {
let flags = if visible {
D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE
} else {
D3D12_DESCRIPTOR_HEAP_FLAG_NONE
};
// SAFETY: plain heap creation.
unsafe {
device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: kind,
NumDescriptors: count,
Flags: flags,
NodeMask: 0,
})
.unwrap()
}
}
fn pipeline(device: &ID3D12Device, root: &ID3D12RootSignature, vs: &[u8], ps: &[u8]) -> ID3D12PipelineState {
let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
pShaderBytecode: bytes.as_ptr().cast(),
BytecodeLength: bytes.len(),
};
let mut blend = D3D12_BLEND_DESC::default();
blend.RenderTarget[0].RenderTargetWriteMask = 0xf;
let mut formats = [DXGI_FORMAT(0); 8];
formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
// SAFETY: the description points at live data and never releases
// its pointer to the root signature.
unsafe {
let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(root),
VS: code(vs),
PS: code(ps),
BlendState: blend,
SampleMask: u32::MAX,
RasterizerState: D3D12_RASTERIZER_DESC {
FillMode: D3D12_FILL_MODE_SOLID,
CullMode: D3D12_CULL_MODE_NONE,
DepthClipEnable: true.into(),
..Default::default()
},
// Depth is tested and never written, so the texture may be
// in the write state or in the read state under one view.
DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
DepthEnable: true.into(),
DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO,
DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL,
..Default::default()
},
PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
NumRenderTargets: 1,
RTVFormats: formats,
DSVFormat: DXGI_FORMAT_D32_FLOAT,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
..Default::default()
};
device.CreateGraphicsPipelineState(&desc).unwrap()
}
}
impl Rig {
/// The default adapter, as the layer takes it; `None` without one
/// or on a software adapter.
fn new() -> Option<Self> {
let vs = compile(DRAW, s!("corner"), s!("vs_5_1")).ok()?;
let ps = [
compile(DRAW, s!("first"), s!("ps_5_1")).ok()?,
compile(DRAW, s!("second"), s!("ps_5_1")).ok()?,
];
let cs = compile(WORK, s!("work"), s!("cs_5_1")).ok()?;
// SAFETY: plain object creation on a device of our own; the
// views are made in heaps that live as long as the rig.
unsafe {
let mut device: Option<ID3D12Device> = None;
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?;
let device = device?;
let desc = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
.and_then(|factory| factory.EnumAdapterByLuid::<IDXGIAdapter3>(device.GetAdapterLuid()))
.ok()?
.cast::<IDXGIAdapter1>()
.ok()?
.GetDesc1()
.ok()?;
if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 {
return None;
}
let card = String::from_utf16_lossy(&desc.Description)
.trim_end_matches('\0')
.to_owned();
let queue: ID3D12CommandQueue = device
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
..Default::default()
})
.ok()?;
let allocator: ID3D12CommandAllocator =
device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?;
let list: ID3D12GraphicsCommandList = device
.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
.ok()?;
let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
let event = CreateEventW(None, false, false, None).ok()?;
let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs[..]).ok()?;
let pipelines = [
pipeline(&device, &root, &vs, &ps[0]),
pipeline(&device, &root, &vs, &ps[1]),
];
let work_root: ID3D12RootSignature = device.CreateRootSignature(0, &cs[..]).ok()?;
let work: ID3D12PipelineState = device
.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&work_root),
CS: D3D12_SHADER_BYTECODE {
pShaderBytecode: cs.as_ptr().cast(),
BytecodeLength: cs.len(),
},
..Default::default()
})
.ok()?;
let size = (WIDTH, HEIGHT);
let colour = |state| texture(&device, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, state);
let target = [
colour(D3D12_RESOURCE_STATE_RENDER_TARGET),
colour(D3D12_RESOURCE_STATE_RENDER_TARGET),
];
let other = colour(D3D12_RESOURCE_STATE_RENDER_TARGET);
let depth = texture(
&device,
size,
DXGI_FORMAT_D32_FLOAT,
D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
D3D12_RESOURCE_STATE_DEPTH_WRITE,
);
let image = texture(
&device,
(4, 4),
DXGI_FORMAT_R8G8B8A8_UNORM,
D3D12_RESOURCE_FLAG_NONE,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
);
let words = buffer(
&device,
64 << 10,
D3D12_HEAP_TYPE_DEFAULT,
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
);
let back = buffer(
&device,
16,
D3D12_HEAP_TYPE_READBACK,
D3D12_RESOURCE_FLAG_NONE,
D3D12_RESOURCE_STATE_COPY_DEST,
);
let mut stamps: Option<ID3D12QueryHeap> = None;
device
.CreateQueryHeap(
&D3D12_QUERY_HEAP_DESC {
Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP,
Count: 2,
NodeMask: 0,
},
&mut stamps,
)
.ok()?;
let stamps = stamps?;
// Target and depth views.
let rtvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, false);
let rtv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize;
let mut targets = [rtvs.GetCPUDescriptorHandleForHeapStart(); 2];
targets[1].ptr += rtv_step;
device.CreateRenderTargetView(&target[0], None, targets[0]);
device.CreateRenderTargetView(&target[1], None, targets[1]);
let dsvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, false);
let dsv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize;
let depth_written = dsvs.GetCPUDescriptorHandleForHeapStart();
let mut depth_tested = depth_written;
depth_tested.ptr += dsv_step;
device.CreateDepthStencilView(&depth, None, depth_written);
let tested = D3D12_DEPTH_STENCIL_VIEW_DESC {
Format: DXGI_FORMAT_D32_FLOAT,
ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH,
..Default::default()
};
device.CreateDepthStencilView(&depth, Some(&tested), depth_tested);
// Two pairs of shader-visible heaps: views (one view of the
// small texture each) and samplers (none used).
let view_heaps = [
heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true),
heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true),
];
let sampler_heaps = [
heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true),
heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true),
];
for views in &view_heaps {
device.CreateShaderResourceView(&image, None, views.GetCPUDescriptorHandleForHeapStart());
}
let tables = [
view_heaps[0].GetGPUDescriptorHandleForHeapStart(),
view_heaps[1].GetGPUDescriptorHandleForHeapStart(),
];
let heap_pairs = [
[Some(view_heaps[0].clone()), Some(sampler_heaps[0].clone())],
[Some(view_heaps[1].clone()), Some(sampler_heaps[1].clone())],
];
// The first list: both targets and the depth texture cleared.
list.ClearRenderTargetView(targets[0], &[0.0; 4], None);
list.ClearRenderTargetView(targets[1], &[0.0; 4], None);
list.ClearDepthStencilView(depth_written, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None);
let [first_target, second_target] = target;
let mut rig = Rig {
queue,
allocator,
list,
fence,
submitted: 0,
event,
root,
pipelines,
work_root,
work,
words,
other,
depth,
_kept: vec![first_target, second_target, image],
_target_heaps: [rtvs, dsvs],
heap_pairs,
tables,
targets,
depth_written,
depth_tested,
stamps,
back,
card,
};
rig.finish();
Some(rig)
}
}
/// Closes the open list, runs it, waits for the card and opens the
/// list again.
fn finish(&mut self) {
self.submitted += 1;
// SAFETY: our list, queue and fence; the allocator is reset
// only after the card finished everything recorded from it.
unsafe {
self.list.Close().unwrap();
let run: ID3D12CommandList = self.list.cast().unwrap();
self.queue.ExecuteCommandLists(&[Some(run)]);
self.queue.Signal(&self.fence, self.submitted).unwrap();
self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap();
WaitForSingleObject(self.event, INFINITE);
self.allocator.Reset().unwrap();
self.list.Reset(&self.allocator, None).unwrap();
}
}
/// What every list starts with: a new list has nothing set.
fn begin(&self) {
let l = &self.list;
// SAFETY: an open list and live objects and views.
unsafe {
l.SetDescriptorHeaps(&self.heap_pairs[0]);
l.SetGraphicsRootSignature(&self.root);
l.SetPipelineState(&self.pipelines[0]);
l.SetGraphicsRootDescriptorTable(0, self.tables[0]);
l.OMSetRenderTargets(1, Some(&self.targets[0]), false, Some(&self.depth_tested));
l.RSSetViewports(&[D3D12_VIEWPORT {
TopLeftX: 0.0,
TopLeftY: 0.0,
Width: WIDTH as f32,
Height: HEIGHT as f32,
MinDepth: 0.0,
MaxDepth: 1.0,
}]);
l.RSSetScissorRects(&[RECT {
left: 0,
top: 0,
right: WIDTH as i32,
bottom: HEIGHT as i32,
}]);
// A triangle list.
l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4));
}
}
/// One batch of [`DRAWS`] draws in `lists` lists run one by one,
/// with `between` recorded before every draw: the microseconds a
/// draw took on the card, and the milliseconds recording took.
fn batch(&mut self, between: Between, lists: u32) -> (f64, f64) {
let (target, read, written, tested) = (
D3D12_RESOURCE_STATE_RENDER_TARGET,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
D3D12_RESOURCE_STATE_DEPTH_WRITE,
D3D12_RESOURCE_STATE_DEPTH_READ,
);
let started = std::time::Instant::now();
let mut drawn = 0u32;
for part in 0..lists {
let l = &self.list;
// SAFETY: an open list; our query heap; live objects.
unsafe {
if part == 0 {
l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0);
}
}
self.begin();
// SAFETY: an open list with everything set; live objects.
// Every state moved is moved back within the batch (the
// draws of a list are an even number).
unsafe {
for _ in 0..DRAWS / lists {
let odd = (drawn % 2) as usize;
match between {
Between::Nothing => {}
Between::Pipeline => l.SetPipelineState(&self.pipelines[odd]),
Between::BarrierPair => {
l.ResourceBarrier(&[transition(&self.other, target, read)]);
l.ResourceBarrier(&[transition(&self.other, read, target)]);
}
Between::DepthMove => {
let (from, to) = if odd == 0 { (written, tested) } else { (tested, written) };
l.ResourceBarrier(&[transition(&self.depth, from, to)]);
}
Between::Heaps => {
l.SetDescriptorHeaps(&self.heap_pairs[odd]);
l.SetGraphicsRootDescriptorTable(0, self.tables[odd]);
}
Between::Targets => {
l.OMSetRenderTargets(1, Some(&self.targets[odd]), false, Some(&self.depth_tested));
}
Between::Compute | Between::ComputeWithWaits => {
let waits = between == Between::ComputeWithWaits;
if waits {
l.ResourceBarrier(&[super::uav_barrier()]);
}
l.SetComputeRootSignature(&self.work_root);
l.SetPipelineState(&self.work);
l.SetComputeRootUnorderedAccessView(0, self.words.GetGPUVirtualAddress());
l.Dispatch(1, 1, 1);
if waits {
l.ResourceBarrier(&[super::uav_barrier()]);
}
l.SetPipelineState(&self.pipelines[0]);
}
}
l.DrawInstanced(3, 1, 0, 0);
drawn += 1;
}
if part + 1 < lists {
// The next list of the batch: this one is sent on
// its own and the list is opened again at once
// (the allocator is not reset before the card is
// done with all of them).
l.Close().unwrap();
let run: ID3D12CommandList = l.cast().unwrap();
self.queue.ExecuteCommandLists(&[Some(run)]);
l.Reset(&self.allocator, None).unwrap();
} else {
l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1);
l.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0);
}
}
}
let recording = started.elapsed().as_secs_f64() * 1e3;
self.finish();
let mut data = std::ptr::null_mut();
let range = D3D12_RANGE { Begin: 0, End: 16 };
// SAFETY: a read-back buffer the finished list resolved two
// timestamps into.
let ticks = unsafe {
self.back.Map(0, Some(&range), Some(&mut data)).unwrap();
let stamps = std::slice::from_raw_parts(data.cast::<u64>(), 2).to_vec();
self.back.Unmap(0, None);
stamps[1].saturating_sub(stamps[0])
};
// SAFETY: a plain query of our queue.
let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1).max(1);
(ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), recording)
}
}
#[test]
#[ignore = "a measurement on the card: run it by name with --ignored --nocapture"]
fn bare_command_cost() {
let Some(mut rig) = Rig::new() else {
eprintln!("no hardware adapter, or our shaders did not compile; skipped");
return;
};
eprintln!("bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", rig.card);
// The first batch pays for whatever the driver does at first use.
rig.batch(Between::Nothing, 1);
let variants = [
("(a) nothing changes between draws", Between::Nothing, 1),
("(b) another pipeline every draw", Between::Pipeline, 1),
("(c) a barrier pair on a second texture every draw", Between::BarrierPair, 1),
("(d) the tested depth texture moved between write and read every draw", Between::DepthMove, 1),
("(e) another pair of descriptor heaps every draw", Between::Heaps, 1),
("(f) another colour target every draw", Between::Targets, 1),
("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100),
("(h) a compute pass of ours of one group before every draw", Between::Compute, 1),
("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1),
];
let mut least = Vec::new();
for (name, between, lists) in variants {
let mut runs: Vec<(f64, f64)> = (0..3).map(|_| rig.batch(between, lists)).collect();
runs.sort_by(|a, b| a.0.total_cmp(&b.0));
eprintln!(
"{name}: {:.2} microseconds a draw on the card (the three: {:.2}, {:.2}, {:.2}); recording took {:.1} ms",
runs[0].0, runs[0].0, runs[1].0, runs[2].0, runs[0].1
);
least.push(runs[0].0);
}
assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch");
}
}
+217
View File
@@ -1414,6 +1414,210 @@ fn room_percent() -> u64 {
})
}
/// For the card accounting line ([`card_accounting`]): the title texture
/// made for a view of memory at `address` with the resource description
/// `desc`, if there is one ([`texture_at`] makes it; this does not).
#[cfg(windows)]
pub(crate) fn placed_known(address: u64, desc: &[u32; 14]) -> Option<This> {
// Without the filler words and with them: whichever `texture_at` keeps.
let mut key = *desc;
key[1] = 0;
key[13] = 0;
let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
map.get(&(address, key)).or_else(|| map.get(&(address, *desc))).map(|&r| r as This)
}
/// For the card accounting line: whether title texture `this` has a host
/// copy now (2), had one that was let go and not made again (1), or never
/// had one (0); the bytes (its host copy's on the card, or without one
/// what its console layout takes in title memory); and where its title
/// memory is. `None` for buffers. Not a use of the texture.
#[cfg(windows)]
pub(crate) fn copy_state(this: This) -> Option<(u8, u64, u64)> {
use std::sync::atomic::Ordering::Relaxed;
if this.is_null() {
return None;
}
let r = resource(this);
if r.desc.dimension == BUFFER {
return None;
}
let memory = r.data() as u64;
let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
Some(match made.as_ref() {
Some((host, _)) => (2, host.bytes, memory),
None => (u8::from(r.host.gone.load(Relaxed)), footprint(&r.desc).map_or(0, |f| f.size), memory),
})
}
/// One line of where the card's memory is and what the queue of textures
/// picked by index would need (`VICTORY_CARD_ACCOUNTING=1`; `draw.rs`
/// `card_accounting` says when, and hands over the queue's side: `room`
/// as the pass found it, `due` its counts, `never` and `gone` the memory
/// of the due textures without a host copy). The line holds
/// - the host copies of textures the title fills that are alive: how
/// many, their bytes, and the bytes of the levels whose title memory is
/// not mapped (a host copy is made with every level of the description;
/// a texture streaming in has its small levels only). A copy's bytes
/// are shared out to its levels by their texels, so that part is an
/// estimate;
/// - the due slots: how many, and their textures by what they have on
/// the card (a host copy alive: no card memory needed; never one; one
/// that was let go), with the bytes the last two would need and how
/// much of their memory is mapped now;
/// - the host copies let go, made again and made since the line before.
///
/// The textures are noted under the table's lock (their memory, their
/// description, their copy's bytes: about a millisecond for 18,000) and
/// the kernel is asked about their memory on a thread of its own, after
/// the lock is given back: one question for a texture that is all there
/// (up to 256 pages each; 18,000 textures of 5.5 GB are 1.4 million
/// pages, some 20,000 questions), one per level and array slice more for
/// one that is not. Not measured: a tenth to half a second is expected,
/// and the line says what it took. No line is begun while one is walking.
#[cfg(windows)]
pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, gone: Vec<(u64, u64)>) {
use std::sync::atomic::Ordering::Relaxed;
static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
// Host copies let go and their bytes, made again and their bytes, and
// made in all, at the line before.
static BEFORE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
if WALKING.swap(true, Relaxed) {
return;
}
let began = std::time::Instant::now();
let mut copies: Vec<(usize, ResourceDesc, u64)> = Vec::new();
// Textures the title fills without a host copy: never one, one let go.
let mut without = [0u64; 2];
{
let all = textures();
for &at in all.iter() {
// SAFETY: as in `let_go_idle`.
let r = unsafe { &*(at as *const Resource) };
if !fills(&r.desc) {
continue;
}
let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
match made.as_ref() {
Some((host, _)) => copies.push((r.data() as usize, r.desc, host.bytes)),
None => without[usize::from(r.host.gone.load(Relaxed))] += 1,
}
}
}
let kinds = KINDS.each_ref().map(|k| k.load(Relaxed));
let mut since = [0u64; 5];
for ((slot, now), before) in since.iter_mut().zip([kinds[2], kinds[3], kinds[4], kinds[5], kinds[6]]).zip(&BEFORE) {
*slot = now.saturating_sub(before.swap(now, Relaxed));
}
let video = crate::host::host().and_then(|h| h.video_memory());
let noted_us = began.elapsed().as_micros() as u64;
let walk = move || {
fn texels(m: &texture::Mip) -> u64 {
u64::from(m.width) * u64::from(m.height) * u64::from(m.depth)
}
let began = std::time::Instant::now();
// Copies; their bytes; the bytes of levels not mapped; copies with
// a level not mapped; with the largest level not mapped; with no
// level mapped; copies without a console layout (not asked).
let mut c = [0u64; 7];
for &(memory, desc, bytes) in &copies {
c[0] += 1;
c[1] += bytes;
let Some(layout) = texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else {
c[6] += 1;
continue;
};
if layout.size == 0 || crate::texture::committed(memory as *const u8, layout.size as usize) {
continue;
}
c[3] += 1;
// Every slice holds the whole chain: the levels of the tail in
// its first block, the others after it from the smallest up
// (`victory_formats::texture::Layout`).
let mips = &layout.mips;
let tail = (layout.first_tail_mip as usize).min(mips.len());
let there = |from: u64, to: u64| {
(0..u64::from(layout.slices)).all(|slice| {
let at = memory as u64 + slice * layout.slice_size + from;
crate::texture::committed(at as *const u8, (to - from) as usize)
})
};
let all: u64 = mips.iter().map(texels).sum::<u64>().max(1);
let (mut missing, mut any) = (0u64, false);
for (level, m) in mips.iter().enumerate().take(tail) {
let end = if level == 0 { layout.slice_size } else { mips[level - 1].offset };
if end <= m.offset {
continue;
}
if there(m.offset, end) {
any = true;
} else {
missing += texels(m);
c[4] += u64::from(level == 0);
}
}
if tail < mips.len() {
if there(0, layout.alignment.min(layout.slice_size).max(1)) {
any = true;
} else {
missing += mips[tail..].iter().map(texels).sum::<u64>();
}
}
c[2] += (u128::from(bytes) * u128::from(missing) / u128::from(all)) as u64;
c[5] += u64::from(!any);
}
// Of the due textures without a host copy: how many; the bytes of
// their memory; with all of it mapped, and those bytes; with part
// of it mapped, and the bytes that are; with none of it mapped.
let mapped = |list: &[(u64, u64)]| {
let mut n = [0u64; 7];
for &(at, len) in list {
n[0] += 1;
n[1] += len;
let there = crate::texture::mapped_bytes(at as *const u8, len as usize);
if len > 0 && there >= len {
n[2] += 1;
n[3] += len;
} else if there > 0 {
n[4] += 1;
n[5] += there;
} else {
n[6] += 1;
}
}
n
};
let (never, gone) = (mapped(&never), mapped(&gone));
let [budget_mb, used_mb] = video.map_or([0, 0], |v| [v[0] >> 20, v[1] >> 20]);
let [copies_n, copies_mb, unmapped_mb, partly, largest, nothing, unknown] =
[c[0], c[1] >> 20, c[2] >> 20, c[3], c[4], c[5], c[6]];
let [without_never, without_gone] = without;
let [due_slots, due_uploaded, due_other, alive_n, alive_mb] = [due[0], due[1], due[2], due[3], due[4] >> 20];
let [never_n, never_mb, never_whole, never_whole_mb, never_part, never_part_mb, never_none] =
[never[0], never[1] >> 20, never[2], never[3] >> 20, never[4], never[5] >> 20, never[6]];
let [gone_n, gone_mb, gone_whole, gone_whole_mb, gone_part, gone_part_mb, gone_none] =
[gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]];
let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]];
let walk_ms = began.elapsed().as_millis() as u64;
tracing::info!(
"card accounting: room {room}, the card {used_mb} MB in use of a budget of {budget_mb} MB; host copies of textures the title \
fills: {copies_n} alive {copies_mb} MB, of which {unmapped_mb} MB are levels whose title memory is not mapped ({partly} copies \
with such a level, {largest} of them the largest level, {nothing} with no level mapped; {unknown} without a console layout, not \
asked); title textures without a host copy: {without_never} never had one, {without_gone} had one let go; due slots: \
{due_slots} ({due_uploaded} uploaded before, {due_other} of nothing the title fills), their textures: {alive_n} with a host \
copy alive ({alive_mb} MB, no card memory needed); {never_n} that never had one ({never_mb} MB of title memory: {never_whole} \
all mapped {never_whole_mb} MB, {never_part} in part {never_part_mb} MB mapped, {never_none} not mapped); {gone_n} whose host \
copy was let go ({gone_mb} MB: {gone_whole} all mapped {gone_whole_mb} MB, {gone_part} in part {gone_part_mb} MB mapped, \
{gone_none} not mapped); since the line before: {let_go} host copies let go {let_go_mb} MB, {again} made again {again_mb} MB, \
{made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own"
);
WALKING.store(false, Relaxed);
};
if std::thread::Builder::new().name("card accounting".into()).spawn(walk).is_err() {
WALKING.store(false, Relaxed);
}
}
/// Lets go of the host copies of textures the title fills that nothing
/// names any more: placed textures were never released (one host texture
/// per address and description ever viewed: 18,639 of them, 2.5 GB, after
@@ -2100,6 +2304,19 @@ pub(crate) fn placed_bytes(desc: &[u32; 14]) -> Option<u64> {
footprint(&d).map(|f| f.size)
}
/// The resource [`texture_at`] made for a texture placed at `address` with
/// the description `desc`, if it has made one: never made here (for the
/// frame listing, which must not count as a use).
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option<This> {
let mut key = *desc;
key[1] = 0;
key[13] = 0;
let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
let found = map.get(&(address, key)).or_else(|| map.get(&(address, *desc)))?;
Some(*found as This)
}
/// The resource for a texture placed at `address` with the resource
/// description `desc` (as words), made on first use.
#[cfg(windows)]
+94
View File
@@ -2554,6 +2554,7 @@ impl Shadow {
if let Some((now, written)) = crate::watch::writes(from, to, true) {
self.watched.store(1, Ordering::Relaxed);
let copied = self.copy_stale(from, to, now, &written);
self.refresh_check(from, to);
#[cfg(feature = "diagnostics")]
{
use crate::copystat::{C, add};
@@ -2574,6 +2575,63 @@ impl Shadow {
to - from
}
/// Diagnostic (`VICTORY_REFRESH_CHECK=1`; off by default): after a
/// refresh of `[from, to)` that trusted the write watch or the guards,
/// the first 256 bytes of every 64 KiB block of it are read from title
/// memory and compared with the copy. A block that differs on three
/// refreshes in a row was changed with nothing to tell of it (a write
/// through another view of its pages, as DirectStorage's page
/// destinations make) and the card reads old bytes there: said with
/// the copy and the address. One that differs once is a write of the
/// title's that arrived between the refresh and the look.
fn refresh_check(&self, from: usize, to: usize) {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1") || crate::host::walls_trace()) {
return;
}
const SAMPLE: usize = 256;
// Blocks found differing: how many refreshes in a row.
static DIFFERING: Mutex<Option<std::collections::HashMap<usize, u32>>> = Mutex::new(None);
static SAID: AtomicU64 = AtomicU64::new(0);
let start = self.start as usize;
let mut title = [0u8; SAMPLE];
let mut at = from;
while at < to {
let n = SAMPLE.min(to - at);
if crate::host::read_into(at as *const u8, &mut title[..n]) {
// SAFETY: `[from, to)` lies inside the buffer (`update`),
// so these bytes are inside the copy's mapping.
let copy = unsafe { std::slice::from_raw_parts(self.data.add(at - start).cast_const(), n) };
let mut map = DIFFERING.lock().unwrap_or_else(|e| e.into_inner());
let map = map.get_or_insert_with(Default::default);
if copy == &title[..n] {
map.remove(&at);
} else {
let times = map.entry(at).or_insert(0);
*times += 1;
if *times == 3 {
let said = SAID.fetch_add(1, Ordering::Relaxed) + 1;
if said <= 64 || said.is_power_of_two() {
tracing::warn!(
said,
copy = self.id,
copy_start = format_args!("{start:#x}"),
copy_bytes = self.len,
address = format_args!("{at:#x}"),
refreshed = format_args!("{from:#x}..{to:#x}"),
on_the_card = self.card.is_some(),
window = self.window,
"a host copy of title memory is stale after its refresh, three times in a row: the memory changed with nothing to tell of it (VICTORY_REFRESH_CHECK=1)"
);
}
}
}
}
// The first bytes of the next 64 KiB block.
at = (at / PAGE + 1) * PAGE;
}
}
/// Copies the pages of `[from, to)` written after their last copy
/// (`written`: last writes by page, in page order; `now`: this
/// asking), whole pages within the buffer.
@@ -2693,6 +2751,42 @@ impl Shadow {
card_piece_of(self.start as usize, self.len as usize, span, i)
}
/// The walls trace (`crate::host::walls_trace`): a piece of `fetched`
/// bytes of this copy came back from the card and `written` of them
/// went into title memory. Summed per buffer and logged once a frame:
/// which shader-written buffers the title's CPU could see fresh in
/// that frame, and how much of each changed.
pub(crate) fn walls_merged(&self, fetched: usize, written: usize) {
if !crate::host::walls_trace() {
return;
}
static SEEN: Mutex<(u64, BTreeMap<u64, (u64, u32, u64, u64)>)> = Mutex::new((0, BTreeMap::new()));
let frame = crate::frame::current();
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
if seen.0 != frame {
let buffers: Vec<String> = seen
.1
.iter()
.map(|(at, v)| format!("{at:#x}+{:#x}: {} pieces, {} fetched, {} written", v.0, v.1, v.2, v.3))
.take(32)
.collect();
if !buffers.is_empty() {
tracing::info!(
frame = seen.0,
count = seen.1.len(),
buffers = ?buffers,
"walls trace: shader-written card buffers merged into title memory in this frame"
);
}
seen.1.clear();
seen.0 = frame;
}
let entry = seen.1.entry(self.start).or_insert((self.len, 0, 0, 0));
entry.1 += 1;
entry.2 += fetched as u64;
entry.3 += written as u64;
}
/// After a submission, for a copy in the card's memory: `gpu` is what
/// the card's side holds at offset `at` on, in a piece the compare
/// found differing. The bytes shaders wrote (those that differ from the
+10
View File
@@ -989,6 +989,16 @@ pub(crate) fn fingerprint(at: u64, len: u64) -> u64 {
/// Whether a title texture has a staging buffer: a list recorded its
/// upload, and the lists that sample it check it at submission.
/// For the frame listing: whether a list has uploaded `resource`'s staging
/// buffer, and whether it was detiled since. None: it has none.
#[cfg(feature = "diagnostics")]
pub(crate) fn staged_state(resource: This) -> Option<(bool, bool)> {
use std::sync::atomic::Ordering::Relaxed;
let map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
let staging = map.as_ref()?.get(&(resource as usize))?;
Some((staging.uploaded.load(Relaxed), staging.dirty.load(Relaxed)))
}
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)))
@@ -141,10 +141,12 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out
tracing::warn!(path = name, %error, "dstorage: opening a file failed");
return from_win32(&error);
}
let kept = name.clone();
tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened");
// SAFETY: a handle we just opened and nobody else owns.
let file = unsafe { std::fs::File::from_raw_handle(handle) };
let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file });
WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept));
put(out, file)
}
@@ -440,6 +442,52 @@ impl Scheduler {
}
}
/// The walls trace (`VICTORY_WALLS_TRACE`): 0 or unset: off; 1: a line for
/// every read request that fails, with its file; 2: for every request (the
/// list of a launch's reads, by file and offset, is what a launch with the
/// first room's walls and one without are compared by).
fn walls_trace() -> u8 {
static ON: OnceLock<u8> = OnceLock::new();
*ON.get_or_init(|| {
std::env::var("VICTORY_WALLS_TRACE").ok().and_then(|v| v.trim().parse::<u8>().ok()).unwrap_or(0)
})
}
/// The files opened, by the address of our file object, with their paths
/// (for the walls trace: a request names its file by that address).
static WALLS_FILES: Mutex<Vec<(usize, String)>> = Mutex::new(Vec::new());
/// The walls trace's line for a request that is done.
fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std::time::Instant) {
let level = walls_trace();
if level == 0 || (level == 1 && result.is_ok()) {
return;
}
let file = if request.options & MEMORY_SOURCE != 0 {
"memory".to_string()
} else {
let files = WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner());
let source = request.source as usize;
files.iter().find(|f| f.0 == source).map_or_else(|| "?".to_string(), |f| f.1.clone())
};
let hr = match result {
Ok(()) => 0,
Err(hr) => *hr as u32,
};
tracing::info!(
file,
offset = request.offset,
source_size = request.source_size,
destination_size = request.destination_size,
to_pages = request.options & PAGE_DESTINATION != 0,
options = format_args!("{:#x}", request.options),
ms = started.elapsed().as_millis() as u64,
ok = result.is_ok(),
hr = format_args!("{hr:#010x}"),
"walls trace: a read request is done"
);
}
/// A worker: runs the next read of the most deserving queue.
fn work(scheduler: &'static Scheduler) {
let mut lanes = scheduler.lock();
@@ -451,6 +499,7 @@ fn work(scheduler: &'static Scheduler) {
drop(lanes);
let started = std::time::Instant::now();
let result = execute(&job.request);
walls_request(&job.request, &result, started);
lanes = scheduler.lock();
lanes.finish(&job, result);
lanes.count(&job, started);