Merge fork main a26859f (the first room renders right)
Descriptor records the title copies as bytes are mirrored before each submission. Views off their copy's elements: our rule (raw views too, and now typed views on 16 bytes), the fork's copies. Wave sums of halves: ours (the fork's test passes with it). Sizes of descriptors nothing uses: ours, then the fork's for 2D images. The fork's count of cut indirect groups is left out: up to WIDEST groups run as asked here. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
f1650b7e45
13 files changed
+964
-109
No files matched your search
@@ -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)]
|
||||
@@ -984,6 +1101,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 {
|
||||
@@ -1041,6 +1162,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();
|
||||
@@ -1067,6 +1216,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
|
||||
@@ -806,14 +810,14 @@ fn view_elements(view: &View) -> Option<(u32, bool, u32)> {
|
||||
/// the title puts parameter blocks at ring positions: a raw view of 128 bytes
|
||||
/// at 8 (the colour table bakes'), structured ones of elements that are no
|
||||
/// divisor of their place (the culling's 456-byte constants). Such a view gets
|
||||
/// a copy of its own bytes ([`crate::shadow::own_bytes`]).
|
||||
/// a copy of its own bytes ([`crate::shadow::exact`]). (A typed view of
|
||||
/// 12-byte elements at a multiple of 16 that is none of 12 is one of them: it
|
||||
/// was passed over, and stayed null.)
|
||||
fn off_elements(offset: u64, stride: u32, raw: bool, element: u64) -> bool {
|
||||
if offset.is_multiple_of(16) {
|
||||
false
|
||||
} else if raw {
|
||||
true
|
||||
if raw {
|
||||
!offset.is_multiple_of(16)
|
||||
} else if stride > 0 {
|
||||
!offset.is_multiple_of(u64::from(stride))
|
||||
!offset.is_multiple_of(16) && !offset.is_multiple_of(u64::from(stride))
|
||||
} else {
|
||||
element > 0 && !offset.is_multiple_of(element)
|
||||
}
|
||||
@@ -837,14 +841,14 @@ fn view_home(
|
||||
let Some(offset) = shadow.offset_in(start).map(|_| shadow.offset(start)) else {
|
||||
return shadow;
|
||||
};
|
||||
if offset.is_multiple_of(16) || !view_bytes() {
|
||||
if !view_bytes() {
|
||||
return shadow;
|
||||
}
|
||||
let element = crate::resource::element(format).map_or(0, |(bytes, _)| bytes);
|
||||
if !off_elements(offset, stride, raw, element) {
|
||||
return shadow;
|
||||
}
|
||||
crate::shadow::own_bytes(start, len).unwrap_or(shadow)
|
||||
crate::shadow::exact(start, len).unwrap_or(shadow)
|
||||
}
|
||||
|
||||
/// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for
|
||||
@@ -1031,6 +1035,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),
|
||||
@@ -1908,6 +1913,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
|
||||
@@ -1993,6 +2037,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).
|
||||
@@ -3157,6 +3211,9 @@ mod tests {
|
||||
assert!(!off_elements(456, 456, false, 0));
|
||||
assert!(!off_elements(32, 456, false, 0));
|
||||
assert!(off_elements(100, 456, false, 0));
|
||||
// A typed view of 12-byte elements on 16 bytes and not on an element.
|
||||
assert!(off_elements(23_702_896, 0, false, 12));
|
||||
assert!(!off_elements(48, 0, false, 12));
|
||||
assert!(!off_elements(12, 0, false, 4));
|
||||
assert!(off_elements(12, 0, false, 8));
|
||||
}
|
||||
|
||||
@@ -1946,7 +1946,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(memory);
|
||||
let mut room = crate::resource::room(memory);
|
||||
// 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");
|
||||
@@ -2211,6 +2216,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(crate::host::host().and_then(|h| h.video_memory()));
|
||||
}
|
||||
HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed);
|
||||
HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed);
|
||||
match memory {
|
||||
|
||||
@@ -4726,6 +4726,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();
|
||||
// That list runs first, and is one of the submission's from here on.
|
||||
let with: Vec<&HostList>;
|
||||
let runs = match &own {
|
||||
@@ -7130,6 +7133,8 @@ 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"
|
||||
);
|
||||
crate::shadow::exact_line(frames);
|
||||
crate::descriptor::sync_line(frames);
|
||||
late_line(frames);
|
||||
card_clock_line(frames, ms);
|
||||
crate::shadow::back_line(frames);
|
||||
@@ -7228,7 +7233,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" },
|
||||
|
||||
@@ -1451,12 +1451,48 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool {
|
||||
}
|
||||
match 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)]
|
||||
|
||||
@@ -244,11 +244,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.
|
||||
@@ -256,7 +272,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.
|
||||
@@ -341,10 +357,30 @@ fn card_room_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 {
|
||||
@@ -4428,55 +4464,6 @@ fn longest_tail(windows: impl Iterator<Item = (u64, u64)>, address: u64, end: u6
|
||||
.min()
|
||||
}
|
||||
|
||||
/// Copies of single views' bytes ([`own_bytes`]), by (start, length), with
|
||||
/// the use that last asked for each.
|
||||
#[allow(clippy::type_complexity)]
|
||||
static OWN: Mutex<(u64, BTreeMap<(u64, u64), (Arc<Shadow>, u64)>)> = Mutex::new((0, BTreeMap::new()));
|
||||
|
||||
/// Copies [`OWN`] keeps: ring positions change every frame, so the least
|
||||
/// recently asked for go (lists and heap slots using one keep its buffer
|
||||
/// alive).
|
||||
/// shortcut: a slot whose view goes unused while this many others are asked
|
||||
/// for shows the buffer of a copy that is made anew at its next use.
|
||||
const OWN_KEPT: usize = 1024;
|
||||
/// The largest of them: one this long is no parameter block.
|
||||
const OWN_MOST: u64 = 4 << 20;
|
||||
|
||||
/// A host copy of the `len` bytes at `address` alone, for a view no host
|
||||
/// view of its buffer's copy can stand for (it would not begin where host
|
||||
/// views may; upstream 86a5ed6). What other views' shaders write there in the
|
||||
/// same submission it does not see: it is as title memory is at the
|
||||
/// submission, and what is written through it goes back there after.
|
||||
/// `None`: no view the title made on purpose (off its dwords, empty or huge).
|
||||
pub(crate) fn own_bytes(address: u64, len: u64) -> Option<Arc<Shadow>> {
|
||||
if len == 0 || len > OWN_MOST || !address.is_multiple_of(4) {
|
||||
return None;
|
||||
}
|
||||
let mut guard = OWN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (tick, map) = &mut *guard;
|
||||
*tick += 1;
|
||||
if let Some((shadow, used)) = map.get_mut(&(address, len)) {
|
||||
*used = *tick;
|
||||
return Some(shadow.clone());
|
||||
}
|
||||
if map.len() >= OWN_KEPT
|
||||
&& let Some(&oldest) = map.iter().min_by_key(|(_, (_, used))| *used).map(|(k, _)| k)
|
||||
{
|
||||
map.remove(&oldest);
|
||||
}
|
||||
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(), *tick));
|
||||
OWN_MADE.fetch_add(1, Ordering::Relaxed);
|
||||
Some(shadow)
|
||||
}
|
||||
|
||||
/// Copies of single views' bytes made since the start.
|
||||
pub(crate) static OWN_MADE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Copies of title memory outside buffers, by (start, length).
|
||||
static LOOSE: Mutex<BTreeMap<(u64, u64), Arc<Shadow>>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
@@ -4555,6 +4542,88 @@ 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` `view_home`).
|
||||
/// 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;
|
||||
/// The largest, and no view the title made on purpose: off its dwords.
|
||||
const MOST: u64 = 64 << 20;
|
||||
if len == 0 || len > MOST || !address.is_multiple_of(4) {
|
||||
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);
|
||||
OWN_MADE.fetch_add(1, Ordering::Relaxed);
|
||||
Some(shadow)
|
||||
}
|
||||
|
||||
/// Copies of single views' bytes made since the start.
|
||||
pub(crate) static OWN_MADE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// 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_BYTES=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::{
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,27 @@ fn next_asking() -> u64 {
|
||||
ASKED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// Page number → the asking that last found it written.
|
||||
written: BTreeMap<usize, u64>,
|
||||
@@ -498,6 +519,42 @@ pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64],
|
||||
&& j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged))
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
@@ -1424,16 +1481,22 @@ impl Drop for KernelWrite {
|
||||
/// 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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user