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

Battery: the real charge and charging state, from the audio DSP, as a power source iOS reads

vcvkkfa751696afa8
diff --git a/README.md b/README.md
index 30b8209..c544e26 100644
--- a/README.md
+++ b/README.md
@@ -246,6 +246,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 дБ тише), тон звучит 3 с, потом всё затихает, выключается и возвращается как было. `sound=4` — то, что играет iOS (`/dev/redwood-audio`), до конца сеанса: порт и поток работают всё время (без звука в них идёт тишина), усилители настраиваются один раз и выключены, а когда в записи iOS появляется не тишина, включаются и быстро (как у драйвера Android) выводятся на `sound_below`; после трёх секунд тишины снова выключаются. Звук доходит до усилителей через 160 мс после записи, усилители готовы через 65 мс. У динамика в модуле HAL есть регулятор громкости, его значение уходит в ядро (`ioctl` `REDWOOD_AUDIO_SET_VOLUME`) и задаёт уровень усилителей ниже потолка (0 — усилители не включаются), но iOS ставит его только раз, на максимум, а громкость кнопок и Пункта управления применяет к самим отсчётам (программная громкость для динамика iPhone X в таблицах VirtualAudio); при громкости 0 iOS пишет тишину, и усилители тоже не включаются. Проверка — `RC_JOBS=rc.jobs.volume`. `sound_secs=S` (не больше 3 с тоном), `sound_pause=MS`. Подробности в начале `bsd/dev/redwood_sound.c` и `bsd/dev/redwood_speaker.c` |
+| `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 ядер запускаются и чисто возвращаются в загрузчик). На одном и
том же сценарии `cpus=4` (четыре больших ядра: 7, 6, 5, 4) дал 929 кадров вместо 671 на одном ядре, пики 35
diff --git a/userland/build.sh b/userland/build.sh
index 8b2bdc7..9ec7665 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -116,6 +116,10 @@ if [ -d $IOS/rootfs/usr/lib ]; then
$DYN -framework CoreFoundation -framework IOSurface -o obj/cow_test src/cow_test.c
$DYN -framework CoreFoundation -framework CoreGraphics -framework ImageIO -o obj/snap_test src/snap_test.c
$DYN -fobjc-arc -framework Foundation -framework SystemConfiguration -o obj/net_test src/net_test.m
+ # (with an entitlement for "battery_test open URL", if ldid is there: src/battery_test.c)
+ $DYN -framework CoreFoundation -framework IOKit -o obj/battery_test src/battery_test.c &&
+ { ${LDID:-ldid} -Ssrc/battery_test.entitlements obj/battery_test 2>/dev/null ||
+ echo "build.sh: no ldid: battery_test is unsigned, and SpringBoard will not open URLs for it"; }
# (the keychain answers only a program that has a keychain access group: signed with one, if ldid is there)
$DYN -framework CoreFoundation -framework Security -o obj/keychain_test src/keychain_test.c &&
{ ${LDID:-ldid} -Ssrc/keychain_test.entitlements obj/keychain_test 2>/dev/null ||
@@ -152,6 +156,7 @@ if [ -d $IOS/rootfs/usr/lib ]; then
[ -f obj/cow_test ] && cp obj/cow_test root/bin/
[ -f obj/snap_test ] && cp obj/snap_test root/bin/
[ -f obj/net_test ] && cp obj/net_test root/bin/
+ [ -f obj/battery_test ] && cp obj/battery_test root/bin/
[ -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/
diff --git a/userland/rc.jobs.battery b/userland/rc.jobs.battery
new file mode 100644
index 0000000..ae3c41a
--- /dev/null
+++ b/userland/rc.jobs.battery
@@ -0,0 +1,14 @@
+# Commands run by the launchd job com.redwood.demo (see com.redwood.demo.plist).
+# The battery (RC_JOBS=rc.jobs.battery, with adsp=1): what the kernel's power source says and what
+# powerd and IOPS have made of it (src/battery_test.c); then the places that show it, for screenshots:
+# the home screen's status bar, the Today view with its widgets (Batteries among them), Settings >
+# Battery (its Battery Percentage switched off and on again: the number beside the status bar's
+# battery goes and comes back) and Battery Health & Charging, and the lock screen ("56% Charged"
+# under the date).
+/redwood/bin/battery_test 1
+/redwood/bin/rwtouch wait 40 swipe 0.1 0.5 0.9 0.5 300 wait 6 swipe 0.5 0.8 0.5 0.35 300 wait 6 button home wait 5
+/redwood/bin/battery_test open prefs:root=BATTERY_USAGE
+/redwood/bin/rwtouch wait 7 tap 0.843 0.179 wait 5 tap 0.843 0.179 wait 5 drag 0.5 0.85 0.5 0.45 2000 400 wait 5
+/redwood/bin/battery_test open prefs:root=BATTERY_USAGE&path=BATTERY_HEALTH
+/redwood/bin/rwtouch wait 8 button home wait 4 button lock wait 3 button lock wait 6
+/redwood/bin/battery_test 8 15
diff --git a/userland/src/battery_test.c b/userland/src/battery_test.c
new file mode 100644
index 0000000..b4b3a3e
--- /dev/null
+++ b/userland/src/battery_test.c
@@ -0,0 +1,179 @@
+/*
+ * The battery as iOS sees it: the kernel's power source (the IOPMPowerSource that powerd reads,
+ * iokit/Kernel/RedwoodBattery.cpp) and what powerd has made of it (the power sources list that
+ * the status bar, the lock screen and Settings get through IOPS), side by side with the kernel's
+ * own numbers (kern.redwood.battery_*).
+ *
+ * battery_test once
+ * battery_test N S N times, S seconds apart
+ * battery_test open URL have SpringBoard open a URL, such as prefs:root=BATTERY_USAGE (Settings >
+ * Battery): for screenshots of a page that is hard to reach by touches alone
+ * (needs the entitlement in battery_test.entitlements, which build.sh signs in)
+ */
+#include <CoreFoundation/CoreFoundation.h>
+#include <IOKit/IOKitLib.h>
+#include <dlfcn.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/sysctl.h>
+#include <unistd.h>
+
+/* IOKit's IOPowerSources.h and IOPSKeys.h, which the SDK leaves out */
+extern CFTypeRef IOPSCopyPowerSourcesInfo(void);
+extern CFArrayRef IOPSCopyPowerSourcesList(CFTypeRef blob);
+extern CFDictionaryRef IOPSGetPowerSourceDescription(CFTypeRef blob, CFTypeRef ps);
+extern CFStringRef IOPSGetProvidingPowerSourceType(CFTypeRef snapshot);
+extern CFDictionaryRef IOPSCopyExternalPowerAdapterDetails(void);
+extern double IOPSGetTimeRemainingEstimate(void);
+extern int IOPSGetPercentRemaining(int *percent, bool *charging, bool *full);
+
+/* a value in short: a number, yes or no, a string, or a dictionary of them in braces */
+static void
+put(char *line, size_t size, CFTypeRef value)
+{
+ size_t used = strlen(line);
+ char text[256] = "";
+
+ if (value == NULL) {
+ snprintf(line + used, size - used, "-");
+ } else if (CFGetTypeID(value) == CFBooleanGetTypeID()) {
+ snprintf(line + used, size - used, "%s", CFBooleanGetValue(value) ? "yes" : "no");
+ } else if (CFGetTypeID(value) == CFNumberGetTypeID()) {
+ long long n = 0;
+
+ CFNumberGetValue(value, kCFNumberLongLongType, &n);
+ snprintf(line + used, size - used, "%lld", n);
+ } else if (CFGetTypeID(value) == CFStringGetTypeID()) {
+ CFStringGetCString(value, text, sizeof(text), kCFStringEncodingUTF8);
+ snprintf(line + used, size - used, "\"%s\"", text);
+ } else if (CFGetTypeID(value) == CFDictionaryGetTypeID()) {
+ CFIndex count = CFDictionaryGetCount(value);
+ const void **keys = calloc(count + 1, sizeof(void *)), **values = calloc(count + 1, sizeof(void *));
+
+ CFDictionaryGetKeysAndValues(value, keys, values);
+ snprintf(line + used, size - used, "{");
+ for (CFIndex i = 0; i < count; i++) {
+ used = strlen(line);
+ text[0] = 0;
+ if (CFGetTypeID(keys[i]) == CFStringGetTypeID()) {
+ CFStringGetCString(keys[i], text, sizeof(text), kCFStringEncodingUTF8);
+ }
+ snprintf(line + used, size - used, "%s%s=", i ? ", " : "", text);
+ put(line, size, values[i]);
+ }
+ used = strlen(line);
+ snprintf(line + used, size - used, "}");
+ free(keys);
+ free(values);
+ } else {
+ snprintf(line + used, size - used, "(something else)");
+ }
+}
+
+static void
+show(const char *what, CFTypeRef object)
+{
+ static char line[16384];
+
+ if (object == NULL) {
+ printf("%s: none\n", what);
+ return;
+ }
+ line[0] = 0;
+ put(line, sizeof(line), object);
+ printf("%s: %s\n", what, line);
+}
+
+static int
+kernel(const char *name)
+{
+ int value = -1;
+ size_t size = sizeof(value);
+
+ sysctlbyname(name, &value, &size, NULL, 0);
+ return value;
+}
+
+static void
+once(void)
+{
+ io_service_t service = IOServiceGetMatchingService(0, IOServiceMatching("IOPMPowerSource"));
+ CFTypeRef blob = IOPSCopyPowerSourcesInfo();
+ CFArrayRef list = blob ? IOPSCopyPowerSourcesList(blob) : NULL;
+ CFDictionaryRef adapter = IOPSCopyExternalPowerAdapterDetails();
+ int percent = -1;
+ bool charging = false, full = false;
+ int got = IOPSGetPercentRemaining(&percent, &charging, &full);
+
+ printf("battery_test: the kernel says %d%%, %d mV, %d mA, %d C, battery %d, charger %d, charging %d, from the DSP %d\n",
+ kernel("kern.redwood.battery_soc"), kernel("kern.redwood.battery_voltage_mv"), kernel("kern.redwood.battery_current_ma"),
+ kernel("kern.redwood.battery_temperature_c"), kernel("kern.redwood.battery_present"),
+ kernel("kern.redwood.battery_charger_present"), kernel("kern.redwood.battery_charging"),
+ kernel("kern.redwood.battery_from_dsp"));
+ if (service != 0) {
+ CFMutableDictionaryRef properties = NULL;
+ io_name_t name = "";
+
+ IORegistryEntryGetName(service, name);
+ if (IORegistryEntryCreateCFProperties(service, &properties, kCFAllocatorDefault, 0) == KERN_SUCCESS) {
+ printf("battery_test: the power source in the kernel is %s\n", name);
+ show("battery_test: its properties", properties);
+ CFRelease(properties);
+ }
+ IOObjectRelease(service);
+ } else {
+ printf("battery_test: there is no IOPMPowerSource in the kernel\n");
+ }
+ printf("battery_test: IOPSGetPercentRemaining: %d (%#x), %d%%, charging %d, full %d; time remaining %.0f s\n", got, got,
+ percent, charging, full, IOPSGetTimeRemainingEstimate());
+ if (blob != NULL) {
+ show("battery_test: powered by", IOPSGetProvidingPowerSourceType(blob));
+ }
+ for (CFIndex i = 0; list != NULL && i < CFArrayGetCount(list); i++) {
+ show("battery_test: power source", IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(list, i)));
+ }
+ if (list == NULL || CFArrayGetCount(list) == 0) {
+ printf("battery_test: powerd lists no power source\n");
+ }
+ show("battery_test: the power adapter", adapter);
+ if (adapter != NULL) CFRelease(adapter);
+ if (list != NULL) CFRelease(list);
+ if (blob != NULL) CFRelease(blob);
+ fflush(stdout);
+}
+
+/* SpringBoardServices' way of opening a URL, as a program with the entitlement may */
+static int
+open_url(const char *text)
+{
+ void *sbs = dlopen("/System/Library/PrivateFrameworks/SpringBoardServices.framework/SpringBoardServices", RTLD_NOW);
+ int (*open)(CFURLRef, Boolean) = sbs ? (int (*)(CFURLRef, Boolean))dlsym(sbs, "SBSOpenSensitiveURLAndUnlock") : NULL;
+ CFURLRef url = CFURLCreateWithBytes(NULL, (const UInt8 *)text, (CFIndex)strlen(text), kCFStringEncodingUTF8, NULL);
+ int result;
+
+ if (open == NULL || url == NULL) {
+ printf("battery_test: cannot open %s: %s\n", text, open == NULL ? "no SBSOpenSensitiveURLAndUnlock" : "not a URL");
+ return 1;
+ }
+ result = open(url, true);
+ printf("battery_test: SpringBoard was asked to open %s: %s\n", text, result ? "it does" : "it REFUSES");
+ CFRelease(url);
+ return result ? 0 : 1;
+}
+
+int
+main(int argc, char **argv)
+{
+ if (argc > 2 && strcmp(argv[1], "open") == 0) {
+ return open_url(argv[2]);
+ }
+ int times = argc > 1 ? atoi(argv[1]) : 1;
+ int seconds = argc > 2 ? atoi(argv[2]) : 10;
+
+ for (int i = 0; i < times; i++) {
+ if (i > 0) sleep(seconds);
+ once();
+ }
+ return 0;
+}
diff --git a/userland/src/battery_test.entitlements b/userland/src/battery_test.entitlements
new file mode 100644
index 0000000..10ca799
--- /dev/null
+++ b/userland/src/battery_test.entitlements
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.springboard.opensensitiveurl</key>
+ <true/>
+</dict>
+</plist>
diff --git a/userland/src/inject_sb.c b/userland/src/inject_sb.c
index 657c4e9..48d8866 100644
--- a/userland/src/inject_sb.c
+++ b/userland/src/inject_sb.c
@@ -209,13 +209,16 @@ snapshot_output_format(__unused id self, __unused SEL selector, id snapshot)
/*
* iOS reads battery level through UIDevice.batteryLevel and UIDevice.batteryState; SpringBoard's
- * status bar reads it the same way via SBBatteryController. There is no IOPMPowerSource kernel
- * driver yet (that is the right long-term fix), so we hook the UIDevice accessors to return what
- * xnuloader reads through Qualcomm's UEFI charger protocols and XNU publishes as
- * kern.redwood.battery_soc (0..100) and kern.redwood.battery_charging.
+ * status bar reads it the same way via SBBatteryController. Where the battery has no power source
+ * of its own in the kernel (battery=1, the loader's way through Qualcomm's UEFI charger protocols),
+ * we hook the UIDevice accessors to return what XNU publishes as kern.redwood.battery_soc (0..100)
+ * and kern.redwood.battery_charging.
* When the sysctl is missing (battery=1 not in boot-args, or the driver never started) we hand
* back the value the real implementation computed; the status bar then shows whatever iOS last
* knew, which is better than crashing.
+ * With adsp=1 the battery is a power source (the service RedwoodBattery, an IOPMPowerSource:
+ * iokit/Kernel/RedwoodBattery.cpp), which powerd reads like an iPhone's own, and from it iOS knows
+ * everything by itself; once that service is there, the hooks hand everything to iOS's own code.
*/
static float (*original_battery_level)(id self, SEL sel);
static long (*original_battery_state)(id self, SEL sel);
@@ -236,13 +239,27 @@ sysctl_int(const char *name)
return value;
}
+/* Is the battery a power source that iOS reads by itself (see above)? Once it is, it stays one. */
+static bool
+battery_power_source(void)
+{
+ static bool found;
+ io_service_t service;
+
+ if (!found && (service = IOServiceGetMatchingService(0, IOServiceMatching("RedwoodBattery"))) != 0) {
+ IOObjectRelease(service);
+ found = true;
+ }
+ return found;
+}
+
/* UIDevice.batteryLevel: 0.0..1.0; -1.0 if monitoring not enabled */
static float
battery_level(id self, SEL sel)
{
int soc = sysctl_int("kern.redwood.battery_soc");
- if (soc < 0 || soc > 100) {
+ if (soc < 0 || soc > 100 || battery_power_source()) {
return original_battery_level ? original_battery_level(self, sel) : -1.0f;
}
return (float)soc / 100.0f;
@@ -257,7 +274,7 @@ battery_state(id self, SEL sel)
int plugged = sysctl_int("kern.redwood.battery_charger_present");
int soc = sysctl_int("kern.redwood.battery_soc");
- if (charging == -1 || present == -1 || plugged == -1 || soc < 0 || soc > 100) {
+ if (charging == -1 || present == -1 || plugged == -1 || soc < 0 || soc > 100 || battery_power_source()) {
return original_battery_state ? original_battery_state(self, sel) : 0;
}
if (!present) return 0;
@@ -265,13 +282,17 @@ battery_state(id self, SEL sel)
return charging ? 2 : 1;
}
-/* UIKitCore's status-bar view has its own presentation policy, separate from UIDevice. */
+/*
+ * UIKitCore's status-bar view has its own presentation policy, separate from UIDevice. With the power
+ * source it is iOS's own again: the switch Battery Percentage in Settings > Battery, which the image
+ * turns on (SBShowBatteryPercentage in userland/var/mobile/Library/Preferences/com.apple.springboard.plist).
+ */
static BOOL
battery_view_shows_percentage(id self, SEL sel)
{
int soc = sysctl_int("kern.redwood.battery_soc");
- if (soc >= 0 && soc <= 100) return YES;
+ if (soc >= 0 && soc <= 100 && !battery_power_source()) return YES;
return original_battery_view_shows_percentage ? original_battery_view_shows_percentage(self, sel) : NO;
}
@@ -280,7 +301,7 @@ battery_view_set_shows_percentage(id self, SEL sel, BOOL shows)
{
int soc = sysctl_int("kern.redwood.battery_soc");
- original_battery_view_set_shows_percentage(self, sel, (soc >= 0 && soc <= 100) ? YES : shows);
+ original_battery_view_set_shows_percentage(self, sel, (soc >= 0 && soc <= 100 && !battery_power_source()) ? YES : shows);
}
static BOOL
@@ -290,7 +311,7 @@ battery_view_should_show_bolt(id self, SEL sel)
int present = sysctl_int("kern.redwood.battery_present");
int plugged = sysctl_int("kern.redwood.battery_charger_present");
- if (charging != -1 && present != -1 && plugged != -1) return charging && present && plugged;
+ if (charging != -1 && present != -1 && plugged != -1 && !battery_power_source()) return charging && present && plugged;
return original_battery_view_should_show_bolt ? original_battery_view_should_show_bolt(self, sel) : NO;
}
@@ -306,7 +327,7 @@ battery_view_charge_percent(id self, SEL sel)
{
int soc = sysctl_int("kern.redwood.battery_soc");
- if (soc >= 0 && soc <= 100) return (double)soc / 100.0;
+ if (soc >= 0 && soc <= 100 && !battery_power_source()) return (double)soc / 100.0;
return original_battery_view_charge_percent ? original_battery_view_charge_percent(self, sel) : 0.0;
}
@@ -315,7 +336,7 @@ battery_view_set_charge_percent(id self, SEL sel, double p)
{
int soc = sysctl_int("kern.redwood.battery_soc");
- original_battery_view_set_charge_percent(self, sel, (soc >= 0 && soc <= 100) ? (double)soc / 100.0 : p);
+ original_battery_view_set_charge_percent(self, sel, (soc >= 0 && soc <= 100 && !battery_power_source()) ? (double)soc / 100.0 : p);
}
/* The big charging ring on the lock screen (CoverSheet) reads its fill level the same way. */
@@ -324,7 +345,7 @@ ring_charging_level(id self, SEL sel)
{
int soc = sysctl_int("kern.redwood.battery_soc");
- if (soc >= 0 && soc <= 100) return (double)soc / 100.0;
+ if (soc >= 0 && soc <= 100 && !battery_power_source()) return (double)soc / 100.0;
return original_ring_charging_level ? original_ring_charging_level(self, sel) : 0.0;
}
@@ -338,7 +359,7 @@ battery_post_notifications(void)
id center = notification_center ? ((id (*)(Class, SEL))objc_msgSend)(notification_center,
sel_registerName("defaultCenter")) : nil;
- if (center != nil) {
+ if (center != nil && !battery_power_source()) {
SEL post = sel_registerName("postNotificationName:object:");
((void (*)(id, SEL, id, id))objc_msgSend)(center, post,
(id)CFSTR("UIDeviceBatteryLevelDidChangeNotification"), device);
diff --git a/userland/var/mobile/Library/Preferences/com.apple.springboard.plist b/userland/var/mobile/Library/Preferences/com.apple.springboard.plist
index 961b5d9..dc39f07 100644
--- a/userland/var/mobile/Library/Preferences/com.apple.springboard.plist
+++ b/userland/var/mobile/Library/Preferences/com.apple.springboard.plist
@@ -13,5 +13,9 @@
the application switcher. -->
<key>BKNoWatchdogs</key>
<true/>
+ <!-- the battery's percentage beside its icon in the status bar (Settings > Battery > Battery
+ Percentage, which an iPhone X has off at first) -->
+ <key>SBShowBatteryPercentage</key>
+ <true/>
</dict>
</plist>
diff --git a/xnu/files/bsd/dev/redwood_adsp.c b/xnu/files/bsd/dev/redwood_adsp.c
index d6181e0..e0c54e4 100644
--- a/xnu/files/bsd/dev/redwood_adsp.c
+++ b/xnu/files/bsd/dev/redwood_adsp.c
@@ -81,6 +81,7 @@
#include <kern/locks.h>
#include <kern/thread.h>
#include <libkern/libkern.h>
+#include <os/atomic_private.h>
#include <mach/mach_types.h>
#include <mach/vm_param.h>
#include <vm/memory_types.h>
@@ -94,6 +95,7 @@
#include <sys/vnode_internal.h>
#include <vm/vm_kern.h>
#include <sys/redwood_audio.h>
+#include <sys/redwood_input.h>
extern vm_offset_t ml_io_map(vm_offset_t phys_addr, vm_size_t size);
extern vm_offset_t ml_io_map_unmappable(vm_offset_t phys_addr, vm_size_t size, unsigned int flags);
@@ -1833,7 +1835,7 @@ struct glink_packet {
* carries APR, the audio services' own protocol (below; Android's apr_tal_rpmsg.c asks for no
* particular intents: what the DSP sends there is a few hundred bytes, up to a few kilobytes).
*/
-enum { CHANNEL_QRTR, CHANNEL_APR, CHANNELS };
+enum { CHANNEL_QRTR, CHANNEL_APR, CHANNEL_PMIC, CHANNELS };
struct glink_channel {
const char *name;
@@ -1869,6 +1871,8 @@ static struct {
.channel = {
[CHANNEL_QRTR] = { .name = "IPCRTR", .ours = 1, .intents = { { 0x800, 5 }, { 0x2000, 3 }, { 0x4400, 2 } } },
[CHANNEL_APR] = { .name = "apr_audio_svc", .ours = 2, .intents = { { 0x200, 8 }, { 0x1000, 4 }, { 0x2000, 2 } } },
+ /* the battery manager's (battmgr below): answers of a few dozen bytes, a name of 128 */
+ [CHANNEL_PMIC] = { .name = "PMIC_RTR_ADSP_APPS", .ours = 3, .intents = { { 0x200, 6 }, { 0x1000, 2 }, { 0, 0 } } },
},
};
@@ -2628,6 +2632,236 @@ apr_ask(uint8_t service, uint32_t opcode, const void *payload, uint32_t length,
return redwood_adsp_apr(service, 0, 0, opcode, payload, length, ms, NULL);
}
+/* ---- the battery manager, on the channel PMIC_RTR_ADSP_APPS ------------------------------------------ */
+
+/*
+ * On this SoC the audio DSP also runs the battery's and the charger's management -- the fuel gauge,
+ * the charging -- and the operating system only asks it how things are: Android's
+ * qti_battery_charger.c, Linux's qcom_battmgr.c over pmic_glink.c, on the channel PMIC_RTR_ADSP_APPS
+ * that the DSP opens. A message is a header (owner 32778, the battery manager; type 1, request and
+ * answer, or 2, a notice; an opcode) and its words; a property is asked for with opcode 0x30 (the
+ * battery's) or 0x32 (the USB port's), the battery's number (0), the property's number and a word
+ * that a get does not use, and is answered with the property's number, its value and a result (0:
+ * good). Only gets are sent from here: nothing is set, no limit, no current, no notice asked for.
+ * With adsp=1 (battmgr=0: not) it is asked every BATTMGR_SECONDS while the DSP runs, and what it says
+ * goes to bsd/dev/redwood_battery.c (redwood_battery_report()), and from there to the power source
+ * that iOS reads (iokit/Kernel/RedwoodBattery.cpp). battmgr=2: every property once, for the log.
+ * Units: capacity in hundredths of a percent, voltage in uV, current in uA (more than 0 while the
+ * battery takes charge), the temperature in hundredths of a degree, charges in uAh.
+ * The properties' numbers are this phone's firmware's, read with battmgr=2 and checked against what
+ * Android shows at the same moment (dumpsys battery, /sys/class/power_supply/battery): up to 9 they
+ * are those of Linux's qcom_battmgr.c (sm8350), from there on one more property comes before the
+ * temperature, so the temperature is 13, not 12, and the charge counter, the cycles, the designed and
+ * the learnt full charge are 15 to 18.
+ */
+#define BATTMGR_OWNER 32778
+#define BATTMGR_REQUEST 1
+#define BATTMGR_NOTICE 2
+#define BATTMGR_BATTERY_GET 0x30
+#define BATTMGR_USB_GET 0x32
+#define BATT_STATUS 0 /* Linux's POWER_SUPPLY_STATUS_*: 1 charging, 2 discharging, 3 not charging, 4 full */
+#define BATT_HEALTH 1
+#define BATT_PRESENT 2
+#define BATT_CAPACITY 4
+#define BATT_VOLT_NOW 7
+#define BATT_CURR_NOW 9
+#define BATT_TEMP 13 /* hundredths of a degree: 3900 when Android says 39.0 */
+#define BATT_CHG_COUNTER 15 /* the charge in the battery now, uAh */
+#define BATT_CYCLE_COUNT 16
+#define BATT_CHG_FULL_DESIGN 17 /* 5000000 uAh */
+#define BATT_CHG_FULL 18 /* the full charge as the fuel gauge has learnt it, uAh */
+#define USB_VOLT_NOW 1 /* uV */
+#define USB_CURR_NOW 3 /* uA, what the port gives */
+#define USB_TYPE 6 /* Linux's POWER_SUPPLY_USB_TYPE_*: 1 here, a computer's port */
+#define USB_ONLINE 0
+#define BATTMGR_SECONDS 10
+
+struct battmgr_message {
+ uint32_t owner, type, opcode;
+ uint32_t words[3]; /* asked: battery, property, value; answered: property, value, result */
+};
+
+static struct {
+ volatile uint32_t answers, notices;
+ uint32_t opcode, property, value, result, length;
+ bool wanted;
+ volatile bool runs;
+} battmgr;
+
+static void
+battmgr_input(const uint8_t *data, uint32_t length)
+{
+ struct battmgr_message m;
+
+ bzero(&m, sizeof(m));
+ memcpy(&m, data, length < sizeof(m) ? length : sizeof(m));
+ if (m.owner != BATTMGR_OWNER || length < 12) {
+ printf("adsp: battmgr: < %u bytes of owner %u, type %u, opcode %#x: not the battery manager's\n", length, m.owner,
+ m.type, m.opcode);
+ return;
+ }
+ if (m.type == BATTMGR_NOTICE) {
+ if (battmgr.notices++ < 8) {
+ tell("adsp: battmgr: < a notice, opcode %#x, %u bytes (%#x %#x %#x)\n", m.opcode, length, m.words[0], m.words[1],
+ m.words[2]);
+ }
+ return;
+ }
+ battmgr.opcode = m.opcode;
+ battmgr.property = m.words[0];
+ battmgr.value = m.words[1];
+ battmgr.result = m.words[2];
+ battmgr.length = length;
+ os_atomic_inc(&battmgr.answers, release);
+}
+
+/* One property asked for and its answer waited for (a second at most); one thread asks at a time (battmgr_thread). */
+static bool
+battmgr_get(uint32_t opcode, uint32_t property, uint32_t *value)
+{
+ struct battmgr_message q = { BATTMGR_OWNER, BATTMGR_REQUEST, opcode, { 0, property, 0 } };
+ uint32_t before = os_atomic_load(&battmgr.answers, acquire);
+
+ if (glink_send(&glink.channel[CHANNEL_PMIC], &q, sizeof(q)) != 0) {
+ return false;
+ }
+ for (unsigned ms = 0; ms < 1000; ms++) {
+ if (os_atomic_load(&battmgr.answers, acquire) != before) {
+ if (battmgr.opcode != opcode || battmgr.property != property || battmgr.length < sizeof(struct battmgr_message)) {
+ before = battmgr.answers; /* (somebody else's answer: wait on) */
+ continue;
+ }
+ if (battmgr.result != 0) {
+ return false;
+ }
+ *value = battmgr.value;
+ return true;
+ }
+ sleep_ms(1);
+ }
+ return false;
+}
+
+static void
+battmgr_thread(__unused void *parameter, __unused wait_result_t result)
+{
+ battmgr.runs = true;
+ for (unsigned ms = 0; ms < 15000 && battmgr.wanted && !glink.channel[CHANNEL_PMIC].open; ms += 10) {
+ sleep_ms(10);
+ }
+ if (!glink.channel[CHANNEL_PMIC].open) {
+ tell("adsp: battmgr: the DSP has not opened PMIC_RTR_ADSP_APPS: nothing is asked\n");
+ battmgr.runs = false;
+ thread_terminate(current_thread());
+ }
+ {
+ /* boot-arg battmgr=2: every property once, for the log (which number is which on this phone's firmware) */
+ uint32_t mode = 1;
+
+ PE_parse_boot_argn("battmgr", &mode, sizeof(mode));
+ for (uint32_t p = 0; mode == 2 && p < 32; p++) {
+ uint32_t v = 0;
+ bool ok = battmgr_get(BATTMGR_BATTERY_GET, p, &v);
+
+ tell("adsp: battmgr: battery property %u: %s %u (%d)\n", p, ok ? "" : "NO ANSWER", v, (int)v);
+ }
+ for (uint32_t p = 0; mode == 2 && p < 12; p++) {
+ uint32_t v = 0;
+ bool ok = battmgr_get(BATTMGR_USB_GET, p, &v);
+
+ tell("adsp: battmgr: USB property %u: %s %u (%d)\n", p, ok ? "" : "NO ANSWER", v, (int)v);
+ }
+ }
+ for (unsigned round = 0; battmgr.wanted && glink.up && glink.channel[CHANNEL_PMIC].open; round++) {
+ struct redwood_battery_state b = { .size = sizeof(b) };
+ uint32_t capacity = 0, status = 0, present = 0, volt = 0, curr = 0, temp = 0, usb = 0;
+ uint32_t usb_type = 0, usb_volt = 0, usb_curr = 0, charge = 0;
+ static uint32_t full, design, cycles;
+ bool good = battmgr_get(BATTMGR_BATTERY_GET, BATT_CAPACITY, &capacity) &&
+ battmgr_get(BATTMGR_BATTERY_GET, BATT_STATUS, &status) &&
+ battmgr_get(BATTMGR_BATTERY_GET, BATT_PRESENT, &present) &&
+ battmgr_get(BATTMGR_BATTERY_GET, BATT_VOLT_NOW, &volt) &&
+ battmgr_get(BATTMGR_BATTERY_GET, BATT_CURR_NOW, &curr) &&
+ battmgr_get(BATTMGR_BATTERY_GET, BATT_TEMP, &temp) &&
+ battmgr_get(BATTMGR_USB_GET, USB_ONLINE, &usb);
+
+ if (good) {
+ /* (what may be missing without harm, and the capacities and the cycles only now and then: they hardly change) */
+ (void)battmgr_get(BATTMGR_BATTERY_GET, BATT_CHG_COUNTER, &charge);
+ if (usb) {
+ (void)battmgr_get(BATTMGR_USB_GET, USB_TYPE, &usb_type);
+ (void)battmgr_get(BATTMGR_USB_GET, USB_VOLT_NOW, &usb_volt);
+ (void)battmgr_get(BATTMGR_USB_GET, USB_CURR_NOW, &usb_curr);
+ }
+ if (round % 30 == 0 || full == 0) {
+ (void)battmgr_get(BATTMGR_BATTERY_GET, BATT_CHG_FULL, &full);
+ (void)battmgr_get(BATTMGR_BATTERY_GET, BATT_CHG_FULL_DESIGN, &design);
+ (void)battmgr_get(BATTMGR_BATTERY_GET, BATT_CYCLE_COUNT, &cycles);
+ }
+ b.percent_hundredths = (int32_t)capacity;
+ b.voltage_uv = (int32_t)volt;
+ b.current_ua = (int32_t)curr;
+ b.temperature_hundredths = (int32_t)temp;
+ b.present = present != 0;
+ b.external = usb != 0;
+ b.status = (int32_t)status;
+ b.charge_uah = (int32_t)charge;
+ b.full_uah = (int32_t)full;
+ b.design_uah = (int32_t)design;
+ b.cycles = (int32_t)cycles;
+ b.usb_type = (int32_t)usb_type;
+ b.usb_voltage_uv = (int32_t)usb_volt;
+ b.usb_current_ua = (int32_t)usb_curr;
+ redwood_battery_report(&b);
+ }
+ if (round < 3 || round % 6 == 0 || !good) {
+ tell("adsp: battmgr: %s capacity %u (hundredths of a percent), status %u, present %u, %d uV, %d uA, temperature %d "
+ "(hundredths of a degree), charge %u uAh, USB online %u (type %u, %u uV, %u uA)\n",
+ good ? "the DSP says:" : "NO ANSWER to all of", capacity, status, present, (int)volt, (int)curr, (int)temp,
+ charge, usb, usb_type, usb_volt, usb_curr);
+ if (round % 30 == 0 && good) {
+ tell("adsp: battmgr: full charge %u uAh, as designed %u uAh, %u cycles\n", full, design, cycles);
+ }
+ }
+ for (unsigned ms = 0; ms < BATTMGR_SECONDS * 1000 && battmgr.wanted && glink.up; ms += 50) {
+ sleep_ms(50);
+ }
+ }
+ battmgr.runs = false;
+ thread_terminate(current_thread());
+}
+
+static void
+battmgr_start(void)
+{
+ thread_t thread;
+
+ uint32_t wanted = 1; /* (on with adsp=1 unless battmgr=0) */
+
+ PE_parse_boot_argn("battmgr", &wanted, sizeof(wanted));
+ if (wanted == 0 || battmgr.runs) {
+ return;
+ }
+ if (option("battery")) {
+ /* (the loader's way, through Qualcomm's UEFI charger drivers: one way to the battery at a time) */
+ tell("adsp: battmgr: not with battery=1: the battery is asked about the loader's way\n");
+ return;
+ }
+ battmgr.wanted = true;
+ if (kernel_thread_start(battmgr_thread, NULL, &thread) == KERN_SUCCESS) {
+ thread_deallocate(thread);
+ }
+}
+
+static void
+battmgr_stop(void)
+{
+ battmgr.wanted = false;
+ for (unsigned ms = 0; ms < 2000 && battmgr.runs; ms++) {
+ sleep_ms(1);
+ }
+}
+
/* ---- the link's thread ----------------------------------------------------------------------------- */
static volatile bool link_wanted, link_runs;
@@ -2674,6 +2908,8 @@ link_thread(__unused void *parameter, __unused wait_result_t result)
}
if (from == CHANNEL_QRTR) {
qrtr_input(packet->data, packet->length);
+ } else if (from == CHANNEL_PMIC) {
+ battmgr_input(packet->data, packet->length);
} else {
apr_input(packet->data, packet->length);
}
@@ -2902,6 +3138,7 @@ steps_over(uint32_t done)
void
redwood_adsp_stop(void)
{
+ battmgr_stop();
redwood_sound_dsp_down(); /* the amplifiers, the stream and the port first, while the DSP still listens */
lck_mtx_lock(&dsp_lock);
if (dsp_started) {
@@ -2971,6 +3208,7 @@ whole_thread(__unused void *parameter, __unused wait_result_t result)
tell("adsp: THE AUDIO DSP IS UP AND LINKED, its audio services up (APR), %llu ms after the kernel began on it (the "
"root's waited for included): node %u, %u services; it stays on\n", (now_us() - began) / 1000, qrtr_peer, services);
redwood_sound_dsp_up(); /* (boot-arg sound=N: the speakers' path, redwood_sound.c) */
+ battmgr_start(); /* (how the battery is, from the DSP; battmgr=0: not asked) */
} else {
tell("adsp: THE AUDIO DSP DID NOT COME UP: step %u failed (%s); see the kernel's own log for the steps\n", step + 1,
last_write);
diff --git a/xnu/files/bsd/dev/redwood_battery.c b/xnu/files/bsd/dev/redwood_battery.c
index 0171709..7e7509e 100644
--- a/xnu/files/bsd/dev/redwood_battery.c
+++ b/xnu/files/bsd/dev/redwood_battery.c
@@ -103,6 +103,52 @@ battery_poll(void)
battery_updates++;
}
+/*
+ * What the audio DSP's battery manager says (bsd/dev/redwood_adsp.c, with adsp=1 unless battmgr=0):
+ * the values that Android shows, from where Android takes them. They are kept here for the sysctls
+ * and passed on to the power source that iOS reads (iokit/Kernel/RedwoodBattery.cpp).
+ */
+static int battery_full_uah, battery_design_uah, battery_cycles, battery_source_dsp;
+
+SYSCTL_INT(_kern_redwood, OID_AUTO, battery_full_uah, CTLFLAG_RD | CTLFLAG_LOCKED,
+ &battery_full_uah, 0, "the battery's full charge as the fuel gauge has learnt it, in uAh (0 if unknown)");
+SYSCTL_INT(_kern_redwood, OID_AUTO, battery_design_uah, CTLFLAG_RD | CTLFLAG_LOCKED,
+ &battery_design_uah, 0, "the battery's charge as designed, in uAh (0 if unknown)");
+SYSCTL_INT(_kern_redwood, OID_AUTO, battery_cycles, CTLFLAG_RD | CTLFLAG_LOCKED,
+ &battery_cycles, 0, "the battery's charge cycles (0 if unknown)");
+SYSCTL_INT(_kern_redwood, OID_AUTO, battery_from_dsp, CTLFLAG_RD | CTLFLAG_LOCKED,
+ &battery_source_dsp, 0, "1 when the values come from the audio DSP's battery manager");
+
+extern void RedwoodBatteryReport(const void *state, unsigned size); /* iokit/Kernel/RedwoodBattery.cpp */
+
+void
+redwood_battery_report(const struct redwood_battery_state *b)
+{
+ int percent = (b->percent_hundredths + 50) / 100;
+
+ battery_soc_percent = percent < 0 ? 0 : percent > 100 ? 100 : percent;
+ battery_voltage_mv = b->voltage_uv / 1000;
+ battery_current_ma = b->current_ua / 1000;
+ battery_temperature_c = (b->temperature_hundredths + 50) / 100;
+ battery_present = b->present != 0;
+ battery_charger_present = b->external != 0;
+ battery_charging = b->status == 1; /* POWER_SUPPLY_STATUS_CHARGING */
+ battery_soc_estimated = 0;
+ battery_charger_action = b->status;
+ if (b->full_uah > 0) {
+ battery_full_uah = b->full_uah;
+ }
+ if (b->design_uah > 0) {
+ battery_design_uah = b->design_uah;
+ }
+ if (b->cycles > 0) {
+ battery_cycles = b->cycles;
+ }
+ battery_source_dsp = 1;
+ battery_updates++;
+ RedwoodBatteryReport(b, sizeof(*b));
+}
+
static void
battery_thread(__unused void *parameter, __unused wait_result_t result)
{
diff --git a/xnu/files/bsd/sys/redwood_input.h b/xnu/files/bsd/sys/redwood_input.h
index e6fb113..8fda7bf 100644
--- a/xnu/files/bsd/sys/redwood_input.h
+++ b/xnu/files/bsd/sys/redwood_input.h
@@ -43,6 +43,26 @@ 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 */
+/*
+ * 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
+ * passes it on to iokit/Kernel/RedwoodBattery.cpp, the power source that iOS reads. The structure
+ * is repeated there (this header is not seen from iokit/), and `size` tells whether the two agree.
+ */
+struct redwood_battery_state {
+ uint32_t size; /* sizeof(struct redwood_battery_state) */
+ int32_t percent_hundredths; /* the charge, 0..10000 */
+ int32_t voltage_uv;
+ int32_t current_ua; /* more than 0 while the battery takes charge */
+ int32_t temperature_hundredths; /* of a degree Celsius */
+ int32_t present; /* 1 if there is a battery */
+ int32_t external; /* 1 if a charger or a computer is on the USB port */
+ int32_t status; /* Linux's POWER_SUPPLY_STATUS_*: 1 charging, 2 discharging, 3 not charging, 4 full */
+ int32_t charge_uah, full_uah, design_uah, cycles; /* 0 when not known (yet) */
+ int32_t usb_type; /* Linux's POWER_SUPPLY_USB_TYPE_*: 1 a computer's port, 2 a charger, ... */
+ int32_t usb_voltage_uv, usb_current_ua; /* what the port gives */
+};
+void redwood_battery_report(const struct redwood_battery_state *state);
void redwood_net_init(void); /* en0, if there is something to carry its frames: sys/redwood_net.h */
void redwood_cpufreq_init(void); /* boot-arg cpufreq=1: the phone's processor at full speed */
void redwood_adreno_init(void); /* boot-arg adreno=N: the first N steps of waking the phone's GPU */
diff --git a/xnu/files/iokit/Kernel/RedwoodBattery.cpp b/xnu/files/iokit/Kernel/RedwoodBattery.cpp
new file mode 100644
index 0000000..87223c2
--- /dev/null
+++ b/xnu/files/iokit/Kernel/RedwoodBattery.cpp
@@ -0,0 +1,230 @@
+/*
+ * RedwoodBattery: the phone's battery as iOS looks for it, an IOPMPowerSource.
+ *
+ * powerd finds every service of the class IOPMPowerSource (it calls the first "InternalBattery-0"),
+ * listens for its kIOPMMessageBatteryStatusHasChanged and then reads its properties: whether a
+ * battery is installed, CurrentCapacity and MaxCapacity (without both it gives up on the battery),
+ * whether a charger is connected and charging, voltage, current, cycles, the charger's details.
+ * From them it makes the power sources list (IOPSCopyPowerSourcesInfo) and posts its notifications,
+ * and everything else follows from that: the status bar's battery, the lock screen's "Charging",
+ * the Batteries widget, Settings > Battery.
+ *
+ * What the values are comes from the audio DSP's battery manager (bsd/dev/redwood_adsp.c,
+ * with adsp=1, unless battmgr=0), by way of bsd/dev/redwood_battery.c, which calls
+ * RedwoodBatteryReport() with every reading; the first one makes the service. Nothing here asks
+ * the charger anything or tells it anything.
+ *
+ * As on Apple's newer batteries, CurrentCapacity is the percentage that the fuel gauge shows (and
+ * MaxCapacity 100); the charges in mAh are AppleRawCurrentCapacity, AppleRawMaxCapacity (what the
+ * gauge has learnt a full charge to be), NominalChargeCapacity and DesignCapacity.
+ */
+
+#include <IOKit/IOLib.h>
+#include <IOKit/IOPlatformExpert.h>
+#include <IOKit/pwr_mgt/IOPM.h>
+#include <IOKit/pwr_mgt/IOPMPowerSource.h>
+#include <libkern/c++/OSBoolean.h>
+#include <libkern/c++/OSDictionary.h>
+#include <libkern/c++/OSNumber.h>
+#include <libkern/c++/OSSymbol.h>
+
+/* The same as struct redwood_battery_state in bsd/sys/redwood_input.h, which is not seen from here. */
+struct redwood_battery_state {
+ uint32_t size;
+ int32_t percent_hundredths;
+ int32_t voltage_uv;
+ int32_t current_ua; /* more than 0 while the battery takes charge */
+ int32_t temperature_hundredths;
+ int32_t present, external, status;
+ int32_t charge_uah, full_uah, design_uah, cycles;
+ int32_t usb_type;
+ int32_t usb_voltage_uv, usb_current_ua;
+};
+
+extern "C" void RedwoodBatteryReport(const void * state, unsigned size);
+
+class RedwoodBattery : public IOPMPowerSource
+{
+ OSDeclareDefaultStructors(RedwoodBattery);
+
+public:
+ void report(const struct redwood_battery_state * b);
+
+private:
+ void number(const char * key, long long value);
+ void flag(const char * key, bool value);
+ void object(const char * key, OSObject * value);
+};
+
+OSDefineMetaClassAndStructors(RedwoodBattery, IOPMPowerSource);
+
+static RedwoodBattery * battery;
+
+void
+RedwoodBattery::number(const char * key, long long value)
+{
+ const OSSymbol * symbol = OSSymbol::withCString(key);
+ OSNumber * n = OSNumber::withNumber((unsigned long long) value, 32);
+
+ if (symbol != NULL && n != NULL) {
+ setPSProperty(symbol, n);
+ }
+ OSSafeReleaseNULL(n);
+ OSSafeReleaseNULL(symbol);
+}
+
+void
+RedwoodBattery::flag(const char * key, bool value)
+{
+ const OSSymbol * symbol = OSSymbol::withCString(key);
+
+ if (symbol != NULL) {
+ setPSProperty(symbol, value ? kOSBooleanTrue : kOSBooleanFalse);
+ }
+ OSSafeReleaseNULL(symbol);
+}
+
+void
+RedwoodBattery::object(const char * key, OSObject * value)
+{
+ const OSSymbol * symbol = OSSymbol::withCString(key);
+
+ if (symbol != NULL && value != NULL) {
+ setPSProperty(symbol, value);
+ }
+ OSSafeReleaseNULL(symbol);
+}
+
+/*
+ * What iOS calls the charger by (IOPSKeysPrivate.h's kIOPSFamilyCode*, iokit_family_err(sub_iokit_usb, n)),
+ * from Linux's POWER_SUPPLY_USB_TYPE_*, as the DSP gives it.
+ */
+static unsigned
+family_code(int usb_type)
+{
+ switch (usb_type) {
+ case 1: return 0xe0004000; /* SDP, a computer's port: kIOPSFamilyCodeUSBHost */
+ case 2: return 0xe0004004; /* DCP, a charger: kIOPSFamilyCodeUSBChargingPortDedicated */
+ case 3: return 0xe0004005; /* CDP, a computer's charging port: kIOPSFamilyCodeUSBChargingPortDownstream */
+ case 5: return 0xe0004009; /* USB-C: kIOPSFamilyCodeUSBCTypeC */
+ case 6: case 7: case 8: return 0xe000400a; /* USB Power Delivery: kIOPSFamilyCodeUSBCPD */
+ default: return 0xe0004007; /* kIOPSFamilyCodeUSBUnknown */
+ }
+}
+
+void
+RedwoodBattery::report(const struct redwood_battery_state * b)
+{
+ int percent = (b->percent_hundredths + 50) / 100;
+ bool charging = b->external && b->status == 1; /* POWER_SUPPLY_STATUS_CHARGING */
+
+ percent = percent < 0 ? 0 : percent > 100 ? 100 : percent;
+ setBatteryInstalled(b->present != 0);
+ setExternalConnected(b->external != 0);
+ setExternalChargeCapable(b->external != 0);
+ setIsCharging(charging);
+ flag("FullyCharged", b->external && (b->status == 4 || percent == 100)); /* POWER_SUPPLY_STATUS_FULL */
+ flag("AppleRawExternalConnected", b->external != 0);
+ setCurrentCapacity((unsigned) percent);
+ setMaxCapacity(100);
+ setVoltage((unsigned) (b->voltage_uv / 1000));
+ setAmperage(b->current_ua / 1000);
+ number("InstantAmperage", b->current_ua / 1000);
+ number("Temperature", b->temperature_hundredths);
+ if (b->charge_uah > 0) {
+ number("AppleRawCurrentCapacity", b->charge_uah / 1000);
+ }
+ if (b->full_uah > 0) {
+ number("AppleRawMaxCapacity", b->full_uah / 1000);
+ number("NominalChargeCapacity", b->full_uah / 1000);
+ }
+ if (b->design_uah > 0) {
+ number("DesignCapacity", b->design_uah / 1000);
+ }
+ if (b->cycles > 0) {
+ setCycleCount((unsigned) b->cycles);
+ }
+
+ if (b->external) {
+ OSDictionary * adapter = OSDictionary::withCapacity(6);
+ long long mv = b->usb_voltage_uv / 1000, ma = b->usb_current_ua / 1000;
+ OSNumber * n;
+
+ if (adapter != NULL) {
+ if ((n = OSNumber::withNumber((unsigned long long) ((mv * ma + 500000) / 1000000), 32)) != NULL) {
+ adapter->setObject(kIOPMPSAdapterDetailsWattsKey, n);
+ n->release();
+ }
+ if ((n = OSNumber::withNumber((unsigned long long) ma, 32)) != NULL) {
+ adapter->setObject(kIOPMPSAdapterDetailsAmperageKey, n);
+ n->release();
+ }
+ if ((n = OSNumber::withNumber((unsigned long long) mv, 32)) != NULL) {
+ adapter->setObject(kIOPMPSAdapterDetailsVoltage, n);
+ n->release();
+ }
+ if ((n = OSNumber::withNumber((unsigned long long) family_code(b->usb_type), 32)) != NULL) {
+ adapter->setObject(kIOPMPSAdapterDetailsFamilyKey, n);
+ n->release();
+ }
+ adapter->setObject("IsWireless", kOSBooleanFalse);
+ object(kIOPMPSAdapterDetailsKey, adapter);
+ adapter->release();
+ }
+ } else {
+ OSDictionary * none = OSDictionary::withCapacity(1);
+ OSNumber * n = OSNumber::withNumber(0ULL, 32); /* kIOPSFamilyCodeDisconnected */
+
+ if (none != NULL && n != NULL) {
+ none->setObject(kIOPMPSAdapterDetailsFamilyKey, n);
+ object(kIOPMPSAdapterDetailsKey, none);
+ }
+ OSSafeReleaseNULL(n);
+ OSSafeReleaseNULL(none);
+ }
+ updateStatus();
+}
+
+/* With every reading of the battery (bsd/dev/redwood_battery.c); the first one makes the service. One caller at a time. */
+void
+RedwoodBatteryReport(const void * state, unsigned size)
+{
+ const struct redwood_battery_state * b = (const struct redwood_battery_state *) state;
+ IOService * platform;
+
+ if (size != sizeof(struct redwood_battery_state) || b->size != sizeof(struct redwood_battery_state)) {
+ static bool said;
+
+ if (!said) {
+ said = true;
+ IOLog("RedwoodBattery: the battery's state is %u bytes, not %lu: bsd/sys/redwood_input.h and this file disagree\n",
+ size, sizeof(struct redwood_battery_state));
+ }
+ return;
+ }
+ if (battery == NULL) {
+ RedwoodBattery * made = OSTypeAlloc(RedwoodBattery);
+
+ if ((platform = IOService::getPlatform()) == NULL || made == NULL || !made->init()) {
+ OSSafeReleaseNULL(made);
+ return;
+ }
+ made->report(b); /* (the properties are there before anybody finds the service) */
+ if (!made->attach(platform)) {
+ made->release();
+ return;
+ }
+ made->setName("RedwoodBattery");
+ if (!made->start(platform)) {
+ made->detach(platform);
+ made->release();
+ return;
+ }
+ made->registerService();
+ battery = made;
+ IOLog("RedwoodBattery: the battery's power source is up: %d%%, %s\n", (b->percent_hundredths + 50) / 100,
+ b->external ? (b->status == 1 ? "charging" : "on a charger, not charging") : "not on a charger");
+ return;
+ }
+ battery->report(b);
+}
diff --git a/xnu/redwood.patch b/xnu/redwood.patch
index b12ac65..86b206e 100644
--- a/xnu/redwood.patch
+++ b/xnu/redwood.patch
@@ -1431,10 +1431,10 @@ index 5219fb0d9ed6..29978e9cff43 100644
}
}
diff --git a/iokit/conf/files b/iokit/conf/files
-index 5fb0a52062e0..f90b663607f3 100644
+index 5fb0a52062e0..6c430c2b23c7 100644
--- a/iokit/conf/files
+++ b/iokit/conf/files
-@@ -79,6 +79,13 @@ iokit/Kernel/IOSubMemoryDescriptor.cpp optional iokitcpp
+@@ -79,6 +79,14 @@ iokit/Kernel/IOSubMemoryDescriptor.cpp optional iokitcpp
iokit/Kernel/IOGuardPageMemoryDescriptor.cpp optional iokitcpp
iokit/Kernel/IOPlatformExpert.cpp optional iokitcpp
@@ -1443,6 +1443,7 @@ index 5fb0a52062e0..f90b663607f3 100644
+iokit/Kernel/MiniIOMobileFramebuffer.cpp optional iokitcpp
+iokit/Kernel/RedwoodGPU.cpp optional iokitcpp
+iokit/Kernel/RedwoodWLAN.cpp optional iokitcpp
++iokit/Kernel/RedwoodBattery.cpp optional iokitcpp
+iokit/Kernel/MiniAppleKeyStore.cpp optional iokitcpp
+iokit/Kernel/MiniIONetworkStack.cpp optional iokitcpp
iokit/Kernel/IOPlatformIO.cpp optional iokitcpp