Skip to content
Open
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
298 changes: 283 additions & 15 deletions Cargo.lock

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,17 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper.
console shaders' hashes (`cs`, `vs` / `ps`, `ms` / `ps`, `vs` / `gs` / `ps`).
- `XCL_TEXTURE_LEVEL_PAGES=1` gives sampled title textures backing as their mip levels stream in.
Zero-filled mip uploads in a batch share one staging span and still clear any mapped tiles.
- **Profiling with [Tracy](https://github.com/wolfpld/tracy)**: `cargo build --release -p xcl
--features profile-tracy` builds an XCL that records a timeline, every thread's zones
(shader translation, DXC, driver PSO compiles with their record hash, async PSO builds,
`ExecuteCommandLists`, translated dispatches, `PresentX`, `WaitFrameEventX`,
`Wait32/64BitValueX`, DirectStorage entries), a frame mark at each `PresentX`, and plots of
commit, video memory, presents, draws, dispatches and DirectStorage MB. It shows what a frame
or a loading stall spent its time on, and on which thread: the 2 s `XCL_ACTIVITY` lines only
count what happened. Connect Tracy 0.14.1 (`tracy-profiler`, or `tracy-capture -o run.tracy`)
on localhost; run elevated for its CPU sampling and context switches. Without the feature
the zones compile to nothing. Tracy's crash handler is left out (XCL's exception handlers
must see the title's faults).
- `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib
requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget
(`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order.
Expand Down
4 changes: 4 additions & 0 deletions crates/xcl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ path = "src/lib.rs"
[features]
pipeline-resolution-bench = []
texture-selection-bench = []
profile-tracy = ["dep:tracy-client"]

[[bin]]
name = "xcl"
Expand All @@ -28,6 +29,9 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "1"
windows-core = "0.62"
# local profiling only (not for a PR): `--features profile-tracy`. No crash handler: XCL's own
# vectored handlers must see the title's faults and illegal instructions first.
tracy-client = { version = "0.19", optional = true, default-features = false, features = ["enable", "sampling", "system-tracing", "context-switch-tracing", "code-transfer", "flush-on-exit", "demangle", "only-localhost", "manual-lifetime"] }

[dependencies.windows]
version = "0.62"
Expand Down
2 changes: 2 additions & 0 deletions crates/xcl/src/gpu/recomp/dxc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -875,6 +875,7 @@ fn pool() -> &'static Arc<CompileQueue> {

/// Compile HLSL to signed DXIL. `profile` e.g. "cs_6_6"; `extra` are dxc arguments.
pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<Vec<u8>, String> {
crate::prof_zone!("DXC compile (incl. queue wait)", format!("{profile} {entry}, {} B HLSL", src.len()));
let (reply, rx) = std::sync::mpsc::channel();
let job = Job {
src: src.into(),
Expand All @@ -894,6 +895,7 @@ pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<
pub const UNOPTIMISED_ABOVE: usize = 8 * 1024 * 1024;

fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result<Vec<u8>, String> {
crate::prof_zone!("DXC compile (worker)", format!("{profile} {entry}, {} B HLSL", src.len()));
// compute (also what MS and GS programs run as): DXC's time for its memory accesses is
// linear this way (`emit::linked_form`). Anything wrong with it: as one program, as before.
if profile.starts_with("cs_") && linking() {
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1940,6 +1940,7 @@ pub(crate) fn needs_coherent_mem(insts: &[Decoded]) -> bool {
#[inline]
pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
let _stall = crate::stall::span(crate::stall::StallKind::ShaderTranslation);
crate::prof_zone!("recompile RDNA2 -> HLSL", format!("{} B", code.len()));
translate_inner(code, opt)
}

Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4981,6 +4981,7 @@ unsafe fn translated_dispatch(
z: u32,
limits: [u32; 3],
) -> Result<(), String> {
crate::prof_zone!("translated dispatch");
if super::present::trace_frame() {
trace_fullscreen(this, pso, [x, y, z]);
}
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/hle/d3d12x/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,7 @@ fn trace_calls(what: std::fmt::Arguments) {
pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, ty: u32, timeout_ms: u32, block: *const u8, flags: u32, token: *mut u64) -> HRESULT {
// (`XCL_LOOK_STATS=2`: a frame's time on the thread that submits, added up)
let _cost = super::look_stats::deep().then(|| crate::hle::api_cost::time(crate::hle::api_cost::Call::WaitFrameEvent));
crate::prof_zone!("WaitFrameEventX");
trace_calls(format_args!("WaitFrameEventX(type {ty}, timeout {timeout_ms} ms, block {block:p}, flags {flags:#x}, token in {:#x})", if token.is_null() { 0 } else { *token }));
let scheduled = with(|c| {
((ty as usize) < TYPES && c.kinds[ty as usize].scheduled)
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/hle/d3d12x/list_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4915,6 +4915,7 @@ unsafe fn prepare_deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty:
/// segment and complete its deferred store before this wait is evaluated. A prior `Write64` to
/// another cell keeps its existing split so its signal runs before the wait.
unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, value: u64, mask: u64, what: &str) {
crate::prof_zone!("Wait32/64BitValueX (CPU)");
static N: AtomicU64 = AtomicU64::new(0);
let n = width as u64;
if !va.is_multiple_of(n) {
Expand Down
2 changes: 2 additions & 0 deletions crates/xcl/src/hle/d3d12x/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ static PRESENTX_LOCK: Mutex<()> = Mutex::new(());
pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, planes: *const u8, _params: *const u8) -> i32 {
// (`XCL_LOOK_STATS=2`: a frame's time on the thread that submits, added up)
let _cost = super::look_stats::deep().then(|| crate::hle::api_cost::time(crate::hle::api_cost::Call::Present));
crate::prof_zone!("PresentX");
if plane_count == 0 || planes.is_null() || !crate::gpu::shader::readable(planes as usize, 0x18) {
return 0;
}
Expand All @@ -63,6 +64,7 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl
// The title can use flip statistics to decide when to reuse its buffer.
// Queue our copy before reporting the flip.
super::frame::mark_flipped(token);
crate::prof_frame!();
0
}

Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/hle/d3d12x/pso_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,7 @@ fn run_build(build: &Arc<Build>, job: Job) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_NORMAL};
let preload = PRELOAD_WORKER.get();
BUILDING.with(|b| *b.borrow_mut() = Some(build.clone()));
crate::prof_zone!("async PSO build", if preload { "preload" } else { "on demand" });
if preload {
let mut d = build.demand.lock().unwrap();
d.preload_thread = unsafe { GetCurrentThreadId() };
Expand Down
7 changes: 7 additions & 0 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5505,6 +5505,7 @@ fn driver_compile_identified<R>(kind: &str, bytes: usize, gate: bool, record: Op
let medium = gate && worker && medium_compute_compile(kind, bytes, huge_bytes, ADAPTER_VENDOR.load(Ordering::Acquire));
let huge = gate && worker && bytes >= huge_bytes;
let gated = medium || huge;
crate::prof_zone!("driver PSO compile", format!("{kind}, {bytes} B DXIL{}", record.map_or(String::new(), |h| format!(", record {h:016x}, blob {}", if cached { "supplied" } else { "absent" }))));
let waited = std::time::Instant::now();
let gate_stall = gated.then(|| crate::stall::span(crate::stall::StallKind::DriverCompileGate)).flatten();
let _slot = gated.then(|| {
Expand Down Expand Up @@ -6003,6 +6004,7 @@ unsafe fn translated_compute_pso(this: *mut c_void, f: PsoFn, desc: *const c_voi
}

unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option<Result<HRESULT, ()>> {
crate::prof_zone!("translate+create compute PSO");
use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage};
if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::<D3D12_COMPUTE_PIPELINE_STATE_DESC>()) {
return None;
Expand Down Expand Up @@ -7929,6 +7931,7 @@ unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_vo
}

unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, cacheable: bool, depth_bounds: bool) -> Option<HRESULT> {
crate::prof_zone!("translate+create graphics PSO");
use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage};
if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::<D3D12_GRAPHICS_PIPELINE_STATE_DESC>()) {
return None;
Expand Down Expand Up @@ -8650,6 +8653,7 @@ pub(crate) unsafe fn prepare_graphics(device: usize, desc: &D3D12_GRAPHICS_PIPEL
}

unsafe fn build_compute(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool {
crate::prof_zone!("build compute (split)");
let iid = pc_iid(Kind::PipelineState);
matches!(translated_compute_pso(dev.0 as *mut c_void, dev.1, d.ptr(), &iid, out), Some(Ok(hr)) if hr >= 0)
}
Expand Down Expand Up @@ -9692,6 +9696,7 @@ unsafe fn translated_mesh_stream(this: *mut c_void, desc: *const c_void, riid: *
}

unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option<HRESULT> {
crate::prof_zone!("translate+create mesh PSO");
use crate::gpu::recomp::pso::{console_mesh, is_console};
if !crate::gpu::shader::readable(desc as usize, 16) {
return None;
Expand Down Expand Up @@ -9794,6 +9799,7 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri
/// A graphics PSO with a console VS + GS: the GS pipeline in two passes, as a mesh pipeline
/// with the description's state.
unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs: &[u8], gs: &[u8], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
crate::prof_zone!("translate+create GS PSO");
let rt32 = rt32_mask_d3d12(d.NumRenderTargets, &d.RTVFormats);
let (tp, (ps, ps_samplers)) = match (
crate::gpu::recomp::pso::console_geometry(vs, gs, shader_bytes(&d.PS), wave32_only(this)),
Expand Down Expand Up @@ -11834,6 +11840,7 @@ unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT
}

unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lists: *const *mut c_void) {
crate::prof_zone!("ExecuteCommandLists", format!("{n} lists"));
type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void);
let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12CommandQueue", "ExecuteCommandLists")));
// Internal XCL submits (`sparse` uploads/readbacks, `title_textures` uploads, tile zeroing)
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/hle/dstorage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1267,6 +1267,7 @@ impl QueueInner {

#[inline]
fn run_entry(&self, e: Entry, since_status: &mut HRESULT, file_input: Option<&mut Vec<u8>>) {
crate::prof_zone!("DirectStorage entry");
if self.closed.load(Ordering::Acquire) {
if let Entry::Status(s, i) = e {
if let Some(slot) = s.slots.get(i as usize) {
Expand Down
8 changes: 8 additions & 0 deletions crates/xcl/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ pub fn host_main(boot_path: &Path) -> i32 {
boot.config.log_to_stderr,
);
crate::log::log_panics();
crate::prof::start();
crate::xlog_info!("XCL {} – host for '{}'", env!("CARGO_PKG_VERSION"), boot.title);
crate::xlog_info!("game: {} (read-only folder: {})", boot.exe_path.display(), boot.game_root.display());
crate::xlog_info!("XCL data: {}", boot.data_dir.display());
Expand Down Expand Up @@ -234,6 +235,13 @@ pub fn host_main(boot_path: &Path) -> i32 {
if let Some(over) = crate::hle::d3d12x::real::over_video_budget(local, budget) {
crate::xlog_warn!("video memory: {} MB in use, {} MB over the budget of {} MB Windows gives this process", mb(local), mb(over), mb(budget));
}
crate::prof_plot!("commit MB", mb(private as u64));
crate::prof_plot!("video local MB", mb(local));
crate::prof_plot!("video non-local MB", mb(non_local));
crate::prof_plot!("presents / 2 s", d[0]);
crate::prof_plot!("draws / 2 s", d[2]);
crate::prof_plot!("dispatches / 2 s", d[3]);
crate::prof_plot!("DirectStorage MB / 2 s", d[9]);
last = Some(now);
}
});
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub mod loader;
pub mod modules;
pub mod pe;
pub mod preflight;
pub mod prof;
pub mod report;
pub mod resolver;
pub mod rpf;
Expand Down
83 changes: 83 additions & 0 deletions crates/xcl/src/prof.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
//! Tracy instrumentation (`--features profile-tracy`); without the feature every macro here
//! expands to nothing. Zones are only recorded once `start()` ran (the host process), so the
//! launcher, `xcl shaders` and tests are unaffected even with the feature on.

/// Starts the Tracy client in this process (host mode only).
pub fn start() {
#[cfg(feature = "profile-tracy")]
{
let c = tracy_client::Client::start();
c.set_thread_name("xcl-host-main");
c.message("xcl host started", 0);
}
}

/// What the title's `_register_thread_local_exe_atexit_callback` import gets with the feature
/// on. Tracy's C++ `thread_local`s make xcl.exe's own CRT startup register a callback, and the
/// UCRT takes one per process: the title's CRT startup registering its own would `terminate()`
/// (0xC0000409). The title's main-thread `thread_local` destructors are then not run at exit;
/// the other threads' run from its TLS callbacks as before.
#[cfg(feature = "profile-tracy")]
pub unsafe extern "C" fn register_thread_local_exe_atexit_callback(_callback: usize) {}

/// A zone for the rest of the enclosing block: `prof_zone!("name")`, or
/// `prof_zone!("name", text_expr)` to attach a text (evaluated only while profiling).
#[macro_export]
macro_rules! prof_zone {
($name:literal) => {
#[cfg(feature = "profile-tracy")]
let _prof_zone = tracy_client::Client::running().map(|c| c.span(tracy_client::span_location!($name), 0));
};
($name:literal, $text:expr) => {
#[cfg(feature = "profile-tracy")]
let _prof_zone = tracy_client::Client::running().map(|c| {
let s = c.span(tracy_client::span_location!($name), 0);
s.emit_text(&$text);
s
});
};
}

/// The end of a presented frame.
#[macro_export]
macro_rules! prof_frame {
() => {
#[cfg(feature = "profile-tracy")]
if let Some(c) = tracy_client::Client::running() {
c.frame_mark();
}
};
}

/// A value on a named plot.
#[macro_export]
macro_rules! prof_plot {
($name:literal, $value:expr) => {
#[cfg(feature = "profile-tracy")]
if let Some(c) = tracy_client::Client::running() {
c.plot(tracy_client::plot_name!($name), $value as f64);
}
};
}

#[cfg(test)]
mod tests {
// Tests never call `start()`: the macros must be no-ops without a running client (with the
// feature on, `Client::running()` is `None`; off, they expand to nothing), and a zone's text
// must not be evaluated then.
#[test]
fn macros_are_no_ops_without_a_running_client() {
let evaluated = std::cell::Cell::new(false);
let _text = || {
evaluated.set(true);
String::from("text")
};
{
crate::prof_zone!("plain zone");
crate::prof_zone!("zone with text", _text());
crate::prof_plot!("plot", 1u64);
crate::prof_frame!();
}
assert!(!evaluated.get(), "a zone's text was built without a running client");
}
}
4 changes: 4 additions & 0 deletions crates/xcl/src/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,10 @@ pub fn resolve_import(dll: &str, what: &ImportName, importer: &str, delay: bool)
if matches!(source, Source::GameDll(_)) && crate::hle::bink::is_bink_dll(&key) {
addr = crate::hle::bink::wrap(&fname(what), addr);
}
#[cfg(feature = "profile-tracy")]
if fname(what) == "_register_thread_local_exe_atexit_callback" {
addr = crate::prof::register_thread_local_exe_atexit_callback as usize;
}
crate::xlog_debug!("import {importer}: {key}!{what} → {source:?}");
if let Some(f) = trace_filter() {
if f.wants(&key, &fname(what), &source) {
Expand Down
Loading