From f194ea7d12b26b2cf5633a161d2bb220b99fade4 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 11:41:56 -0800 Subject: [PATCH] D3D12.X: measure submission residency phases Per-submit VRAM mapping and retirement work was folded into other active time, so gate contention, device lookup, fence polling, page-state work, native waits, and retirement could not be distinguished. Accumulate those phases per activity look without changing their locks or ordering. Cross-checked debug tests and release all-target builds for x86_64-pc-windows-gnu; Windows runtime tests, GPU tests, and smoke were not run here. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/hle/d3d12x/sparse.rs | 87 ++++++++++++++++-- crates/xcl/src/hle/d3d12x/vram.rs | 133 +++++++++++++++++++++++++++- 2 files changed, 213 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index bd1be3eba4..0116b7ff72 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -3711,7 +3711,7 @@ pub fn mapped_ranges() -> Vec<(usize, usize)> { s.runs.clone().unwrap_or_default() } -const LOOK_FIELDS: usize = 25; +const LOOK_FIELDS: usize = 35; const ACTIVE_US: usize = 0; const REFRESH_WAIT_US: usize = 1; const WATCH_US: usize = 2; @@ -3737,12 +3737,27 @@ const TEXTURES_VISITED: usize = 21; const TEXTURE_DIRTY_TESTS: usize = 22; const TEXTURE_MATCHES: usize = 23; const TEXTURES_RETAINED: usize = 24; +const VRAM_GATE_WAIT_US: usize = 25; +const VRAM_DEVICE_US: usize = 26; +const VRAM_UNMAP_POLL_US: usize = 27; +const VRAM_STATE_US: usize = 28; +const VRAM_QUEUE_WAIT_US: usize = 29; +const VRAM_RETIREMENT_US: usize = 30; +const VRAM_CALLS: usize = 31; +const VRAM_MAPPING_WAITS: usize = 32; +const VRAM_RECLAIM_PASSES: usize = 33; +const VRAM_RETIREMENT_PASSES: usize = 34; /// One complete `XCL_ACTIVITY` look. It is built without shared updates, then published once so /// the reporting thread cannot split one look across adjacent intervals. -#[derive(Default)] pub(super) struct LookSample([u64; LOOK_FIELDS]); +impl Default for LookSample { + fn default() -> Self { + Self([0; LOOK_FIELDS]) + } +} + impl LookSample { pub(super) fn add(&mut self, field: usize, value: u64) { self.0[field] = self.0[field].wrapping_add(value); @@ -3801,7 +3816,23 @@ pub(super) fn note_texture_selection( sample.add(TEXTURES_RETAINED, retained as u64); } +fn note_vram_before_execute(sample: &mut LookSample, timing: super::vram::BeforeExecuteTiming) { + sample.add_time(VRAM_GATE_WAIT_US, timing.gate_wait); + sample.add_time(VRAM_DEVICE_US, timing.device); + sample.add_time(VRAM_UNMAP_POLL_US, timing.unmap_poll); + sample.add_time(VRAM_STATE_US, timing.state); + sample.add_time(VRAM_QUEUE_WAIT_US, timing.queue_wait); + sample.add_time(VRAM_RETIREMENT_US, timing.retirement); + sample.add(VRAM_CALLS, timing.calls as u64); + sample.add(VRAM_MAPPING_WAITS, timing.mapping_waits as u64); + sample.add(VRAM_RECLAIM_PASSES, timing.reclaim_passes as u64); + sample.add(VRAM_RETIREMENT_PASSES, timing.retirement_passes as u64); +} + pub(super) fn note_look(mut sample: LookSample, active: std::time::Duration, refresh_wait: std::time::Duration) { + if let Some(timing) = super::vram::take_before_execute_timing() { + note_vram_before_execute(&mut sample, timing); + } sample.add_time(ACTIVE_US, active); sample.add_time(REFRESH_WAIT_US, refresh_wait); sample.add(LOOKS, 1); @@ -3824,12 +3855,20 @@ pub fn look_line(d: [u64; LOOK_FIELDS], secs: u64) -> String { runs, transfer_bytes, upload_wait, submit_gate_wait, submit_gate_hold, readback_gate_wait, readback_gate_hold, readback_gate_released, texture_select_wait, texture_select_hold, textures_visited, texture_dirty_tests, texture_matches, textures_retained, + vram_gate_wait, vram_device, vram_unmap_poll, vram_state, vram_queue_wait, vram_retirement, + vram_calls, vram_mapping_waits, vram_reclaim_passes, vram_retirement_passes, ] = d; let ms = |us: u64| us / 1000; let sparse = queue_wait.saturating_add(maintenance).saturating_add(scan).saturating_add(upload).saturating_add(upload_wait); let texture_select = texture_select_wait.saturating_add(texture_select_hold); + let vram = vram_gate_wait + .saturating_add(vram_device) + .saturating_add(vram_unmap_poll) + .saturating_add(vram_state) + .saturating_add(vram_queue_wait) + .saturating_add(vram_retirement); format!( - "looks before submits ({secs} s): {looks} looks did {} ms active work ({:.1} % of the time) after {} ms waiting for the refresh turn: write-watch {} ms ({:.1} MB in {:.1} ranges/look, {pages} pages written); texture select wait/hold {}/{} ms ({textures_visited} visited, {texture_dirty_tests} dirty-tested, {texture_matches} matched, {textures_retained} retained); sparse queue wait/fence+state/scan/upload/ownership wait {}/{}/{}/{}/{} ms ({runs} runs, {:.1} MB zero/dirty bytes); upload gate submit wait/hold {}/{} ms, readback wait/hold/released wait+reacquire {}/{}/{} ms; other active work {} ms", + "looks before submits ({secs} s): {looks} looks did {} ms active work ({:.1} % of the time) after {} ms waiting for the refresh turn: write-watch {} ms ({:.1} MB in {:.1} ranges/look, {pages} pages written); texture select wait/hold {}/{} ms ({textures_visited} visited, {texture_dirty_tests} dirty-tested, {texture_matches} matched, {textures_retained} retained); sparse queue wait/fence+state/scan/upload/ownership wait {}/{}/{}/{}/{} ms ({runs} runs, {:.1} MB zero/dirty bytes); VRAM gate/device/unmap poll/state/queue wait/retire {}/{}/{}/{}/{}/{} ms ({vram_calls} calls, {vram_mapping_waits} mapping waits, {vram_reclaim_passes} reclaim passes, {vram_retirement_passes} retirement passes); upload gate submit wait/hold {}/{} ms, readback wait/hold/released wait+reacquire {}/{}/{} ms; other active work {} ms", ms(active), active as f64 / (secs.max(1) * 10_000) as f64, ms(refresh_wait), @@ -3844,12 +3883,18 @@ pub fn look_line(d: [u64; LOOK_FIELDS], secs: u64) -> String { ms(upload), ms(upload_wait), transfer_bytes as f64 / (1 << 20) as f64, + ms(vram_gate_wait), + ms(vram_device), + ms(vram_unmap_poll), + ms(vram_state), + ms(vram_queue_wait), + ms(vram_retirement), ms(submit_gate_wait), ms(submit_gate_hold), ms(readback_gate_wait), ms(readback_gate_hold), ms(readback_gate_released), - ms(active.saturating_sub(watch.saturating_add(sparse).saturating_add(texture_select))) + ms(active.saturating_sub(watch.saturating_add(sparse).saturating_add(texture_select).saturating_add(vram))) ) } @@ -3974,6 +4019,9 @@ unsafe fn poll_retirement_fences() -> Vec<(ID3D12Fence, u64)> { /// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video /// memory, and `queue` GPU-waits for that and for new tile mappings. pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize, mut look: Option<&mut LookSample>) -> PreparationOutcome { + if look.is_some() { + super::vram::begin_before_execute_timing(); + } let q = queue.as_raw() as usize; let t0 = look.is_some().then(std::time::Instant::now); let queue_gate = WAIT_GATES.lock().unwrap().entry(q).or_default().clone(); @@ -4342,12 +4390,23 @@ mod tests { 8_000, 1_200, 1_190, + 1_000, + 2_000, + 3_000, + 4_000, + 5_000, + 6_000, + 240, + 8, + 2, + 1, ], 2); assert!(line.contains("240 looks did 830 ms active work (41.5 % of the time) after 120 ms waiting"), "{line}"); assert!(line.contains("write-watch 610 ms (1641.0 MB in 69.0 ranges/look, 4800 pages written)"), "{line}"); assert!(line.contains("texture select wait/hold 7/13 ms (24000 visited, 8000 dirty-tested, 1200 matched, 1190 retained)"), "{line}"); assert!(line.contains("sparse queue wait/fence+state/scan/upload/ownership wait 10/30/40/40/20 ms (90 runs, 96.0 MB zero/dirty bytes)"), "{line}"); - assert!(line.contains("upload gate submit wait/hold 5/105 ms, readback wait/hold/released wait+reacquire 3/70/12 ms; other active work 60 ms"), "{line}"); + assert!(line.contains("VRAM gate/device/unmap poll/state/queue wait/retire 1/2/3/4/5/6 ms (240 calls, 8 mapping waits, 2 reclaim passes, 1 retirement passes)"), "{line}"); + assert!(line.contains("upload gate submit wait/hold 5/105 ms, readback wait/hold/released wait+reacquire 3/70/12 ms; other active work 39 ms"), "{line}"); let idle = look_line([0; LOOK_FIELDS], 2); assert!(idle.contains("0 looks did 0 ms active work (0.0 % of the time) after 0 ms waiting"), "{idle}"); assert!(idle.contains("0.0 MB in 0.0 ranges/look"), "{idle}"); @@ -4373,6 +4432,24 @@ mod tests { assert_eq!(sample.0[TEXTURE_SELECT_WAIT_US..=TEXTURES_RETAINED], [7, 13, 101, 79, 11, 10]); } + #[test] + fn vram_metrics_keep_phases_and_counts_distinct() { + let mut sample = LookSample::default(); + note_vram_before_execute(&mut sample, super::super::vram::BeforeExecuteTiming { + gate_wait: std::time::Duration::from_micros(1), + device: std::time::Duration::from_micros(2), + unmap_poll: std::time::Duration::from_micros(3), + state: std::time::Duration::from_micros(4), + queue_wait: std::time::Duration::from_micros(5), + retirement: std::time::Duration::from_micros(6), + calls: 7, + mapping_waits: 8, + reclaim_passes: 9, + retirement_passes: 10, + }); + assert_eq!(sample.0[VRAM_GATE_WAIT_US..=VRAM_RETIREMENT_PASSES], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + } + #[test] fn upload_gate_times_accumulate_into_distinct_submit_and_readback_fields() { let mut sample = [0; LOOK_FIELDS]; diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 921e9596cd..e760babc57 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1477,6 +1477,63 @@ fn wait_gates() -> &'static Mutex>>> { GATES.get_or_init(|| Mutex::new(HashMap::new())) } +/// CPU time inside the residency work one `XCL_ACTIVITY` look caused. The look owns this +/// thread-local accumulator; internal uploads on the same thread join the same sample without +/// adding shared counters to the submission path. +#[derive(Default)] +pub(super) struct BeforeExecuteTiming { + pub gate_wait: std::time::Duration, + pub device: std::time::Duration, + pub unmap_poll: std::time::Duration, + pub state: std::time::Duration, + pub queue_wait: std::time::Duration, + pub retirement: std::time::Duration, + pub calls: usize, + pub mapping_waits: usize, + pub reclaim_passes: usize, + pub retirement_passes: usize, +} + +thread_local! { + static BEFORE_EXECUTE_TIMING: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// Begin an activity look's residency measurement. Retried sparse preparation reaches this more +/// than once, so an already-active accumulator is preserved until `take_before_execute_timing`. +pub(super) fn begin_before_execute_timing() { + BEFORE_EXECUTE_TIMING.with(|timing| { + let mut timing = timing.borrow_mut(); + if timing.is_none() { + *timing = Some(BeforeExecuteTiming::default()); + } + }); +} + +pub(super) fn take_before_execute_timing() -> Option { + BEFORE_EXECUTE_TIMING.with(|timing| timing.borrow_mut().take()) +} + +fn before_execute_timing_active() -> bool { + BEFORE_EXECUTE_TIMING.with(|timing| timing.borrow().is_some()) +} + +fn record_before_execute_timing(measured: BeforeExecuteTiming) { + BEFORE_EXECUTE_TIMING.with(|timing| { + let mut timing = timing.borrow_mut(); + let Some(total) = timing.as_mut() else { return }; + total.gate_wait += measured.gate_wait; + total.device += measured.device; + total.unmap_poll += measured.unmap_poll; + total.state += measured.state; + total.queue_wait += measured.queue_wait; + total.retirement += measured.retirement; + total.calls = total.calls.saturating_add(measured.calls); + total.mapping_waits = total.mapping_waits.saturating_add(measured.mapping_waits); + total.reclaim_passes = total.reclaim_passes.saturating_add(measured.reclaim_passes); + total.retirement_passes = total.retirement_passes.saturating_add(measured.retirement_passes); + }); +} + fn reserve_page_wait(waited: &mut HashMap, queue: usize, value: u64) -> bool { if value == 0 || waited.get(&queue).copied().unwrap_or(0) >= value { return false; @@ -2306,22 +2363,51 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla /// per second per device) retire completely empty 64 MiB VRAM pool heaps and idle arenas behind /// per-queue GPU fence signals across all live queues on the device. pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { + let measure = before_execute_timing_active(); + let mut measured = BeforeExecuteTiming { calls: measure as usize, ..Default::default() }; + let gate_started = measure.then(std::time::Instant::now); let queue_key = queue.as_raw() as usize; let wait_gate = wait_gates().lock().unwrap().entry(queue_key).or_default().clone(); let _queue_serial = wait_gate.lock().unwrap(); + if let Some(started) = gate_started { + measured.gate_wait = started.elapsed(); + } + let device_started = measure.then(std::time::Instant::now); let mut dev: Option = None; if queue.GetDevice(&mut dev).is_err() { + if let Some(started) = device_started { + measured.device = started.elapsed(); + } + if measure { + record_before_execute_timing(measured); + } return; } - let Some(dev) = dev else { return }; + let Some(dev) = dev else { + if let Some(started) = device_started { + measured.device = started.elapsed(); + } + if measure { + record_before_execute_timing(measured); + } + return; + }; + if let Some(started) = device_started { + measured.device = started.elapsed(); + } let dev_key = dev.as_raw() as usize; let now = std::time::Instant::now(); + let poll_started = measure.then(std::time::Instant::now); let unmap_completions = held_unmap_completions(dev_key); + if let Some(started) = poll_started { + measured.unmap_poll = started.elapsed(); + } let mut newly_reclaimed = Vec::new(); let mut do_reclaim = false; let mut unmap_mark: Option<(ID3D12Fence, u64)> = None; let mut completed_unmaps = Vec::new(); let mut wait = None; + let state_started = measure.then(std::time::Instant::now); { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { @@ -2342,17 +2428,35 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { } } } + if let Some(started) = state_started { + measured.state = started.elapsed(); + measured.mapping_waits = wait.is_some() as usize; + measured.reclaim_passes = do_reclaim as usize; + } + let queue_wait_started = measure.then(std::time::Instant::now); if let Some((fence, value)) = wait { let _ = super::real::native_queue_wait(queue, &fence, value); super::list_x::note_internal_wait(queue_key, "texture page mappings", &fence, value); } + if let Some(started) = queue_wait_started { + measured.queue_wait = started.elapsed(); + } + let retirement_started = measure.then(std::time::Instant::now); if do_reclaim { newly_reclaimed.extend(ARENAS.lock().unwrap().sweep_dropped_for(dev_key, now)); } - if do_reclaim || !newly_reclaimed.is_empty() || RETIRING_BATCHES.load(std::sync::atomic::Ordering::Acquire) > 0 { + let retire = do_reclaim || !newly_reclaimed.is_empty() || RETIRING_BATCHES.load(std::sync::atomic::Ordering::Acquire) > 0; + if retire { retire_heaps_and_sweep(&dev, dev_key, newly_reclaimed, unmap_mark, Some(queue)); } drop(completed_unmaps); + if let Some(started) = retirement_started { + measured.retirement = started.elapsed(); + measured.retirement_passes = retire as usize; + } + if measure { + record_before_execute_timing(measured); + } } #[cfg(test)] @@ -2633,6 +2737,31 @@ mod tests { receipt.fence.load(std::sync::atomic::Ordering::Relaxed) >= receipt.value } + #[test] + fn before_execute_timing_is_one_thread_local_activity_sample() { + drop(take_before_execute_timing()); + assert!(!before_execute_timing_active()); + begin_before_execute_timing(); + begin_before_execute_timing(); + record_before_execute_timing(BeforeExecuteTiming { + gate_wait: std::time::Duration::from_micros(3), + calls: 1, + mapping_waits: 1, + ..Default::default() + }); + record_before_execute_timing(BeforeExecuteTiming { + state: std::time::Duration::from_micros(7), + calls: 1, + reclaim_passes: 1, + ..Default::default() + }); + let timing = take_before_execute_timing().unwrap(); + assert_eq!(timing.gate_wait, std::time::Duration::from_micros(3)); + assert_eq!(timing.state, std::time::Duration::from_micros(7)); + assert_eq!((timing.calls, timing.mapping_waits, timing.reclaim_passes), (2, 1, 1)); + assert!(!before_execute_timing_active()); + } + #[test] fn shared_view_epochs_cancel_retire_and_remain_monotonic() { let mut epochs = SharedViewEpochs::new();