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

Flashlight: the PM8350C's flash LED for iOS, at Android's torch current (torch=N)

vcvkkcc159f51fc6b
diff --git a/README.md b/README.md
index ed9590f..c480acc 100644
--- a/README.md
+++ b/README.md
@@ -268,6 +268,7 @@ XL_SECS=900 XL_CMDLINE="touchscreen=1 cpufreq=1 bootcpu=7 cpus=8" ./xl run #
| `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. `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 с на эффект; в конце сеанса и при панике — сброс |
+| `torch=N` | фонарик: светодиодный модуль вспышки PM8350C (SPMI, ведомый 2, регистры 0xee00; задний светодиод — канал 0), значения Android: его фонарик горит на 125 мА через канал 0 (прочитано у включённого фонарика Android), шаг тока 12,5 мА, порядок записей — драйвера Xiaomi `leds-qti-flash.c` (`bsd/dev/redwood_torch.c`). `torch=1` — только читать: канал арбитра, тип модуля, регистры, температурная тревога PMIC. `torch=2` — ещё и зажечь один раз на 125 мА на `torch_secs` (по умолчанию 2 с). `torch=3` — фонарик для iOS: `/dev/redwood-torch` принимает уровень 0…1000 (тысячные тока Android, не выше 125 мА); загрузчик с `torch=N` добавляет в дерево `/product/camera` со свойством `flash` айфона (кнопка фонарика в Пункте управления), а `libredwood-media.dylib` отдаёт FigFlashlight в mediaserverd своё «устройство» вместо отсутствующей камеры (`userland/src/inject_media.c`). Пределы: записи — только в шесть регистров этого модуля, каждая читается обратно, канал арбитра перепроверяется; не дольше `torch_max_s` подряд (по умолчанию 30 с, не больше 120), потом темно, пока iOS не попросит снова; 10 раз в секунду — флаги неисправности и перегрева модуля, температурная тревога PMIC и температура батареи (не выше 45 °C; из battmgr при `adsp=1` или из `battery=1`) — что-то не так, и фонарик гаснет до конца сеанса; в конце сеанса и при панике — погашен. Проверка: `RC_JOBS=rc.jobs.torch` (`torch_test` — как программа, через AVFlashlight; потом кнопка в Пункте управления) |
| `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 ядер запускаются и чисто возвращаются в загрузчик). На одном и
@@ -408,6 +409,8 @@ iPhone»); перегенерировать: `python3 ios165/fetch-from-ipsw.py
корня и `/product` оттуда же берётся узел `/product/haptics` (`closed-loop`, `supports-3rd-party-haptics`): по нему
MobileGestalt отвечает `DeviceSupportsClosedLoopHaptics`, и iOS играет вибрацию и отклики волнами на устройстве
«Actuator»; без него она ищет в IOKit старый вибромотор («vibrator»), которого у iPhone X нет, и не вибрирует вовсе.
+Из узла `/product/camera` загрузчик берёт (только с `torch=N`) одно свойство `flash` — MobileGestalt `camera-flash`,
+кнопка фонарика в Пункте управления; остального о камере айфона здесь нет, и дерево этого не говорит.
### Userland и образы
diff --git a/userland/build.sh b/userland/build.sh
index a6e4d41..9e1987d 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -112,6 +112,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then
$DYN -o obj/rwtouch src/rwtouch.c
$DYN -framework CoreFoundation -framework AudioToolbox -framework AVFoundation -lobjc -o obj/sound_test src/sound_test.c
$DYN -framework CoreFoundation -lMobileGestalt -o obj/mg_test src/mg_test.c
+ $DYN -framework CoreFoundation -framework AVFoundation -lobjc -o obj/torch_test src/torch_test.c
$DYN -o obj/cpu_test src/cpu_test.c
$DYN -framework CoreFoundation -framework IOSurface -o obj/cow_test src/cow_test.c
$DYN -framework CoreFoundation -framework CoreGraphics -framework IOSurface -o obj/cg_test src/cg_test.c
@@ -164,6 +165,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then
[ -f obj/keychain_test ] && cp obj/keychain_test root/bin/
[ -f obj/wifipw_test ] && cp obj/wifipw_test root/bin/
[ -f obj/sound_test ] && cp obj/sound_test root/bin/
+ [ -f obj/torch_test ] && cp obj/torch_test root/bin/
for f in $EXTRA; do cp "$f" root/bin/; done
mkdir -p root/lib
cp obj/libredwood.dylib obj/libredwood-sb.dylib root/lib/
diff --git a/userland/rc.jobs.torch b/userland/rc.jobs.torch
new file mode 100644
index 0000000..bd2747a
--- /dev/null
+++ b/userland/rc.jobs.torch
@@ -0,0 +1,13 @@
+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).
+# The flashlight for iOS (RC_JOBS=rc.jobs.torch, with torch=3): as a program works it (torch_test: AVFlashlight, i.e.
+# mediaserverd's FigFlashlight, i.e. the kernel's /dev/redwood-torch) at full and at a quarter, then off; then from
+# Control Center, as a finger works it: opened from the top right corner, its flashlight button pressed, pressed again
+# 5 s later, Control Center closed (a tap below its buttons); then on for 8 s, which the kernel cuts with torch_max_s=5
+# (and leaves alone at its default of 30). The kernel's "torch:" lines say what was lit, and the end of the run repeats
+# them.
+/redwood/bin/sound_test springboard
+/redwood/bin/torch_test state level 1.0 wait 3 state level 0.25 wait 3 state off wait 1 state
+/redwood/bin/rwtouch wait 2 swipe 0.85 0.005 0.85 0.6 300 wait 3
+/redwood/bin/rwtouch tap 0.385 0.61 wait 5 tap 0.385 0.61 wait 3 tap 0.5 0.92 wait 2
+/redwood/bin/torch_test state
+/redwood/bin/torch_test level 1.0 wait 8 state off wait 1 state
diff --git a/userland/src/inject_media.c b/userland/src/inject_media.c
index 43c4a63..7a01bec 100644
--- a/userland/src/inject_media.c
+++ b/userland/src/inject_media.c
@@ -13,13 +13,25 @@
* and the stock wallpaper of iOS 16, whose layers are four such pictures, is its gradient alone.
* There is no hardware decoder here; VideoToolbox takes its software one (VCPHEVC.videocodec).
*
- * CMCapture is not loaded yet when this library is: the method is replaced when its image
+ * The flashlight (only where the kernel has one: torch=3, /dev/redwood-torch): Control Center's
+ * button and AVFlashlight reach FigFlashlight in here, which asks the capture stack's device vendor
+ * (+[BWFigCaptureDeviceVendor sharedCaptureDeviceVendor]) for the camera device and its back
+ * camera's stream, and sets the stream's "TorchLevel" (0 to 1). Without a camera there is no
+ * vendor (it is nil), every message to it does nothing, and FigFlashlight says it has set the level
+ * when nothing has been. So where there is no vendor, FigFlashlight -- and only FigFlashlight,
+ * by where it calls from -- is given one of ours, with a device and a stream whose torch level goes
+ * to the kernel (see flashlight_*() below). Everybody else still gets none, as before.
+ *
+ * CMCapture is not loaded yet when this library is: the methods are replaced when its image
* arrives.
*/
#include <CoreFoundation/CoreFoundation.h>
+#include <fcntl.h>
#include <mach-o/dyld.h>
+#include <objc/message.h>
#include <objc/runtime.h>
#include <stdarg.h>
+#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
@@ -52,18 +64,172 @@ prewarm_portrait_filter(__unused id self, __unused SEL selector, __unused int ve
{
}
+/* ---- the flashlight ------------------------------------------------------------------------------- */
+
+static int torch = -1; /* /dev/redwood-torch */
+static Class vendor_class, device_class, stream_class;
+static IMP original_shared_vendor;
+static unsigned torch_said;
+
+/*
+ * FigFlashlight's functions that ask for the vendor, unslid (20F66): flashlight_IsAvailable,
+ * _NotifyForCurrentState and _setupDevice lie together, _teardownDevice apart.
+ */
+static const struct { uintptr_t from, to; } flashlight_code[] = {
+ { 0x1a1fb0830UL, 0x1a1fb0c5cUL }, { 0x1a1eee5c0UL, 0x1a1eee6e8UL },
+};
+
+/* +[BWFigCaptureDeviceVendor sharedCaptureDeviceVendor] */
+static id
+flashlight_shared_vendor(id self, SEL selector)
+{
+ uintptr_t caller = (uintptr_t)__builtin_return_address(0) - slide;
+ id vendor = ((id (*)(id, SEL))original_shared_vendor)(self, selector);
+ static id ours;
+
+ if (vendor != NULL) {
+ return vendor;
+ }
+ for (size_t i = 0; i < sizeof(flashlight_code) / sizeof(flashlight_code[0]); i++) {
+ if (caller >= flashlight_code[i].from && caller < flashlight_code[i].to) {
+ if (ours == NULL) {
+ ours = class_createInstance(vendor_class, 0);
+ say("redwood: mediaserverd: no camera, so no device vendor: FigFlashlight gets the flashlight's own\n");
+ }
+ return ours;
+ }
+ }
+ return NULL;
+}
+
+static void
+flashlight_set(uint32_t level)
+{
+ ssize_t written = write(torch, &level, sizeof(level));
+
+ if (written != (ssize_t)sizeof(level) || torch_said < 40) {
+ torch_said++;
+ say("redwood: mediaserverd: the flashlight at %u of 1000%s\n", level, written == (ssize_t)sizeof(level) ? "" :
+ " (NOT TAKEN by /dev/redwood-torch)");
+ }
+}
+
+/* the vendor's: one client, one device, always available to it */
+static int
+flashlight_register(__unused id self, __unused SEL selector, __unused int pid, __unused id description, __unused int priority,
+ __unused BOOL steal, __unused BOOL share, __unused id handler)
+{
+ return 1;
+}
+
+static id
+flashlight_copy_device(__unused id self, __unused SEL selector, __unused int client, __unused BOOL inform, int *error)
+{
+ if (error != NULL) {
+ *error = 0;
+ }
+ return class_createInstance(device_class, 0);
+}
+
+static id
+flashlight_copy_stream(__unused id self, __unused SEL selector, __unused int position, __unused int type, id device)
+{
+ return device != NULL && object_getClass(device) == device_class ? class_createInstance(stream_class, 0) : NULL;
+}
+
+static void
+flashlight_take_back(__unused id self, __unused SEL selector, __unused id device, __unused int client, __unused BOOL inform)
+{
+ flashlight_set(0);
+}
+
+static BOOL
+flashlight_active_equals(__unused id self, __unused SEL selector, id device)
+{
+ return device == NULL || object_getClass(device) == device_class;
+}
+
+/* the stream's -supportedProperties: none that FigFlashlight looks for ("HighCurrentTorchEnabled") */
+static id
+flashlight_stream_properties(__unused id self, __unused SEL selector)
+{
+ static CFDictionaryRef none;
+
+ if (none == NULL) {
+ none = CFDictionaryCreate(NULL, NULL, NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
+ }
+ return (id)none;
+}
+
+/* the stream's -setProperty:value: -- "TorchLevel", 0 to 1, as thousandths to the kernel */
+static int
+flashlight_stream_set(__unused id self, __unused SEL selector, id key, id value)
+{
+ float level = 0;
+
+ if (key != NULL && CFEqual((CFTypeRef)key, CFSTR("TorchLevel"))) {
+ if (value != NULL && CFGetTypeID((CFTypeRef)value) == CFNumberGetTypeID()) {
+ CFNumberGetValue((CFNumberRef)value, kCFNumberFloatType, &level);
+ }
+ level = level < 0 ? 0 : level > 1 ? 1 : level;
+ flashlight_set((uint32_t)(level * 1000 + 0.5f));
+ }
+ return 0;
+}
+
+struct method_spec {
+ const char *selector, *types;
+ IMP imp;
+};
+
+static Class
+make_class(const char *name, const struct method_spec *methods, size_t count)
+{
+ Class cls = objc_allocateClassPair(objc_getClass("NSObject"), name, 0);
+
+ for (size_t i = 0; i < count; i++) {
+ class_addMethod(cls, sel_registerName(methods[i].selector), methods[i].imp, methods[i].types);
+ }
+ objc_registerClassPair(cls);
+ return cls;
+}
+
+static void
+flashlight_classes(void)
+{
+ static const struct method_spec vendor[] = {
+ { "registerClientWithPID:clientDescription:clientPriority:canStealFromClientsWithSamePriority:"
+ "deviceSharingWithOtherClientsAllowed:deviceAvailabilityChangedHandler:", "i@:i@iBB@", (IMP)flashlight_register },
+ { "copyDeviceForClient:informClientWhenDeviceAvailableAgain:error:", "@@:iB^i", (IMP)flashlight_copy_device },
+ { "copyStreamForFlashlightWithPosition:deviceType:forDevice:", "@@:ii@", (IMP)flashlight_copy_stream },
+ { "takeBackDevice:forClient:informClientWhenDeviceAvailableAgain:", "v@:@iB", (IMP)flashlight_take_back },
+ { "activeDeviceEquals:", "B@:@", (IMP)flashlight_active_equals },
+ }, stream[] = {
+ { "supportedProperties", "@@:", (IMP)flashlight_stream_properties },
+ { "setProperty:value:", "i@:@@", (IMP)flashlight_stream_set },
+ };
+
+ vendor_class = make_class("RedwoodFlashlightVendor", vendor, sizeof(vendor) / sizeof(vendor[0]));
+ device_class = make_class("RedwoodFlashlightDevice", NULL, 0);
+ stream_class = make_class("RedwoodFlashlightStream", stream, sizeof(stream) / sizeof(stream[0]));
+}
+
/*
* The class methods replaced, each as soon as its class exists. `expected` is the unslid address
- * of the code in iOS 16.5 (20F66): a method that is not what it was is left alone.
+ * of the code in iOS 16.5 (20F66): a method that is not what it was is left alone. `original`, where
+ * there is one, keeps what was there; the flashlight's is replaced only where the kernel has one.
*/
static struct replacement {
const char *class_name, *selector;
+ bool flashlight;
uintptr_t expected;
- IMP replacement;
+ IMP replacement, *original;
bool done;
} replacements[] = {
- { "BWCoreImageFilterRenderer", "prewarmPortraitFilterVersion:semanticStyleFilters:", 0x1a2115c0cUL,
- (IMP)prewarm_portrait_filter, false },
+ { "BWCoreImageFilterRenderer", "prewarmPortraitFilterVersion:semanticStyleFilters:", false, 0x1a2115c0cUL,
+ (IMP)prewarm_portrait_filter, NULL, false },
+ { "BWFigCaptureDeviceVendor", "sharedCaptureDeviceVendor", true, 0x1a1ef0d04UL,
+ (IMP)flashlight_shared_vendor, &original_shared_vendor, false },
};
static void
@@ -75,7 +241,7 @@ image_added(__unused const struct mach_header *header, __unused intptr_t image_s
Method method;
IMP original;
- if (r->done || (cls = objc_getClass(r->class_name)) == NULL) {
+ if (r->done || (r->flashlight && torch < 0) || (cls = objc_getClass(r->class_name)) == NULL) {
continue;
}
r->done = true;
@@ -86,6 +252,9 @@ image_added(__unused const struct mach_header *header, __unused intptr_t image_s
original ? (uintptr_t)original - slide : 0, r->expected);
continue;
}
+ if (r->original != NULL) {
+ *r->original = original;
+ }
method_setImplementation(method, r->replacement);
say("redwood: mediaserverd: +[%s %s] replaced\n", r->class_name, r->selector);
}
@@ -102,5 +271,10 @@ redwood_media_init(void)
return;
}
slide = (uintptr_t)_dyld_get_shared_cache_range(&length) - CACHE_BASE;
+ torch = open("/dev/redwood-torch", O_WRONLY);
+ if (torch >= 0) {
+ flashlight_classes();
+ say("redwood: mediaserverd: the kernel has a flashlight (/dev/redwood-torch)\n");
+ }
_dyld_register_func_for_add_image(image_added); /* also called for every image already there */
}
diff --git a/userland/src/torch_test.c b/userland/src/torch_test.c
new file mode 100644
index 0000000..9362f9b
--- /dev/null
+++ b/userland/src/torch_test.c
@@ -0,0 +1,116 @@
+/*
+ * torch_test: the flashlight the way a program (and Control Center) works it: AVFlashlight, which
+ * asks mediaserverd's FigFlashlight, which sets the back camera's torch level (on this machine:
+ * libredwood-media.dylib in mediaserverd, the kernel's /dev/redwood-torch, torch=3).
+ *
+ * usage: torch_test STEP...
+ * wait SECONDS
+ * level L the flashlight at L (0 to 1; Control Center's steps are fractions of 1)
+ * off the flashlight off (level 0, then AVFlashlight's turnPowerOff)
+ * state what the kernel says is lit now (thousandths of Android's current)
+ *
+ * Says first whether iOS believes there is a flashlight (AVFlashlight's hasFlashlight: MobileGestalt's
+ * camera-flash) and whether it is available.
+ */
+#include <CoreFoundation/CoreFoundation.h>
+#include <fcntl.h>
+#include <objc/message.h>
+#include <objc/runtime.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+static id
+send(id object, const char *selector)
+{
+ return object ? ((id (*)(id, SEL))objc_msgSend)(object, sel_registerName(selector)) : NULL;
+}
+
+static BOOL
+yes(id object, const char *selector)
+{
+ return object ? ((BOOL (*)(id, SEL))objc_msgSend)(object, sel_registerName(selector)) : NO;
+}
+
+static const char *
+text(id object)
+{
+ id description = send(object, "description");
+ const char *utf8 = description ? ((const char *(*)(id, SEL))objc_msgSend)(description, sel_registerName("UTF8String")) : NULL;
+
+ return utf8 ? utf8 : "(none)";
+}
+
+static void
+kernel_state(void)
+{
+ int device = open("/dev/redwood-torch", O_RDONLY);
+ uint32_t lit = 0;
+
+ if (device < 0 || read(device, &lit, sizeof(lit)) != (ssize_t)sizeof(lit)) {
+ printf("torch_test: the kernel has no flashlight (/dev/redwood-torch)\n");
+ } else {
+ printf("torch_test: the kernel says: %s%u of 1000\n", lit ? "LIT at " : "dark, ", lit);
+ }
+ if (device >= 0) {
+ close(device);
+ }
+}
+
+int
+main(int argc, char **argv)
+{
+ Class flashlight_class = objc_getClass("AVFlashlight");
+ id flashlight;
+ int failed = 0;
+
+ setvbuf(stdout, NULL, _IONBF, 0);
+ if (flashlight_class == NULL) {
+ printf("torch_test: no AVFlashlight\n");
+ return 1;
+ }
+ printf("torch_test: AVFlashlight says hasFlashlight %s\n", yes((id)flashlight_class, "hasFlashlight") ? "YES" : "NO");
+ if (!yes((id)flashlight_class, "hasFlashlight")) {
+ /* (AVFlashlight refuses to be made, with an exception, where there is none: the loader adds the flash with torch=N) */
+ kernel_state();
+ return 1;
+ }
+ flashlight = send(send((id)flashlight_class, "alloc"), "init");
+ printf("torch_test: an AVFlashlight %s; available %s, overheated %s, level %.2f\n", flashlight ? "made" : "NOT MADE",
+ yes(flashlight, "isAvailable") ? "YES" : "NO", yes(flashlight, "isOverheated") ? "YES" : "NO",
+ flashlight ? ((float (*)(id, SEL))objc_msgSend)(flashlight, sel_registerName("flashlightLevel")) : -1.0f);
+ if (flashlight == NULL) {
+ return 1;
+ }
+ for (int i = 1; i < argc; i++) {
+ if (strcmp(argv[i], "wait") == 0 && i + 1 < argc) {
+ usleep((useconds_t)(atof(argv[++i]) * 1e6));
+ } else if (strcmp(argv[i], "level") == 0 && i + 1 < argc) {
+ float level = (float)atof(argv[++i]);
+ id error = NULL;
+ BOOL done = ((BOOL (*)(id, SEL, float, id *))objc_msgSend)(flashlight, sel_registerName("setFlashlightLevel:withError:"),
+ level, &error);
+
+ printf("torch_test: level %.2f: %s%s; available %s, level now %.2f\n", level, done ? "done" : "FAILED: ",
+ done ? "" : text(error), yes(flashlight, "isAvailable") ? "YES" : "NO",
+ ((float (*)(id, SEL))objc_msgSend)(flashlight, sel_registerName("flashlightLevel")));
+ failed |= !done;
+ } else if (strcmp(argv[i], "off") == 0) {
+ /* (as Control Center does it: level 0, then the power; FigFlashlight powers off only what is dark) */
+ id error = NULL;
+
+ ((BOOL (*)(id, SEL, float, id *))objc_msgSend)(flashlight, sel_registerName("setFlashlightLevel:withError:"), 0.0f,
+ &error);
+ send(flashlight, "turnPowerOff");
+ printf("torch_test: off; level now %.2f\n", ((float (*)(id, SEL))objc_msgSend)(flashlight,
+ sel_registerName("flashlightLevel")));
+ } else if (strcmp(argv[i], "state") == 0) {
+ kernel_state();
+ } else {
+ printf("torch_test: what is \"%s\"?\n", argv[i]);
+ return 2;
+ }
+ }
+ return failed;
+}
diff --git a/xnu/files/bsd/dev/redwood_audio.c b/xnu/files/bsd/dev/redwood_audio.c
index 9509615..fd0f475 100644
--- a/xnu/files/bsd/dev/redwood_audio.c
+++ b/xnu/files/bsd/dev/redwood_audio.c
@@ -336,4 +336,5 @@ redwood_audio_init(void)
redwood_virtio_sound_init();
redwood_speaker_init();
redwood_haptic_init();
+ redwood_torch_init();
}
diff --git a/xnu/files/bsd/dev/redwood_battery.c b/xnu/files/bsd/dev/redwood_battery.c
index 7e7509e..6e80b4d 100644
--- a/xnu/files/bsd/dev/redwood_battery.c
+++ b/xnu/files/bsd/dev/redwood_battery.c
@@ -43,6 +43,13 @@ static int battery_temperature_c = -273, battery_present, battery_charger_presen
static int battery_charging, battery_soc_estimated, battery_charger_action = -1;
static uint64_t battery_updates, battery_failures;
+/* for others in the kernel (the flashlight's thermal guard): -273 while it is not known */
+int
+redwood_battery_temperature(void)
+{
+ return battery_temperature_c;
+}
+
SYSCTL_NODE(_kern, OID_AUTO, redwood, CTLFLAG_RW | CTLFLAG_LOCKED, 0, "redwood phone bits");
SYSCTL_INT(_kern_redwood, OID_AUTO, battery_soc, CTLFLAG_RD | CTLFLAG_LOCKED,
&battery_soc_percent, 0, "battery state of charge, 0..100 percent, or -1 if unknown");
diff --git a/xnu/files/bsd/dev/redwood_buttons.c b/xnu/files/bsd/dev/redwood_buttons.c
index 4ba54f4..0bb4555 100644
--- a/xnu/files/bsd/dev/redwood_buttons.c
+++ b/xnu/files/bsd/dev/redwood_buttons.c
@@ -43,6 +43,7 @@
* and the phone's own device tree (qcom,spmi@c440000, pon_hlos@1300, gpio_keys).
*/
#include <kern/clock.h>
+#include <kern/locks.h>
#include <kern/thread.h>
#include <libkern/libkern.h>
#include <mach/mach_types.h>
@@ -122,6 +123,26 @@ wr(vm_offset_t address, uint32_t value)
static vm_offset_t arb_core, arb_cnfg, arb_observer;
+/*
+ * One transfer at a time through the arbiter for this system, whoever asks (the flashlight's
+ * driver, bsd/dev/redwood_torch.c, as well): with two at once the arbiter drops one ("the transfer
+ * was dropped"), as Linux never lets happen (one lock for the bus).
+ */
+static LCK_GRP_DECLARE(spmi_lck_grp, "redwood-spmi");
+static LCK_SPIN_DECLARE(spmi_lock, &spmi_lck_grp);
+
+void
+redwood_spmi_lock(void)
+{
+ lck_spin_lock(&spmi_lock);
+}
+
+void
+redwood_spmi_unlock(void)
+{
+ lck_spin_unlock(&spmi_lock);
+}
+
struct peripheral {
const char * name;
uint16_t id; /* slave << 8 | peripheral: the high byte of its register addresses */
@@ -149,11 +170,15 @@ spmi_read(const struct peripheral *p, uint8_t reg, uint8_t *bytes, uint32_t coun
const char *problem = NULL;
nanoseconds_to_absolutetime(READ_TIMEOUT_US * (uint64_t)NSEC_PER_USEC, &interval);
+ redwood_spmi_lock();
wr(channel + OBSERVER_COMMAND, COMMAND_READ | (uint32_t)reg << 4 | (count - 1));
do {
status = rd(channel + OBSERVER_STATUS);
now = mach_absolute_time();
} while (!(status & STATUS_DONE) && now - start < interval);
+ data[0] = rd(channel + OBSERVER_DATA0);
+ data[1] = count > 4 ? rd(channel + OBSERVER_DATA1) : 0;
+ redwood_spmi_unlock();
if (!(status & STATUS_DONE)) {
problem = "no answer from the arbiter";
@@ -164,8 +189,6 @@ spmi_read(const struct peripheral *p, uint8_t reg, uint8_t *bytes, uint32_t coun
} else if (status & STATUS_DROPPED) {
problem = "the transfer was dropped";
} else {
- data[0] = rd(channel + OBSERVER_DATA0);
- data[1] = count > 4 ? rd(channel + OBSERVER_DATA1) : 0;
for (uint32_t i = 0; i < count; i++) {
bytes[i] = (uint8_t)(data[i / 4] >> (8 * (i % 4)));
}
diff --git a/xnu/files/bsd/dev/redwood_torch.c b/xnu/files/bsd/dev/redwood_torch.c
new file mode 100644
index 0000000..e3ea958
--- /dev/null
+++ b/xnu/files/bsd/dev/redwood_torch.c
@@ -0,0 +1,763 @@
+/*
+ * The flashlight of the POCO X5 Pro (redwood): the flash LED module of the PM8350C (SPMI slave 2,
+ * registers 0xee00; "qcom,pm8350c-flash-led", four channels), the rear flash LED on its channel 0.
+ * Every address and number below belongs to this phone, from Android's own device tree, Xiaomi's
+ * driver for it (drivers/leds/leds-qti-flash.c of the phone's kernel, MiCode redwood-s-oss) and
+ * what Android does when its own flashlight is switched on (its LED class devices read, nothing
+ * written by us):
+ *
+ * Android's torch led:torch_0 at 125 mA through led:switch_0 (channel 0 alone), current
+ * resolution 12.5 mA ("qcom,ires-ua" 12500): IRESOLUTION bit 0 clear, ITARGET
+ * code round(125 / 12.5) - 1 = 9; the module enabled (0x46 = 0x80), then the
+ * channel (0x4e bit 0). Off in the reverse order, ITARGET back to 0. The
+ * torch has no safety timer (its bit is kept clear, as the driver keeps it)
+ * at Android's probe channel 0's strobe is the software's (0x4a: bits 6:4 and 2 clear) and its
+ * safety timer off (0x3e bit 7 clear)
+ *
+ * Writing to a PMIC is not like writing anywhere else: the PMICs make the phone's supplies. So
+ * every write goes through one function that takes only this module's registers above (the
+ * peripheral the arbiter's channel is checked to be, the registers by a list), every write is
+ * read back, and any surprise ends all writing for the run. Transfers through the arbiter are made
+ * one at a time with the buttons' driver (redwood_spmi_lock()): two at once, and it drops one.
+ *
+ * What iOS's flashlight is on this machine: the loader says the camera has a flash (with torch=N,
+ * /product/camera "flash": MobileGestalt's camera-flash, Control Center's flashlight button), and
+ * libredwood-media.dylib in mediaserverd hands FigFlashlight, which finds no camera here, a device
+ * of ours whose torch level is written to /dev/redwood-torch (userland/src/inject_media.c).
+ *
+ * Nothing here is done unless a boot-arg asks for it:
+ *
+ * torch=1 a look, reading only: the arbiter's channel for the module and who may write
+ * through it, the module's type, its registers, the PMIC's temperature alarm
+ * torch=2 ... and the light on once at Android's torch current for torch_secs (default 2),
+ * then off, every write read back
+ * torch=3 ... no light at the start; the light for iOS until the run ends: /dev/redwood-torch
+ * takes a level of 0 to 1000 (a 32-bit number; thousandths of Android's current, 0
+ * off) and the module is set to it -- never above Android's 125 mA; a read gives
+ * what is lit now
+ *
+ * Limits, whatever asks: Android's current at most; the light on for torch_max_s at a time at most
+ * (default 30, never more than 120), after which it stays off until it is asked for anew (0, then
+ * more); while it is on, ten times a second, the module's fault and over-temperature flags, the
+ * PMIC's temperature alarm and the battery's temperature (at most 45 C; from the audio DSP's battery
+ * manager with adsp=1, or the firmware's with battery=1; with neither the other two guard): any of
+ * them, a read that fails or a write that does not read back, and the light goes off and stays off
+ * for the rest of the run. At the run's end (and on a panic's way out) it goes off.
+ *
+ * Register layouts: Linux drivers/spmi/spmi-pmic-arb.c (arbiter version 5: a system's write
+ * channel for a peripheral is 0x10000 bytes of "chnls" per channel), Xiaomi's leds-qti-flash.c,
+ * drivers/thermal/qcom/qcom-spmi-temp-alarm.c.
+ */
+#include <kern/clock.h>
+#include <kern/thread.h>
+#include <libkern/libkern.h>
+#include <mach/mach_types.h>
+#include <machine/machine_routines.h>
+#include <miscfs/devfs/devfs.h>
+#include <pexpert/pexpert.h>
+#include <sys/conf.h>
+#include <sys/redwood_audio.h>
+#include <sys/redwood_input.h>
+#include <sys/systm.h>
+#include <sys/uio.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 uint32_t level;
+static bool broken, leaving;
+
+static int say(const char *format, ...) __printflike(1, 2);
+
+/* every line to the loader's log as well (and to the console when that may be written) */
+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;
+}
+
+/*
+ * The events that matter (lit, off, cut, trouble) are also kept, and said again at the run's end:
+ * the log of a long run keeps its beginning and its end, and these happen in between.
+ */
+#define NOTES 24
+static char notes[NOTES][200];
+static unsigned noted;
+
+static void note(const char *format, ...) __printflike(1, 2);
+
+static void
+note(const char *format, ...)
+{
+ char *slot = notes[noted++ % NOTES];
+ uint64_t ns;
+ va_list list;
+ int n;
+
+ absolutetime_to_nanoseconds(mach_absolute_time(), &ns);
+ n = snprintf(slot, sizeof(notes[0]), "%llu.%03llu s: ", ns / NSEC_PER_SEC, ns / NSEC_PER_MSEC % 1000);
+ va_start(list, format);
+ vsnprintf(slot + n, sizeof(notes[0]) - (size_t)n, format, list);
+ va_end(list);
+ say("torch: %s\n", slot);
+}
+
+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);
+ }
+}
+
+/* ---- the PMIC arbiter (version 5) ---------------------------------------------------------------- */
+
+#define ARB_CORE_PHYS 0x0c440000UL /* the version, and which peripheral each channel is */
+#define ARB_CORE_SIZE 0x1100UL
+#define ARB_CNFG_PHYS 0x0c40a000UL /* which system may write through each channel */
+#define ARB_CNFG_SIZE 0x1000UL
+#define ARB_OBSERVER_PHYS 0x0e600000UL /* reads: 0x80 per channel for our system (the first) */
+#define ARB_OBSERVER_SIZE 0x10000UL
+#define ARB_CHNLS_PHYS 0x0c600000UL /* writes: 0x10000 per channel */
+#define ARB_SYSTEM 0 /* who we are to the arbiter: the device tree's "qcom,ee" */
+
+#define ARB_VERSION 0x000
+#define ARB_VERSION_5 0x50000000u
+#define ARB_VERSION_7 0x70000000u
+#define ARB_FEATURES 0x004
+#define ARB_CHANNEL(n) (0x900 + 4 * (n)) /* [19:8] slave and peripheral */
+#define ARB_OWNER(n) (0x700 + 4 * (n)) /* [2:0] the system that may write through channel n */
+#define ARB_MAX_CHANNELS 512
+
+#define CHANNEL_COMMAND 0x00
+#define CHANNEL_STATUS 0x08
+#define CHANNEL_WDATA0 0x10
+#define OBSERVER_DATA0 0x18
+#define OBSERVER_DATA1 0x1c
+#define STATUS_DONE 0x1
+#define STATUS_FAILURE 0x2
+#define STATUS_DENIED 0x4
+#define STATUS_DROPPED 0x8
+#define COMMAND_WRITE (0u << 27) /* "extended register write long"; [11:4] register, [2:0] bytes - 1 */
+#define COMMAND_READ (1u << 27) /* "extended register read long" */
+#define TRANSFER_TIMEOUT_US 2000
+#define DROPPED "the transfer was dropped"
+
+struct peripheral {
+ const char * name;
+ uint16_t id; /* slave << 8 | peripheral */
+ uint16_t channel;
+ bool found, writable;
+ vm_offset_t write; /* its write channel, mapped (only the flash module's) */
+};
+static struct peripheral flash = { .name = "the PM8350C's flash LED module", .id = 0x2ee };
+static struct peripheral alarm = { .name = "the PM8350C's temperature alarm", .id = 0x20a };
+
+static vm_offset_t arb_core, arb_cnfg, arb_observer;
+static uint8_t alarm_subtype;
+
+/* (the arbiter one transfer at a time with the buttons' driver; at the run's end the others are stopped, perhaps holding it) */
+static void
+lock(void)
+{
+ if (!leaving) {
+ redwood_spmi_lock();
+ }
+}
+
+static void
+unlock(void)
+{
+ if (!leaving) {
+ redwood_spmi_unlock();
+ }
+}
+
+static const char *
+wait_done(vm_offset_t channel)
+{
+ uint64_t start = mach_absolute_time(), interval;
+ uint32_t status;
+
+ nanoseconds_to_absolutetime(TRANSFER_TIMEOUT_US * (uint64_t)NSEC_PER_USEC, &interval);
+ do {
+ status = rd(channel + CHANNEL_STATUS);
+ } while (!(status & STATUS_DONE) && mach_absolute_time() - start < interval);
+ return !(status & STATUS_DONE) ? "no answer from the arbiter" : (status & STATUS_DENIED) ? "the arbiter refuses" :
+ (status & STATUS_FAILURE) ? "the transfer failed" : (status & STATUS_DROPPED) ? DROPPED : NULL;
+}
+
+/*
+ * `count' (1 to 8) registers from `reg' on; NULL, or what went wrong. A transfer the arbiter drops
+ * now and then (the buttons' driver sees one in a thousand or so, from whatever else is on the bus)
+ * is asked for again, twice at most.
+ */
+static const char *spmi_read_once(const struct peripheral *p, uint8_t reg, uint8_t *bytes, uint32_t count);
+
+static const char *
+spmi_read(const struct peripheral *p, uint8_t reg, uint8_t *bytes, uint32_t count)
+{
+ const char *problem = NULL;
+
+ for (int tries = 0; tries < 3; tries++) {
+ if ((problem = spmi_read_once(p, reg, bytes, count)) == NULL || strcmp(problem, DROPPED) != 0) {
+ break;
+ }
+ }
+ return problem;
+}
+
+static const char *
+spmi_read_once(const struct peripheral *p, uint8_t reg, uint8_t *bytes, uint32_t count)
+{
+ vm_offset_t channel = arb_observer + 0x10000UL * ARB_SYSTEM + 0x80UL * p->channel;
+ const char *problem;
+ uint32_t data[2];
+
+ if (!p->found) {
+ return "no channel";
+ }
+ lock();
+ wr(channel + CHANNEL_COMMAND, COMMAND_READ | (uint32_t)reg << 4 | (count - 1));
+ problem = wait_done(channel);
+ data[0] = rd(channel + OBSERVER_DATA0);
+ data[1] = count > 4 ? rd(channel + OBSERVER_DATA1) : 0;
+ unlock();
+ if (problem != NULL) {
+ return problem;
+ }
+ for (uint32_t i = 0; i < count; i++) {
+ bytes[i] = (uint8_t)(data[i / 4] >> (8 * (i % 4)));
+ }
+ return NULL;
+}
+
+/* ---- the flash LED module -------------------------------------------------------------------------- */
+
+#define FLASH_REVISION1 0x00
+#define FLASH_TYPE 0x04 /* 0x18: a flash LED module */
+#define FLASH_SUBTYPE 0x05 /* 0x07: four channels */
+#define FLASH_STATUS1 0x06 /* a channel open or shorted */
+#define FLASH_STATUS2 0x07
+#define STATUS2_OTST1 0x20 /* over-temperature, the first and the second threshold */
+#define STATUS2_OTST2 0x10
+#define STATUS2_VPH_LOW 0x01 /* the supply drooped */
+#define FLASH_INT_RT_STS 0x10
+#define RT_STS_FAULT 0x01 /* open, short, or its supply not ready */
+#define FLASH_SAFETY_TIMER0 0x3e /* [7] on */
+#define FLASH_ITARGET0 0x42 /* [6:0]: (code + 1) x the resolution */
+#define FLASH_MODULE_EN 0x46 /* [7] */
+#define FLASH_IRESOLUTION 0x49 /* a bit per channel: 0 12.5 mA, 1 5 mA */
+#define FLASH_STROBE_CTRL0 0x4a /* [6:4] hardware strobe's kind, [2] hardware strobe */
+#define FLASH_EN_LED_CTRL 0x4e /* a bit per channel */
+#define FLASH_OTST2_CFG1 0x78
+#define FLASH_OTST1_CFG1 0x7a
+
+#define ALARM_SUBTYPE 0x05 /* 0x08: the first generation, 0x09 the second */
+#define ALARM_STATUS 0x08 /* the over-temperature stage: [1:0] (first generation) or [6:4] */
+
+#define ANDROID_TORCH_MA 125 /* led:torch_0 while Android's flashlight is on */
+#define IRES_UA 12500 /* its resolution ("qcom,ires-ua") */
+#define ANDROID_ITARGET 9 /* round(125000 / 12500) - 1: the most ever written */
+#define HOTTEST_BATTERY_C 45
+
+static const uint8_t writable_regs[] = {
+ FLASH_SAFETY_TIMER0, FLASH_ITARGET0, FLASH_MODULE_EN, FLASH_IRESOLUTION, FLASH_STROBE_CTRL0, FLASH_EN_LED_CTRL,
+};
+
+static void
+give_up(const char *why)
+{
+ if (!broken) {
+ broken = true;
+ note("%s: no more writing to the flash module for the rest of the run", why);
+ }
+}
+
+/*
+ * One register of the flash module (and of the six above only) written and read back: false, and
+ * no more writing, if it cannot be or does not read back.
+ */
+static bool
+put(uint8_t reg, uint8_t value)
+{
+ const char *problem;
+ uint8_t back = 0xff;
+ bool allowed = false;
+
+ for (size_t i = 0; i < sizeof(writable_regs); i++) {
+ allowed |= writable_regs[i] == reg;
+ }
+ if (broken || !allowed || !flash.writable || flash.write == 0 || flash.id != 0x2ee) {
+ give_up(allowed ? "a write that may not be made" : "a register that is not to be written");
+ return false;
+ }
+ /* (the channel is still the module's: its entry in the arbiter's table is looked at again) */
+ if (((rd(arb_core + ARB_CHANNEL(flash.channel)) >> 8) & 0xfff) != flash.id) {
+ give_up("the arbiter's channel is no longer the flash module's");
+ return false;
+ }
+ for (int tries = 0; tries < 3; tries++) {
+ lock();
+ wr(flash.write + CHANNEL_WDATA0, value);
+ wr(flash.write + CHANNEL_COMMAND, COMMAND_WRITE | (uint32_t)reg << 4);
+ problem = wait_done(flash.write);
+ unlock();
+ if (problem == NULL || strcmp(problem, DROPPED) != 0) {
+ break; /* (a dropped write has not been made: asked for again, then read back) */
+ }
+ }
+ if (problem != NULL || (problem = spmi_read(&flash, reg, &back, 1)) != NULL) {
+ say("torch: %#04x <- %#04x: %s\n", reg, value, problem);
+ give_up("a write that failed");
+ return false;
+ }
+ if (back != value) {
+ say("torch: %#04x <- %#04x, but it reads %#04x\n", reg, value, back);
+ give_up("a register that did not read back as written");
+ return false;
+ }
+ return true;
+}
+
+static bool
+get(const struct peripheral *p, uint8_t reg, uint8_t *value)
+{
+ const char *problem = spmi_read(p, reg, value, 1);
+
+ if (problem != NULL) {
+ say("torch: reading %#04x of %s: %s\n", reg, p->name, problem);
+ return false;
+ }
+ return true;
+}
+
+/* only the bits of `mask' changed, as the driver's masked writes do */
+static bool
+put_bits(uint8_t reg, uint8_t mask, uint8_t value)
+{
+ uint8_t now;
+
+ if (!get(&flash, reg, &now)) {
+ give_up("a read that failed");
+ return false;
+ }
+ return (now & mask) == (value & mask) || put(reg, (uint8_t)((now & ~mask) | (value & mask)));
+}
+
+static void
+find_channel(struct peripheral *p, uint32_t channels)
+{
+ for (uint32_t n = 0; n < channels; n++) {
+ uint32_t map = rd(arb_core + ARB_CHANNEL(n)), owner;
+
+ if (map == 0 || ((map >> 8) & 0xfff) != p->id) {
+ continue;
+ }
+ owner = rd(arb_cnfg + ARB_OWNER(n)) & 7;
+ say("torch: channel %u is %s (%#x); written by system %u%s\n", n, p->name, map, owner,
+ owner == ARB_SYSTEM ? ", which is us" : "");
+ if (!p->found || owner == ARB_SYSTEM) {
+ p->found = true;
+ p->channel = (uint16_t)n;
+ p->writable = owner == ARB_SYSTEM;
+ }
+ }
+ if (!p->found) {
+ say("torch: no channel of the arbiter is %s\n", p->name);
+ }
+}
+
+static void
+show_registers(void)
+{
+ uint8_t r[8];
+ char line[200];
+
+ for (unsigned base = 0; base < 0x100; base += 0x20) {
+ int n = snprintf(line, sizeof(line), "torch: %#04x:", base);
+
+ for (unsigned i = 0; i < 0x20; i += 8) {
+ if (spmi_read(&flash, (uint8_t)(base + i), r, 8) != NULL) {
+ n += snprintf(line + n, sizeof(line) - (size_t)n, " (unreadable)");
+ continue;
+ }
+ for (unsigned j = 0; j < 8; j++) {
+ n += snprintf(line + n, sizeof(line) - (size_t)n, " %02x", r[j]);
+ }
+ }
+ say("%s\n", line);
+ }
+}
+
+/* What would make the light go off now, or NULL. */
+static const char *
+trouble(void)
+{
+ static char why[180];
+ uint8_t rt = 0, status1 = 0, status2 = 0, alarm_status = 0, stage;
+
+ if (!get(&flash, FLASH_INT_RT_STS, &rt) || !get(&flash, FLASH_STATUS1, &status1) ||
+ !get(&flash, FLASH_STATUS2, &status2) || (alarm.found && !get(&alarm, ALARM_STATUS, &alarm_status))) {
+ return "a read of the flags that failed";
+ }
+ stage = alarm_subtype == 0x08 ? alarm_status & 0x03 : (alarm_status >> 4) & 0x07;
+ if ((rt & RT_STS_FAULT) || status1 != 0 || (status2 & (STATUS2_OTST1 | STATUS2_OTST2 | STATUS2_VPH_LOW)) || stage != 0) {
+ uint8_t more[8] = { 0 }, latched[2] = { 0 };
+
+ (void)spmi_read(&flash, 0x06, more, 8);
+ (void)spmi_read(&flash, 0x18, latched, 2);
+ snprintf(why, sizeof(why), "the module says fault %#x, channels %#x, temperature and supply %#x (0x06-0x0d: %02x %02x %02x "
+ "%02x %02x %02x %02x %02x, latched %#x); the PMIC's temperature stage %u", rt, status1, status2, more[0], more[1],
+ more[2], more[3], more[4], more[5], more[6], more[7], latched[0], stage);
+ return why;
+ }
+ if (redwood_battery_temperature() >= HOTTEST_BATTERY_C) {
+ snprintf(why, sizeof(why), "the battery is at %d C", redwood_battery_temperature());
+ return why;
+ }
+ return NULL;
+}
+
+static bool configured, lit;
+
+/* Android's probe, once: channel 0 strobed by software, its safety timer off. */
+static bool
+configure(void)
+{
+ if (!configured && put_bits(FLASH_STROBE_CTRL0, 0x74, 0x00) && put_bits(FLASH_SAFETY_TIMER0, 0x80, 0x00)) {
+ configured = true;
+ }
+ return configured;
+}
+
+/* The light at `permille' of Android's current: its writes in its order. */
+static bool
+light(uint32_t permille)
+{
+ uint32_t ua = ANDROID_TORCH_MA * 1000 * permille / 1000, code;
+ const char *why;
+
+ if (ua < IRES_UA) {
+ ua = IRES_UA; /* (the driver's least: one step) */
+ }
+ code = (ua + IRES_UA / 2) / IRES_UA - 1;
+ if (code > ANDROID_ITARGET) {
+ code = ANDROID_ITARGET;
+ }
+ if (!lit && (why = trouble()) != NULL) {
+ note("not lit: %s", why);
+ give_up("trouble before the light");
+ return false;
+ }
+ if (!configure() || !put_bits(FLASH_IRESOLUTION, 0x01, 0x00) || !put_bits(FLASH_ITARGET0, 0x7f, (uint8_t)code)) {
+ return false;
+ }
+ if (!lit && (!put(FLASH_MODULE_EN, 0x80) || !put_bits(FLASH_EN_LED_CTRL, 0x01, 0x01))) {
+ return false;
+ }
+ lit = true;
+ return true;
+}
+
+/* Off, in Android's order: the channel, the module, the target current, the timer's bit. */
+static bool
+dark(void)
+{
+ bool ok = put_bits(FLASH_EN_LED_CTRL, 0x01, 0x00) && put(FLASH_MODULE_EN, 0x00) && put_bits(FLASH_ITARGET0, 0x7f, 0x00) &&
+ put_bits(FLASH_SAFETY_TIMER0, 0x80, 0x00);
+
+ lit = !ok && lit;
+ return ok;
+}
+
+/* ---- torch=3: the light for iOS --------------------------------------------------------------------- */
+
+static volatile uint32_t wanted; /* the level asked for last, 0 to 1000 */
+static volatile uint32_t asked; /* how many times one was */
+static uint32_t max_secs = 30;
+
+static int
+torch_write(__unused dev_t dev, struct uio *uio, __unused int ioflag)
+{
+ uint32_t value;
+ int error;
+
+ while (uio_resid(uio) >= (user_ssize_t)sizeof(value)) {
+ if ((error = uiomove((caddr_t)&value, sizeof(value), uio)) != 0) {
+ return error;
+ }
+ wanted = value > 1000 ? 1000 : value;
+ asked++;
+ }
+ return 0;
+}
+
+/* what is lit now: the level, 0 if nothing */
+static uint32_t shown;
+
+static int
+torch_read(__unused dev_t dev, struct uio *uio, __unused int ioflag)
+{
+ uint32_t value = shown;
+
+ return uiomove((caddr_t)&value, (int)MIN(sizeof(value), (size_t)uio_resid(uio)), uio);
+}
+
+static int
+torch_open(__unused dev_t dev, __unused int flags, __unused int type, __unused struct proc *p)
+{
+ return 0;
+}
+
+static const struct cdevsw torch_cdevsw = {
+ .d_open = torch_open, .d_close = torch_open, .d_read = torch_read, .d_write = torch_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
+};
+
+static uint64_t
+now_ms(void)
+{
+ uint64_t ns;
+
+ absolutetime_to_nanoseconds(mach_absolute_time(), &ns);
+ return ns / NSEC_PER_MSEC;
+}
+
+static void
+serve(void)
+{
+ uint32_t applied = 0, times = 0, cut = 0;
+ uint64_t since = 0, last_look = 0;
+ bool waiting_for_off = false; /* cut at the limit: dark until iOS asks for 0 */
+ int major = cdevsw_add(-1, &torch_cdevsw);
+
+ if (major < 0 || devfs_make_node(makedev(major, 0), DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0666, "redwood-torch") == NULL) {
+ say("torch: /dev/redwood-torch cannot be made\n");
+ return;
+ }
+ say("torch: THE LIGHT IS IOS'S (/dev/redwood-torch) from here on, until the run ends: at most Android's %u mA, at most %u s "
+ "at a time\n", ANDROID_TORCH_MA, max_secs);
+ while (!broken) {
+ uint32_t want = wanted;
+ uint64_t now = now_ms();
+
+ if (want == 0) {
+ waiting_for_off = false;
+ }
+ if (waiting_for_off) {
+ want = 0;
+ }
+ if (want != applied) {
+ if (want == 0 ? dark() : light(want)) {
+ if (applied == 0) {
+ since = now;
+ times++;
+ }
+ if (want == 0) {
+ note("off (iOS asked for 0)");
+ } else {
+ note("ON (iOS asked for %u of 1000; the battery %d C)", wanted, redwood_battery_temperature());
+ }
+ applied = want;
+ shown = want;
+ } else {
+ break;
+ }
+ }
+ if (applied != 0 && now - since >= max_secs * 1000ull) {
+ cut++;
+ note("on for %u s, the limit: off until iOS asks again", max_secs);
+ waiting_for_off = true;
+ if (!dark()) {
+ break;
+ }
+ applied = 0;
+ shown = 0;
+ continue;
+ }
+ if (applied != 0 && now - last_look >= 100) {
+ const char *why;
+
+ last_look = now;
+ if ((why = trouble()) != NULL) {
+ note("OFF: %s", why);
+ (void)dark();
+ give_up("trouble while lit");
+ break;
+ }
+ }
+ wait_ms(20);
+ }
+ if (lit) {
+ (void)dark();
+ }
+ shown = 0;
+ say("torch: the light is given up on (%u times lit, %u cut at %u s)\n", times, cut, max_secs);
+}
+
+/* ---- the start ------------------------------------------------------------------------------------- */
+
+static void
+torch_thread(__unused void *parameter, __unused wait_result_t result)
+{
+ uint32_t version, channels;
+ uint8_t id[2] = { 0, 0 }, revision = 0, alarm_status = 0;
+
+ say("torch: level %u: %s\n", level, level == 1 ? "a look, reading only" : level == 2 ? "the light on once" :
+ "the light for iOS");
+ arb_core = ml_io_map(ARB_CORE_PHYS, ARB_CORE_SIZE);
+ arb_cnfg = ml_io_map(ARB_CNFG_PHYS, ARB_CNFG_SIZE);
+ arb_observer = ml_io_map(ARB_OBSERVER_PHYS, ARB_OBSERVER_SIZE);
+ version = rd(arb_core + ARB_VERSION);
+ channels = rd(arb_core + ARB_FEATURES) & 0x7ff;
+ if (version < ARB_VERSION_5 || version >= ARB_VERSION_7) {
+ say("torch: PMIC arbiter version %#x, not 5: nothing done\n", version);
+ goto out;
+ }
+ if (channels == 0 || channels > ARB_MAX_CHANNELS) {
+ channels = ARB_MAX_CHANNELS;
+ }
+ find_channel(&flash, channels);
+ find_channel(&alarm, channels);
+ if (!flash.found || spmi_read(&flash, FLASH_TYPE, id, 2) != NULL || spmi_read(&flash, FLASH_REVISION1, &revision, 1) != NULL) {
+ say("torch: the flash module cannot be read\n");
+ goto out;
+ }
+ say("torch: the module says type %#x, subtype %#x, revision %#x%s\n", id[0], id[1], revision,
+ id[0] == 0x18 && id[1] == 0x07 ? ": a flash LED module of four channels, as Android's driver expects" : ": NOT WHAT WAS EXPECTED");
+ show_registers();
+ if (alarm.found && get(&alarm, ALARM_SUBTYPE, &alarm_subtype) && get(&alarm, ALARM_STATUS, &alarm_status)) {
+ uint8_t stage = alarm_subtype == 0x08 ? alarm_status & 0x03 : (alarm_status >> 4) & 0x07;
+
+ say("torch: the PMIC's temperature alarm (subtype %#x) says %#x: stage %u%s\n", alarm_subtype, alarm_status, stage,
+ stage == 0 ? " (all is well)" : "");
+ } else {
+ alarm.found = false;
+ }
+ if (id[0] != 0x18 || id[1] != 0x07 || level < 2) {
+ goto out;
+ }
+ if (!flash.writable) {
+ say("torch: the channel is not ours to write through: nothing written\n");
+ goto out;
+ }
+ flash.write = ml_io_map(ARB_CHNLS_PHYS + 0x10000UL * flash.channel, 0x1000);
+ PE_parse_boot_argn("torch_max_s", &max_secs, sizeof(max_secs));
+ max_secs = max_secs < 1 ? 1 : max_secs > 120 ? 120 : max_secs;
+ if (level == 2) {
+ uint32_t secs = 2;
+ uint64_t until;
+ const char *why = NULL;
+
+ PE_parse_boot_argn("torch_secs", &secs, sizeof(secs));
+ secs = secs < 1 ? 1 : secs > max_secs ? max_secs : secs;
+ say("torch: the light ON at Android's %u mA (ITARGET %u, 12.5 mA steps) for %u s\n", ANDROID_TORCH_MA, ANDROID_ITARGET,
+ secs);
+ if (light(1000)) {
+ uint8_t rt = 0, s1 = 0, s2 = 0;
+
+ wait_ms(50);
+ (void)get(&flash, FLASH_INT_RT_STS, &rt);
+ (void)get(&flash, FLASH_STATUS1, &s1);
+ (void)get(&flash, FLASH_STATUS2, &s2);
+ note("lit at Android's %u mA; 50 ms on: interrupt status %#x (%s), channels %#x, temperature and supply %#x",
+ ANDROID_TORCH_MA, rt, (rt & 0x10) ? "ramped up" : "NOT ramped up", s1, s2);
+ show_registers();
+ for (until = now_ms() + secs * 1000ull; now_ms() < until && (why = trouble()) == NULL;) {
+ wait_ms(100);
+ }
+ if (why != NULL) {
+ note("OFF early: %s", why);
+ }
+ if (dark()) {
+ note("off again after %u s", secs);
+ }
+ show_registers();
+ }
+ } else {
+ serve();
+ }
+out:
+ say("torch: done\n");
+ thread_terminate(current_thread());
+}
+
+void
+redwood_torch_init(void)
+{
+ thread_t thread;
+
+ if (!PE_parse_boot_argn("torch", &level, sizeof(level)) || level == 0) {
+ return;
+ }
+ level = level > 3 ? 3 : level;
+ if (kernel_thread_start(torch_thread, NULL, &thread) == KERN_SUCCESS) {
+ thread_deallocate(thread);
+ }
+}
+
+/* At the run's end and on a panic's way out: the light off, if it was ever lit. */
+void
+redwood_torch_quiesce(void)
+{
+ uint8_t module = 0xff, channels = 0xff, target = 0xff;
+
+ if (level < 2 || flash.write == 0) {
+ return;
+ }
+ leaving = true;
+ if (lit) {
+ broken = false; /* (one last time, whatever went before) */
+ say("torch: at the run's end: the light %s\n", dark() ? "switched off" : "COULD NOT BE SWITCHED OFF");
+ }
+ say("torch: what happened in this run (%u events):\n", noted);
+ for (unsigned i = noted > NOTES ? noted - NOTES : 0; i < noted; i++) {
+ say("torch: %s\n", notes[i % NOTES]);
+ }
+ (void)spmi_read(&flash, FLASH_MODULE_EN, &module, 1);
+ (void)spmi_read(&flash, FLASH_EN_LED_CTRL, &channels, 1);
+ (void)spmi_read(&flash, FLASH_ITARGET0, &target, 1);
+ say("torch: at the run's end the module reads: enable %#04x, channels %#04x, target %#04x%s\n", module, channels, target,
+ module == 0 && (channels & 0x01) == 0 && target == 0 ? " (dark)" : " (NOT DARK)");
+}
diff --git a/xnu/files/bsd/sys/redwood_audio.h b/xnu/files/bsd/sys/redwood_audio.h
index a0043fd..ef77512 100644
--- a/xnu/files/bsd/sys/redwood_audio.h
+++ b/xnu/files/bsd/sys/redwood_audio.h
@@ -54,6 +54,8 @@ void redwood_virtio_sound_init(void); /* boot-arg virtio_sound=1: QEMU's virti
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 */
+void redwood_torch_init(void); /* boot-arg torch=N: the phone's flashlight (bsd/dev/redwood_torch.c) */
+void redwood_torch_quiesce(void); /* the light off: 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/bsd/sys/redwood_input.h b/xnu/files/bsd/sys/redwood_input.h
index 8fda7bf..bdfb148 100644
--- a/xnu/files/bsd/sys/redwood_input.h
+++ b/xnu/files/bsd/sys/redwood_input.h
@@ -43,6 +43,10 @@ void redwood_virtio_input_init(void); /* boot-arg virtio_input=1: QEMU's virti
void redwood_goodix_init(void); /* boot-arg touchscreen=1: the phone's Goodix or FocalTech touch screen */
void redwood_buttons_init(void); /* boot-arg buttons=1: the phone's power and volume keys */
void redwood_battery_init(void); /* boot-arg battery=1: Qualcomm UEFI charger state shared by xnuloader */
+int redwood_battery_temperature(void); /* the battery's temperature in C, -273 while it is not known */
+/* one transfer at a time through the PMIC arbiter for this system (bsd/dev/redwood_buttons.c) */
+void redwood_spmi_lock(void);
+void redwood_spmi_unlock(void);
/*
* How the battery is, as the audio DSP's battery manager says (bsd/dev/redwood_adsp.c, with adsp=1):
* handed to bsd/dev/redwood_battery.c, which keeps it for the sysctls kern.redwood.battery_* and
diff --git a/xnu/files/osfmk/arm64/loader_return.c b/xnu/files/osfmk/arm64/loader_return.c
index c171fc7..21e2d44 100644
--- a/xnu/files/osfmk/arm64/loader_return.c
+++ b/xnu/files/osfmk/arm64/loader_return.c
@@ -53,6 +53,7 @@ extern void redwood_adsp_stop(void);
extern void redwood_adsp_quiesce(void);
extern void redwood_ddr_quiesce(void);
extern void redwood_haptic_quiesce(void);
+extern void redwood_torch_quiesce(void);
void loader_checkpoint(uint64_t n);
/* Also referenced from the early exception vector in start.s. */
@@ -369,6 +370,7 @@ loader_return(void)
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 */
+ redwood_torch_quiesce(); /* the flashlight off, if it was lit */
/*
* 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 4a5c06d..b8af330 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..318eecb89391 100644
+index 44274016a4cf..ecf7c73a228e 100644
--- a/bsd/conf/files
+++ b/bsd/conf/files
-@@ -109,6 +109,28 @@ bsd/dev/munge.c optional config_requires_u32_munging
+@@ -109,6 +109,29 @@ bsd/dev/munge.c optional config_requires_u32_munging
bsd/dev/unix_startup.c standard
bsd/dev/monotonic.c optional monotonic
@@ -68,6 +68,7 @@ index 44274016a4cf..318eecb89391 100644
+bsd/dev/redwood_speaker.c standard
+bsd/dev/redwood_guard.c standard
+bsd/dev/redwood_haptic.c standard
++bsd/dev/redwood_torch.c standard
+bsd/dev/redwood_wifi.c standard
+bsd/dev/redwood_adsp.c standard
+bsd/dev/redwood_sound.c standard
@@ -78,7 +79,7 @@ index 44274016a4cf..318eecb89391 100644
bsd/dev/dev_perfmon.c optional config_perfmon
bsd/libkern/crc32.c standard
-@@ -155,6 +177,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs
+@@ -155,6 +178,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
@@ -89,7 +90,7 @@ index 44274016a4cf..318eecb89391 100644
bsd/miscfs/routefs/routefs_ops.c optional routefs
-@@ -361,6 +387,7 @@ bsd/security/audit/audit_syscalls.c standard
+@@ -361,6 +388,7 @@ bsd/security/audit/audit_syscalls.c standard
bsd/security/audit/audit_worker.c optional config_audit
bsd/pthread/pthread_shims.c standard
@@ -97,7 +98,7 @@ index 44274016a4cf..318eecb89391 100644
bsd/pthread/pthread_priority.c standard
bsd/pthread/pthread_workqueue.c standard
-@@ -383,6 +410,7 @@ bsd/kern/kern_debug.c standard
+@@ -383,6 +411,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
diff --git a/xnuloader/identity.h b/xnuloader/identity.h
index cfad9ce..980ca05 100644
--- a/xnuloader/identity.h
+++ b/xnuloader/identity.h
@@ -112,3 +112,61 @@ static const unsigned char identity_haptics_data[] = {
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
};
+/* 43 properties */
+static const struct identity_prop identity_camera[] = {
+ { "aggregate-cam-video-zoom", 0, 4 },
+ { "rear-max-video-fps-4k", 4, 4 },
+ { "rear-max-video-zoom", 8, 4 },
+ { "rear-max-burst-length", 12, 4 },
+ { "camera-hdr-version", 16, 4 },
+ { "front-max-burst-length", 20, 4 },
+ { "auto-focus", 24, 4 },
+ { "front-auto-hdr", 28, 4 },
+ { "front-burst-image-duration", 32, 4 },
+ { "rear-max-video-fps-720p", 36, 4 },
+ { "rear-slowmo", 40, 4 },
+ { "flash", 44, 4 },
+ { "pipelined-stillimage-capability", 48, 4 },
+ { "rear-max-slomo-video-fps-1080p", 52, 4 },
+ { "front-hdr", 56, 4 },
+ { "front-flash-capability", 60, 4 },
+ { "pearl-camera", 64, 4 },
+ { "video-cap", 68, 4 },
+ { "front-hdr-on", 72, 4 },
+ { "rear-auto-hdr", 76, 4 },
+ { "front-burst", 80, 4 },
+ { "p3-color-space-video-recording", 84, 4 },
+ { "rear-burst-image-duration", 88, 4 },
+ { "rear-max-slomo-video-fps-720p", 92, 4 },
+ { "video-stills", 96, 4 },
+ { "rear-max-video-frame_rate", 100, 4 },
+ { "rear-hdr-on", 104, 4 },
+ { "rear-max-video-fps-1080p", 108, 4 },
+ { "aggregate-camera", 112, 4 },
+ { "rear-stage-light-portrait", 116, 0 },
+ { "aggregate-cam-photo-zoom", 116, 4 },
+ { "rear-hdr", 120, 4 },
+ { "rear-burst", 124, 4 },
+ { "rear-cam-telephoto-capability", 128, 4 },
+ { "post-effects", 132, 4 },
+ { "stage-light-portrait-preview", 136, 4 },
+ { "live-effects", 140, 4 },
+ { "front-max-video-zoom", 144, 4 },
+ { "front-max-video-fps-720p", 148, 4 },
+ { "panorama", 152, 4 },
+ { "front-max-video-fps-1080p", 156, 4 },
+ { "front-stage-light-portrait", 160, 0 },
+ { "live-photo-capture", 160, 4 },
+};
+static const unsigned char identity_camera_data[] = {
+ 0x58, 0x02, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x58, 0x02, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
+ 0x58, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00,
+ 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
+ 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
+ 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
+ 0x3c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00,
+ 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00,
+ 0x01, 0x00, 0x00, 0x00,
+};
+
diff --git a/xnuloader/loader.c b/xnuloader/loader.c
index 1e7e56a..6fa06ce 100644
--- a/xnuloader/loader.c
+++ b/xnuloader/loader.c
@@ -432,6 +432,17 @@ dt_identity(struct dt_writer *w, const struct identity_prop *props, uint32_t cou
}
}
+/* One property of those copied from the iPhone's device tree, by name. */
+static void
+dt_identity_one(struct dt_writer *w, const struct identity_prop *props, uint32_t count, const unsigned char *data, const char *name)
+{
+ for (uint32_t i = 0; i < count; i++) {
+ if (str_eq(props[i].name, name)) {
+ dt_prop(w, props[i].name, data + props[i].offset, props[i].length);
+ }
+ }
+}
+
static void
dt_begin(struct dt_writer *w, const char *name)
{
@@ -1722,6 +1733,8 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)
uint64_t this_mpidr = READ_SYSREG(MPIDR_EL1) & 0xFFFFFF, kernel_mpidr = this_mpidr;
/* "cpus=N" or "cpumask=M" there too: the kernel may have more cores than the one it starts on */
int more_cores = 0, battery_requested = 0;
+ /* "torch=N" (not 0) there too: the phone's flashlight is the kernel's (bsd/dev/redwood_torch.c) */
+ int torch_requested = 0;
for (const char *c = pi.cmdline; *c; c++) {
if (starts_with(c, "bootcpu=") && (c == pi.cmdline || c[-1] == ' ') && c[8] >= '0' && c[8] <= '7') {
kernel_mpidr = (uint64_t)(c[8] - '0') << PLAT->core_shift;
@@ -1729,6 +1742,7 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)
more_cores |= (starts_with(c, "cpus=") || starts_with(c, "cpumask=")) && (c == pi.cmdline || c[-1] == ' ');
battery_requested |= starts_with(c, "battery=1") && (c == pi.cmdline || c[-1] == ' ') &&
(c[9] == 0 || c[9] == ' ');
+ torch_requested |= starts_with(c, "torch=") && (c == pi.cmdline || c[-1] == ' ') && c[6] >= '1' && c[6] <= '9';
}
if (battery_requested) {
charger_start();
@@ -1973,6 +1987,15 @@ run_kernel(int have_checkpoint, uint64_t checkpoint)
dt_begin(&w, "haptics");
dt_identity(&w, identity_haptics, sizeof(identity_haptics) / sizeof(identity_haptics[0]), identity_haptics_data);
dt_end(&w);
+ /*
+ * and of its camera what is here: with torch=N the flash (MobileGestalt's camera-flash; without
+ * it Control Center has no flashlight). The rest of the iPhone's camera is not here, nor said to be.
+ */
+ if (torch_requested) {
+ dt_begin(&w, "camera");
+ dt_identity_one(&w, identity_camera, sizeof(identity_camera) / sizeof(identity_camera[0]), identity_camera_data, "flash");
+ 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 663940f..b689490 100755
--- a/xnuloader/mkidentity.py
+++ b/xnuloader/mkidentity.py
@@ -11,7 +11,8 @@ tree: the root node's model and compatible, and the /product node (screen class,
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
+which the iPhone X does not have), and of the /product/camera node what the phone here has as well (its
+"flash": MobileGestalt's camera-flash, without which there is no flashlight in Control Center). 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.
@@ -71,6 +72,8 @@ def main():
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'))
+ # (the camera's: the loader takes from it what the hardware here has, the flash so far)
+ emit('identity_camera', product['camera'][0], ('name', 'AAPL,phandle'))
if __name__ == '__main__':