The first room renders right: byte-copied descriptor records are mirrored, views off their copy's elements get their own bytes, card room for the first world frame, levels on demand run on the card
- Descriptor records the title copies into its heap as bytes are mirrored before each submission (pull request #305 by Flyander, after upstream VIctory 86a5ed6), with a per-slot fingerprint so only records that changed are mirrored, the page read through the kernel, a switch (VICTORY_HEAP_SYNC=0) and a counter: about 40,000 records a frame on the test machine. - A buffer view off its copy's elements gets a copy of its own bytes (after upstream 86a5ed6; VICTORY_VIEW_OWN_COPY=0: refused as before). - Room on the card for the world's first-frame bursts: buffer copies (VICTORY_CARD_ROOM_FOR_BUFFERS, now on) and render targets (VICTORY_CARD_ROOM_FOR_TARGETS_MB, 3,072); a copy turned down gives its room up and is logged; the texture pass asks again every 32 MiB. 98 buffer copies made (945 MB) where earlier runs made 1; 25 MB compared on the processor a frame where it was 550 to 710. - Levels on demand: the fixes of pull request #747 by AscilCH. First run on a card (RTX 4070, VICTORY_LEVELS_ON_DEMAND=1): no device loss, 3.1 GB not allocated for levels the title does not hold. Still off by default. - The guarded blocks under storage writes into physical pages are opened by default (VICTORY_PAGE_WRITES=0: counted only). - Shaders: a program is translated with first-half interpolation pairs only if it was refused for one (with it on for every program 8,551 working pixel programs came out changed); parked lane-mask pairs, f64 conversions and sums, lane permutations: 14 more programs translate. - Counted, not fixed: an indirect compute pass asks for about 77,500 groups in x and is cut to 65,535. One five-minute game run of these changes on the test machine: no device loss, no failed request. This merged tree was built; its test suites were not run. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
1 parent
8dd30ab472
commit
a26859fc5f
13 files changed
+1188
-58
No files matched your search
@@ -46,6 +46,33 @@ Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB,
|
||||
|
||||
### Newest (2026-11-25, later the same day)
|
||||
|
||||
**Update, the same night: the first room now renders right on the test
|
||||
machine** (walls, textures, people, lamps), at 190 to 450 ms a frame (2 to 5
|
||||
frames a second): the picture work has caught up, the frame rate has not.
|
||||
What did it, on top of the list below:
|
||||
- Descriptor records the title copies into its heap as plain bytes are
|
||||
mirrored before every submission (pull request #305 by Flyander, after
|
||||
upstream VIctory 86a5ed6). Measured here: about 40,000 records a frame
|
||||
that no call had announced; their host slots were empty or stale.
|
||||
- A buffer view that does not start on an element of its buffer's host
|
||||
copy gets a copy of its own bytes instead of being refused (after
|
||||
upstream 86a5ed6): 3 to 6 such views a frame.
|
||||
- Room on the card is kept for the render targets and buffer copies a
|
||||
world makes in its first frame: 98 buffer copies are made (945 MB) where
|
||||
the runs before made 1, and the processor no longer compares 550 to
|
||||
710 MB a frame looking for shader writes (25 MB now).
|
||||
- Levels on demand ran on the card for the first time
|
||||
(`VICTORY_LEVELS_ON_DEMAND=1`, still off by default; with the fixes of
|
||||
pull request #747 by AscilCH): 3.1 GB of the card not allocated for
|
||||
texture levels the title does not hold, no device loss.
|
||||
- Guarded blocks under storage writes are opened by default; 14 more
|
||||
shader programs translate; a program is translated with first-half
|
||||
interpolation pairs only if it was refused for one (with that on for
|
||||
every program, 8,551 working pixel programs came out changed).
|
||||
- Known and counted, not fixed yet: an indirect compute pass asks for
|
||||
about 77,500 thread groups in x where one dispatch runs 65,535 (the
|
||||
rest is cut off).
|
||||
|
||||
Memory sync between the title's memory and the copies on the card:
|
||||
- **A write through one view of a physical page is seen by the copies taken
|
||||
through its other views** (`VICTORY_VIEW_GUARD=0` turns it off). The title
|
||||
|
||||
@@ -59,6 +59,10 @@ pub(crate) struct Heap {
|
||||
host: std::sync::OnceLock<Option<host::HostHeap>>,
|
||||
#[cfg(windows)]
|
||||
pending: std::sync::Mutex<Vec<u32>>,
|
||||
/// Changed pages of a placed shader-visible heap. Some titles copy
|
||||
/// descriptor records into it as bytes, without a descriptor API call.
|
||||
#[cfg(windows)]
|
||||
written: Option<crate::watch::Tracked>,
|
||||
}
|
||||
|
||||
pub(crate) fn heap<'a>(this: This) -> &'a Heap {
|
||||
@@ -155,6 +159,119 @@ fn mirror(handle: u64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirrors records copied directly into placed shader-visible heaps. Calls
|
||||
/// to `Create*View` are already mirrored by [`mirror`]; raw CPU copies leave
|
||||
/// only write-watch pages to reveal which slots changed.
|
||||
///
|
||||
/// Upstream VIctory 86a5ed6 does the same and counts 1,300 to 14,400 such
|
||||
/// slots a frame in the world of the title this fork works on, against a
|
||||
/// few hundred views made by calls; without it those host slots stayed
|
||||
/// null, or went on showing what they showed before.
|
||||
/// `VICTORY_HEAP_SYNC=0`: not done, as before. [`SYNCED`] counts.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn sync_heaps() {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "0")) {
|
||||
return;
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let (mut pages, mut looked, mut mirrored) = (0u64, 0u64, 0u64);
|
||||
let mut page_bytes: Vec<u8> = Vec::new();
|
||||
let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for &(start, end, at) in heaps.iter() {
|
||||
// SAFETY: registered heaps are live (removed when dropped).
|
||||
let heap = unsafe { &*(at as *const Heap) };
|
||||
let (Some(Some(host)), Some(written), Some(step)) =
|
||||
(heap.host.get(), &heap.written, increment(heap.desc.kind))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let step = u64::from(step);
|
||||
// Capped host heaps have no counterparts for the title slots reserved
|
||||
// for per-draw tables; raw writes there must not be mirrored.
|
||||
let mirrored_count = heap.desc.count.min(host.count());
|
||||
for (range_from, range_end) in written.take(start as usize, end as usize) {
|
||||
let mut page = range_from & !(crate::watch::PAGE - 1);
|
||||
while page < range_end {
|
||||
let from = page.max(range_from);
|
||||
let to = (page + crate::watch::PAGE).min(range_end);
|
||||
// The page's records are read through the kernel, into a
|
||||
// copy: a page the title unmaps meanwhile fails the read
|
||||
// where 2,048 reads in place would fault.
|
||||
page_bytes.resize(to - from, 0);
|
||||
if crate::host::read_into(from as *const u8, &mut page_bytes) {
|
||||
pages += 1;
|
||||
let slots = changed_slots(from, to, start as usize, step, mirrored_count);
|
||||
for index in slots {
|
||||
let handle = start + index * step;
|
||||
// A record that straddles the range's ends is left
|
||||
// to the range that holds its first byte.
|
||||
let Some(at) = (handle as usize).checked_sub(from) else {
|
||||
continue;
|
||||
};
|
||||
let Some(record) = page_bytes.get(at..at + step as usize) else {
|
||||
continue;
|
||||
};
|
||||
looked += 1;
|
||||
// Only a record that is not the one last seen there
|
||||
// (`HostHeap::mirror_copied`).
|
||||
if host.mirror_copied(index as u32, handle, record) {
|
||||
mirrored += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
page += crate::watch::PAGE;
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(heaps);
|
||||
for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, started.elapsed().as_micros() as u64]) {
|
||||
count.fetch_add(n, Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Since the last frame line, of [`sync_heaps`]: changed pages of placed
|
||||
/// shader-visible heaps looked at, slots on them, slots whose record was
|
||||
/// not the one last seen (mirrored), and the microseconds it took.
|
||||
#[cfg(windows)]
|
||||
pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
|
||||
|
||||
/// With the frame line: what [`sync_heaps`] did per frame over `frames`.
|
||||
/// Nothing while no heap page changed.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn sync_line(frames: f64) {
|
||||
let [pages, looked, mirrored, micros] = [0, 1, 2, 3].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed));
|
||||
if pages == 0 {
|
||||
return;
|
||||
}
|
||||
tracing::info!(
|
||||
"descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \
|
||||
{:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.2} ms",
|
||||
pages as f64 / frames,
|
||||
looked as f64 / frames,
|
||||
mirrored as f64 / frames,
|
||||
micros as f64 / 1000.0 / frames
|
||||
);
|
||||
}
|
||||
|
||||
/// Title descriptor slots in a changed byte range that have host counterparts.
|
||||
/// `range_end` is exclusive.
|
||||
#[cfg(windows)]
|
||||
fn changed_slots(
|
||||
range_from: usize,
|
||||
range_end: usize,
|
||||
heap_start: usize,
|
||||
step: u64,
|
||||
mirrored_count: u32,
|
||||
) -> std::ops::Range<u64> {
|
||||
let from = (range_from - heap_start) as u64;
|
||||
let to = (range_end - heap_start) as u64;
|
||||
let first = from / step;
|
||||
let last = to.div_ceil(step).min(u64::from(mirrored_count));
|
||||
first.min(last)..last
|
||||
}
|
||||
|
||||
/// Gives back dynamic slots of the host heap behind the title heap at
|
||||
/// `heap`, if that heap still exists.
|
||||
#[cfg(windows)]
|
||||
@@ -970,6 +1087,10 @@ pub(crate) extern "system" fn create_heap(
|
||||
host: std::sync::OnceLock::new(),
|
||||
#[cfg(windows)]
|
||||
pending: Default::default(),
|
||||
#[cfg(windows)]
|
||||
written: (placed && visible)
|
||||
.then(|| crate::watch::track(start as usize, size as usize, true))
|
||||
.flatten(),
|
||||
});
|
||||
#[cfg(windows)]
|
||||
if visible {
|
||||
@@ -1027,6 +1148,34 @@ mod tests {
|
||||
create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn raw_heap_sync_stops_before_dynamic_host_slots() {
|
||||
let start = 0x1000usize;
|
||||
let step = 32;
|
||||
let capped = 5;
|
||||
assert_eq!(
|
||||
changed_slots(
|
||||
start + 3 * step + 4,
|
||||
start + 4 * step + 8,
|
||||
start,
|
||||
step as u64,
|
||||
capped
|
||||
),
|
||||
3..5
|
||||
);
|
||||
assert_eq!(
|
||||
changed_slots(
|
||||
start + 6 * step,
|
||||
start + 9 * step,
|
||||
start,
|
||||
step as u64,
|
||||
capped
|
||||
),
|
||||
5..5
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heaps_hold_count_descriptors_from_their_start() {
|
||||
let null = std::ptr::null();
|
||||
@@ -1053,6 +1202,58 @@ mod tests {
|
||||
assert_eq!(create(bad, none, &mut h), E_INVALIDARG);
|
||||
}
|
||||
|
||||
/// A descriptor copied into a placed heap as bytes is mirrored before
|
||||
/// the next submission, even though no descriptor method saw the copy.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn records_copied_as_bytes_are_made_at_the_next_sync() {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree,
|
||||
};
|
||||
const MEM_WRITE_WATCH: u32 = 0x20_0000;
|
||||
let memory = unsafe {
|
||||
VirtualAlloc(
|
||||
std::ptr::null(),
|
||||
crate::watch::PAGE,
|
||||
MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH,
|
||||
PAGE_READWRITE,
|
||||
)
|
||||
};
|
||||
assert!(!memory.is_null());
|
||||
let desc = HeapDesc {
|
||||
kind: SAMPLERS,
|
||||
count: 64,
|
||||
flags: SHADER_VISIBLE,
|
||||
nodes: 1,
|
||||
};
|
||||
let placement = Placement {
|
||||
address: memory as u64,
|
||||
size: 64 * 16,
|
||||
};
|
||||
let mut h: This = std::ptr::null();
|
||||
assert_eq!(create(desc, placement, &mut h), S_OK);
|
||||
if let Some(host) = heap(h).host() {
|
||||
let mut elsewhere = [0u64; 2];
|
||||
let source = elsewhere.as_mut_ptr() as u64;
|
||||
let sampler = [21, 3, 3, 3, 0, 1, 0, 0, 0, 0, 0, 0x7f7f_ffff, 0];
|
||||
create_sampler(std::ptr::null(), &sampler, source);
|
||||
// SAFETY: the heap slot and source both hold 16 descriptor bytes.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(
|
||||
source as *const u8,
|
||||
memory.cast::<u8>().add(5 * 16),
|
||||
16,
|
||||
)
|
||||
};
|
||||
assert!(!host.made(5));
|
||||
sync_heaps();
|
||||
assert!(host.made(5));
|
||||
}
|
||||
slot::<extern "system" fn(This) -> u32>(h, 0x10)(h);
|
||||
// SAFETY: this allocation belongs to the test.
|
||||
unsafe { VirtualFree(memory, 0, MEM_RELEASE) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn views_survive_copies() {
|
||||
let null = std::ptr::null();
|
||||
|
||||
@@ -26,6 +26,10 @@ pub(crate) struct HostHeap {
|
||||
sampler: bool,
|
||||
/// The record (view index and generation) each slot was last made from.
|
||||
made: Mutex<Vec<u64>>,
|
||||
/// A fingerprint of the record each slot held when the pass over
|
||||
/// records copied in as bytes last looked at it
|
||||
/// ([`HostHeap::mirror_copied`]; 0: never looked at). Made on first use.
|
||||
copied: Mutex<Vec<u64>>,
|
||||
/// The host resource each slot views, held while the slot does: shaders
|
||||
/// index heaps directly, so a slot the title has not rewritten since it
|
||||
/// released the resource may still be read, and a freed host resource
|
||||
@@ -947,6 +951,7 @@ impl HostHeap {
|
||||
dynamic: extra,
|
||||
sampler,
|
||||
made: Mutex::new(vec![0; count as usize]),
|
||||
copied: Mutex::new(Vec::new()),
|
||||
kept: Mutex::new(vec![None; (count + extra) as usize]),
|
||||
next: Mutex::new((0, vec![false; DYNAMIC as usize])),
|
||||
free: std::sync::atomic::AtomicU32::new(DYNAMIC),
|
||||
@@ -1789,6 +1794,45 @@ impl HostHeap {
|
||||
}
|
||||
}
|
||||
|
||||
/// For a slot on a page of the title's heap that changed with no call
|
||||
/// (`super::sync_heaps`: the title copies records into its heap as
|
||||
/// bytes): [`HostHeap::mirror`], if the `bytes` bytes of the record at
|
||||
/// `handle` are not the ones this last saw there. True if it did.
|
||||
///
|
||||
/// The page says only that something on it was written, and `mirror`
|
||||
/// by itself would take every buffer or placed-texture record on it for
|
||||
/// newly written each time (it leaves such a slot unmade until a draw
|
||||
/// or a pass uses it): the texture queue's entry for the slot would
|
||||
/// start again, and the buffer pass would look at 2,048 slots for one
|
||||
/// that changed.
|
||||
/// `record`: the record's bytes as the caller read them (through the
|
||||
/// kernel, which fails on a page the title unmapped meanwhile where a
|
||||
/// read in place would fault: the title unmaps heap pages too).
|
||||
pub(crate) fn mirror_copied(&self, index: u32, handle: u64, record: &[u8]) -> bool {
|
||||
if index >= self.count {
|
||||
return false;
|
||||
}
|
||||
let n = record.len();
|
||||
// Never 0, which is "never looked at".
|
||||
let print = u64::from_le_bytes(blake3::hash(record).as_bytes()[..8].try_into().unwrap_or([1; 8])) | 1;
|
||||
{
|
||||
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if copied.is_empty() {
|
||||
copied.resize(self.count as usize, 0);
|
||||
}
|
||||
let Some(last) = copied.get_mut(index as usize) else {
|
||||
return false;
|
||||
};
|
||||
// A slot never looked at that holds nothing: as it was.
|
||||
if *last == print || (*last == 0 && record[..n].iter().all(|&b| b == 0)) {
|
||||
return false;
|
||||
}
|
||||
*last = print;
|
||||
}
|
||||
self.mirror(index, handle, false);
|
||||
true
|
||||
}
|
||||
|
||||
/// Makes host slot `index` from the record the title has at `handle`
|
||||
/// if it changed since, and returns the view recorded there. Buffer
|
||||
/// views are made only for draws (`for_draw`), which also copy their
|
||||
@@ -1874,6 +1918,16 @@ impl HostHeap {
|
||||
Some(view)
|
||||
}
|
||||
|
||||
/// Whether slot `index` is backed by a made host descriptor (tests).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn made(&self, index: u32) -> bool {
|
||||
self.made
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.get(index as usize)
|
||||
.is_some_and(|&key| key != 0)
|
||||
}
|
||||
|
||||
/// Whether host slot `index` shows `buffer`; `None` if it shows no
|
||||
/// resource (diagnostics: a buffer view's slot must show the host copy
|
||||
/// that is brought up to date for it).
|
||||
@@ -2041,6 +2095,18 @@ pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc<crate::shadow::
|
||||
if len == 0 {
|
||||
return None;
|
||||
}
|
||||
// A view off its buffer's elements is made on a copy of its own bytes
|
||||
// (`own_bytes`): the same question `buffer_srv` and `buffer_uav` ask,
|
||||
// of the copy they find, so that the copy brought up to date is the
|
||||
// one the slot shows.
|
||||
if let Some((base, width)) = buffer_extent(view)
|
||||
&& let Some((first, count, element, stride, unknown)) = buffer_fields(view)
|
||||
&& let Some(whole) = crate::shadow::find(base, width)
|
||||
&& let Some((start, bytes)) = own_bytes(whole.offset(base), base, first, count, element, stride, unknown)
|
||||
&& let Some(own) = crate::shadow::exact(start, bytes)
|
||||
{
|
||||
return Some((own, start, bytes));
|
||||
}
|
||||
if view_extent()
|
||||
&& let Some((base, width)) = buffer_extent(view)
|
||||
// (The console is lax: a view may begin past its buffer's end.)
|
||||
@@ -2074,6 +2140,80 @@ fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
|
||||
/// The host resource a slot made by [`make`] views, if any.
|
||||
type Kept = Option<ID3D12Resource>;
|
||||
|
||||
/// Whether a buffer view off its buffer's elements gets a copy of its own
|
||||
/// bytes (`VICTORY_VIEW_OWN_COPY=0`: it is refused and reads zeros, as
|
||||
/// before).
|
||||
fn own_copy_on() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_OWN_COPY").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// The title memory (start, bytes) of a buffer view that cannot be made on
|
||||
/// the host copy of its buffer: `count` elements of `element` bytes from
|
||||
/// element `first` of the buffer at `base`, which lies `offset` bytes into
|
||||
/// that copy, where `offset` is not a whole number of elements and the view
|
||||
/// cannot be a raw view of the same bytes either ([`raw_window`]:
|
||||
/// `unknown`, the view has no format, and `stride` is its structure's).
|
||||
/// The host counts a view's first element from its buffer's start, so such
|
||||
/// a view has no host view there; it is made on a copy of its own bytes
|
||||
/// (`crate::shadow::exact`), where it starts at element 0. `None`: the
|
||||
/// view is made on its buffer's copy, as every other.
|
||||
fn own_bytes(offset: u64, base: u64, first: u64, count: u32, element: u64, stride: u32, unknown: bool) -> Option<(u64, u64)> {
|
||||
own_bytes_if(own_copy_on(), offset, base, first, count, element, stride, unknown)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn own_bytes_if(
|
||||
on: bool,
|
||||
offset: u64,
|
||||
base: u64,
|
||||
first: u64,
|
||||
count: u32,
|
||||
element: u64,
|
||||
stride: u32,
|
||||
unknown: bool,
|
||||
) -> Option<(u64, u64)> {
|
||||
if !on || element == 0 || count == 0 || offset.is_multiple_of(element) {
|
||||
return None;
|
||||
}
|
||||
if unknown && raw_window(offset, first, count, stride).is_some() {
|
||||
return None;
|
||||
}
|
||||
let start = base.checked_add(first.checked_mul(element)?)?;
|
||||
Some((start, u64::from(count) * element))
|
||||
}
|
||||
|
||||
/// Of a buffer view: its first element, its elements, the bytes of one (a
|
||||
/// raw view's: 4), its structure's stride, and whether it has no format.
|
||||
/// As [`buffer_srv`] and [`buffer_uav`] read them from the same words.
|
||||
fn buffer_fields(view: &View) -> Option<(u64, u32, u64, u32, bool)> {
|
||||
const BUFFER: u32 = 1;
|
||||
let (words, unordered): (&[u32; 10], bool) = match view {
|
||||
View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false),
|
||||
View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true),
|
||||
View::Placed(unordered, resource, d) if resource[0] == BUFFER => (d[..10].try_into().ok()?, *unordered),
|
||||
_ => return None,
|
||||
};
|
||||
if unordered {
|
||||
let d = uav_desc(words);
|
||||
// SAFETY: a buffer view's union member.
|
||||
let b = unsafe { d.Anonymous.Buffer };
|
||||
let element = if b.StructureByteStride > 0 {
|
||||
u64::from(b.StructureByteStride)
|
||||
} else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
|
||||
4
|
||||
} else {
|
||||
crate::resource::element(d.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
|
||||
};
|
||||
Some((b.FirstElement, b.NumElements, element, b.StructureByteStride, d.Format == DXGI_FORMAT_UNKNOWN))
|
||||
} else {
|
||||
let d = srv_desc(words);
|
||||
// SAFETY: a buffer view's union member.
|
||||
let b = unsafe { d.Anonymous.Buffer };
|
||||
Some((b.FirstElement, b.NumElements, element_size(&d), b.StructureByteStride, d.Format == DXGI_FORMAT_UNKNOWN))
|
||||
}
|
||||
}
|
||||
|
||||
/// A structured buffer view (`first`, `count` elements of `stride` bytes,
|
||||
/// `offset` bytes into its host copy) as a raw view of the same bytes:
|
||||
/// its first dword and its dwords. Translated shaders read untyped buffers
|
||||
@@ -2140,6 +2280,22 @@ fn buffer_srv(
|
||||
) -> Option<Kept> {
|
||||
let shadow = crate::shadow::find(address, len)?;
|
||||
let offset = shadow.offset(address);
|
||||
// Off the elements of that copy: on a copy of its own bytes, from its
|
||||
// element 0 (`own_bytes`).
|
||||
let (shadow, offset) = {
|
||||
// SAFETY: a buffer view's union member.
|
||||
let b = unsafe { desc.Anonymous.Buffer };
|
||||
let unknown = desc.Format == DXGI_FORMAT_UNKNOWN;
|
||||
match own_bytes(offset, address, b.FirstElement, b.NumElements, element_size(&desc), b.StructureByteStride, unknown)
|
||||
.and_then(|(start, bytes)| crate::shadow::exact(start, bytes))
|
||||
{
|
||||
Some(own) => {
|
||||
desc.Anonymous.Buffer.FirstElement = 0;
|
||||
(own, 0)
|
||||
}
|
||||
None => (shadow, offset),
|
||||
}
|
||||
};
|
||||
// A structured view as a raw view of the same bytes (see `raw_window`).
|
||||
// SAFETY: a buffer view's union member.
|
||||
let structured = unsafe { desc.Anonymous.Buffer };
|
||||
@@ -2211,6 +2367,29 @@ fn buffer_uav(
|
||||
at: D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
) -> Option<Kept> {
|
||||
let shadow = crate::shadow::find(address, len)?;
|
||||
// Off the elements of that copy: on a copy of its own bytes, from its
|
||||
// element 0 (`own_bytes`).
|
||||
let (shadow, own) = {
|
||||
// SAFETY: a buffer view's union member.
|
||||
let b = unsafe { desc.Anonymous.Buffer };
|
||||
let element = if b.StructureByteStride > 0 {
|
||||
u64::from(b.StructureByteStride)
|
||||
} else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
|
||||
4
|
||||
} else {
|
||||
crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
|
||||
};
|
||||
let unknown = desc.Format == DXGI_FORMAT_UNKNOWN;
|
||||
match own_bytes(shadow.offset(address), address, b.FirstElement, b.NumElements, element, b.StructureByteStride, unknown)
|
||||
.and_then(|(start, bytes)| crate::shadow::exact(start, bytes))
|
||||
{
|
||||
Some(own) => {
|
||||
desc.Anonymous.Buffer.FirstElement = 0;
|
||||
(own, true)
|
||||
}
|
||||
None => (shadow, false),
|
||||
}
|
||||
};
|
||||
// SAFETY: a live buffer.
|
||||
let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
|
||||
if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
|
||||
@@ -2226,7 +2405,7 @@ fn buffer_uav(
|
||||
} else {
|
||||
crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
|
||||
};
|
||||
let offset = shadow.offset(address);
|
||||
let offset = if own { 0 } else { shadow.offset(address) };
|
||||
// A structured view as a raw view of the same bytes (see `raw_window`).
|
||||
let window = (desc.Format == DXGI_FORMAT_UNKNOWN)
|
||||
.then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride))
|
||||
@@ -3292,3 +3471,33 @@ mod tests {
|
||||
assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod own_copy_tests {
|
||||
use super::own_bytes_if;
|
||||
|
||||
/// A buffer view gets a copy of its own bytes only when it has no host
|
||||
/// view on its buffer's copy: off that copy's elements, and not a
|
||||
/// structured view that can be a raw view of the same bytes.
|
||||
#[test]
|
||||
fn a_view_off_its_copys_elements_gets_its_own_bytes() {
|
||||
let base = 0xd_9000_0000u64;
|
||||
// On an element: the buffer's copy (the two cases of every run's
|
||||
// log are the ones below).
|
||||
assert_eq!(own_bytes_if(true, 24, base, 3, 10, 12, 0, false), None);
|
||||
assert_eq!(own_bytes_if(true, 0, base, 0, 10, 12, 0, false), None);
|
||||
// A typed view of 12-byte elements, 5,222,240 bytes into its copy
|
||||
// (8 past an element): its own bytes, from its first element.
|
||||
assert_eq!(own_bytes_if(true, 5_222_240, base, 3, 10, 12, 0, false), Some((base + 36, 120)));
|
||||
// A structured view of 32-byte elements 8 bytes in: not on 16, so
|
||||
// no raw view of the copy either.
|
||||
assert_eq!(own_bytes_if(true, 8, base, 2, 4, 32, 32, true), Some((base + 64, 128)));
|
||||
// The same 16 bytes in: off its elements, but a raw view of the
|
||||
// copy's bytes does (as before).
|
||||
assert_eq!(own_bytes_if(true, 16, base, 2, 4, 32, 32, true), None);
|
||||
// No elements, no size, or the switch off: as before.
|
||||
assert_eq!(own_bytes_if(true, 8, base, 2, 0, 32, 32, true), None);
|
||||
assert_eq!(own_bytes_if(true, 8, base, 2, 4, 0, 0, false), None);
|
||||
assert_eq!(own_bytes_if(false, 8, base, 2, 4, 32, 32, true), None);
|
||||
}
|
||||
}
|
||||
@@ -1698,7 +1698,12 @@ impl State {
|
||||
// makes room again: so the slots are still looked at (the pass
|
||||
// returned here, and a slot whose texture had been streamed out
|
||||
// kept its host copy for as long as the card was full).
|
||||
let room = crate::resource::room();
|
||||
let mut room = crate::resource::room();
|
||||
// Bytes uploaded by this pass since the card was last asked
|
||||
// whether it has room: asked again every 32 MiB (a pass may upload
|
||||
// 192 MB and more, and one asking a pass let the queue run some
|
||||
// 400 MB past its line while the world loaded: run 193).
|
||||
let mut since_asked = 0u64;
|
||||
if !room {
|
||||
HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed);
|
||||
once!("textures picked by index: the card has no room for more; they wait");
|
||||
@@ -1962,6 +1967,11 @@ impl State {
|
||||
};
|
||||
crate::texture::unstage(resource);
|
||||
SPENT.fetch_add(bytes, Ordering::Relaxed);
|
||||
since_asked += bytes;
|
||||
if room && since_asked >= 32 << 20 {
|
||||
since_asked = 0;
|
||||
room = crate::resource::room();
|
||||
}
|
||||
HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed);
|
||||
HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed);
|
||||
match memory {
|
||||
|
||||
@@ -1270,6 +1270,11 @@ pub(crate) fn dred_on() -> bool {
|
||||
/// budget buffers, a run late).
|
||||
static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
|
||||
|
||||
/// Since the last frame line: the largest group count in x an indirect
|
||||
/// compute record asked for, and the records that asked for more than the
|
||||
/// 65,535 one dispatch runs (cut to that: the groups past it do not run).
|
||||
static COMPUTE_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
|
||||
|
||||
/// Whether each list of a submission runs and is timed on its own, slow
|
||||
/// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
|
||||
/// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
|
||||
@@ -3990,6 +3995,9 @@ impl Host {
|
||||
self.settle(&mut submitted, why);
|
||||
}
|
||||
}
|
||||
// Descriptors the title copied into placed heaps directly, before
|
||||
// command lists that index those slots are submitted.
|
||||
crate::descriptor::sync_heaps();
|
||||
let behind = late && flying();
|
||||
// Before this submission counts as started: what the sweep lets go
|
||||
// of is named by no list, and nothing runs now (behind flights the
|
||||
@@ -5116,7 +5124,12 @@ impl HostList {
|
||||
let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile());
|
||||
MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed);
|
||||
MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed);
|
||||
for k in 0..3 {
|
||||
// And of its indirect compute records: the largest x asked
|
||||
// for, and how many asked for more than a dispatch runs.
|
||||
let (widest, cut) = (words.add(3).read_volatile(), words.add(4).read_volatile());
|
||||
COMPUTE_GROUPS[0].fetch_max(u64::from(widest), Ordering::Relaxed);
|
||||
COMPUTE_GROUPS[1].fetch_add(u64::from(cut), Ordering::Relaxed);
|
||||
for k in 0..5 {
|
||||
words.add(k).write_volatile(0);
|
||||
}
|
||||
})));
|
||||
@@ -5799,6 +5812,13 @@ impl Meter {
|
||||
tracing::info!(
|
||||
"indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame"
|
||||
);
|
||||
let compute_widest = COMPUTE_GROUPS[0].swap(0, Ordering::Relaxed);
|
||||
let compute_cut = COMPUTE_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
|
||||
tracing::info!(
|
||||
"indirect compute dispatches: the largest group count in x asked for {compute_widest} (run: at most 65535), {compute_cut:.1} records per frame asked for more and were cut to that"
|
||||
);
|
||||
crate::shadow::exact_line(frames);
|
||||
crate::descriptor::sync_line(frames);
|
||||
late_line(frames);
|
||||
card_clock_line(frames, ms);
|
||||
crate::shadow::back_line(frames);
|
||||
@@ -5892,7 +5912,7 @@ impl Meter {
|
||||
let [kept, dropped, slots, uploaded] =
|
||||
[0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed));
|
||||
tracing::info!(
|
||||
"writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset counts, 1 acts, guards, slots, all)",
|
||||
"writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset or guards opens the guarded blocks, 0 counts only, 1, slots, all)",
|
||||
bytes >> 20,
|
||||
if mode & 1 != 0 { "opened, taken again" } else { "left as they were" },
|
||||
if mode & 4 != 0 { "told as well" } else { "counted only" },
|
||||
|
||||
@@ -74,7 +74,20 @@ void main(uint3 id : SV_DispatchThreadID) {
|
||||
cost = count * instances;
|
||||
draw_counts = uint2(count, instances);
|
||||
} else if (kind == 2) {
|
||||
uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u));
|
||||
uint3 asked = src_args.Load3(src_at);
|
||||
// Diagnostics, in the budget buffer's words after the mesh ones:
|
||||
// the largest x a compute record asked for, and the records that
|
||||
// asked for more groups in x than one dispatch runs (they are cut
|
||||
// to 65,535 below, so the groups past it never run). Not the
|
||||
// garbage of a slot nothing wrote.
|
||||
if (asked.x <= (1u << 24) && asked.y <= 64u && asked.z <= 64u) {
|
||||
uint noted;
|
||||
budget.InterlockedMax(12, asked.x, noted);
|
||||
if (asked.x > 65535u) {
|
||||
budget.InterlockedAdd(16, 1u, noted);
|
||||
}
|
||||
}
|
||||
uint3 g = min(asked, uint3(65535u, 65535u, 65535u));
|
||||
// x * y fits 32 bits; the whole count may not.
|
||||
if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
|
||||
g = uint3(0, 0, 0);
|
||||
|
||||
@@ -1433,12 +1433,48 @@ pub(crate) fn room() -> bool {
|
||||
}
|
||||
match crate::host::host().and_then(|h| h.video_memory()) {
|
||||
// What is kept for card copies of title buffers not made yet
|
||||
// counts as used (`crate::shadow::card_room_kept`; 0 by default).
|
||||
Some([budget, used, ..]) => used + crate::shadow::card_room_kept() < budget / 100 * room_percent(),
|
||||
// (`crate::shadow::card_room_kept`) and for the render targets a
|
||||
// world makes in its first frame ([`targets_room_kept`]) counts as
|
||||
// used.
|
||||
Some([budget, used, ..]) => {
|
||||
used + crate::shadow::card_room_kept() + targets_room_kept() < budget / 100 * room_percent()
|
||||
}
|
||||
None => filled < WITHOUT_BUDGET,
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of the card's memory the texture queue leaves free for
|
||||
/// render targets and other host copies the host itself writes that are
|
||||
/// not made yet: `VICTORY_CARD_ROOM_FOR_TARGETS_MB` (3,072; 0: none, as
|
||||
/// before) less what such copies hold now.
|
||||
///
|
||||
/// Measured (runs 193, 197, 198): 652 MB of them before the world, 2,255
|
||||
/// to 2,352 MB right after its first frame, 2,800 to 3,100 MB two minutes
|
||||
/// on, none of them idle (run 198's census). They are made with no room
|
||||
/// test, in the same frame as the card copies of title buffers (762 MB),
|
||||
/// after the texture queue has filled the card to its line with textures
|
||||
/// written while the world loaded (7.3 GB of them at the first world frame
|
||||
/// of run 193, of which 2.3 GB were let go again within 13 seconds). The
|
||||
/// card then stood at 99 to 100.5 % of its budget, buffer copies were
|
||||
/// turned down for good (31 of 95 made: the frame 355 ms where 95 give
|
||||
/// 238), and the queue was refused from the first world frame on. With
|
||||
/// their room kept, the queue stops that much earlier while the world
|
||||
/// loads and gets it back as the targets are made.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn targets_room_kept() -> u64 {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
|
||||
let most = *MOST.get_or_init(|| {
|
||||
std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_MB")
|
||||
.ok()
|
||||
.and_then(|v| v.trim().parse::<u64>().ok())
|
||||
.map_or(3072 << 20, |mb| mb.min(8192) << 20)
|
||||
});
|
||||
// Every host texture's bytes less those of the copies the title fills.
|
||||
let targets = HOST_TEXTURES[1].load(Relaxed).saturating_sub(KINDS[1].load(Relaxed));
|
||||
most.saturating_sub(targets)
|
||||
}
|
||||
|
||||
/// [`room`] as it was at most a tenth of a second ago, for a question
|
||||
/// asked of many textures a frame ([`room`] asks the system each time).
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -181,11 +181,27 @@ static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
|
||||
/// used, and a copy may be made up to nine tenths of the budget: the room
|
||||
/// it takes was kept for it. After the burst what is kept is what the
|
||||
/// burst left of the limit (87 MB of 1,024 in run 189).
|
||||
///
|
||||
/// On by default from the build after run 199
|
||||
/// (`VICTORY_CARD_ROOM_FOR_BUFFERS=0`: off, as before). Run 193 had it on and still made 31 copies of 95: the copies
|
||||
/// and the world's render targets (+1,603 MB) arrive in the same first
|
||||
/// world frame and raced for the 448 MB left under the line, and a copy
|
||||
/// turned down is not asked for again (`lookup` asks once), while its room
|
||||
/// went on being kept (616 MB to the end of the run). So now: the texture
|
||||
/// queue also keeps room for the targets (`resource::targets_room_kept`),
|
||||
/// a copy is made up to 97 hundredths of the budget (its room was kept),
|
||||
/// and the room of a copy turned down is given up ([`CARD_REFUSED`]).
|
||||
fn card_room_kept_on() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_some_and(|v| v == "1"))
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ROOM_FOR_BUFFERS").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// Title buffers big enough for a copy in the card's memory that were
|
||||
/// turned down for want of room, since the start, and their bytes: their
|
||||
/// copies stay in the PC's memory for as long as the title keeps the
|
||||
/// buffers, so no room is kept for them any more.
|
||||
static CARD_REFUSED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
|
||||
|
||||
/// The bytes of the card's memory the texture queue leaves free for card
|
||||
/// copies of title buffers not made yet ([`card_room_kept_on`]): 0 with
|
||||
/// the switch off or without card copies.
|
||||
@@ -193,7 +209,7 @@ pub(crate) fn card_room_kept() -> u64 {
|
||||
if !card_room_kept_on() || !cards() {
|
||||
return 0;
|
||||
}
|
||||
card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed))
|
||||
card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// The copies in the card's memory.
|
||||
@@ -248,10 +264,30 @@ fn card_for(size: u64) -> Option<ID3D12Resource> {
|
||||
// shrinks by the copies' bytes, at most `card_limits`' second number.
|
||||
// (With `card_room_kept_on` the texture queue kept this copy's room
|
||||
// free, and the copy may go up to the queue's own line.)
|
||||
let tenths = if card_room_kept_on() { 9 } else { 8 };
|
||||
let hundredths = if card_room_kept_on() { 97 } else { 80 };
|
||||
if let Some([budget, used, ..]) = host.video_memory()
|
||||
&& used + size > budget / 10 * tenths
|
||||
&& used + size > budget / 100 * hundredths
|
||||
{
|
||||
// Said, with the numbers it was decided by: run 193 made 31 copies
|
||||
// of 95 and no line named the others. The first 64, then every
|
||||
// 32nd.
|
||||
let n = CARD_REFUSED[0].fetch_add(1, Ordering::Relaxed) + 1;
|
||||
let bytes = CARD_REFUSED[1].fetch_add(size, Ordering::Relaxed) + size;
|
||||
if n <= 64 || n.is_multiple_of(32) {
|
||||
tracing::info!(
|
||||
"no card copy for a title buffer of {} KiB: the card has {} MB in use of a budget of {} MB and a copy is made up to \
|
||||
{} MB; the copies made hold {} MB of at most {} MB; {} buffers turned down so far ({} MB), frame {}",
|
||||
size >> 10,
|
||||
used >> 20,
|
||||
budget >> 20,
|
||||
(budget / 100 * hundredths) >> 20,
|
||||
CARD_BYTES[0].load(Ordering::Relaxed) >> 20,
|
||||
most >> 20,
|
||||
n,
|
||||
bytes >> 20,
|
||||
crate::frame::current()
|
||||
);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + size > most {
|
||||
@@ -3550,6 +3586,82 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Sha
|
||||
Some(shadow)
|
||||
}
|
||||
|
||||
/// Copies of single buffer views' own bytes ([`exact`]), by (start,
|
||||
/// bytes), each with the asking that last took it; and the askings so far.
|
||||
#[allow(clippy::type_complexity)]
|
||||
static EXACT: Mutex<(u64, BTreeMap<(u64, u64), (Arc<Shadow>, u64)>)> = Mutex::new((0, BTreeMap::new()));
|
||||
|
||||
/// Since the last frame line: askings for such copies, and copies made.
|
||||
static EXACT_STATS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
|
||||
|
||||
/// A copy of the title memory `[address, address + len)` that starts at
|
||||
/// `address` itself: for a buffer view whose bytes do not start on an
|
||||
/// element of the copy its buffer has (`descriptor/host.rs` `own_bytes`).
|
||||
/// A host view counts its first element from its buffer's start; a console
|
||||
/// view starts at any address, and the title places views at ring
|
||||
/// positions inside its big GPU heap. Such a view was refused and its slot
|
||||
/// read zeros ("buffer view not on an element of its host copy", in every
|
||||
/// run; upstream VIctory 86a5ed6 found its meshlet culling constants and
|
||||
/// colour-bake parameter blocks among them and gives each a copy of its
|
||||
/// own bytes, as here).
|
||||
///
|
||||
/// The copy is brought up to date and written back like any other (a list
|
||||
/// refreshes the copy its view's slot shows, `buffer_copy`). Kept by
|
||||
/// (start, bytes) for as long as a list or a slot holds it; of the others,
|
||||
/// those not asked for lately go once there are many (ring positions
|
||||
/// change every frame).
|
||||
pub(crate) fn exact(address: u64, len: u64) -> Option<Arc<Shadow>> {
|
||||
/// Copies kept before the idle ones are looked for, and the askings an
|
||||
/// idle one stays for.
|
||||
const MANY: usize = 256;
|
||||
const LATELY: u64 = 512;
|
||||
if len == 0 {
|
||||
return None;
|
||||
}
|
||||
EXACT_STATS[0].fetch_add(1, Ordering::Relaxed);
|
||||
let mut guard = EXACT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (tick, map) = &mut *guard;
|
||||
*tick += 1;
|
||||
let now = *tick;
|
||||
if let Some((shadow, used)) = map.get_mut(&(address, len)) {
|
||||
*used = now;
|
||||
shadow.used.store(crate::host::moment(), Ordering::Relaxed);
|
||||
return Some(shadow.clone());
|
||||
}
|
||||
if map.len() >= MANY {
|
||||
// Held by the map alone (no list), its buffer by the copy alone (no
|
||||
// slot shows it), and not asked for lately.
|
||||
map.retain(|_, (shadow, used)| {
|
||||
Arc::strong_count(shadow) > 1 || crate::host::references(&shadow.buffer) > 1 || *used + LATELY > now
|
||||
});
|
||||
}
|
||||
let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(256))?;
|
||||
crate::host::name(&buffer, || format!("title view {address:#x}+{len:#x}"));
|
||||
// SAFETY: a live buffer.
|
||||
let gpu = unsafe { buffer.GetGPUVirtualAddress() };
|
||||
let shadow = Arc::new(Shadow::new(buffer, data, gpu, address, len));
|
||||
map.insert((address, len), (shadow.clone(), now));
|
||||
EXACT_STATS[1].fetch_add(1, Ordering::Relaxed);
|
||||
Some(shadow)
|
||||
}
|
||||
|
||||
/// With the frame line: the buffer views that got a copy of their own
|
||||
/// bytes ([`exact`]), per frame over `frames`, and the copies kept now.
|
||||
/// Nothing while there are none.
|
||||
pub(crate) fn exact_line(frames: f64) {
|
||||
let [asked, made] = [0, 1].map(|i| EXACT_STATS[i].swap(0, Ordering::Relaxed));
|
||||
if asked == 0 {
|
||||
return;
|
||||
}
|
||||
let kept = EXACT.lock().unwrap_or_else(|e| e.into_inner()).1.len();
|
||||
tracing::info!(
|
||||
"buffer views off their copy's elements (they were refused and read zeros; VICTORY_VIEW_OWN_COPY=0 refuses them again): \
|
||||
{:.1} asked for per frame, {:.1} copies of their own bytes made per frame, {kept} kept",
|
||||
asked as f64 / frames,
|
||||
made as f64 / frames
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod window_tests {
|
||||
use super::{WINDOW, cover, grid, holder, longest_tail, tail_of, window_of};
|
||||
|
||||
+200
-32
@@ -105,18 +105,19 @@ pub(crate) fn wanted() -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_floor(value: Option<&str>) -> u64 {
|
||||
value
|
||||
.and_then(|v| v.trim().parse::<u64>().ok())
|
||||
.map_or(1 << 20, |kb| kb.max(64).saturating_mul(1024))
|
||||
}
|
||||
|
||||
/// The bytes from which a texture is made this way: a megabyte, or
|
||||
/// `VICTORY_LEVELS_MIN_KB`. (The accounting of run 189: the levels not
|
||||
/// held are 1.9 MB a copy on some 1,600 copies; a 512x512 texture has six
|
||||
/// tiles at most, and most of the calls for nothing.)
|
||||
pub(crate) fn floor() -> u64 {
|
||||
static BYTES: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
|
||||
*BYTES.get_or_init(|| {
|
||||
std::env::var("VICTORY_LEVELS_MIN_KB")
|
||||
.ok()
|
||||
.and_then(|v| v.trim().parse::<u64>().ok())
|
||||
.map_or(1 << 20, |kb| kb.max(64) << 10)
|
||||
})
|
||||
*BYTES.get_or_init(|| parse_floor(std::env::var("VICTORY_LEVELS_MIN_KB").ok().as_deref()))
|
||||
}
|
||||
|
||||
/// The bytes of the tiles given to textures now: the card's memory they
|
||||
@@ -304,14 +305,18 @@ impl Tiled {
|
||||
}
|
||||
let mut standard = Vec::with_capacity(standard_levels as usize);
|
||||
for tiling in &tilings[..standard_levels as usize] {
|
||||
let tiles = tiling.WidthInTiles * u32::from(tiling.HeightInTiles) * u32::from(tiling.DepthInTiles);
|
||||
let tiles = tiling
|
||||
.WidthInTiles
|
||||
.checked_mul(u32::from(tiling.HeightInTiles))
|
||||
.and_then(|n| n.checked_mul(u32::from(tiling.DepthInTiles)))
|
||||
.unwrap_or(0);
|
||||
if tiles == 0 || tiles > HEAP_TILES || tiling.StartTileIndexInOverallResource == D3D12_PACKED_TILE {
|
||||
return None;
|
||||
}
|
||||
standard.push(tiles);
|
||||
}
|
||||
let packed_tiles = if packed.NumPackedMips > 0 { packed.NumTilesForPackedMips } else { 0 };
|
||||
if packed_tiles > HEAP_TILES {
|
||||
if (packed.NumPackedMips > 0 && packed_tiles == 0) || packed_tiles > HEAP_TILES {
|
||||
return None;
|
||||
}
|
||||
let full = u64::from(total) * TILE;
|
||||
@@ -366,13 +371,16 @@ impl Tiled {
|
||||
held: u32,
|
||||
room: bool,
|
||||
) -> (bool, bool) {
|
||||
let held = held & self.every_level();
|
||||
let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.held.store(held, Ordering::Relaxed);
|
||||
let card = self.card.load(Ordering::Relaxed);
|
||||
let named = held | card;
|
||||
// The levels the card itself writes are few and are not kept
|
||||
// waiting: a write of the card's into no memory is lost.
|
||||
let changed = self.give_on(queue, device, texture, named, if room { named } else { card });
|
||||
(changed, self.without(named) != 0)
|
||||
let changed = self.give_locked(&mut given, queue, device, texture, named, if room { named } else { card });
|
||||
let missing = self.without_locked(&given, named) != 0;
|
||||
(changed, missing)
|
||||
}
|
||||
|
||||
/// At the submission of a list in which the card itself writes the
|
||||
@@ -397,12 +405,25 @@ impl Tiled {
|
||||
texture: &ID3D12Resource,
|
||||
levels: u32,
|
||||
) -> bool {
|
||||
let card = self.card.fetch_or(levels, Ordering::Relaxed) | levels;
|
||||
let changed = self.give_on(queue, device, texture, card | self.held.load(Ordering::Relaxed), levels);
|
||||
// A level that got no tiles (no heap could be had): the list's
|
||||
// zeros and its write went nowhere, so the next list that writes
|
||||
// the level sends its zeros again.
|
||||
let without = self.without(levels);
|
||||
let levels = levels & self.every_level();
|
||||
let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let prev = self.card.load(Ordering::Relaxed);
|
||||
let changed = self.give_locked(
|
||||
&mut given,
|
||||
queue,
|
||||
device,
|
||||
texture,
|
||||
prev | levels | self.held.load(Ordering::Relaxed),
|
||||
levels,
|
||||
);
|
||||
// Only levels that actually received tiles (or already had them) saw
|
||||
// the card's write; a level that got no tiles saw its zeros and write
|
||||
// dropped, so neither `card` nor `claimed` should keep it.
|
||||
let without = self.without_locked(&given, levels);
|
||||
let backed = levels & !without;
|
||||
if backed != 0 {
|
||||
self.card.fetch_or(backed, Ordering::Relaxed);
|
||||
}
|
||||
if without != 0 {
|
||||
self.unclaim(without);
|
||||
}
|
||||
@@ -446,6 +467,10 @@ impl Tiled {
|
||||
/// Of `levels` (a bit a level), the ones that have no tiles now.
|
||||
pub(crate) fn without(&self, levels: u32) -> u32 {
|
||||
let given = self.given.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.without_locked(&given, levels)
|
||||
}
|
||||
|
||||
fn without_locked(&self, given: &Given, levels: u32) -> u32 {
|
||||
let first_packed = self.standard.len() as u32;
|
||||
let mut without = 0;
|
||||
for level in 0..self.levels.min(32) {
|
||||
@@ -469,6 +494,7 @@ impl Tiled {
|
||||
/// Returns whether the first level a view may show changed
|
||||
/// ([`Tiled::first_shown`]): the caller has the texture's slots made
|
||||
/// again.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn give_on(
|
||||
&self,
|
||||
queue: &ID3D12CommandQueue,
|
||||
@@ -476,10 +502,22 @@ impl Tiled {
|
||||
texture: &ID3D12Resource,
|
||||
named: u32,
|
||||
may: u32,
|
||||
) -> bool {
|
||||
let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.give_locked(&mut given, queue, device, texture, named, may)
|
||||
}
|
||||
|
||||
fn give_locked(
|
||||
&self,
|
||||
given: &mut Given,
|
||||
queue: &ID3D12CommandQueue,
|
||||
device: &ID3D12Device,
|
||||
texture: &ID3D12Resource,
|
||||
named: u32,
|
||||
may: u32,
|
||||
) -> bool {
|
||||
let has = |level: u32| level < 32 && named & (1 << level) != 0;
|
||||
let now = |level: u32| level < 32 && named & may & (1 << level) != 0;
|
||||
let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let first_packed = self.standard.len() as u32;
|
||||
// (subresource, tiles, the level if it has tiles of its own) to map now.
|
||||
let mut wanted: Vec<(u32, u32, Option<usize>)> = Vec::new();
|
||||
@@ -607,24 +645,40 @@ impl Drop for Tiled {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps a two-dimensional shader view from the levels before `first` of a
|
||||
/// texture of `levels` levels: it starts at `first` if it started before
|
||||
/// it, and shows as many levels fewer. A sample then lands on the first
|
||||
/// level that has memory instead of reading zeros from one that has none;
|
||||
/// level numbers and sizes a shader asks for count from that level.
|
||||
/// Keeps a two-dimensional shader view (2D or 2D array) from the levels
|
||||
/// before `first` of a texture of `levels` levels: it starts at `first` if
|
||||
/// it started before it, shows as many levels fewer (clamped to the
|
||||
/// remaining levels), and reduces `ResourceMinLODClamp` by the same shift so
|
||||
/// the effective minimum LOD stays at the same resource level.
|
||||
pub(crate) fn show_from(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, first: u32, levels: u32) {
|
||||
if desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D || first >= levels {
|
||||
if first >= levels {
|
||||
return;
|
||||
}
|
||||
// SAFETY: a 2D view's member of the union.
|
||||
let view = unsafe { &mut desc.Anonymous.Texture2D };
|
||||
if first <= view.MostDetailedMip {
|
||||
return;
|
||||
}
|
||||
let fewer = first - view.MostDetailedMip;
|
||||
view.MostDetailedMip = first;
|
||||
if view.MipLevels != u32::MAX {
|
||||
view.MipLevels = view.MipLevels.saturating_sub(fewer).max(1);
|
||||
let clamp = |most: &mut u32, mips: &mut u32, min_lod: &mut f32| {
|
||||
if first <= *most {
|
||||
return;
|
||||
}
|
||||
let fewer = first - *most;
|
||||
*most = first;
|
||||
if *mips != u32::MAX {
|
||||
*mips = mips.saturating_sub(fewer).clamp(1, levels - first);
|
||||
}
|
||||
if *min_lod > 0.0 {
|
||||
*min_lod = (*min_lod - fewer as f32).max(0.0);
|
||||
}
|
||||
};
|
||||
match desc.ViewDimension {
|
||||
D3D12_SRV_DIMENSION_TEXTURE2D => {
|
||||
// SAFETY: `ViewDimension` selects `Texture2D`.
|
||||
let view = unsafe { &mut desc.Anonymous.Texture2D };
|
||||
clamp(&mut view.MostDetailedMip, &mut view.MipLevels, &mut view.ResourceMinLODClamp);
|
||||
}
|
||||
D3D12_SRV_DIMENSION_TEXTURE2DARRAY => {
|
||||
// SAFETY: `ViewDimension` selects `Texture2DArray`.
|
||||
let view = unsafe { &mut desc.Anonymous.Texture2DArray };
|
||||
clamp(&mut view.MostDetailedMip, &mut view.MipLevels, &mut view.ResourceMinLODClamp);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1416,4 +1470,118 @@ void look() {
|
||||
s[8]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floor_saturates_instead_of_wrapping() {
|
||||
assert_eq!(parse_floor(None), 1 << 20);
|
||||
assert_eq!(parse_floor(Some("0")), 64 << 10);
|
||||
assert_eq!(parse_floor(Some("2048")), 2048 << 10);
|
||||
assert_eq!(parse_floor(Some(&(1u64 << 54).to_string())), u64::MAX);
|
||||
assert_eq!(parse_floor(Some(&u64::MAX.to_string())), u64::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_from_clamps_2d_and_2d_array_and_adjusts_min_lod() {
|
||||
let mut srv2d = D3D12_SHADER_RESOURCE_VIEW_DESC {
|
||||
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
|
||||
Shader4ComponentMapping: 5768,
|
||||
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
|
||||
Texture2D: D3D12_TEX2D_SRV {
|
||||
MostDetailedMip: 0,
|
||||
MipLevels: 12,
|
||||
PlaneSlice: 0,
|
||||
ResourceMinLODClamp: 3.5,
|
||||
},
|
||||
},
|
||||
};
|
||||
show_from(&mut srv2d, 3, 11);
|
||||
// SAFETY: `ViewDimension` is `TEXTURE2D`.
|
||||
let v2d = unsafe { srv2d.Anonymous.Texture2D };
|
||||
assert_eq!(v2d.MostDetailedMip, 3);
|
||||
// Clamped to remaining levels (11 - 3 = 8), not 12 - 3 = 9.
|
||||
assert_eq!(v2d.MipLevels, 8);
|
||||
assert_eq!(v2d.ResourceMinLODClamp, 0.5);
|
||||
|
||||
let mut srv_arr = D3D12_SHADER_RESOURCE_VIEW_DESC {
|
||||
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY,
|
||||
Shader4ComponentMapping: 5768,
|
||||
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
|
||||
Texture2DArray: D3D12_TEX2D_ARRAY_SRV {
|
||||
MostDetailedMip: 0,
|
||||
MipLevels: 6,
|
||||
FirstArraySlice: 0,
|
||||
ArraySize: 1,
|
||||
PlaneSlice: 0,
|
||||
ResourceMinLODClamp: 1.5,
|
||||
},
|
||||
},
|
||||
};
|
||||
show_from(&mut srv_arr, 2, 11);
|
||||
// SAFETY: `ViewDimension` is `TEXTURE2DARRAY`.
|
||||
let varr = unsafe { srv_arr.Anonymous.Texture2DArray };
|
||||
assert_eq!(varr.MostDetailedMip, 2);
|
||||
assert_eq!(varr.MipLevels, 4);
|
||||
assert_eq!(varr.ResourceMinLODClamp, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn card_wrote_failure_does_not_poison_card_mask() {
|
||||
let Some(host) = host() else {
|
||||
return;
|
||||
};
|
||||
// A dummy live resource (never mapped because `take()` rejects `HEAP_TILES + 1`).
|
||||
let heap = D3D12_HEAP_PROPERTIES {
|
||||
Type: D3D12_HEAP_TYPE_DEFAULT,
|
||||
..Default::default()
|
||||
};
|
||||
let desc = Rig::desc(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 2, false);
|
||||
let mut tex: Option<ID3D12Resource> = None;
|
||||
// SAFETY: plain texture creation on the host device.
|
||||
unsafe {
|
||||
host.device
|
||||
.CreateCommittedResource(
|
||||
&heap,
|
||||
D3D12_HEAP_FLAG_NONE,
|
||||
&desc,
|
||||
D3D12_RESOURCE_STATE_COMMON,
|
||||
None,
|
||||
&mut tex,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let tex = tex.unwrap();
|
||||
STATS[0].fetch_add(1, Ordering::Relaxed);
|
||||
STATS[1].fetch_add(TILE, Ordering::Relaxed);
|
||||
let mut tiled = Tiled {
|
||||
// Level 0 demands > HEAP_TILES so `take()` fails deterministically.
|
||||
standard: vec![HEAP_TILES + 1, 1],
|
||||
packed: 0,
|
||||
levels: 2,
|
||||
full: TILE,
|
||||
given: Mutex::new(Given {
|
||||
levels: vec![false, false],
|
||||
packed: false,
|
||||
runs: Vec::new(),
|
||||
}),
|
||||
shown: AtomicU32::new(u32::MAX),
|
||||
held: AtomicU32::new(0),
|
||||
card: AtomicU32::new(0),
|
||||
claimed: AtomicU32::new(0),
|
||||
};
|
||||
assert_eq!(tiled.claim(1 << 0), 1 << 0);
|
||||
let changed = tiled.card_wrote_on(host.queue(), &host.device, &tex, 1 << 0);
|
||||
assert!(!changed);
|
||||
assert_eq!(tiled.card.load(Ordering::Relaxed), 0, "failed tile allocation must not poison `card`");
|
||||
assert_eq!(tiled.first_shown(), None);
|
||||
assert_eq!(tiled.claim(1 << 0), 1 << 0, "failed level must be unclaimed");
|
||||
// Even if level 0 later becomes allocatable, an upload with `room == false`
|
||||
// that does not hold level 0 must not treat level 0 as card-owned.
|
||||
tiled.standard[0] = 1;
|
||||
let (changed, waiting) = tiled.uploaded_on(host.queue(), &host.device, &tex, 1 << 1, false);
|
||||
assert!(!changed && waiting);
|
||||
assert!(!tiled.has_tiles(0));
|
||||
assert_eq!(tiled.given_bytes(), 0);
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,27 @@ pub(crate) const PAGE: usize = 64 << 10;
|
||||
/// The kernel's page, the unit of its answers.
|
||||
const KERNEL_PAGE: usize = 4096;
|
||||
|
||||
/// A title-memory range whose changed pages another subsystem needs to read.
|
||||
pub(crate) struct Tracked {
|
||||
start: usize,
|
||||
end: usize,
|
||||
seen: Mutex<BTreeMap<usize, u64>>,
|
||||
}
|
||||
|
||||
/// Tracks a runtime GPU-memory range, including physical-page views when
|
||||
/// `views` is true. Other process memory is not tracked.
|
||||
pub(crate) fn track(start: usize, len: usize, views: bool) -> Option<Tracked> {
|
||||
let end = start.checked_add(len)?;
|
||||
if len == 0 || writes(start, end, views).is_none() {
|
||||
return None;
|
||||
}
|
||||
Some(Tracked {
|
||||
start,
|
||||
end,
|
||||
seen: Mutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
struct Journal {
|
||||
/// Numbers the askings; 0 is "never".
|
||||
asked: u64,
|
||||
@@ -377,6 +398,42 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve
|
||||
))
|
||||
}
|
||||
|
||||
impl Tracked {
|
||||
/// Takes changed pages of `[from, to)`, cut to the tracked range. A
|
||||
/// partial page stays changed so a later take can read its other bytes.
|
||||
pub(crate) fn take(&self, from: usize, to: usize) -> Vec<(usize, usize)> {
|
||||
let (from, to) = (from.max(self.start), to.min(self.end));
|
||||
if from >= to {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some((_, pages)) = writes(from, to, true) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut ranges: Vec<(usize, usize)> = Vec::new();
|
||||
for (page, write) in pages {
|
||||
if seen.get(&page).is_some_and(|&last| last >= write) {
|
||||
continue;
|
||||
}
|
||||
let (start, end) = ((page * PAGE).max(from), ((page + 1) * PAGE).min(to));
|
||||
if start >= end {
|
||||
continue;
|
||||
}
|
||||
// Keep partial pages dirty: the caller has not taken the rest.
|
||||
if (page * PAGE).max(self.start) >= from
|
||||
&& ((page + 1) * PAGE).min(self.end) <= to
|
||||
{
|
||||
seen.insert(page, write);
|
||||
}
|
||||
match ranges.last_mut() {
|
||||
Some((_, last)) if *last == start => *last = end,
|
||||
_ => ranges.push((start, end)),
|
||||
}
|
||||
}
|
||||
ranges
|
||||
}
|
||||
}
|
||||
|
||||
/// Guarded blocks of view memory.
|
||||
const BLOCK: usize = PAGE;
|
||||
|
||||
@@ -698,16 +755,22 @@ pub fn writing(at: usize, len: usize) {
|
||||
/// copies of buffers and textures read through tables take them again);
|
||||
/// 2, the placed textures picked by index that lie under it are due again;
|
||||
/// 4, both also for reads to plain addresses when they have finished.
|
||||
/// Unset or `0`: nothing, counted only. `1`: bits 1 and 2. `guards`: bit 1
|
||||
/// alone. `slots`: bit 2 alone. `all`: everything.
|
||||
/// Unset or `guards`: bit 1 alone. `0`: nothing, counted only (the default
|
||||
/// until run 199). `1`: bits 1 and 2. `slots`: bit 2 alone. `all`:
|
||||
/// everything.
|
||||
/// (Bit 1 by default: in every run 10,000 to 50,000 guarded blocks of host
|
||||
/// copies lay under such writes and kept the bytes from before; runs 197
|
||||
/// and 198 opened them, 9,766 and 10,796 blocks, with nothing worse for
|
||||
/// it. Bit 2 makes texture slots due and is the one that flooded the
|
||||
/// queue in an earlier form: still asked for by name.)
|
||||
pub(crate) fn page_writes() -> u8 {
|
||||
static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
|
||||
*MODE.get_or_init(|| match std::env::var("VICTORY_PAGE_WRITES").as_deref().map(str::trim) {
|
||||
Ok("0") => 0,
|
||||
Ok("1") => 3,
|
||||
Ok("guards") => 1,
|
||||
Ok("slots") => 2,
|
||||
Ok("all") => 7,
|
||||
_ => 0,
|
||||
_ => 1,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1016,6 +1016,26 @@ fn own_bits_on() -> bool {
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// The refusal of a first half of an interpolation whose result is read
|
||||
/// as data ([`Lower::interp`]).
|
||||
pub(super) const FIRST_HALF: &str = "the first half of an interpolation";
|
||||
|
||||
thread_local! {
|
||||
/// Whether first halves of interpolations are evaluated as the pair
|
||||
/// they start ([`with_first_half_pairs`]).
|
||||
static FIRST_HALF_PAIRS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Runs `translate` with first halves of interpolations evaluated as the
|
||||
/// pair they start: the translation of a program refused with
|
||||
/// [`FIRST_HALF`] (`VICTORY_FIRST_HALF=0`: refused again, as before).
|
||||
pub(super) fn with_first_half_pairs<R>(translate: impl FnOnce() -> R) -> R {
|
||||
let before = FIRST_HALF_PAIRS.replace(true);
|
||||
let result = translate();
|
||||
FIRST_HALF_PAIRS.set(before);
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn host_max_wave() -> u32 {
|
||||
#[cfg(test)]
|
||||
if let Some(lanes) = TEST_HOST_WAVE.get() {
|
||||
@@ -1497,7 +1517,9 @@ impl<'a> Lower<'a> {
|
||||
// the other half of its dst, PS_DeferredTextured): evaluated as the pair it
|
||||
// starts. Approximate for those other bits (P0 + i P10 on the console); a
|
||||
// first half only the second half reads is gone before lowering.
|
||||
if std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") {
|
||||
// Only in the second translation of a program the first
|
||||
// one refused for it ([`with_first_half_pairs`]).
|
||||
if FIRST_HALF_PAIRS.get() && std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") {
|
||||
for (_, i) in &x.io.interps {
|
||||
if let Interp::Interpolated { first, .. } = i {
|
||||
for s in first {
|
||||
@@ -2083,8 +2105,9 @@ impl<'a> Lower<'a> {
|
||||
if !every {
|
||||
if halves {
|
||||
need(self.cur_ir);
|
||||
return Err(WHERE);
|
||||
}
|
||||
return Err(WHERE);
|
||||
return Ok(self.half_sum_present(x));
|
||||
}
|
||||
let c = self.cur;
|
||||
let i32t = self.s.t.i32;
|
||||
@@ -2112,6 +2135,61 @@ impl<'a> Lower<'a> {
|
||||
Ok(self.s.m.bin(c, Bin::Or, first, total))
|
||||
}
|
||||
|
||||
/// [`Self::half_sum`] in one host wave of 64 where some lanes have left (a thread past
|
||||
/// the end of the data returns early): the console runs the sum in every lane, a lane
|
||||
/// outside EXEC with +0, so after step k every lane of an aligned run of 2^k lanes holds
|
||||
/// that run's partial sum, the lanes that left included. A lane reads its partner run's
|
||||
/// sum from the first lane of that run that is here, and +0 where none is (every lane of
|
||||
/// the run left, so its terms were all +0). Lane 0's high half likewise: 0 if it left.
|
||||
fn half_sum_present(&mut self, x: V) -> V {
|
||||
let c = self.cur;
|
||||
let i32t = self.s.t.i32;
|
||||
self.s.flags |= flags::WAVE_OPS;
|
||||
let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]);
|
||||
let here = self.s.m.bool(true);
|
||||
let ballot = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[here]);
|
||||
let (blo, bhi) = (self.s.m.extract(c, ballot, 0), self.s.m.extract(c, ballot, 1));
|
||||
let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
|
||||
let [zero, k31, k32] = [0, 31, 32].map(|k| self.s.m.i32(k));
|
||||
// The lanes of the run of `size` lanes at `base` that are here, from bit 0.
|
||||
let present = |l: &mut Self, base: V, size: u32| -> V {
|
||||
let upper = l.s.m.cmp(c, pred::IUGE, base, k32);
|
||||
let word = l.s.m.select(c, upper, bhi, blo);
|
||||
let at = l.s.m.bin(c, Bin::And, base, k31);
|
||||
let bits = l.s.m.bin(c, Bin::LShr, word, at);
|
||||
if size >= 32 {
|
||||
bits
|
||||
} else {
|
||||
let m = l.s.m.i32((1u32 << size) - 1);
|
||||
l.s.m.bin(c, Bin::And, bits, m)
|
||||
}
|
||||
};
|
||||
let mut sum = x;
|
||||
for step in 0..6u32 {
|
||||
let size = 1u32 << step;
|
||||
let (bit, run) = (self.s.m.i32(size), self.s.m.i32(!(size - 1)));
|
||||
let other = self.s.m.bin(c, Bin::Xor, lane, bit);
|
||||
let base = self.s.m.bin(c, Bin::And, other, run);
|
||||
let bits = present(self, base, size);
|
||||
// FirstbitLo (dx.op 32): the run's first lane that is here
|
||||
let first = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[bits]);
|
||||
let any = self.s.m.cmp(c, pred::NE, bits, zero);
|
||||
let first = self.s.m.select(c, any, first, zero);
|
||||
let from = self.s.m.bin(c, Bin::Add, base, first);
|
||||
let theirs = self.read_lane(sum, from);
|
||||
let theirs = self.s.m.select(c, any, theirs, zero);
|
||||
sum = self.add_halves(sum, theirs);
|
||||
}
|
||||
let (high, low, one) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(1));
|
||||
let lane0 = self.s.m.bin(c, Bin::And, blo, one);
|
||||
let lane0 = self.s.m.cmp(c, pred::NE, lane0, zero);
|
||||
let first = self.read_lane(x, zero);
|
||||
let first = self.s.m.select(c, lane0, first, zero);
|
||||
let first = self.s.m.bin(c, Bin::And, first, high);
|
||||
let sum = self.s.m.bin(c, Bin::And, sum, low);
|
||||
self.s.m.bin(c, Bin::Or, first, sum)
|
||||
}
|
||||
|
||||
fn run(mut self) -> Result<Lowered, Stop> {
|
||||
let p = self.x.p;
|
||||
let order = crate::ir::reverse_postorder(&p.blocks);
|
||||
@@ -5617,6 +5695,18 @@ impl<'a> Lower<'a> {
|
||||
.find_map(|(s, _)| use_of(*s))
|
||||
};
|
||||
let use_at = use_of(site).or_else(twin);
|
||||
// A descriptor nothing uses as one, whose size the code reads all the same (a
|
||||
// texture picked from the heap by an index in a constant buffer, its width and
|
||||
// height turned into a texel size; a buffer tested for being empty by its record
|
||||
// count): the kind from its dwords and its used-resource entry.
|
||||
let unused = if use_at.is_none() {
|
||||
self.unused_descriptor_kind(inst, site, code, count)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (first, props, image, uav, used) = if let Some(kind) = unused {
|
||||
kind
|
||||
} else {
|
||||
let Some((at, first)) = use_at 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
|
||||
@@ -5726,6 +5816,9 @@ impl<'a> Lower<'a> {
|
||||
}
|
||||
_ => return Err("a scalar memory read as data"),
|
||||
};
|
||||
(first, props, image, uav, used)
|
||||
};
|
||||
let src = Source::Loaded { load: site, first };
|
||||
let h = self.handle(site, &src, false, props)?;
|
||||
let c = self.cur;
|
||||
let i32t = self.s.t.i32;
|
||||
@@ -5793,8 +5886,10 @@ impl<'a> Lower<'a> {
|
||||
inst.write(Reg::S(code + first + k))
|
||||
.is_some_and(|v| self.computed_with(v, 6))
|
||||
});
|
||||
// (A descriptor nothing uses as one gets it whenever the host can tell it, as
|
||||
// a buffer whose address alone is read does.)
|
||||
if first == 0
|
||||
&& computed
|
||||
&& (computed || unused.is_some())
|
||||
&& let Some((lo, hi)) = self.view_address(site)
|
||||
{
|
||||
words.extend([(0, lo), (1, hi)]);
|
||||
@@ -5817,6 +5912,67 @@ impl<'a> Lower<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What [`Self::descriptor_data`] makes of a descriptor load that nothing uses as a
|
||||
/// descriptor but whose dwords the code reads: the first dword, the handle properties,
|
||||
/// the image kind (none for a buffer), whether it is an unordered view, and its
|
||||
/// used-resource entry. An image's eight dwords read as a 2D texture's, a buffer's four
|
||||
/// as a raw view's where the code reads its record count (dword 2); none for anything
|
||||
/// else (a constant buffer, a sampler, a buffer whose address alone is read).
|
||||
// shortcut: an image whose kind nothing tells is taken for a 2D texture (the title's
|
||||
// reads are texel sizes of 2D textures: puddle masks, shadow masks); a host view of
|
||||
// another kind would answer its own sizes.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn unused_descriptor_kind(
|
||||
&self,
|
||||
inst: &Inst,
|
||||
site: Site,
|
||||
code: u8,
|
||||
count: u32,
|
||||
) -> Option<(u8, (u32, u32), Option<u32>, bool, Option<&'a UsedResource>)> {
|
||||
// Kept per lane and compared (`Resources::lane_copied`), or a sampler's: the cases
|
||||
// `descriptor_data` handles on their own.
|
||||
if self.x.res.lane_copied.contains(&site)
|
||||
|| self.x.res.descriptors.iter().any(|d| {
|
||||
d.role == Role::Sampler
|
||||
&& d.source.leaves().into_iter().any(
|
||||
|l| matches!(*l, Source::Loaded { load, .. } if load == site),
|
||||
)
|
||||
})
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let used = self.used_kind(&Source::Loaded {
|
||||
load: site,
|
||||
first: 0,
|
||||
});
|
||||
if used.is_some_and(|u| !matches!(u.kind, ResourceType::Srv | ResourceType::Uav)) {
|
||||
return None;
|
||||
}
|
||||
let read = |k: u32| {
|
||||
inst.write(Reg::S(code + k as u8)).is_some_and(|v| {
|
||||
self.x
|
||||
.p
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|b| &b.insts)
|
||||
.any(|i| i.reads.iter().any(|r| r.1 == v))
|
||||
})
|
||||
};
|
||||
let uav = used.is_some_and(|u| u.kind == ResourceType::Uav);
|
||||
let u = if uav { 0x1000 } else { 0 };
|
||||
match count {
|
||||
// width (dwords 1-2), height (2), levels (3), depth (4)
|
||||
8 if (1..5).any(read) && used.is_none_or(|u| u.dwords == 8) => {
|
||||
Some((0, (2 | u, 0x409), Some(2), uav, used))
|
||||
}
|
||||
// the record count
|
||||
4 if read(2) && used.is_none_or(|u| u.dwords == 4) => {
|
||||
Some((0, (11 | u, 0), None, uav, used))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `s_load_dword*` from the program's constant table.
|
||||
fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> {
|
||||
let Fields::Smem {
|
||||
@@ -7115,12 +7271,6 @@ impl<'a> Lower<'a> {
|
||||
let r = self.read_lane(x, from);
|
||||
int(self, r)
|
||||
}
|
||||
"v_cvt_f32_f64" => {
|
||||
let (lo, hi) = self.f64_pair(inst, 0)?;
|
||||
let bits = self.f64_to_f32_bits(lo, hi);
|
||||
let r = self.as_float(bits);
|
||||
float(self, r)
|
||||
}
|
||||
"v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1"
|
||||
| "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => {
|
||||
let mut a = s(self, 0)?;
|
||||
@@ -7138,6 +7288,12 @@ impl<'a> Lower<'a> {
|
||||
let r = self.s.m.cast(c, op, a, self.s.t.f32);
|
||||
float(self, r)
|
||||
}
|
||||
"v_cvt_f32_f64" => {
|
||||
let (lo, hi) = self.f64_pair(inst, 0)?;
|
||||
let bits = self.f64_to_f32_bits(lo, hi);
|
||||
let r = self.as_float(bits);
|
||||
float(self, r)
|
||||
}
|
||||
"v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => {
|
||||
// Each source is f32, or with op_sel_hi the low (op_sel: high)
|
||||
// f16 half; neg_hi is the absolute value here.
|
||||
@@ -8902,7 +9058,26 @@ impl<'a> Lower<'a> {
|
||||
|
||||
fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> {
|
||||
let Some(&interp) = self.interps.get(&site) else {
|
||||
return Err("the first half of an interpolation");
|
||||
// The first half of a pair: its second half interpolates the
|
||||
// attribute itself, so nothing needs this half's partial sum.
|
||||
// But an f16 second half that writes the high half of the
|
||||
// register this one wrote keeps the low half as it was (the
|
||||
// console compiler reuses the register; the low half is not
|
||||
// read), so the register needs a value: 0.
|
||||
let name = inst.name();
|
||||
if name == "v_interp_p1_f32" || name == "v_interp_p1ll_f16" {
|
||||
let dst = match &inst.fields {
|
||||
Fields::Vintrp { dst, .. } => Some(*dst),
|
||||
Fields::Valu(v) => v.dst,
|
||||
_ => None,
|
||||
};
|
||||
if let Some(Operand::Vector { reg, .. }) = dst {
|
||||
let zero = self.s.m.i32(0);
|
||||
self.write(inst, Reg::V(reg), zero, None);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
return Err(FIRST_HALF);
|
||||
};
|
||||
let name = inst.name();
|
||||
let (dst, src) = match &inst.fields {
|
||||
|
||||
@@ -297,7 +297,23 @@ pub struct UserData {
|
||||
|
||||
/// Translates the vertex, pixel, compute or mesh program of a console
|
||||
/// shader container.
|
||||
///
|
||||
/// A program refused because the first half of an interpolation is read as
|
||||
/// data is translated once more with first halves evaluated as the pair
|
||||
/// they start (`lower::with_first_half_pairs`), and only such a program:
|
||||
/// with that on for every program, 8,551 pixel programs of the title that
|
||||
/// already translated came out changed (an extra evaluation in each), for
|
||||
/// the sake of 9 that did not translate.
|
||||
pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
|
||||
match translate_plain(container) {
|
||||
Err(ShaderError::Unsupported { what, .. }) if what == lower::FIRST_HALF => {
|
||||
lower::with_first_half_pairs(|| translate_plain(container))
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
fn translate_plain(container: &[u8]) -> Result<HostShader, ShaderError> {
|
||||
let c = Container::parse(container)?;
|
||||
let dxil = c
|
||||
.part(FourCC::DXIL)
|
||||
|
||||
@@ -95,10 +95,20 @@ fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram {
|
||||
|
||||
/// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide.
|
||||
fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet<usize>) -> Result<HostShader, ShaderError> {
|
||||
lowered_on(native, p, wide, 32)
|
||||
}
|
||||
|
||||
/// [`lowered`] for a host whose waves have at most `host_wave` lanes.
|
||||
fn lowered_on(
|
||||
native: &NativeProgram,
|
||||
p: &ir::Program,
|
||||
wide: &HashSet<usize>,
|
||||
host_wave: u32,
|
||||
) -> Result<HostShader, ShaderError> {
|
||||
let st = structure::structure_wide(p, wide).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(32));
|
||||
let was = lower::TEST_HOST_WAVE.replace(Some(host_wave));
|
||||
let lowered = lower::lower(&lower::Parts {
|
||||
native,
|
||||
p,
|
||||
@@ -199,6 +209,76 @@ 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]);
|
||||
}
|
||||
|
||||
/// The console's 16-bit wave sum where the lanes at or past s0 have left the program (a
|
||||
/// thread past the end of the data): on the console they add +0, and after each step of the
|
||||
/// tree they hold their run's partial sum all the same. On a host of 64-lane waves (AMD) the
|
||||
/// lanes that are here read each partner run's sum from a lane of it that is here.
|
||||
#[test]
|
||||
fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() {
|
||||
let mut words = vec![
|
||||
0x7DA8_0000, // v_cmpx_gt_u32 exec, s0, v0: the lanes below s0 stay
|
||||
0, // s_cbranch_execz to the end (filled in below)
|
||||
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
|
||||
];
|
||||
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
|
||||
]);
|
||||
// past every word after it, to the program's end
|
||||
words[1] = 0xBF88_0000 | (words.len() as u32 - 2);
|
||||
let native = native(&words);
|
||||
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
|
||||
let shader = lowered_on(&native, &p, &HashSet::new(), 64).expect("lower");
|
||||
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");
|
||||
}
|
||||
let wide = |h: u16| {
|
||||
if h == 0 {
|
||||
0.0
|
||||
} else {
|
||||
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
|
||||
};
|
||||
let add = |a: u16, b: u16| narrow(wide(a) + wide(b));
|
||||
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut ran = false;
|
||||
for stay in [64u32, 63, 40, 33, 32, 17, 5, 1] {
|
||||
let terms: Vec<u16> = (0..64u32)
|
||||
.map(|t| if t < stay { (0x3C00 + 37 * t) as u16 } else { 0 })
|
||||
.collect();
|
||||
let mut tree = terms.clone();
|
||||
while tree.len() > 1 {
|
||||
tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect();
|
||||
}
|
||||
let Some(got) = on_the_card(&shader, [stay, 0]) else {
|
||||
return;
|
||||
};
|
||||
ran = true;
|
||||
// (the high half is lane 0's term's: zero)
|
||||
assert_eq!(got, u32::from(tree[0]), "{stay} lanes stay: got {got:#x}, the console's tree {:#x}", tree[0]);
|
||||
}
|
||||
if ran {
|
||||
eprintln!("ran on the hardware device: the console's tree with lanes gone, in every case");
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
Reference in new issue
Block a user