GPU: the world stays up; indirect execution behind a switch
The host device was removed seconds into the world because a shader read a descriptor of the wrong kind: empty slots held a null 2D texture view where the shader expected a buffer, which gave a garbage heap index and a read far past the view heap. Null descriptors now have the kind the shader expects (raw buffer, constant buffer, or a texture of the title's own dimension). The world then ran to a 240 s time limit with no removal. Also: - Host lists hold the textures, pipelines, root signatures and heaps they name, and heap slots hold the resource they view (the title releases objects before submitting lists that use them). - The device-removed report places the fault against the host descriptor heaps and names our own uploads; VICTORY_D3D12_GBV turns on GPU-based validation, VICTORY_DUMP_TARGETS works. - Indirect execution (draw, indexed draw, dispatch, mesh dispatch): the world draws most of its geometry this way. Arguments are clamped and charged to a per-list budget by a small compute pass first, so garbage cannot hang the GPU. Off by default (VICTORY_INDIRECT=1): with it on the title's own GPU watchdog ends the run about 30 s into the world. - Shader-written ranges are copied back once per submission and only where they differ; refreshes beside them copy only stale pages. The frame-rate line counts copy-backs and dropped draws. Not working yet: the world's picture is black (indirect draws off, and hundreds of draws per frame have no translated shader). Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
1 parent
1922261412
commit
d50f2368cb
14 files changed
+973
-151
No files matched your search
@@ -19,7 +19,7 @@ loads the world, where rendering fails.
|
||||
| Intro video with sound | works |
|
||||
| Start screen, profile and saves | works |
|
||||
| Loading into the world (about 50 s) | works |
|
||||
| The world (first mission's intro) | reached; the picture is black and the host GPU fails within seconds |
|
||||
| The world (first mission's intro) | reached and runs (two minutes without a GPU failure); the picture is black, 1.5-3 s per frame |
|
||||
|
||||
Tested on one machine: Windows 11, AMD RX 6700 XT.
|
||||
|
||||
@@ -39,7 +39,7 @@ What each part does today and what it still needs:
|
||||
| Input | XInput pads, keyboard, keyboard stand-in pad | Trigger rumble |
|
||||
| Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title |
|
||||
| GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds |
|
||||
| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes are in | The host device is lost and frames are black; frames take seconds; indirect dispatches, real queries, depth bounds, HDR and scaling are missing |
|
||||
| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped) are in | Frames are black (most geometry is drawn indirectly; untranslated shaders drop the rest); frames take seconds; real queries, depth bounds, HDR and scaling are missing |
|
||||
| Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | 64-bit image atomics, merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves |
|
||||
| Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes |
|
||||
| Series S mode | Runs through the menus to the loading screen | The world, as above |
|
||||
@@ -114,6 +114,8 @@ cargo build --profile diag -p victory --features diagnostics # target\diag\vic
|
||||
| `VICTORY_CAPTURE=<dir>` | saves presented frames (powers of two, or `VICTORY_CAPTURE_FRAMES=<list>`) |
|
||||
| `VICTORY_DUMP_TARGETS=1` | with the two above, saves every render target of those frames |
|
||||
| `VICTORY_D3D12_DEBUG=1` | host debug layer |
|
||||
| `VICTORY_INDIRECT=1` | runs the title's indirect draws and dispatches (off: the world's first frame stalls with it) |
|
||||
| `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) |
|
||||
| `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight |
|
||||
| `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) |
|
||||
| `VICTORY_AUDIO_CAPTURE=<file.wav>` | records what the title plays (our process only) |
|
||||
|
||||
@@ -30,6 +30,7 @@ workspace = true
|
||||
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
windows = { workspace = true, features = [
|
||||
"Win32_Graphics_Direct3D",
|
||||
"Win32_Graphics_Direct3D_Fxc",
|
||||
"Win32_Graphics_Direct3D12",
|
||||
"Win32_Graphics_Dxgi",
|
||||
"Win32_Graphics_Dxgi_Common",
|
||||
|
||||
@@ -203,7 +203,10 @@ pub(crate) fn save_read_back(
|
||||
/// at that frame's present as `frame-<n>-<i>-<resource>-<w>x<h>-f<format>.png`
|
||||
/// (what each holds at the end of the frame; formats normalized to show
|
||||
/// structure: floats scaled by their largest value, depth by its range).
|
||||
static TARGETS: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
|
||||
/// The host copies are held: the title may release a target before the
|
||||
/// frame is presented.
|
||||
static TARGETS: std::sync::Mutex<Vec<(usize, std::sync::Arc<crate::resource::HostTexture>)>> =
|
||||
std::sync::Mutex::new(Vec::new());
|
||||
|
||||
fn dump_on() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
@@ -216,33 +219,28 @@ pub(crate) fn note_target(resource: crate::object::This) {
|
||||
return;
|
||||
}
|
||||
let mut targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !targets.contains(&(resource as usize)) {
|
||||
targets.push(resource as usize);
|
||||
if !targets.iter().any(|&(r, _)| r == resource as usize)
|
||||
&& let Some(copy) = crate::resource::host_copy(resource)
|
||||
{
|
||||
targets.push((resource as usize, copy));
|
||||
}
|
||||
}
|
||||
|
||||
/// At the present of frame `frame`: saves the noted targets.
|
||||
pub(crate) fn dump_targets(frame: u64) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let targets = std::mem::take(&mut *TARGETS.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
let Some(host) = crate::host::host() else { return };
|
||||
for (i, &resource) in targets.iter().enumerate() {
|
||||
let resource = resource as crate::object::This;
|
||||
let Some(texture) = crate::resource::host_resource(resource) else {
|
||||
continue;
|
||||
};
|
||||
for (i, (resource, copy)) in targets.iter().enumerate() {
|
||||
let texture = ©.texture;
|
||||
// SAFETY: a live resource.
|
||||
let d = unsafe { texture.GetDesc() };
|
||||
if d.SampleDesc.Count > 1 || d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D {
|
||||
continue;
|
||||
}
|
||||
const COPY_SOURCE: u32 = 0x800;
|
||||
let Some(before) = crate::resource::host_transition(resource, COPY_SOURCE).map(|(_, b)| b)
|
||||
else {
|
||||
dump_one(host, texture, COPY_SOURCE, frame, i, resource, &d);
|
||||
continue;
|
||||
};
|
||||
dump_one(host, texture, before, frame, i, resource, &d);
|
||||
crate::resource::host_transition(resource, before);
|
||||
// Every submission has run; the dump's list moves it there and back.
|
||||
let state = copy.state.load(Relaxed);
|
||||
dump_one(host, texture, state, frame, i, *resource as crate::object::This, &d);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,8 +361,10 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option
|
||||
15..=16 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)), f32::from_bits(u32_at(b, 1)), 0.0])),
|
||||
35..=38 => (4, Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0])),
|
||||
48..=52 => (2, Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0])),
|
||||
// Single channels: shown as grey.
|
||||
// Single channels (and depth planes): shown as grey.
|
||||
39..=43 => (4, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])),
|
||||
19..=22 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])),
|
||||
44..=47 => (4, Box::new(move |b| [(u32_at(b, 0) & 0xff_ffff) as f32; 3])),
|
||||
53..=54 => (2, Box::new(move |b| [half(u16_at(b, 0)); 3])),
|
||||
55..=59 => (2, Box::new(move |b| [f32::from(u16_at(b, 0)); 3])),
|
||||
60..=65 => (1, Box::new(move |b| [f32::from(b[0]); 3])),
|
||||
@@ -374,7 +374,7 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option
|
||||
.flat_map(|y| (0..w).map(move |x| (x, y)))
|
||||
.map(|(x, y)| decode(px(x, y, n)))
|
||||
.collect();
|
||||
let grey = matches!(format, 39..=43 | 53..=65);
|
||||
let grey = matches!(format, 19..=22 | 39..=47 | 53..=65);
|
||||
let finite = values.iter().flatten().copied().filter(|v| v.is_finite());
|
||||
let (low, high) = if grey {
|
||||
finite.fold((f32::MAX, f32::MIN), |(l, h), v| (l.min(v), h.max(v)))
|
||||
|
||||
@@ -22,11 +22,39 @@ pub(crate) struct HostHeap {
|
||||
sampler: bool,
|
||||
/// The record (view index and generation) each slot was last made from.
|
||||
made: Mutex<Vec<u64>>,
|
||||
/// The host resource each slot views, held while the slot does: shaders
|
||||
/// index heaps directly, so a slot the title has not rewritten since it
|
||||
/// released the resource may still be read, and a freed host resource
|
||||
/// read there is a GPU page fault (the console reads stale memory).
|
||||
kept: Mutex<Vec<Option<ID3D12Resource>>>,
|
||||
/// Where the search for free dynamic slots starts, and which are taken
|
||||
/// (by lists not yet reset).
|
||||
next: Mutex<(u32, Vec<bool>)>,
|
||||
}
|
||||
|
||||
/// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for
|
||||
/// device-removed reports: a shader indexing a heap past its end faults.
|
||||
static GPU_RANGES: Mutex<Vec<(u64, u64, u64, bool)>> = Mutex::new(Vec::new());
|
||||
|
||||
/// For device-removed reports: where host GPU address `va` lies against
|
||||
/// the host descriptor heaps.
|
||||
pub(crate) fn near_heaps(va: u64) -> String {
|
||||
let ranges = GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut text = String::new();
|
||||
for &(start, bytes, step, sampler) in ranges.iter() {
|
||||
let kind = if sampler { "sampler" } else { "view" };
|
||||
let place = if va < start {
|
||||
format!("{:#x} below", start - va)
|
||||
} else if va < start + bytes {
|
||||
format!("inside, slot {}", (va - start) / step)
|
||||
} else {
|
||||
format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step)
|
||||
};
|
||||
text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}"));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The host's limit for shader-visible view heaps on resource binding
|
||||
/// tiers 1 and 2; tier 3 hardware may take more.
|
||||
const PORTABLE_VIEWS: u32 = 1_000_000;
|
||||
@@ -78,6 +106,14 @@ impl HostHeap {
|
||||
)
|
||||
};
|
||||
tracing::debug!(count, sampler, "host descriptor heap");
|
||||
// SAFETY: a live shader-visible heap.
|
||||
let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr };
|
||||
GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((
|
||||
gpu,
|
||||
u64::from(count + extra) * u64::from(step),
|
||||
u64::from(step),
|
||||
sampler,
|
||||
));
|
||||
let h = HostHeap {
|
||||
heap,
|
||||
cpu,
|
||||
@@ -85,6 +121,7 @@ impl HostHeap {
|
||||
count,
|
||||
sampler,
|
||||
made: Mutex::new(vec![0; count as usize]),
|
||||
kept: Mutex::new(vec![None; (count + extra) as usize]),
|
||||
next: Mutex::new((0, vec![false; DYNAMIC as usize])),
|
||||
};
|
||||
// A slot never written is undefined: shaders reading one (a slot
|
||||
@@ -215,9 +252,11 @@ impl HostHeap {
|
||||
/// Makes slot `index` (a dynamic one) from `view`; a null view if the
|
||||
/// host cannot.
|
||||
pub(crate) fn make_at(&self, index: u32, view: &View) {
|
||||
if !make(view, self.cpu(index)) {
|
||||
let kept = make(view, self.cpu(index));
|
||||
if kept.is_none() {
|
||||
null_for(view, self.cpu(index));
|
||||
}
|
||||
self.keep(index, kept.flatten());
|
||||
}
|
||||
|
||||
/// Makes slot `index` read nothing: a null view, or a plain sampler.
|
||||
@@ -227,11 +266,21 @@ impl HostHeap {
|
||||
} else {
|
||||
null_view(self.cpu(index));
|
||||
}
|
||||
self.keep(index, None);
|
||||
}
|
||||
|
||||
/// Slot `index` now views `resource` (or nothing of the host's).
|
||||
fn keep(&self, index: u32, resource: Option<ID3D12Resource>) {
|
||||
let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(slot) = kept.get_mut(index as usize) {
|
||||
*slot = resource;
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes slot `index` (a dynamic one) a constant buffer view of host
|
||||
/// memory.
|
||||
/// memory (the list's own, which it holds).
|
||||
pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) {
|
||||
self.keep(index, None);
|
||||
let Some(host) = host() else { return };
|
||||
let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
|
||||
BufferLocation: gpu,
|
||||
@@ -276,9 +325,15 @@ impl HostHeap {
|
||||
if made[index as usize] != key {
|
||||
let later = !for_draw && view.is_buffer();
|
||||
made[index as usize] = if later { 0 } else { key };
|
||||
if (later || !make(&view, self.cpu(index))) && !self.sampler {
|
||||
let kept = if later {
|
||||
None
|
||||
} else {
|
||||
make(&view, self.cpu(index))
|
||||
};
|
||||
if kept.is_none() && !self.sampler {
|
||||
null_for(&view, self.cpu(index));
|
||||
}
|
||||
self.keep(index, kept.flatten());
|
||||
}
|
||||
Some(view)
|
||||
}
|
||||
@@ -398,15 +453,16 @@ fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
|
||||
))
|
||||
}
|
||||
|
||||
/// The host resource a slot made by [`make`] views, if any.
|
||||
type Kept = Option<ID3D12Resource>;
|
||||
|
||||
fn buffer_srv(
|
||||
address: u64,
|
||||
len: u64,
|
||||
mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC,
|
||||
at: D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
) -> bool {
|
||||
let Some(shadow) = crate::shadow::find(address, len) else {
|
||||
return false;
|
||||
};
|
||||
) -> Option<Kept> {
|
||||
let shadow = crate::shadow::find(address, len)?;
|
||||
let element = element_size(&desc);
|
||||
// SAFETY: a buffer view's union member.
|
||||
let buffer = unsafe { &mut desc.Anonymous.Buffer };
|
||||
@@ -417,16 +473,16 @@ fn buffer_srv(
|
||||
element,
|
||||
"buffer view not on an element of its host copy"
|
||||
);
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
buffer.FirstElement += offset / element;
|
||||
let Some(host) = host() else { return false };
|
||||
let host = host()?;
|
||||
// SAFETY: a live buffer and a slot of our heap.
|
||||
unsafe {
|
||||
host.device
|
||||
.CreateShaderResourceView(&shadow.buffer, Some(&desc), at)
|
||||
};
|
||||
true
|
||||
Some(Some(shadow.buffer.clone()))
|
||||
}
|
||||
|
||||
/// An unordered access view of title buffer memory at `address` (`len`
|
||||
@@ -439,15 +495,13 @@ fn buffer_uav(
|
||||
len: u64,
|
||||
mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC,
|
||||
at: D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
) -> bool {
|
||||
let Some(shadow) = crate::shadow::find(address, len) else {
|
||||
return false;
|
||||
};
|
||||
) -> Option<Kept> {
|
||||
let shadow = crate::shadow::find(address, len)?;
|
||||
// SAFETY: a live buffer.
|
||||
let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
|
||||
if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
|
||||
once!("unordered access to a buffer whose host copy shaders cannot write");
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
// SAFETY: a buffer view's union member.
|
||||
let buffer = unsafe { &mut desc.Anonymous.Buffer };
|
||||
@@ -461,17 +515,17 @@ fn buffer_uav(
|
||||
let offset = shadow.offset(address);
|
||||
if element == 0 || offset % element != 0 {
|
||||
once!(offset, element, "unordered buffer view not on an element of its host copy");
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
buffer.FirstElement += offset / element;
|
||||
buffer.CounterOffsetInBytes = 0;
|
||||
let Some(host) = host() else { return false };
|
||||
let host = host()?;
|
||||
// SAFETY: a live buffer and a slot of our heap.
|
||||
unsafe {
|
||||
host.device
|
||||
.CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at)
|
||||
};
|
||||
true
|
||||
Some(Some(shadow.buffer.clone()))
|
||||
}
|
||||
|
||||
/// Whether the host can make a shader (or unordered access) view of
|
||||
@@ -527,22 +581,21 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere
|
||||
true
|
||||
}
|
||||
|
||||
/// Makes the host descriptor for `view` at `at`; false if it cannot.
|
||||
fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool {
|
||||
let Some(host) = host() else { return false };
|
||||
/// Makes the host descriptor for `view` at `at`: the host resource it
|
||||
/// views, or `None` if it cannot.
|
||||
fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> {
|
||||
let host = host()?;
|
||||
let device = &host.device;
|
||||
match view {
|
||||
&View::Constant(address, size) => {
|
||||
let Some(shadow) = crate::shadow::find(address, u64::from(size)) else {
|
||||
return false;
|
||||
};
|
||||
let shadow = crate::shadow::find(address, u64::from(size))?;
|
||||
let gpu = shadow.gpu(address);
|
||||
if gpu % 256 != 0 {
|
||||
once!(
|
||||
address = format_args!("{address:#x}"),
|
||||
"constant buffer not 256-byte aligned on the host"
|
||||
);
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
|
||||
BufferLocation: gpu,
|
||||
@@ -550,14 +603,14 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool {
|
||||
};
|
||||
// SAFETY: a slot of our heap; the range lies in the host copy.
|
||||
unsafe { device.CreateConstantBufferView(Some(&desc), at) };
|
||||
true
|
||||
Some(Some(shadow.buffer.clone()))
|
||||
}
|
||||
View::Shader(resource, desc) => {
|
||||
let resource = *resource as crate::object::This;
|
||||
if let Some(texture) = crate::resource::host_resource(resource) {
|
||||
let mut desc = desc.as_ref().map(srv_desc);
|
||||
if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) {
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
// SAFETY: a live texture and a slot of our heap.
|
||||
unsafe {
|
||||
@@ -567,13 +620,13 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool {
|
||||
at,
|
||||
)
|
||||
};
|
||||
true
|
||||
Some(Some(texture.clone()))
|
||||
} else if let (Some((data, len)), Some(desc)) =
|
||||
(crate::resource::buffer_bytes(resource), desc)
|
||||
{
|
||||
buffer_srv(data as u64, len, srv_desc(desc), at)
|
||||
} else {
|
||||
false
|
||||
None
|
||||
}
|
||||
}
|
||||
View::Unordered(resource, _counter, desc) => {
|
||||
@@ -583,12 +636,12 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool {
|
||||
(Some((data, len)), Some(desc)) => {
|
||||
buffer_uav(data as u64, len, uav_desc(desc), at)
|
||||
}
|
||||
_ => false,
|
||||
_ => None,
|
||||
};
|
||||
};
|
||||
let mut desc = desc.as_ref().map(uav_desc);
|
||||
if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) {
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
// SAFETY: a live texture and a slot of our heap.
|
||||
unsafe {
|
||||
@@ -599,7 +652,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool {
|
||||
at,
|
||||
)
|
||||
};
|
||||
true
|
||||
Some(Some(texture.clone()))
|
||||
}
|
||||
View::Sampler(words) => {
|
||||
// SAFETY: 13 words in the host's layout.
|
||||
@@ -610,13 +663,13 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool {
|
||||
};
|
||||
// SAFETY: a slot of our sampler heap.
|
||||
unsafe { device.CreateSampler(&desc, at) };
|
||||
true
|
||||
Some(None)
|
||||
}
|
||||
View::ConsoleSampler(words) => {
|
||||
let desc = crate::sampler::console(words);
|
||||
// SAFETY: a slot of our sampler heap.
|
||||
unsafe { device.CreateSampler(&desc, at) };
|
||||
true
|
||||
Some(None)
|
||||
}
|
||||
View::Placed(unordered, resource, desc) => {
|
||||
if let Some(view) = placed_texture(view) {
|
||||
@@ -628,7 +681,7 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool {
|
||||
// itself is not mirrored; give it a resource as shader
|
||||
// views of such textures get when a dispatch writes one.
|
||||
once!(dimension = resource[0], "placed unordered texture view not mirrored");
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
// The resource description's width, after the alignment.
|
||||
let len = u64::from(resource[4]) | u64::from(resource[5]) << 32;
|
||||
@@ -662,12 +715,30 @@ pub(crate) fn placed_texture(view: &View) -> Option<View> {
|
||||
/// cannot make: unordered access (to a buffer or a 2D texture) or a shader
|
||||
/// view. Writes to it are dropped, reads give zeros.
|
||||
fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
let Some(host) = host() else { return };
|
||||
let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some();
|
||||
let buffer = match view {
|
||||
View::Unordered(r, _, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_some(),
|
||||
View::Unordered(r, _, _) => is_buffer(r),
|
||||
View::Placed(true, resource, _) => resource[0] == 1,
|
||||
// Shader views of buffers read nothing through a null buffer view:
|
||||
// a null 2D view where the shader expects a buffer is a mismatch
|
||||
// the hardware does not survive in general (GPU-based validation
|
||||
// reports it).
|
||||
View::Shader(r, _) if is_buffer(r) => return null_buffer_view(at),
|
||||
View::Placed(false, resource, _) if resource[0] == 1 => return null_buffer_view(at),
|
||||
// Textures: a null view of the title's dimension (1D, arrays, 3D,
|
||||
// cubes), not always 2D.
|
||||
View::Shader(_, Some(desc)) => return null_like(desc, at),
|
||||
View::Placed(false, _, desc) => {
|
||||
return null_like(desc[..10].try_into().unwrap_or(&[0; 10]), at);
|
||||
}
|
||||
View::Constant(..) => {
|
||||
let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default();
|
||||
// SAFETY: a slot of our heap; a zero location makes a null view.
|
||||
return unsafe { host.device.CreateConstantBufferView(Some(&desc), at) };
|
||||
}
|
||||
_ => return null_view(at),
|
||||
};
|
||||
let Some(host) = host() else { return };
|
||||
let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
|
||||
Format: DXGI_FORMAT_R32_UINT,
|
||||
ViewDimension: if buffer {
|
||||
@@ -688,6 +759,56 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
};
|
||||
}
|
||||
|
||||
/// A buffer view that reads zeros (raw, as translated shaders mostly read
|
||||
/// buffers).
|
||||
fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
let Some(host) = host() else { return };
|
||||
let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
|
||||
Format: DXGI_FORMAT_R32_TYPELESS,
|
||||
ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
|
||||
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
|
||||
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
|
||||
Buffer: D3D12_BUFFER_SRV {
|
||||
NumElements: 1,
|
||||
Flags: D3D12_BUFFER_SRV_FLAG_RAW,
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
};
|
||||
// SAFETY: a slot of our heap; a null resource is allowed with a desc.
|
||||
unsafe {
|
||||
host.device
|
||||
.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
|
||||
};
|
||||
}
|
||||
|
||||
/// A texture view that reads zeros with the dimension (and mip and array
|
||||
/// counts) of the title's description `words`; 2D if it names none.
|
||||
fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
const TEXTURES: std::ops::RangeInclusive<u32> = 2..=10;
|
||||
if !TEXTURES.contains(&words[1]) {
|
||||
return null_view(at);
|
||||
}
|
||||
let Some(host) = host() else { return };
|
||||
// One mip, one slice or cube, plane 0: fields a null view still checks.
|
||||
let mut w = [0u32; 10];
|
||||
w[1] = words[1];
|
||||
match words[1] {
|
||||
6 => {}
|
||||
7 => w[5] = 1,
|
||||
3 | 5 | 10 => (w[5], w[7]) = (1, 1),
|
||||
_ => w[5] = 1,
|
||||
}
|
||||
let mut desc = srv_desc(&w);
|
||||
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
|
||||
// SAFETY: a slot of our heap; a null resource is allowed with a desc.
|
||||
unsafe {
|
||||
host.device
|
||||
.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
|
||||
};
|
||||
}
|
||||
|
||||
/// A view that reads zeros, for slots whose view the host cannot make.
|
||||
fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
let Some(host) = host() else { return };
|
||||
|
||||
@@ -106,6 +106,13 @@ pub(crate) fn take_frame() -> Vec<String> {
|
||||
std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner()))
|
||||
}
|
||||
|
||||
/// Draws, mesh dispatches and dispatches recorded but not run on the host
|
||||
/// (no host pipeline) since the last call.
|
||||
pub(crate) fn take_dropped() -> u64 {
|
||||
DROPPED.swap(0, Ordering::Relaxed)
|
||||
}
|
||||
static DROPPED: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Marks the last traced draw as not run on the host.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn dropped() {
|
||||
@@ -403,6 +410,7 @@ impl State {
|
||||
.filter_map(|&h| crate::descriptor::heap(h as This).host())
|
||||
.map(|h| Some(h.heap.clone()))
|
||||
.collect();
|
||||
heaps.iter().flatten().for_each(|h| list.keep(h));
|
||||
// SAFETY: an open list and shader-visible heaps.
|
||||
unsafe { l.SetDescriptorHeaps(&heaps) };
|
||||
self.host_heaps = self.heaps;
|
||||
@@ -420,11 +428,16 @@ impl State {
|
||||
}
|
||||
self.host_roots[usize::from(compute)] = root;
|
||||
}
|
||||
if self.host_pipeline != self.pipeline {
|
||||
// By host object: a title pipeline released and another made at its
|
||||
// address is another host pipeline (the list keeps the old one).
|
||||
if self.host_pipeline != p.pso.as_raw() as usize {
|
||||
// SAFETY: an open list and a live pipeline.
|
||||
unsafe { l.SetPipelineState(&p.pso) };
|
||||
self.host_pipeline = self.pipeline;
|
||||
self.host_pipeline = p.pso.as_raw() as usize;
|
||||
list.used_pipeline(&p.name);
|
||||
// The title may release the pipeline before it submits the list.
|
||||
list.keep(&p.pso);
|
||||
list.keep(&p.root);
|
||||
}
|
||||
for stage in &p.stages {
|
||||
let t = stage.translated();
|
||||
@@ -480,6 +493,7 @@ impl State {
|
||||
pipeline = format_args!("{:#x}", self.pipeline),
|
||||
"a dispatch without a host pipeline dropped"
|
||||
);
|
||||
DROPPED.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
};
|
||||
if !p.compute {
|
||||
@@ -548,12 +562,11 @@ impl State {
|
||||
}
|
||||
Err(_) => false,
|
||||
};
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if !ran {
|
||||
DROPPED.fetch_add(1, Ordering::Relaxed);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
dropped();
|
||||
}
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
let _ = ran;
|
||||
}
|
||||
|
||||
fn roots_ref(&self, compute: bool) -> &Vec<Root> {
|
||||
@@ -781,8 +794,9 @@ impl State {
|
||||
};
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if !ran {
|
||||
DROPPED.fetch_add(1, Ordering::Relaxed);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
dropped();
|
||||
}
|
||||
}
|
||||
@@ -867,13 +881,139 @@ impl State {
|
||||
};
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if !ran {
|
||||
DROPPED.fetch_add(1, Ordering::Relaxed);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
dropped();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Indirect execution of a one-argument signature of `kind` (PC
|
||||
/// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with
|
||||
/// records `stride` bytes apart at title address `arguments`, and the
|
||||
/// record count at `count` if the title gives one: the GPU reads them
|
||||
/// from the buffer's host copy, where earlier dispatches may have
|
||||
/// written them. False if it cannot run on the host.
|
||||
pub(crate) fn execute_indirect(
|
||||
&mut self,
|
||||
list: &HostList,
|
||||
(kind, stride, max): (u32, u32, u32),
|
||||
arguments: u64,
|
||||
count: Option<u64>,
|
||||
) -> bool {
|
||||
const DRAW: u32 = 0;
|
||||
const INDEXED: u32 = 1;
|
||||
const DISPATCH: u32 = 2;
|
||||
const MESH: u32 = 10;
|
||||
let len = u64::from(stride) * u64::from(max.max(1));
|
||||
let Some(args) = crate::shadow::find(arguments, len) else {
|
||||
return false;
|
||||
};
|
||||
let counter = match count {
|
||||
Some(at) => match crate::shadow::find(at, 4) {
|
||||
Some(s) => Some((s, at)),
|
||||
None => return false,
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH)
|
||||
.then(|| host_signature(kind, stride))
|
||||
.flatten()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
args.refresh(list, arguments, len);
|
||||
if let Some((s, at)) = &counter {
|
||||
s.refresh(list, *at, 4);
|
||||
}
|
||||
// Bounded first: the clamp binds a compute pipeline of its own.
|
||||
if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) {
|
||||
return false;
|
||||
}
|
||||
self.host_pipeline = 0;
|
||||
self.host_roots[1] = 0;
|
||||
let ran = match kind {
|
||||
DRAW | INDEXED => self.topology != RECTANGLES && self.prepare(list, kind == INDEXED),
|
||||
MESH => self.prepare_for(list, false, true),
|
||||
DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) {
|
||||
Some(p) if p.compute => {
|
||||
self.bind(list, p, true);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
};
|
||||
if !ran {
|
||||
crate::indirect::done(list, &args.buffer);
|
||||
return false;
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
list.note_op(|| {
|
||||
self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH)
|
||||
});
|
||||
// SAFETY: an open list with everything set; the buffers are host
|
||||
// copies the list keeps alive (refresh), the signature is cached.
|
||||
unsafe {
|
||||
list.list.ExecuteIndirect(
|
||||
&signature,
|
||||
max,
|
||||
&args.buffer,
|
||||
args.offset(arguments),
|
||||
counter.as_ref().map(|(s, _)| &s.buffer),
|
||||
counter.as_ref().map_or(0, |(s, at)| s.offset(*at)),
|
||||
)
|
||||
};
|
||||
crate::indirect::done(list, &args.buffer);
|
||||
if kind == DISPATCH {
|
||||
DISPATCHED.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The host command signature for one argument of `kind` with records
|
||||
/// `stride` bytes apart (no root arguments, so no root signature), made
|
||||
/// once.
|
||||
fn host_signature(kind: u32, stride: u32) -> Option<ID3D12CommandSignature> {
|
||||
static MADE: std::sync::Mutex<Vec<((u32, u32), ID3D12CommandSignature)>> =
|
||||
std::sync::Mutex::new(Vec::new());
|
||||
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((_, s)) = made.iter().find(|(k, _)| *k == (kind, stride)) {
|
||||
return Some(s.clone());
|
||||
}
|
||||
let argument = D3D12_INDIRECT_ARGUMENT_DESC {
|
||||
Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
|
||||
..Default::default()
|
||||
};
|
||||
let desc = D3D12_COMMAND_SIGNATURE_DESC {
|
||||
ByteStride: stride,
|
||||
NumArgumentDescs: 1,
|
||||
pArgumentDescs: &argument,
|
||||
NodeMask: 0,
|
||||
};
|
||||
let mut signature: Option<ID3D12CommandSignature> = None;
|
||||
// SAFETY: a description of one argument; no root arguments.
|
||||
let result = unsafe {
|
||||
crate::host::host()?.device.CreateCommandSignature(
|
||||
&desc,
|
||||
None::<&ID3D12RootSignature>,
|
||||
&mut signature,
|
||||
)
|
||||
};
|
||||
if let Err(e) = result {
|
||||
once!(error = %e, kind, stride, "host command signature refused");
|
||||
return None;
|
||||
}
|
||||
let signature = signature?;
|
||||
made.push(((kind, stride), signature.clone()));
|
||||
Some(signature)
|
||||
}
|
||||
|
||||
/// Gets what a shader reads or writes through a view ready: buffer data
|
||||
/// copied, textures moved to the state they need.
|
||||
fn readable(list: &HostList, u: &UsedResource, view: &View) {
|
||||
|
||||
+185
-31
@@ -67,6 +67,12 @@ unsafe impl Sync for Host {}
|
||||
static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
|
||||
[std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
|
||||
|
||||
/// After submissions: shader-written ranges compared and copied back into
|
||||
/// title memory (microseconds, bytes that differed), since the last
|
||||
/// frame-rate line.
|
||||
static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
|
||||
[std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
|
||||
|
||||
/// Of the preparing: title memory copies (microseconds, bytes) and texture
|
||||
/// refreshes (microseconds, bytes hashed), since the last frame-rate line.
|
||||
pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
|
||||
@@ -134,9 +140,26 @@ fn create() -> windows::core::Result<Host> {
|
||||
if debug {
|
||||
let mut layer: Option<ID3D12Debug> = None;
|
||||
match D3D12GetDebugInterface(&mut layer) {
|
||||
Ok(()) => layer.into_iter().for_each(|l| l.EnableDebugLayer()),
|
||||
Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
|
||||
Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
|
||||
}
|
||||
// GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
|
||||
// descriptor heap indices and the like become messages naming
|
||||
// the command instead of page faults. Without state tracking
|
||||
// (directly indexed textures are not transitioned).
|
||||
if std::env::var_os("VICTORY_D3D12_GBV").is_some()
|
||||
&& let Some(l) = &layer
|
||||
{
|
||||
if let Ok(d1) = l.cast::<ID3D12Debug1>() {
|
||||
d1.SetEnableGPUBasedValidation(true);
|
||||
}
|
||||
if let Ok(d2) = l.cast::<ID3D12Debug2>() {
|
||||
d2.SetGPUBasedValidationFlags(
|
||||
D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
|
||||
);
|
||||
}
|
||||
tracing::info!("GPU-based validation on");
|
||||
}
|
||||
}
|
||||
// Diagnostics: device-removed data (the command that faulted, the
|
||||
// faulting address), read when the device is removed.
|
||||
@@ -213,21 +236,35 @@ pub(crate) struct HostList {
|
||||
/// Upload memory for data the list's draws make (expanded vertices),
|
||||
/// reused after a reset.
|
||||
scratch: Mutex<Scratch>,
|
||||
/// Host texture states the list assumes, by title resource: at its
|
||||
/// start and at its end. Lists are recorded on many threads and run in
|
||||
/// submission order, so the transitions from a texture's real state are
|
||||
/// made at submission, in `prelude`.
|
||||
states: Mutex<std::collections::HashMap<usize, (u32, u32)>>,
|
||||
/// Host texture states the list assumes, by host copy: at its start and
|
||||
/// at its end. Lists are recorded on many threads and run in submission
|
||||
/// order, so the transitions from a texture's real state are made at
|
||||
/// submission, in `prelude`. Holding the copies keeps every texture the
|
||||
/// list names alive until it is reset, even if the title releases the
|
||||
/// resource first.
|
||||
states: Mutex<States>,
|
||||
/// The list that runs those transitions just before this one.
|
||||
prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList),
|
||||
/// The pipelines the list binds, for reports of slow submissions.
|
||||
pipelines: Mutex<std::collections::BTreeSet<String>>,
|
||||
/// The work its indirect executions may still do (`indirect`): a
|
||||
/// shader-writable word, zeroed when the list is submitted.
|
||||
budget: OnceLock<Option<(ID3D12Resource, usize)>>,
|
||||
/// The texts of the markers `note_op` set, in order (for device-removed
|
||||
/// data without marker texts).
|
||||
/// data without marker texts), with the host GPU range a copy reads.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
notes: Mutex<Vec<String>>,
|
||||
notes: Mutex<Vec<Note>>,
|
||||
}
|
||||
|
||||
/// A marker's text and the host range its command reads (diagnostics).
|
||||
#[cfg(feature = "diagnostics")]
|
||||
type Note = (String, Option<(u64, u64)>);
|
||||
|
||||
type States = std::collections::HashMap<
|
||||
usize,
|
||||
(u32, u32, std::sync::Arc<crate::resource::HostTexture>),
|
||||
>;
|
||||
|
||||
/// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
|
||||
/// builds).
|
||||
pub(crate) fn dred_on() -> bool {
|
||||
@@ -289,6 +326,10 @@ struct Deferred {
|
||||
/// Destination, source, bytes.
|
||||
copies: Vec<Step>,
|
||||
uploads: Vec<ID3D12Resource>,
|
||||
/// Host objects the list's commands name (pipelines, root signatures,
|
||||
/// descriptor heaps): the title may release its objects before it
|
||||
/// submits the list.
|
||||
kept: Vec<windows::core::IUnknown>,
|
||||
/// Buffer ranges refreshed since the last title copy (host copy,
|
||||
/// address, bytes): refreshing them again would find the same bytes.
|
||||
refreshed: std::collections::HashSet<(usize, usize, usize)>,
|
||||
@@ -297,6 +338,8 @@ struct Deferred {
|
||||
/// Bottom-of-pipe writes, done once the list has run: address, what,
|
||||
/// bytes.
|
||||
writes: Vec<(usize, crate::queue::Written, usize)>,
|
||||
/// Whether a step zeroes the indirect-work budget.
|
||||
budget_zeroed: bool,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
@@ -366,6 +409,7 @@ impl Host {
|
||||
states: Mutex::default(),
|
||||
prelude: (prelude_allocator, prelude),
|
||||
pipelines: Mutex::default(),
|
||||
budget: OnceLock::new(),
|
||||
#[cfg(feature = "diagnostics")]
|
||||
notes: Mutex::default(),
|
||||
})
|
||||
@@ -424,16 +468,32 @@ impl Host {
|
||||
last_notes(runs)
|
||||
));
|
||||
}
|
||||
// What shaders wrote goes back before the bottom-of-pipe writes,
|
||||
// which tell the title the GPU is done; each range once per
|
||||
// submission, however many dispatches declared it (the world's
|
||||
// passes declare the same big ranges dozens of times).
|
||||
let copying = std::time::Instant::now();
|
||||
// One list's lock at a time: a submission may name a list twice.
|
||||
let mut back: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
|
||||
for list in runs {
|
||||
let deferred = list.deferred();
|
||||
// Before the bottom-of-pipe writes, which tell the title the
|
||||
// GPU is done.
|
||||
for step in &deferred.copies {
|
||||
if let Step::GpuWrite(shadow, address, len) = step {
|
||||
shadow.copy_back(*address, *len);
|
||||
for step in &list.deferred().copies {
|
||||
if let Step::GpuWrite(shadow, address, len) = step
|
||||
&& !back
|
||||
.iter()
|
||||
.any(|(s, a, l)| std::sync::Arc::ptr_eq(s, shadow) && (*a, *l) == (*address, *len))
|
||||
{
|
||||
back.push((shadow.clone(), *address, *len));
|
||||
}
|
||||
}
|
||||
for &(at, what, bytes) in &deferred.writes {
|
||||
}
|
||||
for (shadow, address, len) in &back {
|
||||
let (address, len) = (*address, *len);
|
||||
let written = shadow.copy_back(address, len);
|
||||
COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
|
||||
}
|
||||
COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
|
||||
for list in runs {
|
||||
for &(at, what, bytes) in &list.deferred().writes {
|
||||
what.write(at as *mut u8, bytes);
|
||||
}
|
||||
}
|
||||
@@ -450,6 +510,7 @@ impl Host {
|
||||
return String::new();
|
||||
};
|
||||
let mut text = String::new();
|
||||
let mut fault_va = None;
|
||||
// SAFETY: the outputs are the runtime's, valid while the device
|
||||
// lives; nodes are walked as linked, histories have their counts.
|
||||
unsafe {
|
||||
@@ -457,6 +518,7 @@ impl Host {
|
||||
&& fault.PageFaultVA != 0
|
||||
{
|
||||
let va = fault.PageFaultVA;
|
||||
fault_va = Some(va);
|
||||
text.push_str(&format!("; page fault at {va:#x}"));
|
||||
for (what, head) in [
|
||||
("inside", fault.pHeadExistingAllocationNode),
|
||||
@@ -480,12 +542,28 @@ impl Host {
|
||||
}
|
||||
}
|
||||
text.push_str(&crate::shadow::near(va));
|
||||
text.push_str(&crate::descriptor::host::near_heaps(va));
|
||||
}
|
||||
// The plain output: the extended one (with marker texts) came
|
||||
// back without stopped lists on this host.
|
||||
let Ok(crumbs) = dred.GetAutoBreadcrumbsOutput() else {
|
||||
return text;
|
||||
let crumbs = match dred.GetAutoBreadcrumbsOutput() {
|
||||
Ok(crumbs) => crumbs,
|
||||
Err(e) => {
|
||||
text.push_str(&format!("; no breadcrumbs ({e})"));
|
||||
return text;
|
||||
}
|
||||
};
|
||||
// Every list's progress (done/count), in the runtime's order.
|
||||
let mut progress = Vec::new();
|
||||
let mut node = crumbs.pHeadAutoBreadcrumbNode;
|
||||
while let Some(p) = node.as_ref() {
|
||||
let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
|
||||
let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
|
||||
let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
|
||||
progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
|
||||
node = p.pNext;
|
||||
}
|
||||
text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
|
||||
let mut plain = crumbs.pHeadAutoBreadcrumbNode;
|
||||
while let Some(p) = plain.as_ref() {
|
||||
let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
|
||||
@@ -507,11 +585,16 @@ impl Host {
|
||||
.enumerate()
|
||||
.filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
|
||||
.zip(notes.iter())
|
||||
.map(|((at, _), note)| (at as u32, note.clone()))
|
||||
.map(|((at, _), (note, range))| {
|
||||
let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
|
||||
(at as u32, format!("{note}{}", place.unwrap_or_default()))
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
let markers: Vec<(u32, String)> = Vec::new();
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
let _ = fault_va;
|
||||
if done > 0 {
|
||||
text.push_str(&in_flight(history, &markers, done as usize));
|
||||
} else if let Some(r) = run {
|
||||
@@ -636,11 +719,12 @@ impl HostList {
|
||||
wanted: u32,
|
||||
) -> Option<(&'static ID3D12Resource, u32)> {
|
||||
let texture = crate::resource::host_resource(resource)?;
|
||||
let copy = crate::resource::host_copy(resource)?;
|
||||
let wanted = legal_state(texture, wanted);
|
||||
let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match states.entry(resource as usize) {
|
||||
match states.entry(std::sync::Arc::as_ptr(©) as usize) {
|
||||
std::collections::hash_map::Entry::Vacant(v) => {
|
||||
v.insert((wanted, wanted));
|
||||
v.insert((wanted, wanted, copy));
|
||||
None
|
||||
}
|
||||
std::collections::hash_map::Entry::Occupied(mut o) => {
|
||||
@@ -656,16 +740,14 @@ impl HostList {
|
||||
fn prelude(&self) -> Option<ID3D12CommandList> {
|
||||
let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let barriers: Vec<D3D12_RESOURCE_BARRIER> = states
|
||||
.iter()
|
||||
.filter_map(|(&resource, &(first, last))| {
|
||||
let resource = resource as crate::object::This;
|
||||
let texture = crate::resource::host_resource(resource)?;
|
||||
let real = crate::resource::swap_host_state(resource, last);
|
||||
(real != first).then(|| {
|
||||
.values()
|
||||
.filter_map(|(first, last, copy)| {
|
||||
let real = copy.state.swap(*last, Ordering::Relaxed);
|
||||
(real != *first).then(|| {
|
||||
transition(
|
||||
texture,
|
||||
©.texture,
|
||||
D3D12_RESOURCE_STATES(real as i32),
|
||||
D3D12_RESOURCE_STATES(first as i32),
|
||||
D3D12_RESOURCE_STATES(*first as i32),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -695,6 +777,18 @@ impl HostList {
|
||||
/// texts in order and names the commands a fault stopped among.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
|
||||
self.note(what, None);
|
||||
}
|
||||
|
||||
/// As [`HostList::note_op`], for a copy that reads the host GPU range
|
||||
/// `(address, bytes)`: the report places the faulting address in it.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
|
||||
self.note(what, Some(range));
|
||||
}
|
||||
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
|
||||
if dred_on() {
|
||||
let what = what();
|
||||
let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
|
||||
@@ -703,7 +797,10 @@ impl HostList {
|
||||
unsafe {
|
||||
self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
|
||||
};
|
||||
self.notes.lock().unwrap_or_else(|e| e.into_inner()).push(what);
|
||||
self.notes
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.push((what, range));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -778,6 +875,7 @@ impl HostList {
|
||||
/// shortcut: one buffer per copy; pool them once uploads are frequent.
|
||||
pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
|
||||
let (buffer, data) = host.upload_buffer(size)?;
|
||||
name(&buffer, || format!("list upload {size:#x}"));
|
||||
self.deferred().uploads.push(buffer.clone());
|
||||
Some((buffer, data))
|
||||
}
|
||||
@@ -813,6 +911,36 @@ impl HostList {
|
||||
Some((gpu + at, (data + at as usize) as *mut u8))
|
||||
}
|
||||
|
||||
/// The host address of the list's indirect-work budget, zeroed at each
|
||||
/// submission of the list from the first use after a reset on.
|
||||
pub(crate) fn budget(&self) -> Option<u64> {
|
||||
let (buffer, data) = self
|
||||
.budget
|
||||
.get_or_init(|| {
|
||||
let (b, d) = host()?.shared_buffer(256)?;
|
||||
Some((b, d as usize))
|
||||
})
|
||||
.as_ref()?;
|
||||
let mut deferred = self.deferred();
|
||||
if !deferred.budget_zeroed {
|
||||
deferred.budget_zeroed = true;
|
||||
let at = *data;
|
||||
// SAFETY: the list's own mapped word, written before it runs.
|
||||
deferred
|
||||
.copies
|
||||
.push(Step::Host(Box::new(move || unsafe { (at as *mut u32).write_volatile(0) })));
|
||||
}
|
||||
// SAFETY: a live buffer.
|
||||
Some(unsafe { buffer.GetGPUVirtualAddress() })
|
||||
}
|
||||
|
||||
/// Keeps `object` alive until the list is reset.
|
||||
pub(crate) fn keep(&self, object: &impl Interface) {
|
||||
if let Ok(object) = object.cast::<windows::core::IUnknown>() {
|
||||
self.deferred().kept.push(object);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this is the first time since the reset that the list asks
|
||||
/// about `key` (a texture to bring up to date).
|
||||
pub(crate) fn first_use(&self, key: usize) -> bool {
|
||||
@@ -976,6 +1104,12 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b
|
||||
});
|
||||
}
|
||||
|
||||
/// Reads title memory at `src` into `dst`; false if a page of it is not
|
||||
/// readable.
|
||||
pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
|
||||
read(src, dst.as_mut_ptr(), dst.len())
|
||||
}
|
||||
|
||||
/// Copies `len` bytes from `src` to `dst` unless a source page is not
|
||||
/// readable.
|
||||
fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
|
||||
@@ -1141,12 +1275,18 @@ impl Meter {
|
||||
let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
|
||||
PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
|
||||
});
|
||||
let [back_ms, back_mb] = [0, 1].map(|i| {
|
||||
COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
|
||||
});
|
||||
let dropped = crate::draw::take_dropped() as f64 / frames;
|
||||
let indirect = crate::list::take_indirect() as f64 / frames;
|
||||
if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
|
||||
self.logged = std::time::Instant::now();
|
||||
tracing::info!(
|
||||
"{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
|
||||
{copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
|
||||
GPU), {draws:.0} draws/frame"
|
||||
GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
|
||||
dropped {dropped:.0} without a host pipeline and {indirect:.0} indirect"
|
||||
);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::log(frames);
|
||||
@@ -1429,7 +1569,7 @@ fn last_notes(runs: &[&HostList]) -> String {
|
||||
let mut text = String::new();
|
||||
for (i, r) in runs.iter().enumerate() {
|
||||
let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for n in notes.iter().rev().take(6).rev() {
|
||||
for (n, _) in notes.iter().rev().take(6).rev() {
|
||||
text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
|
||||
}
|
||||
}
|
||||
@@ -1442,6 +1582,20 @@ fn last_notes(runs: &[&HostList]) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the faulting address `va` lies against a range `(start, bytes)` a
|
||||
/// command reads (diagnostics).
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
|
||||
let end = start + bytes;
|
||||
if va < start {
|
||||
format!(" (fault {:#x} below its source)", start - va)
|
||||
} else if va < end {
|
||||
format!(" (fault at source +{:#x})", va - start)
|
||||
} else {
|
||||
format!(" (fault {:#x} past its source's end)", va - end)
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands that may have been running where a list stopped at
|
||||
/// command `done`: those between the barriers around it (work between
|
||||
/// barriers overlaps on the GPU), by kind, and what the markers just
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
//! Indirect execution's arguments, bounded before the GPU reads them. The
|
||||
//! title's own compute passes write most of them; a pass we drop or
|
||||
//! translate wrongly leaves whatever the memory held, and a draw of four
|
||||
//! billion vertices or a dispatch past the host's limits runs until the
|
||||
//! host resets the display driver. So every record is clamped on the GPU,
|
||||
//! just before its execution, by a compute shader of ours (HLSL compiled by
|
||||
//! the system's compiler; a 5.1 shader with its root signature inside).
|
||||
//!
|
||||
//! Each list also has a budget (2^28 vertex instances or threads, mesh
|
||||
//! groups counted as 128): records past it run empty, so a list of
|
||||
//! thousands of garbage records cannot run for seconds either.
|
||||
//!
|
||||
//! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
|
||||
//! groups per dimension, one-dimensional mesh dispatches, the budget) cut
|
||||
//! legitimate work beyond them; raise them if the title needs more.
|
||||
|
||||
use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
|
||||
use windows::Win32::Graphics::Direct3D::ID3DBlob;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::core::s;
|
||||
|
||||
use crate::host::{HostList, host, transition};
|
||||
|
||||
const SOURCE: &str = r#"
|
||||
#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)"
|
||||
cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; };
|
||||
RWByteAddressBuffer args : register(u0);
|
||||
// The list's work so far (vertex instances, threads): past the budget,
|
||||
// records run empty.
|
||||
RWByteAddressBuffer budget : register(u1);
|
||||
static const uint BUDGET = 1u << 28;
|
||||
[RootSignature(RS)]
|
||||
[numthreads(64, 1, 1)]
|
||||
void main(uint3 id : SV_DispatchThreadID) {
|
||||
if (id.x >= records) return;
|
||||
uint at = id.x * stride;
|
||||
uint cost;
|
||||
if (kind <= 1) {
|
||||
// Draws: vertex or index count, then instances.
|
||||
uint count = min(args.Load(at), 1u << 24);
|
||||
uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u));
|
||||
cost = count * instances;
|
||||
args.Store2(at, uint2(count, instances));
|
||||
} else if (kind == 2) {
|
||||
uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535));
|
||||
cost = min(g.x * g.y * g.z, 1u << 20) * 64;
|
||||
args.Store3(at, g);
|
||||
} else {
|
||||
// Mesh dispatches: the console's are one-dimensional.
|
||||
uint3 g = args.Load3(at);
|
||||
g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u));
|
||||
cost = g.x * g.y * g.z * 128;
|
||||
args.Store3(at, g);
|
||||
}
|
||||
uint before;
|
||||
budget.InterlockedAdd(0, cost, before);
|
||||
if (before >= BUDGET || before + cost > BUDGET) {
|
||||
// Draws keep their layout with no vertices; groups become zero.
|
||||
args.Store(at, 0);
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
struct Clamp {
|
||||
root: ID3D12RootSignature,
|
||||
pso: ID3D12PipelineState,
|
||||
}
|
||||
|
||||
// SAFETY: D3D12 objects are free-threaded.
|
||||
unsafe impl Send for Clamp {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Sync for Clamp {}
|
||||
|
||||
fn clamp() -> Option<&'static Clamp> {
|
||||
static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
|
||||
CLAMP
|
||||
.get_or_init(|| match make() {
|
||||
Ok(c) => Some(c),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "no argument clamp: indirect execution dropped");
|
||||
None
|
||||
}
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
fn make() -> windows::core::Result<Clamp> {
|
||||
let device = &host().ok_or_else(windows::core::Error::empty)?.device;
|
||||
let mut code: Option<ID3DBlob> = None;
|
||||
let mut errors: Option<ID3DBlob> = None;
|
||||
// SAFETY: the source and names live through the call; out pointers ours.
|
||||
let compiled = unsafe {
|
||||
D3DCompile(
|
||||
SOURCE.as_ptr().cast(),
|
||||
SOURCE.len(),
|
||||
s!("clamp"),
|
||||
None,
|
||||
None,
|
||||
s!("main"),
|
||||
s!("cs_5_1"),
|
||||
0,
|
||||
0,
|
||||
&mut code,
|
||||
Some(&mut errors),
|
||||
)
|
||||
};
|
||||
if let Err(e) = compiled {
|
||||
if let Some(errors) = errors {
|
||||
// SAFETY: the blob's own bytes.
|
||||
let text = unsafe {
|
||||
std::slice::from_raw_parts(errors.GetBufferPointer().cast::<u8>(), errors.GetBufferSize())
|
||||
};
|
||||
tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text));
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
let code = code.ok_or_else(windows::core::Error::empty)?;
|
||||
// SAFETY: the blob's own bytes; the root signature is inside the shader.
|
||||
unsafe {
|
||||
let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
|
||||
let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
|
||||
let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
|
||||
pRootSignature: std::mem::transmute_copy(&root),
|
||||
CS: D3D12_SHADER_BYTECODE {
|
||||
pShaderBytecode: bytes.as_ptr().cast(),
|
||||
BytecodeLength: bytes.len(),
|
||||
},
|
||||
..Default::default()
|
||||
})?;
|
||||
Ok(Clamp { root, pso })
|
||||
}
|
||||
}
|
||||
|
||||
/// Records, in `list`, the clamp of `records` records of `kind` (PC
|
||||
/// argument numbering) `stride` bytes apart at host address `gpu` in
|
||||
/// `buffer`, and leaves the buffer ready to be read as arguments. Replaces
|
||||
/// the list's compute root signature and pipeline (callers bind theirs
|
||||
/// after). False if the clamp is not available.
|
||||
pub(crate) fn bound(
|
||||
list: &HostList,
|
||||
buffer: &ID3D12Resource,
|
||||
gpu: u64,
|
||||
(kind, stride, records): (u32, u32, u32),
|
||||
) -> bool {
|
||||
let (Some(c), Some(budget)) = (clamp(), list.budget()) else {
|
||||
return false;
|
||||
};
|
||||
if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) {
|
||||
return false;
|
||||
}
|
||||
let l = &list.list;
|
||||
let constants = [kind, stride, records, 0];
|
||||
// SAFETY: an open list; our root signature, pipeline and a live buffer
|
||||
// the caller's list holds.
|
||||
unsafe {
|
||||
// Earlier shader writes (the title's argument passes) first.
|
||||
l.ResourceBarrier(&[uav_barrier()]);
|
||||
l.SetComputeRootSignature(&c.root);
|
||||
l.SetPipelineState(&c.pso);
|
||||
l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0);
|
||||
l.SetComputeRootUnorderedAccessView(1, gpu);
|
||||
l.SetComputeRootUnorderedAccessView(2, budget);
|
||||
l.Dispatch(records.div_ceil(64), 1, 1);
|
||||
l.ResourceBarrier(&[
|
||||
uav_barrier(),
|
||||
transition(
|
||||
buffer,
|
||||
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
|
||||
D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
|
||||
),
|
||||
]);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// After the execution: the buffer back to unordered access, where the
|
||||
/// title's passes keep using it.
|
||||
pub(crate) fn done(list: &HostList, buffer: &ID3D12Resource) {
|
||||
// SAFETY: an open list and a live buffer.
|
||||
unsafe {
|
||||
list.list.ResourceBarrier(&[transition(
|
||||
buffer,
|
||||
D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
|
||||
D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
|
||||
)])
|
||||
};
|
||||
}
|
||||
|
||||
fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
|
||||
D3D12_RESOURCE_BARRIER {
|
||||
Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
|
||||
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
|
||||
Anonymous: D3D12_RESOURCE_BARRIER_0 {
|
||||
UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// The clamp compiles with the system's compiler and the host takes it.
|
||||
#[test]
|
||||
fn argument_clamp_builds() {
|
||||
if super::host().is_none() {
|
||||
return; // no host GPU here
|
||||
}
|
||||
assert!(super::clamp().is_some());
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,8 @@ pub mod fence;
|
||||
pub mod frame;
|
||||
#[cfg(windows)]
|
||||
mod host;
|
||||
#[cfg(windows)]
|
||||
mod indirect;
|
||||
pub mod list;
|
||||
pub mod object;
|
||||
pub mod pipeline;
|
||||
|
||||
@@ -510,6 +510,8 @@ extern "system" fn copy_texture_region(
|
||||
};
|
||||
let mut from = src;
|
||||
let _upload; // keeps the source alive while this call records it
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let mut read = None;
|
||||
if src.kind == FOOTPRINT {
|
||||
let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else {
|
||||
return;
|
||||
@@ -523,6 +525,11 @@ extern "system" fn copy_texture_region(
|
||||
list.defer_copy(staging, data, bytes as usize);
|
||||
from.resource = buffer.as_raw().cast_const().cast();
|
||||
from.footprint.offset = 0;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
// SAFETY: a live buffer.
|
||||
read = Some((unsafe { buffer.GetGPUVirtualAddress() }, bytes));
|
||||
}
|
||||
_upload = buffer;
|
||||
} else {
|
||||
let Some(texture) = crate::resource::host_resource(src.resource) else {
|
||||
@@ -537,21 +544,27 @@ extern "system" fn copy_texture_region(
|
||||
to_location.resource = to.as_raw().cast_const().cast();
|
||||
let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
|
||||
#[cfg(feature = "diagnostics")]
|
||||
list.note_op(|| {
|
||||
// SAFETY: a live texture; the box is the title's or null.
|
||||
let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) };
|
||||
format!(
|
||||
"copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}",
|
||||
dst.resource,
|
||||
d.Width,
|
||||
d.Height,
|
||||
d.Format.0,
|
||||
dst.kind,
|
||||
src.resource,
|
||||
src.kind,
|
||||
(src.kind == FOOTPRINT).then_some(src.footprint)
|
||||
)
|
||||
});
|
||||
{
|
||||
let text = || {
|
||||
// SAFETY: a live texture; the box is the title's or null.
|
||||
let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) };
|
||||
format!(
|
||||
"copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}",
|
||||
dst.resource,
|
||||
d.Width,
|
||||
d.Height,
|
||||
d.Format.0,
|
||||
dst.kind,
|
||||
src.resource,
|
||||
src.kind,
|
||||
(src.kind == FOOTPRINT).then_some(src.footprint)
|
||||
)
|
||||
};
|
||||
match read {
|
||||
Some(range) => list.note_read(text, range),
|
||||
None => list.note_op(text),
|
||||
}
|
||||
}
|
||||
const _: () =
|
||||
assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>());
|
||||
// SAFETY: an open list; both locations in the host's layout, naming
|
||||
@@ -1110,9 +1123,77 @@ fn count_draw() {
|
||||
/// Draws of the kinds the host does not run yet (indirect, mesh), and
|
||||
/// dispatches, counted per frame for the log.
|
||||
/// shortcut: dropped until their shaders translate (decision 0007).
|
||||
#[cfg(not(windows))]
|
||||
extern "system" fn draw(_: This) {
|
||||
count_draw();
|
||||
}
|
||||
|
||||
/// `ExecuteIndirect(signature, max count, arguments, offset, count buffer,
|
||||
/// offset)`. Grand Theft Auto VI's signatures (2026-11-23) hold one
|
||||
/// argument each: draw (stride 16), indexed draw (20), dispatch (12), mesh
|
||||
/// dispatch (12), and a console type 105 (stride 12, fields 0, 60000, 0,
|
||||
/// over its 174 MB buffer) whose meaning is unknown. Those of PC types run
|
||||
/// through the host's indirect execution (`State::execute_indirect`).
|
||||
/// shortcut: type 105 and signatures that change root arguments are
|
||||
/// dropped (logged once per signature); decode 105 when its draws are
|
||||
/// missed.
|
||||
extern "system" fn execute_indirect(
|
||||
this: This,
|
||||
signature: This,
|
||||
max: u32,
|
||||
arguments: This,
|
||||
offset: u64,
|
||||
count: This,
|
||||
count_offset: u64,
|
||||
) {
|
||||
count_draw();
|
||||
let Some((stride, args)) = crate::signature::layout(signature) else {
|
||||
return;
|
||||
};
|
||||
let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset);
|
||||
let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset);
|
||||
let mut ran = false;
|
||||
// shortcut: off unless `VICTORY_INDIRECT` is set (diagnostics builds):
|
||||
// with it the world presented no frame for 30 s and the title's own
|
||||
// GPU watchdog ended it (2026-11-24, cause not found); without it the
|
||||
// world runs, with most geometry missing.
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
let on = *ON.get_or_init(|| {
|
||||
cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_INDIRECT").is_some()
|
||||
});
|
||||
#[cfg(windows)]
|
||||
if on
|
||||
&& let ([[kind, ..]], Some(address)) = (args, address)
|
||||
&& (count.is_null() || counter.is_some())
|
||||
{
|
||||
with_state(this, |list, s| {
|
||||
ran = s.execute_indirect(list, (*kind, stride, max), address, counter);
|
||||
});
|
||||
}
|
||||
if ran {
|
||||
return;
|
||||
}
|
||||
INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
static SEEN: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
|
||||
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !seen.contains(&(signature as usize)) {
|
||||
seen.push(signature as usize);
|
||||
tracing::info!(
|
||||
stride,
|
||||
?args,
|
||||
max,
|
||||
address = ?address.map(|a| format!("{a:#x}")),
|
||||
counted = !count.is_null(),
|
||||
"indirect execution dropped (first time for this signature)"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Indirect executions dropped since the last call.
|
||||
pub(crate) fn take_indirect() -> u64 {
|
||||
INDIRECT.swap(0, std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
static INDIRECT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
fn count_dispatch() {
|
||||
DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
@@ -1231,7 +1312,7 @@ const METHODS: [(usize, *const ()); 52] = [
|
||||
(50, state::targets as *const ()), // 0x190
|
||||
(51, clear_dsv as *const ()), // 0x198
|
||||
(52, clear_rtv as *const ()), // 0x1a0
|
||||
(59, draw as *const ()), // 0x1d8 indirect
|
||||
(59, execute_indirect as *const ()), // 0x1d8 indirect
|
||||
(60, copy_memory as *const ()), // 0x1e0
|
||||
(68, ignored_state as *const ()), // 0x220 depth bounds
|
||||
(69, write32 as *const ()), // 0x228
|
||||
|
||||
@@ -406,6 +406,7 @@ impl HostPipeline {
|
||||
}
|
||||
};
|
||||
tracing::info!(?shaders, "host pipeline");
|
||||
crate::host::name(&pso, || format!("{shaders:?}"));
|
||||
return Some(HostPipeline {
|
||||
compute: true,
|
||||
mesh: false,
|
||||
@@ -430,6 +431,7 @@ impl HostPipeline {
|
||||
}
|
||||
};
|
||||
tracing::info!(?shaders, "host mesh pipeline");
|
||||
crate::host::name(&pso, || format!("{shaders:?}"));
|
||||
return Some(HostPipeline {
|
||||
compute: false,
|
||||
mesh: true,
|
||||
@@ -478,6 +480,7 @@ impl HostPipeline {
|
||||
}
|
||||
};
|
||||
tracing::info!(?shaders, "host pipeline");
|
||||
crate::host::name(&pso, || format!("{shaders:?}"));
|
||||
tracing::debug!(
|
||||
?shaders,
|
||||
depth = ?g.depth,
|
||||
|
||||
@@ -748,11 +748,19 @@ struct Resource {
|
||||
/// Textures also live on the host GPU (decision 0007); buffers do not
|
||||
/// yet.
|
||||
#[cfg(windows)]
|
||||
host: Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource>,
|
||||
/// The state the host texture is in. The title's barriers name console
|
||||
/// states (looser than the host's), so we transition from this one.
|
||||
#[cfg(windows)]
|
||||
host_state: std::sync::atomic::AtomicU32,
|
||||
host: Option<std::sync::Arc<HostTexture>>,
|
||||
}
|
||||
|
||||
/// A title texture's host copy and the state it is in. The title's barriers
|
||||
/// name console states (looser than the host's), so we transition from this
|
||||
/// one. Lists that use the texture hold it until they are reset: the title
|
||||
/// may release a resource whose commands it recorded but not yet submitted
|
||||
/// (console memory outlives the object; a host texture must outlive the
|
||||
/// lists that name it).
|
||||
#[cfg(windows)]
|
||||
pub(crate) struct HostTexture {
|
||||
pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource,
|
||||
pub(crate) state: std::sync::atomic::AtomicU32,
|
||||
}
|
||||
|
||||
/// Moves the host texture to `wanted` (a host texture state); the host
|
||||
@@ -760,21 +768,11 @@ struct Resource {
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> {
|
||||
use windows::core::Interface;
|
||||
let r = resource(this);
|
||||
let host = r.host.as_ref()?;
|
||||
let before = r
|
||||
.host_state
|
||||
let host = resource(this).host.as_ref()?;
|
||||
let before = host
|
||||
.state
|
||||
.swap(wanted, std::sync::atomic::Ordering::Relaxed);
|
||||
(before != wanted).then(|| (host.as_raw(), before))
|
||||
}
|
||||
|
||||
/// Sets the state the host texture is in after a submission; returns the
|
||||
/// one it was in.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn swap_host_state(this: This, state: u32) -> u32 {
|
||||
resource(this)
|
||||
.host_state
|
||||
.swap(state, std::sync::atomic::Ordering::Relaxed)
|
||||
(before != wanted).then(|| (host.texture.as_raw(), before))
|
||||
}
|
||||
|
||||
/// The host GPU's copy of a title resource, if it has one.
|
||||
@@ -785,7 +783,16 @@ pub(crate) fn host_resource<'a>(
|
||||
if this.is_null() {
|
||||
return None;
|
||||
}
|
||||
resource(this).host.as_ref()
|
||||
resource(this).host.as_deref().map(|h| &h.texture)
|
||||
}
|
||||
|
||||
/// A title texture's host copy, shared, for a list to hold.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn host_copy(this: This) -> Option<std::sync::Arc<HostTexture>> {
|
||||
if this.is_null() {
|
||||
return None;
|
||||
}
|
||||
resource(this).host.clone()
|
||||
}
|
||||
|
||||
/// A host texture like the title's: same description, in GPU memory,
|
||||
@@ -929,12 +936,13 @@ fn hand_out_resource(
|
||||
heap_flags,
|
||||
backing,
|
||||
#[cfg(windows)]
|
||||
host_state: host
|
||||
.as_ref()
|
||||
.map_or(0, |t| crate::host::legal_state(t, crate::host::texture_state(state)))
|
||||
.into(),
|
||||
#[cfg(windows)]
|
||||
host,
|
||||
host: host.map(|texture| {
|
||||
let state = crate::host::legal_state(&texture, crate::host::texture_state(state));
|
||||
std::sync::Arc::new(HostTexture {
|
||||
texture,
|
||||
state: state.into(),
|
||||
})
|
||||
}),
|
||||
});
|
||||
#[cfg(windows)]
|
||||
if desc.dimension == BUFFER {
|
||||
@@ -947,6 +955,24 @@ fn hand_out_resource(
|
||||
#[cfg(windows)]
|
||||
impl Drop for Resource {
|
||||
fn drop(&mut self) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if self
|
||||
.host
|
||||
.as_ref()
|
||||
.is_some_and(|h| std::sync::Arc::strong_count(h) > 1)
|
||||
{
|
||||
// Before lists held their textures, this freed a texture that
|
||||
// lists not yet run still named (a GPU page fault).
|
||||
static OUTLIVED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let n = OUTLIVED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
|
||||
if n.is_power_of_two() {
|
||||
tracing::info!(
|
||||
n,
|
||||
desc = ?self.desc,
|
||||
"a title texture was released while a list not yet reset names its host copy"
|
||||
);
|
||||
}
|
||||
}
|
||||
crate::texture::forget(std::ptr::from_ref::<Resource>(self) as usize);
|
||||
crate::descriptor::forget(std::ptr::from_ref::<Resource>(self) as usize);
|
||||
if self.desc.dimension == BUFFER {
|
||||
@@ -1705,6 +1731,8 @@ mod tests {
|
||||
let host_image = host_resource(image).unwrap();
|
||||
let back = host.new_list().unwrap();
|
||||
let (_, before) = host_transition(image, 0x800).unwrap();
|
||||
// The upload list holds the texture until it is reset.
|
||||
assert!(std::sync::Arc::strong_count(&host_copy(image).unwrap()) > 2);
|
||||
use windows::core::Interface;
|
||||
let out_to = Location {
|
||||
resource: readback.as_raw().cast_const().cast(),
|
||||
|
||||
@@ -113,14 +113,30 @@ impl Shadow {
|
||||
/// back into title memory (unmapped pages left alone). Pages wholly
|
||||
/// written are current in this copy, so our own write is not taken for
|
||||
/// the title's.
|
||||
pub(crate) fn copy_back(&self, address: usize, len: usize) {
|
||||
/// Returns the bytes written.
|
||||
pub(crate) fn copy_back(&self, address: usize, len: usize) -> usize {
|
||||
let mut written = 0;
|
||||
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
|
||||
let (from, to) = (address.max(start), (address + len).min(end));
|
||||
if from < to {
|
||||
// SAFETY: inside the mapping.
|
||||
let at = unsafe { self.data.add(from - start) };
|
||||
crate::watch::writing(from, to - from);
|
||||
crate::host::write_mapped(from as *mut u8, at, to - from);
|
||||
// Only the pieces that differ: shaders rewrite part of what they
|
||||
// may write, and writing title memory through the kernel (and
|
||||
// opening guarded blocks) was the world's biggest cost (~1 s per
|
||||
// frame for 450 MB).
|
||||
const PIECE: usize = 64 << 10;
|
||||
let mut title = vec![0u8; PIECE];
|
||||
let mut at = from;
|
||||
while at < to {
|
||||
let n = (PIECE - at % PIECE).min(to - at);
|
||||
// SAFETY: inside the mapping.
|
||||
let host = unsafe { std::slice::from_raw_parts(self.data.add(at - start), n) };
|
||||
if !crate::host::read_into(at as *const u8, &mut title[..n]) || title[..n] != *host {
|
||||
crate::watch::writing(at, n);
|
||||
crate::host::write_mapped(at as *mut u8, host.as_ptr(), n);
|
||||
written += n;
|
||||
}
|
||||
at += n;
|
||||
}
|
||||
let (first, last) = (from.div_ceil(PAGE), to / PAGE);
|
||||
if first < last
|
||||
&& self.watched.load(Ordering::Relaxed) != NOT_WATCHED
|
||||
@@ -131,10 +147,10 @@ impl Shadow {
|
||||
copied[first - base..last - base].fill(now);
|
||||
}
|
||||
}
|
||||
// Every submitted step that declared the range is done with it.
|
||||
let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(i) = pending.iter().position(|&r| r == (address, address + len)) {
|
||||
pending.swap_remove(i);
|
||||
}
|
||||
pending.retain(|&r| r != (address, address + len));
|
||||
written
|
||||
}
|
||||
|
||||
/// At submission: copies what changed of `[address, address + len)`
|
||||
@@ -155,20 +171,28 @@ impl Shadow {
|
||||
.filter(|&(a, e)| a < to && e > from)
|
||||
.collect();
|
||||
if !busy.is_empty() {
|
||||
// Rare: around ranges shaders are writing, everything is copied.
|
||||
// Around ranges shaders are writing: the gaps, each as below
|
||||
// (in the world most submissions have such ranges; copying the
|
||||
// gaps whole cost ~1 s per frame).
|
||||
busy.sort_unstable();
|
||||
let (mut at, mut bytes) = (from, 0);
|
||||
for (a, e) in busy {
|
||||
if a > at {
|
||||
bytes += self.copy(at, a);
|
||||
bytes += self.update_free(at, a);
|
||||
}
|
||||
at = at.max(e);
|
||||
}
|
||||
if at < to {
|
||||
bytes += self.copy(at, to);
|
||||
bytes += self.update_free(at, to);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
self.update_free(from, to)
|
||||
}
|
||||
|
||||
/// [`Shadow::update`] of `[from, to)` (inside the buffer) where no
|
||||
/// shader writes.
|
||||
fn update_free(&self, from: usize, to: usize) -> usize {
|
||||
if self.watched.load(Ordering::Relaxed) != NOT_WATCHED {
|
||||
if let Some((now, written)) = crate::watch::writes(from, to, true) {
|
||||
self.watched.store(1, Ordering::Relaxed);
|
||||
@@ -206,14 +230,20 @@ impl Shadow {
|
||||
};
|
||||
let at = &mut copied[page - base];
|
||||
if *at == 0 || write > *at {
|
||||
*at = now;
|
||||
// A page only partly in the range is copied in part: it
|
||||
// stays stale for the rest.
|
||||
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
|
||||
if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to {
|
||||
*at = now;
|
||||
}
|
||||
run.get_or_insert(page);
|
||||
} else if let Some(first) = run.take() {
|
||||
bytes += self.copy(first * PAGE, page * PAGE);
|
||||
bytes += self.copy((first * PAGE).max(from), (page * PAGE).min(to));
|
||||
}
|
||||
}
|
||||
// Cut to the range: next to it shaders may be writing the copy.
|
||||
if let Some(first) = run {
|
||||
bytes += self.copy(first * PAGE, (last + 1) * PAGE);
|
||||
bytes += self.copy((first * PAGE).max(from), ((last + 1) * PAGE).min(to));
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
@@ -65,6 +65,17 @@ pub(crate) extern "system" fn create(
|
||||
object::hand_out(COMMAND_SIGNATURE, signature, iid, &SIGNATURE_IIDS, out)
|
||||
}
|
||||
|
||||
/// A signature's record stride and arguments (type, then up to three
|
||||
/// fields each).
|
||||
pub(crate) fn layout<'a>(this: This) -> Option<(u32, &'a [[u32; 4]])> {
|
||||
if this.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the title passes one of our signatures.
|
||||
let s = unsafe { &*this.cast::<Signature>() };
|
||||
Some((s.stride, &s.arguments))
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = object::is(iid, &SIGNATURE_IIDS).then_some(this);
|
||||
object::answer(COMMAND_SIGNATURE, iid, found, out)
|
||||
|
||||
@@ -34,6 +34,9 @@ macro_rules! once {
|
||||
/// texture's subresources, and what was last detiled.
|
||||
struct Staging {
|
||||
buffer: ID3D12Resource,
|
||||
/// Its bytes.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
size: u64,
|
||||
data: *mut u8,
|
||||
footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>,
|
||||
rows: Vec<u32>,
|
||||
@@ -113,7 +116,36 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
|
||||
};
|
||||
const COPY_DEST: u32 = 0x400;
|
||||
crate::list::ensure_state(list, resource, COPY_DEST);
|
||||
// The staging buffer lives as long as `staging`, which the deferred
|
||||
// refresh below holds until the list is reset.
|
||||
for (i, footprint) in staging.footprints.iter().enumerate() {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
let f = footprint.Footprint;
|
||||
// SAFETY: live resources.
|
||||
let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) };
|
||||
let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth);
|
||||
list.note_read(
|
||||
|| {
|
||||
format!(
|
||||
"texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}",
|
||||
d.Width,
|
||||
d.Height,
|
||||
d.DepthOrArraySize,
|
||||
d.Format.0,
|
||||
d.MipLevels,
|
||||
staging.footprints.len(),
|
||||
staging.size,
|
||||
footprint.Offset,
|
||||
f.Width,
|
||||
f.Height,
|
||||
f.Depth,
|
||||
f.RowPitch
|
||||
)
|
||||
},
|
||||
(gpu + footprint.Offset, len),
|
||||
);
|
||||
}
|
||||
let to = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer the location never releases.
|
||||
pResource: unsafe { std::mem::transmute_copy(texture) },
|
||||
@@ -287,9 +319,17 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
|
||||
);
|
||||
}
|
||||
let (buffer, data) = host.upload_buffer(total)?;
|
||||
crate::host::name(&buffer, || {
|
||||
format!(
|
||||
"staging of {resource:?} {}x{}x{} f{}",
|
||||
d.Width, d.Height, d.DepthOrArraySize, d.Format.0
|
||||
)
|
||||
});
|
||||
tracing::debug!(?desc, total, "texture contents uploaded from title memory");
|
||||
let s = Arc::new(Staging {
|
||||
buffer,
|
||||
#[cfg(feature = "diagnostics")]
|
||||
size: total,
|
||||
data,
|
||||
footprints,
|
||||
rows,
|
||||
|
||||
Reference in new issue
Block a user