Merge the frame critical path recorder: TOTK_CRIT=<first>-<last frame> with TOTK_TRACE=sched writes the guest threads' state changes and wakes, read by tools/crit_path.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Valiantsin DzerakhandClaude Opus 5.5 committed 2026-10-28 14:13:40 +03:00
commit 5da6c5bb89
3 files changed
+180 -1

No files matched your search

+1 -1
View File
@@ -33,7 +33,7 @@ static const char *const known[] = {
"APP_POOL", "ASSUME_FOCUS", "ASTC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_OFF", "AUDIO_PREFILL_MS", "APP_POOL", "ASSUME_FOCUS", "ASTC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_OFF", "AUDIO_PREFILL_MS",
"BACKGROUND_WINDOW", "BIND_A", "BIND_B", "BIND_DOWN", "BIND_L", "BIND_LCLICK", "BIND_LEFT", "BIND_MINUS", "BACKGROUND_WINDOW", "BIND_A", "BIND_B", "BIND_DOWN", "BIND_L", "BIND_LCLICK", "BIND_LEFT", "BIND_MINUS",
"BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y", "BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y",
"BIND_ZL", "BIND_ZR", "CLOTH_REALTIME", "CORE_DIAG", "DESC_TEMPLATE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", "BIND_ZL", "BIND_ZR", "CLOTH_REALTIME", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG",
"EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS", "EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS",
"FLIGHT_THUMBS", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "GPL", "GPL_DRAW_BUILD", "GPU", "FLIGHT_THUMBS", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "GPL", "GPL_DRAW_BUILD", "GPU",
"GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", "GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD",
+59
View File
@@ -123,6 +123,21 @@ static void unlock(void) { ReleaseSRWLockExclusive(&G); }
uint64_t kern_now_ns(void) { return plat_now_ns(); } uint64_t kern_now_ns(void) { return plat_now_ns(); }
// ---- TOTK_CRIT=<first>-<last frame> with TOTK_TRACE=sched: every state change and wake of the guest threads and
// every present over those frames, written to TOTK_CRIT_OUT (default crit.bin) at the last one, for
// tools/crit_path.py, which walks the chain of waits back from each present (holding G).
typedef struct { uint64_t ts, obj; uint32_t a, b; uint16_t kind, st; uint32_t pad; } CritEv;
enum { CRIT_STATE, CRIT_WAKE, CRIT_FRAME }; // a: thread; b: its waker (STATE), the waker (WAKE); st: new S_* state
#define CRIT_N (1u << 22) // 128 MiB, about 2000 fight frames
static CritEv *g_crit;
static uint32_t g_crit_n;
static int g_crit_on;
static uint64_t g_crit_lo, g_crit_hi;
static void crit_add(int kind, uint32_t a, uint32_t b, int st, uint64_t obj, uint64_t ts) {
if (g_crit_n < CRIT_N) g_crit[g_crit_n++] = (CritEv){ts, obj, a, b, (uint16_t)kind, (uint16_t)st, 0};
}
// ---- TOTK_TRACE=sched accounting (holding G) // ---- TOTK_TRACE=sched accounting (holding G)
#define RW_N 32 #define RW_N 32
static RtThread *g_render; // the thread that presents (sched trace, core diag) static RtThread *g_render; // the thread that presents (sched trace, core diag)
@@ -153,6 +168,7 @@ static void acct(RtThread *t, int st) {
wait_add(t == g_render ? g_rw : g_mw, t->st, t->wobj, waker, now - t->st_since); wait_add(t == g_render ? g_rw : g_mw, t->st, t->wobj, waker, now - t->st_since);
} }
} }
if (g_crit_on) crit_add(CRIT_STATE, t->handle, t->waker, st, t->wobj, now);
t->st = st; t->st = st;
t->st_since = now; t->st_since = now;
} }
@@ -218,6 +234,7 @@ static void wake(RtThread *t, uint32_t res) {
t->wres = res; t->wres = res;
t->waker = tcur ? tcur->handle : 0; t->waker = tcur ? tcur->handle : 0;
if (rt_trace & RT_TRACE_SCHED) t->wake_at = kern_now_ns(); if (rt_trace & RT_TRACE_SCHED) t->wake_at = kern_now_ns();
if (g_crit_on) crit_add(CRIT_WAKE, t->handle, t->waker, 0, 0, t->wake_at);
WakeConditionVariable(&t->cv); WakeConditionVariable(&t->cv);
} }
@@ -1013,6 +1030,47 @@ void kern_core_stats_reset(void) {
// calls) and of the render thread, the render and the main thread's longest waits by object and by the thread whose // calls) and of the render thread, the render and the main thread's longest waits by object and by the thread whose
// signal ended them, and the preemption latency. // signal ended them, and the preemption latency.
#define REP_N 8 #define REP_N 8
// At each present (holding G): starts recording at TOTK_CRIT's first frame, stops and writes the file at its last.
// File: "CRIT", thread count, event count (u32 each); per thread handle, priority, flags (1 main, 2 presents), host
// tid (u32 each); then the CritEv records.
static void crit_frame(RtThread *self, uint64_t frame) {
static int parsed;
if (!parsed) {
parsed = 1;
const char *e = cfg_get("TOTK_CRIT");
unsigned long long lo, hi;
if (e && sscanf(e, "%llu-%llu", &lo, &hi) == 2 && lo < hi && (g_crit = malloc(CRIT_N * sizeof *g_crit))) {
g_crit_lo = lo;
g_crit_hi = hi;
rt_log("crit: recording frames %llu-%llu", lo, hi);
}
}
if (!g_crit || frame < g_crit_lo || frame > g_crit_hi) return;
g_crit_on = 1;
crit_add(CRIT_FRAME, self ? self->handle : 0, 0, 0, frame, kern_now_ns());
if (frame < g_crit_hi) return;
g_crit_on = 0;
const char *path = cfg_get("TOTK_CRIT_OUT");
FILE *f = fopen(path && *path ? path : "crit.bin", "wb");
if (!f) {
rt_log("crit: cannot write %s", path && *path ? path : "crit.bin");
return;
}
uint32_t nt = 0;
for (RtThread *t = g_all; t; t = t->all) nt++;
fwrite("CRIT", 1, 4, f);
fwrite(&nt, 4, 1, f);
fwrite(&g_crit_n, 4, 1, f);
for (RtThread *t = g_all; t; t = t->all) {
uint32_t row[4] = {t->handle, (uint32_t)t->prio, (uint32_t)(t->is_main | (t == g_render) << 1), t->tid};
fwrite(row, 4, 4, f);
}
fwrite(g_crit, sizeof *g_crit, g_crit_n, f);
fclose(f);
rt_log("crit: %u events, %u threads, frames %llu-%llu%s", g_crit_n, nt, (unsigned long long)g_crit_lo,
(unsigned long long)g_crit_hi, g_crit_n >= CRIT_N ? " (buffer full: the last frames are incomplete)" : "");
}
void kern_sched_report(uint64_t frame) { void kern_sched_report(uint64_t frame) {
static uint64_t last; static uint64_t last;
typedef struct { typedef struct {
@@ -1029,6 +1087,7 @@ void kern_sched_report(uint64_t frame) {
g_render = self; g_render = self;
memset(g_rw, 0, sizeof g_rw); memset(g_rw, 0, sizeof g_rw);
} }
crit_frame(self, frame);
if (frame % 120) { if (frame % 120) {
unlock(); unlock();
return; return;
+120
View File
@@ -0,0 +1,120 @@
"""Critical path of each frame from a TOTK_CRIT recording (runtime/kernel.c crit_frame).
Walks back from every present on the presenting thread to the previous one. While the thread runs, waits for a
virtual core, sits in a host call or sleeps, the time goes to that thread and state. When it waits on a guest object,
the wake that ended the wait names the waker: the time from that signal to the end of the wait is wake latency, and
the walk goes on on the waker at the moment it signalled. A wait no guest thread ended (a timeout, a host signal)
counts whole. The sums per frame add up to the frame interval.
Usage: crit_path.py <crit.bin> [--top N]
"""
import argparse
import bisect
import struct
from collections import Counter, defaultdict
import numpy as np
STATES = ['off', 'run', 'core', 'host', 'sleep', 'sync', 'cv', 'lock', 'addr']
S_RUN, S_CORE, S_HOST, S_SLEEP = 1, 2, 3, 4
CRIT_STATE, CRIT_WAKE, CRIT_FRAME = 0, 1, 2
EV = np.dtype([('ts', '<u8'), ('obj', '<u8'), ('a', '<u4'), ('b', '<u4'), ('kind', '<u2'), ('st', '<u2'),
('pad', '<u4')])
def load(path):
data = open(path, 'rb').read()
assert data[:4] == b'CRIT', path
nt, ne = struct.unpack_from('<II', data, 4)
threads = {}
for i in range(nt):
h, prio, flags, tid = struct.unpack_from('<IiII', data, 12 + 16 * i)
threads[h] = (prio, flags, tid)
ev = np.frombuffer(data, EV, ne, 12 + 16 * nt)
return threads, ev
def label(h, threads):
prio, flags, _ = threads.get(h, (0, 0, 0))
role = 'main' if flags & 1 else 'present' if flags & 2 else ''
return f'{h:#x} p{prio}{" " + role if role else ""}' if h else 'host'
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('crit')
ap.add_argument('--top', type=int, default=30)
a = ap.parse_args()
threads, ev = load(a.crit)
seg = defaultdict(lambda: ([], [], [])) # per thread: starts, states, wakers at the start
wakes = defaultdict(lambda: ([], [])) # per thread: signal times, wakers
frames = []
for e in ev:
k = int(e['kind'])
if k == CRIT_STATE:
s = seg[int(e['a'])]
s[0].append(int(e['ts']))
s[1].append(int(e['st']))
s[2].append(int(e['b']))
elif k == CRIT_WAKE:
w = wakes[int(e['a'])]
w[0].append(int(e['ts']))
w[1].append(int(e['b']))
else:
frames.append((int(e['ts']), int(e['a']), int(e['obj'])))
tot = Counter()
lens = []
for (t0, p0, _), (t1, p1, _) in zip(frames, frames[1:]):
x, t, steps = p1, t1, 0
acc = Counter()
while t > t0 and steps < 100000:
steps += 1
starts, states, _ = seg[x]
i = bisect.bisect_left(starts, t) - 1
if i < 0:
acc[(x, 'unknown')] += t - t0
break
st, lo = states[i], max(starts[i], t0)
if st in (S_RUN, S_CORE, S_HOST, S_SLEEP) or st >= len(STATES):
acc[(x, STATES[st] if st < len(STATES) else f's{st}')] += t - lo
t = lo
continue
if st == 0:
acc[(x, 'off')] += t - lo
t = lo
continue
# a wait from starts[i] to the next state change: the last signal for x inside it ended it
end = starts[i + 1] if i + 1 < len(starts) else t
ws, wk = wakes[x]
j = bisect.bisect_right(ws, end) - 1
if j >= 0 and ws[j] >= starts[i] and wk[j]:
w = ws[j]
if w <= t0:
acc[(x, 'wake latency')] += t - t0
break
acc[(x, 'wake latency')] += max(0, t - w)
x, t = wk[j], min(t, w)
else:
acc[(x, 'wait ' + STATES[st] + ' (no guest waker)')] += t - lo
t = lo
tot.update(acc)
lens.append(t1 - t0)
n = len(lens)
if not n:
raise SystemExit('fewer than two presents recorded')
frame_ms = sum(lens) / n / 1e6
print(f'{n} frames, mean interval {frame_ms:.2f} ms; critical path per frame (ms, share):')
for (h, kind), ns in tot.most_common(a.top):
print(f' {ns / n / 1e6:7.3f} {100 * ns / sum(lens):5.1f}% {label(h, threads):24} {kind}')
by_kind = Counter()
for (h, kind), ns in tot.items():
by_kind[kind] += ns
print('by kind: ' + ', '.join(f'{k} {v / n / 1e6:.2f}' for k, v in by_kind.most_common()))
by_thread = Counter()
for (h, kind), ns in tot.items():
by_thread[h] += ns
print('by thread: ' + ', '.join(f'{label(h, threads)} {v / n / 1e6:.2f}' for h, v in by_thread.most_common(10)))
if __name__ == '__main__':
main()