From 77d91f585d33c9e7a2193bb986f287dc51614b98 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:18:10 -0800 Subject: [PATCH] D3D12.X: attribute submitting-thread recording costs Add a separate detailed stall-tracing tier for high-frequency command recording. The first title submit identifies the submitting thread, and only that thread's draw, dispatch, binding, barrier, copy, and list-lifecycle work is timed. Coarse tracing and default runs still avoid clock reads and counter updates at those hot call sites. Assisted-by: Codex (GPT-5.6-sol) --- README.md | 4 ++ crates/xcl/src/hle/d3d12x/bind.rs | 20 ++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 15 ++++- crates/xcl/src/hle/d3d12x/real.rs | 7 +++ crates/xcl/src/host.rs | 5 +- crates/xcl/src/report.rs | 6 ++ crates/xcl/src/stall.rs | 88 +++++++++++++++++++++++++++-- 7 files changed, 137 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 434ad889b9..346d884ebd 100644 --- a/README.md +++ b/README.md @@ -322,6 +322,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder With `XCL_STALL_TRACE=1`, `report.json` also contains versioned aggregate counts, total/max time and log2-nanosecond histograms for coarse runtime stalls, plus a bounded list of the newest spans of at least 50 ms. The tracing is off by default. + `XCL_STALL_TRACE_DETAIL=1` includes high-frequency draw, dispatch, binding, barrier, copy and + command-list lifecycle recording costs on the title's first observed submitting thread; it also + enables the coarse trace. Use it only for a diagnostic run because every recorded call reads the + clock and updates counters. - **Diagnostics for a bug report** (all off by default; set them in the environment of `xcl run`): - `XCL_RUN_SECONDS=n`: the title ends itself after `n` seconds, with the GPU drained and `xcl.log` and `report.json` written, so a run of a fixed length can be attached. A value that diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 7314eade25..f2c79a967e 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -224,6 +224,7 @@ fn put(list: *mut c_void, i: u32, offset: u32, bytes: &[u8]) { /// #34 SetGraphicsRootSignature (PC #30) pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_void, rs: *mut c_void) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); let layout = console_list::layout_of(rs as usize); with(this, |s| { s.args_gfx = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; @@ -234,16 +235,19 @@ pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_vo /// #36 SetGraphicsRootDescriptorTable (PC #32) pub(super) unsafe extern "system" fn set_graphics_root_table(this: *mut c_void, i: u32, handle: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); put_in(this, true, i, 0, &(handle as u32).to_le_bytes()); } /// #38 SetGraphicsRoot32BitConstant (PC #34) pub(super) unsafe extern "system" fn set_graphics_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); put_in(this, true, i, offset, &value.to_le_bytes()); } /// #40 SetGraphicsRoot32BitConstants (PC #36) pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); if !data.is_null() { let bytes: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); put_in(this, true, i, offset, &bytes); @@ -253,6 +257,7 @@ pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_vo /// #42 / #44 / #46 SetGraphicsRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #38 / /// #40 / #42) pub(super) unsafe extern "system" fn set_graphics_root_descriptor(this: *mut c_void, i: u32, va: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); note_address(va); put_in(this, true, i, 0, &va.to_le_bytes()); } @@ -317,7 +322,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); let raw_pso = with(this, |s| s.pso); - let unbuilt_compute = signature_dispatches(sig) && super::pso_async::is_pending(raw_pso) && super::real::is_console_compute(raw_pso); + let dispatches = signature_dispatches(sig); + let _detail = crate::stall::detail_span(if dispatches { crate::stall::StallKind::DetailDispatch } else { crate::stall::StallKind::DetailDraw }); + let unbuilt_compute = dispatches && super::pso_async::is_pending(raw_pso) && super::real::is_console_compute(raw_pso); if unbuilt_compute && super::list_x::defer(this, raw_pso, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { return; } @@ -360,7 +367,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // A native PC compute pipeline is not one of these and still goes to the PC call. // (`CONSOLE_COMPUTE` holds the title's object, which for a shared stand-in differs from // the driver pipeline `resolve_wait` returned.) - if signature_dispatches(sig) && (super::real::is_console_compute(raw_pso) || super::real::is_console_compute(pso)) { + if dispatches && (super::real::is_console_compute(raw_pso) || super::real::is_console_compute(pso)) { count(DISPATCHES_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -587,6 +594,7 @@ fn cpu_rect_expansion(pso: usize) -> bool { /// #12 DrawInstanced pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDraw); DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); if let Some(list) = graphics_bound(this) { if draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { @@ -604,6 +612,7 @@ thread_local! { /// #13 DrawIndexedInstanced pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDraw); if let Some(list) = prepare_indexed_draw(this, indices, instances, first_index, base_vertex) { super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, if first_instance != 0 { instances.max(2) } else { instances }); emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); @@ -926,6 +935,7 @@ unsafe fn root_args_summary(this: *mut c_void, buffer_words: usize) -> String { /// #33 SetComputeRootSignature (PC #29) pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_void, rs: *mut c_void) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); let layout = console_list::layout_of(rs as usize); with(this, |s| { s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; @@ -935,16 +945,19 @@ pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_voi /// #35 SetComputeRootDescriptorTable (PC #31): the table's console address, 32 bits pub(super) unsafe extern "system" fn set_compute_root_table(this: *mut c_void, i: u32, handle: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); put(this, i, 0, &(handle as u32).to_le_bytes()); } /// #37 SetComputeRoot32BitConstant (PC #33) pub(super) unsafe extern "system" fn set_compute_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); put(this, i, offset, &value.to_le_bytes()); } /// #39 SetComputeRoot32BitConstants (PC #35) pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); if !data.is_null() { let bytes: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); put(this, i, offset, &bytes); @@ -954,18 +967,21 @@ pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_voi /// #41 / #43 / #45 SetComputeRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #37 / /// #39 / #41): the 64-bit GPU address pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_void, i: u32, va: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); note_address(va); put(this, i, 0, &va.to_le_bytes()); } /// #25 SetPipelineState: noted, then bound as on the PC pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: *mut c_void) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); with(this, |s| s.pso = pso as usize); super::real::bind_pipeline(this, pso); } /// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDispatch); dispatch_flags(this, x, y, z, 0); } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 2192a29c3f..cdff2814db 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -4634,6 +4634,7 @@ pub(super) unsafe fn ensure_view_heap(this: *mut c_void) { /// console #32 SetDescriptorHeaps (PC #28) pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n: u32, heaps: *const usize) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); const PC_SET_DESCRIPTOR_HEAPS: usize = 28; let f = pc::(this, PC_SET_DESCRIPTOR_HEAPS); if heaps.is_null() || n == 0 { @@ -4856,6 +4857,7 @@ const PC_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80 | 0x100 /// PC ones – state bits the PC does not know are dropped (logged: the console's own), a /// transition left with nothing to do goes, aliasing barriers name placed textures pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u32, barriers: *const [u32; 8]) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBarrier); static N: AtomicU64 = AtomicU64::new(0); if barriers.is_null() || n == 0 { return; @@ -4953,6 +4955,7 @@ unsafe fn is_buffer(res: usize) -> bool { /// DMA list #9 Close: as on the PC; a failure is logged (the title stops on it) pub(super) unsafe extern "system" fn dma_close_x(this: *mut c_void) -> i32 { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailListLifecycle); let ext = *(this as *const usize); let hr = pc:: i32>(this, 9)(this); real::preserve_vtable(this, ext); @@ -4991,6 +4994,11 @@ fn note_gpu_write(what: &str, va: usize, n: u64) { } pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst: usize, dst_off: u64, src: usize, src_off: u64, n: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); + copy_buffer_region_inner(this, dst, dst_off, src, src_off, n) +} + +unsafe fn copy_buffer_region_inner(this: *mut c_void, dst: usize, dst_off: u64, src: usize, src_off: u64, n: u64) { if super::present::trace_frame() { if let Some(a) = real::title_address(dst) { note_gpu_write("CopyBufferRegion", a + dst_off as usize, n); @@ -5025,6 +5033,7 @@ unsafe fn trace_watched_copy(what: &str, dst: usize, src: usize) { /// CopyTextureRegion(dst, x, y, z, src, box) (PC #16; DMA list #12) pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, dst: *const D3D12_TEXTURE_COPY_LOCATION, x: u32, y: u32, z: u32, src: *const D3D12_TEXTURE_COPY_LOCATION, bx: *const D3D12_BOX) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); if let Some(d) = dst.as_ref() { let r: usize = transmute_copy(&d.pResource); super::present::note_use(r, super::present::USE_COPY); @@ -5157,6 +5166,7 @@ fn uav_clear_handles(gpu: Option, cpu: Option (gpu, cpu), UavClearHandles::Pc => (gpu, cpu), @@ -5209,6 +5219,7 @@ unsafe fn trace_resolve(what: &str, dst: usize, src: usize, format: i32, extra: /// command list #19 ResolveSubresource(dst, dst sub, src, src sub, format) (PC #19) pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, dst: usize, dst_sub: u32, src: usize, src_sub: u32, format: i32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); super::present::note_use(dst, super::present::USE_COPY); trace_resolve("ResolveSubresource", dst, src, format, ""); pc::(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format) @@ -5218,6 +5229,7 @@ pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, ds /// mode) (PC #64) #[allow(clippy::too_many_arguments)] pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_void, dst: usize, dst_sub: u32, x: u32, y: u32, src: usize, src_sub: u32, rect: *const windows::Win32::Foundation::RECT, format: i32, mode: i32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); super::present::note_use(dst, super::present::USE_COPY); if super::present::trace_frame() { trace_resolve("ResolveSubresourceRegion", dst, src, format, &format!(" mode {mode} at ({x}, {y}) rect {:?}", rect.as_ref().map(|r| (r.left, r.top, r.right, r.bottom)))); @@ -5228,6 +5240,7 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v /// CopyResource(dst, src) (PC #17; DMA list #13): buffers placed below their console address /// are copied as their own bytes (the PC resources also hold what lies before them) pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); super::present::note_use(dst, super::present::USE_COPY); note_texture_write(this as usize, dst, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES); if super::present::trace_frame() { @@ -5238,7 +5251,7 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi return pc::(this, PC_COPY_RESOURCE)(this, dst, src); } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); - copy_buffer_region_x(this, dst, 0, src, 0, n); + copy_buffer_region_inner(this, dst, 0, src, 0, n); } /// command list #28 BeginQuery(heap, type, index) (PC #52) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 1cb1384893..bd22d432ea 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3166,6 +3166,7 @@ macro_rules! as_usize { /// command list's vtable pointer on Close; adopt the runtime's new state vtable so /// subsequent Reset and console calls dispatch through the current native table. unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); super::list_x::before_close(this); let ext = *(this as *const usize); let f: RefFn = std::mem::transmute(orig_fn(this, slot!(this, "Close"))); @@ -3180,6 +3181,7 @@ unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { /// Reset (PC path): re-adopt the runtime's new open-state vtable if Reset replaced it. unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, initial_state: *mut c_void) -> HRESULT { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); let ext = *(this as *const usize); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot!(this, "Reset"))); @@ -8607,6 +8609,7 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 // --------------------------------------------------------------------------------------- unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, desc: *const c_void, handle: usize) { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailBind); type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void, usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateRenderTargetView"))); // a view in a console-only format, or of a target made R8G8B8A8 (`device_x::pc_resource_desc`) @@ -8629,6 +8632,7 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de /// ClearRenderTargetView: as on the PC (`XCL_TRACE_FRAME`: the colours logged) unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *const [f32; 4], n: u32, rects: *const c_void) { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailCopy); type F = unsafe extern "system" fn(*mut c_void, usize, *const [f32; 4], u32, *const c_void); let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ClearRenderTargetView"))); if super::present::trace_frame() { @@ -8644,6 +8648,7 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co } unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rtvs: *const usize, single: i32, dsv: *const usize) { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailBind); type F = unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize); let f: F = std::mem::transmute(orig_fn(this, slot!(this, "OMSetRenderTargets"))); f(this, n, rtvs, single, dsv); @@ -8815,6 +8820,7 @@ pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { } unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); // Lists may still hold recordings on it that the title submits again (`alloc_pool`). UMA // follows each native backing and is released only when reset_pc_allocator resets that one. match super::alloc_pool::title_reset(this) { @@ -9068,6 +9074,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis stop_if_device_removed(); return; } + crate::stall::note_submitter(); // from here to the end: XCL's uploads and tile mappings before the lists, then the driver's // own work in the submission. Where that takes long, it is not the title's time // (`pso_async::title_held`) diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 79cd2874bb..f557d0eb75 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -31,7 +31,10 @@ pub fn host_main(boot_path: &Path) -> i32 { boot.config.title_memory_mb, boot.config.title_memory ); - if std::env::var_os("XCL_STALL_TRACE").is_some() { + if std::env::var_os("XCL_STALL_TRACE_DETAIL").is_some() { + crate::stall::enable_detail(); + crate::xlog_info!("detailed stall attribution enabled (XCL_STALL_TRACE_DETAIL)"); + } else if std::env::var_os("XCL_STALL_TRACE").is_some() { crate::stall::enable(); crate::xlog_info!("stall attribution enabled (XCL_STALL_TRACE)"); } diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index 60612b592d..ec6a29a674 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -98,6 +98,12 @@ fn stall_kind_name(kind: crate::stall::StallKind) -> &'static str { StallKind::GpuWait => "gpu_wait", StallKind::Present => "present", StallKind::DirectStorage => "direct_storage", + StallKind::DetailDraw => "detail_draw", + StallKind::DetailDispatch => "detail_dispatch", + StallKind::DetailBind => "detail_bind", + StallKind::DetailBarrier => "detail_barrier", + StallKind::DetailCopy => "detail_copy", + StallKind::DetailListLifecycle => "detail_list_lifecycle", } } diff --git a/crates/xcl/src/stall.rs b/crates/xcl/src/stall.rs index 06add3c292..c0fc764838 100644 --- a/crates/xcl/src/stall.rs +++ b/crates/xcl/src/stall.rs @@ -1,11 +1,11 @@ //! Opt-in attribution of time spent in coarse runtime operations. //! //! A disabled span is one relaxed atomic load. In particular, it does not read the clock, allocate, -//! lock, or update a counter. Callers should keep spans coarse enough that enabled tracing remains -//! useful diagnostics rather than becoming the workload. +//! lock, or update a counter. High-frequency command-recording spans have a separate detail switch, +//! so enabling coarse attribution does not turn them on. use std::collections::VecDeque; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use std::sync::{Mutex, OnceLock}; use std::time::Instant; @@ -30,10 +30,16 @@ pub enum StallKind { GpuWait, Present, DirectStorage, + DetailDraw, + DetailDispatch, + DetailBind, + DetailBarrier, + DetailCopy, + DetailListLifecycle, } impl StallKind { - pub const ALL: [Self; 14] = [ + pub const ALL: [Self; 20] = [ Self::ShaderTranslation, Self::DxcQueue, Self::DxcCompile, @@ -48,6 +54,12 @@ impl StallKind { Self::GpuWait, Self::Present, Self::DirectStorage, + Self::DetailDraw, + Self::DetailDispatch, + Self::DetailBind, + Self::DetailBarrier, + Self::DetailCopy, + Self::DetailListLifecycle, ]; const fn index(self) -> usize { @@ -125,6 +137,9 @@ struct SlowSpans { struct Recorder { enabled: AtomicBool, + detail_enabled: AtomicBool, + /// First title thread observed submitting command lists; zero until then. + submitter: AtomicU32, aggregates: [Aggregate; StallKind::ALL.len()], slow_spans: Mutex, } @@ -137,6 +152,8 @@ impl Recorder { const fn new() -> Self { Self { enabled: AtomicBool::new(false), + detail_enabled: AtomicBool::new(false), + submitter: AtomicU32::new(0), aggregates: [const { Aggregate::new() }; StallKind::ALL.len()], slow_spans: Mutex::new(SlowSpans { next_sequence: 0, spans: VecDeque::new() }), } @@ -146,6 +163,15 @@ impl Recorder { self.enabled.store(true, Ordering::Relaxed); } + fn enable_detail(&self) { + self.enable(); + self.detail_enabled.store(true, Ordering::Relaxed); + } + + fn note_submitter(&self, thread: u32) { + let _ = self.submitter.compare_exchange(0, thread, Ordering::Relaxed, Ordering::Relaxed); + } + #[inline] fn start_with<'a>(&'a self, kind: StallKind, clock: &'a dyn Clock) -> Option> { if !self.enabled.load(Ordering::Relaxed) { @@ -154,6 +180,14 @@ impl Recorder { Some(Span { recorder: self, kind, started_ns: clock.now_ns(), clock, finished: false }) } + #[inline] + fn start_detail_with<'a>(&'a self, kind: StallKind, clock: &'a dyn Clock, thread: u32) -> Option> { + if !self.detail_enabled.load(Ordering::Relaxed) || self.submitter.load(Ordering::Relaxed) != thread { + return None; + } + Some(Span { recorder: self, kind, started_ns: clock.now_ns(), clock, finished: false }) + } + fn record(&self, kind: StallKind, started_ns: u64, duration_ns: u64) { self.aggregates[kind.index()].record(duration_ns); if duration_ns < SLOW_SPAN_NS { @@ -204,17 +238,45 @@ pub fn enable() { RECORDER.enable(); } +pub fn enable_detail() { + RECORDER.enable_detail(); +} + +/// Mark the first title thread that submits command lists as the thread detailed spans describe. +pub fn note_submitter() { + RECORDER.note_submitter(current_thread()); +} + #[inline] pub fn span(kind: StallKind) -> Option> { RECORDER.start_with(kind, &CLOCK) } +/// A high-frequency command-recording span, enabled only by `XCL_STALL_TRACE_DETAIL`. +#[inline] +pub fn detail_span(kind: StallKind) -> Option> { + if !RECORDER.detail_enabled.load(Ordering::Relaxed) { + return None; + } + RECORDER.start_detail_with(kind, &CLOCK, current_thread()) +} + +/// Like [`detail_span`], without even consulting the detail switch when `on` is false. +#[inline] +pub fn detail_span_if(on: bool, kind: StallKind) -> Option> { + on.then(|| detail_span(kind)).flatten() +} + pub fn snapshot() -> Option { RECORDER.enabled.load(Ordering::Relaxed).then(|| RECORDER.snapshot()) } struct SystemClock; +fn current_thread() -> u32 { + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } +} + impl Clock for SystemClock { fn now_ns(&self) -> u64 { static ORIGIN: OnceLock = OnceLock::new(); @@ -254,6 +316,24 @@ mod tests { assert_eq!(recorder.snapshot().aggregates[StallKind::DxcCompile.index()].count, 0); } + #[test] + fn coarse_tracing_does_not_enable_detail_spans() { + let recorder = Recorder::new(); + recorder.enable(); + let clock = TestClock::new(10); + recorder.note_submitter(7); + assert!(recorder.start_detail_with(StallKind::DetailDraw, &clock, 7).is_none()); + assert_eq!(clock.calls.load(Ordering::Relaxed), 0); + + recorder.enable_detail(); + assert!(recorder.start_detail_with(StallKind::DetailDraw, &clock, 8).is_none()); + let span = recorder.start_detail_with(StallKind::DetailDraw, &clock, 7).unwrap(); + clock.now.store(42, Ordering::Relaxed); + drop(span); + let aggregate = &recorder.snapshot().aggregates[StallKind::DetailDraw.index()]; + assert_eq!((aggregate.count, aggregate.total_ns), (1, 32)); + } + #[test] fn a_span_updates_its_aggregate_and_log2_bucket() { let recorder = Recorder::new();