wip: submissions send their own bytes

This commit is contained in:
local committed 2026-11-24 23:51:11 -06:00
1 parent 5ff9f4e56a
commit b64d65845f
5 files changed
+575 -23

No files matched your search

+261
View File
@@ -0,0 +1,261 @@
//! What goes up to copies in the card's memory goes up as it was when its
//! submission was prepared (`VICTORY_SEND_OWN`, on by default; `0`: as
//! before).
//!
//! The sends were copies out of the copies' CPU sides, which the card makes
//! when it comes to the submission. By then later submissions are prepared
//! (two frames of them with `VICTORY_RELAY`), and their refreshes have
//! written the same CPU sides: the earlier submission's shaders then read a
//! later one's bytes. For what the title's CPU writes that is as on the
//! console (it does not write what the card still reads). But the title's
//! own buffer copies are commands in its lists, and those are done by us
//! when a submission is prepared: "a value to a buffer, a draw that reads
//! it" in one submission and the same with another value in the next is
//! ordinary, and both draws read the second value.
//!
//! So each submission's bytes are taken out of the CPU sides into memory of
//! the submission's own when they are taken from the dirty lists, and the
//! card copies them from there. Runs of a few words, which a refresh that
//! sends only what changed makes many of, go as pairs of offset and value,
//! stored by one dispatch per copy; the others as a copy each.
use super::*;
use crate::shadow::Shadow;
pub(super) fn own() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_SEND_OWN").is_none_or(|v| v != "0"))
}
/// Runs up to this many bytes go as pairs.
const SHORT: usize = 256;
const SCATTER: &str = r#"
#define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)"
cbuffer Part : register(b0) { uint at; uint count; };
ByteAddressBuffer pairs : register(t0);
RWByteAddressBuffer card : register(u0);
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
if (id.x >= count) return;
uint2 p = pairs.Load2(at + id.x * 8u);
card.Store(p.x, p.y);
}
"#;
struct Pass {
root: ID3D12RootSignature,
pso: ID3D12PipelineState,
}
fn pass(host: &Host) -> Option<&'static Pass> {
static PASS: OnceLock<Option<Pass>> = OnceLock::new();
PASS.get_or_init(|| {
let code = compile(SCATTER, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?;
// SAFETY: the code lives through the calls; the root signature is
// inside it.
unsafe {
let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?;
let pso: ID3D12PipelineState = host
.device
.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE {
pShaderBytecode: code.as_ptr().cast(),
BytecodeLength: code.len(),
},
..Default::default()
})
.ok()?;
name(&pso, || "victory: changed words sent to the card".into());
Some(Pass { root, pso })
}
})
.as_ref()
}
/// Memory a submission's sends come from, mapped.
pub(super) struct Memory {
buffer: ID3D12Resource,
data: usize,
size: u64,
}
// SAFETY: a D3D12 object (free-threaded) and its mapping, with one owner.
unsafe impl Send for Memory {}
/// What submissions that have run gave back.
static SPARE: Mutex<Vec<Memory>> = Mutex::new(Vec::new());
/// At most this much is kept.
const KEPT: u64 = 768 << 20;
fn memory(host: &Host, size: u64) -> Option<Memory> {
{
let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
let fit = spare.iter().enumerate().filter(|(_, m)| m.size >= size).min_by_key(|(_, m)| m.size).map(|(i, _)| i);
if let Some(i) = fit {
return Some(spare.swap_remove(i));
}
}
let size = size.next_multiple_of(8 << 20);
let (buffer, data) = host.upload_buffer(size)?;
name(&buffer, || "bytes a submission sends up".into());
Some(Memory {
buffer,
data: data as usize,
size,
})
}
/// The submission has run.
pub(super) fn give_back(memory: Memory) {
let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
spare.push(memory);
spare.sort_by_key(|m| std::cmp::Reverse(m.size));
while spare.iter().map(|m| m.size).sum::<u64>() > KEPT {
spare.remove(0);
}
}
/// Since the last frame-rate line: bytes copied, runs copied, words stored,
/// microseconds of taking them out of the CPU sides.
pub(super) static STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
/// One copy's sends: ranges copied (offset in the copy, in the memory,
/// bytes), and its pairs (where in the memory, how many).
struct Copy {
runs: Vec<(usize, u64, usize)>,
pairs: (u64, u32),
}
/// Where a submission's bytes are taken to.
pub(super) struct Own {
memory: Memory,
copies: Vec<Copy>,
}
/// Takes what `dirty` sends up out of the CPU sides.
pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)]) -> Option<Own> {
let began = std::time::Instant::now();
pass(host)?;
// Runs of whole words of the copy: only those are pairs. (A byte beside
// them in a word may be the card's.)
let short = |&(a, b): &(usize, usize)| b - a <= SHORT && a % 4 == 0 && b % 4 == 0;
let mut at = 0u64;
let mut copies = Vec::with_capacity(dirty.len());
for (_, ranges) in dirty {
let mut runs = Vec::new();
for &(a, b) in ranges.iter().filter(|r| !short(r)) {
runs.push((a, at, b - a));
at += ((b - a) as u64).next_multiple_of(16);
}
let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum();
copies.push(Copy { runs, pairs: (at, words as u32) });
at += (words as u64 * 8).next_multiple_of(16);
}
if at == 0 {
return None;
}
let memory = memory(host, at)?;
let mut moves: Vec<(usize, usize, usize)> = Vec::new();
for ((shadow, ranges), copy) in dirty.iter().zip(&copies) {
let from = shadow.card_data() as usize;
moves.extend(copy.runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n)));
let mut to = (memory.data + copy.pairs.0 as usize) as *mut [u32; 2];
for &(a, b) in ranges.iter().filter(|r| short(r)) {
for offset in (a..b).step_by(4) {
// SAFETY: inside the copy's mapping (its CPU side, which
// this thread alone writes in these ranges) and inside the
// memory, which has room for every pair.
unsafe {
let word = ((from + offset) as *const u32).read_unaligned();
to.write([offset as u32, word]);
to = to.add(1);
}
}
}
}
STATS[0].fetch_add(moves.iter().map(|m| m.2 as u64).sum(), Ordering::Relaxed);
STATS[1].fetch_add(moves.len() as u64, Ordering::Relaxed);
STATS[2].fetch_add(copies.iter().map(|c| u64::from(c.pairs.1)).sum(), Ordering::Relaxed);
crate::shadow::copy_all(moves);
STATS[3].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed);
Some(Own { memory, copies })
}
impl Own {
/// Records the sends into `list`; the copies that `looked` says are in
/// `COPY_DEST`, the others in the common state. Those with a "before" are
/// left readable by compute shaders.
///
/// # Safety
/// An open list of ours, whose compute state is set anew behind this.
pub(super) unsafe fn record(
&self,
host: &Host,
list: &ID3D12GraphicsCommandList,
dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)],
looked: impl Fn(&Shadow) -> bool,
) {
let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
let write = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
let dest = D3D12_RESOURCE_STATE_COPY_DEST;
let (mut first, mut last) = (Vec::new(), Vec::new());
for ((shadow, _), copy) in dirty.iter().zip(&self.copies) {
for &(a, from, n) in &copy.runs {
// SAFETY: the caller's; live buffers, ranges inside them.
unsafe { list.CopyBufferRegion(&shadow.buffer, a as u64, &self.memory.buffer, from, n as u64) };
}
let mut state = (looked(shadow) || !copy.runs.is_empty()).then_some(dest);
if copy.pairs.1 > 0 {
if let Some(was) = state {
first.push(transition(&shadow.buffer, was, write));
}
state = Some(write);
}
let hashed = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
if let Some(was) = state
&& hashed
&& (!copy.runs.is_empty() || copy.pairs.1 > 0)
{
last.push(transition(&shadow.buffer, was, read));
}
}
// SAFETY: the caller's; live objects.
unsafe {
if !first.is_empty() {
list.ResourceBarrier(&first);
}
if let Some(pass) = pass(host)
&& self.copies.iter().any(|c| c.pairs.1 > 0)
{
list.SetComputeRootSignature(&pass.root);
list.SetPipelineState(&pass.pso);
list.SetComputeRootShaderResourceView(1, self.memory.buffer.GetGPUVirtualAddress());
for ((shadow, _), copy) in dirty.iter().zip(&self.copies).filter(|(_, c)| c.pairs.1 > 0) {
list.SetComputeRootUnorderedAccessView(2, shadow.buffer.GetGPUVirtualAddress());
const MOST: u32 = 64 * D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
let (at, words) = copy.pairs;
let mut done = 0;
while done < words {
let n = (words - done).min(MOST);
let constants = [at as u32 + done * 8, n];
list.SetComputeRoot32BitConstants(0, 2, constants.as_ptr().cast(), 0);
list.Dispatch(n.div_ceil(64), 1, 1);
done += n;
}
}
}
if !last.is_empty() {
list.ResourceBarrier(&last);
}
}
}
/// The memory, to be kept until the submission has run.
pub(super) fn memory(self) -> Memory {
self.memory
}
}
+170 -12
View File
@@ -112,12 +112,21 @@ pub(crate) fn note(copy: u64, at: usize, was: &[u8], new: &[u8]) {
if n == 0 {
return;
}
let at = at + skip;
let (mut was, new) = (was[skip..skip + n].to_vec(), new[skip..skip + n].to_vec());
let mut noted = NOTED.lock().unwrap_or_else(|e| e.into_inner());
noted.entry(copy).or_default().push(Taken {
at: at + skip,
was: was[skip..skip + n].to_vec(),
new: new[skip..skip + n].to_vec(),
});
let noted = noted.entry(copy).or_default();
// What was noted before in this submission has not gone up yet: the card
// knows what stood there before that. And what it took is not what goes
// up where this took it again.
for t in noted.iter_mut() {
let (a, b) = (at.max(t.at), (at + n).min(t.at + t.was.len()));
if a < b {
was[a - at..b - at].copy_from_slice(&t.was[a - t.at..b - t.at]);
t.new[a - t.at..b - t.at].copy_from_slice(&new[a - at..b - at]);
}
}
noted.push(Taken { at, was, new });
}
/// A submission's look at what it sends up, until it has run.
@@ -202,6 +211,11 @@ pub(super) fn record(
}
impl Looks {
/// Whether `shadow` was looked at: it is left in `COPY_DEST`.
pub(super) fn hold(&self, shadow: &Shadow) -> bool {
self.of.iter().any(|(s, _)| s.id() == shadow.id())
}
/// The submission has run: what it found is counted.
pub(super) fn read(self) {
// SAFETY: the mapping holds an answer for each; the card has run.
@@ -354,6 +368,69 @@ pub(super) fn reads(runs: &[&HostList]) {
}
}
/// The title's buffer copies that are out of their place in a submission:
/// by what is wrong, bytes and destination: how often, the last source, and
/// (for shader writes) how much was declared.
type Misplaced = BTreeMap<(&'static str, usize, usize), (u64, usize, usize)>;
static MISPLACED: Mutex<(u64, Misplaced)> = Mutex::new((0, BTreeMap::new()));
/// A submission is about to be prepared: its title buffer copies are done on
/// the CPU then, all of them before the first of its draws runs. Where that
/// is not the order of its lists: what an earlier draw of it reads of the
/// destination, or shaders of it write there, or an earlier copy of it put
/// there for what lies between; and a source that shaders of it write first.
pub(super) fn order(runs: &[&HostList]) {
let (mut read, mut written, mut copied): (Vec<(usize, usize)>, Vec<(usize, usize)>, Vec<(usize, usize)>) =
(Vec::new(), Vec::new(), Vec::new());
let meets = |all: &[(usize, usize)], from: usize, to: usize| all.iter().rev().find(|r| r.0 < to && from < r.1).copied();
let mut misplaced = MISPLACED.lock().unwrap_or_else(|e| e.into_inner());
for list in runs {
for step in &list.deferred().copies {
match step {
Step::Refresh(_, at, len) => read.push((*at, *at + *len)),
Step::GpuWrite(_, at, len) => written.push((*at, *at + *len)),
&Step::Copy(dst, src, len) => {
let mut say = |what: &'static str, range: (usize, usize)| {
let e = misplaced.1.entry((what, len, dst)).or_default();
*e = (e.0 + 1, src, range.1 - range.0);
};
if let Some(r) = meets(&written, src, src + len) {
say("its source is declared written earlier in the submission", r);
}
if let Some(r) = meets(&written, dst, dst + len) {
say("its destination is declared written earlier in the submission", r);
}
if let Some(r) = meets(&copied, dst, dst + len) {
say("its destination is copied to earlier in the submission", r);
} else if let Some(r) = meets(&read, dst, dst + len) {
say("its destination is read earlier in the submission", r);
}
copied.push((dst, dst + len));
}
_ => {}
}
}
}
let now = now_ms();
if now < misplaced.0 + 4000 {
return;
}
misplaced.0 = now;
let mut all: Vec<_> = std::mem::take(&mut misplaced.1).into_iter().collect();
all.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
let mut kinds: BTreeMap<&str, (u64, u64)> = BTreeMap::new();
for ((what, len, _), (n, ..)) in &all {
let e = kinds.entry(what).or_default();
*e = (e.0 + n, e.1 + n * *len as u64);
}
for (what, (n, bytes)) in kinds {
tracing::warn!("up-copy check, copies out of place: {n} ({bytes} bytes): {what}");
}
for ((what, len, dst), (n, src, declared)) in all.into_iter().take(16) {
tracing::warn!("up-copy check, a copy out of place: {n} times {len:#x} bytes from {src:#x} to {dst:#x}: {what} ({declared:#x} bytes there)");
}
}
/// A run of words that differ at rest.
struct Differs {
shadow: std::sync::Arc<Shadow>,
@@ -567,6 +644,12 @@ mod tests {
/// Title memory of our own (write-watched, or a view of a section, which
/// is guarded), and the card copy of the title buffer it is.
fn title(resource: usize, view: bool) -> (&'static mut [u8], usize, std::sync::Arc<Shadow>) {
let all = title_of(resource, view, LEN);
assert!(all.2.carded(), "the copy is in the card's memory");
all
}
fn title_of(resource: usize, view: bool, len: usize) -> (&'static mut [u8], usize, std::sync::Arc<Shadow>) {
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE, VirtualAlloc,
};
@@ -574,20 +657,19 @@ mod tests {
// SAFETY: memory of our own, never freed.
let base = unsafe {
if view {
let section = CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, LEN as u32, std::ptr::null());
let section = CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
assert!(!section.is_null());
MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, LEN).Value.cast::<u8>()
MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value.cast::<u8>()
} else {
VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE).cast::<u8>()
VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE).cast::<u8>()
}
};
assert!(!base.is_null());
crate::shadow::register(resource, base as u64, LEN as u64);
crate::shadow::register(resource, base as u64, len as u64);
let shadow = crate::shadow::find(base as u64, 64).expect("a copy");
assert!(shadow.carded(), "the copy is in the card's memory");
assert!(super::super::relay_exact() && super::super::relay_copy(), "set VICTORY_RELAY=2 VICTORY_RELAY_COPY=1");
// SAFETY: `LEN` bytes just committed.
(unsafe { std::slice::from_raw_parts_mut(base, LEN) }, base as usize, shadow)
// SAFETY: `len` bytes just committed.
(unsafe { std::slice::from_raw_parts_mut(base, len) }, base as usize, shadow)
}
/// Work for the card that takes some milliseconds.
@@ -765,6 +847,81 @@ mod tests {
assert!(first <= 6 && back[first..].iter().all(|b| *b), "{back:?}");
}
/// The title copies another value to the same bytes in each of three
/// submissions, and each has a draw (a copy here) that reads them. The
/// card is busy meanwhile, so all three are prepared before the first
/// runs: each must read its own.
fn each_reads_its_own(len: usize, resource: usize, carded: bool) {
let Some(host) = host() else {
return;
};
let (title, start, shadow) = title_of(resource, true, len);
assert_eq!(shadow.carded(), carded, "where the copy is");
let slow = Slow::new(host);
let (out, out_data) = host.shared_buffer(1 << 16).unwrap();
let mut lists = Vec::new();
const AT: usize = 8192;
// All there once.
let all = host.new_list().unwrap();
shadow.refresh(&all, start as u64, len as u64);
all.close();
host.execute_own(&all);
settle_now(WHY_SYNC);
lists.push(all);
let mut wrong = Vec::new();
for round in 0..6u8 {
for v in 0..3u8 {
title[65_536 + usize::from(v) * 256..][..256].fill(round * 16 + v + 1);
}
let busy = host.new_list().unwrap();
slow.record(&busy, 40);
busy.close();
host.execute_own(&busy);
lists.push(busy);
for v in 0..3usize {
let list = host.new_list().unwrap();
list.defer_copy((start + AT) as *mut u8, (start + 65_536 + v * 256) as *const u8, 256);
shadow.refresh(&list, (start + AT) as u64, 256);
// SAFETY: an open list; live buffers.
unsafe {
list.list.CopyBufferRegion(&out, (v * 256) as u64, &shadow.buffer, AT as u64, 256);
}
list.close();
host.execute_own(&list);
lists.push(list);
}
settle_now(WHY_SYNC);
// SAFETY: a mapping of 64 KiB; the copies into it have run.
let read = unsafe { std::slice::from_raw_parts(out_data, 768) };
for v in 0..3u8 {
let got = read[usize::from(v) * 256];
if got != round * 16 + v + 1 {
wrong.push((round, v, got - round * 16));
}
}
}
eprintln!("read another submission's value (round, submission, whose + 1): {wrong:?}");
let stale = STALE.lock().unwrap_or_else(|e| e.into_inner());
let found = stale.get(&shadow.span()).map_or(0, |s| s.words);
eprintln!("the check at sends found {found} words");
assert!(wrong.is_empty());
assert_eq!(found, 0);
// With the debug layer (`VICTORY_D3D12_DEBUG=1`, diagnostics).
assert_eq!(host.log_messages(), None);
}
#[test]
#[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
fn each_submission_reads_its_own_copy_on_the_card() {
each_reads_its_own(LEN, 0x7777, true);
}
#[test]
#[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
fn each_submission_reads_its_own_copy_in_pc_memory() {
each_reads_its_own(256 << 10, 0x8888, std::env::var_os("VICTORY_CARD_ALL").is_some_and(|v| v == "1"));
}
/// Declared writes beside the title's own, in the same 64 KiB pieces and
/// dword by dword, flights landing while later ones are in the air: in
/// the end title memory and the card hold what each wrote last. (A byte
@@ -860,6 +1017,7 @@ mod tests {
on_card.is_empty() && in_title.is_empty(),
"round {round}: words {on_card:x?} on the card and {in_title:x?} in title memory are not what was written last"
);
assert_eq!(host.log_messages(), None);
}
}
}