Преглед изворни кода

Merge night/cpu: a sampling profiler

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local пре 1 дан
родитељ
комит
f76060a65d

+ 1 - 0
apps/victory/src/run.rs

@@ -196,6 +196,7 @@ pub fn run(
 #[cfg(all(windows, feature = "diagnostics"))]
 fn diagnostics(image: &victory_loader::LoadedImage, cfg: &victory_core::Config) {
     victory_loader::dump_stacks_on_schedule();
+    victory_loader::profile_on_schedule(victory_hle::frame_phase);
     victory_hle::modules::audio::capture::start();
     watch(image.base(), image.info().size_of_image as usize);
     poke(image.base(), image.info().size_of_image as usize);

+ 18 - 0
crates/victory-gpu/src/copystat.rs

@@ -1009,6 +1009,7 @@ pub(crate) fn recorded(started: std::time::Instant) {
 /// submission lock).
 pub(crate) fn submission_begins() {
     let now = now_us();
+    INSIDE.fetch_add(1, Relaxed);
     if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) {
         add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed)));
     }
@@ -1029,6 +1030,7 @@ pub(crate) fn submission_begins() {
 /// submission lock.
 pub(crate) fn submission_ends(lock: u64) {
     let now = now_us();
+    INSIDE.fetch_sub(1, Relaxed);
     SUBMITTED_AT.store(now, Relaxed);
     let (user, kernel) = thread_times();
     let (u, k) = ENTERED.with(|e| e.get());
@@ -1042,6 +1044,22 @@ pub(crate) fn submission_ends(lock: u64) {
     s.inside_kernel += kernel.saturating_sub(k);
 }
 
+/// The submissions being prepared now.
+static INSIDE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+
+/// What the frame is at, for the sampling profiler (`VICTORY_PROFILE`): 3
+/// in a submission, else 0 after a present until the first list call, 1 until
+/// the first submission, 2 behind it.
+pub(crate) fn phase() -> u32 {
+    if INSIDE.load(Relaxed) > 0 {
+        3
+    } else if SUBMITTED_SINCE.load(Relaxed) {
+        2
+    } else {
+        u32::from(RECORDED_SINCE.load(Relaxed))
+    }
+}
+
 /// The title calls its present (before our own copy to the window runs).
 pub(crate) fn present_begins() {
     add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed)));

+ 6 - 0
crates/victory-gpu/src/lib.rs

@@ -73,6 +73,12 @@ mod watch;
 
 #[cfg(windows)]
 pub use host::on_failure;
+
+/// What the frame is at (`copystat::phase`), for the sampling profiler.
+#[cfg(all(windows, feature = "diagnostics"))]
+pub fn frame_phase() -> u32 {
+    copystat::phase()
+}
 #[cfg(windows)]
 pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view};
 #[cfg(windows)]

+ 3 - 0
crates/victory-hle/src/lib.rs

@@ -13,6 +13,9 @@
 
 mod host;
 mod image_watch;
+#[cfg(all(windows, feature = "diagnostics"))]
+pub use victory_gpu::frame_phase;
+
 pub mod modules;
 mod registry;
 pub mod runtime;

+ 4 - 0
crates/victory-loader/src/lib.rs

@@ -28,6 +28,8 @@ pub mod prepare;
 pub(crate) mod publish;
 pub mod resolve;
 #[cfg(all(windows, feature = "diagnostics"))]
+mod profile;
+#[cfg(all(windows, feature = "diagnostics"))]
 mod stacks;
 #[cfg(windows)]
 mod threads;
@@ -48,6 +50,8 @@ pub use prepare::{PrepareError, PreparedImage, prepare};
 pub use resolve::{ImportResolver, Provenance, Resolution};
 #[cfg(all(windows, feature = "diagnostics"))]
 pub use stacks::{dump_stacks, dump_stacks_on_schedule};
+#[cfg(all(windows, feature = "diagnostics"))]
+pub use profile::profile_on_schedule;
 #[cfg(windows)]
 pub use threads::disable_thread_calls;
 #[cfg(windows)]

+ 195 - 0
crates/victory-loader/src/profile.rs

@@ -0,0 +1,195 @@
+//! Where the process's time goes: `VICTORY_PROFILE=<from>,<to>,<ms>,<file>`
+//! samples the stacks of the busiest threads every `<ms>` milliseconds
+//! between two times (seconds, as `VICTORY_STACKS`), and writes them counted
+//! to `<file>` at the end (several of them, one after another, with `;`
+//! between). A thread that waits is sampled like one that
+//! runs: its top frame says which (`ntdll`'s system calls).
+//!
+//! The file: `thread <id> <start> <cpu ms> <samples> <name>`, then
+//! `stack <thread> <phase> <count> <frame>;<frame>;...` (innermost first, as
+//! `module+rva`), where the phase is what the caller's function says of the
+//! frame at that moment.
+
+use std::collections::HashMap;
+use std::io::Write;
+use std::time::{Duration, Instant};
+
+use windows_sys::Win32::Foundation::{CloseHandle, FILETIME, HANDLE};
+use windows_sys::Win32::System::Threading::{
+    GetThreadTimes, OpenThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME,
+};
+
+use crate::crash::locate;
+use crate::stacks::{frames_of, name_of, other_threads, start_of};
+
+/// The threads sampled: those that ran most since they were last chosen.
+const BUSIEST: usize = 28;
+/// How often they are chosen anew.
+const CHOOSE: Duration = Duration::from_secs(1);
+
+/// What `VICTORY_PROFILE` says: from, to, every, the file.
+fn asked(list: &str) -> Option<(Duration, Duration, Duration, String)> {
+    let mut parts = list.splitn(4, ',');
+    let mut seconds = || parts.next()?.trim().parse::<f64>().ok();
+    let (from, to, ms) = (seconds()?, seconds()?, seconds()?);
+    let of = |s: f64| Duration::try_from_secs_f64(s).ok();
+    let file = parts.next()?.trim().to_string();
+    Some((of(from)?, of(to)?, of(ms / 1000.0)?, file)).filter(|(a, b, ms, f)| a < b && !ms.is_zero() && !f.is_empty())
+}
+
+struct Thread {
+    handle: HANDLE,
+    start: String,
+    name: String,
+    /// Its processor time, 100 ns: at first, when last chosen, now.
+    first: u64,
+    last: u64,
+    now: u64,
+    samples: u64,
+}
+
+fn cpu(thread: HANDLE) -> u64 {
+    // SAFETY: zeroed is a valid FILETIME, and the calls write them.
+    let mut t: [FILETIME; 4] = unsafe { std::mem::zeroed() };
+    let [a, b, c, d] = &mut t;
+    // SAFETY: an open thread; the pointers are to the structures above.
+    unsafe { GetThreadTimes(thread, a, b, c, d) };
+    let of = |f: &FILETIME| u64::from(f.dwHighDateTime) << 32 | u64::from(f.dwLowDateTime);
+    of(&t[2]) + of(&t[3])
+}
+
+/// Reads `VICTORY_PROFILE` and, if set, starts the thread that samples.
+/// `phase` is asked at each round.
+pub fn profile_on_schedule(phase: fn() -> u32) {
+    let Ok(list) = std::env::var("VICTORY_PROFILE") else {
+        return;
+    };
+    let start = Instant::now();
+    let all: Vec<_> = list.split(';').filter_map(asked).collect();
+    std::thread::spawn(move || {
+        for one in all {
+            profile(one, start, phase);
+        }
+    });
+}
+
+fn profile((from, to, every, file): (Duration, Duration, Duration, String), start: Instant, phase: fn() -> u32) {
+    std::thread::sleep(from.saturating_sub(start.elapsed()));
+    eprintln!("VIctory: the profile begins");
+    let mut threads: HashMap<u32, Thread> = HashMap::new();
+    let mut chosen: Vec<u32> = Vec::new();
+    let mut counts: HashMap<(u32, u32, Vec<u64>), u64> = HashMap::new();
+    let mut phases: HashMap<u32, u64> = HashMap::new();
+    let mut choose_at = Instant::now();
+    let mut rounds = 0u64;
+    while start.elapsed() < to {
+        let round = Instant::now();
+        if round >= choose_at {
+            choose_at = round + CHOOSE;
+            choose(&mut threads, &mut chosen);
+        }
+        let phase = phase();
+        *phases.entry(phase).or_default() += 1;
+        for id in &chosen {
+            if let Some(t) = threads.get_mut(id) {
+                let (frames, _) = frames_of(t.handle);
+                t.samples += 1;
+                if !frames.is_empty() {
+                    *counts.entry((*id, phase, frames)).or_default() += 1;
+                }
+            }
+        }
+        rounds += 1;
+        std::thread::sleep(every.saturating_sub(round.elapsed()));
+    }
+    choose(&mut threads, &mut chosen);
+    if let Err(e) = write(&file, &threads, &counts, &phases, rounds) {
+        eprintln!("VIctory: the profile was not written: {e}");
+    } else {
+        eprintln!("VIctory: the profile is in {file}");
+    }
+}
+
+/// Opens the threads that are new, and chooses the ones to sample.
+fn choose(threads: &mut HashMap<u32, Thread>, chosen: &mut Vec<u32>) {
+    for id in other_threads() {
+        threads.entry(id).or_insert_with(|| {
+            // SAFETY: opens a thread of our own process; kept open for the
+            // profile's life, so the id stays its own.
+            let handle =
+                unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, id) };
+            let first = if handle.is_null() { 0 } else { cpu(handle) };
+            Thread {
+                handle,
+                start: if handle.is_null() { String::new() } else { locate(start_of(handle)) },
+                name: if handle.is_null() { String::new() } else { name_of(handle) },
+                first,
+                last: first,
+                now: first,
+                samples: 0,
+            }
+        });
+    }
+    let mut ran: Vec<(u64, u32)> = Vec::new();
+    for (&id, t) in threads.iter_mut().filter(|(_, t)| !t.handle.is_null()) {
+        t.now = cpu(t.handle);
+        ran.push((t.now - t.last, id));
+        t.last = t.now;
+    }
+    ran.sort_unstable_by(|a, b| b.cmp(a));
+    *chosen = ran.into_iter().take(BUSIEST).map(|(_, id)| id).collect();
+}
+
+fn write(
+    file: &str,
+    threads: &HashMap<u32, Thread>,
+    counts: &HashMap<(u32, u32, Vec<u64>), u64>,
+    phases: &HashMap<u32, u64>,
+    rounds: u64,
+) -> std::io::Result<()> {
+    let mut out = std::io::BufWriter::new(std::fs::File::create(file)?);
+    writeln!(out, "rounds {rounds}")?;
+    for (phase, n) in phases {
+        writeln!(out, "phase {phase} {n}")?;
+    }
+    let mut names: HashMap<u64, String> = HashMap::new();
+    for (id, t) in threads {
+        writeln!(out, "thread {id} {} {} {} {}", t.start, (t.now - t.first) / 10_000, t.samples, t.name)?;
+        if !t.handle.is_null() {
+            // SAFETY: opened by `choose`.
+            unsafe { CloseHandle(t.handle) };
+        }
+    }
+    for ((id, phase, frames), n) in counts {
+        write!(out, "stack {id} {phase} {n} ")?;
+        for f in frames {
+            let name = names.entry(*f).or_insert_with(|| locate(*f as usize));
+            write!(out, "{name};")?;
+        }
+        writeln!(out)?;
+    }
+    out.flush()
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn what_is_asked_is_read_whole_or_not_at_all() {
+        assert_eq!(
+            asked("150, 160.5,5,D:\\a b,c.txt"),
+            Some((
+                Duration::from_secs(150),
+                Duration::from_millis(160_500),
+                Duration::from_millis(5),
+                "D:\\a b,c.txt".to_string()
+            ))
+        );
+        assert_eq!(asked("150,160,5"), None);
+        assert_eq!(asked("160,150,5,x"), None);
+        assert_eq!(asked("a,160,5,x"), None);
+        assert_eq!(asked("-1,160,5,x"), None);
+        assert_eq!(asked("1,160,0,x"), None);
+    }
+}

+ 14 - 8
crates/victory-loader/src/stacks.rs

@@ -66,10 +66,8 @@ struct BasicInfo {
 #[repr(C, align(16))]
 struct Aligned(CONTEXT);
 
-/// Prints every other thread's stack to stderr. Each thread is suspended
-/// only while its context is read and unwound into a buffer allocated
-/// beforehand (it may hold the heap lock).
-pub fn dump_stacks() {
+/// The ids of this process's threads but the caller's.
+pub(crate) fn other_threads() -> Vec<u32> {
     // SAFETY: plain queries and a snapshot of this process's threads.
     let (me, process, snapshot) = unsafe {
         (
@@ -79,7 +77,7 @@ pub fn dump_stacks() {
         )
     };
     if snapshot == INVALID_HANDLE_VALUE {
-        return;
+        return Vec::new();
     }
     let mut ids = Vec::new();
     // SAFETY: zeroed is a valid THREADENTRY32; its size is set before use.
@@ -96,6 +94,14 @@ pub fn dump_stacks() {
     }
     // SAFETY: we opened it.
     unsafe { CloseHandle(snapshot) };
+    ids
+}
+
+/// Prints every other thread's stack to stderr. Each thread is suspended
+/// only while its context is read and unwound into a buffer allocated
+/// beforehand (it may hold the heap lock).
+pub fn dump_stacks() {
+    let ids = other_threads();
     eprintln!("VIctory: stacks of {} threads", ids.len());
     for id in ids {
         // SAFETY: opens a thread of our own process.
@@ -124,7 +130,7 @@ pub fn dump_stacks() {
 }
 
 /// The thread's frames and its current and base scheduling priority (0-31).
-fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32, usize)) {
+pub(crate) fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32, usize)) {
     let mut frames = Vec::with_capacity(MAX_FRAMES);
     let mut info: BasicInfo = BasicInfo {
         exit_status: 0,
@@ -173,7 +179,7 @@ fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32, usize)) {
     (frames, (info.priority, info.base_priority, info.affinity))
 }
 
-fn start_of(thread: HANDLE) -> usize {
+pub(crate) fn start_of(thread: HANDLE) -> usize {
     let mut start = 0usize;
     // SAFETY: writes one pointer-sized start address.
     unsafe {
@@ -188,7 +194,7 @@ fn start_of(thread: HANDLE) -> usize {
     start
 }
 
-fn name_of(thread: HANDLE) -> String {
+pub(crate) fn name_of(thread: HANDLE) -> String {
     let mut name = std::ptr::null_mut();
     // SAFETY: the system allocates the string; we free it with LocalFree.
     unsafe {