Skip to content
Open
48 changes: 41 additions & 7 deletions apps/victory/src/translate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,14 +140,17 @@ impl Tally {
}
}

/// Emitted shaders by label, shared between threads.
type Kept = std::sync::Arc<Mutex<Vec<(String, emit::HostShader)>>>;
/// Emitted shaders by label, with their containers, shared between threads.
type Kept = std::sync::Arc<Mutex<Vec<(String, emit::HostShader, Vec<u8>)>>>;

/// The optional checks after emission, one set per thread.
struct Checks {
/// Shaders named in `VICTORY_PAIRS` (`vs+ps,...`, label substrings),
/// kept to build those pipelines after the walk.
/// kept to build those pipelines after the walk: the names, and the
/// container being translated when its label holds one of them.
keep: Option<Kept>,
names: Vec<String>,
current: Option<Vec<u8>>,
validator: Option<Validator>,
host: Option<(Host, emit::HostShader)>,
}
Expand Down Expand Up @@ -216,6 +219,8 @@ pub fn run(
};
let mut checks = Checks {
keep: (!pairs.is_empty()).then(|| kept.clone()),
names: pairs.iter().flat_map(|(v, p)| [v.clone(), p.clone()]).collect(),
current: None,
validator: validate
.then(|| Validator::load(dll.as_deref()).ok())
.flatten(),
Expand Down Expand Up @@ -284,10 +289,34 @@ pub fn run(
if !pairs.is_empty() {
let host = Host::new(false).map_err(anyhow::Error::msg)?;
let kept = lock(&kept);
let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name));
let find = |name: &str| kept.iter().find(|(l, _, _)| l.contains(name));
let mut validator = Validator::load(dll.as_deref()).ok();
for (v, p) in &pairs {
let made = match (find(v), find(p)) {
(Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms {
// A mesh program whose outputs pass the host's 32 KiB alone: linked with
// this pixel program, as the runtime makes its pipeline
// (`emit::link_mesh`), each of the two validated.
(Some((_, ms, msc)), Some((_, ps, psc))) if ms.stage == HwStage::Ms && !emit::mesh_fits(&ms.dxil).unwrap_or(true) => {
match emit::link_mesh(msc, ms, psc, ps) {
Ok(Some((lms, lps))) => {
let mut checked = Vec::new();
for (what, s) in [("mesh", &lms), ("pixel", &lps)] {
if let Some(v) = validator.as_mut() {
let mut copy = s.dxil.clone();
checked.push(match v.validate(&mut copy) {
Ok(()) => format!("{what} validated"),
Err(e) => format!("{what} invalid: {}", e.lines().find(|l| l.contains("error")).unwrap_or(&e)),
});
}
}
let made = host.mesh_pipeline(&lms, &lps).map(|_| "pipeline created".to_owned()).unwrap_or_else(|e| e);
format!("linked, {}, {made}", checked.join(", "))
}
Ok(None) => "not linked (over 32 KiB)".to_owned(),
Err(e) => format!("not linked: {e}"),
}
}
(Some((_, vs, _)), Some((_, ps, _))) => if vs.stage == HwStage::Ms {
host.mesh_pipeline(vs, ps)
} else {
host.pipeline(vs, ps)
Expand Down Expand Up @@ -463,6 +492,11 @@ fn translate(
let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), &bytes[..]);
}
}
// (`VICTORY_PAIRS`: a container whose label names a shader of a pair is kept)
checks.current = (!checks.names.is_empty())
.then(example)
.filter(|line| checks.names.iter().any(|n| line.contains(n.as_str())))
.map(|_| bytes.to_vec());
if !lock(seen).insert(code) {
t.duplicates += 1;
if t.list {
Expand Down Expand Up @@ -632,8 +666,8 @@ fn check(
checks: &mut Checks,
label: impl Fn() -> String,
) {
if let Some(keep) = &checks.keep {
lock(keep).push((label(), shader.clone()));
if let (Some(keep), Some(bytes)) = (&checks.keep, &checks.current) {
lock(keep).push((label(), shader.clone(), bytes.clone()));
}
// `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file.
if t.list
Expand Down
28 changes: 13 additions & 15 deletions crates/victory-gpu/src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,25 +346,23 @@ fn feature_levels(data: *mut c_void) -> HRESULT {
}
}

/// Device methods 0x1c8 and 0x218 (`SLOT`). The title calls both
/// (title+0x2477578 and title+0x24800d5) as `(this, description, interface
/// id, out)`, asks for `ID3D12PipelineState`, and on success keeps the
/// object `out` names and draws with it; on failure it goes without that
/// pipeline, silently. What the descriptions hold is not known: the calls
/// fail as they always did, with `out` null, and the first ones log the
/// description's words and what its first word points at, so that the two
/// methods can be written.
/// shortcut: not implemented. Answering `S_OK` here without making the
/// Device method 0x1c8 (title+0x2477578): a graphics pipeline from programs
/// the title compiled itself, called as `(this, description, interface id,
/// out)` for `ID3D12PipelineState`. On failure the title goes without that
/// pipeline, silently. The first calls log the description's words and what
/// its first word points at.
/// shortcut: not implemented. A host pipeline also needs the render-target
/// formats, which only the draw gives; answering `S_OK` without making the
/// pipeline would hand the title whatever its stack held as an object.
extern "system" fn unknown_pipeline<const SLOT: usize>(
extern "system" fn unknown_graphics_pipeline(
_: This,
desc: *const u8,
_iid: *const Iid,
out: *mut This,
) -> HRESULT {
use std::sync::atomic::{AtomicU32, Ordering};
static CALLS: [AtomicU32; 2] = [const { AtomicU32::new(0) }; 2];
let calls = CALLS[usize::from(SLOT == 0x218)].fetch_add(1, Ordering::Relaxed) + 1;
static CALLS: AtomicU32 = AtomicU32::new(0);
let calls = CALLS.fetch_add(1, Ordering::Relaxed) + 1;
if !out.is_null() {
// SAFETY: the title's out pointer (a local of its own).
unsafe { *out = std::ptr::null() };
Expand All @@ -389,7 +387,7 @@ extern "system" fn unknown_pipeline<const SLOT: usize>(
.as_ref()
.and_then(|w| words(w[0] as usize));
tracing::warn!(
slot = format_args!("{:#x}", SLOT),
slot = "0x1c8",
calls,
description = format_args!("{description:x?}"),
first_points_at = format_args!("{first:x?}"),
Expand Down Expand Up @@ -435,10 +433,10 @@ static FUNCTIONS: Table<160> = {
f[39] = query::create as *const (); // 0x138
f[41] = signature::create as *const (); // 0x148
f[48] = queue::create_x as *const (); // 0x180
f[57] = unknown_pipeline::<0x1c8> as *const (); // 0x1c8
f[57] = unknown_graphics_pipeline as *const (); // 0x1c8
f[61] = descriptor::create_sampler_x as *const (); // 0x1e8
f[62] = pipeline::create_compute_x as *const (); // 0x1f0
f[67] = unknown_pipeline::<0x218> as *const (); // 0x218
f[67] = pipeline::create_native_compute as *const (); // 0x218
f[69] = object::ignore as *const (); // 0x228 debug error filter
f[70] = descriptor::create_placed_srv as *const (); // 0x230
f[71] = descriptor::create_placed_uav as *const (); // 0x238
Expand Down
22 changes: 22 additions & 0 deletions crates/victory-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2345,6 +2345,12 @@ impl State {

/// Runs a dispatch on the host.
pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32, flags: Option<u32>) {
#[cfg(feature = "diagnostics")]
let trace = crate::pipeline::dispatch_trace(self.pipeline as This);
#[cfg(feature = "diagnostics")]
if let Some(trace) = trace {
trace.attempt(false);
}
// It may write the arguments a window holds clamped.
self.window = None;
let builder = crate::pipeline::is_builder(self.pipeline as This);
Expand Down Expand Up @@ -2450,6 +2456,10 @@ impl State {
unsafe { list.list.Dispatch(x, y, z) };
}
}
#[cfg(feature = "diagnostics")]
if let Some(trace) = trace {
trace.record(false);
}
if let Some((param, word, _)) = tail {
// Later ordinary or indirect dispatches use all lanes.
unsafe { list.list.SetComputeRoot32BitConstant(param, 0, word) };
Expand Down Expand Up @@ -3378,7 +3388,19 @@ impl State {
arguments: u64,
count: Option<u64>,
) -> bool {
#[cfg(feature = "diagnostics")]
let trace = (kind == 2 && max != 0)
.then(|| crate::pipeline::dispatch_trace(self.pipeline as This))
.flatten();
#[cfg(feature = "diagnostics")]
if let Some(trace) = trace {
trace.attempt(true);
}
let ran = self.run_indirect(list, (kind, stride, max), arguments, count);
#[cfg(feature = "diagnostics")]
if ran && let Some(trace) = trace {
trace.record(true);
}
if kind == 2 && max != 0 && crate::pipeline::is_builder(self.pipeline as This) {
if !ran {
crate::pipeline::builder_off("an indirect builder dispatch could not run");
Expand Down
2 changes: 2 additions & 0 deletions crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,8 @@ pub fn on_failure(report: fn(&str) -> !) {
/// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
/// diagnostics build names the command).
pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
#[cfg(feature = "diagnostics")]
crate::pipeline::report_dispatch_traces(crate::queue::presented());
let mut text = what.to_string();
if let Some(host) = host() {
// SAFETY: a plain query.
Expand Down
26 changes: 23 additions & 3 deletions crates/victory-gpu/src/inplace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1333,6 +1333,23 @@ mod tests {
}
}

/// Tries `free` (a `VirtualFree` of pages a heap was opened on) until
/// it succeeds, for two seconds at most: when the heap's last reference
/// goes, the runtime may destroy it, and unlock its pages, a moment
/// later. Whether it succeeded.
fn once_released(mut free: impl FnMut() -> bool) -> bool {
let until = std::time::Instant::now() + std::time::Duration::from_secs(2);
loop {
if free() {
return true;
}
if std::time::Instant::now() > until {
return false;
}
std::thread::sleep(std::time::Duration::from_millis(1));
}
}

pub(crate) fn warp() -> Option<ID3D12Device> {
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
use windows::Win32::Graphics::Dxgi::*;
Expand Down Expand Up @@ -1398,10 +1415,13 @@ mod tests {
rig.store(&placed.buffer, placed.bias + 16, &[0xa5; 64]).unwrap();
assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address");
drop(placed);
// Half of it decommitted: turned down, the host not asked.
assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0);
// Half of it decommitted: turned down, the host not asked. The
// heap's pages stay locked until the runtime has destroyed it,
// which may come a moment after the last reference goes.
assert!(once_released(|| mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0), "the pages are given back once the heap goes");
assert!(matches!(place_part(&device, start, len), Err(None)));
mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE);
drop(rig);
assert_ne!(mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE), 0);
}
}

Expand Down
Loading