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

Vibration: the phone's motor driver brought up and one waveform played (haptic=1..4)

vcvkk34fd064f6ccd
diff --git a/README.md b/README.md
index 41af7b6..a622dc8 100644
--- a/README.md
+++ b/README.md
@@ -267,6 +267,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #
| `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 дБ тише; выше уровня Android — никогда), тон звучит 3 с, потом всё затихает, выключается и возвращается как было. `sound=4` — то, что играет iOS (`/dev/redwood-audio`), до конца сеанса: порт и поток работают всё время (без звука в них идёт тишина), усилители настраиваются один раз и выключены, а когда в записи iOS появляется не тишина, включаются и быстро (как у драйвера Android) выводятся на `sound_below`; после трёх секунд тишины снова выключаются. Звук доходит до усилителей через 160 мс после записи, усилители готовы через 65 мс. У динамика в модуле HAL есть регулятор громкости, его значение уходит в ядро (`ioctl` `REDWOOD_AUDIO_SET_VOLUME`) и задаёт уровень усилителей ниже потолка (0 — усилители не включаются), но iOS ставит его только раз, на максимум, а громкость кнопок и Пункта управления применяет к самим отсчётам (программная громкость для динамика iPhone X в таблицах VirtualAudio); при громкости 0 iOS пишет тишину, и усилители тоже не включаются. Проверка — `RC_JOBS=rc.jobs.volume`. По пути к усилителям — сторож (см. выше): `sound_gain=N` (восьмые доли дБ, 0–96), `sound_guard_as=N` (для проверки: сторож считает усилители на N ниже уровня Android и сдерживает, как сдерживал бы там). `sound_secs=S` (не больше 3 с тоном), `sound_pause=MS`. Подробности в начале `bsd/dev/redwood_sound.c` и `bsd/dev/redwood_speaker.c` |
+| `haptic=N` | моторчик вибрации: Awinic AW86927 на I2C (шина QUP SE9, GPIO 36/37, адрес 0x5a; сброс — GPIO 35), линейный мотор с резонансом 175,5 Гц; всё — из живого дерева устройств Android, его журнала и регистров (`bsd/dev/redwood_haptic.c`). `haptic=1` — только читать: из загрузчика Android сброс держит чип выключенным, он не отвечает. `haptic=2` — сброс отпущен, как это делает драйвер Android, регистры прочитаны и сравнены с Android. `haptic=3` — ещё и настройка Android (каждая запись читается обратно; аналоговые регистры — за разблокировкой 0x5b) и волновые формы Android (`/vendor/firmware/aw8697_haptic.bin` телефона в `fw-haptic/`, в git не попадает; `userland/build.sh` кладёт его в `fw/` малого образа) в ОЗУ чипа, с проверкой чтением. `haptic=4` — ещё и одна короткая форма (`haptic_effect=1…10`) один раз, с усилением Android. Любая неисправность, о которой говорит чип, несовпадение при чтении или неотвеченный байт — чип снова в сброс до конца сеанса; не дольше 1 с на эффект; в конце сеанса и при панике — сброс |
| `battmgr=0` | с `adsp=1` батарея не спрашивается. Без него (по умолчанию) ядро раз в 10 с спрашивает у звукового процессора, который у этого телефона и ведёт батарею с зарядкой (как Android — `qti_battery_charger`, Linux — `qcom_battmgr` поверх `pmic_glink`), по каналу `PMIC_RTR_ADSP_APPS` процент заряда, зарядку, напряжение, ток, температуру, заряд в мА·ч, ёмкость, циклы и что даёт порт USB — только читает, ни пределов, ни токов не задаёт — и показывает это iOS так же, как батарея iPhone: службой `RedwoodBattery` класса `IOPMPowerSource` (`iokit/Kernel/RedwoodBattery.cpp`). Её читает powerd, и дальше всё делает сама iOS: батарея с процентом и молнией в строке состояния, «58% Charged» на экране блокировки, виджет «Батареи», Настройки → Аккумулятор (переключатель «Заряд в процентах» работает; в образе он включён); перехваты батареи в SpringBoard при этой службе уступают iOS. Сверено с Android (`dumpsys battery` и `/sys/class/power_supply/battery` сразу после): 56 % и 58 %, «заряжается», напряжение, температура, заряд, ёмкость 3677 из 5000 мА·ч, 890 циклов совпадают. Номера свойств — этой прошивки: до 9-го как у Linux, дальше на один больше; `battmgr=2` пишет в журнал все. Те же числа — в `kern.redwood.battery_*`. С `battery=1` (путь загрузчика через UEFI) не включается. Не показываются история заряда (нужен powerlogd) и износ в «Состоянии аккумулятора» (powerd ждёт серийный номер батареи, а его прошивка не даёт). Проверка — `RC_JOBS=rc.jobs.battery` (`battery_test`) |
Несколько ядер на телефоне проверены (2, 4 и 7 ядер запускаются и чисто возвращаются в загрузчик). На одном и
diff --git a/userland/build.sh b/userland/build.sh
index 3375138..a6e4d41 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -220,6 +220,12 @@ if [ -f ../fw-wifi/wpss.mdt ]; then
rm -f root/fw/network
[ -f ../fw-wifi/network ] && install -m 0600 ../fw-wifi/network root/fw/network
fi
+# ... and the vibration motor's waveforms, the phone's /vendor/firmware/aw8697_haptic.bin, from ../fw-haptic
+# (bsd/dev/redwood_haptic.c, haptic=3; 3.6 KB, the vendor's and not in the repository either)
+if [ -f ../fw-haptic/aw8697_haptic.bin ]; then
+ mkdir -p root/fw
+ install -m 0644 ../fw-haptic/aw8697_haptic.bin root/fw/
+fi
# ... and with ADSP=1 the image of the audio DSP, from the same place into ../fw-audio (bsd/dev/redwood_adsp.c):
# adsp.mdt and adsp.b02 to adsp.b36, 20 MB. Only when asked for: beside GL=1 the payload would be more than the 64 MB
# the loader takes.
diff --git a/xnu/files/bsd/dev/redwood_audio.c b/xnu/files/bsd/dev/redwood_audio.c
index 7f14bb9..9509615 100644
--- a/xnu/files/bsd/dev/redwood_audio.c
+++ b/xnu/files/bsd/dev/redwood_audio.c
@@ -335,4 +335,5 @@ redwood_audio_init(void)
audio_recording_init();
redwood_virtio_sound_init();
redwood_speaker_init();
+ redwood_haptic_init();
}
diff --git a/xnu/files/bsd/dev/redwood_haptic.c b/xnu/files/bsd/dev/redwood_haptic.c
new file mode 100644
index 0000000..690fe92
--- /dev/null
+++ b/xnu/files/bsd/dev/redwood_haptic.c
@@ -0,0 +1,709 @@
+/*
+ * The vibration motor of the POCO X5 Pro (redwood): a linear resonant actuator driven by an
+ * Awinic AW86927 (chip ID 0x9270), Android's "haptic_hv" (Xiaomi's driver aw8692x, version 1.7.0).
+ * Every address and number below belongs to this phone, from Android's own device tree, its
+ * kernel's log and the chip's registers as Android leaves them (read from sysfs, read-only):
+ *
+ * I2C the serial engine 9 (qupv3_se9_i2c at 0xa84000, function qup11 on GPIO 36 data and
+ * 37 clock, internal pull-ups, 400 kHz under Android), address 0x5a; done by hand here
+ * as for the amplifiers (redwood_speaker.c), the two pins taken for each transaction
+ * and given back as they were found
+ * reset GPIO 35, high = running (Android: low for 5 ms, then high, at its driver's start)
+ * interrupt GPIO 18, pulled up, low when the chip has something to say (not used: polled)
+ * the motor f0 175.5 Hz as Android calibrated it (f0_pre 170.0 Hz, calibration data 0x0d)
+ * effects Android's RAM waveforms, /vendor/firmware/aw8697_haptic.bin of the phone (fw-haptic/
+ * here, not in the repository; userland/build.sh puts it into /fw of the system image):
+ * eleven of them, 1..10 short (Android's effects 0..9), 11 the one looped for a
+ * vibration of some length
+ *
+ * Nothing here is done unless a boot-arg asks for it:
+ *
+ * haptic=1 a look, reading only: the pins, and whether the chip answers (its ID and registers,
+ * against what Android leaves in them). Out of Android's bootloader the reset pin is an
+ * input with a pull-down: the chip is held in reset and does not answer.
+ * haptic=2 ... and the reset released as Android's driver releases it (low 5 ms, then high; it
+ * stays released until the run ends), and the chip's registers read as they come out
+ * of reset, against Android's. Nothing is written to the chip.
+ * haptic=3 ... and Android's configuration written (every write read back), Android's
+ * waveforms loaded into its RAM and read back; then standby. Nothing moves.
+ * haptic=4 ... and one short effect played (haptic_effect=N, default 1: Android's effect 0)
+ *
+ * Limits, whatever asks: Android's own values only (its gain 0x80, its boost and drive levels, its
+ * waveforms); no effect longer than HAPTIC_MAX_MS, and the chip is told to stop and put into
+ * standby when that is over whether it has stopped or not; any fault the chip reports (under-
+ * voltage, over-current, over-temperature, the boost's short circuit or over-voltage), a write that
+ * does not read back or a byte nobody acknowledges, and the chip is put into reset and nothing more
+ * is done for the rest of the run. At the run's end (and on a panic's way out) the chip goes back
+ * into reset. Nothing is written anywhere but to the chip's registers and its RAM.
+ */
+#include <kern/clock.h>
+#include <kern/thread.h>
+#include <libkern/libkern.h>
+#include <mach/mach_types.h>
+#include <machine/machine_routines.h>
+#include <pexpert/pexpert.h>
+#include <sys/systm.h>
+#include <sys/redwood_audio.h>
+#include <sys/redwood_input.h>
+
+extern vm_offset_t ml_io_map(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;
+static uint32_t level;
+static bool broken, released, leaving;
+
+/* every line to the loader's log as well (and to the console when that may be written) */
+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 && ml_get_interrupts_enabled()) {
+ printf("%s", line);
+ }
+ return length;
+}
+
+static inline uint32_t
+rd(vm_offset_t address)
+{
+ return *(volatile uint32_t *)address;
+}
+
+static inline void
+wr(vm_offset_t address, uint32_t value)
+{
+ *(volatile uint32_t *)address = value;
+}
+
+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
+#define TLMM_SIZE 0x100000UL
+#define GPIO_CFG(n) (tlmm + 0x1000UL * (n)) /* [1:0] pull, [5:2] function, [8:6] drive, [9] output */
+#define GPIO_IO(n) (tlmm + 0x1000UL * (n) + 4) /* bit 0 in, bit 1 out */
+#define CFG_PULL_UP 3
+#define CFG_OUTPUT (1u << 9)
+
+#define PIN_SDA 36 /* the serial engine's first pin is the data line, the second the clock */
+#define PIN_SCL 37
+#define PIN_RESET 35
+#define PIN_INT 18
+
+static void
+show_pins(void)
+{
+ static const struct {
+ unsigned pin;
+ const char *what;
+ } pins[] = { { PIN_SDA, "I2C data" }, { PIN_SCL, "I2C clock" }, { PIN_RESET, "reset" }, { PIN_INT, "interrupt" } };
+
+ 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));
+
+ say("haptic: 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);
+ }
+}
+
+/* the reset pin as an output of the GPIO function, driving `high' (2 mA, no pull, as Android has it) */
+static void
+reset_pin(bool high)
+{
+ wr(GPIO_IO(PIN_RESET), high ? 2 : 0);
+ wr(GPIO_CFG(PIN_RESET), CFG_OUTPUT);
+ released = high;
+}
+
+/* ---- I2C by hand (as in redwood_speaker.c) ---------------------------------------------------------- */
+
+static void
+half_bit(void)
+{
+ spin_us(5); /* 100 kHz at most */
+}
+
+static void
+line(unsigned pin, bool high)
+{
+ wr(GPIO_IO(pin), 0);
+ wr(GPIO_CFG(pin), CFG_PULL_UP | (high ? 0 : CFG_OUTPUT));
+}
+
+static bool
+level_of(unsigned pin)
+{
+ return rd(GPIO_IO(pin)) & 1;
+}
+
+static void
+i2c_start(void)
+{
+ line(PIN_SDA, true);
+ line(PIN_SCL, true);
+ half_bit();
+ line(PIN_SDA, false);
+ half_bit();
+ line(PIN_SCL, false);
+ half_bit();
+}
+
+static void
+i2c_stop(void)
+{
+ line(PIN_SDA, false);
+ half_bit();
+ line(PIN_SCL, true);
+ half_bit();
+ line(PIN_SDA, true);
+ half_bit();
+}
+
+static bool
+i2c_bit(bool out)
+{
+ bool in;
+
+ line(PIN_SDA, out);
+ half_bit();
+ line(PIN_SCL, true);
+ for (unsigned stretched = 0; !level_of(PIN_SCL) && stretched < 100; stretched++) {
+ half_bit();
+ }
+ half_bit();
+ in = level_of(PIN_SDA);
+ line(PIN_SCL, false);
+ return in;
+}
+
+static bool
+i2c_write(uint8_t byte)
+{
+ for (int bit = 7; bit >= 0; bit--) {
+ i2c_bit((byte >> bit) & 1);
+ }
+ return !i2c_bit(true);
+}
+
+static uint8_t
+i2c_read(bool more)
+{
+ uint8_t byte = 0;
+
+ for (int bit = 7; bit >= 0; bit--) {
+ byte = (uint8_t)(byte << 1 | i2c_bit(true));
+ }
+ i2c_bit(!more);
+ return byte;
+}
+
+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_of(PIN_SDA) || !level_of(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]);
+ say("haptic: the I2C bus is not at rest (gpio%u reads %u, gpio%u reads %u): not touched\n", PIN_SDA,
+ level_of(PIN_SDA), PIN_SCL, level_of(PIN_SCL));
+ 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]);
+}
+
+#define AW_ADDRESS 0x5a
+
+/* `count' 8-bit registers from `reg' on (the chip's address counts up, but for its RAM data port) */
+static bool
+regs_read(uint8_t reg, uint8_t *values, unsigned count)
+{
+ bool answered;
+
+ if (!bus_take()) {
+ return false;
+ }
+ i2c_start();
+ answered = i2c_write(AW_ADDRESS << 1) && i2c_write(reg);
+ if (answered) {
+ i2c_start();
+ answered = i2c_write(AW_ADDRESS << 1 | 1);
+ }
+ for (unsigned i = 0; answered && i < count; i++) {
+ values[i] = i2c_read(i + 1 < count);
+ }
+ i2c_stop();
+ bus_give_back();
+ return answered;
+}
+
+static bool
+regs_write(uint8_t reg, const uint8_t *values, unsigned count)
+{
+ bool answered;
+
+ if (!bus_take()) {
+ return false;
+ }
+ i2c_start();
+ answered = i2c_write(AW_ADDRESS << 1) && i2c_write(reg);
+ for (unsigned i = 0; answered && i < count; i++) {
+ answered = i2c_write(values[i]);
+ }
+ i2c_stop();
+ bus_give_back();
+ return answered;
+}
+
+/* ---- the chip -------------------------------------------------------------------------------------- */
+
+#define AW_RSTCFG 0x00 /* 0xaa: a soft reset */
+#define AW_SYSST 0x01
+#define AW_SYSINT 0x02 /* read: cleared */
+#define AW_SYSINTM 0x03
+#define AW_PLAYCFG1 0x06 /* [7] boost on, [6:0] its voltage */
+#define AW_PLAYCFG2 0x07 /* the gain */
+#define AW_PLAYCFG3 0x08 /* [1:0] the play mode: 0 RAM */
+#define AW_PLAYCFG4 0x09 /* [1] stop, [0] go */
+#define AW_WAVCFG1 0x0a /* the first waveform to play, 1..127 (0: the end) */
+#define AW_WAVCFG2 0x0b
+#define AW_WAVCFG9 0x12 /* [7:4] how often the first is repeated, 15: until told to stop */
+#define AW_BASEADDRH 0x2d
+#define AW_BASEADDRL 0x2e
+#define AW_GLBRD5 0x3f /* [3:0] the state: 0 standby */
+#define AW_RAMADDRH 0x40
+#define AW_RAMADDRL 0x41
+#define AW_RAMDATA 0x42
+#define AW_SYSCTRL3 0x45 /* [5] standby, [2] the RAM open for loading */
+#define AW_TMCFG 0x5b /* 0x7d opens the analog registers 0x70.. for writing, 0 closes them */
+#define AW_TRIM_LRA 0x79 /* the motor's f0 calibration */
+#define AW_CHIPIDH 0x57
+#define AW_CHIPIDL 0x58
+#define AW_CHIPID 0x9270
+
+#define SYSINT_FAULTS 0xe6 /* boost short circuit and over-voltage, under-voltage, over-current, over-temperature */
+#define HAPTIC_MAX_MS 1000
+
+static void
+give_up(const char *why)
+{
+ broken = true;
+ say("haptic: %s: THE CHIP IS PUT INTO RESET (gpio%u low) and nothing more is done\n", why, PIN_RESET);
+ if (tlmm != 0) {
+ reset_pin(false);
+ }
+}
+
+static bool
+get(uint8_t reg, uint8_t *value)
+{
+ if (!regs_read(reg, value, 1)) {
+ say("haptic: %#04x NOT READ\n", reg);
+ return false;
+ }
+ return true;
+}
+
+/* One register written and read back. */
+static bool
+put(uint8_t reg, uint8_t value)
+{
+ uint8_t after = 0;
+
+ if (broken) {
+ return false;
+ }
+ if (!regs_write(reg, &value, 1)) {
+ say("haptic: %#04x <- %#04x NOT ACKNOWLEDGED\n", reg, value);
+ give_up("a write was not acknowledged");
+ return false;
+ }
+ if (!regs_read(reg, &after, 1)) {
+ give_up("a register could not be read back");
+ return false;
+ }
+ say("haptic: %#04x <- %#04x, reads %#04x%s\n", reg, value, after, after == value ? "" : ": NOT AS WRITTEN");
+ if (after != value) {
+ give_up("a register did not read back as written");
+ return false;
+ }
+ return true;
+}
+
+/* The chip's interrupt flags (reading clears them): false, and the chip given up on, if one is a fault. */
+static bool
+healthy(const char *when)
+{
+ uint8_t flags = 0;
+
+ if (!get(AW_SYSINT, &flags)) {
+ give_up("the flags could not be read");
+ return false;
+ }
+ if (flags & SYSINT_FAULTS) {
+ say("haptic: %s: the chip reports %#04x:%s%s%s%s%s\n", when, flags, flags & 0x80 ? " BOOST SHORT CIRCUIT" : "",
+ flags & 0x40 ? " BOOST OVER-VOLTAGE" : "", flags & 0x20 ? " UNDER-VOLTAGE" : "", flags & 0x04 ? " OVER-CURRENT" : "",
+ flags & 0x02 ? " OVER-TEMPERATURE" : "");
+ give_up("a fault");
+ return false;
+ }
+ return true;
+}
+
+/* Android's registers as its driver leaves them, read from the phone's sysfs (fw-haptic/android/haptic-sysfs.txt) */
+static const uint8_t android_regs[0x7d] = {
+ [0x00] = 0x82, [0x01] = 0x10, [0x02] = 0x11, [0x03] = 0x59, [0x04] = 0x09, [0x05] = 0x00, [0x06] = 0x47, [0x07] = 0x80,
+ [0x08] = 0x07, [0x09] = 0x00, [0x0a] = 0x0b, [0x12] = 0xf0, [0x18] = 0x1e, [0x19] = 0x8d, [0x1a] = 0x71, [0x1b] = 0x06,
+ [0x1c] = 0x58, [0x1d] = 0xcf, [0x1e] = 0x28, [0x1f] = 0x04, [0x20] = 0x06, [0x21] = 0x08, [0x22] = 0x0c, [0x23] = 0x0c,
+ [0x24] = 0x62, [0x25] = 0x08, [0x26] = 0xa0, [0x27] = 0x08, [0x28] = 0x8c, [0x2d] = 0x08, [0x2f] = 0x46, [0x33] = 0x01,
+ [0x34] = 0x01, [0x35] = 0x01, [0x36] = 0x02, [0x37] = 0x02, [0x38] = 0x02, [0x3b] = 0x05, [0x3c] = 0x08, [0x3e] = 0x1b,
+ [0x40] = 0x08, [0x41] = 0x03, [0x45] = 0x12, [0x46] = 0x09, [0x47] = 0x5a, [0x49] = 0x28, [0x4a] = 0xbf, [0x4b] = 0x32,
+ [0x4d] = 0x24, [0x4e] = 0x04, [0x4f] = 0x0a, [0x51] = 0x07, [0x57] = 0x92, [0x58] = 0x70, [0x59] = 0x04, [0x5a] = 0x98,
+ [0x5d] = 0xf5, [0x5e] = 0x0d, [0x5f] = 0xf5, [0x60] = 0x41, [0x61] = 0xf6, [0x62] = 0x5c, [0x63] = 0x0e, [0x64] = 0xf9,
+ [0x68] = 0x05, [0x69] = 0x21, [0x6b] = 0x02, [0x6c] = 0x15, [0x6d] = 0x89, [0x6e] = 0xc2, [0x6f] = 0x48, [0x70] = 0x0f,
+ [0x71] = 0x93, [0x72] = 0x69, [0x73] = 0xa4, [0x74] = 0x89, [0x75] = 0x88, [0x77] = 0x40, [0x79] = 0x0d,
+};
+
+/* What the chip holds now, against Android's (registers 0x00..0x7c; 0x32 and 0x42 are data ports, not read). */
+static void
+show_registers(void)
+{
+ unsigned differ = 0;
+
+ for (unsigned reg = 0; reg <= 0x7c; reg++) {
+ uint8_t value = 0;
+
+ if (reg == 0x32 || reg == 0x42) {
+ continue;
+ }
+ if (!regs_read((uint8_t)reg, &value, 1)) {
+ say("haptic: %#04x NOT READ\n", reg);
+ return;
+ }
+ if (value != android_regs[reg]) {
+ differ++;
+ say("haptic: %#04x = %#04x (Android leaves %#04x)\n", reg, value, android_regs[reg]);
+ }
+ }
+ say("haptic: %u registers differ from what Android leaves in them\n", differ);
+}
+
+static bool
+chip_answers(void)
+{
+ uint8_t id[2] = { 0, 0 };
+
+ if (!regs_read(AW_CHIPIDH, id, 2)) {
+ say("haptic: nobody answers at %#x on the bus of gpio%u/%u\n", AW_ADDRESS, PIN_SDA, PIN_SCL);
+ return false;
+ }
+ say("haptic: the chip at %#x is %#06x%s\n", AW_ADDRESS, id[0] << 8 | id[1], (id[0] << 8 | id[1]) == AW_CHIPID ? ", an AW86927" :
+ ": NOT THE AW86927 EXPECTED");
+ return (id[0] << 8 | id[1]) == AW_CHIPID;
+}
+
+/*
+ * Android's configuration: the registers its driver sets (and the mainline Linux driver aw86927.c sets the
+ * same way), with Android's values -- those that differ from the chip's own after a reset, as the phone
+ * showed (haptic=2). Not written: the status and interrupt flags, the RAM's address and data ports, the
+ * results of the chip's measurements (0x25..0x28: they do not take what is written, they are what its f0
+ * tracking found under Android; 0x4f, 0x51, 0x59, 0x5a likewise), and what is set for each playing (0x08 the mode,
+ * 0x0a/0x12 the waveform and its repeats). The values are all read from the chip as Android leaves it.
+ */
+static const uint8_t android_config[][2] = {
+ { 0x03, 0x59 }, /* the interrupt mask */
+ { 0x06, 0x47 }, /* PLAYCFG1: the boost in bypass, its voltage setting 0x47 (Android's vmax 7938 mV) */
+ { 0x1a, 0x71 }, /* CONTCFG3 */
+ { 0x1d, 0xcf }, /* CONTCFG6: f0 tracking on, the first drive level 0x4f */
+ { 0x1e, 0x28 }, /* CONTCFG7: the second drive level */
+ { 0x2f, 0x46 }, /* the FIFO's thresholds */
+ { 0x36, 0x02 }, { 0x37, 0x02 }, { 0x38, 0x02 }, /* the trigger pins' waveforms (the triggers stay off) */
+ { 0x39, 0x00 }, { 0x3a, 0x00 }, /* ... and off */
+ { 0x46, 0x09 }, /* SYSCTRL4: 24 kHz waveforms, the gain applied as it is */
+ { 0x47, 0x5a },
+};
+/*
+ * ... and the analog ones, behind AW_TMCFG (the boost: skip mode, peak current 3.45 A, peak back, slew).
+ * These too are Android's: what the phone's registers hold under Android (they differ from the chip's
+ * own after a reset, so Android's driver set them); mainline Linux's aw86927.c sets the same values.
+ */
+static const uint8_t android_analog[][2] = {
+ { 0x70, 0x0f }, { 0x71, 0x93 }, { 0x72, 0x69 }, { 0x74, 0x89 }, { 0x75, 0x88 },
+ { AW_TRIM_LRA, 0x0d }, /* Android's f0 calibration of this motor (its log: "f0_cali_data = 0x0D") */
+};
+
+/* The analog registers opened or closed for writing (AW_TMCFG reads back as 0 either way: what tells is that the writes stick). */
+static bool
+unlock(bool open)
+{
+ uint8_t value = open ? 0x7d : 0x00;
+
+ if (broken || !regs_write(AW_TMCFG, &value, 1)) {
+ give_up("the analog registers could not be opened");
+ return false;
+ }
+ say("haptic: %#04x <- %#04x (the analog registers %s)\n", AW_TMCFG, value, open ? "opened" : "closed");
+ return true;
+}
+
+static bool
+configure(void)
+{
+ say("haptic: Android's configuration is written\n");
+ for (unsigned i = 0; i < sizeof(android_config) / sizeof(android_config[0]); i++) {
+ if (!put(android_config[i][0], android_config[i][1])) {
+ return false;
+ }
+ }
+ if (!unlock(true)) {
+ return false;
+ }
+ for (unsigned i = 0; i < sizeof(android_analog) / sizeof(android_analog[0]); i++) {
+ if (!put(android_analog[i][0], android_analog[i][1])) {
+ (void)unlock(false);
+ return false;
+ }
+ }
+ return unlock(false) && healthy("after the configuration");
+}
+
+static uint32_t states_seen; /* the GLBRD5 states seen by the last wait, a bit each */
+
+/* until the chip says it is in standby (GLBRD5 state 0), at most `ms' */
+static bool
+wait_standby(unsigned ms)
+{
+ states_seen = 0;
+ for (unsigned waited = 0; waited <= ms; waited += 2) {
+ uint8_t state = 0xff;
+
+ if (!get(AW_GLBRD5, &state)) {
+ return false;
+ }
+ states_seen |= 1u << (state & 0x0f);
+ if ((state & 0x0f) == 0) {
+ return true;
+ }
+ wait_ms(2);
+ }
+ return false;
+}
+
+/*
+ * Android's waveforms into the chip's RAM: the file is a checksum (16 bits, of all that follows), the
+ * address the RAM's contents begin at (0x0800), and those contents -- a version byte, the start and end
+ * address of each waveform, the waveforms. Written through the data port with the address counting up,
+ * then read back the same way and compared.
+ */
+static bool
+load_waveforms(void)
+{
+ uint64_t size = 0;
+ const uint8_t *file = redwood_wifi_file("aw8697_haptic.bin", &size);
+ uint32_t sum = 0, base, length;
+ uint8_t address[2], back[64];
+
+ if (file == NULL || size < 8) {
+ say("haptic: no aw8697_haptic.bin in fw/ of the small image (fw-haptic/ when it is built)\n");
+ return false;
+ }
+ for (uint64_t i = 2; i < size; i++) {
+ sum += file[i];
+ }
+ if ((sum & 0xffff) != (uint32_t)(file[0] << 8 | file[1])) {
+ say("haptic: aw8697_haptic.bin does not add up (%#x, it says %#x): not loaded\n", sum & 0xffff, file[0] << 8 | file[1]);
+ return false;
+ }
+ base = (uint32_t)(file[2] << 8 | file[3]);
+ length = (uint32_t)size - 4;
+ say("haptic: Android's waveforms: %u bytes from %#x on, %u waveforms\n", length, base, (unsigned)(((file[5] << 8 | file[6]) -
+ base - 1) / 4));
+ if (!wait_standby(250) || !put(AW_SYSCTRL3, (uint8_t)(android_regs[AW_SYSCTRL3] | 0x04))) {
+ give_up("the RAM could not be opened");
+ return false;
+ }
+ address[0] = (uint8_t)(base >> 8);
+ address[1] = (uint8_t)base;
+ if (!put(AW_BASEADDRH, address[0]) || !put(AW_BASEADDRL, address[1]) || !regs_write(AW_RAMADDRH, address, 2)) {
+ give_up("the RAM's address could not be set");
+ return false;
+ }
+ for (uint32_t at = 0; at < length; at += 32) {
+ unsigned n = length - at < 32 ? length - at : 32;
+
+ if (!regs_write(AW_RAMDATA, file + 4 + at, n)) {
+ give_up("the RAM could not be written");
+ return false;
+ }
+ }
+ if (!regs_write(AW_RAMADDRH, address, 2)) {
+ give_up("the RAM's address could not be set again");
+ return false;
+ }
+ for (uint32_t at = 0; at < length; at += sizeof(back)) {
+ unsigned n = length - at < sizeof(back) ? length - at : sizeof(back);
+
+ if (!regs_read(AW_RAMDATA, back, n) || memcmp(back, file + 4 + at, n) != 0) {
+ say("haptic: the RAM reads back differently at %#x\n", base + at);
+ give_up("the waveforms did not load");
+ return false;
+ }
+ }
+ if (!put(AW_SYSCTRL3, android_regs[AW_SYSCTRL3])) {
+ return false;
+ }
+ say("haptic: Android's waveforms are in the chip's RAM and read back as written\n");
+ return healthy("after the waveforms");
+}
+
+/* One waveform played once (Android's effect `effect' - 1), stopped at HAPTIC_MAX_MS at the latest. */
+static bool
+play_effect(unsigned effect)
+{
+ uint64_t began = mach_absolute_time(), ended;
+ bool done;
+
+ say("haptic: waveform %u is played once, at Android's gain %#x\n", effect, android_regs[AW_PLAYCFG2]);
+ if (!wait_standby(250) || !put(AW_PLAYCFG3, 0x04) || !put(AW_WAVCFG1, (uint8_t)effect) || !put(AW_WAVCFG2, 0x00) ||
+ !put(AW_WAVCFG9, 0x00) || !put(AW_PLAYCFG2, android_regs[AW_PLAYCFG2]) || !healthy("before playing")) {
+ return false;
+ }
+ {
+ uint8_t go = 0x01;
+
+ if (!regs_write(AW_PLAYCFG4, &go, 1)) {
+ give_up("the start was not acknowledged");
+ return false;
+ }
+ }
+ wait_ms(2);
+ done = wait_standby(HAPTIC_MAX_MS);
+ absolutetime_to_nanoseconds(mach_absolute_time() - began, &ended);
+ if (!done) {
+ uint8_t stop = 0x02;
+
+ say("haptic: STILL PLAYING after %u ms: stopped\n", HAPTIC_MAX_MS);
+ (void)regs_write(AW_PLAYCFG4, &stop, 1);
+ if (!wait_standby(50)) {
+ give_up("it does not stop");
+ return false;
+ }
+ }
+ say("haptic: the waveform has played: back in standby after %llu ms (states seen meanwhile: %#x, a bit each; 0 is "
+ "standby)\n", ended / NSEC_PER_MSEC, states_seen);
+ return healthy("after playing");
+}
+
+static void
+haptic_thread(__unused void *parameter, __unused wait_result_t result)
+{
+ tlmm = ml_io_map(TLMM_PHYS, TLMM_SIZE);
+ say("haptic: level %u: %s\n", level, level == 1 ? "a look, reading only" : level == 2 ? "the reset released, registers read" :
+ level == 3 ? "the chip configured and its waveforms loaded, nothing played" : "one effect played");
+ show_pins();
+ if (level >= 2 && !((rd(GPIO_CFG(PIN_RESET)) & CFG_OUTPUT) && (rd(GPIO_IO(PIN_RESET)) & 2))) {
+ /* (Android's driver: the pin low, 5 ms, high, and the chip ready for I2C 8 ms later) */
+ say("haptic: the reset is released: gpio%u low for 5 ms, then high\n", PIN_RESET);
+ reset_pin(false);
+ wait_ms(5);
+ reset_pin(true);
+ wait_ms(8);
+ }
+ if (!chip_answers()) {
+ say("haptic: (the reset pin %s)\n", (rd(GPIO_CFG(PIN_RESET)) & CFG_OUTPUT) && (rd(GPIO_IO(PIN_RESET)) & 2) ?
+ "drives high: the chip should answer" : "does not drive high: the chip is held in reset or not powered");
+ if (released) {
+ give_up("the chip does not answer");
+ }
+ } else {
+ show_registers();
+ if (level >= 3 && configure() && load_waveforms() && level >= 4) {
+ uint32_t effect = 1;
+
+ PE_parse_boot_argn("haptic_effect", &effect, sizeof(effect));
+ if (effect < 1 || effect > 10) {
+ effect = 1; /* (the short ones only) */
+ }
+ (void)play_effect(effect);
+ }
+ }
+ say("haptic: done\n");
+ thread_terminate(current_thread());
+}
+
+void
+redwood_haptic_init(void)
+{
+ thread_t thread;
+
+ if (!PE_parse_boot_argn("haptic", &level, sizeof(level)) || level == 0) {
+ return;
+ }
+ if (level > 4) {
+ level = 4;
+ }
+ if (kernel_thread_start(haptic_thread, NULL, &thread) == KERN_SUCCESS) {
+ thread_deallocate(thread);
+ }
+}
+
+/* At the run's end and on a panic's way out: the chip back into reset, if it was let out. */
+void
+redwood_haptic_quiesce(void)
+{
+ if (released && tlmm != 0) {
+ leaving = true;
+ reset_pin(false);
+ }
+}
diff --git a/xnu/files/bsd/sys/redwood_audio.h b/xnu/files/bsd/sys/redwood_audio.h
index ac48555..a0043fd 100644
--- a/xnu/files/bsd/sys/redwood_audio.h
+++ b/xnu/files/bsd/sys/redwood_audio.h
@@ -52,6 +52,8 @@ 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 */
+void redwood_haptic_init(void); /* boot-arg haptic=N: the phone's vibration motor (bsd/dev/redwood_haptic.c) */
+void redwood_haptic_quiesce(void); /* its chip back into reset: at the run's end and on a panic's way out */
/*
* The phone's speakers (bsd/dev/redwood_speaker.c): its two Awinic amplifiers, set up as
diff --git a/xnu/files/osfmk/arm64/loader_return.c b/xnu/files/osfmk/arm64/loader_return.c
index 97c677c..c171fc7 100644
--- a/xnu/files/osfmk/arm64/loader_return.c
+++ b/xnu/files/osfmk/arm64/loader_return.c
@@ -52,6 +52,7 @@ extern void redwood_wifi_quiesce(void);
extern void redwood_adsp_stop(void);
extern void redwood_adsp_quiesce(void);
extern void redwood_ddr_quiesce(void);
+extern void redwood_haptic_quiesce(void);
void loader_checkpoint(uint64_t n);
/* Also referenced from the early exception vector in start.s. */
@@ -367,6 +368,7 @@ loader_return(void)
redwood_wifi_quiesce(); /* the Wi-Fi DSP, if it still runs (a panic), is not left to itself */
redwood_adsp_quiesce(); /* nor the audio DSP */
redwood_ddr_quiesce(); /* and the vote for the memory's bandwidth taken away */
+ redwood_haptic_quiesce(); /* the vibration motor's chip back into reset, if it was let out */
/*
* A panic's text is first collected in the panic buffer and only later
* flushed to the console; if the console itself is what failed, that
diff --git a/xnu/redwood.patch b/xnu/redwood.patch
index 5087acf..4a5c06d 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..f393c22a6ebf 100644
+index 44274016a4cf..318eecb89391 100644
--- a/bsd/conf/files
+++ b/bsd/conf/files
-@@ -109,6 +109,27 @@ bsd/dev/munge.c optional config_requires_u32_munging
+@@ -109,6 +109,28 @@ bsd/dev/munge.c optional config_requires_u32_munging
bsd/dev/unix_startup.c standard
bsd/dev/monotonic.c optional monotonic
@@ -67,6 +67,7 @@ index 44274016a4cf..f393c22a6ebf 100644
+bsd/dev/redwood_virtio_sound.c standard
+bsd/dev/redwood_speaker.c standard
+bsd/dev/redwood_guard.c standard
++bsd/dev/redwood_haptic.c standard
+bsd/dev/redwood_wifi.c standard
+bsd/dev/redwood_adsp.c standard
+bsd/dev/redwood_sound.c standard
@@ -77,7 +78,7 @@ index 44274016a4cf..f393c22a6ebf 100644
bsd/dev/dev_perfmon.c optional config_perfmon
bsd/libkern/crc32.c standard
-@@ -155,6 +176,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs
+@@ -155,6 +177,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
@@ -88,7 +89,7 @@ index 44274016a4cf..f393c22a6ebf 100644
bsd/miscfs/routefs/routefs_ops.c optional routefs
-@@ -361,6 +386,7 @@ bsd/security/audit/audit_syscalls.c standard
+@@ -361,6 +387,7 @@ bsd/security/audit/audit_syscalls.c standard
bsd/security/audit/audit_worker.c optional config_audit
bsd/pthread/pthread_shims.c standard
@@ -96,7 +97,7 @@ index 44274016a4cf..f393c22a6ebf 100644
bsd/pthread/pthread_priority.c standard
bsd/pthread/pthread_workqueue.c standard
-@@ -383,6 +409,7 @@ bsd/kern/kern_debug.c standard
+@@ -383,6 +410,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