From 36b9d5d3079c9c611512195e8dafb938b5d6e768 Mon Sep 17 00:00:00 2001 From: Claudius Date: Tue, 24 Nov 2026 19:02:26 +0000 Subject: [PATCH] iOS 27: what holds a home-screen flick near 30 a second (PACING.md), the frame timeline tool and the two frame observers Phone 2, 24 Nov, fork f523de65 + the trace branch, 7 min after SpringBoard: half of a flick's frames are a SpringBoard animation that asks for 30 a second (render thread wakes every refresh, nothing new on every other one); the page movement is GPU-bound: SpringBoard moves the page 52.8 times a second, 35-37 frames reach the panel, a heavy frame is 25-30 ms of GPU with two fragment chains of 11.5-12.9 and 6.4-7.6 ms. GPU at 455 MHz: heavy frames 1.79 -> 1.90 refreshes, light frames stay at 2. --- docs/ios27/PACING.md | 75 +++++++++ tools/ios27/perf/fbt-timeline.py | 188 ++++++++++++++++++++++ tools/ios27/perf/frame-observers/build.sh | 12 ++ tools/ios27/perf/frame-observers/cawake.m | 82 ++++++++++ tools/ios27/perf/frame-observers/sbpage.m | 107 ++++++++++++ 5 files changed, 464 insertions(+) create mode 100644 docs/ios27/PACING.md create mode 100755 tools/ios27/perf/fbt-timeline.py create mode 100755 tools/ios27/perf/frame-observers/build.sh create mode 100644 tools/ios27/perf/frame-observers/cawake.m create mode 100644 tools/ios27/perf/frame-observers/sbpage.m diff --git a/docs/ios27/PACING.md b/docs/ios27/PACING.md new file mode 100644 index 000000000..2a7f24134 --- /dev/null +++ b/docs/ios27/PACING.md @@ -0,0 +1,75 @@ +# iOS 27 on the Galaxy S9: what holds a home-screen flick near 30 a second (24 November 2026) + +Phone 2 (iOS 27.2.1, 24B156), fork kernel `scion/xnu-12377` f523de65 with the charger guard, the owner's root. Every number here +was measured on the phone with the console flicks of `msr.sh` (20 page flicks 1.2 s apart, then the Settings list and +open/close), seven minutes after SpringBoard started (after the slow mode). M = measured, I = inferred. + +## 1. The answer + +The "30 fps" of a flick is two different things, and neither is the clock of the big cores: + +1. **About half of the frames of every flick are a SpringBoard animation that asks for 30 a second.** Around each page slide + SpringBoard runs small animations whose frame rate range prefers 30 (seen: `SBFFluidBehaviorSettings` 20..120 preferred 30, + a display link 20..120 preferred 30). CoreAnimation draws them every second refresh exactly: its render thread wakes at + every refresh and goes back to sleep in 20 to 60 us on every other one; the frame itself is 4 to 12 GPU chains, 2 to 3 ms of + GPU, 3 ms of render, nothing held (M). This is Apple's own choice, made the same way on an iPhone; it is left as it is. It + is why the old yardstick (frames per 5-s window) sticks near 30 whatever is changed. +2. **The page movement itself is GPU-bound.** SpringBoard sets the page's offset 53 times a second (p50 16.7 ms apart), but + the window server shows 35 to 37 of those frames a second: a heavy frame (40 to 86 chains) costs 25 to 30 ms of GPU, and + two fragment passes are about 18 ms of it (one of 11.5 to 12.9 ms, one of 6.4 to 7.6 ms) (M). The render thread's CPU + encode, 12 to 16 ms a heavy frame, overlaps the GPU's work on the frame before (M). + +Not the cause (M): the vsync source (CoreAnimation's render thread wakes every 16.7 ms; the panel refreshes at 60 Hz, the +DECON's frame counter moves by one each refresh), the present path (present 1.8 ms; SwapEnd holds p50 0 ms), a frame-rate +limit we report (CoreAnimation renders at every refresh when it has something new), the kernel's GPU queue (10 us of idle +between two waiting chains), GPU waits by the render thread (it makes none: all of them, about 30 a second, are by the bridge's completion +thread `metal2vulkan-queue-wait`). + +## 2. A frame, end to end (trace T5/T6/T10, home-screen flicks, fast mode) + +| Stage | Where it is measured | Light frame (the 30-a-second animation) | Heavy frame (page moving) | +|---|---|---|---| +| SpringBoard moves the page | `sbpage.m`: `setContentOffset:` | - | every 16.7 ms (p50), 52.8 a second | +| Render thread wakes (CoreAnimation's display timer) | `cawake.m`: `display.primary` run loop | every 16.7 ms; every other wake ends in 20-60 us | never sleeps: late | +| Render (wake to SwapEnd call) | ring `S` | 3.1 ms | 12-25 ms | +| First chain queued | ring `B` | wake + 2.8 ms | in a burst just before SwapEnd | +| SwapEnd held (for the frame before's chains) | ring `S` to `R` | 0 | 5-18.5 ms | +| GPU work of the frame | ring `B`-`E`, `sgu_dump` | 2-5 ms, 4-14 chains | 25-30 ms, 40-86 chains; f 11.5-12.9 ms + f 6.4-7.6 ms + ~30 small | +| Our tick takes it, waits for its chains | ring `F`, `G` | next tick, nothing to wait | up to 25-35 ms | +| Present (GPU scale to 1440x2960) | ring `G` to `P` | 1.8 ms | 1.8-2.6 ms | +| On the panel | DECON frame counter at `P` (`dpu_probe=1`) | +2 refreshes each frame | +1 to +3 | + +Swap-to-present p50 15 ms. In refreshes between swaps (runs of a flick, T5 / T6 / T10): heavy 1.79 / 1.72 / 1.76 (33.5 / +34.8 / 34.1 a second), light 2.0 exactly. + +## 3. The proofs + +- **GPU clock** (T7, `stargpu=455000`, the GPU 20 % slower, a lower level of Samsung's table): heavy frames 1.79 -> 1.90 + refreshes (33.5 -> 31.7 a second), light frames unchanged at 2; flicks 28.5-29.6 -> 26.8 fps on the old yardstick, the + Settings list 20.9-22.7 -> 18.9 (M). The GPU is a stage the movement depends on; the light frames do not depend on it. +- **CPU clock** (bigcore-1124 F1066, the big cores at 1066 MHz): flicks 28.5 fps, unchanged on the old yardstick (M). With + half of that yardstick fixed at 30 by the animation above and the movement GPU-bound, that is what both models predict (I). +- **Light frames' cadence**: the render thread wakes at every refresh with nothing new on every other one (M), while the + requests seen in SpringBoard ask for 30 (M). A test that raises those requests to 60 (`sbpage.m` with `pd_raise=1`) is built + and not run: it would show the light frames' cadence moving and the heavy frames not (the prediction). + +## 4. What would make the movement 60 + +The GPU time of a heavy frame has to fall from 25-30 ms to under 16.7 ms, and two fragment passes are most of it: +1. Name the two passes (which render target, size, format, shader, blend and samples): the bridge's pass log + (`tools/ios27/metal2/PassLog.h`) during one flick, matched to `sgu_dump`'s long chains by order. +2. Usual suspects for an 11.5 ms full-screen fragment pass on a Mali-G72 MP18 at 572 MHz with the memory bus at 1794 MHz: + a large texture minified without mipmaps (the wallpaper), a blur done with many taps at full size, an extended-range + (RGBA16Float, `SWEET_MTL2_DEXR=1`) target read and written several times, no AFBC on CoreAnimation's own targets. +3. Then the render thread's 12-16 ms of encode becomes the next limit at ~60-80 a second. + +## 5. Tools + +- Fork (`agent/pacing/frame-trace`): `kern.hakios.sweetfb_trace_go=S` starts the framebuffer's event ring from the USB + console (6144 events, printed S seconds later with the first event's mach time); `P` carries the DECON's frame counter with + `dpu_probe=1`; GPU waits by thread (`W`/`X`); `sgu_dump=S` also starts from it and prints 480 chains with the GPU's idle time + before each. All off by default. +- `tools/ios27/perf/fbt-timeline.py LOG`: the ring, `cawake` and `sbpage` lines as one timeline, per-stage quantiles, swaps by + size per flick, the page movement's own rate, the GPU waits by thread. +- `tools/ios27/perf/frame-observers/` (diagnostics, never in a root): `cawake.m` for backboardd (its CoreAnimation threads' run + loops), `sbpage.m` for SpringBoard (the page offset, its main run loop, the frame rate requests it makes). diff --git a/tools/ios27/perf/fbt-timeline.py b/tools/ios27/perf/fbt-timeline.py new file mode 100755 index 000000000..829b17876 --- /dev/null +++ b/tools/ios27/perf/fbt-timeline.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT-0 +# fbt-timeline.py LOG [FROM_HHMMSS [T0_MS T1_MS]] : one frame timeline out of a phone's console log (docs/ios27/PACING.md). +# - the kernel's event ring (the fork's sweetfb_trace, started with kern.hakios.sweetfb_trace_go=S): T tick, F frame taken, G its chains +# done, P presented (number: the DECON's frame counter with dpu_probe=1), S SwapEnd called (chains queued), R recorded (released), +# B/E the GPU queue started / ran empty (chains run), W/X a GPU wait by a client's thread (1 render thread, 2 render-server, +# 3 metal2vulkan, 4 other; +10 whole queue, +20 one chain); +# - "BD:" lines of tools/ios27/perf/frame-observers/cawake.m (backboardd's CoreAnimation threads waking and sleeping); +# - "PD:" lines of sbpage.m (SpringBoard's page offset set, O, and its main run loop W/Z). +# Prints the stages per frame (quantiles), the swaps per flick by size (runs), the page movement's own rate, and with T0/T1 the +# merged events of that span. +import re, sys, statistics as st +log = open(sys.argv[1], errors='replace').read().splitlines() +frm = sys.argv[2] if len(sys.argv) > 2 else None +# FBT +starts = [i for i, l in enumerate(log) if 'FBT: first event at mach_absolute_time' in l and (frm is None or l[:8] >= frm)] +if not starts: print('no FBT dump'); sys.exit(1) +i0 = starts[-1] +m = re.search(r'mach_absolute_time (\d+) \((\d+) us\)', log[i0]); A0 = int(m.group(1)); U0 = int(m.group(2)) +ev = [] +for l in log[i0 + 1:]: + if 'FBT: done' in l: break + if 'FBT:' not in l: continue + for x in re.finditer(r' (\d+)([A-Z])(\d+)', l.split('FBT:', 1)[1]): + ev.append((int(x.group(1)) / 1000.0, x.group(2), int(x.group(3)))) +ev.sort(key=lambda e: e[0]) +tb = U0 / A0 if A0 else 1 # us per tick +# PD (SpringBoard): abs base + us deltas +pd = [] +for l in log: + if 'PD: ' not in l or 'loaded' in l: continue + s = l.split('PD: ', 1)[1].split() + try: base = int(s[0]) + except Exception: continue + for tok in s[1:]: + x = re.match(r'(\d+)([A-Z])(-?\d+)', tok) + if not x: continue + t_us = base * tb + int(x.group(1)) - U0 + pd.append((t_us / 1000.0, x.group(2), int(x.group(3)))) +lo, hi = ev[0][0], ev[-1][0] +pd = sorted(e for e in pd if lo <= e[0] <= hi) +print('FBT events %d over %.0f ms; PD events in that span %d' % (len(ev), hi - lo, len(pd))) +def q(xs): + if not xs: return '-' + xs = sorted(xs); n = len(xs) + return 'n %d p10 %.1f p50 %.1f p90 %.1f max %.1f' % (n, xs[n // 10], xs[n // 2], xs[min(n - 1, 9 * n // 10)], xs[-1]) +T = [t for t, w, a in ev if w == 'T']; S = [(t, a) for t, w, a in ev if w == 'S']; R = [t for t, w, a in ev if w == 'R'] +P = [(t, a) for t, w, a in ev if w == 'P']; F = [(t, a) for t, w, a in ev if w == 'F']; G = [t for t, w, a in ev if w == 'G'] +O = [t for t, w, a in pd if w == 'O'] +print('ticks: period', q([b - a for a, b in zip(T, T[1:])])) +# motion runs: present gaps <= 3 ticks (50 ms) +Pt = [t for t, a in P] +runs = []; cur = [Pt[0]] if Pt else [] +for a, b in zip(Pt, Pt[1:]): + if b - a <= 50: cur.append(b) + else: + if len(cur) >= 6: runs.append(cur) + cur = [b] +if len(cur) >= 6: runs.append(cur) +mot = sum(r[-1] - r[0] for r in runs); nfr = sum(len(r) - 1 for r in runs) +print('motion runs (presents <= 50 ms apart, >= 6): %d, %.0f ms, %d frames: %.1f fps in motion' % (len(runs), mot, nfr, 1000.0 * nfr / mot if mot else 0)) +inrun = lambda t: any(r[0] - 20 <= t <= r[-1] for r in runs) +print('present gaps in motion (ms):', q([b - a for r in runs for a, b in zip(r, r[1:])])) +g = [round((b - a) / 16.667) for r in runs for a, b in zip(r, r[1:])] +print(' in refreshes: ' + ' '.join('%d:%d' % (k, g.count(k)) for k in sorted(set(g)))) +St = [t for t, a in S if inrun(t)] +print('swap calls in motion: period', q([b - a for a, b in zip(St, St[1:]) if b - a < 60])) +# swap hold: S -> next R +hold = [] +for t, a in S: + r = next((x for x in R if x >= t), None) + if r is not None and inrun(t): hold.append(r - t) +print('SwapEnd held', q(hold)) +# tick took frame -> chains done -> presented +fg = []; gp = []; sp = []; dec = [] +for t, a in F: + if not inrun(t): continue + gg = next((x for x in G if x >= t), None); pp = next(((x, d) for x, d in P if x >= t), None) + if gg: fg.append(gg - t) + if pp and gg: gp.append(pp[0] - gg) + s = [x for x, sid in S if x <= t] + if s and pp: sp.append(pp[0] - s[-1]) +print('tick took frame -> its chains done (tick slept)', q(fg)); print('chains done -> present done', q(gp)) +print('last swap call -> present done', q(sp)) +dc = [d for t, d in P if inrun(t)] +if dc and dc[-1]: + print('DECON refreshes between presents in motion:', ' '.join('%d:%d' % (k, [b - a for a, b in zip(dc, dc[1:])].count(k)) for k in range(0, 6))) +# GPU busy runs +B = [t for t, w, a in ev if w == 'B']; E = [(t, a) for t, w, a in ev if w == 'E'] +busy = [] +for b in B: + e = next(((x, n) for x, n in E if x >= b), None) + if e and inrun(b): busy.append((e[0] - b, e[1])) +print('GPU queue busy runs in motion: ms', q([x for x, n in busy]), '| chains', q([n for x, n in busy])) +tot = sum(x for x, n in busy); print('GPU queue busy share of motion: %.0f %%' % (100 * tot / mot if mot else 0)) +if O: + Om = [t for t in O if inrun(t)] + print('SpringBoard offset sets in motion: period', q([b - a for a, b in zip(Om, Om[1:]) if b - a < 60])) + # each offset -> next swap call + os_ = [] + for t in Om: + s = next((x for x, a in S if x >= t), None) + if s is not None: os_.append(s - t) + print('offset set -> next swap call', q(os_)) +# backboardd's CoreAnimation threads (bd.dylib): W woke / Z about to sleep, arg = thread index +names = {} +for l in log: + m = re.search(r"BD: observer on thread (\d+) '([^']+)'", l) + if m: names[int(m.group(1))] = m.group(2).replace('com.apple.coreanimation.', '') +bd = [] +for l in log: + if 'BD: ' not in l: continue + s = l.split('BD: ', 1)[1].split() + try: base = int(s[0]) + except Exception: continue + for tok in s[1:]: + x = re.match(r'(\d+)([A-Z])(-?\d+)$', tok) + if not x: continue + t_us = base * tb + int(x.group(1)) - U0 + bd.append((t_us / 1000.0, x.group(2), int(x.group(3)))) +bd = sorted(e for e in bd if lo <= e[0] <= hi) +print('BD events in the span: %d; threads %s' % (len(bd), names)) +for idx, nm in sorted(names.items()): + W = [t for t, w, a in bd if w == 'W' and a == idx]; Z = [t for t, w, a in bd if w == 'Z' and a == idx] + Wm = [t for t in W if inrun(t)] + print(' %-22s wakes in motion %d (%.1f/s): period %s' % (nm, len(Wm), 1000.0 * len(Wm) / mot if mot else 0, q([b - a for a, b in zip(Wm, Wm[1:]) if b - a < 60]))) + busy = [] + for t in Wm: + z = next((x for x in Z if x >= t), None) + if z is not None: busy.append(z - t) + print(' %-22s awake per wake in motion: %s' % ('', q(busy))) + # wake -> next swap call (for the render thread) + if 'display' in nm: + ws = [] + for t in Wm: + s_ = next((x for x, a in S if x >= t), None) + if s_ is not None and s_ - t < 40: ws.append(s_ - t) + print(' %-22s wake -> swap call: %s (%d of %d wakes end in a swap within 40 ms)' % ('', q(ws), len(ws), len(Wm))) + +# swaps in runs (<= 60 ms apart): refreshes since the swap before, for big (>= 10 chains) and small swaps +Sx = [(t, a) for t, w, a in ev if w == 'S'] +rr = []; cur = Sx[:1] +for p, c in zip(Sx, Sx[1:]): + if c[0] - p[0] <= 60: cur.append(c) + else: rr.append(cur); cur = [c] +rr.append(cur) +big = []; small = [] +for r in rr: + if len(r) < 5: continue + for p, c in zip(r, r[1:]): (big if c[1] >= 10 else small).append(round((c[0] - p[0]) / 16.667)) +h = lambda xs: ' '.join('%d:%d' % (k, xs.count(k)) for k in sorted(set(xs))) +print('swaps in runs, refreshes since the swap before: >= 10 chains %s | < 10 chains %s' % (h(big), h(small))) +if big: print(' big swaps: %.2f refreshes each = %.1f a second' % (sum(big) / len(big), 60.0 * len(big) / sum(big))) +# the page movement: SpringBoard's offset runs (<= 60 ms apart, >= 4) and the swaps inside them +Op = [(t, a) for t, w, a in pd if w == 'O'] +if Op: + orr = []; cur = Op[:1] + for p, c in zip(Op, Op[1:]): + if c[0] - p[0] <= 60: cur.append(c) + else: orr.append(cur); cur = [c] + orr.append(cur) + no = ns = 0; tt = 0.0; po = []; ps = [] + for r in orr: + if len(r) < 4: continue + a, b = r[0][0], r[-1][0]; ss = [t for t, x in Sx if a <= t <= b + 5] + no += len(r) - 1; ns += len(ss); tt += b - a + po += [y[0] - x[0] for x, y in zip(r, r[1:])]; ps += [y - x for x, y in zip(ss, ss[1:])] + if tt: print('page movement: %.0f ms: SpringBoard offsets %.1f a second (%s), swaps %.1f a second (%s)' % (tt, 1000.0 * no / tt, q(po), 1000.0 * ns / tt, q(ps))) +# GPU waits by thread (W/X) +Wt = {} +for t, w, a in ev: + if w == 'W': Wt.setdefault(a, []).append(t) +for a, ts in sorted(Wt.items()): + xs = [t for t, w, b in ev if w == 'X' and b == a] + d = [] + for t in ts: + x = next((y for y in xs if y >= t), None) + if x is not None: d.append(x - t) + print('GPU waits by %s (%s): %d, %s, total %.0f ms' % ({1: 'the render thread', 2: 'render-server', 3: 'metal2vulkan', 4: 'another thread'}.get(a % 10, '?'), + {0: 'one buffer', 1: 'whole queue', 2: 'one chain'}.get(a // 10, '?'), len(d), q(d), sum(d))) +def dump(t0, t1): + allev = sorted([(t, w, a, 'K') for t, w, a in ev] + [(t, w, a, 'B') for t, w, a in bd] + [(t, w, a, 'P') for t, w, a in pd]) + prev = None + for t, w, a, src in allev: + if t0 <= t <= t1: + lab = (names.get(a, str(a))[:14] if src == 'B' else '') + print('%9.2f %+6.2f %s %s%d %s' % (t, t - (prev or t), src, w, a, lab)); prev = t +if len(sys.argv) > 3: dump(float(sys.argv[3]), float(sys.argv[4])) diff --git a/tools/ios27/perf/frame-observers/build.sh b/tools/ios27/perf/frame-observers/build.sh new file mode 100755 index 000000000..a88ca2f29 --- /dev/null +++ b/tools/ios27/perf/frame-observers/build.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# SPDX-License-Identifier: MIT-0 +# build.sh [OUT]: the two frame observers of docs/ios27/PACING.md (diagnostics, not part of any root): cawake.dylib for backboardd +# (/usr/lib/bd.dylib on the phone, sweetinject ...;/usr/lib/bd.dylib,backboardd) and sbpage.dylib for SpringBoard (/usr/lib/pd.dylib, +# ...;/usr/lib/pd.dylib,SpringBoard). Needs the iPhoneOS SDK (xcrun); nothing of Apple's is copied. +set -eu +HERE=$(cd "$(dirname "$0")" && pwd); OUT=${1:-$HERE/out}; mkdir -p "$OUT" +CC="xcrun --sdk iphoneos clang -arch arm64 -mios-version-min=16.0 -O2 -Wall -fobjc-arc -dynamiclib" +$CC -install_name /usr/lib/bd.dylib -framework Foundation -framework CoreFoundation "$HERE/cawake.m" -o "$OUT/cawake.dylib" +$CC -install_name /usr/lib/pd.dylib -framework UIKit -framework QuartzCore -framework Foundation -framework CoreFoundation \ + "$HERE/sbpage.m" -o "$OUT/sbpage.dylib" +codesign -f -s - "$OUT/cawake.dylib" "$OUT/sbpage.dylib" diff --git a/tools/ios27/perf/frame-observers/cawake.m b/tools/ios27/perf/frame-observers/cawake.m new file mode 100644 index 000000000..1f1c1cd94 --- /dev/null +++ b/tools/ios27/perf/frame-observers/cawake.m @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT-0 +// Diagnostic (docs/ios27/PACING.md): when does backboardd's CoreAnimation render thread wake and sleep? Injected by sweetinject +// into backboardd. 8 s after load: every thread's name to /dev/console once; a CFRunLoop observer added (via _CFRunLoopGet0) to the run +// loop of each thread whose name has "coreanimation" (W woke, Z about to sleep, arg = thread index); every 2 s "BD: ..." +#import +#include +#include +#include +#include +#include +#include +#include +extern CFRunLoopRef _CFRunLoopGet0(pthread_t t); +#define N 65536 +static struct { uint64_t at; int32_t arg; char what; } ring[N]; +static volatile uint32_t wr, rd; +static int con = -1; +static void ev(char w, int32_t a) { uint32_t i = __atomic_fetch_add(&wr, 1, __ATOMIC_RELAXED); if (i - rd >= N) return; ring[i % N].at = mach_absolute_time(); ring[i % N].arg = a; ring[i % N].what = w; } +static void obs(CFRunLoopObserverRef o, CFRunLoopActivity a, void *info) { ev(a == kCFRunLoopAfterWaiting ? 'W' : 'Z', (int32_t)(intptr_t)info); } +static void say(const char *s) { if (con >= 0) write(con, s, strlen(s)); } +static void flush(void) { + uint32_t w = __atomic_load_n(&wr, __ATOMIC_ACQUIRE); if (w - rd > N) w = rd + N; + if (w == rd || con < 0) return; + char line[1024]; int n = 0; uint64_t base = ring[rd % N].at; mach_timebase_info_data_t tb; mach_timebase_info(&tb); + n = snprintf(line, sizeof line, "BD: %llu", base); + for (uint32_t i = rd; i < w; i++) { + uint64_t us = (ring[i % N].at - base) * tb.numer / tb.denom / 1000; + n += snprintf(line + n, sizeof line - n, " %llu%c%d", us, ring[i % N].what, ring[i % N].arg); + if (n > 900) { line[n++] = '\n'; write(con, line, n); n = snprintf(line, sizeof line, "BD: %llu", base); usleep(3000); } + } + line[n++] = '\n'; write(con, line, n); + __atomic_store_n(&rd, w, __ATOMIC_RELEASE); +} +/* SpringBoard's pd.dylib (mobile: no console) writes /private/var/tmp/pd.log: its new lines are passed on to the console */ +static off_t relay_at; +static void relay(void) { + int fd = open("/private/var/tmp/pd.log", O_RDONLY); if (fd < 0) return; + char buf[16384]; ssize_t n; + while ((n = pread(fd, buf, sizeof buf, relay_at)) > 0) { + ssize_t end = n; while (end > 0 && buf[end - 1] != '\n') end--; + if (end == 0) break; + for (ssize_t i = 0; i < end; ) { ssize_t k = i; while (k < end && buf[k] != '\n') k++; write(con, buf + i, k + 1 - i); i = k + 1; if (((i >> 10) & 3) == 0) usleep(500); } + relay_at += end; + } + close(fd); +} +static void attach(void) { + thread_act_array_t th; mach_msg_type_number_t n = 0; + if (task_threads(mach_task_self(), &th, &n) != KERN_SUCCESS) { say("BD: task_threads failed\n"); return; } + char line[1024]; int len = snprintf(line, sizeof line, "BD: %u threads:", n); + for (unsigned i = 0; i < n; i++) { + pthread_t p = pthread_from_mach_thread_np(th[i]); char name[64] = ""; + if (p) pthread_getname_np(p, name, sizeof name); + if (len < 900) len += snprintf(line + len, sizeof line - len, " [%u %s]", i, name[0] ? name : "-"); + if (p && strstr(name, "coreanimation")) { + CFRunLoopRef rl = _CFRunLoopGet0(p); + CFRunLoopObserverContext ctx = { 0, (void *)(intptr_t)i, NULL, NULL, NULL }; + CFRunLoopObserverRef o = CFRunLoopObserverCreate(NULL, kCFRunLoopAfterWaiting | kCFRunLoopBeforeWaiting, true, 0, obs, &ctx); + CFRunLoopAddObserver(rl, o, kCFRunLoopCommonModes); + CFArrayRef modes = CFRunLoopCopyAllModes(rl); char ms[300] = ""; int ml = 0; + for (CFIndex k = 0; modes && k < CFArrayGetCount(modes); k++) { + CFStringRef md = CFArrayGetValueAtIndex(modes, k); char mn[96] = ""; + CFStringGetCString(md, mn, sizeof mn, kCFStringEncodingUTF8); + if (!CFEqual(md, kCFRunLoopDefaultMode)) CFRunLoopAddObserver(rl, o, md); + if (ml < 280) ml += snprintf(ms + ml, sizeof ms - ml, " %s", mn); + } + if (modes) CFRelease(modes); + CFRunLoopWakeUp(rl); + char s[512]; snprintf(s, sizeof s, "BD: observer on thread %u '%s' run loop %p, modes:%s\n", i, name, rl, ms); say(s); + } + } + line[len++] = '\n'; line[len] = 0; say(line); +} +__attribute__((constructor)) static void bd_init(void) { + con = open("/dev/console", O_WRONLY | O_NOCTTY); + char s[96]; snprintf(s, sizeof s, "BD: loaded into %s pid %d\n", getprogname(), getpid()); say(s); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 8 * NSEC_PER_SEC), dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ attach(); }); + static dispatch_source_t t; t = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)); + dispatch_source_set_timer(t, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), 2 * NSEC_PER_SEC, 100 * NSEC_PER_MSEC); + dispatch_source_set_event_handler(t, ^{ flush(); relay(); }); + dispatch_resume(t); +} diff --git a/tools/ios27/perf/frame-observers/sbpage.m b/tools/ios27/perf/frame-observers/sbpage.m new file mode 100644 index 000000000..290b7f4e9 --- /dev/null +++ b/tools/ios27/perf/frame-observers/sbpage.m @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: MIT-0 +// Diagnostic (docs/ios27/PACING.md): when does SpringBoard move its page, and when does its main thread wake and sleep? +// Injected by sweetinject into SpringBoard. Events (mach_absolute_time) into a ring; every 2 s the new ones go to /dev/console as +// "PD: ..." : O page scroll view offset set (arg x in points), W main run loop woke, Z about to sleep +// (W/Z always). As mobile (no /dev/console): /private/var/tmp/pd.log instead. +#import +#include +#include +#include +#include +#include +#include +#include +#include +#include +/* frame rate requests (CAFrameRateRange) seen in SpringBoard, written as text lines; with the boot-arg pd_raise=1 a range whose + * most is under 60 is raised to 60 (most and preferred), as the 16.5 line's sb_fps did (userland/src/inject_sb.c) */ +typedef struct { float minimum, maximum, preferred; } fr_t; +static int raise60; static unsigned said; +static void tl(const char *fmt, ...); +static fr_t fr_fix(fr_t r) { + if (raise60 && r.maximum > 0 && r.maximum < 60) { r.maximum = 60; r.preferred = 60; } + if (raise60 && r.preferred > 0 && r.preferred < 60) r.preferred = 60; /* pd_raise=1: no request prefers under the panel's rate */ + return r; +} +static void (*o_dl)(id, SEL, fr_t); static void h_dl(id self, SEL c, fr_t r) { if (said++ < 400) tl("RANGE link %p %.0f..%.0f pref %.0f", self, r.minimum, r.maximum, r.preferred); o_dl(self, c, fr_fix(r)); } +static void (*o_dlf)(id, SEL, long); static void h_dlf(id self, SEL c, long f) { if (said++ < 400) tl("FPS link %p %ld", self, f); o_dlf(self, c, (raise60 && f > 0 && f < 60) ? 60 : f); } +static void (*o_an)(id, SEL, fr_t); static void h_an(id self, SEL c, fr_t r) { if (said++ < 400) tl("RANGE anim %s %.0f..%.0f pref %.0f", object_getClassName(self), r.minimum, r.maximum, r.preferred); o_an(self, c, fr_fix(r)); } +static void (*o_sf)(id, SEL, fr_t, unsigned); static void h_sf(id self, SEL c, fr_t r, unsigned why) { if (said++ < 400) tl("RANGE settings %s %.0f..%.0f pref %.0f reason %u", object_getClassName(self), r.minimum, r.maximum, r.preferred, why); o_sf(self, c, fr_fix(r), why); } +static void (*o_sa)(id, SEL, fr_t, unsigned); static void h_sa(id self, SEL c, fr_t r, unsigned why) { if (said++ < 400) tl("RANGE asettings %s %.0f..%.0f pref %.0f reason %u", object_getClassName(self), r.minimum, r.maximum, r.preferred, why); o_sa(self, c, fr_fix(r), why); } +#define N 32768 +static struct { uint64_t at; int32_t arg; char what; } ring[N]; +static volatile uint32_t wr, rd; +static uint64_t last_o; +static uint64_t one_s; +static int con = -1; +static void ev(char w, int32_t a) { uint32_t i = __atomic_fetch_add(&wr, 1, __ATOMIC_RELAXED); if (i - rd >= N) return; ring[i % N].at = mach_absolute_time(); ring[i % N].arg = a; ring[i % N].what = w; } +static void (*orig_sco)(id, SEL, CGPoint); +static void my_sco(id self, SEL _cmd, CGPoint p) { + CGPoint before = ((UIScrollView *)self).contentOffset; + orig_sco(self, _cmd, p); + if (p.x != before.x && ((UIScrollView *)self).bounds.size.width >= 300) { last_o = mach_absolute_time(); ev('O', (int32_t)p.x); } +} +static void (*orig_sb)(id, SEL, CGRect); +static void my_sb(id self, SEL _cmd, CGRect r) { + CGRect before = ((UIView *)self).bounds; + orig_sb(self, _cmd, r); + if (r.origin.x != before.origin.x && r.size.width >= 300) { last_o = mach_absolute_time(); ev('B', (int32_t)r.origin.x); } +} +static void obs(CFRunLoopObserverRef o, CFRunLoopActivity a, void *info) { + uint64_t now = mach_absolute_time(); + (void)now; + ev(a == kCFRunLoopAfterWaiting ? 'W' : 'Z', 0); +} +#include +/* text lines go to a ring too (no console write on the main thread); the flush timer writes them */ +static char tlr[1024][200]; static volatile uint32_t tlw, tlrd; +static void tl(const char *fmt, ...) { + uint32_t i = __atomic_fetch_add(&tlw, 1, __ATOMIC_RELAXED); if (i - tlrd >= 1024) return; + char *b = tlr[i % 1024]; int n = snprintf(b, 200, "PDT: %llu ", mach_absolute_time()); + va_list ap; va_start(ap, fmt); n += vsnprintf(b + n, 200 - n - 2, fmt, ap); va_end(ap); if (n > 197) n = 197; b[n++] = '\n'; b[n] = 0; +} +static void tl_flush(void) { + uint32_t w = __atomic_load_n(&tlw, __ATOMIC_ACQUIRE); if (w - tlrd > 1024) w = tlrd + 1024; + for (uint32_t i = tlrd; i < w; i++) { if (con >= 0) write(con, tlr[i % 1024], strlen(tlr[i % 1024])); } + __atomic_store_n(&tlrd, w, __ATOMIC_RELEASE); +} +static void hook(const char *cls, const char *sel, IMP h, IMP *o) { + Class c = objc_getClass(cls); Method m = c ? class_getInstanceMethod(c, sel_registerName(sel)) : NULL; + if (!m) { tl("no -[%s %s]", cls, sel); return; } + *o = method_setImplementation(m, h); tl("hooked -[%s %s] %s", cls, sel, method_getTypeEncoding(m)); +} +static void flush(void) { + uint32_t w = __atomic_load_n(&wr, __ATOMIC_ACQUIRE); if (w - rd > N) w = rd + N; + if (w == rd || con < 0) return; + char line[1024]; int n = 0; uint64_t base = ring[rd % N].at; mach_timebase_info_data_t tb; mach_timebase_info(&tb); + n = snprintf(line, sizeof line, "PD: %llu", base); + for (uint32_t i = rd; i < w; i++) { + uint64_t us = (ring[i % N].at - base) * tb.numer / tb.denom / 1000; + n += snprintf(line + n, sizeof line - n, " %llu%c%d", us, ring[i % N].what, ring[i % N].arg); + if (n > 900) { line[n++] = '\n'; write(con, line, n); n = snprintf(line, sizeof line, "PD: %llu", base); usleep(2000); } + } + line[n++] = '\n'; write(con, line, n); + __atomic_store_n(&rd, w, __ATOMIC_RELEASE); +} +__attribute__((constructor)) static void pd_init(void) { + mach_timebase_info_data_t tb; mach_timebase_info(&tb); one_s = 1000000000ull * tb.denom / tb.numer; + con = open("/dev/console", O_WRONLY | O_NOCTTY); + if (con < 0) con = open("/private/var/tmp/pd.log", O_WRONLY | O_CREAT | O_APPEND, 0644); /* SpringBoard runs as mobile: no console */ + { char a[4096] = ""; size_t l = sizeof a - 1; if (sysctlbyname("kern.bootargs", a, &l, NULL, 0) == 0) raise60 = strstr(a, "pd_raise=1") != NULL; } + tl("pd: raise60 %d", raise60); + hook("CADisplayLink", "setPreferredFrameRateRange:", (IMP)h_dl, (IMP *)&o_dl); + hook("CADisplayLink", "setPreferredFramesPerSecond:", (IMP)h_dlf, (IMP *)&o_dlf); + hook("CAAnimation", "setPreferredFrameRateRange:", (IMP)h_an, (IMP *)&o_an); + hook("SBFFluidBehaviorSettings", "setFrameRateRange:highFrameRateReason:", (IMP)h_sf, (IMP *)&o_sf); + hook("SBFAnimationSettings", "setFrameRateRange:highFrameRateReason:", (IMP)h_sa, (IMP *)&o_sa); + Class c = objc_getClass("UIScrollView"); + Method m = class_getInstanceMethod(c, @selector(setContentOffset:)); tl("UIScrollView setContentOffset: %p, own %d", m, m && class_getInstanceMethod(class_getSuperclass(c), @selector(setContentOffset:)) != m); orig_sco = (void *)method_getImplementation(m); method_setImplementation(m, (IMP)my_sco); + (void)my_sb; (void)orig_sb; + CFRunLoopObserverRef o = CFRunLoopObserverCreate(NULL, kCFRunLoopAfterWaiting | kCFRunLoopBeforeWaiting, true, 2000001, obs, NULL); + CFRunLoopAddObserver(CFRunLoopGetMain(), o, kCFRunLoopCommonModes); + static dispatch_source_t t; t = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)); + dispatch_source_set_timer(t, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), 2 * NSEC_PER_SEC, 100 * NSEC_PER_MSEC); + dispatch_source_set_event_handler(t, ^{ tl_flush(); flush(); }); + dispatch_resume(t); + if (con >= 0) { char s[128]; int n = snprintf(s, sizeof s, "PD: loaded into %s pid %d\n", getprogname(), getpid()); write(con, s, n); } +}