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
Speakers: a guard in place of the DSP's protection, 12 dB of gain, and 20 dB under Android by default
vcvkk315e973099d1
diff --git a/README.md b/README.mdindex c544e26..7885361 100644--- a/README.md+++ b/README.md@@ -105,7 +105,20 @@ AUDIO=pipewire qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # или AUD`RC_JOBS=rc.jobs.speakers` проигрывает тон, звук блокировки, щелчки клавиатуры и фанфары). То, что iOS играет,можно и забрать: параметр ядра `rec_sound=N` сохраняет первые N секунд звука в памяти, послесеанса `./xl sound out.wav` достаёт их (в QEMU — `pmemsave` по адресу из строки `redwood-audio: recording … at 0x…`,-затем `tools/sound.py`). В QEMU запись проверена; на самом телефоне звук ещё не проверялся вовсе.+затем `tools/sound.py`); с `rec_sound_fed=1` — то, что ушло к усилителям. На телефоне звук проверен на слух.+Защиты динамиков, которая у Android работает в звуковом процессоре (алгоритм Awinic с калибровкой), здесь нет;+вместо неё отсчёты по пути к усилителям проходят «сторож» ядра (`bsd/dev/redwood_guard.c`): сначала усиление+`sound_gain` (по умолчанию и самое большее 12 дБ: обработка самой iOS для динамика iPhone X держит даже полный тон+на максимуме громкости на 12,6–14,3 дБ ниже полной шкалы), затем фильтр верхних частот 200 Гц, три средних мощности+на динамике — за 0,2, 3 и 60 с, пределы на 3, 6 и 9 дБ ниже мощности синуса полной шкалы на уровне Android (громкость+опускается так, чтобы ни одно не вышло за свой; средние падают и при выключенных усилителях, как динамик остывает) — и+ограничитель пиков на 3 дБ ниже полной шкалы на уровне Android. Раз в секунду читаются температура усилителей и+напряжение батареи, как их видят сами усилители, и по таблице «монитора» драйвера Android из той же конфигурации+громкость снижается на холоде и при разряженной батарее. Проверка на телефоне: `sound_below=160` (−20 дБ, теперь по+умолчанию) — сторож работает, у усилителей ни одной ошибки; −10 дБ и уровень Android — ещё впереди.+`RC_JOBS=rc.jobs.loud` — самое тяжёлое: тон полной шкалы 60 с прямо в `/dev/redwood-audio` мимо обработки iOS, потом+тон через iOS на максимуме громкости; `sound_guard_as=0` вместе с `sound_below=720` показывает в журнале и записи,+что сторож делает на уровне Android, без единого звука. `tools/guard_test.c` — сторож на этой машине.Замечания:@@ -217,7 +230,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #| `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` |+| `rec_sound=N` | сохранить первые N секунд звука, который играет iOS (тишина между звуками места не занимает); потом `./xl sound out.wav`. С `rec_sound_fed=1` — то, что пропустил к усилителям сторож динамиков || `speaker_probe=N` | только телефон, **ещё ни разу не запускалось**: посмотреть на звуковое железо, ничего не включая. `1` — только чтение (состояние выводов, имена питаний у RPMh, один регистр тактового генератора); `2` — ещё и спросить у усилителей динамиков, кто они, по I2C, для чего на время перенастраиваются два вывода (GPIO 12 и 13). Ответы — строки `speaker:` в журнале || `-v` | текст загрузки на экране (по умолчанию у `xl run`, если `XL_CMDLINE` не задана) || `applog=1` / `applog=2` | stderr приложений в журнал / плюс os_log всех процессов |@@ -245,7 +258,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #| `wifi_irq=0`, `wifi_ba=0`, `wifi_wide=0` | с `wifi=1`: без прерываний радио (его кольца опрашиваются раз в миллисекунду, как раньше), без блочных подтверждений (точка доступа шлёт кадры по одному — скорость впятеро ниже), без широкого канала (только 20 МГц) || `wifi_step=N` | то же по шагам, как это выяснялось: первые N шагов, и ядро ждёт, пока они пройдут. 1–5 только читают (общая память процессоров, почтовый ящик процессора питания, RPMh, шины питания, выводы), 6–11 кладут прошивку процессора Wi-Fi в его память, заводят в общей памяти нашу половину его сигнальных битов (SMP2P) и запускают его через TrustZone, 12–14 поднимают связь с ним (GLINK, канал IPCRTR) и QRTR поверх неё: процессор Wi-Fi объявляет свои службы, среди них службу прошивки Wi-Fi; 15 — разговор с этой службой, какой драйвер ведёт до того, как тронет радио (нужны описания сообщений из ath11k: `tools/mk-wlfw.sh`, затем пересобрать ядро): прошивка принимает сообщения ath11k, файл платы и базу регионов телефона, с `wifi_cal=1` калибруется и через 7 секунд говорит «готова»; с `wifi_mission=1` прошивка получает настройку и переходит в рабочий режим; 16 — чтение нескольких регистров радио (`wifi_radio_read=1`): в рабочем режиме они отвечают, вне его чтение кончается ошибкой шины, и шаг его не делает (`adb pull` файлов `wpss.mdt`, `wpss.b02`…`wpss.b07` из `/vendor/firmware_mnt/image` в каталог `fw-wifi/`; в git они не попадают, `userland/build.sh` кладёт их в малый образ). Каждый шаг пишет в журнал, что собирается тронуть и что прочёл. `wifi_keep=1` оставляет процессор Wi-Fi и связь с ним работать, пока идёт сеанс. С `wifi_lx=1` шаг 15 ведёт сам драйвер ath11k из Linux (см. «Драйвер Wi-Fi» ниже; ядро собирается после `tools/mk-ath11k.sh`): его `qmi.c` проходит весь разговор с прошивкой до рабочего режима, со своей настройкой и списком теневых регистров, а регистры радио не трогает. С `wifi_lx=2 wifi_smmu=2` потоку радио в SMMU даётся контекст с нашими таблицами страниц (`wifi_smmu=2` в одиночку — только это, с возвратом как было), `ce.c` и `hal.c` драйвера заводят в регистрах радио кольца его «копировальных машин», `htc.c` подключает по ним службу WMI, и прошивка по WMI рассказывает о радио (одно, две антенные цепи, 2,4 и 5 ГГц) и через четверть секунды после запуска шины сообщает, что готова к командам («unified ready»); собственного адреса у прошивки нет (нули). Прерываний при этом нет: кольца опрашиваются раз в миллисекунду. С `wifi_scan=1` драйвер после этого регистрирует радио, заводит интерфейс в режиме станции и просит прошивку просканировать эфир — только слушая, в эфир ничего не уходит: 26 каналов 2,4 и 5 ГГц за четыре секунды, и в журнале появляются точки доступа вокруг с каналами и уровнем сигнала (имена и адреса чужих сетей — только в журнале запуска на вашей машине). Адрес радио у прошивки свой не записан: он лежит одной строкой в `fw-wifi/mac` (в git не попадает), и `xl run` передаёт его ядру параметром `wifi_mac`. С `wifi_join=1` драйвер подключается к сети из `fw-wifi/network` (WPA2 с паролем): находит её точку доступа, проходит аутентификацию, ассоциацию и четырёхстороннее рукопожатие, отдаёт ключи прошивке и становится тем, что стоит за `en0`; с `wifi_keep=1` он остаётся работать, пока идёт сеанс, без него — сворачивается, когда шаги кончились (`wifi_hold=S` — на S секунд позже). Остановленный без спроса (ядро, которое до этого не дошло) второй раз без перезагрузки телефона не запускается — такой запуск сбрасывал телефон, и драйвер от него сам отказывается; шаги и остальные параметры описаны в начале `bsd/dev/redwood_wifi.c` || `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` |+| `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 (по умолчанию 160, то есть на 20 дБ тише; выше уровня Android — никогда), тон звучит 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_gain=N` (восьмые доли дБ, 0–96), `sound_guard_as=N` (для проверки: сторож считает усилители на N ниже уровня Android и сдерживает, как сдерживал бы там). `sound_secs=S` (не больше 3 с тоном), `sound_pause=MS`. Подробности в начале `bsd/dev/redwood_sound.c` и `bsd/dev/redwood_speaker.c` || `battmgr=0` | с `adsp=1` батарея не спрашивается. Без него (по умолчанию) ядро раз в 10 с спрашивает у звукового процессора, который у этого телефона и ведёт батарею с зарядкой (как Android — `qti_battery_charger`, Linux — `qcom_battmgr` поверх `pmic_glink`), по каналу `PMIC_RTR_ADSP_APPS` процент заряда, зарядку, напряжение, ток, температуру, заряд в мА·ч, ёмкость, циклы и что даёт порт USB — только читает, ни пределов, ни токов не задаёт — и показывает это iOS так же, как батарея iPhone: службой `RedwoodBattery` класса `IOPMPowerSource` (`iokit/Kernel/RedwoodBattery.cpp`). Её читает powerd, и дальше всё делает сама iOS: батарея с процентом и молнией в строке состояния, «58% Charged» на экране блокировки, виджет «Батареи», Настройки → Аккумулятор (переключатель «Заряд в процентах» работает; в образе он включён); перехваты батареи в SpringBoard при этой службе уступают iOS. Сверено с Android (`dumpsys battery` и `/sys/class/power_supply/battery` сразу после): 56 % и 58 %, «заряжается», напряжение, температура, заряд, ёмкость 3677 из 5000 мА·ч, 890 циклов совпадают. Номера свойств — этой прошивки: до 9-го как у Linux, дальше на один больше; `battmgr=2` пишет в журнал все. Те же числа — в `kern.redwood.battery_*`. С `battery=1` (путь загрузчика через UEFI) не включается. Не показываются история заряда (нужен powerlogd) и износ в «Состоянии аккумулятора» (powerd ждёт серийный номер батареи, а его прошивка не даёт). Проверка — `RC_JOBS=rc.jobs.battery` (`battery_test`) |Несколько ядер на телефоне проверены (2, 4 и 7 ядер запускаются и чисто возвращаются в загрузчик). На одном иdiff --git a/tools/guard-test.sh b/tools/guard-test.shnew file mode 100755index 0000000..c6653a0--- /dev/null+++ b/tools/guard-test.sh@@ -0,0 +1,13 @@+#!/bin/sh+# The speakers' guard (bsd/dev/redwood_guard.c) on this machine: tools/guard_test.c built against it and run.+# The kernel's header is all it needs, and an empty sys/ioccom.h beside it (the ioctl numbers are not used).+set -e+cd "$(dirname "$0")/.."+SRC=xnu-src/xnu-8796.121.2/bsd+tmp=$(mktemp -d)+trap 'rm -rf "$tmp"' EXIT+mkdir -p "$tmp/sys"+cp $SRC/sys/redwood_audio.h "$tmp/sys/"+printf '#define _IOW(g, n, t) 0\n' > "$tmp/sys/ioccom.h"+cc -O2 -Wall -DKERNEL -I"$tmp" tools/guard_test.c $SRC/dev/redwood_guard.c -lm -o "$tmp/guard_test"+"$tmp/guard_test"diff --git a/tools/guard_test.c b/tools/guard_test.cnew file mode 100644index 0000000..eaccc05--- /dev/null+++ b/tools/guard_test.c@@ -0,0 +1,148 @@+/*+ * The speakers' guard (bsd/dev/redwood_guard.c) on this machine, with signals made up for it:+ * what comes out, second by second, for a sustained full-scale tone at the amplifiers' levels that+ * are tried on the phone, for music-like noise, and for the tone once it stops (the cooling).+ *+ * cc -O2 -DKERNEL -I<a directory with sys/redwood_audio.h and a sys/ioccom.h> tools/guard_test.c \+ * xnu-src/xnu-8796.121.2/bsd/dev/redwood_guard.c -lm -o guard_test && ./guard_test+ * (tools/guard-test.sh does that.)+ */+#include <math.h>+#include <stdbool.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <sys/redwood_audio.h>++#define RATE 48000+#define BLOCK 960++static double phase, pink_scale = 1;+static uint64_t noise = 88172645463325252ull;++static double+random_uniform(void)+{+ noise ^= noise << 13;+ noise ^= noise >> 7;+ noise ^= noise << 17;+ return (double)(noise >> 11) / (double)(1ull << 53) * 2 - 1;+}++/* one block: kind 0 silence, 1 a sine at `level' (of full scale, peak), 2 noise filtered to fall 3 dB an octave, at RMS `level' */+static void+make(int16_t *frames, int kind, double level, double hz)+{+ static double b[7];++ for (int f = 0; f < BLOCK; f++) {+ double v = 0;++ if (kind == 1) {+ v = level * sin(phase);+ phase += 2 * M_PI * hz / RATE;+ } else if (kind == 2) {+ /* Paul Kellet's pink noise, scaled to about the RMS asked for */+ double w = random_uniform();++ b[0] = 0.99886 * b[0] + w * 0.0555179;+ b[1] = 0.99332 * b[1] + w * 0.0750759;+ b[2] = 0.96900 * b[2] + w * 0.1538520;+ b[3] = 0.86650 * b[3] + w * 0.3104856;+ b[4] = 0.55000 * b[4] + w * 0.5329522;+ b[5] = -0.7616 * b[5] - w * 0.0168980;+ v = (b[0] + b[1] + b[2] + b[3] + b[4] + b[5] + b[6] + w * 0.5362) * pink_scale * level;+ b[6] = w * 0.115926;+ }+ v *= 32767;+ v = v > 32767 ? 32767 : v < -32768 ? -32768 : v;+ frames[2 * f] = frames[2 * f + 1] = (int16_t)lrint(v);+ }+}++static double+decibels(double ratio)+{+ return ratio > 0 ? 10 * log10(ratio) : -99;+}++/* `seconds' of one kind of signal; a line every `every' seconds: the output's RMS and peak at the speaker, and the guard */+static void+run(const char *what, uint32_t attenuation, int kind, double level, double hz, int seconds, int every)+{+ int16_t frames[2 * BLOCK];+ bool silent = attenuation == REDWOOD_GUARD_SILENT;+ double at_speaker = silent ? 0 : pow(10, -(double)attenuation / 80.0); /* power */++ if (silent) {+ printf("-- %s, the amplifiers off\n", what);+ } else {+ printf("-- %s, the amplifiers %.1f dB under Android's level\n", what, attenuation / 8.0);+ }+ redwood_guard_attenuation(attenuation);+ for (int s = 0; s < seconds; s++) {+ double sum = 0, peak = 0, in_sum = 0;+ struct redwood_guard_report r;++ for (int b = 0; b < RATE / BLOCK; b++) {+ make(frames, kind, level, hz);+ for (int i = 0; i < 2 * BLOCK; i++) {+ in_sum += (double)frames[i] * frames[i];+ }+ redwood_guard_process(frames, BLOCK);+ for (int i = 0; i < 2 * BLOCK; i++) {+ double v = frames[i] / 32768.0;++ sum += v * v;+ peak = fabs(v) > peak ? fabs(v) : peak;+ }+ }+ redwood_guard_take_report(&r);+ if ((s + 1) % every == 0 || s == 0) {+ /* at the speaker: relative to a full-scale square wave at Android's level */+ printf("%4d s: in %6.1f dB, out %6.1f dB (peak %6.1f dB) at the speaker; guard %5.1f dB (%u rms, %u fast, %u slow "+ "blocks), peaks limited in %u frames; averages %.1f %.1f %.1f dB\n", s + 1,+ decibels(in_sum / (2.0 * RATE) / (32768.0 * 32768.0) * at_speaker), decibels(sum / (2.0 * RATE) * at_speaker),+ silent ? -99 : 20 * log10(peak > 0 ? peak : 1e-9) - attenuation / 8.0, redwood_guard_decibels(r.gain * r.gain >> 30) / 10.0,+ r.rms_blocks, r.fast_blocks, r.slow_blocks, r.limited_frames, redwood_guard_decibels(r.rms) / 10.0,+ redwood_guard_decibels(r.fast) / 10.0, redwood_guard_decibels(r.slow) / 10.0);+ }+ }+}++int+main(void)+{+ int16_t frames[2 * BLOCK];+ double sum = 0;++ /* the noise's own RMS, so that it can be made as loud as asked (at full scale, then scaled down in make()) */+ pink_scale = 1.0 / 32767;+ for (int b = 0; b < 500; b++) {+ make(frames, 2, 1.0, 0);+ for (int i = 0; i < 2 * BLOCK; i += 2) {+ sum += (double)frames[i] * frames[i];+ }+ }+ pink_scale = 1.0 / sqrt(sum / (500.0 * BLOCK));+ redwood_guard_configure(true, 0);+ run("a full-scale 1 kHz sine", 160, 1, 1.0, 1000, 10, 5);+ run("a full-scale 1 kHz sine", 80, 1, 1.0, 1000, 10, 5);+ run("a full-scale 1 kHz sine", 0, 1, 1.0, 1000, 120, 10);+ run("silence, the speakers cooling", REDWOOD_GUARD_SILENT, 0, 0, 0, 120, 20);+ run("the same sine again", 0, 1, 1.0, 1000, 5, 1);+ run("silence", REDWOOD_GUARD_SILENT, 0, 0, 0, 300, 300);+ run("a 100 Hz sine at full scale (the high-pass filter)", 0, 1, 1.0, 100, 4, 2);+ run("silence", REDWOOD_GUARD_SILENT, 0, 0, 0, 300, 300);+ run("pink noise at -15 dB RMS (loud music)", 0, 2, pow(10, -15 / 20.0), 0, 60, 10);+ run("pink noise at -9 dB RMS (music mastered as loud as it goes)", 0, 2, pow(10, -9 / 20.0), 0, 120, 20);+ run("silence", REDWOOD_GUARD_SILENT, 0, 0, 0, 300, 300);+ /* iOS at its top: a tone 12.6 dB under full scale, then 12 dB of gain before the guard */+ redwood_guard_configure(true, 96);+ run("iOS's top (a 440 Hz sine at -12.6 dB) with 12 dB of gain", 0, 1, pow(10, -12.6 / 20), 440, 90, 10);+ run("silence", REDWOOD_GUARD_SILENT, 0, 0, 0, 600, 600);+ run("pink noise at -24 dB RMS (loud music as iOS leaves it) with 12 dB of gain", 0, 2, pow(10, -24 / 20.0), 0, 60, 20);+ run("silence", REDWOOD_GUARD_SILENT, 0, 0, 0, 600, 600);+ run("the same with the amplifiers 90 dB under (as tonight)", 720, 2, pow(10, -24 / 20.0), 0, 10, 5);+ return 0;+}diff --git a/userland/rc.jobs.loud b/userland/rc.jobs.loudnew file mode 100644index 0000000..277711f--- /dev/null+++ b/userland/rc.jobs.loud@@ -0,0 +1,12 @@+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).+# The speakers at their loudest (RC_JOBS=rc.jobs.loud, with adsp=1 sound=4 and the sound_below being tried). First a+# tone at full scale (1 kHz left, 440 Hz right) for 60 seconds written straight to /dev/redwood-audio, past iOS's+# own processing, which never lets a tone come near full scale: the hardest thing the speakers can be given, for+# the guard to hold back (the kernel's "sound: the guard" lines; its "speaker:" lines are the amplifiers' status,+# temperature and battery voltage). Then the same tone through iOS for 30 seconds, with its volume pressed up to the+# top, the lock sound and a fanfare.+/redwood/bin/sound_test springboard route+/redwood/bin/sound_test level 1 raw 60 wait 6+/redwood/bin/sound_test level 1 tone 30 &+/redwood/bin/rwtouch wait 2 button volup wait 0.5 button volup wait 0.5 button volup wait 0.5 button volup wait 0.5 button volup wait 0.5 button volup wait 0.5 button volup wait 0.5 button volup wait 0.5 button volup+/redwood/bin/sound_test route wait 32 system 1100 wait 3 file /System/Library/Audio/UISounds/New/Fanfare.caf wait 5diff --git a/userland/src/sound_test.c b/userland/src/sound_test.cindex fc4a77d..ca46e7e 100644--- a/userland/src/sound_test.c+++ b/userland/src/sound_test.c@@ -8,6 +8,11 @@* as on an iPhone with its switch on silent* tone SECONDS [LEFT_HZ RIGHT_HZ] a sine wave in each channel (default 1000 and 440 Hz) at half of* full scale, through an audio queue: what a music player does+ * level PEAK the tones after this one at PEAK of full scale (0 to 1) instead+ * (before iOS's volume, which scales the samples itself)+ * raw SECONDS the same tone written straight to /dev/redwood-audio, past iOS's own+ * processing and volume (which keep a tone more than 12 dB under full+ * scale even at the top): to try what the kernel does with full scale* system ID a system sound by its number (1100 is the lock sound,* 1104 a keyboard click), as SpringBoard plays them* file PATH a sound file, played as a system sound@@ -22,6 +27,8 @@#include <AudioToolbox/AudioToolbox.h>#include <CoreFoundation/CoreFoundation.h>#include <errno.h>+#include <fcntl.h>+#include <mach/mach_time.h>#include <math.h>#include <notify.h>#include <objc/message.h>@@ -35,7 +42,7 @@#define RATE 48000#define BUFFER_FRAMES 4096-static double frequency[2] = { 1000, 440 };+static double frequency[2] = { 1000, 440 }, peak = 0.5;static uint64_t frame, frames_wanted;static void@@ -50,7 +57,7 @@ fill(__unused void *context, AudioQueueRef queue, AudioQueueBufferRef buffer)frames_wanted - frame < RATE / 100 ? (frames_wanted - frame) / (RATE / 100.0) : 1;for (int channel = 0; channel < 2; channel++) {- samples[2 * count + channel] = (int16_t)(16384 * edge * sin(2 * M_PI * frequency[channel] * frame / RATE));+ samples[2 * count + channel] = (int16_t)(32767 * peak * edge * sin(2 * M_PI * frequency[channel] * frame / RATE));}}if (count == 0) {@@ -61,6 +68,52 @@ fill(__unused void *context, AudioQueueRef queue, AudioQueueBufferRef buffer)AudioQueueEnqueueBuffer(queue, buffer, 0, NULL);}+/* The tone to the kernel's device itself, 10 ms at a time and as fast as it plays (48000 frames a second). */+static int+raw(double seconds)+{+ int device = open("/dev/redwood-audio", O_WRONLY);+ int16_t block[2 * 480];+ uint64_t total = (uint64_t)(seconds * RATE), written = 0, start;+ mach_timebase_info_data_t timebase;++ if (device < 0) {+ printf("sound_test: /dev/redwood-audio: %s\n", strerror(errno));+ return 1;+ }+ mach_timebase_info(&timebase);+ printf("sound_test: a tone of %.0f and %.0f Hz at %.2f of full scale for %.1f s, straight to /dev/redwood-audio\n",+ frequency[0], frequency[1], peak, seconds);+ fflush(stdout);+ start = mach_absolute_time();+ while (written < total) {+ uint64_t due;+ uint32_t count = total - written < 480 ? (uint32_t)(total - written) : 480;++ for (uint32_t f = 0; f < count; f++) {+ uint64_t n = written + f;+ double edge = n < RATE / 100 ? n / (RATE / 100.0) : total - n < RATE / 100 ? (total - n) / (RATE / 100.0) : 1;++ for (int channel = 0; channel < 2; channel++) {+ block[2 * f + channel] = (int16_t)(32767 * peak * edge * sin(2 * M_PI * frequency[channel] * n / RATE));+ }+ }+ if (write(device, block, count * 4) != (ssize_t)(count * 4)) {+ printf("sound_test: /dev/redwood-audio: a write failed: %s\n", strerror(errno));+ break;+ }+ written += count;+ /* stay 100 ms ahead of the clock, not more: the kernel's ring holds 0.68 s */+ due = start + (written > RATE / 10 ? written - RATE / 10 : 0) * 1000000000ull / RATE * timebase.denom / timebase.numer;+ if (mach_absolute_time() < due) {+ mach_wait_until(due);+ }+ }+ close(device);+ printf("sound_test: %llu frames written straight to the device\n", written);+ return written < total;+}+static inttone(double seconds){@@ -91,7 +144,8 @@ tone(double seconds)fill(NULL, queue, buffer);}status = AudioQueueStart(queue, NULL);- printf("sound_test: a tone of %.0f and %.0f Hz for %.1f s: AudioQueueStart: %d\n", frequency[0], frequency[1], seconds,+ printf("sound_test: a tone of %.0f and %.0f Hz at %.2f of full scale for %.1f s: AudioQueueStart: %d\n", frequency[0],+ frequency[1], peak, seconds,(int)status);if (status == 0) {/* a slow machine may take its time: wait for the end, three times as long as it should take at most */@@ -231,6 +285,12 @@ main(int argc, char **argv)frequency[1] = atof(argv[++i]);}failed |= tone(seconds);+ } else if (strcmp(argv[i], "raw") == 0 && i + 1 < argc) {+ failed |= raw(atof(argv[++i]));+ } else if (strcmp(argv[i], "level") == 0 && i + 1 < argc) {+ peak = atof(argv[++i]);+ peak = peak < 0 ? 0 : peak > 1 ? 1 : peak;+ printf("sound_test: the tones from now on at %.2f of full scale\n", peak);} else if (strcmp(argv[i], "system") == 0 && i + 1 < argc) {failed |= system_sound((SystemSoundID)atoi(argv[++i]));} else if (strcmp(argv[i], "file") == 0 && i + 1 < argc) {diff --git a/xnu/files/bsd/dev/redwood_audio.c b/xnu/files/bsd/dev/redwood_audio.cindex 6fe8467..7f14bb9 100644--- a/xnu/files/bsd/dev/redwood_audio.c+++ b/xnu/files/bsd/dev/redwood_audio.c@@ -16,6 +16,9 @@** struct rec_header, then per write: struct rec_block, frames * 4 bytes*+ * With rec_sound_fed=1 as well, the recording has instead what the speakers' guard+ * let through (redwood_guard.c, on the phone): what reaches the amplifiers.+ ** When the writer has stopped, a line in the log says how long it wrote, at what rate, how much* of it was not silence and how loud: the only way to "hear" a machine one cannot listen to.* (The audio server writes for as long as its device runs, a second or two beyond the sound.)@@ -64,6 +67,7 @@ static LCK_MTX_DECLARE(audio_lock, &audio_lck_grp);static redwood_audio_sink_t audio_sink;static uint8_t *rec_base;+static bool rec_fed; /* boot-arg rec_sound_fed=1: what the guard let through is recorded, not what was written */static uint64_t rec_size, rec_used;static uint64_t rec_frames, rec_frames_max;@@ -140,6 +144,21 @@ audio_record(const int16_t *frames, uint32_t count)}}+bool+redwood_audio_recording_fed(void)+{+ return rec_fed && rec_base != NULL && rec_frames < rec_frames_max;+}++/* From the speakers' feeder: what the guard let through, into the recording (rec_sound_fed=1). */+void+redwood_audio_record_fed(const int16_t *frames, uint32_t count)+{+ lck_mtx_lock(&audio_lock);+ audio_record(frames, count);+ lck_mtx_unlock(&audio_lock);+}+static voidaudio_play(const int16_t *frames, uint32_t count){@@ -154,7 +173,9 @@ audio_play(const int16_t *frames, uint32_t count)}}lck_mtx_lock(&audio_lock);- audio_record(frames, count);+ if (!rec_fed) {+ audio_record(frames, count);+ }if (audio_sink != NULL) {taken = audio_sink(frames, count);stretch_lost += count - taken;@@ -265,7 +286,7 @@ static voidaudio_recording_init(void){struct rec_header *header;- uint32_t seconds = 0;+ uint32_t seconds = 0, fed = 0;vm_offset_t memory = 0;uint64_t size;@@ -295,7 +316,10 @@ audio_recording_init(void)loader_sound[0] = kvtophys(memory);loader_sound[1] = rec_used;loader_sound[2] = (uint64_t)memory;- printf("redwood-audio: recording the first %u s of sound, into %llu MB at %#llx\n", seconds, size >> 20, loader_sound[0]);+ PE_parse_boot_argn("rec_sound_fed", &fed, sizeof(fed));+ rec_fed = fed != 0;+ printf("redwood-audio: recording the first %u s of sound%s, into %llu MB at %#llx\n", seconds,+ rec_fed ? " as the speakers' guard lets it through" : "", size >> 20, loader_sound[0]);}voiddiff --git a/xnu/files/bsd/dev/redwood_guard.c b/xnu/files/bsd/dev/redwood_guard.cnew file mode 100644index 0000000..ebcb79d--- /dev/null+++ b/xnu/files/bsd/dev/redwood_guard.c@@ -0,0 +1,315 @@+/*+ * The speakers' guard: what the samples go through on their way to the phone's two amplifiers+ * (bsd/dev/redwood_sound.c's feeder), in place of the protection Android has in the audio DSP.+ *+ * Under Android the DSP runs Awinic's algorithm (SKTune, "aw882xx_rx_switch") with each+ * speaker's calibration: it keeps the cone's excursion and the voice coil's temperature in+ * bounds, measuring both through the amplifiers' current and voltage feedback. None of that runs+ * here, and nothing here knows the speakers' parameters (Android's files that can be read have+ * none: the amplifiers' register profile, the battery tables of its "monitor", and in the device+ * tree a range of 4 to 9 ohms for the calibrated resistance). So the guard holds what reaches the+ * speakers to levels that are safe for small phone speakers whatever they are exactly, measured+ * the only way there is without feedback -- from the samples and the amplifiers' level -- and+ * kept well under what the speakers can take at Android's level:+ *+ * high-pass a second-order Butterworth filter at 200 Hz: a phone's speaker gives out next to+ * nothing below its resonance (several hundred Hz), and what it is given there only+ * moves the cone further and heats the coil+ * power the power that would reach a speaker, averaged three ways -- over 0.2 s (the+ * cone and coil at once), 3 s (the voice coil's warming) and 60 s (the magnet and+ * the frame) -- and the level turned down so that none of the three averages goes+ * over its limit: 3, 6 and 9 dB under the power of a full-scale sine at Android's+ * level. Sound of ordinary loudness never comes near them; a sustained full-scale+ * tone is turned down at once to the first, after seconds to the second and over a+ * minute to the third, and the level comes back up as the averages fall, as a+ * speaker cools. The averages go on falling while the amplifiers are off.+ * peaks no sample above 3 dB under full scale at Android's level: a limiter that turns+ * the level down at the sample that would go over (so none does) and lets it come+ * back with a time constant of 43 ms+ * monitor a further reduction that the amplifiers' watch asks for (redwood_speaker.c:+ * Android's table for a cold amplifier, and a low battery)+ *+ * Before all that, a gain (sound_gain, at most 12 dB): iOS's own processing for the iPhone X's+ * speaker keeps even a full-scale tone at its top volume 12.6 to 14.3 dB under full scale, so+ * without it iOS at the top would stay that much under Android at the top. What it lifts over+ * full scale is held to full scale by the peak limiter (or to its lower limit), never clipped.+ *+ * All the limits are in terms of the speakers: a signal at full scale with the amplifiers at+ * Android's level (the loudest they are ever set to) is 0 dB. With the amplifiers turned down+ * (sound_below) the same samples are that much quieter at the speakers, and the guard holds them+ * back only that much later. Everything is integer arithmetic (the kernel's threads do no+ * floating point); fractions are in Q30 unless said otherwise.+ *+ * One caller at a time (the feeder); redwood_guard_attenuation() and redwood_guard_monitor() may+ * be called from another thread.+ */+#include <stdbool.h>+#include <stdint.h>+#include <sys/redwood_audio.h>++#define ONE (1ll << 30)+#define FULL_SCALE 32768++/* The limits, in eighths of a dB under full scale at Android's level (powers: under a full-scale square wave's) */+#define PEAK_LIMIT (3 * 8)+#define RMS_LIMIT (6 * 8) /* a full-scale sine is 3 dB under a square wave: these are 3, 6, 9 dB under it */+#define FAST_LIMIT (9 * 8)+#define SLOW_LIMIT (12 * 8)+/* ... and the averages' time constants, in frames (48 kHz) */+#define RMS_FRAMES 9600 /* 0.2 s */+#define FAST_FRAMES 144000 /* 3 s */+#define SLOW_FRAMES 2880000 /* 60 s */+#define RELEASE_SHIFT 11 /* the peak limiter lets go with a time constant of 2048 frames, 43 ms */+#define MAX_FRAMES 1024 /* the most frames processed at once (the feeder's period: 960) */++/* 10^(-n/160), n = 0..47, in Q30: an attenuation of n eighths of a dB, as a factor of amplitude */+static const uint32_t eighths[48] = {+ 1073741824, 1058400094, 1043277569, 1028371116, 1013677647, 999194121, 984917536, 970844937, 956973408, 943300077,+ 929822112, 916536722, 903441154, 890532697, 877808678, 865266461, 852903448, 840717079, 828704830, 816864213,+ 805192776, 793688102, 782347808, 771169545, 760150998, 749289885, 738583957, 728030996, 717628817, 707375265,+ 697268218, 687305580, 677485290, 667805313, 658263644, 648858308, 639587356, 630448869, 621440953, 612561743,+ 603809400, 595182112, 586678091, 578295576, 570032831, 561888146, 553859832, 545946228,+};+#define SIX_DB 538145694 /* 10^(-6/20) in Q30 */++/* the high-pass filter, 200 Hz at 48 kHz, Q = 1/sqrt(2): b0, b1, b2, a1, a2 in Q30 (RBJ's cookbook) */+static const int64_t hpf_b0 = 1054047540, hpf_b1 = -2108095079, hpf_b2 = 1054047540;+static const int64_t hpf_a1 = -2107733822, hpf_a2 = 1034714513;++static struct {+ bool hpf;+ uint64_t gain; /* the gain before everything, Q30 (1 to 4) */+ volatile uint32_t attenuation; /* the amplifiers' level under Android's, eighths of a dB; REDWOOD_GUARD_SILENT: off */+ volatile uint32_t monitor; /* the monitor's reduction, eighths of a dB */+ int64_t x1[2], x2[2], y1[2], y2[2]; /* the filter's past, in 1/256 of a sample */+ uint64_t rms[2], fast[2], slow[2]; /* average powers at each speaker, Q30 of a full-scale square wave at Android's level */+ uint64_t level; /* the power guard's and the monitor's gain at the end of the last block */+ uint64_t envelope; /* the peak limiter's, 1/65536 of a sample */+ struct redwood_guard_report report;+} guard = { .hpf = true, .attenuation = REDWOOD_GUARD_SILENT, .gain = ONE, .level = ONE, .report = { .least_gain = ONE, .least_peak_gain = 65536 } };++static int32_t work[2 * MAX_FRAMES];++/* 10^(-n/160) in Q30: n eighths of a dB under, as a factor of amplitude */+static uint64_t+amplitude(uint32_t n)+{+ uint64_t value = eighths[n % 48];++ for (uint32_t i = 0; i < n / 48 && value != 0; i++) {+ value = value * SIX_DB >> 30;+ }+ return value;+}++static uint64_t+isqrt(uint64_t value)+{+ uint64_t root = 0, bit = 1ull << 62;++ while (bit > value) {+ bit >>= 2;+ }+ while (bit != 0) {+ if (value >= root + bit) {+ value -= root + bit;+ root = (root >> 1) + bit;+ } else {+ root >>= 1;+ }+ bit >>= 2;+ }+ return root;+}++/* how much of `limit' a power is, as the square of the gain that would bring it down to it (Q30, at most 1) */+static uint64_t+headroom(uint64_t power, uint64_t limit)+{+ if (power <= limit) {+ return ONE;+ }+ return (limit << 30) / power;+}++void+redwood_guard_configure(bool hpf, uint32_t gain)+{+ guard.hpf = hpf;+ /* 10^(gain/160): one over the attenuation by as much */+ guard.gain = (1ull << 60) / amplitude(gain > REDWOOD_GUARD_MAX_GAIN ? REDWOOD_GUARD_MAX_GAIN : gain);+}++void+redwood_guard_attenuation(uint32_t below)+{+ guard.attenuation = below;+}++void+redwood_guard_monitor(uint32_t below)+{+ guard.monitor = below;+}++static void+block(int16_t *frames, uint32_t count)+{+ uint32_t attenuation = guard.attenuation;+ struct redwood_guard_report *r = &guard.report;+ uint64_t to_speaker = attenuation == REDWOOD_GUARD_SILENT ? 0 : amplitude(2 * attenuation);+ uint64_t sum[2] = { 0, 0 }, g2 = ONE, g, start = guard.level, ceiling;+ uint32_t binding = 0;++ /* the high-pass filter, and what comes out of it: its power, per channel */+ for (uint32_t i = 0; i < 2 * count; i++) {+ unsigned c = i & 1;+ int64_t x = (int64_t)frames[i] * (int64_t)guard.gain >> 22, y; /* (the gain, and 1/256 of a sample) */+ uint32_t level = frames[i] < 0 ? (uint32_t)-frames[i] : (uint32_t)frames[i];++ if (level > r->peak_in) {+ r->peak_in = level;+ }+ if (guard.hpf) {+ y = (hpf_b0 * x + hpf_b1 * guard.x1[c] + hpf_b2 * guard.x2[c] - hpf_a1 * guard.y1[c] - hpf_a2 * guard.y2[c]) >> 30;+ guard.x2[c] = guard.x1[c];+ guard.x1[c] = x;+ guard.y2[c] = guard.y1[c];+ guard.y1[c] = y;+ } else {+ y = x;+ }+ work[i] = (int32_t)((y + 128) >> 8);+ sum[c] += (uint64_t)((int64_t)work[i] * work[i]);+ }++ /* the averages at the speakers, and the gain that keeps all three under their limits */+ for (unsigned c = 0; c < 2; c++) {+ /* the block's power, Q30 of full scale (a square wave at 32768), then as it reaches the speaker */+ uint64_t power = (uint64_t)((unsigned __int128)(sum[c] / count) * to_speaker >> 30), h;++ guard.rms[c] = (uint64_t)((int64_t)guard.rms[c] + ((int64_t)power - (int64_t)guard.rms[c]) * count / RMS_FRAMES);+ guard.fast[c] = (uint64_t)((int64_t)guard.fast[c] + ((int64_t)power - (int64_t)guard.fast[c]) * count / FAST_FRAMES);+ guard.slow[c] = (uint64_t)((int64_t)guard.slow[c] + ((int64_t)power - (int64_t)guard.slow[c]) * count / SLOW_FRAMES);+ if ((h = headroom(guard.rms[c], amplitude(2 * RMS_LIMIT))) < g2) {+ g2 = h;+ binding = 1;+ }+ if ((h = headroom(guard.fast[c], amplitude(2 * FAST_LIMIT))) < g2) {+ g2 = h;+ binding = 2;+ }+ if ((h = headroom(guard.slow[c], amplitude(2 * SLOW_LIMIT))) < g2) {+ g2 = h;+ binding = 3;+ }+ }+ g = isqrt(g2 << 30) * amplitude(guard.monitor) >> 30;+ if (g > ONE) {+ g = ONE;+ }+ r->blocks++;+ if (binding == 1) {+ r->rms_blocks++;+ } else if (binding == 2) {+ r->fast_blocks++;+ } else if (binding == 3) {+ r->slow_blocks++;+ }+ if (g < r->least_gain) {+ r->least_gain = g;+ }++ /* the peaks: no sample over the limit at the speaker (and none over full scale) */+ ceiling = FULL_SCALE - 1;+ if (attenuation != REDWOOD_GUARD_SILENT && attenuation < PEAK_LIMIT) {+ ceiling = (uint64_t)FULL_SCALE * amplitude(PEAK_LIMIT - attenuation) >> 30;+ }+ for (uint32_t f = 0; f < count; f++) {+ /* (the power guard's gain moves from the last block's to this one's across the block) */+ uint64_t gain = (uint64_t)((int64_t)start + ((int64_t)g - (int64_t)start) * (int64_t)(f + 1) / (int64_t)count);+ int64_t y[2];+ uint64_t level, peak_gain = 65536;++ for (unsigned c = 0; c < 2; c++) {+ y[c] = (int64_t)work[2 * f + c] * (int64_t)gain >> 30;+ }+ level = (uint64_t)(y[0] < 0 ? -y[0] : y[0]);+ if ((uint64_t)(y[1] < 0 ? -y[1] : y[1]) > level) {+ level = (uint64_t)(y[1] < 0 ? -y[1] : y[1]);+ }+ guard.envelope -= guard.envelope >> RELEASE_SHIFT;+ if (level << 16 > guard.envelope) {+ guard.envelope = level << 16;+ }+ if (guard.envelope > ceiling << 16) {+ peak_gain = (ceiling << 32) / guard.envelope;+ r->limited_frames++;+ if (peak_gain < r->least_peak_gain) {+ r->least_peak_gain = (uint32_t)peak_gain;+ }+ }+ for (unsigned c = 0; c < 2; c++) {+ int64_t out = y[c] * (int64_t)peak_gain >> 16;+ uint32_t magnitude;++ out = out > FULL_SCALE - 1 ? FULL_SCALE - 1 : out < -FULL_SCALE ? -FULL_SCALE : out;+ frames[2 * f + c] = (int16_t)out;+ magnitude = (uint32_t)(out < 0 ? -out : out);+ if (magnitude > r->peak_out) {+ r->peak_out = magnitude;+ }+ }+ }+ guard.level = g;+ r->gain = g;+ r->rms = guard.rms[0] > guard.rms[1] ? guard.rms[0] : guard.rms[1];+ r->fast = guard.fast[0] > guard.fast[1] ? guard.fast[0] : guard.fast[1];+ r->slow = guard.slow[0] > guard.slow[1] ? guard.slow[0] : guard.slow[1];+}++void+redwood_guard_process(int16_t *frames, uint32_t count)+{+ while (count > 0) {+ uint32_t n = count < MAX_FRAMES ? count : MAX_FRAMES;++ block(frames, n);+ frames += 2 * n;+ count -= n;+ }+}++/* What has happened since the last call (and the averages and the gain as they are now). */+void+redwood_guard_take_report(struct redwood_guard_report *report)+{+ *report = guard.report;+ guard.report = (struct redwood_guard_report){ .least_gain = ONE, .least_peak_gain = 65536 };+}++/* 10 log10 of a Q30 ratio, in tenths of a dB (for what is said) */+int+redwood_guard_decibels(uint64_t ratio)+{+ static const uint16_t fraction[17] = {+ 0, 5732, 11136, 16248, 21098, 25711, 30109, 34312, 38336, 42196, 45904, 49472, 52911, 56229, 59434, 62534, 65535,+ };+ int64_t log2; /* Q16 */+ unsigned top = 63;++ if (ratio == 0) {+ return -999;+ }+ while (!(ratio >> top)) {+ top--;+ }+ {+ /* the 4 bits under the top one choose a segment, the next 12 where in it */+ uint64_t mantissa = top >= 16 ? ratio >> (top - 16) : ratio << (16 - top);+ unsigned index = (unsigned)(mantissa >> 12) & 15, within = (unsigned)mantissa & 4095;++ log2 = ((int64_t)top - 30) * 65536 + fraction[index] + (int64_t)(fraction[index + 1] - fraction[index]) * within / 4096;+ }+ return (int)(log2 * 30103 / 65536 / 1000);+}diff --git a/xnu/files/bsd/dev/redwood_sound.c b/xnu/files/bsd/dev/redwood_sound.cindex 0bc6882..117f6f3 100644--- a/xnu/files/bsd/dev/redwood_sound.c+++ b/xnu/files/bsd/dev/redwood_sound.c@@ -23,7 +23,7 @@* events say whether it takes the samples at 48 kHz. The amplifiers stay off.* sound=3 ... and the amplifiers, with the tone playing: set up as Android's driver sets them* up, started once the clock runs, faded in to sound_below eighths of a dB under- * Android's own level (default 240: 30 dB under, the least it may be is 0), faded+ * Android's own level (default 160: 20 dB under, the least it may be is 0), faded* out and powered down at the end. Audible.* sound=4 what iOS plays (/dev/redwood-audio, redwood_audio.c), until the run ends: the port* and the stream as above, kept running (silence when iOS writes nothing); the@@ -33,7 +33,14 @@* so far under sound_below, which stays the loudest, and at 0 they stay off. (iOS sets* that control only once, to the top, and applies its volume to the samples itself --* see userland/src/audio_plugin.c --; at its volume 0 it writes silence, and the- * amplifiers stay off for that too.)+ * amplifiers stay off for that too.) On their way the samples go through the speakers'+ * guard (redwood_guard.c), in place of the DSP's speaker protection that Android has:+ * sound_gain eighths of a dB of gain (default and most 96, 12 dB: iOS's own processing+ * keeps its top that far under full scale), a high-pass filter, three averages of the+ * power at the speakers and a peak limiter. sound_guard_as=N, for a test: the guard+ * reckons the amplifiers N eighths of a dB under Android's level (louder than they are)+ * and holds back as it would there -- with sound_below=720 (the amplifiers at -90 dB)+ * what it does at the loudest can be seen in the log and the recording without a sound.** The numbers are Android's own, from the phone's live device tree (qcom,msm-dai-tdm-pri-rx and* its port, the pins pri_tdm_*_active), its mixer paths (the speaker: PRI_TDM_RX_0 at 48 kHz,@@ -85,7 +92,8 @@ extern lck_mtx_t redwood_smmu_lock;static LCK_GRP_DECLARE(sound_lock_group, "redwood-sound");static LCK_MTX_DECLARE(sound_lock, &sound_lock_group); /* the path being set up or taken down */-static uint32_t level, seconds = 3, below = 240, pause_ms = 1000;+static uint32_t level, seconds = 3, below = 160, pause_ms = 1000, gain = REDWOOD_GUARD_MAX_GAIN;+static uint32_t guard_as = UINT32_MAX; /* boot-arg sound_guard_as=N: the guard reckons the amplifiers at most N under (a test) */static char last_write[96] = "nothing written";/* ---- what is said: to the loader's log as well, as it happens ---------------------------------------- */@@ -1019,6 +1027,38 @@ ios_sink(const int16_t *frames, uint32_t count)return taken;}+static uint32_t guard_periods; /* periods through the guard */+static volatile bool guard_on; /* the amplifiers are on: what the guard lets through is heard */++/* tenths of a dB as text: "-5.7" */+static const char *+db_text(char *text, int tenths)+{+ snprintf(text, 16, "%s%d.%d", tenths < 0 ? "-" : "", (tenths < 0 ? -tenths : tenths) / 10, (tenths < 0 ? -tenths : tenths) % 10);+ return text;+}++/* What the guard has done since it was last said (redwood_guard.c), as one line; nothing if `quiet'. */+static void+guard_say(const char *when, bool quiet)+{+ struct redwood_guard_report r;+ char t[6][16];++ redwood_guard_take_report(&r);+ if (r.blocks == 0 || quiet) {+ return;+ }+ /* (levels at the speakers: dB under a full-scale square wave at Android's level; gains in dB) */+ say("sound: the guard%s: peaks in %u, out %u (of 32768); gain now %s dB, least %s dB, held down by the 0.2 s/3 s/60 s "+ "averages in %u/%u/%u of %u periods; peaks limited in %u frames (by %s dB at most); averages %s/%s/%s dB\n",+ when, r.peak_in, r.peak_out, db_text(t[0], redwood_guard_decibels(r.gain * r.gain >> 30)),+ db_text(t[1], redwood_guard_decibels(r.least_gain * r.least_gain >> 30)), r.rms_blocks, r.fast_blocks, r.slow_blocks,+ r.blocks, r.limited_frames, db_text(t[2], redwood_guard_decibels((uint64_t)r.least_peak_gain * r.least_peak_gain >> 2)),+ db_text(t[3], redwood_guard_decibels(r.rms)), db_text(t[4], redwood_guard_decibels(r.fast)),+ db_text(t[5], redwood_guard_decibels(r.slow)));+}+/* A period from the ring, the rest of it silence. */static voidperiod_fill_ios(unsigned period)@@ -1036,6 +1076,12 @@ period_fill_ios(unsigned period)ring_tail = tail + n;fed_frames += n;silent_frames += PERIOD_FRAMES - n;+ /* the guard, on every period, silence too: its filter and its averages go on (redwood_guard.c) */+ redwood_guard_process(samples, PERIOD_FRAMES);+ if (n != 0 && redwood_audio_recording_fed()) {+ redwood_audio_record_fed(samples, n);+ }+ guard_periods++;for (vm_offset_t line = (vm_offset_t)samples; line < (vm_offset_t)samples + PERIOD_BYTES; line += 64) {__asm__ volatile ("dc cvac, %0" : : "r" (line));}@@ -1054,7 +1100,18 @@ feeder_thread(__unused void *parameter, __unused wait_result_t result)}while (!stopping) {uint32_t back = returned;-+ static bool was_on;++ if (guard_on && !was_on) {+ guard_say("", true); /* (what it did to the silence meanwhile is of no interest) */+ guard_periods = 0;+ } else if (was_on && !guard_on) {+ guard_say(" until the amplifiers stopped", false);+ } else if (guard_on && guard_periods >= 250) {+ guard_say(", 5 s", false);+ guard_periods = 0;+ }+ was_on = guard_on;if (back != 0) {OSBitAndAtomic(~back, &returned);for (unsigned p = 0; p < PERIODS; p++) {@@ -1077,6 +1134,28 @@ feeder_thread(__unused void *parameter, __unused wait_result_t result)thread_terminate(current_thread());}+/* The amplifiers' level as the guard is to reckon with it (sound_guard_as: louder than it is, for a test). */+static void+guard_level(uint32_t level_below)+{+ redwood_guard_attenuation(level_below < guard_as ? level_below : guard_as);+}++/*+ * The amplifiers are off. The guard goes on at their level all the same: what it lets through now reaches them+ * 160 ms later, behind the periods queued at the DSP, and if that is sound, they will have been started by then+ * (70 ms after it comes). While they are off nothing but silence comes, and the averages fall as a speaker cools.+ * Only when nothing can be heard at all -- iOS's volume at 0, the amplifiers given up on -- is the guard told so.+ */+static void+guard_off(bool unheard)+{+ guard_on = false;+ if (unheard) {+ redwood_guard_attenuation(REDWOOD_GUARD_SILENT);+ }+}+/** The amplifiers on while there is sound, at the volume iOS has set (redwood_audio_volume(): how* far under the loudest, sound_below under Android's level), and off while iOS's volume is 0;@@ -1086,8 +1165,10 @@ static voidwatch(void){bool on = false, given_up = false, muted = false;- uint64_t last_look = 0;- uint32_t starts = 0, changes = 0, generation = 0, extra = 0;+ uint64_t last_look = 0, last_monitor = 0;+ uint32_t starts = 0, changes = 0, generation = 0, extra = 0, monitor = 0, monitor_looks = 0;++ guard_level(below); /* (from the first sample on: see guard_off()) */while (!stopping) {uint64_t now = now_us(), sounded = last_sound_us;@@ -1102,12 +1183,18 @@ watch(void)say("sound: iOS sets the volume: %s%u.%03u dB under the loudest, which is %u.%03u dB under Android's level%s\n",muted ? "muted (0), " : "", extra / 8, extra % 8 * 125, below / 8, below % 8 * 125,on ? (muted ? ": the amplifiers are stopped" : ": the amplifiers follow") : "");- if (on && muted) {- redwood_speaker_stop();- on = false;+ if (muted) {+ guard_off(true);+ if (on) {+ redwood_speaker_stop();+ on = false;+ }} else if (on && !redwood_speaker_volume(below + extra, 1)) {+ guard_off(true);on = false;given_up = true;+ } else if (!given_up) {+ guard_level(below + extra);}}if (!on && !given_up && !muted && sounded != 0 && now - sounded < 100000) {@@ -1116,10 +1203,14 @@ watch(void)ios_peak = 0;if (!redwood_speaker_start() || !redwood_speaker_volume(below + extra, 1)) {say("sound: THE AMPLIFIERS DID NOT START; iOS's sound goes on to the DSP, unheard\n");+ guard_off(true);given_up = true;} else {on = true;+ guard_on = true;last_look = now_us();+ last_monitor = 0;+ monitor_looks = 0;/* (what is written now is heard after the periods already queued at the DSP: PERIODS x 20 ms) */say("sound: the amplifiers are up %llu ms after the first write that was not silence; that write reaches ""them %u ms after it was made, behind the periods queued at the DSP\n", (last_look - sounded) / 1000,@@ -1129,17 +1220,32 @@ watch(void)say_when("three seconds of silence: the amplifiers are stopped");say("sound: what iOS wrote while they were on peaked at %u%% of full scale (%u)\n", ios_peak * 100 / 32768,ios_peak);+ guard_off(false);redwood_speaker_stop();on = false;} else if (on && now - last_look >= 200000) {last_look = now;if (!redwood_speaker_healthy()) {+ guard_off(true);on = false;given_up = true;+ } else if (now - last_monitor >= 1000000) {+ /* the amplifiers' temperature and the battery as they see it, every second: a reduction if Android's table asks for one */+ uint32_t wanted;++ last_monitor = now;+ wanted = redwood_speaker_monitor(monitor_looks++ % 10 == 0);+ if (wanted != monitor) {+ say("sound: the amplifiers' watch asks for %u.%03u dB less (it was %u.%03u)\n", wanted / 8, wanted % 8 * 125,+ monitor / 8, monitor % 8 * 125);+ monitor = wanted;+ redwood_guard_monitor(monitor);+ }}}sleep_ms(5);}+ guard_off(true);say("sound: the watcher stops; the amplifiers were started %u times, iOS set the volume %u times%s\n", starts, changes,given_up ? ", and the amplifiers were then given up on" : "");watcher_runs = false;@@ -1265,6 +1371,12 @@ sound_thread(__unused void *parameter, __unused wait_result_t result)redwood_audio_set_sink("the speakers (the audio DSP, redwood_sound.c)", ios_sink);say("sound: WHAT IOS PLAYS GOES TO THE SPEAKERS from here on, %u.%03u dB under Android's level, until the run ends\n",below / 8, below % 8 * 125);+ say("sound: through the guard (redwood_guard.c): %u.%03u dB of gain first (sound_gain), then high-pass at 200 Hz; peaks "+ "3 dB, the 0.2 s/3 s/60 s power 6/9/12 dB under full scale at Android's level\n", gain / 8, gain % 8 * 125);+ if (guard_as < below) {+ say("sound: sound_guard_as=%u: FOR A TEST the guard reckons the amplifiers %u.%03u dB under Android's level, louder "+ "than they are, and holds back as much as it would there\n", guard_as, guard_as / 8, guard_as % 8 * 125);+ }lck_mtx_unlock(&sound_lock);watch();thread_terminate(current_thread());@@ -1312,6 +1424,12 @@ redwood_sound_dsp_up(void)PE_parse_boot_argn("sound_secs", &seconds, sizeof(seconds));PE_parse_boot_argn("sound_below", &below, sizeof(below));PE_parse_boot_argn("sound_pause", &pause_ms, sizeof(pause_ms));+ PE_parse_boot_argn("sound_guard_as", &guard_as, sizeof(guard_as));+ PE_parse_boot_argn("sound_gain", &gain, sizeof(gain));+ if (gain > REDWOOD_GUARD_MAX_GAIN) {+ gain = REDWOOD_GUARD_MAX_GAIN;+ }+ redwood_guard_configure(true, gain);if (level >= 2 && level <= 3 && seconds > 3) {seconds = 3; /* the test tone: three seconds at most */}diff --git a/xnu/files/bsd/dev/redwood_speaker.c b/xnu/files/bsd/dev/redwood_speaker.cindex 00f88ef..cd1bcc7 100644--- a/xnu/files/bsd/dev/redwood_speaker.c+++ b/xnu/files/bsd/dev/redwood_speaker.c@@ -50,9 +50,10 @@* the boost or the output, over-temperature, no clock, the watchdog, over-voltage) has both* amplifiers powered down at once (amplifier power-down and power-down, bits 1 and 0 of 0x04)* and nothing more done. What is not done, compared with Android: the DSP's Awinic algorithm,- * which protects the speakers with their calibration (aw882xx_rx_switch), and the driver's- * watch of battery voltage and temperature, which only ever turns the volume down -- whoever- * plays through this keeps the level low.+ * which protects the speakers with their calibration (aw882xx_rx_switch); in its place the+ * samples go through redwood_guard.c on their way here. The driver's monitor is done+ * (redwood_speaker_monitor(), below): once a second the chips' temperature and the battery's+ * voltage, and the reduction that the file's table asks for at either.** I2C is done by hand: a pin is either pulled low or let go (and the pull-ups raise it), at 100* kHz at most. For each register read or written the two pins are taken from the serial engine@@ -360,6 +361,11 @@ amplifier_name(uint16_t id)#define AW_SYSCTRL 0x04#define AW_SYSCTRL2 0x05 /* [9:0] the volume, attenuation: [9:6] 6 dB steps, [5:0] eighths of a dB */#define AW_I2SCTRL3 0x08+#define AW_VBAT 0x21 /* [9:0] the battery's voltage as the amplifier sees it: x 6025 / 1023 mV */+#define AW_TEMP 0x22 /* [9:0] the amplifier's temperature, degrees Celsius, two's complement */+#define AW_PVDD 0x23 /* [9:0] its boosted supply */+#define AW_ISNDAT 0x24 /* the current and voltage sense, as last measured */+#define AW_VSNDAT 0x25#define AW_DBGCTRL 0x14#define AW_VSNTM1 0x50#define AW_EFRH4 0x78@@ -397,6 +403,8 @@ amplifier_name(uint16_t id)/* Android's configuration file ("ACF", Awinic's format; Linux: sound/soc/codecs/aw88395/aw88395_lib.c) */#define ACF_PROFILE_MUSIC 0#define ACF_DATA_REGISTERS 4 /* a block with a header of its own and registers in it */+#define ACF_DATA_MONITOR 10 /* the driver's "monitor": what to do when the chip is cold or the battery low */+#define MONITOR_ROWS 8#define ACF_BLOCK_HEADER 0x3cstruct amplifier {@@ -411,11 +419,16 @@ struct amplifier {uint16_t volume; /* where it is now */uint16_t volume_high; /* the profile's bits 15:10 of 0x05, which the volume leaves as they are */bool prepared, started;+ /* the monitor's tables (from the file) and what was last seen */+ struct { int16_t min, max; uint16_t less; } temp_rows[MONITOR_ROWS], vbat_rows[MONITOR_ROWS];+ unsigned temp_count, vbat_count, looks;+ int temps[3], vbats[3];+ int temp_row, vbat_row;};static struct amplifier amplifiers[2] = {- { .address = 0x35, .device = 0, .where = "0x35, slot 0" },- { .address = 0x34, .device = 1, .where = "0x34, slot 1" },+ { .address = 0x35, .device = 0, .where = "0x35, slot 0", .temp_row = -1, .vbat_row = -1 },+ { .address = 0x34, .device = 1, .where = "0x34, slot 1", .temp_row = -1, .vbat_row = -1 },};static bool broken; /* something went wrong: both have been powered down, nothing more is done */@@ -425,6 +438,82 @@ le32(const uint8_t *p)return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24;}+/*+ * The driver's monitor for one amplifier (Android has it on: aw_dev_N_monitor), from the file: every second it+ * reads the chip's temperature and the battery's voltage, and a table says what to do for each range of them.+ * This file's: at 7 to 100 degrees nothing; at 2 to 5 degrees 3 dB less, at -2 to 0 4.5 dB, at -50 to -5 8 dB (and+ * a lower current limit for the boost, which is not done here); from 3.85 V nothing, at 3.65 to 3.75 V and up to+ * 3.55 V a lower "vmax" for the DSP's algorithm, which does not run here. In its temperature rows a vmax goes with+ * each reduction of the volume, so the battery rows' vmax is turned into a volume reduction in the same proportion+ * (the first temperature row's: 3 dB for its vmax): 1.6 and 3.1 dB. Between the ranges the last one holds.+ * block: checksum (of the bytes after it), version, chip name[16], ui version, the time and count of looks,+ * switches, then for the temperatures and for the voltages each: a value, the number of rows, a row's size and+ * the rows' offset; a row: int16 lowest, int16 highest, uint16 boost current, uint16 reduction (eighths of a+ * dB), int32 vmax+ */+static void+acf_monitor(uint16_t device, const uint8_t *block, uint32_t length)+{+ struct amplifier *a = NULL;+ uint32_t sum = 0, temp_count, temp_size, temp_at, vbat_count, vbat_size, vbat_at;+ int64_t per_eighth = 0;++ for (unsigned i = 0; i < 2; i++) {+ if (amplifiers[i].device == device) {+ a = &lifiers[i];+ }+ }+ if (a == NULL || length < 0x48) {+ return;+ }+ for (uint32_t i = 4; i < length; i++) {+ sum += block[i];+ }+ temp_count = le32(block + 0x2c);+ temp_size = le32(block + 0x30);+ temp_at = le32(block + 0x34);+ vbat_count = le32(block + 0x3c);+ vbat_size = le32(block + 0x40);+ vbat_at = le32(block + 0x44);+ if (sum != le32(block) || temp_size < 12 || vbat_size < 12 || temp_count > MONITOR_ROWS || vbat_count > MONITOR_ROWS ||+ temp_at + temp_count * temp_size > length || vbat_at + vbat_count * vbat_size > length) {+ say("speaker: device %u's monitor table is not of the shape known: not used\n", device);+ return;+ }+ for (uint32_t i = 0; i < temp_count; i++) {+ const uint8_t *row = block + temp_at + i * temp_size;+ int32_t vmax = (int32_t)le32(row + 8);++ a->temp_rows[i].min = (int16_t)(row[0] | row[1] << 8);+ a->temp_rows[i].max = (int16_t)(row[2] | row[3] << 8);+ a->temp_rows[i].less = (uint16_t)(row[6] | row[7] << 8);+ if (per_eighth == 0 && a->temp_rows[i].less != 0 && vmax < 0) {+ per_eighth = -(int64_t)vmax / a->temp_rows[i].less;+ }+ }+ for (uint32_t i = 0; i < vbat_count; i++) {+ const uint8_t *row = block + vbat_at + i * vbat_size;+ int32_t vmax = (int32_t)le32(row + 8);++ a->vbat_rows[i].min = (int16_t)(row[0] | row[1] << 8);+ a->vbat_rows[i].max = (int16_t)(row[2] | row[3] << 8);+ a->vbat_rows[i].less = (uint16_t)(row[6] | row[7] << 8);+ if (vmax < 0 && per_eighth > 0) {+ a->vbat_rows[i].less += (uint16_t)((-(int64_t)vmax + per_eighth / 2) / per_eighth);+ }+ }+ a->temp_count = temp_count;+ a->vbat_count = vbat_count;+ for (uint32_t i = 0; i < temp_count; i++) {+ say("speaker: the amplifier %s's monitor: at %d to %d degrees, %u.%03u dB less\n", a->where, a->temp_rows[i].min,+ a->temp_rows[i].max, a->temp_rows[i].less / 8, a->temp_rows[i].less % 8 * 125);+ }+ for (uint32_t i = 0; i < vbat_count; i++) {+ say("speaker: the amplifier %s's monitor: at %d to %d mV, %u.%03u dB less\n", a->where, a->vbat_rows[i].min,+ a->vbat_rows[i].max, a->vbat_rows[i].less / 8, a->vbat_rows[i].less % 8 * 125);+ }+}+/* The "Music" profile of every amplifier, from the file; false if the file is not of the shape known. */static boolacf_profiles(const uint8_t *acf, uint64_t size)@@ -455,6 +544,10 @@ acf_profiles(const uint8_t *acf, uint64_t size)memcpy(name, entry + 4, 16);name[16] = 0;+ if (kind == ACF_DATA_MONITOR) {+ acf_monitor(device, acf + offset, (uint64_t)offset + length <= size ? length : 0);+ continue;+ }if (kind != ACF_DATA_REGISTERS || profile != ACF_PROFILE_MUSIC || strcmp(name, "aw88261") != 0) {continue;}@@ -871,6 +964,71 @@ redwood_speaker_healthy(void)return true;}+/* the row of a monitor table that a value falls in; between rows, the one before */+static int+monitor_row(const struct amplifier *a, bool temperature, int value, int before)+{+ unsigned count = temperature ? a->temp_count : a->vbat_count;++ for (unsigned i = 0; i < count; i++) {+ int min = temperature ? a->temp_rows[i].min : a->vbat_rows[i].min;+ int max = temperature ? a->temp_rows[i].max : a->vbat_rows[i].max;++ if (value >= min && value <= max) {+ return (int)i;+ }+ }+ return before;+}++/*+ * The driver's monitor, once: the temperature and the battery voltage of every amplifier that runs (the average of+ * the last three looks, as the file's count says), and the reduction their tables ask for, the larger of the two+ * amplifiers'. With `tell', what was read (also the boosted supply and the current and voltage sense, raw).+ */+uint32_t+redwood_speaker_monitor(bool tell)+{+ uint32_t wanted = 0;++ for (unsigned i = 0; i < 2; i++) {+ struct amplifier *a = &lifiers[i];+ uint16_t vbat = 0, temp = 0, pvdd = 0, isn = 0, vsn = 0;+ int t = 0, v = 0;+ uint32_t less = 0;++ if (broken || !a->started) {+ continue;+ }+ if (!get(a, AW_VBAT, &vbat) || !get(a, AW_TEMP, &temp)) {+ continue;+ }+ a->temps[a->looks % 3] = (temp & 0x200) ? (int)(temp & 0x3ff) - 0x400 : (int)(temp & 0x3ff);+ a->vbats[a->looks % 3] = (int)(vbat & 0x3ff) * 6025 / 1023;+ a->looks++;+ for (unsigned k = 0; k < 3 && k < a->looks; k++) {+ t += a->temps[k];+ v += a->vbats[k];+ }+ t /= (int)(a->looks < 3 ? a->looks : 3);+ v /= (int)(a->looks < 3 ? a->looks : 3);+ a->temp_row = monitor_row(a, true, t, a->temp_row);+ a->vbat_row = monitor_row(a, false, v, a->vbat_row);+ less = (a->temp_row >= 0 ? a->temp_rows[a->temp_row].less : 0) + (a->vbat_row >= 0 ? a->vbat_rows[a->vbat_row].less : 0);+ if (less > wanted) {+ wanted = less;+ }+ if (tell) {+ (void)get(a, AW_PVDD, &pvdd);+ (void)get(a, AW_ISNDAT, &isn);+ (void)get(a, AW_VSNDAT, &vsn);+ say("speaker: the amplifier %s: %d degrees, the battery %d mV (%#05x, %#05x; supply %#05x, sense %#06x %#06x): "+ "%u.%03u dB less\n", a->where, t, v, temp, vbat, pvdd, isn, vsn, less / 8, less % 8 * 125);+ }+ }+ return wanted;+}+voidredwood_speaker_stop(void){diff --git a/xnu/files/bsd/sys/redwood_audio.h b/xnu/files/bsd/sys/redwood_audio.hindex 650cfe8..ac48555 100644--- a/xnu/files/bsd/sys/redwood_audio.h+++ b/xnu/files/bsd/sys/redwood_audio.h@@ -63,6 +63,33 @@ bool redwood_speaker_volume(uint32_t below, uint32_t step_ms); /* below Android'bool redwood_speaker_healthy(void); /* no fault reported; on one, both are powered down at once */void redwood_speaker_stop(void); /* faded out, muted, powered down, in Android's order */void redwood_speaker_quiesce(void); /* powered down at once, without sleeping: on a panic's way out */+/* the amplifiers' own temperature and battery voltage read (every second while they play): the reduction they call for */+uint32_t redwood_speaker_monitor(bool tell);++/*+ * The speakers' guard (bsd/dev/redwood_guard.c): what the samples go through in the feeder on their+ * way to the amplifiers, for want of the DSP's speaker protection. Levels in eighths of a dB.+ */+#define REDWOOD_GUARD_SILENT 0xffffffffu /* the amplifiers are off: nothing reaches the speakers */+struct redwood_guard_report {+ uint32_t blocks, rms_blocks, fast_blocks, slow_blocks; /* blocks done, and in how many each average held the level down */+ uint32_t limited_frames; /* frames in which the peak limiter turned the level down */+ uint32_t peak_in, peak_out; /* the largest sample that came in and that went out */+ uint32_t least_peak_gain; /* the peak limiter's least gain, in 1/65536 */+ uint64_t least_gain, gain; /* the power guard's (with the monitor's) least gain and the latest, Q30 */+ uint64_t rms, fast, slow; /* the averages now, the louder speaker's: Q30 of a full-scale square wave at Android's level */+};+#define REDWOOD_GUARD_MAX_GAIN (12 * 8) /* the most gain before the guard: 12 dB */+void redwood_guard_configure(bool hpf, uint32_t gain); /* the high-pass filter; `gain' before everything */+void redwood_guard_attenuation(uint32_t below); /* the amplifiers' level under Android's (or REDWOOD_GUARD_SILENT):+ * what the limits are reckoned from */+void redwood_guard_monitor(uint32_t below); /* a reduction asked for by redwood_speaker_monitor() */+void redwood_guard_process(int16_t *frames, uint32_t count); /* stereo frames, in place */+void redwood_guard_take_report(struct redwood_guard_report *report); /* what happened since the last call */+int redwood_guard_decibels(uint64_t ratio); /* 10 log10 of a Q30 ratio, in tenths of a dB */+/* boot-arg rec_sound_fed=1: the recording (rec_sound=N) has what the guard let through instead of what iOS wrote */+bool redwood_audio_recording_fed(void);+void redwood_audio_record_fed(const int16_t *frames, uint32_t count);/** The audio DSP's services, for the sound's path (bsd/dev/redwood_adsp.c, bsd/dev/redwood_sound.c).diff --git a/xnu/redwood.patch b/xnu/redwood.patchindex 86b206e..5087acf 100644--- a/xnu/redwood.patch+++ b/xnu/redwood.patch@@ -46,10 +46,10 @@ index 222158a93918..68bb0f3e56bf 100755####################################################################### HISTORYdiff --git a/bsd/conf/files b/bsd/conf/files-index 44274016a4cf..c4058651c5a6 100644+index 44274016a4cf..f393c22a6ebf 100644--- a/bsd/conf/files+++ b/bsd/conf/files-@@ -109,6 +109,26 @@ bsd/dev/munge.c optional config_requires_u32_munging+@@ -109,6 +109,27 @@ bsd/dev/munge.c optional config_requires_u32_mungingbsd/dev/unix_startup.c standardbsd/dev/monotonic.c optional monotonic@@ -66,6 +66,7 @@ index 44274016a4cf..c4058651c5a6 100644+bsd/dev/redwood_audio.c standard+bsd/dev/redwood_virtio_sound.c standard+bsd/dev/redwood_speaker.c standard++bsd/dev/redwood_guard.c standard+bsd/dev/redwood_wifi.c standard+bsd/dev/redwood_adsp.c standard+bsd/dev/redwood_sound.c standard@@ -76,7 +77,7 @@ index 44274016a4cf..c4058651c5a6 100644bsd/dev/dev_perfmon.c optional config_perfmonbsd/libkern/crc32.c standard-@@ -155,6 +175,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs+@@ -155,6 +176,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfsbsd/miscfs/mockfs/mockfs_fsnode.c optional mockfsbsd/miscfs/mockfs/mockfs_vfsops.c optional mockfsbsd/miscfs/mockfs/mockfs_vnops.c optional mockfs@@ -87,7 +88,7 @@ index 44274016a4cf..c4058651c5a6 100644bsd/miscfs/routefs/routefs_ops.c optional routefs-@@ -361,6 +385,7 @@ bsd/security/audit/audit_syscalls.c standard+@@ -361,6 +386,7 @@ bsd/security/audit/audit_syscalls.c standardbsd/security/audit/audit_worker.c optional config_auditbsd/pthread/pthread_shims.c standard@@ -95,7 +96,7 @@ index 44274016a4cf..c4058651c5a6 100644bsd/pthread/pthread_priority.c standardbsd/pthread/pthread_workqueue.c standard-@@ -383,6 +408,7 @@ bsd/kern/kern_debug.c standard+@@ -383,6 +409,7 @@ bsd/kern/kern_debug.c standardbsd/kern/kern_symfile.c standardbsd/kern/kern_descrip.c standardbsd/kern/kern_guarded.c standard