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 for iOS: the system's haptics play on the phone's motor (haptic=5)

vcvkk00d72f51eae5
diff --git a/README.md b/README.md
index a622dc8..ed9590f 100644
--- a/README.md
+++ b/README.md
@@ -267,7 +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 с на эффект; в конце сеанса и при панике — сброс |
+| `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. `haptic=5` — моторчик для iOS до конца сеанса: всё, что iOS играет на своём устройстве «Actuator» (системные отклики и вибрация звонка, CoreHaptics приложений, отклики UIKit — например, меню иконки по долгому нажатию), звуковой модуль HAL отдаёт в `/dev/redwood-haptic`, и ядро играет по нему формы Android: каждую волну iOS — коротким толчком (форма 1), а длинную — повтором формы 11, пока iOS играет, но не дольше 1 с, после чего мотор столько же отдыхает; усиление — по громкости волны iOS, до усиления Android (0x80) и не выше. Без `haptic=5` iOS играет на «Actuator» как обычно, но в мотор ничего не идёт. Проверка: `RC_JOBS=rc.jobs.haptic`. Любая неисправность, о которой говорит чип, несовпадение при чтении или неотвеченный байт — чип снова в сброс до конца сеанса; не дольше 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 ядер запускаются и чисто возвращаются в загрузчик). На одном и
@@ -404,7 +404,10 @@ xnuloader/build.sh # clang + lld-link → xnuloader/loader.efi (EFI-пр
`xnuloader/identity.h` сгенерирован `mkidentity.py` из дерева устройств iPhone X (так система узнаёт, «какой она
iPhone»); перегенерировать: `python3 ios165/fetch-from-ipsw.py Firmware/all_flash/DeviceTree.d22ap.im4p dt.im4p`,
-`ipsw img4 im4p extract dt.im4p -o dt.bin`, `xnuloader/mkidentity.py dt.bin > xnuloader/identity.h`.
+`ipsw img4 im4p extract dt.im4p -o dt.bin`, `xnuloader/mkidentity.py dt.bin > xnuloader/identity.h`. Кроме свойств
+корня и `/product` оттуда же берётся узел `/product/haptics` (`closed-loop`, `supports-3rd-party-haptics`): по нему
+MobileGestalt отвечает `DeviceSupportsClosedLoopHaptics`, и iOS играет вибрацию и отклики волнами на устройстве
+«Actuator»; без него она ищет в IOKit старый вибромотор («vibrator»), которого у iPhone X нет, и не вибрирует вовсе.
### Userland и образы
diff --git a/userland/rc.jobs.haptic b/userland/rc.jobs.haptic
new file mode 100644
index 0000000..1a9bfd7
--- /dev/null
+++ b/userland/rc.jobs.haptic
@@ -0,0 +1,11 @@
+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).
+# The vibration motor for iOS (RC_JOBS=rc.jobs.haptic, with haptic=5): the system's haptic feedbacks -- peek (1519),
+# pop (1520), "nope" (1521: three short ones) -- and the vibration of the ringer (4095), each played the way a program
+# plays a system sound; then haptics the way an application plays them (CoreHaptics: a tap, a vibration, three taps),
+# once with a vibration longer than the kernel's limit of 1 s, which the kernel cuts; then the feedback of the home
+# screen, as a finger gets it: a long press on an icon of the dock and on one of the page (each opens its menu, with
+# a tap), the menu dismissed. The kernel's "haptic:" lines and the plug-in's "the actuator plays" say what came.
+/redwood/bin/sound_test springboard route
+/redwood/bin/sound_test system 1519 wait 2 system 1520 wait 2 system 1521 wait 2 system 4095 wait 3 system 4095 wait 3
+/redwood/bin/sound_test haptic wait 3 haptic 1.5
+/redwood/bin/rwtouch hold 0.15 0.925 1200 wait 6 tap 0.5 0.2 wait 3 hold 0.385 0.475 1200 wait 6 tap 0.5 0.2 wait 3
diff --git a/userland/src/audio_plugin.c b/userland/src/audio_plugin.c
index 7d64a90..c5e2679 100644
--- a/userland/src/audio_plugin.c
+++ b/userland/src/audio_plugin.c
@@ -14,7 +14,7 @@
* through which everything in iOS is routed. It knows an iPhone's own devices by their names
* (their UIDs) and makes a port of each: "Speaker" becomes the speaker port, the route an iPhone
* with nothing plugged in plays through, with a volume, the volume display and the place in
- * Control Center that go with it. So this presents two devices under those names:
+ * Control Center that go with it. So this presents three devices under those names:
*
* "Speaker" a stereo output whose samples are written to /dev/redwood-audio, where the
* kernel takes them to whatever can play them (see sys/redwood_audio.h), and a
@@ -23,6 +23,9 @@
* speaker route without a second virtual device of its own (its type 'vhaw', a
* mandatory companion of the default one in the iPhone X's routing tables) whose
* only port is this input; without it everything stays on the null port.
+ * "Actuator" one output of one channel: the iPhone's Taptic Engine, on which iOS plays its
+ * haptics as waveforms (through the chain 'd22_actuator_general'); its samples go to
+ * the kernel's motor driver, /dev/redwood-haptic (see actuator_write())
*
* CoreAudio's own null device ("Null_Device", described in the framework's Info.plist, playing
* into nowhere) stays as it is: it is the only device the virtual audio device takes while it
@@ -183,6 +186,7 @@ enum {
OBJECT_PLUGIN = 1,
OBJECT_SPEAKER, OBJECT_SPEAKER_OUTPUT, OBJECT_SPEAKER_INPUT,
OBJECT_HAWKING, OBJECT_HAWKING_INPUT,
+ OBJECT_ACTUATOR, OBJECT_ACTUATOR_OUTPUT,
OBJECT_SPEAKER_VOLUME, /* the speaker output's volume control */
OBJECT_LAST = OBJECT_SPEAKER_VOLUME
};
@@ -193,7 +197,7 @@ struct device {
AudioObjectID object;
CFStringRef uid; /* the name the virtual audio device knows it by */
AudioObjectID output, input; /* its streams; 0 = none */
- UInt32 input_channels;
+ UInt32 output_channels, input_channels;
/* its clock, running while anybody does I/O */
unsigned running; /* how many clients have started I/O */
UInt64 anchor; /* mach_absolute_time() when the first of them did */
@@ -202,8 +206,9 @@ struct device {
static struct device devices[] = {
{ .object = OBJECT_SPEAKER, .uid = CFSTR("Speaker"), .output = OBJECT_SPEAKER_OUTPUT, .input = OBJECT_SPEAKER_INPUT,
- .input_channels = 2 },
+ .output_channels = REDWOOD_AUDIO_CHANNELS, .input_channels = 2 },
{ .object = OBJECT_HAWKING, .uid = CFSTR("Hawking"), .input = OBJECT_HAWKING_INPUT, .input_channels = 1 },
+ { .object = OBJECT_ACTUATOR, .uid = CFSTR("Actuator"), .output = OBJECT_ACTUATOR_OUTPUT, .output_channels = 1 },
};
#define DEVICES (sizeof(devices) / sizeof(devices[0]))
@@ -283,7 +288,7 @@ static AudioStreamBasicDescription
format_of(AudioObjectID stream)
{
const struct device *d = device_of(stream);
- UInt32 channels = stream == d->output ? REDWOOD_AUDIO_CHANNELS : d->input_channels;
+ UInt32 channels = stream == d->output ? d->output_channels : d->input_channels;
return (AudioStreamBasicDescription) {
.mSampleRate = REDWOOD_AUDIO_RATE, .mFormatID = kAudioFormatLinearPCM,
@@ -799,6 +804,41 @@ begin_end_io_operation(__unused AudioServerPlugInDriverRef driver, __unused Audi
return 0;
}
+/*
+ * What iOS plays on the actuator -- the haptics: the system's feedbacks and the ringer's vibration,
+ * CoreHaptics' patterns, UIKit's feedbacks, as waveforms of one channel -- goes to the kernel's motor
+ * driver (/dev/redwood-haptic, bsd/dev/redwood_haptic.c, haptic=5), which plays Android's own
+ * waveforms on the phone's motor by it. (iOS plays on this device at all only because the device
+ * tree says the phone's haptics are "closed-loop": see mkidentity.py.) Said the first times, with
+ * how loud.
+ */
+static int haptic = -1; /* the motor driver; -2: not there (the kernel runs without haptic=5) */
+static unsigned haptic_said;
+
+static void
+actuator_write(const int16_t *samples, UInt32 frames)
+{
+ int peak = 0;
+
+ for (UInt32 i = 0; i < frames; i++) {
+ int v = samples[i] < 0 ? -samples[i] : samples[i];
+
+ peak = v > peak ? v : peak;
+ }
+ if (haptic == -1) {
+ haptic = open("/dev/redwood-haptic", O_WRONLY | O_NONBLOCK);
+ haptic = haptic >= 0 ? haptic : -2;
+ }
+ if (haptic >= 0) {
+ (void)write(haptic, samples, (size_t)frames * 2);
+ }
+ if (peak > 0 && haptic_said < 12) {
+ haptic_said++;
+ say("redwood: audio: the actuator plays: %u frames, peak %d of 32768%s\n", (unsigned)frames, peak,
+ haptic >= 0 ? "" : " (no /dev/redwood-haptic: not felt)");
+ }
+}
+
static OSStatus
do_io_operation(__unused AudioServerPlugInDriverRef driver, __unused AudioObjectID object, AudioObjectID stream,
__unused UInt32 client, UInt32 operation, UInt32 frames, __unused const AudioServerPlugInIOCycleInfo *cycle, void *buffer,
@@ -812,6 +852,8 @@ do_io_operation(__unused AudioServerPlugInDriverRef driver, __unused AudioObject
if (operation == kAudioServerPlugInIOOperationReadInput) {
/* nobody is listening on this machine: silence */
memset(buffer, 0, (size_t)frames * 2 * d->input_channels);
+ } else if (operation == kAudioServerPlugInIOOperationWriteMix && stream == OBJECT_ACTUATOR_OUTPUT) {
+ actuator_write(buffer, frames);
} else if (operation == kAudioServerPlugInIOOperationWriteMix && stream == d->output) {
/* the kernel takes it all or leaves it: this thread must not wait */
if (sink < 0 || write(sink, buffer, (size_t)frames * REDWOOD_AUDIO_FRAME) < 0) {
diff --git a/userland/src/sound_test.c b/userland/src/sound_test.c
index ca46e7e..5cc9fd2 100644
--- a/userland/src/sound_test.c
+++ b/userland/src/sound_test.c
@@ -18,6 +18,10 @@
* file PATH a sound file, played as a system sound
* route where iOS says its sound goes: the audio session's outputs and volume,
* and the devices of the system's output context
+ * haptic [SECONDS] haptics the way an application (and UIKit's feedback generators) plays
+ * them, through CoreHaptics: a tap, then a vibration of SECONDS (default
+ * 0.3, at most 3: the kernel cuts a vibration at 1 s) at half strength, then
+ * three taps of falling strength
* restart kill the audio server (launchd starts it again when it is next asked for):
* what every program then sees as "media services were reset"
*
@@ -26,6 +30,7 @@
*/
#include <AudioToolbox/AudioToolbox.h>
#include <CoreFoundation/CoreFoundation.h>
+#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <mach/mach_time.h>
@@ -242,6 +247,110 @@ route(void)
}
}
+/* CoreHaptics' constants (NSString *) by name, the framework opened when first asked for */
+static id
+haptics_constant(const char *name)
+{
+ static void *framework;
+ id *constant;
+
+ if (framework == NULL) {
+ framework = dlopen("/System/Library/Frameworks/CoreHaptics.framework/CoreHaptics", RTLD_NOW);
+ }
+ constant = framework ? dlsym(framework, name) : NULL;
+ return constant ? *constant : NULL;
+}
+
+static id
+haptic_parameter(const char *name, float value)
+{
+ id parameter = send((id)objc_getClass("CHHapticEventParameter"), "alloc");
+
+ return ((id (*)(id, SEL, id, float))objc_msgSend)(parameter, sel_registerName("initWithParameterID:value:"),
+ haptics_constant(name), value);
+}
+
+/* A haptic event: transient (a tap) when `duration' is 0, otherwise continuous for that long. */
+static id
+haptic_event(double at, double duration, float intensity, float sharpness)
+{
+ const void *parameters[2] = {
+ haptic_parameter("CHHapticEventParameterIDHapticIntensity", intensity),
+ haptic_parameter("CHHapticEventParameterIDHapticSharpness", sharpness),
+ };
+ CFArrayRef list = CFArrayCreate(NULL, parameters, 2, &kCFTypeArrayCallBacks);
+ id event = send((id)objc_getClass("CHHapticEvent"), "alloc");
+
+ if (duration > 0) {
+ event = ((id (*)(id, SEL, id, id, double, double))objc_msgSend)(event,
+ sel_registerName("initWithEventType:parameters:relativeTime:duration:"),
+ haptics_constant("CHHapticEventTypeHapticContinuous"), (id)list, at, duration);
+ } else {
+ event = ((id (*)(id, SEL, id, id, double))objc_msgSend)(event, sel_registerName("initWithEventType:parameters:relativeTime:"),
+ haptics_constant("CHHapticEventTypeHapticTransient"), (id)list, at);
+ }
+ CFRelease(list);
+ return event;
+}
+
+static int
+haptic(double seconds)
+{
+ id error = NULL, engine, pattern, player;
+ const void *events[5];
+ CFArrayRef list, none = CFArrayCreate(NULL, NULL, 0, &kCFTypeArrayCallBacks);
+ BOOL started;
+
+ if (haptics_constant("CHHapticEventTypeHapticTransient") == NULL) {
+ printf("sound_test: haptic: no CoreHaptics\n");
+ return 1;
+ }
+ {
+ /* what an application asks first, and what UIKit's feedback generators go by */
+ id capabilities = send((id)objc_getClass("CHHapticEngine"), "capabilitiesForHardware");
+ SEL first = sel_registerName("supports1stPartyHaptics");
+ BOOL answers = capabilities && ((BOOL (*)(id, SEL, SEL))objc_msgSend)(capabilities,
+ sel_registerName("respondsToSelector:"), first);
+
+ printf("sound_test: haptic: the hardware %s haptics%s\n", capabilities && ((BOOL (*)(id, SEL))objc_msgSend)(capabilities,
+ sel_registerName("supportsHaptics")) ? "supports" : "DOES NOT SUPPORT", !answers ? "" :
+ ((BOOL (*)(id, SEL))objc_msgSend)(capabilities, first) ? " (also the system's own, as UIKit's feedbacks)" :
+ " (but NOT the system's own, as UIKit's feedbacks)");
+ }
+ engine = ((id (*)(id, SEL, id *))objc_msgSend)(send((id)objc_getClass("CHHapticEngine"), "alloc"),
+ sel_registerName("initAndReturnError:"), &error);
+ if (engine == NULL) {
+ printf("sound_test: haptic: no engine: %s\n", text(send(error, "description")));
+ return 1;
+ }
+ started = ((BOOL (*)(id, SEL, id *))objc_msgSend)(engine, sel_registerName("startAndReturnError:"), &error);
+ printf("sound_test: haptic: the engine %s%s\n", started ? "has started" : "DOES NOT START: ",
+ started ? "" : text(send(error, "description")));
+ if (!started) {
+ return 1;
+ }
+ events[0] = haptic_event(0, 0, 1.0f, 0.5f);
+ events[1] = haptic_event(0.3, seconds, 0.5f, 0.3f);
+ events[2] = haptic_event(0.6 + seconds, 0, 1.0f, 0.8f);
+ events[3] = haptic_event(0.8 + seconds, 0, 0.6f, 0.8f);
+ events[4] = haptic_event(1.0 + seconds, 0, 0.3f, 0.8f);
+ list = CFArrayCreate(NULL, events, 5, &kCFTypeArrayCallBacks);
+ pattern = ((id (*)(id, SEL, id, id, id *))objc_msgSend)(send((id)objc_getClass("CHHapticPattern"), "alloc"),
+ sel_registerName("initWithEvents:parameters:error:"), (id)list, (id)none, &error);
+ player = pattern ? ((id (*)(id, SEL, id, id *))objc_msgSend)(engine, sel_registerName("createPlayerWithPattern:error:"),
+ pattern, &error) : NULL;
+ if (player == NULL ||
+ !((BOOL (*)(id, SEL, double, id *))objc_msgSend)(player, sel_registerName("startAtTime:error:"), 0.0, &error)) {
+ printf("sound_test: haptic: the pattern does not play: %s\n", text(send(error, "description")));
+ return 1;
+ }
+ printf("sound_test: haptic: playing a tap, %.2f s of vibration at half strength, three taps\n", seconds);
+ usleep((useconds_t)((1.5 + seconds) * 1e6));
+ ((void (*)(id, SEL, id))objc_msgSend)(engine, sel_registerName("stopWithCompletionHandler:"), NULL);
+ printf("sound_test: haptic: done\n");
+ return 0;
+}
+
extern int proc_listallpids(void *buffer, int size);
extern int proc_name(int pid, void *buffer, uint32_t size);
@@ -277,6 +386,10 @@ main(int argc, char **argv)
route();
} else if (strcmp(argv[i], "restart") == 0) {
restart();
+ } else if (strcmp(argv[i], "haptic") == 0) {
+ double seconds = i + 1 < argc && atof(argv[i + 1]) > 0 ? atof(argv[++i]) : 0.3;
+
+ failed |= haptic(seconds > 3 ? 3 : seconds);
} else if (strcmp(argv[i], "tone") == 0 && i + 1 < argc) {
double seconds = atof(argv[++i]);
diff --git a/xnu/files/bsd/dev/redwood_haptic.c b/xnu/files/bsd/dev/redwood_haptic.c
index 690fe92..e886a74 100644
--- a/xnu/files/bsd/dev/redwood_haptic.c
+++ b/xnu/files/bsd/dev/redwood_haptic.c
@@ -27,6 +27,16 @@
* 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)
+ * haptic=5 ... configured and loaded as for 3, and instead of the effect the motor for iOS until
+ * the run ends: what iOS plays on its "Actuator" device (the HAL plug-in's,
+ * userland/src/audio_plugin.c: the system's feedbacks and vibrations, CoreHaptics'
+ * patterns, UIKit's feedbacks) is written to /dev/redwood-haptic as samples of one
+ * channel, and the motor plays Android's waveforms by it: each waveform of iOS's (a
+ * stretch of samples after a pause) a short tap (waveform 1), and one that goes on for
+ * longer than a tap the waveform Android loops for vibrations (11), until it ends -- or
+ * for HAPTIC_MAX_MS at most, after which the motor rests for as long before it plays
+ * again. The gain is as loud as iOS's waveform: Android's own (0x80) at full scale,
+ * never above it.
*
* 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
@@ -42,7 +52,10 @@
#include <mach/mach_types.h>
#include <machine/machine_routines.h>
#include <pexpert/pexpert.h>
+#include <miscfs/devfs/devfs.h>
+#include <sys/conf.h>
#include <sys/systm.h>
+#include <sys/uio.h>
#include <sys/redwood_audio.h>
#include <sys/redwood_input.h>
@@ -645,12 +658,250 @@ play_effect(unsigned effect)
return healthy("after playing");
}
+/* ---- haptic=5: the motor for iOS ------------------------------------------------------------------- */
+
+#define ACTIVE_US 30000 /* a write that was not silence counts for this long */
+#define SILENT_BELOW 256 /* of 32768: samples no larger are silence */
+#define TAP_US 60000 /* longer than this, and it is a vibration, not a tap */
+#define SETTLE_US 8000 /* how long iOS's waveform is listened to before a tap: its loudness */
+#define FOLLOW_US 20000 /* how often a vibration's strength follows iOS's */
+
+#define TOLD_EVENTS 24 /* the first so many taps and vibrations are each said */
+
+static volatile uint64_t heard_us; /* when the last write that was not silence came */
+static volatile uint64_t quiet_us; /* when the last write that was silence came */
+static volatile uint64_t onset_us; /* when iOS's last waveform began: the first write not silence after a pause */
+static volatile uint32_t heard_peak; /* the largest sample of that waveform, or since the service last looked */
+static uint64_t written_frames;
+static unsigned taps, loops, capped; /* what has been played, for the run's end */
+
+static uint64_t
+now_us(void)
+{
+ uint64_t ns;
+
+ absolutetime_to_nanoseconds(mach_absolute_time(), &ns);
+ return ns / NSEC_PER_USEC;
+}
+
+/* From the audio server's I/O thread: never waits. */
+static int
+haptic_write(__unused dev_t dev, struct uio *uio, __unused int ioflag)
+{
+ int16_t samples[256];
+ int error = 0;
+
+ while (uio_resid(uio) >= 2) {
+ user_ssize_t bytes = uio_resid(uio);
+ uint32_t peak = 0;
+
+ if (bytes > (user_ssize_t)sizeof(samples)) {
+ bytes = sizeof(samples);
+ }
+ bytes &= ~(user_ssize_t)1;
+ if ((error = uiomove((caddr_t)samples, (int)bytes, uio)) != 0) {
+ break;
+ }
+ for (unsigned i = 0; i < bytes / 2; i++) {
+ uint32_t v = samples[i] < 0 ? (uint32_t)-(int32_t)samples[i] : (uint32_t)samples[i];
+
+ peak = v > peak ? v : peak;
+ }
+ written_frames += (uint64_t)bytes / 2;
+ if (peak > SILENT_BELOW) {
+ uint64_t now = now_us();
+
+ if (heard_us == 0 || quiet_us > heard_us || now - heard_us >= ACTIVE_US) {
+ onset_us = now;
+ heard_peak = 0;
+ }
+ heard_us = now;
+ if (peak > heard_peak) {
+ heard_peak = peak;
+ }
+ } else {
+ quiet_us = now_us();
+ }
+ }
+ return error;
+}
+
+static int
+haptic_open(__unused dev_t dev, __unused int flags, __unused int type, __unused struct proc *p)
+{
+ return 0;
+}
+
+static const struct cdevsw haptic_cdevsw = {
+ .d_open = haptic_open, .d_close = haptic_open, .d_read = eno_rdwrt, .d_write = haptic_write,
+ .d_ioctl = eno_ioctl, .d_stop = eno_stop, .d_reset = eno_reset, .d_select = eno_select,
+ .d_mmap = eno_mmap, .d_strategy = eno_strat, .d_type = 0
+};
+
+/* Start a waveform without waiting for it: once, or (`forever') until stopped. */
+static bool
+start_waveform(unsigned waveform, bool forever, uint8_t gain)
+{
+ uint8_t go = 0x01;
+
+ if (!put(AW_PLAYCFG3, 0x04) || !put(AW_WAVCFG1, (uint8_t)waveform) || !put(AW_WAVCFG2, 0x00) ||
+ !put(AW_WAVCFG9, forever ? 0xf0 : 0x00) || !put(AW_PLAYCFG2, gain)) {
+ return false;
+ }
+ if (!regs_write(AW_PLAYCFG4, &go, 1)) {
+ give_up("the start was not acknowledged");
+ return false;
+ }
+ return true;
+}
+
+static bool
+stop_waveform(void)
+{
+ uint8_t stop = 0x02;
+
+ if (!regs_write(AW_PLAYCFG4, &stop, 1) || !wait_standby(50)) {
+ give_up("it does not stop");
+ return false;
+ }
+ return true;
+}
+
+/* the chip's state (GLBRD5: 0 standby, 7 and 11 seen while a waveform plays), 0xff if it cannot be read */
+static unsigned
+chip_state(void)
+{
+ uint8_t state = 0xff;
+
+ return get(AW_GLBRD5, &state) ? state & 0x0f : 0xff;
+}
+
+static void
+serve(void)
+{
+ enum { IDLE, TAP, LOOP, REST } state = IDLE;
+ uint64_t since = 0, rest_until = 0, last_look = 0, tap_onset = 0, followed = 0;
+ uint8_t playing_gain = 0;
+ unsigned follows = 0; /* how often the vibration playing now has changed strength */
+ int major = cdevsw_add(-1, &haptic_cdevsw);
+
+ if (major < 0 || devfs_make_node(makedev(major, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666, "redwood-haptic") == NULL) {
+ say("haptic: /dev/redwood-haptic cannot be made\n");
+ return;
+ }
+ say("haptic: THE MOTOR PLAYS WHAT IOS PLAYS ON ITS ACTUATOR (/dev/redwood-haptic) from here on, until the run ends\n");
+ while (!broken) {
+ uint64_t now = now_us();
+ bool active = heard_us != 0 && now - heard_us < ACTIVE_US;
+ uint32_t peak = heard_peak;
+ /* (the gain as loud as iOS's waveform, Android's 0x80 at full scale and never above) */
+ uint8_t gain = (uint8_t)(peak >= 32767 ? android_regs[AW_PLAYCFG2] : (uint32_t)android_regs[AW_PLAYCFG2] * peak / 32767);
+
+ switch (state) {
+ case IDLE:
+ case TAP:
+ /*
+ * A waveform of iOS's that has begun (after a pause: a tap of a series is a tap of its own) is
+ * a tap -- once its first milliseconds are heard: a waveform begins softly, and they say how
+ * loud it is; one that goes on without a pause, a vibration.
+ */
+ if (active && onset_us != tap_onset && now - onset_us >= SETTLE_US) {
+ uint64_t began = onset_us;
+
+ if (state == TAP && !wait_standby(0) && !stop_waveform()) {
+ break;
+ }
+ if (!start_waveform(1, false, gain ? gain : 1)) {
+ break;
+ }
+ state = TAP;
+ since = now;
+ tap_onset = began;
+ taps++;
+ if (taps + loops <= TOLD_EVENTS) {
+ wait_ms(4);
+ say("haptic: tap %u: iOS's waveform peaks at %u of 32768: Android's waveform 1 at gain %#04x; the "
+ "chip's state %u\n", taps, peak, gain ? gain : 1, chip_state());
+ }
+ break;
+ }
+ if (state == IDLE) {
+ break;
+ }
+ if (active && quiet_us < tap_onset && now - since > TAP_US) {
+ if (stop_waveform() && start_waveform(11, true, gain ? gain : 1)) {
+ state = LOOP;
+ since = followed = now;
+ playing_gain = gain ? gain : 1;
+ follows = 0;
+ loops++;
+ heard_peak = 0;
+ if (taps + loops <= TOLD_EVENTS) {
+ wait_ms(4);
+ say("haptic: vibration %u: iOS goes on playing (peak %u): Android's waveform 11 over and over at "
+ "gain %#04x, %u ms at most; the chip's state %u\n", loops, peak, gain ? gain : 1,
+ HAPTIC_MAX_MS, chip_state());
+ }
+ }
+ } else if (!active && now - since > TAP_US) {
+ state = wait_standby(0) || stop_waveform() ? IDLE : state;
+ }
+ break;
+ case LOOP:
+ /* as strong as iOS's waveform is now (Android's gain at full scale, never more) */
+ if (active && now - followed >= FOLLOW_US) {
+ followed = now;
+ heard_peak = 0;
+ if (gain != 0 && (gain > playing_gain + 8 || gain + 8 < playing_gain)) {
+ if (!put(AW_PLAYCFG2, gain)) {
+ break;
+ }
+ playing_gain = gain;
+ follows++;
+ }
+ }
+ if (!active || now - since > HAPTIC_MAX_MS * 1000ull) {
+ bool cut = now - since > HAPTIC_MAX_MS * 1000ull;
+
+ if (cut) {
+ capped++;
+ rest_until = now + HAPTIC_MAX_MS * 1000ull;
+ }
+ if (stop_waveform()) {
+ state = rest_until > now ? REST : IDLE;
+ if (taps + loops <= TOLD_EVENTS + 1) {
+ say("haptic: vibration %u: %s after %llu ms (its strength changed %u times, last to gain %#04x); "
+ "the chip is in standby\n", loops, cut ? "CUT at the limit" : "iOS stopped, and so does the motor",
+ (now - since) / 1000, follows, playing_gain);
+ }
+ }
+ }
+ break;
+ case REST:
+ if (now >= rest_until) {
+ state = IDLE;
+ }
+ break;
+ }
+ if (state != IDLE && state != REST && now - last_look > 50000) {
+ last_look = now;
+ if (!healthy("while playing")) {
+ break;
+ }
+ }
+ wait_ms(4);
+ }
+ say("haptic: the motor is given up on (%u taps and %u vibrations played, %u cut at %u ms)\n", taps, loops, capped,
+ HAPTIC_MAX_MS);
+}
+
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");
+ level == 3 ? "the chip configured and its waveforms loaded, nothing played" : level == 4 ? "one effect played" :
+ "the motor for iOS");
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) */
@@ -668,7 +919,7 @@ haptic_thread(__unused void *parameter, __unused wait_result_t result)
}
} else {
show_registers();
- if (level >= 3 && configure() && load_waveforms() && level >= 4) {
+ if (level >= 3 && configure() && load_waveforms() && level == 4) {
uint32_t effect = 1;
PE_parse_boot_argn("haptic_effect", &effect, sizeof(effect));
@@ -676,6 +927,8 @@ haptic_thread(__unused void *parameter, __unused wait_result_t result)
effect = 1; /* (the short ones only) */
}
(void)play_effect(effect);
+ } else if (level == 5 && !broken) {
+ serve();
}
}
say("haptic: done\n");
@@ -690,8 +943,8 @@ redwood_haptic_init(void)
if (!PE_parse_boot_argn("haptic", &level, sizeof(level)) || level == 0) {
return;
}
- if (level > 4) {
- level = 4;
+ if (level > 5) {
+ level = 5;
}
if (kernel_thread_start(haptic_thread, NULL, &thread) == KERN_SUCCESS) {
thread_deallocate(thread);
@@ -705,5 +958,9 @@ redwood_haptic_quiesce(void)
if (released && tlmm != 0) {
leaving = true;
reset_pin(false);
+ if (level == 5) {
+ say("haptic: at the run's end: %u taps and %u vibrations played (%u cut at %u ms), from %llu frames iOS "
+ "wrote; the chip is held in reset\n", taps, loops, capped, HAPTIC_MAX_MS, written_frames);
+ }
}
}
diff --git a/xnuloader/identity.h b/xnuloader/identity.h
index 799ee77..cfad9ce 100644
--- a/xnuloader/identity.h
+++ b/xnuloader/identity.h
@@ -103,3 +103,12 @@ static const unsigned char identity_product_data[] = {
0x00, 0xea, 0x3f, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
};
+/* 2 properties */
+static const struct identity_prop identity_haptics[] = {
+ { "closed-loop", 0, 4 },
+ { "supports-3rd-party-haptics", 4, 4 },
+};
+static const unsigned char identity_haptics_data[] = {
+ 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
+};
+
diff --git a/xnuloader/loader.c b/xnuloader/loader.c
index d27a3b9..1e7e56a 100644
--- a/xnuloader/loader.c
+++ b/xnuloader/loader.c
@@ -1964,6 +1964,15 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)
/* the product: screen class, artwork scale, name ... as on the real phone */
dt_begin(&w, "product");
dt_identity(&w, identity_product, sizeof(identity_product) / sizeof(identity_product[0]), identity_product_data);
+ /*
+ * and its haptics: "closed-loop" (MobileGestalt's DeviceSupportsClosedLoopHaptics) makes iOS play
+ * its vibrations and feedbacks as waveforms on the "Actuator" audio device (the audio plug-in
+ * hands them to the kernel's motor driver); without it iOS looks for an IOKit vibration motor
+ * that the iPhone X does not have, and nothing vibrates.
+ */
+ dt_begin(&w, "haptics");
+ dt_identity(&w, identity_haptics, sizeof(identity_haptics) / sizeof(identity_haptics[0]), identity_haptics_data);
+ dt_end(&w);
dt_end(&w);
/* IOKit publishes its NVRAM object on this node; without it IOKit asserts. */
diff --git a/xnuloader/mkidentity.py b/xnuloader/mkidentity.py
index 73095da..663940f 100755
--- a/xnuloader/mkidentity.py
+++ b/xnuloader/mkidentity.py
@@ -8,7 +8,10 @@ of the IPSW, decompressed: "ipsw img4 im4p extract DeviceTree.d22ap.im4p -o Devi
iOS user space (MobileGestalt above all) decides what device it runs on from the device
tree: the root node's model and compatible, and the /product node (screen class, artwork
-scale, product name ...). The loader builds its own device tree for the hardware we really
+scale, product name ...), and the /product/haptics node: what the phone's haptics are (MobileGestalt's
+DeviceSupportsClosedLoopHaptics is its "closed-loop"; with it iOS plays the system's vibrations and
+feedbacks as waveforms on the actuator, and without it looks for an old vibration motor in IOKit,
+which the iPhone X does not have). The loader builds its own device tree for the hardware we really
have, but copies these properties from the device tree in the iOS firmware so that the
system believes it is the iPhone its files were built for.
@@ -66,6 +69,8 @@ def main():
emit('identity_root', root[0], ('name', '#address-cells', '#size-cells', 'AAPL,phandle', 'clock-frequency',
'platform-name', 'time-stamp', 'secure-root-prefix'))
emit('identity_product', children['product'][0], ('name', 'AAPL,phandle'))
+ product = {name_of(c): c for c in children['product'][1]}
+ emit('identity_haptics', product['haptics'][0], ('name', 'AAPL,phandle'))
if __name__ == '__main__':