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: what iOS plays comes out of the speakers (sound=4)

vcvkkf60e2e95a536
diff --git a/README.md b/README.md
index 2ebf688..13df687 100644
--- a/README.md
+++ b/README.md
@@ -100,9 +100,10 @@ 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`.
-На телефоне то, что играет iOS, до динамиков пока не доходит. Сами динамики уже звучат: с `adsp=1 sound=3`
-ядро через звуковой процессор (порт TDM, поток, путь к порту) и оба усилителя Awinic играет пробный тон
-(см. параметр `sound=N` ниже). То, что iOS играет, можно забрать: параметр ядра `rec_sound=N` сохраняет первые N секунд звука в памяти, после
+На телефоне с `adsp=1 sound=4` то, что играет iOS, звучит из обоих динамиков: через звуковой процессор (порт TDM,
+поток, путь к порту) и два усилителя Awinic, которые включаются, только пока есть звук (параметр `sound=N` ниже;
+`RC_JOBS=rc.jobs.speakers` проигрывает тон, звук блокировки, щелчки клавиатуры и фанфары). То, что iOS играет,
+можно и забрать: параметр ядра `rec_sound=N` сохраняет первые N секунд звука в памяти, после
сеанса `./xl sound out.wav` достаёт их (в QEMU — `pmemsave` по адресу из строки `redwood-audio: recording … at 0x…`,
затем `tools/sound.py`). В QEMU запись проверена; на самом телефоне звук ещё не проверялся вовсе.
@@ -234,7 +235,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` |
+| `sound=N` | с `adsp=1`, шаг 3 звука, путь к динамикам, как его строит Android (числа — из живого дерева устройств телефона, его путей микшера и его ядра): `sound=1` — ножки TDM (GPIO 97–100) отданы интерфейсу, звуковой процессор включает его тактовую частоту (3,072 МГц), группу и порт 0x9000 (PRI_TDM_RX_0) и запускает его; по ножкам видно, что тактовый сигнал и синхронизация кадров идут. `sound=2` — ещё и поток: наша память видна процессору через SMMU (поток 0x1801), путь ADM к порту, поток ASM, и в него 3 с пишется тон 1 кГц −20 дБ полной шкалы; процессор забирает его с частотой 48 кГц. Усилители выключены. `sound=3` — ещё и усилители: настраиваются из профиля «Music» конфигурации Android (`/vendor/etc/aw882xx_acf.bin` телефона в `fw-audio/`, в git не попадает, `userland/build.sh` кладёт её в `/fw` образа системы), каждая запись читается обратно, при любом расхождении или сбое оба сразу выключаются; громкость плавно поднимается до `sound_below` восьмых долей дБ ниже уровня Android (по умолчанию 240, то есть на 30 дБ тише), тон звучит 3 с, потом всё затихает, выключается и возвращается как было. `sound=4` — то, что играет iOS (`/dev/redwood-audio`), до конца сеанса: порт и поток работают всё время (без звука в них идёт тишина), усилители настраиваются один раз и выключены, а когда в записи iOS появляется не тишина, включаются и быстро (как у драйвера Android) выводятся на `sound_below`; после трёх секунд тишины снова выключаются. Звук доходит до усилителей через 160 мс после записи, усилители готовы через 65 мс. `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/rc.jobs.speakers b/userland/rc.jobs.speakers
new file mode 100644
index 0000000..4cc734c
--- /dev/null
+++ b/userland/rc.jobs.speakers
@@ -0,0 +1,8 @@
+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).
+# The phone's speakers (boot-arg sound=4 with adsp=1, bsd/dev/redwood_sound.c): once SpringBoard is up, what iOS
+# plays in the ways that matter to the amplifiers, which are on only while there is sound -- a tone of three
+# seconds (1000 Hz left, 440 Hz right), the lock sound, keyboard clicks four seconds apart (each one starts the
+# amplifiers anew: after three seconds of silence they are stopped), three clicks half a second apart (they
+# stay on), a fanfare. The kernel's "sound:" and "speaker:" lines say when the amplifiers started and stopped.
+/redwood/bin/sound_test springboard route wait 3 tone 3 wait 4 system 1100 wait 4 system 1104 wait 4 system 1104 wait 4 system 1104 wait 0.5 system 1104 wait 0.5 system 1104 wait 4 file /System/Library/Audio/UISounds/New/Fanfare.caf wait 5
+/bin/ps -A
diff --git a/xnu/files/bsd/dev/redwood_sound.c b/xnu/files/bsd/dev/redwood_sound.c
index 18941bc..cef6912 100644
--- a/xnu/files/bsd/dev/redwood_sound.c
+++ b/xnu/files/bsd/dev/redwood_sound.c
@@ -25,6 +25,10 @@
* 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.
+ * sound=4 what iOS plays (/dev/redwood-audio, redwood_audio.c), until the run ends: the port
+ * and the stream as above, kept running (silence when iOS writes nothing); the
+ * amplifiers set up once and powered down, started and faded in (the driver's quick
+ * fade) whenever a write is not silence, stopped after three seconds of silence
*
* 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,
@@ -716,6 +720,7 @@ space_off(void)
#define PCM_CHANNEL_FL 1
#define PCM_CHANNEL_FR 2
+static volatile bool stopping; /* the run is ending: whatever plays stops */
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) */
@@ -919,7 +924,7 @@ play(uint32_t ms, bool amplifiers)
sent++;
}
}
- if (!tone_over && now - began >= ms * 1000ull) {
+ if (!tone_over && (now - began >= ms * 1000ull || stopping)) {
tone_over = true;
}
if (tone_over && written_done - done_before >= sent) {
@@ -961,6 +966,149 @@ play(uint32_t ms, bool amplifiers)
return ok;
}
+/* ---- sound=4: what iOS plays ------------------------------------------------------------------------------ */
+
+/*
+ * /dev/redwood-audio's writer (the audio server's real-time thread, redwood_audio.c) puts frames
+ * into a ring and does not wait; the feeder, a thread of ours, takes them from there into each
+ * period the DSP gives back (and silence when there is nothing), so the stream never stops
+ * while the run lasts. The amplifiers are only on while there is sound: the watcher starts them
+ * (and fades them in to sound_below) when a write is not silence, and stops them after three
+ * seconds of silence or no writes.
+ */
+#define RING_FRAMES 32768 /* 0.68 s; a power of two, the indices run on and wrap */
+#define SILENCE 8 /* samples no larger than this are silence (as redwood_audio.c's) */
+#define QUIET_BEFORE_OFF_US 3000000ull
+
+static int16_t ring[RING_FRAMES * 2];
+static volatile uint32_t ring_head, ring_tail; /* frames: written by the sink, taken by the feeder */
+static volatile uint64_t last_sound_us; /* when the latest write that was not silence came */
+static volatile bool feeder_runs, watcher_runs;
+static uint64_t fed_frames, silent_frames, ios_frames;
+
+/* From the writer's thread, under redwood_audio.c's lock: never waits. */
+static uint32_t
+ios_sink(const int16_t *frames, uint32_t count)
+{
+ uint32_t head = ring_head, room = RING_FRAMES - (head - ring_tail), taken = count < room ? count : room;
+ bool sound = false;
+
+ for (uint32_t i = 0; i < taken; i++) {
+ int16_t left = frames[2 * i], right = frames[2 * i + 1];
+
+ ring[2 * ((head + i) % RING_FRAMES)] = left;
+ ring[2 * ((head + i) % RING_FRAMES) + 1] = right;
+ sound |= left > SILENCE || left < -SILENCE || right > SILENCE || right < -SILENCE;
+ }
+ OSMemoryBarrier();
+ ring_head = head + taken;
+ ios_frames += taken;
+ if (sound) {
+ last_sound_us = now_us();
+ }
+ return taken;
+}
+
+/* A period from the ring, the rest of it silence. */
+static void
+period_fill_ios(unsigned period)
+{
+ int16_t *samples = (int16_t *)(buffer + 4096 * period);
+ uint32_t tail = ring_tail, available = ring_head - tail, n = available < PERIOD_FRAMES ? available : PERIOD_FRAMES;
+
+ OSMemoryBarrier();
+ for (uint32_t i = 0; i < n; i++) {
+ samples[2 * i] = ring[2 * ((tail + i) % RING_FRAMES)];
+ samples[2 * i + 1] = ring[2 * ((tail + i) % RING_FRAMES) + 1];
+ }
+ bzero(samples + 2 * n, (PERIOD_FRAMES - n) * 4);
+ OSMemoryBarrier();
+ ring_tail = tail + n;
+ fed_frames += n;
+ silent_frames += PERIOD_FRAMES - n;
+ 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));
+ }
+ __asm__ volatile ("dsb sy");
+}
+
+static void
+feeder_thread(__unused void *parameter, __unused wait_result_t result)
+{
+ uint32_t sent = 0, failed = 0;
+
+ returned = 0;
+ for (unsigned p = 0; p < PERIODS; p++) {
+ period_fill_ios(p);
+ sent += period_write(p);
+ }
+ while (!stopping) {
+ uint32_t back = returned;
+
+ if (back != 0) {
+ OSBitAndAtomic(~back, &returned);
+ for (unsigned p = 0; p < PERIODS; p++) {
+ if (back & 1u << p) {
+ period_fill_ios(p);
+ if (period_write(p)) {
+ sent++;
+ } else {
+ failed++;
+ }
+ }
+ }
+ }
+ sleep_ms(2);
+ }
+ say("sound: the feeder stops: %u periods written (%u could not be sent), %u given back (%u with an error), %u underflows; "
+ "from iOS %llu frames came, %llu went to the DSP, %llu of silence filled in\n", sent, failed, written_done, write_errors,
+ underflows, ios_frames, fed_frames, silent_frames);
+ feeder_runs = false;
+ thread_terminate(current_thread());
+}
+
+/* The amplifiers on while there is sound; their status looked at every 200 ms while they are. On the sound's thread. */
+static void
+watch(void)
+{
+ bool on = false, given_up = false;
+ uint64_t last_look = 0;
+ uint32_t starts = 0;
+
+ while (!stopping) {
+ uint64_t now = now_us(), sounded = last_sound_us;
+
+ if (!on && !given_up && sounded != 0 && now - sounded < 100000) {
+ say_when("iOS plays: the amplifiers are started");
+ starts++;
+ if (!redwood_speaker_start() || !redwood_speaker_volume(below, 1)) {
+ say("sound: THE AMPLIFIERS DID NOT START; iOS's sound goes on to the DSP, unheard\n");
+ given_up = true;
+ } else {
+ on = true;
+ last_look = now_us();
+ /* (what is written now is heard after the periods already queued at the DSP: PERIODS x 20 ms) */
+ say("sound: the amplifiers are up %llu ms after the first write that was not silence; that write reaches "
+ "them %u ms after it was made, behind the periods queued at the DSP\n", (last_look - sounded) / 1000,
+ PERIODS * PERIOD_FRAMES / 48);
+ }
+ } else if (on && now - sounded > QUIET_BEFORE_OFF_US) {
+ say_when("three seconds of silence: the amplifiers are stopped");
+ redwood_speaker_stop();
+ on = false;
+ } else if (on && now - last_look >= 200000) {
+ last_look = now;
+ if (!redwood_speaker_healthy()) {
+ on = false;
+ given_up = true;
+ }
+ }
+ sleep_ms(5);
+ }
+ say("sound: the watcher stops; the amplifiers were started %u times%s\n", starts, given_up ? ", and then given up on" : "");
+ watcher_runs = false;
+}
+
/* ---- the whole ---------------------------------------------------------------------------------------- */
static bool running, taken_down;
@@ -968,6 +1116,13 @@ static bool running, taken_down;
static void
take_down(void)
{
+ stopping = true;
+ if (level >= 4) {
+ redwood_audio_set_sink("nothing", NULL);
+ }
+ for (unsigned ms = 0; ms < 3000 && (feeder_runs || watcher_runs); ms++) {
+ sleep_ms(1);
+ }
lck_mtx_lock(&sound_lock);
if (running && !taken_down) {
taken_down = true;
@@ -997,9 +1152,13 @@ sound_thread(__unused void *parameter, __unused wait_result_t result)
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 == 4) {
+ say("sound: level 4: what iOS plays, through the port, a stream and the amplifiers, until the run ends\n");
+ } else {
+ 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) {
@@ -1050,6 +1209,30 @@ sound_thread(__unused void *parameter, __unused wait_result_t result)
if (!stream_on()) {
goto out;
}
+ if (level == 4) {
+ thread_t feeder;
+
+ announce("the amplifiers, set up from Android's Music profile, powered down until iOS plays");
+ if (!redwood_speaker_prepare(acf, acf_size)) {
+ goto out;
+ }
+ redwood_adsp_fw_free(acf, acf_size);
+ acf = NULL;
+ feeder_runs = true;
+ if (kernel_thread_start(feeder_thread, NULL, &feeder) != KERN_SUCCESS) {
+ feeder_runs = false;
+ say("sound: no thread for the feeder\n");
+ goto out;
+ }
+ thread_deallocate(feeder);
+ watcher_runs = true;
+ redwood_audio_set_sink("the speakers (the audio DSP, redwood_sound.c)", ios_sink);
+ say("sound: WHAT IOS PLAYS GOES TO THE SPEAKERS from here on, %u.%03u dB under Android's level, until the run ends\n",
+ below / 8, below % 8 * 125);
+ lck_mtx_unlock(&sound_lock);
+ watch();
+ thread_terminate(current_thread());
+ }
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");
@@ -1058,7 +1241,7 @@ sound_thread(__unused void *parameter, __unused wait_result_t result)
}
}
/* (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)) {
+ if (level >= 3 && !redwood_speaker_volume(below, 50)) {
goto out;
}
if (level >= 3) {
@@ -1087,13 +1270,13 @@ redwood_sound_dsp_up(void)
if (!PE_parse_boot_argn("sound", &level, sizeof(level)) || level == 0) {
return;
}
- if (level > 3) {
- level = 3;
+ if (level > 4) {
+ level = 4;
}
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) {
+ if (level >= 2 && level <= 3 && seconds > 3) {
seconds = 3; /* the test tone: three seconds at most */
}
running = true;
diff --git a/xnu/files/bsd/dev/redwood_speaker.c b/xnu/files/bsd/dev/redwood_speaker.c
index 02bd7f8..00f88ef 100644
--- a/xnu/files/bsd/dev/redwood_speaker.c
+++ b/xnu/files/bsd/dev/redwood_speaker.c
@@ -39,8 +39,9 @@
* 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
+ * volume stepwise, 6 dB a step (the driver takes one every 100 us), 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
*
@@ -53,7 +54,7 @@
* 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
+ * I2C is done by hand: a pin is either pulled low or let go (and the pull-ups raise it), at 100
* kHz at most. For each register read or written the two pins are taken from the serial engine
* (function qup03) as GPIOs and given back as they were found right after.
*
@@ -171,7 +172,7 @@ show_pins(void)
static void
half_bit(void)
{
- spin_us(10); /* 50 kHz at most; the bus does not mind slower */
+ spin_us(5); /* 100 kHz at most, I2C's standard mode; 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). */
@@ -408,6 +409,7 @@ struct amplifier {
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 */
+ uint16_t volume_high; /* the profile's bits 15:10 of 0x05, which the volume leaves as they are */
bool prepared, started;
};
@@ -505,6 +507,7 @@ acf_profiles(const uint8_t *acf, uint64_t size)
} 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));
+ a->volume_high = value & 0xfc00;
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",
@@ -611,10 +614,9 @@ set_volume(struct amplifier *a, uint16_t volume)
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))) {
+ /* (the other bits as the profile has them and as they were written: not read first, for a quick fade) */
+ value = (uint16_t)(a->volume_high | (volume / VOLUME_STEP) << 6 | volume % VOLUME_STEP);
+ if (broken || !put(a, AW_SYSCTRL2, value)) {
return false;
}
a->volume = volume;
@@ -793,7 +795,7 @@ redwood_speaker_start(void)
}
bool
-redwood_speaker_volume(uint32_t below)
+redwood_speaker_volume(uint32_t below, uint32_t step_ms)
{
uint16_t status;
@@ -807,10 +809,10 @@ redwood_speaker_volume(uint32_t below)
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);
+ say("speaker: the amplifier %s: the volume to -%u.%03u dB (Android's level less %u.%03u dB), 6 dB a step every %u ms\n",
+ a->where, target / 8, target % 8 * 125, (target - a->volume_at) / 8, (target - a->volume_at) % 8 * 125, step_ms);
}
- /* both together, a step every 50 ms, the status looked at after every step */
+ /* both together, a step every step_ms, the status looked at after every step */
for (;;) {
bool moved = false;
@@ -829,7 +831,8 @@ redwood_speaker_volume(uint32_t below)
if (!set_volume(a, (uint16_t)next)) {
return false;
}
- if (faulty(a, &status)) {
+ /* (a slow fade looks at the status after every step, a quick one once it is over) */
+ if (step_ms >= 10 && faulty(a, &status)) {
say("speaker: the amplifier %s: status %#06x\n", a->where, status);
power_down_now("an amplifier reports a fault");
return false;
@@ -839,9 +842,11 @@ redwood_speaker_volume(uint32_t below)
if (!moved) {
break;
}
- wait_ms(50);
+ if (step_ms) {
+ wait_ms(step_ms);
+ }
}
- return true;
+ return redwood_speaker_healthy();
}
bool
diff --git a/xnu/files/bsd/sys/redwood_audio.h b/xnu/files/bsd/sys/redwood_audio.h
index 3465fb7..5aebce0 100644
--- a/xnu/files/bsd/sys/redwood_audio.h
+++ b/xnu/files/bsd/sys/redwood_audio.h
@@ -43,7 +43,7 @@ void redwood_speaker_init(void); /* boot-arg speaker_probe=N: a look at t
*/
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_volume(uint32_t below, uint32_t step_ms); /* below Android's level, in eighths of a dB; 6 dB a step */
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 */