Merge local/next (a79e248) into local/tests
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
338f42479e
40 files changed
+12028
-434
No files matched your search
@@ -53,15 +53,34 @@ pub(crate) struct Replay {
|
||||
/// Leave out the argument clamps: what they bound is kept from a first run.
|
||||
#[arg(long)]
|
||||
skip_clamps: bool,
|
||||
/// The argument clamps in batches, as VICTORY_INDIRECT_BATCH does (2:
|
||||
/// a wait before every indirect dispatch).
|
||||
#[arg(long, num_args = 0..=1, default_missing_value = "1", default_value_t = 0)]
|
||||
batch_clamps: u32,
|
||||
/// Leave out the hash and compare passes over card buffers.
|
||||
#[arg(long)]
|
||||
skip_hash_passes: bool,
|
||||
/// Where buffers lie.
|
||||
#[arg(long, value_enum, default_value_t = Buffers::AsRecorded)]
|
||||
buffers: Buffers,
|
||||
/// With --buffers, only the buffers all of these match: `name=<text>`,
|
||||
/// `min=<bytes>`, `max=<bytes>`, `seen=<No, Cached, Combined>`,
|
||||
/// `id=<a>..<b>`, or `!` and one of those (may be given several times).
|
||||
#[arg(long)]
|
||||
only_buffers: Vec<String>,
|
||||
/// One ExecuteCommandLists for the whole frame.
|
||||
#[arg(long)]
|
||||
one_submit: bool,
|
||||
/// Let copies of what the CPU wrote also overwrite what the card wrote in
|
||||
/// the replay (as the recorded commands say).
|
||||
#[arg(long)]
|
||||
no_merge: bool,
|
||||
/// A full wait after every draw, dispatch, copy and clear.
|
||||
#[arg(long)]
|
||||
wait_all: bool,
|
||||
/// Each list sent on its own, and waited for.
|
||||
#[arg(long)]
|
||||
wait_lists: bool,
|
||||
/// Run only these lists, by their place in the frame (`3..7`, or `5`);
|
||||
/// of the others only barriers.
|
||||
#[arg(long)]
|
||||
@@ -70,6 +89,48 @@ pub(crate) struct Replay {
|
||||
/// (may be given several times).
|
||||
#[arg(long = "skip-shader")]
|
||||
skip_shader: Vec<String>,
|
||||
/// Find the commands that make identical runs differ: each list is run
|
||||
/// this often from the same memory.
|
||||
#[arg(long, num_args = 0..=1, default_missing_value = "3")]
|
||||
diverge: Option<u32>,
|
||||
/// Find where the picture's variants are decided: from each list on, the
|
||||
/// rest of the frame is run this often from the same memory.
|
||||
#[arg(long, num_args = 0..=1, default_missing_value = "5")]
|
||||
diverge_picture: Option<u32>,
|
||||
/// Run each draw of one list (--lists) whose pipeline's name has this in
|
||||
/// it alone, --diverge times: how many outcomes it has.
|
||||
#[arg(long)]
|
||||
draws: Option<String>,
|
||||
/// Say which lists (with --lists: commands) change words of buffers:
|
||||
/// `<resource>:<offset>:<bytes>` (hexadecimal; repeatable).
|
||||
#[arg(long)]
|
||||
watch: Vec<String>,
|
||||
/// With --diverge-picture and one list in --lists: its commands (`0..900`)
|
||||
/// and how many are stepped over at a time.
|
||||
#[arg(long)]
|
||||
commands: Option<String>,
|
||||
#[arg(long, default_value_t = 1)]
|
||||
step: usize,
|
||||
/// With --diverge and --diverge-picture: only these lists (`3..7`).
|
||||
#[arg(long)]
|
||||
lists: Option<String>,
|
||||
/// With --diverge: the most commands named of one list.
|
||||
#[arg(long, default_value_t = 4)]
|
||||
roots: u32,
|
||||
/// Name resources the frame changes that the replay does not put back.
|
||||
#[arg(long)]
|
||||
check_written: bool,
|
||||
/// Name what the heap slots hold that a command's constants name:
|
||||
/// `<list>:<command>`.
|
||||
#[arg(long)]
|
||||
slots: Option<String>,
|
||||
/// Only write the DXIL of pipelines with this in their name to the
|
||||
/// capture's `shaders` folder.
|
||||
#[arg(long)]
|
||||
dump: Option<String>,
|
||||
/// Only write the frame's buffers and the commands of these lists (`3..7`).
|
||||
#[arg(long)]
|
||||
listing: Option<String>,
|
||||
/// Use the D3D12 debug layer (slow).
|
||||
#[arg(long)]
|
||||
debug_layer: bool,
|
||||
@@ -84,6 +145,16 @@ fn range(text: &str) -> Option<(u32, u32)> {
|
||||
}
|
||||
|
||||
pub(crate) fn run(r: Replay) -> Result<()> {
|
||||
if let Some(text) = &r.dump {
|
||||
for line in play::dump(&r.folder, text)? {
|
||||
println!("{line}");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(text) = &r.listing {
|
||||
let lists = range(text).with_context(|| format!("--listing {text}"))?;
|
||||
return play::listing(&r.folder, lists, &mut |line| println!("{line}"));
|
||||
}
|
||||
let only = match &r.only {
|
||||
Some(text) => Some(
|
||||
range(text)
|
||||
@@ -102,16 +173,84 @@ pub(crate) fn run(r: Replay) -> Result<()> {
|
||||
Buffers::Vram => play::Buffers::Card,
|
||||
Buffers::Sysmem => play::Buffers::Pc,
|
||||
},
|
||||
only_buffers: r.only_buffers,
|
||||
no_barriers: r.no_barriers,
|
||||
merge_barriers: r.merge_barriers,
|
||||
skip_clamps: r.skip_clamps,
|
||||
batch_clamps: r.batch_clamps,
|
||||
skip_hash_passes: r.skip_hash_passes,
|
||||
one_submit: r.one_submit,
|
||||
merge: !r.no_merge,
|
||||
wait_all: r.wait_all,
|
||||
wait_lists: r.wait_lists,
|
||||
only,
|
||||
skip_shaders: r.skip_shader,
|
||||
compare: r.compare,
|
||||
debug: r.debug_layer,
|
||||
};
|
||||
if let Some(text) = &r.slots {
|
||||
let (list, command) = text
|
||||
.split_once(':')
|
||||
.and_then(|(l, c)| Some((l.parse().ok()?, c.parse().ok()?)))
|
||||
.with_context(|| format!("--slots {text}: not <list>:<command>"))?;
|
||||
let player = play::Player::load(&r.folder, &options)?;
|
||||
return player.slots(list, command, &mut |line| println!("{line}"));
|
||||
}
|
||||
if r.check_written {
|
||||
let mut player = play::Player::load(&r.folder, &options)?;
|
||||
return player.check_written(&mut |line| println!("{line}"));
|
||||
}
|
||||
let mut watched = Vec::new();
|
||||
for text in &r.watch {
|
||||
let mut n = text
|
||||
.split(':')
|
||||
.map(|p| u64::from_str_radix(p.trim_start_matches("0x"), 16));
|
||||
let mut next = || {
|
||||
n.next()
|
||||
.and_then(Result::ok)
|
||||
.with_context(|| format!("--watch {text}"))
|
||||
};
|
||||
let id = text
|
||||
.split(':')
|
||||
.next()
|
||||
.and_then(|p| p.parse().ok())
|
||||
.with_context(|| format!("--watch {text}"))?;
|
||||
let _ = next();
|
||||
watched.push((id, next()?, next()?));
|
||||
}
|
||||
if let Some(runs) = r
|
||||
.diverge
|
||||
.or(r.diverge_picture)
|
||||
.or((!watched.is_empty()).then_some(2))
|
||||
{
|
||||
let lists = match &r.lists {
|
||||
Some(text) => Some(range(text).with_context(|| format!("--lists {text}"))?),
|
||||
None => None,
|
||||
};
|
||||
let search = play::diverge::Search {
|
||||
runs: runs.max(2),
|
||||
lists,
|
||||
roots: r.roots,
|
||||
wait_all: options.wait_all,
|
||||
options: options.clone(),
|
||||
};
|
||||
let mut player = play::Player::load(&r.folder, &options)?;
|
||||
if !watched.is_empty() {
|
||||
return player.watch(&search, &watched, &mut |line| println!("{line}"));
|
||||
}
|
||||
if let Some(text) = &r.draws {
|
||||
return player.diverge_draws(&search, text, &mut |line| println!("{line}"));
|
||||
}
|
||||
if r.diverge_picture.is_some() {
|
||||
let commands = match &r.commands {
|
||||
Some(text) => Some(range(text).with_context(|| format!("--commands {text}"))?),
|
||||
None => None,
|
||||
};
|
||||
return player
|
||||
.diverge_picture(&search, commands, r.step, &mut |line| println!("{line}"));
|
||||
}
|
||||
return player.diverge(&search, &mut |line| println!("{line}"));
|
||||
}
|
||||
let reports = play::replay(&r.folder, &options)?;
|
||||
for (what, report) in &reports {
|
||||
println!("{}", report.text(what));
|
||||
|
||||
@@ -598,6 +598,12 @@ fn check(
|
||||
if let Some(keep) = &checks.keep {
|
||||
lock(keep).push((label(), shader.clone()));
|
||||
}
|
||||
// With `--list`: a hash of the module and of what the host binds for it,
|
||||
// to show which shaders a change to the translator touches.
|
||||
if t.list {
|
||||
let hash = blake3::hash(format!("{shader:?}").as_bytes()).to_hex();
|
||||
t.lines.push(format!("{} emitted {}", label(), &hash[..16]));
|
||||
}
|
||||
// `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file.
|
||||
if t.list
|
||||
&& let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP")
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
@@ -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 {
|
||||
|
||||
+1429
-160
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
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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>>,
|
||||
|
||||
@@ -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
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -141,10 +141,12 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out
|
||||
tracing::warn!(path = name, %error, "dstorage: opening a file failed");
|
||||
return from_win32(&error);
|
||||
}
|
||||
let kept = name.clone();
|
||||
tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened");
|
||||
// SAFETY: a handle we just opened and nobody else owns.
|
||||
let file = unsafe { std::fs::File::from_raw_handle(handle) };
|
||||
let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file });
|
||||
WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept));
|
||||
put(out, file)
|
||||
}
|
||||
|
||||
@@ -440,6 +442,52 @@ impl Scheduler {
|
||||
}
|
||||
}
|
||||
|
||||
/// The walls trace (`VICTORY_WALLS_TRACE`): 0 or unset: off; 1: a line for
|
||||
/// every read request that fails, with its file; 2: for every request (the
|
||||
/// list of a launch's reads, by file and offset, is what a launch with the
|
||||
/// first room's walls and one without are compared by).
|
||||
fn walls_trace() -> u8 {
|
||||
static ON: OnceLock<u8> = OnceLock::new();
|
||||
*ON.get_or_init(|| {
|
||||
std::env::var("VICTORY_WALLS_TRACE").ok().and_then(|v| v.trim().parse::<u8>().ok()).unwrap_or(0)
|
||||
})
|
||||
}
|
||||
|
||||
/// The files opened, by the address of our file object, with their paths
|
||||
/// (for the walls trace: a request names its file by that address).
|
||||
static WALLS_FILES: Mutex<Vec<(usize, String)>> = Mutex::new(Vec::new());
|
||||
|
||||
/// The walls trace's line for a request that is done.
|
||||
fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std::time::Instant) {
|
||||
let level = walls_trace();
|
||||
if level == 0 || (level == 1 && result.is_ok()) {
|
||||
return;
|
||||
}
|
||||
let file = if request.options & MEMORY_SOURCE != 0 {
|
||||
"memory".to_string()
|
||||
} else {
|
||||
let files = WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let source = request.source as usize;
|
||||
files.iter().find(|f| f.0 == source).map_or_else(|| "?".to_string(), |f| f.1.clone())
|
||||
};
|
||||
let hr = match result {
|
||||
Ok(()) => 0,
|
||||
Err(hr) => *hr as u32,
|
||||
};
|
||||
tracing::info!(
|
||||
file,
|
||||
offset = request.offset,
|
||||
source_size = request.source_size,
|
||||
destination_size = request.destination_size,
|
||||
to_pages = request.options & PAGE_DESTINATION != 0,
|
||||
options = format_args!("{:#x}", request.options),
|
||||
ms = started.elapsed().as_millis() as u64,
|
||||
ok = result.is_ok(),
|
||||
hr = format_args!("{hr:#010x}"),
|
||||
"walls trace: a read request is done"
|
||||
);
|
||||
}
|
||||
|
||||
/// A worker: runs the next read of the most deserving queue.
|
||||
fn work(scheduler: &'static Scheduler) {
|
||||
let mut lanes = scheduler.lock();
|
||||
@@ -451,6 +499,7 @@ fn work(scheduler: &'static Scheduler) {
|
||||
drop(lanes);
|
||||
let started = std::time::Instant::now();
|
||||
let result = execute(&job.request);
|
||||
walls_request(&job.request, &result, started);
|
||||
lanes = scheduler.lock();
|
||||
lanes.finish(&job, result);
|
||||
lanes.count(&job, started);
|
||||
|
||||
@@ -419,6 +419,7 @@ impl Drop for Section {
|
||||
})
|
||||
};
|
||||
}
|
||||
victory_gpu::title_memory_section_gone(self.handle as usize);
|
||||
// SAFETY: our handle; views keep the section alive on their own.
|
||||
unsafe { CloseHandle(self.handle) };
|
||||
}
|
||||
|
||||
@@ -63,6 +63,8 @@ pub const ALL: u32 = MODULE | FIRST;
|
||||
pub(crate) struct Usage {
|
||||
/// A wave or quad operation.
|
||||
pub wave_ops: bool,
|
||||
/// A rasterizer ordered view.
|
||||
pub rovs: bool,
|
||||
/// A 64-bit integer, as a result or an operand.
|
||||
pub int64: bool,
|
||||
/// A typed load of several components from a UAV.
|
||||
@@ -388,7 +390,7 @@ impl Module {
|
||||
}
|
||||
|
||||
/// An integer constant's width and value (the bits of that width).
|
||||
fn int_k(&self, v: V) -> Option<(u32, u64)> {
|
||||
pub(crate) fn int_k(&self, v: V) -> Option<(u32, u64)> {
|
||||
let V::Const(i) = v else { return None };
|
||||
let (ty, Const::Int(x)) = &self.consts[i as usize] else {
|
||||
return None;
|
||||
@@ -1009,6 +1011,8 @@ impl Module {
|
||||
Some((_, 0)) => u.heap_views = true,
|
||||
_ => u.heap_samplers = true,
|
||||
}
|
||||
} else if name == "annotateHandle" {
|
||||
u.rovs |= annotation(V::Inst(i)).is_some_and(|(kind, _)| kind & 0x2000 != 0);
|
||||
} else if name.starts_with("atomic") && name.ends_with(".i64") {
|
||||
u.atomic64 = true;
|
||||
} else if name.starts_with("textureLoad") || name.starts_with("bufferLoad") {
|
||||
|
||||
@@ -107,6 +107,64 @@ pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> {
|
||||
const TWO_PI: f32 = std::f32::consts::TAU;
|
||||
/// `s_sendmsg` id of a mesh or NGG stage's output allocation request.
|
||||
const GS_ALLOC_REQ: u16 = 9;
|
||||
/// `s_sendmsg` id that ends a pixel wave's ordered section.
|
||||
const ORDERED_PS_DONE: u16 = 7;
|
||||
/// Hardware register (of `s_setreg_b32`) a pixel wave names its packer in
|
||||
/// before it waits for the waves it overlaps.
|
||||
const POPS_PACKER: u16 = 25;
|
||||
/// The operand `src_pops_exiting_wave_id`.
|
||||
const POPS_EXITING: u8 = 239;
|
||||
|
||||
/// The instructions inside a pixel program's ordered section
|
||||
/// (primitive-ordered pixel shading, which the console compiler makes of
|
||||
/// rasterizer ordered views): from the write of `POPS_PACKER`, along every
|
||||
/// path, to the message that ends the section or the program's end. The
|
||||
/// console waits there until the waves holding earlier primitives' samples
|
||||
/// of the same pixels have left their sections; a host's rasterizer ordered
|
||||
/// views wait by themselves, at their first access. Empty for a program
|
||||
/// without such a section.
|
||||
fn ordered_section(p: &Program) -> HashSet<Site> {
|
||||
let starts = |i: &Inst| {
|
||||
i.name() == "s_setreg_b32"
|
||||
&& matches!(i.fields, Fields::Sop { imm: Some(imm), .. } if imm & 0x3F == POPS_PACKER)
|
||||
};
|
||||
let ends = |i: &Inst| {
|
||||
i.name() == "s_sendmsg"
|
||||
&& matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == ORDERED_PS_DONE)
|
||||
};
|
||||
let mut section = HashSet::new();
|
||||
let mut entered = vec![false; p.blocks.len()];
|
||||
let mut work: Vec<Site> = p
|
||||
.blocks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(b, block)| {
|
||||
(0..block.insts.len())
|
||||
.filter(|&i| starts(&block.insts[i]))
|
||||
.map(move |i| (b, i))
|
||||
})
|
||||
.collect();
|
||||
while let Some((b, from)) = work.pop() {
|
||||
let block = &p.blocks[b];
|
||||
let mut done = false;
|
||||
for i in from..block.insts.len() {
|
||||
if ends(&block.insts[i]) {
|
||||
done = true;
|
||||
break;
|
||||
}
|
||||
section.insert((b, i));
|
||||
}
|
||||
if done {
|
||||
continue;
|
||||
}
|
||||
for (t, next) in p.blocks.iter().enumerate() {
|
||||
if next.preds.contains(&b) && !std::mem::replace(&mut entered[t], true) {
|
||||
work.push((t, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
section
|
||||
}
|
||||
|
||||
/// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0,
|
||||
/// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)).
|
||||
@@ -194,6 +252,13 @@ struct Lower<'a> {
|
||||
/// Descriptor dwords with no host value (addresses, formats, all of a constant
|
||||
/// buffer's): no program reads them as numbers ([`Self::dead`]).
|
||||
stale: HashSet<Value>,
|
||||
/// See [`ordered_section`] (pixel programs).
|
||||
ordered: HashSet<Site>,
|
||||
/// Raw UAV buffers (see [`Lower::entry`]) the program loads from past its
|
||||
/// wave's cache (GLC): other groups write what it waits for. On the host
|
||||
/// they are globally coherent; a load in a loop that only waits would
|
||||
/// be made once otherwise.
|
||||
coherent: HashSet<(usize, u32)>,
|
||||
mask_phis: HashMap<Value, V>,
|
||||
pending_masks: Vec<(V, usize, usize)>,
|
||||
data_phis: Vec<(V, usize, usize)>,
|
||||
@@ -1486,6 +1551,12 @@ impl<'a> Lower<'a> {
|
||||
data_phis: Vec::new(),
|
||||
read_phis: HashSet::new(),
|
||||
stale: HashSet::new(),
|
||||
coherent: HashSet::new(),
|
||||
ordered: if x.native.stage == HwStage::Ps {
|
||||
ordered_section(p)
|
||||
} else {
|
||||
HashSet::new()
|
||||
},
|
||||
params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(),
|
||||
user_data: None,
|
||||
user_reads: BTreeMap::new(),
|
||||
@@ -2064,9 +2135,12 @@ impl<'a> Lower<'a> {
|
||||
/// lane whose number differs in one bit, step by step; two host waves of 32 then exchange
|
||||
/// their halves' sums for the last addition. The high half of the result is lane 0's,
|
||||
/// which no `v_add_f16` writes.
|
||||
/// That needs every lane of a full wave there to be read: refused where not every lane
|
||||
/// runs, in a thread group that does not fill its waves, and for each half-wave on its
|
||||
/// own (half a sum is no sum).
|
||||
/// On a host wave of 64 lanes where not every lane runs, the lanes that are elsewhere
|
||||
/// count as the console's do (it masks them to +0): a partner's partial sum is read from
|
||||
/// the first lane there is of the partner's run of lanes, and is +0 without one. Two host
|
||||
/// waves of 32 can only exchange where every lane runs: refused elsewhere, in a thread
|
||||
/// group that does not fill its waves, and for each half-wave on its own (half a sum is
|
||||
/// no sum).
|
||||
fn half_sum(&mut self, x: V) -> Result<V, Why> {
|
||||
const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs";
|
||||
let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?;
|
||||
@@ -2087,24 +2161,54 @@ impl<'a> Lower<'a> {
|
||||
} else {
|
||||
all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false))
|
||||
};
|
||||
if !every {
|
||||
if halves {
|
||||
need(self.cur_ir);
|
||||
}
|
||||
if !every && halves {
|
||||
need(self.cur_ir);
|
||||
return Err(WHERE);
|
||||
}
|
||||
let c = self.cur;
|
||||
let i32t = self.s.t.i32;
|
||||
let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
|
||||
let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0));
|
||||
// the lanes that are here, when not all are
|
||||
let here = (!every).then(|| {
|
||||
self.s.flags |= flags::WAVE_OPS;
|
||||
let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
|
||||
let yes = self.s.m.bool(true);
|
||||
let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[yes]);
|
||||
(self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1))
|
||||
});
|
||||
// `v` of the first lane here of the `n` (a power of two) lanes from `base`: +0 of none
|
||||
let first_of = |l: &mut Self, v: V, base: V, n: u32| {
|
||||
let Some((lo, hi)) = here else {
|
||||
return l.read_lane(v, base);
|
||||
};
|
||||
let (k31, k32) = (l.s.m.i32(31), l.s.m.i32(32));
|
||||
let lower = l.s.m.cmp(c, pred::IULT, base, k32);
|
||||
let word = l.s.m.select(c, lower, lo, hi);
|
||||
let shift = l.s.m.bin(c, Bin::And, base, k31);
|
||||
let word = l.s.m.bin(c, Bin::LShr, word, shift);
|
||||
let run = l.s.m.i32(u32::MAX >> (32 - n));
|
||||
let word = l.s.m.bin(c, Bin::And, word, run);
|
||||
let any = l.s.m.cmp(c, pred::NE, word, zero);
|
||||
let nth = l.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[word]);
|
||||
let from = l.s.m.bin(c, Bin::Add, base, nth);
|
||||
// (no lane there: this one, which is here; the read is not used)
|
||||
let from = l.s.m.select(c, any, from, lane);
|
||||
let got = l.read_lane(v, from);
|
||||
l.s.m.select(c, any, got, zero)
|
||||
};
|
||||
let mut sum = x;
|
||||
for step in 0..if halves { 5 } else { 6 } {
|
||||
let bit = self.s.m.i32(1 << step);
|
||||
let partner = self.s.m.bin(c, Bin::Xor, lane, bit);
|
||||
let theirs = self.read_lane(sum, partner);
|
||||
let mut partner = self.s.m.bin(c, Bin::Xor, lane, bit);
|
||||
if !every {
|
||||
let run = self.s.m.i32(!((1 << step) - 1));
|
||||
partner = self.s.m.bin(c, Bin::And, partner, run);
|
||||
}
|
||||
let theirs = first_of(self, sum, partner, 1 << step);
|
||||
sum = self.add_halves(sum, theirs);
|
||||
}
|
||||
let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0));
|
||||
let first = self.read_lane(x, zero);
|
||||
let first = first_of(self, x, zero, 1);
|
||||
let first = self.s.m.bin(c, Bin::And, first, high);
|
||||
let sum = self.s.m.bin(c, Bin::And, sum, low);
|
||||
let mine = self.s.m.bin(c, Bin::Or, first, sum);
|
||||
@@ -2121,6 +2225,7 @@ impl<'a> Lower<'a> {
|
||||
|
||||
fn run(mut self) -> Result<Lowered, Stop> {
|
||||
let p = self.x.p;
|
||||
self.find_coherent();
|
||||
let order = crate::ir::reverse_postorder(&p.blocks);
|
||||
for (n, &b) in order.iter().enumerate() {
|
||||
self.rpo[b] = n;
|
||||
@@ -2258,6 +2363,8 @@ impl<'a> Lower<'a> {
|
||||
// paths only seem to allow it before any save: the lane of a VGPR
|
||||
// nobody wrote, and VGPRs nobody set read as zero.
|
||||
None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)),
|
||||
// No wave overlaps this one (see `ordered_section`).
|
||||
None if self.pops_collision(v) => Val::I32(self.s.m.i32(0)),
|
||||
None => Val::Missing("a hardware SGPR input"),
|
||||
},
|
||||
Reg::Scc => Val::Missing("SCC on entry"),
|
||||
@@ -2273,6 +2380,36 @@ impl<'a> Lower<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the input SGPR `v` is the POPS collision wave id: a program
|
||||
/// with an ordered section only takes its fields apart (bit 31 says
|
||||
/// that the wave overlaps another, the others which packer and waves).
|
||||
fn pops_collision(&self, v: Value) -> bool {
|
||||
if self.ordered.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let mut packer = false;
|
||||
for block in &self.x.p.blocks {
|
||||
if block.phis.iter().any(|p| p.args.contains(&v)) {
|
||||
return false;
|
||||
}
|
||||
for i in &block.insts {
|
||||
if !i.reads.iter().any(|r| r.1 == v) {
|
||||
continue;
|
||||
}
|
||||
let Fields::Sop { src, .. } = &i.fields else {
|
||||
return false;
|
||||
};
|
||||
match (i.name(), src.get(1)) {
|
||||
// bits 28 and 29: the packer
|
||||
("s_bfe_u32", Some(Operand::Literal(0x0002_001C))) => packer = true,
|
||||
("s_bfe_u32" | "s_lshr_b32", _) => {}
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
packer
|
||||
}
|
||||
|
||||
fn input(&mut self, input: Input) -> Val {
|
||||
let (kind, col) = match input {
|
||||
Input::VertexId => (1, 0),
|
||||
@@ -2632,6 +2769,18 @@ impl<'a> Lower<'a> {
|
||||
self.s.m.extract(entry, r, index % 4)
|
||||
}
|
||||
|
||||
/// Whether some instruction reads `v` as a number (or may, through a
|
||||
/// join), rather than in a descriptor operand.
|
||||
fn read_as_number(&self, v: Value) -> bool {
|
||||
self.x.p.blocks.iter().any(|b| {
|
||||
b.phis.iter().any(|p| p.args.contains(&v))
|
||||
|| b.insts.iter().any(|i| {
|
||||
matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_))
|
||||
&& i.reads.iter().any(|r| r.1 == v)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether some instruction computes with `v` (scalar or vector
|
||||
/// arithmetic), rather than only naming it in a descriptor operand,
|
||||
/// moving it (at most `depth` moves are followed) or comparing it: a
|
||||
@@ -2665,6 +2814,112 @@ impl<'a> Lower<'a> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the image `src` names is one of 32-bit integers (one channel):
|
||||
/// the program has an integer atomic on the same table entry, which
|
||||
/// takes no other view.
|
||||
fn is_counter(&self, src: &Source) -> bool {
|
||||
let Some(this) = self.entry(src) else {
|
||||
return false;
|
||||
};
|
||||
self.x.res.descriptors.iter().any(|d| {
|
||||
let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
|
||||
d.role == Role::Resource
|
||||
&& matches!(i.fields, Fields::Image { dmask: 1, .. })
|
||||
&& matches!(
|
||||
i.name(),
|
||||
"image_atomic_add"
|
||||
| "image_atomic_sub"
|
||||
| "image_atomic_and"
|
||||
| "image_atomic_or"
|
||||
| "image_atomic_xor"
|
||||
| "image_atomic_smin"
|
||||
| "image_atomic_smax"
|
||||
| "image_atomic_umin"
|
||||
| "image_atomic_umax"
|
||||
)
|
||||
&& self.entry(&d.source) == Some(this)
|
||||
})
|
||||
}
|
||||
|
||||
/// Which table entry `src` is loaded from: its root parameter and byte.
|
||||
fn entry(&self, src: &Source) -> Option<(usize, u32)> {
|
||||
let Source::Loaded { load, first } = src else {
|
||||
return None;
|
||||
};
|
||||
let a = self.scalar.get(load).filter(|a| a.dynamic.is_none())?;
|
||||
Some((a.param, a.offset + 4 * u32::from(*first)))
|
||||
}
|
||||
|
||||
/// See [`Lower::coherent`].
|
||||
fn find_coherent(&mut self) {
|
||||
let found: Vec<_> = self
|
||||
.x
|
||||
.res
|
||||
.descriptors
|
||||
.iter()
|
||||
.filter(|d| {
|
||||
let i = &self.x.p.blocks[d.site.0].insts[d.site.1];
|
||||
matches!(&i.fields, Fields::Buffer { cache, .. } if cache.glc)
|
||||
&& i.name().starts_with("buffer_load_dword")
|
||||
&& self.used_kind(&d.source).is_some_and(|u| u.kind == ResourceType::Uav)
|
||||
})
|
||||
.filter_map(|d| self.entry(&d.source))
|
||||
.collect();
|
||||
self.coherent.extend(found);
|
||||
}
|
||||
|
||||
/// The kind of a view no instruction uses (in this program, or through
|
||||
/// another load of its address), by what the code reads of the
|
||||
/// descriptor the load `inst` at `site` writes to the SGPRs from `code`:
|
||||
/// `Some(true)` for a 2D image, read only for its size, `Some(false)`
|
||||
/// for a structured buffer, read only for its record count.
|
||||
///
|
||||
/// - Eight dwords are an image's. `GetDimensions` of a 2D one reads the
|
||||
/// width (dwords 1 and 2), the height (dword 2, bits 14-29, with one
|
||||
/// `s_bfe_u32`) and the base level or the last (dword 3); of an array,
|
||||
/// a cube or a volume also dword 4.
|
||||
/// - Four dwords at a table entry the used resources list as an SRV or
|
||||
/// UAV are a buffer's. A stride above 4 bytes there is an element's
|
||||
/// (a typed or raw view has at most 4): a test for a null view reads
|
||||
/// the record count, nothing else.
|
||||
fn sized_view(&self, inst: &Inst, site: Site, code: u8, count: u32) -> Option<bool> {
|
||||
let dword = |k: u8| inst.write(Reg::S(code + k));
|
||||
let read = |v: Value| {
|
||||
self.x.p.blocks.iter().any(|b| {
|
||||
b.insts.iter().any(|i| i.reads.iter().any(|r| r.1 == v))
|
||||
|| b.phis.iter().any(|p| p.args.contains(&v))
|
||||
})
|
||||
};
|
||||
let only = |allowed: &[u8]| {
|
||||
(0..count as u8).all(|k| allowed.contains(&k) || !dword(k).is_some_and(read))
|
||||
};
|
||||
match count {
|
||||
8 => {
|
||||
const HEIGHT: u32 = 16 << 16 | 14;
|
||||
let v = dword(2)?;
|
||||
let height = self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| {
|
||||
i.name() == "s_bfe_u32"
|
||||
&& i.reads.iter().any(|r| r.1 == v)
|
||||
&& matches!(&i.fields, Fields::Sop { src, .. }
|
||||
if matches!(src.get(1), Some(Operand::Literal(HEIGHT))))
|
||||
});
|
||||
(height && only(&[1, 2, 3])).then_some(true)
|
||||
}
|
||||
4 => {
|
||||
let used = self.used_kind(&Source::Loaded { load: site, first: 0 })?;
|
||||
let a = self.scalar.get(&site)?;
|
||||
let buffer = used.dwords == 4
|
||||
&& a.dynamic.is_none()
|
||||
&& used.table_offset_dwords == a.offset / 4
|
||||
&& matches!(used.kind, ResourceType::Srv | ResourceType::Uav)
|
||||
&& used.stride > 4
|
||||
&& used.stride.is_multiple_of(4);
|
||||
(buffer && only(&[2])).then_some(false)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The title address (low dword, bits from 32 up) of the buffer view
|
||||
/// whose descriptor the scalar load at `site` reads from the start of
|
||||
/// a table entry, as the host tells it when it binds (`shader.rs`
|
||||
@@ -3116,6 +3371,8 @@ impl<'a> Lower<'a> {
|
||||
let bit = self.scc_in(inst)?;
|
||||
Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32))
|
||||
}
|
||||
// Nothing to wait for (see `ordered_section`).
|
||||
Operand::Const(POPS_EXITING) if !self.ordered.is_empty() => Ok(self.s.m.i32(0)),
|
||||
Operand::Const(c) => crate::resource::inline(c)
|
||||
.map(|x| self.s.m.i32(x))
|
||||
.ok_or("a special operand (vccz, execz, scc, lds_direct)"),
|
||||
@@ -5400,12 +5657,30 @@ impl<'a> Lower<'a> {
|
||||
|
||||
fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
|
||||
let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
|
||||
match self.get(v)? {
|
||||
Val::Bit(x) => Ok(x),
|
||||
_ => Err("SCC without a value"),
|
||||
match self.get(v) {
|
||||
Ok(Val::Bit(x)) => Ok(x),
|
||||
Ok(_) => Err("SCC without a value"),
|
||||
// Of a mask operation whose result lies within EXEC: whether
|
||||
// some lane is left.
|
||||
Err(LANE_MASK) if self.within_exec(v) => self.scc_some(v),
|
||||
Err(why) => Err(why),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the mask operation that sets the SCC value `scc` gives no
|
||||
/// lane outside EXEC a bit.
|
||||
fn within_exec(&self, scc: Value) -> bool {
|
||||
let Some(&b) = self.def_block.get(&scc) else {
|
||||
return false;
|
||||
};
|
||||
let by = self.x.p.blocks[b].insts.iter().find(|i| i.write(Reg::Scc) == Some(scc));
|
||||
by.is_some_and(|i| {
|
||||
i.write(Reg::S(EXEC)).is_some()
|
||||
|| matches!(&i.fields, Fields::Sop { dst: Some(Operand::Scalar { code, .. }), .. }
|
||||
if i.write(Reg::S(*code)).is_some_and(|lo| self.x.st.active.contains(&lo)))
|
||||
})
|
||||
}
|
||||
|
||||
fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
|
||||
let Fields::Smem {
|
||||
data,
|
||||
@@ -5653,7 +5928,12 @@ impl<'a> Lower<'a> {
|
||||
.find_map(|(s, _)| use_of(*s))
|
||||
};
|
||||
let use_at = use_of(site).or_else(twin);
|
||||
let Some((at, first)) = use_at else {
|
||||
// A view whose kind no use tells, but what is read of it does.
|
||||
let sized = match use_at {
|
||||
Some(_) => None,
|
||||
None => self.sized_view(inst, site, code, count),
|
||||
};
|
||||
let Some((at, first)) = use_at.or(sized.map(|_| (site, 0))) else {
|
||||
// A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only
|
||||
// copies its dwords and compares them, lane against first lane, and every load
|
||||
// that reaches those lanes reads one address. Each dword stands in as its place
|
||||
@@ -5721,6 +6001,8 @@ impl<'a> Lower<'a> {
|
||||
|| used.is_some_and(|u| u.kind == ResourceType::Uav);
|
||||
let u = if uav { 0x1000 } else { 0 };
|
||||
let (props, image) = match &ui.fields {
|
||||
_ if sized.is_some_and(|image| image) => ((2 | u, 0x409), Some(2)),
|
||||
_ if sized.is_some() => ((11 | u, 0), None),
|
||||
// A ray-tracing structure in a buffer of the host: read raw.
|
||||
Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None),
|
||||
Fields::Image { dim, .. } => {
|
||||
@@ -5736,13 +6018,25 @@ impl<'a> Lower<'a> {
|
||||
}
|
||||
Fields::Buffer { idxen, format, .. } => {
|
||||
let stride = used.map_or(0, |u| u.stride);
|
||||
let counted = inst
|
||||
.write(Reg::S(code + first + 2))
|
||||
.is_some_and(|v| self.read_as_number(v));
|
||||
let props = if un.starts_with("buffer_load_format")
|
||||
|| un.starts_with("buffer_store_format")
|
||||
{
|
||||
(10 | u, 0x409)
|
||||
} else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) {
|
||||
} else if !counted
|
||||
&& *idxen
|
||||
&& format.is_none()
|
||||
&& stride >= 4
|
||||
&& stride.is_multiple_of(4)
|
||||
{
|
||||
// Nothing reads the count: the query is cleaned up.
|
||||
(12 | u, stride)
|
||||
} else {
|
||||
// Structured ones too: the host's views of them are raw
|
||||
// (see `buffer`), which count bytes, and a size asked
|
||||
// for as a structured view's is that count on AMD.
|
||||
(11 | u, 0)
|
||||
};
|
||||
if used.is_some_and(|u| u.kind == ResourceType::Cbv) {
|
||||
@@ -5816,9 +6110,20 @@ impl<'a> Lower<'a> {
|
||||
// A raw view counts bytes; the descriptor's record count is in elements.
|
||||
let n = field(self, 0);
|
||||
let stride = used.map_or(0, |u| u.stride);
|
||||
let counted = inst
|
||||
.write(Reg::S(code + first + 2))
|
||||
.is_some_and(|v| self.read_as_number(v));
|
||||
let n = if props.0 & 0xFF == 11 && stride > 1 {
|
||||
let k = self.s.m.i32(stride);
|
||||
self.s.m.bin(c, Bin::UDiv, n, k)
|
||||
} else if props.0 & 0xFF == 11
|
||||
&& counted
|
||||
&& let Some(stride) = self.slot_stride(&src)?
|
||||
{
|
||||
// Picked from the heap: the host's table has the stride.
|
||||
let (i32t, one) = (self.s.t.i32, self.s.m.i32(1));
|
||||
let k = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 39, &[stride, one]);
|
||||
self.s.m.bin(c, Bin::UDiv, n, k)
|
||||
} else {
|
||||
n
|
||||
};
|
||||
@@ -6610,6 +6915,17 @@ impl<'a> Lower<'a> {
|
||||
self.lane(inst, Some(true));
|
||||
return Ok(());
|
||||
}
|
||||
// One lane of a VGPR a whole-wave section left.
|
||||
if name == "v_readlane_b32"
|
||||
&& let Some(&(_, w)) = inst.writes.first()
|
||||
&& let Some(sh) = self.sections.get(&b).and_then(|s| {
|
||||
s.iter().filter(|s| s.1.end < i).find_map(|s| s.1.reads.get(&w).copied())
|
||||
})
|
||||
{
|
||||
let x = self.shape(sh, false)?;
|
||||
self.vals.insert(w, Val::I32(x));
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) {
|
||||
let r = if v.dpp.is_some() {
|
||||
Err("a compare with DPP")
|
||||
@@ -9549,7 +9865,13 @@ impl<'a> Lower<'a> {
|
||||
|| self
|
||||
.used_kind(src)
|
||||
.is_some_and(|u| u.kind == ResourceType::Uav);
|
||||
let props = (kind | if uav { 0x1000 } else { 0 }, 0x409);
|
||||
// A UAV inside an ordered section is a rasterizer ordered view.
|
||||
let ordered = uav && self.ordered.contains(&site);
|
||||
if ordered {
|
||||
self.s.flags |= flags::ROVS;
|
||||
}
|
||||
let rov = if ordered { 0x2000 } else { 0 };
|
||||
let props = (kind | if uav { 0x1000 } else { 0 } | rov, 0x409);
|
||||
if let Some(op) = name.strip_prefix("image_atomic_") {
|
||||
// GLC returns the old value. DXIL implements subtraction by adding
|
||||
// the two's complement of the operand at the same width.
|
||||
@@ -9607,7 +9929,7 @@ impl<'a> Lower<'a> {
|
||||
} else {
|
||||
original
|
||||
};
|
||||
let h = self.handle(site, src, false, (kind | 0x1000, component))?;
|
||||
let h = self.handle(site, src, false, (kind | 0x1000 | rov, component))?;
|
||||
let mut args = vec![h];
|
||||
let (intrinsic, opcode) = if compare {
|
||||
let comparand = if wide {
|
||||
@@ -9660,7 +9982,9 @@ impl<'a> Lower<'a> {
|
||||
}
|
||||
// shortcut: stores are taken to write all four channels of a
|
||||
// float format (the console converts by the view's format).
|
||||
if *dmask != 0xF {
|
||||
// One channel goes into a view the program also counts in.
|
||||
let counter = *dmask == 1 && self.is_counter(src);
|
||||
if *dmask != 0xF && !counter {
|
||||
return Err("an image store of some channels");
|
||||
}
|
||||
let iu = self.s.m.undef(self.s.t.i32);
|
||||
@@ -9671,6 +9995,34 @@ impl<'a> Lower<'a> {
|
||||
let Operand::Vector { reg, .. } = *data else {
|
||||
return Err("image store data");
|
||||
};
|
||||
if counter {
|
||||
let v = inst.read(Reg::V(reg)).ok_or("image store data")?;
|
||||
let x = self.i32_of(v)?;
|
||||
// A 16-bit integer, extended by the view's sign: the same
|
||||
// number either way only if it is known to be small.
|
||||
if *d16 && !self.s.m.int_k(x).is_some_and(|(_, k)| k < 0x8000) {
|
||||
return Err("a 16-bit image store of one channel");
|
||||
}
|
||||
let h = self.handle(site, src, false, (kind | 0x1000 | rov, 0x105))?;
|
||||
let at = self.begin_guarded(guard);
|
||||
// All four channels are written (the validator wants them
|
||||
// all): the view has the first alone.
|
||||
let mut args = vec![h];
|
||||
args.extend(cs);
|
||||
args.extend([x; 4]);
|
||||
args.push(self.s.m.i8(0xF));
|
||||
let void = self.s.t.void;
|
||||
self.s.op(
|
||||
self.cur,
|
||||
"textureStore.i32",
|
||||
Attr::NoUnwind,
|
||||
void,
|
||||
67,
|
||||
&args,
|
||||
);
|
||||
self.end_guarded(at, &[]);
|
||||
return Ok(());
|
||||
}
|
||||
let mut vals = Vec::new();
|
||||
for k in 0..4u8 {
|
||||
// d16: two f16 channels per VGPR, low half first.
|
||||
@@ -10445,7 +10797,10 @@ impl<'a> Lower<'a> {
|
||||
return Ok(());
|
||||
}
|
||||
let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav);
|
||||
let u = if uav { 0x1000 } else { 0 };
|
||||
let mut u = if uav { 0x1000 } else { 0 };
|
||||
if uav && !typed && self.entry(src).is_some_and(|e| self.coherent.contains(&e)) {
|
||||
u |= 0x4000;
|
||||
}
|
||||
let iu = self.s.m.undef(self.s.t.i32);
|
||||
if let Some((bits, signed)) = narrow {
|
||||
// Below a dword: raw buffers are read and written in dwords on
|
||||
|
||||
@@ -99,6 +99,8 @@ mod threading;
|
||||
#[cfg(windows)]
|
||||
pub mod validator;
|
||||
#[cfg(all(test, windows))]
|
||||
mod size_tests;
|
||||
#[cfg(all(test, windows))]
|
||||
mod valu_tests;
|
||||
#[cfg(all(test, windows))]
|
||||
mod waterfall_tests;
|
||||
@@ -859,6 +861,134 @@ mod tests {
|
||||
assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef");
|
||||
}
|
||||
|
||||
/// A pixel program with an ordered section, as the console compiler
|
||||
/// makes one of rasterizer ordered views (the title's hair cards keep
|
||||
/// their nearest layers that way): the wait for overlapped waves is
|
||||
/// skipped, the views inside the section are the host's ordered ones,
|
||||
/// the one after it is not.
|
||||
#[test]
|
||||
fn an_ordered_section_uses_rasterizer_ordered_views() {
|
||||
let section = [
|
||||
0xBE82_0300u32, // s_mov_b32 s2, s0
|
||||
0xBE83_0380, // s_mov_b32 s3, 0
|
||||
0xF40C_0201, // s_load_dwordx8 s[8:15], s[2:3], 0
|
||||
0xFA00_0000,
|
||||
0x9390_FF01, // s_bfe_u32 s16, s1, 0x2001c
|
||||
0x0002_001C,
|
||||
0x9391_FF01, // s_bfe_u32 s17, s1, 0xa0000
|
||||
0x000A_0000,
|
||||
0x8F10_8110, // s_lshl_b32 s16, s16, 1
|
||||
0x9392_FF01, // s_bfe_u32 s18, s1, 0xa0010
|
||||
0x000A_0010,
|
||||
0xBE91_0711, // s_not_b32 s17, s17
|
||||
0x9013_9F01, // s_lshr_b32 s19, s1, 31
|
||||
0x8810_8110, // s_or_b32 s16, s16, 1
|
||||
0x8112_1112, // s_add_i32 s18, s18, s17
|
||||
0xBF06_8013, // s_cmp_eq_u32 s19, 0
|
||||
0xB990_1019, // s_setreg_b32 hwreg(HW_REG_POPS_PACKER, 0, 3), s16
|
||||
0x8514_807E, // s_cselect_b32 s20, exec_lo, 0
|
||||
0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17
|
||||
0xBF08_1215, // s_cmp_gt_u32 s21, s18
|
||||
0x8516_807E, // s_cselect_b32 s22, exec_lo, 0
|
||||
0x8814_1614, // s_or_b32 s20, s20, s22
|
||||
0x876A_147E, // s_and_b32 vcc_lo, exec_lo, s20
|
||||
0xBF87_0004, // s_cbranch_vccnz past the wait
|
||||
0xBF8E_FFFF, // s_sleep 0xffff
|
||||
0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17
|
||||
0xBF0A_1512, // s_cmp_lt_u32 s18, s21
|
||||
0xBF84_FFFC, // s_cbranch_scc0 back to the sleep
|
||||
0x7E00_0280, // v_mov_b32 v0, 0
|
||||
0x7E02_0280, // v_mov_b32 v1, 0
|
||||
0xF000_3F88, // image_load v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc dlc
|
||||
0x0002_0200,
|
||||
0x0604_04F2, // v_add_f32 v2, 1.0, v2
|
||||
0xF020_3F08, // image_store v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc
|
||||
0x0002_0200,
|
||||
0xBEFC_0380, // s_mov_b32 m0, 0
|
||||
0xBF90_0007, // s_sendmsg sendmsg(MSG_ORDERED_PS_DONE)
|
||||
];
|
||||
let end = [
|
||||
0xF800_180Fu32, // exp mrt0 v2, v2, v2, v2 done vm
|
||||
0x0202_0202,
|
||||
0xBF81_0000, // s_endpgm
|
||||
];
|
||||
// A store after the section, through an ordinary view.
|
||||
let after = [0xF020_3F08u32, 0x0002_0200];
|
||||
let lower = |words: Vec<u32>| {
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Ps,
|
||||
wave64: false,
|
||||
vgprs: 8,
|
||||
layout: vec![crate::native::RootParam {
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
}],
|
||||
used: vec![crate::native::UsedResource {
|
||||
kind: crate::native::ResourceType::Uav,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords: 0,
|
||||
lower_bound: 0,
|
||||
stride: 4,
|
||||
dwords: 8,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
}],
|
||||
io: StageIo::Ps {
|
||||
inputs: vec![],
|
||||
input_addr: 0,
|
||||
db_shader_control: 0,
|
||||
patches: vec![],
|
||||
},
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let target = SigElement {
|
||||
name: "SV_Target".into(),
|
||||
index: 0,
|
||||
kind: 16,
|
||||
comp: 9,
|
||||
interp: 0,
|
||||
row: Some(0),
|
||||
col: 0,
|
||||
cols: 4,
|
||||
usage: 15,
|
||||
half: false,
|
||||
};
|
||||
let osg1 = container::signature(&[target], false);
|
||||
let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]);
|
||||
let c = Container::parse(&bytes).unwrap();
|
||||
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
|
||||
let st = structure::structure(&p)?;
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
|
||||
let io = io::raise(&p, &native)?;
|
||||
let out = emit(&c, &native, &p, &st, &io, &res)?;
|
||||
#[cfg(windows)]
|
||||
if let Ok(mut v) = super::validator::Validator::load(
|
||||
super::validator::Validator::default_path().as_deref(),
|
||||
) {
|
||||
v.validate(&mut out.dxil.clone()).unwrap();
|
||||
}
|
||||
let host = Container::parse(&out.dxil).unwrap();
|
||||
let sfi0 = host.part(FourCC::SFI0).unwrap().data;
|
||||
Ok::<u64, ShaderError>(u64::from_le_bytes(sfi0.try_into().unwrap()))
|
||||
};
|
||||
// D3D_SHADER_REQUIRES_ROVS
|
||||
let features = lower([§ion[..], &end].concat()).unwrap();
|
||||
assert_ne!(features & 0x1000, 0, "SFI0 {features:#x}: no ROVs");
|
||||
lower([§ion[..], &after, &end].concat()).unwrap();
|
||||
// The same accesses outside a section: ordinary views, no feature.
|
||||
let plain = [§ion[..4], §ion[28..35], &end].concat();
|
||||
let features = lower(plain).unwrap();
|
||||
assert_eq!(features & 0x1000, 0, "SFI0 {features:#x}: ROVs");
|
||||
// Without the section's start the wait stays unknown.
|
||||
let mut unmarked = [§ion[..], &end].concat();
|
||||
unmarked.remove(16);
|
||||
assert!(lower(unmarked).is_err());
|
||||
}
|
||||
|
||||
/// A wave64 compute program that writes only EXEC's high dword
|
||||
/// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was
|
||||
/// opaque and keyed by the unchanged low dword, so building its lane bit
|
||||
|
||||
@@ -76,6 +76,7 @@ pub(crate) mod flags {
|
||||
pub const DOUBLES: u64 = 1 << 2;
|
||||
pub const STENCIL_REF: u64 = 1 << 11;
|
||||
pub const TYPED_UAV_LOADS: u64 = 1 << 13;
|
||||
pub const ROVS: u64 = 1 << 18;
|
||||
pub const WAVE_OPS: u64 = 1 << 19;
|
||||
pub const BARYCENTRICS: u64 = 1 << 22;
|
||||
pub const INT64: u64 = 1 << 20;
|
||||
@@ -455,6 +456,7 @@ impl Shader {
|
||||
self.m.optimise(passes);
|
||||
let used = self.m.usage();
|
||||
for (flag, used) in [
|
||||
(flags::ROVS, used.rovs),
|
||||
(flags::WAVE_OPS, used.wave_ops),
|
||||
(flags::INT64, used.int64),
|
||||
(flags::TYPED_UAV_LOADS, used.typed_uav_loads),
|
||||
@@ -787,6 +789,9 @@ impl Shader {
|
||||
if self.flags & flags::TYPED_UAV_LOADS != 0 {
|
||||
features |= 0x800;
|
||||
}
|
||||
if self.flags & flags::ROVS != 0 {
|
||||
features |= 0x1000;
|
||||
}
|
||||
if self.flags & flags::WAVE_OPS != 0 {
|
||||
features |= 0x4000;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
//! End-to-end tests of what a program tells about a view by how it uses it:
|
||||
//! descriptors read for sizes (the dwords of a view no instruction uses) and
|
||||
//! counters, lowered to DXIL, validated by `dxil.dll` when present, and run
|
||||
//! on the host GPU and WARP.
|
||||
|
||||
use super::host::{Stride, View};
|
||||
use super::waterfall_tests::run;
|
||||
use super::{HostShader, lower, validator};
|
||||
use crate::native::{
|
||||
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
|
||||
};
|
||||
use crate::{ShaderError, io, ir, resource, structure};
|
||||
|
||||
/// Lowers a wave32 compute program of one thread with the table of views at
|
||||
/// s0 and the view heap at s1; `srv`: the dwords and the stride of the used
|
||||
/// resource at the table's first entry (the third is a raw UAV).
|
||||
fn build(words: &[u32], srv: (u8, u32)) -> Result<HostShader, ShaderError> {
|
||||
let param = |root, user_data| RootParam {
|
||||
root,
|
||||
table_offset_dwords: 0,
|
||||
sgprs: 1,
|
||||
base_register: 0,
|
||||
user_data,
|
||||
slot: 0,
|
||||
};
|
||||
let range = |kind, table_offset_dwords, dwords, stride| UsedResource {
|
||||
kind,
|
||||
root: RootType::Table,
|
||||
table_offset_dwords,
|
||||
lower_bound: 0,
|
||||
stride,
|
||||
dwords,
|
||||
user_data: 0,
|
||||
slot: 0,
|
||||
};
|
||||
let native = NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64: false,
|
||||
vgprs: 32,
|
||||
layout: vec![param(RootType::Table, 0), param(RootType::ResourceHeap, 1)],
|
||||
used: vec![
|
||||
range(ResourceType::Srv, 0, srv.0, srv.1),
|
||||
range(ResourceType::Uav, 16, 4, 0),
|
||||
],
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: 2 << 1,
|
||||
threads: [1, 1, 1],
|
||||
}),
|
||||
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
|
||||
};
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs)?;
|
||||
let st = structure::structure(&p)?;
|
||||
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
|
||||
let io = io::raise(&p, &native)?;
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native: &native,
|
||||
p: &p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
})?;
|
||||
let shader = HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: Vec::new(),
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
v.validate(&mut shader.dxil.clone())
|
||||
.expect("DXIL validation failed");
|
||||
} else {
|
||||
eprintln!("no dxil.dll; validation skipped");
|
||||
}
|
||||
Ok(shader)
|
||||
}
|
||||
|
||||
/// The table at s[2:3], its raw UAV's descriptor in s[20:23].
|
||||
const TABLE: &[u32] = &[
|
||||
0xBE82_0300, // s_mov_b32 s2, s0
|
||||
0xBE83_0380, // s_mov_b32 s3, 0
|
||||
0xF408_0501, // s_load_dwordx4 s[20:23], s[2:3], 64
|
||||
0xFA00_0040,
|
||||
];
|
||||
|
||||
/// Stores s4 and s5 at bytes 0 and 4 of the UAV.
|
||||
const STORE: &[u32] = &[
|
||||
0x7E08_0204, // v_mov_b32 v4, s4
|
||||
0x7E0A_0205, // v_mov_b32 v5, s5
|
||||
0xE070_0000, // buffer_store_dword v4, off, s[20:23], 0
|
||||
0x8005_0400,
|
||||
0xE070_0004, // buffer_store_dword v5, off, s[20:23], 0 offset:4
|
||||
0x8005_0500,
|
||||
0xBF81_0000, // s_endpgm
|
||||
];
|
||||
|
||||
/// `GetDimensions` of a texture as the console compiler expands it, from
|
||||
/// the descriptor in s[8:15]: width in s4, height in s5, base level in s6.
|
||||
const SIZES: &[u32] = &[
|
||||
0x9004_9E09, // s_lshr_b32 s4, s9, 30
|
||||
0x8F05_820A, // s_lshl_b32 s5, s10, 2
|
||||
0x8804_0504, // s_or_b32 s4, s4, s5
|
||||
0x8704_FF04, // s_and_b32 s4, s4, 0xffff
|
||||
0x0000_FFFF,
|
||||
0x9385_FF0A, // s_bfe_u32 s5, s10, 0x10000e
|
||||
0x0010_000E,
|
||||
0x9386_FF0B, // s_bfe_u32 s6, s11, 0x4000c
|
||||
0x0004_000C,
|
||||
0x8104_8104, // s_add_i32 s4, s4, 1
|
||||
0x8105_8105, // s_add_i32 s5, s5, 1
|
||||
0x9004_0604, // s_lshr_b32 s4, s4, s6
|
||||
0x9005_0605, // s_lshr_b32 s5, s5, s6
|
||||
];
|
||||
|
||||
/// s_load_dwordx8 s[8:15], s[6:7], s12: entry 1 of the view heap.
|
||||
const FROM_HEAP: &[u32] = &[
|
||||
0xBE86_0301, // s_mov_b32 s6, s1
|
||||
0xBE87_0380, // s_mov_b32 s7, 0
|
||||
0xBE8C_03A0, // s_mov_b32 s12, 32
|
||||
0xF40C_0203,
|
||||
0x1800_0000,
|
||||
];
|
||||
|
||||
/// `s_load_dwordx4 s[8:11], s[2:3], 0`, then the record count in s4 and 0
|
||||
/// in s5.
|
||||
const COUNT: &[u32] = &[
|
||||
0xF408_0201,
|
||||
0xFA00_0000,
|
||||
0xBE84_030A, // s_mov_b32 s4, s10
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
];
|
||||
|
||||
/// A puddle pass of the title picks three textures from the view heap,
|
||||
/// reads the first one's size and samples the other two.
|
||||
#[test]
|
||||
fn the_size_of_a_heap_texture_nothing_reads() {
|
||||
let words = [TABLE, FROM_HEAP, SIZES, STORE].concat();
|
||||
let shader = build(&words, (8, 0)).expect("translates");
|
||||
let (one, texels) = ([[0.0; 4]; 1], [[0.0; 4]; 15]);
|
||||
let views = [
|
||||
View::Texture(1, 1, &one),
|
||||
View::Texture(5, 3, &texels),
|
||||
View::RawUav(2),
|
||||
];
|
||||
for (label, got) in run(&shader, &views) {
|
||||
assert_eq!(got[..2], [5, 3], "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Without the height nothing tells a 2D texture from the others, and a
|
||||
/// volume's depth or an array's layers are no 2D texture's.
|
||||
#[test]
|
||||
fn sizes_of_unknown_dimensions_stay_untranslated() {
|
||||
let width = [
|
||||
0x9004_9E09, // s_lshr_b32 s4, s9, 30
|
||||
0x8F05_820A, // s_lshl_b32 s5, s10, 2
|
||||
0x8804_0504, // s_or_b32 s4, s4, s5
|
||||
];
|
||||
let words = [TABLE, FROM_HEAP, &width, STORE].concat();
|
||||
assert!(build(&words, (8, 0)).is_err());
|
||||
let depth = [
|
||||
0x8805_0C05, // s_or_b32 s5, s5, s12
|
||||
];
|
||||
let words = [TABLE, FROM_HEAP, SIZES, &depth, STORE].concat();
|
||||
assert!(build(&words, (8, 0)).is_err());
|
||||
}
|
||||
|
||||
/// A water simulation step runs only while a structured buffer is bound:
|
||||
/// it tests the record count of a view it never reads.
|
||||
#[test]
|
||||
fn the_record_count_of_a_structured_buffer_nothing_reads() {
|
||||
let words = [TABLE, COUNT, STORE].concat();
|
||||
let shader = build(&words, (4, 16)).expect("translates");
|
||||
let (data, texel) = ([0u32; 12], [[0.0; 4]; 1]);
|
||||
// The runtime makes structured views raw.
|
||||
let views = [
|
||||
View::Buffer {
|
||||
data: &data,
|
||||
stride: Stride::Raw,
|
||||
},
|
||||
View::Texture(1, 1, &texel),
|
||||
View::RawUav(2),
|
||||
];
|
||||
for (label, got) in run(&shader, &views) {
|
||||
assert_eq!(got[..2], [3, 0], "{label}");
|
||||
}
|
||||
// A stride of 4 or less may be a typed view's component count.
|
||||
assert!(build(&words, (4, 4)).is_err());
|
||||
assert!(build(&words, (4, 0)).is_err());
|
||||
}
|
||||
|
||||
/// As [`the_record_count_of_a_structured_buffer_nothing_reads`], of one the
|
||||
/// program also reads by index.
|
||||
#[test]
|
||||
fn the_record_count_of_a_structured_buffer_read_by_index() {
|
||||
let load = [
|
||||
0x7E06_0280, // v_mov_b32 v3, 0
|
||||
0xE030_2000, // buffer_load_dword v5, v3, s[8:11], 0 idxen
|
||||
0x8002_0503,
|
||||
0x7E0A_0505, // v_readfirstlane_b32 s5, v5
|
||||
];
|
||||
let words = [TABLE, COUNT, &load, STORE].concat();
|
||||
let shader = build(&words, (4, 16)).expect("translates");
|
||||
let (mut data, texel) = ([0u32; 12], [[0.0; 4]; 1]);
|
||||
data[0] = 77;
|
||||
let views = [
|
||||
View::Buffer {
|
||||
data: &data,
|
||||
stride: Stride::Raw,
|
||||
},
|
||||
View::Texture(1, 1, &texel),
|
||||
View::RawUav(2),
|
||||
];
|
||||
for (label, got) in run(&shader, &views) {
|
||||
assert_eq!(got[..2], [3, 77], "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An upscaler counts its groups in a texture with atomics and sets the
|
||||
/// counter back with a store of one channel, 16 bits wide.
|
||||
#[test]
|
||||
fn a_counter_texture_is_set_by_a_store_of_one_channel() {
|
||||
let program = |store: [u32; 2], value: u32| {
|
||||
let words = [
|
||||
0xF40C_0201u32, // s_load_dwordx8 s[8:15], s[2:3], 0
|
||||
0xFA00_0000,
|
||||
0x7E00_0280, // v_mov_b32 v0, 0
|
||||
0x7E02_0280, // v_mov_b32 v1, 0
|
||||
0x7E04_0283, // v_mov_b32 v2, 3
|
||||
0xF044_3108, // image_atomic_add v2, v[0:1], s[8:15] dmask:0x1 2D glc
|
||||
0x0002_0200,
|
||||
value, // v_mov_b32 v3, ..
|
||||
store[0],
|
||||
store[1],
|
||||
0x7E08_0281, // v_mov_b32 v4, 1
|
||||
0xF044_3108, // image_atomic_add v4, v[0:1], s[8:15] dmask:0x1 2D glc
|
||||
0x0002_0400,
|
||||
0xBE84_0380, // s_mov_b32 s4, 0
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
];
|
||||
build(&[TABLE, &words, STORE].concat(), (8, 0))
|
||||
};
|
||||
// image_store v3, v[0:1], s[8:15] dmask:0x1 2D, with and without d16
|
||||
for store in [[0xF020_1108, 0x0002_0300], [0xF020_1108, 0x8002_0300]] {
|
||||
let shader = program(store, 0x7E06_0289).expect("translates"); // v3 = 9
|
||||
let texel = [[0.0; 4]; 1];
|
||||
let views = [
|
||||
View::UintTextureUav(1, 1),
|
||||
View::Texture(1, 1, &texel),
|
||||
View::RawUav(2),
|
||||
];
|
||||
for (label, got) in run(&shader, &views) {
|
||||
assert_eq!(got[0], 10, "{label}");
|
||||
}
|
||||
}
|
||||
// Sixteen bits of a number only the card knows may be signed.
|
||||
assert!(program([0xF020_1108, 0x8002_0300], 0x7E06_0302).is_err()); // v3 = v2
|
||||
// A store of two channels says nothing about the view.
|
||||
assert!(program([0xF020_1308, 0x0002_0300], 0x7E06_0289).is_err());
|
||||
}
|
||||
|
||||
/// A load past the wave's cache (GLC) of a buffer other groups write: its
|
||||
/// view is globally coherent on the host, as is every access to it.
|
||||
#[test]
|
||||
fn a_buffer_loaded_past_the_cache_is_coherent() {
|
||||
let program = |load: u32| {
|
||||
let words = [
|
||||
0x7E04_028Bu32, // v_mov_b32 v2, 11
|
||||
0xE070_0008, // buffer_store_dword v2, off, s[20:23], 0 offset:8
|
||||
0x8005_0200,
|
||||
load, // buffer_load_dword v3, off, s[20:23], 0 offset:8
|
||||
0x8005_0300,
|
||||
0x7E08_0503, // v_readfirstlane_b32 s4, v3
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
];
|
||||
build(&[TABLE, &words, STORE].concat(), (8, 0)).expect("translates")
|
||||
};
|
||||
let (plain, coherent) = (program(0xE030_0008), program(0xE030_C008));
|
||||
// the annotations of the store's and the load's handles
|
||||
assert_ne!(plain.dxil, coherent.dxil);
|
||||
let texel = [[0.0; 4]; 1];
|
||||
let views = [
|
||||
View::Texture(1, 1, &texel),
|
||||
View::Texture(1, 1, &texel),
|
||||
View::RawUav(3),
|
||||
];
|
||||
for shader in [&plain, &coherent] {
|
||||
for (label, got) in run(shader, &views) {
|
||||
assert_eq!(got[..3], [11, 0, 11], "{label}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader {
|
||||
/// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the
|
||||
/// hardware GPU and on WARP (each skipped without a device) and returns,
|
||||
/// per one that ran, the UAV's 32 dwords.
|
||||
fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec<u32>)> {
|
||||
pub(super) fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec<u32>)> {
|
||||
let samplers = [D3D12_SAMPLER_DESC {
|
||||
Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
|
||||
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
|
||||
@@ -143,6 +143,10 @@ pub(crate) enum Shape {
|
||||
pub(crate) struct Section {
|
||||
pub end: usize,
|
||||
pub shapes: HashMap<Value, Shape>,
|
||||
/// What a `v_readlane_b32` of one lane takes, later in the block, from a
|
||||
/// VGPR the section leaves (by the scalar it writes): the last lanes of
|
||||
/// a reduction hold it before the first do.
|
||||
pub reads: HashMap<Value, Shape>,
|
||||
}
|
||||
|
||||
/// Every whole-wave section of `block`, by start index.
|
||||
@@ -180,8 +184,25 @@ pub(crate) fn sections(p: &Program, block: usize) -> HashMap<usize, Section> {
|
||||
let Some(end) = end else {
|
||||
break;
|
||||
};
|
||||
let shapes = simulate(&insts[i + 1..end], wave, saved);
|
||||
out.insert(i, Section { end, shapes });
|
||||
let (vec, uni) = simulate(&insts[i + 1..end], wave, saved);
|
||||
let mut reads = HashMap::new();
|
||||
for later in insts[end + 1..].iter().filter(|i| i.name() == "v_readlane_b32") {
|
||||
if let Fields::Valu(v) = &later.fields
|
||||
&& let (Some(Operand::Scalar { code, .. }), [Operand::Vector { reg, .. }, lane]) =
|
||||
(v.dst, &v.src[..])
|
||||
&& let Some(left) = later.read(Reg::V(*reg)).and_then(|x| vec.get(&x))
|
||||
&& let Some(w) = later.write(Reg::S(code))
|
||||
&& let Some(l) = lane_number(lane)
|
||||
&& let Some(&sym) = left.get(l as usize)
|
||||
// (a lane's own value stays a lane read)
|
||||
&& !matches!(sym, Sym::Own(_))
|
||||
&& let Some(shape) = single(sym, wave)
|
||||
{
|
||||
reads.insert(w, shape);
|
||||
}
|
||||
}
|
||||
let shapes = shapes(vec, uni, wave);
|
||||
out.insert(i, Section { end, shapes, reads });
|
||||
i = end + 1;
|
||||
}
|
||||
out
|
||||
@@ -268,7 +289,19 @@ fn combine(op: Op, a: Sym, b: Sym) -> Sym {
|
||||
}
|
||||
}
|
||||
|
||||
fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
/// The lane a `v_readlane_b32` names.
|
||||
fn lane_number(op: &Operand) -> Option<u32> {
|
||||
match *op {
|
||||
Operand::Const(c) => crate::resource::inline(c),
|
||||
Operand::Literal(x) => Some(x),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The lanes' values of the VGPRs the section writes, and its scalars.
|
||||
type Left = (HashMap<Value, Vec<Sym>>, HashMap<Value, Sym>);
|
||||
|
||||
fn simulate(insts: &[Inst], wave: u32, saved: Value) -> Left {
|
||||
let all = if wave == 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
@@ -289,7 +322,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
.then(|| constant(inst))
|
||||
.flatten();
|
||||
let Some(k) = lo else {
|
||||
return shapes(vec, uni, wave);
|
||||
return (vec, uni);
|
||||
};
|
||||
exec = (if name == "s_mov_b64" {
|
||||
k
|
||||
@@ -304,7 +337,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
.then(|| constant(inst))
|
||||
.flatten()
|
||||
else {
|
||||
return shapes(vec, uni, wave);
|
||||
return (vec, uni);
|
||||
};
|
||||
exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all;
|
||||
continue;
|
||||
@@ -371,11 +404,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let l = match *lane {
|
||||
Operand::Const(c) => crate::resource::inline(c),
|
||||
Operand::Literal(x) => Some(x),
|
||||
_ => None,
|
||||
};
|
||||
let l = lane_number(lane);
|
||||
let x = lanes(src, &vec, &uni);
|
||||
if let Some(w) = inst.write(Reg::S(code)) {
|
||||
let s = l
|
||||
@@ -664,7 +693,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> {
|
||||
.collect();
|
||||
vec.insert(dst, merged);
|
||||
}
|
||||
shapes(vec, uni, wave)
|
||||
(vec, uni)
|
||||
}
|
||||
|
||||
fn constant(inst: &Inst) -> Option<u64> {
|
||||
@@ -688,19 +717,10 @@ fn constant(inst: &Inst) -> Option<u64> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape of each value, where every lane agrees on one.
|
||||
fn shapes(
|
||||
vec: HashMap<Value, Vec<Sym>>,
|
||||
uni: HashMap<Value, Sym>,
|
||||
wave: u32,
|
||||
) -> HashMap<Value, Shape> {
|
||||
let all = if wave == 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
u64::from(u32::MAX)
|
||||
};
|
||||
let mut out = HashMap::new();
|
||||
let single = |s: Sym| match s {
|
||||
/// The shape of a scalar.
|
||||
fn single(s: Sym, wave: u32) -> Option<Shape> {
|
||||
let all = u64::MAX >> (64 - wave);
|
||||
match s {
|
||||
Sym::K(k) => Some(Shape::K(k)),
|
||||
Sym::Own(x) | Sym::Uni(x) => Some(Shape::Value(x)),
|
||||
Sym::Red {
|
||||
@@ -718,9 +738,19 @@ fn shapes(
|
||||
high,
|
||||
} if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape of each value, where every lane agrees on one.
|
||||
fn shapes(
|
||||
vec: HashMap<Value, Vec<Sym>>,
|
||||
uni: HashMap<Value, Sym>,
|
||||
wave: u32,
|
||||
) -> HashMap<Value, Shape> {
|
||||
let all = u64::MAX >> (64 - wave);
|
||||
let mut out = HashMap::new();
|
||||
for (v, s) in uni {
|
||||
if let Some(sh) = single(s) {
|
||||
if let Some(sh) = single(s, wave) {
|
||||
out.insert(v, sh);
|
||||
}
|
||||
}
|
||||
@@ -1074,6 +1104,40 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A wave OR whose last step stays in the section's VGPR: the lower
|
||||
/// lanes add the first half's to themselves, so only the upper ones
|
||||
/// hold the whole, and the last lane is read after the section (an
|
||||
/// upscaler's programs).
|
||||
#[test]
|
||||
fn one_lane_of_what_a_section_leaves_is_read_after_it() {
|
||||
let words = |lane: u32| {
|
||||
let mut w = WAVE_OR_V7_TO_S7[..14].to_vec(); // .. v_or_b32 v1, v2, v1
|
||||
w.extend([
|
||||
0xD760_0007,
|
||||
0x0001_0101, // v_readlane_b32 s7, v1, 0
|
||||
0x3802_0207, // v_or_b32 v1, s7, v1
|
||||
0xBEFE_0404, // s_mov_b64 exec, s[4:5]
|
||||
0xD760_0006,
|
||||
0x0001_0101 | lane << 9, // v_readlane_b32 s6, v1, lane
|
||||
S_ENDPGM,
|
||||
]);
|
||||
w
|
||||
};
|
||||
let read = |lane: u32| {
|
||||
let p = build(&words(lane), true);
|
||||
let insts = &p.blocks[0].insts;
|
||||
let saved = insts[0].write(Reg::S(4)).unwrap();
|
||||
let v7 = p.inputs.iter().find_map(|&(r, v)| (r == Reg::V(7)).then_some(v)).unwrap();
|
||||
let got = insts[insts.len() - 2].write(Reg::S(6)).unwrap();
|
||||
let sec = §ions(&p, 0)[&0];
|
||||
(sec.reads.get(&got).copied(), Shape::Active(Op::Or, v7, saved, 0))
|
||||
};
|
||||
let (found, whole) = read(63);
|
||||
assert_eq!(found, Some(whole));
|
||||
// Lane 0 has the first half's alone: still a lane read.
|
||||
assert_eq!(read(0).0, None);
|
||||
}
|
||||
|
||||
/// `WaveActiveSum` of 16-bit floats, as compiled in
|
||||
/// `compute_graph_ops:CS_TransposeVecMatMulAlignedOperation` (0x19c on): the tree the
|
||||
/// lowering reproduces. A tree in another order is not followed.
|
||||
|
||||
@@ -199,6 +199,162 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() {
|
||||
eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]);
|
||||
}
|
||||
|
||||
/// "Some lane is left" of a mask operation as a number: an upscaler's programs wait for
|
||||
/// other groups in a loop that ends when every lane saw its flag, or after enough rounds:
|
||||
/// both tests become -1 or 0 and SCC of `timeout | ~waiting` ends it.
|
||||
#[test]
|
||||
fn some_lane_of_a_mask_is_a_number_the_whole_wave_agrees_on() {
|
||||
let native = native(&[
|
||||
0xD765_0001,
|
||||
0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0
|
||||
0xD766_0001,
|
||||
0x0002_02C1, // v_mbcnt_hi_u32_b32 v1, -1, v1
|
||||
0x7D84_0200, // v_cmp_eq_u32 vcc, s0, v1
|
||||
0x8792_7E6A, // s_and_b64 s[18:19], vcc, exec
|
||||
0x8592_80C1, // s_cselect_b64 s[18:19], -1, 0
|
||||
0xBF09_8501, // s_cmp_ge_u32 s1, 5
|
||||
0x8594_80C1, // s_cselect_b64 s[20:21], -1, 0
|
||||
0x8B92_1214, // s_orn2_b64 s[18:19], s[20:21], s[18:19]
|
||||
0x8506_8081, // s_cselect_b32 s6, 1, 0
|
||||
0x7E04_0206, // v_mov_b32 v2, s6
|
||||
0xE070_0000,
|
||||
0x8002_0200, // buffer_store_dword v2, off, s[8:11], 0
|
||||
]);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let shader = on_64_lanes(&native, &p);
|
||||
// (lane s0 waits, if there is one; s1 rounds)
|
||||
for (wait, rounds, done) in [(0, 0, 0), (37, 4, 0), (63, 4, 0), (64, 0, 1), (37, 5, 1), (64, 9, 1)] {
|
||||
let Some(out) = dispatched(&shader, &[wait, rounds]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(out, done, "lane {wait} after {rounds} rounds");
|
||||
}
|
||||
}
|
||||
|
||||
/// `native` for a host of 64-lane waves.
|
||||
fn on_64_lanes(native: &NativeProgram, p: &ir::Program) -> HostShader {
|
||||
let st = structure::structure(p).expect("structure");
|
||||
let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track");
|
||||
let io = io::raise(p, native).expect("io::raise");
|
||||
let was = lower::TEST_HOST_WAVE.replace(Some(64));
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native,
|
||||
p,
|
||||
st: &st,
|
||||
io: &io,
|
||||
res: &res,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
prims: Vec::new(),
|
||||
mesh_stride: 0,
|
||||
});
|
||||
lower::TEST_HOST_WAVE.set(was);
|
||||
let lowered = lowered.expect("lower");
|
||||
assert_eq!(lowered.wave_size, Some(64));
|
||||
let shader = HostShader {
|
||||
stage: HwStage::Cs,
|
||||
dxil: lowered.dxil,
|
||||
user_data: lowered.user_data,
|
||||
samplers: lowered.samplers,
|
||||
static_samplers: Vec::new(),
|
||||
root_cbvs: lowered.root_cbvs,
|
||||
root_srvs: lowered.root_srvs,
|
||||
root_uavs: lowered.root_uavs,
|
||||
root_indexed_views: res.root_indexed_views,
|
||||
};
|
||||
if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
|
||||
let mut copy = shader.dxil.clone();
|
||||
v.validate(&mut copy).expect("DXIL validation failed");
|
||||
}
|
||||
shader
|
||||
}
|
||||
|
||||
/// Dword 0 of the UAV after `shader` ran with root constants `constants`; none without a
|
||||
/// device that takes it.
|
||||
fn dispatched(shader: &HostShader, constants: &[u32]) -> Option<u32> {
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Ok(host) = Host::new(false) else {
|
||||
eprintln!("no SM 6.6 hardware device; not run");
|
||||
return None;
|
||||
};
|
||||
let (root, pso) = match host.compute_pipeline(shader) {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
eprintln!("the hardware device does not take this program (waves of 64?): {e}; not run");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
|
||||
for u in &shader.user_data {
|
||||
if u.root == RootType::Constants {
|
||||
ud[u.index as usize] = constants.get(u.dword as usize).copied().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
let out = host
|
||||
.dispatch(
|
||||
&root,
|
||||
&pso,
|
||||
&Dispatch {
|
||||
roots: vec![(0, Root::Constants(ud))],
|
||||
views: &[View::RawUav(1)],
|
||||
samplers: &[],
|
||||
groups: [1, 1, 1],
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
|
||||
Some(out[0][0])
|
||||
}
|
||||
|
||||
/// The same sum inside `if (t >= s0) { ... }` on a host of 64-lane waves: the lanes below s0
|
||||
/// are elsewhere, and count as +0 in the console's tree.
|
||||
#[test]
|
||||
fn a_sum_of_halves_where_not_every_lane_runs_on_a_wave_of_64() {
|
||||
let mut words = vec![
|
||||
0x340C_0085, // v_lshlrev_b32 v6, 5, v0
|
||||
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
|
||||
0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7
|
||||
0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7
|
||||
0x4A0E_0EFF,
|
||||
0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7
|
||||
0x7D86_0000, // v_cmp_le_u32 vcc, s0, v0
|
||||
0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc
|
||||
0xBF88_0000 | 23, // s_cbranch_execz to the restore of EXEC
|
||||
];
|
||||
words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w }));
|
||||
words.extend_from_slice(&[
|
||||
0x7E00_0207, // v_mov_b32 v0, s7
|
||||
0x38 << 26 | 0x1C << 18,
|
||||
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
|
||||
0xBEFE_040C, // s_mov_b64 exec, s[12:13]
|
||||
]);
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let shader = on_64_lanes(&native, &p);
|
||||
let wide = |h: u16| match h {
|
||||
0 => 0.0,
|
||||
h => f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13),
|
||||
};
|
||||
let narrow = |f: f32| {
|
||||
if f == 0.0 {
|
||||
return 0;
|
||||
}
|
||||
let b = f.to_bits();
|
||||
let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF);
|
||||
let rest = b & 0x1FFF;
|
||||
(h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16
|
||||
};
|
||||
for from in [0u32, 1, 5, 31, 32, 37, 63] {
|
||||
let mut tree: Vec<u16> = (0..64u16).map(|t| if u32::from(t) < from { 0 } else { 0x3C00 + 37 * t }).collect();
|
||||
while tree.len() > 1 {
|
||||
tree = tree.chunks(2).map(|c| narrow(wide(c[0]) + wide(c[1]))).collect();
|
||||
}
|
||||
let Some(out) = dispatched(&shader, &[from]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(out, u32::from(tree[0]), "lanes from {from}");
|
||||
}
|
||||
}
|
||||
|
||||
/// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2
|
||||
/// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The
|
||||
/// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the
|
||||
|
||||
+193
-57
@@ -15,6 +15,8 @@
|
||||
//! operand's whole possible range: from the encoded register up to the
|
||||
//! program's VGPR count, all read (and all written, for a destination).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::ShaderError;
|
||||
use crate::gfx10::{self, Fields, Flow, Instruction, Operand};
|
||||
|
||||
@@ -149,7 +151,7 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
|
||||
}
|
||||
leaders.sort_unstable();
|
||||
leaders.dedup();
|
||||
let parked = unspill(&mut list, &leaders, wave64, lanes, vgprs);
|
||||
let parked = unspill(&mut list, &flows, &leaders, wave64, lanes, vgprs);
|
||||
let block_at = |offset: usize| {
|
||||
leaders
|
||||
.binary_search(&offset)
|
||||
@@ -242,12 +244,21 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result<Program, ShaderErr
|
||||
/// is left of a cross-lane operation, which a console wave run as two host
|
||||
/// waves could not do where not every lane runs (the lane may be in the other
|
||||
/// wave, or not running).
|
||||
/// A VGPR of other uses is such a store too from its first save on, when every
|
||||
/// use from there is one of the two forms, in one block, and saves a lane
|
||||
/// before it restores it (a register free again after a wave reduction).
|
||||
/// A register pair parked in two neighbouring lanes (a lane mask, a 64-bit
|
||||
/// address) moves as a pair (`s_mov_b64`) when every save and every restore
|
||||
/// of the two lanes come together, so a parked lane mask comes back as the
|
||||
/// mask it is; otherwise its halves come back as two scalars.
|
||||
///
|
||||
/// The compiler reuses a lane once what it held is dead, for a pair first and
|
||||
/// a scalar later, say. Where that keeps a pair from being one, each life of a
|
||||
/// lane (the saves that reach a restore in common, and those restores) is a
|
||||
/// store of its own.
|
||||
fn unspill(
|
||||
list: &mut [gfx10::Instruction],
|
||||
flows: &[Flow],
|
||||
leaders: &[usize],
|
||||
wave64: bool,
|
||||
lanes: u8,
|
||||
@@ -276,7 +287,7 @@ fn unspill(
|
||||
// VGPRs used by parking alone, the scalar codes the program uses, and
|
||||
// per instruction the scalar codes it writes.
|
||||
let mut stores = [false; 256];
|
||||
let mut other = [false; 256];
|
||||
let mut other: [Option<usize>; 256] = [None; 256]; // the last such use
|
||||
let mut used = [false; 128];
|
||||
let mut parks: Vec<Option<(bool, u8, u8, u32)>> = Vec::with_capacity(list.len());
|
||||
let mut written: Vec<Vec<u8>> = Vec::with_capacity(list.len());
|
||||
@@ -314,7 +325,7 @@ fn unspill(
|
||||
match reg {
|
||||
Reg::S(c) => used[usize::from(c)] = true,
|
||||
Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true,
|
||||
Reg::V(r) => other[usize::from(r)] = true,
|
||||
Reg::V(r) => other[usize::from(r)] = Some(parks.len()),
|
||||
Reg::Scc => {}
|
||||
}
|
||||
}
|
||||
@@ -323,16 +334,33 @@ fn unspill(
|
||||
written.push(codes);
|
||||
read.push(from);
|
||||
}
|
||||
for (i, park) in parks.iter_mut().enumerate() {
|
||||
if park.is_some_and(|p| other[usize::from(p.1)]) {
|
||||
*park = None;
|
||||
let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok();
|
||||
for reg in 0..256 {
|
||||
let Some(last) = other[reg] else { continue };
|
||||
let of = |p: &Option<(bool, u8, u8, u32)>| p.filter(|p| usize::from(p.1) == reg);
|
||||
let first = parks.iter().position(|p| of(p).is_some_and(|p| p.0));
|
||||
let late = first.is_some_and(|first| {
|
||||
let end = parks.iter().rposition(|p| of(p).is_some()).unwrap_or(first);
|
||||
let mut saved = Vec::new();
|
||||
last < first
|
||||
&& !(first + 1..=end).any(leader)
|
||||
&& parks[first..=end].iter().filter_map(of).all(|(save, _, _, lane)| {
|
||||
if save {
|
||||
saved.push(lane);
|
||||
}
|
||||
saved.contains(&lane)
|
||||
})
|
||||
});
|
||||
let from = if late { first.unwrap_or(0) } else { parks.len() };
|
||||
for park in &mut parks[..from] {
|
||||
if of(park).is_some() {
|
||||
*park = None;
|
||||
}
|
||||
}
|
||||
let _ = i;
|
||||
}
|
||||
if parks.iter().all(Option::is_none) {
|
||||
return Vec::new();
|
||||
}
|
||||
let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok();
|
||||
// Lane pairs (register, lower lane) that always move together: each
|
||||
// save of the lower lane is followed, in the same block and before its
|
||||
// register changes, by the save of the next register into the next
|
||||
@@ -342,9 +370,6 @@ fn unspill(
|
||||
// compiler puts loads and constants between the two: five instructions later
|
||||
// in the ped mesh programs). Only wave64 programs have pairs: a wave32 mask
|
||||
// is one dword, and a pair move of it with its neighbour would hide it.
|
||||
let mut slots: Vec<(u8, u32)> = parks.iter().flatten().map(|p| (p.1, p.3)).collect();
|
||||
slots.sort_unstable();
|
||||
slots.dedup();
|
||||
// instruction -> the instruction that completes its pair
|
||||
let partner = |i: usize| -> Option<usize> {
|
||||
let (save, reg, code, lane) = parks[i]?;
|
||||
@@ -385,52 +410,163 @@ fn unspill(
|
||||
None
|
||||
}
|
||||
};
|
||||
let mut pairs: Vec<(u8, u32)> = Vec::new();
|
||||
for &(reg, lane) in &slots {
|
||||
if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) {
|
||||
continue;
|
||||
// The store each parking instruction uses, and what the stores are lanes
|
||||
// of: one per (VGPR, lane), or (`split`) one per life of it.
|
||||
let stores_of = |split: bool| -> (Vec<usize>, Vec<(u8, u32)>) {
|
||||
let slot = |i: usize| parks[i].map(|p| (p.1, p.3));
|
||||
// Instructions of one store, by the first of them.
|
||||
let mut first: Vec<usize> = (0..list.len()).collect();
|
||||
if split {
|
||||
fn root(first: &mut [usize], mut i: usize) -> usize {
|
||||
while first[i] != i {
|
||||
first[i] = first[first[i]];
|
||||
i = first[i];
|
||||
}
|
||||
i
|
||||
}
|
||||
let at = |offset: usize| list.partition_point(|i| i.offset < offset);
|
||||
for save in (0..list.len()).filter(|&i| parks[i].is_some_and(|p| p.0)) {
|
||||
let mut seen = HashSet::new();
|
||||
let mut work = vec![save + 1];
|
||||
while let Some(from) = work.pop() {
|
||||
for i in from..list.len() {
|
||||
if slot(i).is_some() && slot(i) == slot(save) {
|
||||
if parks[i].is_some_and(|p| p.0) {
|
||||
break;
|
||||
}
|
||||
let (a, b) = (root(&mut first, save), root(&mut first, i));
|
||||
first[a.max(b)] = a.min(b);
|
||||
}
|
||||
let mut go = |to: usize| {
|
||||
if seen.insert(to) {
|
||||
work.push(to);
|
||||
}
|
||||
};
|
||||
match flows[i] {
|
||||
Flow::Next if i + 1 < list.len() && leader(i + 1) => go(i + 1),
|
||||
Flow::Next => continue,
|
||||
Flow::Stop => {}
|
||||
Flow::Jump(t) => go(at(t)),
|
||||
Flow::Branch(t) => {
|
||||
go(at(t));
|
||||
go(i + 1);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for i in 0..list.len() {
|
||||
first[i] = root(&mut first, i);
|
||||
}
|
||||
} else {
|
||||
let mut of: HashMap<(u8, u32), usize> = HashMap::new();
|
||||
for i in 0..list.len() {
|
||||
if let Some(s) = slot(i) {
|
||||
first[i] = *of.entry(s).or_insert(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
let lower: Vec<usize> = (0..list.len()).filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))).collect();
|
||||
let upper = parks.iter().flatten().filter(|p| (p.1, p.3) == (reg, lane + 1)).count();
|
||||
let partners: Vec<Option<usize>> = lower.iter().map(|&i| partner(i)).collect();
|
||||
let mut distinct: Vec<usize> = partners.iter().flatten().copied().collect();
|
||||
distinct.sort_unstable();
|
||||
distinct.dedup();
|
||||
if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() {
|
||||
pairs.push((reg, lane));
|
||||
let mut stores: Vec<((u8, u32), usize)> = (0..list.len())
|
||||
.filter(|&i| first[i] == i)
|
||||
.filter_map(|i| Some((slot(i)?, i)))
|
||||
.collect();
|
||||
stores.sort_unstable();
|
||||
let number = |i: usize| stores.iter().position(|s| s.1 == first[i]);
|
||||
let of = (0..list.len())
|
||||
.map(|i| parks[i].and_then(|_| number(i)).unwrap_or(usize::MAX))
|
||||
.collect();
|
||||
(of, stores.into_iter().map(|s| s.0).collect())
|
||||
};
|
||||
// The stores that move as pairs (lower, upper) and every store's code;
|
||||
// none if the spare codes do not suffice.
|
||||
let plan = |split: bool| -> Option<(Vec<usize>, Vec<(usize, usize)>, Vec<u8>)> {
|
||||
let (mut of, stores) = stores_of(split);
|
||||
let mut pairs: Vec<(usize, usize)> = Vec::new();
|
||||
for (n, &(reg, lane)) in stores.iter().enumerate() {
|
||||
if !wave64 || pairs.iter().any(|&(_, upper)| upper == n) {
|
||||
continue;
|
||||
}
|
||||
let lower: Vec<usize> = (0..list.len()).filter(|&i| of[i] == n).collect();
|
||||
let partners: Vec<Option<usize>> = lower.iter().map(|&i| partner(i)).collect();
|
||||
let mut distinct: Vec<usize> = partners.iter().flatten().copied().collect();
|
||||
distinct.sort_unstable();
|
||||
distinct.dedup();
|
||||
let Some(upper) = distinct.first().map(|&j| of[j]) else {
|
||||
continue;
|
||||
};
|
||||
if stores[upper] == (reg, lane + 1)
|
||||
&& partners.iter().all(Option::is_some)
|
||||
&& distinct.len() == lower.len()
|
||||
&& distinct.iter().all(|&j| of[j] == upper)
|
||||
&& of.iter().filter(|&&o| o == upper).count() == lower.len()
|
||||
{
|
||||
pairs.push((n, upper));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Codes for the parked scalars: the trap temporaries (108..=123), then
|
||||
// user SGPRs the program never names, from the top, then the codes past
|
||||
// the machine's (`PARKED`..=254; 255 stays unused so that the code after a
|
||||
// parked one always exists). A material resolve program parks up to 63
|
||||
// scalars and leaves about 20 machine codes unused.
|
||||
let past = usize::from(PARKED);
|
||||
let mut free = [false; 256];
|
||||
for c in (0..105).chain(108..=123) {
|
||||
free[c] = !used[c];
|
||||
}
|
||||
free[past..255].fill(true);
|
||||
let mut codes: Vec<((u8, u32), u8)> = Vec::new();
|
||||
for &(reg, lane) in &pairs {
|
||||
let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]);
|
||||
// Not enough spare codes: leave the program as it is.
|
||||
let Some(c) = at else { return Vec::new() };
|
||||
(free[c], free[c + 1]) = (false, false);
|
||||
codes.push(((reg, lane), c as u8));
|
||||
codes.push(((reg, lane + 1), c as u8 + 1));
|
||||
}
|
||||
for &slot in &slots {
|
||||
if codes.iter().any(|c| c.0 == slot) {
|
||||
continue;
|
||||
}
|
||||
let Some(c) = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c]) else {
|
||||
return Vec::new();
|
||||
// Lives of one lane that move alike share a code, as they share the lane.
|
||||
let role = |n: usize| {
|
||||
let (lower, upper) = (pairs.iter().any(|p| p.0 == n), pairs.iter().any(|p| p.1 == n));
|
||||
(stores[n], u8::from(lower) + 2 * u8::from(upper))
|
||||
};
|
||||
free[c] = false;
|
||||
codes.push((slot, c as u8));
|
||||
let mut shared: Vec<_> = (0..stores.len()).map(role).collect();
|
||||
let place: Vec<usize> = {
|
||||
let all = shared.clone();
|
||||
shared.sort_unstable();
|
||||
shared.dedup();
|
||||
all.iter().filter_map(|r| shared.binary_search(r).ok()).collect()
|
||||
};
|
||||
for o in of.iter_mut().filter(|o| **o != usize::MAX) {
|
||||
*o = place[*o];
|
||||
}
|
||||
for p in &mut pairs {
|
||||
*p = (place[p.0], place[p.1]);
|
||||
}
|
||||
pairs.sort_unstable();
|
||||
pairs.dedup();
|
||||
// Codes for the parked scalars: the trap temporaries (108..=123), then
|
||||
// user SGPRs the program never names, from the top, then the codes past
|
||||
// the machine's (`PARKED`..=254; 255 stays unused so that the code after a
|
||||
// parked one always exists). A material resolve program parks up to 63
|
||||
// scalars and leaves about 20 machine codes unused.
|
||||
let past = usize::from(PARKED);
|
||||
let mut free = [false; 256];
|
||||
for c in (0..105).chain(108..=123) {
|
||||
free[c] = !used[c];
|
||||
}
|
||||
free[past..255].fill(true);
|
||||
let mut codes: Vec<Option<u8>> = vec![None; shared.len()];
|
||||
for &(lower, upper) in &pairs {
|
||||
let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]);
|
||||
// Not enough spare codes: leave the program as it is.
|
||||
let c = at?;
|
||||
(free[c], free[c + 1]) = (false, false);
|
||||
codes[lower] = Some(c as u8);
|
||||
codes[upper] = Some(c as u8 + 1);
|
||||
}
|
||||
for code in codes.iter_mut().filter(|c| c.is_none()) {
|
||||
let c = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c])?;
|
||||
free[c] = false;
|
||||
*code = Some(c as u8);
|
||||
}
|
||||
Some((of, pairs, codes.into_iter().flatten().collect()))
|
||||
};
|
||||
let Some(mut chosen) = plan(false) else { return Vec::new() };
|
||||
let lonely = |(of, pairs, _): &(Vec<usize>, Vec<(usize, usize)>, Vec<u8>)| {
|
||||
(0..list.len()).any(|i| {
|
||||
parks[i].is_some_and(|p| p.0)
|
||||
&& partner(i).is_some()
|
||||
&& !pairs.iter().any(|&(lower, upper)| of[i] == lower || of[i] == upper)
|
||||
})
|
||||
};
|
||||
if wave64
|
||||
&& lonely(&chosen)
|
||||
&& let Some(split) = plan(true)
|
||||
&& split.1.len() > chosen.1.len()
|
||||
{
|
||||
chosen = split;
|
||||
}
|
||||
let code_of = |reg: u8, lane: u32| codes.iter().find(|c| c.0 == (reg, lane)).map(|c| c.1);
|
||||
let (store, pairs, codes) = chosen;
|
||||
let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| {
|
||||
list[i] = gfx10::Instruction {
|
||||
offset: list[i].offset,
|
||||
@@ -446,11 +582,11 @@ fn unspill(
|
||||
const NOP: u32 = 0xBF80_0000;
|
||||
let mut edits: Vec<(usize, Option<(bool, u8, u8)>)> = Vec::new();
|
||||
for i in 0..list.len() {
|
||||
let Some((save, reg, code, lane)) = parks[i] else {
|
||||
let Some((save, _, code, _)) = parks[i] else {
|
||||
continue;
|
||||
};
|
||||
let Some(slot) = code_of(reg, lane) else { return Vec::new() };
|
||||
if pairs.contains(&(reg, lane)) {
|
||||
let slot = codes[store[i]];
|
||||
if pairs.iter().any(|p| p.0 == store[i]) {
|
||||
let Some(j) = partner(i) else { return Vec::new() };
|
||||
// A save moves the pair where its second half is saved; a
|
||||
// restore where its first half is restored.
|
||||
@@ -458,7 +594,7 @@ fn unspill(
|
||||
let (dst, src) = if save { (slot, code) } else { (code, slot) };
|
||||
edits.push((at, Some((true, dst, src))));
|
||||
edits.push((gone, None));
|
||||
} else if lane > 0 && pairs.contains(&(reg, lane - 1)) {
|
||||
} else if pairs.iter().any(|p| p.1 == store[i]) {
|
||||
// the upper half of a pair: moved with the lower
|
||||
} else {
|
||||
let (dst, src) = if save { (slot, code) } else { (code, slot) };
|
||||
|
||||
@@ -2611,6 +2611,94 @@ pub(crate) mod tests {
|
||||
assert_eq!(r.scalar, [((0, 3), at(0, 0x20))]);
|
||||
}
|
||||
|
||||
/// A VGPR a wave reduction used is free again after it: from the first
|
||||
/// save on it holds parked scalars alone (an upscaler program parks a
|
||||
/// constant buffer's descriptor that way).
|
||||
#[test]
|
||||
fn a_vgpr_used_before_holds_spilled_sgprs_from_its_first_save() {
|
||||
let before = [
|
||||
0x7E00_0281, // v_mov_b32 v0, 1
|
||||
0x7E02_0300, // v_mov_b32 v1, v0
|
||||
];
|
||||
let park = [
|
||||
0xD761_0000,
|
||||
0x0001_0609, // v_writelane_b32 v0, s9, 3
|
||||
0xD760_0002,
|
||||
0x0001_0700, // v_readlane_b32 s2, v0, 3
|
||||
0xBE83_0380, // s_mov_b32 s3, 0
|
||||
];
|
||||
let load = [
|
||||
0xF40C_0001,
|
||||
0xFA00_0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20
|
||||
S_ENDPGM,
|
||||
];
|
||||
let words = [&before[..], &park, &load].concat();
|
||||
let r = track_words(&words, &[param(Table, 9, 1)], HwStage::Ps);
|
||||
assert_eq!(r.scalar, [((0, 5), at(0, 0x20))]);
|
||||
// Still lane reads: a lane restored before it is saved, and a
|
||||
// register with an ordinary use after the first save.
|
||||
let restored_first = [&before[..], &park[2..4], &park[..2], &load].concat();
|
||||
let used_after = [&before[..], &park, &before[1..], &load].concat();
|
||||
for words in [restored_first, used_after] {
|
||||
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let p = crate::ir::build(&code, true, 8).unwrap();
|
||||
let insts = p.blocks.iter().flat_map(|b| &b.insts);
|
||||
assert_eq!(insts.filter(|i| i.name() == "v_readlane_b32").count(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Two lanes hold a pair (a lane mask, say) and later one of them a
|
||||
/// scalar, as in a water volume program that parks more than the lanes
|
||||
/// of one VGPR hold: the pair still moves as one.
|
||||
#[test]
|
||||
fn a_lane_spilled_to_again_later_does_not_split_an_earlier_pair() {
|
||||
let pair = [
|
||||
0xD761_0000u32,
|
||||
0x0001_0004, // v_writelane_b32 v0, s4, 0
|
||||
0xD761_0000,
|
||||
0x0001_0205, // v_writelane_b32 v0, s5, 1
|
||||
0xBE84_0380, // s_mov_b32 s4, 0
|
||||
0xBE85_0380, // s_mov_b32 s5, 0
|
||||
0xD760_0004,
|
||||
0x0001_0100, // v_readlane_b32 s4, v0, 0
|
||||
0xD760_0005,
|
||||
0x0001_0300, // v_readlane_b32 s5, v0, 1
|
||||
];
|
||||
let scalar = [
|
||||
0xD761_0000u32,
|
||||
0x0001_0006, // v_writelane_b32 v0, s6, 0
|
||||
0xBE86_0380, // s_mov_b32 s6, 0
|
||||
0xD760_0006,
|
||||
0x0001_0100, // v_readlane_b32 s6, v0, 0
|
||||
S_ENDPGM,
|
||||
];
|
||||
let moves = |words: &[u32]| {
|
||||
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let p = crate::ir::build(&code, true, 8).unwrap();
|
||||
let names: Vec<_> = p.blocks[0].insts.iter().map(|i| i.name()).collect();
|
||||
assert!(!names.iter().any(|n| n.contains("lane")));
|
||||
names.iter().filter(|n| **n == "s_mov_b64").count()
|
||||
};
|
||||
assert_eq!(moves(&[&pair[..], &scalar].concat()), 2);
|
||||
// A restore both saves reach keeps the lane one scalar.
|
||||
let joined = [
|
||||
&pair[..4],
|
||||
&[0xBF84_0002], // s_cbranch_scc0 past the second save
|
||||
&scalar[..2],
|
||||
&pair[4..],
|
||||
&scalar[2..],
|
||||
]
|
||||
.concat();
|
||||
assert_eq!(moves_anywhere(&joined), 0);
|
||||
}
|
||||
|
||||
fn moves_anywhere(words: &[u32]) -> usize {
|
||||
let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let p = crate::ir::build(&code, true, 8).unwrap();
|
||||
let insts = p.blocks.iter().flat_map(|b| &b.insts);
|
||||
insts.filter(|i| i.name() == "s_mov_b64").count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptors_joined_by_control_flow_are_traced_per_edge() {
|
||||
let r = track_words(
|
||||
|
||||
+28
-1
@@ -56,14 +56,18 @@ with the presented one.
|
||||
|
||||
| switch | does |
|
||||
|---|---|
|
||||
| `--compare` | runs the frame unchanged first and prints the difference |
|
||||
| `--compare` | runs the frame unchanged and with the experiments turn by turn, and prints the difference |
|
||||
| `--skip-clamps` | no argument clamps and no barriers of their scratch buffers; draws read arguments kept from a first run |
|
||||
| `--batch-clamps` / `--batch-clamps 2` | argument clamps in batches, as `VICTORY_INDIRECT_BATCH=2` / `=1` does |
|
||||
| `--skip-hash-passes` | no compare/rehash passes over card buffers |
|
||||
| `--no-barriers` | no unordered-access barriers |
|
||||
| `--merge-barriers` | joins barrier calls with no work between them |
|
||||
| `--buffers vram` / `sysmem` | all buffers in the card's / the PC's memory |
|
||||
| `--only-buffers <what>` | with `--buffers`: only the buffers all of these match: `name=<text>`, `min=<bytes>`, `max=<bytes>`, `seen=No`, `Cached` or `Combined`, `id=<a>..<b>`, or `!` and one of them (repeatable) |
|
||||
| `--listing 3..7` | only writes the frame's buffers and those lists' commands |
|
||||
| `--one-submit` | one `ExecuteCommandLists`, with a full wait between the former ones |
|
||||
| `--only 3..7` | runs these lists; of the others only barriers |
|
||||
| `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) |
|
||||
| `--skip-shader <text>` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) |
|
||||
| `--no-restore` | leaves what a loop changed |
|
||||
| `--debug-layer` | D3D12's debug layer; its errors in the report |
|
||||
@@ -73,6 +77,29 @@ leaves out waits or work can draw another picture and, with wild data, lose
|
||||
the device: save work in other programs first. Do not run the title at the
|
||||
same time.
|
||||
|
||||
## Runs that differ
|
||||
|
||||
Shaders that give out places with atomics (the title's culling) give other
|
||||
ones in every run. The host layer brings such results to title memory and
|
||||
sends 64 KiB pieces of it up again, so the recorded copies hold the recorded
|
||||
run's results. Put over a replay's own, lists and what points into them are of
|
||||
two runs, and things are drawn from other things' lists. So copies of what the
|
||||
CPU wrote leave alone words the card has written in this run (`merge.rs`; the
|
||||
report counts them). `--no-merge` runs the copies as recorded.
|
||||
|
||||
| switch | does |
|
||||
|---|---|
|
||||
| `--wait-all` / `--wait-lists` | a full wait after every command / each list sent alone and waited for: if pictures still differ, waits are not what is missing |
|
||||
| `--diverge [runs]` | runs each list this often from the very same memory, finds the first commands that make different memory of it, and says what differs (same values in another order: places given out); contents go to `diverge` in the capture |
|
||||
| `--diverge-picture [runs]` | from each list on, runs the rest this often from the same memory: where the pictures start to agree, what lies before decides. `--lists 76 --commands 0..900 --step 8` goes into one list |
|
||||
| `--diverge 10 --lists 76 --draws <text>` | each draw of the pipelines named, alone, this often: how many outcomes, and what it reads |
|
||||
| `--watch <id>:<offset>:<bytes>` | which lists (with `--lists`: commands) change those words |
|
||||
| `--slots <list>:<command>` | the heap slots its constants name |
|
||||
| `--check-written` | that everything the frame changes is put back |
|
||||
| `--dump <text>` | the DXIL of the pipelines named, in `shaders` |
|
||||
|
||||
The `--diverge` family runs the recorded copies without the merge.
|
||||
|
||||
## Limits
|
||||
|
||||
- Not recorded, but reported when used: reserved (tiled) resources, bundles,
|
||||
|
||||
Reference in new issue
Block a user