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

Sound, step 3: the speakers play a test tone (sound=1..3, with adsp=1)

vcvkk63e317d6865f
diff --git a/README.md b/README.md
index 5ae7f7d..2ebf688 100644
--- a/README.md
+++ b/README.md
@@ -100,8 +100,9 @@ AUDIO=pipewire qemu/run-ios.sh 1200 -display gtk > logs/qemu.log # или AUD
(`userland/src/sound_test.c`); когда звук смолкает, ядро пишет в журнал строку
`redwood-audio: N s written at R frames a second, M s of it sound, peak P% of full scale`.
-На телефоне динамики пока молчат (ими управляет звуковой процессор Qualcomm, который наше ядро не запускает),
-но то, что iOS играет, можно забрать: параметр ядра `rec_sound=N` сохраняет первые N секунд звука в памяти, после
+На телефоне то, что играет iOS, до динамиков пока не доходит. Сами динамики уже звучат: с `adsp=1 sound=3`
+ядро через звуковой процессор (порт TDM, поток, путь к порту) и оба усилителя Awinic играет пробный тон
+(см. параметр `sound=N` ниже). То, что iOS играет, можно забрать: параметр ядра `rec_sound=N` сохраняет первые N секунд звука в памяти, после
сеанса `./xl sound out.wav` достаёт их (в QEMU — `pmemsave` по адресу из строки `redwood-audio: recording … at 0x…`,
затем `tools/sound.py`). В QEMU запись проверена; на самом телефоне звук ещё не проверялся вовсе.
@@ -233,6 +234,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=4" ./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_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,
diff --git a/userland/build.sh b/userland/build.sh
index 660646f..8b2bdc7 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -244,6 +244,12 @@ if [ -f $IOS/system.manifest ] && [ -f $CACHE/dyld_shared_cache_arm64 ] &&
mkdir -p sysroot/fw
cp ../fw-audio/adsp.mdt ../fw-audio/adsp.b0[2-9] ../fw-audio/adsp.b[1-9][0-9] sysroot/fw/
fi
+ # ... and the speaker amplifiers' configuration, the phone's /vendor/etc/aw882xx_acf.bin (bsd/dev/redwood_speaker.c,
+ # for sound=3): Android's own register values, which are not in the repository either
+ if [ -f ../fw-audio/aw882xx_acf.bin ]; then
+ mkdir -p sysroot/fw
+ cp ../fw-audio/aw882xx_acf.bin sysroot/fw/
+ fi
# our audio device, where the audio server looks for such plug-ins (and for no others: Apple's are left out)
mkdir -p sysroot/System/Library/Audio/Plug-Ins/HAL
ln -s /redwood/lib/RedwoodAudio.driver sysroot/System/Library/Audio/Plug-Ins/HAL/RedwoodAudio.driver
diff --git a/xnu/files/bsd/dev/redwood_adsp.c b/xnu/files/bsd/dev/redwood_adsp.c
index 125505b..d6181e0 100644
--- a/xnu/files/bsd/dev/redwood_adsp.c
+++ b/xnu/files/bsd/dev/redwood_adsp.c
@@ -52,6 +52,10 @@
* 11 talks APR, on the channel apr_audio_svc that the DSP opens and we answer as well: whether
* the audio services are up, and which there are (see step_apr())
*
+ * Once everything is up with adsp=1, the sound's path takes over (redwood_sound.c, boot-arg sound=N):
+ * redwood_adsp_apr() is how it speaks to the audio services (any service, port and token; what
+ * nobody waits for goes to its handler of events), and it is stopped before the DSP is.
+ *
* What is started is stopped: when the steps are over (unless adsp_keep=1, and then when the run
* ends), and on a panic's way back to the loader. The DSP is asked first (bit 0 of our entry
* "master-kernel"), then TrustZone shuts it down, then the always-on processor hears "adsp: off".
@@ -89,6 +93,7 @@
#include <sys/vnode.h>
#include <sys/vnode_internal.h>
#include <vm/vm_kern.h>
+#include <sys/redwood_audio.h>
extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
extern vm_offset_t ml_io_map_unmappable(vm_offset_t phys_addr, vm_size_t size, unsigned int flags);
@@ -1029,6 +1034,21 @@ root_file(const char *name, uint64_t *size)
static bool from_root; /* the image is in memory of ours (root_file()), to be given back once written */
+/* For the sound (redwood_sound.c): a file of /fw on the root, read whole into memory of ours, and given back. */
+const uint8_t *
+redwood_adsp_fw_file(const char *name, uint64_t *size)
+{
+ return root_file(name, size);
+}
+
+void
+redwood_adsp_fw_free(const uint8_t *data, uint64_t size)
+{
+ uint8_t *ours = __DECONST(uint8_t *, data);
+
+ kfree_data(ours, size);
+}
+
/* A file of fw/ in the small image (ADSP=1 userland/build.sh puts fw-audio/ there), else of /fw on the root (above). */
static const uint8_t *
image_file(const char *name, uint64_t *size)
@@ -2474,6 +2494,9 @@ static struct {
} apr_answer;
static uint32_t apr_in, apr_out, apr_next_token = 1;
static bool audio_up; /* the core service has said that the audio services are up (step 11) */
+static uint32_t apr_waited_for; /* the token a question waits for the answer to; 0: none */
+static redwood_apr_events_t apr_events; /* the sound's (redwood_sound.c): what nobody waits for */
+static LCK_MTX_DECLARE(apr_lock, &adsp_lock_group); /* one question at a time */
/* A packet from the DSP's audio services. From the link's thread. */
static void
@@ -2494,6 +2517,17 @@ apr_input(const uint8_t *data, uint32_t length)
}
payload = (header.size < length ? header.size : length) - header_length;
apr_in++;
+ if (header.token != apr_waited_for || apr_waited_for == 0) {
+ redwood_apr_events_t events = apr_events;
+ uint32_t words[64];
+
+ bzero(words, sizeof(words));
+ memcpy(words, data + header_length, payload < sizeof(words) ? payload : sizeof(words));
+ if (events != NULL && events(header.from_service, header.from_port, header.opcode, header.token, words,
+ payload < sizeof(words) ? payload : sizeof(words))) {
+ return;
+ }
+ }
if (apr_in <= 40) {
uint32_t w[4] = { 0, 0, 0, 0 };
@@ -2510,16 +2544,21 @@ apr_input(const uint8_t *data, uint32_t length)
apr_answer.there = true;
}
-/* A command to one of the DSP's services, and its answer waited for: true, and the answer in apr_answer, if it came. */
-static bool
-apr_ask(uint8_t service, uint32_t opcode, const void *payload, uint32_t length, uint32_t ms)
+/*
+ * A command to one of the DSP's services (and its answer waited for, with ms): true when it was
+ * sent and, if waited for, answered; the answer is in apr_answer and, if asked for, in *answer.
+ * The port is the service's own numbering of what the command is for (ASM: session << 8 | stream).
+ */
+bool
+redwood_adsp_apr(uint8_t service, uint16_t port, uint32_t token, uint32_t opcode, const void *payload, uint32_t length,
+ uint32_t ms, struct redwood_apr_answer *answer)
{
uint8_t packet[sizeof(struct apr_header) + 256];
struct apr_header *header = (struct apr_header *)packet;
- uint32_t token = apr_next_token++;
+ bool answered = false;
int error;
- if (length > sizeof(packet) - sizeof(*header)) {
+ if (length > sizeof(packet) - sizeof(*header) || !glink.channel[CHANNEL_APR].open) {
return false;
}
bzero(packet, sizeof(packet));
@@ -2527,27 +2566,66 @@ apr_ask(uint8_t service, uint32_t opcode, const void *payload, uint32_t length,
header->size = (uint16_t)(sizeof(*header) + length);
header->from_service = service;
header->from_domain = APR_DOMAIN_APPS;
+ header->from_port = port;
header->to_service = service;
header->to_domain = APR_DOMAIN_ADSP;
- header->token = token;
+ header->to_port = port;
header->opcode = opcode;
if (length != 0) {
memcpy(packet + sizeof(*header), payload, length);
}
+ if (ms == 0) {
+ /* (sent and not waited for: what comes back is the events' handler's) */
+ header->token = token;
+ error = glink_send(&glink.channel[CHANNEL_APR], packet, (uint32_t)sizeof(*header) + length);
+ apr_out += error == 0;
+ return error == 0;
+ }
+ lck_mtx_lock(&apr_lock);
+ if (token == 0) {
+ token = apr_next_token++;
+ if (apr_next_token >= 0x01000000u) {
+ apr_next_token = 1;
+ }
+ }
+ header->token = token;
apr_answer.there = false;
+ apr_waited_for = token;
error = glink_send(&glink.channel[CHANNEL_APR], packet, (uint32_t)sizeof(*header) + length);
if (error != 0) {
printf("adsp: apr: > opcode %#x to service %u: NOT SENT (%d)\n", opcode, service, error);
- return false;
- }
- apr_out++;
- for (uint32_t waited = 0; waited < ms; waited++) {
- if (apr_answer.there && apr_answer.token == token) {
- return true;
+ } else {
+ apr_out++;
+ for (uint32_t waited = 0; waited < ms && !answered; waited++) {
+ if (apr_answer.there && apr_answer.token == token) {
+ answered = true;
+ if (answer != NULL) {
+ answer->opcode = apr_answer.opcode;
+ answer->token = apr_answer.token;
+ answer->length = apr_answer.length;
+ memcpy(answer->words, apr_answer.words, sizeof(answer->words));
+ }
+ break;
+ }
+ sleep_ms(1);
}
- sleep_ms(1);
}
- return false;
+ apr_waited_for = 0;
+ lck_mtx_unlock(&apr_lock);
+ return answered;
+}
+
+void
+redwood_adsp_apr_events(redwood_apr_events_t handler)
+{
+ apr_events = handler;
+}
+
+/* A command to one of the DSP's services, and its answer waited for: true, and the answer in apr_answer, if it came. */
+static bool
+apr_ask(uint8_t service, uint32_t opcode, const void *payload, uint32_t length, uint32_t ms)
+{
+ return redwood_adsp_apr(service, 0, 0, opcode, payload, length, ms, NULL);
}
/* ---- the link's thread ----------------------------------------------------------------------------- */
@@ -2824,6 +2902,7 @@ steps_over(uint32_t done)
void
redwood_adsp_stop(void)
{
+ redwood_sound_dsp_down(); /* the amplifiers, the stream and the port first, while the DSP still listens */
lck_mtx_lock(&dsp_lock);
if (dsp_started) {
unsigned services = 0;
@@ -2846,6 +2925,7 @@ redwood_adsp_stop(void)
void
redwood_adsp_quiesce(void)
{
+ redwood_sound_quiesce(); /* the amplifiers off, whatever the DSP's state */
if (!dsp_started) {
return;
}
@@ -2890,6 +2970,7 @@ whole_thread(__unused void *parameter, __unused wait_result_t result)
if (step == STEPS && dsp_started) {
tell("adsp: THE AUDIO DSP IS UP AND LINKED, its audio services up (APR), %llu ms after the kernel began on it (the "
"root's waited for included): node %u, %u services; it stays on\n", (now_us() - began) / 1000, qrtr_peer, services);
+ redwood_sound_dsp_up(); /* (boot-arg sound=N: the speakers' path, redwood_sound.c) */
} else {
tell("adsp: THE AUDIO DSP DID NOT COME UP: step %u failed (%s); see the kernel's own log for the steps\n", step + 1,
last_write);
diff --git a/xnu/files/bsd/dev/redwood_sound.c b/xnu/files/bsd/dev/redwood_sound.c
new file mode 100644
index 0000000..18941bc
--- /dev/null
+++ b/xnu/files/bsd/dev/redwood_sound.c
@@ -0,0 +1,1120 @@
+/*
+ * The phone's sound, step 3: what the audio DSP's services are told so that the speakers play.
+ * Every address and number below belongs to the POCO X5 Pro (redwood), and nothing here happens
+ * unless boot-arg sound=N asks for it, with adsp=1 (redwood_adsp.c), which starts the DSP and
+ * calls redwood_sound_dsp_up() once its audio services are up.
+ *
+ * Under Android the speakers' sound goes from the audio server through three of the DSP's
+ * services: ASM, a stream the samples are written into; ADM, the matrix that routes a stream to
+ * a device path ("COPP"); and AFE, the port at the SoC's interface. The two amplifiers
+ * (redwood_speaker.c) sit on the primary TDM interface, which the DSP runs: Android's
+ * PRI_TDM_RX_0, AFE port 0x9000 in group 0x9100 (with 0x9002, unused). The samples themselves
+ * lie in memory of ours that the DSP reads through the application processors' SMMU, as
+ * stream 0x1801 (Android: qcom,msm-audio-ion, iommus <&apps_smmu 0x1801 0>, its addresses from
+ * 0x10000000, and the stream's low four bits in bits 32 to 35 of every address the DSP is given:
+ * qcom,smmu-sid-mask 0xf, msm_audio_ion.c).
+ *
+ * sound=1 the port: the TDM pins to the interface, the interface's bit clock, the group, the
+ * port, started; whether the bit clock and the frame sync then toggle at the pins is
+ * looked at; held for sound_secs (default 3), then everything stopped and put back
+ * sound=2 ... and a stream: our memory shown to the DSP through the SMMU, a device path
+ * (ADM) to the port, an ASM stream routed to it, and a test tone -- 1 kHz at -20 dBFS,
+ * both channels -- written into it for sound_secs (at most 3); the DSP's "written"
+ * 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
+ * out and powered down at the end. Audible.
+ *
+ * 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,
+ * two channels, S32_LE) and its kernel (Xiaomi's redwood-s-oss, techpack/audio: asoc/lahaina.c,
+ * asoc/msm-dai-q6-v2.c, dsp/q6afe.c, dsp/q6adm.c, dsp/q6asm.c):
+ * - the bit clock: the interface's internal one (clock 0x200, "PRI_TDM_IBIT"), attribute 4
+ * ("invert, couple no", msm-dai-q6-v2.c's default; the tree names none), at 48000 x 32 bits x
+ * 2 slots = 3.072 MHz -- the machine driver sets that rate itself (lahaina.c, which on redwood
+ * halves its four slots to two: "Using default tdm max slot: 4" in Android's log), not the
+ * tree's 1.536 MHz
+ * - the group: ports 0x9000 and 0x9002, two 32-bit slots, mask 3, 48 kHz
+ * - the port: two channels of 32 bits at 48 kHz, linear PCM; sync mode 0, sync source 1, data
+ * out 0, inverted sync 1, data delay 1; slot mapping: channels at byte offsets 0 and 4 (slot
+ * 0, the amplifier at 0x35; slot 1, the one at 0x34), MSB-aligned
+ * - the pins: GPIO 97 (bit clock) and 100 (frame sync) function mi2s0, 8 mA, no pull, output
+ * high; 98 and 99 (data in and out) function mi2s0, 8 mA, no pull (pinctrl-yupik.c: function
+ * 1 for all four)
+ * - the path: ADM's device open (version 5) for playback to port 0x9000 with no processing
+ * (topology 0x10312), two channels, 24 bits, 48 kHz; the stream: ASM session 1, stream 1,
+ * opened for writing linear PCM of 16 bits, no processing (0x10c68), routed to that path
+ *
+ * What is started is stopped, and what is written is put back, when the time is over -- or, if
+ * the DSP is to be shut down earlier (the run's end), before that (redwood_sound_dsp_down()).
+ * The amplifiers are powered down on a panic's way out (redwood_sound_quiesce()).
+ *
+ * Message layouts: the files above, and Linux's sound/soc/qcom/qdsp6/ (q6afe.c, q6adm.c,
+ * q6asm.c); the SMMU: redwood_wifi.c, which does the same for the Wi-Fi's stream.
+ */
+#include <kern/clock.h>
+#include <kern/locks.h>
+#include <kern/thread.h>
+#include <libkern/libkern.h>
+#include <libkern/OSAtomic.h>
+#include <mach/mach_types.h>
+#include <mach/vm_param.h>
+#include <pexpert/pexpert.h>
+#include <sys/systm.h>
+#include <sys/redwood_audio.h>
+#include <vm/vm_kern.h>
+
+extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
+extern uint64_t kvtophys(vm_offset_t va);
+extern kern_return_t thread_terminate(thread_t thread);
+extern void loader_log_putc(char c);
+
+/* The SMMU's match registers and contexts are found free and taken by the Wi-Fi's start as well (redwood_wifi.c). */
+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 char last_write[96] = "nothing written";
+
+/* ---- what is said: to the loader's log as well, as it happens ---------------------------------------- */
+
+static int say(const char *format, ...) __printflike(1, 2);
+
+static int
+say(const char *format, ...)
+{
+ char line[400];
+ va_list list;
+ int length;
+
+ va_start(list, format);
+ length = vsnprintf(line, sizeof(line), format, list);
+ va_end(list);
+ for (const char *c = line; *c != 0; c++) {
+ loader_log_putc(*c);
+ }
+ printf("%s", line);
+ return length;
+}
+
+static void
+sleep_ms(uint32_t ms)
+{
+ delay_for_interval(ms, NSEC_PER_MSEC);
+}
+
+static uint64_t
+now_us(void)
+{
+ uint64_t nanoseconds;
+
+ absolutetime_to_nanoseconds(mach_absolute_time(), &nanoseconds);
+ return nanoseconds / 1000;
+}
+
+/* The time of day (UTC, as the host gave it: boot-arg epoch) and since the kernel began, for whoever listens. */
+static void
+say_when(const char *what)
+{
+ clock_sec_t secs;
+ clock_usec_t usecs;
+ uint64_t up = now_us();
+
+ clock_get_calendar_microtime(&secs, &usecs);
+ say("sound: %s at %02lu:%02lu:%02lu.%01u UTC (%llu.%01llu s after the kernel began)\n", what, (unsigned long)(secs / 3600 % 24),
+ (unsigned long)(secs / 60 % 60), (unsigned long)(secs % 60), (unsigned)(usecs / 100000), up / 1000000, up / 100000 % 10);
+}
+
+/* Time for the loader to note what has just been said, before something not yet seen to be harmless. */
+static void
+announce(const char *what)
+{
+ say("sound: %s\n", what);
+ if (pause_ms) {
+ sleep_ms(pause_ms);
+ }
+}
+
+static uint32_t __attribute__((noinline))
+rd(vm_offset_t address)
+{
+ uint32_t value;
+
+ __asm__ volatile ("ldr %w0, [%1]" : "=r" (value) : "r" (address) : "memory");
+ return value;
+}
+
+static void __attribute__((noinline))
+wr(vm_offset_t address, uint32_t value)
+{
+ __asm__ volatile ("str %w0, [%1]" : : "r" (value), "r" (address) : "memory");
+}
+
+struct block {
+ const char *name;
+ uint32_t phys, size;
+ vm_offset_t base;
+};
+
+static uint32_t
+get(struct block *b, const char *name, uint32_t offset)
+{
+ uint32_t value;
+
+ if (b->base == 0) {
+ b->base = ml_io_map(b->phys, b->size);
+ }
+ value = rd(b->base + offset);
+ say("sound: %s %s (%#x) = %#x\n", b->name, name, b->phys + offset, value);
+ return value;
+}
+
+static void
+put(struct block *b, const char *name, uint32_t offset, uint32_t value)
+{
+ if (b->base == 0) {
+ b->base = ml_io_map(b->phys, b->size);
+ }
+ say("sound: about to write %s %s at %#x: %#x\n", b->name, name, b->phys + offset, value);
+ snprintf(last_write, sizeof(last_write), "wrote %#x to %s %s at %#x", value, b->name, name, b->phys + offset);
+ wr(b->base + offset, value);
+}
+
+/* ---- the TDM pins ------------------------------------------------------------------------------------- */
+
+static struct block tlmm = { "pin controller", 0x0f100000, 0x100000 };
+#define GPIO_CFG(n) (0x1000u * (n)) /* [1:0] pull, [5:2] function, [8:6] drive (mA / 2 - 1), [9] output */
+#define GPIO_IO(n) (0x1000u * (n) + 4) /* bit 0 in, bit 1 out */
+#define CFG_MI2S0 (1u << 2)
+#define CFG_8MA (3u << 6)
+#define CFG_OUTPUT (1u << 9)
+
+static const struct {
+ unsigned pin;
+ const char *name;
+ uint32_t cfg, io; /* Android's active state */
+} tdm_pins[] = {
+ { 97, "gpio97 (bit clock)", CFG_MI2S0 | CFG_8MA | CFG_OUTPUT, 2 },
+ { 100, "gpio100 (frame sync)", CFG_MI2S0 | CFG_8MA | CFG_OUTPUT, 2 },
+ { 98, "gpio98 (data in)", CFG_MI2S0 | CFG_8MA, 0 },
+ { 99, "gpio99 (data out)", CFG_MI2S0 | CFG_8MA, 0 },
+};
+#define TDM_PINS (sizeof(tdm_pins) / sizeof(tdm_pins[0]))
+static uint32_t found_cfg[TDM_PINS], found_io[TDM_PINS];
+static bool pins_taken;
+
+static void
+pins_on(void)
+{
+ for (unsigned i = 0; i < TDM_PINS; i++) {
+ found_cfg[i] = get(&tlmm, tdm_pins[i].name, GPIO_CFG(tdm_pins[i].pin));
+ found_io[i] = get(&tlmm, tdm_pins[i].name, GPIO_IO(tdm_pins[i].pin));
+ }
+ pins_taken = true;
+ for (unsigned i = 0; i < TDM_PINS; i++) {
+ put(&tlmm, tdm_pins[i].name, GPIO_IO(tdm_pins[i].pin), tdm_pins[i].io);
+ put(&tlmm, tdm_pins[i].name, GPIO_CFG(tdm_pins[i].pin), tdm_pins[i].cfg);
+ }
+}
+
+static void
+pins_off(void)
+{
+ if (!pins_taken) {
+ return;
+ }
+ for (unsigned i = 0; i < TDM_PINS; i++) {
+ put(&tlmm, tdm_pins[i].name, GPIO_CFG(tdm_pins[i].pin), found_cfg[i]);
+ put(&tlmm, tdm_pins[i].name, GPIO_IO(tdm_pins[i].pin), found_io[i] & 2);
+ get(&tlmm, tdm_pins[i].name, GPIO_CFG(tdm_pins[i].pin));
+ }
+ pins_taken = false;
+}
+
+/* Whether a pin toggles: read many times as fast as it goes. */
+static void
+pin_activity(unsigned pin, const char *name, uint32_t *changes, uint32_t *ones)
+{
+ uint32_t last = rd(tlmm.base + GPIO_IO(pin)) & 1, reads = 20000;
+ uint64_t began = now_us();
+
+ *changes = *ones = 0;
+ for (uint32_t i = 0; i < reads; i++) {
+ uint32_t now = rd(tlmm.base + GPIO_IO(pin)) & 1;
+
+ *changes += now != last;
+ *ones += now;
+ last = now;
+ }
+ say("sound: %s: %u changes and %u ones in %u reads (%llu us)\n", name, *changes, *ones, reads, now_us() - began);
+}
+
+/* ---- APR ------------------------------------------------------------------------------------------- */
+
+#define APR_SVC_AFE 4
+#define APR_SVC_ASM 7
+#define APR_SVC_ADM 8
+#define APR_BASIC_RSP_RESULT 0x000110e8u
+#define APR_WAIT_MS 1000
+
+static const char *
+dsp_error(uint32_t status)
+{
+ static const char *const names[] = { "ok", "failed", "bad parameter", "unsupported", "version", "unexpected", "panic",
+ "no resource", "bad handle", "already", "not ready", "pending", "busy", "aborted",
+ "preempted", "continue", "immediate", "not implemented", "need more", "no memory",
+ "not there" };
+
+ return status < sizeof(names) / sizeof(names[0]) ? names[status] : "an error this does not know";
+}
+
+/*
+ * One command, its answer waited for: true if the answer is the basic one with status 0, or the
+ * opcode `wanted' (then in *answer).
+ */
+static bool
+command(const char *what, uint8_t service, uint16_t port, uint32_t opcode, const void *payload, uint32_t length, uint32_t wanted,
+ struct redwood_apr_answer *answer)
+{
+ struct redwood_apr_answer local;
+
+ if (answer == NULL) {
+ answer = &local;
+ }
+ snprintf(last_write, sizeof(last_write), "sent %s (opcode %#x)", what, opcode);
+ if (!redwood_adsp_apr(service, port, 0, opcode, payload, length, APR_WAIT_MS, answer)) {
+ say("sound: %s (opcode %#x to service %u, port %#x): NO ANSWER\n", what, opcode, service, port);
+ return false;
+ }
+ if (answer->opcode == APR_BASIC_RSP_RESULT && answer->words[0] == opcode) {
+ say("sound: %s: %s%s\n", what, answer->words[1] == 0 ? "done" : "REFUSED: ", answer->words[1] == 0 ? "" :
+ dsp_error(answer->words[1]));
+ return answer->words[1] == 0 && wanted == 0;
+ }
+ if (wanted != 0 && answer->opcode == wanted) {
+ return true;
+ }
+ say("sound: %s: an answer not expected: opcode %#x, %u bytes: %#x %#x\n", what, answer->opcode, answer->length,
+ answer->words[0], answer->words[1]);
+ return false;
+}
+
+/* ---- AFE: the port ---------------------------------------------------------------------------------- */
+
+#define AFE_PORT_CMD_DEVICE_START 0x000100e5u
+#define AFE_PORT_CMD_DEVICE_STOP 0x000100e6u
+#define AFE_PORT_CMD_SET_PARAM_V2 0x000100efu
+#define AFE_SVC_CMD_SET_PARAM 0x000100f3u
+#define AFE_MODULE_AUDIO_DEV_INTERFACE 0x0001020cu
+#define AFE_PARAM_ID_TDM_CONFIG 0x0001029du
+#define AFE_MODULE_TDM 0x0001028au
+#define AFE_PARAM_ID_PORT_SLOT_MAPPING_CONFIG 0x00010297u
+#define AFE_MODULE_GROUP_DEVICE 0x00010254u
+#define AFE_PARAM_ID_GROUP_DEVICE_ENABLE 0x00010256u
+#define AFE_PARAM_ID_GROUP_DEVICE_TDM_CONFIG 0x0001029eu
+#define AFE_MODULE_CLOCK_SET 0x0001028fu
+#define AFE_PARAM_ID_CLOCK_SET 0x00010290u
+
+#define PORT 0x9000 /* PRI_TDM_RX_0 */
+#define GROUP 0x9100 /* PRI_TDM_RX */
+#define GROUP_OTHER_PORT 0x9002
+#define PORT_INVALID 0xffff
+#define CLOCK_PRI_TDM_IBIT 0x200
+#define CLOCK_INVERT_COUPLE_NO 4
+#define RATE 48000
+#define SLOTS 2
+#define SLOT_BITS 32
+#define PORT_BITS 32 /* the mixer path's S32_LE */
+
+struct afe_param {
+ uint32_t module, param;
+ uint16_t size, reserved;
+} __attribute__((packed));
+
+struct afe_clock_set {
+ uint32_t version, id, hz;
+ uint16_t attribute, root;
+ uint32_t enable;
+} __attribute__((packed));
+
+struct afe_group_tdm {
+ uint32_t version;
+ uint16_t group, reserved;
+ uint16_t ports[8];
+ uint32_t channels, rate, bits;
+ uint16_t slots, slot_bits;
+ uint32_t slot_mask;
+} __attribute__((packed));
+
+struct afe_group_enable {
+ uint16_t group, enable;
+} __attribute__((packed));
+
+struct afe_tdm {
+ uint32_t version, channels, rate, bits;
+ uint16_t data_format, sync_mode, sync_source, slots, data_out, invert_sync, data_delay, slot_bits;
+ uint32_t slot_mask;
+} __attribute__((packed));
+
+struct afe_slot_mapping {
+ uint32_t version;
+ uint16_t channels, bits;
+ uint32_t align;
+ uint16_t offsets[8];
+} __attribute__((packed));
+
+/* A parameter for the AFE as a whole (its clocks, its groups): in the packet, not in shared memory. */
+static bool
+afe_service_param(const char *what, uint32_t module, uint32_t param, const void *data, uint16_t size)
+{
+ uint8_t packet[16 + sizeof(struct afe_param) + 64];
+ uint32_t *head = (uint32_t *)packet;
+ struct afe_param *p = (struct afe_param *)(packet + 16);
+
+ bzero(packet, sizeof(packet));
+ head[0] = (uint32_t)sizeof(*p) + size; /* payload size; address 0 and handle 0: in band */
+ p->module = module;
+ p->param = param;
+ p->size = size;
+ memcpy(packet + 16 + sizeof(*p), data, size);
+ return command(what, APR_SVC_AFE, 0, AFE_SVC_CMD_SET_PARAM, packet, 16 + (uint32_t)sizeof(*p) + size, 0, NULL);
+}
+
+/* A parameter of the port. */
+static bool
+afe_port_param(const char *what, uint32_t module, uint32_t param, const void *data, uint16_t size)
+{
+ uint8_t packet[16 + sizeof(struct afe_param) + 64];
+ struct afe_param *p = (struct afe_param *)(packet + 16);
+
+ bzero(packet, sizeof(packet));
+ *(uint16_t *)packet = PORT;
+ *(uint16_t *)(packet + 2) = (uint16_t)(sizeof(*p) + size);
+ p->module = module;
+ p->param = param;
+ p->size = size;
+ memcpy(packet + 16 + sizeof(*p), data, size);
+ return command(what, APR_SVC_AFE, 0, AFE_PORT_CMD_SET_PARAM_V2, packet, 16 + (uint32_t)sizeof(*p) + size, 0, NULL);
+}
+
+static bool clock_on, group_on, port_on;
+
+static bool
+afe_clock(bool on)
+{
+ struct afe_clock_set clock = { 1, CLOCK_PRI_TDM_IBIT, RATE * SLOT_BITS * SLOTS, CLOCK_INVERT_COUPLE_NO, 0, on };
+
+ return afe_service_param(on ? "the TDM bit clock (0x200) at 3.072 MHz, on" : "the TDM bit clock, off", AFE_MODULE_CLOCK_SET,
+ AFE_PARAM_ID_CLOCK_SET, &clock, sizeof(clock));
+}
+
+static bool
+afe_on(void)
+{
+ struct afe_group_tdm group = {
+ .version = 1, .group = GROUP, .ports = { PORT, GROUP_OTHER_PORT, PORT_INVALID, PORT_INVALID, PORT_INVALID,
+ PORT_INVALID, PORT_INVALID, PORT_INVALID },
+ .channels = SLOTS, .rate = RATE, .bits = SLOT_BITS, .slots = SLOTS, .slot_bits = SLOT_BITS, .slot_mask = 3,
+ };
+ struct afe_group_enable enable = { GROUP, 1 };
+ struct afe_tdm tdm = {
+ .version = 1, .channels = 2, .rate = RATE, .bits = PORT_BITS, .data_format = 0, .sync_mode = 0, .sync_source = 1,
+ .slots = SLOTS, .data_out = 0, .invert_sync = 1, .data_delay = 1, .slot_bits = SLOT_BITS, .slot_mask = 3,
+ };
+ struct afe_slot_mapping mapping = { .version = 1, .channels = 2, .bits = PORT_BITS, .align = 0,
+ .offsets = { 0, 4, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff } };
+ uint16_t start[2] = { PORT, 0 };
+
+ announce("the DSP is asked for the TDM interface's bit clock, the group, the port and its start (AFE)");
+ clock_on = afe_clock(true);
+ if (!clock_on) {
+ return false;
+ }
+ group_on = afe_service_param("the group 0x9100: ports 0x9000 0x9002, 2 slots of 32 bits, 48 kHz", AFE_MODULE_GROUP_DEVICE,
+ AFE_PARAM_ID_GROUP_DEVICE_TDM_CONFIG, &group, sizeof(group)) &&
+ afe_service_param("the group 0x9100, on", AFE_MODULE_GROUP_DEVICE, AFE_PARAM_ID_GROUP_DEVICE_ENABLE, &enable,
+ sizeof(enable));
+ if (!group_on) {
+ return false;
+ }
+ if (!afe_port_param("the port 0x9000: 2 channels of 32 bits at 48 kHz in 2 slots, sync 0 1, inverted, delay 1",
+ AFE_MODULE_AUDIO_DEV_INTERFACE, AFE_PARAM_ID_TDM_CONFIG, &tdm, sizeof(tdm)) ||
+ !afe_port_param("the port's slots: channels at bytes 0 and 4", AFE_MODULE_TDM, AFE_PARAM_ID_PORT_SLOT_MAPPING_CONFIG,
+ &mapping, sizeof(mapping))) {
+ return false;
+ }
+ port_on = command("the port 0x9000, started", APR_SVC_AFE, 0, AFE_PORT_CMD_DEVICE_START, start, sizeof(start), 0, NULL);
+ return port_on;
+}
+
+static void
+afe_off(void)
+{
+ uint16_t stop[2] = { PORT, 0 };
+ struct afe_group_enable disable = { GROUP, 0 };
+
+ if (port_on) {
+ command("the port 0x9000, stopped", APR_SVC_AFE, 0, AFE_PORT_CMD_DEVICE_STOP, stop, sizeof(stop), 0, NULL);
+ port_on = false;
+ }
+ if (group_on) {
+ afe_service_param("the group 0x9100, off", AFE_MODULE_GROUP_DEVICE, AFE_PARAM_ID_GROUP_DEVICE_ENABLE, &disable,
+ sizeof(disable));
+ group_on = false;
+ }
+ if (clock_on) {
+ afe_clock(false);
+ clock_on = false;
+ }
+}
+
+/* ---- the DSP's view of our memory: stream 0x1801 of the SMMU ------------------------------------------- */
+
+static struct block apps_smmu = { "apps smmu", 0x15000000, 0x2000 };
+static struct block apps_smmu_second = { "apps smmu", 0, 0x1000 }; /* the second page: a word per context */
+static struct block apps_smmu_context = { "apps smmu, the audio context", 0, 0x1000 };
+#define SMMU_SCR0 0x000
+#define SMMU_IDR0 0x020
+#define SMMU_IDR1 0x024
+#define SMMU_SGFSR 0x048
+#define SMMU_SGFSYNR1 0x054
+#define SMMU_SMR(n) (0x800 + 4 * (n)) /* bit 31 valid, [30:16] mask, [14:0] stream */
+#define SMMU_S2CR(n) (0xc00 + 4 * (n)) /* [17:16] 0 translate 1 bypass 2 fault, [7:0] context */
+#define SMMU_CBAR(n) (4 * (n))
+#define SMMU_CBAR_STAGE_1 (1u << 16 | 3u << 8 | 0xfu << 12)
+#define SMMU_CBA2R(n) (0x800 + 4 * (n))
+#define SMMU_CBA2R_64_BIT 1
+#define SMMU_CB_SCTLR 0x00
+#define SMMU_CB_TCR2 0x10
+#define SMMU_CB_TTBR0 0x20
+#define SMMU_CB_TTBR1 0x28
+#define SMMU_CB_TCR 0x30
+#define SMMU_CB_MAIR0 0x38
+#define SMMU_CB_MAIR1 0x3c
+#define SMMU_CB_FSR 0x58
+#define SMMU_CB_FAR 0x60
+#define SMMU_CB_FSYNR0 0x68
+#define SMMU_CB_TLBIASID 0x610
+#define SMMU_CB_TLBSYNC 0x7f0
+#define SMMU_CB_TLBSTATUS 0x7f4
+#define SMMU_SCTLR_ON (1u << 0 | 1u << 1 | 1u << 2 | 1u << 5 | 1u << 8 | 1u << 12)
+#define SMMU_TCR_39_BITS (25u | 1u << 8 | 1u << 10 | 3u << 12 | 1u << 23)
+#define SMMU_TCR2 (1u | 1u << 4 | 7u << 15)
+#define SMMU_MAIR0 0xf404ff44
+#define SMMU_FSR_ALL 0xc00001fe
+#define PTE_ADDRESS 0x0000fffffffff000ull
+#define AUDIO_PTE (3ull | 1ull << 6 | 2ull << 8 | 1ull << 10 | 1ull << 11) /* as redwood_wifi.c's */
+
+#define AUDIO_STREAM 0x1801
+#define AUDIO_ADDRESSES 0x10000000ull /* dt: qcom,iommu-dma-addr-pool of qcom,msm-audio-ion */
+#define AUDIO_STREAM_BITS (1ull << 32) /* the stream's low bits (0x1801 & 0xf), where the DSP takes them from */
+
+#define PERIODS 8
+#define PERIOD_FRAMES 960 /* 20 ms */
+#define PERIOD_BYTES (PERIOD_FRAMES * 4)
+#define BUFFER_BYTES (PERIODS * 4096) /* a page each */
+
+static struct {
+ bool found, on, passed; /* passed: the boot chain lets the stream through untranslated */
+ uint32_t page, pages, match, context, old_smr, old_s2cr, old_sctlr;
+ vm_offset_t tables; /* three of 4K: the root, one of the second level, one of the third */
+} space;
+static vm_offset_t buffer; /* BUFFER_BYTES of ours, the periods */
+static uint64_t buffer_address; /* as the DSP is to know it */
+
+static bool
+space_find(void)
+{
+ bool used[256] = { false };
+ uint32_t scr0 = get(&apps_smmu, "scr0", SMMU_SCR0), idr0 = get(&apps_smmu, "idr0", SMMU_IDR0);
+ uint32_t idr1 = get(&apps_smmu, "idr1", SMMU_IDR1), matches = idr0 & 0xff, contexts = idr1 & 0xff;
+
+ if (scr0 & 1u << 3) {
+ say("sound: this SMMU numbers its streams with 16 bits, which nothing here is written for\n");
+ return false;
+ }
+ space.page = idr1 >> 31 ? 0x10000 : 0x1000;
+ space.pages = 2u << (idr1 >> 28 & 7);
+ if (2 * space.pages * space.page != 0x100000) {
+ say("sound: the SMMU says it has 2 x %u pages of %#x bytes, not a megabyte: its contexts are not looked for\n",
+ space.pages, space.page);
+ return false;
+ }
+ space.match = ~0u;
+ for (uint32_t n = 0; n < matches && SMMU_SMR(n) < 0xc00; n++) {
+ uint32_t smr = rd(apps_smmu.base + SMMU_SMR(n)), s2cr = rd(apps_smmu.base + SMMU_S2CR(n));
+ uint32_t stream = smr & 0x7fff, mask = smr >> 16 & 0x7fff;
+
+ if (smr >> 31) {
+ used[s2cr & 0xff] = true;
+ if (((stream ^ AUDIO_STREAM) & ~mask) == 0) {
+ say("sound: match register %u covers the audio stream already: stream %#x mask %#x, s2cr %#x\n", n,
+ stream, mask, s2cr);
+ if ((s2cr >> 16 & 3) == 1) {
+ space.passed = true;
+ return true;
+ }
+ say("sound: ... and does not let it through untranslated: it is somebody's, and is left alone\n");
+ return false;
+ }
+ } else if (space.match == ~0u) {
+ space.match = n;
+ space.old_smr = smr;
+ space.old_s2cr = s2cr;
+ }
+ }
+ for (space.context = 0; space.context < contexts && used[space.context]; space.context++) {
+ }
+ if (space.match == ~0u || space.context >= contexts) {
+ say("sound: the SMMU has no match register or no context left\n");
+ return false;
+ }
+ apps_smmu_second.phys = apps_smmu.phys + space.page;
+ apps_smmu_context.phys = apps_smmu.phys + (space.pages + space.context) * space.page;
+ say("sound: the boot chain has set nothing up for stream %#x; free: match register %u (smr %#x, s2cr %#x) and context %u, at "
+ "%#x\n", AUDIO_STREAM, space.match, space.old_smr, space.old_s2cr, space.context, apps_smmu_context.phys);
+ space.old_sctlr = get(&apps_smmu_context, "sctlr", SMMU_CB_SCTLR);
+ if (space.old_sctlr & 1) {
+ say("sound: CONTEXT %u IS SWITCHED ON although no stream is sent through it: it is somebody's, and is left alone\n",
+ space.context);
+ return false;
+ }
+ space.found = true;
+ return true;
+}
+
+static void
+space_faults(void)
+{
+ uint32_t status, global;
+
+ if (!space.on) {
+ return;
+ }
+ status = rd(apps_smmu_context.base + SMMU_CB_FSR);
+ global = rd(apps_smmu.base + SMMU_SGFSR);
+ if ((status & SMMU_FSR_ALL) == 0 && global == 0) {
+ say("sound: the SMMU has refused the DSP nothing (context %u: fsr %#x; sgfsr 0)\n", space.context, status);
+ return;
+ }
+ say("sound: THE SMMU HAS REFUSED A REQUEST: context %u: status %#x, address %#llx, syndrome %#x; the SMMU as a whole: status "
+ "%#x, stream %#x\n", space.context, status, (uint64_t)rd(apps_smmu_context.base + SMMU_CB_FAR + 4) << 32 |
+ rd(apps_smmu_context.base + SMMU_CB_FAR), rd(apps_smmu_context.base + SMMU_CB_FSYNR0), global,
+ rd(apps_smmu.base + SMMU_SGFSYNR1));
+}
+
+/* Our buffer behind the DSP's addresses from AUDIO_ADDRESSES on, through a context of ours. */
+static bool
+space_on(void)
+{
+ uint64_t *root, *second, *third, table_root;
+ uint32_t smr = SMMU_SMR(space.match), s2cr = SMMU_S2CR(space.match), sees = 1u << 31 | AUDIO_STREAM;
+
+ if (kmem_alloc(kernel_map, &space.tables, 3 * 4096, KMA_KOBJECT | KMA_ZERO | KMA_DATA, VM_KERN_MEMORY_IOKIT) != KERN_SUCCESS) {
+ return false;
+ }
+ root = (uint64_t *)space.tables;
+ second = (uint64_t *)(space.tables + 4096);
+ third = (uint64_t *)(space.tables + 8192);
+ root[AUDIO_ADDRESSES >> 30 & 0x1ff] = kvtophys((vm_offset_t)second) | 3;
+ second[AUDIO_ADDRESSES >> 21 & 0x1ff] = kvtophys((vm_offset_t)third) | 3;
+ for (unsigned page = 0; page < BUFFER_BYTES / 4096; page++) {
+ third[(AUDIO_ADDRESSES >> 12 & 0x1ff) + page] = kvtophys(buffer + 4096 * page) | AUDIO_PTE;
+ }
+ for (vm_offset_t line = space.tables; line < space.tables + 3 * 4096; line += 64) {
+ __asm__ volatile ("dc civac, %0" : : "r" (line));
+ }
+ __asm__ volatile ("dsb sy");
+ table_root = kvtophys(space.tables) | (uint64_t)space.context << 48;
+ say("sound: THE SMMU IS ABOUT TO BE WRITTEN: context %u gets page tables of ours (root %#llx) for the %u KB of the periods "
+ "at %#llx, and match register %u sends stream %#x through it\n", space.context, table_root & PTE_ADDRESS,
+ BUFFER_BYTES / 1024, AUDIO_ADDRESSES, space.match, AUDIO_STREAM);
+ if (pause_ms) {
+ sleep_ms(pause_ms);
+ }
+ put(&apps_smmu_context, "sctlr", SMMU_CB_SCTLR, 0);
+ put(&apps_smmu_second, "cba2r", SMMU_CBA2R(space.context), SMMU_CBA2R_64_BIT);
+ put(&apps_smmu_second, "cbar", SMMU_CBAR(space.context), SMMU_CBAR_STAGE_1);
+ put(&apps_smmu_context, "tcr2", SMMU_CB_TCR2, SMMU_TCR2);
+ put(&apps_smmu_context, "tcr", SMMU_CB_TCR, SMMU_TCR_39_BITS);
+ put(&apps_smmu_context, "ttbr0, low", SMMU_CB_TTBR0, (uint32_t)table_root);
+ put(&apps_smmu_context, "ttbr0, high", SMMU_CB_TTBR0 + 4, (uint32_t)(table_root >> 32));
+ put(&apps_smmu_context, "ttbr1, low", SMMU_CB_TTBR1, 0);
+ put(&apps_smmu_context, "ttbr1, high", SMMU_CB_TTBR1 + 4, 0);
+ put(&apps_smmu_context, "mair0", SMMU_CB_MAIR0, SMMU_MAIR0);
+ put(&apps_smmu_context, "mair1", SMMU_CB_MAIR1, 0);
+ put(&apps_smmu_context, "fsr", SMMU_CB_FSR, SMMU_FSR_ALL);
+ put(&apps_smmu_context, "tlbiasid", SMMU_CB_TLBIASID, space.context);
+ put(&apps_smmu_context, "tlbsync", SMMU_CB_TLBSYNC, 1);
+ for (unsigned ms = 0; rd(apps_smmu_context.base + SMMU_CB_TLBSTATUS) & 1; ms++) {
+ if (ms == 100) {
+ say("sound: the SMMU does not finish forgetting old translations\n");
+ return false;
+ }
+ sleep_ms(1);
+ }
+ put(&apps_smmu_context, "sctlr", SMMU_CB_SCTLR, SMMU_SCTLR_ON);
+ space.on = true;
+ put(&apps_smmu, "s2cr", s2cr, space.context);
+ put(&apps_smmu, "smr", smr, sees);
+ if (get(&apps_smmu, "smr", smr) != sees || (get(&apps_smmu, "s2cr", s2cr) & 0x300ff) != space.context ||
+ !(get(&apps_smmu_context, "sctlr", SMMU_CB_SCTLR) & 1) ||
+ get(&apps_smmu_context, "ttbr0, low", SMMU_CB_TTBR0) != (uint32_t)table_root) {
+ say("sound: THE SMMU DID NOT TAKE WHAT WAS WRITTEN: stream %#x is not going through context %u\n", AUDIO_STREAM,
+ space.context);
+ return false;
+ }
+ say("sound: THE AUDIO STREAM GOES THROUGH CONTEXT %u of the SMMU, with our page tables\n", space.context);
+ return true;
+}
+
+static void
+space_off(void)
+{
+ if (!space.on) {
+ return;
+ }
+ space_faults();
+ say("sound: the audio stream and context %u of the SMMU are put back as they were found\n", space.context);
+ put(&apps_smmu, "smr", SMMU_SMR(space.match), space.old_smr);
+ put(&apps_smmu, "s2cr", SMMU_S2CR(space.match), space.old_s2cr);
+ put(&apps_smmu_context, "sctlr", SMMU_CB_SCTLR, space.old_sctlr);
+ get(&apps_smmu, "smr", SMMU_SMR(space.match));
+ space.on = false;
+}
+
+/* ---- ADM and ASM: the path and the stream --------------------------------------------------------------- */
+
+#define ADM_CMD_DEVICE_OPEN_V5 0x00010326u
+#define ADM_CMDRSP_DEVICE_OPEN_V5 0x00010329u
+#define ADM_CMD_DEVICE_CLOSE_V5 0x00010327u
+#define ADM_CMD_MATRIX_MAP_ROUTINGS_V5 0x00010325u
+#define ADM_PATH_PLAYBACK 1
+#define ADM_MATRIX_AUDIO_RX 0
+#define ADM_TOPOLOGY_NONE 0x00010312u
+#define ADM_BITS 24
+
+#define ASM_CMD_SHARED_MEM_MAP_REGIONS 0x00010d92u
+#define ASM_CMDRSP_SHARED_MEM_MAP_REGIONS 0x00010d93u
+#define ASM_CMD_SHARED_MEM_UNMAP_REGIONS 0x00010d94u
+#define ASM_STREAM_CMD_OPEN_WRITE_V3 0x00010db3u
+#define ASM_DATA_CMD_MEDIA_FMT_UPDATE_V2 0x00010d98u
+#define ASM_SESSION_CMD_RUN_V2 0x00010daau
+#define ASM_DATA_CMD_WRITE_V2 0x00010dabu
+#define ASM_DATA_EVENT_WRITE_DONE_V2 0x00010d99u
+#define ASM_SESSION_EVENT_RX_UNDERFLOW 0x00010c17u
+#define ASM_STREAM_CMD_CLOSE 0x00010bcdu
+#define ASM_TOPOLOGY_NONE 0x00010c68u
+#define ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2 0x00010da5u
+#define ASM_SHMEM_4K_POOL 3
+#define SESSION 1
+#define STREAM_PORT (SESSION << 8 | 1)
+#define WRITE_TOKEN 0x80000000u /* | the period: what a write's "done" carries back */
+#define PCM_CHANNEL_FL 1
+#define PCM_CHANNEL_FR 2
+
+static bool mapped, copp_open, stream_open;
+static uint32_t map_handle, copp;
+static volatile uint32_t returned; /* the periods the DSP has said it is done with (a bit each) */
+static volatile uint32_t written_done, underflows, write_errors;
+
+/* The DSP's events: the "done" of every write, and underflows. On the link's thread. */
+static bool
+events(uint8_t service, __unused uint16_t port, uint32_t opcode, uint32_t token, const uint32_t *payload, uint32_t length)
+{
+ if (service != APR_SVC_ASM) {
+ return false;
+ }
+ if (opcode == ASM_DATA_EVENT_WRITE_DONE_V2 && (token & WRITE_TOKEN)) {
+ if (length >= 16 && payload[3] != 0) {
+ OSIncrementAtomic((volatile SInt32 *)&write_errors);
+ }
+ OSIncrementAtomic((volatile SInt32 *)&written_done);
+ OSBitOrAtomic(1u << (token & 31), &returned);
+ return true;
+ }
+ if (opcode == APR_BASIC_RSP_RESULT && (token & WRITE_TOKEN)) {
+ /* (a write the DSP refused outright: it answers it as a command) */
+ OSIncrementAtomic((volatile SInt32 *)&write_errors);
+ OSIncrementAtomic((volatile SInt32 *)&written_done);
+ OSBitOrAtomic(1u << (token & 31), &returned);
+ return true;
+ }
+ if (opcode == ASM_SESSION_EVENT_RX_UNDERFLOW) {
+ OSIncrementAtomic((volatile SInt32 *)&underflows);
+ return true;
+ }
+ return false;
+}
+
+static bool
+stream_on(void)
+{
+ struct {
+ uint16_t pool, regions;
+ uint32_t property;
+ uint32_t low, high, size;
+ } __attribute__((packed)) map = { ASM_SHMEM_4K_POOL, 1, 0, (uint32_t)buffer_address, (uint32_t)(buffer_address >> 32),
+ BUFFER_BYTES };
+ struct {
+ uint16_t flags, mode, endpoint1, endpoint2;
+ uint32_t topology;
+ uint16_t channels, bits;
+ uint32_t rate;
+ uint8_t map[8];
+ } __attribute__((packed)) open = { 0, ADM_PATH_PLAYBACK, PORT, 0xffff, ADM_TOPOLOGY_NONE, 2, ADM_BITS, RATE,
+ { PCM_CHANNEL_FL, PCM_CHANNEL_FR } };
+ struct {
+ uint32_t matrix, sessions;
+ uint16_t session, copps;
+ uint16_t copp[2];
+ } __attribute__((packed)) route = { ADM_MATRIX_AUDIO_RX, 1, SESSION, 1, { 0, 0 } };
+ struct {
+ uint32_t flags;
+ uint16_t sink, bits;
+ uint32_t topology, format;
+ } __attribute__((packed)) write = { 0, 0, 16, ASM_TOPOLOGY_NONE, ASM_MEDIA_FMT_MULTI_CHANNEL_PCM_V2 };
+ struct {
+ uint32_t size;
+ uint16_t channels, bits;
+ uint32_t rate;
+ uint16_t is_signed, reserved;
+ uint8_t map[8];
+ } __attribute__((packed)) format = { 20, 2, 16, RATE, 1, 0, { PCM_CHANNEL_FL, PCM_CHANNEL_FR } };
+ uint32_t run[3] = { 0, 0, 0 };
+ struct redwood_apr_answer answer;
+
+ announce("the DSP is given our periods (ASM), a device path to the port (ADM) and a stream routed to it (ASM)");
+ if (!command("our periods, mapped for the DSP", APR_SVC_ASM, 0, ASM_CMD_SHARED_MEM_MAP_REGIONS, &map, sizeof(map),
+ ASM_CMDRSP_SHARED_MEM_MAP_REGIONS, &answer)) {
+ return false;
+ }
+ mapped = true;
+ map_handle = answer.words[0];
+ say("sound: our %u KB at %#llx are the DSP's handle %#x\n", BUFFER_BYTES / 1024, buffer_address, map_handle);
+ if (!command("a device path to the port: playback, no processing, 2 channels of 24 bits at 48 kHz", APR_SVC_ADM, PORT,
+ ADM_CMD_DEVICE_OPEN_V5, &open, sizeof(open), ADM_CMDRSP_DEVICE_OPEN_V5, &answer)) {
+ return false;
+ }
+ if (answer.words[0] != 0) {
+ say("sound: the device path: REFUSED: %s\n", dsp_error(answer.words[0]));
+ return false;
+ }
+ copp_open = true;
+ copp = answer.words[1] & 0xffff; /* (the upper half is reserved) */
+ route.copp[0] = (uint16_t)copp;
+ say("sound: the device path is open: COPP %u\n", copp);
+ if (!command("the stream, opened for writing: 16-bit linear PCM, no processing", APR_SVC_ASM, STREAM_PORT,
+ ASM_STREAM_CMD_OPEN_WRITE_V3, &write, sizeof(write), 0, NULL)) {
+ return false;
+ }
+ stream_open = true;
+ return command("session 1 routed to the device path", APR_SVC_ADM, 0, ADM_CMD_MATRIX_MAP_ROUTINGS_V5, &route, sizeof(route),
+ 0, NULL) &&
+ command("the stream's format: 2 channels of 16 bits at 48 kHz, left and right", APR_SVC_ASM, STREAM_PORT,
+ ASM_DATA_CMD_MEDIA_FMT_UPDATE_V2, &format, sizeof(format), 0, NULL) &&
+ command("the session, run", APR_SVC_ASM, STREAM_PORT, ASM_SESSION_CMD_RUN_V2, run, sizeof(run), 0, NULL);
+}
+
+static void
+stream_off(void)
+{
+ uint32_t handle = map_handle;
+
+ if (stream_open) {
+ command("the stream, closed", APR_SVC_ASM, STREAM_PORT, ASM_STREAM_CMD_CLOSE, NULL, 0, 0, NULL);
+ stream_open = false;
+ }
+ if (copp_open) {
+ command("the device path, closed", APR_SVC_ADM, (uint16_t)copp, ADM_CMD_DEVICE_CLOSE_V5, NULL, 0, 0, NULL);
+ copp_open = false;
+ }
+ if (mapped) {
+ command("our periods, unmapped", APR_SVC_ASM, 0, ASM_CMD_SHARED_MEM_UNMAP_REGIONS, &handle, sizeof(handle), 0, NULL);
+ mapped = false;
+ }
+}
+
+/* ---- the test tone ----------------------------------------------------------------------------------- */
+
+/* 1 kHz at 48 kHz, -20 dBFS (a peak of 3277): one cycle */
+static const int16_t tone[48] = {
+ 0, 428, 848, 1254, 1638, 1995, 2317, 2600, 2838, 3028, 3165, 3249,
+ 3277, 3249, 3165, 3028, 2838, 2600, 2317, 1995, 1638, 1254, 848, 428,
+ 0, -428, -848, -1254, -1638, -1995, -2317, -2600, -2838, -3028, -3165, -3249,
+ -3277, -3249, -3165, -3028, -2838, -2600, -2317, -1995, -1638, -1254, -848, -428,
+};
+static uint32_t tone_at;
+
+static void
+period_fill(unsigned period, bool silent)
+{
+ int16_t *samples = (int16_t *)(buffer + 4096 * period);
+
+ for (unsigned frame = 0; frame < PERIOD_FRAMES; frame++) {
+ int16_t sample = silent ? 0 : tone[tone_at++ % 48];
+
+ samples[2 * frame] = sample;
+ samples[2 * frame + 1] = sample;
+ }
+ 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)); /* the DSP reads memory, not our caches */
+ }
+ __asm__ volatile ("dsb sy");
+}
+
+static bool
+period_write(unsigned period)
+{
+ uint32_t write[8] = { (uint32_t)(buffer_address + 4096 * period), (uint32_t)((buffer_address + 4096 * period) >> 32),
+ map_handle, PERIOD_BYTES, period, 0, 0, 0 };
+
+ return redwood_adsp_apr(APR_SVC_ASM, STREAM_PORT, WRITE_TOKEN | period, ASM_DATA_CMD_WRITE_V2, write, sizeof(write), 0, NULL);
+}
+
+/*
+ * The tone, written period after period as the DSP gives them back, for `ms'; then silence until
+ * the DSP has given every period back. What came back and how fast is said.
+ */
+static bool
+play(uint32_t ms, bool amplifiers)
+{
+ uint64_t began, last_look, ended;
+ uint32_t sent = 0, done_before = written_done, healthy_looks = 0;
+ bool ok = true, tone_over = false;
+
+ returned = 0;
+ tone_at = 0;
+ for (unsigned p = 0; p < PERIODS; p++) {
+ period_fill(p, false);
+ }
+ began = last_look = now_us();
+ for (unsigned p = 0; p < PERIODS; p++) {
+ if (!period_write(p)) {
+ say("sound: the write of period %u could not be sent\n", p);
+ return false;
+ }
+ sent++;
+ }
+ for (;;) {
+ uint32_t back = returned;
+ uint64_t now = now_us();
+
+ if (back != 0) {
+ OSBitAndAtomic(~back, &returned);
+ for (unsigned p = 0; p < PERIODS; p++) {
+ if (!(back & 1u << p) || tone_over) {
+ continue;
+ }
+ period_fill(p, false);
+ if (!period_write(p)) {
+ say("sound: the write of period %u could not be sent\n", p);
+ ok = false;
+ tone_over = true;
+ break;
+ }
+ sent++;
+ }
+ }
+ if (!tone_over && now - began >= ms * 1000ull) {
+ tone_over = true;
+ }
+ if (tone_over && written_done - done_before >= sent) {
+ break;
+ }
+ if (now - began > ms * 1000ull + 2000000) {
+ say("sound: THE DSP HAS NOT GIVEN EVERY PERIOD BACK 2 s after the end (%u of %u)\n", written_done - done_before,
+ sent);
+ ok = false;
+ break;
+ }
+ if (written_done == done_before && now - began > 1000000) {
+ say("sound: THE DSP HAS GIVEN NO PERIOD BACK IN A SECOND\n");
+ ok = false;
+ break;
+ }
+ if (amplifiers && now - last_look >= 200000) {
+ last_look = now;
+ healthy_looks++;
+ if (!redwood_speaker_healthy()) {
+ ok = false;
+ tone_over = true;
+ }
+ }
+ sleep_ms(2);
+ }
+ ended = now_us();
+ {
+ uint32_t done = written_done - done_before;
+ uint64_t frames = (uint64_t)done * PERIOD_FRAMES, us = ended - began;
+
+ say("sound: %u periods written, %u given back (%u with an error), %u underflows, in %llu ms: the DSP took %llu frames a "
+ "second%s\n", sent, done, write_errors, underflows, us / 1000, us ? frames * 1000000 / us : 0,
+ amplifiers ? "" : " (the amplifiers off: nothing to hear)");
+ if (amplifiers) {
+ say("sound: the amplifiers' status looked at %u times while it played\n", healthy_looks);
+ }
+ }
+ return ok;
+}
+
+/* ---- the whole ---------------------------------------------------------------------------------------- */
+
+static bool running, taken_down;
+
+static void
+take_down(void)
+{
+ lck_mtx_lock(&sound_lock);
+ if (running && !taken_down) {
+ taken_down = true;
+ redwood_speaker_stop();
+ stream_off();
+ afe_off();
+ pins_off();
+ lck_mtx_lock(&redwood_smmu_lock);
+ space_off();
+ lck_mtx_unlock(&redwood_smmu_lock);
+ redwood_adsp_apr_events(NULL);
+ say("sound: everything of the sound's is stopped and put back\n");
+ }
+ lck_mtx_unlock(&sound_lock);
+}
+
+static void
+sound_thread(__unused void *parameter, __unused wait_result_t result)
+{
+ const uint8_t *acf = NULL;
+ uint64_t acf_size = 0;
+ uint32_t changes, ones, sync_changes, sync_ones;
+ bool ok = false;
+
+ lck_mtx_lock(&sound_lock);
+ if (taken_down) {
+ lck_mtx_unlock(&sound_lock);
+ thread_terminate(current_thread());
+ }
+ say("sound: level %u: %s, for %u s\n", level, level == 1 ? "the speakers' TDM port" : level == 2 ?
+ "the port and a stream with a test tone, the amplifiers off" : "the port, a stream with a test tone, and the amplifiers",
+ seconds);
+ if (level >= 3) {
+ acf = redwood_adsp_fw_file("aw882xx_acf.bin", &acf_size);
+ if (acf == NULL) {
+ say("sound: no /fw/aw882xx_acf.bin: put the phone's /vendor/etc/aw882xx_acf.bin into fw-audio/ and run SYSTEM=1 "
+ "userland/build.sh\n");
+ goto out;
+ }
+ }
+ if (level >= 2) {
+ if (kmem_alloc(kernel_map, &buffer, BUFFER_BYTES, KMA_KOBJECT | KMA_ZERO | KMA_DATA, VM_KERN_MEMORY_IOKIT) !=
+ KERN_SUCCESS) {
+ say("sound: no memory for the periods\n");
+ goto out;
+ }
+ lck_mtx_lock(&redwood_smmu_lock);
+ ok = space_find() && (space.passed || space_on());
+ lck_mtx_unlock(&redwood_smmu_lock);
+ if (!ok) {
+ goto out;
+ }
+ ok = false;
+ buffer_address = space.passed ? (kvtophys(buffer) | AUDIO_STREAM_BITS) : (AUDIO_ADDRESSES | AUDIO_STREAM_BITS);
+ if (space.passed) {
+ for (unsigned page = 1; page < BUFFER_BYTES / 4096; page++) {
+ if (kvtophys(buffer + 4096 * page) != kvtophys(buffer) + 4096 * page) {
+ say("sound: the periods are not one piece of memory, and the stream is not translated\n");
+ goto out;
+ }
+ }
+ }
+ redwood_adsp_apr_events(events);
+ }
+ announce("the TDM pins (GPIO 97 to 100) to the interface, as Android's active state has them");
+ pins_on();
+ if (!afe_on()) {
+ goto out;
+ }
+ sleep_ms(20);
+ pin_activity(97, "the bit clock (gpio97)", &changes, &ones);
+ pin_activity(100, "the frame sync (gpio100)", &sync_changes, &sync_ones);
+ say("sound: %s\n", changes > 100 && sync_changes > 4 ? "THE TDM CLOCK AND FRAME SYNC RUN at the pins" :
+ "THE PINS DO NOT SHOW A RUNNING TDM CLOCK");
+ if (level == 1) {
+ sleep_ms(seconds * 1000);
+ ok = true;
+ goto out;
+ }
+ if (!stream_on()) {
+ goto out;
+ }
+ if (level >= 3) {
+ /* the clock runs (the port is started, the stream as well): the amplifiers can lock to it */
+ announce("the amplifiers, set up from Android's Music profile, then started at the lowest volume");
+ if (!redwood_speaker_prepare(acf, acf_size) || !redwood_speaker_start()) {
+ goto out;
+ }
+ }
+ /* (the amplifiers are faded in before the tone begins: they fade in on silence, and the tone starts at that level) */
+ if (level >= 3 && !redwood_speaker_volume(below)) {
+ goto out;
+ }
+ if (level >= 3) {
+ say("sound: THE TONE PLAYS NOW for %u s: 1 kHz at -20 dBFS, both speakers, %u.%03u dB under Android's level\n",
+ seconds, below / 8, below % 8 * 125);
+ }
+ say_when("the tone begins");
+ ok = play(seconds * 1000, level >= 3);
+ say_when("the tone has ended");
+ space_faults();
+out:
+ if (acf != NULL) {
+ redwood_adsp_fw_free(acf, acf_size);
+ }
+ lck_mtx_unlock(&sound_lock);
+ take_down();
+ say("sound: %s; last: %s\n", ok ? "LEVEL DONE" : "STOPPED SHORT", last_write);
+ thread_terminate(current_thread());
+}
+
+void
+redwood_sound_dsp_up(void)
+{
+ thread_t thread;
+
+ if (!PE_parse_boot_argn("sound", &level, sizeof(level)) || level == 0) {
+ return;
+ }
+ if (level > 3) {
+ level = 3;
+ }
+ 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));
+ if (level >= 2 && seconds > 3) {
+ seconds = 3; /* the test tone: three seconds at most */
+ }
+ running = true;
+ if (kernel_thread_start(sound_thread, NULL, &thread) != KERN_SUCCESS) {
+ running = false;
+ say("sound: no thread\n");
+ return;
+ }
+ thread_deallocate(thread);
+}
+
+void
+redwood_sound_dsp_down(void)
+{
+ if (running) {
+ take_down();
+ }
+}
+
+void
+redwood_sound_quiesce(void)
+{
+ redwood_speaker_quiesce();
+}
diff --git a/xnu/files/bsd/dev/redwood_speaker.c b/xnu/files/bsd/dev/redwood_speaker.c
index aeeaeb5..02bd7f8 100644
--- a/xnu/files/bsd/dev/redwood_speaker.c
+++ b/xnu/files/bsd/dev/redwood_speaker.c
@@ -1,55 +1,103 @@
/*
- * The speakers of the POCO X5 Pro (redwood): so far only a look at what is there.
- * Only with boot-arg speaker_probe=N: every address below belongs to this phone.
- * speaker_probe=1 reads registers and nothing else: pins, power (below)
- * speaker_probe=2 ... and asks the amplifiers who they are, for which two pins are
- * reconfigured for the time it takes (I2C, below)
- * NEITHER HAS BEEN RUN ON THE PHONE YET.
+ * The speakers of the POCO X5 Pro (redwood): their two amplifiers. Every address below belongs
+ * to this phone, and nothing here is touched unless a boot-arg asks for it.
*
- * Each of the phone's two speakers has an amplifier of its own, an Awinic AW882xx ("smart
- * PA"), which is set up over I2C (bus of the SoC's serial engine 3, GPIO 12 data and 13 clock;
- * addresses 0x34, the bottom speaker, and 0x35, the top one) and takes its samples from the
- * SoC's first I2S interface ("MI2S 0": GPIO 97 bit clock, 100 word select, 98 and 99 data).
- * That interface belongs to the audio subsystem (LPASS), which under Android is run by the
- * audio DSP: there, sound goes from the kernel to the DSP's firmware as messages, and the
- * firmware drives the interface. None of that is running here, and before anything is built
- * the questions are which amplifier it is and whether it is powered without Android.
+ * Each speaker has an amplifier of its own, an Awinic AW88261 (chip ID 0x2113, a "smart PA"),
+ * set up over I2C -- the bus of the SoC's serial engine 3, GPIO 12 data and 13 clock, on which
+ * Android's device tree and its running kernel have these two and nothing else -- and fed by
+ * the SoC's first TDM interface ("MI2S 0": GPIO 97 bit clock, 100 frame sync, 99 data out),
+ * which the audio DSP drives (redwood_sound.c). In Android's tree the amplifier at 0x35 is
+ * "sound-channel 0" and takes slot 0 of the frame (the left channel), the one at 0x34 is
+ * channel 1 and takes slot 1; neither has a reset pin.
*
- * pins how the firmware left the pins involved: their configuration and level are read
- * from the pin controller, nothing is written
- * power the names under which the audio subsystem's supplies can be asked for (read from
- * the command database the boot loader left in memory), and whether its bus clock
- * runs (one register of the global clock controller, read)
- * I2C register 0 (the chip ID) and three more of each amplifier, read through the two
- * pins driven by hand, open-drain: a pin is either pulled low or let go. This
- * WRITES the configuration of GPIO 12 and 13 (to "GPIO, pull-up", and the output
- * enable for every low bit) and puts back what was there before; if the bus is not
- * at rest when the pins are let go, nothing more is done. The amplifiers are only
- * read: the writes on the bus are their addresses and the numbers of the registers
- * to read. They stay in the power-down state they start in.
+ * Two uses:
*
- * (Whether the secure world would start the audio DSP for us cannot be asked without doing it:
- * its "is this image supported" answers no for every image, the GPU's included, which it then
- * authenticates and starts all the same -- see redwood_adreno.c.)
+ * speaker_probe=1 reads registers and nothing else: the pins, the power names (below)
+ * speaker_probe=2 ... and asks the amplifiers who they are (I2C, below)
*
- * Register layouts: Linux sound/soc/codecs/aw88261.c and aw88395/, drivers/pinctrl/qcom/
- * pinctrl-sc7280.c, drivers/clk/qcom/gcc-sc7280.c, drivers/soc/qcom/cmd-db.c, and the phone's
- * own device tree.
+ * redwood_speaker_prepare() and the rest (sys/redwood_audio.h), for boot-arg sound=3 of
+ * redwood_sound.c: the amplifiers set up and run exactly as Android's own driver does it
+ * (Xiaomi's redwood-s-oss kernel, techpack/audio/asoc/codecs/aw88263s_m20: aw882xx_device.c,
+ * aw882xx_init.c and aw882xx_pid_2113_reg.h; the phone runs its version 2.0.0), with the
+ * registers' values from Android's own configuration file -- /vendor/etc/aw882xx_acf.bin of
+ * the phone, which userland/build.sh puts into /fw of the system image from fw-audio/ and
+ * which is not in this repository. Its "Music" profile is what Android plays the speakers
+ * with (tinymix: aw_dev_0_prof, aw_dev_1_prof); 55 of its 57 registers read back from the
+ * idle chips under Android exactly as the file has them, and the other two as the driver
+ * leaves them (0x04 powered down and muted, 0x08 with the feedback off).
+ *
+ * What the driver does and this does the same way, per amplifier:
+ *
+ * prepare reads the chip ID and the four fuse registers; a soft reset (0x55aa into
+ * register 0); the profile's registers, every one but three as the file has them:
+ * 0x04 keeps the power-down, amplifier power-down and mute bits as they are and
+ * sets the mute of the power stage ("ULS"), 0x08 has the feedback off, and 0x05 (the
+ * volume) is turned down to the lowest, -90 dB, right after; 0x50 gets the value the
+ * driver works out from the fuses (8192 * (1000 + icalk) / (1000 + vcalk)), which for
+ * this phone's two chips is the value Android left in them
+ * start only while the TDM clock runs: power-down off, 2 ms, the PLL locked (status bits 0
+ * and 4); amplifier power-down off, 1 ms, the status as the driver wants it (bits 0, 4,
+ * 8, 9); the feedback on; the two mutes off; the interrupts read away; the volume
+ * stays at the lowest
+ * volume stepwise, 6 dB a step, to `below' eighths of a dB under Android's own level (the
+ * profile's 0x05, -2.1 dB, with Android's aw_dev_N_volume 0) and never above it
+ * stop the power stage muted, the volume stepped down to the lowest, muted, the feedback
+ * off, 1 ms, amplifier power-down, power-down
+ *
+ * Every write is said in the log and read back; a value that does not read back as written, a
+ * byte nobody acknowledges, or a fault in the status register (under-voltage, over-current of
+ * 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.
+ *
+ * I2C is done by hand: a pin is either pulled low or let go (and the pull-ups raise it), at 50
+ * kHz at most. For each register read or written the two pins are taken from the serial engine
+ * (function qup03) as GPIOs and given back as they were found right after.
+ *
+ * Register layouts: the files above, and Linux's sound/soc/codecs/aw88261.c; pins:
+ * drivers/pinctrl/qcom/pinctrl-yupik.c of the same kernel and the phone's own device tree.
*/
#include <kern/clock.h>
#include <kern/thread.h>
#include <libkern/libkern.h>
#include <mach/mach_types.h>
#include <pexpert/pexpert.h>
-#include <sys/redwood_audio.h>
#include <sys/systm.h>
+#include <sys/redwood_audio.h>
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);
+extern void loader_log_putc(char c);
static vm_offset_t tlmm, gcc, cmd_db;
static uint32_t probe_level;
+static bool leaving; /* on a panic's way out: nothing sleeps, nothing is said but to the loader */
+
+/* Every line to the loader's log as well: what is written to the amplifiers should be known even if the kernel dies. */
+static int say(const char *format, ...) __printflike(1, 2);
+
+static int
+say(const char *format, ...)
+{
+ char line[300];
+ va_list list;
+ int length;
+
+ va_start(list, format);
+ length = vsnprintf(line, sizeof(line), format, list);
+ va_end(list);
+ for (const char *c = line; *c != 0; c++) {
+ loader_log_putc(*c);
+ }
+ if (!leaving) {
+ printf("%s", line);
+ }
+ return length;
+}
static inline uint32_t
rd(vm_offset_t address)
@@ -63,6 +111,28 @@ wr(vm_offset_t address, uint32_t value)
*(volatile uint32_t *)address = value;
}
+/* Waits without sleeping (also with interrupts off, on a panic's way out). */
+static void
+spin_us(uint32_t us)
+{
+ uint64_t until;
+
+ nanoseconds_to_absolutetime((uint64_t)us * NSEC_PER_USEC, &until);
+ until += mach_absolute_time();
+ while (mach_absolute_time() < until) {
+ }
+}
+
+static void
+wait_ms(uint32_t ms)
+{
+ if (leaving) {
+ spin_us(ms * 1000);
+ } else {
+ delay_for_interval(ms, NSEC_PER_MSEC);
+ }
+}
+
/* ---- pins ------------------------------------------------------------------------------------------ */
#define TLMM_PHYS 0x0f100000UL
@@ -72,16 +142,16 @@ wr(vm_offset_t address, uint32_t value)
#define CFG_PULL_UP 3
#define CFG_OUTPUT (1u << 9)
-/* the serial engine's first pin is the data line, the second the clock (should the board differ, see show_amplifiers) */
-static unsigned PIN_SDA = 12, PIN_SCL = 13;
+#define PIN_SDA 12 /* the serial engine's first pin is the data line, the second the clock */
+#define PIN_SCL 13
static const struct {
unsigned pin;
const char *what;
} pins[] = {
- { 12, "I2C data" }, { 13, "I2C clock" }, { 96, "MI2S 0 master clock" }, { 97, "MI2S 0 bit clock" },
- { 100, "MI2S 0 word select" }, { 98, "MI2S 0 data 0" }, { 99, "MI2S 0 data 1" }, { 102, "top amplifier's interrupt" },
- { 45, "bottom amplifier's interrupt" },
+ { 12, "I2C data" }, { 13, "I2C clock" }, { 97, "MI2S 0 bit clock" }, { 100, "MI2S 0 word select" },
+ { 98, "MI2S 0 data 0" }, { 99, "MI2S 0 data 1" }, { 102, "the amplifier 0x35's interrupt" },
+ { 45, "the amplifier 0x34's interrupt" },
};
static void
@@ -90,7 +160,7 @@ show_pins(void)
for (unsigned i = 0; i < sizeof(pins) / sizeof(pins[0]); i++) {
uint32_t cfg = rd(GPIO_CFG(pins[i].pin)), io = rd(GPIO_IO(pins[i].pin));
- printf("speaker: gpio%u (%s): function %u, pull %u, %u mA, %s, reads %u\n", pins[i].pin, pins[i].what,
+ say("speaker: gpio%u (%s): function %u, pull %u, %u mA, %s, reads %u\n", pins[i].pin, pins[i].what,
(cfg >> 2) & 15, cfg & 3, (((cfg >> 6) & 7) + 1) * 2, (cfg & CFG_OUTPUT) ? (io & 2 ? "drives high" : "drives low") :
"input", io & 1);
}
@@ -101,7 +171,7 @@ show_pins(void)
static void
half_bit(void)
{
- delay_for_interval(10, NSEC_PER_USEC); /* 50 kHz at most; the bus does not mind slower */
+ spin_us(10); /* 50 kHz at most; the bus does not mind slower */
}
/* A line is pulled low (the pin drives 0) or let go (the pin is an input and the pull-up raises it). */
@@ -150,6 +220,9 @@ i2c_bit(bool out)
line(PIN_SDA, out);
half_bit();
line(PIN_SCL, true);
+ for (unsigned stretched = 0; !level(PIN_SCL) && stretched < 100; stretched++) {
+ half_bit(); /* (a device may hold the clock low until it is ready) */
+ }
half_bit();
in = level(PIN_SDA);
line(PIN_SCL, false);
@@ -178,12 +251,52 @@ i2c_read(bool more)
return byte;
}
+/*
+ * The two pins taken from the serial engine for one transaction, and given back as found. False
+ * if the bus is not at rest: then nothing is driven.
+ */
+static uint32_t taken_cfg[2], taken_io[2];
+
+static bool
+bus_take(void)
+{
+ taken_cfg[0] = rd(GPIO_CFG(PIN_SDA));
+ taken_cfg[1] = rd(GPIO_CFG(PIN_SCL));
+ taken_io[0] = rd(GPIO_IO(PIN_SDA));
+ taken_io[1] = rd(GPIO_IO(PIN_SCL));
+ line(PIN_SDA, true);
+ line(PIN_SCL, true);
+ half_bit();
+ if (!level(PIN_SDA) || !level(PIN_SCL)) {
+ wr(GPIO_IO(PIN_SDA), taken_io[0] & 2);
+ wr(GPIO_IO(PIN_SCL), taken_io[1] & 2);
+ wr(GPIO_CFG(PIN_SDA), taken_cfg[0]);
+ wr(GPIO_CFG(PIN_SCL), taken_cfg[1]);
+ return false;
+ }
+ return true;
+}
+
+static void
+bus_give_back(void)
+{
+ wr(GPIO_IO(PIN_SDA), taken_io[0] & 2);
+ wr(GPIO_IO(PIN_SCL), taken_io[1] & 2);
+ wr(GPIO_CFG(PIN_SDA), taken_cfg[0]);
+ wr(GPIO_CFG(PIN_SCL), taken_cfg[1]);
+}
+
/* A 16-bit register of an Awinic amplifier, most significant byte first. Returns false if nobody answers. */
static bool
-amplifier_read(uint8_t address, uint8_t reg, uint16_t *value)
+register_read(uint8_t address, uint8_t reg, uint16_t *value)
{
bool answered;
+ if (!bus_take()) {
+ say("speaker: the I2C bus is not at rest (gpio%u reads %u, gpio%u reads %u): not touched\n", PIN_SDA,
+ level(PIN_SDA), PIN_SCL, level(PIN_SCL));
+ return false;
+ }
i2c_start();
answered = i2c_write((uint8_t)(address << 1)) && i2c_write(reg);
if (answered) {
@@ -195,6 +308,25 @@ amplifier_read(uint8_t address, uint8_t reg, uint16_t *value)
*value |= i2c_read(false);
}
i2c_stop();
+ bus_give_back();
+ return answered;
+}
+
+static bool
+register_write(uint8_t address, uint8_t reg, uint16_t value)
+{
+ bool answered;
+
+ if (!bus_take()) {
+ say("speaker: the I2C bus is not at rest (gpio%u reads %u, gpio%u reads %u): not touched\n", PIN_SDA,
+ level(PIN_SDA), PIN_SCL, level(PIN_SCL));
+ return false;
+ }
+ i2c_start();
+ answered = i2c_write((uint8_t)(address << 1)) && i2c_write(reg) && i2c_write((uint8_t)(value >> 8)) &&
+ i2c_write((uint8_t)value);
+ i2c_stop();
+ bus_give_back();
return answered;
}
@@ -216,71 +348,607 @@ amplifier_name(uint16_t id)
return "an amplifier this list does not know";
}
+/* ---- the amplifiers, as Android's driver runs them -------------------------------------------------- */
+
+#define AW_ID 0x00 /* reads the chip ID; 0x55aa written resets the chip */
+#define AW_ID_AW88261 0x2113
+#define AW_SOFT_RESET 0x55aa
+#define AW_SYSST 0x01
+#define AW_SYSINT 0x02 /* read: cleared */
+#define AW_SYSINTM 0x03
+#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_DBGCTRL 0x14
+#define AW_VSNTM1 0x50
+#define AW_EFRH4 0x78
+#define AW_EFRH3 0x79
+#define AW_EFRL4 0x7c
+#define AW_EFRL3 0x7d
+
+#define SYSCTRL_PWDN (1u << 0)
+#define SYSCTRL_AMPPD (1u << 1)
+#define SYSCTRL_HMUTE (1u << 8)
+#define SYSCTRL_ULS_HMUTE (1u << 14)
+#define I2SCTRL3_TXEN (1u << 6)
+#define DBGCTRL_EF_OR (1u << 3) /* the fuses' two copies are or-ed; else and-ed */
+#define SYSINTM_DEFAULT 0xffff
+
+#define SYSST_PLLS (1u << 0)
+#define SYSST_OTHS (1u << 1)
+#define SYSST_OCDS (1u << 3)
+#define SYSST_CLKS (1u << 4)
+#define SYSST_NOCLKS (1u << 5)
+#define SYSST_WDS (1u << 6)
+#define SYSST_SWS (1u << 8)
+#define SYSST_BSTS (1u << 9)
+#define SYSST_BSTOCS (1u << 11)
+#define SYSST_UVLS (1u << 14)
+#define SYSST_OVP2S (1u << 15)
+#define SYSST_PLL_CHECK (SYSST_CLKS | SYSST_PLLS)
+#define SYSST_CHECK (SYSST_BSTS | SYSST_SWS | SYSST_CLKS | SYSST_PLLS)
+#define SYSST_FAULTS (SYSST_OVP2S | SYSST_UVLS | SYSST_BSTOCS | SYSST_WDS | SYSST_NOCLKS | SYSST_OCDS | SYSST_OTHS)
+
+#define VOLUME_LOWEST (90 * 8) /* the driver's "mute volume", in eighths of a dB */
+#define VOLUME_STEP (6 * 8)
+#define STATUS_TRIES 10 /* the driver's AW_DEV_SYSST_CHECK_MAX, 2 ms apart */
+
+/* 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_BLOCK_HEADER 0x3c
+
+struct amplifier {
+ uint8_t address;
+ unsigned device; /* the file's device number for it (Android's sound-channel) */
+ const char *where;
+ uint16_t profile[64][2]; /* register, value */
+ unsigned count;
+ uint16_t sysctrl; /* what the profile has for 0x04, 0x08 and 0x05 */
+ uint16_t i2sctrl3;
+ uint16_t volume_at; /* Android's level: from the profile's 0x05, in eighths of a dB of attenuation */
+ uint16_t volume; /* where it is now */
+ bool prepared, started;
+};
+
+static struct amplifier amplifiers[2] = {
+ { .address = 0x35, .device = 0, .where = "0x35, slot 0" },
+ { .address = 0x34, .device = 1, .where = "0x34, slot 1" },
+};
+static bool broken; /* something went wrong: both have been powered down, nothing more is done */
+
+static uint32_t
+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 "Music" profile of every amplifier, from the file; false if the file is not of the shape known. */
+static bool
+acf_profiles(const uint8_t *acf, uint64_t size)
+{
+ uint32_t entry_size, entries, at;
+
+ if (size < 0x50 || size > 0x100000) {
+ say("speaker: the configuration file is %llu bytes: not one of Awinic's\n", size);
+ return false;
+ }
+ entry_size = le32(acf + 0x34);
+ entries = le32(acf + 0x38);
+ at = le32(acf + 0x3c);
+ if (entries == 0 || entries > 64 || entry_size % entries != 0 || entry_size / entries < 0x30 ||
+ (uint64_t)at + entry_size > size) {
+ say("speaker: the configuration file's table (%u entries, %u bytes at %#x) is not of a shape known\n", entries,
+ entry_size, at);
+ return false;
+ }
+ for (uint32_t e = 0; e < entries; e++) {
+ const uint8_t *entry = acf + at + e * (entry_size / entries);
+ char name[17];
+ uint16_t device = (uint16_t)(entry[20] | entry[21] << 8), profile = (uint16_t)(entry[26] | entry[27] << 8);
+ uint32_t kind = le32(entry + 28), length = le32(entry + 32), offset = le32(entry + 36);
+ uint32_t checksum, sum = 0, data_length, count;
+ const uint8_t *block = acf + offset;
+ struct amplifier *a = NULL;
+
+ memcpy(name, entry + 4, 16);
+ name[16] = 0;
+ if (kind != ACF_DATA_REGISTERS || profile != ACF_PROFILE_MUSIC || strcmp(name, "aw88261") != 0) {
+ continue;
+ }
+ for (unsigned i = 0; i < 2; i++) {
+ if (amplifiers[i].device == device) {
+ a = &amplifiers[i];
+ }
+ }
+ if (a == NULL || (uint64_t)offset + length > size || length < ACF_BLOCK_HEADER + 4) {
+ say("speaker: the configuration file's entry %u (device %u) does not fit\n", e, device);
+ return false;
+ }
+ checksum = le32(block);
+ data_length = le32(block + 0x10);
+ count = le32(block + ACF_BLOCK_HEADER);
+ if (ACF_BLOCK_HEADER + data_length > length || data_length != 4 + 4 * count || count > 64 ||
+ le32(block + 0x20) != 2 || le32(block + 0x24) != 2) {
+ say("speaker: device %u's Music profile is not a list of 16-bit registers (%u bytes, %u registers)\n", device,
+ data_length, count);
+ return false;
+ }
+ for (uint32_t i = 4; i < ACF_BLOCK_HEADER + data_length; i++) {
+ sum += block[i];
+ }
+ if (sum != checksum) {
+ say("speaker: device %u's Music profile does not add up (%#x, the file says %#x)\n", device, sum, checksum);
+ return false;
+ }
+ a->count = count;
+ for (uint32_t i = 0; i < count; i++) {
+ const uint8_t *pair = block + ACF_BLOCK_HEADER + 4 + 4 * i;
+
+ a->profile[i][0] = (uint16_t)(pair[0] | pair[1] << 8);
+ a->profile[i][1] = (uint16_t)(pair[2] | pair[3] << 8);
+ }
+ }
+ for (unsigned i = 0; i < 2; i++) {
+ struct amplifier *a = &amplifiers[i];
+ bool have[3] = { false, false, false };
+
+ for (unsigned r = 0; r < a->count; r++) {
+ uint16_t reg = a->profile[r][0], value = a->profile[r][1];
+
+ if (reg == AW_SYSCTRL) {
+ a->sysctrl = value;
+ have[0] = true;
+ } else if (reg == AW_I2SCTRL3) {
+ a->i2sctrl3 = value;
+ have[1] = true;
+ } else if (reg == AW_SYSCTRL2) {
+ /* the driver's aw_pid_2113_reg_val_to_db() */
+ a->volume_at = (uint16_t)(((value & 0x3ff) >> 6) * VOLUME_STEP + (value & 0x3f));
+ have[2] = true;
+ } else if (reg == AW_ID || reg >= 0x70) {
+ say("speaker: device %u's Music profile writes register %#x, which is not one of the configuration's\n",
+ a->device, reg);
+ return false;
+ }
+ }
+ if (a->count == 0 || !have[0] || !have[1] || !have[2] || a->volume_at >= VOLUME_LOWEST) {
+ say("speaker: no usable Music profile for device %u (the amplifier at %#x) in the configuration file\n",
+ a->device, a->address);
+ return false;
+ }
+ say("speaker: the amplifier %s: Music profile of %u registers; Android's volume there is -%u.%03u dB (%#x)\n", a->where,
+ a->count, a->volume_at / 8, a->volume_at % 8 * 125, a->volume_at);
+ }
+ return true;
+}
+
+/* Both powered down at once, without the driver's ceremony: a fault, or a value that did not stick. */
+static void
+power_down_now(const char *why)
+{
+ broken = true;
+ say("speaker: %s: BOTH AMPLIFIERS ARE POWERED DOWN AT ONCE (0x04: amplifier power-down and power-down set)\n", why);
+ for (unsigned i = 0; i < 2; i++) {
+ struct amplifier *a = &amplifiers[i];
+ uint16_t value = 0, after = 0;
+
+ if (!a->prepared && !a->started) {
+ continue;
+ }
+ if (!register_read(a->address, AW_SYSCTRL, &value)) {
+ value = a->sysctrl;
+ }
+ value |= SYSCTRL_PWDN | SYSCTRL_AMPPD | SYSCTRL_HMUTE;
+ if (!register_write(a->address, AW_SYSCTRL, value) || !register_read(a->address, AW_SYSCTRL, &after)) {
+ say("speaker: the amplifier %s: 0x04 <- %#06x NOT ACKNOWLEDGED\n", a->where, value);
+ } else {
+ say("speaker: the amplifier %s: 0x04 <- %#06x, reads %#06x\n", a->where, value, after);
+ }
+ a->started = false;
+ }
+}
+
+/* One register written, said and read back; false (and both powered down) if it did not stick. */
+static bool
+put(struct amplifier *a, uint8_t reg, uint16_t value)
+{
+ uint16_t after = 0;
+
+ if (broken) {
+ return false;
+ }
+ if (!register_write(a->address, reg, value)) {
+ say("speaker: the amplifier %s: %#04x <- %#06x NOT ACKNOWLEDGED\n", a->where, reg, value);
+ power_down_now("a write was not acknowledged");
+ return false;
+ }
+ if (!register_read(a->address, reg, &after)) {
+ say("speaker: the amplifier %s: %#04x <- %#06x, NOT READ BACK\n", a->where, reg, value);
+ power_down_now("a register could not be read back");
+ return false;
+ }
+ say("speaker: the amplifier %s: %#04x <- %#06x, reads %#06x%s\n", a->where, reg, value, after, after == value ? "" :
+ ": NOT AS WRITTEN");
+ if (after != value) {
+ power_down_now("a register did not read back as written");
+ return false;
+ }
+ return true;
+}
+
+static bool
+get(struct amplifier *a, uint8_t reg, uint16_t *value)
+{
+ if (!register_read(a->address, reg, value)) {
+ say("speaker: the amplifier %s: %#04x NOT READ\n", a->where, reg);
+ return false;
+ }
+ return true;
+}
+
+/* The bits of 0x04 named in `bits' set or cleared, the rest as they read. */
+static bool
+sysctrl(struct amplifier *a, uint16_t bits, bool set)
+{
+ uint16_t value;
+
+ if (broken || !get(a, AW_SYSCTRL, &value)) {
+ return false;
+ }
+ return put(a, AW_SYSCTRL, set ? (value | bits) : (value & ~bits));
+}
+
+/* The volume register at `volume' eighths of a dB of attenuation (the driver's aw_pid_2113_set_volume()). */
+static bool
+set_volume(struct amplifier *a, uint16_t volume)
+{
+ uint16_t value;
+
+ if (volume > VOLUME_LOWEST) {
+ volume = VOLUME_LOWEST;
+ }
+ if (volume < a->volume_at) {
+ volume = a->volume_at; /* never louder than Android */
+ }
+ if (broken || !get(a, AW_SYSCTRL2, &value)) {
+ return false;
+ }
+ if (!put(a, AW_SYSCTRL2, (uint16_t)((value & 0xfc00) | (volume / VOLUME_STEP) << 6 | volume % VOLUME_STEP))) {
+ return false;
+ }
+ a->volume = volume;
+ return true;
+}
+
+/* What the status register says, and whether it says a fault. */
+static bool
+faulty(struct amplifier *a, uint16_t *status)
+{
+ if (!get(a, AW_SYSST, status)) {
+ return true;
+ }
+ return (*status & SYSST_FAULTS) != 0;
+}
+
+bool
+redwood_speaker_prepare(const uint8_t *acf, uint64_t size)
+{
+ if (tlmm == 0) {
+ tlmm = ml_io_map(TLMM_PHYS, TLMM_SIZE);
+ }
+ broken = false;
+ say("speaker: the amplifiers are prepared as Android's driver prepares them; the I2C pins as found:\n");
+ show_pins();
+ if (!acf_profiles(acf, size)) {
+ return false;
+ }
+ for (unsigned i = 0; i < 2; i++) {
+ struct amplifier *a = &amplifiers[i];
+ uint16_t id = 0, h4 = 0, h3 = 0, l4 = 0, l3 = 0, icalk_bits, vcalk_bits;
+ int icalk, vcalk;
+ uint16_t vcalb, ef_or = 0;
+
+ if (!get(a, AW_ID, &id)) {
+ say("speaker: nobody at I2C address %#x: not powered, or not there\n", a->address);
+ power_down_now("an amplifier does not answer");
+ return false;
+ }
+ say("speaker: the amplifier %s: chip ID %#06x, %s\n", a->where, id, amplifier_name(id));
+ if (id != AW_ID_AW88261) {
+ return false;
+ }
+ if (!get(a, AW_EFRH4, &h4) || !get(a, AW_EFRH3, &h3) || !get(a, AW_EFRL4, &l4) || !get(a, AW_EFRL3, &l3)) {
+ return false;
+ }
+ for (unsigned r = 0; r < a->count; r++) {
+ if (a->profile[r][0] == AW_DBGCTRL) {
+ ef_or = a->profile[r][1] & DBGCTRL_EF_OR;
+ }
+ }
+ /* the driver's aw_dev_get_icalk(), aw_dev_get_vcalk() and aw_dev_set_vcalb() */
+ icalk_bits = ef_or ? ((h4 & 0x3ff) | (l4 & 0x3ff)) : ((h4 & 0x3ff) & (l4 & 0x3ff));
+ vcalk_bits = ef_or ? ((h3 & 0x3ff) | (l3 & 0x3ff)) : ((h3 & 0x3ff) & (l3 & 0x3ff));
+ icalk = 1000 + ((icalk_bits & 0x200) ? (int)icalk_bits - 0x400 : (int)icalk_bits);
+ vcalk = 1000 + ((vcalk_bits & 0x200) ? (int)vcalk_bits - 0x400 : (int)vcalk_bits);
+ if (vcalk <= 0 || icalk <= 0) {
+ say("speaker: the amplifier %s: fuses %#x %#x %#x %#x make no sense\n", a->where, h4, h3, l4, l3);
+ return false;
+ }
+ vcalb = (uint16_t)(8192 * icalk / vcalk);
+ say("speaker: the amplifier %s: fuses %#06x %#06x %#06x %#06x: icalk %d, vcalk %d, so 0x50 is to be %#06x\n", a->where,
+ h4, h3, l4, l3, icalk, vcalk, vcalb);
+
+ say("speaker: the amplifier %s: soft reset (0x00 <- 0x55aa), as the driver does it first\n", a->where);
+ a->prepared = true;
+ if (!register_write(a->address, AW_ID, AW_SOFT_RESET)) {
+ power_down_now("the soft reset was not acknowledged");
+ return false;
+ }
+ wait_ms(2);
+ for (unsigned r = 0; r < a->count; r++) {
+ uint8_t reg = (uint8_t)a->profile[r][0];
+ uint16_t value = a->profile[r][1], now;
+
+ switch (reg) {
+ case AW_SYSINTM:
+ value = SYSINTM_DEFAULT;
+ break;
+ case AW_SYSCTRL:
+ /* the three power and mute bits stay as they are; the power stage's mute on */
+ if (!get(a, AW_SYSCTRL, &now)) {
+ power_down_now("0x04 could not be read");
+ return false;
+ }
+ value = (uint16_t)((value & ~(SYSCTRL_PWDN | SYSCTRL_AMPPD | SYSCTRL_HMUTE)) |
+ (now & (SYSCTRL_PWDN | SYSCTRL_AMPPD | SYSCTRL_HMUTE)) | SYSCTRL_ULS_HMUTE);
+ break;
+ case AW_I2SCTRL3:
+ value &= (uint16_t)~I2SCTRL3_TXEN;
+ break;
+ case AW_VSNTM1:
+ continue;
+ }
+ if (!put(a, reg, value)) {
+ return false;
+ }
+ }
+ if (!put(a, AW_VSNTM1, vcalb) || !set_volume(a, VOLUME_LOWEST)) {
+ return false;
+ }
+ }
+ say("speaker: BOTH AMPLIFIERS ARE CONFIGURED as Android's Music profile has them: powered down, muted, at the lowest volume\n");
+ return true;
+}
+
+bool
+redwood_speaker_start(void)
+{
+ for (unsigned i = 0; i < 2; i++) {
+ struct amplifier *a = &amplifiers[i];
+ uint16_t status = 0, interrupts = 0;
+ unsigned tries;
+
+ if (broken || !a->prepared) {
+ return false;
+ }
+ say("speaker: the amplifier %s: power-down off\n", a->where);
+ a->started = true;
+ if (!sysctrl(a, SYSCTRL_PWDN, false)) {
+ return false;
+ }
+ wait_ms(2);
+ for (tries = 0; tries < STATUS_TRIES; tries++) {
+ if (!get(a, AW_SYSST, &status)) {
+ power_down_now("the status could not be read");
+ return false;
+ }
+ if ((status & SYSST_PLL_CHECK) == SYSST_PLL_CHECK) {
+ break;
+ }
+ wait_ms(2);
+ }
+ say("speaker: the amplifier %s: status %#06x: its PLL %s\n", a->where, status, tries < STATUS_TRIES ?
+ "IS LOCKED to the bit clock" : "DOES NOT LOCK: no clock?");
+ if (tries == STATUS_TRIES) {
+ power_down_now("an amplifier's PLL does not lock");
+ return false;
+ }
+ say("speaker: the amplifier %s: amplifier power-down off\n", a->where);
+ if (!sysctrl(a, SYSCTRL_AMPPD, false)) {
+ return false;
+ }
+ wait_ms(1);
+ for (tries = 0; tries < STATUS_TRIES; tries++) {
+ if (faulty(a, &status)) {
+ break;
+ }
+ if ((status & SYSST_CHECK) == SYSST_CHECK) {
+ break;
+ }
+ wait_ms(2);
+ }
+ say("speaker: the amplifier %s: status %#06x\n", a->where, status);
+ if ((status & SYSST_FAULTS) != 0 || (status & SYSST_CHECK) != SYSST_CHECK) {
+ power_down_now((status & SYSST_FAULTS) ? "an amplifier reports a fault" : "an amplifier's status is not as "
+ "the driver wants it");
+ return false;
+ }
+ if (!put(a, AW_I2SCTRL3, a->i2sctrl3) || /* the feedback on, as the profile has it */
+ !sysctrl(a, SYSCTRL_ULS_HMUTE, false) || !sysctrl(a, SYSCTRL_HMUTE, false)) {
+ return false;
+ }
+ if (!get(a, AW_SYSINT, &interrupts) || !get(a, AW_SYSINT, &interrupts) || !put(a, AW_SYSINTM, SYSINTM_DEFAULT)) {
+ power_down_now("the interrupts could not be read");
+ return false;
+ }
+ if (faulty(a, &status)) {
+ say("speaker: the amplifier %s: status %#06x\n", a->where, status);
+ power_down_now("an amplifier reports a fault");
+ return false;
+ }
+ say("speaker: THE AMPLIFIER %s RUNS, unmuted at the lowest volume (status %#06x)\n", a->where, status);
+ }
+ return true;
+}
+
+bool
+redwood_speaker_volume(uint32_t below)
+{
+ uint16_t status;
+
+ for (unsigned i = 0; i < 2; i++) {
+ struct amplifier *a = &amplifiers[i];
+ uint32_t target = a->volume_at + below;
+
+ if (broken || !a->started) {
+ return false;
+ }
+ if (target > VOLUME_LOWEST) {
+ target = VOLUME_LOWEST;
+ }
+ say("speaker: the amplifier %s: the volume to -%u.%03u dB (Android's level less %u.%03u dB), 6 dB a step\n", a->where,
+ target / 8, target % 8 * 125, (target - a->volume_at) / 8, (target - a->volume_at) % 8 * 125);
+ }
+ /* both together, a step every 50 ms, the status looked at after every step */
+ for (;;) {
+ bool moved = false;
+
+ for (unsigned i = 0; i < 2; i++) {
+ struct amplifier *a = &amplifiers[i];
+ uint32_t target = a->volume_at + below, next;
+
+ if (target > VOLUME_LOWEST) {
+ target = VOLUME_LOWEST;
+ }
+ if (a->volume == target) {
+ continue;
+ }
+ next = a->volume > target ? (a->volume - target > VOLUME_STEP ? a->volume - VOLUME_STEP : target) :
+ (target - a->volume > VOLUME_STEP ? a->volume + VOLUME_STEP : target);
+ if (!set_volume(a, (uint16_t)next)) {
+ return false;
+ }
+ if (faulty(a, &status)) {
+ say("speaker: the amplifier %s: status %#06x\n", a->where, status);
+ power_down_now("an amplifier reports a fault");
+ return false;
+ }
+ moved = true;
+ }
+ if (!moved) {
+ break;
+ }
+ wait_ms(50);
+ }
+ return true;
+}
+
+bool
+redwood_speaker_healthy(void)
+{
+ for (unsigned i = 0; i < 2; i++) {
+ struct amplifier *a = &amplifiers[i];
+ uint16_t status;
+
+ if (broken) {
+ return false;
+ }
+ if (!a->started) {
+ continue;
+ }
+ if (faulty(a, &status)) {
+ say("speaker: the amplifier %s: status %#06x\n", a->where, status);
+ power_down_now("an amplifier reports a fault");
+ return false;
+ }
+ }
+ return true;
+}
+
+void
+redwood_speaker_stop(void)
+{
+ if (broken) {
+ return; /* (already powered down) */
+ }
+ for (unsigned i = 0; i < 2; i++) {
+ struct amplifier *a = &amplifiers[i];
+
+ if (!a->started) {
+ continue;
+ }
+ say("speaker: the amplifier %s is stopped as Android's driver stops it\n", a->where);
+ if (!sysctrl(a, SYSCTRL_ULS_HMUTE, true)) {
+ return;
+ }
+ while (a->volume < VOLUME_LOWEST) {
+ if (!set_volume(a, (uint16_t)(a->volume + VOLUME_STEP > VOLUME_LOWEST ? VOLUME_LOWEST : a->volume +
+ VOLUME_STEP))) {
+ return;
+ }
+ wait_ms(1);
+ }
+ if (!sysctrl(a, SYSCTRL_HMUTE, true) || !put(a, AW_I2SCTRL3, (uint16_t)(a->i2sctrl3 & ~I2SCTRL3_TXEN))) {
+ return;
+ }
+ wait_ms(1);
+ if (!sysctrl(a, SYSCTRL_AMPPD, true) || !sysctrl(a, SYSCTRL_PWDN, true)) {
+ return;
+ }
+ a->started = false;
+ say("speaker: THE AMPLIFIER %s IS POWERED DOWN\n", a->where);
+ }
+}
+
+void
+redwood_speaker_quiesce(void)
+{
+ bool any = false;
+
+ for (unsigned i = 0; i < 2; i++) {
+ any |= amplifiers[i].started;
+ }
+ if (!any || tlmm == 0) {
+ return;
+ }
+ leaving = true;
+ power_down_now("the kernel is on its way out");
+}
+
+/* ---- speaker_probe=N: a look ------------------------------------------------------------------------ */
+
static void
show_amplifiers(void)
{
- static const struct {
- uint8_t address;
- const char *where;
- } amplifiers[] = { { 0x34, "bottom" }, { 0x35, "top" } };
/* the chip ID, then registers that every chip of the family has at the same place and that reading does not change */
static const struct {
uint8_t reg;
const char *name;
} more[] = { { 0x01, "status" }, { 0x04, "system control" }, { 0x06, "I2S control" } };
- const unsigned first = PIN_SDA, second = PIN_SCL;
- uint32_t first_cfg = rd(GPIO_CFG(first)), second_cfg = rd(GPIO_CFG(second));
- uint32_t first_io = rd(GPIO_IO(first)), second_io = rd(GPIO_IO(second));
- unsigned found = 0;
- line(PIN_SDA, true);
- line(PIN_SCL, true);
- delay_for_interval(1, NSEC_PER_MSEC);
- if (!level(PIN_SDA) || !level(PIN_SCL)) {
- /* nothing of ours on a bus that is not at rest: its supply may be off, and then so are the amplifiers */
- printf("speaker: the I2C bus is not idle (gpio%u reads %u, gpio%u reads %u): no supply for its pull-ups? Not touched\n",
- PIN_SDA, level(PIN_SDA), PIN_SCL, level(PIN_SCL));
- } else {
- /* as the pins should be, and if nobody answers, the other way round */
- for (int attempt = 0; attempt < 2 && found == 0; attempt++) {
- if (attempt == 1) {
- PIN_SDA = second;
- PIN_SCL = first;
- printf("speaker: once more with gpio%u as the data line and gpio%u as the clock\n", PIN_SDA, PIN_SCL);
- }
- for (unsigned i = 0; i < sizeof(amplifiers) / sizeof(amplifiers[0]); i++) {
- uint16_t id = 0, value = 0;
+ for (unsigned i = 0; i < 2; i++) {
+ uint16_t id = 0, value = 0;
- if (!amplifier_read(amplifiers[i].address, 0x00, &id)) {
- printf("speaker: nobody at I2C address %#x (the %s amplifier): not powered, or not there\n",
- amplifiers[i].address, amplifiers[i].where);
- continue;
- }
- found++;
- printf("speaker: the %s amplifier (I2C address %#x) is there: chip ID %#06x, %s\n", amplifiers[i].where,
- amplifiers[i].address, id, amplifier_name(id));
- for (unsigned r = 0; r < sizeof(more) / sizeof(more[0]); r++) {
- if (amplifier_read(amplifiers[i].address, more[r].reg, &value)) {
- printf("speaker: register %#04x (%s) = %#06x\n", more[r].reg, more[r].name, value);
- }
- }
+ if (!register_read(amplifiers[i].address, AW_ID, &id)) {
+ say("speaker: nobody at I2C address %#x: not powered, or not there\n", amplifiers[i].address);
+ continue;
+ }
+ say("speaker: the amplifier %s is there: chip ID %#06x, %s\n", amplifiers[i].where, id, amplifier_name(id));
+ for (unsigned r = 0; r < sizeof(more) / sizeof(more[0]); r++) {
+ if (register_read(amplifiers[i].address, more[r].reg, &value)) {
+ say("speaker: register %#04x (%s) = %#06x\n", more[r].reg, more[r].name, value);
}
}
}
- /* as the firmware left them */
- wr(GPIO_IO(first), first_io & 2);
- wr(GPIO_IO(second), second_io & 2);
- wr(GPIO_CFG(first), first_cfg);
- wr(GPIO_CFG(second), second_cfg);
}
-/* ---- power and clock of the audio subsystem --------------------------------------------------------- */
+/* ---- power names of the audio subsystem ------------------------------------------------------------- */
#define CMD_DB_PHYS 0x80860000UL
#define CMD_DB_SIZE 0x20000UL
#define GCC_PHYS 0x00100000UL
#define GCC_SIZE 0x60000UL
-#define GCC_CFG_NOC_LPASS_CBCR (gcc + 0x47020) /* bit 0: asked for, bit 31: off */
struct cmd_db_slave {
uint16_t id, header_offset, data_offset, count, version, reserved[3];
@@ -336,9 +1004,9 @@ show_power(void)
uint32_t address = rpmh_address(supplies[i]);
if (address) {
- printf("speaker: supply \"%s\" can be asked for at RPMh address %#x\n", supplies[i], address);
+ say("speaker: supply \"%s\" can be asked for at RPMh address %#x\n", supplies[i], address);
} else {
- printf("speaker: no supply \"%s\" in the command database\n", supplies[i]);
+ say("speaker: no supply \"%s\" in the command database\n", supplies[i]);
}
}
/*
@@ -351,16 +1019,18 @@ show_power(void)
static void
probe_thread(__unused void *parameter, __unused wait_result_t result)
{
- tlmm = ml_io_map(TLMM_PHYS, TLMM_SIZE);
+ if (tlmm == 0) {
+ tlmm = ml_io_map(TLMM_PHYS, TLMM_SIZE);
+ }
gcc = ml_io_map(GCC_PHYS, GCC_SIZE);
cmd_db = ml_io_map_wcomb(CMD_DB_PHYS, CMD_DB_SIZE); /* memory, not registers: no alignment rules */
- printf("speaker: a look at the phone's sound hardware (level %u; nothing is switched on)\n", probe_level);
+ say("speaker: a look at the phone's sound hardware (level %u; nothing is switched on)\n", probe_level);
show_pins();
show_power();
if (probe_level >= 2) {
show_amplifiers();
}
- printf("speaker: done\n");
+ say("speaker: done\n");
thread_terminate(current_thread());
}
diff --git a/xnu/files/bsd/dev/redwood_wifi.c b/xnu/files/bsd/dev/redwood_wifi.c
index 4709e7c..66c50dc 100644
--- a/xnu/files/bsd/dev/redwood_wifi.c
+++ b/xnu/files/bsd/dev/redwood_wifi.c
@@ -190,6 +190,8 @@ static LCK_GRP_DECLARE(wifi_lock_group, "redwood-wifi");
*/
LCK_MTX_DECLARE(redwood_aop_mailbox_lock, &wifi_lock_group);
LCK_MTX_DECLARE(redwood_smem_alloc_lock, &wifi_lock_group);
+/* ... and the sound's (redwood_sound.c): a free match register and context of the SMMU, found and taken */
+LCK_MTX_DECLARE(redwood_smmu_lock, &wifi_lock_group);
static uint32_t last_step, pause_ms = 2200, fine, watch_seconds = 3;
static uint32_t step; /* the one being performed */
@@ -3935,13 +3937,19 @@ radio_map(uint64_t physical, uint64_t size, uint64_t attributes, unsigned long l
"a context of the SMMU (wifi_smmu=2)\n", step, size >> 10, physical, *address);
return true;
}
+ lck_mtx_lock(&redwood_smmu_lock); /* (the sound may be looking for a free context at the same time) */
if ((!radio_space.found && !radio_space_find()) || !radio_enter(*address, physical, size, attributes)) {
+ lck_mtx_unlock(&redwood_smmu_lock);
return false;
}
printf("wifi: %u: the radio is to see %llu KB of ours (%#llx) at %#llx\n", step, size >> 10, physical, *address);
if (!radio_space.on) {
- return radio_space_on();
+ bool on = radio_space_on();
+
+ lck_mtx_unlock(&redwood_smmu_lock);
+ return on;
}
+ lck_mtx_unlock(&redwood_smmu_lock);
put(&apps_smmu_context, "tlbiasid", SMMU_CB_TLBIASID, radio_space.context);
put(&apps_smmu_context, "tlbsync", SMMU_CB_TLBSYNC, 1);
return true;
diff --git a/xnu/files/bsd/sys/redwood_audio.h b/xnu/files/bsd/sys/redwood_audio.h
index 9cefd3f..3465fb7 100644
--- a/xnu/files/bsd/sys/redwood_audio.h
+++ b/xnu/files/bsd/sys/redwood_audio.h
@@ -34,6 +34,43 @@ void redwood_audio_set_sink(const char *name, redwood_audio_sink_t sink);
void redwood_audio_init(void);
void redwood_virtio_sound_init(void); /* boot-arg virtio_sound=1: QEMU's virtio sound device */
void redwood_speaker_init(void); /* boot-arg speaker_probe=N: a look at the phone's speaker amplifiers */
+
+#include <stdbool.h>
+
+/*
+ * The phone's speakers (bsd/dev/redwood_speaker.c): its two Awinic amplifiers, set up as
+ * Android's driver sets them up, from Android's own configuration file (see there).
+ */
+bool redwood_speaker_prepare(const uint8_t *acf, uint64_t size); /* found, reset, configured: powered down, muted */
+bool redwood_speaker_start(void); /* powered up and unmuted at the lowest volume: only while the I2S clock runs */
+bool redwood_speaker_volume(uint32_t below); /* below Android's level, in eighths of a dB; stepwise */
+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 audio DSP's services, for the sound's path (bsd/dev/redwood_adsp.c, bsd/dev/redwood_sound.c).
+ * redwood_adsp_apr() sends one APR packet to a service of the DSP (AFE 4, ASM 7, ADM 8) with the
+ * given port and token (0: one of its own) and, with wait_ms, waits for the packet that carries
+ * that token back. What is not waited for goes to the handler of events, if there is one and it
+ * takes it (returns true). The handler is called on the link's thread and must not wait.
+ */
+struct redwood_apr_answer {
+ uint32_t opcode, token, length; /* length: of the payload, in bytes */
+ uint32_t words[64];
+};
+typedef bool (*redwood_apr_events_t)(uint8_t service, uint16_t port, uint32_t opcode, uint32_t token, const uint32_t *payload,
+ uint32_t length);
+
+bool redwood_adsp_apr(uint8_t service, uint16_t port, uint32_t token, uint32_t opcode, const void *payload, uint32_t length,
+ uint32_t wait_ms, struct redwood_apr_answer *answer);
+void redwood_adsp_apr_events(redwood_apr_events_t handler);
+const uint8_t *redwood_adsp_fw_file(const char *name, uint64_t *size); /* /fw/name, read whole; give back with: */
+void redwood_adsp_fw_free(const uint8_t *data, uint64_t size);
+
+void redwood_sound_dsp_up(void); /* the DSP's audio services are up (adsp=1): boot-arg sound=N begins */
+void redwood_sound_dsp_down(void); /* before the DSP is shut down at the run's end: everything of the sound's stopped */
+void redwood_sound_quiesce(void); /* on a panic's way out: the amplifiers off, without sleeping */
#endif
#endif /* _SYS_REDWOOD_AUDIO_H_ */
diff --git a/xnu/redwood.patch b/xnu/redwood.patch
index dfbb965..c012456 100644
--- a/xnu/redwood.patch
+++ b/xnu/redwood.patch
@@ -46,10 +46,10 @@ index 222158a93918..68bb0f3e56bf 100755
######################################################################
# HISTORY
diff --git a/bsd/conf/files b/bsd/conf/files
-index 44274016a4cf..f061b6eb9c2c 100644
+index 44274016a4cf..c4058651c5a6 100644
--- a/bsd/conf/files
+++ b/bsd/conf/files
-@@ -109,6 +109,25 @@ bsd/dev/munge.c optional config_requires_u32_munging
+@@ -109,6 +109,26 @@ bsd/dev/munge.c optional config_requires_u32_munging
bsd/dev/unix_startup.c standard
bsd/dev/monotonic.c optional monotonic
@@ -68,6 +68,7 @@ index 44274016a4cf..f061b6eb9c2c 100644
+bsd/dev/redwood_speaker.c standard
+bsd/dev/redwood_wifi.c standard
+bsd/dev/redwood_adsp.c standard
++bsd/dev/redwood_sound.c standard
+bsd/dev/redwood_qmi.c standard
+bsd/dev/redwood_wlfw.c standard
+bsd/dev/redwood_lx.c standard
@@ -75,7 +76,7 @@ index 44274016a4cf..f061b6eb9c2c 100644
bsd/dev/dev_perfmon.c optional config_perfmon
bsd/libkern/crc32.c standard
-@@ -155,6 +174,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs
+@@ -155,6 +175,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs
bsd/miscfs/mockfs/mockfs_fsnode.c optional mockfs
bsd/miscfs/mockfs/mockfs_vfsops.c optional mockfs
bsd/miscfs/mockfs/mockfs_vnops.c optional mockfs
@@ -86,7 +87,7 @@ index 44274016a4cf..f061b6eb9c2c 100644
bsd/miscfs/routefs/routefs_ops.c optional routefs
-@@ -361,6 +384,7 @@ bsd/security/audit/audit_syscalls.c standard
+@@ -361,6 +385,7 @@ bsd/security/audit/audit_syscalls.c standard
bsd/security/audit/audit_worker.c optional config_audit
bsd/pthread/pthread_shims.c standard
@@ -94,7 +95,7 @@ index 44274016a4cf..f061b6eb9c2c 100644
bsd/pthread/pthread_priority.c standard
bsd/pthread/pthread_workqueue.c standard
-@@ -383,6 +407,7 @@ bsd/kern/kern_debug.c standard
+@@ -383,6 +408,7 @@ bsd/kern/kern_debug.c standard
bsd/kern/kern_symfile.c standard
bsd/kern/kern_descrip.c standard
bsd/kern/kern_guarded.c standard