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
PM7250B battery: read SOC/voltage/current from the fuel gauge, show it in iOS
shimoku74e7594bedf983
diff --git a/userland/src/inject_sb.c b/userland/src/inject_sb.cindex f740f60..754f91c 100644--- a/userland/src/inject_sb.c+++ b/userland/src/inject_sb.c@@ -145,6 +145,59 @@ snapshot_output_format(__unused id self, __unused SEL selector, id snapshot)return SNAPSHOT_FORMAT_PNG;}+/* ---- real battery level from the PM7250B fuel gauge ---------------------------------------------- */++/*+ * 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; see redwood_battery.c for the register work), so+ * we hook the UIDevice accessors to return what the kernel's SPMI poller found, which it stores+ * in kern.redwood.battery_soc (0..100) and kern.redwood.battery_current_ma (negative = 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.+ */+static float (*original_battery_level)(id self, SEL sel);+static long (*original_battery_state)(id self, SEL sel);++static int+sysctl_int(const char *name)+{+ int value = -1;+ size_t size = sizeof(value);++ sysctlbyname(name, &value, &size, NULL, 0);+ return value;+}++/* 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) {+ return original_battery_level ? original_battery_level(self, sel) : -1.0f;+ }+ return (float)soc / 100.0f;+}++/* UIDevice.batteryState: 0=unknown 1=unplugged 2=charging 3=full */+static long+battery_state(id self, SEL sel)+{+ int ma = sysctl_int("kern.redwood.battery_current_ma");+ int soc = sysctl_int("kern.redwood.battery_soc");++ if (ma == -1 && soc == -1) {+ return original_battery_state ? original_battery_state(self, sel) : 0;+ }+ if (ma < -50) { /* negative current = charging */+ return soc >= 99 ? 3 : 2;+ }+ return 1;+}+/* ---- the lock screen's clock without a GPU ------------------------------------------------------- */#define REDWOOD_GL "/redwood/lib/libredwood-gl.dylib"@@ -436,7 +489,7 @@ redwood_springboard_init(void){const char *name = getprogname();size_t length = 0;- IMP activation, snapshot_format;+ IMP activation, snapshot_format, battery_lvl, battery_st;int token;if (name == NULL || strcmp(name, "SpringBoard") != 0) {@@ -451,9 +504,20 @@ redwood_springboard_init(void)plain_vibrancy();original_lock_long_press = (void (*)(id, SEL, id))replace_method("SBLockHardwareButton", "longPress:", 0x1c4f6ab44UL,(IMP)lock_long_press);- say("redwood: SpringBoard: activation %s, setup assistant %s, application snapshots %s, the side button's long press %s\n",+ /*+ * Battery hooks on UIDevice: these are the methods every app and SpringBoard itself calls, so+ * hooking them here in the SpringBoard process covers both the status bar and any app that+ * reads [UIDevice currentDevice].batteryLevel. The addresses are for iOS 16.5 (20F66).+ */+ original_battery_level = (float (*)(id, SEL))replace_method("UIDevice", "batteryLevel", 0x1aa038b5cUL, (IMP)battery_level);+ original_battery_state = (long (*)(id, SEL))replace_method("UIDevice", "batteryState", 0x1aa038b90UL, (IMP)battery_state);+ battery_lvl = (IMP)original_battery_level;+ battery_st = (IMP)original_battery_state;+ say("redwood: SpringBoard: activation %s, setup assistant %s, application snapshots %s, the side button's long press %s, "+ "battery level %s, battery state %s\n",activation ? "answered here" : "NOT replaced", original_set_setup_required_reason ? "refused" : "NOT replaced",- snapshot_format ? "as JPEG" : "NOT changed", original_lock_long_press ? "checked" : "NOT checked");+ snapshot_format ? "as JPEG" : "NOT changed", original_lock_long_press ? "checked" : "NOT checked",+ battery_lvl ? "from QG" : "NOT replaced", battery_st ? "from QG" : "NOT replaced");{char args[1024] = "";size_t size = sizeof(args) - 1;@@ -464,6 +528,21 @@ redwood_springboard_init(void)usleep((useconds_t)(atof(delay + 9) * 1e6));}}+ /*+ * UIDevice won't call batteryLevel/batteryState unless monitoring is enabled. Flip it on once+ * SpringBoard's run loop is running (the dispatch_after fires on the main queue, which means+ * we are past UIApplication startup).+ */+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{+ Class uidev = objc_getClass("UIDevice");+ SEL current = sel_registerName("currentDevice");+ SEL monitoring = sel_registerName("setBatteryMonitoringEnabled:");+ id device = uidev ? ((id (*)(Class, SEL))objc_msgSend)(uidev, current) : nil;++ if (device && class_getInstanceMethod(object_getClass(device), monitoring)) {+ ((void (*)(id, SEL, BOOL))objc_msgSend)(device, monitoring, YES);+ }+ });notify_register_dispatch("com.redwood.unlock", &token, dispatch_get_main_queue(), ^(__unused int t) {unlock();});diff --git a/xnu/files/bsd/dev/redwood_battery.c b/xnu/files/bsd/dev/redwood_battery.cnew file mode 100644index 0000000..a62bfb7--- /dev/null+++ b/xnu/files/bsd/dev/redwood_battery.c@@ -0,0 +1,299 @@+/*+ * Battery monitor for the POCO X5 Pro (redwood). This reads the live state-of-charge, battery+ * voltage, and battery current straight from the fuel-gauge peripheral inside PM7250B over+ * SPMI, so iOS can show real numbers in the status bar instead of a fake low-battery icon.+ *+ * Enabled only with boot-arg battery=1. Read-only: we do not touch the charger here, we do not+ * reconfigure any PMIC rail, we just poll a few registers and expose the result through+ * sysctl kern.redwood.battery_*. Writing to the charger is a separate project and a much+ * larger pile of code (sm8350-kernel-OKX ships ~3000 lines of qpnp-smb5 for that).+ *+ * Hardware layout: PM7250B lives at SPMI slave 2. The Qualcomm Gauge ("QG") peripheral is at+ * SPMI peripheral 0x48, so registers live at 0x48XX in that slave's address space. The+ * fuel-gauge chip ran its initial ADC burst back in Android before we yanked the system out+ * from under it, so its state-of-charge estimate is already current and keeps drifting with+ * use. We just read what the chip computed, we do not re-run the gauge algorithm. Register+ * meanings taken from drivers/power/supply/qcom/qg-reg.h in sm8350-kernel-OKX:+ *+ * QG_SOC_MONOTONIC (0xBF) -- 1 byte, 0..255 maps to 0..100 % (monotonic, i.e.+ * never ticks up on discharge, never down on charge;+ * this is what Android shows as "battery level")+ * QG_LAST_ADC_V_DATA (0xC0, 0xC1) -- 2 bytes LE, battery voltage in units of 194.6 uV+ * (max 12.75 V, we never go anywhere near that)+ * QG_LAST_ADC_I_DATA (0xC2, 0xC3) -- 2 bytes LE, battery current, signed, LSB is 61 uA+ * at the chip's default 5A range (negative = charging)+ *+ * SPMI itself is already set up by the buttons driver (redwood_buttons.c) which maps the PMIC+ * arbiter at step 1 and finds channels at step 2. We do the same two steps here independently+ * so this driver works even when buttons=0; it is a few kB of code to duplicate and it keeps+ * the two drivers from stepping on each other's state.+ *+ * Register layouts: Linux drivers/spmi/spmi-pmic-arb.c (arbiter version 5),+ * drivers/power/supply/qcom/qpnp-qg.c and qg-reg.h, and the phone's own pm7250b.dtsi.+ */+#include <kern/clock.h>+#include <kern/thread.h>+#include <libkern/libkern.h>+#include <mach/mach_types.h>+#include <pexpert/pexpert.h>+#include <sys/redwood_input.h>+#include <sys/sysctl.h>+#include <sys/systm.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);++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;+}++/* ---- PMIC arbiter (copied verbatim from redwood_buttons.c) ---------------------------------------- */++#define ARB_CORE_PHYS 0x0c440000UL+#define ARB_CORE_SIZE 0x1100UL+#define ARB_CNFG_PHYS 0x0c40a000UL+#define ARB_CNFG_SIZE 0x1000UL+#define ARB_OBSERVER_PHYS 0x0e600000UL+#define ARB_OBSERVER_SIZE 0x10000UL+#define ARB_SYSTEM 0++#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))+#define ARB_OWNER(n) (0x700 + 4 * (n))+#define ARB_MAX_CHANNELS 512++#define OBSERVER_COMMAND 0x00+#define OBSERVER_STATUS 0x08+#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_READ (1u << 27)+#define READ_TIMEOUT_US 2000++static vm_offset_t arb_core, arb_cnfg, arb_observer;++struct peripheral {+ const char * name;+ uint16_t id; /* slave << 8 | peripheral: the high byte of its register addresses */+ uint16_t channel;+ bool found;+};+static struct peripheral qg = { .name = "the PM7250B fuel gauge (QG)", .id = 0x248 };++/*+ * Read `count` (1 to 8) registers of a peripheral, from register `reg` on. Returns NULL on+ * success, or a short description of what went sideways. Verbatim copy of the buttons driver's+ * version -- the SPMI arbiter is the same regardless of what peripheral we poke at.+ */+static const char *+spmi_read(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;+ uint64_t start = mach_absolute_time(), now, interval;+ uint32_t status, data[2];+ const char *problem = NULL;++ nanoseconds_to_absolutetime(READ_TIMEOUT_US * (uint64_t)NSEC_PER_USEC, &interval);+ 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);++ if (!(status & STATUS_DONE)) {+ problem = "no answer from the arbiter";+ } else if (status & STATUS_DENIED) {+ problem = "the arbiter refuses";+ } else if (status & STATUS_FAILURE) {+ problem = "the transfer failed (nobody at that address?)";+ } 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)));+ }+ }+ return problem;+}++/* Scan the arbiter's channel table for the SPMI peripheral we want to talk to. */+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));+ uint32_t owner;++ if (map == 0 || ((map >> 8) & 0xfff) != p->id) {+ continue;+ }+ owner = rd(arb_cnfg + ARB_OWNER(n)) & 7;+ printf("battery: channel %u is %s (%#x); written by system %u\n", n, p->name, map, owner);+ if (!p->found || owner == ARB_SYSTEM) {+ p->found = true;+ p->channel = (uint16_t)n;+ }+ }+ if (!p->found) {+ printf("battery: no channel of the arbiter is %s (slave %u, peripheral %#x)\n",+ p->name, p->id >> 8, p->id & 0xff);+ }+}++/* ---- QG (fuel gauge) registers ---------------------------------------------------------------- */++#define QG_PERIPH_OFFSET 0x00 /* registers 0x4800..0x48ff on PM7250B */+#define QG_REG_PERPH_TYPE (QG_PERIPH_OFFSET + 0x04)+#define QG_REG_PERPH_SUBTYPE (QG_PERIPH_OFFSET + 0x05)+#define QG_REG_STATUS1 (QG_PERIPH_OFFSET + 0x08)+#define QG_STATUS1_BATTERY_PRESENT (1u << 0)+#define QG_STATUS1_QG_OK (1u << 7)+#define QG_REG_SOC_MONOTONIC (QG_PERIPH_OFFSET + 0xbf)+#define QG_REG_LAST_V_DATA_LSB (QG_PERIPH_OFFSET + 0xc0)+#define QG_REG_LAST_I_DATA_LSB (QG_PERIPH_OFFSET + 0xc2)+#define QG_TYPE 0x0d /* vendor PERPH_TYPE_QG */++/* Live state. These are updated by battery_thread and read by the sysctls below. */+static int battery_soc_percent = -1; /* 0..100, or -1 if we have not read it yet */+static int battery_voltage_mv = -1; /* millivolts; signed only because -1 means unknown */+static int battery_current_ma = 0; /* negative = charging, positive = discharging, mA */+static int battery_present = 0; /* 1 if a battery is wired up, 0 otherwise */+static uint64_t battery_updates; /* how many successful poll cycles so far */+static uint64_t battery_failures; /* and failed ones */++/*+ * One polling cycle: read SOC, voltage, current, status. Each read is one SPMI transaction and+ * takes a few tens of microseconds, so the whole thing is fast enough that we can do it every+ * couple of seconds without noticing it in the system's cpu budget.+ */+static void+battery_poll(void)+{+ uint8_t soc = 0, status = 0, v[2] = { 0 }, i[2] = { 0 };+ const char *problem;++ problem = spmi_read(&qg, QG_REG_STATUS1, &status, 1);+ if (problem != NULL) {+ battery_failures++;+ return;+ }+ battery_present = (status & QG_STATUS1_BATTERY_PRESENT) ? 1 : 0;++ problem = spmi_read(&qg, QG_REG_SOC_MONOTONIC, &soc, 1);+ if (problem == NULL) {+ battery_soc_percent = (int)soc * 100 / 255; /* the chip packs 0..100 % into 0..255 */+ }++ problem = spmi_read(&qg, QG_REG_LAST_V_DATA_LSB, v, 2);+ if (problem == NULL) {+ /* 2-byte LE raw ADC code; the chip's step is 194.6 uV per LSB. Keep math in integers:+ * 1946 * raw / 10000 is millivolts. Range of a healthy single-cell li-ion is 3000..4400. */+ uint32_t raw = (uint32_t)v[0] | ((uint32_t)v[1] << 8);+ battery_voltage_mv = (int)((1946u * raw) / 10000u);+ }++ problem = spmi_read(&qg, QG_REG_LAST_I_DATA_LSB, i, 2);+ if (problem == NULL) {+ /* 2-byte LE SIGNED raw ADC code; LSB is 61 uA at the 5A range. Negative value = current+ * is flowing INTO the battery (charging), positive = flowing OUT (discharging). */+ int16_t raw = (int16_t)((uint16_t)i[0] | ((uint16_t)i[1] << 8));+ battery_current_ma = (int)(((int32_t)raw * 61) / 1000);+ }++ battery_updates++;+}++/* ---- sysctl: kern.redwood.battery_* --------------------------------------------------------- */++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");+SYSCTL_INT(_kern_redwood, OID_AUTO, battery_voltage_mv, CTLFLAG_RD | CTLFLAG_LOCKED,+ &battery_voltage_mv, 0, "battery voltage in millivolts, or -1 if unknown");+SYSCTL_INT(_kern_redwood, OID_AUTO, battery_current_ma, CTLFLAG_RD | CTLFLAG_LOCKED,+ &battery_current_ma, 0, "battery current in milliamps (negative = charging)");+SYSCTL_INT(_kern_redwood, OID_AUTO, battery_present, CTLFLAG_RD | CTLFLAG_LOCKED,+ &battery_present, 0, "1 if the fuel gauge sees a battery wired up, 0 otherwise");++/* ---- all of it together ---------------------------------------------------------------------- */++static void+battery_thread(__unused void *parameter, __unused wait_result_t result)+{+ uint32_t version, channels;+ uint8_t subtype;+ const char *problem;++ printf("battery: step 1: map the PMIC arbiter and read its version\n");+ 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;+ printf("battery: PMIC arbiter version %#x, %u channels\n", version, channels);+ if (version < ARB_VERSION_5 || version >= ARB_VERSION_7) {+ printf("battery: this driver knows version 5 of the arbiter only; giving up\n");+ thread_terminate(current_thread());+ return;+ }+ if (channels == 0 || channels > ARB_MAX_CHANNELS) {+ channels = ARB_MAX_CHANNELS;+ }++ printf("battery: step 2: find the fuel-gauge channel in the arbiter\n");+ find_channel(&qg, channels);+ if (!qg.found) {+ thread_terminate(current_thread());+ return;+ }++ printf("battery: step 3: confirm the fuel-gauge peripheral is where we think it is\n");+ problem = spmi_read(&qg, QG_REG_PERPH_TYPE, &subtype, 1);+ if (problem != NULL) {+ printf("battery: cannot read the peripheral type (%s)\n", problem);+ thread_terminate(current_thread());+ return;+ }+ printf("battery: peripheral type is %#x (expected %#x for the fuel gauge)\n", subtype, QG_TYPE);++ printf("battery: step 4: polling every 5 seconds\n");+ for (unsigned tick = 0;; tick++) {+ battery_poll();+ if (tick % 12 == 0) { /* once a minute at 5-second cadence */+ printf("battery: SOC=%d%%, V=%d mV, I=%d mA, %spresent (%llu reads, %llu failed)\n",+ battery_soc_percent, battery_voltage_mv, battery_current_ma,+ battery_present ? "" : "not ", battery_updates, battery_failures);+ }+ delay_for_interval(5000, NSEC_PER_MSEC);+ }+}++void+redwood_battery_init(void)+{+ uint32_t enabled = 0;+ thread_t thread;++ if (!PE_parse_boot_argn("battery", &enabled, sizeof(enabled)) || !enabled) {+ return;+ }+ if (kernel_thread_start(battery_thread, NULL, &thread) == KERN_SUCCESS) {+ thread_deallocate(thread);+ }+}diff --git a/xnu/files/bsd/dev/redwood_goodix.c b/xnu/files/bsd/dev/redwood_goodix.cindex 6aac1ab..a39ebd5 100644--- a/xnu/files/bsd/dev/redwood_goodix.c+++ b/xnu/files/bsd/dev/redwood_goodix.c@@ -1,36 +1,29 @@/*- * Touch screen driver for the POCO X5 Pro (redwood). Depending on the panel the phone shipped- * with, this is either a Goodix GT9916 ("Berlin-D") or a FocalTech FT3680 hanging off the SoC's- * QUP serial engine 13 over SPI. We feed samples into /dev/redwood-touch (sys/redwood_input.h),- * which userland's inject.c then turns into HID events for backboardd. Only runs when the kernel- * gets touchscreen=1 on the boot args.- *- * This kernel has no clock / pin / regulator / SPI framework, so this file is the whole stack- * from registers upward. The bring-up order matches what Linux does for both chips:+ * The touch screen of the POCO X5 Pro (redwood): either a Goodix GT9916 ("Berlin-D") or a+ * FocalTech FT3680 on the SPI bus of the SoC's serial engine 13, as a source of touches for+ * /dev/redwood-touch (sys/redwood_input.h). Only with boot-arg touchscreen=1: every address+ * below belongs to this phone.*+ * There is no clock, pin, regulator or SPI framework in this kernel, so the driver does all of+ * it itself, in the order the vendor's Linux drivers do:* power the chip's I/O supply is LDO2 of the PM8350C, switched through RPMh (one request* written into the "always on" processor's command slots); the analog supply is- * behind a GPIO load switch- * clocks the serial engine's three clocks, by vote in the global clock controller (GCC)- * pins four GPIOs for SPI, plus reset / interrupt / analog supply enable- * SPI the serial engine ("GENI") in FIFO mode, polled; or (used for both chips in- * practice because GENI returns zeroes) the same four pins driven by hand- * panel GPIO96=1 and GPIO68=0 means the FocalTech variant, anything else is Goodix.- * Same discriminator sm8350-kernel-OKX's fts_init_sysfs() uses.- * chip Goodix: find the registers that hold the touch report, then poll them whenever- * the IRQ line signals a new one- * FocalTech: whole different animal -- the chip comes up totally brain-dead and- * won't do anything until the host uploads its ~114 KB firmware blob- * into PRAM via the boot ROM every single power cycle. See the big- * comment block above focaltech_probe() for the whole dance.- *- * No interrupt is wired up: a thread polls the INT line 125 times a second. Good enough for- * finger input, saves us from writing an interrupt controller stub.+ * behind a GPIO+ * clocks the serial engine's three clocks, by vote in the global clock controller+ * pins four GPIOs to the serial engine, plus reset, interrupt and the analog supply switch+ * SPI the serial engine ("GENI") in FIFO mode, polled; or, if the engine cannot be used,+ * the same four pins driven by hand+ * panel GPIO96=1 and GPIO68=0 identify the FocalTech variant; everything else is Goodix,+ * the same discriminator the vendor sm8350-kernel-OKX uses+ * chip Goodix: find where it keeps the touch report, then read it when the IRQ line signals;+ * FocalTech: read the report at register 0x01 with FTS 5.x SPI framing (cmd 0xC1 for+ * read, 0xC0 for write, two-byte CRC-16/Kermit)+ * No interrupt is used: a thread looks at the interrupt line 125 times a second.*- * References: Linux drivers/spi/spi-geni-qcom.c, drivers/soc/qcom/{qcom-geni-se,rpmh-rsc,+ * Register layouts: Linux drivers/spi/spi-geni-qcom.c, drivers/soc/qcom/{qcom-geni-se,rpmh-rsc,* cmd-db}.c, drivers/clk/qcom/gcc-sc7280.c, drivers/pinctrl/qcom/pinctrl-sc7280.c,- * drivers/input/touchscreen/{goodix_berlin_*,focaltech_3680/*}.c (OKX fork for the FTS bits),- * and the phone's own device tree.+ * drivers/input/touchscreen/{goodix_berlin_*,focaltech_touch/focaltech_core}.c, and the phone's+ * own device tree.*/#include <kern/clock.h>#include <kern/thread.h>@@ -850,27 +843,16 @@ goodix_poll(void)/* ---- the FocalTech FT3680 chip --------------------------------------------------------------------- *//*- * So here's the deal with FocalTech: unlike Goodix which just boots itself from its own flash- * and gets to work, this chip comes up totally brain-dead with nothing but a boot ROM. The host- * (us) has to shove the whole firmware blob (~114 KB) into the chip's PRAM over SPI every single- * cold boot, THEN tell it to go run that code. Only after the chip has the firmware actually- * executing can we read touch events out of it.- *- * The whole SPI framing is lifted verbatim from sm8350-kernel-OKX drivers/input/touchscreen/- * focaltech_3680/focaltech_spi.c. Every transfer looks like this:- *- * TX[0] = register address (writebuf[0] / cmd[0])- * TX[1] = ctrl byte: 0xA0 for read (with CRC check), 0x00 for write (no CRC)- * TX[2..3] = data length, big-endian- * TX[4..6] = three dummy bytes (SPI_DUMMY_BYTE), give the chip time to think- * TX[7..] = write data (reads leave this blank so the chip can drive MISO here)- * TX[last-1..] = CRC-16/Kermit of the data bytes, LE (reads only; writes have no CRC)- *- * SPI_HEADER_LENGTH = 4 + SPI_DUMMY_BYTE = 7 bytes.- *- * Status byte lives at RX[3]: bit 7 = chip busy, bit 5 = CRC error, 0 means we're good.- * If the data we read back is 0xEF with a valid CRC, the chip's firmware isn't running --- * that's its "no app in memory, go upload firmware or shut up" NACK pattern.+ * FTS 5.x SPI framing from sm8350-kernel-OKX drivers/input/touchscreen/focaltech_3680/+ * focaltech_spi.c (verbatim):+ * TX[0] = register address (writebuf[0] / cmd[0])+ * TX[1] = FOCALTECH_READ_CTRL (0xA0 = READ_CMD, CRC_EN set) or FOCALTECH_WRITE_CTRL (0x00)+ * TX[2..3] = data length BE (for read: datalen; for write: writelen - 1)+ * TX[4..6] = three dummy bytes (SPI_DUMMY_BYTE)+ * TX[7..7+len-1] = write data (empty on read; chip drives MISO here)+ * TX[last-1..last] = CRC-16/Kermit of the data bytes, little-endian (only when READ_CMD or+ * when a vendor WRITE op needs CRC; vendor WRITE_CMD = 0x00 has no CRC)+ * SPI_HEADER_LENGTH = 4 + SPI_DUMMY_BYTE = 7.*/#define FOCALTECH_READ_CTRL 0xa0 /* READ_CMD = 0x80 | DATA_CRC_EN(0x20) */#define FOCALTECH_WRITE_CTRL 0x00 /* WRITE_CMD, no CRC on TX */@@ -883,9 +865,7 @@ goodix_poll(void)static uint8_t focaltech_tx[FOCALTECH_MAX_TRANSFER], focaltech_rx[FOCALTECH_MAX_TRANSFER];-/* The chip's CRC flavor: Kermit (0x8408 poly reflected, init 0xffff). Byte-for-byte identical to- * the vendor's rckit_crc16() so our math matches whatever the chip wants to see.- */+/* CRC-16/Kermit (polynomial 0x8408 reflected, initial 0xffff) -- same as vendor rckit_crc16(). */static uint16_tfocaltech_crc(const uint8_t *data, uint32_t length){@@ -998,14 +978,10 @@ focaltech_write(uint8_t address, const uint8_t *data, uint32_t length)#include "redwood_focaltech_fw.h"/*- * Knock on the chip's boot ROM door and ask who it is. The handshake is:- * 1. framed write { 0x55, 0xAA } -- this is really a "write 0xAA to register 0x55", the- * magic combo FocalTech decided means "yo, pay attention, host is here"- * 2. chill for 12 ms (FTS_CMD_START_DELAY) -- less and the chip isn't ready, more and it- * may have already auto-booted past this point- * 3. framed read of 2 bytes from register 0x90 -- the boot ROM answers with its ID- * For FT3680 the expected answer is { 0x56, 0x62 }. Anything else means the chip is either- * running firmware already or hung somewhere we don't want to be.+ * Vendor fts_read_bootid(): send { 0x55, 0xAA } as a 2-byte framed write (treated as a write of+ * one data byte 0xAA to register 0x55), wait 12 ms, then do a framed read of 2 bytes at+ * register 0x90. The chip answers with its ROM ID (0x56 0x62 for FT3680) if it is sitting in+ * the boot ROM waiting for a firmware download.*/static boolfocaltech_read_boot_id(uint8_t *high, uint8_t *low)@@ -1024,11 +1000,7 @@ focaltech_read_boot_id(uint8_t *high, uint8_t *low)return ok;}-/*- * Poll the runtime chip-ID registers (0xA3 / 0x9F) until the firmware has had time to boot- * and start answering with { 0x56, 0x62 }. Vendor's fts_wait_tp_to_valid gives up after 1 s;- * we do the same: 5 attempts, 200 ms apart.- */+/* Vendor fts_wait_tp_to_valid: poll chip ID for up to TIMEOUT_READ_REG (1 s) at 200 ms steps. */static boolfocaltech_wait_valid(uint8_t *high, uint8_t *low){@@ -1045,10 +1017,9 @@ focaltech_wait_valid(uint8_t *high, uint8_t *low)}/*- * Reset-and-knock. The boot ROM has a tiny window after reset release where it listens --- * blink and you miss it, which is why our old 200 ms wait never caught the chip in boot mode.- * Vendor fts_get_ic_information tries 3 times with escalating settle delays (12, 20, 28 ms)- * so we do the same. Returns true if we caught it: boot-ID register answers { 0x56, 0x62 }.+ * Reset the chip and send 0x55/0xAA to put it in boot ROM, as vendor fts_get_ic_information+ * does. Try up to 3 times with escalating settle delays (12, 20, 28 ms). Returns true if the+ * chip is sitting in its boot ROM, with { 0x56, 0x62 } read back from the boot-ID register.*/static boolfocaltech_enter_boot_rom(void)@@ -1071,19 +1042,9 @@ focaltech_enter_boot_rom(void)}/*- * Here's the main event: shove the firmware blob into the chip's PRAM.- *- * The boot ROM can only speak this one tiny upload protocol -- SET_PRAM_ADDR (0xAD) tells it- * where to write, then WRITE (0xAE) hands over the data. We chunk the 116 KB file into 32-byte- * packets (FTS_FLASH_PACKET_LENGTH), so for FT3680 it's ~3640 packets per cold boot. Each- * packet costs two framed writes = ~7280 SPI transactions. On bit-banged pins at full tilt- * this takes ~700 ms wall time, which is honestly fine for a once-per-boot thing.- *- * No ECC check here (vendor does one afterwards via register 0xCC) -- our framed writes- * already carry per-packet status that we validate inside focaltech_write(), and if any- * packet actually corrupts, the firmware either fails to start or runtime ID stays wrong.- * Either way we notice without the extra round-trip, and skipping the ECC pass saves another- * ~100 ms. If the chip ever ships flaky, add it back.+ * Download the embedded firmware (pramboot + application) into the chip's PRAM via the boot+ * ROM's SPI_V2 upload protocol. Each 32-byte packet is sent as two framed writes: first set+ * the PRAM destination address (SET_PRAM_ADDR + 3 BE address bytes), then WRITE + data bytes.*/static boolfocaltech_write_pram(const uint8_t *buf, uint32_t len)@@ -1110,12 +1071,6 @@ focaltech_write_pram(const uint8_t *buf, uint32_t len)return true;}-/*- * Tell the boot ROM to shut up and hand control over to the code we just uploaded. One byte- * command (0x08), no payload. After this the chip starts executing from PRAM address 0 and- * (if everything above went right) a few hundred ms later it's answering runtime register- * reads like a normal functioning touchscreen.- */static boolfocaltech_start_app(void){@@ -1125,33 +1080,19 @@ focaltech_start_app(void)}/*- * The whole dance, start to finish:- *- * 1. Maybe the chip is already running from a previous session (warm reboot, loader bounce,- * whatever) -- try reading runtime chip ID first, that's basically free. If it answers- * 0x56 / 0x62, skip the upload entirely and get on with the touchscreen's actual job.- * 2. Otherwise, hard reset and catch the chip in its boot ROM (the handshake window is- * narrow, see focaltech_enter_boot_rom).- * 3. Blast the firmware blob into PRAM (focaltech_write_pram) and tell it to run- * (focaltech_start_app).- * 4. Give the firmware 300 ms to actually come up and initialize whatever analog stuff it- * needs (sensor drive signals, calibration load, whatever), then poll runtime ID again.- *- * If any of this fails we log where and give up -- the caller falls back to Goodix probe path- * which will also fail for a FocalTech board, and bring_up() prints "no touch screen" and the- * driver thread just exits. iOS still boots thanks to the auto-unlock in inject_sb.c.+ * Full chip bring-up: look for an already-running firmware; if none, reset to boot ROM and+ * download the embedded firmware into PRAM; then start it and wait for runtime to come up.*/static boolfocaltech_probe(bool verbose){uint8_t high = 0, low = 0;- /* Step 1: maybe firmware is already running. */+ /* Maybe firmware is already running (previous session, warm boot). */if (focaltech_wait_valid(&high, &low)) {return true;}- /* Step 2: reset and catch the boot ROM. */if (!focaltech_enter_boot_rom()) {if (verbose) {printf("focaltech: chip not in boot ROM; last read runtime %02x %02x\n", high, low);@@ -1159,7 +1100,6 @@ focaltech_probe(bool verbose)return false;}- /* Step 3: upload firmware and start it. */printf("focaltech: downloading %u bytes of firmware to PRAM...\n", FOCALTECH_FW_LENGTH);if (!focaltech_write_pram(focaltech_fw, FOCALTECH_FW_LENGTH)) {printf("focaltech: PRAM download failed\n");@@ -1170,9 +1110,8 @@ focaltech_probe(bool verbose)printf("focaltech: start-app command failed\n");return false;}- sleep_ms(300); /* let the firmware spin up all its analog bits */+ sleep_ms(300); /* firmware needs time to initialize all peripherals */- /* Step 4: confirm firmware is up and answering. */if (focaltech_wait_valid(&high, &low)) {return true;}@@ -1185,29 +1124,20 @@ focaltech_probe(bool verbose)/* ---- FocalTech touch reports --------------------------------------------------------------------- *//*- * Report layout for FT3680 (vendor focaltech_core.c, FTS_TOUCH_OFF_* offsets).- *- * The first two bytes are the header: a gesture byte (nonzero only when the chip is in- * gesture mode, which we don't use) and a count byte that packs chip type in the upper- * nibble and the number of fingers currently touching in the lower nibble.- *- * After that, each finger slot is six bytes:- *- * [0] E_XH: [7:6] event (0 = finger down, 1 = finger up, 2 = still touching aka contact)- * [3:0] x bits 14..11- * [1] XL: x bits 10..3- * [2] ID_YH: [7:4] finger id (0..9), [3:0] y bits 14..11- * [3] YL: y bits 10..3- * [4] PRE: [7:5] x bits 2..0, [4:2] y bits 2..0 (yes, both axes borrow bits from the- * pressure byte -- the chip gives us- * "super-high resolution" sub-pixel coords- * and this is where the extra precision- * lives)- * [5] AREA: touch area / major axis (we don't use it)- *- * X and Y are 15-bit sub-pixel values. The physical panel is 1080 x 2400 but the chip reports- * in 10x finer units -- 10800 x 24000 (same as Goodix on this same panel). We then rescale to- * 0..65535 before shipping to iOS via /dev/redwood-touch.+ * Per-chip report layout for FT3680 (vendor focaltech_core.c, FTS_TOUCH_OFF_* offsets):+ * report[0] = gesture (0 outside gesture mode)+ * report[1] = (chip_type << 4) | finger_count+ * report[2 + 6*i + 0] = E_XH: bits 7..6 = event (0 = down, 1 = up, 2 = contact)+ * bits 3..0 = x bits 14..11+ * report[2 + 6*i + 1] = XL: x bits 10..3+ * report[2 + 6*i + 2] = ID_YH: bits 7..4 = finger id, bits 3..0 = y bits 14..11+ * report[2 + 6*i + 3] = YL: y bits 10..3+ * report[2 + 6*i + 4] = PRE: bits 7..5 = x bits 2..0, bits 4..2 = y bits 2..0+ * (also the pressure byte -- the lowest bits of each 15-bit axis+ * are packed in with it)+ * report[2 + 6*i + 5] = AREA: touch area / major+ * Coordinates are 15-bit "super-high resolution" sub-pixel values; the touch panel's actual+ * extent is reported through the device tree as x_max/y_max (10800 x 24000 for redwood).*/#define FOCALTECH_EVENT_DOWN 0#define FOCALTECH_EVENT_UP 1@@ -1313,19 +1243,7 @@ focaltech_poll(void)focaltech_report(report);}-/*- * Which touch chip is physically on this particular board. Xiaomi ships redwood with two- * different touch controllers depending on which panel the factory happened to grab -- Goodix- * GT9916 or FocalTech FT3680. They're on the same SPI pins but speak totally different- * protocols, so we need to figure out which one before doing anything else.- *- * The vendor's sm8350-kernel-OKX uses two GPIO straps to tell them apart:- * GPIO96 reads high AND GPIO68 reads low --> FocalTech- * anything else --> Goodix- *- * These pins are tied to specific pads on the panel connector and set by the panel itself, so- * reading them tells us what's actually plugged in. We just copy the vendor's discriminator.- */+/* Which touch chip is on this board. */enum touch_chip { TOUCH_GOODIX, TOUCH_FOCALTECH };static enum touch_chip touch_chip;@@ -1340,9 +1258,6 @@ touch_chip_detect(void)return TOUCH_GOODIX;}-/* The two per-chip dispatchers below just hand off to goodix_* or focaltech_* based on what- * touch_chip_detect() figured out. Keeps bring_up() clean of per-vendor if-else noise. */-static boolchip_probe(bool verbose){diff --git a/xnu/files/bsd/dev/redwood_input.c b/xnu/files/bsd/dev/redwood_input.cindex b9a5a6f..8ac7a2a 100644--- a/xnu/files/bsd/dev/redwood_input.c+++ b/xnu/files/bsd/dev/redwood_input.c@@ -171,6 +171,7 @@ redwood_input_init(void)redwood_virtio_input_init();redwood_goodix_init();redwood_buttons_init();+ redwood_battery_init();redwood_net_init();redwood_adreno_init();redwood_wifi_init();diff --git a/xnu/files/bsd/sys/redwood_input.h b/xnu/files/bsd/sys/redwood_input.hindex 551a263..2dc4c90 100644--- a/xnu/files/bsd/sys/redwood_input.h+++ b/xnu/files/bsd/sys/redwood_input.h@@ -40,7 +40,8 @@ struct redwood_touch {void redwood_touch_post(uint32_t type, uint32_t finger, uint32_t x, uint32_t y);void redwood_input_init(void);void redwood_virtio_input_init(void); /* boot-arg virtio_input=1: QEMU's virtio pointer and keyboard */-void redwood_goodix_init(void); /* boot-arg touchscreen=1: the phone's touch screen */+void redwood_goodix_init(void); /* boot-arg touchscreen=1: the phone's Goodix or FocalTech touch screen */+void redwood_battery_init(void); /* boot-arg battery=1: SOC/voltage/current from PM7250B fuel gauge */void redwood_buttons_init(void); /* boot-arg buttons=1: the phone's power and volume keys */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 */diff --git a/xnu/redwood.patch b/xnu/redwood.patchindex 040f203..2deeb4d 100644--- a/xnu/redwood.patch+++ b/xnu/redwood.patch@@ -46,10 +46,10 @@ index 222158a93918..68bb0f3e56bf 100755####################################################################### HISTORYdiff --git a/bsd/conf/files b/bsd/conf/files-index 44274016a4cf..4ca9899feb85 100644+index 44274016a4cf..fb5e9cb8a444 100644--- a/bsd/conf/files+++ b/bsd/conf/files-@@ -109,6 +109,20 @@ bsd/dev/munge.c optional config_requires_u32_munging+@@ -109,6 +109,21 @@ bsd/dev/munge.c optional config_requires_u32_mungingbsd/dev/unix_startup.c standardbsd/dev/monotonic.c optional monotonic@@ -57,6 +57,7 @@ index 44274016a4cf..4ca9899feb85 100644+bsd/dev/redwood_virtio_input.c standard+bsd/dev/redwood_goodix.c standard+bsd/dev/redwood_buttons.c standard++bsd/dev/redwood_battery.c standard+bsd/dev/redwood_net.c standard+bsd/dev/redwood_virtio_net.c standard+bsd/dev/redwood_apple80211.c standard@@ -70,7 +71,7 @@ index 44274016a4cf..4ca9899feb85 100644bsd/dev/dev_perfmon.c optional config_perfmonbsd/libkern/crc32.c standard-@@ -155,6 +169,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfs+@@ -155,6 +170,10 @@ bsd/miscfs/devfs/devfs_vfsops.c optional devfsbsd/miscfs/mockfs/mockfs_fsnode.c optional mockfsbsd/miscfs/mockfs/mockfs_vfsops.c optional mockfsbsd/miscfs/mockfs/mockfs_vnops.c optional mockfs@@ -81,7 +82,7 @@ index 44274016a4cf..4ca9899feb85 100644bsd/miscfs/routefs/routefs_ops.c optional routefs-@@ -361,6 +379,7 @@ bsd/security/audit/audit_syscalls.c standard+@@ -361,6 +380,7 @@ bsd/security/audit/audit_syscalls.c standardbsd/security/audit/audit_worker.c optional config_auditbsd/pthread/pthread_shims.c standard@@ -89,7 +90,7 @@ index 44274016a4cf..4ca9899feb85 100644bsd/pthread/pthread_priority.c standardbsd/pthread/pthread_workqueue.c standard-@@ -383,6 +402,7 @@ bsd/kern/kern_debug.c standard+@@ -383,6 +403,7 @@ bsd/kern/kern_debug.c standardbsd/kern/kern_symfile.c standardbsd/kern/kern_descrip.c standardbsd/kern/kern_guarded.c standard@@ -2530,3 +2531,23 @@ index 97028c06bb92..0daad830d0c0 100644uio_t auio;int error;+diff --git a/tools/lldbmacros/core/syntax_checker.py b/tools/lldbmacros/core/syntax_checker.py+index 3ebc295117a3..de101eafc83b 100755+--- a/tools/lldbmacros/core/syntax_checker.py++++ b/tools/lldbmacros/core/syntax_checker.py+@@ -12,10 +12,13 @@ Usage:+ """+ import sys+ import os++# When this file is executed directly, its directory is first on sys.path.++# That directory contains collections.py, which shadows Python's standard++# library collections module while importing re on Python 3.14 and newer.++_script_dir = os.path.dirname(os.path.abspath(__file__))++sys.path = [p for p in sys.path if os.path.abspath(p or os.curdir) != _script_dir]+ import re+-+ tabs_search_rex = re.compile("^\s*\t+",re.MULTILINE|re.DOTALL)+-+ def find_non_ascii(s):+ for c in s:+ if ord(c) >= 0x80: return True