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

All seven cores no slower than four: the small ones are used after the big; frame pacing measured

vcvkk002a24c4c1cd
diff --git a/README.md b/README.md
index a1f5f0c..62abdbb 100644
--- a/README.md
+++ b/README.md
@@ -209,11 +209,12 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./xl run #
| Параметр | Что делает |
|---|---|
| `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` показывает, кто занимал процессор) |
+| `touch_lat=1` | замер задержки касания и ровности кадров (`RC_JOBS=rc.jobs.fps`: листание домашнего экрана, Поиск, Пункт управления, открытие Настроек, бросок списка, закрытие — трижды; `tools/frames.py ЖУРНАЛ ЖУРНАЛ.live*` — кадров в секунду и доля кадров дольше 16,7 и 33 мс по каждому жесту, куда ушло время медленных; `XL_FOLLOW=8 XL_FOLLOW_KEEP=1` сохраняет все промежуточные журналы, в которых есть то, что конечный теряет). Вместе с `glslow=МКС` — строка о каждом вызове OpenGL ES дольше МКС; SpringBoard пишет `tl: a` о каждом обороте своего главного цикла. Замер задержки касания: строки `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` | запустить ядро на самом большом ядре процессора (загрузчик остаётся на нулевом и наблюдает) |
-| `cpus=N` | использовать N ядер процессора: то, на котором ядро запущено, и ещё N−1 ближайших к нему по номеру (после 7 — 6, 5, 4, потом малые 3, 2, 1); их запускает само ядро через PSCI. `cpumask=M` — выбрать по позиции в этом порядке (бит 0 — загрузочное). Без параметра — одно ядро. **На телефоне не проверено**, порядок проверки — в конце раздела |
+| `cpus=N` | использовать N ядер процессора: то, на котором ядро запущено, и ещё N−1 ближайших к нему по номеру (после 7 — 6, 5, 4, потом малые 3, 2, 1); их запускает само ядро через PSCI. `cpumask=M` — выбрать по позиции в этом порядке (бит 0 — загрузочное). Без параметра — одно ядро. На телефоне ядру достаётся не больше семи: нулевое занято загрузчиком, который наблюдает за сеансом. Малые ядра (Cortex-A55, в 2,5 раза медленнее больших) загрузчик помечает в дереве устройств (`small-core`), и планировщик берёт их, только когда все большие заняты: каждое малое — пара своему большому, как второй поток ядра с гиперпотоками у XNU, но без его ограничений, а поток с малого ядра переводится на большое, как только то освободилось. `small_cores=0` — все ядра одинаковы, как было раньше (тогда `cpus=8` заметно медленнее `cpus=4`); `small_cores=1` — пары ровно как у гиперпотоков XNU. Нужен загрузчик от 15 октября (`./xl reload`): со старым малые ядра не помечены |
+| `cpuload=MS` | каждые MS миллисекунд строка `tl: u` о том, насколько было занято каждое ядро процессора (в процентах; `tools/frames.py` показывает это по жестам) |
| `cpufreq=1` | поднять частоту до максимума (иначе 300 МГц) всем группам ядер, в которых есть наши |
| `rec_secs=N` | записывать экран N секунд (`rec_start=S`, `rec_mb=M`, не больше 640); потом `./xl recording out.mp4`. `rec_ring=1` — по кругу: когда память кончилась, запись идёт поверх самых старых кадров, и к концу сеанса в ней последнее (для того, что случается раз за долгий сеанс: сеанс кончают сразу после — пятью пальцами); `rec_step=N` — каждый N-й пиксель вместо третьего (4 — в 1,8 раза больше кадров). Память на запись отнимается у системы на весь сеанс: с `rec_mb=640` в долгом сеансе iOS убивала процессы ради памяти, вплоть до SpringBoard (респринги), с 256 — нет. `XL_REC_KEEP=1 ./xl recording` оставляет саму запись в `logs/recording.raw`; `tools/recording.py logs/recording.raw out.mp4 --frames DIR` раскладывает её на кадры с именами по времени ядра в миллисекундах — тому же, что в строках `glframes=1` |
| `rec_sound=N` | сохранить первые N секунд звука, который играет iOS (тишина между звуками места не занимает); потом `./xl sound out.wav` |
@@ -222,11 +223,13 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./xl run #
| `applog=1` / `applog=2` | stderr приложений в журнал / плюс os_log всех процессов |
| `applog_name=ИМЯ[,ИМЯ]` | вместе с `applog=1`: os_log только тех программ, чьи имена файлов начинаются с одного из ИМЁН (так читают расширения приложений — виджеты, обои: их запускает launchd по просьбе других процессов, описания задания у нас для них нет) |
| `launchd_disable_all_timeouts=1` | параметр самого launchd: не убивать расширение приложения, которое не отметилось за 5 секунд после запуска («Extension is hanging on launch. Killing.»). Нужен только в QEMU, где при загрузке полсотни расширений стартуют одновременно на эмулируемом процессоре; на телефоне таких убийств нет |
+| `ustacks=ИМЯ ustacks_at=С` | через С секунд после запуска напечатать, где стоит каждый поток процесса ИМЯ (`ustacks_ms=МС` — повторять каждые МС, `ustacks_count=N` — N раз, `ustacks_threads=N` — только первые N потоков, `ustacks_tname=ТЕКСТ` — только потоки, в имени которых есть ТЕКСТ: тогда строки идут и в журнал загрузчика, с именем потока и временем); имена функций — `qemu/symstack.py ЖУРНАЛ ИМЯ`. `ustacks=top` — кто сколько занимал процессор |
| `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_threads=N` | столько ядер вместе масштабируют кадр на панель (по умолчанию 3: кадр в памяти панели через 3 мс вместо 9–10; `fb_threads=1` — как было) |
| `fb_beat=0` | кадр уходит на панель сразу, как GPU его закончил, а не по собственному такту драйвера 60 Гц (такт держит ровный шаг, но кадр ждёт его в среднем 5–7 мс; панель всё равно обновляется 120 раз в секунду и к такту не привязана) |
+| `ca_vbl=1` | (опыт) CoreAnimation ведёт кадры по уведомлениям драйвера экрана о такте (`CA_FORCE_TIMER=1` в backboardd), а не по своим часам; на ровность кадров не повлияло |
| `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 — загрузочный) и/или через панику |
@@ -240,10 +243,14 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./xl run #
| `adsp=1` | аудиопроцессор телефона (ADSP: звук, а у Xiaomi ещё и зарядка), шаг 1 звука: прошивка `adsp.mdt` и `adsp.b02`…`adsp.b36` с разделов телефона (`/vendor/firmware_mnt/image`, в каталог `fw-audio/`, в git не попадает; `userland/build.sh` кладёт её в образ системы в `/fw`, откуда ядро читает её, когда корень смонтирован, — после её появления образ системы пересобирается с `SYSTEM=1`; для `adsp_step=N`, который идёт до монтирования, — в малый образ с `ADSP=1`, и только без `GL=1`: вместе они не помещаются в 64 МБ, что берёт загрузчик) кладётся в его память, RPMh просят о его шинах питания LCX и LMX, пока он не попросит о них сам, TrustZone его запускает, через 41 мс он говорит «готов», поднимается GLINK (канал IPCRTR) и QRTR поверх него: процессор — узел 5 — объявляет 12 служб и открывает свои каналы, среди них `apr_audio_svc`; на нём — APR, протокол звуковых служб: служба ядра процессора отвечает, что звуковые службы готовы, и перечисляет их (9, среди них AFE, ASM, ADM — то, через что пойдёт звук). Рядом с загрузкой системы и рядом с `wifi=1`; в конце сеанса его просят остановиться и выключают. `adsp_step=N` — то же по шагам (первые N из 11, ядро ждёт), подробности в начале `bsd/dev/redwood_adsp.c` |
| `sound=N` | с `adsp=1`, шаг 3 звука, путь к динамикам, как его строит Android (числа — из живого дерева устройств телефона, его путей микшера и его ядра): `sound=1` — ножки TDM (GPIO 97–100) отданы интерфейсу, звуковой процессор включает его тактовую частоту (3,072 МГц), группу и порт 0x9000 (PRI_TDM_RX_0) и запускает его; по ножкам видно, что тактовый сигнал и синхронизация кадров идут. `sound=2` — ещё и поток: наша память видна процессору через SMMU (поток 0x1801), путь ADM к порту, поток ASM, и в него 3 с пишется тон 1 кГц −20 дБ полной шкалы; процессор забирает его с частотой 48 кГц. Усилители выключены. `sound=3` — ещё и усилители: настраиваются из профиля «Music» конфигурации Android (`/vendor/etc/aw882xx_acf.bin` телефона в `fw-audio/`, в git не попадает, `userland/build.sh` кладёт её в `/fw` образа системы), каждая запись читается обратно, при любом расхождении или сбое оба сразу выключаются; громкость плавно поднимается до `sound_below` восьмых долей дБ ниже уровня Android (по умолчанию 240, то есть на 30 дБ тише), тон звучит 3 с, потом всё затихает, выключается и возвращается как было. `sound=4` — то, что играет iOS (`/dev/redwood-audio`), до конца сеанса: порт и поток работают всё время (без звука в них идёт тишина), усилители настраиваются один раз и выключены, а когда в записи iOS появляется не тишина, включаются и быстро (как у драйвера Android) выводятся на `sound_below`; после трёх секунд тишины снова выключаются. Звук доходит до усилителей через 160 мс после записи, усилители готовы через 65 мс. У динамика в модуле HAL есть регулятор громкости, его значение уходит в ядро (`ioctl` `REDWOOD_AUDIO_SET_VOLUME`) и задаёт уровень усилителей ниже потолка (0 — усилители не включаются), но iOS ставит его только раз, на максимум, а громкость кнопок и Пункта управления применяет к самим отсчётам (программная громкость для динамика iPhone X в таблицах VirtualAudio); при громкости 0 iOS пишет тишину, и усилители тоже не включаются. Проверка — `RC_JOBS=rc.jobs.volume`. `sound_secs=S` (не больше 3 с тоном), `sound_pause=MS`. Подробности в начале `bsd/dev/redwood_sound.c` и `bsd/dev/redwood_speaker.c` |
-Несколько ядер на телефоне проверены (2, 4 и 7 ядер запускаются и чисто возвращаются в загрузчик). Лучший
-вариант — **`cpus=4`**: четыре больших ядра (7, 6, 5, 4). На одном и том же сценарии: 929 кадров вместо 671,
-пики 35 кадров/с вместо 19, SpringBoard готов на 7 секунд раньше. `cpus=7` хуже четырёх: планировщик не знает,
-что ядра 1–3 малые, и сажает на них интерфейс. Паника «Ticket spinlock … timeout» значила бы, что ядрам тесно
+Несколько ядер на телефоне проверены (2, 4 и 7 ядер запускаются и чисто возвращаются в загрузчик). На одном и
+том же сценарии `cpus=4` (четыре больших ядра: 7, 6, 5, 4) дал 929 кадров вместо 671 на одном ядре, пики 35
+кадров/с вместо 19, SpringBoard готов на 7 секунд раньше. Все семь (`cpus=8`) раньше были хуже четырёх:
+планировщик не знал, что ядра 1–3 малые, и сажал на них интерфейс (84 % кадров дольше 16,7 мс против 46 %,
+копирование кадра на панель 15 мс вместо 4). Теперь малые ядра помечены (см. `cpus=N` в таблице), и `cpus=8`
+вровень с `cpus=4` по кадрам (`rc.jobs.fps`, трижды: 39 % и 35 % кадров дольше 16,7 мс, 8 % и 7 % дольше 33 мс),
+а вся работа запуска кончается на 2–4 с раньше (36–38 с против 40); экран блокировки при этом готов на ~1 с
+позже (27,5 с против 26,7: малые ядра делят с большими память и кэш, пока все семь заняты запуском). Паника «Ticket spinlock … timeout» значила бы, что ядрам тесно
во времени (в QEMU загрузчик сам увеличивает эти сроки в 20 раз): помогает `ml-timeout-global-scale=4`.
## GPU
diff --git a/qemu/symstack.py b/qemu/symstack.py
index 81ec10c..450c5c8 100755
--- a/qemu/symstack.py
+++ b/qemu/symstack.py
@@ -67,10 +67,10 @@ def main():
continue
if not show:
continue
- m = re.search(r'ustacks: thread (0x[0-9a-f]+): (.*)', line)
+ m = re.search(r'ustacks: thread (0x[0-9a-f]+)([^:]*): (.*)', line)
if m:
- print(f' thread {m.group(1)}')
- for depth, text in enumerate(m.group(2).split()):
+ print(f' thread {m.group(1)}{m.group(2)}')
+ for depth, text in enumerate(m.group(3).split()):
if depth == 1:
continue # the link register: usually stale, the frame chain has the caller
print(f' {name(int(text, 16), slide)}')
diff --git a/tools/frames.py b/tools/frames.py
new file mode 100644
index 0000000..6ec6ca7
--- /dev/null
+++ b/tools/frames.py
@@ -0,0 +1,140 @@
+#!/usr/bin/env python3
+"""
+frames.py RUN.log [MORE.log ...]: how evenly the frames of a run's gestures came, and what held up the slow ones.
+(More logs: the live ones of the same run, XL_FOLLOW=N XL_FOLLOW_KEEP=1, which keep what the run's log loses.)
+
+Reads the "tl:" lines a run with boot-arg touch_lat=1 writes (see tools/latency.py for what each
+says): the samples and buttons of rwtouch (tl: p), the window server's frames (tl: g: began, ended),
+their hand-over (tl: s), the display driver's GPU wait and copy (tl: v), and every wait of a program
+for the GPU of a millisecond or more (tl: f). Every gesture -- from a touch going down, or a button,
+to the next one or 2.5 s later -- is a segment; for each:
+
+ frames a second while frames came; the share of frame-to-frame times (as the frames reached the
+ panel's memory) over 16.7 ms (counted from 18.0: a 60 Hz frame missed) and over 33 ms (from 34.5);
+ with boot-arg cpuload=MS (tl: u), how busy each processor core was meanwhile, in percent;
+ and for the frames over 16.7 ms, where the time between the previous frame and this one went:
+ draw the window server drawing it (its first draw to its glFlush done: CPU, Mesa included)
+ gpu the GPU after the hand-over (SwapEnd to done)
+ idle the window server not drawing at all before it began (waiting for a commit, a fence, ...)
+ copy the display driver's copy into the panel's memory
+
+The thresholds are as the coordinator asked for them; 18.0 rather than 16.7 because a frame of a steady
+60 comes 16.6 to 16.8 ms after the one before.
+"""
+import sys
+
+OVER_ONE, OVER_TWO, SEGMENT_US = 18000, 34500, 2500000
+
+
+def lines_of(paths):
+ seen, out = set(), []
+ for path in paths:
+ 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)
+ out.append(line)
+ return out
+
+
+def main():
+ if len(sys.argv) < 2:
+ sys.exit(__doc__)
+ gestures, frames, swaps, shows, waits, loads = [], [], {}, {}, [], []
+ for line in lines_of(sys.argv[1:]):
+ w = line.split()
+ try:
+ if w[1] == 'p' and len(w) >= 8 and int(w[2]) in (1, 4):
+ gestures.append((int(w[7]), int(w[2]), int(w[3]), int(w[4]), int(w[5])))
+ 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] == 'f' and len(w) >= 6:
+ waits.append((int(w[5]), w[2], int(w[3])))
+ elif w[1] == 'u' and len(w) >= 4:
+ loads.append((int(w[3]), {int(a): int(b) for a, b in (x.split(':') for x in w[4:])}))
+ except ValueError:
+ pass
+ gestures.sort()
+ frames.sort(key=lambda f: f[1])
+ # every frame on the panel, with the drawing it came from
+ timeline = []
+ for sid in sorted(shows):
+ if sid not in swaps:
+ 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]
+ timeline.append(dict(began=began, ended=ended, swap=swap, ready=ready, shown=shown, done=done))
+ timeline.sort(key=lambda f: f['done'])
+ all_counts = [0, 0, 0]
+ kinds, previous = {}, '' # the same gesture done more than once: its frames together
+ print(f'frames.py: {len(gestures)} gestures, {len(timeline)} frames on the panel, {len(waits)} waits for the GPU '
+ f'of 1 ms or more')
+ for i, (start, kind, button, x, y) in enumerate(gestures):
+ end = min(gestures[i + 1][0] if i + 1 < len(gestures) else start + SEGMENT_US, start + SEGMENT_US)
+ chosen = [f for f in timeline if start <= f['done'] < end]
+ what = f'button {button}' if kind == 4 else f'touch at {x / 655.35:.0f}%,{y / 655.35:.0f}%'
+ key = f'{what} after {previous}' if kind == 4 else what
+ previous = what
+ if len(chosen) < 3:
+ print(f'{i + 1:2}. {start / 1e6:9.3f} s {what}: {len(chosen)} frames')
+ continue
+ gaps = [(b['done'] - a['done'], a, b) for a, b in zip(chosen, chosen[1:])]
+ moving = [g for g in gaps if g[0] < 100000] # (a pause is the end of the movement, not a slow frame)
+ span = sum(g[0] for g in moving)
+ over1 = [g for g in moving if g[0] > OVER_ONE]
+ over2 = [g for g in moving if g[0] > OVER_TWO]
+ all_counts[0] += len(moving)
+ all_counts[1] += len(over1)
+ all_counts[2] += len(over2)
+ k = kinds.setdefault(key, [0, 0, 0, 0, 0])
+ k[0] += 1
+ k[1] += len(moving)
+ k[2] += span
+ k[3] += len(over1)
+ k[4] += len(over2)
+ fps = len(moving) * 1e6 / span if span else 0
+ line = (f'{i + 1:2}. {start / 1e6:9.3f} s {what}: {len(moving)} frames at {fps:4.1f} a second; '
+ f'over 16.7 ms {100 * len(over1) / max(1, len(moving)):3.0f}%, over 33 ms {100 * len(over2) / max(1, len(moving)):3.0f}%')
+ if over1:
+ # where the slow frames' time went (means over them)
+ def mean(values):
+ return sum(values) / len(values) / 1000 if values else 0
+ draw = mean([b['ended'] - b['began'] for _, a, b in over1])
+ gpu = mean([b['ready'] - b['swap'] for _, a, b in over1])
+ idle = mean([b['began'] - a['ready'] for _, a, b in over1])
+ copy = mean([b['done'] - b['shown'] for _, a, b in over1])
+ line += f'; the slow ones: draw {draw:4.1f}, gpu {gpu:4.1f}, idle before {idle:5.1f}, copy {copy:3.1f} ms'
+ stalls = [w for w in waits if start <= w[0] < end]
+ if stalls:
+ line += f'; {len(stalls)} waits for the GPU ({sum(w[2] for w in stalls) / 1000:.0f} ms)'
+ # the load samples that end within the movement (each covers the cpuload=MS before it)
+ within = [l for t, l in loads if chosen[0]['done'] < t <= chosen[-1]['done']]
+ if within:
+ cores = sorted({c for l in within for c in l}, reverse=True)
+ line += '; cores busy ' + ' '.join(f'{c}:{sum(l.get(c, 0) for l in within) / len(within):.0f}%' for c in cores)
+ print(line)
+ if any(k[0] > 1 for k in kinds.values()):
+ print('the same gestures together:')
+ for key, (times, steps, span, over1, over2) in kinds.items():
+ print(f' {key:40} {times} times, {steps:4} frames at {steps * 1e6 / span if span else 0:4.1f} a second; '
+ f'over 16.7 ms {100 * over1 / max(1, steps):3.0f}%, over 33 ms {100 * over2 / max(1, steps):3.0f}%')
+ if all_counts[0]:
+ print(f'all gestures: {all_counts[0]} frame steps, over 16.7 ms {100 * all_counts[1] / all_counts[0]:.0f}%, '
+ f'over 33 ms {100 * all_counts[2] / all_counts[0]:.0f}%')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/latency.py b/tools/latency.py
index cde7186..5d8e5cc 100644
--- a/tools/latency.py
+++ b/tools/latency.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
"""
-latency.py RUN.log RECORDING.raw: how far behind the finger the phone's screen is.
+latency.py RUN.log [MORE.log ...] [RECORDING.raw]: how far behind the finger the phone's screen is.
+(More logs: the live ones of the same run, XL_FOLLOW=N XL_FOLLOW_KEEP=1, which keep what the run's log loses.)
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):
@@ -31,10 +32,13 @@ 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)."""
+def micros_lines(paths):
+ """The tl: lines of the logs, once each (the kernel's own also come back in its log at the end)."""
seen, lines = set(), []
- with open(path, 'rb') as f:
+ if isinstance(paths, str):
+ paths = [paths]
+ for path in paths:
+ with open(path, 'rb') as f:
for raw in f:
text = raw.decode('utf-8', 'replace')
at = text.find('tl: ')
@@ -172,7 +176,9 @@ def mean(values):
def main():
if len(sys.argv) < 2:
sys.exit(__doc__)
- samples, reads, frames, swaps, shows, chip = parse(micros_lines(sys.argv[1]))
+ logs = [a for a in sys.argv[1:] if not a.endswith('.raw')]
+ raws = [a for a in sys.argv[1:] if a.endswith('.raw')]
+ samples, reads, frames, swaps, shows, chip = parse(micros_lines(logs))
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:
@@ -180,7 +186,7 @@ def main():
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)
+ pictures, width, height = recording(raws[0]) if raws else ([], 0, 0)
totals = []
for number, (down, up, touch) in enumerate(zigzags(samples)):
moves = [p for p in touch[1:-1]]
diff --git a/userland/rc.jobs.fps b/userland/rc.jobs.fps
new file mode 100644
index 0000000..d1b46b8
--- /dev/null
+++ b/userland/rc.jobs.fps
@@ -0,0 +1,15 @@
+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).
+# The everyday cases for frame pacing (boot-arg touch_lat=1; tools/frames.py): unlock, then 100 s for the
+# start-up's background work to be over, then home-screen page swipes both ways, Search pulled down and
+# closed, Control Center from the top right corner and closed, Settings opened (the zoom), its list flung
+# down and up, and closed with the home gesture (the zoom back); all of it three times over.
+/redwood/bin/rwtouch wait 26 swipe 0.5 0.985 0.5 0.3 200 wait 100
+/redwood/bin/rwtouch swipe 0.85 0.5 0.15 0.5 300 wait 2 swipe 0.15 0.5 0.85 0.5 300 wait 2 swipe 0.85 0.5 0.15 0.5 300 wait 2 swipe 0.15 0.5 0.85 0.5 300 wait 3
+/redwood/bin/rwtouch swipe 0.5 0.4 0.5 0.7 300 wait 3 button home wait 3 swipe 0.92 0.003 0.92 0.5 300 wait 3 button home wait 3
+/redwood/bin/rwtouch tap 0.615 0.71 wait 3 swipe 0.5 0.8 0.5 0.3 150 wait 3 swipe 0.5 0.3 0.5 0.8 150 wait 3 swipe 0.5 0.995 0.5 0.55 150 wait 3
+/redwood/bin/rwtouch swipe 0.85 0.5 0.15 0.5 300 wait 2 swipe 0.15 0.5 0.85 0.5 300 wait 2 swipe 0.85 0.5 0.15 0.5 300 wait 2 swipe 0.15 0.5 0.85 0.5 300 wait 3
+/redwood/bin/rwtouch swipe 0.5 0.4 0.5 0.7 300 wait 3 button home wait 3 swipe 0.92 0.003 0.92 0.5 300 wait 3 button home wait 3
+/redwood/bin/rwtouch tap 0.615 0.71 wait 3 swipe 0.5 0.8 0.5 0.3 150 wait 3 swipe 0.5 0.3 0.5 0.8 150 wait 3 swipe 0.5 0.995 0.5 0.55 150 wait 3
+/redwood/bin/rwtouch swipe 0.85 0.5 0.15 0.5 300 wait 2 swipe 0.15 0.5 0.85 0.5 300 wait 2 swipe 0.85 0.5 0.15 0.5 300 wait 2 swipe 0.15 0.5 0.85 0.5 300 wait 3
+/redwood/bin/rwtouch swipe 0.5 0.4 0.5 0.7 300 wait 3 button home wait 3 swipe 0.92 0.003 0.92 0.5 300 wait 3 button home wait 3
+/redwood/bin/rwtouch tap 0.615 0.71 wait 3 swipe 0.5 0.8 0.5 0.3 150 wait 3 swipe 0.5 0.3 0.5 0.8 150 wait 3 swipe 0.5 0.995 0.5 0.55 150 wait 3
diff --git a/userland/src/eagl.c b/userland/src/eagl.c
index 789e35a..08c0d06 100644
--- a/userland/src/eagl.c
+++ b/userland/src/eagl.c
@@ -128,6 +128,9 @@ 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 uint64_t slow_calls_us; /* boot-arg glslow=US: a line for every call that takes longer (eagl_leave()) */
+static uint64_t call_began_us; /* (when the call in progress began) */
+static uint64_t now_us(void);
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);
@@ -336,6 +339,9 @@ eagl_enter(struct eagl *e, unsigned offset)
}
slot_calls[offset / 8]++;
e->calls++;
+ if (slow_calls_us != 0) {
+ call_began_us = now_us();
+ }
}
static void
@@ -348,6 +354,15 @@ eagl_leave(struct eagl *e, unsigned offset)
say("redwood-gl: %s: error %#x\n", eagl_slot_name(offset), error);
}
}
+ if (slow_calls_us != 0) {
+ uint64_t now = now_us();
+
+ /* "tl: slow NAME US at US, frame N": a call that took long, and when it ended (tools/frames.py) */
+ if (now - call_began_us >= slow_calls_us) {
+ say("tl: slow %s %llu at %llu, frame %u%s\n", eagl_slot_name(offset), now - call_began_us, now, e->frames + 1,
+ e->in_frame ? "" : " (before its first draw)");
+ }
+ }
}
/* An entry the library has no function for: say so, once an entry. */
@@ -2988,6 +3003,9 @@ install(void)
census_on = strstr(arguments, "glcensus=1") != NULL;
frame_lines = strstr(arguments, "glframes=1") != NULL;
latency_lines = strstr(arguments, "touch_lat=1") != NULL;
+ if ((argument = strstr(arguments, "glslow=")) != NULL) {
+ slow_calls_us = strtoull(argument + 7, NULL, 10);
+ }
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 f2e9241..f04104f 100644
--- a/userland/src/inject.c
+++ b/userland/src/inject.c
@@ -831,6 +831,20 @@ redwood_init(void)
}
slide = (uintptr_t)cache - CACHE_BASE;
if (strcmp(name, "backboardd") == 0) {
+ char arguments[1024] = "";
+ size_t size = sizeof(arguments) - 1;
+
+ /*
+ * Boot-arg ca_vbl=1: CoreAnimation's frame clock from the display driver's refresh
+ * notifications. QuartzCore takes them (IOMobileFramebufferEnableVSyncNotifications) only on
+ * the phones with an A7 to A10, or when CA_FORCE_TIMER is in the environment
+ * (CADeviceUseVBL()); on the iPhone X it runs a timer of its own instead (CADisplayTimer),
+ * whose phase it would set from the frame timings of a display driver this one is not.
+ */
+ if (sysctlbyname("kern.bootargs", arguments, &size, NULL, 0) == 0 && strstr(arguments, "ca_vbl=1") != NULL) {
+ setenv("CA_FORCE_TIMER", "1", 1);
+ say("redwood: ca_vbl=1: CoreAnimation is to take the display driver's refresh notifications\n");
+ }
opengl_es();
window_server_fixes();
/*
diff --git a/userland/src/inject_sb.c b/userland/src/inject_sb.c
index dfd4e69..e67698a 100644
--- a/userland/src/inject_sb.c
+++ b/userland/src/inject_sb.c
@@ -33,6 +33,7 @@
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <dispatch/dispatch.h>
+#include <mach/mach_time.h>
#include <notify.h>
#include <objc/message.h>
#include <objc/runtime.h>
@@ -60,6 +61,51 @@ say(const char *format, ...)
write(2, line, (size_t)n);
}
+/*
+ * Boot-arg touch_lat=1: a line for every turn of SpringBoard's main run loop -- when it woke up (a
+ * touch, a timer, the display link ...) and when it went to sleep again, CoreAnimation's commit of
+ * what that turn changed done (its observer comes before ours) -- in microseconds of
+ * mach_absolute_time, as the other "tl:" lines (tools/latency.py, tools/frames.py):
+ * tl: a WOKE SLEPT
+ */
+static uint64_t main_woke;
+static mach_timebase_info_data_t timebase;
+
+static uint64_t
+now_us(void)
+{
+ return mach_absolute_time() * timebase.numer / timebase.denom / 1000;
+}
+
+static void
+main_loop_turn(__unused CFRunLoopObserverRef observer, CFRunLoopActivity activity, __unused void *info)
+{
+ if (activity == kCFRunLoopAfterWaiting) {
+ main_woke = now_us();
+ } else if (activity == kCFRunLoopBeforeWaiting && main_woke != 0) {
+ say("tl: a %llu %llu\n", main_woke, now_us());
+ main_woke = 0;
+ }
+}
+
+static void
+watch_main_loop(void)
+{
+ char args[1024] = "";
+ size_t size = sizeof(args) - 1;
+ const char *arg;
+
+ if (sysctlbyname("kern.bootargs", args, &size, NULL, 0) != 0 || (arg = strstr(args, "touch_lat=1")) == NULL ||
+ (arg != args && arg[-1] != ' ')) {
+ return;
+ }
+ mach_timebase_info(&timebase);
+ CFRunLoopAddObserver(CFRunLoopGetMain(), CFRunLoopObserverCreate(NULL, kCFRunLoopAfterWaiting, true, LONG_MIN,
+ main_loop_turn, NULL), kCFRunLoopCommonModes);
+ CFRunLoopAddObserver(CFRunLoopGetMain(), CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, true, LONG_MAX,
+ main_loop_turn, NULL), kCFRunLoopCommonModes);
+}
+
/* ---- methods of SpringBoard's classes, replaced --------------------------------------------------- */
extern const void *_dyld_get_shared_cache_range(size_t *length);
@@ -710,6 +756,7 @@ redwood_springboard_init(void)
if (device && class_getInstanceMethod(object_getClass(device), monitoring)) {
((void (*)(id, SEL, BOOL))objc_msgSend)(device, monitoring, YES);
}
+ watch_main_loop();
say("redwood: battery: SOC=%d%% battery=%d charger=%d charging=%d\n",
sysctl_int("kern.redwood.battery_soc"), sysctl_int("kern.redwood.battery_present"),
sysctl_int("kern.redwood.battery_charger_present"), sysctl_int("kern.redwood.battery_charging"));
diff --git a/userland/src/rwtouch.c b/userland/src/rwtouch.c
index 85e0857..ff4072e 100644
--- a/userland/src/rwtouch.c
+++ b/userland/src/rwtouch.c
@@ -9,7 +9,8 @@
* (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):
+ * a sample every STEP milliseconds (default 8, what the touch screen gives, as
+ * swipe and drag give them):
* 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)
@@ -58,15 +59,48 @@ button(uint32_t which, int ms)
write(device, &t, sizeof(t));
}
+#define SAMPLE_MS 8 /* a sample every so many milliseconds: what the touch screen gives */
+
+static mach_timebase_info_data_t timebase;
+
+/* Until `at` microseconds after `start` (mach_absolute_time()): on a clock of its own, not one sleep after another */
+static void
+sleep_until(uint64_t start, uint64_t at)
+{
+ uint64_t now_us;
+
+ do {
+ now_us = (mach_absolute_time() - start) * timebase.numer / timebase.denom / 1000;
+ if (now_us < at) {
+ usleep((useconds_t)(at - now_us));
+ }
+ } while (now_us < at);
+}
+
+/*
+ * A sample every SAMPLE_MS on the way, each where the finger would be by then. (Once one sleep of a
+ * frame after another: those came out at 21 ms apart, 48 samples a second, fewer than the display's
+ * 60 frames, and an application that is moved by the samples drew no more frames than that.)
+ */
static void
drag(double x0, double y0, double x1, double y1, int ms, int hold)
{
- int steps = ms / 16 > 2 ? ms / 16 : 2; /* a sample per display frame */
+ uint64_t start, total_us = (uint64_t)(ms > 0 ? ms : 1) * 1000;
post(REDWOOD_TOUCH_DOWN, x0, y0);
- for (int i = 1; i <= steps; i++) {
- usleep((useconds_t)ms * 1000 / (useconds_t)steps);
- post(REDWOOD_TOUCH_MOVE, x0 + (x1 - x0) * i / steps, y0 + (y1 - y0) * i / steps);
+ start = mach_absolute_time();
+ for (uint64_t at = SAMPLE_MS * 1000;; at += SAMPLE_MS * 1000) {
+ double part;
+
+ if (at > total_us) {
+ at = total_us;
+ }
+ part = (double)at / (double)total_us;
+ sleep_until(start, at);
+ post(REDWOOD_TOUCH_MOVE, x0 + (x1 - x0) * part, y0 + (y1 - y0) * part);
+ if (at == total_us) {
+ break;
+ }
}
usleep(16000);
if (hold > 0) {
@@ -83,28 +117,19 @@ 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);
+ sleep_until(start, at);
post(REDWOOD_TOUCH_MOVE, x, y);
}
usleep(16000);
@@ -116,6 +141,7 @@ main(int argc, char **argv)
{
/* a gesture is a matter of timing: do not let the rest of a busy system stretch it */
pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
+ mach_timebase_info(&timebase);
device = open(REDWOOD_TOUCH_DEVICE, O_RDWR);
if (device < 0) {
perror("rwtouch: " REDWOOD_TOUCH_DEVICE);
diff --git a/xl b/xl
index e52b120..cffb2c4 100755
--- a/xl
+++ b/xl
@@ -130,7 +130,10 @@ run() { # run <oem command> <label>
[ "$(date +%s)" -ge "$deadline" ] && { result=; break; }
if [ -n "$XL_FOLLOW" ] && [ $(( $(date +%s) - followed )) -ge "$XL_FOLLOW" ]; then
followed=$(date +%s)
- fb oem log | grep -q OKAY && fetch_log "$log.live"
+ # (XL_FOLLOW_KEEP=1: every one kept, $log.live.1, .2, ...: a long run's middle, which the log
+ # itself loses once more than a megabyte follows it, is then all there)
+ followed_n=$(( ${followed_n:-0} + 1 ))
+ fb oem log | grep -q OKAY && fetch_log "$log.live" && { [ -z "$XL_FOLLOW_KEEP" ] || cp "$log.live" "$log.live.$followed_n"; }
fi
sleep 2
done
diff --git a/xnu/files/bsd/dev/redwood_cpufreq.c b/xnu/files/bsd/dev/redwood_cpufreq.c
index 9d345de..9c438ae 100644
--- a/xnu/files/bsd/dev/redwood_cpufreq.c
+++ b/xnu/files/bsd/dev/redwood_cpufreq.c
@@ -12,14 +12,38 @@
* Register layout: Linux drivers/cpufreq/qcom-cpufreq-hw.c ("epss" variant).
*/
#include <kern/clock.h>
+#include <kern/thread.h>
#include <libkern/libkern.h>
#include <mach/mach_types.h>
#include <machine/machine_routines.h>
#include <pexpert/pexpert.h>
#include <sys/redwood_input.h>
#include <sys/systm.h>
+#include <vm/vm_kern.h>
extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
+extern void loader_log_putc(char c);
+extern void redwood_tl(const char *format, ...) __printflike(1, 2);
+extern bool ml_cpu_idle_time(int cpu_id, uint64_t *idle);
+
+/* The loader's log as well: this runs early, and the kernel's own log of a run keeps only its end. */
+static void
+tell(const char *format, ...) __printflike(1, 2);
+
+static void
+tell(const char *format, ...)
+{
+ char line[256];
+ va_list list;
+
+ va_start(list, format);
+ vsnprintf(line, sizeof(line), format, list);
+ va_end(list);
+ for (const char *c = line; *c != 0; c++) {
+ loader_log_putc(*c);
+ }
+ printf("%s", line);
+}
#define EPSS_PHYS 0x18591000UL /* three groups ("domains") of 0x1000: small cores, big, biggest */
#define EPSS_DOMAIN_SIZE 0x1000UL
@@ -73,16 +97,116 @@ raise_domain(uint32_t domain, uint32_t cores)
was = *(volatile uint32_t *)(base + EPSS_PERF_STATE);
*(volatile uint32_t *)(base + EPSS_PERF_STATE) = top;
delay_for_interval(20, NSEC_PER_MSEC);
- printf("cpufreq: group %u (%u of our cores): row %u -> %u of the frequency table, %u MHz\n", domain, cores, was, top,
+ tell("cpufreq: group %u (%u of our cores): row %u -> %u of the frequency table, %u MHz\n", domain, cores, was, top,
top_khz / 1000);
}
+/*
+ * Boot-arg membench=1: how fast this processor reads, writes and copies memory, in MB a second
+ * (32 MB at a time, far more than any cache): what the memory's clock allows a processor, which
+ * nobody here asks to be raised.
+ */
+static void
+memory_bench(void)
+{
+ const vm_size_t size = 32u << 20;
+ vm_offset_t a = 0, b = 0;
+ uint64_t began, ns[3] = { 0, 0, 0 };
+ volatile uint64_t sum = 0;
+
+ if (kmem_alloc(kernel_map, &a, size, KMA_KOBJECT | KMA_DATA, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS ||
+ kmem_alloc(kernel_map, &b, size, KMA_KOBJECT | KMA_DATA, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
+ printf("membench: no memory\n");
+ return;
+ }
+ memset((void *)a, 1, size);
+ memset((void *)b, 2, size);
+ for (int round = 0; round < 4; round++) {
+ uint64_t t;
+
+ began = mach_absolute_time();
+ memset((void *)a, round, size);
+ absolutetime_to_nanoseconds(mach_absolute_time() - began, &t);
+ ns[0] += t;
+ began = mach_absolute_time();
+ for (const uint64_t *p = (const uint64_t *)b, *end = (const uint64_t *)(b + size); p < end; p += 8) {
+ sum += p[0] + p[1] + p[2] + p[3] + p[4] + p[5] + p[6] + p[7];
+ }
+ absolutetime_to_nanoseconds(mach_absolute_time() - began, &t);
+ ns[1] += t;
+ began = mach_absolute_time();
+ memcpy((void *)b, (const void *)a, size);
+ absolutetime_to_nanoseconds(mach_absolute_time() - began, &t);
+ ns[2] += t;
+ }
+ tell("membench: on core %llu: writing %llu MB/s, reading %llu MB/s, copying %llu MB/s\n",
+ (__builtin_arm_rsr64("MPIDR_EL1") >> 8) & 0xff, 4ull * (size >> 20) * 1000000000ull / ns[0],
+ 4ull * (size >> 20) * 1000000000ull / ns[1], 4ull * (size >> 20) * 1000000000ull / ns[2]);
+ kmem_free(kernel_map, a, size);
+ kmem_free(kernel_map, b, size);
+}
+
+/*
+ * Boot-arg cpuload=MS: every MS milliseconds, how busy each of our cores was meanwhile, in
+ * percent, to the loader's log (tools/frames.py shows it per gesture):
+ * tl: u at US 7:NN 6:NN ... 1:NN the core's number (as in its MPIDR), then its share
+ * of the time it was not idle (interrupts included).
+ */
+static uint32_t load_every_ms;
+
+static void
+load_thread(void *arg __unused, wait_result_t wr __unused)
+{
+ const ml_topology_info_t *topology = ml_get_topology_info();
+ uint64_t idle_before[MAX_CPUS] = { 0 }, then = mach_absolute_time();
+
+ for (;;) {
+ char line[192];
+ int at;
+ uint64_t now, us;
+
+ delay_for_interval(load_every_ms, NSEC_PER_MSEC);
+ now = mach_absolute_time();
+ absolutetime_to_nanoseconds(now, &us);
+ at = snprintf(line, sizeof(line), "tl: u at %llu", us / 1000);
+ for (unsigned int i = 0; i < topology->num_cpus && i < MAX_CPUS; i++) {
+ uint64_t idle = 0, busy;
+
+ if (!ml_cpu_idle_time((int)i, &idle)) {
+ continue;
+ }
+ busy = (now - then) > (idle - idle_before[i]) ? (now - then) - (idle - idle_before[i]) : 0;
+ idle_before[i] = idle;
+ if (at < (int)sizeof(line) - 12) {
+ at += snprintf(line + at, sizeof(line) - at, " %u:%llu", (topology->cpus[i].phys_id >> 8) & 0xff,
+ 100 * busy / (now - then));
+ }
+ }
+ then = now;
+ redwood_tl("%s\n", line);
+ }
+}
+
+static void
+load_start(void)
+{
+ thread_t thread;
+
+ if (!PE_parse_boot_argn("cpuload", &load_every_ms, sizeof(load_every_ms)) || load_every_ms == 0) {
+ return;
+ }
+ if (kernel_thread_start(load_thread, NULL, &thread) == KERN_SUCCESS) {
+ thread_deallocate(thread);
+ }
+}
+
void
redwood_cpufreq_init(void)
{
const ml_topology_info_t *topology = ml_get_topology_info();
uint32_t enabled = 0, cores[EPSS_DOMAINS] = { 0 }, before, here;
+ load_start();
if (!PE_parse_boot_argn("cpufreq", &enabled, sizeof(enabled)) || !enabled) {
return;
}
@@ -98,4 +222,7 @@ redwood_cpufreq_init(void)
}
}
printf("cpufreq: on core %u a loop ran at %u, now at %u\n", here, before, loop_speed());
+ if (PE_parse_boot_argn("membench", &enabled, sizeof(enabled)) && enabled) {
+ memory_bench();
+ }
}
diff --git a/xnu/files/bsd/dev/redwood_goodix.c b/xnu/files/bsd/dev/redwood_goodix.c
index 6918f1c..f969cbd 100644
--- a/xnu/files/bsd/dev/redwood_goodix.c
+++ b/xnu/files/bsd/dev/redwood_goodix.c
@@ -36,6 +36,8 @@
#include <sys/redwood_input.h>
#include <sys/systm.h>
+extern void redwood_tl(const char *format, ...) __printflike(1, 2);
+
extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
extern vm_offset_t ml_io_map_wcomb(vm_offset_t phys_addr, vm_size_t size);
extern kern_return_t thread_terminate(thread_t thread);
@@ -1478,7 +1480,7 @@ goodix_thread(__unused void *parameter, __unused wait_result_t result)
reads++;
reading += read_at - looked;
if (latency) {
- printf("tl: c before %llu seen %llu read %llu\n", before, looked, read_at);
+ redwood_tl("tl: c before %llu seen %llu read %llu\n", before, looked, read_at);
}
} else if (++idle >= idle_looks) {
idle = 0;
diff --git a/xnu/files/bsd/dev/redwood_input.c b/xnu/files/bsd/dev/redwood_input.c
index 25fb261..6c584d6 100644
--- a/xnu/files/bsd/dev/redwood_input.c
+++ b/xnu/files/bsd/dev/redwood_input.c
@@ -25,6 +25,26 @@
*/
static uint32_t touch_lat = 2; /* 2: not yet looked up */
+extern void loader_log_line(const char *line);
+
+/*
+ * A "tl:" line, for the kernel's drivers: into the loader's log as it is written -- the kernel's own
+ * log keeps only the last of a run, and a live look at the loader's (XL_FOLLOW) then misses nothing.
+ */
+void redwood_tl(const char *format, ...) __printflike(1, 2);
+
+void
+redwood_tl(const char *format, ...)
+{
+ char line[192];
+ va_list list;
+
+ va_start(list, format);
+ vsnprintf(line, sizeof(line), format, list);
+ va_end(list);
+ loader_log_line(line);
+}
+
static bool
latency_lines(void)
{
@@ -101,7 +121,7 @@ touch_post(uint32_t type, uint32_t finger, uint32_t x, uint32_t y, bool from_dri
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);
+ redwood_tl("tl: p %u %u %u %u at %llu\n", type, finger, x, y, ns / 1000);
}
t->type = type;
t->finger = finger;
diff --git a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
index 8d4fd88..3efc5c6 100644
--- a/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
+++ b/xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp
@@ -37,6 +37,8 @@ extern struct vc_info vinfo; /* the boot framebuffer, as the text con
#include "MiniIOSurface.h"
+extern "C" void redwood_tl(const char * format, ...) __printflike(1, 2);
+
/* IOConnectCallMethod selectors of the framebuffer user client (iOS 16.5) */
enum {
kFBMethodGetLayerDefaultSurface = 3,
@@ -855,7 +857,7 @@ IOMobileFramebuffer::present(const uint8_t * swap)
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));
+ redwood_tl("tl: s %u at %llu\n", swapWord(swap, SWAP_ID), micros(now));
}
IOLockLock(fSwapLock);
fStatSwapsLate += fSwapTime != 0 && now - fSwapTime > period && now - fSwapTime < pause;
@@ -1029,7 +1031,7 @@ IOMobileFramebuffer::show(const uint8_t * swap, MiniIOSurface ** surfaces)
}
fSwapsShown++;
if (gTouchLat) {
- IOLog("tl: v %u ready %llu shown %llu done %llu\n", swapWord(swap, SWAP_ID), micros(ready), micros(shown),
+ redwood_tl("tl: v %u ready %llu shown %llu done %llu\n", swapWord(swap, SWAP_ID), micros(ready), micros(shown),
micros(drawn));
}
if (layers != fLayersShown) {
@@ -1334,6 +1336,11 @@ IOMobileFramebufferUserClient::externalMethod(uint32_t selector, IOExternalMetho
return kIOReturnSuccess;
case kFBMethodSwapWait: /* a swap is on the screen as soon as it is made */
+ if (gTouchLat) {
+ redwood_tl("tl: w %llu %#llx %#llx at %llu\n", args->scalarInputCount > 0 ? in[0] : 0,
+ args->scalarInputCount > 1 ? in[1] : 0, args->scalarInputCount > 2 ? in[2] : 0, micros(mach_absolute_time()));
+ }
+ return kIOReturnSuccess;
case kFBMethodSwapSignal:
case kFBMethodSwapCancel:
case kFBMethodSwapCancelAll:
diff --git a/xnu/files/iokit/Kernel/RedwoodGPU.cpp b/xnu/files/iokit/Kernel/RedwoodGPU.cpp
index 1c6670f..ad3bd9b 100644
--- a/xnu/files/iokit/Kernel/RedwoodGPU.cpp
+++ b/xnu/files/iokit/Kernel/RedwoodGPU.cpp
@@ -42,6 +42,8 @@
#include "MiniIOSurface.h"
+extern "C" void redwood_tl(const char * format, ...) __printflike(1, 2);
+
extern "C" {
/* bsd/dev/redwood_adreno.c ("the GPU kept on"; declared in bsd/sys/redwood_input.h, which is not seen from here) */
bool redwood_gpu_ready(void);
@@ -223,6 +225,27 @@ MiniIOSurfaceDrawn(MiniIOSurface * surface, uint64_t milliseconds)
return done;
}
+/*
+ * Boot-arg touch_lat=1: a line for every wait of a program's for the GPU that took a millisecond or
+ * more ("tl: f KIND US at US"), for telling apart what holds a frame up (tools/frames.py).
+ */
+static TUNABLE(uint32_t, gWaitLines, "touch_lat", 0);
+
+static void
+slowWait(const char * kind, uint64_t began)
+{
+ uint64_t now = mach_absolute_time(), ns, at;
+
+ if (!gWaitLines) {
+ return;
+ }
+ absolutetime_to_nanoseconds(now - began, &ns);
+ if (ns >= NSEC_PER_MSEC) {
+ absolutetime_to_nanoseconds(now, &at);
+ redwood_tl("tl: f %s %llu at %llu\n", kind, ns / 1000, at / 1000);
+ }
+}
+
/* How long from now a time of msm's is, in milliseconds; 0: now or past. */
static uint64_t
millisecondsUntil(const struct msm_timespec * when)
@@ -910,7 +933,7 @@ RedwoodGPUUserClient::externalMethod(uint32_t selector, IOExternalMethodArgument
size_t size = args->structureInputSize;
struct gpu_buffer * b;
IOReturn ret = kIOReturnSuccess;
- uint64_t zero = 0, patience;
+ uint64_t zero = 0, patience, waitBegan;
if (args->structureInput == NULL || size > sizeof(r) || fBuffers == NULL) {
return kIOReturnBadArgument;
@@ -936,6 +959,7 @@ RedwoodGPUUserClient::externalMethod(uint32_t selector, IOExternalMethodArgument
ret = gemInfo(&r.gemInfo);
break;
case kMsmGemCpuPrep: /* is the GPU done with a buffer: with all it has been given, here */
+ waitBegan = mach_absolute_time();
IOLockLock(gGPULock);
patience = (r.cpuPrep.op & MSM_PREP_NOSYNC) ? 0 : millisecondsUntil(&r.cpuPrep.timeout);
if (!gpuWait(redwood_gpu_last(), patience)) {
@@ -945,11 +969,13 @@ RedwoodGPUUserClient::externalMethod(uint32_t selector, IOExternalMethodArgument
}
}
IOLockUnlock(gGPULock);
+ slowWait("cpu-prep", waitBegan);
break;
case kMsmGemSubmit:
ret = submit(&r.submit);
break;
case kMsmWaitFence:
+ waitBegan = mach_absolute_time();
IOLockLock(gGPULock);
patience = millisecondsUntil(&r.waitFence.timeout);
if (!gpuWait(r.waitFence.fence, patience)) {
@@ -959,6 +985,7 @@ RedwoodGPUUserClient::externalMethod(uint32_t selector, IOExternalMethodArgument
}
}
IOLockUnlock(gGPULock);
+ slowWait("fence", waitBegan);
break;
case kMsmGemMadvise:
r.madvise.retained = 1;
diff --git a/xnu/files/osfmk/arm64/loader_return.c b/xnu/files/osfmk/arm64/loader_return.c
index ac2f743..3e6e5c4 100644
--- a/xnu/files/osfmk/arm64/loader_return.c
+++ b/xnu/files/osfmk/arm64/loader_return.c
@@ -75,6 +75,8 @@ static char loader_log_scratch[LOADER_LOG_RING];
*/
static uint32_t loader_log_lock;
+static void loader_log_put_locked(char c);
+
void
loader_log_putc(char c)
{
@@ -89,7 +91,44 @@ loader_log_putc(char c)
for (uint32_t tries = 0; !locked && tries < 10000000; tries++) {
locked = os_atomic_cmpxchg(&loader_log_lock, 0, 1, acquire);
}
+ loader_log_put_locked(c);
+ if (locked) {
+ os_atomic_store(&loader_log_lock, 0, release);
+ }
+ __builtin_arm_wsr64("DAIF", daif);
+}
+
+/*
+ * A whole line at once, under the lock: lines written from several processors at the same time
+ * (tools/latency.py's "tl:" lines, a frame's on one and a touch's on another) are not mixed up.
+ */
+void loader_log_line(const char *line);
+
+void
+loader_log_line(const char *line)
+{
+ uint64_t daif;
+ bool locked = false;
+
+ daif = __builtin_arm_rsr64("DAIF");
+ __builtin_arm_wsr("DAIFSet", DAIFSC_IRQF | DAIFSC_FIQF);
+ for (uint32_t tries = 0; !locked && tries < 10000000; tries++) {
+ locked = os_atomic_cmpxchg(&loader_log_lock, 0, 1, acquire);
+ }
+ for (; *line != 0; line++) {
+ if (*line != '\r') {
+ loader_log_put_locked(*line);
+ }
+ }
+ if (locked) {
+ os_atomic_store(&loader_log_lock, 0, release);
+ }
+ __builtin_arm_wsr64("DAIF", daif);
+}
+static void
+loader_log_put_locked(char c)
+{
if (loader_log_linear || loader_log_len < LOADER_LOG_HEAD) {
if (loader_log_len < LOADER_LOG_SIZE) {
loader_log[loader_log_len++] = c;
@@ -104,11 +143,6 @@ loader_log_putc(char c)
loader_log_len = LOADER_LOG_HEAD + loader_log_ring_at;
}
}
-
- if (locked) {
- os_atomic_store(&loader_log_lock, 0, release);
- }
- __builtin_arm_wsr64("DAIF", daif);
}
/* Oldest first: the head, a note about what was dropped, then the ring from its oldest character. */
diff --git a/xnu/files/osfmk/arm64/user_exception_trace.c b/xnu/files/osfmk/arm64/user_exception_trace.c
index 6989451..d97224c 100644
--- a/xnu/files/osfmk/arm64/user_exception_trace.c
+++ b/xnu/files/osfmk/arm64/user_exception_trace.c
@@ -166,14 +166,39 @@ extern lck_mtx_t tasks_threads_lock;
static char ustacks_name[32];
static uint32_t ustacks_every;
+static uint32_t ustacks_threads = USTACKS_MAX_THREADS; /* boot-arg ustacks_threads=N: only the first N (1: the main thread) */
+/*
+ * Boot-arg ustacks_tname=TEXT: only the threads whose name has TEXT in it (ustacks_tname=coreanimation:
+ * the window server's render-server and its other threads), each line with the thread's name and, in
+ * the first, the time in microseconds of mach_absolute_time (as the "tl:" lines of tools/latency.py);
+ * the lines are few enough then to go to the loader's log as well, where all of a long run is kept.
+ */
+static char ustacks_tname[32];
+static uint32_t ustacks_count; /* boot-arg ustacks_count=N: so many times, then no more (0: for ever) */
static thread_call_t ustacks_call;
+extern void bsd_getthreadname(void *uth, char *buffer);
+extern void loader_log_line(const char *line);
+
+static void
+ustacks_say(const char *line)
+{
+ printf("%s", line);
+ if (ustacks_tname[0] != 0) {
+ loader_log_line(line);
+ }
+}
+
static void
ustacks_task(task_t task, struct proc *proc)
{
static struct {
uint64_t tid, pc, lr, fp;
+ int state;
+ char name[64]; /* (bsd_getthreadname() copies MAXTHREADNAMESIZE, 64) */
} snap[USTACKS_MAX_THREADS];
+ char line[512];
+ int at;
vm_shared_region_t region;
vm_map_t map, old_map;
thread_t thread;
@@ -184,10 +209,19 @@ ustacks_task(task_t task, struct proc *proc)
queue_iterate(&task->threads, thread, thread_t, task_threads) {
const arm_saved_state_t *state = get_user_regs(thread);
- if (count == USTACKS_MAX_THREADS || state == NULL || !is_saved_state64(state)) {
+ if (count == USTACKS_MAX_THREADS || count >= ustacks_threads || state == NULL || !is_saved_state64(state)) {
+ continue;
+ }
+ snap[count].name[0] = 0;
+ if (get_bsdthread_info(thread) != NULL) {
+ bsd_getthreadname(get_bsdthread_info(thread), snap[count].name);
+ snap[count].name[63] = 0;
+ }
+ if (ustacks_tname[0] != 0 && strnstr(snap[count].name, ustacks_tname, sizeof(snap[count].name)) == NULL) {
continue;
}
snap[count].tid = thread_tid(thread);
+ snap[count].state = thread->state;
snap[count].pc = get_saved_state_pc(state);
snap[count].lr = get_saved_state_lr(state);
snap[count].fp = get_saved_state_fp(state);
@@ -209,27 +243,36 @@ ustacks_task(task_t task, struct proc *proc)
clock_sec_t secs;
clock_usec_t usecs;
+ uint64_t nanos;
+
clock_get_system_microtime(&secs, &usecs);
- printf("ustacks: %s[%d] %u threads, shared cache slide 0x%x, uptime %lu.%03u\n", proc_name_address(proc),
- proc_pid(proc), count, slide, (unsigned long)secs, (unsigned)usecs / 1000);
+ absolutetime_to_nanoseconds(mach_absolute_time(), &nanos);
+ snprintf(line, sizeof(line), "ustacks: %s[%d] %u threads, shared cache slide 0x%x, uptime %lu.%03u, at %llu\n",
+ proc_name_address(proc), proc_pid(proc), count, slide, (unsigned long)secs, (unsigned)usecs / 1000, nanos / 1000);
+ ustacks_say(line);
old_map = vm_map_switch(map);
for (unsigned i = 0; i < count; i++) {
uint64_t frame[2], fp = snap[i].fp;
- printf("ustacks: thread 0x%llx: 0x%llx 0x%llx", (unsigned long long)snap[i].tid,
- (unsigned long long)snap[i].pc, (unsigned long long)snap[i].lr);
+ /* (a thread that runs shows where it last came into the kernel, not where it is) */
+ at = snprintf(line, sizeof(line), "ustacks: thread 0x%llx%s%s%s%s: 0x%llx 0x%llx", (unsigned long long)snap[i].tid,
+ snap[i].name[0] ? " \"" : "", snap[i].name, snap[i].name[0] ? "\"" : "",
+ (snap[i].state & TH_RUN) ? " (running)" : "", (unsigned long long)snap[i].pc, (unsigned long long)snap[i].lr);
for (int depth = 0; depth < USTACKS_MAX_FRAMES && plausible_user_address(fp) && (fp & 7) == 0; depth++) {
if (copyin((user_addr_t)fp, frame, sizeof(frame)) != 0) {
break;
}
- printf(" 0x%llx", (unsigned long long)frame[1]);
+ if (at < (int)sizeof(line) - 24) {
+ at += snprintf(line + at, sizeof(line) - at, " 0x%llx", (unsigned long long)frame[1]);
+ }
if (frame[0] <= fp) {
break;
}
fp = frame[0];
}
- printf("\n");
+ snprintf(line + at, sizeof(line) - at, "\n");
+ ustacks_say(line);
}
vm_map_switch(old_map);
vm_map_deallocate(map);
@@ -350,6 +393,9 @@ ustacks_fire(__unused thread_call_param_t p0, __unused thread_call_param_t p1)
task_deallocate(found[i]);
}
again:
+ if (ustacks_count != 0 && --ustacks_count == 0) {
+ return;
+ }
if (ustacks_every != 0) {
uint64_t deadline;
@@ -382,6 +428,9 @@ ustacks_init(void)
return;
}
PE_parse_boot_argn("ustacks_ms", &ustacks_every, sizeof(ustacks_every));
+ PE_parse_boot_argn("ustacks_threads", &ustacks_threads, sizeof(ustacks_threads));
+ PE_parse_boot_argn("ustacks_tname", ustacks_tname, sizeof(ustacks_tname));
+ PE_parse_boot_argn("ustacks_count", &ustacks_count, sizeof(ustacks_count));
ustacks_call = thread_call_allocate(ustacks_fire, NULL);
clock_interval_to_deadline(at, NSEC_PER_SEC, &deadline);
thread_call_enter_delayed(ustacks_call, deadline);
diff --git a/xnu/redwood.patch b/xnu/redwood.patch
index c012456..b12ac65 100644
--- a/xnu/redwood.patch
+++ b/xnu/redwood.patch
@@ -1891,7 +1891,7 @@ index 94e91306b143..0ec1323086b7 100644
#endif
diff --git a/osfmk/arm64/machine_routines.c b/osfmk/arm64/machine_routines.c
-index e76e7e70ab9c..a1503e9d28ea 100644
+index e76e7e70ab9c..4f540f8caf43 100644
--- a/osfmk/arm64/machine_routines.c
+++ b/osfmk/arm64/machine_routines.c
@@ -734,6 +734,9 @@ ml_get_machine_mem(void)
@@ -1914,7 +1914,170 @@ index e76e7e70ab9c..a1503e9d28ea 100644
while (1) {
;
}
-@@ -2237,8 +2243,16 @@ _enable_virtual_timer(void)
+@@ -932,6 +938,99 @@ ml_read_chip_revision(unsigned int *rev __unused)
+ #endif
+ }
+
++/*
++ * The slower cores (an L2 access penalty, or the loader's "small-core"): each is made the SMT
++ * sibling ("secondary") of a faster core of its own, and the scheduler then treats it as XNU
++ * treats the second thread of a hyperthreaded core: a thread is put on it only when no faster
++ * core is idle or running something of lower priority; it looks for work only when none of
++ * them is idle; and what runs on it goes back to the run queue at every rescheduling, to be
++ * put on a faster core that has come free meanwhile. (XNU itself pairs such a core with the
++ * boot processor, which allows one of them; the phone has three: with cpus=8, cores 3, 2 and
++ * 1 go with 4, 5 and 6, so that 7, the boot core and the fastest, where real-time threads go
++ * first, stays alone: the scheduler idles a secondary while its primary runs a real-time
++ * thread.)
++ */
++static uint32_t small_cores_apart = 2; /* boot-arg small_cores, read in ml_parse_cpu_topology() (before tunables are) */
++static int ml_slow_core_partner[MAX_CPUS]; /* by cpu_id: the faster core it is paired with, -1 if none */
++
++static void
++ml_choose_slow_core_partners(void)
++{
++ bool taken[MAX_CPUS] = { false };
++
++ for (int i = 0; i < MAX_CPUS; i++) {
++ ml_slow_core_partner[i] = -1;
++ }
++ for (int i = 0; i < (int)topology_info.num_cpus; i++) {
++ int partner = -1;
++
++ if (topology_info.cpus[i].l2_access_penalty == 0) {
++ continue;
++ }
++ /* the last fast core not yet taken; the boot core only if there is no other */
++ for (int j = (int)topology_info.num_cpus - 1; j >= 0; j--) {
++ if (topology_info.cpus[j].l2_access_penalty != 0 || taken[j]) {
++ continue;
++ }
++ if (&topology_info.cpus[j] == topology_info.boot_cpu) {
++ if (partner < 0) {
++ partner = j;
++ }
++ continue;
++ }
++ partner = j;
++ break;
++ }
++ if (partner >= 0) {
++ taken[partner] = true;
++ ml_slow_core_partner[i] = partner;
++ }
++ }
++}
++
++extern void loader_log_line(const char *line);
++
++/* At the registration of each processor: pairs it with its partner, if that one is registered too. */
++static void
++ml_pair_slow_processors(int cpu_id)
++{
++ for (int i = 0; i < (int)topology_info.num_cpus; i++) {
++ int partner = ml_slow_core_partner[i];
++ processor_t slow, fast;
++ char line[128];
++
++ if (partner < 0 || (i != cpu_id && partner != cpu_id)) {
++ continue;
++ }
++ slow = processor_array[i];
++ fast = processor_array[partner];
++ if (slow == PROCESSOR_NULL || fast == PROCESSOR_NULL || slow->processor_primary == fast) {
++ continue;
++ }
++ sched_slow_secondaries = small_cores_apart >= 2;
++ processor_set_primary(slow, fast);
++ snprintf(line, sizeof(line), "cpu %d (phys id 0x%x) is a slower core: the scheduler uses it after cpu %d (phys id 0x%x)\n",
++ i, topology_info.cpus[i].phys_id, partner, topology_info.cpus[partner].phys_id);
++ printf("%s", line);
++ loader_log_line(line); /* (the kernel's own log of a run keeps only its end) */
++ }
++}
++
++/* How long processor cpu_id has been idle since it started, in mach_absolute_time() units (redwood_cpufreq.c's cpuload). */
++bool ml_cpu_idle_time(int cpu_id, uint64_t *idle);
++
++bool
++ml_cpu_idle_time(int cpu_id, uint64_t *idle)
++{
++ struct recount_usage usage = { 0 };
++
++ if (cpu_id < 0 || cpu_id >= MAX_SCHED_CPUS || processor_array[cpu_id] == PROCESSOR_NULL) {
++ return false;
++ }
++ recount_processor_usage(&processor_array[cpu_id]->pr_recount, &usage, idle);
++ return true;
++}
++
+ void
+ ml_parse_cpu_topology(void)
+ {
+@@ -945,6 +1044,7 @@ ml_parse_cpu_topology(void)
+ int64_t cluster_max_cpu_phys_id[MAX_CPU_CLUSTER_PHY_ID + 1];
+ const boolean_t cpus_boot_arg_present = PE_parse_boot_argn("cpus", &cpu_boot_arg, sizeof(cpu_boot_arg));
+ const boolean_t cpumask_boot_arg_present = PE_parse_boot_argn("cpumask", &cpumask_boot_arg, sizeof(cpumask_boot_arg));
++ PE_parse_boot_argn("small_cores", &small_cores_apart, sizeof(small_cores_apart));
+
+ // The cpus=N and cpumask=N boot args cannot be used simultaneously. Flag this
+ // so that we trigger a panic later in the boot process, once serial is enabled.
+@@ -1005,6 +1105,20 @@ ml_parse_cpu_topology(void)
+ cpu->phys_id = (uint32_t)ml_readprop(child, "reg", ML_READPROP_MANDATORY);
+
+ cpu->l2_access_penalty = (uint32_t)ml_readprop(child, "l2-access-penalty", 0);
++ /*
++ * A core the boot loader calls small (on the phone the Cortex-A55s; the Cortex-A78 the
++ * kernel boots on is about 2.5 times as fast) is to be used only when the faster ones are all
++ * busy: what XNU does with a core that has an L2 access penalty (ml_pair_slow_processors()).
++ * The loader gives it a name of its own because a kernel without that function would make
++ * every such core the sibling of the boot processor, and stop at the assertion that a
++ * processor has only one. Boot-arg small_cores=0: all cores alike, as before; 1: paired as
++ * XNU pairs the two threads of a hyperthreaded core (a secondary kept idle while its primary
++ * runs a real-time thread, and so on); 2 (the default): as cores of their own (see
++ * sched_slow_secondaries in osfmk/kern/sched.h).
++ */
++ if (cpu->l2_access_penalty == 0 && ml_readprop(child, "small-core", 0) != 0 && small_cores_apart) {
++ cpu->l2_access_penalty = 1;
++ }
+ cpu->l2_cache_size = (uint32_t)ml_readprop(child, "l2-cache-size", 0);
+ cpu->l2_cache_id = (uint32_t)ml_readprop(child, "l2-cache-id", 0);
+ cpu->l3_cache_size = (uint32_t)ml_readprop(child, "l3-cache-size", 0);
+@@ -1107,6 +1221,7 @@ ml_parse_cpu_topology(void)
+ cluster_offsets[0] = 0;
+ #endif
+ assert(topology_info.boot_cpu != NULL);
++ ml_choose_slow_core_partners();
+ ml_read_chip_revision(&topology_info.chip_revision);
+
+ /*
+@@ -1427,17 +1542,15 @@ ml_processor_register(ml_processor_info_t *in_processor_info,
+ processor_t processor = PERCPU_GET_RELATIVE(processor, cpu_data, this_cpu_datap);
+ if (!is_boot_cpu) {
+ processor_init(processor, this_cpu_datap->cpu_number, pset);
+-
+- if (this_cpu_datap->cpu_l2_access_penalty) {
+- /*
+- * Cores that have a non-zero L2 access penalty compared
+- * to the boot processor should be de-prioritized by the
+- * scheduler, so that threads use the cores with better L2
+- * preferentially.
+- */
+- processor_set_primary(processor, master_processor);
+- }
+ }
++ /*
++ * Cores that have a non-zero L2 access penalty compared
++ * to the boot processor should be de-prioritized by the
++ * scheduler, so that threads use the cores with better L2
++ * preferentially. (Each with a faster core of its own, not all with the boot
++ * processor: see ml_choose_slow_core_partners().)
++ */
++ ml_pair_slow_processors(this_cpu_datap->cpu_number);
+
+ *processor_out = processor;
+ *ipi_handler_out = cpu_signal_handler;
+@@ -2237,8 +2350,16 @@ _enable_virtual_timer(void)
uint64_t cntvctl = CNTV_CTL_EL0_ENABLE; /* One wants to use 32 bits, but "mrs" prefers it this way */
__builtin_arm_wsr64("CNTV_CTL_EL0", cntvctl);
@@ -2426,6 +2589,136 @@ index 4fb223ee9788..df563bc04910 100644
#pragma mark - implementation details
+diff --git a/osfmk/kern/sched.h b/osfmk/kern/sched.h
+index a5f68ade084b..9741eb1b3ecd 100644
+--- a/osfmk/kern/sched.h
++++ b/osfmk/kern/sched.h
+@@ -464,4 +464,13 @@ extern int sched_rt_n_backup_processors;
+
+ extern bool system_is_SMT;
+
++/*
++ * The "secondaries" are not the second threads of hyperthreaded cores but slower cores of their
++ * own, each paired with a faster one (ml_pair_slow_processors() in osfmk/arm64/machine_routines.c):
++ * the scheduler still prefers the primaries, but what runs on one core does not slow the other,
++ * so a secondary is not kept idle for its primary's sake, and when a primary goes idle a thread
++ * running on a secondary is moved to it.
++ */
++extern bool sched_slow_secondaries;
++
+ #endif /* _KERN_SCHED_H_ */
+diff --git a/osfmk/kern/sched_clutch.c b/osfmk/kern/sched_clutch.c
+index 3657d83c5b6f..ded2ff427d68 100644
+--- a/osfmk/kern/sched_clutch.c
++++ b/osfmk/kern/sched_clutch.c
+@@ -3204,7 +3204,7 @@ extern int sched_allow_rt_smt;
+ static bool
+ sched_clutch_thread_avoid_processor(processor_t processor, thread_t thread)
+ {
+- if (processor->processor_primary != processor) {
++ if (processor->processor_primary != processor && !sched_slow_secondaries) {
+ /*
+ * This is a secondary SMT processor. If the primary is running
+ * a realtime thread, only allow realtime threads on the secondary.
+diff --git a/osfmk/kern/sched_prim.c b/osfmk/kern/sched_prim.c
+index 8e29586464de..0a7de6fc4be7 100644
+--- a/osfmk/kern/sched_prim.c
++++ b/osfmk/kern/sched_prim.c
+@@ -2042,6 +2042,7 @@ sched_vm_group_maintenance(void)
+ #endif
+
+ int sched_allow_rt_smt = 1;
++bool sched_slow_secondaries = false;
+ int sched_avoid_cpu0 = SCHED_AVOID_CPU0;
+ int sched_allow_rt_steal = 1;
+ int sched_backup_cpu_timeout_count = 5; /* The maximum number of 10us delays to wait before using a backup cpu */
+@@ -2097,6 +2098,7 @@ void
+ sched_SMT_balance(processor_t cprocessor, processor_set_t cpset)
+ {
+ processor_t ast_processor = NULL;
++ sched_ipi_type_t ipi_type = SCHED_IPI_NONE;
+
+ #if (DEVELOPMENT || DEBUG)
+ if (__improbable(sched_smt_balance == 0)) {
+@@ -2105,7 +2107,39 @@ sched_SMT_balance(processor_t cprocessor, processor_set_t cpset)
+ #endif
+
+ assert(cprocessor == current_processor());
+- if (cprocessor->is_SMT == FALSE) {
++ if (cprocessor->is_SMT == FALSE && !sched_slow_secondaries) {
++ goto smt_balance_exit;
++ }
++
++ if (sched_slow_secondaries) {
++ /*
++ * A faster core is going idle: the thread of highest priority that runs on a slower one
++ * (not a real-time one: those stay where they are) is sent here. Its core is made to
++ * reschedule; a thread on a secondary goes back to the run queue then, and an idle
++ * primary is where it is put.
++ */
++ integer_t highest = -1;
++
++ if (cprocessor->processor_primary != cprocessor) {
++ goto smt_balance_exit;
++ }
++ uint64_t running_secondaries = (cpset->cpu_state_map[PROCESSOR_RUNNING] & ~cpset->primary_map &
++ ~cpset->pending_AST_URGENT_cpu_mask);
++ for (int cpuid = lsb_first(running_secondaries); cpuid >= 0; cpuid = lsb_next(running_secondaries, cpuid)) {
++ processor_t sprocessor = processor_array[cpuid];
++
++ if (sprocessor->current_pri < BASEPRI_RTQUEUES && sprocessor->current_pri > highest &&
++ sprocessor->current_pri > MINPRI) {
++ highest = sprocessor->current_pri;
++ ast_processor = sprocessor;
++ }
++ }
++ if (ast_processor != PROCESSOR_NULL) {
++ ipi_type = sched_ipi_action(ast_processor, NULL, SCHED_IPI_EVENT_SMT_REBAL);
++ if (ipi_type == SCHED_IPI_NONE) {
++ ast_processor = PROCESSOR_NULL;
++ }
++ }
+ goto smt_balance_exit;
+ }
+
+@@ -2120,7 +2154,6 @@ sched_SMT_balance(processor_t cprocessor, processor_set_t cpset)
+
+ processor_t sprocessor;
+
+- sched_ipi_type_t ipi_type = SCHED_IPI_NONE;
+ uint64_t running_secondary_map = (cpset->cpu_state_map[PROCESSOR_RUNNING] &
+ ~cpset->primary_map);
+ for (int cpuid = lsb_first(running_secondary_map); cpuid >= 0; cpuid = lsb_next(running_secondary_map, cpuid)) {
+@@ -2581,6 +2614,10 @@ restart:
+ bool is_yielding = (*reason & AST_YIELD) == AST_YIELD;
+
+ bool needs_smt_rebalance = !is_yielding && thread->sched_pri < BASEPRI_RTQUEUES && processor->processor_primary != processor;
++ if (needs_smt_rebalance && sched_slow_secondaries) {
++ /* (a slower core of its own: worth leaving only for a faster one that is idle) */
++ needs_smt_rebalance = (pset->recommended_bitmask & pset->primary_map & pset->cpu_state_map[PROCESSOR_IDLE]) != 0;
++ }
+
+ bool affinity_mismatch = thread->affinity_set != AFFINITY_SET_NULL && thread->affinity_set->aset_pset != pset;
+
+@@ -2705,7 +2742,7 @@ pick_new_rt_thread:
+
+ clear_pending_AST_bits(pset, processor, 3);
+
+- if (processor->processor_secondary != NULL) {
++ if (processor->processor_secondary != NULL && !sched_slow_secondaries) {
+ processor_t sprocessor = processor->processor_secondary;
+ if ((sprocessor->state == PROCESSOR_RUNNING) || (sprocessor->state == PROCESSOR_DISPATCHING)) {
+ ipi_type = sched_ipi_action(sprocessor, NULL, SCHED_IPI_EVENT_SMT_REBAL);
+@@ -2774,7 +2811,8 @@ send_followup_ipi_before_idle:
+ goto restart;
+ }
+
+- if ((processor->processor_primary != processor) && (processor->processor_primary->current_pri >= BASEPRI_RTQUEUES)) {
++ if ((processor->processor_primary != processor) && (processor->processor_primary->current_pri >= BASEPRI_RTQUEUES) &&
++ !sched_slow_secondaries) {
+ /* secondary can only run realtime thread */
+ if (idle_reason == 0) {
+ idle_reason = 4;
diff --git a/osfmk/kern/startup.c b/osfmk/kern/startup.c
index bec97fbf7243..203e1f48783f 100644
--- a/osfmk/kern/startup.c
diff --git a/xnuloader/loader.c b/xnuloader/loader.c
index 8c552c2..67e6a22 100644
--- a/xnuloader/loader.c
+++ b/xnuloader/loader.c
@@ -452,6 +452,7 @@ struct platform {
int cores; /* at most this many processor cores, numbered from 0 ... */
int core_shift; /* ... in this bit of MPIDR: the phone numbers them in the second affinity field */
uint32_t timeout_scale; /* a kernel on several cores gets this much longer to wait for a lock, 0: as it is */
+ uint32_t small_cores; /* a bit for each of the slower cores, by number: "small-core" in the device tree */
};
static const struct platform platform_qemu_virt = {
@@ -471,6 +472,12 @@ static const struct platform platform_redwood = {
.name = "redwood", .io_base = 0x00400000, .io_size = 0x3FC00000,
.gic_dist = 0x17A00000, .gic_redist = 0x17A60000, .uart = 0, .log_other_cpu = 1,
.cores = 8, .core_shift = 8,
+ /*
+ * Cores 0-3 are Cortex-A55s (1.8 GHz at most), 4-7 Cortex-A78s (2.4 GHz): a big one is about
+ * 2.5 times as fast. The kernel uses the small ones only when the big ones are all busy
+ * (XNU's machine_routines.c, ml_choose_slow_core_partners()).
+ */
+ .small_cores = 0x0f,
};
/* ------------------------------------------------------------------------ */
@@ -2011,6 +2018,9 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)
dt_prop_u64(&w, "bus-frequency", 100000000ULL);
dt_prop_u64(&w, "memory-frequency", 100000000ULL);
dt_prop_u64(&w, "peripheral-frequency", 24000000ULL);
+ if (plat->small_cores & (1u << ((cpu_mpidr[i] >> plat->core_shift) & 31))) {
+ dt_prop_u32(&w, "small-core", 1);
+ }
dt_end(&w);
}
dt_end(&w);