Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 56 additions & 6 deletions crates/victory-gpu/src/descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1146,8 +1146,9 @@ mod tests {
put(3, addr + small, 0); // touches the nominal interval, starts after the visible mips
let revived = host.demand_material_texture(heap, 1, stamp, frame).unwrap();
assert!(host.texture_slots_due(frame, 8).0.contains(&revived));
assert!(host.material_upload_allowed(1, revived.1, addr, small, small));
assert!(!host.material_upload_allowed(1, revived.1, addr, small, small - 1));
assert_eq!(host.material_upload_refusal(1, revived.1, addr, small, small), None);
assert_eq!(host.material_upload_refusal(1, revived.1 + 1, addr, small, small), Some("stale_write"));
assert_eq!(host.material_upload_refusal(1, revived.1, addr, small, small - 1), Some("pages_unavailable"));
let srv = host.mirror(1, heap.handle(1).unwrap(), true).unwrap();
let live = host::placed_texture(&srv).unwrap();
let View::Shader(texture, _) = live.view else { panic!("no sampled texture") };
Expand Down Expand Up @@ -1212,8 +1213,22 @@ mod tests {
#[cfg(windows)]
#[test]
fn material_demand_follows_gpu_record_and_rejects_reused_texture_memory() {
material_record_on_gpu(false);
}

#[cfg(all(windows, feature = "diagnostics"))]
#[test]
fn material_trace_reads_packed_indices_without_scheduling_uploads() {
material_record_on_gpu(true);
}

#[cfg(windows)]
fn material_record_on_gpu(trace: bool) {
use windows::Win32::Graphics::Direct3D12::*;
let Some(device) = crate::host::host() else { return };
let Some(device) = crate::host::host() else {
assert!(!trace, "trace fixture requires a D3D12 device");
return;
};
let null = std::ptr::null();
let mut object = null;
assert_eq!(create(HeapDesc { kind: 0, count: 128, flags: 1, nodes: 0 }, Placement { address: 0, size: 0 }, &mut object), S_OK);
Expand Down Expand Up @@ -1267,19 +1282,54 @@ mod tests {
create_placed_srv(null, &shape, &srv, heap.handle(8).unwrap());
create_cbv(null, &[0x400, 6, 256, 0], heap.handle(8).unwrap());
}
let words = [0xf800_0003u32, 0, 7, 0, 5, 6];
let mut words = [0xf800_0003u32, 0, 7, 0, 5, 6, 0, 0, 0];
let fields = if trace {
words[4..6].fill(0);
words[7..9].copy_from_slice(&[5, 6]);
crate::material_demand::fields("b15ba4896d650511").unwrap()
} else {
&[0, 16, 20][..]
};
let bytes = std::mem::size_of_val(&words) as u64;
let (upload, mapped) = device.upload_buffer(bytes).unwrap();
// SAFETY: copy the full upload allocation into the owned material range.
// CPU memory for all six words stays zero; the selected values exist only on the GPU.
// CPU memory for these words stays zero; the selected values exist only on the GPU.
unsafe {
std::ptr::copy_nonoverlapping(words.as_ptr().cast::<u8>(), mapped, bytes as usize);
list.list.CopyBufferRegion(&shadow.buffer, shadow.offset(address), &upload, 0, bytes);
list.list.ResourceBarrier(&[crate::host::transition(&shadow.buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
}
crate::material_demand::record(&list, heap, heap.start, 0, &[0, 16, 20]);
crate::material_demand::record(&list, heap, heap.start, crate::material_demand::Request {
record: 0,
fields,
prioritize: !trace,
capture: trace.then_some(crate::material_demand::Capture {
shader: "b15ba4896d650511",
frame: frame + 1,
list: std::ptr::from_ref(&list) as usize,
}),
});
#[cfg(feature = "diagnostics")]
let trace_stamp = host.material_write_stamp();
list.close();
device.execute(&[&list]);
#[cfg(feature = "diagnostics")]
if trace {
let fields = host.material_demand.captured_fields();
assert_eq!(fields, [
(0, 3), (4, 0), (8, 7), (12, 0), (16, 0), (20, 0), (24, 0), (28, 5), (32, 6),
]);
assert_eq!(record_bytes, [0; 8]);
assert!(host.material_slot_state(heap, 5, trace_stamp, frame)
.contains("title_texture=true native_resource=false"));
create_cbv(null, &[0x400, 6, 256, 0], heap.handle(6).unwrap());
assert_eq!(host.material_slot_state(heap, 6, trace_stamp, frame), "title descriptor rewritten");
let due = host.texture_slots_due(frame, 128).0;
assert!(host.material_demand.take(heap, host, frame).is_empty());
assert_eq!(host.texture_slots_due(frame, 128).0, due);
assert_eq!(release(object), 0);
return;
}
let mut due: Vec<_> = (32..48).map(|n| (n,1,false)).collect();
due.push(write);
let wanted = host.material_demand.take(heap, host, frame);
Expand Down
93 changes: 87 additions & 6 deletions crates/victory-gpu/src/descriptor/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1339,6 +1339,55 @@ impl HostHeap {
}
}

/// Observe a sampled descriptor at readback time. A title rewrite
/// invalidates comparison with the command that selected the slot.
#[cfg(feature = "diagnostics")]
pub(crate) fn material_slot_state(
&self,
heap: &super::Heap,
index: u32,
stamp: crate::material_demand::Mark,
frame: u64,
) -> String {
let Some(epoch) = self.material_epochs.get().and_then(|e| e.get(index as usize)) else {
return "outside host view heap".into();
};
let unchanged = || epoch.load(std::sync::atomic::Ordering::Relaxed) <= stamp.descriptor;
if !unchanged() {
return "title descriptor rewritten".into();
}
let title = heap.handle(index).and_then(super::checked_view);
let native = self
.kept
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(index as usize)
.is_some_and(Option::is_some);
let host = self.describe_slot(index).unwrap_or_else(|| "unavailable".into());
let queue = self.texture_slot_state(index, frame, title.as_ref());
if unchanged() {
format!(
"title_texture={} native_resource={native} host=[{host}] queue=[{queue}]",
title.as_ref().is_some_and(is_texture_view),
)
} else {
"title descriptor rewritten".into()
}
}

/// A sampled generation still owned by the texture upload queue.
#[cfg(feature = "diagnostics")]
pub(crate) fn material_queued_write(&self, heap: &super::Heap, index: u32, stamp: crate::material_demand::Mark) -> Option<u64> {
let epoch = self.material_epochs.get()?.get(index as usize)?;
let unchanged = || epoch.load(std::sync::atomic::Ordering::Relaxed) <= stamp.descriptor;
if !unchanged() || !heap.handle(index).and_then(super::checked_view).as_ref().is_some_and(is_texture_view) {
return None;
}
let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
let queued = textures.slots.get(&index)?;
(unchanged() && (queued.write <= stamp.write || queued.recovered)).then_some(queued.write)
}

/// A shader-selected material field can re-enrol its current null block-compressed SRV.
/// Never supersede another allocation, or upload title bytes over a GPU writer.
pub(crate) fn demand_material_texture(&self, heap: &super::Heap, index: u32, stamp: crate::material_demand::Mark, frame: u64) -> Option<(u32, u64, bool)> {
Expand Down Expand Up @@ -1385,14 +1434,21 @@ impl HostHeap {

/// Between observation and upload the queue can be delayed by budgeting, a writable
/// resource can appear over the same pages, or streaming can remove a mip.
pub(crate) fn material_upload_allowed(&self, index: u32, write: u64, start: u64, len: u64, mapped: u64) -> bool {
pub(crate) fn material_upload_refusal(&self, index: u32, write: u64, start: u64, len: u64, mapped: u64) -> Option<&'static str> {
let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
let Some(waiting) = textures.slots.get(&index).filter(|w| w.write == write) else { return false };
if !waiting.recovered { return false; }
if !textures.slots.get(&index).is_some_and(|w| w.write == write && w.recovered) {
return Some("stale_write");
}
drop(textures);
start.checked_add(len).is_some_and(|end| mapped == len
&& !crate::resource::writable_texture_overlaps(start, end)
&& !crate::texture::host_written_overlaps(start, end))
let Some(end) = start.checked_add(len) else {
return Some("invalid_texture_span");
};
if mapped != len {
return Some("pages_unavailable");
}
(crate::resource::writable_texture_overlaps(start, end)
|| crate::texture::host_written_overlaps(start, end))
.then_some("recovery_conflicts_with_gpu_writes")
}

/// Every title slot of the queue that is due at `frame`, and whether
Expand Down Expand Up @@ -2483,6 +2539,12 @@ impl HostHeap {
queued_write: Option<u64>,
allow: impl FnOnce(&View, bool) -> bool,
) -> Result<Option<View>, ()> {
#[cfg(feature = "diagnostics")]
let trace = |outcome| {
if let Some(write) = queued_write {
self.material_demand.upload_outcome(index, write, crate::frame::current(), outcome);
}
};
if index >= self.count {
// Diagnostic (NVIDIA heap cap): the highest title slot past the
// host heap seen so far.
Expand All @@ -2495,10 +2557,14 @@ impl HostHeap {
"title slot past the host heap"
);
}
#[cfg(feature = "diagnostics")]
trace("outside_host_heap");
return Ok(None);
}
let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
if queued_write.is_some_and(|write| !self.queued_write_current(index, write)) {
#[cfg(feature = "diagnostics")]
trace("stale_write");
return Ok(None);
}
if !for_draw && let Some(epochs) = self.material_epochs.get() {
Expand All @@ -2524,6 +2590,8 @@ impl HostHeap {
let _ = self.note_buffer(index, None, false);
}
self.update_sparse(index, None, None, false);
#[cfg(feature = "diagnostics")]
trace("invalid_title_view");
return Ok(None);
};
if queued_write.is_some() && let View::Placed(false, resource, desc) = &view {
Expand All @@ -2536,6 +2604,8 @@ impl HostHeap {
let span = placed.bytes(resource, crate::resource::first_mip(desc))
.map(|bytes| (start, start.saturating_add(bytes)));
if span.is_none() || placed.by_slot.get(&index) != span.as_ref() {
#[cfg(feature = "diagnostics")]
trace("displaced_view");
return Ok(None);
}
}
Expand All @@ -2552,6 +2622,8 @@ impl HostHeap {
});
let current = (made[index as usize] == key && !changed_owner) || pending;
if !allow(&view, current) {
#[cfg(feature = "diagnostics")]
trace("vram_budget");
return Err(());
}
if !current {
Expand Down Expand Up @@ -2621,6 +2693,15 @@ impl HostHeap {
}
self.keep(index, kept.flatten());
}
#[cfg(feature = "diagnostics")]
if queued_write.is_some() && crate::material_demand::trace_enabled() && is_texture_view(&view) {
let native = self.kept.lock().unwrap_or_else(|e| e.into_inner())[index as usize].is_some();
trace(match (current, native) {
(false, true) => "srv_installed",
(true, true) => "srv_already_present",
(_, false) => "srv_unavailable",
});
}
Ok(Some(view))
}

Expand Down
43 changes: 37 additions & 6 deletions crates/victory-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1269,7 +1269,11 @@ impl State {
None => self.user_value(compute, u.slot, u.root, u.dword),
};
}
if !compute && crate::material_demand::enabled()
let capture = (!compute)
.then(|| crate::material_demand::capture_for(&stage.shader.hash, list))
.flatten();
let demand = !compute && crate::material_demand::enabled();
if (demand || capture.is_some())
&& let Some(fields) = crate::material_demand::fields(&stage.shader.hash)
&& t.host.user_data.iter().any(|u| u.index == 8 && u.root == RootType::Table && u.slot == 0)
&& let Some(u) = t.host.user_data.iter().find(|u| u.index == 14 && u.root == RootType::Constants)
Expand All @@ -1280,9 +1284,16 @@ impl State {
&& !heap.samplers()
&& let Some(&bound) = values.get(8)
&& Some(u64::from(bound)) == table.checked_sub(heap.start)
&& crate::material_demand::wants(heap, record, fields)
{
crate::material_demand::record(list, heap, *table, record, fields);
let prioritize = demand && crate::material_demand::wants(heap, record, fields);
if prioritize || capture.is_some() {
crate::material_demand::record(
list,
heap,
*table,
crate::material_demand::Request { record, fields, prioritize, capture },
);
}
}
// SAFETY: an open list; `values` covers the parameter.
unsafe {
Expand Down Expand Up @@ -1983,7 +1994,8 @@ impl State {
HEAP_TEXTURES_RECHECKED[1].fetch_add(changed, Ordering::Relaxed);
HEAP_TEXTURES_RECHECKED[2].store(waiting, Ordering::Relaxed);
}
let wanted = crate::material_demand::enabled().then(|| host.material_demand.take(heap, host, frame));
let wanted = (crate::material_demand::enabled() || crate::material_demand::trace_enabled())
.then(|| host.material_demand.take(heap, host, frame));
let (mut due, census) = host.texture_slots_due(frame, 4096);
if let Some(wanted) = wanted {
crate::material_demand::promote(&mut due, &wanted, frame);
Expand Down Expand Up @@ -2054,7 +2066,11 @@ impl State {
};
let began = std::time::Instant::now();
for (index, write, recovered) in due {
#[cfg(feature = "diagnostics")]
let trace = |outcome| host.material_demand.upload_outcome(index, write, frame, outcome);
if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span {
#[cfg(feature = "diagnostics")]
trace("staging_pass_limit");
break;
}
// A placed texture whose memory is not mapped (not streamed in
Expand All @@ -2075,11 +2091,17 @@ impl State {
// another texture's.
let len = crate::resource::placed_bytes_from(&resource, crate::resource::first_mip(&desc)).unwrap_or(1);
let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize);
if recovered && !host.material_upload_allowed(index, write, address, len, mapped) {
if recovered && let Some(reason) = host.material_upload_refusal(index, write, address, len, mapped) {
#[cfg(feature = "diagnostics")]
trace(reason);
#[cfg(not(feature = "diagnostics"))]
let _ = reason;
host.texture_slot_done(index, write, None);
continue;
}
if mapped == 0 {
#[cfg(feature = "diagnostics")]
trace("pages_unavailable");
HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed);
// Streamed out: what the slot showed is let go.
host.texture_slot_gone(index, write);
Expand All @@ -2088,6 +2110,8 @@ impl State {
}
if mapped < len {
if mapped <= host.texture_slot_mapped(index) {
#[cfg(feature = "diagnostics")]
trace("no_more_pages_mapped");
HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed);
host.texture_slot_later(index, write, frame, most);
continue;
Expand Down Expand Up @@ -2123,10 +2147,17 @@ impl State {
// under the line. `VICTORY_REUPLOAD_WHEN_FULL=0`: refused, as
// before.
let Some(handle) = heap.handle(index) else {
#[cfg(feature = "diagnostics")]
trace("missing_title_slot");
host.texture_slot_done(index, write, None);
continue;
};
let upload = (room || reupload_when_full())
let can_mirror = room || reupload_when_full();
#[cfg(feature = "diagnostics")]
if !can_mirror {
trace("vram_budget");
}
let upload = can_mirror
.then(|| host.mirror_queued(index, handle, write, !room))
.and_then(Result::ok);
let Some((view, _residence)) = upload else {
Expand Down
Loading