A timeline of a few frames, with the chain each present came out of (VICTORY_TIMELINE)

Diagnostics only. VICTORY_TIMELINE=<file> records three frames (or
VICTORY_TIMELINE_FRAMES) after VICTORY_TIMELINE_AT seconds and writes a
Chrome trace and a text summary: spans of our work, the waits and wake-ups
of the title's threads (its imports) and of ours (our import table), long
kernel calls on the address space, and when each submission ran on the card.
The summary walks back from each present through who waited on whom.
Nothing is wrapped without the variable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 008de5f9ffcef132079b1af8b7f4f1c22235cee9)
This commit is contained in:
local committed 2026-11-25 07:46:13 -06:00
1 parent faf5687af9
commit 7c62f5b707
25 files changed
+2506 -7

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@ diagnostics = []
workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
windows = { workspace = true, features = [
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D_Fxc",
+122
View File
@@ -0,0 +1,122 @@
//! Diagnostics: switches that change while the title runs, so that one run
//! measures both sides in the same scene. `VICTORY_AB=<seconds>,<switch>[,<switch>..]`:
//! every so many seconds, at a present, the next phase begins; switch number
//! n is on in the phases whose number has bit n, so that all combinations
//! come one after another, again and again. Each phase's frame times are
//! logged at its end (the frames of its first second left out). A switch
//! named here does not go by its own variable any more.
use std::sync::atomic::{AtomicU32, Ordering::Relaxed};
use std::sync::{Mutex, OnceLock};
struct Asked {
seconds: f64,
switches: Vec<String>,
}
fn parse(text: &str) -> Option<Asked> {
let mut parts = text.split(',').map(str::trim);
let seconds = parts.next()?.parse::<f64>().ok().filter(|s| *s > 1.0)?;
let switches: Vec<String> = parts.filter(|s| !s.is_empty()).map(str::to_string).collect();
(!switches.is_empty() && switches.len() <= 8).then_some(Asked { seconds, switches })
}
fn asked() -> Option<&'static Asked> {
static ASKED: OnceLock<Option<Asked>> = OnceLock::new();
ASKED.get_or_init(|| parse(&std::env::var("VICTORY_AB").ok()?)).as_ref()
}
/// The switches that are on now, a bit each.
static BITS: AtomicU32 = AtomicU32::new(0);
/// Whether `switch` is on now, if it is one of those that change.
pub(crate) fn pick(switch: &str) -> Option<bool> {
let n = asked()?.switches.iter().position(|s| s == switch)?;
Some(BITS.load(Relaxed) >> n & 1 != 0)
}
/// What the run has seen of the phase under way.
struct Phase {
started: std::time::Instant,
number: u64,
began: std::time::Instant,
last: std::time::Instant,
drawn: u64,
frames: Vec<f32>,
draws: u64,
}
/// The frames' mean, median and nine tenths.
fn summary(frames: &mut [f32]) -> (f32, f32, f32) {
if frames.is_empty() {
return (0.0, 0.0, 0.0);
}
let mean = frames.iter().sum::<f32>() / frames.len() as f32;
frames.sort_by(f32::total_cmp);
(mean, frames[frames.len() / 2], frames[frames.len() * 9 / 10])
}
/// The title's present ends on this thread. `change`: called when another
/// phase begins, before any switch changes, with what `switch` is and what it
/// will be.
pub(crate) fn presented(change: impl Fn(&str, bool, bool)) {
let Some(asked) = asked() else {
return;
};
static PHASE: Mutex<Option<Phase>> = Mutex::new(None);
let now = std::time::Instant::now();
let drawn = crate::draw::drawn();
let mut phase = PHASE.lock().unwrap_or_else(|e| e.into_inner());
let p = phase.get_or_insert_with(|| Phase {
started: now,
number: 0,
began: now,
last: now,
drawn,
frames: Vec::new(),
draws: 0,
});
if (now - p.began).as_secs_f64() > 1.0 {
p.frames.push((now - p.last).as_secs_f32() * 1000.0);
p.draws += drawn.saturating_sub(p.drawn);
}
(p.last, p.drawn) = (now, drawn);
let number = ((now - p.started).as_secs_f64() / asked.seconds) as u64;
if number == p.number {
return;
}
let bits = |number: u64| (number % (1 << asked.switches.len())) as u32;
let (was, will) = (bits(p.number), bits(number));
let (mean, median, most) = summary(&mut p.frames);
let on: Vec<&str> = asked.switches.iter().enumerate().filter(|(n, _)| was >> n & 1 != 0).map(|(_, s)| s.as_str()).collect();
tracing::info!(
"A/B phase {} bits {was} on [{}]: {} frames, mean {mean:.1} ms, median {median:.1}, p90 {most:.1}, {:.0} draws a frame",
p.number,
on.join(" "),
p.frames.len(),
p.draws as f64 / p.frames.len().max(1) as f64
);
for (n, switch) in asked.switches.iter().enumerate() {
change(switch, was >> n & 1 != 0, will >> n & 1 != 0);
}
BITS.store(will, Relaxed);
(p.number, p.began, p.draws) = (number, now, 0);
p.frames.clear();
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn switches_and_seconds_are_read_and_frames_summed_up() {
let a = parse("10, VICTORY_A,VICTORY_B").unwrap();
assert_eq!((a.seconds, a.switches), (10.0, vec!["VICTORY_A".to_string(), "VICTORY_B".to_string()]));
assert!(parse("10").is_none());
assert!(parse("x,VICTORY_A").is_none());
assert!(parse("0,VICTORY_A").is_none());
assert_eq!(summary(&mut [30.0, 10.0, 20.0]), (20.0, 20.0, 30.0));
assert_eq!(summary(&mut []), (0.0, 0.0, 0.0));
assert_eq!(pick("VICTORY_NONE_SUCH"), None);
}
}
+3 -1
View File
@@ -981,7 +981,9 @@ fn submitter(all: &mut Vec<(u32, Submitter)>, id: u32) -> &mut Submitter {
/// A list call on this thread that began at `started` has returned.
pub(crate) fn recorded(started: std::time::Instant) {
let ns = started.elapsed().as_nanos() as u64;
let took = started.elapsed();
let ns = took.as_nanos() as u64;
crate::timeline::called(took);
add(C::RecordCalls, 1);
add(C::RecordNs, ns);
if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) {
+2
View File
@@ -249,6 +249,8 @@ pub(crate) fn begin_sync_heaps() -> SyncedHeaps {
last = std::time::Instant::now();
Over
});
let _round =
crate::timeline::span(if asked { "the heaps' records, for a submission" } else { "the heaps' records, early" });
let _ = std::panic::catch_unwind(sync_heaps);
}
});
+3
View File
@@ -1846,6 +1846,7 @@ impl State {
return Some(gpu);
}
let started = std::time::Instant::now();
let mut stage = crate::timeline::span("the heap pass: begun, or done here");
if crate::host::aside::on() {
let at = std::ptr::from_ref(heap) as usize;
list.refreshes_coming(move || {
@@ -1860,7 +1861,9 @@ impl State {
}
#[cfg(feature = "diagnostics")]
let refreshed = std::time::Instant::now();
stage.next("the heap pass: textures");
self.heap_textures(list, heap, host);
stage.end();
#[cfg(feature = "diagnostics")]
HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed);
HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed);
+13 -1
View File
@@ -85,6 +85,13 @@ extern "system" fn release(this: This) -> u32 {
pub(crate) extern "system" fn completed(this: This) -> u64 {
fence(this).value.load(Ordering::Acquire)
}
/// The title's `GetCompletedValue`.
extern "system" fn completed_called(this: This) -> u64 {
let value = completed(this);
#[cfg(all(windows, feature = "diagnostics"))]
crate::timeline::polled(this as usize, value);
value
}
extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT {
let fence = fence(this);
let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner());
@@ -94,6 +101,8 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c
}
return S_OK;
}
#[cfg(all(windows, feature = "diagnostics"))]
crate::timeline::told("an event asked for", this as usize, value);
if event.is_null() {
// With submissions sent to the card and not waited for
// (`crate::host::late`) the signal may be behind them: they are
@@ -120,6 +129,8 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c
/// Moves the fence to `value` and sets the events that waited for it.
pub(crate) fn set(this: This, value: u64) {
let fence = fence(this);
#[cfg(all(windows, feature = "diagnostics"))]
crate::timeline::told("a fence set", this as usize, value);
let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner());
fence.value.store(value, Ordering::Release);
waiters.retain(|&(wanted, event)| {
@@ -131,6 +142,7 @@ pub(crate) fn set(this: This, value: u64) {
});
}
pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
let _called = crate::timeline::span("a fence set");
set(this, value);
// A queue may have waited for it: what it held runs now.
#[cfg(windows)]
@@ -153,7 +165,7 @@ static FUNCTIONS: Table<24> = {
f[0] = query as *const ();
f[2] = release as *const ();
f[7] = object::parent_device as *const (); // 0x38
f[8] = completed as *const (); // 0x40
f[8] = completed_called as *const (); // 0x40
f[9] = set_event_on_completion as *const (); // 0x48
f[10] = signal as *const (); // 0x50
f[11] = creation_flags as *const (); // 0x58
+1
View File
@@ -148,6 +148,7 @@ pub(crate) extern "system" fn wait(
tick -= 1;
wait = Duration::ZERO;
}
let _called = crate::timeline::span("the title's frame wait");
let hr = if wait > limit {
std::thread::sleep(limit);
TIMEOUT
+78
View File
@@ -2894,7 +2894,9 @@ fn late_helper() {
}
};
let Some(target) = target else {
let mut helping = crate::timeline::span("helper: landed lists reset and given back");
land();
helping.next("helper: looking at what queues hold");
crate::queue::release_held(false);
continue;
};
@@ -2903,6 +2905,8 @@ fn late_helper() {
// SAFETY: our fence and event.
unsafe {
if host.fence.SetEventOnCompletion(target, event).is_ok() {
#[cfg(feature = "diagnostics")]
let _card = crate::timeline::card_wait(Some(target));
WaitForSingleObject(event, INFINITE);
}
}
@@ -2960,6 +2964,15 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
LATE_STATS[why].fetch_add(1, Ordering::Relaxed);
let was_working = working(false);
let waiting = std::time::Instant::now();
let _waiting = crate::timeline::span(match why {
WHY_SYNC => "waiting for landings: everything (a present, the sweep)",
WHY_VALUE => "waiting for landings: a memory value",
WHY_STALE => "waiting for landings: title memory changed under shader writes",
WHY_READ => "waiting for landings: title memory read",
WHY_MOST => "waiting for landings: lists in the air",
WHY_FENCE => "waiting for landings: a blocking fence wait",
_ => "waiting for landings: another reason",
});
while !done(&line) {
line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner());
}
@@ -3051,6 +3064,8 @@ fn relay_worker() {
Ok(items) => host.relay_land(items, &mut fetch),
Err(target) => {
let waiting = std::time::Instant::now();
#[cfg(feature = "diagnostics")]
let _card = crate::timeline::card_wait(Some(target));
// SAFETY: the host's fence and this thread's event.
let waited = unsafe {
host.fence.SetEventOnCompletion(target, event).map(|()| {
@@ -3281,6 +3296,10 @@ pub(crate) use send::{goes_as_words, words_under};
pub(crate) mod spans;
mod torn;
pub(crate) mod upcheck;
#[cfg(feature = "diagnostics")]
mod stamps;
#[cfg(feature = "diagnostics")]
pub(crate) use stamps::{timeline_ready, timeline_restart, timeline_stamps};
#[cfg(test)]
mod late_tests {
@@ -4300,11 +4319,14 @@ impl Host {
}
list.Close()?;
let lists = [Some(list.cast::<ID3D12CommandList>()?)];
let _fetching = crate::timeline::span("landing: fetching pieces");
if let Some(queue) = &copy_queue {
queue.ExecuteCommandLists(&lists);
queue.Signal(&fence, sent)?;
meanwhile();
fence.SetEventOnCompletion(sent, event)?;
#[cfg(feature = "diagnostics")]
let _card = crate::timeline::card_wait(None);
WaitForSingleObject(event, INFINITE);
return Ok(behind);
}
@@ -4318,6 +4340,8 @@ impl Host {
self.queue.Signal(&fence, sent)?;
meanwhile();
fence.SetEventOnCompletion(sent, event)?;
#[cfg(feature = "diagnostics")]
let _card = crate::timeline::card_wait(None);
WaitForSingleObject(event, INFINITE);
Ok(after)
})()
@@ -4336,6 +4360,7 @@ impl Host {
CARD_STATS[6].fetch_add(us, Ordering::Relaxed);
}
let merging = std::time::Instant::now();
let _merging = crate::timeline::span("landing: merging fetched pieces");
let mut written = 0;
if land::on() {
let titles: Vec<(usize, usize)> =
@@ -4404,6 +4429,7 @@ impl Host {
/// is complete before the title is told anything.
fn relay_land(&self, items: Vec<Late>, fetch: &mut Option<RelayFetch>) {
let landing = std::time::Instant::now();
let mut stage = crate::timeline::span("landing: what is to be looked through");
{
let flights: Vec<&Flight> = items
.iter()
@@ -4436,12 +4462,16 @@ impl Host {
}
}
let mut hand_back = relay_hand_back(&back);
stage.next("landing: copies in the card's memory");
self.relay_card_back(&plans, fetch, &mut || {
if crate::land::on() {
let _looking = crate::timeline::span("landing: looking through copies, beside the fetch");
hand_back.look(crate::land::stat::SCAN_BESIDE);
}
});
stage.next("landing: copies in the PC's memory");
hand_back.merge();
stage.next("landing: ranges done with");
let finishing = std::time::Instant::now();
// Only now, and flight by flight: a range another flight
// in the air declared too stays closed to refreshes.
@@ -4457,6 +4487,7 @@ impl Host {
}
}
// In the order given: what tells the title the card is done.
stage.next("landing: read-backs, telling the title");
let mut last = 0;
let mut landed = Vec::new();
let mut telling = std::time::Instant::now();
@@ -4490,6 +4521,7 @@ impl Host {
FINISHED.store(last, Ordering::Release);
bury(last);
}
stage.next("landing: the rest");
self.log_messages();
crate::land::spent(crate::land::stat::REST, telling);
RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed);
@@ -4726,6 +4758,7 @@ impl Host {
LINE_MOVED.notify_one();
}
drop(submitted);
let _landing = crate::timeline::span("landed lists reset and given back");
land();
}
@@ -4791,6 +4824,7 @@ impl Host {
return;
}
let was_working = working(true);
let _settling = crate::timeline::span("settling flights");
let mut counted = false;
loop {
let items = {
@@ -4820,6 +4854,8 @@ impl Host {
match self.fence.SetEventOnCompletion(*submitted, self.event) {
Ok(()) => {
working(false);
#[cfg(feature = "diagnostics")]
let _card = crate::timeline::card_wait(Some(*submitted));
WaitForSingleObject(self.event, INFINITE);
stood(waiting);
working(true);
@@ -4962,6 +4998,7 @@ impl Host {
crate::copystat::submission_begins();
// One submission at a time from preparation to copy-back: snapshots
// and the ranges shaders write are per host copy, not per submission.
let mut stage = crate::timeline::span("submit: the submission lock");
let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
let was_working = working(true);
submitting(1, runs.len());
@@ -4969,6 +5006,7 @@ impl Host {
let ahead = Split::begin();
#[cfg(feature = "diagnostics")]
SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed);
stage.next("submit: steps given to the card");
// Flights in the air ([`late`]): a submission that is waited for
// settles them first, one sent ahead only if preparing it reads
// what they write.
@@ -4976,6 +5014,7 @@ impl Host {
let own = if late { self.card_steps(runs) } else { None };
#[cfg(feature = "diagnostics")]
ahead.part(12);
stage.next("submit: waiting for flights it reads from");
if !late {
self.settle(&mut submitted, WHY_SYNC);
} else if own.is_none()
@@ -5005,6 +5044,7 @@ impl Host {
}
None => runs,
};
stage.next("submit: the sweep");
let behind = late && flying();
// Before this submission counts as started: what the sweep lets go
// of is named by no list, and nothing runs now (behind flights the
@@ -5028,6 +5068,7 @@ impl Host {
SWEPT.store(now_ms(), Ordering::Relaxed);
}
let behind = late && flying();
stage.next("submit: gathering what to ask about");
let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1;
// The ranges shaders write are counted for it (with the relay).
crate::shadow::preparing(this_submission);
@@ -5067,9 +5108,11 @@ impl Host {
let ranges: Vec<(usize, usize)> = spans.into_values().collect();
#[cfg(feature = "diagnostics")]
SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed);
stage.next("submit: asking the write watch");
crate::watch::ask_once(&ranges);
#[cfg(feature = "diagnostics")]
split.part(0);
stage.next("submit: title bytes under flights' writes");
// Behind flights: the title wrote memory that a flight's shaders
// may write too, and this submission refreshes it. The flights
// are settled, and the asking made again: the copy-back wrote
@@ -5095,9 +5138,11 @@ impl Host {
split.part(1);
// What flights in the air may write.
let air = line().written.clone();
stage.next("submit: refreshes ahead of writes");
if ahead_of_writes() {
batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i)));
}
stage.next("submit: the lists' steps");
for list in runs {
list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
firsts.push(lists.len());
@@ -5107,10 +5152,12 @@ impl Host {
lists.push(list.list.cast().ok());
}
batch.fill();
stage.next("submit: the last refreshes");
batch.flush();
crate::watch::ask_once_end();
#[cfg(feature = "diagnostics")]
split.part(2);
stage.next("submit: snapshots");
// The snapshots of the ranges shaders may write, if they were left
// for now (`crate::shadow::wide_back`): the refreshes are done, the
// lists have not gone to the card.
@@ -5123,6 +5170,7 @@ impl Host {
}
#[cfg(feature = "diagnostics")]
split.part(3);
stage.next("submit: copies in the card's memory");
// Copies in the card's memory: what changed on their CPU side goes
// up ahead of the lists, and a compare of what the shaders may
// write follows them in the same submission.
@@ -5149,6 +5197,7 @@ impl Host {
}
#[cfg(feature = "diagnostics")]
split.part(4);
stage.next("submit: waiting for the heaps' records");
drop(heaps_synced);
// The slots that waited for a texture's host copy, before the
// lists that may read them run.
@@ -5156,6 +5205,18 @@ impl Host {
#[cfg(feature = "diagnostics")]
split.part(15);
let prepared = std::time::Instant::now();
stage.next("submit: sending");
// When it runs on the card, for the timeline.
#[cfg(feature = "diagnostics")]
let stamp = stamps::take();
#[cfg(feature = "diagnostics")]
if let Some((ahead, behind)) = stamp.and_then(stamps::lists) {
lists.insert(0, Some(ahead));
lists.push(Some(behind));
firsts.iter_mut().for_each(|first| *first += 1);
}
#[cfg(feature = "diagnostics")]
let sending = crate::timeline::ticks();
if late {
*submitted += 1;
#[cfg(feature = "diagnostics")]
@@ -5169,7 +5230,10 @@ impl Host {
self.queue.Signal(&self.fence, *submitted)
};
awake::sent(&self.device);
#[cfg(feature = "diagnostics")]
crate::timeline::sent(sending, *submitted, stamp);
self.card_sent();
stage.next("submit: noting what is in the air");
if let Err(e) = signalled {
fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
}
@@ -5216,9 +5280,13 @@ impl Host {
.queue
.Signal(&self.fence, *submitted)
.and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
#[cfg(feature = "diagnostics")]
crate::timeline::sent(sending, *submitted, stamp);
match waited {
Ok(()) => {
working(false);
#[cfg(feature = "diagnostics")]
let _card = crate::timeline::card_wait(Some(*submitted));
WaitForSingleObject(self.event, INFINITE);
stood(started);
working(true);
@@ -5285,6 +5353,7 @@ impl Host {
));
}
submitting(3, runs.len());
stage.next("submit: copying back");
// What shaders wrote goes back before the bottom-of-pipe writes,
// which tell the title the GPU is done; each range once per
// submission, however many dispatches declared it (the world's
@@ -5633,6 +5702,7 @@ impl HostList {
}
pub(crate) fn close(&self) {
let _closing = crate::timeline::span("closing a host list");
self.twins_to_depth();
let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
if let Some((scratch, _)) = scratch {
@@ -5685,6 +5755,7 @@ impl HostList {
pub(crate) fn reset(&self) {
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
let _resetting = crate::timeline::span("resetting a host list");
self._alive.used();
*self.coming.lock().unwrap_or_else(|e| e.into_inner()) = None;
*self.deferred() = Deferred::default();
@@ -6622,6 +6693,7 @@ impl HostList {
if matches!(step, Step::Run(_)) {
batch.title_written();
}
let _step = crate::timeline::span("a step of ours");
work();
// It wrote title memory, where is not known here: the
// submission's one asking ends, later refreshes ask anew.
@@ -7052,6 +7124,7 @@ impl Batch {
/// Brings `[from, to)` of a copy up to date, timed.
fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) {
let started = std::time::Instant::now();
let _one = crate::timeline::span("a copy's refresh");
let copied = shadow.update(from, to - from);
let us = started.elapsed().as_micros() as u64;
#[cfg(feature = "diagnostics")]
@@ -7155,6 +7228,7 @@ impl Batch {
self.due.drain(..).for_each(|staging| staging.refresh());
return;
}
let _textures = crate::timeline::span("textures brought up to date");
// The time counted is the time it took, not the threads' sum.
let started = std::time::Instant::now();
let before = PREPARING[2].load(Ordering::Relaxed);
@@ -7172,6 +7246,7 @@ impl Batch {
}
#[cfg(feature = "diagnostics")]
let (began, all) = (std::time::Instant::now(), self.refreshes.len());
let _flush = crate::timeline::span("refreshes of copies");
self.flush_all();
#[cfg(feature = "diagnostics")]
{
@@ -8095,8 +8170,11 @@ impl Host {
}
#[cfg(feature = "diagnostics")]
crate::replay::record::present(texture, state);
let mut showing = crate::timeline::span("the host's Present");
let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
showing.next("the frame meter");
p.meter.frame(p.hwnd);
showing.end();
#[cfg(feature = "diagnostics")]
return Some(probe.is_some_and(|b| crate::capture::black(&b)));
#[cfg(not(feature = "diagnostics"))]
+2
View File
@@ -25,6 +25,7 @@ impl Coming {
/// What was found.
pub(crate) fn wait(&self) -> Vec<Refresh> {
let began = std::time::Instant::now();
let _waiting = crate::timeline::span("a list's close waits for the heap's views");
let mut found = self.0.lock().unwrap_or_else(|e| e.into_inner());
loop {
if let Some(found) = found.take() {
@@ -56,6 +57,7 @@ pub(crate) fn begin(work: impl FnOnce() -> Vec<Refresh> + Send + 'static) -> std
let told = coming.clone();
let job: Job = Box::new(move || {
// (However it ends, the list that waits goes on.)
let _aside = crate::timeline::span("beside: the heap's views");
let found = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)).unwrap_or_default();
told.found(found);
});
+187
View File
@@ -0,0 +1,187 @@
//! Diagnostics: when each submission began and ended on the card, for the
//! timeline (`crate::timeline`). Lists made ahead, each a timestamp and its
//! way into memory the PC reads, go ahead of and behind every submission
//! while the timeline records.
use std::sync::atomic::{AtomicUsize, Ordering};
use windows::core::Interface;
use super::*;
/// Submissions stamped (three frames have some hundred and twenty).
const MOST: usize = 1024;
struct Stamps {
/// The first half the lists that go ahead, then those that go behind.
lists: Vec<ID3D12CommandList>,
/// The mapping of what they write, a tick count each.
back: usize,
/// Keeps it all.
_kept: (ID3D12CommandAllocator, ID3D12QueryHeap, ID3D12Resource),
/// The card's ticks and the PC's counter at one moment.
calibrated: (u64, u64),
}
// SAFETY: free-threaded objects, and a mapping only read.
unsafe impl Send for Stamps {}
// SAFETY: as above.
unsafe impl Sync for Stamps {}
static STAMPS: OnceLock<Option<Stamps>> = OnceLock::new();
static NEXT: AtomicUsize = AtomicUsize::new(0);
/// Makes the lists, before the recording begins.
pub(crate) fn timeline_ready() {
let Some(host) = host() else {
return;
};
STAMPS.get_or_init(|| match host.make_stamps() {
Ok(stamps) => Some(stamps),
Err(e) => {
tracing::warn!(error = %e, "the timeline is without the card's times");
None
}
});
}
/// The place of the next submission's stamps, if the timeline records.
pub(super) fn take() -> Option<usize> {
if !crate::timeline::on() || STAMPS.get()?.is_none() {
return None;
}
let at = NEXT.fetch_add(1, Ordering::Relaxed);
(at < MOST).then_some(at)
}
/// The list that goes ahead of the submission at `at`, and the one behind.
pub(super) fn lists(at: usize) -> Option<(ID3D12CommandList, ID3D12CommandList)> {
let stamps = STAMPS.get()?.as_ref()?;
Some((stamps.lists[at].clone(), stamps.lists[MOST + at].clone()))
}
/// By place, from when to when a submission ran on the card, in ticks of
/// the PC's counter. Once the card has run them.
pub(crate) fn timeline_stamps() -> Vec<(u64, u64)> {
times(NEXT.load(Ordering::Relaxed).min(MOST))
}
/// The stamps are used from the first again, for the next timeline.
pub(crate) fn timeline_restart() {
if let Some(Some(stamps)) = STAMPS.get() {
// SAFETY: the mapping holds twice `MOST` tick counts; the card wrote
// them some frames ago.
unsafe { std::ptr::write_bytes(stamps.back as *mut u8, 0, 16 * MOST) };
}
NEXT.store(0, Ordering::Relaxed);
}
/// The first `taken` of them.
fn times(taken: usize) -> Vec<(u64, u64)> {
let (Some(Some(stamps)), Some(host)) = (STAMPS.get(), host()) else {
return Vec::new();
};
let (mut card, mut pc) = (0, 0);
// SAFETY: plain queries; the mapping holds twice `MOST` tick counts.
let (frequency, back) = unsafe {
if host.queue.GetClockCalibration(&mut card, &mut pc).is_err() {
return Vec::new();
}
let frequency = host.queue.GetTimestampFrequency().unwrap_or(0);
(frequency, std::slice::from_raw_parts(stamps.back as *const u64, 2 * MOST))
};
if frequency == 0 {
return Vec::new();
}
// By the two calibrations, the card's clock as it ran between them.
let (card0, pc0) = stamps.calibrated;
let rate = match card.saturating_sub(card0) {
0 => 1e7 / frequency as f64,
passed => pc.saturating_sub(pc0) as f64 / passed as f64,
};
let place = |ticks: u64| (pc0 as f64 + (ticks as f64 - card0 as f64) * rate) as u64;
(0..taken)
.map(|at| match (back[at], back[MOST + at]) {
(0, _) | (_, 0) => (0, 0),
(from, to) => (place(from), place(to)),
})
.collect()
}
impl Host {
fn make_stamps(&self) -> windows::core::Result<Stamps> {
let Some((buffer, back)) = self.shared_buffer(16 * MOST as u64) else {
return Err(windows::core::Error::from(windows::Win32::Foundation::E_OUTOFMEMORY));
};
// SAFETY: plain object creation; a fresh mapping of that size.
unsafe {
std::ptr::write_bytes(back, 0, 16 * MOST);
let mut heap: Option<ID3D12QueryHeap> = None;
self.device.CreateQueryHeap(
&D3D12_QUERY_HEAP_DESC {
Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP,
Count: 2 * MOST as u32,
NodeMask: 0,
},
&mut heap,
)?;
let heap = heap.ok_or_else(windows::core::Error::empty)?;
let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
let mut lists = Vec::with_capacity(2 * MOST);
for at in 0..2 * MOST as u32 {
let list: ID3D12GraphicsCommandList =
self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
list.EndQuery(&heap, D3D12_QUERY_TYPE_TIMESTAMP, at);
list.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, at, 1, &buffer, u64::from(at) * 8);
list.Close()?;
lists.push(list.cast()?);
}
let (mut card, mut pc) = (0, 0);
self.queue.GetClockCalibration(&mut card, &mut pc)?;
Ok(Stamps {
lists,
back: back as usize,
_kept: (allocator, heap, buffer),
calibrated: (card, pc),
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// What goes ahead of and behind a submission says when it ran, by the
/// PC's own counter.
#[test]
fn a_submissions_times_are_the_pcs() {
let Some(host) = host() else {
return;
};
timeline_ready();
let Some((ahead, behind)) = lists(5) else {
return;
};
let sent = crate::timeline::ticks();
{
let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner());
*submitted += 1;
// SAFETY: closed lists; the fence and event are the host's, under
// its lock.
unsafe {
host.queue.ExecuteCommandLists(&[Some(ahead), Some(behind)]);
host.queue.Signal(&host.fence, *submitted).unwrap();
host.fence.SetEventOnCompletion(*submitted, host.event).unwrap();
WaitForSingleObject(host.event, INFINITE);
}
}
let done = crate::timeline::ticks();
let times = times(6);
assert_eq!(times[4], (0, 0), "not run");
let (from, to) = times[5];
// (The two clocks agree to some tens of microseconds.)
let near = 2_000;
assert!(from <= to && from + near >= sent && to <= done + near, "{sent} {from} {to} {done}");
}
}
+3
View File
@@ -254,8 +254,10 @@ impl Pool {
};
state.running += 1;
drop(state);
let working = crate::timeline::span("a landing's job");
// SAFETY: counted in `running`, so `each` has not returned.
let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { (*work.0)(i) }));
working.end();
state = self.state();
state.running -= 1;
state.panicked |= ran.is_err();
@@ -272,6 +274,7 @@ impl Pool {
(0..count).for_each(f);
return;
}
let _spread = crate::timeline::span("landing: spread over threads");
let _turn = self.turn.lock().unwrap_or_else(|e| e.into_inner());
// SAFETY: the lifetime is left out only until this call returns, and
// it does not before no helper is inside `f` and none can enter.
+3
View File
@@ -68,10 +68,13 @@ mod shadow;
mod tiles;
pub mod signature;
mod switch;
#[cfg(all(windows, feature = "diagnostics"))]
mod ab;
#[cfg(windows)]
mod tdr;
#[cfg(windows)]
mod texture;
pub mod timeline;
#[cfg(windows)]
mod upload;
#[cfg(windows)]
+2
View File
@@ -621,6 +621,7 @@ extern "system" fn list_type(this: This) -> u32 {
unsafe { (*this.cast::<List>()).kind }
}
extern "system" fn close(this: This) -> HRESULT {
let _called = crate::timeline::span("the title's Close");
#[cfg(windows)]
if let Some(host) = host_list(this) {
host.close();
@@ -631,6 +632,7 @@ extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT
if allocator.is_null() {
return E_INVALIDARG;
}
let _called = crate::timeline::span("the title's list Reset");
// A wait recorded and never submitted goes with the recording.
VALUE_WAITS
.lock()
+30
View File
@@ -320,6 +320,7 @@ pub(crate) fn release_held(all: bool) {
if lock(&WAITING).is_empty() {
return;
}
let _looking = crate::timeline::span("looking at what queues hold");
let _one = lock(&RELEASING);
loop {
let queues = lock(&WAITING).clone();
@@ -549,6 +550,9 @@ extern "system" fn execute(this: This, count: u32, lists: *const This) {
if lists.is_null() {
return;
}
let _called = crate::timeline::span("the title's ExecuteCommandLists");
#[cfg(all(windows, feature = "diagnostics"))]
crate::timeline::title_thread();
#[cfg(windows)]
if let Some(host) = crate::host::host() {
// SAFETY: the title passes `count` lists.
@@ -650,6 +654,7 @@ extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT {
if fence.is_null() {
return E_INVALIDARG;
}
let _called = crate::timeline::span("the title's queue Signal");
#[cfg(windows)]
if behind::on() && !this.is_null() {
behind::signal(this, fence, value);
@@ -680,6 +685,7 @@ extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT {
if fence.is_null() {
return E_INVALIDARG;
}
let _called = crate::timeline::span("the title's queue Wait");
#[cfg(windows)]
if !this.is_null() {
let now = crate::fence::completed(fence);
@@ -767,6 +773,8 @@ impl Written {
}
Written::SystemTimestamp => system_timestamp(),
};
#[cfg(all(windows, feature = "diagnostics"))]
crate::timeline::told("written when its list had run", at as usize, value);
// SAFETY: the title names writable GPU memory (unified with ours).
unsafe {
if bytes == 4 {
@@ -837,6 +845,9 @@ extern "system" fn present(
let _ = this;
#[cfg(all(windows, feature = "diagnostics"))]
crate::copystat::present_begins();
let called = crate::timeline::span("the title's Present");
#[cfg(all(windows, feature = "diagnostics"))]
crate::timeline::title_thread();
// Submissions sent to the card and not waited for are settled first,
// and what that frees runs in its own order, before anything is forced.
#[cfg(windows)]
@@ -917,6 +928,9 @@ extern "system" fn present(
};
let resource = texture.as_ref().map_or(0, |t| t.0);
behind::present(this, texture.map(|(_, copy, state)| (copy, state)), Shown { frame, resource });
called.end();
#[cfg(feature = "diagnostics")]
frame_ends();
return S_OK;
}
#[cfg(windows)]
@@ -939,8 +953,23 @@ extern "system" fn present(
}
#[cfg(not(windows))]
let _ = (planes, plane_parameters);
called.end();
#[cfg(all(windows, feature = "diagnostics"))]
frame_ends();
S_OK
}
/// Diagnostics: the title's present is over.
#[cfg(all(windows, feature = "diagnostics"))]
fn frame_ends() {
crate::timeline::presented();
crate::ab::presented(|switch, was, will| {
if switch == "VICTORY_ASYNC_SUBMIT" && was && !will {
behind::leave();
}
});
}
/// The frame a present shows, and the title's resource it shows.
#[cfg(windows)]
#[derive(Clone, Copy)]
@@ -1037,6 +1066,7 @@ extern "system" fn copy_page_mappings(
if batches.is_null() && count > 0 {
return E_INVALIDARG;
}
let _called = crate::timeline::span("the title's CopyPageMappings");
let batches = (count > 0).then(|| {
// SAFETY: the title passes `count` batches.
unsafe { std::slice::from_raw_parts(batches, count as usize) }
+27 -3
View File
@@ -340,6 +340,12 @@ impl Work for Job {
fn go(self, forced: bool) {
let began = Instant::now();
let _doing = crate::timeline::span(match self {
Job::Run(..) => "the line: a submission",
Job::Present(..) => "the line: a present",
Job::Signal(..) => "the line: a signal",
_ => "the line: a wait that is met",
});
if forced {
STATS[FORCED].fetch_add(1, Relaxed);
#[cfg(feature = "diagnostics")]
@@ -426,11 +432,27 @@ thread_local! {
/// (`VICTORY_ASYNC_SUBMIT=1`; needs flights with the present sent ahead, as
/// the relay has them, and lists cut at their waits).
pub(super) fn on() -> bool {
// Diagnostics: on and off while the title runs (`crate::ab`).
#[cfg(feature = "diagnostics")]
if let Some(on) = crate::ab::pick("VICTORY_ASYNC_SUBMIT") {
return on && started();
}
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") && started())
}
/// The line is about to be left for the way without it: everything in it is
/// done first. (At a present, by the title's thread that submits.)
#[cfg(feature = "diagnostics")]
pub(super) fn leave() {
LANE.wait_presents(0);
LANE.drain();
}
/// Starts the thread, once: whether there is one.
fn started() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| {
if !std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") {
return false;
}
if !crate::host::late_free_present() || !super::cuts() {
tracing::warn!("VICTORY_ASYNC_SUBMIT=1 needs the relay and lists cut at their waits: submissions are prepared by the thread that makes them");
return false;
@@ -528,6 +550,7 @@ pub(super) fn submit(this: This, lists: &[This]) {
LANE.push(queue, jobs);
if before + runs > runs_most() as u64 {
let began = Instant::now();
let _waiting = crate::timeline::span("a submission waits for room in the line");
LANE.wait_runs(runs_most());
STATS[ROOM].fetch_add(began.elapsed().as_micros() as u64, Relaxed);
}
@@ -558,6 +581,7 @@ pub(super) fn present(this: This, texture: Option<(std::sync::Arc<crate::resourc
STATS[PRESENTS].fetch_add(1, Relaxed);
LANE.push(this as usize, [Job::Present(texture, shown)]);
let began = Instant::now();
let _waiting = crate::timeline::span("a present waits for the one before it to be sent");
LANE.wait_presents(frames_most());
STATS[AT_PRESENT].fetch_add(began.elapsed().as_micros() as u64, Relaxed);
}
+2
View File
@@ -1465,6 +1465,7 @@ fn workers() -> &'static Workers {
jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner());
}
};
let _working = crate::timeline::span("a job for another thread");
job();
}
});
@@ -1483,6 +1484,7 @@ fn wide(jobs: Vec<Job>) {
return;
}
let workers = workers();
let _wide = crate::timeline::span("work spread over threads");
let left = Arc::new((Mutex::new(jobs.len()), std::sync::Condvar::new()));
{
let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
+1
View File
@@ -1155,6 +1155,7 @@ impl Staging {
pub(crate) fn refresh(&self) {
use std::sync::atomic::Ordering::Relaxed;
let started = std::time::Instant::now();
let _texture = crate::timeline::span("a texture's refresh");
let read = self.refresh_now();
let preparing = &crate::host::PREPARING;
preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed);
+57
View File
@@ -0,0 +1,57 @@
//! Diagnostics: a timeline of a few frames. `VICTORY_TIMELINE=<file>` writes
//! one, from the first present after `VICTORY_TIMELINE_AT` seconds (60) on
//! and for `VICTORY_TIMELINE_FRAMES` frames (3);
//! `VICTORY_TIMELINE=<from s>[+<from s>..],<frames>,<file>` one for each of
//! the times (each in a file of its own, the second in its name): a Chrome trace (JSON, for
//! `chrome://tracing` or Perfetto) and beside it a text summary (`.txt`)
//! with the chain of work and waits each frame's present came out of.
//!
//! What is recorded while it runs, by every thread:
//! - spans of ours ([`span`]): the title's calls, the submitting thread's
//! stages, the relay's, the pools' jobs, texture and streaming work;
//! - waits and the wake-ups that end them ([`hooks`]): the functions the
//! title's threads wait with (its imports are bound to wrappers) and those
//! our own code does (the entries of our own import table: every contended
//! lock, condition and park of the standard library is a `WaitOnAddress`),
//! each with the thread that woke it and where it waited;
//! - kernel calls on the address space that took long;
//! - the card: when each submission began and ended on it (timestamps).
//!
//! Without the variable nothing is wrapped and a span is one load of a
//! flag; a build without `diagnostics` has nothing of it.
#[cfg(all(windows, feature = "diagnostics"))]
mod hooks;
#[cfg(all(windows, feature = "diagnostics"))]
mod record;
#[cfg(all(windows, feature = "diagnostics"))]
mod report;
#[cfg(all(windows, feature = "diagnostics"))]
pub use hooks::import;
#[cfg(all(windows, feature = "diagnostics"))]
pub use record::{Span, span};
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) use record::{called, card_wait, on, polled, presented, sent, ticks, title_thread, told};
/// A span of ours: from where it is made until it is dropped.
#[cfg(not(all(windows, feature = "diagnostics")))]
pub struct Span;
#[cfg(not(all(windows, feature = "diagnostics")))]
impl Span {
/// The span ends here and another begins.
#[inline(always)]
pub fn next(&mut self, _name: &'static str) {}
/// The span ends here.
#[inline(always)]
pub fn end(self) {}
}
/// A span named `name`.
#[cfg(not(all(windows, feature = "diagnostics")))]
#[inline(always)]
pub fn span(_name: &'static str) -> Span {
Span
}
+322
View File
@@ -0,0 +1,322 @@
//! The wrappers around what threads wait and wake each other with. The
//! title's imports are bound to them ([`import`]), and the entries of our
//! own import table point at them, if a timeline was asked for; else nothing
//! is wrapped. While nothing is recorded a wrapper is a load and a jump.
use std::ffi::{CStr, c_void};
use std::sync::Once;
use std::sync::atomic::{AtomicUsize, Ordering};
use super::record::{kernel, on, standing, stood_at, ticks, waited, woken};
type Handle = *mut c_void;
macro_rules! wrapped {
($($index:literal $name:ident ($($arg:ident: $type:ty),*) $(-> $result:ty)? => $body:expr;)*) => {
/// The functions wrapped, by name: their own addresses, ours.
static TABLE: [(&str, AtomicUsize, usize); [$($index),*].len()] = [
$((stringify!($name), AtomicUsize::new(0), $index)),*
];
fn wrapper(index: usize) -> usize {
match index {
$($index => wrappers::$name as *const () as usize,)*
_ => 0,
}
}
#[allow(non_snake_case)]
mod wrappers {
use super::*;
$(
pub(super) unsafe extern "system" fn $name($($arg: $type),*) $(-> $result)? {
// SAFETY: the function of that name, as the system has it
// (or the module the title imports it from).
let real: unsafe extern "system" fn($($type),*) $(-> $result)? =
unsafe { std::mem::transmute(TABLE[$index].1.load(Ordering::Relaxed)) };
if !on() {
// SAFETY: the caller's own call.
return unsafe { real($($arg),*) };
}
($body)(real)
}
)*
}
};
}
/// Runs `call`, a wait on `object` that may be long; what the caller may
/// ask [`GetLastError`] about stays.
///
/// [`GetLastError`]: windows_sys::Win32::Foundation::GetLastError
fn wait<T>(name: &'static str, object: u64, call: impl FnOnce() -> T) -> T {
use windows_sys::Win32::Foundation::{GetLastError, SetLastError};
let t0 = ticks();
let result = {
let _standing = standing(object);
call()
};
// SAFETY: plain queries of this thread's own.
unsafe {
let error = GetLastError();
waited(name, object, t0);
SetLastError(error);
}
result
}
/// Runs `call`, a call of the kernel's on `bytes`.
fn measured<T>(name: &'static str, bytes: usize, call: impl FnOnce() -> T) -> T {
use windows_sys::Win32::Foundation::{GetLastError, SetLastError};
let t0 = ticks();
let result = call();
// SAFETY: plain queries of this thread's own.
unsafe {
let error = GetLastError();
kernel(name, bytes as u64, t0);
SetLastError(error);
}
result
}
/// The function `name` of the table, as the system has it.
fn real(name: &str) -> usize {
TABLE.iter().find(|t| t.0 == name).map_or(0, |t| t.1.load(Ordering::Relaxed))
}
/// `take(lock)`, a try that does not wait, then `wait`.
fn lock_of(name: &'static str, lock: Handle, take: &str, call: impl FnOnce()) {
let take = real(take);
if take != 0 {
// SAFETY: `TryEnterCriticalSection` or a `TryAcquireSRWLock` call:
// one pointer, a truth value (one byte of it for the latter).
let taken = unsafe { std::mem::transmute::<usize, unsafe extern "system" fn(Handle) -> u8>(take)(lock) };
if taken != 0 {
return;
}
}
wait(name, lock as u64, call);
}
fn released(name: &'static str, object: Handle) {
if stood_at(object as u64) {
woken(name, object as u64);
}
}
wrapped! {
0 WaitForSingleObject(object: Handle, ms: u32) -> u32 => |real: unsafe extern "system" fn(Handle, u32) -> u32| {
// SAFETY: the caller's own call (so below).
wait("WaitForSingleObject", object as u64, || unsafe { real(object, ms) })
};
1 WaitForSingleObjectEx(object: Handle, ms: u32, alertable: i32) -> u32 => |real: unsafe extern "system" fn(Handle, u32, i32) -> u32| {
wait("WaitForSingleObjectEx", object as u64, || unsafe { real(object, ms, alertable) })
};
2 Sleep(ms: u32) => |real: unsafe extern "system" fn(u32)| {
wait("Sleep", 0, || unsafe { real(ms) })
};
3 SleepEx(ms: u32, alertable: i32) -> u32 => |real: unsafe extern "system" fn(u32, i32) -> u32| {
wait("SleepEx", 0, || unsafe { real(ms, alertable) })
};
4 SetEvent(object: Handle) -> i32 => |real: unsafe extern "system" fn(Handle) -> i32| {
woken("SetEvent", object as u64);
unsafe { real(object) }
};
5 ReleaseSemaphore(object: Handle, count: i32, before: *mut i32) -> i32 => |real: unsafe extern "system" fn(Handle, i32, *mut i32) -> i32| {
woken("ReleaseSemaphore", object as u64);
unsafe { real(object, count, before) }
};
6 ReleaseMutex(object: Handle) -> i32 => |real: unsafe extern "system" fn(Handle) -> i32| {
woken("ReleaseMutex", object as u64);
unsafe { real(object) }
};
7 EnterCriticalSection(lock: Handle) => |real: unsafe extern "system" fn(Handle)| {
lock_of("EnterCriticalSection", lock, "TryEnterCriticalSection", || unsafe { real(lock) })
};
8 LeaveCriticalSection(lock: Handle) => |real: unsafe extern "system" fn(Handle)| {
released("LeaveCriticalSection", lock);
unsafe { real(lock) }
};
9 AcquireSRWLockExclusive(lock: Handle) => |real: unsafe extern "system" fn(Handle)| {
lock_of("AcquireSRWLockExclusive", lock, "TryAcquireSRWLockExclusive", || unsafe { real(lock) })
};
10 ReleaseSRWLockExclusive(lock: Handle) => |real: unsafe extern "system" fn(Handle)| {
released("ReleaseSRWLockExclusive", lock);
unsafe { real(lock) }
};
11 AcquireSRWLockShared(lock: Handle) => |real: unsafe extern "system" fn(Handle)| {
lock_of("AcquireSRWLockShared", lock, "TryAcquireSRWLockShared", || unsafe { real(lock) })
};
12 ReleaseSRWLockShared(lock: Handle) => |real: unsafe extern "system" fn(Handle)| {
released("ReleaseSRWLockShared", lock);
unsafe { real(lock) }
};
13 WaitOnAddress(at: Handle, compare: Handle, size: usize, ms: u32) -> i32 => |real: unsafe extern "system" fn(Handle, Handle, usize, u32) -> i32| {
wait("WaitOnAddress", at as u64, || unsafe { real(at, compare, size, ms) })
};
14 WakeByAddressSingle(at: Handle) => |real: unsafe extern "system" fn(Handle)| {
released("WakeByAddressSingle", at);
unsafe { real(at) }
};
15 WakeByAddressAll(at: Handle) => |real: unsafe extern "system" fn(Handle)| {
released("WakeByAddressAll", at);
unsafe { real(at) }
};
16 SleepConditionVariableSRW(at: Handle, lock: Handle, ms: u32, flags: u32) -> i32 => |real: unsafe extern "system" fn(Handle, Handle, u32, u32) -> i32| {
wait("SleepConditionVariableSRW", at as u64, || unsafe { real(at, lock, ms, flags) })
};
17 SleepConditionVariableCS(at: Handle, lock: Handle, ms: u32) -> i32 => |real: unsafe extern "system" fn(Handle, Handle, u32) -> i32| {
wait("SleepConditionVariableCS", at as u64, || unsafe { real(at, lock, ms) })
};
18 WakeConditionVariable(at: Handle) => |real: unsafe extern "system" fn(Handle)| {
released("WakeConditionVariable", at);
unsafe { real(at) }
};
19 WakeAllConditionVariable(at: Handle) => |real: unsafe extern "system" fn(Handle)| {
released("WakeAllConditionVariable", at);
unsafe { real(at) }
};
20 WaitForMultipleObjects(count: u32, objects: *const Handle, all: i32, ms: u32) -> u32 => |real: unsafe extern "system" fn(u32, *const Handle, i32, u32) -> u32| {
// (Named by the first of them.)
// SAFETY: the caller passes `count` handles.
let first = if count > 0 && !objects.is_null() { (unsafe { *objects }) as u64 } else { 0 };
wait("WaitForMultipleObjects", first, || unsafe { real(count, objects, all, ms) })
};
21 GetWriteWatch(flags: u32, at: Handle, size: usize, found: Handle, count: Handle, granularity: Handle) -> u32 => |real: unsafe extern "system" fn(u32, Handle, usize, Handle, Handle, Handle) -> u32| {
measured("GetWriteWatch", size, || unsafe { real(flags, at, size, found, count, granularity) })
};
22 VirtualProtect(at: Handle, size: usize, new: u32, old: Handle) -> i32 => |real: unsafe extern "system" fn(Handle, usize, u32, Handle) -> i32| {
measured("VirtualProtect", size, || unsafe { real(at, size, new, old) })
};
23 ReadProcessMemory(process: Handle, at: Handle, to: Handle, size: usize, done: Handle) -> i32 => |real: unsafe extern "system" fn(Handle, Handle, Handle, usize, Handle) -> i32| {
measured("ReadProcessMemory", size, || unsafe { real(process, at, to, size, done) })
};
24 VirtualQuery(at: Handle, info: Handle, size: usize) -> usize => |real: unsafe extern "system" fn(Handle, Handle, usize) -> usize| {
measured("VirtualQuery", 0, || unsafe { real(at, info, size) })
};
25 VirtualAlloc(at: Handle, size: usize, kind: u32, protect: u32) -> Handle => |real: unsafe extern "system" fn(Handle, usize, u32, u32) -> Handle| {
measured("VirtualAlloc", size, || unsafe { real(at, size, kind, protect) })
};
26 VirtualFree(at: Handle, size: usize, kind: u32) -> i32 => |real: unsafe extern "system" fn(Handle, usize, u32) -> i32| {
measured("VirtualFree", size, || unsafe { real(at, size, kind) })
};
27 _Mtx_lock(lock: Handle) -> i32 => |real: unsafe extern "system" fn(Handle) -> i32| {
wait("_Mtx_lock", lock as u64, || unsafe { real(lock) })
};
28 _Mtx_unlock(lock: Handle) -> i32 => |real: unsafe extern "system" fn(Handle) -> i32| {
released("_Mtx_unlock", lock);
unsafe { real(lock) }
};
29 TryEnterCriticalSection(lock: Handle) -> u8 => |real: unsafe extern "system" fn(Handle) -> u8| unsafe { real(lock) };
30 TryAcquireSRWLockExclusive(lock: Handle) -> u8 => |real: unsafe extern "system" fn(Handle) -> u8| unsafe { real(lock) };
31 TryAcquireSRWLockShared(lock: Handle) -> u8 => |real: unsafe extern "system" fn(Handle) -> u8| unsafe { real(lock) };
}
/// The wrappers from here on are there for their real functions only.
const ONLY_REAL: usize = 29;
/// Asks the system for the real functions, and points our own import table
/// at the wrappers: once, if a timeline is wanted.
fn arm() -> bool {
static ONCE: Once = Once::new();
if !super::record::wanted() {
return false;
}
ONCE.call_once(wrap_own);
true
}
/// See [`arm`].
pub(super) fn wrap_own() {
find_real();
// SAFETY: our own module's mapped image.
let changed = unsafe { wrap_imports() };
tracing::info!(changed, "the timeline's wrappers are in (VICTORY_TIMELINE)");
}
fn find_real() {
use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress};
for dll in [c"kernelbase.dll", c"kernel32.dll", c"ntdll.dll"] {
// SAFETY: NUL-terminated names of modules every process has.
let module = unsafe { GetModuleHandleA(dll.as_ptr().cast()) };
for (name, at, _) in &TABLE {
if at.load(Ordering::Relaxed) == 0 && !module.is_null() {
let text = std::ffi::CString::new(*name).expect("a plain name");
// SAFETY: as above.
if let Some(f) = unsafe { GetProcAddress(module, text.as_ptr().cast()) } {
at.store(f as *const () as usize, Ordering::Relaxed);
}
}
}
}
}
/// What the title's import `name`, found at `address`, is bound to: the
/// address itself, or our wrapper of it.
pub fn import(name: &str, address: usize) -> usize {
if !arm() {
return address;
}
let Some((i, (_, at, _))) = TABLE.iter().enumerate().find(|(i, t)| *i < ONLY_REAL && t.0 == name) else {
return address;
};
if at.load(Ordering::Relaxed) == 0 {
at.store(address, Ordering::Relaxed);
}
wrapper(i)
}
/// Points the entries of our own import table that are in [`TABLE`] at the
/// wrappers: how many.
///
/// # Safety
/// The process's module is mapped as the loader left it.
unsafe fn wrap_imports() -> usize {
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect};
// SAFETY: a plain query.
let base = unsafe { GetModuleHandleW(std::ptr::null()) } as usize;
let mut changed = 0;
// SAFETY: the headers, the import directory and the tables it names lie
// in the mapped image, as the loader read them; an entry is eight bytes,
// aligned, and made writable for the store.
unsafe {
let at = |rva: u32| base + rva as usize;
let read = |at: usize| (at as *const u32).read_unaligned();
let headers = at(read(base + 0x3c));
// The second data directory of the 64-bit optional header: imports.
let mut descriptor = at(read(headers + 0x18 + 0x70 + 8));
loop {
let (names, first) = (read(descriptor), read(descriptor + 16));
if first == 0 {
break;
}
let names = if names != 0 { names } else { first };
for i in 0.. {
let entry = (at(names) as *const u64).add(i).read_unaligned();
if entry == 0 {
break;
}
if entry >> 63 != 0 {
continue; // by number
}
let name = CStr::from_ptr((at(entry as u32) + 2) as *const _);
let Some(index) = TABLE[..ONLY_REAL].iter().position(|t| t.0.as_bytes() == name.to_bytes()) else {
continue;
};
if TABLE[index].1.load(Ordering::Relaxed) == 0 {
continue;
}
let slot = (at(first) as *mut usize).add(i);
let (mut old, mut ignored) = (0, 0);
if VirtualProtect(slot.cast(), 8, PAGE_READWRITE, &mut old) != 0 {
(*slot.cast::<AtomicUsize>()).store(wrapper(index), Ordering::SeqCst);
VirtualProtect(slot.cast(), 8, old, &mut ignored);
changed += 1;
}
}
descriptor += 20;
}
}
changed
}
+678
View File
@@ -0,0 +1,678 @@
//! What is recorded, and when. Every event goes into one buffer made ahead:
//! a write takes a place in it (one atomic addition) and nothing else, so it
//! can be done anywhere, the handler of write faults included.
use std::cell::Cell;
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicUsize, Ordering};
use std::sync::{Mutex, OnceLock};
/// What an event is.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Kind {
/// A span of ours.
Span,
/// A run of list calls: `a` calls, `b` ticks inside them.
Calls,
/// A wait on the object `a` (an address, or a handle's value); `b`: the
/// value of the host's fence it stands for (0: none, [`COPY_QUEUE`]).
Wait,
/// The object `a` is signalled or released.
Wake,
/// A call of the kernel's that took long; `a` its bytes.
Kernel,
/// Lists went to the card: `a` the value signalled behind them, `b` the
/// place of their timestamps plus one.
Sent,
/// A present came back: a frame ends.
Frame,
/// The title is told something: `b` is stored at `a` (a fence, or what
/// a list writes when it has run).
Told,
/// The title asked a fence (`a`) for its value and got `b`, again and
/// again from the beginning to the end.
Poll,
/// Where a thread of the title's was: `a` the instruction, the stack
/// what on its stack may be return addresses.
Sample,
}
/// The `b` of a wait for the card's copy queue.
pub(super) const COPY_QUEUE: u64 = u64::MAX;
#[derive(Clone, Copy, Debug)]
pub(super) struct Event {
pub(super) t0: u64,
pub(super) t1: u64,
pub(super) a: u64,
pub(super) b: u64,
pub(super) name: &'static str,
pub(super) thread: u32,
/// Its place among the stacks, plus one (0: none).
pub(super) stack: u32,
pub(super) cpu: u16,
pub(super) kind: Kind,
}
struct Slot {
event: std::cell::UnsafeCell<std::mem::MaybeUninit<Event>>,
written: AtomicBool,
}
/// Events kept, and stacks.
const EVENTS: usize = 1 << 20;
const STACKS: usize = 1 << 16;
/// Return addresses of a stack.
pub(super) const DEPTH: usize = 14;
static ON: AtomicBool = AtomicBool::new(false);
static SLOTS: AtomicPtr<Slot> = AtomicPtr::new(std::ptr::null_mut());
static NEXT: AtomicUsize = AtomicUsize::new(0);
static STACK: AtomicPtr<[usize; DEPTH]> = AtomicPtr::new(std::ptr::null_mut());
static NEXT_STACK: AtomicUsize = AtomicUsize::new(0);
/// [`ticks`] per second.
pub(super) fn frequency() -> u64 {
static TICKS: OnceLock<u64> = OnceLock::new();
*TICKS.get_or_init(|| {
let mut ticks = 0;
// SAFETY: a valid out pointer.
unsafe { windows_sys::Win32::System::Performance::QueryPerformanceFrequency(&mut ticks) };
ticks.max(1) as u64
})
}
/// The performance counter: the clock the card's is calibrated against.
pub(crate) fn ticks() -> u64 {
let mut ticks = 0;
// SAFETY: a valid out pointer.
unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut ticks) };
ticks as u64
}
pub(super) fn micros(ticks: u64) -> u64 {
ticks.saturating_mul(1_000_000) / frequency()
}
/// Whether events are recorded now.
#[inline(always)]
pub(crate) fn on() -> bool {
ON.load(Ordering::Relaxed)
}
pub(super) fn thread() -> u32 {
thread_local!(static ID: Cell<u32> = const { Cell::new(0) });
ID.with(|id| {
if id.get() == 0 {
// SAFETY: a plain query.
id.set(unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() });
}
id.get()
})
}
/// Records an event of this thread.
pub(super) fn put(kind: Kind, name: &'static str, t: (u64, u64), a: u64, b: u64, stack: u32) {
put_of(thread(), kind, name, t, a, b, stack);
}
/// Records an event of `thread`.
fn put_of(thread: u32, kind: Kind, name: &'static str, (t0, t1): (u64, u64), a: u64, b: u64, stack: u32) {
let slots = SLOTS.load(Ordering::Acquire);
if slots.is_null() {
return;
}
let at = NEXT.fetch_add(1, Ordering::Relaxed);
if at >= EVENTS {
return;
}
// SAFETY: a plain query.
let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as u16;
let event = Event { t0, t1, a, b, name, thread, stack, cpu, kind };
// SAFETY: within the buffer, and this place was given to this call alone.
unsafe {
let slot = &*slots.add(at);
(*slot.event.get()).write(event);
slot.written.store(true, Ordering::Release);
}
}
/// The caller's stack: its place, plus one.
fn stack() -> u32 {
let stacks = STACK.load(Ordering::Acquire);
if stacks.is_null() {
return 0;
}
let at = NEXT_STACK.fetch_add(1, Ordering::Relaxed);
if at >= STACKS {
return 0;
}
let mut frames = [0usize; DEPTH];
// SAFETY: room for `DEPTH` return addresses; the place was given to this
// call alone.
unsafe {
windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace(
1,
DEPTH as u32,
frames.as_mut_ptr().cast(),
std::ptr::null_mut(),
);
stacks.add(at).write(frames);
}
at as u32 + 1
}
/// Shorter spans of ours are not kept (microseconds).
const SHORTEST: u64 = 5;
/// The stack of a wait or a list call this long is kept (microseconds).
const DEEP: u64 = 50;
/// A span of ours: from where it is made until it is dropped.
pub struct Span {
name: &'static str,
/// When it began (0: nothing is recorded).
began: u64,
}
/// A span named `name`.
#[inline(always)]
pub fn span(name: &'static str) -> Span {
Span {
name,
began: if on() { ticks() } else { 0 },
}
}
impl Span {
/// The span ends here and another begins.
#[inline(always)]
pub fn next(&mut self, name: &'static str) {
self.close();
(self.name, self.began) = (name, if on() { ticks() } else { 0 });
}
/// The span ends here.
#[inline(always)]
pub fn end(self) {}
fn close(&mut self) {
let began = std::mem::take(&mut self.began);
if began != 0 {
let now = ticks();
if micros(now - began) >= SHORTEST {
put(Kind::Span, self.name, (began, now), 0, 0, 0);
}
}
}
}
impl Drop for Span {
#[inline(always)]
fn drop(&mut self) {
if self.began != 0 {
self.close();
}
}
}
/// List calls closer than this (microseconds) are one event.
const RUN_GAP: u64 = 10;
/// A list call of the title's that took `took` has returned.
pub(crate) fn called(took: std::time::Duration) {
if !on() {
return;
}
let inside = (took.as_nanos() as u64).saturating_mul(frequency()) / 1_000_000_000;
let t1 = ticks();
let t0 = t1 - inside;
thread_local! {
/// The run under way: from, to, calls, ticks inside them.
static RUN: Cell<(u64, u64, u64, u64)> = const { Cell::new((0, 0, 0, 0)) };
}
RUN.with(|run| {
let (from, to, calls, sum) = run.get();
if calls > 0 && micros(t0.saturating_sub(to)) < RUN_GAP {
run.set((from, t1, calls + 1, sum + inside));
return;
}
if calls > 0 {
put(Kind::Calls, "list calls", (from, to), calls, sum, 0);
}
run.set((t0, t1, 1, inside));
});
if micros(inside) >= DEEP {
put(Kind::Span, "a long list call", (t0, t1), 0, 0, stack());
}
}
thread_local! {
/// What the wait this thread makes now stands for ([`card_wait`]).
static CARD: Cell<u64> = const { Cell::new(0) };
}
/// While it lives, this thread's waits are for the card.
pub(crate) struct CardWait(());
/// This thread's waits are for the card to reach `fence` (`None`: for its
/// copy queue) until what comes back is dropped.
pub(crate) fn card_wait(fence: Option<u64>) -> CardWait {
CARD.with(|c| c.set(fence.unwrap_or(COPY_QUEUE)));
CardWait(())
}
impl Drop for CardWait {
fn drop(&mut self) {
CARD.with(|c| c.set(0));
}
}
/// This thread waited on `object` with `name` since `t0`.
pub(super) fn waited(name: &'static str, object: u64, t0: u64) {
let t1 = ticks();
let us = micros(t1 - t0);
if us >= 2 {
let stack = if us >= DEEP { stack() } else { 0 };
put(Kind::Wait, name, (t0, t1), object, CARD.with(Cell::get), stack);
}
}
/// `object` is about to be signalled.
pub(super) fn woken(name: &'static str, object: u64) {
let t = ticks();
put(Kind::Wake, name, (t, t), object, 0, 0);
}
/// A call of the kernel's on `bytes` began at `t0`.
pub(super) fn kernel(name: &'static str, bytes: u64, t0: u64) {
let t1 = ticks();
if micros(t1 - t0) >= 20 {
put(Kind::Kernel, name, (t0, t1), bytes, 0, 0);
}
}
/// Lists went to the card between `t0` ([`ticks`]) and now, the value
/// `fence` signalled behind them, with the timestamps at `stamp`.
pub(crate) fn sent(t0: u64, fence: u64, stamp: Option<usize>) {
if on() {
put(Kind::Sent, "ExecuteCommandLists", (t0, ticks()), fence, stamp.map_or(0, |s| s as u64 + 1), 0);
}
}
/// `value` is being stored at `at`, where the title looks for it.
#[inline(always)]
pub(crate) fn told(name: &'static str, at: usize, value: u64) {
if on() {
let t = ticks();
put(Kind::Told, name, (t, t), at as u64, value, 0);
}
}
/// The title asked the fence at `at` for its value, which is `value`.
#[inline(always)]
pub(crate) fn polled(at: usize, value: u64) {
if !on() {
return;
}
thread_local! {
/// The same answer, again and again: fence, value, from, to.
static SAME: Cell<(usize, u64, u64, u64)> = const { Cell::new((0, 0, 0, 0)) };
}
let t = ticks();
SAME.with(|same| {
let (fence, was, from, to) = same.get();
if (fence, was) == (at, value) && micros(t.saturating_sub(to)) < 1000 {
same.set((at, value, from, t));
return;
}
if fence != 0 && micros(to.saturating_sub(from)) >= 100 {
put(Kind::Poll, "asks a fence", (from, to), fence as u64, was, 0);
}
same.set((at, value, t, t));
});
}
/// Threads of the title's that submit or present.
static TITLES: [AtomicU32; 4] = [const { AtomicU32::new(0) }; 4];
/// This thread is one of the title's that submit: what it does is sampled.
#[inline(always)]
pub(crate) fn title_thread() {
if !on() {
return;
}
let id = thread();
for place in &TITLES {
match place.load(Ordering::Relaxed) {
there if there == id => return,
0 if place.compare_exchange(0, id, Ordering::Relaxed, Ordering::Relaxed).is_ok() => return,
_ => {}
}
}
}
/// Looks every quarter of a millisecond where the title's submitting threads
/// are, while the recording goes on: what they do outside our calls (a loop
/// on a value in memory has no event of its own).
fn sample() {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Diagnostics::Debug::{CONTEXT, CONTEXT_CONTROL_AMD64, GetThreadContext};
use windows_sys::Win32::System::Threading::{
OpenThread, ResumeThread, SuspendThread, THREAD_GET_CONTEXT, THREAD_SUSPEND_RESUME,
};
/// `GetThreadContext` wants a 16-byte aligned context.
#[repr(C, align(16))]
struct Aligned(CONTEXT);
let mut open: Vec<(u32, *mut std::ffi::c_void)> = Vec::new();
while on() {
for place in &TITLES {
let id = place.load(Ordering::Relaxed);
if id == 0 {
continue;
}
let thread = match open.iter().find(|o| o.0 == id) {
Some(o) => o.1,
None => {
// SAFETY: a thread of our own process.
let handle = unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT, 0, id) };
open.push((id, handle));
handle
}
};
if thread.is_null() {
continue;
}
let mut words = [0usize; 64];
// SAFETY: zeroed is a valid CONTEXT; the thread is another one of
// this process and runs on before anything here allocates or
// locks; its stack is read from its pointer to the end of that
// page alone.
let at = unsafe {
let mut context = Aligned(std::mem::zeroed());
context.0.ContextFlags = CONTEXT_CONTROL_AMD64;
if SuspendThread(thread) == u32::MAX {
continue;
}
let known = GetThreadContext(thread, &mut context.0) != 0;
if known {
let sp = context.0.Rsp as usize & !7;
let n = ((sp | 0xfff) + 1 - sp) / 8;
for (i, word) in words.iter_mut().enumerate().take(n) {
*word = (sp as *const usize).add(i).read_volatile();
}
}
ResumeThread(thread);
if known { context.0.Rip as usize } else { 0 }
};
let t = ticks();
// What lies near the instruction may be a return address; where
// the instruction is the system's, all of it may tell something.
let mut frames = [0usize; DEPTH];
let near = words.iter().copied().filter(|w| *w != 0 && (at >> 40 == 0x7f || w.abs_diff(at) < 0x1000_0000));
for (frame, word) in frames.iter_mut().zip(near) {
*frame = word;
}
put_of(id, Kind::Sample, "a sample", (t, t), at as u64, 0, keep(frames));
}
let until = ticks() + frequency() / 4000;
while ticks() < until {
std::hint::spin_loop();
}
}
for (_, handle) in open {
// SAFETY: opened above.
unsafe { CloseHandle(handle) };
}
}
/// `frames` among the stacks: its place, plus one.
fn keep(frames: [usize; DEPTH]) -> u32 {
let stacks = STACK.load(Ordering::Acquire);
let at = NEXT_STACK.fetch_add(1, Ordering::Relaxed);
if stacks.is_null() || at >= STACKS {
return 0;
}
// SAFETY: the place was given to this call alone.
unsafe { stacks.add(at).write(frames) };
at as u32 + 1
}
/// What was asked for.
struct Asked {
file: std::path::PathBuf,
/// Seconds after which a recording begins, for each.
after: Vec<f64>,
frames: u64,
started: std::time::Instant,
}
/// `<from s>[+<from s>..],<frames>,<file>`, or a file alone.
fn parse(text: &str) -> (Option<(Vec<f64>, u64)>, &str) {
let mut parts = text.splitn(3, ',');
let three = (parts.next(), parts.next(), parts.next());
if let (Some(from), Some(frames), Some(file)) = three
&& let Ok(from) = from.split('+').map(|f| f.trim().parse::<f64>()).collect::<Result<Vec<f64>, _>>()
&& let Ok(frames) = frames.trim().parse::<u64>()
{
return (Some((from, frames)), file);
}
(None, text)
}
/// The variables, read once (before the title runs: its imports are bound
/// by them).
fn asked() -> Option<&'static Asked> {
static ASKED: OnceLock<Option<Asked>> = OnceLock::new();
ASKED
.get_or_init(|| {
let file = std::env::var_os("VICTORY_TIMELINE").filter(|v| !v.is_empty())?;
let number = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<f64>().ok());
let text = file.to_string_lossy();
let (when, file) = parse(&text);
let (after, frames) = when.unwrap_or_else(|| {
(
vec![number("VICTORY_TIMELINE_AT").unwrap_or(60.0)],
number("VICTORY_TIMELINE_FRAMES").map_or(3, |n| n as u64),
)
});
Some(Asked {
file: file.into(),
after,
frames: frames.clamp(1, 60),
started: std::time::Instant::now(),
})
})
.as_ref()
}
/// Whether a timeline was asked for.
pub(super) fn wanted() -> bool {
asked().is_some()
}
/// Where the recording is.
struct Stage {
ready: bool,
began: bool,
frames: u64,
/// Recordings made, and whether one is being written.
made: usize,
writing: bool,
before: Option<super::report::Threads>,
}
/// The title's present came back.
pub(crate) fn presented() {
let Some(asked) = asked() else {
return;
};
static STAGE: Mutex<Stage> = Mutex::new(Stage {
ready: false,
began: false,
frames: 0,
made: 0,
writing: false,
before: None,
});
let mut stage = STAGE.lock().unwrap_or_else(|e| e.into_inner());
let Some(&after) = asked.after.get(stage.made) else {
return;
};
if stage.writing || asked.started.elapsed().as_secs_f64() < after {
return;
}
if !stage.ready {
// The buffers, the card's lists and the threads' clocks take a
// while: the recording begins two frames later.
stage.ready = true;
make_room();
crate::host::timeline_ready();
return;
}
if !stage.began {
stage.began = true;
stage.before = Some(super::report::Threads::now());
tracing::info!(file = %asked.file.display(), frames = asked.frames, "the timeline begins (VICTORY_TIMELINE)");
begin();
if std::thread::Builder::new().name("victory-sample".into()).spawn(sample).is_err() {
tracing::warn!("the timeline is without samples of the title's threads");
}
frame();
return;
}
frame();
stage.frames += 1;
if stage.frames < asked.frames {
return;
}
stage.writing = true;
let before = stage.before.take().unwrap_or_default();
// Several recordings: a file each.
let file = match asked.after.len() {
1 => asked.file.clone(),
_ => {
let end = asked.file.extension().map_or("json".into(), |e| e.to_string_lossy().into_owned());
asked.file.with_extension(format!("{after:.0}.{end}"))
}
};
drop(stage);
let write = move || {
let after = super::report::Threads::now();
// The spans under way at the last present end first.
std::thread::sleep(std::time::Duration::from_millis(250));
let data = end();
super::report::write(&file, data, &before, &after, crate::host::timeline_stamps());
crate::host::timeline_restart();
let mut stage = STAGE.lock().unwrap_or_else(|e| e.into_inner());
(stage.began, stage.frames, stage.writing) = (false, 0, false);
stage.made += 1;
};
if std::thread::Builder::new().name("victory-timeline".into()).spawn(write).is_err() {
tracing::warn!("no thread to write the timeline");
}
}
/// A frame ends now.
pub(super) fn frame() {
let t = ticks();
put(Kind::Frame, "present", (t, t), 0, 0, 0);
}
/// Makes the buffers (kept for good: a thread may be about to write).
pub(super) fn make_room() {
if !SLOTS.load(Ordering::Acquire).is_null() {
return;
}
fn zeroed<T>(n: usize) -> *mut T {
let layout = std::alloc::Layout::array::<T>(n).expect("a small number");
// SAFETY: not of no size.
unsafe { std::alloc::alloc_zeroed(layout) }.cast()
}
STACK.store(zeroed(STACKS), Ordering::Release);
SLOTS.store(zeroed(EVENTS), Ordering::Release);
}
/// Recording starts.
pub(super) fn begin() {
ON.store(true, Ordering::SeqCst);
}
/// What was recorded, in no order.
pub(super) struct Data {
pub(super) events: Vec<Event>,
pub(super) stacks: Vec<[usize; DEPTH]>,
/// Events there was no room for.
pub(super) lost: usize,
}
/// Recording ends.
pub(super) fn end() -> Data {
ON.store(false, Ordering::SeqCst);
// Those about to write do.
std::thread::sleep(std::time::Duration::from_millis(20));
let taken = NEXT.load(Ordering::SeqCst);
TITLES.iter().for_each(|t| t.store(0, Ordering::SeqCst));
let slots = SLOTS.load(Ordering::Acquire);
let mut events = Vec::with_capacity(taken.min(EVENTS));
for at in 0..taken.min(EVENTS) {
// SAFETY: within the buffer; a written place is never written again.
unsafe {
let slot = &*slots.add(at);
if slot.written.load(Ordering::Acquire) {
events.push((*slot.event.get()).assume_init());
slot.written.store(false, Ordering::Release);
}
}
}
NEXT.store(0, Ordering::SeqCst);
let count = NEXT_STACK.swap(0, Ordering::SeqCst).min(STACKS);
// SAFETY: that many were given out; each was written before the event
// that names it.
let stacks = unsafe { std::slice::from_raw_parts(STACK.load(Ordering::Acquire), count) }.to_vec();
Data {
events,
stacks,
lost: taken.saturating_sub(EVENTS),
}
}
/// Objects threads stand at now, by a hash of theirs: releases of a lock
/// nobody waits for are not recorded.
static STOOD_AT: [AtomicU32; 4096] = [const { AtomicU32::new(0) }; 4096];
fn place(object: u64) -> &'static AtomicU32 {
&STOOD_AT[(object.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 52) as usize]
}
/// This thread is about to wait for `object`, until what comes back is
/// dropped.
pub(super) fn standing(object: u64) -> Standing {
place(object).fetch_add(1, Ordering::SeqCst);
Standing(object)
}
/// See [`standing`].
pub(super) struct Standing(u64);
impl Drop for Standing {
fn drop(&mut self) {
place(self.0).fetch_sub(1, Ordering::SeqCst);
}
}
/// Whether a thread may wait for `object`.
pub(super) fn stood_at(object: u64) -> bool {
place(object).load(Ordering::SeqCst) != 0
}
#[cfg(test)]
mod tests {
use super::parse;
#[test]
fn a_timeline_is_asked_for_by_seconds_frames_and_a_file() {
assert_eq!(parse("120,20,D:/a.json"), (Some((vec![120.0], 20)), "D:/a.json"));
assert_eq!(parse("120+130.5,20,D:/a,b.json"), (Some((vec![120.0, 130.5], 20)), "D:/a,b.json"));
assert_eq!(parse("D:/a,1,2.json"), (None, "D:/a,1,2.json"));
assert_eq!(parse("D:/a.json"), (None, "D:/a.json"));
}
}
+957
View File
@@ -0,0 +1,957 @@
//! What was recorded, put in order: the Chrome trace, and the text summary
//! with the chain each present came out of.
use std::collections::{BTreeMap, HashMap};
use std::fmt::Write as _;
use super::record::{COPY_QUEUE, DEPTH, Data, Event, Kind, frequency};
/// The process's threads at a moment.
#[derive(Default)]
pub(super) struct Threads {
/// By number: its processor cycles so far, its name, where it started.
all: HashMap<u32, (u64, String, usize)>,
/// The processor's clock and the performance counter then.
cycles: u64,
ticks: u64,
}
#[link(name = "kernel32")]
unsafe extern "system" {
fn QueryThreadCycleTime(thread: *mut std::ffi::c_void, cycles: *mut u64) -> i32;
}
#[link(name = "ntdll")]
unsafe extern "system" {
fn NtQueryInformationThread(
thread: *mut std::ffi::c_void,
class: i32,
out: *mut std::ffi::c_void,
len: u32,
returned: *mut u32,
) -> i32;
}
impl Threads {
pub(super) fn now() -> Threads {
use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE, LocalFree};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
use windows_sys::Win32::System::Threading::{
GetCurrentProcessId, GetThreadDescription, OpenThread, THREAD_QUERY_INFORMATION,
};
/// `ThreadQuerySetWin32StartAddress`.
const START: i32 = 9;
let mut threads = Threads::default();
// SAFETY: a snapshot of our own, walked with a sized entry; handles
// opened here are closed; the name is the system's, freed as asked.
unsafe {
let own = GetCurrentProcessId();
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if snapshot == INVALID_HANDLE_VALUE {
return threads;
}
let mut entry = THREADENTRY32 {
dwSize: size_of::<THREADENTRY32>() as u32,
..Default::default()
};
let mut more = Thread32First(snapshot, &mut entry) != 0;
while more {
if entry.th32OwnerProcessID == own {
let thread = OpenThread(THREAD_QUERY_INFORMATION, 0, entry.th32ThreadID);
if !thread.is_null() {
let (mut cycles, mut start, mut name) = (0, 0usize, std::ptr::null_mut());
QueryThreadCycleTime(thread, &mut cycles);
NtQueryInformationThread(thread, START, (&raw mut start).cast(), 8, std::ptr::null_mut());
let mut text = String::new();
if GetThreadDescription(thread, &mut name) >= 0 && !name.is_null() {
let len = (0..).take_while(|&i| *name.add(i) != 0).count();
text = String::from_utf16_lossy(std::slice::from_raw_parts(name, len));
LocalFree(name.cast());
}
CloseHandle(thread);
threads.all.insert(entry.th32ThreadID, (cycles, text, start));
}
}
more = Thread32Next(snapshot, &mut entry) != 0;
}
CloseHandle(snapshot);
threads.cycles = std::arch::x86_64::_rdtsc();
}
threads.ticks = super::record::ticks();
threads
}
}
/// Names of addresses.
pub(super) struct Names {
known: HashMap<usize, String>,
symbols: Option<Symbols>,
}
/// The system's symbol library (asked for when a timeline is written, not
/// at start).
struct Symbols {
from_address: unsafe extern "system" fn(*mut std::ffi::c_void, u64, *mut u64, *mut u8) -> i32,
process: *mut std::ffi::c_void,
}
impl Symbols {
fn load() -> Option<Symbols> {
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExA};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
type Initialize = unsafe extern "system" fn(*mut std::ffi::c_void, *const u16, i32) -> i32;
type Options = unsafe extern "system" fn(u32) -> u32;
// SAFETY: the system's own library and functions, by their names and
// signatures.
unsafe {
let module = LoadLibraryExA(c"dbghelp.dll".as_ptr().cast(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32);
if module.is_null() {
return None;
}
let options: Options = std::mem::transmute(GetProcAddress(module, c"SymSetOptions".as_ptr().cast())?);
let initialize: Initialize = std::mem::transmute(GetProcAddress(module, c"SymInitializeW".as_ptr().cast())?);
let from_address = std::mem::transmute::<
unsafe extern "system" fn() -> isize,
unsafe extern "system" fn(*mut std::ffi::c_void, u64, *mut u64, *mut u8) -> i32,
>(GetProcAddress(module, c"SymFromAddr".as_ptr().cast())?);
let process = GetCurrentProcess();
// Undecorated names, loaded when asked for, no dialogs.
options(0x2 | 0x4 | 0x200);
// Our symbols lie beside the program, which names them by their
// file alone. (It fails if a backtrace was asked for before:
// then it is there, and looks beside every module.)
let beside = std::env::current_exe().ok().and_then(|p| Some(p.parent()?.to_path_buf())).unwrap_or_default();
let beside: Vec<u16> = std::os::windows::ffi::OsStrExt::encode_wide(beside.as_os_str()).chain([0]).collect();
initialize(process, beside.as_ptr(), 1);
Some(Symbols { from_address, process })
}
}
fn name(&self, address: usize) -> Option<String> {
// `SYMBOL_INFO`: 88 bytes with the name's first character at 84.
const NAME: usize = 84;
const ROOM: usize = 512;
let mut info = [0u64; (NAME + ROOM) / 8 + 1];
let at = info.as_mut_ptr().cast::<u8>();
let mut off = 0u64;
// SAFETY: a buffer of the structure's size and the name's, its size
// fields set as asked.
unsafe {
at.cast::<u32>().write(88);
at.add(80).cast::<u32>().write(ROOM as u32);
if (self.from_address)(self.process, address as u64 - 1, &mut off, at) == 0 {
return None;
}
let name = std::ffi::CStr::from_ptr(at.add(NAME).cast());
Some(name.to_string_lossy().into_owned())
}
}
}
impl Names {
pub(super) fn new() -> Names {
Names {
known: HashMap::new(),
symbols: Symbols::load(),
}
}
/// The module `address` lies in, and where in it; whether it is ours.
fn module(address: usize) -> (String, usize, bool) {
use windows_sys::Win32::System::LibraryLoader::{
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameW,
GetModuleHandleExW, GetModuleHandleW,
};
let mut module = std::ptr::null_mut();
let mut path = [0u16; 260];
// SAFETY: an address, no name; plain queries.
unsafe {
let flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;
if GetModuleHandleExW(flags, address as *const u16, &mut module) == 0 {
return ("?".into(), address, false);
}
let len = GetModuleFileNameW(module, path.as_mut_ptr(), path.len() as u32) as usize;
let path = String::from_utf16_lossy(&path[..len]);
let file = path.rsplit('\\').next().unwrap_or("?").to_string();
(file, address - module as usize, module == GetModuleHandleW(std::ptr::null()))
}
}
/// A name for `address`: our own functions by their names, others by
/// their module and place in it.
fn of(&mut self, address: usize) -> String {
if let Some(name) = self.known.get(&address) {
return name.clone();
}
let (file, at, ours) = Self::module(address);
let name = match self.symbols.as_ref().filter(|_| ours).and_then(|s| s.name(address)) {
Some(name) => name,
None => format!("{}+{at:#x}", file.strip_suffix(".dll").unwrap_or(&file)),
};
self.known.insert(address, name.clone());
name
}
/// Where a stack says the thread was: the innermost functions that are
/// not the standard library's or this module's.
fn site(&mut self, stack: &[usize; DEPTH]) -> String {
let mut parts: Vec<String> = Vec::new();
for &address in stack.iter().take_while(|a| **a != 0) {
let name = self.of(address);
let plain = name.trim_start_matches('<').trim_start_matches("impl$").trim_start_matches(|c: char| c.is_ascii_digit());
let skipped = ["std::", "core::", "alloc::", "windows_core::", "windows::"].iter().any(|p| plain.starts_with(p))
|| ["timeline::hooks::", "timeline::record::"].iter().any(|p| name.contains(p))
|| ["KERNEL", "ntdll", "kernel"].iter().any(|p| name.starts_with(p));
if !skipped {
parts.push(name.replace("victory_gpu::", "").replace("victory_hle::", "hle::"));
}
if parts.len() == 3 {
break;
}
}
parts.join(" < ")
}
}
/// A part of a chain: what was done, or waited for, from when to when.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Part {
pub(super) from: u64,
pub(super) to: u64,
/// The thread (0: the card).
pub(super) thread: u32,
pub(super) cause: String,
}
/// A wait that ended, as the chains see it.
#[derive(Clone, Copy, Debug)]
struct Wait {
t0: u64,
t1: u64,
object: u64,
fence: u64,
event: usize,
}
/// A submission: when it went to the card, from which thread, and from when
/// to when it ran there.
#[derive(Clone, Copy, Debug)]
pub(super) struct Run {
pub(super) fence: u64,
pub(super) t0: u64,
pub(super) t1: u64,
pub(super) thread: u32,
pub(super) on: (u64, u64),
}
/// What was recorded, by thread and in order.
pub(super) struct Trace {
pub(super) events: Vec<Event>,
/// The spans of a thread (places among the events), by their beginning.
spans: HashMap<u32, Vec<usize>>,
/// The waits of a thread, by their end.
waits: HashMap<u32, Vec<Wait>>,
/// Who signalled an object when.
wakes: HashMap<u64, Vec<(u64, u32)>>,
/// The submissions, by the fence's value.
pub(super) runs: Vec<Run>,
pub(super) frames: Vec<(u64, u32)>,
}
impl Trace {
/// `stamps`: the card's times of a submission by its place, as ticks.
pub(super) fn new(mut events: Vec<Event>, stamps: &[(u64, u64)]) -> Trace {
events.sort_by_key(|e| (e.t0, std::cmp::Reverse(e.t1)));
let mut trace = Trace {
events: Vec::new(),
spans: HashMap::new(),
waits: HashMap::new(),
wakes: HashMap::new(),
runs: Vec::new(),
frames: Vec::new(),
};
for (i, e) in events.iter().enumerate() {
match e.kind {
Kind::Span | Kind::Calls | Kind::Kernel => trace.spans.entry(e.thread).or_default().push(i),
Kind::Wait => trace.waits.entry(e.thread).or_default().push(Wait {
t0: e.t0,
t1: e.t1,
object: e.a,
fence: e.b,
event: i,
}),
Kind::Wake => trace.wakes.entry(e.a).or_default().push((e.t0, e.thread)),
Kind::Sent => {
let on = (e.b as usize).checked_sub(1).and_then(|at| stamps.get(at)).copied().unwrap_or((0, 0));
trace.runs.push(Run {
fence: e.a,
t0: e.t0,
t1: e.t1,
thread: e.thread,
on,
});
trace.spans.entry(e.thread).or_default().push(i);
}
Kind::Frame => trace.frames.push((e.t1, e.thread)),
Kind::Told | Kind::Poll | Kind::Sample => {}
}
}
for waits in trace.waits.values_mut() {
waits.sort_by_key(|w| w.t1);
}
trace.runs.sort_by_key(|r| r.fence);
trace.events = events;
trace
}
/// Who ended the wait `w` of `thread`, and when.
fn waker(&self, thread: u32, w: &Wait) -> Option<(u32, u64)> {
let wakes = self.wakes.get(&w.object)?;
let end = wakes.partition_point(|k| k.0 <= w.t1);
wakes[..end].iter().rev().take_while(|k| k.0 >= w.t0).find(|k| k.1 != thread).map(|k| (k.1, k.0))
}
/// What `thread` was doing in `[from, to)`, the innermost span counting;
/// the newest part first.
fn doing(&self, thread: u32, from: u64, to: u64, out: &mut Vec<Part>) {
if from >= to {
return;
}
let none = Vec::new();
let spans = self.spans.get(&thread).unwrap_or(&none);
// The spans that touch it (a span is at most some frames long).
let end = spans.partition_point(|&i| self.events[i].t0 < to);
let touching: Vec<&Event> =
spans[..end].iter().map(|&i| &self.events[i]).filter(|e| e.t1 > from).collect();
let mut edges: Vec<u64> = vec![from, to];
for e in &touching {
edges.extend([e.t0, e.t1].iter().filter(|t| **t > from && **t < to));
}
edges.sort_unstable();
edges.dedup();
let mut parts: Vec<Part> = Vec::new();
for pair in edges.windows(2) {
let (a, b) = (pair[0], pair[1]);
let inner = touching.iter().filter(|e| e.t0 <= a && e.t1 >= b).max_by_key(|e| (e.t0, std::cmp::Reverse(e.t1)));
let cause = match inner {
Some(e) if e.kind == Kind::Calls => {
// Of a run of list calls, the part that was ours.
let ours = (b - a) * e.b.min(e.t1 - e.t0) / (e.t1 - e.t0).max(1);
parts.push(Part {
from: a,
to: a + ours,
thread,
cause: "recording: inside our list calls".into(),
});
parts.push(Part {
from: a + ours,
to: b,
thread,
cause: "recording: between list calls (the caller's code)".into(),
});
continue;
}
Some(e) if e.kind == Kind::Kernel => format!("kernel: {}", e.name),
Some(e) => e.name.to_string(),
None => OUTSIDE.into(),
};
match parts.last_mut() {
Some(last) if last.cause == cause => last.to = b,
_ => parts.push(Part { from: a, to: b, thread, cause }),
}
}
out.extend(parts.into_iter().rev().filter(|p| p.from < p.to));
}
/// The chain that ended at `t` on `thread`, back to `until`: what that
/// thread did since its last wait ended, then what the thread that ended
/// the wait had done, or the card, and so on. Newest first, end to end.
pub(super) fn chain(&self, mut thread: u32, mut t: u64, until: u64) -> Vec<Part> {
let mut out = Vec::new();
for _ in 0..200_000 {
if t <= until {
break;
}
let waits = self.waits.get(&thread).map_or(&[][..], |w| w);
let last = waits[..waits.partition_point(|w| w.t1 <= t)].last().filter(|w| w.t1 > until).copied();
let Some(w) = last else {
self.doing(thread, until, t, &mut out);
break;
};
self.doing(thread, w.t1, t, &mut out);
let name = self.events[w.event].name;
if w.fence != 0 && w.fence != COPY_QUEUE {
match self.card(w.fence, w.t1, until, &mut out) {
Some((sender, at)) if at < t => {
(thread, t) = (sender, at);
continue;
}
Some(_) => {}
None => break,
}
}
match self.waker(thread, &w) {
Some((other, at)) if at < t && w.fence == 0 => {
out.push(Part {
from: at.max(until),
to: w.t1,
thread,
cause: "woken, not running yet".into(),
});
(thread, t) = (other, at);
}
_ => {
let cause = match w.fence {
0 => format!("a wait nobody seen here ended ({name})"),
COPY_QUEUE => "the card's copy queue".into(),
_ => "the card (no times of it)".into(),
};
out.push(Part {
from: w.t0.max(until),
to: w.t1,
thread,
cause,
});
t = w.t0;
}
}
}
out.retain(|p| p.from < p.to);
out
}
/// The card's part of a chain: it reached `fence` by `t`. Back through
/// the submissions that stood in its queue, to the sending of one that
/// found it idle: by whom, and when; `None` if that goes back before
/// `until`, or (nothing put in) if the card's times are not known.
fn card(&self, fence: u64, t: u64, until: u64, out: &mut Vec<Part>) -> Option<(u32, u64)> {
let mut i = self.runs.partition_point(|r| r.fence < fence);
let first = self.runs.get(i)?;
if first.on == (0, 0) || first.t0 >= t {
return Some((0, u64::MAX));
}
let part = |from: u64, to: u64, cause: &str| Part {
from: from.max(until),
to: to.max(until),
thread: 0,
cause: cause.into(),
};
let mut end = first.on.1.min(t);
out.push(part(end, t, "the card was done, the wait not over yet"));
loop {
let run = self.runs[i];
let begun = run.on.0.clamp(run.t0.min(end), end);
out.push(part(begun, end, "the card running submissions"));
if begun <= until {
return None;
}
match i.checked_sub(1).map(|before| self.runs[before]) {
Some(before) if before.on != (0, 0) && before.on.1 >= run.t0 => {
let to = before.on.1.min(begun);
out.push(part(to, begun, "the card between submissions"));
end = to;
i -= 1;
if end <= until {
return None;
}
}
_ => {
let sent = run.t1.min(begun);
out.push(part(sent, begun, "sent, the card not started yet"));
return Some((run.thread, sent));
}
}
}
}
}
/// The cause of what a thread did outside every span.
const OUTSIDE: &str = "outside our spans";
fn ms(ticks: u64) -> f64 {
ticks as f64 * 1e3 / frequency() as f64
}
/// `parts` by cause, the largest first.
fn by_cause(parts: &[Part], label: &dyn Fn(u32) -> String) -> Vec<(String, u64)> {
let mut sums: BTreeMap<String, u64> = BTreeMap::new();
for p in parts {
let cause = if p.cause == OUTSIDE { format!("{} on {}", p.cause, label(p.thread)) } else { p.cause.clone() };
*sums.entry(cause).or_default() += p.to - p.from;
}
let mut sums: Vec<(String, u64)> = sums.into_iter().collect();
sums.sort_by_key(|s| std::cmp::Reverse(s.1));
sums
}
/// The summary.
pub(super) fn summary(trace: &Trace, names: &mut Names, stacks: &[[usize; DEPTH]], before: &Threads, after: &Threads) -> String {
let mut text = String::new();
let Some((&(start, _), &(stop, _))) = trace.frames.first().zip(trace.frames.last()) else {
return "no frames\n".into();
};
let frames = (trace.frames.len() - 1).max(1) as f64;
let mut labels: HashMap<u32, String> = HashMap::new();
for (&id, (_, name, begun)) in after.all.iter().chain(before.all.iter()) {
labels.entry(id).or_insert_with(|| match name.is_empty() {
true => format!("{id} ({})", names.of(*begun + 1)),
false => format!("{id} \"{name}\""),
});
}
let label = |id: u32| match id {
0 => "the card".to_string(),
id => labels.get(&id).cloned().unwrap_or_else(|| id.to_string()),
};
let _ = writeln!(text, "{} frames in {:.1} ms ({:.1} ms a frame); {} events", frames, ms(stop - start), ms(stop - start) / frames, trace.events.len());
// The chains.
let mut all: Vec<Part> = Vec::new();
for pair in trace.frames.windows(2) {
let chain = trace.chain(pair[1].1, pair[1].0, pair[0].0);
let _ = writeln!(text, "\nframe of {:.1} ms, present on {}: the chain it came out of, by cause", ms(pair[1].0 - pair[0].0), label(pair[1].1));
for (cause, sum) in by_cause(&chain, &label).into_iter().take(24) {
let _ = writeln!(text, " {:7.2} ms {cause}", ms(sum));
}
all.extend(chain);
}
let whole = trace.chain(trace.frames.last().map_or(0, |f| f.1), stop, start);
let _ = writeln!(text, "\nthe chain back through all frames, per frame, by cause");
for (cause, sum) in by_cause(&whole, &label).into_iter().take(40) {
let _ = writeln!(text, " {:7.2} ms {cause}", ms(sum) / frames);
}
let _ = writeln!(text, "\nby thread, per frame");
let mut by_thread: BTreeMap<u32, u64> = BTreeMap::new();
for p in &whole {
*by_thread.entry(p.thread).or_default() += p.to - p.from;
}
let mut by_thread: Vec<(u32, u64)> = by_thread.into_iter().collect();
by_thread.sort_by_key(|t| std::cmp::Reverse(t.1));
for (thread, sum) in by_thread {
let _ = writeln!(text, " {:7.2} ms {}", ms(sum) / frames, label(thread));
}
let _ = writeln!(text, "\nthat chain, oldest first (parts under 0.15 ms left out; ms since the first present)");
for p in whole.iter().rev().filter(|p| ms(p.to - p.from) >= 0.15) {
let _ = writeln!(text, " {:8.2} +{:6.2} {:32} {}", ms(p.from - start), ms(p.to - p.from), label(p.thread), p.cause);
}
// The card.
let runs: Vec<&Run> = trace.runs.iter().filter(|r| r.on != (0, 0) && r.on.1 > start && r.on.0 < stop).collect();
let (mut busy, mut reach) = (0, start);
let mut idle: BTreeMap<String, u64> = BTreeMap::new();
let mut idle_all = 0;
for r in &runs {
let (a, b) = (r.on.0.clamp(start, stop), r.on.1.clamp(start, stop));
if a > reach {
idle_all += a - reach;
if r.t1 > reach {
for p in trace.chain(r.thread, r.t1.min(a), reach) {
let cause = if p.cause == OUTSIDE { format!("{} on {}", p.cause, label(p.thread)) } else { p.cause };
*idle.entry(cause).or_default() += p.to - p.from;
}
}
}
busy += b.saturating_sub(a.max(reach));
reach = reach.max(b);
}
let _ = writeln!(
text,
"\nthe card, per frame: {:.2} ms running {:.1} submissions, {:.2} ms idle between them; of the idle time, by what the chain to the \
next submission was",
ms(busy) / frames,
runs.len() as f64 / frames,
ms(idle_all) / frames
);
let mut idle: Vec<(String, u64)> = idle.into_iter().collect();
idle.sort_by_key(|i| std::cmp::Reverse(i.1));
for (cause, sum) in idle.into_iter().take(30) {
let _ = writeln!(text, " {:7.2} ms {cause}", ms(sum) / frames);
}
// Threads.
let rate = (after.cycles.saturating_sub(before.cycles)) as f64 / ms(after.ticks.saturating_sub(before.ticks)).max(1e-9);
let mut threads: Vec<(u32, f64, u64)> = after
.all
.iter()
.map(|(&id, t)| {
let ran = t.0.saturating_sub(before.all.get(&id).map_or(0, |b| b.0)) as f64 / rate.max(1e-9);
let waits = trace.waits.get(&id).map_or(&[][..], |w| w);
let waited = waits.iter().map(|w| w.t1.min(stop).saturating_sub(w.t0.max(start))).sum();
(id, ran, waited)
})
.collect();
threads.sort_by(|a, b| b.1.total_cmp(&a.1));
let _ = writeln!(text, "\nthreads, per frame: running, waiting in what is wrapped, outermost spans of ours");
for (id, ran, waited) in threads.into_iter().filter(|t| t.1 / frames >= 0.2).take(60) {
let mut sums: BTreeMap<&str, u64> = BTreeMap::new();
let mut reach = 0;
for &i in trace.spans.get(&id).map_or(&[][..], |s| s) {
let e = &trace.events[i];
if e.t1 > reach {
*sums.entry(e.name).or_default() += e.t1.min(stop).saturating_sub(e.t0.max(reach).max(start));
reach = e.t1;
}
}
let mut sums: Vec<(&str, u64)> = sums.into_iter().collect();
sums.sort_by_key(|s| std::cmp::Reverse(s.1));
let spans: Vec<String> = sums.iter().take(5).map(|(name, sum)| format!("{name} {:.1}", ms(*sum) / frames)).collect();
let _ = writeln!(text, " {:6.1} ran {:6.1} waited {:36} {}", ran / frames, ms(waited) / frames, label(id), spans.join(", "));
}
// Spans, all threads, each by name with what lies in it.
let mut sums: BTreeMap<&str, (u64, u64, u64)> = BTreeMap::new();
for e in trace.events.iter().filter(|e| matches!(e.kind, Kind::Span | Kind::Kernel | Kind::Sent) && e.t1 > start && e.t0 < stop) {
let s = sums.entry(e.name).or_default();
let took = e.t1.min(stop) - e.t0.max(start);
*s = (s.0 + took, s.1 + 1, s.2.max(took));
}
let mut sums: Vec<_> = sums.into_iter().collect();
sums.sort_by_key(|s| std::cmp::Reverse(s.1.0));
let _ = writeln!(text, "\nspans and kernel calls, all threads, per frame (a span counts what lies in it)");
for (name, (sum, n, most)) in sums.into_iter().take(80) {
let _ = writeln!(text, " {:8.2} ms in {:8.1}, longest {:6.2} {name}", ms(sum) / frames, n as f64 / frames, ms(most));
}
// Waits: who, where, for whom.
let mut groups: HashMap<(u32, String, String), (u64, u64, u64)> = HashMap::new();
for (&thread, waits) in &trace.waits {
for w in waits.iter().filter(|w| w.t1 > start && w.t0 < stop && ms(w.t1 - w.t0) >= 0.05) {
let e = &trace.events[w.event];
let site = (e.stack as usize).checked_sub(1).and_then(|s| stacks.get(s)).map_or(String::new(), |s| names.site(s));
let by = match (w.fence, self_waker(trace, thread, w)) {
(COPY_QUEUE, _) => "the card's copy queue".to_string(),
(0, Some((other, _))) => label(other),
(0, None) => "nobody seen".into(),
_ => "the card".into(),
};
let g = groups.entry((thread, format!("{} at {site}", e.name), by)).or_default();
let took = w.t1.min(stop) - w.t0.max(start);
*g = (g.0 + took, g.1 + 1, g.2.max(took));
}
}
let mut groups: Vec<_> = groups.into_iter().collect();
groups.sort_by_key(|g| std::cmp::Reverse(g.1.0));
let _ = writeln!(text, "\nwaits of 50 us or more, per frame: who, what and where, who ended them");
for ((thread, what, by), (sum, n, most)) in groups.into_iter().take(150) {
let _ = writeln!(
text,
" {:7.2} ms in {:7.1}, longest {:6.2} {} | {what} | ended by {by}",
ms(sum) / frames,
n as f64 / frames,
ms(most),
label(thread)
);
}
// Long list calls.
let mut calls: HashMap<String, (u64, u64)> = HashMap::new();
for e in trace.events.iter().filter(|e| e.name == "a long list call" && e.t1 > start && e.t0 < stop) {
let site = (e.stack as usize).checked_sub(1).and_then(|s| stacks.get(s)).map_or(String::new(), |s| names.site(s));
let c = calls.entry(site).or_default();
*c = (c.0 + (e.t1 - e.t0), c.1 + 1);
}
let mut calls: Vec<_> = calls.into_iter().collect();
calls.sort_by_key(|c| std::cmp::Reverse(c.1.0));
let _ = writeln!(text, "\nlist calls of 50 us or more, per frame");
for (site, (sum, n)) in calls.into_iter().take(25) {
let _ = writeln!(text, " {:7.2} ms in {:7.1} {site}", ms(sum) / frames, n as f64 / frames);
}
text
}
fn self_waker(trace: &Trace, thread: u32, w: &Wait) -> Option<(u32, u64)> {
trace.waker(thread, w)
}
fn escaped(text: &str) -> String {
text.chars()
.flat_map(|c| match c {
'"' => vec!['\\', '"'],
'\\' => vec!['\\', '\\'],
c if (c as u32) < 32 => vec![' '],
c => vec![c],
})
.collect()
}
/// The Chrome trace.
pub(super) fn chrome(
trace: &Trace,
names: &mut Names,
stacks: &[[usize; DEPTH]],
threads: &Threads,
out: &mut impl std::io::Write,
) -> std::io::Result<()> {
let start = trace.events.first().map_or(0, |e| e.t0);
let us = |t: u64| t.saturating_sub(start) as f64 * 1e6 / frequency() as f64;
write!(out, "{{\"traceEvents\":[\n{{\"ph\":\"M\",\"pid\":1,\"tid\":0,\"name\":\"thread_name\",\"args\":{{\"name\":\"the card\"}}}}")?;
for (id, (_, name, begun)) in &threads.all {
let name = if name.is_empty() { names.of(*begun + 1) } else { name.clone() };
write!(
out,
",\n{{\"ph\":\"M\",\"pid\":1,\"tid\":{id},\"name\":\"thread_name\",\"args\":{{\"name\":\"{}\"}}}}",
escaped(&name)
)?;
}
for e in &trace.events {
let (ts, dur) = (us(e.t0), us(e.t1) - us(e.t0));
let (pid, tid, cpu) = (1, e.thread, e.cpu);
match e.kind {
Kind::Wake => {}
Kind::Told => write!(
out,
",\n{{\"ph\":\"i\",\"s\":\"t\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"cat\":\"told\",\"name\":\"{}\",\"args\":{{\"at\":\"{:#x}\",\"value\":\"{:#x}\"}}}}",
escaped(e.name),
e.a,
e.b
)?,
Kind::Sample => {
let stack = (e.stack as usize).checked_sub(1).and_then(|s| stacks.get(s)).map_or(&[][..], |s| &s[..]);
let stack: Vec<String> = stack.iter().take_while(|a| **a != 0).map(|a| format!("{a:#x}")).collect();
write!(
out,
",\n{{\"ph\":\"i\",\"s\":\"t\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"cat\":\"sample\",\"name\":\"{}\",\"args\":{{\"at\":\"{:#x}\",\"stack\":\"{}\"}}}}",
escaped(&names.of(e.a as usize)),
e.a,
stack.join(" ")
)?;
}
Kind::Frame => write!(out, ",\n{{\"ph\":\"i\",\"s\":\"g\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"name\":\"a frame ends\"}}")?,
Kind::Wait => {
let site = (e.stack as usize).checked_sub(1).and_then(|s| stacks.get(s)).map_or(String::new(), |s| names.site(s));
write!(
out,
",\n{{\"ph\":\"X\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"dur\":{dur:.1},\"cat\":\"wait\",\"cname\":\"grey\",\
\"name\":\"wait\",\"args\":{{\"what\":\"{}\",\"object\":\"{:#x}\",\"fence\":\"{}\",\"at\":\"{}\"}}}}",
e.name,
e.a,
e.b,
escaped(&site)
)?;
}
_ => write!(
out,
",\n{{\"ph\":\"X\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"dur\":{dur:.1},\"cat\":\"{:?}\",\"name\":\"{}\",\
\"args\":{{\"a\":{},\"b\":{},\"cpu\":{cpu}}}}}",
e.kind,
escaped(e.name),
e.a,
e.b
)?,
}
}
for r in trace.runs.iter().filter(|r| r.on != (0, 0)) {
write!(
out,
",\n{{\"ph\":\"X\",\"pid\":1,\"tid\":0,\"ts\":{:.1},\"dur\":{:.1},\"name\":\"submission {}\",\"args\":{{\"sent by\":{}}}}}",
us(r.on.0),
us(r.on.1) - us(r.on.0),
r.fence,
r.thread
)?;
}
// Who woke whom.
let mut id = 0u64;
for (&thread, waits) in &trace.waits {
for w in waits.iter().filter(|w| ms(w.t1 - w.t0) >= 0.1) {
if let Some((other, at)) = trace.waker(thread, w) {
id += 1;
write!(
out,
",\n{{\"ph\":\"s\",\"pid\":1,\"tid\":{other},\"ts\":{:.1},\"id\":{id},\"cat\":\"wake\",\"name\":\"woke\"}},\
\n{{\"ph\":\"f\",\"bp\":\"e\",\"pid\":1,\"tid\":{thread},\"ts\":{:.1},\"id\":{id},\"cat\":\"wake\",\"name\":\"woke\"}}",
us(at),
us(w.t1)
)?;
}
}
}
writeln!(out, "\n]}}")
}
/// Writes both files.
pub(super) fn write(file: &std::path::Path, data: Data, before: &Threads, after: &Threads, stamps: Vec<(u64, u64)>) {
let mut names = Names::new();
let (events, lost) = (data.events.len(), data.lost);
let trace = Trace::new(data.events, &stamps);
let mut text = summary(&trace, &mut names, &data.stacks, before, after);
if lost > 0 {
let _ = writeln!(text, "\n{lost} events were lost: the buffer was full");
}
let beside = file.with_extension("txt");
let written = std::fs::write(&beside, text).and_then(|()| {
let mut out = std::io::BufWriter::new(std::fs::File::create(file)?);
chrome(&trace, &mut names, &data.stacks, after, &mut out)?;
std::io::Write::flush(&mut out)
});
match written {
Ok(()) => tracing::info!(file = %file.display(), summary = %beside.display(), events, lost, "the timeline is written"),
Err(e) => tracing::warn!(error = %e, file = %file.display(), "the timeline could not be written"),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn event(kind: Kind, name: &'static str, thread: u32, t: (u64, u64), a: u64, b: u64) -> Event {
Event {
t0: t.0,
t1: t.1,
a,
b,
name,
thread,
stack: 0,
cpu: 0,
kind,
}
}
fn causes(parts: &[Part]) -> Vec<(u32, u64, u64, &str)> {
parts.iter().map(|p| (p.thread, p.from, p.to, p.cause.as_str())).collect()
}
/// The present's thread waited for the title's, which waited for the
/// relay, which waited for the card, whose submission a third thread
/// sent: the chain goes back through all of them, end to end.
#[test]
fn a_chain_goes_back_through_who_woke_whom_and_the_card() {
let events = vec![
event(Kind::Frame, "present", 1, (1000, 1000), 0, 0),
event(Kind::Frame, "present", 1, (2000, 2000), 0, 0),
// Thread 1 presents after waiting for object 7.
event(Kind::Span, "present", 1, (1900, 2000), 0, 0),
event(Kind::Wait, "WaitForSingleObject", 1, (1100, 1850), 7, 0),
event(Kind::Wake, "SetEvent", 2, (1840, 1840), 7, 0),
// (An earlier wake of the same object, before the wait.)
event(Kind::Wake, "SetEvent", 9, (1050, 1050), 7, 0),
// Thread 2 landed flights after the card reached 12.
event(Kind::Span, "landing", 2, (1700, 1845), 0, 0),
event(Kind::Span, "merging", 2, (1750, 1800), 0, 0),
event(Kind::Wait, "WaitForSingleObject", 2, (1200, 1690), 99, 12),
// The card ran 11 and 12, both sent by thread 3; 11 found it idle.
event(Kind::Sent, "ExecuteCommandLists", 3, (1290, 1300), 11, 1),
event(Kind::Sent, "ExecuteCommandLists", 3, (1390, 1400), 12, 2),
event(Kind::Span, "steps", 3, (1100, 1290), 0, 0),
];
let trace = Trace::new(events, &[(1310, 1500), (1500, 1680)]);
let chain = trace.chain(1, 2000, 1000);
assert_eq!(
causes(&chain),
[
(1, 1900, 2000, "present"),
(1, 1850, 1900, OUTSIDE),
(1, 1840, 1850, "woken, not running yet"),
(2, 1800, 1840, "landing"),
(2, 1750, 1800, "merging"),
(2, 1700, 1750, "landing"),
(2, 1690, 1700, OUTSIDE),
(0, 1680, 1690, "the card was done, the wait not over yet"),
(0, 1500, 1680, "the card running submissions"),
(0, 1310, 1500, "the card running submissions"),
(0, 1300, 1310, "sent, the card not started yet"),
(3, 1290, 1300, "ExecuteCommandLists"),
(3, 1100, 1290, "steps"),
(3, 1000, 1100, OUTSIDE),
]
);
// End to end: no part of the frame is missing or counted twice.
assert!(chain.windows(2).all(|p| p[0].from == p[1].to));
}
/// A wait nobody was seen to end (a timer) is a cause of its own, and
/// the chain goes on with the thread before it.
#[test]
fn a_wait_without_a_waker_stays_with_its_thread() {
let events = vec![
event(Kind::Wait, "Sleep", 1, (120, 180), 0, 0),
event(Kind::Wait, "WaitOnAddress", 1, (20, 60), 5, 0),
event(Kind::Wake, "WakeByAddressSingle", 1, (50, 50), 5, 0),
];
let trace = Trace::new(events, &[]);
assert_eq!(
causes(&trace.chain(1, 200, 0)),
[
(1, 180, 200, OUTSIDE),
(1, 120, 180, "a wait nobody seen here ended (Sleep)"),
(1, 60, 120, OUTSIDE),
(1, 20, 60, "a wait nobody seen here ended (WaitOnAddress)"),
(1, 0, 20, OUTSIDE),
]
);
}
/// Real threads, real waits: what the wrappers record names who ended
/// them, and the chain leads to the thread that worked.
#[test]
fn real_waits_are_recorded_with_who_ended_them() {
use super::super::{hooks, record, span};
use std::sync::{Arc, Condvar, Mutex};
hooks::wrap_own();
record::make_room();
let gate = Arc::new((Mutex::new(false), Condvar::new()));
let lock = Arc::new(Mutex::new(()));
record::begin();
record::frame();
let first = super::super::record::ticks();
let worker = {
let (gate, lock) = (gate.clone(), lock.clone());
std::thread::spawn(move || {
let held = lock.lock().unwrap();
let working = span("the work of a test");
std::thread::sleep(std::time::Duration::from_millis(5));
let spun = std::time::Instant::now();
while spun.elapsed().as_millis() < 30 {
std::hint::spin_loop();
}
working.end();
drop(held);
*gate.0.lock().unwrap() = true;
gate.1.notify_all();
record::thread()
})
};
{
let mut open = gate.0.lock().unwrap();
while !*open {
open = gate.1.wait(open).unwrap();
}
}
let last = super::super::record::ticks();
let me = record::thread();
let other = worker.join().unwrap();
// A contended lock.
let held = lock.lock().unwrap();
let second = {
let lock = lock.clone();
std::thread::spawn(move || {
drop(lock.lock().unwrap());
record::thread()
})
};
std::thread::sleep(std::time::Duration::from_millis(20));
drop(held);
let second = second.join().unwrap();
let data = record::end();
assert_eq!(data.lost, 0);
let trace = Trace::new(data.events, &[]);
let chain = trace.chain(me, last, first);
let work: u64 = chain.iter().filter(|p| p.thread == other && p.cause == "the work of a test").map(|p| p.to - p.from).sum();
assert!(ms(work) >= 20.0, "{chain:?}");
let contended = trace.waits[&second]
.iter()
.filter(|w| ms(w.t1 - w.t0) >= 10.0)
.find_map(|w| trace.waker(second, w));
assert_eq!(contended.map(|c| c.0), Some(me));
let mut names = Names::new();
let sites: Vec<String> = data.stacks.iter().map(|s| names.site(s)).collect();
assert!(sites.iter().any(|s| s.contains("real_waits_are_recorded")), "{sites:?}");
let mut json = Vec::new();
chrome(&trace, &mut names, &data.stacks, &Threads::now(), &mut json).unwrap();
assert!(json.starts_with(b"{\"traceEvents\""));
let text = summary(&trace, &mut names, &data.stacks, &Threads::now(), &Threads::now());
assert!(text.contains("frames in"));
}
}
+1
View File
@@ -2123,6 +2123,7 @@ pub(crate) fn install() {
EXCEPTION_POINTERS,
};
unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 {
let _fault = crate::timeline::span("a fault looked at");
// SAFETY: the system passes the exception being dispatched.
let r = unsafe { &*(*info).ExceptionRecord };
const READ: usize = 0;
+7 -1
View File
@@ -78,7 +78,13 @@ impl HostPolicy {
if !self.allows(dll) {
return None;
}
imp::resolve(dll, symbol)
let address = imp::resolve(dll, symbol)?;
// With a timeline asked for, what threads wait with is wrapped.
#[cfg(all(windows, feature = "diagnostics"))]
if let ImportSymbol::Name { name, .. } = symbol {
return Some(victory_gpu::timeline::import(name, address));
}
Some(address)
}
}
@@ -774,7 +774,9 @@ fn work(scheduler: &'static Scheduler) {
drop(lanes);
let started = std::time::Instant::now();
let traced = Traced::start(&job);
let reading = victory_gpu::timeline::span("streaming: a request");
let result = execute(&job.request);
reading.end();
walls_request(&job.request, &result, started);
stream_log::request(&job, started, &result);
if let Some(traced) = traced {
@@ -1341,6 +1343,7 @@ fn queue(this: QueueRef, command: Command) {
/// the pages are mapped just before, also those under addresses without a
/// list (memory only the CPU sees).
extern "system" fn submit(this: QueueRef) {
let _called = victory_gpu::timeline::span("the title's DirectStorage Submit");
// SAFETY: as above.
let id = unsafe { &*this }.state.id;
let Some(scheduler) = scheduler() else {
+1
View File
@@ -1065,6 +1065,7 @@ pub extern "system" fn XMemMapPhysicalPages(
// SAFETY: the title passes `n` page numbers, or null.
let pages = (!pages.is_null()).then(|| unsafe { std::slice::from_raw_parts(pages, n) }.to_vec());
let mut costed = Costed::begin(Some(n));
let _called = victory_gpu::timeline::span("the title's XMemMapPhysicalPages");
let mut physical = physical();
if let Some(costed) = &mut costed {
costed.waited = costed.started.elapsed().as_nanos() as u64;