Publish the pareto-residency Windows build and portable launcher

This commit is contained in:
codec_d committed 2026-11-25 22:33:14 -08:00
1 parent efeef1d65b
commit 545f89019e
20 files changed
+1671 -217

No files matched your search

+442 -47
View File
@@ -426,6 +426,48 @@ fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<ID3D12Res
static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new());
/// Deferred slot flips recorded into an open or not-yet-submitted command
/// list (`HostHeap::flip`), tracked so a one-shot decoration bake draw can
/// promote them out of the `neutral()` gray stand-in before sampling them.
pub(crate) struct PendingListFlip {
id: u64,
pub(crate) origin: (usize, u64),
flip: Flip,
}
impl PendingListFlip {
pub(crate) fn index(&self) -> u32 {
self.flip.index
}
pub(crate) fn handle(&self) -> u64 {
self.flip.handle
}
pub(crate) fn key(&self) -> u64 {
self.flip.key
}
}
static NEXT_PENDING_FLIP: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
static PENDING_LIST_FLIPS: Mutex<Vec<PendingListFlip>> = Mutex::new(Vec::new());
static PENDING_LIST_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn take_pending_list_flip(id: u64) -> Option<Flip> {
if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 {
return None;
}
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
let pos = pending.iter().position(|p| p.id == id)?;
let entry = pending.swap_remove(pos);
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
Some(entry.flip)
}
fn remove_pending_list_flip(id: u64) {
let _ = take_pending_list_flip(id);
}
/// Makes the slots whose new texture's upload has run
/// ([`HostHeap::texture_slots_flip`]); on any thread. Not if the heap is at
/// something else: the next texture pass does.
@@ -714,6 +756,12 @@ impl Spans {
/// pass last took the ranges ([`page_written`]). Kept apart from
/// [`REMAPPED`] so that what such writes do is counted by itself.
static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
/// Physical-page writes retained specifically for one-shot decoration/ped
/// texture bakes when `VICTORY_PAGE_WRITES` bit 2 is off (the default): normal
/// frames stay free of queue flooding while every bake still sees freshly
/// DirectStorage-streamed texture bytes immediately instead of waiting on
/// `RECHECK_FRAMES`.
static BAKE_PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
/// Since the start: such ranges kept for a pass; ranges dropped because no
/// pass took them; slots of placed textures that held bytes of them when a
@@ -1105,29 +1153,46 @@ pub(crate) fn device_removed() -> Option<String> {
pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Bytes per element of a buffer view, as the console's descriptor holds
/// them for indexed reads (structured: the stride; raw: 1, the index is the
/// byte; typed: the format's); `None` if `view` is not a buffer view.
fn view_stride(view: &View) -> Option<u32> {
let (stride, raw, format) = view_elements(view)?;
Some(if stride > 0 {
/// Bytes per element and typed integer format bits of a buffer view, decoded
/// in a single pass over the view descriptor; `(None, 0)` if not a buffer view.
fn view_stride_and_kind(view: &View) -> (Option<u32>, u32) {
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
let Some((stride, raw, format)) = view_elements(view) else {
return (None, 0);
};
let bytes = if stride > 0 {
stride
} else if raw {
1
} else {
crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32)
})
};
let kind = if stride == 0 && !raw {
match format {
3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => VIEW_INTEGER,
4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => VIEW_INTEGER | VIEW_SIGNED,
_ => 0,
}
} else {
0
};
(Some(bytes), kind)
}
/// What else the table of strides says of a typed buffer view of an integer
/// format (`victory_shader::emit::VIEW_INTEGER`); 0 for any other view.
/// Packed [`victory_shader::emit::SLOT_STRIDES`] word for `view`.
fn view_stride_word(view: &View) -> u32 {
let (stride, kind) = view_stride_and_kind(view);
stride.unwrap_or(0) | kind
}
#[cfg(test)]
fn view_stride(view: &View) -> Option<u32> {
view_stride_and_kind(view).0
}
#[cfg(test)]
fn view_kind(view: &View) -> u32 {
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
match view_elements(view) {
Some((0, false, 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62)) => VIEW_INTEGER,
Some((0, false, 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64)) => VIEW_INTEGER | VIEW_SIGNED,
_ => 0,
}
view_stride_and_kind(view).1
}
/// A buffer view's structure stride, whether it is raw, and its format;
@@ -1740,7 +1805,7 @@ impl HostHeap {
pub(crate) fn texture_news(&self) -> (u64, bool) {
let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes;
let noted = |ranges: &Mutex<Vec<(u64, u64)>>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty();
(writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN))
(writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN) || noted(&BAKE_PAGE_WRITTEN))
}
/// Every title slot of the queue that is due at `frame`, and whether
@@ -1888,7 +1953,48 @@ impl HostHeap {
if ranges.is_empty() {
return 0;
}
self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2]
let due = crate::watch::page_writes() & 2 != 0;
let made_due = self.slots_written_under(&ranges, frame, due)[2];
if !due {
let mut kept = BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
kept.extend(ranges);
if kept.len() > 256 {
join(&mut kept);
const MOST: usize = 1 << 14;
if kept.len() > MOST {
let drop_n = kept.len() - MOST;
kept.drain(..drop_n);
}
}
}
made_due
}
/// Wakes uploaded placed-texture slots touched by recent physical-page
/// writes (DirectStorage completions) immediately (`due = frame`) right
/// before a one-shot ped/decoration bake draw.
pub(crate) fn texture_slots_bake_written(&self, frame: u64) -> usize {
let mut ranges = std::mem::take(&mut *BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()));
if ranges.is_empty() {
return 0;
}
join(&mut ranges);
let mut slots: Vec<u32> = {
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect()
};
if slots.is_empty() {
return 0;
}
slots.sort_unstable();
slots.dedup();
slots.retain(|&slot| !self.tabled_lately(slot, frame));
let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0));
for &slot in &slots {
textures.changed(slot, frame, frame);
}
slots.len()
}
/// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end):
@@ -2183,6 +2289,7 @@ impl HostHeap {
/// reads the table's dynamic slots).
pub(crate) fn mirror_after(&self, list: &crate::host::HostList, index: u32, handle: u64) {
if show_after()
&& !crate::texture::BAKING.get()
&& index < self.count
&& !self.texture_slot_made_from(index, handle)
&& let Some(view) = super::view(handle)
@@ -2197,14 +2304,143 @@ impl HostHeap {
}
fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, late: Option<u64>) {
use std::sync::atomic::Ordering::{Relaxed, Release};
let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle));
let id = NEXT_PENDING_FLIP.fetch_add(1, Relaxed);
let origin = (std::ptr::from_ref(list) as usize, list.epoch());
{
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
pending.push(PendingListFlip {
id,
origin,
flip: Flip { after: 0, heap, index, handle, key, late },
});
PENDING_LIST_COUNT.store(pending.len(), Release);
}
struct PendingGuard(u64);
impl PendingGuard {
fn id(&self) -> u64 {
self.0
}
}
impl Drop for PendingGuard {
fn drop(&mut self) {
remove_pending_list_flip(self.0);
}
}
let guard = PendingGuard(id);
list.defer_host(move || {
let after = crate::host::submissions().0;
let flip = Flip { after, heap, index, handle, key, late };
// Call a `&self` method so Rust 2021+ moves the whole `guard`
// into this closure rather than copying `guard.0` and dropping
// `guard` immediately at the end of `flip()`.
let Some(mut flip) = take_pending_list_flip(guard.id()) else {
return;
};
flip.after = crate::host::submissions().0;
FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip);
});
}
/// Whether any deferred slot flip or view remake for this heap requires
/// settling in-flight GPU submissions before exposing real textures to a
/// one-shot decoration bake draw.
pub(crate) fn needs_gpu_settle_for_bake(&self) -> bool {
let own = std::ptr::from_ref(self) as usize;
let finished = crate::host::submissions().1;
if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) > 0 {
let pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
if pending.iter().any(|p| p.flip.heap == own) {
return true;
}
}
{
let flips = FLIPS.lock().unwrap_or_else(|e| e.into_inner());
if flips.iter().any(|f| f.heap == own && f.after > finished) {
return true;
}
}
let after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner());
after.iter().any(|&(at, _)| at > finished)
}
/// Drains deferred flips still sitting in unsubmitted command lists for
/// this heap so a decoration bake can mirror them out of `neutral()`.
/// Entries that cannot be promoted yet (unmapped memory or deferred
/// staging) must be returned via [`HostHeap::restore_pending_list_flip`].
pub(crate) fn take_pending_list_flips(&self) -> Vec<PendingListFlip> {
if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 {
return Vec::new();
}
let own = std::ptr::from_ref(self) as usize;
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
let (mine, rest): (Vec<PendingListFlip>, Vec<PendingListFlip>) =
pending.drain(..).partition(|p| p.flip.heap == own);
*pending = rest;
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
mine
}
/// Re-queues an unpromoted deferred flip drained by
/// [`HostHeap::take_pending_list_flips`] so its originating command list
/// still flips it out of `neutral()` once submitted.
pub(crate) fn restore_pending_list_flip(&self, item: PendingListFlip) {
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
pending.push(item);
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
}
/// Whether title descriptor slot `handle` still holds record `key`.
pub(crate) fn slot_still_at(&self, handle: u64, key: u64) -> bool {
key != 0 && record_key(handle) == key
}
/// Looks up `(view, key)` for slot `index` prior to a synchronous bake
/// upload without replacing its current host descriptor with `neutral()`;
/// [`HostHeap::publish_uploaded_slot`] exposes the real descriptor and
/// updates `Spans`/stride tracking once the GPU copy finishes.
pub(crate) fn prepare_bake_slot(&self, index: u32, handle: u64) -> Option<(View, u64)> {
if index >= self.count {
return None;
}
let key = record_key(handle);
let view = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten()?;
Some((view, key))
}
/// Exposes the real host descriptor for slot `index` after its synchronous
/// bake upload has completed on the GPU, updating `Spans`/stride tracking
/// without re-queuing the slot in `TextureQueue`.
pub(crate) fn publish_uploaded_slot(&self, index: u32, handle: u64, key: u64) -> bool {
if index >= self.count || key == 0 {
return false;
}
let (published, stale) = {
let _made = self.made.lock(index);
if self.made.get(index) == Some(key) {
return false;
}
if record_key(handle) != key {
return false;
}
let Some(view) = view_at(key as u32, (key >> 32) as u32) else {
return false;
};
let stale = self.note_buffer(index, Some(&view), true);
if let Some(kept) = make(&view, self.at(index)) {
self.put(index);
self.quick_is(index, 0);
self.clear_twin(index);
self.made.set(index, key);
self.keep(index, kept);
(true, stale)
} else {
(false, stale)
}
};
self.unmake_stale(index, stale);
published
}
/// Makes the slots whose new view's upload has run
/// ([`HostHeap::texture_slot_flip`]); returns how many.
pub(crate) fn texture_slots_flip(&self) -> usize {
@@ -2222,6 +2458,7 @@ impl HostHeap {
ready
};
let mut flipped = 0;
let mut late_flipped = 0;
for f in ready {
let _made = self.made.lock(f.index);
let Some(shown) = self.made.get(f.index) else {
@@ -2264,6 +2501,7 @@ impl HostHeap {
same_bytes(was, f.key);
}
if let Some(since) = f.late {
late_flipped += 1;
let frames = crate::frame::current().saturating_sub(since);
let n = LATE[0].fetch_add(1, Relaxed) + 1;
let all = LATE[1].fetch_add(frames, Relaxed) + frames;
@@ -2282,7 +2520,7 @@ impl HostHeap {
}
}
FLIPPED[0].fetch_add(flipped as u64, Relaxed);
flipped
flipped + late_flipped
}
/// The memory of the texture title slot `index` views is there (again):
@@ -2311,6 +2549,7 @@ impl HostHeap {
}
self.put(index);
self.clear_twin(index);
self.write_stride(index, 0);
self.keep(index, None);
}
@@ -2506,15 +2745,8 @@ impl HostHeap {
textures.remove(slot);
}
}
let stride = view.and_then(view_stride);
let kind = view.map_or(0, view_kind);
if let Some((_, _, data)) = &self.strides
&& index < victory_shader::emit::SLOT_STRIDES_COUNT
{
// SAFETY: inside the mapping; shaders read it while we write (a
// dword, either value is one the slot had).
unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0) | kind) };
}
let (stride, kind) = view.map_or((None, 0), view_stride_and_kind);
self.write_stride(index, stride.unwrap_or(0) | kind);
let was = if stride.is_some() {
self.buffers.put(index);
true
@@ -2527,6 +2759,20 @@ impl HostHeap {
stale
}
/// Writes `word` (stride | format kind) for view-heap slot `index` into
/// the host's [`victory_shader::emit::SLOT_STRIDES`] table.
#[inline]
fn write_stride(&self, index: u32, word: u32) {
if let Some((_, _, data)) = &self.strides
&& index < victory_shader::emit::SLOT_STRIDES_COUNT
{
// SAFETY: inside the mapping; shaders read it while we write (a
// single aligned dword: either value is one the slot had, and
// dynamic slots are exclusively owned until submission finishes).
unsafe { (*data as *mut u32).add(index as usize).write_volatile(word) };
}
}
/// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
/// returned).
///
@@ -2554,6 +2800,7 @@ impl HostHeap {
}
self.put(index);
self.twin_made(index, kept.is_some() && twinned(view));
self.write_stride(index, if kept.is_some() { view_stride_word(view) } else { 0 });
self.keep(index, kept.flatten());
}
@@ -2586,13 +2833,14 @@ impl HostHeap {
}
let twin = twinned(&view);
let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?;
let stride_word = view_stride_word(&view);
let listed = Listed {
kind: crate::draw::view_kind(&view),
texture: is_texture_view(&view),
ready: (0, 0, false),
tabled: None,
};
views.made.insert(words, ListView { view, at, twin, kept, listed });
views.made.insert(words, ListView { view, at, twin, stride_word, kept, listed });
}
let made = &views.made[&words];
self.copy_from(index, views.slot(made.at));
@@ -2602,6 +2850,7 @@ impl HostHeap {
} else {
self.clear_twin(index);
}
self.write_stride(index, made.stride_word);
self.keep(index, made.kept.clone());
Some(made.listed)
})
@@ -2626,6 +2875,7 @@ impl HostHeap {
} else {
null_view(self.at(index));
self.put(index);
self.write_stride(index, 0);
}
self.clear_twin(index);
self.keep(index, None);
@@ -2712,6 +2962,7 @@ impl HostHeap {
self.put(index);
// (Bound by its handle, not read by index.)
self.clear_twin(index);
self.write_stride(index, 1);
self.keep(index, Some(buffer.clone()));
}
@@ -2721,6 +2972,7 @@ impl HostHeap {
null_buffer_view(self.at(index));
self.put(index);
self.clear_twin(index);
self.write_stride(index, 0);
self.keep(index, None);
}
@@ -2755,6 +3007,7 @@ impl HostHeap {
};
self.put(index);
self.clear_twin(index);
self.write_stride(index, 1);
self.keep(index, Some(buffer.clone()));
}
@@ -2784,6 +3037,7 @@ impl HostHeap {
};
self.put(index);
self.clear_twin(index);
self.write_stride(index, 0);
self.keep(index, None);
}
@@ -2841,6 +3095,7 @@ impl HostHeap {
unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) };
}
self.twin_made(index, twin.is_some());
self.write_stride(index, 0);
// After the descriptor: what it showed is let go when nothing shows
// it any more.
self.keep(index, holds.then(|| buffer.clone()));
@@ -4084,24 +4339,27 @@ fn make_twinned(
}
const BUFFER: u32 = 1;
if resource[0] != BUFFER {
// shortcut: unordered access to a texture the title placed
// itself is not mirrored; give it a resource as shader
// views of such textures get when a dispatch writes one.
// Each texture is said once (the first 64), with how many times
// such a view was asked for so far: what shaders write through
// them is lost.
static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let at = u64::from(desc[10]) | u64::from(desc[11]) << 32;
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() {
tracing::warn!(
address = format_args!("{at:#x}"),
times,
"placed unordered texture view not mirrored (null: writes through it are lost): resource {resource:?}, view {:?}",
&desc[..10]
);
if *unordered || at != 0 {
// shortcut: unordered access to a texture the title placed
// itself is not mirrored; give it a resource as shader
// views of such textures get when a dispatch writes one.
// Each texture is said once (the first 64), with how many times
// such a view was asked for so far: what shaders write through
// them is lost.
static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() {
tracing::warn!(
address = format_args!("{at:#x}"),
unordered = *unordered,
times,
"placed texture view not mirrored (null): resource {resource:?}, view {:?}",
&desc[..10]
);
}
}
return None;
}
@@ -5446,6 +5704,71 @@ mod tests {
heap.release(last, 1);
assert_eq!(heap.dynamic(2), None);
}
#[test]
fn dynamic_slots_populate_and_clear_stride_table() {
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
let Some(heap) = HostHeap::new(false, 4) else {
return; // no host GPU
};
let Some((_, _, data)) = heap.strides else {
panic!("view heap should allocate strides table");
};
let read_stride = |slot: u32| -> u32 {
// SAFETY: inside `SLOT_STRIDES_COUNT` mapping of `heap.strides`.
unsafe { *(data as *const u32).add(slot as usize) }
};
let memory = vec![0u64; 1 << 11];
let addr = (memory.as_ptr() as u64).next_multiple_of(4096);
let placed_typed = |uav: bool, dxgi_fmt: u32, elems: u32| {
let resource: [u32; 14] = [1, 0, 0, 0, 4096, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0];
let mut desc = [0u32; 16];
// [format, dim=1 (buffer), mapping/pad, ..., num_elements @6, stride @7, flags @8]
let words = if uav {
[dxgi_fmt, 1, 0, 0, elems, 0, 0, 0, 0, 0]
} else {
[dxgi_fmt, 1, 5768, 0, 0, 0, elems, 0, 0, 0]
};
desc[..10].copy_from_slice(&words);
(desc[10], desc[11]) = (addr as u32, (addr >> 32) as u32);
View::Placed(uav, resource, desc)
};
let s0 = heap.dynamic(4).unwrap();
// R16G16B16A16_UINT (12): 8 bytes + VIEW_INTEGER
let u16x4 = placed_typed(true, 12, 64);
heap.make_at(s0, &u16x4);
assert_eq!(read_stride(s0), 8 | VIEW_INTEGER);
// R16_SINT (59): 2 bytes + VIEW_INTEGER | VIEW_SIGNED
let s16 = placed_typed(false, 59, 64);
heap.make_at(s0 + 1, &s16);
assert_eq!(read_stride(s0 + 1), 2 | VIEW_INTEGER | VIEW_SIGNED);
// R16G16B16A16_FLOAT (10): 8 bytes, no integer bits
let f16x4 = placed_typed(true, 10, 64);
heap.make_at(s0 + 2, &f16x4);
assert_eq!(read_stride(s0 + 2), 8);
// Clearing / nulling / raw views overwrite stale bits cleanly.
heap.make_null(s0);
assert_eq!(read_stride(s0), 0);
heap.null_raw_at(s0 + 1);
assert_eq!(read_stride(s0 + 1), 0);
heap.null_raw_uav_at(s0 + 2);
assert_eq!(read_stride(s0 + 2), 0);
// `make_listed` (both cold creation and cached copy hit) must populate strides.
let mut slot_mem = [0u32; 8];
crate::descriptor::record(slot_mem.as_mut_ptr() as u64, u16x4);
let rec = [slot_mem[0], slot_mem[1], slot_mem[2]];
assert!(heap.make_listed(0x1234, rec, s0).is_some());
assert_eq!(read_stride(s0), 8 | VIEW_INTEGER);
heap.make_null(s0 + 3);
assert_eq!(read_stride(s0 + 3), 0);
assert!(heap.make_listed(0x1234, rec, s0 + 3).is_some());
assert_eq!(read_stride(s0 + 3), 8 | VIEW_INTEGER);
}
}
/// What is known of a record a list's tables hold, in that recording of the
@@ -5466,6 +5789,7 @@ struct ListView {
/// Its descriptor's slot in [`ListViews`]; its raw twin's is the next.
at: u32,
twin: bool,
stride_word: u32,
kept: Kept,
listed: Listed,
}
@@ -5544,3 +5868,74 @@ pub(crate) fn note_listed(recording: u64, words: [u32; 3], listed: Listed) {
pub(crate) fn list_views() -> bool {
crate::toggled!("VICTORY_LIST_VIEWS")
}
#[cfg(test)]
mod bake_flip_tests {
use super::*;
#[test]
fn pending_list_flips_promote_once_and_clean_up() {
let heap = 0xdead_beefusize;
let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
{
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
pending.push(PendingListFlip {
id: id1,
origin: (1, 1),
flip: Flip { after: 0, heap, index: 7, handle: 0, key: 11, late: Some(1) },
});
pending.push(PendingListFlip {
id: id2,
origin: (2, 1),
flip: Flip { after: 0, heap, index: 8, handle: 0, key: 12, late: Some(1) },
});
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
}
let taken = take_pending_list_flip(id1).expect("id1 should be present");
assert_eq!(taken.index, 7);
assert!(take_pending_list_flip(id1).is_none(), "second take must be a no-op");
remove_pending_list_flip(id2);
assert!(take_pending_list_flip(id2).is_none(), "removed entry must be gone");
}
#[test]
fn deferred_flip_closure_keeps_pending_entry_alive_until_called_or_dropped() {
let heap = 0xcafe_babeusize;
let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
{
let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner());
for (id, idx) in [(id1, 10), (id2, 11)] {
pending.push(PendingListFlip {
id,
origin: (3, 1),
flip: Flip { after: 0, heap, index: idx, handle: 0, key: 20, late: Some(1) },
});
}
PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release);
}
struct TestGuard(u64);
impl TestGuard {
fn id(&self) -> u64 {
self.0
}
}
impl Drop for TestGuard {
fn drop(&mut self) {
remove_pending_list_flip(self.0);
}
}
let make_cb = |id: u64| -> Box<dyn Fn() -> Option<u32> + Send + 'static> {
let guard = TestGuard(id);
Box::new(move || take_pending_list_flip(guard.id()).map(|f| f.index))
};
let cb1 = make_cb(id1);
let cb2 = make_cb(id2);
// Must still be present after make_cb returns (guard moved, not dropped).
assert_eq!(cb1(), Some(10));
assert_eq!(cb1(), None);
drop(cb2);
assert!(take_pending_list_flip(id2).is_none(), "dropping uncalled closure cleans up entry");
}
}
+396 -73
View File
@@ -217,12 +217,45 @@ const BAKE_AHEAD: [u64; 2] = [12, 2];
/// until something is new, the next bakes of the frame need no pass.
static BAKE_SERVED: AtomicU64 = AtomicU64::new(0);
/// Free-threaded wrapper around a reusable upload-only [`HostList`] protected
/// by [`BAKE_UPLOAD`]. D3D12 command allocators, lists, and retained COM
/// resources are free-threaded when externally synchronized.
struct BakeList(HostList);
// SAFETY: accessed exclusively under `BAKE_UPLOAD`'s mutex.
unsafe impl Send for BakeList {}
/// Serializes synchronous one-shot ped/decoration bake uploads across
/// concurrent `VICTORY_THIN=1` recording threads and owns the reusable
/// upload-only host command list.
static BAKE_UPLOAD: std::sync::Mutex<Option<BakeList>> = std::sync::Mutex::new(None);
/// Pending descriptor publications for a synchronous bake upload pass: slots
/// stay on `neutral()` (or their previous compatible view) until the dedicated
/// upload list has finished executing on the host GPU.
struct BakeSync {
publish: Vec<(u32, u64, u64)>,
keep: Vec<std::sync::Arc<crate::resource::HostTexture>>,
}
/// 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
/// targets and name no texture in a table.
pub(crate) const BAKE_PIXEL_SHADERS: [&str; 4] =
["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"];
pub(crate) const BAKE_PIXEL_SHADERS: [&str; 7] = [
"c0a7fe77b1862e10",
"0d1575a396dfe513",
"b7cfd8dda91ebb6b",
"280967ad158cee0b",
"fa455c8a3c32577b",
"d126bcae5d5d8d26",
"fcee612943c008e0",
];
/// Geometry stages shared by every ped texture compositor / decoration bake
/// permutation (`vertex 089d6271be6650ef` fullscreen-triangle ped baker and
/// `mesh d4111a6e6ea49d91` decoration projection mesh), catching pixel-shader
/// permutations beyond `BAKE_PIXEL_SHADERS`.
const BAKE_GEOMETRY_SHADERS: [&str; 2] = ["089d6271be6650ef", "d4111a6e6ea49d91"];
/// Since the start: early runs of the texture pass, and those of them
/// made for a bake draw.
@@ -1714,6 +1747,24 @@ impl State {
}
continue;
}
if srv && slot == victory_shader::emit::SLOT_TABLE_STRIDES {
// Ours: the shader inspects typed view kinds for its
// descriptor tables only (already mirrored by `tables`),
// so bind the strides buffer without sweeping the heap.
match self.heap_strides(list) {
// SAFETY: an open list; the table lives as long
// as the heap the list holds.
Some(gpu) => unsafe {
if compute {
l.SetComputeRootShaderResourceView(param, gpu);
} else {
l.SetGraphicsRootShaderResourceView(param, gpu);
}
},
None => once!("a shader inspects table view kinds without a view heap set"),
}
continue;
}
let tabled = srv && crate::pipeline::host::bounded_root_srvs();
let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
else {
@@ -1872,7 +1923,10 @@ impl State {
Some((index, shadow)) => (*index, address.zip(shadow.clone())),
None => {
let shadow = address.and_then(|a| find(a).map(|s| (a, s)));
let Some(index) = host.dynamic(1) else {
let Some(index) = host.dynamic(1).or_else(|| {
crate::host::settle_for_fence();
host.dynamic(1)
}) else {
return false;
};
self.dynamic.push((key.0, index, 1));
@@ -1943,7 +1997,10 @@ impl State {
Some((index, shadow)) => (*index, address.zip(shadow.clone())),
None => {
let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s)));
let Some(index) = host.dynamic(1) else {
let Some(index) = host.dynamic(1).or_else(|| {
crate::host::settle_for_fence();
host.dynamic(1)
}) else {
return false;
};
self.dynamic.push((key.0, index, 1));
@@ -2053,7 +2110,7 @@ impl State {
#[cfg(feature = "diagnostics")]
let refreshed = std::time::Instant::now();
stage.next("the heap pass: textures");
self.heap_textures(list, heap, host);
let _ = self.heap_textures(list, heap, host, None);
stage.end();
#[cfg(feature = "diagnostics")]
HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed);
@@ -2062,20 +2119,179 @@ impl State {
Some(gpu)
}
/// The GPU address of the bound view heap's stride/kind table without
/// running the bindless heap buffer/texture sweep (for shaders that only
/// inspect descriptors already mirrored via their descriptor tables).
fn heap_strides(&self, list: &HostList) -> Option<u64> {
let heap = self
.heaps
.iter()
.filter(|&&h| h != 0)
.map(|&h| crate::descriptor::heap(h as This))
.find(|h| !h.samplers())?;
let host = heap.host()?;
let gpu = host.strides_gpu()?;
// Tag bit 1 (distinct from `heap_buffers`'s `| 1` and aligned guest pointers).
if list.first_use(gpu as usize | 2)
&& let Some(buffer) = host.strides_buffer()
{
list.keep(buffer);
}
Some(gpu)
}
/// Ensures textures claimed by background copy-queue uploads
/// (`VICTORY_UPLOAD_AHEAD=1`) or deferred behind the `neutral()` gray
/// stand-in (`VICTORY_SHOW_AFTER=1` / `shows_other`) have finished
/// uploading and flipped to their real descriptors before a one-shot
/// decoration bake draw samples them.
fn flush_for_bake(
&self,
list: &HostList,
host: &crate::descriptor::host::HostHeap,
mut sync: Option<&mut BakeSync>,
) {
static RESCUED: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
let drained = crate::texture::ahead::drain();
let mut settled = false;
let mut flipped = 0usize;
for _ in 0..4 {
let need_settle = host.needs_gpu_settle_for_bake();
if need_settle {
settled = true;
crate::host::settle_for_fence();
}
flipped += host.texture_views_remade();
flipped += host.texture_slots_flip();
if !need_settle || !host.needs_gpu_settle_for_bake() {
break;
}
}
let pending = host.take_pending_list_flips();
let mut promoted = 0usize;
if !pending.is_empty() {
let this_list = (std::ptr::from_ref(list) as usize, list.epoch());
let sampled = UsedResource {
kind: ResourceType::Srv,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 0,
dwords: 8,
user_data: 0,
slot: 0,
};
for item in pending {
let (origin, index, handle, key) = (item.origin, item.index(), item.handle(), item.key());
if !host.slot_still_at(handle, key) {
continue;
}
let Some(view) = crate::descriptor::view(handle) else {
continue;
};
if let View::Placed(_, resource, desc) = &view {
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
let len = crate::resource::placed_bytes(resource).unwrap_or(1);
if crate::texture::mapped_bytes(address as *const u8, len as usize) == 0 {
host.restore_pending_list_flip(item);
continue;
}
}
if sync.is_some() || origin != this_list {
let placed = crate::descriptor::host::placed_texture(&view);
if let Some(&View::Shader(resource, _)) = placed.as_ref().or(Some(&view)) {
let resource = resource as This;
let texture = crate::resource::host_resource(resource);
let title_fills = texture.is_some_and(crate::texture::title_written);
let first = match (&placed, &view) {
(Some(_), View::Placed(_, _, desc)) => crate::resource::first_mip(desc),
_ => 0,
};
if let (Some(sync), Some(copy)) = (sync.as_deref_mut(), crate::resource::host_copy(resource)) {
sync.keep.push(copy);
}
if title_fills
&& !crate::texture::ahead::there(resource)
&& (sync.is_some() || !crate::texture::unchanged(resource, first))
{
let was_staged = crate::texture::is_staged(resource);
let _ = crate::residency::take_staging_deferred();
readable(list, sampled.kind, &view);
let failed = crate::residency::take_staging_deferred() || crate::residency::upload_refused();
if !was_staged {
crate::texture::unstage(resource);
}
if failed {
host.restore_pending_list_flip(item);
continue;
}
}
}
}
if let Some(sync) = sync.as_deref_mut() {
sync.publish.push((index, handle, key));
} else {
let _ = host.mirror(index, handle, true);
}
promoted += 1;
}
}
if drained > 0 || settled || flipped > 0 || promoted > 0 {
let n = RESCUED[0].fetch_add(1, Ordering::Relaxed) + 1;
let all_drained = RESCUED[1].fetch_add(drained as u64, Ordering::Relaxed) + drained as u64;
let all_flipped = RESCUED[2].fetch_add(flipped as u64, Ordering::Relaxed) + flipped as u64;
let all_promoted = RESCUED[3].fetch_add(promoted as u64, Ordering::Relaxed) + promoted as u64;
if n.is_power_of_two() {
tracing::info!(
frame = crate::frame::current(),
flushes = n,
drained_ahead = all_drained,
flipped = all_flipped,
promoted_from_lists = all_promoted,
settled,
"flushed deferred texture stand-ins before decoration bake"
);
}
}
}
/// Whether a graphics draw is a one-shot texture compositor / decoration
/// bake whose bindless texture inputs must be flushed and up to date
/// before recording the draw. Matches known bake pixel/geometry shaders
/// and structurally detects depth-less 4+ MRT square atlas bakes
/// (`>= 512x512`) so unseen NPC/head/clothing shader permutations never
/// bake `neutral()` or `null` stand-ins into permanent ped textures.
fn is_bake_draw(&self, p: &HostPipeline) -> bool {
if p.stages.iter().any(|s| {
let h = s.shader.hash.as_str();
BAKE_PIXEL_SHADERS.contains(&h) || BAKE_GEOMETRY_SHADERS.contains(&h)
}) {
return true;
}
self.depth == 0
&& self.targets.len() >= 4
&& self
.targets
.first()
.and_then(|&t| crate::resource::texture_kind(t as This))
.is_some_and(|(w, h, _)| w >= 512 && w == u64::from(h))
}
/// Runs the pass that uploads textures picked by index
/// ([`State::heap_textures`]) where nothing has asked for it yet
/// ([`early_budgets`]): once a frame for a few milliseconds, at the
/// frame's first draw with a view heap set, and with a larger budget
/// of its own before every draw whose pixel shader is one of the
/// title's bake programs. The uploads are recorded into `list` ahead
/// of the draw being bound, as the world's pass records them.
/// title's bake programs. For decoration bakes, uploads run synchronously
/// on a dedicated internal command list and descriptors are published only
/// after the GPU copy finishes so concurrent `VICTORY_THIN=1` lists can
/// never submit a bake draw ahead of its texture uploads.
fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) {
let (early_ms, bake_ms) = early_budgets();
if compute || (early_ms == 0 && bake_ms == 0) {
return;
}
let bake = bake_ms > 0
&& p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str()));
let is_bake = bake_ms > 0 && self.is_bake_draw(p);
static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
// The milliseconds this frame's bake draws have taken so far: a
// frame has several, and together they get `bake_ms`.
@@ -2085,15 +2301,9 @@ impl State {
if first {
BAKED_MS.store(0, Ordering::Relaxed);
}
let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
let budget = if bake && left > 0 {
// What a bake may read must be there now: up to 2 GiB.
(left, 2 << 30)
} else if first && early_ms > 0 {
(early_ms, 64 << 20)
} else {
if !is_bake && !(first && early_ms > 0) {
return;
};
}
let Some(heap) = self
.heaps
.iter()
@@ -2106,34 +2316,102 @@ impl State {
let Some(host) = heap.host() else {
return;
};
let bake = bake && left > 0;
if bake && !first && bake_exact() {
let (writes, noted) = host.texture_news();
if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 {
if is_bake {
let began = std::time::Instant::now();
let mut bake_slot = BAKE_UPLOAD.lock().unwrap_or_else(|e| e.into_inner());
let gpu = crate::host::host();
if bake_slot.is_none()
&& let Some(gpu) = gpu
{
match gpu.new_list() {
Ok(upload_list) => *bake_slot = Some(BakeList(upload_list)),
Err(e) => tracing::warn!(error = %e, "no host list for synchronous bake uploads"),
}
}
let exact = bake_exact();
if let (Some(gpu), Some(BakeList(bake_list))) = (gpu, bake_slot.as_ref()) {
let mut sync = BakeSync { publish: Vec::new(), keep: Vec::new() };
crate::texture::BAKING.set(exact);
self.flush_for_bake(bake_list, host, Some(&mut sync));
let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
let run_pass = left > 0
&& (first
|| !exact
|| {
let (writes, noted) = host.texture_news();
noted || BAKE_SERVED.load(Ordering::Relaxed) != writes + 1
});
let mut served = false;
if run_pass {
let n = EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed) + 1;
if n.is_power_of_two() {
let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed));
tracing::info!(
frame,
bakes = n,
queued_at_the_last_pass = slots,
due_at_the_last_pass = due,
uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed),
"a draw of the title's decoration bake: textures picked by index are uploaded synchronously first (VICTORY_BAKE_TEXTURES_MS=0: not)"
);
}
BAKE_SERVED.store(0, Ordering::Relaxed);
PASS_BUDGET.set(Some((left, 2 << 30, true)));
served = self.heap_textures(bake_list, heap, host, Some(&mut sync));
PASS_BUDGET.set(None);
}
crate::texture::BAKING.set(false);
if bake_list.has_recorded_work() {
bake_list.close();
gpu.execute_sync_internal(bake_list);
bake_list.reset();
} else if !sync.publish.is_empty() {
crate::host::settle_for_fence();
}
for (index, handle, key) in sync.publish {
let _ = host.publish_uploaded_slot(index, handle, key);
}
host.texture_views_remade();
host.texture_slots_flip();
drop(sync.keep);
if run_pass && served && exact {
BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed);
}
BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
return;
}
}
let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1;
if bake && n.is_power_of_two() {
let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed));
tracing::info!(
frame,
bakes = n,
queued_at_the_last_pass = slots,
due_at_the_last_pass = due,
uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed),
"a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)"
);
}
let began = std::time::Instant::now();
PASS_BUDGET.set(Some((budget.0, budget.1, bake)));
crate::texture::BAKING.set(bake && bake_exact());
self.heap_textures(list, heap, host);
crate::texture::BAKING.set(false);
PASS_BUDGET.set(None);
if bake {
// Fallback when no host GPU list can be created (e.g. headless tests).
crate::texture::BAKING.set(exact);
self.flush_for_bake(list, host, None);
crate::texture::BAKING.set(false);
let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
if left == 0 {
return;
}
if !first && exact {
let (writes, noted) = host.texture_news();
if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 {
return;
}
}
EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed);
PASS_BUDGET.set(Some((left, 2 << 30, true)));
crate::texture::BAKING.set(exact);
let _ = self.heap_textures(list, heap, host, None);
crate::texture::BAKING.set(false);
PASS_BUDGET.set(None);
BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
return;
}
let budget = if first && early_ms > 0 {
(early_ms, 64 << 20)
} else {
return;
};
EARLY_TEXTURE_PASSES[0].fetch_add(1, Ordering::Relaxed);
PASS_BUDGET.set(Some((budget.0, budget.1, false)));
let _ = self.heap_textures(list, heap, host, None);
PASS_BUDGET.set(None);
}
/// The queue's side of the card accounting line
@@ -2230,10 +2508,11 @@ impl State {
list: &HostList,
heap: &crate::descriptor::Heap,
host: &crate::descriptor::host::HostHeap,
) {
mut sync: Option<&mut BakeSync>,
) -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) {
return;
return true;
}
let memory = crate::host::host().and_then(|h| h.video_memory());
// `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of
@@ -2285,6 +2564,10 @@ impl State {
// Slots whose texture's memory the runtime mapped, unmapped or
// wrote since the last pass are due again.
host.texture_slots_remapped(frame);
let baking = crate::texture::BAKING.get();
if baking {
host.texture_slots_bake_written(frame);
}
host.texture_slots_short(frame);
// The slots of textures whose first level with memory (levels on
// demand), or whose host copy for one with more levels, changed since
@@ -2298,11 +2581,6 @@ impl State {
host.texture_slots_waiting(frame);
}
let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake);
if !crate::residency::admit_texture_pass(required) {
BAKE_SERVED.store(0, Ordering::Relaxed);
return;
}
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();
@@ -2370,17 +2648,22 @@ impl State {
let bytes_at_most = if required || asked.is_some() {
bytes_at_most
} else {
crate::residency::prefetch_limit(bytes_at_most, crate::residency::pressured(),
crate::residency::limited_host_ram(), crate::texture::live_staging_bytes())
crate::residency::prefetch_limit(
bytes_at_most,
crate::residency::pressured(),
crate::residency::critical_commit(),
crate::residency::limited_host_ram(),
crate::texture::live_staging_bytes(),
)
};
let began = std::time::Instant::now();
BAKE_SERVED.store(0, Ordering::Relaxed);
if sync.is_none() {
BAKE_SERVED.store(0, Ordering::Relaxed);
}
let mut served = true;
for (index, write) in due {
if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span
|| !crate::residency::admit_texture_pass(required)
{
if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span {
served = false;
break;
}
@@ -2524,23 +2807,41 @@ impl State {
);
}
}
// Gate new host texture creation / staging on commit reserve after
// `mapped == 0` reclamation (`texture_slot_gone`) has run, and
// before mirroring a slot to an unuploaded texture.
if !crate::residency::admit_texture_pass(required) {
served = false;
break;
}
// 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 sync_bake = sync.is_some();
let shows_other = !baking
&& !sync_bake
&& crate::resource::held_only()
&& heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle));
// A slot that shows nothing of it yet, or something else, shows it
// when the upload has run too.
let late = !shows_other
&& !baking
&& !sync_bake
&& crate::descriptor::host::show_after()
&& heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle));
let view = heap.handle(index).and_then(|handle| {
if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) }
});
let (view, bake_key) = if sync_bake {
match heap.handle(index).and_then(|handle| host.prepare_bake_slot(index, handle)) {
Some((view, key)) => (Some(view), Some(key)),
None => (None, None),
}
} else {
let view = heap.handle(index).and_then(|handle| {
if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) }
});
(view, None)
};
let at_once = || {
if late && let Some(handle) = heap.handle(index) {
if (late || bake_key.is_some()) && let Some(handle) = heap.handle(index) {
let _ = host.mirror(index, handle, true);
}
};
@@ -2581,16 +2882,23 @@ impl State {
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);
}
// Its bytes are in, or on the way there in a list before.
if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) {
if let Some(handle) = heap.handle(index) {
host.texture_slot_show_after(list, index, handle);
if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) {
if let Some(copy) = crate::resource::host_copy(resource) {
sync.keep.push(copy);
}
sync.publish.push((index, handle, key));
} else {
at_once();
if shows_other && let Some(handle) = heap.handle(index) {
let _ = host.mirror(index, handle, true);
}
// Its bytes are in, or on the way there in a list before.
if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) {
if let Some(handle) = heap.handle(index) {
host.texture_slot_show_after(list, index, handle);
}
} else {
at_once();
}
}
let again = partly.map(|mapped| (frame + 1, mapped));
let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None };
@@ -2625,6 +2933,7 @@ impl State {
break;
}
let late = late && ahead.is_none();
let _ = crate::residency::take_staging_deferred();
if let Some(view) = &view
&& ahead.is_none()
{
@@ -2634,12 +2943,21 @@ impl State {
readable(list, sampled.kind, view);
crate::texture::PICKING.set(None);
}
// A failed allocation leaves this slot due. Publishing it or
// marking it served would lose the only retry for some materials.
if ahead.is_none() && crate::residency::upload_refused() {
// A failed or deferred staging allocation leaves this slot due.
// Publishing it or marking it served would lose the only retry for
// some materials.
if ahead.is_none()
&& (crate::residency::take_staging_deferred() || crate::residency::upload_refused())
{
served = false;
break;
}
if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) {
if let Some(copy) = crate::resource::host_copy(resource) {
sync.keep.push(copy);
}
sync.publish.push((index, handle, key));
}
if shows_other && let Some(handle) = heap.handle(index) {
host.texture_slot_flip(list, index, handle);
}
@@ -2672,7 +2990,7 @@ impl State {
let text: String = format!("{view:?}").chars().take(300).collect();
tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}");
crate::host::log_removal_context();
return;
return false;
}
let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true));
// Not all of it there: looked at again next frame, and from
@@ -2723,9 +3041,10 @@ impl State {
None => host.texture_slot_done(index, write, again),
}
}
if baking && served {
if sync.is_none() && baking && served {
BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed);
}
served
}
/// For the frame listing, after a dropped dispatch's line: its group
@@ -3440,7 +3759,10 @@ impl State {
made.push((slot, first * 32));
continue;
}
let Some(first) = host.dynamic(n) else {
let Some(first) = host.dynamic(n).or_else(|| {
crate::host::settle_for_fence();
host.dynamic(n)
}) else {
// No room: the draw must not run with the title's own
// offsets (slots never made for it); `bind` drops it.
made.push((slot, u32::MAX));
@@ -3488,11 +3810,12 @@ impl State {
TESTED_DEPTH.set((tested.0, true));
}
} else if let Some(view) = crate::descriptor::host::listed_view(recording, words) {
let _ = crate::residency::take_staging_deferred();
TESTED_DEPTH.set((tested.0, false));
readable(list, kind, &view);
let depth = TESTED_DEPTH.get().1;
TESTED_DEPTH.set((tested.0, tested.1 || depth));
if kind == ResourceType::Srv {
if kind == ResourceType::Srv && !crate::residency::take_staging_deferred() {
listed.ready = (list.epoch(), tested.0, depth);
}
}
+23 -2
View File
@@ -4912,7 +4912,7 @@ impl Host {
let mut telling = std::time::Instant::now();
for item in items {
telling = match item {
Late::Run(flight) => {
Late::Run(mut flight) => {
last = flight.number;
for &i in &flight.order {
read_backs(flight.lists[i].host());
@@ -4923,6 +4923,9 @@ impl Host {
if let Some(own) = flight.own {
own.landed();
}
for detached in &mut flight.lists {
detached.release_tables();
}
landed.push((flight.lists, flight.order));
crate::land::spent(crate::land::stat::READ_BACKS, telling)
}
@@ -5125,6 +5128,14 @@ impl Host {
let _ = self.submit(runs, &[], false);
}
/// Runs a closed internal upload-only host list synchronously without
/// draining title queues (`queue::before_sync`), so it is deadlock-safe
/// when invoked from `VICTORY_THIN=1` worker threads. Settles in-flight
/// GPU work and waits for the upload list's fence before returning.
pub(crate) fn execute_sync_internal(&self, list: &HostList) {
let _ = self.submit(&[list], &[], false);
}
/// A queue's submission with [`late`]: the host lists `lists`, taken
/// from the title's, go to the card in `order` and are not waited for.
/// They join the line of flights and are settled, with the others in
@@ -5382,7 +5393,7 @@ impl Host {
let mut landed = Vec::new();
for item in items {
match item {
Late::Run(flight) => {
Late::Run(mut flight) => {
last = flight.number;
for &i in &flight.order {
read_backs(flight.lists[i].host());
@@ -5390,6 +5401,9 @@ impl Host {
if let Some(card) = flight.card {
self.card_done(card);
}
for detached in &mut flight.lists {
detached.release_tables();
}
landed.push((flight.lists, flight.order));
}
Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes),
@@ -6348,6 +6362,13 @@ impl HostList {
self.epoch.load(Ordering::Relaxed)
}
/// Whether any deferred steps or texture state transitions have been
/// recorded into this list since creation or its last [`HostList::reset`].
pub(crate) fn has_recorded_work(&self) -> bool {
!self.deferred().copies.is_empty()
|| !self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
}
/// Moves a title texture's host copy to `wanted` (a host state) in this
/// list: the host texture and the state it leaves, if that is a change.
/// The list's first use of a texture records nothing: its prelude brings
+4 -6
View File
@@ -295,12 +295,10 @@ pub(crate) fn amd(device: &ID3D12Device) -> bool {
/// Whether a record that does not fit in what is left of its list's budget
/// takes the rest, so that every record after it runs empty too
/// (`VICTORY_INDIRECT_REST=0`: it takes nothing, and the next one that fits
/// runs). A list whose budget one garbage record empties loses all its later
/// draws, and which record that is may differ from frame to frame. The frame
/// line says how many records a frame are refused.
/// (`VICTORY_INDIRECT_REST=1`; off by default so one oversized record takes
/// nothing and later valid draws still run).
fn rest() -> u32 {
u32::from(std::env::var("VICTORY_INDIRECT_REST").map_or(true, |v| v != "0"))
u32::from(std::env::var("VICTORY_INDIRECT_REST").is_ok_and(|v| v == "1"))
}
/// The clamp compiled from `source` (ours, or in the benchmark the one it
@@ -2607,7 +2605,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
/// left then, and the records as clamped.
fn four_records_of_a_group(rest: bool) -> Option<(u32, Vec<u32>)> {
let mut warp = WarpHarness::new()?;
let source = if rest { SOURCE.to_owned() } else { SOURCE.replace("REST ?", "false ?") };
let source = SOURCE.replace("REST ?", if rest { "true ?" } else { "false ?" });
let clamp = make_from(&warp.device, &source).expect("the clamp must compile on WARP");
const KIND_DRAW: u32 = 0;
const STRIDE: u32 = 16;
+6
View File
@@ -203,6 +203,12 @@ impl Detached {
pub(crate) fn host(&self) -> &crate::host::HostList {
&self.host
}
/// Releases this list's dynamic descriptor slots once its GPU submission
/// has completed, without waiting for the full `bury_lag` allocator delay.
pub(crate) fn release_tables(&mut self) {
self._state.tables_done();
}
}
/// A host list that has run and waits to be used again, and the bytes of
+1
View File
@@ -524,6 +524,7 @@ impl HostPipeline {
slot == victory_shader::emit::SLOT_FAULTS
} else {
slot == victory_shader::emit::SLOT_STRIDES
|| slot == victory_shader::emit::SLOT_TABLE_STRIDES
|| slot == victory_shader::emit::SLOT_MEMORY
};
if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() {
+15 -1
View File
@@ -52,7 +52,14 @@ pub(crate) fn room(memory: Option<[u64; 4]>) {
pool.reclaim(tick, limit, true);
}
if let Ok(mut pool) = STAGING.try_lock() {
pool.reclaim(tick, if pressure { 0 } else { limit }, true);
let staging_limit = if crate::residency::critical_commit() {
0
} else if pressure {
1
} else {
limit
};
pool.reclaim(tick, staging_limit, true);
}
}
@@ -379,6 +386,13 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi
// Copies from a buffer begin at multiples of 512.
let bytes = bytes.next_multiple_of(512);
let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || {
// Only gate speculative bindless prefetch on staging-pool growth
// headroom; table-bound textures and decoration bakes are sampled
// immediately and would otherwise read uninitialized/reused VRAM.
let speculative = crate::texture::PICKING.get().is_some() && !crate::texture::BAKING.get();
if speculative && !crate::residency::allow_staging_growth(false) {
return None;
}
let (buffer, data) = host.upload_buffer(BLOCK)?;
crate::host::name(&buffer, || "staging of textures (a block)".into());
Some(Upload(buffer, data))
+85 -33
View File
@@ -3,6 +3,7 @@ use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
const MIB: u64 = 1 << 20;
const GIB: u64 = 1 << 30;
static PRESSURED: AtomicBool = AtomicBool::new(false);
static HEADROOM: AtomicU64 = AtomicU64::new(u64::MAX);
@@ -25,30 +26,68 @@ pub(crate) fn allocation_error(error: &windows::core::Error) {
}
}
thread_local! {
static STAGING_DEFERRED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) fn note_staging_deferred() {
STAGING_DEFERRED.set(true);
}
pub(crate) fn take_staging_deferred() -> bool {
STAGING_DEFERRED.replace(false)
}
pub(crate) fn upload_refused() -> bool {
crate::host::coarse_ms() < RETRY_UPLOAD_AT.load(Ordering::Relaxed)
}
fn has_upload_reserve(commit: u64, bake: bool) -> bool {
commit >= if bake { 2 * GIB } else { 4 * GIB }
fn sample_commit(now: u64) -> u64 {
let next = NEXT_COMMIT_SAMPLE.load(Ordering::Relaxed);
if now >= next
&& NEXT_COMMIT_SAMPLE
.compare_exchange(next, now.saturating_add(32), Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
&& let Some(status) = memory_status()
{
AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed);
}
AVAILABLE_COMMIT.load(Ordering::Relaxed)
}
/// Leave commit for game allocations and submissions already in flight. Direct
/// texture consumers bypass this gate. Bake prefetch gets priority over lookahead.
fn has_upload_reserve(commit: u64, bake: bool) -> bool {
// Keep a protective floor against Rust/game OOM aborts without starving
// bindless world textures or one-shot ped decoration bakes when steady-state
// commit headroom sits in the 1-4 GiB range on 32 GiB hosts.
commit >= if bake { 256 * MIB } else { 512 * MIB }
}
fn has_growth_reserve(commit: u64, bake: bool) -> bool {
// Growing a fresh 64 MiB upload block for speculative bindless prefetch
// requires more headroom than reusing slices already committed inside the
// staging pool.
commit >= if bake { 256 * MIB } else { 1024 * MIB }
}
/// Leave commit for game allocations and submissions already in flight while
/// still letting bindless textures and one-shot material bakes upload.
pub(crate) fn admit_texture_pass(bake: bool) -> bool {
let now = crate::host::coarse_ms();
if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) {
return false;
}
let next = NEXT_COMMIT_SAMPLE.load(Ordering::Relaxed);
if now >= next && NEXT_COMMIT_SAMPLE.compare_exchange(
next, now.saturating_add(32), Ordering::Relaxed, Ordering::Relaxed,
).is_ok() {
if let Some(status) = memory_status() {
AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed);
}
has_upload_reserve(sample_commit(now), bake)
}
/// Whether the staging allocator may commit a brand-new OS upload buffer
/// (reusing existing free ranges in already-committed pool blocks stays open
/// whenever `admit_texture_pass` is true).
pub(crate) fn allow_staging_growth(bake: bool) -> bool {
let now = crate::host::coarse_ms();
if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) {
return false;
}
has_upload_reserve(AVAILABLE_COMMIT.load(Ordering::Relaxed), bake)
has_growth_reserve(sample_commit(now), bake)
}
pub(crate) fn limited_host_ram() -> bool {
@@ -58,9 +97,9 @@ pub(crate) fn limited_host_ram() -> bool {
fn next_pressure(was: bool, physical: u64, commit: u64) -> bool {
if was {
physical < 6 * GIB || commit < 8 * GIB
physical < 5 * GIB || commit < 6 * GIB
} else {
physical <= 4 * GIB || commit <= 6 * GIB
physical <= 3 * GIB || commit <= 4 * GIB
}
}
@@ -100,13 +139,20 @@ pub(crate) fn pressured() -> bool {
PRESSURED.load(Ordering::Relaxed)
}
/// True when OS commit headroom is critically low (< 1.5 GiB) or an allocation
/// just failed with `E_OUTOFMEMORY`, requiring emergency throttling.
pub(crate) fn critical_commit() -> bool {
let now = crate::host::coarse_ms();
now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) || sample_commit(now) < 1536 * MIB
}
/// A soft per-frame admission limit. A single texture can cross it. The
/// queue retains unserved slots so they can be retried on later frames.
pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, limited: bool, staging: u64) -> u64 {
if pressure {
pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, critical: bool, limited: bool, staging: u64) -> u64 {
if critical {
bytes.min(16 << 20)
} else if limited && staging >= GIB {
bytes.min(32 << 20)
} else if pressure || (limited && staging >= GIB) {
bytes.min(64 << 20)
} else {
bytes
}
@@ -118,32 +164,38 @@ mod tests {
#[test]
fn bake_and_lookahead_leave_room_for_live_game_allocations() {
for (commit, bake, lookahead) in [
(277 << 20, false, false), (2 * GIB, true, false), (4 * GIB, true, true),
for (commit, bake, lookahead, growth) in [
(128 * MIB, false, false, false),
(256 * MIB, true, false, false),
(512 * MIB, true, true, false),
(768 * MIB, true, true, false),
(1024 * MIB, true, true, true),
] {
assert_eq!(has_upload_reserve(commit, true), bake);
assert_eq!(has_upload_reserve(commit, false), lookahead);
assert_eq!(has_growth_reserve(commit, false), growth);
}
}
#[test]
fn either_constraint_enters_pressure_and_both_must_recover() {
assert!(next_pressure(false, 12 * GIB, 6 * GIB));
assert!(next_pressure(false, 4 * GIB, 16 * GIB));
assert!(next_pressure(true, 5 * GIB, 9 * GIB));
assert!(next_pressure(true, 7 * GIB, 7 * GIB));
assert!(!next_pressure(true, 6 * GIB, 8 * GIB));
assert!(!next_pressure(false, 5 * GIB, 7 * GIB));
assert!(next_pressure(false, 12 * GIB, 4 * GIB));
assert!(next_pressure(false, 3 * GIB, 16 * GIB));
assert!(next_pressure(true, 4 * GIB, 7 * GIB));
assert!(next_pressure(true, 6 * GIB, 5 * GIB));
assert!(!next_pressure(true, 5 * GIB, 6 * GIB));
assert!(!next_pressure(false, 4 * GIB, 5 * GIB));
}
#[test]
fn prefetch_respects_existing_budgets_and_resumes_after_recovery() {
assert_eq!(prefetch_limit(512 << 20, false, true, GIB), 32 << 20);
assert_eq!(prefetch_limit(512 << 20, false, true, GIB - 1), 512 << 20);
assert_eq!(prefetch_limit(512 << 20, false, false, 2 * GIB), 512 << 20);
assert_eq!(prefetch_limit(0, true, false, 0), 0);
assert_eq!(prefetch_limit(8 << 20, true, false, 0), 8 << 20);
assert_eq!(prefetch_limit(512 << 20, true, false, 0), 16 << 20);
assert_eq!(prefetch_limit(192 << 20, false, false, 0), 192 << 20);
assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB), 64 << 20);
assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB - 1), 512 << 20);
assert_eq!(prefetch_limit(512 << 20, false, false, false, 2 * GIB), 512 << 20);
assert_eq!(prefetch_limit(0, true, true, false, 0), 0);
assert_eq!(prefetch_limit(8 << 20, true, true, false, 0), 8 << 20);
assert_eq!(prefetch_limit(512 << 20, true, false, false, 0), 64 << 20);
assert_eq!(prefetch_limit(512 << 20, true, true, false, 0), 16 << 20);
assert_eq!(prefetch_limit(192 << 20, false, false, false, 0), 192 << 20);
}
}
+27 -7
View File
@@ -91,6 +91,11 @@ pub(crate) struct Staging {
/// recorded again about a second later if the card has room by then
/// ([`upload`]).
waiting: std::sync::atomic::AtomicU64,
/// Recorded for a one-shot decoration bake (`BAKING`): submission-time
/// refresh must wait for title memory to stop remapping
/// (`title_memory_reading`) instead of taking `no_wait()` /
/// `refresh_unlocked()` or the 30-frame partial-read throttle.
exact: std::sync::atomic::AtomicBool,
}
/// What a texture's staging buffer holds: the hash of the memory detiled
@@ -756,6 +761,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
return;
};
use std::sync::atomic::Ordering::Relaxed;
let baking = BAKING.get();
if baking {
staging.exact.store(true, Relaxed);
}
let picking = PICKING.get();
if picking.is_none() {
// A draw samples it through a table: kept and checked from here on.
@@ -810,8 +819,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
// The host texture has the staging buffer's contents: only the check
// at submission is left, and what it finds changed the next list that
// samples the texture uploads (a frame late where every list of the
// frame was recorded before that check).
if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
// frame was recorded before that check). During a one-shot bake we
// always record the copy so any change found at submission lands in
// VRAM before the bake draw executes.
if !baking && staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexSkipped, 1);
list.defer_texture(staging);
@@ -1254,12 +1265,13 @@ impl Staging {
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;
let exact = self.exact.swap(false, std::sync::atomic::Ordering::Relaxed);
let alone = self.once.load(std::sync::atomic::Ordering::Relaxed);
if alone && last.hash.is_some() {
if alone && !exact && last.hash.is_some() {
return 0;
}
if !alone && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) {
if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
if !exact && last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
return 0;
}
last.asked = now;
@@ -1303,7 +1315,7 @@ impl Staging {
last.hot_until = frame + HOT_FRAMES;
}
let hot = hot_textures() && frame < last.hot_until;
if unwritten && !turn && !hot {
if !exact && unwritten && !turn && !hot {
return 0;
}
blind = unwritten;
@@ -1322,7 +1334,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() && !exact {
// Not waited for: while the runtime remaps title memory the
// texture is read through the kernel instead, whole or not at
// all (`no_wait`).
@@ -1342,7 +1354,7 @@ impl Staging {
// unmapped pages is slow, and nothing tells us when pages
// arrive): a mip that streams in shows up to 30 frames late.
let frame = crate::frame::current();
if last.partial.is_some_and(|at| frame < at + 30) {
if !exact && last.partial.is_some_and(|at| frame < at + 30) {
return 0;
}
last.partial = Some(frame);
@@ -1878,6 +1890,13 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O
let (piece, buffer, base, data) = match crate::pool::staging(host, total) {
Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data),
None => {
let speculative = PICKING.get().is_some() && !BAKING.get();
if crate::residency::upload_refused()
|| (speculative && !crate::residency::allow_staging_growth(false))
{
crate::residency::note_staging_deferred();
return None;
}
let (buffer, data) = host.upload_buffer(total)?;
crate::host::name(&buffer, || {
format!(
@@ -1919,6 +1938,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O
detiled: std::sync::atomic::AtomicU32::new(0),
judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2],
waiting: std::sync::atomic::AtomicU64::new(0),
exact: std::sync::atomic::AtomicBool::new(BAKING.get()),
});
map.insert(resource as usize, s.clone());
Some(s)
+62 -8
View File
@@ -13,7 +13,7 @@
//! it as any texture.
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed};
use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering::Relaxed};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use windows::Win32::Graphics::Direct3D12::*;
@@ -80,6 +80,7 @@ pub(crate) enum Taken {
static QUEUE: (Mutex<VecDeque<Arc<Job>>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new());
/// Those on their way, by host copy ([`HostTexture::serial`]).
static ON_THEIR_WAY: Mutex<Vec<(u64, Arc<Job>)>> = Mutex::new(Vec::new());
static IN_FLIGHT: AtomicUsize = AtomicUsize::new(0);
static LANDED: Condvar = Condvar::new();
static BYTES: AtomicU64 = AtomicU64::new(0);
/// Since the start: uploads, bytes, microseconds from the asking until the
@@ -104,7 +105,7 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone()));
}
let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST };
if crate::residency::pressured()
if !crate::residency::allow_staging_growth(false)
|| BYTES.load(Relaxed) >= most
|| copy.flags() & 0x7 != 0
|| copy.state.load(Relaxed) != 0
@@ -134,7 +135,11 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
}
let job = Arc::new(Job { staging, copy, asked: std::time::Instant::now(), then: Mutex::new(Some(Vec::new())) });
BYTES.fetch_add(job.staging.read as u64, Relaxed);
ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()).push((job.copy.serial, job.clone()));
{
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
way.push((job.copy.serial, job.clone()));
IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release);
}
Some(Taken::New(job))
}
@@ -144,6 +149,25 @@ pub(crate) fn send(job: &Arc<Job>) {
QUEUE.1.notify_one();
}
/// Waits until every upload currently on its way here has finished copying
/// and run its completion callbacks (queuing slot flips into `FLIPS`).
/// Returns how many jobs were waited for.
pub(crate) fn drain() -> usize {
if IN_FLIGHT.load(std::sync::atomic::Ordering::Acquire) == 0 {
return 0;
}
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
let waiting = way.len();
let started = std::time::Instant::now();
while !way.is_empty() && started.elapsed().as_millis() < 2000 {
way = LANDED
.wait_timeout(way, std::time::Duration::from_millis(50))
.unwrap_or_else(|e| e.into_inner())
.0;
}
waiting
}
/// A list is about to record an upload into `copy`: one on its way here runs
/// first, and no other is taken after it.
pub(crate) fn listed(copy: &HostTexture) {
@@ -293,11 +317,6 @@ fn finish(jobs: Vec<Arc<Job>>) {
job.copy.ahead.store(DONE, Relaxed);
BYTES.fetch_sub(job.staging.read as u64, Relaxed);
}
{
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
LANDED.notify_all();
}
for job in &jobs {
let us = job.asked.elapsed().as_micros() as u64;
let n = STATS[0].fetch_add(1, Relaxed) + 1;
@@ -319,6 +338,14 @@ fn finish(jobs: Vec<Arc<Job>>) {
f();
}
}
// Remove from `ON_THEIR_WAY` only after `job.then` callbacks have queued
// their `FLIPS` entries so `drain()` observes every flip ready to apply.
{
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release);
LANDED.notify_all();
}
crate::descriptor::host::flip_now();
}
@@ -416,4 +443,31 @@ mod tests {
back.Unmap(0, None);
}
}
#[test]
fn drain_waits_until_then_callbacks_have_run() {
use std::sync::atomic::AtomicBool;
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
let Some(_host) = crate::host::host() else { return };
let desc = [3u32, 0, 0, 0, 128, 0, 128, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
let whole = crate::resource::placed_bytes(&desc).unwrap() as usize;
// SAFETY: memory of our own that stays for the test.
let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>();
// SAFETY: as above.
unsafe { std::ptr::write_bytes(at, 0x5a, whole) };
let texture = crate::resource::texture_at(at as u64, &desc).unwrap();
crate::resource::want_level(texture, 0);
let copy = crate::resource::host_copy(texture).unwrap();
if !crate::pool::fresh(&copy.texture) {
return;
}
let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") };
let ran = Arc::new(AtomicBool::new(false));
let flag = ran.clone();
job.then(move || flag.store(true, std::sync::atomic::Ordering::Release));
send(&job);
assert!(drain() >= 1);
assert!(ran.load(std::sync::atomic::Ordering::Acquire), "job.then callback must run before drain() returns");
assert_eq!(drain(), 0);
}
}