Merge branch 'local/next' into night/light

# Conflicts:
#	crates/victory-shader/src/emit/mod.rs
This commit is contained in:
local committed 2026-11-25 04:43:44 -06:00
commit ea375caa52
27 files changed
+3107 -163

No files matched your search

+18
View File
@@ -1009,6 +1009,7 @@ pub(crate) fn recorded(started: std::time::Instant) {
/// submission lock).
pub(crate) fn submission_begins() {
let now = now_us();
INSIDE.fetch_add(1, Relaxed);
if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) {
add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed)));
}
@@ -1029,6 +1030,7 @@ pub(crate) fn submission_begins() {
/// submission lock.
pub(crate) fn submission_ends(lock: u64) {
let now = now_us();
INSIDE.fetch_sub(1, Relaxed);
SUBMITTED_AT.store(now, Relaxed);
let (user, kernel) = thread_times();
let (u, k) = ENTERED.with(|e| e.get());
@@ -1042,6 +1044,22 @@ pub(crate) fn submission_ends(lock: u64) {
s.inside_kernel += kernel.saturating_sub(k);
}
/// The submissions being prepared now.
static INSIDE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
/// What the frame is at, for the sampling profiler (`VICTORY_PROFILE`): 3
/// in a submission, else 0 after a present until the first list call, 1 until
/// the first submission, 2 behind it.
pub(crate) fn phase() -> u32 {
if INSIDE.load(Relaxed) > 0 {
3
} else if SUBMITTED_SINCE.load(Relaxed) {
2
} else {
u32::from(RECORDED_SINCE.load(Relaxed))
}
}
/// The title calls its present (before our own copy to the window runs).
pub(crate) fn present_begins() {
add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed)));
+33 -3
View File
@@ -286,6 +286,15 @@ pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 6] = [const { std::sync
/// Nothing while no heap page changed.
#[cfg(windows)]
pub(crate) fn sync_line(frames: f64) {
let [twins, moved, lost] = [0, 1, 2].map(|i| host::TWINS[i].swap(0, std::sync::atomic::Ordering::Relaxed));
if twins > 0 {
tracing::info!(
"raw twins of buffer views made per frame (VICTORY_RAW_VIEWS=0: none): {:.0}, of them {:.1} that do not begin on 16 bytes ({:.1} null)",
twins as f64 / frames,
moved as f64 / frames,
lost as f64 / frames
);
}
let [pages, looked, mirrored, micros, tabled, later] = [0, 1, 2, 3, 4, 5].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed));
if pages == 0 {
return;
@@ -354,17 +363,38 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) {
}
}
/// Runs `f` with the host heap of the title's largest view heap, if there is
/// one (reports: nothing is waited for).
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) fn with_view_heap<T>(f: impl FnOnce(&host::HostHeap) -> T) -> Option<T> {
let heaps = SHADER_HEAPS.try_read().ok()?;
let host = heaps
.iter()
// SAFETY: registered heaps are live (removed when dropped).
.map(|&(_, _, at)| unsafe { &*(at as *const Heap) })
.filter(|heap| !heap.samplers())
.filter_map(|heap| heap.host.get()?.as_ref())
.max_by_key(|host| host.count())?;
Some(f(host))
}
/// Makes dynamic slot `index` of the host heap behind the title heap at
/// `heap`, if that heap still exists, the constant buffer view of `size`
/// bytes at `gpu`.
/// bytes of `buffer` at `gpu`.
#[cfg(windows)]
pub(crate) fn constant_slot(heap: usize, index: u32, gpu: u64, size: u32) {
pub(crate) fn constant_slot(
heap: usize,
index: u32,
buffer: &windows::Win32::Graphics::Direct3D12::ID3D12Resource,
gpu: u64,
size: u32,
) {
let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner());
if heaps.iter().any(|&(_, _, h)| h == heap)
// SAFETY: registered heaps are live (removed when dropped).
&& let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get()
{
host.constant_at(index, gpu, size);
host.constant_at(index, buffer, gpu, size);
}
}
File diff suppressed because it is too large. Load diff
+120 -10
View File
@@ -95,6 +95,34 @@ fn early_budgets() -> (u64, u64) {
})
}
/// Whether a draw of the title's bake finds the textures it picks by index
/// as title memory has them at that moment (`VICTORY_BAKE_EXACT=0`: as the
/// pass leaves them, as before). The pass looks at a slot whose memory was
/// written or mapped a frame or two later, by when the rest of it has
/// landed, and at one uploaded whole a few frames later again, for a title
/// that fills memory unnoticed: a bake in between took the bytes from before
/// (another texture's), and what it bakes stays: coloured specks all over
/// the waitress's face for the whole diner scene (run n01), none in other
/// runs. So the pass ahead of a bake takes those slots too, and its uploads
/// wait for title memory that is being remapped (`crate::texture` `BAKING`).
fn bake_exact() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_BAKE_EXACT").is_none_or(|v| v != "0"))
}
/// Whether a texture found changed with nothing to tell of it is looked at
/// again in the next frame (`VICTORY_RECHECK_SOON=0`: after four, as
/// before).
fn recheck_soon() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_RECHECK_SOON").is_none_or(|v| v != "0"))
}
/// Frames ahead the pass before a bake takes slots from that are due only
/// then ([`bake_exact`]): those of notices (1 and 2), and the first looks
/// again ([`RECHECK_FRAMES`]).
const BAKE_AHEAD: u64 = 12;
/// The pixel shaders of the title's decoration bake (the title:
/// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the
/// frame listings print it. They draw into a 256x256 corner of 2048x2048
@@ -283,6 +311,10 @@ pub(crate) struct State {
/// The records clamped in a batch, if later executions may still read
/// them ([`batches`]).
batch: Option<Batch>,
/// The user data bound last, of the last stage that has some (for the
/// report of a removed device, `crate::host::indirects`).
#[cfg(feature = "diagnostics")]
user: Vec<u32>,
/// What the host list has: pipeline, root signature, heaps.
host_pipeline: usize,
/// Graphics, compute.
@@ -601,6 +633,7 @@ fn heap_recheck() -> bool {
}
/// Times a placed texture's slot was passed over because its memory is not
/// mapped.
pub(crate) static HEAP_TEXTURES_SAME: AtomicU64 = AtomicU64::new(0);
pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0);
/// Slots the pass found up to date already: their texture is uploaded by
/// the draws that read it through a table (it has a staging buffer).
@@ -1268,6 +1301,11 @@ impl State {
None => self.user_value(compute, u.slot, u.root, u.dword),
};
}
#[cfg(feature = "diagnostics")]
{
self.user.clear();
self.user.extend_from_slice(&values);
}
// SAFETY: an open list; `values` covers the parameter.
unsafe {
if compute {
@@ -1842,7 +1880,9 @@ impl State {
}
let began = std::time::Instant::now();
PASS_BUDGET.set(Some(budget));
crate::texture::BAKING.set(bake && bake_exact());
self.heap_textures(list, heap, host);
crate::texture::BAKING.set(false);
PASS_BUDGET.set(None);
if bake {
BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
@@ -1992,15 +2032,26 @@ impl State {
// wrote since the last pass are due again.
host.texture_slots_remapped(frame);
host.texture_slots_short(frame);
// Levels on demand: the slots of textures whose first level with
// memory changed since the last pass are made again from it.
// The slots of textures whose first level with memory (levels on
// demand), or whose host copy for one with more levels, changed since
// the last pass are made again from it; those whose new view's upload
// has run are made from that.
host.texture_views_remade();
host.texture_slots_flip();
// And with room, the textures whose upload left a held level
// without the card's memory are uploaded again.
if room {
host.texture_slots_waiting(frame);
}
let (due, census) = host.texture_slots_due(frame, 4096);
let baking = crate::texture::BAKING.get();
let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 });
// (Those that are due later after all that are due.)
let on_time = due.len();
if baking {
let known: std::collections::HashSet<u32> = due.iter().map(|&(index, _)| index).collect();
let (ahead, _) = host.texture_slots_due(frame + BAKE_AHEAD, 1 << 16);
due.extend(ahead.into_iter().filter(|(index, _)| !known.contains(index)));
}
HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed);
for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) {
count.store(now, Ordering::Relaxed);
@@ -2043,7 +2094,7 @@ impl State {
// drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget.
static CATCHUP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0"));
let (per_frame, span) = if catchup && due.len() >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) };
let (per_frame, span) = if catchup && on_time >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) };
// A run made early (`State::early_textures`) has a budget of its
// own: its bytes on top of what the frame has spent so far.
// (Not `most`: that is the longest wait between looks, used below.)
@@ -2077,6 +2128,12 @@ impl State {
// first look for the rest of the run. The look reads 48 KiB;
// only a changed texture is uploaded again.
// `VICTORY_HEAP_RECHECK=0`: uploaded once, as before.
// One found changed by such a look is looked at in the next frame
// again: the textures left that change unnoticed are ones the
// title paints all the time through another view of their pages
// (all their blocks are shown at other addresses too), and each
// was shown four frames late, over and over.
let mut again_in = RECHECK_FRAMES[0];
if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) {
if crate::texture::fingerprint(at, len) == print {
HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed);
@@ -2088,9 +2145,21 @@ impl State {
}
continue;
}
if recheck_soon() {
again_in = 1;
}
let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed);
if n < 200 || n.is_multiple_of(1000) {
// Whether its pages are the title's at other addresses
// too: what is written there is told of there alone.
let elsewhere = crate::inplace::shown_elsewhere(at as usize & !0xffff, (at + len) as usize);
let first = heap.handle(index).and_then(crate::descriptor::view).map_or(0, |view| match view {
View::Placed(false, _, desc) => crate::resource::first_mip(&desc),
_ => 0,
});
tracing::warn!(
first_level = first,
blocks_shown_elsewhere = elsewhere.len(),
slot = index,
address = format_args!("{at:#x}"),
bytes = len,
@@ -2104,7 +2173,8 @@ impl State {
let mut partly = None;
if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) {
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
let len = crate::resource::placed_bytes(&resource).unwrap_or(1);
let first = crate::resource::first_mip(&desc);
let len = crate::resource::placed_bytes_from(&resource, first).unwrap_or(1);
let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize);
if mapped == 0 {
HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed);
@@ -2177,7 +2247,15 @@ impl State {
);
}
}
let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true));
// A slot that shows the texture by an earlier view of it (one
// from another level) goes on doing so until the upload of what
// the new one shows has run.
let shows_other = !baking
&& crate::resource::held_only()
&& heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle));
let view = heap.handle(index).and_then(|handle| {
if shows_other { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) }
});
let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture);
let resource = match placed.as_ref().or(view.as_ref()) {
Some(&View::Shader(resource, _)) => resource as This,
@@ -2196,9 +2274,34 @@ impl State {
// through a table: they upload it, and check it at every
// submission that samples it.
let tabled = crate::texture::is_staged(resource);
// The host copy holds these very bytes: nothing to upload.
let first = match (&placed, &view) {
(Some(_), Some(View::Placed(_, _, desc))) => crate::resource::first_mip(desc),
_ => 0,
};
let same = !tabled && crate::texture::unchanged(resource, first);
if same {
HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed);
if shows_other && let Some(handle) = heap.handle(index) {
let _ = host.mirror(index, handle, true);
}
let again = partly.map(|mapped| (frame + 1, mapped));
let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None };
match memory {
Some((at, len)) => {
let print = crate::texture::fingerprint(at, len);
host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame);
}
None => host.texture_slot_done(index, write, again),
}
continue;
}
if let Some(view) = &view {
readable(list, sampled.kind, view);
}
if shows_other && let Some(handle) = heap.handle(index) {
host.texture_slot_flip(list, index, handle);
}
// A texture view the host refuses removes the device: name it.
static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if !GONE.load(Ordering::Relaxed)
@@ -2254,7 +2357,7 @@ impl State {
// Whole and uploaded: looked at again (see above).
Some((at, len)) => {
let print = crate::texture::fingerprint(at, len);
host.texture_slot_recheck(index, write, frame + RECHECK_FRAMES[0], (at, len), print, 0, frame);
host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame);
}
None => host.texture_slot_done(index, write, again),
}
@@ -2896,13 +2999,13 @@ impl State {
let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k);
match crate::descriptor::view(table + u64::from(k) * 32) {
Some(View::Constant(address, size)) => {
let Some((gpu, to)) = list.scratch(u64::from(size)) else {
let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else {
host.make_null(index);
continue;
};
let slot = (std::ptr::from_ref(heap) as usize, index);
list.defer_constants(to, address as *const u8, size as usize, slot);
host.constant_at(index, gpu, size);
host.constant_at(index, &buffer, gpu, size);
}
Some(view) => {
host.make_at(index, &view);
@@ -3410,6 +3513,8 @@ impl State {
list.note_op(|| {
self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH)
});
#[cfg(feature = "diagnostics")]
list.ran_indirect(p.pso.as_raw() as usize, &p.name, kind, max, &self.user);
if kind == MESH {
self.mesh_scissor(list, true);
}
@@ -3556,7 +3661,12 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) {
&& let Some(t) = crate::resource::host_resource(*resource as This)
&& crate::texture::title_written(t)
{
crate::texture::upload(list, *resource as This, t);
// Of a texture the title placed, the levels the view shows.
let first = match (&placed, view) {
(Some(_), View::Shader(_, Some(desc))) => crate::resource::first_mip(desc),
_ => 0,
};
crate::texture::upload_from(list, *resource as This, first);
}
// A depth texture shaders also write: what they wrote, first.
list.twin_use(*resource as This, false, false);
+179 -6
View File
@@ -117,6 +117,34 @@ pub(crate) fn available_physical_ram() -> Option<u64> {
ok.then_some(m.ullAvailPhys)
}
/// How long host copies of textures the title fills must have been idle to
/// be let go, in milliseconds, and how many bytes of them go at most (the
/// longest idle first): none but those of ten minutes while what is in use
/// of the card (`used`: without what our own blocks have free, with what is
/// kept free for others) is under 88 % of its budget, else enough to come
/// down to 85 %. `VICTORY_TEXTURE_KEEP=0`: [`vram_idle_ms`]' older rule,
/// all that are idle; `=1`: that rule with its two longer times.
///
/// (By those times everything idle for 2.5 s went from 75 % of the budget
/// on: 61,000 of them in the first 300 s of session play-1125-0203, at 78 to
/// 80 %, of which 13,000 were made and uploaded again.)
pub(crate) fn vram_keep(budget: u64, used: u64) -> (u64, u64) {
const KEPT_MS: u64 = 600_000;
const IDLE_MS: u64 = 5_000;
const SHORT_MS: u64 = 1_500;
if budget == 0 {
return (IDLE_MS, u64::MAX);
}
let share = |percent: u64| budget / 100 * percent;
if used < share(88) {
(KEPT_MS, u64::MAX)
} else if used < share(95) {
(IDLE_MS, used - share(85))
} else {
(SHORT_MS, used - share(85))
}
}
/// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
/// scaled down under VRAM pressure. Never returns less than 1,000 ms so
/// handles not yet recorded into a list or slot remain protected.
@@ -157,11 +185,37 @@ fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 {
}
}
/// Whether memory the card was given stays with it while there is room (on
/// by default; `VICTORY_KEEP_FREED=0`: it is given back as before). A shader
/// that reads past a view (a raw load through a typed, structured or
/// constant buffer view has no end on AMD: `indirect::tests::raw_loads_past_views`)
/// or through a slot that shows wrong data reads whatever lies there, and
/// nothing happens; where memory was given back it is a page fault, and the
/// device is lost. Both losses of 2026-11-25 were reads in memory given back
/// seconds before (a block of textures; a list's scratch and a window of
/// title memory). Kept are: empty blocks of textures ([`crate::pool`]) below
/// 85 % of the card's budget, windows of title memory and staging buffers
/// for five minutes with 12 GiB of the PC's memory free, and 1 GiB of
/// scratch chunks.
pub(crate) fn keep_freed() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_FREED").is_none_or(|v| v != "0"))
}
/// Effective idle timeout (in milliseconds) for system-RAM caches (staging
/// buffers, loose shadows, and the mapped pipeline library), scaled down
/// when free physical RAM is low. Never returns less than 2,000 ms.
/// With plenty of it five minutes ([`keep_freed`]).
pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
ram_idle_for(avail_phys, keep_freed())
}
fn ram_idle_for(avail_phys: Option<u64>, keep: bool) -> u64 {
const GIB: u64 = 1024 * 1024 * 1024;
const KEPT_MS: u64 = 300_000;
if keep && avail_phys.is_some_and(|avail| avail >= 12 * GIB) {
return KEPT_MS;
}
const NORMAL_MS: u64 = 10_000;
const MODERATE_MS: u64 = 5_000;
const HIGH_MS: u64 = 2_000;
@@ -215,12 +269,19 @@ fn sweep() {
{
return;
}
crate::pool::room(host().and_then(|h| h.video_memory()));
crate::pipeline::trim_library();
crate::shadow::let_go_idle();
crate::texture::let_go_idle();
crate::resource::let_go_idle();
}
/// The number of the newest submission begun, and of the newest of which all
/// before it have finished too.
pub(crate) fn submissions() -> (u64, u64) {
(STARTED.load(Ordering::Acquire), FINISHED.load(Ordering::Acquire))
}
/// Drops `object` once every submission running now has finished: at once
/// if none is.
pub(crate) fn retire<T: 'static>(object: T) {
@@ -889,6 +950,9 @@ pub(crate) struct HostList {
prelude: OnceLock<Option<Prelude>>,
/// The pipelines the list binds, for reports of slow submissions.
pipelines: std::sync::Arc<Mutex<std::collections::BTreeSet<String>>>,
/// What its indirect executions ran, for the report of a removed device.
#[cfg(feature = "diagnostics")]
indirects: indirects::Shared,
/// The work its indirect executions may still do (`indirect`): a
/// shader-writable word, zeroed when the list is submitted, and after
/// it what the clamp notes about mesh records. In memory the CPU maps.
@@ -1404,7 +1468,14 @@ pub(crate) fn dred_faults() -> bool {
#[cfg(feature = "diagnostics")]
#[allow(clippy::type_complexity)]
static LIST_NOTES: Mutex<
std::collections::BTreeMap<u32, (std::sync::Weak<Mutex<Vec<Note>>>, std::sync::Weak<Mutex<std::collections::BTreeSet<String>>>)>,
std::collections::BTreeMap<
u32,
(
std::sync::Weak<Mutex<Vec<Note>>>,
std::sync::Weak<Mutex<std::collections::BTreeSet<String>>>,
std::sync::Weak<Mutex<indirects::Indirects>>,
),
>,
> = Mutex::new(std::collections::BTreeMap::new());
/// The number in the name of a list of ours ("victory host list 7", which the
@@ -1531,6 +1602,8 @@ const SCRATCH_CHUNK: u64 = 4 << 20;
const SCRATCH_FIRST: u64 = 256 << 10;
/// The most bytes of chunks kept while no list holds them.
const SPARE_MOST: u64 = 128 << 20;
/// The same with [`keep_freed`].
const SPARE_KEPT: u64 = 1 << 30;
/// Whether lists share their scratch chunks: a list takes a chunk when it
/// first needs one, a small one first, and gives all of them back when it
@@ -1611,7 +1684,7 @@ fn give_chunks(chunks: Vec<(Chunk, u64)>) {
let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
for (chunk, size) in chunks {
let back = if scratch_pool() {
spare.give(chunk, size, SPARE_MOST)
spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST })
} else {
Some(chunk)
};
@@ -3155,6 +3228,7 @@ fn late_line(frames: f64) {
}
mod card_steps;
pub(crate) mod indirects;
mod place;
mod send;
mod torn;
@@ -3522,6 +3596,8 @@ impl Host {
let notes = std::sync::Arc::<Mutex<Vec<Note>>>::default();
let pipelines = std::sync::Arc::<Mutex<std::collections::BTreeSet<String>>>::default();
#[cfg(feature = "diagnostics")]
let indirects = indirects::Shared::default();
#[cfg(feature = "diagnostics")]
if dred_on() || dred_light() {
static NUMBER: AtomicU32 = AtomicU32::new(0);
let number = NUMBER.fetch_add(1, Ordering::Relaxed);
@@ -3530,7 +3606,14 @@ impl Host {
if number.is_multiple_of(256) {
all.retain(|_, l| l.0.strong_count() > 0);
}
all.insert(number, (std::sync::Arc::downgrade(&notes), std::sync::Arc::downgrade(&pipelines)));
all.insert(
number,
(
std::sync::Arc::downgrade(&notes),
std::sync::Arc::downgrade(&pipelines),
std::sync::Arc::downgrade(&indirects),
),
);
}
Ok(HostList {
allocator,
@@ -3541,6 +3624,8 @@ impl Host {
twins: Mutex::default(),
prelude,
pipelines,
#[cfg(feature = "diagnostics")]
indirects,
budget: OnceLock::new(),
card_budget: OnceLock::new(),
indirect_args: Mutex::default(),
@@ -5271,7 +5356,12 @@ impl Host {
#[cfg(feature = "diagnostics")]
let by_name = list_number(&named).and_then(|n| {
let all = LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner());
all.get(&n).map(|(notes, pipelines)| (notes.upgrade(), pipelines.upgrade()))
all.get(&n).map(|(notes, pipelines, _)| (notes.upgrade(), pipelines.upgrade()))
});
#[cfg(feature = "diagnostics")]
let indirects = run.map(|r| r.indirects.clone()).or_else(|| {
let n = list_number(&named)?;
LIST_NOTES.lock().unwrap_or_else(|e| e.into_inner()).get(&n)?.2.upgrade()
});
#[cfg(not(feature = "diagnostics"))]
#[allow(clippy::type_complexity)]
@@ -5301,6 +5391,10 @@ impl Host {
if done > 0 {
text.push_str(&in_flight(history, &markers, done as usize));
}
#[cfg(feature = "diagnostics")]
if let Some(indirects) = indirects {
text.push_str(&indirects_around(history, done as usize, &indirects));
}
// (Without markers a list that stopped midway says what
// it may have been at only by what it binds.)
if (done == 0 || markers.is_empty())
@@ -5498,6 +5592,8 @@ impl HostList {
self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear();
self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
#[cfg(feature = "diagnostics")]
self.indirects.lock().unwrap_or_else(|e| e.into_inner()).clear();
#[cfg(feature = "diagnostics")]
self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
{
let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
@@ -5530,8 +5626,10 @@ impl HostList {
resource: crate::object::This,
wanted: u32,
) -> Option<(&'static ID3D12Resource, u32)> {
let texture = crate::resource::host_resource(resource)?;
let copy = crate::resource::host_copy(resource)?;
// SAFETY: as in `crate::resource::host_resource`; the list's states
// hold the copy from here on.
let texture: &'static ID3D12Resource = unsafe { &*std::ptr::from_ref(&copy.texture) };
let wanted = legal_state(texture, wanted);
let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
@@ -5904,6 +6002,15 @@ impl HostList {
&& self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
}
/// Notes an indirect execution, while device-removed data is kept
/// ([`indirects`]).
#[cfg(feature = "diagnostics")]
pub(crate) fn ran_indirect(&self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) {
if dred_on() || dred_light() {
self.indirects.lock().unwrap_or_else(|e| e.into_inner()).note(pipeline, name, kind, count, user);
}
}
/// Notes a pipeline the list binds.
pub(crate) fn used_pipeline(&self, name: &str) {
let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
@@ -6025,6 +6132,15 @@ impl HostList {
Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data))
}
/// [`HostList::scratch`] and the buffer it lies in, for a descriptor
/// slot to hold: the slot outlives the list's use of it.
pub(crate) fn scratch_held(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
let (buffer, at, data) = self.scratch_at(len)?;
// SAFETY: a live buffer.
let gpu = unsafe { buffer.GetGPUVirtualAddress() } + at;
Some((buffer, gpu, data))
}
/// [`HostList::scratch`]: the buffer, the offset in it and the CPU
/// pointer.
fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
@@ -7408,6 +7524,20 @@ impl Meter {
crate::descriptor::host::STALE[4].load(Ordering::Relaxed)
);
}
if crate::resource::held_only() {
let [copies, bytes, grown, whole] = [0, 1, 2, 3].map(|i| crate::resource::HELD[i].load(Ordering::Relaxed));
let [flipped, missed] = [0, 1].map(|i| crate::descriptor::host::FLIPPED[i].load(Ordering::Relaxed));
tracing::info!(
"textures from the first level viewed (VICTORY_HELD_LEVELS=0: whole), since the start: {copies} host copies of the \
levels viewed alone ({} MB on the card, {} MB of title memory whole), {grown} replaced by one with more levels, \
{flipped} slots made from their new view after its upload had run ({missed} written again first); {} uploads left \
out as the host copy held those bytes (VICTORY_TEXTURE_SAME=0: made); {} MB of texture blocks free",
bytes >> 20,
whole >> 20,
crate::draw::HEAP_TEXTURES_SAME.load(Ordering::Relaxed),
crate::pool::texture_room() >> 20
);
}
{
let mode = crate::watch::page_writes();
let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed));
@@ -7977,6 +8107,34 @@ fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
/// barriers overlaps on the GPU), by kind, and what the markers just
/// before them say (`HostList::note_op`: diagnostics builds with
/// device-removed data on).
/// For a list that stopped at command `done`: what the indirect executions
/// there ran, from the one before it to the next barrier (four at most), and
/// what the heap slots their user data names hold now.
#[cfg(feature = "diagnostics")]
fn indirects_around(history: &[D3D12_AUTO_BREADCRUMB_OP], done: usize, all: &indirects::Shared) -> String {
let indirect = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_EXECUTEINDIRECT;
let all = all.lock().unwrap_or_else(|e| e.into_inner());
let mut text = String::new();
let mut shown = 0;
for (at, op) in history.iter().enumerate().skip(done.saturating_sub(1)) {
if shown == 4 || (at > done && *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER) {
break;
}
if !indirect(op) {
continue;
}
shown += 1;
let Some((what, words)) = all.nth(indirects::before(history, at, indirect)) else {
continue;
};
text.push_str(&format!("; command {at} ran {what}"));
for (word, slot, what) in crate::descriptor::host::describe_slots(words) {
text.push_str(&format!(", word {word} slot {slot}: {what}"));
}
}
text
}
fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
@@ -8904,9 +9062,24 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at
assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000);
}
#[test]
fn textures_are_kept_while_the_card_has_room() {
use super::vram_keep;
let gib = 1 << 30;
assert_eq!(vram_keep(100 * gib, 87 * gib).0, 600_000);
// Past it: the longest idle ones, enough to come down to 85 %.
let (ms, bytes) = vram_keep(100 * gib, 90 * gib);
assert_eq!((ms, bytes), (5_000, 5 * gib));
assert_eq!(vram_keep(100 * gib, 120 * gib), (1_500, 35 * gib));
assert_eq!(vram_keep(0, 7).0, 5_000);
}
#[test]
fn ram_idle_ms_scales_with_pressure() {
use super::ram_idle_ms;
let ram_idle_ms = |avail| super::ram_idle_for(avail, false);
assert_eq!(super::ram_idle_for(Some(12 << 30), true), 300_000);
assert_eq!(super::ram_idle_for(Some((12 << 30) - 1), true), 10_000);
assert_eq!(super::ram_idle_for(None, true), 10_000);
let gib = 1024 * 1024 * 1024;
// Normal (>= 4 GiB)
assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000);
+1 -1
View File
@@ -715,7 +715,7 @@ impl Host {
To::Slot(heap, index) => {
DONE[0].fetch_add(1, Ordering::Relaxed);
// (A heap that is gone: nothing can read the slot.)
crate::descriptor::constant_slot(*heap, *index, gpu + op.at, op.len as u32);
crate::descriptor::constant_slot(*heap, *index, &own.between, gpu + op.at, op.len as u32);
}
To::Buffer(_) => {
DONE[0].fetch_add(1, Ordering::Relaxed);
+127
View File
@@ -0,0 +1,127 @@
//! What the indirect executions of a list ran, for the report of a removed
//! device: with `VICTORY_D3D12_DRED=light` the lists carry no markers, and
//! the two device losses of 2026-11-25 (sessions play-1125-0203 and n02)
//! said only that a list of 814 (954) commands stopped at an indirect
//! execution. The pipeline of each was found hours later by finding the
//! same run of commands in a capture.
//!
//! Per list, in the order recorded: the pipeline (by its host object, whose
//! name is kept once) and the first root constants (user data) it had. The
//! report finds an indirect execution by how many the breadcrumbs' history
//! has before it. Nothing is kept without device-removed data.
//! `VICTORY_D3D12_DRED=faults` and no data at all: nothing is noted.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
/// Words of user data kept of each execution.
pub(crate) const WORDS: usize = 16;
/// One indirect execution.
#[derive(Clone, Copy)]
pub(crate) struct Ran {
pipeline: usize,
kind: u32,
count: u32,
words: [u32; WORDS],
used: u8,
}
#[derive(Default)]
pub(crate) struct Indirects {
names: HashMap<usize, String>,
ran: Vec<Ran>,
}
/// A list's, shared with the report's table of lists.
pub(crate) type Shared = Arc<Mutex<Indirects>>;
impl Indirects {
/// An indirect execution of `kind` (the argument's type) of at most
/// `count` records with `pipeline` (a host object) and user data.
pub(crate) fn note(&mut self, pipeline: usize, name: &str, kind: u32, count: u32, user: &[u32]) {
self.names.entry(pipeline).or_insert_with(|| name.to_owned());
let used = user.len().min(WORDS);
let mut words = [0; WORDS];
words[..used].copy_from_slice(&user[..used]);
self.ran.push(Ran { pipeline, kind, count, words, used: used as u8 });
}
pub(crate) fn clear(&mut self) {
self.ran.clear();
if self.names.len() > 512 {
self.names.clear();
}
}
/// The `nth` execution (from 0): its text and its user data.
pub(crate) fn nth(&self, nth: usize) -> Option<(String, &[u32])> {
let ran = self.ran.get(nth)?;
let name = self.names.get(&ran.pipeline).map_or("a pipeline", String::as_str);
let words = &ran.words[..usize::from(ran.used)];
Some((
format!("{name} (indirect kind {} max {}, the list's indirect execution {nth}, user data {words:x?})", ran.kind, ran.count),
words,
))
}
}
/// How many indirect executions come before command `at` of a history of
/// breadcrumb operations (`is` tells them): which of a list's it is.
pub(crate) fn before<T>(history: &[T], at: usize, is: impl Fn(&T) -> bool) -> usize {
history[..at.min(history.len())].iter().filter(|op| is(op)).count()
}
/// The heap slots the user data may name, for the report to describe: the
/// words that are slots as they are, and the slots from where a word is a
/// table's byte offset (32 bytes a descriptor), `table` of them.
pub(crate) fn slots(words: &[u32], count: u32, table: u32) -> Vec<(usize, u32)> {
let mut out = Vec::new();
for (i, &word) in words.iter().enumerate() {
if word > 0 && word < count && word % 32 != 0 {
out.push((i, word));
}
if word % 32 == 0 && word / 32 > 16 && word / 32 < count {
out.extend((0..table).map(|k| (i, word / 32 + k)).filter(|s| s.1 < count));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// The execution a breadcrumb history stops at is found by the ones
/// before it, and its pipeline and user data are told.
#[test]
fn an_indirect_execution_is_found_by_its_place_in_the_history() {
let mut all = Indirects::default();
all.note(1, "[compute a]", 2, 1, &[0x2549f40, 0x20, 0x11]);
all.note(2, "[compute b]", 2, 1, &[7; 20]);
all.note(1, "another name of the same is not taken", 10, 4, &[]);
// dispatch, indirect, barrier, indirect, indirect
let history = [6, 5, 15, 5, 5];
let nth = before(&history, 3, |op| *op == 5);
assert_eq!(nth, 1);
let (text, words) = all.nth(nth).unwrap();
assert!(text.starts_with("[compute b] (indirect kind 2 max 1"), "{text}");
assert_eq!(words, [7; WORDS]);
let (text, words) = all.nth(2).unwrap();
assert!(text.starts_with("[compute a] (indirect kind 10 max 4"), "{text}");
assert!(words.is_empty());
assert!(all.nth(3).is_none());
assert_eq!(before(&history, 99, |op| *op == 5), 3);
all.clear();
assert!(all.nth(0).is_none());
}
/// A table's byte offset names the slots from it on; a small word that
/// is no multiple of a descriptor's bytes names its own slot.
#[test]
fn user_data_names_slots() {
let words = [0, 0x2549f40, 0x20, 0x11, 0x26f1, 0xffff_ffff];
let slots = slots(&words, 1_245_184, 2);
assert_eq!(slots, [(1, 0x2549f40 / 32), (1, 0x2549f40 / 32 + 1), (3, 0x11), (4, 0x26f1)]);
}
}
+538 -1
View File
@@ -600,7 +600,7 @@ pub(crate) mod tests {
use super::*;
use windows::Win32::Foundation::HANDLE;
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;
use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC};
use windows::Win32::Graphics::Dxgi::*;
use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
use windows::core::Interface;
@@ -984,6 +984,543 @@ void main() {
}
}
/// What raw loads through views that are not raw give past the view's
/// end (ignored: a measurement of the card). A buffer view of 4 KiB in a
/// buffer of 1 MiB whose every dword says where it lies: zeros past the
/// view, or the bytes there (whatever the card has in that place).
#[test]
#[ignore]
fn raw_loads_past_views() {
let Some(mut gpu) = WarpHarness::on(std::env::var_os("VICTORY_BENCH_WARP").is_some()) else {
return;
};
const SOURCE: &str = r#"
#define RS "RootConstants(num32BitConstants=4,b0), DescriptorTable(SRV(t0,numDescriptors=8)), UAV(u0), DescriptorTable(CBV(b1,numDescriptors=8))"
cbuffer C : register(b0) { uint which; uint first; uint step; uint at; }
ByteAddressBuffer v[8] : register(t0);
struct Block { uint4 d[4096]; };
ConstantBuffer<Block> c[8] : register(b1);
RWByteAddressBuffer o : register(u0);
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) {
if (step == 0) { if (id.x == 0) o.Store(at, v[which].Load(first)); }
else if (step == 1) { if (id.x == 0) o.Store(at, c[which].d[first / 16][(first / 4) & 3]); }
else { o.Store(at + id.x * 4, v[which].Load(first + id.x * step)); }
}
"#;
let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile");
let (buffer, data, _) = gpu.shared_buffer(1 << 20);
for i in 0..(1usize << 18) {
// SAFETY: inside the mapping.
unsafe { data.cast::<u32>().add(i).write(0xA000_0000 | i as u32) };
}
let (_out, out_ptr, out_gpu) = gpu.shared_buffer(1 << 16);
// SAFETY: plain heap creation, views of a live buffer.
let heap: ID3D12DescriptorHeap = unsafe {
gpu.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: 16,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
}
.unwrap();
// SAFETY: as above.
let (cpu, table, step) = unsafe {
(
heap.GetCPUDescriptorHandleForHeapStart().ptr,
heap.GetGPUDescriptorHandleForHeapStart(),
gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize,
)
};
let names = ["raw", "structured 24 at 24", "structured 16", "typed u32", "typed u16", "typed 4 x u32", "constant buffer", "null raw"];
let view = |i: usize, format: i32, first: u64, count: u32, stride: u32, raw: bool, null: bool| {
let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT(format),
ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_SRV {
FirstElement: first,
NumElements: count,
StructureByteStride: stride,
Flags: if raw { D3D12_BUFFER_SRV_FLAG_RAW } else { D3D12_BUFFER_SRV_FLAG_NONE },
},
},
};
let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu + i * step };
// SAFETY: a slot of our heap, a live buffer.
unsafe { gpu.device.CreateShaderResourceView(if null { None } else { Some(&buffer) }, Some(&desc), at) };
};
for base in [0, 8] {
view(base, 39, 0, 1024, 0, true, false);
view(base + 1, 0, 1, 170, 24, false, false);
view(base + 2, 0, 0, 256, 16, false, false);
view(base + 3, 42, 0, 1024, 0, false, false);
view(base + 4, 57, 0, 2048, 0, false, false);
view(base + 5, 3, 0, 256, 0, false, false);
view(base + 7, 39, 0, 1, 0, true, true);
let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
// SAFETY: a live buffer.
BufferLocation: unsafe { buffer.GetGPUVirtualAddress() },
SizeInBytes: 4096,
};
// SAFETY: a slot of our heap.
unsafe { gpu.device.CreateConstantBufferView(Some(&desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu + (base + 6) * step }) };
}
let table2 = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: table.ptr + 8 * step as u64 };
let offsets = [0u32, 4092, 4096, 4104, 8192, 65536, 524_288, (1 << 20) - 4];
for mode in ["one load (uniform)", "a load a thread", "constant buffer load"] {
println!("{mode}:");
for (which, name) in names.iter().enumerate() {
// SAFETY: our open list, live buffers.
unsafe {
std::ptr::write_bytes(out_ptr, 0x77, 1 << 16);
gpu.list.SetDescriptorHeaps(&[Some(heap.clone())]);
gpu.list.SetComputeRootSignature(&pass.root);
gpu.list.SetPipelineState(&pass.pso);
gpu.list.SetComputeRootDescriptorTable(1, table);
gpu.list.SetComputeRootUnorderedAccessView(2, out_gpu);
gpu.list.SetComputeRootDescriptorTable(3, table2);
for (k, &offset) in offsets.iter().enumerate() {
let step = match mode.as_bytes()[0] {
b'o' => 0u32,
b'c' => 1,
_ => 4,
};
// (A thread's loads end at the offset.)
let first = if step == 4 { offset.saturating_sub(63 * 4) } else { offset };
let constants = [which as u32, first, step, k as u32 * 256];
gpu.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0);
gpu.list.Dispatch(1, 1, 1);
}
}
gpu.submit_and_wait();
let found: Vec<String> = offsets
.iter()
.enumerate()
.map(|(k, &offset)| {
let thread = if mode.as_bytes()[0] == b'a' { (offset.min(63 * 4) / 4) as usize } else { 0 };
// SAFETY: inside the mapping.
let word = unsafe { out_ptr.cast::<u32>().add(k * 64 + thread).read_volatile() };
format!("{offset}: {word:#x}")
})
.collect();
println!(" {name:20} {}", found.join(" "));
}
}
// SAFETY: a plain query.
println!("device: {:?}", unsafe { gpu.device.GetDeviceRemovedReason() });
}
/// Whether the card can read a texture's descriptor half written
/// (ignored: a measurement of the card, `VICTORY_BENCH_S` seconds a way,
/// 5). Two slots change between a texture of 64x64 and one of 2048x2048
/// as fast as a thread can write them, while groups that each load the
/// descriptor anew ask its size and read its last texel: size and texel
/// of two textures are one descriptor half written. (Both lie in one heap
/// that is there as a whole: a read past the small one finds memory.)
#[test]
#[ignore]
fn descriptors_written_under_readers() {
let Some(mut gpu) = WarpHarness::on(std::env::var_os("VICTORY_BENCH_WARP").is_some()) else {
return;
};
let seconds = std::env::var("VICTORY_BENCH_S").ok().and_then(|v| v.parse().ok()).unwrap_or(5u64);
const SOURCE: &str = r#"
#define RS "RootConstants(num32BitConstants=1,b0), DescriptorTable(SRV(t0,numDescriptors=2,flags=DESCRIPTORS_VOLATILE)), UAV(u0)"
cbuffer C : register(b0) { uint odd; }
Texture2D<float4> t[2] : register(t0);
RWByteAddressBuffer o : register(u0);
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
uint w, h, n;
uint which = (g.x + odd) & 1;
t[which].GetDimensions(0, w, h, n);
uint r = (uint)(t[which].Load(int3(w - 1, h - 1, 0)).x * 255.0 + 0.5);
// 0: small, 1: large, 2: no size of the two, 3: small with another texel, 4: large with another
uint kind = (w == 64 && h == 64) ? (r == 17 ? 0 : 3) : (w == 2048 && h == 2048) ? (r == 34 ? 1 : 4) : 2;
if (i == 0) {
uint was;
o.InterlockedAdd(kind * 4, 1, was);
if (kind > 1) { o.Store(32, w); o.Store(36, h); o.Store(40, r); }
}
}
"#;
let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile");
let texture = |size: u64| D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: size,
Height: size as u32,
DepthOrArraySize: 1,
MipLevels: 1,
Format: DXGI_FORMAT(28),
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
..Default::default()
};
// SAFETY: plain creation; each texture in its own half of the heap.
let (heap, textures) = unsafe {
let mut heap: Option<ID3D12Heap> = None;
gpu.device
.CreateHeap(
&D3D12_HEAP_DESC {
SizeInBytes: 64 << 20,
Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
Alignment: 0,
Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES,
},
&mut heap,
)
.unwrap();
let heap = heap.unwrap();
let textures = [(0u64, 64u64), (32 << 20, 2048)].map(|(at, size)| {
let mut made: Option<ID3D12Resource> = None;
gpu.device
.CreatePlacedResource(&heap, at, &texture(size), D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made)
.unwrap();
made.unwrap()
});
(heap, textures)
};
// Fill them: 17 and 34 in every byte.
for (texture, (size, byte)) in textures.iter().zip([(64u32, 17u8), (2048, 34)]) {
let pitch = size * 4;
let (from, data, _) = gpu.shared_buffer(u64::from(pitch) * u64::from(size));
// SAFETY: the mapping holds the bytes; an open list, live resources.
unsafe {
std::ptr::write_bytes(data, byte, (pitch * size) as usize);
let src = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&from),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: 0,
Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
Format: DXGI_FORMAT(28),
Width: size,
Height: size,
Depth: 1,
RowPitch: pitch,
},
},
},
};
let dst = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(texture),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
};
gpu.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None);
gpu.list.ResourceBarrier(&[crate::host::transition(
texture,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
)]);
}
gpu.submit_and_wait();
}
let view_heap = |visible: bool| -> ID3D12DescriptorHeap {
// SAFETY: plain heap creation.
unsafe {
gpu.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: 4,
Flags: if visible { D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE } else { D3D12_DESCRIPTOR_HEAP_FLAG_NONE },
NodeMask: 0,
})
}
.unwrap()
};
let (shown, kept) = (view_heap(true), view_heap(false));
// SAFETY: live heaps.
let (to, from, step) = unsafe {
(
shown.GetCPUDescriptorHandleForHeapStart().ptr,
kept.GetCPUDescriptorHandleForHeapStart().ptr,
gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize,
)
};
let at = |base: usize, i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: base + i * step };
for (i, texture) in textures.iter().enumerate() {
// SAFETY: slots of our heaps, live textures.
unsafe {
gpu.device.CreateShaderResourceView(texture, None, at(from, i));
gpu.device.CreateShaderResourceView(texture, None, at(to, i));
}
}
let bytes = |base: usize, i: usize| {
// SAFETY: a heap's handle; what it points at is read if it is memory.
let mut out = vec![0u8; step];
crate::host::read_into((base + i * step) as *const u8, &mut out).then_some(out)
};
println!("step {step}, the heaps' handles point at {:#x} and {:#x} (shown, kept)", to, from);
for i in 0..2 {
println!(" shown {i}: {:02x?}", bytes(to, i));
println!(" kept {i}: {:02x?}", bytes(from, i));
}
let same = bytes(to, 0).is_some() && bytes(to, 0) == bytes(from, 0) && bytes(to, 1) == bytes(from, 1);
println!("the shown heap's memory is the descriptors' own bytes: {same}");
let images = [bytes(from, 0), bytes(from, 1)];
// SAFETY: a live heap.
let table = unsafe { shown.GetGPUDescriptorHandleForHeapStart() };
for way in ["view creation", "copies from a CPU heap", "one 32 byte store"] {
if way.starts_with("one") && !(same && step == 32) {
continue;
}
let (_out, out_ptr, out_gpu) = gpu.shared_buffer(1 << 12);
// SAFETY: the mapping.
unsafe { std::ptr::write_bytes(out_ptr, 0, 1 << 12) };
let stop = std::sync::atomic::AtomicBool::new(false);
let writes = std::sync::atomic::AtomicU64::new(0);
std::thread::scope(|scope| {
let device = gpu.device.clone();
let (stop, writes, textures, images) = (&stop, &writes, &textures, &images);
scope.spawn(move || {
let mut k = 0usize;
while !stop.load(std::sync::atomic::Ordering::Relaxed) {
for slot in 0..2 {
let which = (k + slot) & 1;
// SAFETY: slots of our heaps, live textures.
unsafe {
match way.as_bytes()[0] {
b'v' => device.CreateShaderResourceView(&textures[which], None, at(to, slot)),
b'c' => device.CopyDescriptorsSimple(
1,
at(to, slot),
at(from, which),
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
),
_ => store32(to + slot * step, images[which].as_deref().unwrap()),
}
}
}
k += 1;
writes.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
}
});
let started = std::time::Instant::now();
let mut odd = 0u32;
while started.elapsed().as_secs() < seconds {
// SAFETY: our open list, live objects.
unsafe {
gpu.list.SetDescriptorHeaps(&[Some(shown.clone())]);
gpu.list.SetComputeRootSignature(&pass.root);
gpu.list.SetPipelineState(&pass.pso);
gpu.list.SetComputeRootDescriptorTable(1, table);
gpu.list.SetComputeRootUnorderedAccessView(2, out_gpu);
for _ in 0..8 {
gpu.list.SetComputeRoot32BitConstants(0, 1, (&raw const odd).cast(), 0);
gpu.list.Dispatch(65_535, 1, 1);
odd += 1;
}
}
gpu.submit_and_wait();
}
stop.store(true, std::sync::atomic::Ordering::Relaxed);
});
// SAFETY: the mapping, the card is done.
let found: Vec<u32> = (0..11).map(|i| unsafe { out_ptr.cast::<u32>().add(i).read_volatile() }).collect();
println!(
"{way}: {} writes; groups that saw the small texture {}, the large {}; no size of the two {}, the small size with another texel {}, the large size with another texel {}; the last such: {}x{} texel {}",
writes.load(std::sync::atomic::Ordering::Relaxed),
found[0],
found[1],
found[2],
found[3],
found[4],
found[8],
found[9],
found[10]
);
// SAFETY: a plain query.
println!(" device: {:?}", unsafe { gpu.device.GetDeviceRemovedReason() });
}
drop(heap);
}
/// 32 bytes to `to` (32 byte aligned) in one store, then a fence.
///
/// # Safety
/// `to` is 32 bytes of memory that may be written.
unsafe fn store32(to: usize, bytes: &[u8]) {
#[target_feature(enable = "avx")]
unsafe fn store(to: usize, bytes: *const u8) {
use std::arch::x86_64::*;
// SAFETY: the caller's.
unsafe {
_mm256_stream_si256(to as *mut __m256i, _mm256_loadu_si256(bytes.cast()));
_mm_sfence();
}
}
assert!(std::is_x86_feature_detected!("avx") && bytes.len() == 32 && to.is_multiple_of(32));
// SAFETY: asked for above; the caller's memory.
unsafe { store(to, bytes.as_ptr()) }
}
/// What a texture read in another dimension than its view's gives
/// (ignored: a measurement of the card): a view of a small 2D texture
/// read as an array, a volume and a cube, and a small volume read as 2D,
/// far out. The texture lies at the start of a heap whose other megabytes
/// hold other bytes: a texel of those is a read past the texture.
#[test]
#[ignore]
fn textures_read_in_another_dimension() {
let Some(mut gpu) = WarpHarness::on(std::env::var_os("VICTORY_BENCH_WARP").is_some()) else {
return;
};
const SOURCE: &str = r#"
#define RS "RootConstants(num32BitConstants=2,b0), DescriptorTable(SRV(t0,numDescriptors=4,flags=DESCRIPTORS_VOLATILE)), UAV(u0), StaticSampler(s0,filter=FILTER_MIN_MAG_MIP_POINT,addressU=TEXTURE_ADDRESS_WRAP,addressV=TEXTURE_ADDRESS_WRAP,addressW=TEXTURE_ADDRESS_WRAP)"
cbuffer C : register(b0) { uint how; uint far; }
Texture2D<float4> flat_ : register(t0);
Texture2DArray<float4> layers : register(t1);
Texture3D<float4> volume : register(t2);
TextureCubeArray<float4> cube : register(t3);
SamplerState s : register(s0);
RWByteAddressBuffer o : register(u0);
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 t : SV_DispatchThreadID) {
uint2 at = uint2(t.x & 7, t.x >> 3);
float4 c = 0;
if (how == 0) c = flat_.Load(int3(at, 0));
if (how == 1) c = layers.Load(int4(at, far, 0));
if (how == 2) c = volume.Load(int4(at, far, 0));
if (how == 3) c = layers.SampleLevel(s, float3((at + 0.5) / 64, far), 0);
if (how == 4) c = volume.SampleLevel(s, float3((at + 0.5) / 64, (far + 0.5) / 4096.0), 0);
if (how == 5) c = cube.SampleLevel(s, float4(1, (at + 0.5) / 64, far), 0);
if (how == 6) c = flat_.Load(int3(at, far));
uint r = (uint)(c.x * 255.0 + 0.5), was;
// the texture's own bytes, zeros, anything else
o.InterlockedAdd(r == 17 ? 0 : r == 0 ? 4 : 8, 1, was);
if (r != 17 && r != 0) o.Store(12, r);
}
"#;
let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile");
// SAFETY: plain creation, each thing in its own part of the heap.
let (_heap, small) = unsafe {
let mut heap: Option<ID3D12Heap> = None;
gpu.device
.CreateHeap(
&D3D12_HEAP_DESC {
SizeInBytes: 256 << 20,
Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
Alignment: 0,
Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES,
},
&mut heap,
)
.unwrap();
let heap = heap.unwrap();
let place = |at: u64, size: u64| {
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: size,
Height: size as u32,
DepthOrArraySize: 1,
MipLevels: 1,
Format: DXGI_FORMAT(28),
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
..Default::default()
};
let mut made: Option<ID3D12Resource> = None;
gpu.device
.CreatePlacedResource(&heap, at, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made)
.unwrap();
made.unwrap()
};
let small = place(0, 64);
// The rest: 34 in every byte.
let mut fill: Vec<(ID3D12Resource, u32, u8)> = vec![(small.clone(), 64, 17)];
for k in 0..15u64 {
fill.push((place((1 + k) << 24, 2048), 2048, 34));
}
for k in 1..16u64 {
fill.push((place(k << 20, 512), 512, 34));
}
for (texture, size, byte) in fill {
let pitch = size * 4;
let (from, data, _) = gpu.shared_buffer(u64::from(pitch) * u64::from(size));
std::ptr::write_bytes(data, byte, (pitch * size) as usize);
let src = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&from),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: 0,
Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
Format: DXGI_FORMAT(28),
Width: size,
Height: size,
Depth: 1,
RowPitch: pitch,
},
},
},
};
let dst = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&texture),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
};
gpu.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None);
gpu.list.ResourceBarrier(&[crate::host::transition(
&texture,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
)]);
gpu.submit_and_wait();
}
(heap, small)
};
// SAFETY: plain heap creation; slots of it, a live texture.
let heap: ID3D12DescriptorHeap = unsafe {
let heap: ID3D12DescriptorHeap = gpu
.device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: 4,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
.unwrap();
let step = gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize;
for i in 0..4 {
let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: heap.GetCPUDescriptorHandleForHeapStart().ptr + i * step };
// A 2D view of the small texture in every slot.
gpu.device.CreateShaderResourceView(&small, None, at);
}
heap
};
for (how, name) in
["2D", "array, loaded", "volume, loaded", "array, sampled", "volume, sampled", "cube array", "2D, a level it has not"]
.iter()
.enumerate()
{
for far in [0u32, 1, 7, 63, 1000, 4000] {
let (_out, out_ptr, out_gpu) = gpu.shared_buffer(1 << 12);
// SAFETY: the mapping; our open list, live objects.
unsafe {
std::ptr::write_bytes(out_ptr, 0, 1 << 12);
gpu.list.SetDescriptorHeaps(&[Some(heap.clone())]);
gpu.list.SetComputeRootSignature(&pass.root);
gpu.list.SetPipelineState(&pass.pso);
gpu.list.SetComputeRoot32BitConstants(0, 2, [how as u32, far].as_ptr().cast(), 0);
gpu.list.SetComputeRootDescriptorTable(1, heap.GetGPUDescriptorHandleForHeapStart());
gpu.list.SetComputeRootUnorderedAccessView(2, out_gpu);
gpu.list.Dispatch(1, 1, 1);
}
gpu.submit_and_wait();
// SAFETY: the mapping, the card is done.
let found: Vec<u32> = (0..4).map(|i| unsafe { out_ptr.cast::<u32>().add(i).read_volatile() }).collect();
println!("{name} at {far}: its own texels {}, zeros {}, others {} (the last {})", found[0], found[1], found[2], found[3]);
}
}
// SAFETY: a plain query.
println!("device: {:?}", unsafe { gpu.device.GetDeviceRemovedReason() });
}
/// The clamp compiles with the system's compiler and the host takes it.
#[test]
fn argument_clamp_builds() {
+6
View File
@@ -75,6 +75,12 @@ mod watch;
#[cfg(windows)]
pub use host::on_failure;
/// What the frame is at (`copystat::phase`), for the sampling profiler.
#[cfg(all(windows, feature = "diagnostics"))]
pub fn frame_phase() -> u32 {
copystat::phase()
}
#[cfg(windows)]
pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view};
#[cfg(windows)]
+19
View File
@@ -1023,6 +1023,25 @@ extern "system" fn copy_texture_region(
// A depth texture shaders also write: what they wrote, first (the
// source above too).
list.twin_use(dst.resource, false, true);
// The first copy into a texture of the title's: what it does not
// write is what title memory holds, as on the console. (The host
// copy is cut from a block and held whatever lay there, and no
// upload is made once a copy wrote it: the atlas the title copies
// its baked decorations into, a 2048x2048 BC3 texture of which a
// bake writes 256x256 at most, was drawn over a character's face
// with other textures' bytes wherever nothing was baked, runs n01 and
// textures-1.)
static OVER: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if *OVER.get_or_init(|| std::env::var_os("VICTORY_COPY_OVER_TITLE").is_none_or(|v| v != "0"))
&& crate::texture::title_written(to)
&& !crate::texture::host_wrote(dst.resource as usize)
{
crate::texture::upload(list, dst.resource, to);
// (Done before the title's copy writes over it.)
if list.used(dst.resource as usize) {
ensure_state(list, dst.resource, COPY_SOURCE);
}
}
// A destination made level by level gets the level's memory ahead
// of this list (`crate::tiles`): the title's bake copies each level
// of its result into a block-compressed texture of that kind, and
+6 -2
View File
@@ -324,11 +324,15 @@ fn workers() -> bool {
let spawned = std::thread::Builder::new()
.name(format!("victory-pipelines-{i}"))
.spawn(|| {
// Below the title's own threads (loading, recording).
// Below the title's own threads (loading, recording),
// and the streaming one, which is below normal itself
// (`VICTORY_PIPELINE_LOWEST=0`: level with it, as before).
let lowest = std::env::var_os("VICTORY_PIPELINE_LOWEST").is_none_or(|v| v != "0");
// SAFETY: a plain call on our own thread.
unsafe {
use windows::Win32::System::Threading::*;
let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
let priority = if lowest { THREAD_PRIORITY_LOWEST } else { THREAD_PRIORITY_BELOW_NORMAL };
let _ = SetThreadPriority(GetCurrentThread(), priority);
}
loop {
next().make();
+56 -9
View File
@@ -20,7 +20,7 @@
use std::collections::{BTreeMap, VecDeque};
use std::ffi::c_void;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering};
use windows::Win32::Graphics::Direct3D12::*;
use windows::core::{GUID, HRESULT, IUnknown, Interface};
@@ -29,6 +29,28 @@ use windows::core::{GUID, HRESULT, IUnknown, Interface};
const BLOCK: u64 = 64 << 20;
/// Blocks with nothing in them that are kept.
const SPARE: usize = 2;
/// The same while the card has room ([`room`]): 4 GiB of them.
const SPARE_KEPT: usize = 64;
/// The same of blocks of staging buffers, which are the PC's memory: run
/// crash-1 held 5.2 GB of them.
const STAGING_KEPT: usize = 8;
/// How many are kept now.
static SPARES: AtomicUsize = AtomicUsize::new(SPARE);
/// Sets how many empty blocks stay, by the card's memory (budget and use):
/// [`SPARE_KEPT`] below 85 % ([`crate::host::keep_freed`]), else [`SPARE`].
/// Asked once a second.
pub(crate) fn room(memory: Option<[u64; 4]>) {
SPARES.store(spares(memory, crate::host::keep_freed()), Ordering::Relaxed);
}
fn spares(memory: Option<[u64; 4]>, keep: bool) -> usize {
match memory {
Some([budget, used, ..]) if keep && u128::from(used) * 100 < u128::from(budget) * 85 => SPARE_KEPT,
_ => SPARE,
}
}
/// Milliseconds until a piece given back is used again. (It was three
/// frames, a tenth of a second while the title shows a loading screen at 30
/// a second, with up to 18 submissions in the air.)
@@ -106,11 +128,14 @@ struct Pool<B> {
blocks: Vec<Option<Block<B>>>,
/// Pieces given back, and when each may be used again.
resting: VecDeque<(u64, Piece)>,
/// The empty blocks it was last told to keep, and the most it keeps.
spare: usize,
most: usize,
}
impl<B: Clone> Pool<B> {
const fn new() -> Pool<B> {
Pool { blocks: Vec::new(), resting: VecDeque::new() }
const fn new(most: usize) -> Pool<B> {
Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most }
}
/// A piece of `len` bytes and the memory it lies in, and whether that
@@ -168,12 +193,15 @@ impl<B: Clone> Pool<B> {
any |= block.free.whole(BLOCK);
}
}
if any {
// (Without a piece given back too, once there is less room.)
let most = SPARES.load(Ordering::Relaxed).min(self.most);
if any || most < self.spare {
self.spare = most;
let mut spare = 0;
for block in &mut self.blocks {
if block.as_ref().is_some_and(|b| b.free.whole(BLOCK)) {
spare += 1;
if spare > SPARE {
if spare > most {
*block = None;
}
}
@@ -192,13 +220,22 @@ struct Upload(ID3D12Resource, *mut u8);
// SAFETY: the mapping is written by the owners of its pieces, each its own.
unsafe impl Send for Upload {}
static TEXTURES: Mutex<Pool<ID3D12Heap>> = Mutex::new(Pool::new());
static STAGING: Mutex<Pool<Upload>> = Mutex::new(Pool::new());
static TEXTURES: Mutex<Pool<ID3D12Heap>> = Mutex::new(Pool::new(SPARE_KEPT));
static STAGING: Mutex<Pool<Upload>> = Mutex::new(Pool::new(STAGING_KEPT));
fn lock<T>(m: &'static Mutex<T>) -> std::sync::MutexGuard<'static, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
/// Bytes of the pieces textures hold now.
static HELD: AtomicU64 = AtomicU64::new(0);
/// Bytes of the texture blocks no texture holds: the card's memory in use
/// by us that new textures take first.
pub(crate) fn texture_room() -> u64 {
(lock(&TEXTURES).blocks() as u64 * BLOCK).saturating_sub(HELD.load(Ordering::Relaxed))
}
/// For the memory line: blocks of textures and of staging buffers, in MiB.
#[cfg(feature = "diagnostics")]
pub(crate) fn memory() -> [u64; 2] {
@@ -282,6 +319,7 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 {
let left = (*this.cast::<Reclaim>()).references.fetch_sub(1, Ordering::AcqRel) - 1;
if left == 0 {
let gone = Box::from_raw(this.cast::<Reclaim>());
HELD.fetch_sub(gone.piece.len, Ordering::Relaxed);
lock(&TEXTURES).give(gone.piece, now());
}
left
@@ -351,6 +389,7 @@ pub(crate) unsafe fn texture(
let result = unsafe { device.CreatePlacedResource(&heap, piece.start, &d, state, None, &mut made) };
match (result, made) {
(Ok(()), Some(made)) => {
HELD.fetch_add(piece.len, Ordering::Relaxed);
give_back_with(&made, piece);
Some(made)
}
@@ -379,9 +418,17 @@ mod tests {
assert!(r.whole(1024));
}
#[test]
fn empty_blocks_stay_while_the_card_has_room() {
assert_eq!(spares(Some([100, 84, 0, 0]), true), SPARE_KEPT);
assert_eq!(spares(Some([100, 85, 0, 0]), true), SPARE);
assert_eq!(spares(Some([100, 10, 0, 0]), false), SPARE);
assert_eq!(spares(None, true), SPARE);
}
#[test]
fn pieces_never_overlap_and_rest_before_they_are_used_again() {
let mut pool: Pool<u32> = Pool::new();
let mut pool: Pool<u32> = Pool::new(SPARE);
let made = std::cell::Cell::new(0);
let make = || {
made.set(made.get() + 1);
@@ -411,7 +458,7 @@ mod tests {
assert_eq!(pool.blocks(), blocks.min(SPARE));
// Too big for a block, and a block that cannot be made.
assert!(pool.take(BLOCK, 65536, 30, make).is_none());
let mut none: Pool<u32> = Pool::new();
let mut none: Pool<u32> = Pool::new(SPARE);
assert!(none.take(65536, 65536, 0, || None).is_none());
}
+316 -4
View File
@@ -98,6 +98,20 @@ pub(crate) struct ResourceDesc {
flags: u32,
}
#[cfg(windows)]
impl ResourceDesc {
/// The texture of this one's levels from `base` on.
fn from_level(&self, base: u32) -> ResourceDesc {
let mut d = *self;
if base > 0 {
d.width = (d.width >> base).max(1);
d.height = (d.height >> base).max(1);
d.mip_levels -= base as u16;
}
d
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct AllocationInfo {
@@ -1137,8 +1151,27 @@ pub(crate) struct HostTexture {
/// levels have been given. Its `bytes` are 0: what it holds of the card
/// is counted there.
pub(crate) tiled: Option<crate::tiles::Tiled>,
/// The title's level its level 0 is ([`held_only`]): larger levels have
/// no place in it.
pub(crate) base: u32,
/// Tells host copies apart that one texture had one after the other.
pub(crate) serial: u64,
/// Made in place of one with fewer levels: the slots that show that one
/// are made again once this one was filled whole.
pub(crate) grown: std::sync::atomic::AtomicBool,
/// What the last submitted upload put in it.
pub(crate) holds: std::sync::Arc<Holds>,
}
/// What a host copy was filled with last: the first level of it and the
/// hash of the title memory it was read from.
#[cfg(windows)]
pub(crate) type Holds = std::sync::Mutex<Option<(u32, blake3::Hash)>>;
/// [`HostTexture::serial`] of the last one made.
#[cfg(windows)]
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// What a title texture has on the host: its host copy and, for a depth
/// texture shaders also write, the colour twin.
#[cfg(windows)]
@@ -1167,6 +1200,149 @@ struct Hosted {
gone: std::sync::atomic::AtomicBool,
/// A texture of [`PLACED_TEXTURES`].
placed: std::sync::atomic::AtomicBool,
/// The lowest level a view asked for since it had no host copy
/// ([`want_level`]; `u32::MAX`: none said).
wanted: std::sync::atomic::AtomicU32,
/// The next host copy takes the place of one with fewer levels.
grown: std::sync::atomic::AtomicBool,
}
/// Whether a texture the title places in memory is read, kept and uploaded
/// from the first level its views show on (`VICTORY_HELD_LEVELS=0`: whole,
/// as before). Such a title describes every level of a texture and views it
/// from the first one it holds; the memory of the larger ones is the next
/// texture's, or nothing. Of two recorded world frames the levels some slot
/// shows are 1.2 and 1.6 GB of the 6.3 and 6.7 GB of such host copies, and
/// most of what was found "changed" and uploaded again was other textures'
/// bytes.
#[cfg(windows)]
pub(crate) fn held_only() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| {
std::env::var_os("VICTORY_HELD_LEVELS").is_none_or(|v| v != "0") && !crate::tiles::wanted()
})
}
/// The first level a placed texture's view shows: of views of one 2D
/// texture (the others show whole textures). After victory-amd 4436f8f1.
pub(crate) fn first_mip(view: &[u32]) -> u32 {
const TEXTURE_2D_VIEW: u32 = 4;
match *view {
[_, TEXTURE_2D_VIEW, _, _, first, ..] => first.min(15),
_ => 0,
}
}
/// The level from which on a texture of layout `layout` is read for a view
/// that starts at `first`: the smallest levels share a block and are read
/// together; 0 where the larger ones lie between the smaller ones.
pub(crate) fn read_from(layout: &victory_formats::texture::Layout, first: u32) -> u32 {
if layout.slices != 1 || layout.mips.is_empty() {
return 0;
}
let first = first.min(layout.first_tail_mip).min(layout.mips.len() as u32 - 1);
if layout.bytes_from(first) < layout.size { first } else { 0 }
}
/// The level a host copy begins at for views that start at `first`: one the
/// host can have as a texture's level 0 ([`read_from`]; block-compressed
/// formats in whole blocks).
#[cfg(windows)]
fn base_level(desc: &ResourceDesc, first: u32) -> u32 {
const TEXTURE_2D: u32 = 3;
if first == 0
|| !fills(desc)
|| desc.dimension != TEXTURE_2D
|| desc.depth_or_array_size != 1
|| desc.mip_levels <= 1
|| desc.sample_count > 1
{
return 0;
}
let Some(t) = texture_layout(desc).filter(|t| t.planes.len() == 1) else {
return 0;
};
let layout = &t.planes[0].layout;
if layout.desc.swizzle.xor() {
return 0;
}
let block = u64::from(layout.desc.block.max(1));
let mut base = read_from(layout, first).min(u32::from(desc.mip_levels) - 1);
let whole = |side: u64| side != 0 && side.is_multiple_of(block);
while base > 0 && !(whole(desc.width >> base) && whole(u64::from(desc.height) >> base)) {
base -= 1;
}
base
}
/// The bytes of title memory a placed texture with the resource description
/// `desc` is read from for a view that starts at level `first`; `None` as
/// [`placed_bytes`]. Remembered: asked for every slot that is looked at.
#[cfg(windows)]
pub(crate) fn placed_bytes_from(desc: &[u32; 14], first: u32) -> Option<u64> {
if first == 0 || !held_only() {
return placed_bytes(desc);
}
type Known = std::collections::HashMap<([u32; 14], u32), Option<u64>>;
thread_local! {
static KNOWN: std::cell::RefCell<Known> = std::cell::RefCell::default();
}
KNOWN.with(|known| {
*known.borrow_mut().entry((*desc, first)).or_insert_with(|| {
let whole = placed_bytes(desc)?;
// SAFETY: 56 bytes in the description's layout.
let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() };
let Some(t) = texture_layout(&d).filter(|t| t.planes.len() == 1) else {
return Some(whole);
};
let layout = &t.planes[0].layout;
Some(layout.bytes_from(read_from(layout, first)).min(whole))
})
})
}
/// Host copies replaced by ones with more levels, for as long as a thread
/// that asked for one may still be about to record its use
/// ([`host_resource`]): when, and the copy.
#[cfg(windows)]
static REPLACED: std::sync::Mutex<Vec<(u64, Made)>> = std::sync::Mutex::new(Vec::new());
/// Since the start: host copies made with a first level other than the
/// title's, and their bytes; host copies replaced by one with more levels;
/// bytes of title memory such copies' textures take whole.
#[cfg(windows)]
pub(crate) static HELD: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
/// A view of the placed texture `this` that starts at level `first` is made
/// or brought up to date: a host copy without that level is replaced by one
/// with it (made and filled at the next use; the slots that show the old
/// one go on showing it until that is done).
#[cfg(windows)]
pub(crate) fn want_level(this: This, first: u32) {
use std::sync::atomic::Ordering::Relaxed;
if this.is_null() || !held_only() {
return;
}
let r = resource(this);
if r.desc.dimension == BUFFER || !r.host.placed.load(Relaxed) {
return;
}
let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
let Some((host, _)) = made.as_ref() else {
r.host.wanted.fetch_min(first, Relaxed);
return;
};
if host.base == 0 || host.base <= base_level(&r.desc, first) {
return;
}
r.host.wanted.store(first, Relaxed);
// Under the lock, as in `let_go_idle`.
crate::texture::unstage(this);
r.host.grown.store(true, Relaxed);
HELD[2].fetch_add(1, Relaxed);
if let Some(old) = made.take() {
REPLACED.lock().unwrap_or_else(|e| e.into_inner()).push((crate::host::moment(), old));
}
}
/// Counts for the memory line: host copies of textures the title fills
@@ -1254,6 +1430,30 @@ pub(crate) fn alias_of(this: This) -> Option<This> {
&& o.desc.flags & DEPTH == 0
&& target_format(o.desc.format) == o.desc.format
&& element(o.desc.format).is_some_and(|e| e.1 == 1 && Some(e) == element(r.desc.format));
if !same && r.desc.sample_count <= 1 {
// What shaders wrote there is on the card in the other texture; this
// one is filled from title memory, which they never reached. Each
// kind of pair is said once.
static SAID: std::sync::Mutex<std::collections::BTreeSet<[u32; 6]>> =
std::sync::Mutex::new(std::collections::BTreeSet::new());
let pair = [
r.desc.width as u32,
r.desc.height,
r.desc.format,
o.desc.width as u32,
o.desc.height,
o.desc.format,
];
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
if said.len() < 64 && said.insert(pair) {
tracing::warn!(
view = ?this,
texture = ?other,
"a placed texture lies where a texture the host writes does, and is not like it (width, height, format of each): {pair:?}, levels {} and {}, layers {} and {}",
r.desc.mip_levels, o.desc.mip_levels, r.desc.depth_or_array_size, o.desc.depth_or_array_size
);
}
}
same.then_some(other)
}
@@ -1353,9 +1553,20 @@ fn hosted(this: This, make: bool) -> Option<Made> {
texture = reserved;
}
}
// The levels views show ([`held_only`]), those of the slots shaders
// pick by index among them.
let mut base = 0;
if shape_fits && r.host.placed.load(Relaxed) && held_only() && alias_of(this).is_none() {
let wanted = r.host.wanted.load(Relaxed);
let viewed = crate::descriptor::host::first_viewed(r.data() as u64).unwrap_or(u32::MAX);
let first = wanted.min(viewed);
if first != u32::MAX {
base = base_level(&r.desc, first);
}
}
let texture = match texture {
Some(texture) => Some(texture),
None => host_texture(&r.desc, r.host.state, clear),
None => host_texture(&r.desc.from_level(base), r.host.state, clear),
};
let Some(texture) = texture else {
r.host.refused.store(true, Relaxed);
@@ -1378,6 +1589,13 @@ fn hosted(this: This, make: bool) -> Option<Made> {
Some(tiled) => HostTexture::new_tiled(texture, state, tiled),
None => HostTexture::new(texture, state),
};
host.base = base;
host.grown.store(r.host.grown.swap(false, Relaxed), Relaxed);
if base > 0 {
HELD[0].fetch_add(1, Relaxed);
HELD[1].fetch_add(host.bytes, Relaxed);
HELD[3].fetch_add(footprint(&r.desc).map_or(0, |f| f.size), Relaxed);
}
host.filled = fills(&r.desc);
if host.filled {
KINDS[0].fetch_add(1, Relaxed);
@@ -1455,7 +1673,8 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool {
// 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()
used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() + targets_room_kept()
< budget / 100 * room_percent()
}
None => filled < WITHOUT_BUDGET,
}
@@ -1777,12 +1996,52 @@ pub(crate) fn let_go_idle() {
if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_none_or(|v| v != "0")) {
return;
}
let idle_ms = crate::host::vram_idle_ms(crate::host::host().and_then(|h| h.video_memory()));
// Copies replaced by ones with more levels, as any let go.
{
let mut replaced = REPLACED.lock().unwrap_or_else(|e| e.into_inner());
let (gone, keep): (Vec<_>, Vec<_>) =
replaced.drain(..).partition(|(at, _)| crate::host::long_ago(*at, 1000, IDLE_FRAMES));
*replaced = keep;
drop(replaced);
for (_, made) in gone {
crate::host::retire(made);
}
}
let memory = crate::host::host().and_then(|h| h.video_memory());
static KEEP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let keep = *KEEP
.get_or_init(|| !matches!(std::env::var("VICTORY_TEXTURE_KEEP").as_deref(), Ok("0") | Ok("1")));
let (idle_ms, most) = match memory {
Some([budget, used, ..]) if keep => {
let used = used.saturating_sub(crate::pool::texture_room())
+ crate::shadow::card_room_kept()
+ targets_room_kept();
crate::host::vram_keep(budget, used)
}
_ => (crate::host::vram_idle_ms(memory), u64::MAX),
};
// For the trail (`crate::host::trail`): how many went, their bytes,
// and the first one.
let (mut went, mut bytes, mut first) = (0u64, 0u64, None);
let all = textures();
for &at in all.iter() {
// With a limit, the longest idle first.
let mut by_age: Vec<(u64, usize)> = Vec::new();
if most != u64::MAX {
for &at in all.iter() {
// SAFETY: as below.
let r = unsafe { &*(at as *const Resource) };
let used = r.host.used.load(Relaxed);
if used != 0 && fills(&r.desc) && crate::host::long_ago(used, idle_ms, IDLE_FRAMES) {
by_age.push((used & 0xffff_ffff, at));
}
}
by_age.sort_unstable();
}
let every = all.iter().copied().filter(|_| most == u64::MAX);
for at in every.chain(by_age.iter().map(|&(_, at)| at)) {
if bytes >= most {
break;
}
// SAFETY: a texture leaves the table before it is freed, under the
// lock held here (`Drop for Resource`).
let r = unsafe { &*(at as *const Resource) };
@@ -1800,6 +2059,7 @@ pub(crate) fn let_go_idle() {
// Under the lock: the next use must not find the staging
// state of the texture let go (it says "uploaded").
crate::texture::unstage(at as This);
r.host.wanted.store(u32::MAX, Relaxed);
made.take()
} else {
None
@@ -1973,6 +2233,10 @@ impl HostTexture {
bytes,
filled: false,
tiled: None,
base: 0,
serial: SERIAL.fetch_add(1, Relaxed) + 1,
grown: Default::default(),
holds: Default::default(),
}
}
@@ -1990,6 +2254,10 @@ impl HostTexture {
bytes: 0,
filled: false,
tiled: Some(tiled),
base: 0,
serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
grown: Default::default(),
holds: Default::default(),
}
}
}
@@ -2054,6 +2322,15 @@ pub(crate) fn host_copy(this: This) -> Option<std::sync::Arc<HostTexture>> {
hosted(this, true).map(|made| made.0)
}
/// A title texture's host copy if it is made; not made here.
#[cfg(windows)]
pub(crate) fn made_copy(this: This) -> Option<std::sync::Arc<HostTexture>> {
if this.is_null() {
return None;
}
hosted(this, false).map(|made| made.0)
}
/// A host texture like the title's: same description, in GPU memory,
/// without the console's layout and flags.
#[cfg(windows)]
@@ -2330,6 +2607,8 @@ fn hand_out_resource(
refused: std::sync::atomic::AtomicBool::new(false),
gone: std::sync::atomic::AtomicBool::new(false),
placed: std::sync::atomic::AtomicBool::new(false),
wanted: std::sync::atomic::AtomicU32::new(u32::MAX),
grown: std::sync::atomic::AtomicBool::new(false),
},
});
// The host copy waits for the texture's first use ([`Hosted`]).
@@ -4140,4 +4419,37 @@ float4 lit() : SV_Target { return 1.0; }
assert_eq!(texture_floor_bytes(Some(24 * GIB)), 2 * GIB);
assert_eq!(texture_floor_bytes(Some(32 * GIB)), 2 * GIB);
}
/// A placed texture viewed from a later level has a host copy of that
/// and the smaller levels; a view from an earlier one gets another.
#[cfg(windows)]
#[test]
fn a_placed_texture_is_kept_from_the_level_viewed() {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
if crate::host::host().is_none() || !held_only() {
return;
}
// 256x256 BC7, nine levels, 4 KiB blocks.
let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0];
let whole = placed_bytes(&desc).unwrap();
let part = placed_bytes_from(&desc, 2).unwrap();
assert!(part * 8 < whole, "{part} of {whole}");
assert_eq!(placed_bytes_from(&desc, 0), Some(whole));
// SAFETY: memory of our own that stays.
let at = unsafe { VirtualAlloc(std::ptr::null(), whole as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) };
let texture = texture_at(at as u64, &desc).unwrap();
want_level(texture, 2);
let copy = host_copy(texture).unwrap();
// SAFETY: a live texture.
let d = unsafe { copy.texture.GetDesc() };
assert_eq!((copy.base, d.Width, d.Height, d.MipLevels), (2, 64, 64, 7));
want_level(texture, 5);
assert_eq!(host_copy(texture).unwrap().serial, copy.serial);
want_level(texture, 0);
let more = host_copy(texture).unwrap();
// SAFETY: as above.
let d = unsafe { more.texture.GetDesc() };
assert_eq!((more.base, d.Width, d.MipLevels), (0, 256, 9));
assert!(more.serial != copy.serial && more.grown.load(std::sync::atomic::Ordering::Relaxed));
}
}
+209 -18
View File
@@ -46,8 +46,20 @@ pub(crate) struct Staging {
footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>,
rows: Vec<u32>,
layout: victory_formats::texture::Layout,
/// Mips per array slice.
/// Mips per array slice, of the title's texture.
mips: u32,
/// The first of them that is read and uploaded
/// (`crate::resource::held_only`), the one the host copy begins at, and
/// the bytes of title memory read.
first: u32,
level0: u32,
read: usize,
/// Which host copy it uploads into, and what that is told to hold.
serial: u64,
holds: Arc<crate::resource::Holds>,
/// Title memory being remapped is waited for whatever [`no_wait`] says:
/// a list that bakes from the texture now recorded the upload.
waits: std::sync::atomic::AtomicBool,
/// The staging buffer's bytes (counted in `STAGED` while it lives).
bytes: u64,
memory: *const u8,
@@ -160,6 +172,8 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool {
const TARGET_OR_UNORDERED: u32 = 0x4 | 0x8;
const COPY_DEST: u32 = 0x400;
const COPY_SOURCE: u32 = 0x800;
// (All of its levels: the copy is level by level.)
crate::resource::want_level(placed, 0);
let (Some(to), Some(from)) = (
crate::resource::host_resource(placed),
crate::resource::host_resource(source),
@@ -629,7 +643,21 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool {
/// its host copy, and the detiling that refreshes the staging buffer at
/// submission if the memory changed. Leaves the texture in the copy
/// destination state.
pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) {
pub(crate) fn upload(list: &HostList, resource: This, _texture: &ID3D12Resource) {
upload_from(list, resource, 0);
}
thread_local! {
/// The thread records uploads for a draw that bakes from them
/// ([`Staging::waits`]).
pub(crate) static BAKING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// [`upload`] of the levels from `first` on, the ones a view shows: of a
/// texture the title placed there may be no memory of the larger ones, and
/// what lies there is another texture's. (After victory-amd 4436f8f1.)
pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
let first = if crate::resource::held_only() { first } else { 0 };
let host_written = HOST_WRITTEN
.lock()
.unwrap_or_else(|e| e.into_inner())
@@ -637,13 +665,28 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
.is_some_and(|set| set.contains(&(resource as usize)));
// shortcut: a texture the host copied into keeps the host's contents
// even if the title later writes its memory too.
if host_written || !list.first_use(resource as usize) {
if host_written {
return;
}
let Some(staging) = staging(resource, texture) else {
// Once a list for each first level; not again for one that the list's
// upload of larger ones held too.
if !list.first_use(1 << 63 | (resource as usize) << 4 | first as usize & 15) {
return;
}
if !list.first_use(resource as usize) && staged_from(resource) <= first {
return;
}
let Some(copy) = crate::resource::host_copy(resource) else {
return;
};
let texture = &copy.texture;
let Some(staging) = staging(resource, &copy, first) else {
return;
};
use std::sync::atomic::Ordering::Relaxed;
if BAKING.get() {
staging.waits.store(true, Relaxed);
}
staging.used.store(crate::host::moment(), Relaxed);
// Levels on demand: a view of the texture now starts at another
// level, or another texture now starts inside its span, with no byte
@@ -684,7 +727,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexUploads, 1);
if no_wait() && fill_unlocked() {
let there = mapped_bytes(staging.memory, staging.layout.size as usize);
let there = mapped_bytes(staging.memory, staging.read);
staging.expected.store(there, Relaxed);
}
const COPY_DEST: u32 = 0x400;
@@ -741,7 +784,7 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: i as u32,
SubresourceIndex: staging.first - staging.level0 + i as u32,
},
};
let from = D3D12_TEXTURE_COPY_LOCATION {
@@ -768,6 +811,13 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
staging.dirty.store(false, Relaxed);
});
}
// A host copy that took the place of one with fewer levels: the slots
// that show that one are made again once this upload has run.
if staging.first == staging.level0 && copy.grown.swap(false, Relaxed) {
let start = staging.memory as u64;
list.defer_host(move || crate::descriptor::host::levels_changed_after(start));
}
let noted = staging.clone();
// Levels on demand (`crate::tiles`): after the check below, in the
// order of this list's steps, and before the list is executed, the
// levels the staging buffer holds as the title's are given the card's
@@ -778,6 +828,8 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
let Some(on_demand) = on_demand else {
// Once per submission however many of its lists sample the texture.
list.defer_texture(staging);
// Then what the list's copy puts in the host copy is known.
list.defer_host(move || noted.note_held());
return;
};
list.defer_texture(staging.clone());
@@ -971,7 +1023,21 @@ impl Staging {
/// The title memory the texture is read from: address and bytes.
pub(crate) fn memory(&self) -> (usize, usize) {
(self.memory as usize, self.layout.size as usize)
(self.memory as usize, self.read)
}
/// The title's level and the array slice of the staging buffer's part
/// `i`.
fn part(&self, i: usize) -> (u32, u32) {
let mips = self.mips - self.first;
(self.first + i as u32 % mips, i as u32 / mips)
}
/// The host copy holds what the staging buffer was filled from
/// ([`unchanged`]).
fn note_held(&self) {
let hash = self.last.lock().unwrap_or_else(|e| e.into_inner()).hash;
*self.holds.lock().unwrap_or_else(|e| e.into_inner()) = hash.map(|hash| (self.first, hash));
}
/// Detiles the texture memory into the staging buffer if it changed
@@ -994,7 +1060,7 @@ impl Staging {
}
fn refresh_timed(&self) -> usize {
let size = self.layout.size as usize;
let size = self.read;
let start = self.memory as usize;
let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner()));
let last = &mut *last;
@@ -1061,7 +1127,7 @@ impl Staging {
// stays mapped (see `crate::watch::title_memory_reading`; without
// it a page went between the asking and the read in runs 71 and
// 74).
let _mapped = if no_wait() {
let _mapped = if no_wait() && !self.waits.load(std::sync::atomic::Ordering::Relaxed) {
// Not waited for: while the runtime remaps title memory the
// texture is read through the kernel instead, whole or not at
// all (`no_wait`).
@@ -1240,7 +1306,7 @@ impl Staging {
);
}
for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() {
let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips);
let (mip, slice) = self.part(i);
let f = footprint.Footprint;
let pitch = f.RowPitch as usize;
// The last row of the last subresource is not padded to its pitch
@@ -1330,6 +1396,59 @@ pub(crate) fn staged_state(resource: This) -> Option<(bool, bool)> {
Some((staging.uploaded.load(Relaxed), staging.dirty.load(Relaxed)))
}
/// The first level a title texture's staging buffer holds; `u32::MAX`
/// without one.
fn staged_from(resource: This) -> u32 {
let map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
map.as_ref()
.and_then(|map| map.get(&(resource as usize)))
.map_or(u32::MAX, |s| s.first)
}
/// Whether the levels from `first` on of `resource`'s host copy were filled
/// from the bytes title memory holds now: an upload would bring nothing new.
/// (Of 787 repeated uploads of a frame that streams 398 were equal in every
/// byte, and a texture uploaded again costs a staging buffer, a detiling and
/// a copy more than this look.) `VICTORY_TEXTURE_SAME=0`: not asked.
pub(crate) fn unchanged(resource: This, first: u32) -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SAME").is_none_or(|v| v != "0")) {
return false;
}
let Some(copy) = crate::resource::made_copy(resource) else {
return false;
};
let Some((from, held)) = *copy.holds.lock().unwrap_or_else(|e| e.into_inner()) else {
return false;
};
let Some((memory, desc)) = crate::resource::texture_memory(resource) else {
return false;
};
let Some(layout) = crate::resource::texture_layout(&desc) else {
return false;
};
let layout = &layout.planes[0].layout;
if from > crate::resource::read_from(layout, first).max(copy.base) {
return false;
}
let size = layout.bytes_from(from) as usize;
with_read(size, |read| {
if crate::host::read_there(memory, read) == 0 {
return false;
}
blake3::hash(read) == held
})
}
/// Where the levels from `first` on of a title texture are: address and
/// bytes.
pub(crate) fn title_span(resource: This, first: u32) -> Option<(u64, u64)> {
let (memory, desc) = crate::resource::texture_memory(resource)?;
let layout = crate::resource::texture_layout(&desc)?;
let layout = &layout.planes[0].layout;
Some((memory as u64, layout.bytes_from(crate::resource::read_from(layout, first))))
}
pub(crate) fn is_staged(resource: This) -> bool {
let map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize)))
@@ -1342,8 +1461,7 @@ pub(crate) fn staged(resource: This) -> Option<(u64, bool)> {
let map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
map.as_ref()?.get(&(resource as usize))?.clone()
};
let size = s.layout.size as usize;
Some((size as u64, committed(s.memory, size)))
Some((s.read as u64, committed(s.memory, s.read)))
}
/// Whether `[at, at + len)` is committed memory (streamed textures may be
@@ -1509,13 +1627,17 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 {
}
/// The staging state of a title texture, made on first use.
fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> Option<Arc<Staging>> {
let texture = &copy.texture;
// Asked before the table is locked: the sweep lets go of a staging
// buffer with its texture's host side locked, in that order.
let on_demand = crate::resource::host_tiled(resource).is_some();
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
let map = map.get_or_insert_with(HashMap::new);
if let Some(s) = map.get(&(resource as usize)) {
if let Some(s) = map.get(&(resource as usize))
&& s.first <= first.max(copy.base)
&& s.serial == copy.serial
{
return Some(s.clone());
}
let (memory, desc) = crate::resource::texture_memory(resource)?;
@@ -1534,10 +1656,14 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
let host = host()?;
// SAFETY: a live resource.
let d = unsafe { texture.GetDesc() };
let level0 = copy.base;
let mips = level0 + u32::from(d.MipLevels);
let first = crate::resource::read_from(&layout, first).max(level0).min(mips - 1);
let read = layout.bytes_from(first) as usize;
let count = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D {
u32::from(d.MipLevels)
mips - first
} else {
u32::from(d.MipLevels) * u32::from(d.DepthOrArraySize)
(mips - first) * u32::from(d.DepthOrArraySize)
};
let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize];
let mut rows = vec![0u32; count as usize];
@@ -1546,7 +1672,7 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
unsafe {
host.device.GetCopyableFootprints(
&d,
0,
first - level0,
count,
0,
Some(footprints.as_mut_ptr()),
@@ -1581,7 +1707,13 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
footprints,
rows,
layout,
mips: u32::from(d.MipLevels),
mips,
first,
level0,
read,
serial: copy.serial,
holds: copy.holds.clone(),
waits: std::sync::atomic::AtomicBool::new(false),
bytes: total,
memory,
last: Mutex::default(),
@@ -1800,6 +1932,65 @@ mod allocation_costs {
}
}
/// What a texture met for the first time costs, by step, in
/// milliseconds a megabyte on one thread: for whether a store of
/// detiled copies on disk could be worth it (its key is a hash of the
/// title's bytes, so reading and hashing them stay; `VICTORY_BENCH_FILE`
/// is a big file to read past the system's cache).
#[test]
#[ignore = "a measurement, not a check"]
fn cold_texture_costs() {
let Some(host) = crate::host::host() else { return };
let desc = [3u32, 0, 0, 0, 1024, 0, 1024, 0xb_0001, 98, 1, 0, 0x105, 0, 0];
// SAFETY: 56 bytes in the description's layout.
let desc = unsafe { desc.as_ptr().cast::<crate::resource::ResourceDesc>().read_unaligned() };
let layout = crate::resource::texture_layout(&desc).unwrap().planes[0].layout.clone();
let size = layout.size as usize;
let title: Vec<u8> = (0..size).map(|i| (i.wrapping_mul(2654435761) >> 13) as u8).collect();
let (_buffer, up) = host.upload_buffer(2 * layout.size).unwrap();
// SAFETY: the mapping.
let up = unsafe { std::slice::from_raw_parts_mut(up, 2 * size) };
let mut read = vec![0u8; size];
const N: u32 = 200;
let per_mb = |t: std::time::Duration| t.as_secs_f64() * 1e3 / (f64::from(N) * size as f64 / 1e6);
let timed = |what: &str, f: &mut dyn FnMut()| {
f();
let started = std::time::Instant::now();
(0..N).for_each(|_| f());
println!("{what}: {:.3} ms/MB", per_mb(started.elapsed()));
};
timed("read through the kernel or a safe copy", &mut || {
std::hint::black_box(crate::host::read_into(title.as_ptr(), &mut read));
});
timed("blake3", &mut || {
std::hint::black_box(blake3::hash(&title));
});
timed("detiled into upload memory", &mut || {
let mut at = 0;
for (mip, m) in layout.mips.iter().enumerate() {
let pitch = (m.width as usize * 16).next_multiple_of(256);
let len = pitch * m.height as usize;
layout.detile(&title, mip as u32, 0, &mut up[at..at + len], pitch, len).unwrap();
at += len.next_multiple_of(512);
}
});
timed("copied into upload memory", &mut || up[..size].copy_from_slice(&title));
if let Some(file) = std::env::var_os("VICTORY_BENCH_FILE") {
use std::os::windows::fs::{FileExt, OpenOptionsExt};
const NO_BUFFERING: u32 = 0x2000_0000;
let file = std::fs::OpenOptions::new().read(true).custom_flags(NO_BUFFERING).open(file).unwrap();
let len = file.metadata().unwrap().len();
let mut block = vec![0u8; size + 4096];
let skew = block.as_ptr().align_offset(4096);
let n = size / 4096 * 4096;
let mut at = 0u64;
timed("read from the disk, one request at a time", &mut || {
at = (at + 7919 * 4096 * 64) % (len - n as u64) / 4096 * 4096;
file.seek_read(&mut block[skew..skew + n], at).unwrap();
});
}
}
#[test]
#[ignore = "a measurement, not a check"]
fn allocation_costs() {