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: the speaker's volume control, to the amplifiers; what iOS does with it

vcvkk9fa3c3cc6012
diff --git a/README.md b/README.md
index 13df687..5ea1eff 100644
--- a/README.md
+++ b/README.md
@@ -235,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=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` |
+| `sound=N` | с `adsp=1`, шаг 3 звука, путь к динамикам, как его строит Android (числа — из живого дерева устройств телефона, его путей микшера и его ядра): `sound=1` — ножки TDM (GPIO 97–100) отданы интерфейсу, звуковой процессор включает его тактовую частоту (3,072 МГц), группу и порт 0x9000 (PRI_TDM_RX_0) и запускает его; по ножкам видно, что тактовый сигнал и синхронизация кадров идут. `sound=2` — ещё и поток: наша память видна процессору через SMMU (поток 0x1801), путь ADM к порту, поток ASM, и в него 3 с пишется тон 1 кГц −20 дБ полной шкалы; процессор забирает его с частотой 48 кГц. Усилители выключены. `sound=3` — ещё и усилители: настраиваются из профиля «Music» конфигурации Android (`/vendor/etc/aw882xx_acf.bin` телефона в `fw-audio/`, в git не попадает, `userland/build.sh` кладёт её в `/fw` образа системы), каждая запись читается обратно, при любом расхождении или сбое оба сразу выключаются; громкость плавно поднимается до `sound_below` восьмых долей дБ ниже уровня Android (по умолчанию 240, то есть на 30 дБ тише), тон звучит 3 с, потом всё затихает, выключается и возвращается как было. `sound=4` — то, что играет iOS (`/dev/redwood-audio`), до конца сеанса: порт и поток работают всё время (без звука в них идёт тишина), усилители настраиваются один раз и выключены, а когда в записи iOS появляется не тишина, включаются и быстро (как у драйвера Android) выводятся на `sound_below`; после трёх секунд тишины снова выключаются. Звук доходит до усилителей через 160 мс после записи, усилители готовы через 65 мс. У динамика в модуле HAL есть регулятор громкости, его значение уходит в ядро (`ioctl` `REDWOOD_AUDIO_SET_VOLUME`) и задаёт уровень усилителей ниже потолка (0 — усилители не включаются), но iOS ставит его только раз, на максимум, а громкость кнопок и Пункта управления применяет к самим отсчётам (программная громкость для динамика iPhone X в таблицах VirtualAudio); при громкости 0 iOS пишет тишину, и усилители тоже не включаются. Проверка — `RC_JOBS=rc.jobs.volume`. `sound_secs=S` (не больше 3 с тоном), `sound_pause=MS`. Подробности в начале `bsd/dev/redwood_sound.c` и `bsd/dev/redwood_speaker.c` |
Несколько ядер на телефоне проверены (2, 4 и 7 ядер запускаются и чисто возвращаются в загрузчик). Лучший
вариант — **`cpus=4`**: четыре больших ядра (7, 6, 5, 4). На одном и том же сценарии: 929 кадров вместо 671,
diff --git a/userland/rc.jobs.volume b/userland/rc.jobs.volume
new file mode 100644
index 0000000..95267ee
--- /dev/null
+++ b/userland/rc.jobs.volume
@@ -0,0 +1,17 @@
+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).
+# The speakers' volume (boot-arg sound=4 with adsp=1): once SpringBoard is up, a tone of two seconds at
+# iOS's volume as it is, then after every few presses of the volume buttons another one -- four steps down,
+# eight up (to the top), sixteen down (to 0: the amplifiers stay off), four up. Every setting of the
+# plug-in's volume control is in the log ("redwood: audio: the volume is ..."), and the kernel's "sound:" and
+# "speaker:" lines say what the amplifiers did with it (register 0x05).
+/redwood/bin/sound_test springboard route wait 2 tone 2 wait 4
+/redwood/bin/rwtouch button voldown wait 0.5 button voldown wait 0.5 button voldown wait 0.5 button voldown wait 1
+/redwood/bin/sound_test route tone 2 wait 4
+/redwood/bin/rwtouch button volup wait 0.5 button volup wait 0.5 button volup wait 0.5 button volup wait 0.5 button volup wait 0.5 button volup wait 0.5 button volup wait 0.5 button volup wait 1
+/redwood/bin/sound_test route tone 2 wait 4
+/redwood/bin/rwtouch button voldown wait 0.3 button voldown wait 0.3 button voldown wait 0.3 button voldown wait 0.3 button voldown wait 0.3 button voldown wait 0.3 button voldown wait 0.3 button voldown wait 0.3 button voldown wait 0.3
+/redwood/bin/rwtouch button voldown wait 0.3 button voldown wait 0.3 button voldown wait 0.3 button voldown wait 0.3 button voldown wait 0.3 button voldown wait 0.3 button voldown wait 0.3 button voldown wait 1
+/redwood/bin/sound_test route tone 2 wait 4
+/redwood/bin/rwtouch button volup wait 0.5 button volup wait 0.5 button volup wait 0.5 button volup wait 1
+/redwood/bin/sound_test route tone 2 wait 4
+/bin/ps -A
diff --git a/userland/src/audio_plugin.c b/userland/src/audio_plugin.c
index 2ab8dd6..7d64a90 100644
--- a/userland/src/audio_plugin.c
+++ b/userland/src/audio_plugin.c
@@ -34,12 +34,23 @@
*
* The device has no clock but the system's: it claims to play exactly REDWOOD_AUDIO_RATE frames
* a second of mach_absolute_time(), and the HAL's I/O thread paces itself by that.
+ *
+ * The speaker's output has a volume control, as the iPhone's own speaker has: what is set on it
+ * goes to the kernel (ioctl REDWOOD_AUDIO_SET_VOLUME), which sets the amplifiers' level by it -- on
+ * the phone, so far under the loudest it allows. Its scale is 48 dB in a straight line of
+ * decibels, 3 dB for each of iOS's sixteen steps; 0 is silence. What iOS does with it (the phone,
+ * 15 October): the virtual audio device sets it once, to its top (0 dB), when it takes the
+ * device, and leaves it there -- its routing tables keep the iPhone X's speaker in software volume
+ * mode, so the volume buttons and Control Center scale the samples themselves, and at 0 what is
+ * written is silence (on which the kernel keeps the amplifiers off).
*/
#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFPlugInCOM.h>
#include <CoreAudioTypes/CoreAudioTypes.h>
#include <errno.h>
#include <fcntl.h>
+#include <math.h>
+#include <sys/ioctl.h>
#include <mach/mach_time.h>
#include <pthread.h>
#include <stdarg.h>
@@ -154,6 +165,12 @@ enum {
kAudioStreamTerminalTypeSpeaker = 'spkr', kAudioStreamTerminalTypeMicrophone = 'micr',
kAudioServerPlugInIOOperationReadInput = 'read', kAudioServerPlugInIOOperationWriteMix = 'rite',
+
+ kAudioLevelControlClassID = 'levl', kAudioVolumeControlClassID = 'vlme',
+ kAudioControlPropertyScope = 'cscp', kAudioControlPropertyElement = 'celm',
+ kAudioLevelControlPropertyScalarValue = 'lcsv', kAudioLevelControlPropertyDecibelValue = 'lcdv',
+ kAudioLevelControlPropertyDecibelRange = 'lcdr', kAudioLevelControlPropertyConvertScalarToDecibels = 'lcsd',
+ kAudioLevelControlPropertyConvertDecibelsToScalar = 'lcds',
};
/* ---- the devices ---------------------------------------------------------------------------------- */
@@ -166,9 +183,12 @@ enum {
OBJECT_PLUGIN = 1,
OBJECT_SPEAKER, OBJECT_SPEAKER_OUTPUT, OBJECT_SPEAKER_INPUT,
OBJECT_HAWKING, OBJECT_HAWKING_INPUT,
- OBJECT_LAST = OBJECT_HAWKING_INPUT
+ OBJECT_SPEAKER_VOLUME, /* the speaker output's volume control */
+ OBJECT_LAST = OBJECT_SPEAKER_VOLUME
};
+#define VOLUME_RANGE_DB 48.0 /* from the loudest the kernel allows down to the quietest step above 0 */
+
struct device {
AudioObjectID object;
CFStringRef uid; /* the name the virtual audio device knows it by */
@@ -198,6 +218,7 @@ static int sink = -1; /* /dev/redwood-audio */
static Float64 ticks_per_frame;
static UInt64 written, refused; /* frames since the speaker's I/O started */
static Boolean inactive[OBJECT_LAST + 1]; /* streams the HAL has switched off */
+static Float32 volume = 1.0f; /* the speaker's volume control, 0 to 1 (iOS sets it once it routes there) */
static void
say(const char *format, ...)
@@ -215,6 +236,36 @@ say(const char *format, ...)
write(2, line, (size_t)n);
}
+/* The volume control's scale: a straight line of decibels over VOLUME_RANGE_DB. */
+static Float32
+scalar_to_db(Float32 scalar)
+{
+ scalar = scalar < 0 ? 0 : scalar > 1 ? 1 : scalar;
+ return (Float32)(-VOLUME_RANGE_DB * (1.0 - scalar));
+}
+
+static Float32
+db_to_scalar(Float32 db)
+{
+ Float32 scalar = (Float32)(1.0 + db / VOLUME_RANGE_DB);
+
+ return scalar < 0 ? 0 : scalar > 1 ? 1 : scalar;
+}
+
+/* The volume, to the kernel. With the lock held. */
+static void
+volume_to_kernel(void)
+{
+ struct redwood_audio_volume v = { (uint32_t)lround(-scalar_to_db(volume) * 8), volume <= 0 };
+
+ if (sink < 0 || ioctl(sink, REDWOOD_AUDIO_SET_VOLUME, &v) < 0) {
+ say("redwood: audio: the volume %.3f could not be given to the kernel (%s)\n", volume, strerror(errno));
+ return;
+ }
+ say("redwood: audio: the volume is %.3f: %s%.1f dB under the loudest\n", volume, v.muted ? "silence, " : "",
+ v.below / 8.0);
+}
+
/* The device with this object number, or the one this stream belongs to; NULL = neither. */
static struct device *
device_of(AudioObjectID object)
@@ -316,6 +367,7 @@ struct value {
union {
UInt32 words[4];
Float64 number;
+ Float32 decimal;
CFStringRef string;
AudioValueRange range;
AudioStreamBasicDescription format;
@@ -334,6 +386,45 @@ property(AudioObjectID object, const AudioObjectPropertyAddress *address, UInt32
#define WORD(x) (v.u.words[0] = (x), v.size = sizeof(UInt32))
#define LIST(x) (v.u.words[v.size / sizeof(UInt32)] = (x), v.size += sizeof(UInt32))
#define STRING(x) (v.u.string = (x), v.string = true, v.size = sizeof(CFStringRef))
+#define FLOAT(x) (v.u.decimal = (x), v.size = sizeof(Float32))
+ if (object == OBJECT_SPEAKER_VOLUME) {
+ switch (selector) {
+ case kAudioObjectPropertyBaseClass:
+ WORD(kAudioLevelControlClassID);
+ break;
+ case kAudioObjectPropertyClass:
+ WORD(kAudioVolumeControlClassID);
+ break;
+ case kAudioObjectPropertyOwner:
+ WORD(OBJECT_SPEAKER);
+ break;
+ case kAudioObjectPropertyOwnedObjects:
+ v.empty = true;
+ break;
+ case kAudioControlPropertyScope:
+ WORD(kAudioObjectPropertyScopeOutput);
+ break;
+ case kAudioControlPropertyElement:
+ WORD(0);
+ break;
+ case kAudioLevelControlPropertyScalarValue:
+ FLOAT(volume);
+ break;
+ case kAudioLevelControlPropertyDecibelValue:
+ FLOAT(scalar_to_db(volume));
+ break;
+ case kAudioLevelControlPropertyDecibelRange:
+ v.u.range.mMinimum = -VOLUME_RANGE_DB;
+ v.u.range.mMaximum = 0;
+ v.size = sizeof(AudioValueRange);
+ break;
+ case kAudioLevelControlPropertyConvertScalarToDecibels:
+ case kAudioLevelControlPropertyConvertDecibelsToScalar:
+ FLOAT(0); /* (converts what it is given: get_property_data()) */
+ break;
+ }
+ return v;
+ }
if (object != OBJECT_PLUGIN && d == NULL) {
return v;
}
@@ -412,17 +503,23 @@ property(AudioObjectID object, const AudioObjectPropertyAddress *address, UInt32
break;
case kAudioObjectPropertyOwnedObjects:
case kAudioDevicePropertyStreams:
- /* the streams of one direction, or of both */
+ /* the streams of one direction, or of both (and the speaker's volume control, which it owns) */
if (scope != kAudioObjectPropertyScopeInput && d->output != 0) {
LIST(d->output);
}
if (scope != kAudioObjectPropertyScopeOutput && d->input != 0) {
LIST(d->input);
}
+ if (selector == kAudioObjectPropertyOwnedObjects && d->object == OBJECT_SPEAKER) {
+ LIST(OBJECT_SPEAKER_VOLUME);
+ }
v.empty = v.size == 0;
break;
case kAudioObjectPropertyControlList:
- v.empty = true;
+ if (d->object == OBJECT_SPEAKER) {
+ LIST(OBJECT_SPEAKER_VOLUME);
+ }
+ v.empty = v.size == 0;
break;
case kAudioDevicePropertyNominalSampleRate:
v.u.number = REDWOOD_AUDIO_RATE;
@@ -474,6 +571,7 @@ property(AudioObjectID object, const AudioObjectPropertyAddress *address, UInt32
#undef WORD
#undef LIST
#undef STRING
+#undef FLOAT
return v;
}
@@ -499,8 +597,11 @@ is_property_settable(AudioServerPlugInDriverRef driver, AudioObjectID object, pi
if (address == NULL || settable == NULL || !has_property(driver, object, client, address)) {
return kAudioHardwareUnknownPropertyError;
}
- /* the rate and the formats can be "set", to the ones there are */
- if (object == OBJECT_PLUGIN) {
+ /* the rate and the formats can be "set", to the ones there are; the volume can be set */
+ if (object == OBJECT_SPEAKER_VOLUME) {
+ *settable = address->mSelector == kAudioLevelControlPropertyScalarValue ||
+ address->mSelector == kAudioLevelControlPropertyDecibelValue;
+ } else if (object == OBJECT_PLUGIN) {
*settable = false;
} else if (object == d->object) {
*settable = address->mSelector == kAudioDevicePropertyNominalSampleRate;
@@ -532,6 +633,17 @@ get_property_data(AudioServerPlugInDriverRef driver, AudioObjectID object, pid_t
if (address == NULL || size == NULL || data == NULL || !has_property(driver, object, client, address)) {
return object < OBJECT_PLUGIN || object > OBJECT_LAST ? kAudioHardwareBadObjectError : kAudioHardwareUnknownPropertyError;
}
+ if (object == OBJECT_SPEAKER_VOLUME && (address->mSelector == kAudioLevelControlPropertyConvertScalarToDecibels ||
+ address->mSelector == kAudioLevelControlPropertyConvertDecibelsToScalar)) {
+ /* what is in the buffer, converted where it is */
+ if (room < sizeof(Float32)) {
+ return kAudioHardwareBadPropertySizeError;
+ }
+ *(Float32 *)data = address->mSelector == kAudioLevelControlPropertyConvertScalarToDecibels ?
+ scalar_to_db(*(Float32 *)data) : db_to_scalar(*(Float32 *)data);
+ *size = sizeof(Float32);
+ return 0;
+ }
pthread_mutex_lock(&lock);
v = property(object, address, qualifier_size, qualifier);
pthread_mutex_unlock(&lock);
@@ -564,6 +676,28 @@ set_property_data(AudioServerPlugInDriverRef driver, AudioObjectID object, pid_t
if (!settable) {
return kAudioHardwareIllegalOperationError;
}
+ if (object == OBJECT_SPEAKER_VOLUME) {
+ AudioObjectPropertyAddress changed[2] = {
+ { kAudioLevelControlPropertyScalarValue, kAudioObjectPropertyScopeGlobal, 0 },
+ { kAudioLevelControlPropertyDecibelValue, kAudioObjectPropertyScopeGlobal, 0 },
+ };
+ Float32 wanted;
+
+ if (size != sizeof(Float32)) {
+ return kAudioHardwareBadPropertySizeError;
+ }
+ wanted = *(const Float32 *)data;
+ wanted = address->mSelector == kAudioLevelControlPropertyDecibelValue ? db_to_scalar(wanted) :
+ wanted < 0 ? 0 : wanted > 1 ? 1 : wanted;
+ pthread_mutex_lock(&lock);
+ volume = wanted;
+ volume_to_kernel();
+ pthread_mutex_unlock(&lock);
+ if (host != NULL) {
+ host->PropertiesChanged(host, OBJECT_SPEAKER_VOLUME, 2, changed);
+ }
+ return 0;
+ }
if (address->mSelector == kAudioStreamPropertyIsActive) {
if (size != sizeof(UInt32)) {
return kAudioHardwareBadPropertySizeError;
diff --git a/userland/src/redwood_audio.h b/userland/src/redwood_audio.h
index 9cefd3f..650cfe8 100644
--- a/userland/src/redwood_audio.h
+++ b/userland/src/redwood_audio.h
@@ -23,7 +23,23 @@
#define REDWOOD_AUDIO_CHANNELS 2
#define REDWOOD_AUDIO_FRAME 4 /* bytes */
+/*
+ * ioctl(REDWOOD_AUDIO_SET_VOLUME): the speakers' volume, as iOS sets it on the plug-in's volume
+ * control -- how many eighths of a dB under the loudest they may play, and whether they are
+ * muted (iOS's volume at 0). The loudest is the kernel's to say (on the phone: Android's own
+ * level less sound_below, redwood_sound.c); the plug-in only says how far under it.
+ */
+#include <sys/ioccom.h>
+
+struct redwood_audio_volume {
+ uint32_t below; /* eighths of a dB */
+ uint32_t muted;
+};
+#define REDWOOD_AUDIO_SET_VOLUME _IOW('r', 1, struct redwood_audio_volume)
+
#ifdef KERNEL
+#include <stdbool.h>
+
/*
* For drivers. A sink is offered frames as they are written and says how many it took (the
* rest are lost); it is called from the writer's thread and must not wait.
@@ -31,9 +47,46 @@
typedef uint32_t (*redwood_audio_sink_t)(const int16_t *frames, uint32_t count);
void redwood_audio_set_sink(const char *name, redwood_audio_sink_t sink);
+/* The volume iOS has set last (REDWOOD_AUDIO_SET_VOLUME): false if it has set none; *generation counts the settings. */
+bool redwood_audio_volume(uint32_t *below, bool *muted, uint32_t *generation);
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 */
+
+/*
+ * 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, 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 */
+
+/*
+ * 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/files/bsd/dev/redwood_audio.c b/xnu/files/bsd/dev/redwood_audio.c
index 47e675e..6fe8467 100644
--- a/xnu/files/bsd/dev/redwood_audio.c
+++ b/xnu/files/bsd/dev/redwood_audio.c
@@ -222,9 +222,42 @@ audio_write(__unused dev_t dev, struct uio *uio, __unused int ioflag)
return error;
}
+/* the speakers' volume, as iOS sets it (sys/redwood_audio.h): kept for the sink's driver to look at */
+static uint32_t volume_below, volume_generation;
+static bool volume_muted;
+
+static int
+audio_ioctl(__unused dev_t dev, u_long command, caddr_t data, __unused int flags, __unused struct proc *p)
+{
+ const struct redwood_audio_volume *volume = (const struct redwood_audio_volume *)data;
+
+ if (command != REDWOOD_AUDIO_SET_VOLUME) {
+ return ENOTTY;
+ }
+ lck_mtx_lock(&audio_lock);
+ volume_below = volume->below;
+ volume_muted = volume->muted != 0;
+ volume_generation++;
+ lck_mtx_unlock(&audio_lock);
+ printf("redwood-audio: the volume: %s%u.%03u dB under the loudest\n", volume->muted ? "muted; " : "", volume->below / 8,
+ volume->below % 8 * 125);
+ return 0;
+}
+
+bool
+redwood_audio_volume(uint32_t *below, bool *muted, uint32_t *generation)
+{
+ lck_mtx_lock(&audio_lock);
+ *below = volume_below;
+ *muted = volume_muted;
+ *generation = volume_generation;
+ lck_mtx_unlock(&audio_lock);
+ return *generation != 0;
+}
+
static const struct cdevsw audio_cdevsw = {
.d_open = audio_open, .d_close = audio_close, .d_read = eno_rdwrt, .d_write = audio_write,
- .d_ioctl = eno_ioctl, .d_stop = eno_stop, .d_reset = eno_reset, .d_select = eno_select,
+ .d_ioctl = audio_ioctl, .d_stop = eno_stop, .d_reset = eno_reset, .d_select = eno_select,
.d_mmap = eno_mmap, .d_strategy = eno_strat, .d_type = 0
};
diff --git a/xnu/files/bsd/dev/redwood_sound.c b/xnu/files/bsd/dev/redwood_sound.c
index cef6912..0bc6882 100644
--- a/xnu/files/bsd/dev/redwood_sound.c
+++ b/xnu/files/bsd/dev/redwood_sound.c
@@ -28,7 +28,12 @@
* 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
+ * fade) whenever a write is not silence, stopped after three seconds of silence; their
+ * level is what is set on the plug-in's volume control (ioctl REDWOOD_AUDIO_SET_VOLUME):
+ * so far under sound_below, which stays the loudest, and at 0 they stay off. (iOS sets
+ * that control only once, to the top, and applies its volume to the samples itself --
+ * see userland/src/audio_plugin.c --; at its volume 0 it writes silence, and the
+ * amplifiers stay off for that too.)
*
* 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,
@@ -985,6 +990,7 @@ static volatile uint32_t ring_head, ring_tail; /* frames: written by the sink,
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;
+static volatile uint32_t ios_peak; /* the largest sample since the amplifiers last started */
/* From the writer's thread, under redwood_audio.c's lock: never waits. */
static uint32_t
@@ -995,10 +1001,14 @@ ios_sink(const int16_t *frames, uint32_t count)
for (uint32_t i = 0; i < taken; i++) {
int16_t left = frames[2 * i], right = frames[2 * i + 1];
+ uint32_t l = left < 0 ? (uint32_t)-(int32_t)left : (uint32_t)left, r = right < 0 ? (uint32_t)-(int32_t)right : (uint32_t)right;
ring[2 * ((head + i) % RING_FRAMES)] = left;
ring[2 * ((head + i) % RING_FRAMES) + 1] = right;
- sound |= left > SILENCE || left < -SILENCE || right > SILENCE || right < -SILENCE;
+ sound |= l > SILENCE || r > SILENCE;
+ if (l > ios_peak || r > ios_peak) {
+ ios_peak = l > r ? l : r;
+ }
}
OSMemoryBarrier();
ring_head = head + taken;
@@ -1067,21 +1077,44 @@ feeder_thread(__unused void *parameter, __unused wait_result_t result)
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. */
+/*
+ * The amplifiers on while there is sound, at the volume iOS has set (redwood_audio_volume(): how
+ * far under the loudest, sound_below under Android's level), and off while iOS's volume is 0;
+ * their status looked at every 200 ms while they are on. On the sound's thread.
+ */
static void
watch(void)
{
- bool on = false, given_up = false;
+ bool on = false, given_up = false, muted = false;
uint64_t last_look = 0;
- uint32_t starts = 0;
+ uint32_t starts = 0, changes = 0, generation = 0, extra = 0;
while (!stopping) {
uint64_t now = now_us(), sounded = last_sound_us;
-
- if (!on && !given_up && sounded != 0 && now - sounded < 100000) {
+ uint32_t extra_now, generation_now;
+ bool muted_now;
+
+ if (redwood_audio_volume(&extra_now, &muted_now, &generation_now) && generation_now != generation) {
+ generation = generation_now;
+ extra = extra_now;
+ muted = muted_now;
+ changes++;
+ say("sound: iOS sets the volume: %s%u.%03u dB under the loudest, which is %u.%03u dB under Android's level%s\n",
+ muted ? "muted (0), " : "", extra / 8, extra % 8 * 125, below / 8, below % 8 * 125,
+ on ? (muted ? ": the amplifiers are stopped" : ": the amplifiers follow") : "");
+ if (on && muted) {
+ redwood_speaker_stop();
+ on = false;
+ } else if (on && !redwood_speaker_volume(below + extra, 1)) {
+ on = false;
+ given_up = true;
+ }
+ }
+ if (!on && !given_up && !muted && sounded != 0 && now - sounded < 100000) {
say_when("iOS plays: the amplifiers are started");
starts++;
- if (!redwood_speaker_start() || !redwood_speaker_volume(below, 1)) {
+ ios_peak = 0;
+ if (!redwood_speaker_start() || !redwood_speaker_volume(below + extra, 1)) {
say("sound: THE AMPLIFIERS DID NOT START; iOS's sound goes on to the DSP, unheard\n");
given_up = true;
} else {
@@ -1094,6 +1127,8 @@ watch(void)
}
} else if (on && now - sounded > QUIET_BEFORE_OFF_US) {
say_when("three seconds of silence: the amplifiers are stopped");
+ say("sound: what iOS wrote while they were on peaked at %u%% of full scale (%u)\n", ios_peak * 100 / 32768,
+ ios_peak);
redwood_speaker_stop();
on = false;
} else if (on && now - last_look >= 200000) {
@@ -1105,7 +1140,8 @@ watch(void)
}
sleep_ms(5);
}
- say("sound: the watcher stops; the amplifiers were started %u times%s\n", starts, given_up ? ", and then given up on" : "");
+ say("sound: the watcher stops; the amplifiers were started %u times, iOS set the volume %u times%s\n", starts, changes,
+ given_up ? ", and the amplifiers were then given up on" : "");
watcher_runs = false;
}
diff --git a/xnu/files/bsd/sys/redwood_audio.h b/xnu/files/bsd/sys/redwood_audio.h
index 5aebce0..650cfe8 100644
--- a/xnu/files/bsd/sys/redwood_audio.h
+++ b/xnu/files/bsd/sys/redwood_audio.h
@@ -23,7 +23,23 @@
#define REDWOOD_AUDIO_CHANNELS 2
#define REDWOOD_AUDIO_FRAME 4 /* bytes */
+/*
+ * ioctl(REDWOOD_AUDIO_SET_VOLUME): the speakers' volume, as iOS sets it on the plug-in's volume
+ * control -- how many eighths of a dB under the loudest they may play, and whether they are
+ * muted (iOS's volume at 0). The loudest is the kernel's to say (on the phone: Android's own
+ * level less sound_below, redwood_sound.c); the plug-in only says how far under it.
+ */
+#include <sys/ioccom.h>
+
+struct redwood_audio_volume {
+ uint32_t below; /* eighths of a dB */
+ uint32_t muted;
+};
+#define REDWOOD_AUDIO_SET_VOLUME _IOW('r', 1, struct redwood_audio_volume)
+
#ifdef KERNEL
+#include <stdbool.h>
+
/*
* For drivers. A sink is offered frames as they are written and says how many it took (the
* rest are lost); it is called from the writer's thread and must not wait.
@@ -31,12 +47,12 @@
typedef uint32_t (*redwood_audio_sink_t)(const int16_t *frames, uint32_t count);
void redwood_audio_set_sink(const char *name, redwood_audio_sink_t sink);
+/* The volume iOS has set last (REDWOOD_AUDIO_SET_VOLUME): false if it has set none; *generation counts the settings. */
+bool redwood_audio_volume(uint32_t *below, bool *muted, uint32_t *generation);
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).