Skip to content
Merged
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
89 changes: 89 additions & 0 deletions crates/victory-gpu/src/descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,95 @@ pub(crate) fn sync_heaps() {
}
}

/// Per list: the heap-usage bitmap shaders that take views from the view
/// heap `heap` mark the slots they read in (`victory_shader::emit`,
/// `HostShader::heap_usage`), as its host GPU address. After the list ran,
/// each marked slot whose view the host left null (a placed texture, see
/// `host::HostHeap::mirror`) is made, so it reads from the next list on;
/// the bitmap is cleared. With `VICTORY_HEAP_USAGE=0` (or no such heap) the
/// marks are ignored.
#[cfg(windows)]
pub(crate) fn usage_bitmap(list: &crate::host::HostList, heap: usize) -> Option<u64> {
let words = (victory_shader::emit::HEAP_VIEWS / 32) as usize;
let (bitmap, data) = crate::host::host()?.shared_buffer((words as u64 * 4).next_multiple_of(256))?;
crate::host::name(&bitmap, || "heap slots read".into());
// SAFETY: our mapped buffer of at least `words` dwords.
unsafe { std::ptr::write_bytes(data.cast::<u32>(), 0, words) };
// SAFETY: a live buffer.
let gpu = unsafe { bitmap.GetGPUVirtualAddress() };
list.keep(&bitmap);
let data = data as usize;
list.defer_after(move || {
// SAFETY: the bitmap is mapped and the list's run is over.
let marks = unsafe { std::slice::from_raw_parts_mut(data as *mut u32, words) };
let on = heap_usage_on() && heap != 0;
if heap == 0 {
USAGE.2.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
let mut used = Vec::new();
for (w, mark) in marks.iter_mut().enumerate() {
if *mark == 0 {
continue;
}
let mut bits = std::mem::take(mark);
while on && bits != 0 {
used.push((w * 32) as u32 + bits.trailing_zeros());
bits &= bits - 1;
}
}
if used.is_empty() {
return;
}
let made = make_used(heap, &used);
USAGE.0.fetch_add(used.len() as u64, std::sync::atomic::Ordering::Relaxed);
USAGE.1.fetch_add(made, std::sync::atomic::Ordering::Relaxed);
});
Some(gpu)
}

/// Heap slots marked read, and views made for them, since the last call.
#[cfg(windows)]
pub(crate) fn take_usage() -> (u64, u64) {
use std::sync::atomic::Ordering::Relaxed;
(USAGE.0.swap(0, Relaxed), USAGE.1.swap(0, Relaxed))
}
#[cfg(windows)]
pub(crate) static USAGE: (std::sync::atomic::AtomicU64, std::sync::atomic::AtomicU64, std::sync::atomic::AtomicU64) =
(std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0));

#[cfg(windows)]
fn heap_usage_on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("VICTORY_HEAP_USAGE").map_or(true, |v| v != "0"))
}

/// Makes the views of slots `used` of the title view heap `heap` that the
/// host left null for later (placed textures); how many it made.
#[cfg(windows)]
fn make_used(heap: usize, used: &[u32]) -> u64 {
// Held throughout: a heap is not dropped while its slots are made.
let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
if !heaps.iter().any(|&(_, _, h)| h == heap) {
USAGE.2.fetch_add(1000, std::sync::atomic::Ordering::Relaxed);
return 0;
}
// SAFETY: registered heaps are live (removed when dropped).
let h = unsafe { &*(heap as *const Heap) };
let (Some(Some(host)), Some(step)) = (h.host.get(), increment(h.desc.kind)) else {
USAGE.2.fetch_add(1_000_000, std::sync::atomic::Ordering::Relaxed);
return 0;
};
let step = u64::from(step);
let mut made = 0;
for &index in used {
if host.make_placed(index, h.start + u64::from(index) * step) {
made += 1;
}
}
drop(heaps);
made
}

/// Gives back dynamic slots of the host heap behind the title heap at
/// `heap`, if that heap still exists.
#[cfg(windows)]
Expand Down
42 changes: 42 additions & 0 deletions crates/victory-gpu/src/descriptor/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,37 @@ impl HostHeap {
/// if it changed since, and returns the view recorded there. Buffer
/// views are made only for draws (`for_draw`), which also copy their
/// data: a host copy of a buffer is made on first use.
/// Makes the view of slot `index` (at `handle` in title memory) if it
/// is a placed texture's left null for later ([`Self::mirror`]), as a
/// draw reading it through a table would: true if it made it.
pub(crate) fn make_placed(&self, index: u32, handle: u64) -> bool {
use std::sync::atomic::Ordering::Relaxed;
if index >= self.count || self.sampler {
PLACED_WHY[0].fetch_add(1, Relaxed);
return false;
}
// SAFETY: the handle is a descriptor slot in title memory.
let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
let key = u64::from(generation) << 32 | u64::from(i);
{
let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
if made[index as usize] == key {
PLACED_WHY[1].fetch_add(1, Relaxed);
return false;
}
}
let Some(view) = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten() else {
PLACED_WHY[2].fetch_add(1, Relaxed);
return false;
};
if !is_placed_texture(&view) {
PLACED_WHY[3].fetch_add(1, Relaxed);
return false;
}
self.mirror(index, handle, true);
true
}

pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option<View> {
if index >= self.count {
// Diagnostic (NVIDIA heap cap): the highest title slot past the
Expand Down Expand Up @@ -658,6 +689,9 @@ impl HostHeap {
make(&view, self.cpu(index))
};
if kept.is_none() && !self.sampler {
if !later && is_placed_texture(&view) {
PLACED_FAILED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
null_for(&view, self.cpu(index));
}
if !self.sampler {
Expand Down Expand Up @@ -1249,6 +1283,14 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> {
}

/// Whether `view` is a view of a texture the title placed in memory itself.
/// Marked slots not made, by reason: past the heap or a sampler heap,
/// already made, no view of ours there, not a placed texture.
/// Placed-texture views the host tried to make and could not (left null
/// although marked made).
pub(crate) static PLACED_FAILED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

pub(crate) static PLACED_WHY: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];

fn is_placed_texture(view: &View) -> bool {
matches!(view, View::Placed(_, resource, _) if resource[0] != 1)
}
Expand Down
26 changes: 26 additions & 0 deletions crates/victory-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ pub(crate) struct State {
/// The title-memory page table made for this list (`crate::memory`)
/// and its view heap.
memory: Option<(usize, crate::memory::Map)>,
/// The heap-usage bitmap made for this list and its view heap
/// (`crate::descriptor::usage_bitmap`).
heap_usage: Option<(usize, u64)>,
/// Views made for root SRVs and UAVs in this list ([`State::root_view`]):
/// (view heap, host copy, unordered access) → dynamic slot.
root_slots: std::collections::HashMap<(usize, usize, bool), u32>,
Expand Down Expand Up @@ -828,6 +831,29 @@ impl State {
}
}
}
for stage in &p.stages {
if let Some(param) = stage.heap_used {
let heap = self.heaps[0];
let gpu = match self.heap_usage {
Some((h, gpu)) if h == heap => Some(gpu),
_ => crate::descriptor::usage_bitmap(list, heap),
};
let Some(gpu) = gpu else {
once!("a shader marking heap slots dropped: no usage bitmap");
not_run("heap usage without a bitmap");
return false;
};
self.heap_usage = Some((heap, gpu));
// SAFETY: an open list; the bitmap lives with the list.
unsafe {
if compute {
l.SetComputeRootUnorderedAccessView(param, gpu);
} else {
l.SetGraphicsRootUnorderedAccessView(param, gpu);
}
}
}
}
#[cfg(feature = "diagnostics")]
crate::capture::binding("");
true
Expand Down
7 changes: 7 additions & 0 deletions crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3132,6 +3132,13 @@ impl Meter {
crate::texture::ALIAS_COPIES.swap(0, Ordering::Relaxed) as f64 / frames,
crate::twin::COPIES.swap(0, Ordering::Relaxed) as f64 / frames,
);
let (marked, made) = crate::descriptor::take_usage();
tracing::info!(
"heap usage: {marked} heap slots marked read by shaders, {made} placed-texture views made for them (last 5 s); not made: {:?}, no heap {}; placed textures that failed to make: {}",
crate::descriptor::host::PLACED_WHY.each_ref().map(|a| a.swap(0, Ordering::Relaxed)),
crate::descriptor::USAGE.2.swap(0, Ordering::Relaxed),
crate::descriptor::host::PLACED_FAILED.swap(0, Ordering::Relaxed),
);
#[cfg(feature = "diagnostics")]
{
let copy_frames = std::mem::take(&mut self.copy_stats_frames) as f64;
Expand Down
5 changes: 5 additions & 0 deletions crates/victory-gpu/src/pipeline/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,9 @@ pub(crate) struct Stage {
/// written-pages bitmap (`crate::memory`), if it reads or writes there.
pub(crate) memory: Option<u32>,
pub(crate) memory_dirty: Option<u32>,
/// Our root parameter of the heap-usage bitmap
/// (`crate::descriptor::usage_bitmap`), if it marks heap slots.
pub(crate) heap_used: Option<u32>,
/// Our root parameter of the heap's view addresses (`crate::memory`).
pub(crate) view_addresses: Option<u32>,
}
Expand Down Expand Up @@ -523,6 +526,7 @@ impl HostPipeline {
root_uavs: Vec::new(),
memory: None,
memory_dirty: None,
heap_used: None,
view_addresses: None,
};
let dwords = t.user_data_dwords();
Expand Down Expand Up @@ -576,6 +580,7 @@ impl HostPipeline {
(t.memory, D3D12_ROOT_PARAMETER_TYPE_SRV, 0, &mut stage.memory),
(t.memory_writes, D3D12_ROOT_PARAMETER_TYPE_UAV, 0, &mut stage.memory_dirty),
(t.view_addresses, D3D12_ROOT_PARAMETER_TYPE_SRV, 1, &mut stage.view_addresses),
(t.heap_usage, D3D12_ROOT_PARAMETER_TYPE_UAV, 1, &mut stage.heap_used),
] {
if used {
*out = Some(params.len() as u32);
Expand Down
6 changes: 5 additions & 1 deletion crates/victory-gpu/src/shader_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ fn encode(translation: &Result<HostShader, String>) -> Vec<u8> {
root_uavs,
memory,
memory_writes,
heap_usage,
view_addresses,
heap,
heap_writes,
Expand Down Expand Up @@ -260,7 +261,8 @@ fn encode(translation: &Result<HostShader, String>) -> Vec<u8> {
| u32::from(*memory_writes) << 1
| u32::from(*view_addresses) << 2
| u32::from(*heap) << 3
| u32::from(*heap_writes) << 4,
| u32::from(*heap_writes) << 4
| u32::from(*heap_usage) << 5,
);
out
}
Expand Down Expand Up @@ -334,6 +336,7 @@ fn decode(bytes: &[u8]) -> Option<Result<HostShader, String>> {
root_uavs,
memory: memory & 1 != 0,
memory_writes: memory & 2 != 0,
heap_usage: memory & 32 != 0,
view_addresses: memory & 4 != 0,
heap: memory & 8 != 0,
heap_writes: memory & 16 != 0,
Expand Down Expand Up @@ -366,6 +369,7 @@ mod tests {
root_uavs: vec![4],
memory: true,
memory_writes: true,
heap_usage: true,
view_addresses: true,
heap: true,
heap_writes: true,
Expand Down
1 change: 1 addition & 0 deletions crates/victory-shader/src/emit/bvh_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,7 @@ fn build(cfg: Config) -> HostShader {
root_uavs: lowered.root_uavs,
memory: lowered.memory,
memory_writes: lowered.memory_writes,
heap_usage: lowered.heap_usage,
view_addresses: lowered.view_addresses,
heap: lowered.heap,
heap_writes: lowered.heap_writes,
Expand Down
5 changes: 5 additions & 0 deletions crates/victory-shader/src/emit/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,9 @@ impl Host {
if stages.iter().any(|(s, _)| s.view_addresses) {
views.push((1, super::MEMORY_SPACE, 1));
}
if stages.iter().any(|(s, _)| s.heap_usage) {
views.push((1, super::MEMORY_SPACE, 2));
}
for (register, space, kind) in views {
params.push(D3D12_ROOT_PARAMETER1 {
ParameterType: match kind {
Expand Down Expand Up @@ -875,6 +878,7 @@ fn fmad_probe() -> Result<HostShader, crate::ShaderError> {
root_uavs: lowered.root_uavs,
memory: lowered.memory,
memory_writes: lowered.memory_writes,
heap_usage: lowered.heap_usage,
view_addresses: lowered.view_addresses,
heap: lowered.heap,
heap_writes: lowered.heap_writes,
Expand Down Expand Up @@ -973,6 +977,7 @@ fn stub(pixel: bool, outputs: Vec<SigElement>) -> HostShader {
root_uavs: Vec::new(),
memory: false,
memory_writes: false,
heap_usage: false,
view_addresses: false,
heap: false,
heap_writes: false,
Expand Down
1 change: 1 addition & 0 deletions crates/victory-shader/src/emit/lds_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ fn build_cs(body: &[u32], threads: u32) -> HostShader {
root_uavs: lowered.root_uavs,
memory: lowered.memory,
memory_writes: lowered.memory_writes,
heap_usage: lowered.heap_usage,
view_addresses: lowered.view_addresses,
heap: lowered.heap,
heap_writes: lowered.heap_writes,
Expand Down
Loading