Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

Touch latency: measured end to end and per stage; the panel copy shared out

vcvkk6d8f8180880b
diff --git a/README.md b/README.md
index 5ea1eff..a1f5f0c 100644
--- a/README.md
+++ b/README.md
@@ -208,7 +208,8 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./xl run #
| Параметр | Что делает |
|---|---|
-| `touchscreen=1` | включить сенсорный экран телефона (`touch_flip=1\|2\|3` — отразить оси) |
+| `touchscreen=1` | включить сенсорный экран телефона (`touch_flip=1\|2\|3` — отразить оси). На этом телефоне в нём Goodix GT9916. Для меньшей задержки (пальцем ещё не проверено, поэтому не по умолчанию): `touch_poll_us=1000` — смотреть на линию прерывания каждую миллисекунду вместо 8; `touch_spi_hz=5000000` — шина на 5 МГц, как в дереве устройств Android (отчёт читается за 0,14 мс; при 1 МГц — дольше); `touch_rate=480` — команда самой микросхемы (игровой режим Xiaomi, `0xC0`) отчитываться 480 раз в секунду вместо 240. Микросхема её подтверждает; итог видно в строке `goodix: so far …` раз в минуту |
+| `touch_lat=1` | замер задержки касания: строки `tl:` на каждом этапе (ядро выложило отсчёт, оконный сервер прочёл и отдал его системе событий, кадр нарисован, отдан драйверу экрана, GPU закончил, кадр в памяти панели), всё во времени `mach_absolute_time`. `RC_JOBS=rc.jobs.latency` (с `rec_secs=200 rec_ring=1 rec_step=4 rec_mb=256`) через 100 с после запуска водит «пальцем» вверх-вниз по списку Настроек (`rwtouch zigzag`), `tools/latency.py ЖУРНАЛ logs/recording.raw` по развороту пальца в кадрах записи считает задержку от отсчёта касания до кадра в памяти панели и раскладывает её по этапам. Первые 1–2 минуты после запуска все четыре ядра заняты виджетами, searchd и прочими: замер в это время мерит их, а не путь касания (`ustacks=top ustacks_at=S ustacks_ms=MS` показывает, кто занимал процессор) |
| `buttons=0` | не читать кнопки телефона. Вместе с `touchscreen=1` они включены: питание — боковая кнопка, громкость вверх и вниз (опрос микросхемы питания раз в 16 мс, только чтение). Не держать питание дольше 5 с: 10–15 с сбрасывают телефон |
| `autounlock=0` | экран блокировки остаётся, пока его не смахнут вверх, как на iPhone. По умолчанию SpringBoard сам убирает его через 10 с (на случай, если сенсор ещё не ожил) |
| `bootcpu=7` | запустить ядро на самом большом ядре процессора (загрузчик остаётся на нулевом и наблюдает) |
@@ -223,7 +224,9 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./xl run #
| `launchd_disable_all_timeouts=1` | параметр самого launchd: не убивать расширение приложения, которое не отметилось за 5 секунд после запуска («Extension is hanging on launch. Killing.»). Нужен только в QEMU, где при загрузке полсотни расширений стартуют одновременно на эмулируемом процессоре; на телефоне таких убийств нет |
| `systrace=1` | печатать неудачные системные вызовы и аварии процессов (`systrace_name=ИМЯ` — только процессов с этим именем) |
| `fbscale=2` | рисовать в 2 пикселя на точку вместо 3 и растягивать на панель: в 2,25 раза меньше работы программному рендеру (на телефоне пик 28 кадров/с вместо 19), картинка мягче, сверху появляется красная служебная полоса SpringBoard |
-| `fb_filter=0` | масштабировать картинку на панель «ближайшим соседом», как раньше. По умолчанию каждый пиксель панели смешивается из четырёх соседних пикселей картинки (билинейно): 1125×2436 на 1080×2400 «ближайший сосед» выбрасывает каждый 25-й столбец и каждую 67-ю строку, и буквы и наклонные линии там, где они попадают на выброшенные, выходят чуть кривыми. Цена — около 9 мс на кадр в потоке драйвера экрана вместо 4 (отдельный поток, частота кадров та же) |
+| `fb_filter=0` | масштабировать картинку на панель «ближайшим соседом», как раньше. По умолчанию каждый пиксель панели смешивается из четырёх соседних пикселей картинки (билинейно): 1125×2436 на 1080×2400 «ближайший сосед» выбрасывает каждый 25-й столбец и каждую 67-ю строку, и буквы и наклонные линии там, где они попадают на выброшенные, выходят чуть кривыми. Цена — около 9 мс на кадр в потоке драйвера экрана вместо 4 (отдельный поток, частота кадров та же), если считает одно ядро |
+| `fb_threads=N` | столько ядер вместе масштабируют кадр на панель (по умолчанию 3: кадр в памяти панели через 3 мс вместо 9–10; `fb_threads=1` — как было) |
+| `fb_beat=0` | кадр уходит на панель сразу, как GPU его закончил, а не по собственному такту драйвера 60 Гц (такт держит ровный шаг, но кадр ждёт его в среднем 5–7 мс; панель всё равно обновляется 120 раз в секунду и к такту не привязана) |
| `machine_name=0` | сообщать `hw.machine = arm64` вместо iPhone10,3 (как было раньше; тогда iOS не находит ни одного ресурса с суффиксом `~iphone`, и, например, Пункт управления теряет раскладку) |
| `wfi=0 wfe_mode=0` | простаивающее ядро процессора не засыпает, а крутится в цикле, как всегда было с одним ядром (с `cpus=N` простой — это WFI; на случай, если под гипервизором телефона он поведёт себя плохо) |
| `return_cpu=N`, `return_panic=1` | для проверки возврата в загрузчик с несколькими ядрами: вернуться по таймеру с процессора N (по номеру в ядре: 0 — загрузочный) и/или через панику |
diff --git a/tools/latency.py b/tools/latency.py
new file mode 100644
index 0000000..cde7186
--- /dev/null
+++ b/tools/latency.py
@@ -0,0 +1,232 @@
+#!/usr/bin/env python3
+"""
+latency.py RUN.log RECORDING.raw: how far behind the finger the phone's screen is.
+
+A run with boot-arg touch_lat=1 writes a line at every stage a touch passes on its way to the panel,
+all in microseconds of mach_absolute_time (the kernel's clock, which user space reads too):
+
+ tl: p TYPE FINGER X Y at US the kernel posts a sample (bsd/dev/redwood_input.c)
+ tl: c before US seen US read US the touch driver finds the interrupt line low and reads the
+ report (bsd/dev/redwood_goodix.c; only for a real finger)
+ tl: i TYPE posted US read US sent US the window server reads it and hands it to the event system
+ (userland/src/inject.c)
+ tl: g FRAME began US ended US DRAWS the window server draws a frame (userland/src/eagl.c)
+ tl: s ID at US it hands the frame over (SwapEnd)
+ tl: v ID ready US shown US done US the display driver: the GPU done with it, its beat come, its
+ pixels in the panel's memory (MiniIOMobileFramebuffer.cpp)
+
+With rec_secs=... rec_ring=1 the frames themselves are in the screen recording, each with the time it
+was put in the panel's memory. A "zigzag" of rwtouch (the finger up and down over a scrolling list
+without letting go) then gives the latency from end to end: the list follows the finger, and the
+time by which the list's movement lags the finger's is found by fitting the one to the other (a
+constant offset -- the scroll view's slop before it starts to follow -- does not matter; the turns do).
+The stages are averaged over the same frames and samples, and what is left between the event
+system and the frame -- the application's handling and the wait for the next frame of
+CoreAnimation's clock -- is the difference.
+"""
+import re
+import struct
+import sys
+
+import numpy as np
+
+
+def micros_lines(path):
+ """The tl: lines of a log, once each (the kernel's own also come back in its log at the end)."""
+ seen, lines = set(), []
+ with open(path, 'rb') as f:
+ for raw in f:
+ text = raw.decode('utf-8', 'replace')
+ at = text.find('tl: ')
+ if at < 0:
+ continue
+ line = text[at:].strip()
+ if line not in seen:
+ seen.add(line)
+ lines.append(line)
+ return lines
+
+
+def parse(lines):
+ samples, reads, frames, swaps, shows, chip = [], [], [], {}, {}, []
+ for line in lines:
+ w = line.split()
+ try:
+ if w[1] == 'p' and len(w) >= 8:
+ samples.append((int(w[7]), int(w[2]), int(w[3]), int(w[4]), int(w[5])))
+ elif w[1] == 'i' and len(w) >= 9:
+ reads.append((int(w[4]), int(w[6]), int(w[8]), int(w[2])))
+ elif w[1] == 'g' and len(w) >= 8:
+ frames.append((int(w[4]), int(w[6]), int(w[7])))
+ elif w[1] == 's' and len(w) >= 5:
+ swaps[int(w[2])] = int(w[4])
+ elif w[1] == 'v' and len(w) >= 9:
+ shows[int(w[2])] = (int(w[4]), int(w[6]), int(w[8]))
+ elif w[1] == 'c' and len(w) >= 8:
+ chip.append((int(w[3]), int(w[5]), int(w[7])))
+ except ValueError:
+ pass
+ samples.sort()
+ reads.sort()
+ frames.sort(key=lambda f: f[1])
+ return samples, reads, frames, swaps, shows, chip
+
+
+def recording(path):
+ data = open(path, 'rb').read()
+ magic, width, height, count, oldest = struct.unpack_from('<8sIIII', data, 0)
+ if magic != b'RWREC003':
+ sys.exit('latency.py: not a recording of the RWREC003 kind')
+ began = struct.unpack_from('<Q', data, 24)[0]
+ size = 8 + width * height * 3
+ out = []
+ for k in range(count):
+ i = (oldest + k) % count
+ at = 32 + i * size
+ t = struct.unpack_from('<Q', data, at)[0]
+ pixels = np.frombuffer(data, np.uint8, width * height * 3, at + 8).reshape(height, width, 3)
+ out.append(((began + t) // 1000, pixels))
+ out.sort(key=lambda f: f[0])
+ return out, width, height
+
+
+def zigzags(samples):
+ """Touches with many moves, finger 0: (down time, up time, [(t, y)])."""
+ out, current = [], None
+ for t, kind, finger, x, y in samples:
+ if finger != 0:
+ continue
+ if kind == 1:
+ current = [(t, y)]
+ elif kind == 2 and current is not None:
+ current.append((t, y))
+ elif kind == 3 and current is not None:
+ current.append((t, y))
+ ys = [p[1] for p in current]
+ turns = sum(1 for i in range(1, len(ys) - 1) if (ys[i] - ys[i - 1]) * (ys[i + 1] - ys[i]) < 0)
+ if len(current) > 30 and turns >= 3:
+ out.append((current[0][0], t, current))
+ current = None
+ return out
+
+
+def shift(a, b, most):
+ """How far b's content has moved down from a's, in rows: the shift with the least difference."""
+ h = a.shape[0]
+ best, best_cost = 0, None
+ for s in range(-most, most + 1):
+ if s >= 0:
+ pa, pb = a[0:h - s], b[s:h]
+ else:
+ pa, pb = a[-s:h], b[0:h + s]
+ cost = np.mean(np.abs(pa - pb))
+ if best_cost is None or cost < best_cost:
+ best, best_cost = s, cost
+ return best
+
+
+def content_offsets(frames, t0, t1, height):
+ """The list's position in each frame between t0 and t1, in rows of the recording, relative to the first."""
+ chosen = [(t, p) for t, p in frames if t0 <= t <= t1]
+ out = []
+ if not chosen:
+ return out
+ top, bottom = int(height * 0.15), int(height * 0.90)
+ previous, offset = None, 0
+ for t, pixels in chosen:
+ grey = pixels[top:bottom, :, :].astype(np.float32).mean(axis=2)
+ grey = grey[:, grey.shape[1] // 10: grey.shape[1] * 9 // 10]
+ if previous is not None:
+ offset += shift(previous, grey, 48)
+ out.append((t, offset))
+ previous = grey
+ return out
+
+
+def fit_lag(offsets, touch, height):
+ """The lag (us) at which the list's position best follows the finger's: least squares with an offset and a gain."""
+ tt = np.array([p[0] for p in touch], dtype=np.float64)
+ ty = np.array([p[1] for p in touch], dtype=np.float64) / 65535.0 * height
+ ft = np.array([o[0] for o in offsets], dtype=np.float64)
+ fy = np.array([o[1] for o in offsets], dtype=np.float64)
+ best = None
+ for lag in range(0, 250001, 500):
+ at = ft - lag
+ keep = (at >= tt[0]) & (at <= tt[-1])
+ if keep.sum() < 10:
+ continue
+ x = np.interp(at[keep], tt, ty)
+ y = fy[keep]
+ matrix = np.vstack([x, np.ones_like(x)]).T
+ coefficients, residual, _, _ = np.linalg.lstsq(matrix, y, rcond=None)
+ error = float(np.mean((matrix @ coefficients - y) ** 2))
+ if best is None or error < best[1]:
+ best = (lag, error, coefficients[0], int(keep.sum()))
+ return best
+
+
+def mean(values):
+ return sum(values) / len(values) if values else float('nan')
+
+
+def main():
+ if len(sys.argv) < 2:
+ sys.exit(__doc__)
+ samples, reads, frames, swaps, shows, chip = parse(micros_lines(sys.argv[1]))
+ print(f'latency.py: {len(samples)} samples, {len(reads)} read by the window server, {len(frames)} frames drawn, '
+ f'{len(swaps)} handed over, {len(shows)} shown; {len(chip)} reports read from the touch chip')
+ if chip:
+ found = [seen - before for before, seen, read in chip if before]
+ took = [read - seen for before, seen, read in chip]
+ print(f' touch chip: looked at every {mean(found) / 1000:.2f} ms (a report waits half of that on average); '
+ f'reading a report takes {mean(took) / 1000:.2f} ms')
+ pictures, width, height = recording(sys.argv[2]) if len(sys.argv) > 2 else ([], 0, 0)
+ totals = []
+ for number, (down, up, touch) in enumerate(zigzags(samples)):
+ moves = [p for p in touch[1:-1]]
+ print(f'zigzag {number + 1}: {len(touch)} samples over {(up - down) / 1000:.0f} ms')
+ result = None
+ if pictures:
+ offsets = content_offsets(pictures, down, up + 400000, height)
+ result = fit_lag(offsets, moves, height) if len(offsets) > 10 else None
+ if result is None:
+ print(' (no frames of it in the recording)')
+ continue
+ lag, error, gain, used = result
+ print(f' END TO END: the list follows the finger {lag / 1000:.1f} ms behind, until its pixels are in the panel\'s '
+ f'memory (gain {gain:.2f}, misfit {error ** 0.5:.1f} rows, {used} frames)')
+ totals.append(lag)
+ # the stages, over the samples and frames of this zigzag
+ within = [r for r in reads if down <= r[0] <= up]
+ inject = [r[1] - r[0] for r in within]
+ send = [r[2] - r[1] for r in within]
+ rows = []
+ for sid in sorted(shows):
+ if sid not in swaps or not (down <= shows[sid][2] <= up + 400000):
+ continue
+ swap = swaps[sid]
+ drawn = [f for f in frames if f[1] <= swap]
+ if not drawn:
+ continue
+ began, ended, draws = drawn[-1]
+ ready, shown, done = shows[sid]
+ rows.append((ended - began, swap - ended, ready - swap, shown - ready, done - shown))
+ if rows:
+ render, handover, gpu, beat, copy = (mean([r[k] for r in rows]) for k in range(5))
+ rest = lag - mean(inject) - mean(send) - render - handover - gpu - beat - copy
+ print(f' kernel to window server (the touch device read): {mean(inject) / 1000:6.2f} ms')
+ print(f' window server to event system: {mean(send) / 1000:6.2f} ms')
+ print(f' the application, and the wait for the next frame: {rest / 1000:6.2f} ms (what is left)')
+ print(f' the window server drawing the frame (GPU commands): {render / 1000:6.2f} ms')
+ print(f' frame drawn to frame handed over (SwapEnd): {handover / 1000:6.2f} ms')
+ print(f' waiting for the GPU to finish it: {gpu / 1000:6.2f} ms')
+ print(f' waiting for the display driver\'s beat: {beat / 1000:6.2f} ms')
+ print(f' copying (scaling) it into the panel\'s memory: {copy / 1000:6.2f} ms')
+ print(f' ({len(rows)} frames, {len(within)} samples; then the panel\'s next scan of those rows, '
+ f'0 to 8.3 ms at 120 Hz)')
+ if totals:
+ print(f'all zigzags: {mean(totals) / 1000:.1f} ms behind the finger on average')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/userland/rc.jobs.latency b/userland/rc.jobs.latency
new file mode 100644
index 0000000..ab824ff
--- /dev/null
+++ b/userland/rc.jobs.latency
@@ -0,0 +1,7 @@
+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).
+# How far behind the finger the screen is (boot-arg touch_lat=1, with rec_secs/rec_ring for the frames;
+# tools/latency.py): unlock, Settings, then a wait of 100 seconds -- for the first minutes after a start the
+# widget extensions, searchd and the rest keep all four processors busy, and the touch waits for them --, the
+# list scrolled a little down so that there is room both ways, then the finger goes up and down over it
+# without letting go: twice six times 300 ms each way, and every turn of the finger is looked for in the frames.
+/redwood/bin/rwtouch wait 26 swipe 0.5 0.985 0.5 0.3 200 wait 4 tap 0.615 0.71 wait 100 swipe 0.5 0.8 0.5 0.55 600 wait 3 zigzag 0.5 0.75 0.5 300 6 wait 2 zigzag 0.5 0.75 0.5 300 6
diff --git a/userland/src/eagl.c b/userland/src/eagl.c
index 8168e29..789e35a 100644
--- a/userland/src/eagl.c
+++ b/userland/src/eagl.c
@@ -127,6 +127,7 @@ typedef GLDEBUGPROC GLDEBUGPROCKHR;
struct eagl;
static int eagl_tracing; /* this frame's calls are written down (boot-arg gltrace=FIRST-LAST) */
static int frame_lines; /* boot-arg glframes=1: a line for every frame (see frame_end()) */
+static int latency_lines; /* boot-arg touch_lat=1: when every frame began and ended (see frame_end()) */
static void eagl_trace(const char *format, ...) __attribute__((format(printf, 1, 2)));
static void eagl_trace_floats(const float *values, int count);
static void eagl_enter(struct eagl *e, unsigned offset);
@@ -811,6 +812,10 @@ frame_end(struct eagl *e, bool finished)
after = now_us();
e->in_frame = false;
e->frames++;
+ if (latency_lines) {
+ /* "tl: g FRAME began US ended US DRAWS": microseconds of mach_absolute_time (tools/latency.py) */
+ say("tl: g %u began %llu ended %llu %u\n", e->frames, e->began, after, e->draws);
+ }
if (frame_lines) {
/*
* One line a frame, for matching with a screen recording (the kernel's rec_ring, whose log
@@ -2982,6 +2987,7 @@ install(void)
all_shaders = strstr(arguments, "glshaders=1") != NULL;
census_on = strstr(arguments, "glcensus=1") != NULL;
frame_lines = strstr(arguments, "glframes=1") != NULL;
+ latency_lines = strstr(arguments, "touch_lat=1") != NULL;
full_precision = strstr(arguments, "glprecision=0") == NULL;
vblur_on = strstr(arguments, "vblur=0") != NULL ? 0 : strstr(arguments, "vblur=2") != NULL ? 2 : 1;
if ((argument = strstr(arguments, "glplain=")) != NULL) {
diff --git a/userland/src/inject.c b/userland/src/inject.c
index 8b297cd..f2e9241 100644
--- a/userland/src/inject.c
+++ b/userland/src/inject.c
@@ -32,6 +32,7 @@
#include <errno.h>
#include <fcntl.h>
#include <mach/mach.h>
+#include <mach/mach_time.h>
#include <notify.h>
#include <objc/runtime.h>
#include <pthread.h>
@@ -627,6 +628,20 @@ send_button(IOHIDServiceClientRef buttons, const struct redwood_touch *t)
CFRelease(event);
}
+/*
+ * Boot-arg touch_lat=1: a line for every touch sample, "tl: i TYPE posted US read US sent US" -- when
+ * the kernel stamped it, when this thread had it, when the event system had the event -- in
+ * microseconds of mach_absolute_time, the kernel's own time (tools/latency.py).
+ */
+static bool touch_latency;
+static mach_timebase_info_data_t timebase;
+
+static uint64_t
+micros(uint64_t absolute)
+{
+ return absolute * timebase.numer / timebase.denom / 1000;
+}
+
static void *
input_thread(__unused void *arg)
{
@@ -638,6 +653,15 @@ input_thread(__unused void *arg)
int device;
pthread_setname_np("redwood input");
+ {
+ char arguments[1024] = "";
+ size_t size = sizeof(arguments) - 1;
+
+ if (sysctlbyname("kern.bootargs", arguments, &size, NULL, 0) == 0) {
+ touch_latency = strstr(arguments, "touch_lat=1") != NULL;
+ }
+ mach_timebase_info(&timebase);
+ }
device = open(REDWOOD_TOUCH_DEVICE, O_RDONLY);
if (device < 0) {
say("redwood: input: %s: %s\n", REDWOOD_TOUCH_DEVICE, strerror(errno));
@@ -667,6 +691,8 @@ input_thread(__unused void *arg)
}
while (read(device, &t, sizeof(t)) == (ssize_t)sizeof(t)) {
+ uint64_t read_at = mach_absolute_time();
+
if (count++ < 4) {
say("redwood: input: sample type %u finger %u at %u %u\n", t.type, t.finger, t.x, t.y);
}
@@ -691,6 +717,10 @@ input_thread(__unused void *arg)
}
} else {
send_touch(screen, &t);
+ if (touch_latency) {
+ say("tl: i %u posted %llu read %llu sent %llu\n", t.type, micros(t.time), micros(read_at),
+ micros(mach_absolute_time()));
+ }
}
}
say("redwood: input: %s: %s\n", REDWOOD_TOUCH_DEVICE, strerror(errno));
diff --git a/userland/src/rwtouch.c b/userland/src/rwtouch.c
index d2815ec..85e0857 100644
--- a/userland/src/rwtouch.c
+++ b/userland/src/rwtouch.c
@@ -8,6 +8,9 @@
* drag X0 Y0 X1 Y1 MS HOLD the same, then stay at the end HOLD milliseconds before letting go
* (what is dragged is held where it was taken, neither flung nor sprung back)
* hold X Y MS touch and stay
+ * zigzag X Y0 Y1 MS N [STEP] touch at Y0, go to Y1 in MS milliseconds and back again, N times, then let go;
+ * a sample every STEP milliseconds (default 8, what the touch screen gives):
+ * for measuring how far behind the finger the screen is (tools/latency.py)
* button NAME [MS] press a button: home, lock, volup, voldown
* read print the samples that arrive, forever (to watch the queue)
* notify NAME post a Darwin notification (com.redwood.unlock: see inject_sb.c)
@@ -76,6 +79,38 @@ drag(double x0, double y0, double x1, double y1, int ms, int hold)
post(REDWOOD_TOUCH_UP, x1, y1);
}
+static void
+zigzag(double x, double y0, double y1, int ms, int times, int step_ms)
+{
+ uint64_t start, legs = (uint64_t)times * 2, total_us = legs * (uint64_t)ms * 1000;
+ mach_timebase_info_data_t base;
+
+ mach_timebase_info(&base);
+ post(REDWOOD_TOUCH_DOWN, x, y0);
+ start = mach_absolute_time();
+ for (uint64_t at = (uint64_t)step_ms * 1000; at <= total_us; at += (uint64_t)step_ms * 1000) {
+ uint64_t leg = at / ((uint64_t)ms * 1000), within = at % ((uint64_t)ms * 1000);
+ double part = (double)within / (ms * 1000.0), y;
+ uint64_t now_us;
+
+ if (leg >= legs) {
+ leg = legs - 1;
+ part = 1;
+ }
+ y = leg % 2 == 0 ? y0 + (y1 - y0) * part : y1 + (y0 - y1) * part;
+ /* on a clock of its own, not one sleep after another: the samples keep their pace */
+ do {
+ now_us = (mach_absolute_time() - start) * base.numer / base.denom / 1000;
+ if (now_us < at) {
+ usleep((useconds_t)(at - now_us));
+ }
+ } while (now_us < at);
+ post(REDWOOD_TOUCH_MOVE, x, y);
+ }
+ usleep(16000);
+ post(REDWOOD_TOUCH_UP, x, y0);
+}
+
int
main(int argc, char **argv)
{
@@ -100,6 +135,11 @@ main(int argc, char **argv)
usleep(60000);
post(REDWOOD_TOUCH_UP, x, y);
i += 2;
+ } else if (strcmp(step, "zigzag") == 0 && left >= 5) {
+ int step_ms = left >= 6 && atoi(argv[i + 6]) > 0 ? atoi(argv[i + 6]) : 8;
+
+ zigzag(atof(argv[i + 1]), atof(argv[i + 2]), atof(argv[i + 3]), atoi(argv[i + 4]), atoi(argv[i + 5]), step_ms);
+ i += left >= 6 && atoi(argv[i + 6]) > 0 ? 6 : 5;
} else if (strcmp(step, "hold") == 0 && left >= 3) {
double x = atof(argv[i + 1]), y = atof(argv[i + 2]);
diff --git a/xnu/files/bsd/dev/redwood_goodix.c b/xnu/files/bsd/dev/redwood_goodix.c
index a39ebd5..6918f1c 100644
--- a/xnu/files/bsd/dev/redwood_goodix.c
+++ b/xnu/files/bsd/dev/redwood_goodix.c
@@ -18,7 +18,10 @@
* chip Goodix: find where it keeps the touch report, then read it when the IRQ line signals;
* FocalTech: read the report at register 0x01 with FTS 5.x SPI framing (cmd 0xC1 for
* read, 0xC0 for write, two-byte CRC-16/Kermit)
- * No interrupt is used: a thread looks at the interrupt line 125 times a second.
+ * No interrupt is used: a thread looks at the interrupt line 125 times a second (boot-arg
+ * touch_poll_us=N: every N microseconds instead of 8000). With touch_lat=1 a line for every report
+ * read ("tl: c before US seen US read US": the look before, the look that found the line low, the
+ * report read), for measuring how long a touch takes to show (tools/latency.py).
*
* Register layouts: Linux drivers/spi/spi-geni-qcom.c, drivers/soc/qcom/{qcom-geni-se,rpmh-rsc,
* cmd-db}.c, drivers/clk/qcom/gcc-sc7280.c, drivers/pinctrl/qcom/pinctrl-sc7280.c,
@@ -597,7 +600,8 @@ static bool (*spi_transfer)(const uint8_t *tx, uint8_t *rx, uint32_t length);
#define GOODIX_REQUEST_RESET 3
static uint8_t spi_tx[8 + GOODIX_MAX_READ], spi_rx[8 + GOODIX_MAX_READ];
-static uint32_t touch_address;
+static uint32_t touch_address, command_address;
+static const char *report_rate = "240"; /* what the status line says (touch_rate=480) */
static uint32_t max_x = 10800, max_y = 24000; /* the device tree's; the chip may say otherwise */
static bool
@@ -717,6 +721,7 @@ goodix_probe(bool verbose)
return false;
}
touch_address = le32(info + offset + 44);
+ command_address = le32(info + offset + 0); /* (the "misc" part: the command buffer comes first) */
if (offset + 122 + 20 + 2 <= length) {
uint16_t x = le16(info + offset + 122 + 16), y = le16(info + offset + 122 + 18);
@@ -729,6 +734,51 @@ goodix_probe(bool verbose)
return touch_address != 0;
}
+/*
+ * A command to the chip (Android's brl_send_cmd(): goodix_brl_hw.c of the phone's kernel): sixteen
+ * bytes at the command address -- state, acknowledgement, length, command, its data, and the sum of
+ * the bytes from the length on -- then the acknowledgement looked for, 0x80 when done.
+ */
+#define GOODIX_CMD_HIGH_RATE 0xc0 /* data 1: report 480 times a second instead of 240 (Xiaomi's game mode) */
+#define GOODIX_ACK_OK 0x80
+#define GOODIX_ACK_BUSY 0x02
+
+static bool
+goodix_command(uint8_t command, uint8_t data)
+{
+ uint8_t buffer[16], answer[16];
+ uint32_t sum;
+
+ if (command_address == 0) {
+ return false;
+ }
+ memset(buffer, 0, sizeof(buffer));
+ buffer[2] = 5;
+ buffer[3] = command;
+ buffer[4] = data;
+ sum = buffer[2] + buffer[3] + buffer[4];
+ buffer[5] = (uint8_t)sum;
+ buffer[6] = (uint8_t)(sum >> 8);
+ for (int attempt = 0; attempt < 6; attempt++) {
+ if (!goodix_write(command_address, buffer, sizeof(buffer))) {
+ return false;
+ }
+ for (int look = 0; look < 6; look++) {
+ if (!goodix_read(command_address, answer, sizeof(answer))) {
+ return false;
+ }
+ if (answer[1] == GOODIX_ACK_OK) {
+ return true;
+ }
+ sleep_ms(1);
+ if (answer[1] != GOODIX_ACK_BUSY && answer[1] != 0) {
+ break;
+ }
+ }
+ }
+ return false;
+}
+
/* What has been seen so far: said once a minute, so that the end of the log always tells. */
static struct {
uint32_t polls, reports, touches, bad, last_x, last_y;
@@ -1234,6 +1284,7 @@ focaltech_poll(void)
seen.polls++;
if (!focaltech_read(FOCALTECH_TOUCH_DATA, report, sizeof(report))) {
+ seen.bad++;
if (bad++ < 8) {
printf("focaltech: SPI read failed for touch report\n");
}
@@ -1332,7 +1383,15 @@ bring_up(void)
if (clocks_on()) {
printf("goodix: serial engine: firmware %#x, interface %#x, parameters %#x, source clock %u Hz (select %u)\n",
rd(GENI_FW_REVISION_RO), rd(GENI_IF_DISABLE_RO), rd(SE_HW_PARAM_0), se_source_hz, se_clock_select);
- problem = geni_spi_init(1000000);
+ uint32_t spi_hz = 1000000;
+
+ /* boot-arg touch_spi_hz=N: the bus at N Hz (Android's device tree gives the chip 5 MHz) */
+ PE_parse_boot_argn("touch_spi_hz", &spi_hz, sizeof(spi_hz));
+ if (spi_hz < 100000 || spi_hz > 10000000) {
+ spi_hz = 1000000;
+ }
+ printf("goodix: the bus at %u Hz\n", spi_hz);
+ problem = geni_spi_init(spi_hz);
}
if (problem == NULL) {
use_engine_pins();
@@ -1361,10 +1420,28 @@ bring_up(void)
return false;
}
+static uint64_t
+micros_now(void)
+{
+ uint64_t ns;
+
+ absolutetime_to_nanoseconds(mach_absolute_time(), &ns);
+ return ns / 1000;
+}
+
static void
goodix_thread(__unused void *parameter, __unused wait_result_t result)
{
- unsigned idle = 0;
+ unsigned idle = 0, idle_looks;
+ uint32_t poll_us = 8000, latency = 0, reads = 0;
+ uint64_t before = 0, reading = 0;
+
+ PE_parse_boot_argn("touch_poll_us", &poll_us, sizeof(poll_us));
+ PE_parse_boot_argn("touch_lat", &latency, sizeof(latency));
+ if (poll_us < 250 || poll_us > 100000) {
+ poll_us = 8000;
+ }
+ idle_looks = 80000 / poll_us; /* a report read every 80 ms even with the line high, in case it is missed */
tlmm = ml_io_map(TLMM_PHYS, TLMM_SIZE);
gcc = ml_io_map(GCC_PHYS, GCC_SIZE);
@@ -1377,19 +1454,46 @@ goodix_thread(__unused void *parameter, __unused wait_result_t result)
thread_terminate(current_thread());
return;
}
- printf("goodix: %s touch screen ready\n", chip_name());
+ printf("goodix: %s touch screen ready; the interrupt line is looked at every %u us\n", chip_name(), poll_us);
+ {
+ uint32_t rate = 0;
+
+ /* boot-arg touch_rate=480: the chip reports twice as often (Xiaomi's game mode; 240 otherwise) */
+ if (PE_parse_boot_argn("touch_rate", &rate, sizeof(rate)) && rate == 480 && touch_chip == TOUCH_GOODIX) {
+ bool done = goodix_command(GOODIX_CMD_HIGH_RATE, 1);
+
+ report_rate = done ? "480 (acknowledged)" : "240 (480 NOT ACKNOWLEDGED)";
+ printf("goodix: reports 480 times a second (command %#x at %#x): %s\n", GOODIX_CMD_HIGH_RATE, command_address,
+ done ? "acknowledged" : "NOT ACKNOWLEDGED");
+ }
+ }
for (unsigned tick = 1;; tick++) {
+ uint64_t looked = micros_now(), read_at;
+
/* the interrupt line is low while a report waits; look anyway every 80 ms in case it is missed */
- if (!gpio_get(PIN_INT) || ++idle >= 10) {
+ if (!gpio_get(PIN_INT)) {
+ idle = 0;
+ chip_poll();
+ read_at = micros_now();
+ reads++;
+ reading += read_at - looked;
+ if (latency) {
+ printf("tl: c before %llu seen %llu read %llu\n", before, looked, read_at);
+ }
+ } else if (++idle >= idle_looks) {
idle = 0;
chip_poll();
+ reads++;
+ reading += micros_now() - looked;
}
- if (tick % (60 * 125) == 0) {
+ before = looked;
+ if (tick % (60 * (1000000 / poll_us)) == 0) {
printf("%s: so far %u reports in %u looks (%u bad), %u finger positions, the last at %u, %u; "
- "interrupt line %s\n", chip_name(), seen.reports, seen.polls, seen.bad, seen.touches,
- seen.last_x, seen.last_y, gpio_get(PIN_INT) ? "high" : "low");
+ "interrupt line %s; a report takes %llu us to read; the line looked at every %u us, reports %s a second\n",
+ chip_name(), seen.reports, seen.polls, seen.bad, seen.touches, seen.last_x, seen.last_y,
+ gpio_get(PIN_INT) ? "high" : "low", reads ? reading / reads : 0, poll_us, report_rate);
}
- sleep_ms(8);
+ sleep_us(poll_us);
}
}
diff --git a/xnu/files/bsd/dev/redwood_input.c b/xnu/files/bsd/dev/redwood_input.c
index e2155aa..25fb261 100644
--- a/xnu/files/bsd/dev/redwood_input.c
+++ b/xnu/files/bsd/dev/redwood_input.c
@@ -12,9 +12,30 @@
#include <sys/redwood_input.h>
#include <sys/systm.h>
#include <sys/uio.h>
+#include <pexpert/pexpert.h>
#define TOUCH_QUEUE 512 /* records; a power of two */
+/*
+ * Boot-arg touch_lat=1: for measuring how long a touch takes to reach the panel, a line for every
+ * sample posted ("tl: p TYPE FINGER X Y at US", the time in microseconds of mach_absolute_time),
+ * to be matched with the window server's lines about reading it (userland/src/inject.c), drawing
+ * (eagl.c) and the display driver's about the frame (MiniIOMobileFramebuffer.cpp): see
+ * tools/latency.py.
+ */
+static uint32_t touch_lat = 2; /* 2: not yet looked up */
+
+static bool
+latency_lines(void)
+{
+ if (touch_lat == 2) {
+ uint32_t on = 0;
+
+ touch_lat = PE_parse_boot_argn("touch_lat", &on, sizeof(on)) && on != 0;
+ }
+ return touch_lat != 0;
+}
+
static LCK_GRP_DECLARE(touch_lck_grp, "redwood-touch");
static LCK_MTX_DECLARE(touch_lock, &touch_lck_grp);
static struct redwood_touch touch_queue[TOUCH_QUEUE];
@@ -76,6 +97,12 @@ touch_post(uint32_t type, uint32_t finger, uint32_t x, uint32_t y, bool from_dri
}
t = &touch_queue[touch_tail++ % TOUCH_QUEUE];
t->time = mach_absolute_time();
+ if (latency_lines()) {
+ uint64_t ns;
+
+ absolutetime_to_nanoseconds(t->time, &ns);
+ printf("tl: p %u %u %u %u at %llu\n", type, finger, x, y, ns / 1000);
+ }
t->type = type;
t->finger = finger;
t->x = x > 65535 ? 65535 : x;
diff --git a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
index 69744f5..8d4fd88 100644
--- a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
+++ b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
@@ -151,6 +151,28 @@ static TUNABLE(uint32_t, gDiff, "fb_diff", 0);
static TUNABLE(uint32_t, gFilter, "fb_filter", 1);
static TUNABLE(uint32_t, gRefreshHz, "fb_hz", kFBRefreshHz);
static TUNABLE(uint32_t, gOnTheBeat, "fb_beat", 1);
+/*
+ * Boot-arg fb_threads=N (1 to 8): so many processors scale a frame onto the panel together (see
+ * drawRows()). Three by default: a frame is in the panel's memory 3 ms after its turn instead of 9
+ * to 10 (the phone, 15 October; fb_threads=1 is how it was).
+ */
+static TUNABLE(uint32_t, gThreads, "fb_threads", 3);
+/*
+ * Boot-arg touch_lat=1: a line for every swap handed over ("tl: s ID at US") and for every frame
+ * put on the panel ("tl: v ID ready US shown US done US": the GPU done with it, its beat come, the
+ * pixels in the panel's memory), in microseconds of mach_absolute_time, for measuring how long a
+ * touch takes to show (tools/latency.py; the touch's own lines: bsd/dev/redwood_input.c).
+ */
+static TUNABLE(uint32_t, gTouchLat, "touch_lat", 0);
+
+static inline uint64_t
+micros(uint64_t absolute)
+{
+ uint64_t ns;
+
+ absolutetime_to_nanoseconds(absolute, &ns);
+ return ns / 1000;
+}
static inline uint32_t
refreshHz(void)
@@ -188,6 +210,8 @@ swapWord(const uint8_t * swap, unsigned offset)
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+struct RowJob;
+
class IOMobileFramebuffer : public IOService
{
OSDeclareDefaultStructors(IOMobileFramebuffer);
@@ -265,6 +289,15 @@ public:
static void presenterMain(void * self, wait_result_t result);
void reportFrameTimes(void);
void drawLayer(MiniIOSurface * s, const int32_t * src, const int32_t * dst);
+ void drawRows(const struct RowJob * job, int32_t y0, int32_t y1, uint32_t * blendRow);
+ static void helperMain(void * self, wait_result_t result);
+ /* the scaling shared out (fb_threads): fThreads drawers, the presenter and fThreads - 1 helpers */
+ unsigned fThreads;
+ IOLock * fHelperLock;
+ const struct RowJob * fHelperJob;
+ uint64_t fHelperGeneration;
+ unsigned fHelpersBusy, fHelpersStarted;
+ uint32_t * fHelperBlend[7];
void record(MiniIOSurface * s);
};
@@ -362,6 +395,16 @@ IOMobileFramebuffer::start(IOService * provider)
}
thread_set_thread_name(thread, "frames to the panel");
thread_deallocate(thread);
+ fThreads = gThreads >= 1 && gThreads <= 8 ? gThreads : 1;
+ fHelperLock = IOLockAlloc();
+ for (unsigned i = 0; i + 1 < fThreads; i++) {
+ if (kernel_thread_start(&IOMobileFramebuffer::helperMain, this, &thread) != KERN_SUCCESS) {
+ fThreads = i + 1;
+ break;
+ }
+ thread_set_thread_name(thread, "frames to the panel: a helper");
+ thread_deallocate(thread);
+ }
fBase = (uint8_t *) vinfo.v_baseaddr;
fPanelWidth = vinfo.v_width;
fPanelHeight = vinfo.v_height;
@@ -530,67 +573,27 @@ sample_at(int64_t i, int64_t in, int64_t out)
}
/*
- * Put a rectangle of a 32-bit surface on the screen. `dst` is in display coordinates; the
- * panel may be of another size, and the layer itself may be scaled: both are done in one
- * step, bilinear (or nearest neighbour: fb_filter=0).
+ * The rows of one layer, from `y0` to `y1` (panel rows), as drawLayer() has worked them out:
+ * scaling a whole frame takes one processor some 9 ms, so with boot-arg fb_threads=N it is shared
+ * out between N of them, each with rows of its own and a row of blending of its own.
*/
+struct RowJob {
+ const uint8_t * pixels;
+ uint32_t stride;
+ int32_t sx, sy, sw, sh, px0, py0, px1, py1, cx0, cx1;
+ bool filter, unscaled;
+};
+
void
-IOMobileFramebuffer::drawLayer(MiniIOSurface * s, const int32_t * src, const int32_t * dst)
+IOMobileFramebuffer::drawRows(const RowJob * job, int32_t y0, int32_t y1, uint32_t * blendRow)
{
- int32_t sx = src[0], sy = src[1], sw = src[2], sh = src[3];
- int32_t dx = dst[0], dy = dst[1], dw = dst[2], dh = dst[3];
- const uint8_t * pixels = s->pixels();
- uint32_t stride = s->info.bytesPerRow;
- int32_t px0, py0, px1, py1, cx0, cx1;
- bool filter = gFilter != 0;
+ const uint8_t * pixels = job->pixels;
+ uint32_t stride = job->stride;
+ int32_t sx = job->sx, sy = job->sy, sw = job->sw, sh = job->sh;
+ int32_t px0 = job->px0, py0 = job->py0, px1 = job->px1, py1 = job->py1, cx0 = job->cx0, cx1 = job->cx1;
+ bool filter = job->filter;
- if (sw <= 0 || sh <= 0) {
- sx = sy = 0;
- sw = (int32_t) s->info.width;
- sh = (int32_t) s->info.height;
- }
- if (dw <= 0 || dh <= 0) {
- dx = dy = 0;
- dw = (int32_t) fWidth;
- dh = (int32_t) fHeight;
- }
- if (sx < 0 || sy < 0 || (uint32_t) (sx + sw) > s->info.width || (uint32_t) (sy + sh) > s->info.height) {
- return;
- }
- /* the rectangle on the panel */
- px0 = (int32_t) ((int64_t) dx * fPanelWidth / fWidth);
- py0 = (int32_t) ((int64_t) dy * fPanelHeight / fHeight);
- px1 = (int32_t) ((int64_t) (dx + dw) * fPanelWidth / fWidth);
- py1 = (int32_t) ((int64_t) (dy + dh) * fPanelHeight / fHeight);
- if (px1 <= px0 || py1 <= py0) {
- return;
- }
- /* (blending, a row of the picture mixed from two: room for it) */
- if (filter && fBlendRowSize < (uint32_t) sw) {
- if (fBlendRow != NULL) {
- IODelete(fBlendRow, uint32_t, fBlendRowSize);
- }
- fBlendRowSize = (uint32_t) sw;
- fBlendRow = IONew(uint32_t, fBlendRowSize);
- if (fBlendRow == NULL) {
- fBlendRowSize = 0;
- }
- }
- filter = filter && fBlendRow != NULL;
- /* which pixel of a source row each pixel of a panel row takes: worked out once, not 2.6 million times */
- cx0 = px0 < 0 ? 0 : px0;
- cx1 = (uint32_t) px1 > fPanelWidth ? (int32_t) fPanelWidth : px1;
- for (int32_t x = cx0; x < cx1; x++) {
- if (filter) {
- int64_t at = sample_at(x - px0, sw, px1 - px0);
-
- fColumn[x] = (uint32_t) (at >> 8); /* (in the blended row: from sx on) */
- fColumnWeight[x] = (uint16_t) (fColumn[x] + 1 < (uint32_t) sw ? at & 255 : 0);
- } else {
- fColumn[x] = (uint32_t) (sx + (int64_t) (x - px0) * sw / (px1 - px0));
- }
- }
- for (int32_t y = py0; y < py1; y++) {
+ for (int32_t y = y0; y < y1; y++) {
const uint32_t * from;
uint32_t * to;
@@ -598,7 +601,7 @@ IOMobileFramebuffer::drawLayer(MiniIOSurface * s, const int32_t * src, const int
continue;
}
to = (uint32_t *) (fBase + (size_t) y * fRowBytes);
- if (px1 - px0 == sw && py1 - py0 == sh && px0 >= 0 && (uint32_t) px1 <= fPanelWidth) {
+ if (job->unscaled) {
/* not scaled at all */
memcpy(to + px0, pixels + (size_t) (sy + y - py0) * stride + (size_t) sx * 4, (size_t) sw * 4);
continue;
@@ -614,14 +617,14 @@ IOMobileFramebuffer::drawLayer(MiniIOSurface * s, const int32_t * src, const int
const uint32_t * lower = (const uint32_t *) (pixels + (size_t) (sy + row + 1) * stride) + sx;
uint32_t first = fColumn[cx0], last = fColumn[cx1 - 1] + 1 < (uint32_t) sw ? fColumn[cx1 - 1] + 1 : fColumn[cx1 - 1];
- uint32_t * __restrict mixed = fBlendRow;
+ uint32_t * __restrict mixed = blendRow;
for (uint32_t c = first; c <= last; c++) {
uint32_t a = upper[c], b = lower[c];
mixed[c] = a == b ? a : blend(a, b, weight); /* (most of a screen is the same as next to it) */
}
- from = fBlendRow;
+ from = blendRow;
}
} else {
from = (const uint32_t *) (pixels + (size_t) (sy + (int64_t) (y - py0) * sh / (py1 - py0)) * stride);
@@ -658,6 +661,149 @@ IOMobileFramebuffer::drawLayer(MiniIOSurface * s, const int32_t * src, const int
}
}
+/* A helper of the scaling (fb_threads): waits for rows to do, does them, says so. */
+void
+IOMobileFramebuffer::helperMain(void * self, wait_result_t result __unused)
+{
+ IOMobileFramebuffer * fb = (IOMobileFramebuffer *) self;
+ unsigned index;
+ uint64_t done = 0;
+
+ IOLockLock(fb->fHelperLock);
+ index = fb->fHelpersStarted++;
+ IOLockUnlock(fb->fHelperLock);
+ for (;;) {
+ const RowJob * job;
+ int32_t rows, y0, y1;
+ uint32_t * blend;
+
+ IOLockLock(fb->fHelperLock);
+ while (fb->fHelperGeneration == done) {
+ IOLockSleep(fb->fHelperLock, &fb->fHelperGeneration, THREAD_UNINT);
+ }
+ done = fb->fHelperGeneration;
+ job = fb->fHelperJob;
+ IOLockUnlock(fb->fHelperLock);
+ /* share index + 1 of fThreads (the presenter takes share 0) */
+ rows = job->py1 - job->py0;
+ y0 = job->py0 + (int32_t) ((int64_t) rows * (index + 1) / fb->fThreads);
+ y1 = job->py0 + (int32_t) ((int64_t) rows * (index + 2) / fb->fThreads);
+ blend = fb->fHelperBlend[index];
+ fb->drawRows(job, y0, y1, blend);
+ IOLockLock(fb->fHelperLock);
+ fb->fHelpersBusy--;
+ if (fb->fHelpersBusy == 0) {
+ IOLockWakeup(fb->fHelperLock, &fb->fHelpersBusy, true);
+ }
+ IOLockUnlock(fb->fHelperLock);
+ }
+}
+
+/*
+ * Put a rectangle of a 32-bit surface on the screen. `dst` is in display coordinates; the
+ * panel may be of another size, and the layer itself may be scaled: both are done in one
+ * step, bilinear (or nearest neighbour: fb_filter=0).
+ */
+void
+IOMobileFramebuffer::drawLayer(MiniIOSurface * s, const int32_t * src, const int32_t * dst)
+{
+ int32_t sx = src[0], sy = src[1], sw = src[2], sh = src[3];
+ int32_t dx = dst[0], dy = dst[1], dw = dst[2], dh = dst[3];
+ int32_t px0, py0, px1, py1, cx0, cx1;
+ bool filter = gFilter != 0;
+ RowJob job;
+
+ if (sw <= 0 || sh <= 0) {
+ sx = sy = 0;
+ sw = (int32_t) s->info.width;
+ sh = (int32_t) s->info.height;
+ }
+ if (dw <= 0 || dh <= 0) {
+ dx = dy = 0;
+ dw = (int32_t) fWidth;
+ dh = (int32_t) fHeight;
+ }
+ if (sx < 0 || sy < 0 || (uint32_t) (sx + sw) > s->info.width || (uint32_t) (sy + sh) > s->info.height) {
+ return;
+ }
+ /* the rectangle on the panel */
+ px0 = (int32_t) ((int64_t) dx * fPanelWidth / fWidth);
+ py0 = (int32_t) ((int64_t) dy * fPanelHeight / fHeight);
+ px1 = (int32_t) ((int64_t) (dx + dw) * fPanelWidth / fWidth);
+ py1 = (int32_t) ((int64_t) (dy + dh) * fPanelHeight / fHeight);
+ if (px1 <= px0 || py1 <= py0) {
+ return;
+ }
+ /* (blending, a row of the picture mixed from two: room for it, for every one who draws rows) */
+ if (filter && fBlendRowSize < (uint32_t) sw) {
+ if (fBlendRow != NULL) {
+ IODelete(fBlendRow, uint32_t, fBlendRowSize);
+ }
+ for (unsigned i = 0; i + 1 < fThreads; i++) {
+ if (fHelperBlend[i] != NULL) {
+ IODelete(fHelperBlend[i], uint32_t, fBlendRowSize);
+ }
+ }
+ fBlendRowSize = (uint32_t) sw;
+ fBlendRow = IONew(uint32_t, fBlendRowSize);
+ for (unsigned i = 0; i + 1 < fThreads; i++) {
+ fHelperBlend[i] = IONew(uint32_t, fBlendRowSize);
+ if (fHelperBlend[i] == NULL && fBlendRow != NULL) {
+ IODelete(fBlendRow, uint32_t, fBlendRowSize);
+ fBlendRow = NULL;
+ }
+ }
+ if (fBlendRow == NULL) {
+ fBlendRowSize = 0;
+ }
+ }
+ filter = filter && fBlendRow != NULL;
+ /* which pixel of a source row each pixel of a panel row takes: worked out once, not 2.6 million times */
+ cx0 = px0 < 0 ? 0 : px0;
+ cx1 = (uint32_t) px1 > fPanelWidth ? (int32_t) fPanelWidth : px1;
+ for (int32_t x = cx0; x < cx1; x++) {
+ if (filter) {
+ int64_t at = sample_at(x - px0, sw, px1 - px0);
+
+ fColumn[x] = (uint32_t) (at >> 8); /* (in the blended row: from sx on) */
+ fColumnWeight[x] = (uint16_t) (fColumn[x] + 1 < (uint32_t) sw ? at & 255 : 0);
+ } else {
+ fColumn[x] = (uint32_t) (sx + (int64_t) (x - px0) * sw / (px1 - px0));
+ }
+ }
+ job.pixels = s->pixels();
+ job.stride = s->info.bytesPerRow;
+ job.sx = sx;
+ job.sy = sy;
+ job.sw = sw;
+ job.sh = sh;
+ job.px0 = px0;
+ job.py0 = py0;
+ job.px1 = px1;
+ job.py1 = py1;
+ job.cx0 = cx0;
+ job.cx1 = cx1;
+ job.filter = filter;
+ job.unscaled = px1 - px0 == sw && py1 - py0 == sh && px0 >= 0 && (uint32_t) px1 <= fPanelWidth;
+ if (fThreads <= 1 || fDiff || fHelpersStarted + 1 < fThreads) {
+ drawRows(&job, py0, py1, fBlendRow);
+ return;
+ }
+ /* shared out: the helpers take their rows, this thread the first share, then waits for them */
+ IOLockLock(fHelperLock);
+ fHelperJob = &job;
+ fHelpersBusy = fThreads - 1;
+ fHelperGeneration++;
+ IOLockWakeup(fHelperLock, &fHelperGeneration, false);
+ IOLockUnlock(fHelperLock);
+ drawRows(&job, py0, py0 + (int32_t) ((int64_t) (py1 - py0) / fThreads), fBlendRow);
+ IOLockLock(fHelperLock);
+ while (fHelpersBusy != 0) {
+ IOLockSleep(fHelperLock, &fHelpersBusy, THREAD_UNINT);
+ }
+ IOLockUnlock(fHelperLock);
+}
+
/*
* How evenly the frames of the last seconds came: how many followed the one before within the
* time of one refresh at 120, 60, 40 and 30 a second, and the times half and 95 in 100 of them
@@ -708,6 +854,9 @@ IOMobileFramebuffer::present(const uint8_t * swap)
nanoseconds_to_absolutetime(NSEC_PER_SEC / refreshHz() * 5 / 4, &period);
nanoseconds_to_absolutetime(FRAME_PAUSE * NSEC_PER_MSEC, &pause);
clock_interval_to_deadline(SWAP_HELD_MS, kMillisecondScale, &deadline);
+ if (gTouchLat) {
+ IOLog("tl: s %u at %llu\n", swapWord(swap, SWAP_ID), micros(now));
+ }
IOLockLock(fSwapLock);
fStatSwapsLate += fSwapTime != 0 && now - fSwapTime > period && now - fSwapTime < pause;
fSwapTime = now;
@@ -765,8 +914,9 @@ void
IOMobileFramebuffer::show(const uint8_t * swap, MiniIOSurface ** surfaces)
{
uint32_t set = swapWord(swap, SWAP_LAYERS_SET);
- uint64_t began = mach_absolute_time(), nanos;
+ uint64_t began = mach_absolute_time(), nanos, ready, shown, drawn;
uint32_t layers = 0;
+ MiniIOSurface * recorded = NULL;
bool report;
for (unsigned layer = 0; layer < SWAP_LAYERS; layer++) {
@@ -776,7 +926,7 @@ IOMobileFramebuffer::show(const uint8_t * swap, MiniIOSurface ** surfaces)
}
}
fStatWaiting += mach_absolute_time() - began;
- began = mach_absolute_time();
+ began = ready = mach_absolute_time();
if (gOnTheBeat) {
uint64_t period, aim, next;
@@ -801,6 +951,7 @@ IOMobileFramebuffer::show(const uint8_t * swap, MiniIOSurface ** surfaces)
began = mach_absolute_time();
}
}
+ shown = began;
/* its turn has come: the swap after it may be handed over */
IOLockLock(fSwapLock);
fSwapThere = false;
@@ -868,11 +1019,19 @@ IOMobileFramebuffer::show(const uint8_t * swap, MiniIOSurface ** surfaces)
}
drawLayer(s, src, dst);
if (layer == 0) {
- record(s);
+ recorded = s; /* (recorded once the frame is in the panel's memory: see below) */
}
}
}
+ drawn = mach_absolute_time();
+ if (recorded != NULL) {
+ record(recorded);
+ }
fSwapsShown++;
+ if (gTouchLat) {
+ IOLog("tl: v %u ready %llu shown %llu done %llu\n", swapWord(swap, SWAP_ID), micros(ready), micros(shown),
+ micros(drawn));
+ }
if (layers != fLayersShown) {
IOLog("MiniIOMobileFramebuffer: swap #%u: surfaces in layers 0x%x now (0x%x before): %u %u %u %u\n", fSwapsShown, layers,
fLayersShown, swapWord(swap, SWAP_SURFACE(0)), swapWord(swap, SWAP_SURFACE(1)), swapWord(swap, SWAP_SURFACE(2)),
diff --git a/xnu/files/osfmk/arm64/user_exception_trace.c b/xnu/files/osfmk/arm64/user_exception_trace.c
index 22889d5..6989451 100644
--- a/xnu/files/osfmk/arm64/user_exception_trace.c
+++ b/xnu/files/osfmk/arm64/user_exception_trace.c
@@ -326,7 +326,7 @@ ustacks_fire(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
if (strcmp(ustacks_name, "top") == 0) {
ustacks_top();
- return;
+ goto again;
}
lck_mtx_lock(&tasks_threads_lock);
queue_iterate(&tasks, task, task_t, tasks) {
@@ -349,6 +349,7 @@ ustacks_fire(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
}
task_deallocate(found[i]);
}
+again:
if (ustacks_every != 0) {
uint64_t deadline;