Merge local/next (a79e248) into local/tests

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-24 22:38:14 -06:00
commit 9f22d574bc
40 files changed
+12028 -434

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);
+14
View File
@@ -168,6 +168,20 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) {
}
}
/// 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`.
#[cfg(windows)]
pub(crate) fn constant_slot(heap: usize, index: u32, gpu: u64, size: u32) {
let heaps = SHADER_HEAPS.lock().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);
}
}
#[cfg(windows)]
impl Drop for Heap {
fn drop(&mut self) {
+269 -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
@@ -1047,6 +1161,13 @@ impl HostHeap {
buffers.iter().copied().collect()
}
/// Of [`HostHeap::buffer_slots`], those of one of `parts` parts: every
/// slot is in the same part each time.
pub(crate) fn buffer_slots_of(&self, part: u32, parts: u32) -> Vec<u32> {
let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
buffers.iter().copied().filter(|slot| slot % parts == part).collect()
}
/// The title slots whose buffer view was written, or went, since the
/// last call.
pub(crate) fn buffer_changes(&self) -> Vec<u32> {
@@ -1103,7 +1224,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 +1534,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 +2611,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());
+754 -17
View File
@@ -186,6 +186,67 @@ fn windows() -> bool {
*ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1"))
}
/// Whether indirect executions of one record are clamped in batches
/// (`crate::indirect::batch`; `VICTORY_INDIRECT_BATCH=0`: each on its own,
/// or in windows ([`windows`])).
///
/// A frame of gameplay has 4,809 indirect executions (a capture: 3,523 mesh
/// draws, 948 dispatches, 338 draws), and with the windows still 2,355
/// clamps: each a dispatch between two full waits, with the scratch buffer
/// moved twice. The replayed frame's 84.6 ms are 75.3 ms with the clamps in
/// 133 passes, and 77.7 ms in the 980 of this.
///
/// A batch is opened by the first execution after a point where arguments
/// may have changed, and all executions up to the next such point read
/// theirs from it, each exactly the record it asks for (windows guess which
/// are next, and clamp what they do not know). Arguments in buffers change
/// by dispatches and by draws whose shaders store to buffers; those end the
/// batch, so the record an execution reads is clamped after all that was
/// recorded before it, and the pass waits for all of it, exactly as the
/// clamp of its own did. Between two executions of a batch is no wait of
/// ours: there is nothing between them to wait for but draws that store to
/// no buffer.
///
/// `VICTORY_INDIRECT_BATCH=2`: a dispatch does not end the batch before the
/// title waits for it (a barrier, or a pipeline sync) or draws: what a
/// dispatch writes is not there for a later command without a wait, and
/// dispatches the title runs side by side (its tile classes, up to 92 at a
/// time) are not held up by waits of ours. Off: whether the title has ways
/// to wait that do not pass through its lists' methods is not known.
fn batches() -> u8 {
static ON: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
*ON.get_or_init(|| match std::env::var("VICTORY_INDIRECT_BATCH").as_deref() {
Ok("0") => 0,
Ok("2") => 2,
_ => 1,
})
}
/// The records clamped by the pass opened last ([`batches`]).
struct Batch {
table: crate::indirect::batch::Table,
scratch: ID3D12Resource,
/// Dispatches since, which may have written arguments
/// (`VICTORY_INDIRECT_BATCH=2`).
wrote: bool,
}
/// The host copies arguments were read from last: what a batch opens with,
/// as the executions after the first may read theirs from another one.
static ARGUMENT_COPIES: std::sync::Mutex<Vec<std::sync::Weak<crate::shadow::Shadow>>> = std::sync::Mutex::new(Vec::new());
/// [`ARGUMENT_COPIES`] that live, and `first` put in front of them.
fn argument_copies(first: &std::sync::Arc<crate::shadow::Shadow>) -> Vec<(u64, ID3D12Resource)> {
let mut copies = ARGUMENT_COPIES.lock().unwrap_or_else(|e| e.into_inner());
let live: Vec<_> = copies.iter().filter_map(std::sync::Weak::upgrade).filter(|s| s.id() != first.id()).collect();
*copies = std::iter::once(first)
.chain(&live)
.take(crate::indirect::batch::SOURCES)
.map(std::sync::Arc::downgrade)
.collect();
live.iter().map(|s| (s.id(), s.buffer.clone())).collect()
}
/// What one title list has set, and what its host list was last given.
#[derive(Default)]
pub(crate) struct State {
@@ -219,6 +280,9 @@ pub(crate) struct State {
/// The indirect records clamped last, if later draws may still read
/// them ([`windows`]).
window: Option<Window>,
/// The records clamped in a batch, if later executions may still read
/// them ([`batches`]).
batch: Option<Batch>,
/// What the host list has: pipeline, root signature, heaps.
host_pipeline: usize,
/// Graphics, compute.
@@ -365,6 +429,126 @@ pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0);
/// index ([`State::heap_buffers`]), and the microseconds they took.
pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0);
pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0);
/// Of the passes, nanoseconds since the last frame line: looking at slots,
/// the spans and refreshes of their copies, the texture side.
#[cfg(feature = "diagnostics")]
pub(crate) static HEAP_SPLIT: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
/// Passes after which every buffer slot of the heap was looked at again.
const HEAP_ROUND: u64 = 16;
/// Whether the slots looked at again for no write are a part of them at
/// every pass, each slot at every sixteenth (`VICTORY_HEAP_SPREAD=0`: all of
/// them at every sixteenth pass, as before).
///
/// All at once was some 115 ms on a thread that records the frame, every
/// sixteenth frame (72,000 slots; run record-1: 11 ms a pass in the lines
/// without such a pass, 22 in those of ten frames with one). A slot is
/// looked at as often as before.
fn heap_spread() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SPREAD").is_none_or(|v| v != "0"))
}
/// The host copy and range the buffer view of each of a heap's slots reads
/// ([`State::heap_buffers`]), by slot.
#[derive(Default)]
struct HeapRanges<T>(Vec<Option<(T, u64, u64)>>);
impl<T> HeapRanges<T> {
fn set(&mut self, slot: u32, range: Option<(T, u64, u64)>) {
let slot = slot as usize;
if range.is_none() && slot >= self.0.len() {
return;
}
if slot >= self.0.len() {
self.0.resize_with(slot + 1, || None);
}
self.0[slot] = range;
}
/// Forgets the slots of one of `parts` parts
/// (`HostHeap::buffer_slots_of`).
fn forget_part(&mut self, part: u32, parts: u32) {
self.0.iter_mut().skip(part as usize).step_by(parts as usize).for_each(|r| *r = None);
}
fn ranges(&self) -> impl Iterator<Item = &(T, u64, u64)> {
self.0.iter().flatten()
}
}
#[cfg(test)]
mod heap_range_tests {
use super::{HEAP_ROUND, HeapRanges};
/// Round by round every slot is looked at again once, whatever was
/// written between, and what a slot holds is what was found last.
#[test]
fn every_slot_is_looked_at_again_in_a_round() {
const SLOTS: u32 = 1000;
let mut ranges = HeapRanges(Vec::new());
ranges.set(7, None);
assert_eq!(ranges.ranges().count(), 0);
for slot in (0..SLOTS).step_by(3) {
ranges.set(slot, Some(((), 0, 1)));
}
let parts = HEAP_ROUND as u32;
for pass in 1..=HEAP_ROUND {
let part = (pass % HEAP_ROUND) as u32;
ranges.forget_part(part, parts);
for slot in (0..SLOTS).step_by(3).filter(|slot| slot % parts == part) {
assert!(ranges.0[slot as usize].is_none(), "slot {slot} not forgotten");
ranges.set(slot, Some(((), pass, pass)));
}
assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize);
}
assert!(ranges.ranges().all(|r| r.1 != 0), "a slot not looked at in a round");
ranges.set(3, None);
assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize - 1);
}
/// The spans of 4,400 copies from the ranges of 72,000 slots, as a pass
/// makes them, by slot and from the table they were in. Run with
/// `--ignored --nocapture`.
#[test]
#[ignore]
fn spans_of_a_pass() {
use std::collections::HashMap;
use std::sync::Arc;
let copies: Vec<Arc<u64>> = (0..4400).map(Arc::new).collect();
let (mut table, mut slots) = (HashMap::new(), HeapRanges(Vec::new()));
for slot in 0..72_000u32 {
let copy = &copies[slot as usize * 7919 % 4400];
table.insert(slot, (copy.clone(), u64::from(slot), u64::from(slot) + 64));
slots.set(slot, Some((copy.clone(), u64::from(slot), u64::from(slot) + 64)));
}
fn join<S: std::hash::BuildHasher + Default>(ranges: &mut dyn Iterator<Item = &(Arc<u64>, u64, u64)>) -> usize {
let mut spans: HashMap<usize, (Arc<u64>, u64, u64), S> = HashMap::default();
for (copy, from, to) in ranges {
let span = spans.entry(Arc::as_ptr(copy) as usize).or_insert_with(|| (copy.clone(), *from, *to));
span.1 = span.1.min(*from);
span.2 = span.2.max(*to);
}
spans.len()
}
let best = |f: &mut dyn FnMut() -> usize| {
(0..30)
.map(|_| {
let t = std::time::Instant::now();
assert_eq!(f(), 4400);
t.elapsed().as_secs_f64() * 1e3
})
.fold(f64::MAX, f64::min)
};
println!(
"{:.2} ms from the table, {:.2} ms by slot",
best(&mut || join::<std::hash::RandomState>(&mut table.values())),
best(&mut || join::<std::hash::BuildHasherDefault<crate::host::AddressHash>>(&mut slots.ranges())),
);
}
}
/// Textures brought up to date for shaders that pick them by index
/// ([`State::heap_textures`]), the bytes of their memory, and the slots
/// still waiting.
@@ -383,6 +567,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 +1111,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 {
@@ -1164,6 +1363,8 @@ impl State {
let len = s.left(a).min(limit);
s.refresh(list, a, len);
if writes {
#[cfg(feature = "diagnostics")]
crate::host::wide_write(a, len, self.pipeline);
s.gpu_writes(list, a, len);
}
};
@@ -1368,18 +1569,25 @@ impl State {
// at best); all of them every 16 passes, because a view of a
// released resource goes stale without a write, and a slot written
// before its memory had a host copy is only made then.
type Ranges = std::collections::HashMap<u32, (std::sync::Arc<crate::shadow::Shadow>, u64, u64)>;
type Ranges = HeapRanges<std::sync::Arc<crate::shadow::Shadow>>;
static RANGES: std::sync::Mutex<Option<std::collections::HashMap<usize, (u64, Ranges)>>> =
std::sync::Mutex::new(None);
let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner());
let (passes, ranges) = kept
.get_or_insert_with(Default::default)
.entry(std::ptr::from_ref(host) as usize)
.or_insert_with(|| (0, Ranges::new()));
.or_insert_with(|| (0, HeapRanges(Vec::new())));
let changed = host.buffer_changes();
let slots = if *passes % 16 == 0 {
ranges.clear();
let slots = if *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()) {
ranges.0.clear();
host.buffer_slots()
} else if heap_spread() {
// The written ones, and this pass's part of the others.
let (part, parts) = ((*passes % HEAP_ROUND) as u32, HEAP_ROUND as u32);
ranges.forget_part(part, parts);
let mut slots = host.buffer_slots_of(part, parts);
slots.extend(changed);
slots
} else {
changed
};
@@ -1389,7 +1597,7 @@ impl State {
static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none();
for (n, &index) in slots.iter().enumerate() {
ranges.remove(&index);
ranges.set(index, None);
let Some(handle) = heap.handle(index) else {
continue;
};
@@ -1420,13 +1628,15 @@ impl State {
if host.shows(index, &shadow.buffer) == Some(false) {
HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed);
}
ranges.insert(index, (shadow, address, address + len));
ranges.set(index, Some((shadow, address, address + len)));
}
let views = ranges.len() as u32;
#[cfg(feature = "diagnostics")]
let looked = std::time::Instant::now();
// Per host copy, the span its picked views cover.
let mut spans: std::collections::HashMap<usize, (std::sync::Arc<crate::shadow::Shadow>, u64, u64)> =
std::collections::HashMap::new();
for (shadow, from, to) in ranges.values() {
let mut spans: crate::host::ByCopy<(std::sync::Arc<crate::shadow::Shadow>, u64, u64)> = Default::default();
let mut views = 0u32;
for (shadow, from, to) in ranges.ranges() {
views += 1;
let key = std::sync::Arc::as_ptr(shadow) as usize;
let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to));
span.1 = span.1.min(*from);
@@ -1466,7 +1676,13 @@ impl State {
}
shadow.refresh(list, *from, to - from);
}
#[cfg(feature = "diagnostics")]
let refreshed = std::time::Instant::now();
self.heap_textures(list, heap, host);
#[cfg(feature = "diagnostics")]
for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked, refreshed.elapsed()]) {
sum.fetch_add(time.as_nanos() as u64, Ordering::Relaxed);
}
HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed);
HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
static LOGGED: AtomicU64 = AtomicU64::new(0);
@@ -1552,6 +1768,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 +1902,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 +2035,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);
@@ -1916,6 +2230,7 @@ impl State {
list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
// SAFETY: an open list with everything set.
unsafe { list.list.Dispatch(x, y, z) };
self.buffers_written();
DISPATCHED.fetch_add(1, Ordering::Relaxed);
}
@@ -1982,9 +2297,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) {
@@ -2015,6 +2501,7 @@ impl State {
self.mesh_scissor(list, true);
// SAFETY: an open list with everything set.
unsafe { l6.DispatchMesh(x, 1, 1) };
self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
self.mesh_scissor(list, false);
DRAWN.fetch_add(1, Ordering::Relaxed);
true
@@ -2028,6 +2515,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
@@ -2213,7 +2768,8 @@ impl State {
host.make_null(index);
continue;
};
list.defer_fill(to, address as *const u8, size as usize);
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);
}
Some(view) => {
@@ -2347,6 +2903,7 @@ impl State {
list.list
.DrawInstanced(count, instances, from, first_instance)
};
self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
DRAWN.fetch_add(1, Ordering::Relaxed);
}
if !ran {
@@ -2395,7 +2952,7 @@ impl State {
};
let (from, to, stride) = (from as usize, to as usize, stride as usize);
let n = rects as usize;
list.defer_host(move || {
list.defer_host_read(from, n * 3 * stride, move || {
// The vertices are read in place, at submission: no change
// of mapping under the read (see
// `crate::watch::title_memory_reading`).
@@ -2448,6 +3005,7 @@ impl State {
list.list
.DrawIndexedInstanced(indices, instances, first, base, first_instance)
};
self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
DRAWN.fetch_add(1, Ordering::Relaxed);
}
if !ran {
@@ -2459,6 +3017,65 @@ impl State {
}
impl State {
/// Shaders that can write buffers were recorded: arguments may be others
/// from here on.
fn buffers_written(&mut self) {
match &mut self.batch {
Some(batch) if batches() == 2 => batch.wrote = true,
batch => *batch = None,
}
}
/// A draw with the pipeline `p` was recorded (as [`State::buffers_written`]
/// if its shaders can store to buffers).
fn drew(&mut self, p: Option<&HostPipeline>) {
if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) {
self.batch = None;
}
}
/// The title waits for earlier work (a barrier or a pipeline sync).
pub(crate) fn synced(&mut self) {
if self.batch.as_ref().is_some_and(|b| b.wrote) {
self.batch = None;
}
}
/// Where the clamped record of `kind` at `arguments` of the copy `args`
/// is, from the open batch or a new one ([`batches`]). `None` if it
/// cannot be clamped in one.
fn batched(
&mut self,
list: &HostList,
args: &std::sync::Arc<crate::shadow::Shadow>,
arguments: u64,
kind: u32,
) -> Option<(ID3D12Resource, u64)> {
const BATCH_USE: usize = usize::MAX - 0x78;
const DISPATCH: u32 = 2;
// Another host list, or this one after its reset ([`windows`]).
if list.first_use(BATCH_USE) {
self.batch = None;
}
// A draw after dispatches waits for them.
if kind != DISPATCH {
self.synced();
}
let (id, offset) = (args.id(), args.offset(arguments));
if let Some(b) = &mut self.batch
&& let Some(at) = b.table.place(id, offset, kind)
{
return Some((b.scratch.clone(), at));
}
self.batch = None;
let (mut table, scratch) = crate::indirect::open_batch(list, (id, &args.buffer), &argument_copies(args))?;
self.host_pipeline = 0;
self.host_roots[1] = 0;
let at = table.place(id, offset, kind)?;
self.batch = Some(Batch { table, scratch: scratch.clone(), wrote: false });
Some((scratch, at))
}
/// Indirect execution of a one-argument signature of `kind` (PC
/// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with
/// records `stride` bytes apart at title address `arguments`, and the
@@ -2550,6 +3167,16 @@ impl State {
why("mesh draws are switched off (VICTORY_MESH_TEST=skip)");
return false;
}
// One record without a count: clamped in a batch (`batches`).
let batch = if batches() > 0 && max == 1 && count.is_none() {
args.refresh(list, arguments, len);
self.batched(list, &args, arguments, kind)
} else {
None
};
if batch.is_some() {
self.window = None;
}
// A window of records clamped in one pass (`windows`): for single
// records without a count buffer, drawn by shaders that store to no
// buffer. Anything else ends the window: it uses the scratch buffer
@@ -2573,7 +3200,7 @@ impl State {
.filter(|w| same(w) && offset >= w.base)
.filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records))
.map(|w| (w.scratch.clone(), offset - w.base));
let (bounded, at) = match hit {
let (bounded, at) = match batch.or(hit) {
Some(hit) => hit,
None => {
// A record a short step after the last window's last one
@@ -2663,6 +3290,11 @@ impl State {
if kind == MESH {
self.mesh_scissor(list, false);
}
if kind == DISPATCH {
self.buffers_written();
} else {
self.drew(Some(p));
}
// The scratch buffer stays readable as arguments: the next draw of
// the window reads it with no barrier, and the next clamp moves it
// back (`crate::indirect`).
@@ -2763,6 +3395,8 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) {
// A shader that cannot store to buffers leaves the range as
// the title has it: nothing to find afterwards.
if STORES.get() || !write_skip() {
#[cfg(feature = "diagnostics")]
crate::host::wide_write(address, len, 0);
shadow.gpu_writes(list, address, len);
} else {
#[cfg(feature = "diagnostics")]
@@ -2823,6 +3457,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 {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+276
View File
@@ -0,0 +1,276 @@
//! Clamps of many executions in one pass: the arguments of every indirect
//! execution between two points where they may change are bounded together,
//! at the first of them.
//!
//! The executions that come after it are not known yet when the pass is
//! recorded, so it reads what to clamp from a table of jobs in upload
//! memory, which the CPU goes on filling while the list is recorded: the
//! pass is as wide as the table and its threads past the count do nothing.
//! An execution that asks for a record already in the table (the title's
//! tile classes) reads the same clamped one.
//!
//! What the records charge the list's budget is as for records clamped
//! alone, times the executions that read them.
use windows::Win32::Graphics::Direct3D12::*;
use super::{Clamp, uav_barrier};
use crate::host::transition;
/// The jobs of one pass.
pub(crate) const JOBS: u32 = 256;
/// The bytes of its table in upload memory: the count, then the jobs.
pub(crate) const TABLE: u64 = 16 + 16 * JOBS as u64;
/// The bytes of a clamped record's place in the scratch buffer.
pub(crate) const SLOT: u32 = 32;
/// The source buffers a pass can read.
pub(crate) const SOURCES: usize = 4;
/// The most executions charged by one job: the most a record costs (2^26)
/// as often still fits 32 bits.
pub(crate) const TIMES: u32 = 31;
pub(crate) const SOURCE: &str = r#"
#define RS "SRV(t0), SRV(t1), SRV(t2), SRV(t3), SRV(t4), UAV(u0), UAV(u1)"
ByteAddressBuffer src0 : register(t0);
ByteAddressBuffer src1 : register(t1);
ByteAddressBuffer src2 : register(t2);
ByteAddressBuffer src3 : register(t3);
// The count, 12 bytes of nothing, then per job: source (bits 0-1), kind
// (4-7), words (8-11) and the executions that read it (16-31); the
// record's offset in the source; its place in the scratch buffer; nothing.
ByteAddressBuffer jobs : register(t4);
RWByteAddressBuffer dst_args : register(u0);
RWByteAddressBuffer budget : register(u1);
static const uint BUDGET = 1u << 27;
static const uint GROUPS = 1u << 20;
groupshared uint costs[64];
groupshared uint fits[64];
groupshared uint largest_asked;
groupshared uint all_asked;
uint load(uint source, uint at) {
if (source == 0) return src0.Load(at);
if (source == 1) return src1.Load(at);
if (source == 2) return src2.Load(at);
return src3.Load(at);
}
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
uint count = jobs.Load(0);
bool active = id.x < count;
uint4 job = uint4(0, 0, 0, 0);
uint record[5] = {0, 0, 0, 0, 0};
uint cost = 0;
uint asked = 0;
uint kind = 0;
uint words = 0;
if (gi == 0) {
largest_asked = 0;
all_asked = 0;
}
// As the clamp of one execution (`super::SOURCE`) bounds them.
if (active) {
job = jobs.Load4(16 + id.x * 16);
kind = (job.x >> 4) & 15;
words = min((job.x >> 8) & 15, 5);
for (uint w = 0; w < words; w++) {
record[w] = load(job.x & 3, job.y + w * 4);
}
if (kind <= 1) {
record[0] = min(record[0], 1u << 24);
record[1] = min(record[1], (1u << 26) / max(record[0], 1u));
cost = record[0] * record[1];
} else if (kind == 2) {
uint3 g = min(uint3(record[0], record[1], record[2]), uint3(65535u, 65535u, 65535u));
if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
g = uint3(0, 0, 0);
}
cost = g.x * g.y * g.z * 64u;
record[0] = g.x;
record[1] = g.y;
record[2] = g.z;
} else {
asked = record[0];
record[0] = min(record[0], 65535u);
record[1] = min(record[1], 1u);
record[2] = min(record[2], 1u);
cost = record[0] * record[1] * record[2] * 128u;
}
cost *= job.x >> 16;
}
costs[gi] = cost;
GroupMemoryBarrierWithGroupSync();
if (active && kind > 2) {
uint was;
InterlockedMax(largest_asked, asked, was);
InterlockedAdd(all_asked, min(asked, 1u << 24), was);
}
uint first = id.x - gi;
uint n = count > first ? min(64u, count - first) : 0u;
if (gi == 0 && n > 0) {
uint before;
budget.InterlockedOr(0, 0, before);
[allow_uav_condition]
while (before < BUDGET) {
uint next = before;
for (uint j = 0; j < n; j++) {
uint c = costs[j];
if (c > 0 && next < BUDGET) {
next = (BUDGET - next <= c) ? BUDGET : (next + c);
}
}
if (next == before) break;
uint prev;
budget.InterlockedCompareExchange(0, before, next, prev);
if (prev == before) break;
before = prev;
}
uint at = before;
for (uint k = 0; k < n; k++) {
uint c = costs[k];
uint fit = 1;
if (c > 0) {
fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u;
at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c);
}
fits[k] = fit;
}
}
GroupMemoryBarrierWithGroupSync();
if (gi == 0 && n > 0 && all_asked > 0) {
uint was;
budget.InterlockedMax(4, largest_asked, was);
budget.InterlockedAdd(8, all_asked, was);
}
if (!active) {
return;
}
if (fits[gi] == 0) {
record[0] = 0;
record[1] = 0;
if (kind > 1) {
record[2] = 0;
}
}
for (uint s = 0; s < words; s++) {
dst_args.Store(job.z + s * 4, record[s]);
}
}
"#;
/// The words of a record of `kind` (PC argument numbering).
pub(crate) fn words(kind: u32) -> Option<u32> {
super::min_stride(kind).map(|bytes| bytes / 4)
}
/// A job's first word.
pub(crate) fn job(source: u32, kind: u32, times: u32) -> u32 {
source | (kind << 4) | (words(kind).unwrap_or(0) << 8) | (times << 16)
}
/// The jobs of a pass as the CPU fills them ([`SOURCE`]), and where it
/// keeps which record is where.
#[derive(Default)]
pub(crate) struct Table {
/// The table in upload memory ([`TABLE`] bytes).
at: usize,
/// The place of the first clamped record in the scratch buffer.
base: u32,
/// The host copies it can read, by number ([`crate::shadow::Shadow::id`];
/// 0: none).
sources: [u64; SOURCES],
/// How many executions each job is charged for so far.
times: Vec<u32>,
/// The job of a record (source, offset, kind).
known: std::collections::HashMap<(u32, u32, u32), u32>,
}
impl Table {
/// A table at `at`, with no job yet.
///
/// # Safety
/// `at` is [`TABLE`] bytes of mapped upload memory, 4-byte aligned, that
/// live until the list that reads them is recorded and is not run
/// before.
pub(crate) unsafe fn new(at: *mut u8, base: u32, sources: [u64; SOURCES]) -> Table {
// SAFETY: the caller's.
unsafe { at.cast::<u32>().write_volatile(0) };
Table { at: at as usize, base, sources, ..Table::default() }
}
/// The place in the scratch buffer of the record of `kind` at `offset`
/// of the host copy `id`, once the pass has run: a job of it is added if
/// there is none. `None` if the pass cannot read that copy or has no
/// room for another job.
pub(crate) fn place(&mut self, id: u64, offset: u64, kind: u32) -> Option<u64> {
let source = self.sources.iter().position(|&s| s == id)? as u32;
let offset = u32::try_from(offset).ok().filter(|o| o.is_multiple_of(4))?;
offset.checked_add(words(kind)? * 4)?;
let key = (source, offset, kind);
let table = self.at as *mut u32;
let place = |i: u32| u64::from(self.base + i * SLOT);
if let Some(&i) = self.known.get(&key)
&& self.times[i as usize] < TIMES
{
self.times[i as usize] += 1;
// SAFETY: the job's own word of the table ([`Table::new`]).
unsafe { table.add(4 + 4 * i as usize).write_volatile(job(source, kind, self.times[i as usize])) };
return Some(place(i));
}
let i = self.times.len() as u32;
if i == JOBS {
return None;
}
self.times.push(1);
self.known.insert(key, i);
// SAFETY: inside the table: fewer than [`JOBS`] jobs before it.
unsafe {
let to = table.add(4 + 4 * i as usize);
to.write_volatile(job(source, kind, 1));
to.add(1).write_volatile(offset);
to.add(2).write_volatile(self.base + i * SLOT);
to.add(3).write_volatile(0);
table.write_volatile(i + 1);
}
Some(place(i))
}
}
/// Records the pass over the table at `jobs` (a host address) into `dst`,
/// which is in state `before` and left in `INDIRECT_ARGUMENT`: after every
/// earlier shader write (the title's argument passes), before what reads
/// the clamped records.
pub(super) fn record(
c: &Clamp,
l: &ID3D12GraphicsCommandList,
(dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES),
budget: u64,
sources: [u64; SOURCES],
jobs: u64,
) {
let after = transition(
dst,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
);
// SAFETY: an open list; our root signature and pipeline; live buffers:
// the sources and the table are read in the common state (promoted).
unsafe {
l.ResourceBarrier(&[
uav_barrier(),
transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
]);
l.SetComputeRootSignature(&c.root);
l.SetPipelineState(&c.pso);
for (i, source) in sources.into_iter().enumerate() {
l.SetComputeRootShaderResourceView(i as u32, source);
}
l.SetComputeRootShaderResourceView(SOURCES as u32, jobs);
l.SetComputeRootUnorderedAccessView(SOURCES as u32 + 1, dst.GetGPUVirtualAddress());
l.SetComputeRootUnorderedAccessView(SOURCES as u32 + 2, budget);
l.Dispatch(JOBS.div_ceil(64), 1, 1);
// Nothing else the pass writes is read before the next full wait
// (the budget, by the next pass): only the records have to be there.
l.ResourceBarrier(&[after]);
}
}
+53 -1
View File
@@ -269,9 +269,12 @@ struct Views {
views: BTreeMap<usize, (usize, usize, u64)>,
/// Sections by handle: bytes, and whether made committed.
sections: Vec<(usize, u64, bool)>,
/// Our own view of a whole section, by its handle (0: the host gave
/// none), made when first asked for ([`beside`]) and kept.
whole: Vec<(usize, usize)>,
}
static VIEWS: Mutex<Views> = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new() });
static VIEWS: Mutex<Views> = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new(), whole: Vec::new() });
fn views() -> std::sync::MutexGuard<'static, Views> {
VIEWS.lock().unwrap_or_else(|e| e.into_inner())
@@ -282,9 +285,28 @@ fn views() -> std::sync::MutexGuard<'static, Views> {
pub fn title_memory_section(section: usize, bytes: u64, committed: bool) {
let mut v = views();
v.sections.retain(|s| s.0 != section);
// A handle's number given out again: the view was of the section that
// had it before (it stays mapped: someone may be writing through it).
v.whole.retain(|w| w.0 != section);
v.sections.push((section, bytes, committed));
}
/// The runtime lets go of a section, and of its handle: no view the title
/// sees is of it any more, and [`beside`]'s view goes.
pub fn title_memory_section_gone(section: usize) {
let whole = {
let mut v = views();
let at = v.whole.iter().position(|w| w.0 == section);
at.map(|i| v.whole.swap_remove(i).1)
};
if let Some(base) = whole.filter(|&base| base != 0) {
// SAFETY: a view of ours. Who writes through it found the section
// in a view the title saw and holds off its unmapping
// (`crate::watch::title_memory_reading`), which came before this.
unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: base as *mut c_void }) };
}
}
/// The runtime mapped `[at, at + len)` as a view of `section` from
/// `offset` on. Call after [`crate::title_memory_remapped`] of the range.
pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) {
@@ -343,6 +365,36 @@ pub(crate) fn cover(at: usize, len: usize) -> Cover {
cover_in(&views().views, at, len)
}
/// Another address of the title memory `[at, at + len)`, if it is a view of
/// the title's pages, all of it one run of a section: in a view of ours of
/// the whole section, which is never guarded (`crate::watch`) nor changed.
///
/// The section's pages are reserved and the runtime commits each before it
/// shows it, which holds for every view of the section. The caller holds
/// `crate::watch::title_memory_reading`: until it lets go the title sees
/// the same pages at `at`.
pub(crate) fn beside(at: usize, len: usize) -> Option<usize> {
let mut v = views();
let Cover::Run(section, offset) = cover_in(&v.views, at, len) else {
return None;
};
let base = match v.whole.iter().find(|w| w.0 == section) {
Some(w) => w.1,
None => {
let &(_, bytes, _) = v.sections.iter().find(|s| s.0 == section)?;
// SAFETY: the whole of a section the runtime made; a view the
// title sees is of it, so its handle is open.
let base = unsafe { mem::MapViewOfFile(section as _, mem::FILE_MAP_WRITE, 0, 0, bytes as usize) }.Value as usize;
if base == 0 {
tracing::warn!(error = %std::io::Error::last_os_error(), "no view of the title's pages beside its own");
}
v.whole.push((section, base));
base
}
};
(base != 0).then(|| base + offset as usize)
}
/// Whether `[at, at + len)` is private memory, all committed and
/// read-write: what [`From::Part`] takes. One question to Windows (it
/// walks the page tables to the end of the pages that share the first
+556
View File
@@ -0,0 +1,556 @@
//! What shaders wrote goes into title memory on a few threads
//! (`VICTORY_LAND`, on by default; `=0` merges piece by piece on the thread
//! that lands flights, as before).
//!
//! The relay's thread (`crate::host::relay`) was 58-60 ms of a 104 ms frame
//! landing (run record-1): some 1,500 pieces of 64 KiB, 98 MB, fetched from
//! copies in the card's memory, and each of them searched from both ends,
//! cleared room for, read from title memory, copied, merged and compared
//! again while it was put, one after the other; a lock and a protection
//! call to open the guard of each, and the kernel's fault on the first
//! write to each 4 KiB page of memory just made writable again.
//!
//! Here a piece is merged in one pass ([`crate::safecopy::merge`]): what
//! the card holds is compared with what it held 32 bytes at a time, title
//! memory is read only where they differ, just before the dwords that
//! change are stored. The pieces of a landing are cut into jobs for a few
//! threads kept for it ([`Pool`]).
//!
//! What stays in order: pieces in the same 64 KiB of title memory are in
//! one job, in the order they were given (two copies may hold the same
//! title memory); a landing's copies in the card's memory come before its
//! other copies; a landing is done, whole, before the title is told
//! anything and before the next one starts (`Host::relay_land`).
//!
//! With `VICTORY_LAND_BESIDE` (on by default) title memory that is a view of
//! the title's physical pages is written through a view of our own of the
//! same pages ([`crate::inplace::beside`]). The guards (`crate::watch`) are
//! read-only title views: they stay as they are, no protection changes, and
//! [`crate::watch::landed_beside`] notes the blocks written afterwards, so
//! that the next refresh takes them as before.
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Condvar, Mutex, MutexGuard, OnceLock};
/// The unit pieces are cut in (of title memory), and the guards' blocks.
pub(crate) const BLOCK: usize = 64 << 10;
/// The unit title memory is there or not in.
const PAGE: usize = 4096;
/// About this many bytes to a job.
const JOB: usize = 256 << 10;
/// See the file.
pub(crate) fn on() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| {
std::env::var_os("VICTORY_LAND").is_none_or(|v| v != "0") && crate::safecopy::on() && crate::shadow::exact_back()
})
}
/// How many threads land, the relay's own counted (`VICTORY_LAND_THREADS`).
fn threads() -> usize {
static THREADS: OnceLock<usize> = OnceLock::new();
*THREADS.get_or_init(|| {
let asked = std::env::var("VICTORY_LAND_THREADS").ok().and_then(|v| v.trim().parse().ok());
asked.unwrap_or_else(|| std::thread::available_parallelism().map_or(2, |n| n.get() / 4).clamp(1, 4)).clamp(1, 16)
})
}
/// Whether views of the title's pages are written through one of ours.
fn beside_on() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LAND_BESIDE").is_none_or(|v| v != "0"))
}
/// Whether pieces an earlier fetch holds as they are now are left out
/// ([`Had`]; `VICTORY_LAND_SKIP=1`, off by default: counted either way).
pub(crate) fn skip_on() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LAND_SKIP").is_some_and(|v| v == "1"))
}
/// Since the last frame-rate line; microseconds first.
pub(crate) mod stat {
/// Which pieces to fetch; their list recorded and sent.
pub(crate) const GATHER: usize = 0;
/// Looking for what shaders wrote to copies in the PC's memory, the part
/// done while the fetch was on its way.
pub(crate) const SCAN_BESIDE: usize = 1;
/// The same, with nothing else to wait for.
pub(crate) const SCAN: usize = 2;
/// Merging what was fetched: until the last job is done, and the jobs'
/// time on all threads.
pub(crate) const CARD: usize = 3;
pub(crate) const CARD_ALL: usize = 4;
/// Merging what the scan found.
pub(crate) const BACK: usize = 5;
pub(crate) const BACK_ALL: usize = 6;
/// In the jobs: waiting for the lock against the title's bytes going in.
pub(crate) const LOCK: usize = 7;
/// In the jobs: guards opened before a write, or noted after one.
pub(crate) const NOTES: usize = 8;
/// The flights' ranges done with; reading back, resets; what the title
/// is told; the rest (the line's account).
pub(crate) const DONE: usize = 9;
pub(crate) const READ_BACKS: usize = 10;
pub(crate) const TOLD: usize = 11;
pub(crate) const REST: usize = 12;
/// Counts: pieces merged, those with a new byte, their 4 KiB pages,
/// those with a new byte, blocks of 32 bytes with a new byte, dwords put.
pub(crate) const PIECES: usize = 13;
pub(crate) const NEW_PIECES: usize = 14;
pub(crate) const PAGES: usize = 15;
pub(crate) const NEW_PAGES: usize = 16;
pub(crate) const NEW_BLOCKS: usize = 17;
pub(crate) const DWORDS: usize = 18;
/// Pieces put through a view of ours, through the title's; pages where
/// title memory was not there.
pub(crate) const BESIDE: usize = 19;
pub(crate) const DIRECT: usize = 20;
pub(crate) const MISSING: usize = 21;
/// Bytes asked for twice in a landing (fetched once); pieces and bytes
/// an earlier fetch held already.
pub(crate) const TWICE: usize = 22;
pub(crate) const HAD: usize = 23;
pub(crate) const HAD_BYTES: usize = 24;
/// Jobs.
pub(crate) const JOBS: usize = 25;
pub(crate) const COUNT: usize = 26;
}
static STATS: [AtomicU64; stat::COUNT] = [const { AtomicU64::new(0) }; stat::COUNT];
pub(crate) fn count(which: usize, n: u64) {
STATS[which].fetch_add(n, Ordering::Relaxed);
}
/// Adds the microseconds since `from` to `which`; now.
pub(crate) fn spent(which: usize, from: std::time::Instant) -> std::time::Instant {
let now = std::time::Instant::now();
count(which, (now - from).as_micros() as u64);
now
}
/// For the frame-rate line: where landing went, per frame.
pub(crate) fn log(frames: f64) {
let s: Vec<f64> = STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect();
if s[stat::PIECES] == 0.0 && s[stat::REST] == 0.0 {
return;
}
let ms = |i: usize| s[i] / 1000.0;
let mb = |v: f64| v / (1 << 20) as f64;
tracing::info!(
"landing per frame (VICTORY_LAND={}, {} threads): which pieces to fetch {:.2} ms, then the fetches (the relay's line); \
looking through copies in the PC's memory {:.2} ms beside them and {:.2} ms more; merging what was fetched {:.2} ms \
({:.2} ms on all threads, {:.0} jobs), merging the others {:.2} ms ({:.2} on all threads); of the threads' time \
{:.2} ms waiting for the title's bytes going in, {:.2} ms opening or noting guards; then ranges done with {:.2} ms, \
read-backs and lists {:.2}, the title told {:.2}, the rest {:.2}",
u8::from(on()),
threads(),
ms(stat::GATHER),
ms(stat::SCAN_BESIDE),
ms(stat::SCAN),
ms(stat::CARD),
ms(stat::CARD_ALL),
s[stat::JOBS],
ms(stat::BACK),
ms(stat::BACK_ALL),
ms(stat::LOCK),
ms(stat::NOTES),
ms(stat::DONE),
ms(stat::READ_BACKS),
ms(stat::TOLD),
ms(stat::REST),
);
tracing::info!(
"landed per frame: {:.0} pieces, {:.0} with a new byte; of their {:.0} pages of 4 KiB {:.0} with a new byte ({:.1} MB), \
{:.1} MB in blocks of 32 bytes with one, {:.2} MB put as dwords; {:.0} pieces through a view of ours \
(VICTORY_LAND_BESIDE={}), {:.0} through the title's; {:.0} pages not there; asked for twice in a landing {:.1} MB; \
held already by an earlier fetch {:.0} pieces {:.1} MB (VICTORY_LAND_SKIP={})",
s[stat::PIECES],
s[stat::NEW_PIECES],
s[stat::PAGES],
s[stat::NEW_PAGES],
mb(s[stat::NEW_PAGES] * PAGE as f64),
mb(s[stat::NEW_BLOCKS] * 32.0),
mb(s[stat::DWORDS] * 4.0),
s[stat::BESIDE],
u8::from(beside_on()),
s[stat::DIRECT],
s[stat::MISSING],
mb(s[stat::TWICE]),
s[stat::HAD],
mb(s[stat::HAD_BYTES]),
u8::from(skip_on()),
);
}
/// Threads kept for landing, and the work they are at.
struct Pool {
state: Mutex<State>,
more: Condvar,
idle: Condvar,
/// One batch at a time.
turn: Mutex<()>,
threads: usize,
}
struct State {
/// What to do with each number below `count`.
work: Option<Work>,
next: usize,
count: usize,
/// Helpers inside a call.
running: usize,
panicked: bool,
}
#[derive(Clone, Copy)]
struct Work(*const (dyn Fn(usize) + Sync));
// SAFETY: the closure may be called from any thread (`Sync`), and
// `Pool::each` keeps it alive until no helper is inside a call.
unsafe impl Send for Work {}
impl Pool {
fn state(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
fn new(threads: usize) -> &'static Pool {
let pool: &'static Pool = Box::leak(Box::new(Pool {
state: Mutex::new(State { work: None, next: 0, count: 0, running: 0, panicked: false }),
more: Condvar::new(),
idle: Condvar::new(),
turn: Mutex::new(()),
threads,
}));
for i in 1..threads {
// (A helper that is not there is only missed.)
let _ = std::thread::Builder::new().name(format!("victory-land-{i}")).spawn(move || pool.help());
}
pool
}
fn help(&self) {
let mut state = self.state();
loop {
let Some((work, i)) = take(&mut state) else {
state = self.more.wait(state).unwrap_or_else(|e| e.into_inner());
continue;
};
state.running += 1;
drop(state);
// SAFETY: counted in `running`, so `each` has not returned.
let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { (*work.0)(i) }));
state = self.state();
state.running -= 1;
state.panicked |= ran.is_err();
if state.running == 0 {
self.idle.notify_all();
}
}
}
/// Calls `f` with every number below `count`, on the pool's threads and
/// this one, and returns when every call has.
fn each(&self, count: usize, f: &(dyn Fn(usize) + Sync)) {
if count < 2 || self.threads < 2 {
(0..count).for_each(f);
return;
}
let _turn = self.turn.lock().unwrap_or_else(|e| e.into_inner());
// SAFETY: the lifetime is left out only until this call returns, and
// it does not before no helper is inside `f` and none can enter.
let work = Work(unsafe { std::mem::transmute::<*const (dyn Fn(usize) + Sync + '_), *const (dyn Fn(usize) + Sync + 'static)>(f) });
let mut state = self.state();
(state.work, state.next, state.count, state.panicked) = (Some(work), 0, count, false);
drop(state);
if count > self.threads {
self.more.notify_all();
} else {
(1..count).for_each(|_| self.more.notify_one());
}
let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
loop {
let Some((_, i)) = take(&mut self.state()) else { break };
f(i);
}
}));
let mut state = self.state();
// (After a panic here: nothing more is begun.)
state.work = None;
while state.running > 0 {
state = self.idle.wait(state).unwrap_or_else(|e| e.into_inner());
}
let panicked = state.panicked;
drop(state);
if let Err(panic) = ran {
std::panic::resume_unwind(panic);
}
assert!(!panicked, "a job of landing panicked");
}
}
/// The next number of the batch, if there is one.
fn take(state: &mut State) -> Option<(Work, usize)> {
let work = state.work?;
if state.next >= state.count {
return None;
}
state.next += 1;
Some((work, state.next - 1))
}
/// [`Pool::each`] on the threads kept for landing.
pub(crate) fn each(count: usize, f: &(dyn Fn(usize) + Sync)) {
static POOL: OnceLock<&'static Pool> = OnceLock::new();
POOL.get_or_init(|| Pool::new(threads())).each(count, f);
}
/// A piece to land: the copy's number, the title address, its bytes.
pub(crate) type Piece = (u64, usize, usize);
/// `pieces` in the order they are landed: by the 64 KiB block of title
/// memory they lie in, those in one block in the order given (each is
/// within one block). Where one copy alone has pieces in a block, those
/// that overlap or touch are one piece: a landing's flights declare parts
/// of the same memory, and what overlapped came down and was merged twice.
/// Each with the number of the piece given that it begins with.
pub(crate) fn ordered(pieces: &[Piece]) -> Vec<(usize, usize, usize)> {
let mut order: Vec<usize> = (0..pieces.len()).collect();
order.sort_by_key(|&i| pieces[i].1 / BLOCK);
let mut out: Vec<(usize, usize, usize)> = Vec::with_capacity(order.len());
for group in order.chunk_by(|&a, &b| pieces[a].1 / BLOCK == pieces[b].1 / BLOCK) {
let alone = group.len() > 1 && group.iter().all(|&i| pieces[i].0 == pieces[group[0]].0);
if !alone {
out.extend(group.iter().map(|&i| (i, pieces[i].1, pieces[i].2)));
continue;
}
let mut sorted = group.to_vec();
sorted.sort_by_key(|&i| pieces[i].1);
let begun = out.len();
for i in sorted {
let (_, at, len) = pieces[i];
match out[begun..].last_mut() {
Some(last) if at <= last.1 + last.2 => {
let end = (last.1 + last.2).max(at + len);
count(stat::TWICE, (last.2 + len - (end - last.1)) as u64);
last.2 = end - last.1;
}
_ => out.push((i, at, len)),
}
}
}
out
}
/// Pieces (title address, bytes; in [`ordered`]'s order) as jobs: runs of
/// about [`JOB`] bytes that end where a block ends.
pub(crate) fn jobs(pieces: &[(usize, usize)]) -> Vec<std::ops::Range<usize>> {
let mut out: Vec<std::ops::Range<usize>> = Vec::new();
let (mut from, mut bytes) = (0, 0);
for (i, &(at, len)) in pieces.iter().enumerate() {
let new_block = i == 0 || pieces[i - 1].0 / BLOCK != at / BLOCK;
if bytes >= JOB && new_block {
out.push(from..i);
(from, bytes) = (i, 0);
}
bytes += len;
}
if from < pieces.len() {
out.push(from..pieces.len());
}
out
}
/// What earlier fetches brought, for as long as a flight they ran behind
/// has not landed: per fetch, the value the host's fence had been given
/// behind the last flight sent before it, and by copy (its number) and
/// piece the offsets it brought.
///
/// A fetch on the drawing queue runs behind everything sent before it, so
/// it brings what those flights' shaders wrote too, and the merge of it put
/// that into title memory. Their own landings flag the same pieces and
/// fetched them again, to find every byte merged. A piece that a fetch held
/// whole, behind the flight that flags it, has nothing more of that flight.
/// (Bytes left out of that merge, the title's that went up behind the
/// fetch, went up behind that flight too, and stand over what it wrote.)
#[derive(Default)]
pub(crate) struct Had(Vec<(u64, std::collections::HashMap<(u64, usize), (usize, usize)>)>);
impl Had {
/// Flights from the one behind which `fence` is signalled on are landed
/// next: what is of no use to them is dropped.
pub(crate) fn landing(&mut self, fence: u64) {
self.0.retain(|had| had.0 >= fence);
}
/// A fetch that ran behind every flight up to `fence` brought (copy,
/// title address, bytes) `pieces`. They are merged before the next ask.
pub(crate) fn fetched(&mut self, fence: u64, pieces: impl Iterator<Item = Piece>) {
let mut all = std::collections::HashMap::new();
for (copy, at, len) in pieces {
// (Two parts of a block that do not touch: the longer one.)
let had = all.entry((copy, at / BLOCK)).or_insert((at, at + len));
if len > had.1 - had.0 {
*had = (at, at + len);
}
}
self.0.push((fence, all));
}
/// Whether a fetch behind the flight of `fence` brought all of the
/// piece.
pub(crate) fn holds(&self, fence: u64, (copy, at, len): Piece) -> bool {
self.0.iter().any(|(behind, all)| {
*behind >= fence && all.get(&(copy, at / BLOCK)).is_some_and(|had| had.0 <= at && at + len <= had.1)
})
}
}
/// What a job wrote beside the guards, to be noted ([`Notes::flush`]).
#[derive(Default)]
pub(crate) struct Notes {
/// Pages of 4 KiB, by number.
pages: Vec<usize>,
/// Per piece, from the first such page to the last: address, bytes.
spans: Vec<(usize, usize)>,
}
impl Notes {
/// At the end of a job: what it wrote beside the guards is noted.
pub(crate) fn flush(&mut self) {
if self.pages.is_empty() {
return;
}
let noting = std::time::Instant::now();
crate::watch::landed_beside(&self.pages, &self.spans);
self.pages.clear();
self.spans.clear();
spent(stat::NOTES, noting);
}
}
/// Lands one piece: `parts` (offsets from and to) of the bytes at `now`,
/// which the card wrote, go into title memory from `title` on and into
/// `held` ([`crate::safecopy::merge`] says how, and what `take` is). The
/// piece lies in one 64 KiB block of title memory. Returns the bytes put.
///
/// # Safety
/// `now` and `held` are ours from 0 to the last part's end, and nothing but
/// the card writes `now` there, nothing but this call `held`.
pub(crate) unsafe fn piece(
title: usize,
now: *const u8,
held: *mut u8,
parts: &[(usize, usize)],
take: bool,
notes: &mut Notes,
) -> u64 {
// SAFETY: the caller's.
unsafe { piece_at(title, now, held, parts, take, notes, beside_on()) }
}
/// [`piece`], and whether a view of ours is looked for.
///
/// # Safety
/// [`piece`]'s.
unsafe fn piece_at(
title: usize,
now: *const u8,
held: *mut u8,
parts: &[(usize, usize)],
take: bool,
notes: &mut Notes,
beside: bool,
) -> u64 {
let Some(end) = parts.last().map(|p| p.1) else {
return 0;
};
// From here until the piece is put the runtime changes no mapping: our
// view's address stays where the title sees `title`. Not waited for: if
// a change is under way, the title's own address does.
let reading = beside.then(crate::watch::title_memory_reading_now).flatten();
let beside = reading.as_ref().and_then(|_| crate::inplace::beside(title, end));
count(stat::PIECES, 1);
count(if beside.is_some() { stat::BESIDE } else { stat::DIRECT }, 1);
// The pages that differ, before any is written: none, and the guard
// stays; else it is opened once for the piece.
let mut differing = [true; BLOCK / PAGE + 1];
let base = title / PAGE;
if beside.is_none() {
drop(reading);
differing.fill(false);
for_pages(title, parts, |from, n| {
// SAFETY: the caller's.
if unsafe { crate::safecopy::differ(now.add(from), held.add(from), n) } {
differing[(title + from) / PAGE - base] = true;
}
});
let Some(first) = differing.iter().position(|&d| d) else {
for_pages(title, parts, |_, _| count(stat::PAGES, 1));
return 0;
};
let last = differing.iter().rposition(|&d| d).unwrap_or(first);
let (from, to) = (((base + first) * PAGE).max(title), ((base + last + 1) * PAGE).min(title + end));
let opening = std::time::Instant::now();
crate::watch::landing(from, to - from);
spent(stat::NOTES, opening);
}
let into = beside.unwrap_or(title);
let (mut pages, mut new_pages, mut blocks, mut dwords, mut missing) = (0, 0u64, 0, 0, 0);
let mut span: Option<(usize, usize)> = None;
for_pages(title, parts, |from, n| {
pages += 1;
if !differing[(title + from) / PAGE - base] {
return;
}
// SAFETY: the caller's; title memory, by an address that shows it
// (`beside`) or the title's own.
let done = unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) };
blocks += done.new;
dwords += done.dwords;
missing += u64::from(!done.there);
if done.new > 0 {
new_pages += 1;
if beside.is_some() {
let page = (title + from) / PAGE;
// (Two parts in one page.)
if notes.pages.last() != Some(&page) {
notes.pages.push(page);
}
let s = span.get_or_insert((title + from, title + from + n));
s.1 = title + from + n;
}
}
});
if let Some((from, to)) = span {
notes.spans.push((from, to - from));
}
count(stat::NEW_PIECES, u64::from(new_pages > 0));
count(stat::PAGES, pages);
count(stat::NEW_PAGES, new_pages);
count(stat::NEW_BLOCKS, blocks);
count(stat::DWORDS, dwords);
count(stat::MISSING, missing);
crate::shadow::PUT[0].fetch_add(u64::from(dwords > 0), Ordering::Relaxed);
crate::shadow::PUT[2].fetch_add(dwords * 4, Ordering::Relaxed);
dwords * 4
}
/// `parts` of a piece that begins at `title`, cut where 4 KiB pages of title
/// memory end: offset and bytes.
fn for_pages(title: usize, parts: &[(usize, usize)], mut f: impl FnMut(usize, usize)) {
for &(from, to) in parts {
let mut at = from;
while at < to {
let n = (PAGE - (title + at) % PAGE).min(to - at);
f(at, n);
at += n;
}
}
}
#[cfg(test)]
mod tests;
+433
View File
@@ -0,0 +1,433 @@
use super::*;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize};
use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, PAGE_READWRITE};
struct Random(u64);
impl Random {
fn next(&mut self) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 >> 8) as usize
}
}
/// View memory as the runtime makes the title's: a view of a section, noted
/// as it notes it. Kept: the journal of what was written (`crate::watch`)
/// knows its addresses, which must not become another test's fresh memory.
struct Title {
at: usize,
len: usize,
}
impl Title {
fn new(len: usize) -> Title {
// SAFETY: a pagefile section of our own and a view of it.
unsafe {
let section =
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
assert!(!section.is_null());
let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
assert_ne!(at, 0);
crate::inplace::title_memory_section(section as usize, len as u64, true);
crate::title_memory_remapped(at, len);
crate::inplace::title_memory_view(at, len, section as usize, 0);
Title { at, len }
}
}
fn bytes(&self) -> &[u8] {
// SAFETY: the view.
unsafe { std::slice::from_raw_parts(self.at as *const u8, self.len) }
}
}
/// Every number once, whatever the count and the threads, batch after batch
/// and from several callers.
#[test]
fn the_pool_calls_every_number_once() {
for threads in [1usize, 2, 4, 7] {
let pool = Pool::new(threads);
std::thread::scope(|s| {
for _ in 0..3 {
s.spawn(|| {
for round in 0..300usize {
let count = round * 7 % 50;
let calls: Vec<AtomicUsize> = (0..count).map(|_| AtomicUsize::new(0)).collect();
pool.each(count, &|i| {
calls[i].fetch_add(1, Ordering::Relaxed);
});
assert!(calls.iter().all(|c| c.load(Ordering::Relaxed) == 1));
}
});
}
});
}
}
/// A job that panics is told to the caller, and the pool goes on.
#[test]
fn a_panicking_job_reaches_the_caller() {
let pool = Pool::new(3);
for bad in 0..8usize {
let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
pool.each(8, &|i| assert_ne!(i, bad, "(expected)"));
}));
assert!(ran.is_err());
let n = AtomicUsize::new(0);
pool.each(20, &|i| {
n.fetch_add(i, Ordering::Relaxed);
});
assert_eq!(n.into_inner(), 190);
}
}
/// The order pieces are landed in holds every byte of every piece, under its
/// copy, and no other; blocks come in order, pieces of several copies in one
/// block stay in the order given, and jobs never cut a block.
#[test]
fn ordered_pieces_hold_the_same_bytes() {
let mut random = Random(99);
for _ in 0..400 {
let count = random.next() % 40;
let pieces: Vec<Piece> = (0..count)
.map(|_| {
let block = random.next() % 12 * BLOCK;
let from = random.next() % BLOCK / 4 * 4;
let to = (from + 4 + random.next() % BLOCK / 4 * 4).min(BLOCK);
(random.next() as u64 % 3, block + from, to - from)
})
.collect();
let out = ordered(&pieces);
let bytes = |copy: u64, at: usize, all: &[Piece]| all.iter().any(|p| p.0 == copy && p.1 <= at && at < p.1 + p.2);
let landed: Vec<Piece> = out.iter().map(|&(i, at, len)| (pieces[i].0, at, len)).collect();
for copy in 0..3 {
for at in (0..12 * BLOCK).step_by(1024 * 4) {
assert_eq!(bytes(copy, at, &pieces), bytes(copy, at, &landed), "{pieces:?}");
}
}
assert!(out.iter().all(|&(_, at, len)| len > 0 && at / BLOCK == (at + len - 1) / BLOCK));
assert!(out.windows(2).all(|w| w[0].1 / BLOCK <= w[1].1 / BLOCK));
for block in 0..12 {
let given: Vec<Piece> = pieces.iter().copied().filter(|p| p.1 / BLOCK == block).collect();
let here: Vec<Piece> = landed.iter().copied().filter(|p| p.1 / BLOCK == block).collect();
if given.iter().any(|p| p.0 != given[0].0) {
assert_eq!(here, given);
} else {
assert!(here.windows(2).all(|w| w[0].1 + w[0].2 < w[1].1), "apart, in order");
}
}
let cut: Vec<(usize, usize)> = out.iter().map(|&(_, at, len)| (at, len)).collect();
let jobs = jobs(&cut);
assert_eq!(jobs.iter().cloned().flatten().collect::<Vec<_>>(), (0..cut.len()).collect::<Vec<_>>());
for w in jobs.windows(2) {
assert_ne!(cut[w[0].end - 1].0 / BLOCK, cut[w[1].start].0 / BLOCK);
}
}
}
/// A piece is left out only if a fetch behind its own flight, or behind a
/// later one, brought all of it, and is forgotten when that flight is done.
#[test]
fn only_what_a_fetch_behind_the_flight_brought_is_left_out() {
let mut had = Had::default();
had.fetched(7, [(1, BLOCK, BLOCK), (2, 0x100, 0x200)].into_iter());
assert!(had.holds(6, (1, BLOCK, BLOCK)) && had.holds(7, (1, BLOCK + 64, 128)));
assert!(!had.holds(8, (1, BLOCK, BLOCK)), "the fetch ran ahead of flight 8");
assert!(!had.holds(7, (3, BLOCK, BLOCK)) && !had.holds(7, (1, 0, 64)));
assert!(had.holds(7, (2, 0x100, 0x200)) && !had.holds(7, (2, 0x100, 0x204)) && !had.holds(7, (2, 0xfc, 8)));
had.landing(7);
assert!(had.holds(7, (1, BLOCK, BLOCK)));
had.landing(8);
assert!(had.0.is_empty());
}
/// A piece landed through either address holds what the merge of one thread
/// and one pass ([`crate::safecopy::merge`]) is to leave, with parts left
/// out, wherever it begins and ends.
#[test]
fn a_piece_lands_what_the_card_wrote_in_its_parts() {
assert!(crate::safecopy::on());
let title = Title::new(2 * BLOCK);
let mut random = Random(5);
for round in 0..300usize {
let from = (random.next() % 5000) & !3;
let len = (random.next() % BLOCK).min(BLOCK - from).max(1);
let base: Vec<u8> = (0..len).map(|_| random.next() as u8).collect();
let (mut now, mut held) = (base.clone(), base.clone());
for _ in 0..random.next() % 60 {
let at = random.next() % len;
let n = (random.next() % 300).min(len - at);
for b in &mut now[at..at + n] {
*b = random.next() as u8;
}
}
let mut there = base.clone();
for _ in 0..random.next() % 60 {
there[random.next() % len] ^= 0x11;
}
// Left out: some ranges, anywhere.
let mut parts = vec![(0, len)];
for _ in 0..round % 4 {
let a = random.next() % len;
let b = (a + random.next() % 200).min(len);
parts = parts
.into_iter()
.flat_map(|(x, y)| [(x, y.min(a)), (x.max(b), y)])
.filter(|(x, y)| x < y)
.collect();
}
// SAFETY: inside the view; `kernel_will_write`'s rule for our own
// writes: the guard goes first.
unsafe {
crate::watch::writing(title.at, 2 * BLOCK);
std::ptr::copy_nonoverlapping(there.as_ptr(), (title.at + from) as *mut u8, len);
}
// Guarded, as after a refresh, in two rounds of three.
if round % 3 != 0 {
assert!(crate::watch::writes(title.at, title.at + 2 * BLOCK, true).is_some());
assert_eq!(crate::watch::writes(title.at, title.at + 2 * BLOCK, true).map(|w| w.1.len() > 2), Some(false));
}
let asked = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view").0;
let mut notes = Notes::default();
// SAFETY: vectors of `len` bytes.
let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes) };
notes.flush();
let mut expect_held = base.clone();
let mut expect = there.clone();
for &(a, b) in &parts {
for i in a..b {
if now[i] != base[i] {
expect[i] = now[i];
expect_held[i] = now[i];
}
}
}
assert!(held == expect_held, "round {round}");
assert!(title.bytes()[from..from + len] == expect[..], "round {round}");
// Told: a refresh from now on takes the block again.
let (_, written) = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view");
let told = written.iter().any(|&(page, at)| page == title.at / BLOCK && at > asked);
assert!(told || put == 0, "round {round}: {put} bytes, {written:?} after {asked}");
}
}
/// Landings on several threads beside title threads that write the same
/// blocks (other dwords) and a thread that refreshes a copy, guarding what
/// it takes: no write of the title's is lost or undone, all the card wrote
/// arrives, and once everything stands still the next refresh takes the
/// last of it (no note is lost).
#[test]
fn landings_beside_the_title_and_its_refreshes_lose_nothing() {
assert!(crate::safecopy::on());
const BLOCKS: usize = 24;
const LEN: usize = BLOCKS * BLOCK;
let title = Title::new(LEN);
let at = title.at;
// SAFETY: committed, aligned, touched as atomics or by the landing's
// stores of whole dwords.
let dword = |i: usize| unsafe { &*((at + i * 4) as *const AtomicU32) };
let stop = AtomicBool::new(false);
// The copy: its bytes, and per block the asking that last took it.
let copy: Mutex<(Vec<u8>, Vec<u64>)> = Mutex::new((vec![0; LEN], vec![0; BLOCKS]));
let refresh = || {
let mut copy = copy.lock().unwrap_or_else(|e| e.into_inner());
let (now, written) = crate::watch::writes(at, at + LEN, true).expect("a view");
let (bytes, taken) = &mut *copy;
for block in 0..BLOCKS {
let write = written.iter().find(|w| w.0 == at / BLOCK + block).map_or(0, |w| w.1);
if taken[block] == 0 || write > taken[block] {
taken[block] = now;
let part = &mut bytes[block * BLOCK..(block + 1) * BLOCK];
// SAFETY: inside the view; whoever writes it meanwhile is
// noted, and the block taken again.
assert!(unsafe { crate::safecopy::copy(part.as_mut_ptr(), (at + block * BLOCK) as *const u8, BLOCK) });
}
}
};
let mut held = vec![0u8; LEN];
std::thread::scope(|s| {
let writers: Vec<_> = (0..3usize)
.map(|w| {
let stop = &stop;
s.spawn(move || {
let mut value = 1u32;
while !stop.load(Ordering::Relaxed) {
// Its own dwords, in every other block (in the rest
// only landings change anything).
for i in (w..LEN / 4).step_by(4 * 97).filter(|i| i * 4 / BLOCK % 2 == 0) {
assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone");
}
value += 1;
}
value - 1
})
})
.collect();
s.spawn(|| {
while !stop.load(Ordering::Relaxed) {
refresh();
}
});
let mut random = Random(77);
for round in 1..250u32 {
// The card's dwords: every fourth, from the third on, in some
// pages of some blocks.
let mut now = held.clone();
for _ in 0..60 {
let page = random.next() % (LEN / PAGE);
for i in (page * 1024 + 3..(page + 1) * 1024).step_by(4) {
now[i * 4..i * 4 + 4].copy_from_slice(&(round * 4096 + i as u32).to_le_bytes());
}
}
let pieces: Vec<Piece> = (0..BLOCKS).map(|b| (1, at + b * BLOCK, BLOCK)).collect();
let order = ordered(&pieces);
let cut: Vec<(usize, usize)> = order.iter().map(|&(_, at, len)| (at, len)).collect();
let jobs = jobs(&cut);
let into = held.as_mut_ptr() as usize;
each(jobs.len(), &|j| {
let mut notes = Notes::default();
for &(address, len) in &cut[jobs[j].clone()] {
let offset = address - at;
// SAFETY: each job its own pieces of the two vectors.
unsafe {
piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes);
}
}
notes.flush();
});
assert!(held == now, "round {round}");
for i in (3..LEN / 4).step_by(4 * 61) {
let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().expect("four"));
assert_eq!(dword(i).load(Ordering::Relaxed), expect, "round {round} dword {i}");
}
}
stop.store(true, Ordering::Relaxed);
for (w, writer) in writers.into_iter().enumerate() {
let last = writer.join().expect("nothing undone");
for i in (w..LEN / 4).step_by(4 * 97).filter(|i| i * 4 / BLOCK % 2 == 0) {
assert_eq!(dword(i).load(Ordering::Relaxed), last);
}
}
});
refresh();
let copy = copy.into_inner().unwrap_or_else(|e| e.into_inner());
assert!(copy.0 == title.bytes(), "a write was not told to the copy");
}
/// What a frame's landing costs (ignored: a measurement): 1,536 pieces of
/// 64 KiB, 96 MB, of a 174 MB heap of view memory in 15 landings, each block
/// guarded by a refresh before it; three quarters of the pages of a piece
/// with new bytes, every dword of them. As before, and here on one thread
/// and more, through the title's address and through a view of ours.
#[test]
#[ignore]
fn what_landing_costs() {
assert!(crate::safecopy::on());
const HEAP: usize = 2784 * BLOCK;
const COUNT: usize = 1536;
let title = Title::new(HEAP);
let mut held = vec![0u8; HEAP];
let mut card = vec![0u8; COUNT * BLOCK];
let busy = AtomicBool::new(true);
// The pieces: runs of eight blocks, scattered.
let pieces: Vec<usize> = (0..COUNT).map(|i| (i / 8 * 1021 % (HEAP / BLOCK / 8)) * 8 + i % 8).collect();
std::thread::scope(|s| {
// Other threads of the process at work (what a protection change
// has to reach).
for _ in 0..6 {
s.spawn(|| {
let mut v = vec![0u64; 1 << 14];
while busy.load(Ordering::Relaxed) {
for (i, x) in v.iter_mut().enumerate() {
*x = x.wrapping_mul(31).wrapping_add(i as u64);
}
}
});
}
let mut round = 0u32;
// `guarded`: 2 as a refresh leaves them, 1 opened again before (that
// is timed beside), 0 not at all, as they were after the last.
let mut frame = |label: &str, dense: bool, guarded: u8, land: &dyn Fn(&[(usize, usize, usize)])| {
let mut best = f64::MAX;
let (mut guards, mut opening) = (f64::MAX, f64::MAX);
for _ in 0..5 {
round += 1;
for (k, &block) in pieces.iter().enumerate() {
for page in 0..16 {
if page % 4 == 3 {
continue;
}
let from = k * BLOCK + page * PAGE;
let step = if dense { 4 } else { 64 };
// (The rest as held.)
let old = block * BLOCK + page * PAGE;
card[from..from + PAGE].copy_from_slice(&held[old..old + PAGE]);
for b in card[from..from + PAGE].chunks_exact_mut(step) {
b[..4].copy_from_slice(&round.wrapping_mul(0x0101_0101).to_le_bytes());
}
}
let (a, b) = (k * BLOCK + 12 * PAGE, block * BLOCK + 12 * PAGE);
for page in [3usize, 7, 11, 15] {
let (a, b) = (a - 12 * PAGE + page * PAGE, b - 12 * PAGE + page * PAGE);
card[a..a + PAGE].copy_from_slice(&held[b..b + PAGE]);
}
}
let t = std::time::Instant::now();
if guarded > 0 {
assert!(crate::watch::writes(title.at, title.at + HEAP, true).is_some());
}
guards = guards.min(t.elapsed().as_secs_f64() * 1e3);
let t = std::time::Instant::now();
if guarded == 1 {
pieces.iter().for_each(|block| crate::watch::landing(title.at + block * BLOCK, BLOCK));
}
opening = opening.min(t.elapsed().as_secs_f64() * 1e3);
let all: Vec<(usize, usize, usize)> = pieces
.iter()
.enumerate()
.map(|(k, &block)| {
(title.at + block * BLOCK, card.as_ptr() as usize + k * BLOCK, held.as_mut_ptr() as usize + block * BLOCK)
})
.collect();
let t = std::time::Instant::now();
for landing in all.chunks(COUNT / 15 + 1) {
land(landing);
}
best = best.min(t.elapsed().as_secs_f64() * 1e3);
}
println!("{label}: {best:.1} ms a frame to land; the guards before it {guards:.1} ms, opening them {opening:.1} ms");
};
for dense in [true, false] {
println!("{}", if dense { "every dword of three pages in four new" } else { "every sixteenth dword of them new" });
let before: &dyn Fn(&[(usize, usize, usize)]) = &|landing| {
let mut scratch: Vec<u8> = Vec::new();
for &(at, now, held) in landing {
crate::shadow::land_as_before(at, now, held, BLOCK, &mut scratch);
}
};
frame("as before", dense, 2, before);
frame("as before, guards opened ahead", dense, 1, before);
frame("as before, nothing guarded", dense, 0, before);
for threads in [1usize, 2, 3, 4, 5, 6, 8] {
let pool = Pool::new(threads);
for beside in [false, true] {
frame(&format!("{threads} threads, beside {beside}"), dense, 2, &|landing| {
let cut: Vec<(usize, usize)> = landing.iter().map(|p| (p.0, BLOCK)).collect();
let jobs = jobs(&cut);
pool.each(jobs.len(), &|j| {
let mut notes = Notes::default();
for &(at, now, held) in &landing[jobs[j].clone()] {
// SAFETY: each its own bytes.
unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside) };
}
notes.flush();
});
});
}
}
}
busy.store(false, Ordering::Relaxed);
});
}
+3 -1
View File
@@ -33,6 +33,8 @@ mod host;
mod indirect;
#[cfg(windows)]
mod inplace;
#[cfg(windows)]
mod land;
pub mod list;
pub mod object;
pub mod pipeline;
@@ -65,7 +67,7 @@ mod watch;
#[cfg(windows)]
pub use host::on_failure;
#[cfg(windows)]
pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view};
pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view};
#[cfg(windows)]
pub use watch::{
title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping,
+13 -2
View File
@@ -742,6 +742,9 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) ->
if let Some(list) = host_list(this)
&& !barriers.is_null()
{
if count > 0 {
with_state(this, |_, state| state.synced());
}
// SAFETY: the title passes `count` barriers.
let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) };
let mut host: Vec<Barrier> = barriers
@@ -971,7 +974,7 @@ extern "system" fn copy_texture_region(
};
// The list owns this mapped D3D12 upload buffer. Wine can report
// its address as MEM_FREE, so use the host-upload path.
list.defer_fill(staging, data, bytes as usize);
list.defer_fill_buffer(&buffer, staging, data, bytes as usize);
from.resource = buffer.as_raw().cast_const().cast();
from.footprint.offset = 0;
#[cfg(feature = "diagnostics")]
@@ -1396,7 +1399,14 @@ extern "system" fn set_pipeline(this: This, pipeline: This) {
/// bottom of the pipe `(flags, control, address, size)`. Host lists order
/// their own work and every submission is waited for, so there is nothing
/// to do.
extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {}
/// (Arguments may be what earlier shaders wrote from here on:
/// `State::synced`.)
extern "system" fn sync(this: This, _flags: u32, _control: u32, _address: u64, _size: u64) {
#[cfg(windows)]
with_state(this, |_, state| state.synced());
#[cfg(not(windows))]
let _ = this;
}
/// Reset with console flags `(allocator, pipeline, flags)`; the flags only
/// tune the console's command memory.
@@ -1943,6 +1953,7 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
&& let Some(list) = host_list(this)
{
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
with_state(this, |_, state| state.synced());
// SAFETY: the same layout; no resource named.
let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
// SAFETY: an open list.
+2
View File
@@ -304,6 +304,8 @@ pub(crate) fn ready(
shadow.refresh(list, start, len);
}
if writes && (first_write || n >= numbered) {
#[cfg(feature = "diagnostics")]
crate::host::wide_write(start, len, 1);
shadow.gpu_writes(list, start, len);
}
}
+378 -1
View File
@@ -3,7 +3,7 @@
use std::collections::{HashMap, HashSet};
use super::wire::{ALL, Barrier, Cmd, NONE, Va};
use super::wire::{ALL, Barrier, Cmd, NONE, Va, slot};
/// The buffer the clamped arguments of all clamp passes lie in, in lists
/// edited by [`clamps`].
@@ -298,6 +298,276 @@ pub fn skip_clamps(cmds: Vec<Cmd>, clamps: &[Clamp]) -> Vec<Cmd> {
out
}
/// The root signature, pipeline and table of the batched clamp
/// (`crate::indirect::batch`), and the scratch buffer it writes in the
/// first list of the frame (the next lists' are the ids before it), in lists
/// edited by [`batch_clamps`].
pub const BATCH_ROOT: u32 = u32::MAX - 2;
pub const BATCH: u32 = u32::MAX - 3;
pub const BATCH_JOBS: u32 = u32::MAX - 4;
pub const BATCH_SCRATCH: u32 = u32::MAX - 16;
/// What [`batch_clamps`] did to a list.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Batched {
/// Clamp passes before; after; the records the latter clamp.
pub clamps: u32,
pub batches: u32,
pub jobs: u32,
/// The bytes of the scratch buffer.
pub scratch: u64,
}
/// A clamp batch being filled by [`batch_clamps`].
struct Batch {
/// Where its table is in the jobs, and its root views in the list.
table: usize,
at: usize,
sources: Vec<u32>,
/// By source, offset and kind: the job, and how often it is read.
known: HashMap<(u32, u64, u32), (u32, u32)>,
n: u32,
base: u64,
}
/// The list with its clamps done in batches, as `crate::draw` does with
/// `VICTORY_INDIRECT_BATCH`: one pass at the first execution after a
/// point where arguments may have changed (a wait for shader writes, with
/// dispatches since the batch before it; or a draw, with dispatches since
/// the last wait). `careful`: before indirect dispatches too, with
/// dispatches since the last wait. `compute`: the pipelines that are compute
/// ones. The tables go to `jobs` (the contents of [`BATCH_JOBS`]).
pub fn batch_clamps(
cmds: Vec<Cmd>,
psos: &HashSet<u32>,
compute: &HashSet<u32>,
scratch: u32,
careful: bool,
jobs: &mut Vec<u8>,
) -> (Vec<Cmd>, Batched) {
use crate::indirect::batch::{JOBS, SLOT, SOURCES, TIMES, job};
const DISPATCH: u32 = 2;
let mut done = Batched::default();
let scratches: HashSet<u32> = {
let mut next = 0;
let found = find_clamps(&cmds, psos, &mut next);
found.iter().map(|c| c.scratch).collect()
};
if scratches.is_empty() {
return (cmds, done);
}
let of_clamp =
|b: &Barrier| matches!(b, Barrier::Transition { res, .. } if scratches.contains(res));
let moved = |before, after| Barrier::Transition {
flags: 0,
res: scratch,
sub: ALL,
before,
after,
};
// What the last clamp into a scratch buffer clamped: source, offset,
// kind.
let mut clamps: HashMap<u32, (u32, u64, u32)> = HashMap::new();
let (mut bound, mut constants, mut views) = (NONE, [0u32; 6], [(NONE, 0u64); 5]);
let mut out: Vec<Cmd> = Vec::with_capacity(cmds.len());
let mut open: Option<Batch> = None;
let (mut written, mut dirty, mut readable) = (true, true, false);
let mut cmds = cmds.into_iter().peekable();
while let Some(c) = cmds.next() {
match &c {
// A clamp's own commands: its root signature and all it sets.
Cmd::RootSignature {
graphics: false, ..
} if matches!(cmds.peek(), Some(Cmd::Pipeline { pso }) if psos.contains(pso)) => {}
Cmd::Pipeline { pso } => {
bound = *pso;
if !psos.contains(pso) {
out.push(c);
}
}
Cmd::Constants {
graphics: false,
values,
offset,
..
} if psos.contains(&bound) => {
for (i, v) in values.iter().enumerate() {
if let Some(c) = constants.get_mut(*offset as usize + i) {
*c = *v;
}
}
}
Cmd::RootView {
graphics: false,
param,
va: Va::At { res, offset },
..
} if psos.contains(&bound) => {
if let Some(v) = views.get_mut(*param as usize) {
*v = (*res, *offset);
}
}
Cmd::Dispatch { .. } if psos.contains(&bound) => {
done.clamps += 1;
let (source, offset) = views[1];
clamps.insert(
views[3].0,
(source, offset + u64::from(constants[3]), constants[0]),
);
// What it was clamped for follows: a batch is open by then.
let full =
|o: &Batch| !o.sources.contains(&source) && o.sources.len() == SOURCES;
if dirty && (constants[0] != DISPATCH || careful) || open.as_ref().is_some_and(full)
{
open = None;
}
if open.is_some() {
continue;
}
done.batches += 1;
let table = jobs.len();
jobs.resize(table + 16 + 16 * 2048, 0);
out.push(Cmd::Barriers {
all: vec![
Barrier::Uav {
flags: 0,
res: NONE,
},
moved(if readable { INDIRECT_ARGUMENT } else { 0 }, UNORDERED_ACCESS),
],
});
readable = true;
out.push(Cmd::RootSignature {
graphics: false,
root: BATCH_ROOT,
});
out.push(Cmd::Pipeline { pso: BATCH });
let at = out.len();
let mut view = |kind, param: usize, res, offset| {
out.push(Cmd::RootView {
graphics: false,
kind,
param: param as u32,
va: Va::At { res, offset },
});
};
for i in 0..SOURCES {
view(slot::SRV, i, source, 0);
}
view(slot::SRV, SOURCES, BATCH_JOBS, table as u64);
view(slot::UAV, SOURCES + 1, scratch, 0);
view(slot::UAV, SOURCES + 2, views[4].0, views[4].1);
out.push(Cmd::Dispatch {
groups: [JOBS.div_ceil(64), 1, 1],
});
out.push(Cmd::Barriers {
all: vec![moved(UNORDERED_ACCESS, INDIRECT_ARGUMENT)],
});
open = Some(Batch {
table,
at,
sources: Vec::new(),
known: HashMap::new(),
n: 0,
base: done.scratch,
});
(written, dirty) = (false, false);
}
Cmd::Barriers { all } => {
if all.iter().any(of_clamp) {
continue;
}
let waits = |b: &Barrier| matches!(b, Barrier::Uav { res: NONE, .. });
if all.iter().any(waits) {
if written {
open = None;
}
dirty = false;
}
out.push(c);
}
Cmd::Indirect {
signature,
most,
args,
at,
count,
count_at,
} if clamps.contains_key(args) => {
let (source, offset, kind) = clamps.get(args).copied().unwrap_or_default();
let Some(o) = &mut open else {
// Not clamped by any batch: left out, which shows.
continue;
};
let slot = match o.sources.iter().position(|&s| s == source) {
Some(i) => i,
None => {
o.sources.push(source);
let i = o.sources.len() - 1;
if let Some(Cmd::RootView {
va: Va::At { res, .. },
..
}) = out.get_mut(o.at + i)
{
*res = source;
}
i
}
};
let offset = offset + at;
let entry = o.known.entry((source, offset, kind)).or_insert((o.n, 0));
entry.1 += 1;
let (i, times) = *entry;
if i == o.n {
o.n += 1;
done.jobs += 1;
done.scratch = o.base + u64::from(o.n * SLOT);
// Wider than the live pass where its table is longer.
if let Some(Cmd::Dispatch { groups }) = out.get_mut(o.at + SOURCES + 3) {
groups[0] = groups[0].max(o.n.div_ceil(64));
}
}
let place = o.base + u64::from(i * SLOT);
let words = [
job(slot as u32, kind, times.min(TIMES)),
offset as u32,
place as u32,
0,
];
let mut put = |at: usize, w: u32| {
jobs[o.table + at..o.table + at + 4].copy_from_slice(&w.to_le_bytes());
};
for (k, w) in words.into_iter().enumerate() {
put(16 + 16 * i as usize + 4 * k, w);
}
put(0, o.n);
out.push(Cmd::Indirect {
signature: *signature,
most: *most,
args: scratch,
at: place,
count: *count,
count_at: *count_at,
});
if compute.contains(&bound) {
(written, dirty) = (true, true);
}
}
Cmd::Dispatch { .. } => {
(written, dirty) = (true, true);
out.push(c);
}
_ => out.push(c),
}
}
if readable {
out.push(Cmd::Barriers {
all: vec![moved(INDIRECT_ARGUMENT, 0)],
});
}
(out, done)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -501,4 +771,111 @@ mod tests {
[(RESULTS, 12), (RESULTS, 0), (6, 0), (RESULTS, 256 + 24)]
);
}
#[test]
fn clamps_are_batched() {
use crate::indirect::batch::job;
let clamp = |kind, offset, records, source| {
let view = |param, res| Cmd::RootView {
graphics: false,
kind: 2,
param,
va: Va::At { res, offset: 0 },
};
vec![
barriers(&[uav(0), moved(5, 0x200, 8)]),
Cmd::RootSignature {
graphics: false,
root: 8,
},
pso(9),
Cmd::Constants {
graphics: false,
param: 0,
offset: 0,
values: vec![kind, 32, records, offset, 0, 0],
},
view(1, source),
view(2, source),
view(3, 5),
view(4, 6),
go(),
barriers(&[uav(0), moved(5, 8, 0x200)]),
]
};
let run = |at| Cmd::Indirect {
signature: 1,
most: 1,
args: 5,
at,
count: 0,
count_at: 0,
};
// A dispatch, two indirect ones with a wait of the title's between
// them, then draws: a window of two and another buffer's.
let mut list = vec![pso(1), go()];
list.extend(clamp(2, 0, 1, 70));
list.extend([pso(1), run(0)]);
list.extend(clamp(2, 64, 1, 70));
list.extend([pso(1), run(0), barriers(&[uav(0)])]);
list.extend(clamp(2, 64, 1, 70));
list.extend([pso(1), run(0)]);
list.extend(clamp(10, 128, 2, 70));
list.extend([pso(2), run(0), run(32), run(32)]);
list.extend(clamp(10, 256, 1, 71));
list.extend([pso(2), run(0)]);
let (clamps, compute) = (HashSet::from([9]), HashSet::from([1]));
let table = 16 + 16 * 2048;
for (careful, batches) in [(false, 3), (true, 4)] {
let mut jobs = Vec::new();
let (out, done) = batch_clamps(list.clone(), &clamps, &compute, 99, careful, &mut jobs);
assert_eq!((done.clamps, done.batches, done.jobs), (5, batches, 6), "careful {careful}");
assert_eq!(jobs.len(), table * batches as usize);
let passes = out.iter().filter(|c| matches!(c, Cmd::Pipeline { pso: BATCH })).count();
assert_eq!(passes, batches as usize);
// Nothing of the clamps is left; the title's wait is.
assert!(!out.contains(&pso(9)) && out.contains(&barriers(&[uav(0)])));
let names_5 = |c: &Cmd| matches!(c, Cmd::Barriers { all } if all.iter().any(|b| matches!(b, Barrier::Transition { res: 5, .. })));
assert!(!out.iter().any(names_5));
let places: Vec<u64> = out
.iter()
.filter_map(|c| match c {
Cmd::Indirect { args: 99, at, .. } => Some(*at),
_ => None,
})
.collect();
assert_eq!(places, [0, 32, 64, 96, 128, 128, 160]);
// The last table: two records, one read twice, then one of the
// other buffer.
let word = |i: usize| {
let at = jobs.len() - table + 4 * i;
u32::from_le_bytes(jobs[at..at + 4].try_into().unwrap())
};
assert_eq!(word(0), 3);
let all: Vec<u32> = (4..16).map(word).collect();
assert_eq!(
all,
[
[job(0, 10, 1), 128, 96, 0],
[job(0, 10, 2), 160, 128, 0],
[job(1, 10, 1), 256, 160, 0]
]
.concat()
);
let sources: Vec<u32> = out
.iter()
.filter_map(|c| match c {
Cmd::RootView { param: 1, va: Va::At { res, .. }, .. } => Some(*res),
_ => None,
})
.collect();
assert_eq!(sources.last(), Some(&71));
// It ends common, as it began.
assert_eq!(out.last(), Some(&barriers(&[moved(99, 0x200, 0)])));
}
// A list without clamps is left as it is.
let plain = vec![pso(1), go(), barriers(&[uav(0)])];
let (out, done) = batch_clamps(plain.clone(), &clamps, &compute, 99, false, &mut Vec::new());
assert_eq!((out, done), (plain, Batched::default()));
}
}
+482 -60
View File
@@ -29,6 +29,9 @@ use super::wire::{
self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot,
};
pub mod diverge;
mod merge;
/// The name of the argument clamp's pipeline, by which its passes are
/// recognised.
pub const CLAMP: &str = "victory: argument clamp";
@@ -62,11 +65,22 @@ pub struct Options {
/// Where the picture goes (default: `replay.png` in the capture).
pub image: Option<PathBuf>,
pub buffers: Buffers,
/// Of those, only the ones all of these match ([`chosen`]).
pub only_buffers: Vec<String>,
pub no_barriers: bool,
pub merge_barriers: bool,
pub skip_clamps: bool,
/// The clamps in batches (`edit::batch_clamps`); 2: carefully.
pub batch_clamps: u32,
pub skip_hash_passes: bool,
pub one_submit: bool,
/// Copies of what the CPU wrote leave alone what the card wrote in this
/// run (`merge`).
pub merge: bool,
/// A full wait after every command that works.
pub wait_all: bool,
/// Each list sent on its own, and waited for.
pub wait_lists: bool,
/// Run only these lists (by their place in the frame).
pub only: Option<(u32, u32)>,
/// Skip what runs a pipeline whose name or shader hash has one of
@@ -87,11 +101,16 @@ impl Default for Options {
top: 20,
image: None,
buffers: Buffers::AsRecorded,
only_buffers: Vec::new(),
no_barriers: false,
merge_barriers: false,
skip_clamps: false,
batch_clamps: 0,
skip_hash_passes: false,
one_submit: false,
merge: true,
wait_all: false,
wait_lists: false,
only: None,
skip_shaders: Vec::new(),
compare: false,
@@ -105,8 +124,11 @@ impl Options {
self.no_barriers
|| self.merge_barriers
|| self.skip_clamps
|| self.batch_clamps > 0
|| self.skip_hash_passes
|| self.one_submit
|| self.wait_all
|| self.wait_lists
|| self.only.is_some()
|| !self.skip_shaders.is_empty()
}
@@ -117,8 +139,11 @@ impl Options {
no_barriers: false,
merge_barriers: false,
skip_clamps: false,
batch_clamps: 0,
skip_hash_passes: false,
one_submit: false,
wait_all: false,
wait_lists: false,
only: None,
skip_shaders: Vec::new(),
..self.clone()
@@ -144,6 +169,8 @@ pub struct Report {
/// Against the presented picture: dB (infinite: the same), and whether
/// its bytes are the same.
pub picture: Option<(f64, bool)>,
/// Of each loop's picture: dB against the presented one, and its hash.
pub pictures: Vec<(f64, String)>,
/// Things to know: from the capture and the replay.
pub notes: Vec<String>,
}
@@ -205,6 +232,20 @@ impl Report {
}
None => {}
}
if self.pictures.len() > 1 {
let all: Vec<String> = self
.pictures
.iter()
.map(|(db, hash)| format!("{db:.1} dB {}", &hash[..8]))
.collect();
let kinds: HashSet<&String> = self.pictures.iter().map(|p| &p.1).collect();
let _ = writeln!(
t,
" pictures of the loops: {} different: {}",
kinds.len(),
all.join(", ")
);
}
for n in &self.notes {
let _ = writeln!(t, " note: {n}");
}
@@ -212,6 +253,32 @@ impl Report {
}
}
/// Whether `--only-buffers` means a buffer: all of `only` match it.
/// `name=<text in its name>`, `min=<bytes>`, `max=<bytes>`,
/// `seen=<how the CPU saw it>`, `id=<a>..<b>`; with `!` in front: that does not.
fn chosen(r: &wire::Resource, only: &[String]) -> bool {
only.iter().all(|f| {
let (no, f) = match f.strip_prefix('!') {
Some(f) => (true, f),
None => (false, f.as_str()),
};
let (key, value) = f.split_once('=').unwrap_or(("name", f));
let number = value.parse().unwrap_or(0u64);
let is = match key {
"min" => r.desc.width >= number,
"max" => r.desc.width <= number,
"seen" => {
matches!(&r.place, Place::Committed { props, .. } if format!("{:?}", gpu::seen(props)).eq_ignore_ascii_case(value))
}
"id" => value.split_once("..").is_some_and(|(a, b)| {
(a.parse().unwrap_or(0)..b.parse().unwrap_or(u32::MAX)).contains(&r.id)
}),
_ => r.name.contains(value),
};
is != no
})
}
fn median(v: &[f64]) -> f64 {
let mut v = v.to_vec();
v.sort_by(f64::total_cmp);
@@ -241,20 +308,102 @@ pub fn find(folder: &Path) -> Result<PathBuf> {
.ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display()))
}
/// Writes the DXIL of the pipelines whose name has `text` in it to `shaders`
/// in the capture, and the pipelines' descriptions; what was written.
pub fn dump(folder: &Path, text: &str) -> Result<Vec<String>> {
let folder = find(folder)?;
let frame = Frame::read(&folder.join("frame.bin"))?;
let file = File::open(folder.join("shaders.bin"))?;
let to = folder.join("shaders");
std::fs::create_dir_all(&to)?;
let mut out = Vec::new();
for p in frame.pipelines.iter().filter(|p| p.name.contains(text)) {
let mut line = format!("pipeline {} {}:", p.id, p.name);
for part in &p.parts {
match part {
wire::Part::Code { kind, blob } => {
let c = &frame.codes[*blob as usize];
let mut bytes = vec![0; c.len as usize];
read_at(&file, &mut bytes, c.at)?;
let name: String = c.hash[..8].iter().map(|b| format!("{b:02x}")).collect();
std::fs::write(to.join(format!("{name}.dxil")), bytes)?;
let _ = write!(line, " {kind}={name}.dxil");
}
wire::Part::Root { root } => {
if let Some((_, blob)) = frame.roots.iter().find(|r| r.0 == *root) {
std::fs::write(to.join(format!("root-{root}.bin")), &blob.0)?;
}
let _ = write!(line, " root-{root}.bin");
}
other => {
let _ = write!(line, " {other:?}");
}
}
}
out.push(line);
}
Ok(out)
}
/// Writes, one line each, the commands of lists (by their place in the
/// frame), and before them the frame's buffers: `--listing`.
pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) -> Result<()> {
let frame = Frame::read(&find(folder)?.join("frame.bin"))?;
let pipelines: HashMap<u32, &str> =
frame.pipelines.iter().map(|p| (p.id, p.name.as_str())).collect();
for r in &frame.resources {
if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
let place = match &r.place {
Place::Committed { props, .. } => format!("{:?}", gpu::seen(props)),
other => format!("{other:?}"),
};
line(&format!("buffer {} {} bytes, {place}: {}", r.id, r.desc.width, r.name));
}
}
let mut place = 0;
for (i, s) in frame.submits.iter().enumerate() {
for &l in s.lists.iter().filter(|&&l| l != MISSING) {
let here = place;
place += 1;
if here < lists.0 || here > lists.1 {
continue;
}
line(&format!("list {here} of submission {i}"));
for (n, c) in Cmd::all(&frame.lists[l as usize].commands.0)?.iter().enumerate() {
match c {
Cmd::Pipeline { pso } => {
line(&format!("{n} Pipeline {pso} {}", pipelines.get(pso).copied().unwrap_or_default()));
}
c => line(&format!("{n} {c:?}")),
}
}
}
}
Ok(())
}
/// Loads a capture and runs it: the whole of `victory replay`. The reports,
/// with what each is of.
pub fn replay(folder: &Path, options: &Options) -> Result<Vec<(String, Report)>> {
let mut player = Player::load(folder, options)?;
let mut out = Vec::new();
if options.compare && options.edited() {
// Turn by turn: what else the machine does falls on both.
let image = Some(player.folder.join("replay-unchanged.png"));
out.push((
"unchanged".into(),
player.run(&Options {
image,
..options.plain()
})?,
));
let plain = Options {
image,
..options.plain()
};
let mut a = player.prepare(&plain)?;
let mut b = player.prepare(options)?;
let (mut stamps_a, mut stamps_b) = (Vec::new(), Vec::new());
for _ in 0..options.loops.max(1) {
stamps_a = player.once(&plain, &mut a)?;
stamps_b = player.once(options, &mut b)?;
}
out.push(("unchanged".into(), player.finish(&plain, a, &stamps_a)?));
out.push(("with the experiments".into(), player.finish(options, b, &stamps_b)?));
return Ok(out);
}
let what = if options.edited() {
"with the experiments"
@@ -307,11 +456,18 @@ pub struct Player {
/// States at the start of the frame and after it.
start: HashMap<u32, Vec<u32>>,
end: HashMap<u32, Vec<u32>>,
/// For `Options::merge`.
merger: Option<merge::Merger>,
merging: bool,
/// Resources the card may write in the frame.
card_writes: HashSet<u32>,
/// The results of clamp passes ([`RESULTS`]).
results: Option<ID3D12Resource>,
commands: Vec<Vec<Cmd>>,
/// Resources in the states of the start (not those of the end).
fresh: bool,
/// States as the last run left them (`diverge`).
at: States,
notes: Vec<String>,
}
@@ -370,9 +526,13 @@ impl Player {
delta_parts: Vec::new(),
start: HashMap::new(),
end: HashMap::new(),
merger: None,
merging: false,
card_writes: HashSet::new(),
results: None,
commands,
fresh: true,
at: States::default(),
notes: frame
.notes
.iter()
@@ -387,7 +547,7 @@ impl Player {
*at = Instant::now();
};
let mut at = Instant::now();
player.make_resources(options.buffers)?;
player.make_resources(options.buffers, &options.only_buffers)?;
step("resources", &mut at);
player.make_pipelines()?;
step("pipelines", &mut at);
@@ -395,12 +555,22 @@ impl Player {
step("descriptors", &mut at);
player.load_contents()?;
step("contents", &mut at);
player.make_masters()?;
player.make_masters(options.buffers)?;
step("copies to restore from", &mut at);
let steps: Vec<String> = steps
.iter()
.map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64()))
.collect();
if let Some([budget, used, pc]) = player.memory() {
let over = if used + 256 > budget {
": over the budget, so the system moves memory to the PC's and the times are not the card's"
} else {
""
};
player.notes.push(format!(
"{used} MB of the card's memory used, budget {budget} MB; {pc} MB of the PC's{over}"
));
}
player.notes.push(format!(
"loaded in {:.1} s: {}",
began.elapsed().as_secs_f64(),
@@ -467,7 +637,7 @@ impl Player {
}
}
fn make_resources(&mut self, buffers: Buffers) -> Result<()> {
fn make_resources(&mut self, buffers: Buffers, only: &[String]) -> Result<()> {
// A heap of memory the CPU sees becomes one the card may write too:
// what the CPU wrote is put back by the card.
let props = |p: &wire::HeapProps, buffer: bool| -> D3D12_HEAP_PROPERTIES {
@@ -511,7 +681,7 @@ impl Player {
for h in &self.frame.heaps {
let desc = D3D12_HEAP_DESC {
SizeInBytes: h.size,
Properties: props(&h.props, used_by_buffers_only.contains(&h.id)),
Properties: props(&h.props, only.is_empty() && used_by_buffers_only.contains(&h.id)),
Alignment: h.alignment,
Flags: D3D12_HEAP_FLAGS(h.flags & !DROP),
};
@@ -522,8 +692,15 @@ impl Player {
self._heaps.extend(heap.map(|heap| (h.id, heap)));
}
let mut failed = 0;
let mut moves: BTreeMap<String, (u32, u64)> = BTreeMap::new();
for (index, r) in self.frame.resources.iter().enumerate() {
let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
let moved = is_buffer && chosen(r, only);
if moved && let Place::Committed { props, .. } = &r.place {
let seen = gpu::seen(props);
let m = moves.entry(format!("{seen:?}")).or_insert((0u32, 0u64));
*m = (m.0 + 1, m.1 + r.desc.width);
}
let desc = gpu::to_desc(&r.desc);
let mut made: Option<ID3D12Resource> = None;
let clear: Option<D3D12_CLEAR_VALUE> = r.clear.map(|c| {
@@ -546,7 +723,7 @@ impl Player {
None => Err(windows::core::Error::empty()),
},
Place::Committed { props: p, flags } => {
let p = props(p, is_buffer);
let p = props(p, moved);
let state = if p.Type == D3D12_HEAP_TYPE_READBACK {
D3D12_RESOURCE_STATE_COPY_DEST
} else {
@@ -609,6 +786,11 @@ impl Player {
if failed > 0 {
self.note(format!("{failed} resources could not be made again"));
}
if buffers != Buffers::AsRecorded {
self.notes.push(format!(
"--buffers is of, by how the CPU saw them (buffers, bytes): {moves:?}"
));
}
Ok(())
}
@@ -1354,7 +1536,7 @@ impl Player {
}
/// Copies of what the frame changes; and the states it leaves.
fn make_masters(&mut self) -> Result<()> {
fn make_masters(&mut self, buffers: Buffers) -> Result<()> {
let mut states = States::default();
for r in &self.frame.resources {
if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
@@ -1386,6 +1568,7 @@ impl Player {
.filter(|r| r.state.iter().any(|s| s & WRITE != 0))
.map(|r| r.id)
.collect();
let mut by_cpu: HashSet<u32> = HashSet::new();
for (i, s) in self.frame.submits.iter().enumerate() {
for &l in s.lists.iter().filter(|&&l| l != MISSING) {
for c in &self.commands[l as usize] {
@@ -1436,7 +1619,7 @@ impl Player {
}
states.decay();
if i > 0 {
written.extend(self.delta_parts[i].iter().map(|(d, _)| d.res));
by_cpu.extend(self.delta_parts[i].iter().map(|(d, _)| d.res));
}
}
// Buffers any unordered-access view names.
@@ -1469,6 +1652,8 @@ impl Player {
}
}
}
self.card_writes = written.clone();
written.extend(by_cpu);
for id in self.start.keys() {
self.end
.insert(*id, states.get(*id).unwrap_or(vec![COMMON]));
@@ -1500,7 +1685,10 @@ impl Player {
let size = unsafe { self.device.GetResourceAllocationInfo(0, &[desc]) }.SizeInBytes;
let room = self.room();
let buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
let pc = buffer && room.is_some_and(|room| room < size + (1 << 30));
// With all buffers in the card's memory there is no room for
// their copies as well.
let pc = buffer
&& (buffers == Buffers::Card || room.is_some_and(|room| room < size + (1 << 30)));
let props = if pc {
D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_CUSTOM,
@@ -1574,6 +1762,31 @@ impl Player {
Ok(())
}
/// The card's memory budget and use, and the use of the PC's memory, in
/// MB.
fn memory(&self) -> Option<[u64; 3]> {
let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
let mut pc = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
// SAFETY: plain queries.
unsafe {
let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
let adapter: IDXGIAdapter3 = factory
.EnumAdapterByLuid(self.device.GetAdapterLuid())
.ok()?;
adapter
.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
.ok()?;
adapter
.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut pc)
.ok()?;
}
Some([
own.Budget >> 20,
own.CurrentUsage >> 20,
pc.CurrentUsage >> 20,
])
}
/// What is free of the card's memory budget.
fn room(&self) -> Option<u64> {
let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
@@ -1628,6 +1841,13 @@ impl Player {
for (id, m) in &restored {
list.CopyResource(&objects[id].res, *m);
}
if let Some(merger) = &self.merger {
for (id, base) in &merger.bases {
if let Some((_, m)) = self.masters.iter().find(|m| m.0 == *id) {
list.CopyResource(base, m);
}
}
}
barriers(list, &back);
}
})?;
@@ -1671,6 +1891,17 @@ impl Player {
.push(format!("{} pipelines match --skip-shader", skip.len()));
}
let hash = self.pipelines_named(COMPARE);
let clamp = self.pipelines_named(CLAMP);
let compute: HashSet<u32> = self
.frame
.pipelines
.iter()
.filter(|p| p.parts.iter().any(|part| matches!(part, wire::Part::Code { kind, .. } if *kind == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0)))
.map(|p| p.id)
.collect();
let mut batched = edit::Batched::default();
let mut jobs = Vec::new();
let mut scratches = Vec::new();
let (mut skipped, mut hashed, mut uavs, mut merged) = (0, 0, 0, 0);
let mut place = 0;
let mut out = Vec::new();
@@ -1689,6 +1920,24 @@ impl Player {
{
cmds = edit::skip_clamps(cmds, c);
}
if o.batch_clamps > 0 {
let scratch = edit::BATCH_SCRATCH - here;
let done;
(cmds, done) = edit::batch_clamps(
cmds,
&clamp,
&compute,
scratch,
o.batch_clamps > 1,
&mut jobs,
);
batched.clamps += done.clamps;
batched.batches += done.batches;
batched.jobs += done.jobs;
if done.scratch > 0 {
scratches.push((scratch, done.scratch));
}
}
let mut n;
if !skip.is_empty() {
(cmds, n) = edit::skip_pipelines(cmds, &skip);
@@ -1710,6 +1959,15 @@ impl Player {
}
out.push(lists);
}
if o.batch_clamps > 0 {
report.notes.push(format!(
"--batch-clamps: {} clamp passes became {}, of {} records",
batched.clamps, batched.batches, batched.jobs
));
if let Err(e) = self.make_batches(&jobs, &scratches) {
report.notes.push(format!("--batch-clamps failed: {e:#}"));
}
}
if !skip.is_empty() {
report
.notes
@@ -1733,6 +1991,44 @@ impl Player {
out
}
/// What lists edited by [`edit::batch_clamps`] name: the pass, its
/// tables and scratch buffers.
fn make_batches(&mut self, jobs: &[u8], scratches: &[(u32, u64)]) -> Result<()> {
let (root, pso) = crate::indirect::batch_for(&self.device)?;
self.roots.insert(edit::BATCH_ROOT, root);
self.pipelines.insert(edit::BATCH, pso);
let (table, data) = gpu::buffer(
&self.device,
D3D12_HEAP_TYPE_UPLOAD,
jobs.len().max(4) as u64,
D3D12_RESOURCE_FLAG_NONE,
)?;
// SAFETY: a mapping of as many bytes.
unsafe { std::ptr::copy_nonoverlapping(jobs.as_ptr(), data.cast(), jobs.len()) };
let mut all = vec![(edit::BATCH_JOBS, table)];
for &(id, bytes) in scratches {
let (scratch, _) = gpu::buffer(
&self.device,
D3D12_HEAP_TYPE_DEFAULT,
bytes.next_multiple_of(64 << 10),
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
)?;
all.push((id, scratch));
}
for (id, res) in all {
// SAFETY: a live buffer.
let va = unsafe { res.GetGPUVirtualAddress() };
let object = Object {
res,
va,
index: 0,
subs: 1,
};
self.objects.insert(id, object);
}
Ok(())
}
/// The clamp passes of each list of the frame, in order, and their
/// results in [`RESULTS`] (by a run that keeps them).
fn clamp_results(&mut self, report: &mut Report) -> Result<Vec<Vec<Clamp>>> {
@@ -1769,7 +2065,7 @@ impl Player {
);
let built = self.build(&submits, &Options::default())?;
self.restore(true)?;
self.send(&built, false)?;
self.send(&built, &Options::default())?;
self.fresh = false;
Ok(clamps)
}
@@ -1818,10 +2114,15 @@ impl Player {
unsafe {
let mut seen = HashSet::new();
let mut after = Vec::new();
let mut merges = Vec::new();
for (d, at) in parts {
let Some(ob) = self.objects.get(&d.res) else {
continue;
};
if self.merging && self.card_writes.contains(&d.res) {
merges.push((d.res, d.at, *at, d.len));
continue;
}
open.1.CopyBufferRegion(&ob.res, d.at, from, *at, d.len);
if seen.insert(d.res) {
// Back to the common state by itself, for
@@ -1830,6 +2131,11 @@ impl Player {
}
}
barriers(&open.1, &after);
if !merges.is_empty() {
self.wait_for_all(&open.1);
self.merge_all(&open.1, from.GetGPUVirtualAddress(), &merges);
self.wait_for_all(&open.1);
}
}
Some(self.close(open, &heap, &mut next, Vec::new())?)
}
@@ -1838,8 +2144,13 @@ impl Player {
let mut built = Vec::new();
for cmds in lists {
let open = self.open(&heap, &mut next)?;
let stamps =
self.translate(&open.1, cmds, i, o.detailed.then_some((&heap, &mut next)));
let stamps = self.translate(
&open.1,
cmds,
i,
o.detailed.then_some((&heap, &mut next)),
o.wait_all,
);
built.push(self.close(open, &heap, &mut next, stamps)?);
}
steps.push((delta, built));
@@ -1979,9 +2290,11 @@ impl Player {
cmds: &[Cmd],
submit: usize,
mut stamp: Option<(&ID3D12QueryHeap, &mut u32)>,
wait: bool,
) -> Vec<Stamp> {
let version = self.version_of.get(submit).copied().unwrap_or(0);
let clamps = self.pipelines_named(CLAMP);
let mut clamps = self.pipelines_named(CLAMP);
clamps.insert(edit::BATCH);
let compares = self.pipelines_named(COMPARE);
let mesh: HashSet<u32> = self
.frame
@@ -2003,13 +2316,55 @@ impl Player {
.collect();
let mut stamps = Vec::new();
let mut bound = NONE;
// What the compute side has bound.
let mut compute: Vec<Cmd> = Vec::new();
for c in cmds {
if let Cmd::Pipeline { pso } = c {
bound = *pso;
}
// SAFETY: an open list; the objects are the frame's, alive with
// the player; commands the host recorded the same way.
unsafe { self.command(list, c, version) };
let merged = self.merged_copy(c);
if let Some((from, what)) = merged {
// SAFETY: an open list; live buffers; what the compute side
// of it had bound is bound again.
unsafe {
self.wait_for_all(list);
self.merge_all(list, from, &[what]);
self.wait_for_all(list);
for c in &compute {
self.command(list, c, version);
}
}
} else {
// SAFETY: an open list; the objects are the frame's, alive
// with the player; commands the host recorded the same way.
unsafe { self.command(list, c, version) };
}
match c {
Cmd::RootSignature {
graphics: false, ..
} => {
compute.retain(|c| matches!(c, Cmd::Pipeline { .. }));
compute.push(c.clone());
}
Cmd::Pipeline { .. } => {
compute.retain(|c| !matches!(c, Cmd::Pipeline { .. }));
compute.push(c.clone());
}
Cmd::Table {
graphics: false, ..
}
| Cmd::Constants {
graphics: false, ..
}
| Cmd::RootView {
graphics: false, ..
} => compute.push(c.clone()),
_ => {}
}
if wait && c.works() {
// SAFETY: an open list.
unsafe { self.wait_for_all(list) };
}
let timed = c.works() || matches!(c, Cmd::Barriers { .. });
if timed && let Some((heap, next)) = &mut stamp {
// SAFETY: as above.
@@ -2474,7 +2829,7 @@ impl Player {
}
/// Sends the frame, waits for it, and reads the timestamps.
fn send(&mut self, s: &Sends, one: bool) -> Result<Vec<u64>> {
fn send(&mut self, s: &Sends, o: &Options) -> Result<Vec<u64>> {
let cast = |l: &ID3D12GraphicsCommandList| l.cast::<ID3D12CommandList>().map(Some);
let mut submissions: Vec<Vec<Option<ID3D12CommandList>>> = Vec::new();
for (delta, lists) in &s.steps {
@@ -2489,7 +2844,7 @@ impl Player {
submissions.push(all);
}
}
if one {
if o.one_submit {
let mut all = Vec::new();
for (i, lists) in submissions.into_iter().enumerate() {
if i > 0
@@ -2504,7 +2859,14 @@ impl Player {
// SAFETY: closed lists whose last run has finished.
unsafe {
for all in &submissions {
self.worker.queue.ExecuteCommandLists(all);
if !o.wait_lists {
self.worker.queue.ExecuteCommandLists(all);
continue;
}
for l in all {
self.worker.queue.ExecuteCommandLists(&[l.clone()]);
self.worker.idle()?;
}
}
self.worker
.queue
@@ -2519,52 +2881,76 @@ impl Player {
/// Runs the frame as the options say.
pub fn run(&mut self, o: &Options) -> Result<Report> {
let mut made = self.prepare(o)?;
let mut stamps = Vec::new();
for _ in 0..o.loops.max(1) {
stamps = self.once(o, &mut made)?;
}
self.finish(o, made, &stamps)
}
/// The lists for a run as the options say.
fn prepare(&mut self, o: &Options) -> Result<(Sends, Report)> {
let mut report = Report {
notes: self.notes.clone(),
..Default::default()
};
self.set_merging(o.merge)?;
let clamps = if o.skip_clamps {
self.clamp_results(&mut report)?
} else {
Vec::new()
};
let submits = self.edited(o, &mut report, &clamps);
let built = self.build(&submits, o)?;
let mut stamps = Vec::new();
for _ in 0..o.loops.max(1) {
self.restore(o.restore)?;
self.fresh = false;
stamps = self.send(&built, o.one_submit)?;
let ms = |a: u32, b: u32| {
stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency
};
let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect();
let (Some(first), Some(last)) = (lists.first(), lists.last()) else {
bail!("no lists to run");
};
let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref());
report.delta_ms.push(
delta
.filter(|d| d.first > first.first)
.map(|d| ms(d.first, d.last))
.sum(),
);
report.frame_ms.push(ms(first.first, last.last));
let each = |l: &[Built]| match (l.first(), l.last()) {
(Some(a), Some(b)) => ms(a.first, b.last),
_ => 0.0,
};
report.submits = built
.steps
.iter()
.map(|(_, l)| (l.len(), each(l)))
.collect();
report
.busy_ms
.push(report.submits.iter().map(|s| s.1).sum());
Ok((self.build(&submits, o)?, report))
}
/// One run of the frame, noted in the report; its timestamps.
fn once(&mut self, o: &Options, (built, report): &mut (Sends, Report)) -> Result<Vec<u64>> {
self.restore(o.restore)?;
self.fresh = false;
let stamps = self.send(built, o)?;
if let Some((db, _, hash, _)) = self.picture_now()? {
report.pictures.push((db, hash));
}
let ms = |a: u32, b: u32| {
stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency
};
let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect();
let (Some(first), Some(last)) = (lists.first(), lists.last()) else {
bail!("no lists to run");
};
let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref());
report.delta_ms.push(
delta
.filter(|d| d.first > first.first)
.map(|d| ms(d.first, d.last))
.sum(),
);
report.frame_ms.push(ms(first.first, last.last));
let each = |l: &[Built]| match (l.first(), l.last()) {
(Some(a), Some(b)) => ms(a.first, b.last),
_ => 0.0,
};
report.submits = built
.steps
.iter()
.map(|(_, l)| (l.len(), each(l)))
.collect();
report
.busy_ms
.push(report.submits.iter().map(|s| s.1).sum());
Ok(stamps)
}
/// The report after the last run.
fn finish(&mut self, o: &Options, (built, mut report): (Sends, Report), stamps: &[u64]) -> Result<Report> {
if o.detailed {
self.detail(&built, &stamps, o, &mut report);
self.detail(&built, stamps, o, &mut report);
}
if self.merging {
let notes = self.merge_notes(o.loops)?;
report.notes.extend(notes);
}
self.picture(o, &mut report)?;
if let Some(q) = &self.info {
@@ -2607,6 +2993,34 @@ impl Player {
.collect();
}
/// The presented picture as it is now: dB against the recorded one,
/// whether its bytes are the same, its hash, and its pixels.
fn picture_now(&mut self) -> Result<Option<(f64, bool, String, Vec<u8>)>> {
let Some(p) = self.frame.presents.last().cloned() else {
return Ok(None);
};
let Some(bytes) = self.contents(p.res)? else {
return Ok(None);
};
let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else {
return Ok(None);
};
let mut recorded = vec![0; bytes.len()];
read_at(
&File::open(self.folder.join("present.bin"))?,
&mut recorded,
p.file,
)?;
let was = gpu::rgb(p.width, p.height, p.pitch, p.format, &recorded).unwrap_or_default();
let hash = blake3::hash(&rgb).to_hex().to_string();
Ok(Some((
gpu::psnr(&rgb, &was),
rows_equal(&p, &bytes, &recorded),
hash,
rgb,
)))
}
/// Saves the presented picture and compares it with the recorded one.
fn picture(&mut self, o: &Options, report: &mut Report) -> Result<()> {
let Some(p) = self.frame.presents.last().cloned() else {
@@ -2796,7 +3210,15 @@ fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option<ID3D1
if debug {
let mut layer: Option<ID3D12Debug> = None;
match D3D12GetDebugInterface(&mut layer) {
Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
Ok(()) => layer.iter().for_each(|l| {
l.EnableDebugLayer();
// Every shader access checked on the card: very slow.
if std::env::var_os("VICTORY_REPLAY_GBV").is_some()
&& let Ok(l) = l.cast::<ID3D12Debug1>()
{
l.SetEnableGPUBasedValidation(true);
}
}),
Err(e) => tracing::warn!("no debug layer: {e}"),
}
}
File diff suppressed because it is too large. Load diff
+291
View File
@@ -0,0 +1,291 @@
//! What the CPU wrote, put in without what the card wrote.
//!
//! The host layer brings results of shaders back to title memory, and sends
//! pieces of title memory up again (64 KiB at a time) when the title changed
//! some of them. What goes up therefore holds results of the recorded frame.
//! Shaders that give out places with atomics give other places in every run:
//! the recorded results put over a replay's own leave lists and what points
//! into them of two different frames. So where a copy brings memory of the
//! CPU to a buffer the card writes, words the card has written since the
//! start of the frame (which are not what was last put there) stay.
use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
use windows::Win32::Graphics::Direct3D::ID3DBlob;
use super::*;
const SOURCE: &str = r#"
#define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0), UAV(u1), UAV(u2)"
cbuffer C : register(b0) { uint words; uint call; };
ByteAddressBuffer from : register(t0);
RWByteAddressBuffer to : register(u0);
RWByteAddressBuffer base : register(u1);
// For each call: words put, words of the card's left that were to get
// another value, and of those the ones that were to get back what stood
// there before the card wrote.
RWByteAddressBuffer counts : register(u2);
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
if (id.x >= words) return;
uint at = id.x * 4;
uint v = from.Load(at), now = to.Load(at), was = base.Load(at), n;
if (now != was) {
if (v == now) return;
counts.InterlockedAdd(call * 12 + 4, 1, n);
if (v == was) counts.InterlockedAdd(call * 12 + 8, 1, n);
return;
}
if (v == now) return;
counts.InterlockedAdd(call * 12, 1, n);
to.Store(at, v);
base.Store(at, v);
}
"#;
pub(super) struct Merger {
root: ID3D12RootSignature,
pso: ID3D12PipelineState,
/// For each buffer: what was last put there (at first, what it held at
/// the frame's start).
pub(super) bases: HashMap<u32, ID3D12Resource>,
pub(super) counts: ID3D12Resource,
/// The merges recorded: buffer, offset, length (in `CALLS` at the most).
pub(super) calls: std::cell::RefCell<Vec<(u32, u64, u64)>>,
}
const CALLS: u64 = 1 << 16;
impl Player {
/// The copy of a piece of a card buffer's CPU side to it: its source's
/// address, then the buffer, offset, 0 and length.
pub(super) fn merged_copy(&self, c: &Cmd) -> Option<(u64, (u32, u64, u64, u64))> {
let Cmd::CopyBuffer {
dst,
dst_at,
src,
src_at,
len,
} = c
else {
return None;
};
if !self.merging
|| !self.pairs(*src, *dst)
|| dst_at != src_at
|| dst_at % 4 != 0
|| len % 4 != 0
{
return None;
}
self.merger.as_ref()?.bases.get(dst)?;
let from = self.objects.get(src)?.va + src_at;
Some((from, (*dst, *dst_at, 0, *len)))
}
/// Whether `src` is the CPU's side of card buffer `dst`.
fn pairs(&self, src: u32, dst: u32) -> bool {
let (Some(a), Some(b)) = (self.objects.get(&src), self.objects.get(&dst)) else {
return false;
};
let (a, b) = (
&self.frame.resources[a.index],
&self.frame.resources[b.index],
);
let cpu =
matches!(&a.place, Place::Committed { props, .. } if gpu::seen(props) == Seen::Cached);
cpu && b.name.ends_with("on the card")
&& a.desc.width == b.desc.width
&& self.card_writes.contains(&dst)
}
/// Records merges: (buffer, offset in it, offset from `from`, length).
///
/// # Safety
/// An open list; `from` is the address of memory that holds the bytes.
pub(super) unsafe fn merge_all(
&self,
list: &ID3D12GraphicsCommandList,
from: u64,
all: &[(u32, u64, u64, u64)],
) {
let Some(m) = &self.merger else { return };
// SAFETY: the caller's; live buffers.
unsafe {
list.SetComputeRootSignature(&m.root);
list.SetPipelineState(&m.pso);
for (id, at, source, len) in all {
let (Some(o), Some(base)) = (self.objects.get(id), m.bases.get(id)) else {
continue;
};
let base = base.GetGPUVirtualAddress();
// At most 65,535 groups in a dispatch.
const MOST: u64 = 8 << 20;
let mut done = 0;
while done < *len {
let n = MOST.min(len - done);
let words = (n / 4) as u32;
let mut calls = m.calls.borrow_mut();
let call = (calls.len() as u64).min(CALLS - 1) as u32;
if calls.len() < CALLS as usize {
calls.push((*id, at + done, n));
}
drop(calls);
list.SetComputeRoot32BitConstants(0, 2, [words, call].as_ptr().cast(), 0);
list.SetComputeRootUnorderedAccessView(4, m.counts.GetGPUVirtualAddress());
list.SetComputeRootShaderResourceView(1, from + source + done);
list.SetComputeRootUnorderedAccessView(2, o.va + at + done);
list.SetComputeRootUnorderedAccessView(3, base + at + done);
list.Dispatch(words.div_ceil(64), 1, 1);
done += n;
}
}
}
}
/// Switches merging on or off; makes what it needs at first.
pub(super) fn set_merging(&mut self, on: bool) -> Result<()> {
self.merging = on;
if let Some(m) = &self.merger {
m.calls.borrow_mut().clear();
}
if !on || self.merger.is_some() {
return Ok(());
}
let mut code: Option<ID3DBlob> = None;
// SAFETY: the source and names live through the call; the blob's own
// bytes.
let (root, pso) = unsafe {
D3DCompile(
SOURCE.as_ptr().cast(),
SOURCE.len(),
None,
None,
None,
windows::core::s!("main"),
windows::core::s!("cs_5_1"),
0,
0,
&mut code,
None,
)?;
let code = code.context("no merge shader")?;
let bytes = std::slice::from_raw_parts(
code.GetBufferPointer().cast::<u8>(),
code.GetBufferSize(),
);
let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
let pso =
self.device
.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE {
pShaderBytecode: bytes.as_ptr().cast(),
BytecodeLength: bytes.len(),
},
..Default::default()
})?;
(root, pso)
};
let mut ids: HashSet<u32> = HashSet::new();
for c in self.commands.iter().flatten() {
if let Cmd::CopyBuffer { dst, src, .. } = c
&& self.pairs(*src, *dst)
{
ids.insert(*dst);
}
}
ids.extend(
self.delta_parts
.iter()
.flatten()
.map(|(d, _)| d.res)
.filter(|id| self.card_writes.contains(id)),
);
let mut bases = HashMap::new();
let mut total = 0;
for id in ids {
if !self.masters.iter().any(|m| m.0 == id) {
continue;
}
let size = self.frame.resources[self.objects[&id].index].desc.width;
let flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
bases.insert(
id,
gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, size, flags)?.0,
);
total += size;
}
let masters: HashMap<u32, ID3D12Resource> = self.masters.iter().cloned().collect();
self.worker.run(|list| {
for (id, base) in &bases {
// SAFETY: an open list; live buffers of one size.
unsafe { list.CopyResource(base, &masters[id]) };
}
})?;
tracing::info!(
buffers = bases.len(),
mb = total >> 20,
"bases of merged copies"
);
let flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
let counts = gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, CALLS * 12, flags)?.0;
self.merger = Some(Merger {
root,
pso,
bases,
counts,
calls: Default::default(),
});
Ok(())
}
/// What the merges of the last run (of `loops`, which add up) found.
pub(super) fn merge_notes(&mut self, loops: u32) -> Result<Vec<String>> {
let Some(m) = &self.merger else {
return Ok(Vec::new());
};
let (counts, calls) = (m.counts.clone(), m.calls.borrow().clone());
let (back, data) = gpu::buffer(
&self.device,
D3D12_HEAP_TYPE_READBACK,
CALLS * 12,
D3D12_RESOURCE_FLAG_NONE,
)?;
self.worker.run(|list| {
// SAFETY: an open list; live buffers.
unsafe { list.CopyBufferRegion(&back, 0, &counts, 0, CALLS * 12) };
})?;
// SAFETY: the mapping; the copy into it has run.
let all = unsafe { std::slice::from_raw_parts(data.cast::<u32>(), CALLS as usize * 3) };
let each = |k: usize| {
all.iter()
.skip(k)
.step_by(3)
.map(|&n| u64::from(n))
.sum::<u64>()
/ u64::from(loops.max(1))
};
let mut out = vec![format!(
"{} copies of what the CPU wrote to memory the card writes: {} words put; {} left as the card wrote them in this run, where other values were to go ({} of them the values from before the card wrote)",
calls.len(),
each(0),
each(1),
each(2)
)];
let mut worst: Vec<(u32, usize)> = (0..calls.len())
.map(|i| (all[i * 3 + 2], i))
.filter(|w| w.0 > 0)
.collect();
worst.sort_by(|a, b| b.0.cmp(&a.0));
for (n, i) in worst.into_iter().take(8) {
let (id, at, len) = calls[i];
out.push(format!(
" values from before the card wrote: {} words, {} +{at:#x} {len:#x} bytes",
n / loops.max(1),
self.called(id)
));
}
Ok(out)
}
}
+13 -2
View File
@@ -351,7 +351,10 @@ pub(super) struct Recorder {
/// made are kept alive.
pub(super) watching: AtomicBool,
pub(super) writes: Mutex<Vec<(u32, u32, u32)>>,
pub(super) held: Mutex<Vec<ID3D12Resource>>,
/// Resources kept alive for a capture, by id. One that dies all the same
/// (its last reference was going when ours was taken) is taken out: see
/// `Recorder::gone`.
pub(super) held: Mutex<HashMap<u32, ID3D12Resource>>,
/// What could not be recorded, with how often.
problems: Mutex<BTreeMap<String, u64>>,
/// Submissions and presents, one at a time.
@@ -586,7 +589,7 @@ impl Recorder {
write(&self.resources).insert(id, res);
self.ids.set(p as usize, id);
if late {
lock(&self.held).push(ID3D12Resource::clone(&object));
lock(&self.held).insert(id, ID3D12Resource::clone(&object));
}
self.tell_gone(
&*object,
@@ -602,6 +605,14 @@ impl Recorder {
fn gone(&self, what: &Gone) {
match *what {
Gone::Resource { id, ptr, va } => {
// The memory goes whatever we hold: letting go of it later
// would be a call into what is there then.
if let Some(dead) = lock(&self.held).remove(&id) {
std::mem::forget(dead);
self.problem(
"a resource died as the frame started: its contents may be missing",
);
}
self.ids.remove(ptr, id);
write(&self.resources).remove(&id);
if va != 0 {
+23 -12
View File
@@ -279,7 +279,8 @@ impl Reads {
/// A buffer the CPU sees.
struct CpuBuffer {
id: u32,
res: ID3D12Resource,
/// Held by the recorder, not by this.
res: std::mem::ManuallyDrop<ID3D12Resource>,
/// Where it is read: its mapping, or the read-back copy of it.
live: *const u8,
/// The read-back buffer and the offset in it, for one that is slow to
@@ -298,8 +299,6 @@ unsafe impl Sync for CpuBuffer {}
struct Capture {
worker: Worker,
others: Vec<Worker>,
/// Resources the frame can use, kept alive.
held: Vec<ID3D12Resource>,
started: bool,
frame: u32,
states: States,
@@ -341,7 +340,6 @@ impl Capture {
Ok(Capture {
worker: Worker::new(&device, &direct.0)?,
others,
held: Vec::new(),
started: false,
frame: 0,
states: States::default(),
@@ -388,7 +386,8 @@ impl Capture {
let mut all: Vec<Arc<Res>> = Vec::new();
{
let live = read(&r.resources);
for res in live.values() {
let mut held = lock(&r.held);
for res in live.values().filter(|res| !res.late) {
let object = res.object();
// SAFETY: a live resource, or one whose end waits for the
// lock held here (`Recorder::gone`): the count tells which.
@@ -405,9 +404,9 @@ impl Capture {
// giving it back would end it a second time.
continue;
}
// SAFETY: the reference just taken.
self.held
.push(unsafe { ID3D12Resource::from_raw(object.as_raw()) });
// SAFETY: the reference just taken. (The count does not tell
// all that are dying: `Recorder::gone` takes those out.)
held.insert(res.id, unsafe { ID3D12Resource::from_raw(object.as_raw()) });
all.push(res.clone());
}
}
@@ -594,7 +593,11 @@ impl Capture {
}
// Moved in: the writers end when it goes.
let todo = todo;
for pieces in batches {
for mut pieces in batches {
{
let held = lock(&r.held);
pieces.retain(|p| held.contains_key(&p.res.id));
}
if pieces.is_empty() {
continue;
}
@@ -629,8 +632,12 @@ impl Capture {
r.problem("contents of textures in memory the CPU sees are not in the capture");
continue;
}
// Those alive at the start are held, those made since too.
let object = ID3D12Resource::clone(&res.object());
// Those alive at the start are held, those made since too; what
// is not is dying.
if !lock(&r.held).contains_key(&res.id) {
continue;
}
let object = res.object();
let size = res.desc.width as usize;
let (live, through) = if res.seen == Seen::Cached {
let mut data = std::ptr::null_mut();
@@ -675,6 +682,10 @@ impl Capture {
/// zero).
fn changed(&mut self, r: &Recorder, reads: &Reads) -> Result<Vec<Delta>, Fault> {
self.new_buffers(r)?;
{
let held = lock(&r.held);
self.buffers.retain(|b| held.contains_key(&b.id));
}
let parts: Vec<(usize, usize, usize)> = self
.buffers
.iter()
@@ -697,7 +708,7 @@ impl Capture {
list.CopyBufferRegion(
&blocks[block].0,
at + from as u64,
&b.res,
&*b.res,
from as u64,
(to - from) as u64,
)
+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)]
+504 -1
View File
@@ -75,6 +75,105 @@ std::arch::global_asm!(
"vzeroupper",
"xor eax, eax",
"ret",
".globl victory_safe_update",
".globl victory_safe_update_at",
".globl victory_safe_update_after",
".globl victory_safe_update_failed",
// rcx destination, rdx source, r8 bytes (whole 64s, not none), r9 where
// the offset of the first 64 bytes that differed goes (-1: none did) and
// behind it the offset of the end of the last: stores the 64s that
// differ. eax: whether all could be read.
"victory_safe_update:",
"xor r10d, r10d",
"mov r11, -1",
"xor eax, eax",
"2:",
"victory_safe_update_at:",
"vmovdqu ymm0, ymmword ptr [rdx + r10]",
"vmovdqu ymm1, ymmword ptr [rdx + r10 + 32]",
"victory_safe_update_after:",
"vpxor ymm2, ymm0, ymmword ptr [rcx + r10]",
"vpxor ymm3, ymm1, ymmword ptr [rcx + r10 + 32]",
"vpor ymm2, ymm2, ymm3",
"vptest ymm2, ymm2",
"jz 3f",
"vmovdqu ymmword ptr [rcx + r10], ymm0",
"vmovdqu ymmword ptr [rcx + r10 + 32], ymm1",
"cmp r11, -1",
"cmove r11, r10",
"lea rax, [r10 + 64]",
"3:",
"add r10, 64",
"cmp r10, r8",
"jb 2b",
"mov qword ptr [r9], r11",
"mov qword ptr [r9 + 8], rax",
"vzeroupper",
"mov eax, 1",
"ret",
"victory_safe_update_failed:",
"vzeroupper",
"xor eax, eax",
"ret",
".globl victory_safe_merge",
".globl victory_safe_merge_at",
".globl victory_safe_merge_after",
".globl victory_safe_merge_failed",
// rcx title memory, rdx what the card holds, r8 what it held when last
// looked at, r9 blocks of 32 bytes, fifth where the two counts go. Where
// a byte of the second differs from the third, it goes into title memory
// (as whole dwords, and only dwords that then differ from what is there)
// and into the third; each block of title memory is read just before it
// is written. rax: the blocks left when a page of title memory could not
// be read or written (0: all done). The counts: blocks in which the
// second and third differed, dwords stored in title memory.
"victory_safe_merge:",
"xor r10d, r10d",
"xor r11d, r11d",
"test r9, r9",
"jz 6f",
"vpcmpeqd ymm5, ymm5, ymm5",
"2:",
"vmovdqu ymm0, ymmword ptr [rdx]",
"vpcmpeqb ymm1, ymm0, ymmword ptr [r8]",
"vpmovmskb eax, ymm1",
"cmp eax, -1",
"je 5f",
"victory_safe_merge_at:",
"vmovdqu ymm2, ymmword ptr [rcx]",
"vpblendvb ymm3, ymm0, ymm2, ymm1",
"vpcmpeqd ymm4, ymm3, ymm2",
"vmovmskps eax, ymm4",
"xor eax, 255",
"jz 4f",
"cmp eax, 255",
"je 3f",
"vpxor ymm4, ymm4, ymm5",
"vpmaskmovd ymmword ptr [rcx], ymm4, ymm3",
"jmp 7f",
"3:",
"vmovdqu ymmword ptr [rcx], ymm3",
"victory_safe_merge_after:",
"7:",
"popcnt eax, eax",
"add r11, rax",
"4:",
"inc r10",
"vmovdqu ymmword ptr [r8], ymm0",
"5:",
"add rcx, 32",
"add rdx, 32",
"add r8, 32",
"dec r9",
"jnz 2b",
"6:",
"victory_safe_merge_failed:",
"vzeroupper",
"mov rax, qword ptr [rsp + 40]",
"mov qword ptr [rax], r10",
"mov qword ptr [rax + 8], r11",
"mov rax, r9",
"ret",
);
unsafe extern "system" {
@@ -86,6 +185,189 @@ unsafe extern "system" {
fn victory_safe_put_at();
fn victory_safe_put_after();
fn victory_safe_put_failed();
fn victory_safe_update(dst: *mut u8, src: *const u8, len: usize, changed: *mut [usize; 2]) -> u32;
fn victory_safe_update_at();
fn victory_safe_update_after();
fn victory_safe_update_failed();
fn victory_safe_merge(title: *mut u8, now: *const u8, held: *mut u8, blocks: usize, counts: *mut [u64; 2]) -> usize;
fn victory_safe_merge_at();
fn victory_safe_merge_after();
fn victory_safe_merge_failed();
}
/// What [`update`] found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Updated {
/// Every byte was the same already; nothing was stored.
Same,
/// The bytes that changed lie in these offsets.
Changed(usize, usize),
/// Not all of the source could be read; some may have been copied.
Failed,
}
/// Makes `dst` hold what `src` holds, storing only what differs. The source
/// may change meanwhile: what is compared is what is stored, read once.
///
/// # Safety
/// As [`copy`]'s, and the destination is memory of ours that nothing else
/// writes.
pub(crate) unsafe fn update(dst: *mut u8, src: *const u8, len: usize) -> Updated {
let whole = len / 64 * 64;
let (mut from, mut to) = (usize::MAX, 0);
if whole > 0 {
let mut changed = [usize::MAX, 0];
// SAFETY: the source's faults leave through the failing exit; the
// rest is the caller's.
if unsafe { victory_safe_update(dst, src, whole, &mut changed) } == 0 {
return Updated::Failed;
}
[from, to] = changed;
}
if whole < len {
let mut rest = [0u8; 64];
let rest = &mut rest[..len - whole];
// SAFETY: as above; `rest` is ours.
unsafe {
if !copy(rest.as_mut_ptr(), src.add(whole), rest.len()) {
return Updated::Failed;
}
let held = std::slice::from_raw_parts_mut(dst.add(whole), rest.len());
if held != rest {
held.copy_from_slice(rest);
(from, to) = (from.min(whole), len);
}
}
}
if from >= to { Updated::Same } else { Updated::Changed(from, to) }
}
/// What [`merge`] did.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Merged {
/// Blocks of 32 bytes in which the card's bytes were new.
pub(crate) new: u64,
/// Dwords stored in title memory.
pub(crate) dwords: u64,
/// Whether title memory could be read and written wherever it had to be.
pub(crate) there: bool,
}
/// What shaders wrote goes into title memory: every byte of `now` that
/// differs from the one in `held` goes to `title` and into `held`, every
/// other byte of both stays as it is. Title memory is read 32 bytes at a
/// time, each just before what changes of them is stored, and only the
/// dwords that change are stored (at ends that are no dword's, bytes): the
/// title's own threads may be writing those beside them.
///
/// Where title memory cannot be read or written, the rest of `held` takes
/// `now` if `take` says so (the caller has the card's bytes nowhere else),
/// else it stays.
///
/// # Safety
/// `now` and `held` are `len` bytes of ours, not overlapping, that nothing
/// else writes (but for `now` the card: it is read once); `title` is as
/// [`copy`]'s. The stretch lies in one page of 4 KiB of title memory. [`on`]
/// must have been asked.
pub(crate) unsafe fn merge(title: *mut u8, now: *const u8, held: *mut u8, len: usize, take: bool) -> Merged {
let mut out = Merged { there: true, ..Merged::default() };
let mut at = 0;
while at < len {
let address = title.addr() + at;
let left = len - at;
if !address.is_multiple_of(4) || left < 4 {
// A dword only partly in the stretch: its bytes one by one.
// SAFETY: inside the stretch.
unsafe {
let byte = now.add(at).read_volatile();
let mut there = 0u8;
if byte != held.add(at).read() {
out.new += 1;
let mut ok = copy(&mut there, title.add(at), 1);
if ok && there != byte {
ok = copy(title.add(at), &byte, 1);
out.dwords += u64::from(ok);
}
out.there &= ok;
if ok || take {
held.add(at).write(byte);
}
}
}
at += 1;
continue;
}
let into = address % 32;
let mut counts = [0u64; 2];
if into != 0 || left < 32 {
// Part of a block: in a block of its own, equal beside the part.
let n = (32 - into).min(left) & !3;
let (mut new, mut old) = ([0u8; 32], [0u8; 32]);
// SAFETY: inside the stretch; the block of title memory around
// it lies in the same page, and nothing of it outside the part
// is stored (the two arrays are equal there).
unsafe {
std::ptr::copy_nonoverlapping(now.add(at), new.as_mut_ptr().add(into), n);
std::ptr::copy_nonoverlapping(held.add(at), old.as_mut_ptr().add(into), n);
let stuck = victory_safe_merge(title.wrapping_add(at).wrapping_sub(into), new.as_ptr(), old.as_mut_ptr(), 1, &mut counts);
out.there &= stuck == 0;
let from = if stuck != 0 && take { new.as_ptr() } else { old.as_ptr() };
std::ptr::copy_nonoverlapping(from.add(into), held.add(at), n);
}
at += n;
} else {
let blocks = left / 32;
// SAFETY: whole blocks of the stretch.
let stuck = unsafe { victory_safe_merge(title.add(at), now.add(at), held.add(at), blocks, &mut counts) };
if stuck != 0 {
out.there = false;
if take {
let from = at + (blocks - stuck) * 32;
// SAFETY: the blocks that were not done.
unsafe { std::ptr::copy_nonoverlapping(now.add(from), held.add(from), stuck * 32) };
}
}
at += blocks * 32;
}
out.new += counts[0];
out.dwords += counts[1];
}
out
}
/// Whether the `len` bytes at `a` and `b` differ.
///
/// # Safety
/// Both are `len` bytes that can be read; the card may be writing them.
pub(crate) unsafe fn differ(a: *const u8, b: *const u8, len: usize) -> bool {
use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_or_si256, _mm256_setzero_si256, _mm256_testz_si256, _mm256_xor_si256};
/// # Safety
/// [`differ`]'s; the processor has AVX2 (as the code above assumes).
#[target_feature(enable = "avx2")]
unsafe fn blocks(a: *const u8, b: *const u8, n: usize) -> bool {
let mut at = 0;
while at < n {
let mut any = _mm256_setzero_si256();
for k in at..n.min(at + 4) {
// SAFETY: block `k`, inside both.
let (x, y) = unsafe {
(_mm256_loadu_si256(a.add(k * 32).cast::<__m256i>()), _mm256_loadu_si256(b.add(k * 32).cast::<__m256i>()))
};
any = _mm256_or_si256(any, _mm256_xor_si256(x, y));
}
if _mm256_testz_si256(any, any) == 0 {
return true;
}
at += 4;
}
false
}
// SAFETY: the caller's.
if unsafe { blocks(a, b, len / 32) } {
return true;
}
// SAFETY: the bytes behind the blocks.
(len / 32 * 32..len).any(|i| unsafe { a.add(i).read_volatile() != b.add(i).read_volatile() })
}
/// Puts `now` at `dst` where it differs from `was`, whole dwords (as `dst`
@@ -160,7 +442,15 @@ pub(crate) fn failing_exit(at: usize) -> Option<usize> {
return Some(victory_safe_copy_failed as *const () as usize);
}
let (from, to) = (victory_safe_put_at as *const () as usize, victory_safe_put_after as *const () as usize);
(from..to).contains(&at).then_some(victory_safe_put_failed as *const () as usize)
if (from..to).contains(&at) {
return Some(victory_safe_put_failed as *const () as usize);
}
let (from, to) = (victory_safe_update_at as *const () as usize, victory_safe_update_after as *const () as usize);
if (from..to).contains(&at) {
return Some(victory_safe_update_failed as *const () as usize);
}
let (from, to) = (victory_safe_merge_at as *const () as usize, victory_safe_merge_after as *const () as usize);
(from..to).contains(&at).then_some(victory_safe_merge_failed as *const () as usize)
}
#[cfg(test)]
@@ -214,6 +504,52 @@ mod tests {
}
}
/// An update makes the two the same, says where they differed (to 64
/// bytes), stores nothing where they did not, and fails at a page that
/// is not there.
#[test]
fn updates_store_what_differs() {
assert!(on());
let (src, dst) = (Pages::new(1 << 14), Pages::new(1 << 14));
for len in [0usize, 1, 63, 64, 65, 200, 4096, 5000] {
for (da, sa) in [(0usize, 0usize), (3, 0), (0, 5)] {
for changed in [vec![], vec![0usize], vec![len / 2], vec![len.saturating_sub(1)], vec![1, len / 3, len / 2]] {
src.fill();
// SAFETY: inside the two allocations.
unsafe {
std::ptr::write_bytes(dst.0, 0xEE, dst.1);
std::ptr::copy_nonoverlapping(src.0.add(sa), dst.0.add(da), len);
let at: std::collections::BTreeSet<usize> = changed.iter().copied().filter(|&i| i < len).collect();
for &i in &at {
*src.0.add(sa + i) ^= 0x40;
}
let found = update(dst.0.add(da), src.0.add(sa), len);
match (at.iter().min(), at.iter().max()) {
(Some(&first), Some(&last)) => {
let Updated::Changed(from, to) = found else {
panic!("{len} {at:?}: {found:?}")
};
assert_eq!(from, first / 64 * 64);
assert_eq!(to, ((last / 64 + 1) * 64).min(len));
}
_ => assert_eq!(found, Updated::Same),
}
let (to, from) = (std::slice::from_raw_parts(dst.0, dst.1), std::slice::from_raw_parts(src.0, src.1));
assert_eq!(to[da..da + len], from[sa..sa + len]);
assert!(to[..da].iter().chain(&to[da + len..]).all(|&x| x == 0xEE));
}
}
}
}
// SAFETY: our allocation.
unsafe {
VirtualFree(src.0.add(4096).cast(), 4096, MEM_DECOMMIT);
assert_eq!(update(dst.0, src.0, 8192), Updated::Failed);
assert_eq!(update(dst.0, src.0.add(4096), 10), Updated::Failed);
assert_ne!(update(dst.0, src.0, 4096), Updated::Failed);
}
}
/// The dwords that changed are stored, and no byte of any other, at
/// every alignment and length; a page that is not there fails.
#[test]
@@ -266,6 +602,173 @@ mod tests {
}
}
/// [`merge`] against what it is to do, byte by byte, for every kind of
/// start, end and change: the bytes the card changed arrive in title
/// memory and in what it held, no dword without one is stored.
#[test]
fn a_merge_puts_what_the_card_changed_and_nothing_else() {
assert!(on());
let pages = Pages::new(1 << 12);
let mut seed = 1u32;
let mut random = move || {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
seed
};
for round in 0..4000u32 {
let at = random() as usize % 100;
let len = random() as usize % 300;
let (from, to) = (at, (at + len).min(400));
let n = to - from;
let base: Vec<u8> = (0..512).map(|_| random() as u8).collect();
let was: Vec<u8> = base[from..to].to_vec();
let mut held = was.clone();
let mut now = was.clone();
let mut title = base.clone();
// The card's writes: dwords and single bytes; the title's: some
// in the same dwords, some the same values.
for _ in 0..random() % 12 {
if n > 0 {
let i = random() as usize % n;
now[i] = random() as u8;
}
let i = random() as usize % 512;
title[i] = if (from..to).contains(&i) && round % 3 == 0 { now[i - from] } else { random() as u8 };
}
if round % 7 == 0 {
now.iter_mut().for_each(|b| *b = b.wrapping_add(1));
}
// SAFETY: inside the allocation and the vectors.
let done = unsafe {
std::ptr::copy_nonoverlapping(title.as_ptr(), pages.0, 512);
merge(pages.0.add(from), now.as_ptr(), held.as_mut_ptr(), n, round % 2 == 0)
};
assert!(done.there);
// SAFETY: inside the allocation.
let there = unsafe { std::slice::from_raw_parts(pages.0, 512) };
for i in 0..512 {
let wrote = (from..to).contains(&i) && now[i - from] != was[i - from];
let expect = if wrote { now[i - from] } else { title[i] };
assert_eq!(there[i], expect, "round {round} byte {i} of {from}..{to}");
}
assert_eq!(held, now, "round {round}");
assert_eq!(done.new == 0, was == now);
// Found merged already.
// SAFETY: as above.
let again = unsafe { merge(pages.0.add(from), now.as_ptr(), held.as_mut_ptr(), n, false) };
assert_eq!(again, Merged { new: 0, dwords: 0, there: true });
}
}
/// Title memory that is not there: what the card wrote stays to be
/// looked at again, or is taken, as asked; a page that only cannot be
/// written counts the same.
#[test]
fn a_merge_into_missing_memory_fails() {
assert!(on());
let pages = Pages::new(1 << 13);
let mut old = 0;
for (missing, take) in [(true, false), (true, true), (false, false), (false, true)] {
for (at, len) in [(0usize, 4096usize), (4, 64), (7, 1), (40, 100)] {
let was = vec![1u8; len];
let mut now = was.clone();
now[len - 1] = 9;
let mut held = was.clone();
// SAFETY: our allocation.
let done = unsafe {
if missing {
VirtualFree(pages.0.cast(), 4096, MEM_DECOMMIT);
} else {
VirtualProtect(pages.0.cast(), 4096, PAGE_READONLY, &mut old);
}
let done = merge(pages.0.add(at), now.as_ptr(), held.as_mut_ptr(), len, take);
VirtualAlloc(pages.0.cast(), 4096, MEM_COMMIT, PAGE_READWRITE);
VirtualProtect(pages.0.cast(), 4096, PAGE_READWRITE, &mut old);
done
};
assert!(!done.there);
assert_eq!(held, if take { now.clone() } else { was.clone() }, "{missing} {take} {at} {len}");
// Nothing to put: nothing fails.
let mut held = now.clone();
// SAFETY: as above; the addresses are no one's.
let done = unsafe { merge(std::ptr::without_provenance_mut(0x1000 + at), now.as_ptr(), held.as_mut_ptr(), len, take) };
assert!(done.there && done.new == 0);
}
}
}
/// [`merge`] beside threads that write other dwords of the same memory:
/// none of their writes is lost or undone.
#[test]
fn merges_undo_no_write_of_other_threads() {
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
assert!(on());
let pages = Pages::new(1 << 12);
let base = pages.0 as usize;
// SAFETY: committed, aligned memory, only touched as atomics or by
// the merge's stores of whole dwords.
let dword = |i: usize| unsafe { &*((base + i * 4) as *const AtomicU32) };
let stop = AtomicBool::new(false);
std::thread::scope(|s| {
let writers: Vec<_> = (0..2usize)
.map(|w| {
let stop = &stop;
s.spawn(move || {
let mut value = 1u32;
while !stop.load(Ordering::Relaxed) {
for i in (w..1024).step_by(4) {
// This thread's own dword: nobody else's value.
assert_eq!(dword(i).load(Ordering::Relaxed), value - 1, "dword {i}");
dword(i).store(value, Ordering::Relaxed);
}
value += 1;
}
})
})
.collect();
// The card's dwords: every fourth, from the third on.
let mut held = vec![0u8; 4096];
for round in 1..3000u32 {
let mut now = held.clone();
for i in (2..1024).step_by(4) {
if i * 7 % 5 != round as usize % 5 {
now[i * 4..i * 4 + 4].copy_from_slice(&(round + i as u32).to_le_bytes());
}
}
// SAFETY: the allocation, whole.
let done = unsafe { merge(base as *mut u8, now.as_ptr(), held.as_mut_ptr(), 4096, false) };
assert!(done.there);
for i in (2..1024).step_by(4) {
let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().unwrap());
assert_eq!(dword(i).load(Ordering::Relaxed), expect);
}
for i in (3..1024).step_by(4) {
assert_eq!(dword(i).load(Ordering::Relaxed), 0);
}
}
stop.store(true, Ordering::Relaxed);
for w in writers {
w.join().expect("no write was undone");
}
});
}
#[test]
fn differences_are_seen_wherever_they_are() {
for len in [0usize, 1, 31, 32, 33, 127, 128, 129, 200] {
let a = vec![7u8; len];
// SAFETY: the vectors' bytes.
assert!(!unsafe { differ(a.as_ptr(), a.clone().as_ptr(), len) });
for at in 0..len {
let mut b = a.clone();
b[at] = 8;
// SAFETY: as above.
assert!(unsafe { differ(a.as_ptr(), b.as_ptr(), len) }, "{len} {at}");
}
}
}
/// What the copies cost (ignored: a measurement): 64 KiB pieces of
/// scattered memory into a buffer the card reads, by the kernel and here.
#[test]
+733 -30
View File
@@ -17,7 +17,7 @@
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, RwLock};
use windows::Win32::Graphics::Direct3D12::ID3D12Resource;
@@ -35,6 +35,11 @@ pub(crate) struct Shadow {
/// Per page of title memory from `start`'s on: the write-watch asking
/// after which it was last copied (0: never).
copied: Mutex<Vec<u64>>,
/// Two ranges of title memory taken whole, the last one and the longest,
/// and the asking after which each was ([`Shadow::copy_stale`]). A page
/// a range holds in part cannot say so in `copied`. Locked inside
/// `copied`'s lock.
ranged: Mutex<[(usize, usize, u64); 2]>,
/// Whether the memory is write-watched: unknown, yes, no.
watched: AtomicU8,
/// Ranges shaders of a submission not yet copied back may be writing:
@@ -49,6 +54,11 @@ pub(crate) struct Shadow {
/// GPU wrote differs. Room for the whole copy; only those ranges' bytes
/// are set (and read).
before: Mutex<Option<Vec<u8>>>,
/// Held shared while pieces of the copy are landed (`crate::land`), each
/// its own bytes of it on several threads, and alone while title bytes
/// go in under shader writes ([`Shadow::merge_under_writes`]), which
/// takes `before`'s lock too. Taken ahead of that one.
merging: RwLock<()>,
/// With snapshots kept ([`keeps`]): which 64 KiB pieces of the snapshot
/// hold the copy's bytes as they are now, and whether the snapshot is
/// counted in [`KEPT_BYTES`].
@@ -560,40 +570,34 @@ pub(crate) fn relay_fetched(number: u64) {
/// writing: the next refresh would have put title bytes over what the
/// second flight's shaders were writing.
#[derive(Default)]
struct Flights(Vec<((usize, usize), u32, u64)>);
struct Flights(std::collections::HashMap<(usize, usize), (u32, u64)>);
impl Flights {
/// Submission `number` declares `range`: counted once for it, however
/// often it declares it.
fn declare(&mut self, range: (usize, usize), number: u64) {
match self.0.iter_mut().find(|f| f.0 == range) {
Some(f) => {
if f.2 != number {
f.1 += 1;
f.2 = number;
}
}
None => self.0.push((range, 1, number)),
let f = self.0.entry(range).or_insert((0, number));
if f.0 == 0 || f.1 != number {
*f = (f.0 + 1, number);
}
}
/// One submission that declared `ranges` (each once) is copied back:
/// the ranges no other submission still holds.
/// the ranges no other submission still holds, in order.
fn done(&mut self, ranges: &[(usize, usize)]) -> Vec<(usize, usize)> {
let mut free = Vec::new();
for range in ranges {
match self.0.iter().position(|f| f.0 == *range) {
Some(at) => {
self.0[at].1 = self.0[at].1.saturating_sub(1);
if self.0[at].1 == 0 {
self.0.swap_remove(at);
free.push(*range);
}
match self.0.get_mut(range) {
Some(f) if f.0 > 1 => f.0 -= 1,
Some(_) => {
self.0.remove(range);
free.push(*range);
}
// Not counted (declared before anything counted): free.
None => free.push(*range),
}
}
free.sort_unstable();
free
}
}
@@ -1028,6 +1032,11 @@ struct Workers {
more: std::sync::Condvar,
}
/// How many threads are kept for [`wide`].
fn wide_threads() -> usize {
std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6)
}
fn workers() -> &'static Workers {
static WORKERS: std::sync::OnceLock<Workers> = std::sync::OnceLock::new();
static STARTED: std::sync::Once = std::sync::Once::new();
@@ -1036,8 +1045,7 @@ fn workers() -> &'static Workers {
more: std::sync::Condvar::new(),
});
STARTED.call_once(|| {
let n = std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6);
for i in 0..n {
for i in 0..wide_threads() {
let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || {
let workers = WORKERS.get().expect("made above");
loop {
@@ -1103,6 +1111,30 @@ pub(crate) fn wide_run(jobs: Vec<Box<dyn FnOnce() + Send>>) {
wide(jobs);
}
/// Calls `work` with every number under `n`, on the kept threads and on
/// this one, the next number to whichever is free: for thousands of small
/// pieces of work, where a job each ([`wide`]) is mostly the jobs' queue.
pub(crate) fn wide_each(n: usize, work: impl Fn(usize) + Send + Sync + 'static) {
let next = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let work = Arc::new(work);
let threads = (wide_threads() + 1).min(n);
let jobs = (0..threads)
.map(|_| {
let (next, work) = (next.clone(), work.clone());
Box::new(move || {
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
if i >= n {
break;
}
work(i);
}
}) as Job
})
.collect();
wide(jobs);
}
/// About this many bytes to a piece of work for [`wide`].
const WIDE_JOB: usize = 1 << 20;
@@ -1377,6 +1409,25 @@ mod wide_tests {
/// compared, changed runs put in, and their bytes.
static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
/// Why [`Shadow::merge_under_writes`] last left the caller to wait.
static STALE_WHY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn note_stale(why: usize) {
STALE_WHY.store(why, Ordering::Relaxed);
}
/// [`STALE_WHY`] in words (diagnostics).
#[cfg(feature = "diagnostics")]
pub(crate) fn stale_why() -> &'static str {
const WHY: [&str; 4] = [
"the memory is not watched",
"the journal does not say what was written",
"more changed runs than a submission sends up",
"no snapshot",
];
WHY[STALE_WHY.load(Ordering::Relaxed).min(3)]
}
/// [`MERGED`], taken.
pub(crate) fn merged_stats() -> [u64; 3] {
[0, 1, 2].map(|i| MERGED[i].swap(0, Ordering::Relaxed))
@@ -1390,7 +1441,11 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> {
let mut runs = Vec::new();
let mut i = 0;
while i < n {
// Equal bytes, eight at a time while they last.
// Equal bytes, many at a time while they last (a page looked at
// under a flight's writes hardly ever differs at all).
while i + 512 <= n && now[i..i + 512] == was[i..i + 512] {
i += 512;
}
while i + 8 <= n && now[i..i + 8] == was[i..i + 8] {
i += 8;
}
@@ -1409,10 +1464,56 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> {
runs
}
/// Whether pages of a copy in the card's memory that a refresh takes again
/// go up to the card only where they are not what the CPU's side holds
/// already (`VICTORY_SEND_CHANGED=1`; off by default).
///
/// A refresh copies the 64 KiB pages that were written since it last took
/// them, and all of each went up and was hashed there again. Most of them
/// the title did not write: the relay put what shaders wrote into title
/// memory, and the card and the CPU's side hold those bytes already
/// ([`Shadow::card_merge_relay`]). Run record-1: 1,500 pieces (98 MB) a
/// frame fetched from the card, 103 MB in 328 ranges sent up, 322 hash
/// passes, while the title's own writes took some 260 guards off.
///
/// What it rests on: the card's side holds what the CPU's side holds, but
/// for ranges shaders may be writing (no refresh touches them) and what is
/// still to go up. A page's first taking always goes up whole, so does one
/// that could not be read; after that every byte that changes on the CPU's
/// side goes up (the bytes compared are the bytes stored).
///
/// Why it is not on by default: a shader that writes a copy through a view
/// nobody declared (`crate::draw`, buffers picked by index) breaks that
/// rule. Taken again, its page went up over what it wrote; with the switch
/// its bytes stay, as they would on the console, until the title changes the
/// same 64 bytes: clearing them to the zeros they held before is then no
/// change.
fn send_changed() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| {
#[cfg(feature = "diagnostics")]
if crate::copystat::mode() != 0 {
return false;
}
std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") && crate::safecopy::on()
})
}
/// Since the last frame-rate line, of pages taken again into copies in the
/// card's memory ([`send_changed`]): bytes compared, those of pages that
/// held the same, and bytes to go up.
static SEND: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
/// [`SEND`], taken.
#[cfg(feature = "diagnostics")]
pub(crate) fn send_stats() -> [u64; 3] {
[0, 1, 2].map(|i| SEND[i].swap(0, Ordering::Relaxed))
}
/// Whether what shaders wrote goes into title memory run by run
/// ([`put_changed`]; on by default, `VICTORY_EXACT_BACK=0` writes the whole
/// stretch from the first changed byte to the last, as before).
fn exact_back() -> bool {
pub(crate) fn exact_back() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_EXACT_BACK").is_none_or(|v| v != "0"))
}
@@ -1490,6 +1591,27 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize {
written
}
/// For `crate::land`'s measurement: a piece as [`Shadow::card_merge_relay`]
/// lands it without `VICTORY_LAND`: `n` bytes at `now`, `held` what the CPU's
/// side held, both the caller's alone.
#[cfg(test)]
pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, title: &mut Vec<u8>) {
// SAFETY: the caller's.
let (gpu, held) = unsafe { (std::slice::from_raw_parts(now as *const u8, n), std::slice::from_raw_parts_mut(held as *mut u8, n)) };
let Some(first) = first_difference(gpu, held) else {
return;
};
let last = last_difference(gpu, held).unwrap_or(first);
let n = last + 1 - first;
title.clear();
title.resize(n, 0);
assert!(crate::host::read_into((start + first) as *const u8, title));
let was = title.clone();
if merge_piece(&gpu[first..=last], &mut held[first..=last], title) {
put_changed(start + first, &was, title);
}
}
#[cfg(test)]
mod merge_tests {
use super::{changed_runs, dword_runs};
@@ -1520,6 +1642,34 @@ mod merge_tests {
/// The runs hold exactly the bytes that differ: putting them into the
/// old bytes gives the new ones, and no run holds an equal byte.
/// What looking at a page that did not change costs, against the look
/// eight bytes at a time that it was (a frame has some 250 of them, on
/// the submitting thread). Run with `--ignored --nocapture`.
#[test]
#[ignore]
fn runs_of_equal_pages() {
let (a, b) = (vec![7u8; 64 << 10], vec![7u8; 64 << 10]);
let eights = || {
let (now, was) = (std::hint::black_box(&a), std::hint::black_box(&b));
let mut i = 0;
while i + 8 <= now.len() && now[i..i + 8] == was[i..i + 8] {
i += 8;
}
std::hint::black_box(i);
};
let best = |f: &dyn Fn()| {
(0..500)
.map(|_| {
let t = std::time::Instant::now();
f();
t.elapsed().as_secs_f64() * 1e6
})
.fold(f64::MAX, f64::min)
};
let runs = || drop(std::hint::black_box(changed_runs(std::hint::black_box(&a), std::hint::black_box(&b))));
println!("64 KiB that are the same: {:.1} us by eights, {:.1} us now", best(&eights), best(&runs));
}
#[test]
fn changed_runs_are_exactly_the_bytes_that_differ() {
let was: Vec<u8> = (0..300u32).map(|i| (i * 13 + 5) as u8).collect();
@@ -1831,6 +1981,11 @@ impl Shadow {
self.id
}
/// Whether it is no copy but title memory in place (`crate::inplace`).
pub(crate) fn in_place(&self) -> bool {
self.place.is_some()
}
/// Offset of a title address from the buffer's start.
pub(crate) fn offset(&self, address: u64) -> u64 {
address - self.start + self.place.as_ref().map_or(0, |place| place.1)
@@ -1871,10 +2026,12 @@ impl Shadow {
start,
len,
copied: Mutex::new(vec![0; pages as usize]),
ranged: Mutex::default(),
watched: AtomicU8::new(0),
pending: Mutex::default(),
flights: Mutex::default(),
before: Mutex::default(),
merging: RwLock::default(),
kept: Mutex::default(),
used: AtomicU64::new(crate::host::moment()),
asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)],
@@ -2274,7 +2431,7 @@ impl Shadow {
let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
if relay() {
let free = self.flights.lock().unwrap_or_else(|e| e.into_inner()).done(ranges);
pending.retain(|r| !free.contains(r));
pending.retain(|r| free.binary_search(r).is_err());
} else {
pending.retain(|r| !ranges.contains(r));
}
@@ -2338,6 +2495,12 @@ impl Shadow {
!self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
}
/// Whether one of those submissions may be writing in title memory
/// `[from, to)`.
pub(crate) fn writes_pending_in(&self, from: usize, to: usize) -> bool {
self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from)
}
/// Whether [`Shadow::update`] of `[address, address + len)` would leave
/// title bytes behind: a range shaders may be writing holds a page the
/// title wrote since the copy last took it. The answer comes from the
@@ -2413,6 +2576,7 @@ impl Shadow {
return false;
}
if self.watched.load(Ordering::Relaxed) == NOT_WATCHED {
note_stale(0);
return true;
}
let base = start / PAGE;
@@ -2425,6 +2589,7 @@ impl Shadow {
// those were all of run 99's cases: the flights were settled
// 4-5 times a frame for "0 pages looked at".
let Some((now, written)) = crate::watch::writes(a, e, true) else {
note_stale(1);
return true;
};
let stale: Vec<usize> = {
@@ -2450,6 +2615,7 @@ impl Shadow {
// reference under the same lock, and a page read before
// such a merge and compared after it would take the card's
// bytes for the title's.
let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
// A page that is not there is left as it is, and looked at
// again next time.
@@ -2464,6 +2630,7 @@ impl Shadow {
let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
let runs = changed_runs(title, held);
if runs.len() > *runs_left {
note_stale(2);
return true;
}
*runs_left -= runs.len();
@@ -2475,6 +2642,7 @@ impl Shadow {
}
} else {
let Some(snapshot) = before.as_mut() else {
note_stale(3);
return true;
};
// SAFETY: the snapshot's allocation holds the copy's
@@ -2492,6 +2660,7 @@ impl Shadow {
}
}
drop(before);
drop(_merging);
// Taken, if the range holds all of the page that is in the
// copy; else the rest of it is the refresh's, which notes
// only whole pages, and the page is looked at again.
@@ -2547,6 +2716,43 @@ impl Shadow {
self.update_free(from, to)
}
/// Whether [`Shadow::update`] of `[address, address + len)` would copy
/// nothing, and knows it without asking anything
/// (`crate::watch::nothing_new`). `false` if it would have to ask.
pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool {
if self.place.is_some() {
return true;
}
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
let (from, to) = (address.max(start), (address + len).min(end));
if from >= to {
return true;
}
if self.watched.load(Ordering::Relaxed) != 1 {
return false;
}
// Around ranges shaders are writing the refresh asks gap by gap.
if self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) {
return false;
}
let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
let same = crate::watch::nothing_new(from, to, start / PAGE, &copied, self.ranged(from, to));
#[cfg(feature = "diagnostics")]
if same {
use crate::copystat::{C, add};
add(C::Checked, (to - from) as u64);
add(C::Unchanged, (to - from) as u64);
}
same
}
/// The latest asking after which a range that holds `[from, to)` was
/// taken whole (0: none is known). The caller holds `copied`'s lock.
fn ranged(&self, from: usize, to: usize) -> u64 {
let ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner());
ranged.iter().filter(|r| r.0 <= from && to <= r.1).map(|r| r.2).max().unwrap_or(0)
}
/// [`Shadow::update`] of `[from, to)` (inside the buffer) where no
/// shader writes.
fn update_free(&self, from: usize, to: usize) -> usize {
@@ -2554,6 +2760,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 +2781,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.
@@ -2581,7 +2845,13 @@ impl Shadow {
let base = self.start as usize / PAGE;
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
let mut writes = written.iter().peekable();
let (mut bytes, mut run) = (0, None);
// Pages the range holds in part are never noted in `copied`, and
// were copied again at every refresh of the range, written or not:
// of the heap's buffer views alone two ends for each of 4,400
// copies, every frame. A range that was taken whole, and not written
// since, is as it was.
let ranged = if crate::watch::light() { self.ranged(from, to) } else { 0 };
let (mut runs, mut run) = (Vec::new(), None::<(usize, bool)>);
let last = (to - 1) / PAGE;
for page in from / PAGE..=last {
let write = match writes.peek() {
@@ -2592,25 +2862,111 @@ impl Shadow {
_ => 0,
};
let at = &mut copied[page - base];
if *at == 0 || write > *at {
let taken = (*at).max(ranged);
if taken == 0 || write > taken {
// A page only partly in the range is copied in part: it
// stays stale for the rest.
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to {
*at = now;
}
run.get_or_insert(page);
} else if let Some(first) = run.take() {
bytes += self.copy((first * PAGE).max(from), (page * PAGE).min(to));
// Cut where pages taken before meet pages never taken.
let again = taken != 0;
if let Some((first, known)) = run
&& known != again
{
runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known));
run = None;
}
run.get_or_insert((page, again));
} else if let Some((first, known)) = run.take() {
runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known));
}
}
// Cut to the range: next to it shaders may be writing the copy.
if let Some(first) = run {
bytes += self.copy((first * PAGE).max(from), ((last + 1) * PAGE).min(to));
if let Some((first, known)) = run {
runs.push(((first * PAGE).max(from), ((last + 1) * PAGE).min(to), known));
}
let bytes = self.take_all(runs);
if crate::watch::light() {
// All of the range is in the copy as of this asking.
let mut ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner());
ranged[0] = (from, to, now);
if to - from >= ranged[1].1 - ranged[1].0 {
ranged[1] = (from, to, now);
}
}
bytes
}
/// [`Shadow::take`] of `runs` (from, to, known), on several threads if
/// they are long: the big heap's copy has some 4 MB of them in each of
/// 14 refreshes a frame, on one thread while the others had nothing.
fn take_all(&self, runs: Vec<(usize, usize, bool)>) -> usize {
const LONG: usize = 1 << 20;
const PART: usize = 256 << 10;
let bytes = runs.iter().map(|r| r.1 - r.0).sum();
if bytes < LONG || !crate::watch::light() {
for (from, to, known) in runs {
self.take(from, to, known);
}
return bytes;
}
let mut parts = Vec::with_capacity(bytes / PART + runs.len());
for (from, to, known) in runs {
let mut at = from;
while at < to {
// Whole pages to a part.
let next = ((at / PAGE) * PAGE + PART).min(to);
parts.push((at, next, known));
at = next;
}
}
let this = std::ptr::from_ref(self) as usize;
wide_each(parts.len(), move |i| {
// SAFETY: `wide_each` returns when every part is done, before
// the borrow of `self` ends. The parts lie apart.
let this = unsafe { &*(this as *const Shadow) };
let (from, to, known) = parts[i];
this.take(from, to, known);
});
bytes
}
/// Copies title memory `[from, to)` (inside the buffer) into the copy;
/// `known`: the copy held it before ([`send_changed`]).
fn take(&self, from: usize, to: usize, known: bool) -> usize {
if !known || self.card.is_none() || !send_changed() {
return self.copy(from, to);
}
let start = self.start as usize;
let mut at = from;
while at < to {
let n = (PAGE - at % PAGE).min(to - at);
// SAFETY: inside the mapping of the copy's CPU side, which
// nothing else writes there: no shader's range holds it.
let found = unsafe { crate::safecopy::update(self.data.add(at - start), at as *const u8, n) };
SEND[0].fetch_add(n as u64, Ordering::Relaxed);
match found {
crate::safecopy::Updated::Same => {
SEND[1].fetch_add(n as u64, Ordering::Relaxed);
}
crate::safecopy::Updated::Changed(a, b) => {
SEND[2].fetch_add((b - a) as u64, Ordering::Relaxed);
self.changed(at - start + a, at - start + b);
self.card_changed(at - start + a, at - start + b);
}
// A page is not there: as before, around it, and all of it
// goes up.
crate::safecopy::Updated::Failed => {
self.copy(at, at + n);
}
}
at += n;
}
to - from
}
/// Copies title memory `[from, to)`, cut to the buffer, into the copy.
fn copy(&self, from: usize, to: usize) -> usize {
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
@@ -2693,6 +3049,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
@@ -2809,6 +3201,317 @@ impl Shadow {
}
}
/// For tests: copies with no host buffer behind them.
#[cfg(test)]
impl Shadow {
/// A copy at `data` of title memory `[start, start + len)`, with a card
/// side if `card`. It is never let go: there is no buffer to release.
pub(crate) fn unbacked(start: u64, data: *mut u8, len: u64, card: bool) -> Arc<Shadow> {
// SAFETY: an interface pointer nothing calls.
let none = || unsafe { std::mem::transmute::<usize, ID3D12Resource>(8) };
let mut shadow = Shadow::new(none(), data, 0, start, len);
if card {
shadow.card = Some(Card {
staging: none(),
before: Mutex::default(),
dirty: Mutex::default(),
sent: Mutex::default(),
size: len.next_multiple_of(PIECE as u64),
});
}
let shadow = Arc::new(shadow);
std::mem::forget(shadow.clone());
shadow
}
/// What shaders wrote goes into title memory ([`put_changed`]).
pub(crate) fn put(at: usize, title: &[u8], merged: &[u8]) {
put_changed(at, title, merged);
}
/// What is to go up to the card, noted as sent with `number`, as
/// [`card_dirty`] does; notes of sends up to `merged` go.
pub(crate) fn send_up(&self, number: u64, merged: u64) -> Vec<(usize, usize)> {
let card = self.card.as_ref().unwrap();
let mut dirty = card.dirty.lock().unwrap();
let ranges = std::mem::take(&mut *dirty);
let mut sent = card.sent.lock().unwrap();
sent.retain(|s| s.2 > merged);
sent.extend(ranges.iter().map(|&(a, b)| (a, b, number)));
ranges
}
/// What is to go up to the card, taken.
pub(crate) fn take_dirty(&self) -> Vec<(usize, usize)> {
std::mem::take(&mut *self.card.as_ref().unwrap().dirty.lock().unwrap())
}
}
impl Shadow {
/// [`Shadow::card_merge_relay`] of several pieces, each within one
/// 64 KiB block of title memory: from and to (offsets in the copy), and
/// where the fetched bytes are. On any thread: several may land pieces
/// of one copy, no two the same bytes. Returns the bytes put into title
/// memory.
///
/// What is left out is as there, asked once for all of them: the notes
/// of bytes that went up (or are to go up) behind the fetch only move
/// from `dirty` to `sent`, with a later number, and grow only by
/// [`Shadow::merge_under_writes`], which the lock held here keeps out.
///
/// # Safety
/// The third of each piece is the address of its bytes, which stay as
/// they are during the call.
pub(crate) unsafe fn land_card(&self, pieces: &[(usize, usize, usize)], fetched_after: u64, notes: &mut crate::land::Notes) -> u64 {
let Some(card) = &self.card else {
return 0;
};
let waiting = std::time::Instant::now();
let _merging = self.merging.read().unwrap_or_else(|e| e.into_inner());
crate::land::spent(crate::land::stat::LOCK, waiting);
let (from, to) = pieces.iter().fold((usize::MAX, 0), |(a, b), p| (a.min(p.0), b.max(p.1)));
let skip: Vec<(usize, usize)> = {
let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner());
let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner());
dirty
.iter()
.copied()
.chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1)))
.filter(|&(a, b)| a < to && b > from)
.collect()
};
let mut put = 0;
for &(lo, hi, now) in pieces {
if lo >= hi || hi > self.len as usize {
continue;
}
let near: Vec<(usize, usize)> = skip.iter().copied().filter(|&(a, b)| a < hi && b > lo).collect();
let parts: Vec<(usize, usize)> = outside(lo, hi, near).into_iter().map(|(a, b)| (a - lo, b - lo)).collect();
// SAFETY: inside the mapping (checked above), in a range
// declared and not done with, which no refresh writes; the
// title's bytes are kept out by the lock; the caller's.
// Where title memory is not mapped the CPU's side keeps what
// the card wrote, as before.
let merged =
unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes) };
self.walls_merged(hi - lo, merged as usize);
put += merged;
}
put
}
/// [`Shadow::relay_merge`] of a piece `[at, at + n)` (within one 64 KiB
/// block of title memory) of a copy in the PC's memory; on any thread,
/// as [`Shadow::land_card`]. The copy is read once and never written.
/// Returns the bytes put into title memory.
pub(crate) fn land_back(&self, at: usize, n: usize, notes: &mut crate::land::Notes) -> u64 {
if self.card.is_some() || n == 0 || at + n > self.len as usize {
return 0;
}
let waiting = std::time::Instant::now();
let _merging = self.merging.read().unwrap_or_else(|e| e.into_inner());
crate::land::spent(crate::land::stat::LOCK, waiting);
// The snapshot's memory stays where it is until the range is done
// with (`copy_back_done`), which comes after this.
let Some(held) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut().map(Vec::as_mut_ptr) else {
return 0;
};
// SAFETY: inside the copy's mapping (checked above), which only the
// card writes there, and inside the snapshot's allocation, which
// holds the copy's length (`writing`): these offsets are in a range
// declared and not done with, whose bytes it holds, and the lock
// keeps out what else writes them. Title memory that is not there
// is looked at again when the next flight that declared the range
// lands.
unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes) }
}
}
#[cfg(test)]
mod land_tests {
use super::{Card, PIECE, Shadow};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
/// A copy in the card's memory of title memory at `title` (its card side
/// is never looked at here), all bytes 0 on the CPU's side.
fn copy_of(title: usize, len: usize) -> Option<Shadow> {
let (buffer, data) = crate::host::host()?.shared_buffer(len as u64)?;
// SAFETY: the mapping, `len` bytes.
unsafe { std::ptr::write_bytes(data, 0, len) };
let mut shadow = Shadow::new(buffer.clone(), data, 0, title as u64, len as u64);
shadow.card = Some(Card {
staging: buffer,
before: Mutex::default(),
dirty: Mutex::default(),
sent: Mutex::default(),
size: len as u64,
});
Some(shadow)
}
/// Memory that stays (`crate::watch` knows its addresses): private, or a
/// view noted as the runtime notes the title's.
fn memory(len: usize, view: bool) -> usize {
use windows_sys::Win32::System::Memory as mem;
// SAFETY: plain allocations of our own.
unsafe {
if !view {
return mem::VirtualAlloc(std::ptr::null(), len, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as usize;
}
let section = mem::CreateFileMappingW(-1isize as _, std::ptr::null(), mem::PAGE_READWRITE, 0, len as u32, std::ptr::null());
let at = mem::MapViewOfFile(section, mem::FILE_MAP_WRITE, 0, 0, len).Value as usize;
crate::inplace::title_memory_section(section as usize, len as u64, true);
crate::title_memory_remapped(at, len);
crate::inplace::title_memory_view(at, len, section as usize, 0);
at
}
}
fn random(seed: &mut u64) -> usize {
*seed ^= *seed << 13;
*seed ^= *seed >> 7;
*seed ^= *seed << 17;
(*seed >> 8) as usize
}
/// [`Shadow::land_card`] leaves title memory and the CPU's side as
/// [`Shadow::card_merge_relay`] does, with title bytes that went up
/// behind the fetch, or have not gone up, left out.
#[test]
fn pieces_land_as_the_merge_one_by_one_lands_them() {
assert!(crate::safecopy::on());
const LEN: usize = 3 * PIECE;
let mut seed = 0x1234_5678_9abcu64;
for view in [false, true] {
let (a, b) = (memory(LEN, view), memory(LEN, view));
let (Some(one), Some(many)) = (copy_of(a, LEN), copy_of(b, LEN)) else {
return; // no host GPU
};
// SAFETY: the two memories and the two mappings.
let bytes = |at: usize| unsafe { std::slice::from_raw_parts_mut(at as *mut u8, LEN) };
for round in 0..40u32 {
let base: Vec<u8> = (0..LEN).map(|_| random(&mut seed) as u8).collect();
let (mut held, mut title, mut now) = (base.clone(), base.clone(), base);
let (mut dirty, mut sent) = (Vec::new(), Vec::new());
for k in 0..120 {
let at = random(&mut seed) % LEN / 4 * 4;
let n = (random(&mut seed) % 900 / 4 * 4).min(LEN - at);
match k % 4 {
0 | 1 => now[at..at + n].fill(random(&mut seed) as u8),
2 => title[at..at + n].fill(random(&mut seed) as u8),
// Title bytes put into the CPU's side meanwhile.
_ => {
let byte = random(&mut seed) as u8;
held[at..at + n].fill(byte);
title[at..at + n].fill(byte);
if k % 8 == 3 {
dirty.push((at, at + n));
} else {
sent.push((at, at + n, u64::from(round % 3) + (k as u64 / 16)));
}
}
}
}
let after = 4u64;
for (shadow, at) in [(&one, a), (&many, b)] {
crate::watch::writing(at, LEN);
bytes(at).copy_from_slice(&title);
bytes(shadow.data as usize).copy_from_slice(&held);
let card = shadow.card.as_ref().expect("made with one");
*card.dirty.lock().unwrap() = dirty.clone();
*card.sent.lock().unwrap() = sent.clone();
}
let pieces: Vec<(usize, usize)> = (0..3).map(|p| (p * PIECE + 16, (p + 1) * PIECE - 4)).collect();
let mut scratch = Vec::new();
for &(lo, hi) in &pieces {
one.card_merge_relay(lo, &now[lo..hi], after, &mut scratch);
}
let addressed: Vec<(usize, usize, usize)> =
pieces.iter().map(|&(lo, hi)| (lo, hi, now.as_ptr() as usize + lo)).collect();
let mut notes = crate::land::Notes::default();
// SAFETY: the fetched bytes are `now`'s.
unsafe { many.land_card(&addressed, after, &mut notes) };
notes.flush();
assert!(bytes(a) == bytes(b), "title memory, round {round}");
assert!(bytes(one.data as usize) == bytes(many.data as usize), "the CPU's side, round {round}");
}
}
}
/// Landings of one copy on several threads, the title writing dwords of
/// the same blocks, and the title's bytes put into the CPU's side under
/// the shaders' writes ([`Shadow::merge_under_writes`]), all at once. The
/// card has never received the title's bytes: what is fetched holds older
/// ones there, which must not be taken for shaders' writes.
#[test]
fn landings_and_title_bytes_going_in_keep_each_others_bytes() {
assert!(crate::safecopy::on());
const BLOCKS: usize = 16;
const LEN: usize = BLOCKS * PIECE;
let title = memory(LEN, true);
let Some(shadow) = copy_of(title, LEN) else {
return; // no host GPU
};
shadow.pending.lock().unwrap().push((title, title + LEN));
// SAFETY: committed, aligned; touched as atomics or by the landing's
// stores of whole dwords.
let dword = |i: usize| unsafe { &*((title + i * 4) as *const AtomicU32) };
let stop = AtomicBool::new(false);
std::thread::scope(|s| {
let writer = s.spawn(|| {
let mut value = 1u32;
while !stop.load(Ordering::Relaxed) {
for i in (1..LEN / 4).step_by(4 * 331) {
assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone");
}
value += 1;
std::thread::sleep(std::time::Duration::from_micros(200));
}
value - 1
});
s.spawn(|| {
while !stop.load(Ordering::Relaxed) {
let mut runs = usize::MAX;
assert!(!shadow.merge_under_writes(title, LEN, &mut runs));
// Sent up, as the preparing of a submission would: noted
// with a number behind the fetches'.
let card = shadow.card.as_ref().expect("made with one");
let mut dirty = card.dirty.lock().unwrap();
let mut sent = card.sent.lock().unwrap();
let moved: Vec<_> = std::mem::take(&mut *dirty).into_iter().map(|(a, b)| (a, b, 9)).collect();
sent.extend(moved);
sent.sort_unstable();
sent.dedup();
}
});
let mut now = vec![0u8; LEN];
for round in 1..200u32 {
for block in (0..BLOCKS).filter(|b| (*b as u32 * 5 + round) % 3 != 0) {
for i in (block * PIECE / 4 + 3..(block + 1) * PIECE / 4).step_by(4) {
now[i * 4..i * 4 + 4].copy_from_slice(&(round << 20 | i as u32).to_le_bytes());
}
}
let at = now.as_ptr() as usize;
crate::land::each(BLOCKS, &|b| {
let mut notes = crate::land::Notes::default();
let (lo, hi) = (b * PIECE, (b + 1) * PIECE);
// SAFETY: the fetched bytes are `now`'s; each block once.
unsafe { shadow.land_card(&[(lo, hi, at + lo)], 8, &mut notes) };
notes.flush();
});
for i in (3..LEN / 4).step_by(4 * 53) {
let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().expect("four"));
assert_eq!(dword(i).load(Ordering::Relaxed), expect, "round {round} dword {i}");
}
}
stop.store(true, Ordering::Relaxed);
let last = writer.join().expect("nothing undone");
assert!((1..LEN / 4).step_by(4 * 331).all(|i| dword(i).load(Ordering::Relaxed) == last));
});
}
}
struct Entry {
end: u64,
shadow: Option<Arc<Shadow>>,
+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)))
+399 -13
View File
@@ -149,6 +149,8 @@ fn kernel_written(first: usize, last: usize) -> Option<Vec<usize>> {
add(C::Watches, 1);
add(C::WatchUs, started.elapsed().as_micros() as u64);
slow(started.elapsed().as_micros() as u64);
tally(0, 1);
tally(1, ((last - first) * (PAGE >> 10)) as u64);
}
let mut pages: Vec<usize> = found[..count].iter().map(|&at| at / PAGE).collect();
pages.dedup();
@@ -173,7 +175,9 @@ const AHEAD_MAX: usize = (1 << 30) / PAGE;
pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) {
let mut pieces: Vec<(usize, usize)> = ranges
.iter()
.filter(|r| r.0 < r.1)
// Not view memory known by its bits: the kernel would refuse the
// asking (and, asked together with others, theirs).
.filter(|r| r.0 < r.1 && !published(r.0, r.1))
.map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE)))
.collect();
if pieces.len() < 2 {
@@ -291,7 +295,7 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) {
// here, once; what is not write-watched stays with `writes`.
let mut written = Vec::new();
for &(start, end) in ranges {
if start >= end {
if start >= end || published(start, end) {
continue;
}
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
@@ -384,15 +388,24 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
if let Some(known) = ahead(&journal()) {
return Some(known);
}
// Read-only since an asking noted it: the bits first, then the journal.
if guarded && published(start, end) {
#[cfg(feature = "diagnostics")]
tally(2, 1);
let j = journal();
return Some((next_asking(), of(&j)));
}
// Asked, and the answer noted, with the range held: nothing else asks
// about any of it in between.
let _range = Asking::hold(first, last);
if let Some(known) = ahead(&journal()) {
return Some(known);
}
let mut guards_asked = false;
let pages = match kernel_written(first, last) {
Some(pages) => pages,
None => {
guards_asked = true;
if !guarded {
return None;
}
@@ -418,15 +431,189 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
let j = journal();
return Some((next_asking(), of(&j)));
}
let mut j = journal_mut();
let now = next_asking();
j.written.extend(pages.into_iter().map(|page| (page, now)));
Some((now, of(&j)))
let answer = {
let mut j = journal_mut();
let now = next_asking();
j.written.extend(pages.iter().map(|&page| (page, now)));
(now, of(&j))
};
// Noted: what the guards made clean of it is known by its bits from
// now on. (The range is still held: no other asking of any of it came
// between.)
if guards_asked && light() {
publish(&pages);
}
Some(answer)
}
/// Whether nothing of `[start, end)` was written that a copy with the notes
/// `copied` (the asking after which each page from page `base` on was taken)
/// and `ranged` (the asking after which a range that holds this one was
/// taken whole, or 0) does not hold, as [`writes`] would answer with nothing
/// asked: the submission's asking covers the range, or its blocks are known
/// by their bits. `false` if something would have to be asked.
pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], ranged: u64) -> bool {
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
// The bits first, then the journal, as in `writes`.
let known = published(start, end);
let j = journal();
if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) {
return false;
}
let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else {
return false;
};
(ranged != 0 || taken.iter().all(|&at| at != 0))
&& j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged))
}
/// Guarded blocks of view memory.
const BLOCK: usize = PAGE;
/// Whether the refreshes of host copies go the light way
/// (`VICTORY_LIGHT_REFRESH=0`: as before): view memory nothing wrote since
/// it was last asked about is known by its bits ([`PUBLISHED`]), a copy
/// nothing of whose range changed is told so before any thread is woken
/// for it (`crate::host`, `Shadow::nothing_new`), and the ends of a range,
/// pages the range holds in part, are not copied again at every refresh
/// (`Shadow::copy_stale`).
///
/// A frame asked about view memory some 1,500 times, for nearly all of it
/// to hear that nothing was written, on up to seven threads at once, each
/// asking under the guards' one lock and behind [`ASKING`]'s: 94 ms a frame
/// of all threads' time (run record-1), most of it waiting.
pub(crate) fn light() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_LIGHT_REFRESH").is_none_or(|v| v != "0"))
}
/// A bit per block of the address space, in pieces made when first needed
/// and never let go.
struct Bits([std::sync::atomic::AtomicPtr<BitsPiece>; Bits::PIECES]);
/// The bits of 4 GiB.
type BitsPiece = [std::sync::atomic::AtomicU64; Bits::WORDS];
impl Bits {
const WORDS: usize = 1 << 10;
/// 128 TiB, what a process has.
const PIECES: usize = 1 << 15;
const fn new() -> Bits {
Bits([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Bits::PIECES])
}
fn piece(&self, word: usize) -> Option<&BitsPiece> {
let piece = self.0.get(word / Bits::WORDS)?.load(std::sync::atomic::Ordering::Acquire);
// SAFETY: null, or a piece made by `set`, which is never freed.
unsafe { piece.as_ref() }
}
/// One caller at a time (under the guards' lock).
fn set(&self, block: usize) {
use std::sync::atomic::Ordering::{Relaxed, Release};
let word = block / 64;
let Some(place) = self.0.get(word / Bits::WORDS) else {
return;
};
if place.load(Relaxed).is_null() {
let piece: Box<BitsPiece> = Box::new([const { std::sync::atomic::AtomicU64::new(0) }; Bits::WORDS]);
place.store(Box::into_raw(piece), Release);
}
if let Some(piece) = self.piece(word) {
piece[word % Bits::WORDS].fetch_or(1 << (block % 64), Release);
}
}
fn clear(&self, block: usize) {
let word = block / 64;
if let Some(piece) = self.piece(word) {
// Ahead of the protection's change, and seen by whoever the
// writer tells of its write.
piece[word % Bits::WORDS].fetch_and(!(1 << (block % 64)), std::sync::atomic::Ordering::SeqCst);
}
}
/// Whether the bits of all of `[first, last)` are set (not so of none).
fn all(&self, first: usize, last: usize) -> bool {
let mut block = first;
while block < last {
let word = block / 64;
let until = ((word + 1) * 64).min(last);
let mask = (u64::MAX >> (64 - (until - block))) << (block % 64);
let Some(piece) = self.piece(word) else {
return false;
};
if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::Acquire) & mask != mask {
return false;
}
block = until;
}
first < last
}
}
/// The blocks that are read-only by our hand, not written since, and of
/// which the journal holds every write from before that: for those, what
/// [`writes`] answers is in the journal, and neither the kernel, nor the
/// guards' lock, nor [`ASKING`] need be asked.
///
/// Why that is so: a block's bit is set under the guards' lock while the
/// block is clean, by the asking that made it clean, after that asking noted
/// in the journal what it found ([`publish`]). It is cleared under the same
/// lock, before the block becomes writable again ([`open`]) or is forgotten
/// ([`title_memory_remapped`]). So while the bit is set nothing can have
/// written the block through this address, and who sees the bit and looks
/// at the journal after that finds every earlier write in it. A write that
/// comes while the bit is looked at is no different from one that comes just
/// after an asking: the next asking finds the block open.
static PUBLISHED: Bits = Bits::new();
/// An asking made blocks of `pages` clean and noted them in the journal.
fn publish(pages: &[usize]) {
let g = guards();
for page in pages {
if g.clean.contains(page) {
PUBLISHED.set(*page);
}
}
}
/// Whether nothing of `[start, end)` can have been written since an asking
/// noted it in the journal ([`PUBLISHED`]).
fn published(start: usize, end: usize) -> bool {
light() && PUBLISHED.all(start / BLOCK, end.div_ceil(BLOCK))
}
/// Since the last frame line: what asking about title memory was. Kernel
/// askings and the KiB they walked; view ranges answered by their bits, by
/// the guards whole clean, and block by block; blocks made read-only; blocks
/// opened by ourselves; nanoseconds waiting for the guards' lock and
/// nanoseconds of changing protections (all threads).
#[cfg(feature = "diagnostics")]
static ASKS: [std::sync::atomic::AtomicU64; 9] = [const { std::sync::atomic::AtomicU64::new(0) }; 9];
#[cfg(feature = "diagnostics")]
fn tally(what: usize, n: u64) {
ASKS[what].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
}
/// [`ASKS`], taken.
#[cfg(feature = "diagnostics")]
pub(crate) fn asks() -> [u64; 9] {
std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
}
/// The guards' lock, the wait for it counted.
fn guards_timed() -> std::sync::MutexGuard<'static, Guards> {
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
let g = guards();
#[cfg(feature = "diagnostics")]
tally(7, started.elapsed().as_nanos() as u64);
g
}
struct Guards {
/// Blocks we made read-only.
protected: BTreeSet<usize>,
@@ -449,7 +636,28 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> {
/// The 4 KiB pages of title memory that what shaders wrote was put into,
/// and the frame it last was.
static LANDED: Mutex<Option<std::collections::HashMap<usize, u64>>> = Mutex::new(None);
static LANDED: Mutex<Option<std::collections::HashMap<usize, u64, std::hash::BuildHasherDefault<PageHash>>>> = Mutex::new(None);
/// A page's number, spread: some 20,000 a frame are noted in [`LANDED`].
#[derive(Default)]
struct PageHash(u64);
impl std::hash::Hasher for PageHash {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for &byte in bytes {
self.write_u64(u64::from(byte));
}
}
fn write_u64(&mut self, n: u64) {
self.0 = (self.0 ^ n).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(26).wrapping_mul(0x9e37_79b9_7f4a_7c15);
}
fn write_usize(&mut self, n: usize) {
self.write_u64(n as u64);
}
}
/// What shaders wrote is about to go into title memory at `[at, at + len)`.
pub(crate) fn landing(at: usize, len: usize) {
@@ -464,6 +672,48 @@ pub(crate) fn landing(at: usize, len: usize) {
writing(at, len);
}
/// What shaders wrote went into title memory through another view of the
/// same pages (`crate::inplace::beside`): `pages` (of 4 KiB, by number)
/// hold some of it, all of them in `spans` (address, bytes).
///
/// Nothing faulted and no guard was opened. A guarded block stays read-only,
/// clean, and known by its bit ([`PUBLISHED`]), all of which say that the
/// title wrote nothing there: our write is an entry of the journal, which
/// every answer about the block comes from, the quick ones and the guards'
/// alike (a block whose guard is off they report anyway). So neither the
/// guards' lock nor a protection is touched here, or by the next refresh.
/// Noted after the bytes are in, never before: a copy that read the block
/// before they were did so with the number of an asking made before that,
/// which is under the one given here, and takes it again; noted before, a
/// copy could read the older bytes with a number above the note's.
pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) {
{
let frame = crate::frame::current();
let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
let landed = landed.get_or_insert_with(Default::default);
for &page in pages {
landed.insert(page, frame);
}
}
{
let mut j = journal_mut();
let now = next_asking();
let mut last = usize::MAX;
for &page in pages {
let block = page * KERNEL_PAGE / PAGE;
if block != last {
j.written.insert(block, now);
last = block;
}
}
}
for &(at, len) in spans {
// A placed texture there changes with no descriptor written.
crate::descriptor::host::remapped(at, len);
}
}
/// Whether shaders' writes went into a page of `[at, at + len)` in the last
/// `frames` frames.
pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool {
@@ -476,7 +726,8 @@ pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool {
/// Whether every block of `[at, at + len)` is view memory written since a
/// host copy last took it: guarded then, and the guard is off. (Written by
/// the title, or by us putting a flight's shader writes into it.) Not for
/// the title, or by us putting a flight's shader writes into it, if not
/// beside the guard, [`landed_beside`].) Not for
/// blocks no copy ever took, which were never guarded: the caller's range
/// lies in a copy a flight was given, which took all of it.
pub(crate) fn written_since_taken(at: usize, len: usize) -> bool {
@@ -485,7 +736,7 @@ pub(crate) fn written_since_taken(at: usize, len: usize) -> bool {
}
let g = guards();
(at / BLOCK..=(at + len - 1) / BLOCK)
.all(|b| !g.protected.contains(&b) && !g.clean.contains(&b) && !g.absent.contains(&b))
.all(|b| !g.clean.contains(&b) && !g.absent.contains(&b))
}
/// For view memory: the pages of `[start, end)`'s blocks written since
@@ -501,7 +752,7 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
// `VICTORY_GUARD_ASK=1` asks every time, as before.
static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && {
let g = guards();
let g = guards_timed();
let first = start / BLOCK;
g.protected.contains(&first) || g.absent.contains(&first)
};
@@ -509,7 +760,7 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
return None;
}
install();
let mut g = guards();
let mut g = guards_timed();
let mut written = Vec::new();
let mut run: Option<usize> = None;
let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
@@ -521,8 +772,12 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
let clean: Vec<usize> = g.clean.range(first..last).copied().collect();
if clean.len() == last - first {
// Nothing written, mapped or new since the range was last taken.
#[cfg(feature = "diagnostics")]
tally(3, 1);
return Some(written);
}
#[cfg(feature = "diagnostics")]
tally(4, 1);
let mut next_clean = 0;
let mut uncommitted_until = first;
for block in first..=last {
@@ -610,15 +865,23 @@ fn protect(g: &mut Guards, from: usize, to: usize) {
use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect};
let set = |from: usize, to: usize| {
let mut old = 0;
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
// SAFETY: title view memory; only its protection changes.
unsafe {
let done = unsafe {
VirtualProtect(
(from * BLOCK) as *const _,
(to - from) * BLOCK,
PAGE_READONLY,
&mut old,
) != 0
};
#[cfg(feature = "diagnostics")]
{
tally(5, (to - from) as u64);
tally(8, started.elapsed().as_nanos() as u64);
}
done
};
let note = |g: &mut Guards, from: usize, to: usize| {
g.protected.extend(from..to);
@@ -662,13 +925,21 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool {
.range(start / BLOCK..end.div_ceil(BLOCK))
.copied()
.collect();
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
for &block in &blocks {
g.protected.remove(&block);
g.clean.remove(&block);
// Before the block can be written.
PUBLISHED.clear(block);
let mut old = 0;
// SAFETY: a block we made read-only.
unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) };
}
#[cfg(feature = "diagnostics")]
if !blocks.is_empty() {
tally(8, started.elapsed().as_nanos() as u64);
}
!blocks.is_empty()
}
@@ -678,7 +949,14 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool {
/// reads into its own memory.
pub fn writing(at: usize, len: usize) {
// The length is the title's (`fread`'s size times count, saturated).
open(&mut guards(), at, at.saturating_add(len));
{
let mut g = guards_timed();
#[cfg(feature = "diagnostics")]
let held = g.protected.len();
open(&mut g, at, at.saturating_add(len));
#[cfg(feature = "diagnostics")]
tally(6, (held - g.protected.len()) as u64);
}
// A placed texture there changes with no descriptor written.
crate::descriptor::host::remapped(at, len);
}
@@ -758,6 +1036,7 @@ pub fn title_memory_unmapping(at: usize, len: usize) {
for block in blocks {
g.protected.remove(&block);
g.clean.remove(&block);
PUBLISHED.clear(block);
}
}
@@ -1338,4 +1617,111 @@ mod many_askers_tests {
// SAFETY: the reservation made above.
unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) };
}
/// The same of view memory, which is guarded: what its bits answer
/// misses no write either, however often blocks are opened and guarded
/// again between.
#[test]
fn no_write_to_views_is_lost_between_askers() {
const PAGES: usize = 12;
const THREADS: usize = 8;
// SAFETY: a view of a section of our own.
let at = unsafe {
let section = CreateFileMappingW(
-1isize as _,
std::ptr::null(),
PAGE_READWRITE,
0,
(PAGES * PAGE) as u32,
std::ptr::null(),
);
let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, PAGES * PAGE).Value as usize;
crate::title_memory_section(section as usize, (PAGES * PAGE) as u64, true);
super::title_memory_remapped(at, PAGES * PAGE);
crate::title_memory_view(at, PAGES * PAGE, section as usize, 0);
at
};
assert!(at != 0 && at.is_multiple_of(PAGE));
let by_bits = std::sync::atomic::AtomicUsize::new(0);
let past = std::sync::atomic::AtomicUsize::new(0);
std::thread::scope(|s| {
for t in 0..THREADS {
let (by_bits, past) = (&by_bits, &past);
s.spawn(move || {
let mut last = [0u64; PAGES];
let mut seed = t as u64 * 7919 + 1;
let mut next = |n: usize| {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(seed >> 33) as usize % n
};
for _ in 0..500 {
let page = next(PAGES);
let from = page - next(page.min(3) + 1);
let to = page + 1 + next((PAGES - page).min(3));
if next(4) != 0 {
// As in the test above, or after a word of ours,
// or past the guard.
let word = at + page * PAGE + t * 8;
// SAFETY (both): as above.
let reading = (next(3) == 0).then(super::title_memory_reading_now).flatten();
let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8));
if let Some(to) = beside {
unsafe { (to as *mut u64).write_volatile(2) };
super::landed_beside(&[word / 4096], &[(word, 8)]);
past.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
assert_eq!(unsafe { (word as *const u64).read_volatile() }, 2, "put elsewhere");
} else {
if next(4) == 0 {
super::writing(word, 8);
}
unsafe { (word as *mut u64).write_volatile(1) };
}
} else {
// Nothing written: what is asked counts as before.
by_bits.fetch_add(
usize::from(super::published(at + from * PAGE, at + to * PAGE)),
std::sync::atomic::Ordering::Relaxed,
);
let (now, _) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view");
for l in &mut last[from..to] {
*l = now;
}
continue;
}
let (now, written) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view");
let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1);
assert!(number > last[page], "page {page}: {number} is not after {}", last[page]);
for l in &mut last[from..to] {
*l = now;
}
}
});
}
});
assert!(by_bits.into_inner() > 0, "the bits answered none");
assert!(past.into_inner() > 0, "nothing was put past the guards");
// (The view stays: at its address other tests' memory would be told
// of these writes.)
}
/// A range's bits are all of its blocks', whatever lies beside them.
#[test]
fn bits_of_ranges() {
static BITS: super::Bits = super::Bits::new();
let blocks = [0usize, 1, 63, 64, 65, 127, 128, 200, 65535, 65536, 65537, 1 << 20, (1 << 31) - 1];
for &b in &blocks {
assert!(!BITS.all(b, b + 1));
BITS.set(b);
assert!(BITS.all(b, b + 1));
}
assert!(BITS.all(0, 2) && BITS.all(63, 66) && BITS.all(127, 129) && BITS.all(65535, 65538));
assert!(!BITS.all(0, 3) && !BITS.all(62, 64) && !BITS.all(65534, 65536) && !BITS.all(5, 5));
for b in 300..700 {
BITS.set(b);
}
assert!(BITS.all(300, 700) && !BITS.all(299, 700) && !BITS.all(300, 701));
BITS.clear(511);
assert!(!BITS.all(300, 700) && BITS.all(300, 511) && BITS.all(512, 700));
assert!(!BITS.all(1 << 40, (1 << 40) + 1), "outside the address space");
}
}