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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,10 +161,11 @@ cargo build --profile diag -p victory --features diagnostics # target\diag\vic
| `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_PIPELINE_WAIT_MS=24` | reduce the per-frame wait for background pipeline creation from the default of 500 ms. A draw can be omitted until its pipeline is ready |
| `VICTORY_PIPELINE_WORKERS=16` | use this many pipeline worker threads (1-64) instead of half the logical processors, 2-8 by default |
| `VICTORY_SKIP_PIPELINES=<hash>,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash |
| `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands |
| `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) |
| `VICTORY_SHADER_LOOP_LIMIT=<n>` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow |
| `VICTORY_SHADER_LOOP_LIMIT=<n>` | translated shader loops stop after `n` iterations per lane instead of 2^14 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow |
| `VICTORY_AUDIO_CAPTURE=<file.wav>` | records what the title plays (our process only) |
| `VICTORY_XMA_DUMP=<dir>` | saves the first 32 XMA voices' context and input |

Expand Down
9 changes: 9 additions & 0 deletions crates/victory-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1226,6 +1226,15 @@ impl State {
let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}"));
#[cfg(not(feature = "diagnostics"))]
let why = |_: &str| {};
// A call whose pipeline is not made yet cannot run. That is common
// while the world builds its pipelines; drop it before refreshing and
// clamping records nothing will read.
if crate::pipeline::host_pipeline(self.pipeline as This).is_none() {
#[cfg(feature = "diagnostics")]
crate::pipeline::note_drop(self.pipeline as This);
why("no host pipeline");
return false;
}
let len = u64::from(stride) * u64::from(max.max(1));
let Some(args) = crate::shadow::find(arguments, len) else {
why("arguments outside title buffers");
Expand Down
7 changes: 6 additions & 1 deletion crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1599,7 +1599,12 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
for_pieces(dst as usize, len, 64 << 10, |at, n| {
if !write(at, n) {
for_pieces(at, n, 4 << 10, |at, n| {
write(at, n);
// Wine does not write into write-watched pages not written
// since they were committed (ERROR_PARTIAL_COPY), but reads
// into them. The kernel checks this destination as well.
if !write(at, n) {
read(src.wrapping_add(at - dst as usize), at as *mut u8, n);
}
});
}
});
Expand Down
32 changes: 27 additions & 5 deletions crates/victory-gpu/src/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1121,9 +1121,14 @@ mod state {
}
with_state(this, |list, s| s.dispatch_mesh(list, x));
}
/// `DispatchMeshX(x, flags, indirect arguments, payload)`.
/// shortcut: dispatches whose group count is in GPU memory (indirect)
/// are dropped; make them ExecuteIndirect when the title uses them.
/// `DispatchMeshX(x, flags, indirect arguments, payload)`. With
/// `indirect` set, the group counts are in GPU memory at that title
/// address: one mesh dispatch record, `x, y, z` (12 bytes), run as an
/// indirect execution of one record like ExecuteIndirect's mesh signature,
/// so earlier GPU work that wrote the counts is seen.
/// shortcut: the record layout is assumed to be the mesh dispatch
/// arguments the title's ExecuteIndirect signatures use, and `x` is
/// ignored then; not yet checked against the title.
pub(super) extern "system" fn dispatch_mesh_x(
this: This,
x: u32,
Expand All @@ -1133,12 +1138,29 @@ mod state {
) {
super::count_draw();
if indirect != 0 {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped"));
let mut ran = false;
with_state(this, |list, s| {
ran = s.execute_indirect(list, (MESH_INDIRECT, MESH_RECORD, 1), indirect, None);
});
if !ran {
super::INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
tracing::info!(
address = format!("{indirect:#x}"),
"an indirect mesh dispatch dropped (first time)"
)
});
}
return;
}
with_state(this, |list, s| s.dispatch_mesh(list, x));
}
/// The indirect argument kind of a mesh dispatch
/// (`State::execute_indirect`).
const MESH_INDIRECT: u32 = 10;
/// Bytes of one mesh dispatch record: three u32 group counts.
const MESH_RECORD: u32 = 12;
pub(super) extern "system" fn draw_indexed(
this: This,
indices: u32,
Expand Down
40 changes: 30 additions & 10 deletions crates/victory-gpu/src/pipeline/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@
//! graphics state); the next run hands those to the workers at
//! creation, during loading.
//!
//! All library calls are serialised: the interface does not promise that
//! stores, loads and serialising may overlap.
//! Stores and serialising are serialised. Loads run outside that lock on a
//! reference of the library's own: vkd3d-proton keeps no compiled code in its
//! library, so there a load is a whole compile and holding the lock would make
//! the workers wait for one another.

use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::sync::{Arc, LazyLock, Mutex, OnceLock};

use windows::Win32::Graphics::Direct3D12::*;
use windows::core::{HSTRING, Interface, PCWSTR};
Expand Down Expand Up @@ -47,12 +49,17 @@ struct Library {
stored: HashSet<String>,
}

// SAFETY: D3D12 objects are free-threaded; every call is made under the
// mutex that holds the library.
// SAFETY: D3D12 pipeline libraries are internally synchronised except for
// same-name loads, which `LOADS` serialises; stores and serialising are under
// the mutex that holds the library.
unsafe impl Send for Library {}

const LIBRARY_FILE: &str = "host-pipelines.bin";
const EARLY_FILE: &str = "early-pipelines.txt";
/// Loads of the same pipeline serialise (the host documents that one as not
/// thread-safe); loads of different pipelines may overlap.
static LOADS: LazyLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
/// Title pipelines listed for an early start, at most.
const EARLY_MAX: usize = 8192;

Expand Down Expand Up @@ -154,10 +161,23 @@ pub(crate) fn pipeline(
MADE.fetch_add(1, Ordering::Relaxed);
return create();
};
if let Ok(pso) = load(
&library.lock().unwrap_or_else(|e| e.into_inner()).library,
PCWSTR(wide.as_ptr()),
) {
// A load can be a whole compile under vkd3d-proton, whose library keeps
// no compiled code; do not hold the store/serialise lock across it. The
// host requires only same-name loads to serialise, so those get a lock of
// their own and different pipelines still load in parallel.
let handle = library
.lock()
.unwrap_or_else(|e| e.into_inner())
.library
.clone();
let same = LOADS
.lock()
.unwrap_or_else(|e| e.into_inner())
.entry(name.to_owned())
.or_default()
.clone();
let _same = same.lock().unwrap_or_else(|e| e.into_inner());
if let Ok(pso) = load(&handle, PCWSTR(wide.as_ptr())) {
LOADED.fetch_add(1, Ordering::Relaxed);
return Ok(pso);
}
Expand Down
37 changes: 29 additions & 8 deletions crates/victory-gpu/src/pipeline/make.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,11 +248,24 @@ fn wait(p: &Pending, frame: u64) {
/// which runs on it (reserved address space; committed only as used).
const PIPELINE_STACK: usize = 64 << 20;

/// Starts the pipeline workers (half the logical processors, 2 to 8) once.
/// Pipeline workers: half the logical processors, 2 to 8, unless
/// `VICTORY_PIPELINE_WORKERS` names a count (1 to 64). Driver compiles of the
/// world's largest programs bound a first run with an empty pipeline library.
fn worker_count(asked: Option<&str>, processors: usize) -> usize {
asked
.and_then(|v| v.trim().parse::<usize>().ok())
.map_or((processors / 2).clamp(2, 8), |n| n.clamp(1, 64))
}

/// Starts the pipeline workers once.
fn ensure_workers() -> bool {
static WORKERS: OnceLock<bool> = OnceLock::new();
*WORKERS.get_or_init(|| {
let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8));
let workers = worker_count(
std::env::var("VICTORY_PIPELINE_WORKERS").ok().as_deref(),
std::thread::available_parallelism().map_or(4, |n| n.get()),
);
tracing::info!(workers, "host pipeline workers");
let mut started = 0;
for i in 0..workers {
let spawned = std::thread::Builder::new()
Expand All @@ -262,12 +275,9 @@ fn ensure_workers() -> bool {
// on a world compute program and refused it as out of memory.
.stack_size(PIPELINE_STACK)
.spawn(move || {
// Below the title's own threads (loading, recording).
// SAFETY: a plain call on our own thread.
unsafe {
use windows::Win32::System::Threading::*;
let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
}
// At the title's own priority: below it, the world's busy
// threads starved the workers, and draws stayed dropped
// until their pipelines existed.
loop {
let p = {
let (lock, ready) = &WORK;
Expand Down Expand Up @@ -318,6 +328,17 @@ fn drained() {
mod tests {
use super::*;

#[test]
fn worker_count_takes_the_switch_within_bounds() {
assert_eq!(worker_count(None, 20), 8);
assert_eq!(worker_count(None, 2), 2);
assert_eq!(worker_count(Some("16"), 20), 16);
assert_eq!(worker_count(Some(" 3 "), 20), 3);
assert_eq!(worker_count(Some("0"), 20), 1);
assert_eq!(worker_count(Some("1000"), 20), 64);
assert_eq!(worker_count(Some("many"), 12), 6);
}

/// A first use queues the pipeline and, within the budget, gets the
/// worker's answer (here: no host pipeline for no shaders).
#[test]
Expand Down
Loading
Loading