From bfb41e6ea0a9818507f893e7ef2f54af4767813b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:51 +0100 Subject: [PATCH 01/43] ARM: apple: Support the S5L8950X (A6) and its Swift cores MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The A6 (S5L8950X, iPhone 5) has two Apple Swift ARMv7s cores, the A5's PMGR core control and the same AIC. Add it to the S5L machine: - apple.c: match "apple,s5l8950x". The A5 boards' memblock carve-out under iBoot's scanout (0x9f600000..0x9f6fc000) is skipped on the A6, where that address is ordinary RAM; the A6 boards reserve their scanout in the DT. - headsmp.S: run the Cortex-A9 errata fixups and the SCU tag invalidation only on a Cortex-A9 (MIDR part 0xc09). Swift has an integrated L2 and no A9 SCU, CBAR or diagnostic register. - platsmp.c: look up "apple,s5l8950x-pmgr" first. Its core control registers sit at the A5's offsets (+0x1210 stop, +0x1214 start, +0x1220 run; iOS 8.4.1 AppleS5L8950XPerformanceController). On a core that is not a Cortex-A9, power down by switching the D-cache off and cleaning L1, without the A9's ACTLR.SMP write. The A5 boards run the same code as before. Tested on an iPhone5,2: both cores come up and the USB shell is reached. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/mach-apple/apple.c | 5 +++++ arch/arm/mach-apple/headsmp.S | 14 +++++++++++-- arch/arm/mach-apple/platsmp.c | 39 ++++++++++++++++++++++++++++------- 3 files changed, 48 insertions(+), 10 deletions(-) diff --git a/arch/arm/mach-apple/apple.c b/arch/arm/mach-apple/apple.c index 647bfecf9fc315..044d64d9a78c82 100644 --- a/arch/arm/mach-apple/apple.c +++ b/arch/arm/mach-apple/apple.c @@ -29,6 +29,10 @@ static void __init apple_s5l_reserve(void) { phys_addr_t phys = P105_FB_PHYS & ~(SZ_1M - 1); + /* The A6 boards describe iBoot's scanout in reserved-memory. */ + if (of_machine_is_compatible("apple,s5l8950x")) + return; + memblock_remove(phys, P105_FB_PHYS - phys); } @@ -121,6 +125,7 @@ static void __init apple_s5l_init_time(void) static const char * const apple_s5l_dt_compat[] __initconst = { "apple,s5l8940x", "apple,s5l8942x", + "apple,s5l8950x", NULL }; diff --git a/arch/arm/mach-apple/headsmp.S b/arch/arm/mach-apple/headsmp.S index 50cc1d53b2e57d..56c6d4221e255d 100644 --- a/arch/arm/mach-apple/headsmp.S +++ b/arch/arm/mach-apple/headsmp.S @@ -13,9 +13,15 @@ * Invalidate this core's duplicate tags in the SCU (SCU + 0x0c, four bits * per core), as iBoot does when it resets a core: nothing the SCU remembers * about this core's L1 from before the power went is true any more. + * Cortex-A9 only (Apple Swift has an integrated L2 and no A9 SCU/CBAR). * Corrupts r0-r2. */ apple_s5l_scu_inv_self: + mrc p15, 0, r0, c0, c0, 0 @ MIDR + ubfx r1, r0, #4, #12 @ primary part number + movw r2, #0xc09 @ ARM_CPU_PART_CORTEX_A9 >> 4 + cmp r1, r2 + retne lr mrc p15, 4, r0, c15, c0, 0 @ CBAR: the SCU mrc p15, 0, r1, c0, c0, 5 @ MPIDR and r1, r1, #3 @@ -29,11 +35,15 @@ apple_s5l_scu_inv_self: /* * Cortex-A9 errata 743622 (r2p*, diagnostic bit 6) and 751472 (before r3p0, * bit 11), which multi_v7 leaves out: the diagnostic register is secure-only, - * and this kernel runs secure. apple.c does the same for CPU0. Corrupts - * r0-r2. + * and this kernel runs secure. apple.c does the same for CPU0. Skipped on + * non-A9 cores such as Apple Swift. Corrupts r0-r2. */ apple_s5l_a9_errata: mrc p15, 0, r0, c0, c0, 0 @ MIDR + ubfx r1, r0, #4, #12 @ primary part number + movw r2, #0xc09 @ ARM_CPU_PART_CORTEX_A9 >> 4 + cmp r1, r2 + retne lr ubfx r1, r0, #20, #4 @ variant mrc p15, 0, r2, c15, c0, 1 @ diagnostic register cmp r1, #2 diff --git a/arch/arm/mach-apple/platsmp.c b/arch/arm/mach-apple/platsmp.c index 6245ac72c0bf9b..1e2d89aed8fe98 100644 --- a/arch/arm/mach-apple/platsmp.c +++ b/arch/arm/mach-apple/platsmp.c @@ -96,17 +96,38 @@ static void tramp_target(phys_addr_t pa) dsb(st); } -/* On the core going down: clean L1, leave coherency, WFI. Returns only if - * the core was not powered off after all (an interrupt already pending). */ +/* On the core going down: clean L1, leave coherency (on Cortex-A9), WFI. + * Returns only if the core was not powered off after all (an interrupt already + * pending). Apple Swift (S5L8950X) does not use Cortex-A9 ACTLR.SMP bit 6. */ static int apple_s5l_powerdown(unsigned long arg) { - v7_exit_coherency_flush(louis); - wfi(); + if (read_cpuid_part() == ARM_CPU_PART_CORTEX_A9) { + v7_exit_coherency_flush(louis); + wfi(); + asm volatile( + " mrc p15, 0, r0, c1, c0, 1\n" + " orr r0, r0, #(1 << 6)\n" /* ACTLR.SMP */ + " mcr p15, 0, r0, c1, c0, 1\n" + " isb\n" + " mrc p15, 0, r0, c1, c0, 0\n" + " orr r0, r0, #(1 << 2)\n" /* SCTLR.C */ + " mcr p15, 0, r0, c1, c0, 0\n" + " isb\n" + : : : "r0", "memory"); + return 1; + } + asm volatile( - " mrc p15, 0, r0, c1, c0, 1\n" - " orr r0, r0, #(1 << 6)\n" /* ACTLR.SMP */ - " mcr p15, 0, r0, c1, c0, 1\n" + " mrc p15, 0, r0, c1, c0, 0\n" + " bic r0, r0, #(1 << 2)\n" /* SCTLR.C */ + " mcr p15, 0, r0, c1, c0, 0\n" " isb\n" + " bl v7_flush_dcache_louis\n" + " dsb\n" + : : : "r0", "r1", "r2", "r3", "r4", "r5", "r6", + "r9", "r10", "ip", "lr", "memory"); + wfi(); + asm volatile( " mrc p15, 0, r0, c1, c0, 0\n" " orr r0, r0, #(1 << 2)\n" /* SCTLR.C */ " mcr p15, 0, r0, c1, c0, 0\n" @@ -144,7 +165,9 @@ static void __init apple_smp_prepare_cpus(unsigned int max_cpus) of_node_put(page); of_node_put(cpus); - pmgr = of_find_compatible_node(NULL, NULL, "apple,s5l8940x-pmgr"); + pmgr = of_find_compatible_node(NULL, NULL, "apple,s5l8950x-pmgr"); + if (!pmgr) + pmgr = of_find_compatible_node(NULL, NULL, "apple,s5l8940x-pmgr"); if (pmgr) pmgr_base = of_iomap(pmgr, 0); of_node_put(pmgr); From 90b5ca3efa6a9b16cd7fadd92733339f98d5ce14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:51 +0100 Subject: [PATCH 02/43] ARM: apple: Skip the cycle counter and PMU tick on cores without an ARM PMU MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The A6's Swift cores are Apple's own (MIDR 0x613f0001, implementer 'a') and have no ARM PMU. time_init enabled the Cortex-A9 cycle counter unconditionally, and its first CP15 c9 write (PMUSERENR) was an undefined instruction: the iPhone 5 panicked at time 0 ("Attempted to kill the idle task"). Use the cycle counter, its calibration and the PMU overflow tick only on a Cortex-A9 (the A5). Other cores get the 24 MHz watchdog counter as clocksource and sched_clock, and the AIC timer as the tick. The USB SOF tick no longer reads the cycle counter before its checks. With this the iPhone 5 boots to /init in 5.4 s. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/mach-apple/apple.c | 15 +++++++++++++++ arch/arm/mach-apple/apple_sof_clkevt.c | 10 +++++++++- arch/arm/mach-apple/pmccntr.c | 11 +++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/arch/arm/mach-apple/apple.c b/arch/arm/mach-apple/apple.c index 044d64d9a78c82..9ff189c6bd5daa 100644 --- a/arch/arm/mach-apple/apple.c +++ b/arch/arm/mach-apple/apple.c @@ -17,6 +17,7 @@ #include void __init apple_s5l_pmccntr_enable_counter(void); +bool apple_s5l_has_pmccntr(void); void __init apple_s5l_pmccntr_init(unsigned long rate); unsigned long __init apple_s5l_calibrate_cpu_hz(void); void __init apple_s5l_wdt_clocksource_init(void); @@ -104,6 +105,20 @@ static void __init apple_s5l_init_time(void) { unsigned long cpu_hz; + /* + * The A6's Swift cores are Apple's own (MIDR implementer 'a', 0x613f0001 + * on the iPhone 5) and have no ARM PMU: the first CP15 c9 write is an + * undefined instruction, and Linux died on it in time_init. They get the + * 24 MHz watchdog counter only (clocksource, sched_clock); the tick + * comes from the AIC timer. + */ + if (!apple_s5l_has_pmccntr()) { + pr_info("No ARM PMU on this core (MIDR %#x): no cycle counter, no PMU tick\n", + read_cpuid_id()); + apple_s5l_wdt_clocksource_init(); + return; + } + /* Enable the cycle counter first, then measure it against the watchdog's * exact 24 MHz reference, and only then register the clocksource -- its * rate used to be a hardcoded 1 GHz guess, which made all wall-clock time diff --git a/arch/arm/mach-apple/apple_sof_clkevt.c b/arch/arm/mach-apple/apple_sof_clkevt.c index 6c4b4694810922..5dc3b35243e941 100644 --- a/arch/arm/mach-apple/apple_sof_clkevt.c +++ b/arch/arm/mach-apple/apple_sof_clkevt.c @@ -53,6 +53,8 @@ #include #include +bool apple_s5l_has_pmccntr(void); /* pmccntr.c */ + /* One SOF per 125 us microframe at high speed. */ #define SOF_TICK_HZ 8000 @@ -171,13 +173,19 @@ static struct clock_event_device sof_clkevt = { static int __init apple_sof_clkevt_register(void) { unsigned int before = READ_ONCE(sof_seen); - u32 start = pmccntr(); unsigned long cpu_hz = 1000000000UL; /* only used to size the spin */ + u32 start; if (sof_superseded) { pr_err("SOF-TIMER: not needed -- the AIC timer is the tick, SOF interrupts stay off.\n"); return 0; } + /* The spin below counts CPU cycles; the A6 has no cycle counter */ + if (!apple_s5l_has_pmccntr()) { + pr_err("SOF-TIMER: no cycle counter on this core, not registering\n"); + return 0; + } + start = pmccntr(); while ((u32)(pmccntr() - start) < cpu_hz * 2) { /* up to ~2 s */ if (READ_ONCE(sof_seen) != before) diff --git a/arch/arm/mach-apple/pmccntr.c b/arch/arm/mach-apple/pmccntr.c index dc1e349453b28b..d53f5b88c5e846 100644 --- a/arch/arm/mach-apple/pmccntr.c +++ b/arch/arm/mach-apple/pmccntr.c @@ -15,6 +15,7 @@ #include #include +#include #include /* Fallback only. apple_s5l_pmccntr_init() is handed the rate measured against @@ -85,6 +86,16 @@ static void __init apple_pmccntr_enable(void) isb(); } +/* + * Only the A5's Cortex-A9 has the ARM PMU and so this counter. The A6's + * Swift cores (implementer 'a') take an undefined instruction on any CP15 + * c9 PMU access. + */ +bool apple_s5l_has_pmccntr(void) +{ + return read_cpuid_part() == ARM_CPU_PART_CORTEX_A9; +} + /* Split in two so the caller can enable the counter, measure the real CPU * frequency against the watchdog's 24 MHz reference, and only then register * everything with a rate that is not a guess. */ From 8823999516696fc239ed4ed3c68e414deb5b7c72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:51 +0100 Subject: [PATCH 03/43] ARM: apple: Run the S5L8950X watchdog counter and restart through it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three differences on the A6 watchdog: - WDT_CUR_TIME only counts while WDT_CTRL bit 3 (enable) is set. If the boot loader left CTRL at 0, set bit 3 without the reset enable, so the counter runs; a watchdog the boot loader armed (0xc) is left alone. The calibration loop is bounded, so a counter that never moves cannot hang the boot. - A reset needs enable and reset enable together (0xc), programmed the way iBEC's wdt_enable() does: CTRL 0, bite time, count, CTRL 0xc, count 0. The restart handler and the reboot notifier do that on the S5L8950X. - The A6 skips the CPU calibration (no cycle counter), which was the only place that mapped the counter, so the clocksource found nothing mapped and the phone ran on jiffies. Map the counter in a helper that both call. The A5 boards keep their sequence. Tested on an iPhone5,2: the watchdog counter is the clocksource, and panic=10 and reboot reset the phone through the watchdog. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/mach-apple/apple_wdt_clkevt.c | 91 ++++++++++++++++++++------ 1 file changed, 71 insertions(+), 20 deletions(-) diff --git a/arch/arm/mach-apple/apple_wdt_clkevt.c b/arch/arm/mach-apple/apple_wdt_clkevt.c index bd58731f7ceaec..6863ba9ba95481 100644 --- a/arch/arm/mach-apple/apple_wdt_clkevt.c +++ b/arch/arm/mach-apple/apple_wdt_clkevt.c @@ -56,6 +56,7 @@ #define WDT_BITE_TIME 0x04 #define WDT_CTRL 0x0c #define WDT_CTRL_RESET_EN BIT(2) +#define WDT_CTRL_ENABLE BIT(3) #define APPLE_WDT_REF_HZ 24000000UL static inline u32 apple_pmccntr(void) @@ -110,6 +111,47 @@ static struct delay_timer apple_wdt_delay = { .freq = APPLE_WDT_REF_HZ, }; +/* + * Map the watchdog's 24 MHz counter (once). The A5 does this from the CPU + * calibration; the A6 has no cycle counter to calibrate, so its clocksource + * init maps it here directly. + */ +static bool __init apple_wdt_map(void) +{ + struct device_node *np; + + if (wdt_base) + return true; + np = of_find_compatible_node(NULL, NULL, "apple,s5l8940x-wdt-timer"); + if (!np) { + pr_err("no wdt node\n"); + return false; + } + + wdt_base = of_iomap(np, 0); + of_node_put(np); + if (!wdt_base) { + pr_err("cannot map wdt counter\n"); + return false; + } + + /* + * On S5L8950X (A6), WDT_CUR_TIME only ticks while WDT_CTRL_ENABLE (bit 3) + * is set. If the bootloader left CTRL=0 (no watchdog armed), enable the + * counter without RESET_EN so calibration and the clocksource tick; if + * a boot watchdog is already armed (0xc), leave it intact. + */ + if (of_machine_is_compatible("apple,s5l8950x")) { + u32 ctrl = readl_relaxed(wdt_base + WDT_CTRL); + + if (!(ctrl & WDT_CTRL_ENABLE)) { + writel(ctrl | WDT_CTRL_ENABLE, wdt_base + WDT_CTRL); + (void)readl(wdt_base + WDT_CTRL); + } + } + return true; +} + /** * apple_s5l_wdt_clocksource_init - wall time that survives idle * @@ -119,7 +161,7 @@ static struct delay_timer apple_wdt_delay = { */ void __init apple_s5l_wdt_clocksource_init(void) { - if (!wdt_base) { + if (!apple_wdt_map()) { pr_err("CS: counter not mapped, wall time stays on PMCCNTR (wrong in idle)\n"); return; } @@ -138,28 +180,22 @@ void __init apple_s5l_wdt_clocksource_init(void) */ unsigned long __init apple_s5l_calibrate_cpu_hz(void) { - struct device_node *np; u32 w0, w1, c0, c1, wd, cd; u64 hz; - np = of_find_compatible_node(NULL, NULL, "apple,s5l8940x-wdt-timer"); - if (!np) { - pr_err("CALIB: no wdt node; CPU rate stays a guess\n"); + if (!apple_wdt_map()) return 0; - } - - wdt_base = of_iomap(np, 0); - of_node_put(np); - if (!wdt_base) { - pr_err("CALIB: cannot map wdt counter\n"); - return 0; - } /* ~50 ms of reference ticks is plenty and costs nothing at boot. */ w0 = readl_relaxed(wdt_base + WDT_CUR_TIME); c0 = apple_pmccntr(); - while ((u32)(readl_relaxed(wdt_base + WDT_CUR_TIME) - w0) < APPLE_WDT_REF_HZ / 20) - cpu_relax(); + { + u32 guard = 0; + + while ((u32)(readl_relaxed(wdt_base + WDT_CUR_TIME) - w0) < APPLE_WDT_REF_HZ / 20 && + ++guard < 50000000U) + cpu_relax(); + } w1 = readl_relaxed(wdt_base + WDT_CUR_TIME); c1 = apple_pmccntr(); /* deliberately not unmapped: the clocksource lives on this counter */ @@ -191,11 +227,24 @@ unsigned long __init apple_s5l_calibrate_cpu_hz(void) */ static int apple_wdt_restart(struct sys_off_data *data) { - u32 now = readl_relaxed(wdt_base + WDT_CUR_TIME); + if (of_machine_is_compatible("apple,s5l8950x")) { + /* + * S5L8950X (A6) requires both WDT_CTRL_ENABLE and WDT_CTRL_RESET_EN + * (0xc), following iBEC's wdt_enable() sequence. + */ + writel(0, wdt_base + WDT_CTRL); + writel(APPLE_WDT_REF_HZ / 1000, wdt_base + WDT_BITE_TIME); + writel(0x80000000U, wdt_base + WDT_CUR_TIME); + writel(WDT_CTRL_ENABLE | WDT_CTRL_RESET_EN, wdt_base + WDT_CTRL); + writel(0, wdt_base + WDT_CUR_TIME); + (void)readl(wdt_base + WDT_CTRL); + } else { + u32 now = readl_relaxed(wdt_base + WDT_CUR_TIME); - writel_relaxed(now + APPLE_WDT_REF_HZ / 1000, wdt_base + WDT_BITE_TIME); - writel(WDT_CTRL_RESET_EN, wdt_base + WDT_CTRL); - (void)readl(wdt_base + WDT_CTRL); + writel_relaxed(now + APPLE_WDT_REF_HZ / 1000, wdt_base + WDT_BITE_TIME); + writel(WDT_CTRL_RESET_EN, wdt_base + WDT_CTRL); + (void)readl(wdt_base + WDT_CTRL); + } mdelay(500); pr_emerg("the watchdog did not reset the machine\n"); return NOTIFY_DONE; @@ -212,9 +261,11 @@ static int apple_wdt_reboot_notify(struct notifier_block *nb, unsigned long acti { if (action == SYS_RESTART) { u32 now = readl_relaxed(wdt_base + WDT_CUR_TIME); + u32 ctrl = of_machine_is_compatible("apple,s5l8950x") ? + (WDT_CTRL_ENABLE | WDT_CTRL_RESET_EN) : WDT_CTRL_RESET_EN; writel_relaxed(now + 10 * APPLE_WDT_REF_HZ, wdt_base + WDT_BITE_TIME); - writel(WDT_CTRL_RESET_EN, wdt_base + WDT_CTRL); + writel(ctrl, wdt_base + WDT_CTRL); pr_info("restart: the watchdog will reset the machine in 10 s at the latest\n"); } return NOTIFY_DONE; From c4229ae52837d1e6a562da728e13bf70bb3a02fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:52 +0100 Subject: [PATCH 04/43] irqchip/apple-aic1: Give each A6 core its own AIC timer tick MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On the iPhone 5 the only clockevent was the AIC timer of CPU0. CPU1 got the dummy clockevent, and with no broadcast device it never ticked: with idle=poll RCU stalled on it ("timer wakeup didn't happen"), and with WFI idle the whole system froze at about 10.8 s, the first time something waited for a timer on CPU1. The AIC timer is a per-core register: the 0x2000 window is banked by the accessing core, like WHOAMI, EVENT/IACK and IPI_SEND, and the timer fires as a local event (type 7) in that core's EVENT. iOS 10.3.4 on the N42 does not use it (XNU ticks each core from the Swift generic timer), but iBoot runs on it, and so does Linux on CPU0. On the A6, once a secondary core is online (CPUHP_AP_ONLINE_DYN, interrupts on), arm a 10 ms shot in its banked window, then in its explicit window (0x5000 + (cpu << 7)), and wait up to 200 ms of AIC timebase for the event on that core. The first window that fires becomes the core's oneshot clockevent, rating 400, which replaces the dummy. A failed test disarms through the core's explicit window only, so it cannot stop CPU0's tick, and logs FAIL. Per-CPU timer event counts are in /sys/module/aic1/parameters/timer_events. There is no offline teardown: going offline, the core's timer stays its tick device until the tick code lets go of it, and apple_aic1_secondary_init() quiesces the window before the core comes back. The A5 (P105, J1) keeps its PMU tick and CPU0-only AIC timer: the online state is installed only on "apple,s5l8950x". Tested on an iPhone5,2: "PASS -- CPU1 has its own clockevent", and a two-core boot reaches the USB shell with no nohlt or irqaffinity. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/irqchip/irq-apple-aic1.c | 187 ++++++++++++++++++++++++++++--- 1 file changed, 174 insertions(+), 13 deletions(-) diff --git a/drivers/irqchip/irq-apple-aic1.c b/drivers/irqchip/irq-apple-aic1.c index f6fda81687d418..31219f99f7f3e0 100644 --- a/drivers/irqchip/irq-apple-aic1.c +++ b/drivers/irqchip/irq-apple-aic1.c @@ -774,8 +774,33 @@ static bool aic1_tmr_registered; static bool aic1_tmr_percpu; static DEFINE_PER_CPU(struct clock_event_device, aic1_clkevts); +/* + * The timer is one of the per-core registers of the AIC: the window at 0x2000 + * is banked by the core that accesses it (WHOAMI, the EVENT/IACK and the IPI + * registers are, and IPI_SEND there already tells the two cores apart), and + * its timer event is a local event (type 7) in that core's own EVENT. So each + * core has a timer of its own, and the A6's CPU1 is given its own (see + * aic1_tmr_cpu_online). A window picked for one CPU overrides the global + * choice; 0 means none picked. + */ +static DEFINE_PER_CPU(u32, aic1_tmr_cpu_win); +/* The window a CPU's own self-test saw fire, kept across CPU hotplug. */ +static u32 aic1_tmr_cpu_ok[AIC1_NR_CPUS]; +static u64 aic1_tmr_cpu_last[AIC1_NR_CPUS]; + +/* Timer events taken per CPU: /sys/module/aic1/parameters/timer_events. + * Both counts must grow; CPU1's staying at 0 means CPU1 has no tick. */ +#undef MODULE_PARAM_PREFIX +#define MODULE_PARAM_PREFIX "aic1." +static unsigned int timer_events[AIC1_NR_CPUS]; +module_param_array(timer_events, uint, NULL, 0444); + static inline u32 aic1_tmr_base(void) { + u32 win = this_cpu_read(aic1_tmr_cpu_win); + + if (win) + return win; return aic1_tmr_percpu ? AIC1_CPU_WINDOW(smp_processor_id()) : aic1_tmr_win; } @@ -829,8 +854,14 @@ static void aic1_tmr_arm(struct apple_aic1 *aic, u32 delta) */ static void aic1_tmr_event(struct apple_aic1 *aic) { + unsigned int cpu = smp_processor_id(); + aic1_tmr_events++; aic1_tmr_last = aic1_time(aic); + if (cpu < AIC1_NR_CPUS) { + aic1_tmr_cpu_last[cpu] = aic1_tmr_last; + WRITE_ONCE(timer_events[cpu], timer_events[cpu] + 1); + } aic1_tmr_disarm(aic); if (aic1_tmr_registered) { @@ -854,6 +885,23 @@ static int aic1_ce_shutdown(struct clock_event_device *ce) return 0; } +/* The CPU's own clockevent, registered on that CPU. */ +static void aic1_tmr_register_ce(unsigned int cpu) +{ + struct clock_event_device *ce = per_cpu_ptr(&aic1_clkevts, cpu); + + ce->name = "apple-aic1-timer"; + ce->features = CLOCK_EVT_FEAT_ONESHOT; + /* Above the USB SOF tick (250), which stays registered as a spare. */ + ce->rating = 400; + ce->set_next_event = aic1_ce_set_next_event; + ce->set_state_shutdown = aic1_ce_shutdown; + ce->set_state_oneshot = aic1_ce_shutdown; + ce->tick_resume = aic1_ce_shutdown; + ce->cpumask = cpumask_of(cpu); + clockevents_config_and_register(ce, AIC1_TIMER_HZ, 0xf, 0x7fffffff); +} + /* * CPU hotplug STARTING, on the CPU itself with interrupts off: its window's * timer set up the way the probe found it working, and its clockevent. @@ -862,23 +910,13 @@ static int aic1_ce_shutdown(struct clock_event_device *ce) */ static int aic1_tmr_cpu_starting(unsigned int cpu) { - struct clock_event_device *ce = per_cpu_ptr(&aic1_clkevts, cpu); struct apple_aic1 *aic = apple_aic1; if (cpu) { aic1_tmr_write(aic, AIC1_TMR_CFG, AIC1_TMR_CFG_IBOOT); aic1_tmr_disarm(aic); } - ce->name = "apple-aic1-timer"; - ce->features = CLOCK_EVT_FEAT_ONESHOT; - /* Above the USB SOF tick (250), which stays registered as a spare. */ - ce->rating = 400; - ce->set_next_event = aic1_ce_set_next_event; - ce->set_state_shutdown = aic1_ce_shutdown; - ce->set_state_oneshot = aic1_ce_shutdown; - ce->tick_resume = aic1_ce_shutdown; - ce->cpumask = cpumask_of(cpu); - clockevents_config_and_register(ce, AIC1_TIMER_HZ, 0xf, 0x7fffffff); + aic1_tmr_register_ce(cpu); return 0; } @@ -888,6 +926,124 @@ static int aic1_tmr_cpu_dying(unsigned int cpu) return 0; } +#ifdef CONFIG_SMP +/* + * On a secondary CPU, from its own hotplug thread with interrupts on: put + * this CPU's timer in @win, arm a 10 ms shot and wait up to 200 ms of AIC + * timebase for the event to come back to THIS CPU (timer_events[cpu]). An + * event that went to the other core instead is only an early tick there. + */ +static bool aic1_tmr_cpu_try(struct apple_aic1 *aic, unsigned int cpu, u32 win, + const char *what) +{ + unsigned int before = READ_ONCE(timer_events[cpu]); + unsigned int other = READ_ONCE(timer_events[!cpu]); + u32 cfg0, cnt_a, cnt_b; + u64 t0, t; + + this_cpu_write(aic1_tmr_cpu_win, win); + cfg0 = aic1_tmr_read(aic, AIC1_TMR_CFG); + aic1_tmr_write(aic, AIC1_TMR_CFG, AIC1_TMR_CFG_IBOOT); + + t0 = aic1_time(aic); + aic1_tmr_arm(aic, AIC1_TIMER_HZ / 100); + cnt_a = aic1_tmr_read(aic, AIC1_TMR_CNT); + do { + if (READ_ONCE(timer_events[cpu]) != before) + break; + cpu_relax(); + t = aic1_time(aic); + } while (t - t0 < AIC1_TIMER_HZ / 5); + cnt_b = aic1_tmr_read(aic, AIC1_TMR_CNT); + + if (READ_ONCE(timer_events[cpu]) != before) { + pr_info("AIC-TIMER: CPU%u %s window %#x: a 10 ms shot fired on CPU%u after %llu us\n", + cpu, what, win, cpu, + div_u64((aic1_tmr_cpu_last[cpu] - t0) * 1000000ULL, + AIC1_TIMER_HZ)); + return true; + } + + pr_err("AIC-TIMER: CPU%u %s window %#x: nothing on CPU%u in 200 ms (CPU%u took %u timer events meanwhile). CFG was %#x, CNT %#x -> %#x, STAT %#x\n", + cpu, what, win, cpu, !cpu, READ_ONCE(timer_events[!cpu]) - other, + cfg0, cnt_a, cnt_b, aic1_tmr_read(aic, AIC1_TMR_STAT)); + /* Stop it through the window that is this CPU's for certain. Not + * through @win: if the banked window turned out to reach CPU0's timer, + * a disarm there would kill CPU0's tick, while the shot it got was + * only an early tick that CPU0 has re-armed since. */ + this_cpu_write(aic1_tmr_cpu_win, AIC1_CPU_WINDOW(cpu)); + aic1_tmr_disarm(aic); + this_cpu_write(aic1_tmr_cpu_win, 0); + return false; +} + +/* + * CPU hotplug ONLINE (dynamic state), A6 only, on a secondary CPU: give it + * the AIC timer of its own core as its tick. Until this runs the CPU has + * only the dummy clockevent, and with no broadcast device on this SoC a CPU + * left like that never ticks: RCU stalls on it with idle=poll, and in WFI + * the first wait for it hangs the system. The timer is tested before it is + * trusted, through the banked window first (the one CPU0 runs on), then the + * CPU's explicit window. + */ +static int aic1_tmr_cpu_online(unsigned int cpu) +{ + struct apple_aic1 *aic = apple_aic1; + u32 win; + + if (!cpu || cpu >= AIC1_NR_CPUS || !aic) + return 0; + + win = aic1_tmr_cpu_ok[cpu]; + if (!win) { + if (aic1_tmr_cpu_try(aic, cpu, AIC1_ALIAS_WINDOW, "banked")) + win = AIC1_ALIAS_WINDOW; + else if (aic1_tmr_cpu_try(aic, cpu, AIC1_CPU_WINDOW(cpu), "explicit")) + win = AIC1_CPU_WINDOW(cpu); + } + if (!win) { + pr_err("AIC-TIMER: FAIL -- CPU%u: its own AIC timer never fired; CPU%u has no tick (expect RCU stalls; boot with maxcpus=1)\n", + cpu, cpu); + return 0; + } + + aic1_tmr_cpu_ok[cpu] = win; + this_cpu_write(aic1_tmr_cpu_win, win); + aic1_tmr_write(aic, AIC1_TMR_CFG, AIC1_TMR_CFG_IBOOT); + aic1_tmr_disarm(aic); + aic1_tmr_register_ce(cpu); + pr_info("AIC-TIMER: PASS -- CPU%u has its own clockevent (window %#x)\n", + cpu, win); + return 0; +} + +/* + * No teardown: going offline, the CPU's timer is still its tick device until + * the tick code lets go of it, and apple_aic1_secondary_init() quiesces the + * window before the CPU comes back. + */ +static bool __init aic1_tmr_setup_secondaries(void) +{ + int ret; + + /* The A5 keeps its PMU tick and CPU0-only AIC timer as they were. */ + if (num_possible_cpus() < 2 || !of_machine_is_compatible("apple,s5l8950x")) + return false; + + ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, + "irqchip/apple-aic1/timer:online", + aic1_tmr_cpu_online, NULL); + if (ret < 0) { + pr_err("AIC-TIMER: no hotplug state for the secondary timers (%d)\n", + ret); + return false; + } + return true; +} +#else +static inline bool aic1_tmr_setup_secondaries(void) { return false; } +#endif + /* * Arm a 10 ms shot in one window and wait up to 200 ms of timebase for the * event to come back through the dispatcher. IRQs are on before any initcall; @@ -941,6 +1097,7 @@ static bool aic1_tmr_tried __initdata; static int __init aic1_timer_init(void) { struct apple_aic1 *aic = apple_aic1; + bool secondaries = false; if (!aic || aic1_tmr_tried) return 0; @@ -963,8 +1120,10 @@ static int __init aic1_timer_init(void) "irqchip/apple-aic1/timer:starting", aic1_tmr_cpu_starting, aic1_tmr_cpu_dying); } else { - /* The alias fired: one timer, CPU0's. */ + /* The banked window fired: CPU0's timer. On the A6 each further + * CPU tests and takes its own as it comes online. */ aic1_tmr_cpu_starting(0); + secondaries = aic1_tmr_setup_secondaries(); } #ifdef CONFIG_ARCH_APPLE_S5L { @@ -976,7 +1135,9 @@ static int __init aic1_timer_init(void) } #endif pr_err("AIC-TIMER: PASS -- clockevent registered at 24 MHz, %s. The tick no longer needs a USB host.\n", - aic1_tmr_percpu ? "one per CPU" : "CPU0 only"); + aic1_tmr_percpu ? "one per CPU" : + secondaries ? "CPU0 now, each other CPU its own once online" : + "CPU0 only"); return 0; } From 9dda332e69038eb81b27c725207b80ed9d8697cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:52 +0100 Subject: [PATCH 05/43] irqchip/apple-aic1: Report device IRQs as CPU0-only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit aic1_irq_unmask() routes every line to CPU0 (TARGET = BIT(0)) and the chip has no irq_set_affinity, so no device interrupt ever reaches another core. The IRQ core did not know that: /proc/irq/N claimed affinity 0-1, and irqaffinity=0 on the command line only changed what it claimed. Set the affinity and effective affinity of each line to CPU0 when it is mapped, mark it single-target and exclude it from balancing. Routing is unchanged, on the A5 as well; irqaffinity=0 is no longer needed. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/irqchip/irq-apple-aic1.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/drivers/irqchip/irq-apple-aic1.c b/drivers/irqchip/irq-apple-aic1.c index 31219f99f7f3e0..71e0f3cb1a799b 100644 --- a/drivers/irqchip/irq-apple-aic1.c +++ b/drivers/irqchip/irq-apple-aic1.c @@ -559,6 +559,20 @@ static int aic1_irq_domain_map(struct irq_domain *d, unsigned int virq, NULL, NULL); irq_set_probe(virq); + /* Every line is routed to CPU0 (aic1_irq_unmask writes TARGET = CPU0) + * and the chip has no irq_set_affinity, so say so: affinity and + * effective affinity CPU0, and no balancing. /proc/irq/N then tells + * the truth, irqaffinity= is not needed, and nothing expects a + * device interrupt on CPU1. */ + { + struct irq_data *irqd = irq_get_irq_data(virq); + + irqd_set_single_target(irqd); + irq_data_update_affinity(irqd, cpumask_of(0)); + irq_data_update_effective_affinity(irqd, cpumask_of(0)); + irq_set_status_flags(virq, IRQ_NO_BALANCING); + } + return 0; } From 9e8e14ae53d519a13d88c430ad1fd22f5b6cee7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:53 +0100 Subject: [PATCH 06/43] dt-bindings: phy: apple,s5l8942x-usb-phy: Add the S5L8950X MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The A6 (S5L8950X, iPhone 5) has the A5's OTG and HSIC PHY with other PMGR offsets and tuning values, so it gets its own compatible and no S5L8940X fallback. On the S5L8950X the PHY can also take the PMGR gates of the OTG block (UPERF, USB-OTG, USBREG) as clocks, after the reference clock, and holds them from probe. Allow up to four clocks, named in that order. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- .../bindings/phy/apple,s5l8942x-usb-phy.yaml | 42 +++++++++++++++---- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/Documentation/devicetree/bindings/phy/apple,s5l8942x-usb-phy.yaml b/Documentation/devicetree/bindings/phy/apple,s5l8942x-usb-phy.yaml index b9cf8b7d2a9a2f..cc30150ab9e07c 100644 --- a/Documentation/devicetree/bindings/phy/apple,s5l8942x-usb-phy.yaml +++ b/Documentation/devicetree/bindings/phy/apple,s5l8942x-usb-phy.yaml @@ -4,7 +4,7 @@ $id: http://devicetree.org/schemas/phy/apple,s5l8942x-usb-phy.yaml# $schema: http://devicetree.org/meta-schemas/core.yaml# -title: Apple S5L8942X USB and HSIC PHY +title: Apple S5L8942X and S5L8950X USB and HSIC PHY maintainers: - Shayne Legault <8741557+shaynelegault@users.noreply.github.com> @@ -14,19 +14,28 @@ description: | and reset. The first PHY argument selects the output: 0 for USB OTG, 1 for the HSIC host. The HSIC supplies power the attached peripheral. + On the S5L8950X (A6) the PHY can also hold the PMGR power-state gates + of the OTG block (UPERF, USB-OTG and USBREG), which it switches on at + probe and never off again. Its PMGR offsets and tuning differ from the + A5's, so it has no S5L8940X fallback. + select: properties: compatible: contains: - const: apple,s5l8942x-otgphy + enum: + - apple,s5l8942x-otgphy + - apple,s5l8950x-otgphy required: - compatible properties: compatible: - items: - - const: apple,s5l8942x-otgphy - - const: apple,s5l8940x-otgphy + oneOf: + - items: + - const: apple,s5l8942x-otgphy + - const: apple,s5l8940x-otgphy + - const: apple,s5l8950x-otgphy reg: items: @@ -34,11 +43,20 @@ properties: - description: USB complex control registers clocks: - maxItems: 1 - description: PHY reference clock, at 12, 24 or 48 MHz + minItems: 1 + items: + - description: PHY reference clock, at 12, 24 or 48 MHz + - description: UPERF power-state gate + - description: USB-OTG power-state gate + - description: USBREG power-state gate clock-names: - const: ref + minItems: 1 + items: + - const: ref + - const: uperf + - const: otg + - const: usbreg '#phy-cells': const: 1 @@ -67,3 +85,11 @@ examples: clock-names = "ref"; #phy-cells = <1>; }; + - | + phy@36000000 { + compatible = "apple,s5l8950x-otgphy"; + reg = <0x36000000 0x1000>, <0x3f108000 0x1000>; + clocks = <&refclk24mhz>, <&uperf_ps>, <&usb_otg_ps>, <&usbreg_ps>; + clock-names = "ref", "uperf", "otg", "usbreg"; + #phy-cells = <1>; + }; From 1a13a00df2acb31ad4df9d6f85d412b94420fe41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:54 +0100 Subject: [PATCH 07/43] phy: apple-s5l-usb: Add the S5L8950X OTG PHY MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The A6's OTG PHY is the A5's, with its PMGR power states at other offsets: UPERF +0x1084, USB-OTG +0x1088, USB-EHCI +0x108c, USB-OHCI0 +0x1094 and USBREG +0x109c. Its tuning differs too: uotgtune1 is 0x749. Move the gate offsets and the tuning values into per-SoC match data and add "apple,s5l8950x-otgphy" (iPhone5,2 iOS 8.4.1 iBEC and ADT). The S5L8940X and S5L8942X entries carry the values the driver used before. Tested on an iPhone5,2: the dwc2 gadget comes up with CDC ACM and networking. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/phy/phy-apple-s5l-usb.c | 91 +++++++++++++++++++++++++-------- 1 file changed, 69 insertions(+), 22 deletions(-) diff --git a/drivers/phy/phy-apple-s5l-usb.c b/drivers/phy/phy-apple-s5l-usb.c index 91f50b21df104e..2de812f98e08b9 100644 --- a/drivers/phy/phy-apple-s5l-usb.c +++ b/drivers/phy/phy-apple-s5l-usb.c @@ -35,6 +35,7 @@ #define OPHY_UOTGTUNE1 0x40 #define OPHY_UOTGTUNE2 0x44 #define OPHY_UOTGTUNE1_DEVICE 0x549 +#define OPHY_UOTGTUNE1_S5L8950X_DEVICE 0x749 #define OPHY_UOTGTUNE2_DEVICE 0x2ff3 #define PMGR_BASE 0x3F100000 @@ -111,10 +112,52 @@ struct s5l_usbphy_soc_data { bool cold_init; + u32 pmgr_uperf; + u32 pmgr_usb_otg; + u32 pmgr_usbreg; + u32 pmgr_usb_ehci; + u32 pmgr_usb_ohci0; + u32 uotgtune1_device; +}; + +static const struct s5l_usbphy_soc_data s5l8940x_usbphy_data = { + .cold_init = false, + .pmgr_uperf = PMGR_UPERF, + .pmgr_usb_otg = PMGR_USB_OTG, + .pmgr_usbreg = PMGR_USBREG, + .pmgr_usb_ehci = PMGR_USB_EHCI, + .pmgr_usb_ohci0 = PMGR_USB_OHCI0, + .uotgtune1_device = OPHY_UOTGTUNE1_DEVICE, }; static const struct s5l_usbphy_soc_data s5l8942x_usbphy_data = { .cold_init = true, + .pmgr_uperf = PMGR_UPERF, + .pmgr_usb_otg = PMGR_USB_OTG, + .pmgr_usbreg = PMGR_USBREG, + .pmgr_usb_ehci = PMGR_USB_EHCI, + .pmgr_usb_ohci0 = PMGR_USB_OHCI0, + .uotgtune1_device = OPHY_UOTGTUNE1_DEVICE, +}; + +/* + * S5L8950X (Apple A6): verified from iPhone5,2 iOS 8.4.1 ADT device-clocks + * (81 entries x 44 bytes) and iBEC USB init: + * UPERF id 0x04, idx 0x21 -> PMGR + 0x1084 + * USB-OTG id 0x35, idx 0x22 -> PMGR + 0x1088 + * USB-EHCI id 0x36, idx 0x23 -> PMGR + 0x108c + * OHCI0 id 0x37, idx 0x25 -> PMGR + 0x1094 + * USBREG id 0x06, idx 0x27 -> PMGR + 0x109c + * OPHY_UOTGTUNE1 = 0x749, OPHY_UOTGTUNE2 = 0x2ff3. + */ +static const struct s5l_usbphy_soc_data s5l8950x_usbphy_data = { + .cold_init = true, + .pmgr_uperf = 0x1084, + .pmgr_usb_otg = 0x1088, + .pmgr_usbreg = 0x109c, + .pmgr_usb_ehci = 0x108c, + .pmgr_usb_ohci0 = 0x1094, + .uotgtune1_device = OPHY_UOTGTUNE1_S5L8950X_DEVICE, }; struct s5l_usbphy { @@ -173,7 +216,7 @@ static bool s5l_usbphy_is_ready(struct s5l_usbphy *p) (readl(p->base + OPHYCLK) & OPHYCLK_CLKSEL_MASK) == clksel && readl(p->base + OPHYPWR) == OPHYPWR_ACTIVE && !(readl(p->base + ORSTCON) & ORSTCON_PHYSWRESET) && - readl(p->base + OPHY_UOTGTUNE1) == OPHY_UOTGTUNE1_DEVICE && + readl(p->base + OPHY_UOTGTUNE1) == p->data->uotgtune1_device && readl(p->base + OPHY_UOTGTUNE2) == OPHY_UOTGTUNE2_DEVICE && readl(p->base + OPHYUNK4) == OPHYUNK4_START; } @@ -192,7 +235,7 @@ static int s5l_usbphy_cold_init(struct s5l_usbphy *p) writel(OPHYUNK4_START, p->base + OPHYUNK4); writel(OPHYPWR_ACTIVE, p->base + OPHYPWR); writel(OPHYUNK1_START, p->base + OPHYUNK1); - writel(OPHY_UOTGTUNE1_DEVICE, p->base + OPHY_UOTGTUNE1); + writel(p->data->uotgtune1_device, p->base + OPHY_UOTGTUNE1); writel(OPHY_UOTGTUNE2_DEVICE, p->base + OPHY_UOTGTUNE2); udelay(10); @@ -218,33 +261,33 @@ static int s5l_usbphy_init(struct phy *phy) goto out; } - if (p->data && p->data->cold_init) { + if (p->data->cold_init) { ret = clk_prepare_enable(p->refclk); if (ret) goto out; } /* Native firmware enables these parents in this order. */ - if ((readl(p->pmgr + PMGR_UPERF) & 0xff) != 0xff || - (readl(p->pmgr + PMGR_USB_OTG) & 0xff) != 0xff || - (readl(p->pmgr + PMGR_USBREG) & 0xff) != 0xff) + if ((readl(p->pmgr + p->data->pmgr_uperf) & 0xff) != 0xff || + (readl(p->pmgr + p->data->pmgr_usb_otg) & 0xff) != 0xff || + (readl(p->pmgr + p->data->pmgr_usbreg) & 0xff) != 0xff) usleep_range(10000, 11000); /* The legacy compatibles also name the A5X, whose power-state registers * are elsewhere: for them a parent that does not answer is not fatal. */ - ret = s5l_pmgr_on(p, PMGR_UPERF); - if (ret && p->data && p->data->cold_init) + ret = s5l_pmgr_on(p, p->data->pmgr_uperf); + if (ret && p->data->cold_init) goto disable_clock; - ret = s5l_pmgr_on(p, PMGR_USB_OTG); + ret = s5l_pmgr_on(p, p->data->pmgr_usb_otg); if (ret) goto disable_clock; - ret = s5l_pmgr_on(p, PMGR_USBREG); - if (ret && p->data && p->data->cold_init) + ret = s5l_pmgr_on(p, p->data->pmgr_usbreg); + if (ret && p->data->cold_init) goto disable_clock; ret = 0; udelay(100); - if (p->data && p->data->cold_init) { + if (p->data->cold_init) { if (!s5l_usbphy_is_ready(p)) { ret = s5l_usbphy_cold_init(p); if (ret) @@ -259,7 +302,7 @@ static int s5l_usbphy_init(struct phy *phy) writel(0xc, p->base + 0x14); writel(OPHYUNK1_START | OPHYUNK1_OTG_ENABLE, p->base + OPHYUNK1); writel(0xc00, p->base + 0x20); - writel(OPHY_UOTGTUNE1_DEVICE, p->base + OPHY_UOTGTUNE1); + writel(p->data->uotgtune1_device, p->base + OPHY_UOTGTUNE1); writel(OPHY_UOTGTUNE2_DEVICE, p->base + OPHY_UOTGTUNE2); writel(OPHYUNK4_START, p->base + OPHYUNK4); writel(OPHYPWR_ACTIVE, p->base + OPHYPWR); @@ -279,7 +322,7 @@ static int s5l_usbphy_init(struct phy *phy) dev_err(p->dev, "PHY reset did not clear: 0x%08x\n", v); goto disable_clock; } - if (p->data && p->data->cold_init && !s5l_usbphy_is_ready(p)) { + if (p->data->cold_init && !s5l_usbphy_is_ready(p)) { dev_err(p->dev, "PHY power or tuning did not latch\n"); ret = -EIO; goto disable_clock; @@ -288,7 +331,7 @@ static int s5l_usbphy_init(struct phy *phy) goto out; disable_clock: - if (p->data && p->data->cold_init) + if (p->data->cold_init) clk_disable_unprepare(p->refclk); out: mutex_unlock(&p->lock); @@ -406,17 +449,18 @@ static int s5l_hostphy_power_on(struct phy *phy) msleep(10); } - ret = s5l_pmgr_on(p, PMGR_USB_EHCI); + ret = s5l_pmgr_on(p, p->data->pmgr_usb_ehci); if (ret) goto err_disable_hsic; - ret = s5l_pmgr_on(p, PMGR_USB_OHCI0); + ret = s5l_pmgr_on(p, p->data->pmgr_usb_ohci0); if (ret) goto err_disable_hsic; if (p->usbcplx) writel(readl(p->usbcplx) | USBCPLX_HSIC_EN, p->usbcplx); - dev_dbg(p->dev, "host PHY on: EHCI(89)=0x%08x OHCI0(90)=0x%08x usb-complex=0x%08x\n", - readl(p->pmgr + PMGR_USB_EHCI), readl(p->pmgr + PMGR_USB_OHCI0), + dev_dbg(p->dev, "host PHY on: EHCI=0x%08x OHCI0=0x%08x usb-complex=0x%08x\n", + readl(p->pmgr + p->data->pmgr_usb_ehci), + readl(p->pmgr + p->data->pmgr_usb_ohci0), p->usbcplx ? readl(p->usbcplx) : 0); return 0; @@ -620,8 +664,10 @@ static int s5l_usbphy_probe(struct platform_device *pdev) p->dev = &pdev->dev; p->data = device_get_match_data(&pdev->dev); + if (!p->data) + p->data = &s5l8940x_usbphy_data; mutex_init(&p->lock); - if (p->data && p->data->cold_init) { + if (p->data->cold_init) { p->refclk = devm_clk_get(&pdev->dev, "ref"); if (IS_ERR(p->refclk)) return dev_err_probe(&pdev->dev, PTR_ERR(p->refclk), @@ -672,9 +718,10 @@ static int s5l_usbphy_probe(struct platform_device *pdev) } static const struct of_device_id s5l_usbphy_of_match[] = { + { .compatible = "apple,s5l8950x-otgphy", .data = &s5l8950x_usbphy_data }, { .compatible = "apple,s5l8942x-otgphy", .data = &s5l8942x_usbphy_data }, - { .compatible = "apple,s5l8940x-otgphy" }, - { .compatible = "apple,s5l8930x-otgphy" }, + { .compatible = "apple,s5l8940x-otgphy", .data = &s5l8940x_usbphy_data }, + { .compatible = "apple,s5l8930x-otgphy", .data = &s5l8940x_usbphy_data }, { .compatible = "apple,s5l8945x-usb1-phy" }, { }, }; From 28674e8e26d4b843783401917bf9bcc1c5234afc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:55 +0100 Subject: [PATCH 08/43] dt-bindings: usb: dwc2: Add the Apple S5L8950X MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The A6's OTG controller is the A5's dwc2 and runs with the S5L8942X quirks and parameters. Add "apple,s5l8950x-dwc2" in front of the S5L8942X and S5L8940X compatibles, and require the PHY like theirs. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- Documentation/devicetree/bindings/usb/dwc2.yaml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Documentation/devicetree/bindings/usb/dwc2.yaml b/Documentation/devicetree/bindings/usb/dwc2.yaml index 759eb83a36fb39..a838702328e789 100644 --- a/Documentation/devicetree/bindings/usb/dwc2.yaml +++ b/Documentation/devicetree/bindings/usb/dwc2.yaml @@ -20,6 +20,7 @@ allOf: enum: - apple,s5l8940x-dwc2 - apple,s5l8942x-dwc2 + - apple,s5l8950x-dwc2 then: required: - phys @@ -32,6 +33,11 @@ allOf: properties: compatible: oneOf: + - items: + - const: apple,s5l8950x-dwc2 + - const: apple,s5l8942x-dwc2 + - const: apple,s5l8940x-dwc2 + - const: snps,dwc2 - items: - const: apple,s5l8942x-dwc2 - const: apple,s5l8940x-dwc2 From 683349db425475e6e097a91be7e9924f44af7e39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:56 +0100 Subject: [PATCH 09/43] ARM: dts: apple: Add the S5L8950X and the iPhone 5 (N41, N42) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit s5l8950x.dtsi describes the A6 as the iPhone5,2 iOS 8.4.1 (12H321) ADT, iBEC and kernelcache give it: two Swift cores started through PMGR, the AIC, the 24 MHz watchdog counter, PMGR, GPIO (232 pins), UART1-6, the OTG PHY and the dwc2 gadget, and simple-framebuffer over iBoot's 640x1136 scanout. The boot loader fills memory and framebuffer. Every PMGR gate is disabled in the SoC file and enabled by the board next to its consumer. A registered gate that nobody holds is switched off by clk_disable_unused, and iBoot leaves most of them on. When the SoC file registered the CDMA, SPI1, UART1-5 and I2C0-2 gates with no consumer, the N42 booted into clk: Disabling unused clocks phy-apple-s5l-usb 36000000.phy: PHY reference clock selection did not latch udc 36100000.usb: failed to start ...: -5 although no USB gate is among them. A gate that is not registered keeps the state iBoot left. CDMA has no Linux consumer and stays unregistered. s5l8950x-5.dtsi holds what the N41 and N42 share; so far UART6, the debug port. The two boards differ in cellular bands, which Linux does not drive. The N41 is untested. Tested on an iPhone5,2: both cores, the framebuffer console and the USB gadget. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/Makefile | 2 + arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 30 ++ arch/arm/boot/dts/apple/s5l8950x-n41.dts | 24 ++ arch/arm/boot/dts/apple/s5l8950x-n42.dts | 29 ++ arch/arm/boot/dts/apple/s5l8950x.dtsi | 384 +++++++++++++++++++++++ 5 files changed, 469 insertions(+) create mode 100644 arch/arm/boot/dts/apple/s5l8950x-5.dtsi create mode 100644 arch/arm/boot/dts/apple/s5l8950x-n41.dts create mode 100644 arch/arm/boot/dts/apple/s5l8950x-n42.dts create mode 100644 arch/arm/boot/dts/apple/s5l8950x.dtsi diff --git a/arch/arm/boot/dts/apple/Makefile b/arch/arm/boot/dts/apple/Makefile index ba7ec8501b0577..a60735b0905136 100644 --- a/arch/arm/boot/dts/apple/Makefile +++ b/arch/arm/boot/dts/apple/Makefile @@ -2,3 +2,5 @@ dtb-$(CONFIG_ARCH_APPLE_S5L) += s5l8942x-p105.dtb dtb-$(CONFIG_ARCH_APPLE_S5L) += s5l8945x-j1.dtb dtb-$(CONFIG_ARCH_APPLE_S5L) += s5l8940x-k93.dtb +dtb-$(CONFIG_ARCH_APPLE_S5L) += s5l8950x-n41.dtb +dtb-$(CONFIG_ARCH_APPLE_S5L) += s5l8950x-n42.dtb diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi new file mode 100644 index 00000000000000..0d8858f3ece075 --- /dev/null +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-2.0 OR MIT +/* + * Apple iPhone 5 (N41 / iPhone5,1 and N42 / iPhone5,2, S5L8950X / Apple A6): + * what the two models share. Apple sells them as one phone that differs in + * its cellular bands, which Linux does not drive, and the N42's ADT names + * its touch controller "multi-touch,n41". Everything below was read from + * the N42: the iPhone5,2 iOS 8.4.1 (12H321) ADT as iBoot passes it, and the + * iPhone5,2 10.3.4 (14G61) ADT and kernelcache. N41 is untested. + */ + +#include "s5l8950x.dtsi" + +/ { + aliases { + serial0 = &uart6; + }; +}; + +/* + * UART6 is the debug port. Production iBEC leaves it gated off unless + * debug-uarts is set, so there is no earlycon on it: the serial driver + * switches the gate on before its first register access. + */ +&uart6_ps { + status = "okay"; +}; + +&uart6 { + status = "okay"; +}; diff --git a/arch/arm/boot/dts/apple/s5l8950x-n41.dts b/arch/arm/boot/dts/apple/s5l8950x-n41.dts new file mode 100644 index 00000000000000..d1b4f7622346e6 --- /dev/null +++ b/arch/arm/boot/dts/apple/s5l8950x-n41.dts @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-2.0 OR MIT +/* + * Apple iPhone 5 (GSM) -- iPhone5,1 / N41AP / S5L8950X (Apple A6). + * + * The same phone as the N42 for everything Linux drives (s5l8950x-5.dtsi). + * Untested: every value was read from an N42. + */ + +/dts-v1/; + +#include "s5l8950x-5.dtsi" + +/ { + compatible = "apple,n41ap", "apple,s5l8950x", "apple,arm"; + model = "Apple iPhone 5 (GSM) (iPhone5,1)"; + + chosen { + bootargs = "console=tty0 console=ttyGS0,115200 lpj=6500000 root=/dev/ram0 rw rootwait panic=10 loglevel=8 ignore_loglevel g_cdc.host_addr=02:10:5a:51:00:01 g_cdc.dev_addr=02:10:5a:51:00:02"; + + /* Overwritten by m1n1 kboot_prepare_dt() when an initrd is loaded. */ + linux,initrd-start = <0x88000000>; + linux,initrd-end = <0x88000000>; + }; +}; diff --git a/arch/arm/boot/dts/apple/s5l8950x-n42.dts b/arch/arm/boot/dts/apple/s5l8950x-n42.dts new file mode 100644 index 00000000000000..57acd61ab757f3 --- /dev/null +++ b/arch/arm/boot/dts/apple/s5l8950x-n42.dts @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-2.0 OR MIT +/* + * Apple iPhone 5 (Global) -- iPhone5,2 / N42AP / S5L8950X (Apple A6). + * + * Booted from a jailbroken iOS through kDFU: iBSS, then a patched iBEC + * starts m1n1 (armv7) with bootx, and m1n1 starts Linux. + */ + +/dts-v1/; + +#include "s5l8950x-5.dtsi" + +/ { + compatible = "apple,n42ap", "apple,s5l8950x", "apple,arm"; + model = "Apple iPhone 5 (Global) (iPhone5,2)"; + + chosen { + /* + * console=tty0 draws the boot log on the 640x1136 portrait + * simple-framebuffer; ttyGS0 stays last so /dev/console is the + * USB CDC ACM serial gadget. + */ + bootargs = "console=tty0 console=ttyGS0,115200 lpj=6500000 root=/dev/ram0 rw rootwait panic=10 loglevel=8 ignore_loglevel g_cdc.host_addr=02:10:5a:52:00:01 g_cdc.dev_addr=02:10:5a:52:00:02"; + + /* Overwritten by m1n1 kboot_prepare_dt() when an initrd is loaded. */ + linux,initrd-start = <0x88000000>; + linux,initrd-end = <0x88000000>; + }; +}; diff --git a/arch/arm/boot/dts/apple/s5l8950x.dtsi b/arch/arm/boot/dts/apple/s5l8950x.dtsi new file mode 100644 index 00000000000000..a5c3b0b7caef6f --- /dev/null +++ b/arch/arm/boot/dts/apple/s5l8950x.dtsi @@ -0,0 +1,384 @@ +// SPDX-License-Identifier: GPL-2.0 OR MIT +/* + * Apple A6 (S5L8950X) SoC core device tree include. + * + * Shared by iPhone 5 (N41 / iPhone5,1 and N42 / iPhone5,2). + * + * Every address, IRQ, and PMGR power-state offset below was verified from the + * decrypted iPhone5,2 iOS 8.4.1 (12H321) Apple Device Tree, iBEC, and + * kernelcache (AppleS5L8950XPerformanceController + USB PHY init). + * + * What sits outside the SoC (PMU, touch, display panel, Wi-Fi, Bluetooth, + * battery) is described by the iPhone 5 include, s5l8950x-5.dtsi. + */ + +/ { + #address-cells = <1>; + #size-cells = <1>; + interrupt-parent = <&aic>; + + /* + * 1 GiB DRAM at 0x80000000..0xc0000000. m1n1 overwrites reg at boot + * from iBoot's boot_args (phys_base, mem_size). + */ + memory@80000000 { + device_type = "memory"; + reg = <0x80000000 0x3fc00000>; + }; + + reserved-memory { + #address-cells = <1>; + #size-cells = <1>; + ranges; + + /* + * iBoot's scanout buffer. Base and size are patched by m1n1 + * at boot from boot_args.video together with framebuffer0. + */ + fb_region: framebuffer@bf000000 { + reg = <0xbf000000 0x400000>; + no-map; + }; + + /* + * First page of DRAM: physical 0 aliases here when a secondary + * core leaves reset via PMGR+0x1214/+0x1220 (platsmp.c). + */ + cpu_reset_page: cpu-reset@80000000 { + reg = <0x80000000 0x1000>; + no-map; + }; + + /* + * iBoot's 16 KiB persistent RAM (its console and panic data), + * which the boot chain keeps across a reset. + */ + pram_region: pram@bfffc000 { + reg = <0xbfffc000 0x4000>; + no-map; + }; + }; + + /* + * simple-framebuffer over iBoot's live CLCD scanout (640x1136 portrait + * Retina panel on iPhone 5). m1n1 patches reg/width/height/stride + * from boot_args.video before entering Linux. + */ + framebuffer0: framebuffer@bf000000 { + compatible = "simple-framebuffer"; + reg = <0xbf000000 0x400000>; + width = <640>; + height = <1136>; + stride = <2560>; + format = "a8r8g8b8"; + memory-region = <&fb_region>; + status = "okay"; + }; + + /* + * Dual Apple Swift (ARMv7s) cores with integrated architectural L2 + * cache (no external PL310, no Cortex-A9 SCU). + * + * ADT /cpus/cpu0 reg = 0, /cpus/cpu1 reg = 1. XNU indexes cores by + * MPIDR Aff0 (0 and 1, Aff1 = 0). Secondary bring-up uses PMGR + * +0x1214 (START) and +0x1220 (RUN), verified from + * AppleS5L8950XPerformanceController in iOS 8.4.1 kernelcache. + */ + cpus { + #address-cells = <1>; + #size-cells = <0>; + apple,cpu-reset-page = <&cpu_reset_page>; + + cpu0: cpu@0 { + device_type = "cpu"; + compatible = "apple,swift", "arm,armv7"; + reg = <0x0>; + enable-method = "apple,pmgr-core"; + }; + + cpu1: cpu@1 { + device_type = "cpu"; + compatible = "apple,swift", "arm,armv7"; + reg = <0x1>; + enable-method = "apple,pmgr-core"; + }; + }; + + refclk24mhz: clock-24000000 { + compatible = "fixed-clock"; + #clock-cells = <0>; + clock-frequency = <24000000>; + }; + + soc: soc@30000000 { + compatible = "simple-bus"; + #address-cells = <1>; + #size-cells = <1>; + ranges = <0x0 0x30000000 0x10000000>; + + /* Apple Interrupt Controller rev 1 (ADT /arm-io/aic). */ + aic: interrupt-controller@f200000 { + compatible = "aic,1"; + reg = <0xf200000 0x10000>; + interrupt-controller; + #interrupt-cells = <1>; + #address-cells = <0>; + apple,main-cpus = <2>; + }; + + /* + * 24 MHz watchdog counter (ADT /arm-io/wdt, wdt-version 1): + * used as wall clocksource, sched_clock, udelay timer, and + * CPU frequency calibration reference. + */ + wdt: timer@f103020 { + compatible = "apple,s5l8940x-wdt-timer"; + reg = <0xf103020 0x10>; + interrupts = <4>; + clock-frequency = <24000000>; + status = "okay"; + }; + + /* + * Power/clock manager (ADT /arm-io/pmgr). Kept disabled so no + * generic driver gates boot-critical clocks; platsmp.c looks + * up the node directly for PMGR_CORE_STOP/START/RUN + * (+0x1210/+0x1214/+0x1220). + */ + pmgr: power-management@f100000 { + compatible = "apple,s5l8950x-pmgr", "apple,s5l8940x-pmgr", "syscon"; + reg = <0xf100000 0x7000>; + status = "disabled"; + }; + + /* + * Individual PMGR power-state gates (offset = 0x1000 + ps_idx * 4 + * from the 81-entry x 44-byte ADT pmgr device-clocks table). + * + * Every gate is disabled here and enabled by the board next to + * the consumer that claims it. A registered gate nobody holds + * is switched off by clk_disable_unused at late_initcall, and + * iBoot leaves most of these on: on N42 that cut took the USB + * OTG PHY with it ("PHY reference clock selection did not + * latch", gadget start -EIO) although no USB gate is among + * them. An unregistered gate keeps the state iBoot left. + */ + /* + * CDMA (ADT id 0x31, index 0x1f). No Linux driver claims it yet, + * so no board should enable it: it must stay as iBoot left it. + */ + cdma_ps: cdma-ps@f10107c { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf10107c 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "cdma_ps"; + status = "disabled"; + }; + + spi1_ps: spi1-ps@f1010e8 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf1010e8 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "spi1_ps"; + status = "disabled"; + }; + + uart1_ps: uart1-ps@f1010fc { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf1010fc 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "uart1_ps"; + status = "disabled"; + }; + + uart2_ps: uart2-ps@f101100 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf101100 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "uart2_ps"; + status = "disabled"; + }; + + uart3_ps: uart3-ps@f101104 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf101104 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "uart3_ps"; + status = "disabled"; + }; + + uart4_ps: uart4-ps@f101108 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf101108 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "uart4_ps"; + status = "disabled"; + }; + + uart5_ps: uart5-ps@f10110c { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf10110c 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "uart5_ps"; + status = "disabled"; + }; + + uart6_ps: uart6-ps@f101110 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf101110 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "uart6_ps"; + status = "disabled"; + }; + + i2c0_ps: i2c0-ps@f101118 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf101118 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "i2c0_ps"; + status = "disabled"; + }; + + i2c1_ps: i2c1-ps@f10111c { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf10111c 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "i2c1_ps"; + status = "disabled"; + }; + + i2c2_ps: i2c2-ps@f101120 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf101120 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "i2c2_ps"; + status = "disabled"; + }; + + /* + * GPIO / pinctrl block (ADT /arm-io/gpio, "gpio,s5l8950x", + * "gpio,s5l8930x"): 29 ports = 232 pins, IRQ 119. + */ + gpio: gpio@fa00000 { + compatible = "apple,s5l8950x-gpio", "apple,s5l8940x-gpio"; + reg = <0xfa00000 0x1000>; + interrupts = <119>; + gpio-controller; + #gpio-cells = <2>; + interrupt-controller; + #interrupt-cells = <2>; + #address-cells = <0>; + pin-count = <232>; + interrupt-groups = <1>; + status = "okay"; + }; + + /* + * UARTs (ADT /arm-io/uart1..uart6; S5L8950X has no uart0). + * uart6 is the board's boot-console / debug-console port. + */ + uart1: serial@2600000 { + compatible = "apple,s5l8940x-uart", "apple,s5l-uart", + "samsung,s3c6400-uart"; + reg = <0x2600000 0x1000>; + interrupts = <22>; + clocks = <&uart1_ps>, <&refclk24mhz>; + clock-names = "uart", "clk_uart_baud0"; + status = "disabled"; + }; + + uart2: serial@2700000 { + compatible = "apple,s5l8940x-uart", "apple,s5l-uart", + "samsung,s3c6400-uart"; + reg = <0x2700000 0x1000>; + interrupts = <23>; + clocks = <&uart2_ps>, <&refclk24mhz>; + clock-names = "uart", "clk_uart_baud0"; + status = "disabled"; + }; + + uart3: serial@2800000 { + compatible = "apple,s5l8940x-uart", "apple,s5l-uart", + "samsung,s3c6400-uart"; + reg = <0x2800000 0x1000>; + interrupts = <24>; + clocks = <&uart3_ps>, <&refclk24mhz>; + clock-names = "uart", "clk_uart_baud0"; + status = "disabled"; + }; + + uart4: serial@2900000 { + compatible = "apple,s5l8940x-uart", "apple,s5l-uart", + "samsung,s3c6400-uart"; + reg = <0x2900000 0x1000>; + interrupts = <25>; + clocks = <&uart4_ps>, <&refclk24mhz>; + clock-names = "uart", "clk_uart_baud0"; + status = "disabled"; + }; + + uart5: serial@2a00000 { + compatible = "apple,s5l8940x-uart", "apple,s5l-uart", + "samsung,s3c6400-uart"; + reg = <0x2a00000 0x1000>; + interrupts = <26>; + clocks = <&uart5_ps>, <&refclk24mhz>; + clock-names = "uart", "clk_uart_baud0"; + status = "disabled"; + }; + + uart6: serial@2b00000 { + compatible = "apple,s5l8940x-uart", "apple,s5l-uart", + "samsung,s3c6400-uart"; + reg = <0x2b00000 0x1000>; + interrupts = <27>; + clocks = <&uart6_ps>, <&refclk24mhz>; + clock-names = "uart", "clk_uart_baud0"; + status = "disabled"; + }; + + /* + * USB OTG PHY (ADT /arm-io/otgphyctrl + /arm-io/usb-complex). + * Uses S5L8950X PMGR gates (+0x1084/+0x1088/+0x109c) and + * OPHY_UOTGTUNE1 = 0x749. + */ + otgphy: phy@6000000 { + compatible = "apple,s5l8950x-otgphy"; + reg = <0x6000000 0x1000>, /* otgphyctrl */ + <0xf108000 0x1000>; /* usb-complex */ + #phy-cells = <1>; + clocks = <&refclk24mhz>; + clock-names = "ref"; + status = "okay"; + }; + + /* + * DWC2 USB-OTG gadget controller (ADT /arm-io/usb-complex/usb-device: + * reg 0x06100000, IRQ 11, num-of-eps 14, fifo-depth 0x820). + */ + dwc2: usb@6100000 { + compatible = "apple,s5l8950x-dwc2", "apple,s5l8942x-dwc2", + "apple,s5l8940x-dwc2", "snps,dwc2"; + reg = <0x6100000 0x10000>; + interrupts = <11>; + phys = <&otgphy 0>; + phy-names = "usb2-phy"; + dr_mode = "peripheral"; + g-rx-fifo-size = <512>; + g-np-tx-fifo-size = <128>; + g-tx-fifo-size = <128 128 128 128 128 128 128 128>; + status = "okay"; + }; + }; +}; From 738359a5bb8cf70c71f3c5f6ff226d74151cee89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:56 +0100 Subject: [PATCH 10/43] phy: apple-s5l-usb: Program the S5L8950X HSIC tuning MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The N42's otgphyctrl is PHY version 4. Besides uotgtune1 = 0x749 and uotgtune2 = 0x2ff3, its ADT node has hsic-tuning-val = 0xa30a3a3, which AppleS5L8930XUSBPhy writes to +0x5c (iPhone5,2 iOS 10.3.4). Add it to the per-SoC data and write it with the other tuning values on a cold start, and on its own when the PHY was left running. HSIC port 4 carries the BCM4334 Wi-Fi. The other SoCs have no HSIC tuning value and write nothing new. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/phy/phy-apple-s5l-usb.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/drivers/phy/phy-apple-s5l-usb.c b/drivers/phy/phy-apple-s5l-usb.c index 2de812f98e08b9..5801e6d74ec508 100644 --- a/drivers/phy/phy-apple-s5l-usb.c +++ b/drivers/phy/phy-apple-s5l-usb.c @@ -37,6 +37,10 @@ #define OPHY_UOTGTUNE1_DEVICE 0x549 #define OPHY_UOTGTUNE1_S5L8950X_DEVICE 0x749 #define OPHY_UOTGTUNE2_DEVICE 0x2ff3 +/* PHY version 4 (S5L8950X): ADT otgphyctrl hsic-tuning-val, written to +0x5c + * by AppleS5L8930XUSBPhy (14G61). */ +#define OPHY_HSICTUNE 0x5c +#define OPHY_HSICTUNE_S5L8950X 0xa30a3a3 #define PMGR_BASE 0x3F100000 #define PMGR_GATE_ON 0xF @@ -118,6 +122,7 @@ struct s5l_usbphy_soc_data { u32 pmgr_usb_ehci; u32 pmgr_usb_ohci0; u32 uotgtune1_device; + u32 hsic_tuning; /* OPHY_HSICTUNE, when non-zero */ }; static const struct s5l_usbphy_soc_data s5l8940x_usbphy_data = { @@ -158,6 +163,7 @@ static const struct s5l_usbphy_soc_data s5l8950x_usbphy_data = { .pmgr_usb_ehci = 0x108c, .pmgr_usb_ohci0 = 0x1094, .uotgtune1_device = OPHY_UOTGTUNE1_S5L8950X_DEVICE, + .hsic_tuning = OPHY_HSICTUNE_S5L8950X, }; struct s5l_usbphy { @@ -237,6 +243,8 @@ static int s5l_usbphy_cold_init(struct s5l_usbphy *p) writel(OPHYUNK1_START, p->base + OPHYUNK1); writel(p->data->uotgtune1_device, p->base + OPHY_UOTGTUNE1); writel(OPHY_UOTGTUNE2_DEVICE, p->base + OPHY_UOTGTUNE2); + if (p->data->hsic_tuning) + writel(p->data->hsic_tuning, p->base + OPHY_HSICTUNE); udelay(10); v = readl(p->base + OPHYCLK); @@ -292,6 +300,8 @@ static int s5l_usbphy_init(struct phy *phy) ret = s5l_usbphy_cold_init(p); if (ret) goto disable_clock; + } else if (p->data->hsic_tuning) { + writel(p->data->hsic_tuning, p->base + OPHY_HSICTUNE); } } else if (readl(p->base + OPHYPWR) != OPHYPWR_ACTIVE) { /* Legacy compatibles keep the tuning firmware leaves, unless From 0bdd40d1cd641d18b08cfa54191a50433b774466 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:57 +0100 Subject: [PATCH 11/43] phy: apple-s5l-usb: Hold the S5L8950X OTG gates from probe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The OTG PHY switched UPERF, USB-OTG and USBREG on with raw PMGR writes in phy_init, behind the clock framework's back. Describe the three as PMGR gate clocks in s5l8950x.dtsi (+0x1084, +0x1088, +0x109c; ADT device-clocks ids 0x04, 0x35, 0x06) and give them to the PHY, which switches them on at probe in the order the boot loader uses and keeps them on, the way the H2FMI driver holds its gates. The gadget is the console and the network, so nothing switches them off again: not a failed probe, not an unbind, and with the enable count held not clk_disable_unused either. The clocks are optional and looked up by name ("uperf", "otg", "usbreg"). P105, J1 and the other trees name only "ref", get none, and run the code they ran before; phy_init's register checks stay for them and are a no-op on the A6 once the gates are held. The host side's USB-EHCI and USB-OHCI0 gates stay with the host PHY's power-on and are not clocks, so nothing at late_initcall reaches them either. When the reference clock selection does not latch, the error now says what OPHYCLK, OPHYPWR and the three gate registers read. Tested on an iPhone5,2: the gadget comes up without clk_ignore_unused. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x.dtsi | 40 ++++++++++++++++-- drivers/phy/phy-apple-s5l-usb.c | 60 ++++++++++++++++++++++++--- 2 files changed, 92 insertions(+), 8 deletions(-) diff --git a/arch/arm/boot/dts/apple/s5l8950x.dtsi b/arch/arm/boot/dts/apple/s5l8950x.dtsi index a5c3b0b7caef6f..84d98ff6de92ff 100644 --- a/arch/arm/boot/dts/apple/s5l8950x.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x.dtsi @@ -151,6 +151,38 @@ status = "disabled"; }; + /* + * USB OTG gates (ADT usb-complex clock-gates; device-clocks + * UPERF id 0x04 index 0x21, USB-OTG id 0x35 index 0x22, USBREG + * id 0x06 index 0x27). Registered with the OTG PHY, which holds + * them from probe. The host side's USB-EHCI (+0x108c) and + * USB-OHCI0 (+0x1094) stay with the PHY's host power-on and are + * not clocks, so nothing at late_initcall can switch them off. + */ + uperf_ps: uperf-ps@f101084 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf101084 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "uperf_ps"; + }; + + usb_otg_ps: usb-otg-ps@f101088 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf101088 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "usb_otg_ps"; + }; + + usbreg_ps: usbreg-ps@f10109c { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf10109c 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "usbreg_ps"; + }; + /* * Individual PMGR power-state gates (offset = 0x1000 + ps_idx * 4 * from the 81-entry x 44-byte ADT pmgr device-clocks table). @@ -351,15 +383,17 @@ /* * USB OTG PHY (ADT /arm-io/otgphyctrl + /arm-io/usb-complex). * Uses S5L8950X PMGR gates (+0x1084/+0x1088/+0x109c) and - * OPHY_UOTGTUNE1 = 0x749. + * OPHY_UOTGTUNE1 = 0x749. The PHY holds the three OTG gates + * from probe. */ otgphy: phy@6000000 { compatible = "apple,s5l8950x-otgphy"; reg = <0x6000000 0x1000>, /* otgphyctrl */ <0xf108000 0x1000>; /* usb-complex */ #phy-cells = <1>; - clocks = <&refclk24mhz>; - clock-names = "ref"; + clocks = <&refclk24mhz>, <&uperf_ps>, <&usb_otg_ps>, + <&usbreg_ps>; + clock-names = "ref", "uperf", "otg", "usbreg"; status = "okay"; }; diff --git a/drivers/phy/phy-apple-s5l-usb.c b/drivers/phy/phy-apple-s5l-usb.c index 5801e6d74ec508..97a6b4a068711d 100644 --- a/drivers/phy/phy-apple-s5l-usb.c +++ b/drivers/phy/phy-apple-s5l-usb.c @@ -6,6 +6,7 @@ */ #include +#include #include #include #include @@ -176,6 +177,7 @@ struct s5l_usbphy { bool lpo_supply_on; struct device *dev; struct clk *refclk; + struct clk_bulk_data gates[3]; /* uperf, otg, usbreg; optional */ const struct s5l_usbphy_soc_data *data; struct mutex lock; unsigned int init_users; @@ -200,6 +202,44 @@ static int s5l_pmgr_on(struct s5l_usbphy *p, u32 off) return -ETIMEDOUT; } +/* + * The OTG side's PMGR gates, when the tree names them as clocks (S5L8950X: + * UPERF, USB-OTG and USBREG, ADT ids 0x04, 0x35 and 0x06): switched on at + * probe in the order native firmware uses, and held from then on. The + * gadget is the console and the network, so they are never switched off, + * not on a failed probe and not on unbind; the enable count also keeps + * clk_disable_unused away from them. s5l_usbphy_init() still checks the + * same registers directly, which is all a tree without these clocks gets. + */ +static const char * const s5l_usbphy_gate_names[] = { "uperf", "otg", "usbreg" }; + +static int s5l_usbphy_hold_gates(struct s5l_usbphy *p) +{ + int i, n = ARRAY_SIZE(s5l_usbphy_gate_names), ret; + bool any = false; + + BUILD_BUG_ON(ARRAY_SIZE(s5l_usbphy_gate_names) != ARRAY_SIZE(p->gates)); + for (i = 0; i < n; i++) + p->gates[i].id = s5l_usbphy_gate_names[i]; + ret = devm_clk_bulk_get_optional(p->dev, n, p->gates); + if (ret) + return dev_err_probe(p->dev, ret, "PMGR gates\n"); + for (i = 0; i < n; i++) + any |= !!p->gates[i].clk; + if (!any) + return 0; + + for (i = 0; i < n; i++) + if (p->gates[i].clk) + dev_dbg(p->dev, "PMGR gate %s was %s\n", + __clk_get_name(p->gates[i].clk), + __clk_is_enabled(p->gates[i].clk) ? "on" : "off"); + ret = clk_bulk_prepare_enable(n, p->gates); + if (ret) + return dev_err_probe(p->dev, ret, "enabling the PMGR gates\n"); + return 0; +} + static int s5l_usbphy_clk_sel(unsigned long rate) { switch (rate) { @@ -249,8 +289,13 @@ static int s5l_usbphy_cold_init(struct s5l_usbphy *p) v = readl(p->base + OPHYCLK); writel((v & ~OPHYCLK_CLKSEL_MASK) | clksel, p->base + OPHYCLK); - if ((readl(p->base + OPHYCLK) & OPHYCLK_CLKSEL_MASK) != clksel) { - dev_err(p->dev, "PHY reference clock selection did not latch\n"); + v = readl(p->base + OPHYCLK); + if ((v & OPHYCLK_CLKSEL_MASK) != clksel) { + dev_err(p->dev, "PHY reference clock selection did not latch: OPHYCLK 0x%08x OPHYPWR 0x%08x PMGR uperf 0x%08x otg 0x%08x usbreg 0x%08x\n", + v, readl(p->base + OPHYPWR), + readl(p->pmgr + p->data->pmgr_uperf), + readl(p->pmgr + p->data->pmgr_usb_otg), + readl(p->pmgr + p->data->pmgr_usbreg)); return -EIO; } @@ -469,9 +514,9 @@ static int s5l_hostphy_power_on(struct phy *phy) writel(readl(p->usbcplx) | USBCPLX_HSIC_EN, p->usbcplx); dev_dbg(p->dev, "host PHY on: EHCI=0x%08x OHCI0=0x%08x usb-complex=0x%08x\n", - readl(p->pmgr + p->data->pmgr_usb_ehci), - readl(p->pmgr + p->data->pmgr_usb_ohci0), - p->usbcplx ? readl(p->usbcplx) : 0); + readl(p->pmgr + p->data->pmgr_usb_ehci), + readl(p->pmgr + p->data->pmgr_usb_ohci0), + p->usbcplx ? readl(p->usbcplx) : 0); return 0; err_disable_hsic: @@ -664,6 +709,7 @@ static int s5l_usbphy_probe(struct platform_device *pdev) struct s5l_usbphy *p; struct phy *phy; struct phy_provider *provider; + int ret; if (of_device_is_compatible(pdev->dev.of_node, "apple,s5l8945x-usb1-phy")) return s5l_usb1phy_probe(pdev); @@ -696,6 +742,10 @@ static int s5l_usbphy_probe(struct platform_device *pdev) return -ENOMEM; } + ret = s5l_usbphy_hold_gates(p); + if (ret) + return ret; + /* usb-complex, for the HSIC enable bit: optional, the second reg. */ if (platform_get_resource(pdev, IORESOURCE_MEM, 1)) { p->usbcplx = devm_platform_ioremap_resource(pdev, 1); From a8a82930b36c0971f6ac2ad65cd8e484d2e7c622 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:58 +0100 Subject: [PATCH 12/43] mfd: apple-pmu-i2c: Add the Dialog D1972 PMU MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The iPhone 5 (N42, ADT "pmu,d1972") has a Dialog D1972 PMU. Move the GPIO count and the power-off register sequence into per-chip data, and add "apple,pmu-d1972", from AppleD1972PMU (iPhone5,2 iOS 10.3.4): - 8-bit register addresses, 12 GPIOs at 0x68 + n; - power off (_shutdownGated): 0x7d = 0, clear 0x01..0x09, wake masks 0x12..0x1a (88 ff ff ff ff ae ff ff ff), alarm control 0x62 = 0x01, 0xa2 = 0, 0xa4 = 0, boot flags 0xb0 &= ~0xd0, clear the wake bit of the input GPIOs (>= 0x60), standby 0x1b |= 0x01. The D1946, D1974, D2333 and Chestnut paths are unchanged. Tested on an iPhone5,2: the PMU probes, and its GPIOs drive the Bluetooth and Wi-Fi power lines. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mfd/apple-pmu-i2c.c | 179 ++++++++++++++++++++++------------ include/linux/apple-pmu-i2c.h | 3 + 2 files changed, 117 insertions(+), 65 deletions(-) diff --git a/drivers/mfd/apple-pmu-i2c.c b/drivers/mfd/apple-pmu-i2c.c index aa69d2e3626281..f9c3c9a36d535e 100644 --- a/drivers/mfd/apple-pmu-i2c.c +++ b/drivers/mfd/apple-pmu-i2c.c @@ -20,9 +20,74 @@ #include #include +struct apple_pmu_off_info { + u8 pre_zero_reg; /* written 0 first (WLED/boost disable) */ + u8 events_reg; /* read nevents bytes to clear pending events */ + u8 masks_reg; /* write nevents off_masks bytes */ + u8 nevents; + const u8 *off_masks; + u8 alarm_ctrl_reg; /* written 0x01 (no RTC wake alarm) */ + u8 zero_reg1; /* written 0 */ + u8 zero_reg2; /* optional second register written 0 */ + u8 boot_flags_reg; /* cleared with mask 0xd0 for iBoot */ + u8 standby_reg; /* ORed with 0x01 in atomic power-off */ +}; + struct apple_pmu_i2c_info { unsigned reg_bits, val_bits; unsigned gpio_cfg; /* GPIO n's configuration register: gpio_cfg + n */ + unsigned ngpio; + const struct apple_pmu_off_info *off; +}; + +#define APPLE_PMU_GPIO_WAKE 0x02 + +static const u8 d1946_off_masks[9] = { + 0x88, 0xff, 0xff, 0xff, 0xff, 0xff, 0xae, 0xff, 0xff, +}; + +static const struct apple_pmu_off_info d1946_off_info = { + .pre_zero_reg = 0xd2, + .events_reg = 0x01, + .masks_reg = 0x12, + .nevents = ARRAY_SIZE(d1946_off_masks), + .off_masks = d1946_off_masks, + .alarm_ctrl_reg = 0x5b, + .zero_reg1 = 0xa1, + .boot_flags_reg = 0xaf, + .standby_reg = 0x1b, +}; + +/* + * D1972 (iPhone 5, S5L8950X, ADT "pmu,d1972"): 8-bit register addressing, + * 12 GPIOs at 0x68 + n (AppleD1972PMU vtable +0x3c4, 14G61 0x810e7678), and + * the same shutdown sequence as D1946 with shifted registers + * (AppleD1972PMU::_shutdownGated, 14G61 0x810e7a80): + * + * 0x7d = 0 pre-shutdown disable + * read 0x01..0x09 clear pending events + * 0x12..0x1a = mask table wake masks (0xae is at byte 5, not byte 6) + * 0x62 = 0x01 no RTC wake alarm (RTC counter is 0x64..0x67) + * 0xa2 = 0, 0xa4 = 0 + * 0xb0 &= ~0xd0 boot flags for iBoot + * 0x68..0x73: bit 1 off clear wake bit on all 12 input GPIOs (>= 0x60) + * 0x1b |= 1 PMU standby + */ +static const u8 d1972_off_masks[9] = { + 0x88, 0xff, 0xff, 0xff, 0xff, 0xae, 0xff, 0xff, 0xff, +}; + +static const struct apple_pmu_off_info d1972_off_info = { + .pre_zero_reg = 0x7d, + .events_reg = 0x01, + .masks_reg = 0x12, + .nevents = ARRAY_SIZE(d1972_off_masks), + .off_masks = d1972_off_masks, + .alarm_ctrl_reg = 0x62, + .zero_reg1 = 0xa2, + .zero_reg2 = 0xa4, + .boot_flags_reg = 0xb0, + .standby_reg = 0x1b, }; static const struct apple_pmu_i2c_info apple_pmu_i2c_d2333_info = { .reg_bits = 16, .val_bits = 8 }; @@ -46,7 +111,12 @@ static const struct apple_pmu_i2c_info apple_pmu_i2c_chestnut_info = { .reg_bits * _setLDO's bounds check of 0x16. */ static const struct apple_pmu_i2c_info apple_pmu_i2c_d1946_info = { - .reg_bits = 8, .val_bits = 8, .gpio_cfg = 0x61, + .reg_bits = 8, .val_bits = 8, .gpio_cfg = 0x61, .ngpio = 18, + .off = &d1946_off_info, +}; +static const struct apple_pmu_i2c_info apple_pmu_i2c_d1972_info = { + .reg_bits = 8, .val_bits = 8, .gpio_cfg = 0x68, .ngpio = 12, + .off = &d1972_off_info, }; /* * The iPad 3's D1974 (ADT "pmu,d1974") takes the same 8-bit addressing and @@ -56,75 +126,51 @@ static const struct apple_pmu_i2c_info apple_pmu_i2c_d1946_info = { * D1946's power-off is not checked against this chip. */ static const struct apple_pmu_i2c_info apple_pmu_i2c_d1974_info = { - .reg_bits = 8, .val_bits = 8, .gpio_cfg = 0x64, + .reg_bits = 8, .val_bits = 8, .gpio_cfg = 0x64, .ngpio = 18, }; + /* - * Power-off, the way AppleD1946PMU::_shutdownGated does it (kernelcache - * 12H321, 0x80ecec80; vtable slot 0x3a4). In order: - * - * 0xd2 = 0 the backlight's strings off - * read 0x01..0x09 the event registers, which clears them, so - * a stale event does not wake it at once - * 0x12..0x1a = mask table the events allowed to wake it: iOS's table - * 0x5b = 0x01 no RTC wake alarm (0x41 with one) - * 0xa1 = 0 - * 0xaf &= ~0xd0 flags for iBoot; a restart sets 0x90 instead - * 0x61..0x72: bit 1 off wake off on every PMU GPIO configured as an - * input (config >= 0x60) -- "cannot turn off GPIO - * wakes" is iOS's message when this fails - * 0x1b |= 1 "pmu go stdby": the PMU drops every rail - * - * Read on this iPad under Linux before any of it: the masks all 0x00, 0x5b - * 0x03, 0xaf 0x40, 0x1b 0x00. iOS's other branch, an external shutdown - * function, needs function-external_shutdown in the ADT, which P105's PMU - * does not have. Hold starts the iPad again, into iOS. - * - * All of it but the last write runs in the power-off prepare stage, where - * regmap may still sleep; the last one runs with interrupts off, straight - * through the I2C adapter's atomic transfer. + * Power-off, the way AppleD1946PMU::_shutdownGated (12H321, 0x80ecec80) and + * AppleD1972PMU::_shutdownGated (14G61, 0x810e7a80) do it. All of it but the + * last write runs in the power-off prepare stage, where regmap may still sleep; + * the last one runs with interrupts off, straight through the I2C adapter's + * atomic transfer. */ -#define D1946_EVENTS 0x01 -#define D1946_EVENT_MASKS 0x12 -#define D1946_NEVENTS 9 -#define D1946_STANDBY 0x1b -#define D1946_ALARM_CTRL 0x5b -#define D1946_GPIO_CFG 0x61 -#define D1946_NGPIO 18 -#define D1946_GPIO_WAKE 0x02 -#define D1946_REG_A1 0xa1 -#define D1946_BOOT_FLAGS 0xaf -#define D1946_WLED_ENABLE 0xd2 - -static const u8 d1946_off_masks[D1946_NEVENTS] = { - 0x88, 0xff, 0xff, 0xff, 0xff, 0xff, 0xae, 0xff, 0xff, -}; - -static int apple_pmu_d1946_power_off_prepare(struct sys_off_data *data) +static int apple_pmu_power_off_prepare(struct sys_off_data *data) { - struct regmap *map = ((struct apple_pmu_i2c *)data->cb_data)->regmap; + struct apple_pmu_i2c *pmu = data->cb_data; + const struct apple_pmu_i2c_info *info = pmu->info; + const struct apple_pmu_off_info *off = info->off; + struct regmap *map = pmu->regmap; unsigned int i, v; - regmap_write(map, D1946_WLED_ENABLE, 0); - for (i = 0; i < D1946_NEVENTS; i++) - regmap_read(map, D1946_EVENTS + i, &v); - for (i = 0; i < D1946_NEVENTS; i++) - regmap_write(map, D1946_EVENT_MASKS + i, d1946_off_masks[i]); - regmap_write(map, D1946_ALARM_CTRL, 0x01); - regmap_write(map, D1946_REG_A1, 0); - regmap_update_bits(map, D1946_BOOT_FLAGS, 0xd0, 0); - for (i = 0; i < D1946_NGPIO; i++) - if (!regmap_read(map, D1946_GPIO_CFG + i, &v) && v >= 0x60 && (v & D1946_GPIO_WAKE)) - regmap_write(map, D1946_GPIO_CFG + i, v & ~D1946_GPIO_WAKE); + if (off->pre_zero_reg) + regmap_write(map, off->pre_zero_reg, 0); + for (i = 0; i < off->nevents; i++) + regmap_read(map, off->events_reg + i, &v); + for (i = 0; i < off->nevents; i++) + regmap_write(map, off->masks_reg + i, off->off_masks[i]); + regmap_write(map, off->alarm_ctrl_reg, 0x01); + if (off->zero_reg1) + regmap_write(map, off->zero_reg1, 0); + if (off->zero_reg2) + regmap_write(map, off->zero_reg2, 0); + regmap_update_bits(map, off->boot_flags_reg, 0xd0, 0); + for (i = 0; i < info->ngpio; i++) + if (!regmap_read(map, info->gpio_cfg + i, &v) && v >= 0x60 && (v & APPLE_PMU_GPIO_WAKE)) + regmap_write(map, info->gpio_cfg + i, v & ~APPLE_PMU_GPIO_WAKE); return NOTIFY_DONE; } -static int apple_pmu_d1946_power_off(struct sys_off_data *data) +static int apple_pmu_power_off(struct sys_off_data *data) { - struct i2c_client *client = to_i2c_client(((struct apple_pmu_i2c *)data->cb_data)->dev); - int v = i2c_smbus_read_byte_data(client, D1946_STANDBY); + struct apple_pmu_i2c *pmu = data->cb_data; + const struct apple_pmu_off_info *off = pmu->info->off; + struct i2c_client *client = to_i2c_client(pmu->dev); + int v = i2c_smbus_read_byte_data(client, off->standby_reg); if (v >= 0) - i2c_smbus_write_byte_data(client, D1946_STANDBY, v | 0x01); + i2c_smbus_write_byte_data(client, off->standby_reg, v | 0x01); mdelay(1000); pr_emerg("apple-pmu-i2c: the PMU did not power off (standby %d)\n", v); return NOTIFY_DONE; @@ -224,7 +270,8 @@ static int apple_pmu_gpio_direction_input(struct gpio_chip *gc, unsigned int n) return apple_pmu_gpio_get_direction(gc, n) == GPIO_LINE_DIRECTION_IN ? 0 : -EPERM; } -static int apple_pmu_gpio_register(struct apple_pmu_i2c *pmu, unsigned int cfg_base) +static int apple_pmu_gpio_register(struct apple_pmu_i2c *pmu, unsigned int cfg_base, + unsigned int ngpio) { struct apple_pmu_gpio *g = devm_kzalloc(pmu->dev, sizeof(*g), GFP_KERNEL); struct gpio_chip *gc; @@ -238,7 +285,7 @@ static int apple_pmu_gpio_register(struct apple_pmu_i2c *pmu, unsigned int cfg_b gc->parent = pmu->dev; gc->owner = THIS_MODULE; gc->base = -1; - gc->ngpio = D1946_NGPIO; + gc->ngpio = ngpio; gc->can_sleep = true; gc->get_direction = apple_pmu_gpio_get_direction; gc->direction_input = apple_pmu_gpio_direction_input; @@ -250,6 +297,7 @@ static int apple_pmu_gpio_register(struct apple_pmu_i2c *pmu, unsigned int cfg_b static const struct of_device_id apple_pmu_i2c_of_match[] = { { .compatible = "apple,pmu-d1974", .data = &apple_pmu_i2c_d1974_info }, + { .compatible = "apple,pmu-d1972", .data = &apple_pmu_i2c_d1972_info }, { .compatible = "apple,pmu-d1946", .data = &apple_pmu_i2c_d1946_info }, { .compatible = "apple,pmu-d2333", .data = &apple_pmu_i2c_d2333_info }, { .compatible = "apple,pmu-chestnut", .data = &apple_pmu_i2c_chestnut_info }, @@ -276,6 +324,7 @@ static int apple_pmu_i2c_probe(struct i2c_client *i2c) info = of_id->data; pmu->dev = &i2c->dev; + pmu->info = info; i2c_set_clientdata(i2c, pmu); pmu->config.reg_bits = info->reg_bits; @@ -321,20 +370,20 @@ static int apple_pmu_i2c_probe(struct i2c_client *i2c) } } - if (info == &apple_pmu_i2c_d1946_info && of_device_is_system_power_controller(node)) { + if (info->off && of_device_is_system_power_controller(node)) { ret = devm_register_sys_off_handler(&i2c->dev, SYS_OFF_MODE_POWER_OFF_PREPARE, SYS_OFF_PRIO_DEFAULT, - apple_pmu_d1946_power_off_prepare, pmu); + apple_pmu_power_off_prepare, pmu); if (!ret) ret = devm_register_sys_off_handler(&i2c->dev, SYS_OFF_MODE_POWER_OFF, SYS_OFF_PRIO_DEFAULT, - apple_pmu_d1946_power_off, pmu); + apple_pmu_power_off, pmu); if (ret) dev_warn(&i2c->dev, "no power-off: %d\n", ret); } - if (info->gpio_cfg && of_property_read_bool(node, "gpio-controller")) { - ret = apple_pmu_gpio_register(pmu, info->gpio_cfg); + if (info->gpio_cfg && info->ngpio && of_property_read_bool(node, "gpio-controller")) { + ret = apple_pmu_gpio_register(pmu, info->gpio_cfg, info->ngpio); if (ret) dev_warn(&i2c->dev, "no GPIOs: %d\n", ret); } diff --git a/include/linux/apple-pmu-i2c.h b/include/linux/apple-pmu-i2c.h index 8d227b3d5ee543..6390967c13e65d 100644 --- a/include/linux/apple-pmu-i2c.h +++ b/include/linux/apple-pmu-i2c.h @@ -10,10 +10,13 @@ #include #include +struct apple_pmu_i2c_info; + struct apple_pmu_i2c { struct device *dev; struct regmap *regmap; struct regmap_config config; + const struct apple_pmu_i2c_info *info; }; #endif From bd3418af88f3c383df8d846089c28a4ca51c04df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:58 +0100 Subject: [PATCH 13/43] power: supply: apple-pmu-charger: Add the Dialog D1972, read-only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move the per-chip charger registers and the current encoding into struct pmu_chg_chip and add "apple,pmu-d1972-charger" for the iPhone 5, from AppleD1972PMUPowerSource (iPhone5,2 iOS 10.3.4): - the USB input current limit is register 0x3f (0x3d on the D1946); - the code is linear, 10 mA per step from 70 mA: (mA - 70) / 10; - VBUS online is status register 0x0a bit 6; a VBUS sag drops 0x3f to 0x03 (100 mA). The battery temperature comes from the HDQ gauge, not a PMU ADC channel, and corrupt gauge words once alternated "battery at 6272.0 C" with good readings. On the D1972 a reading outside -20..+70 C counts as no reading (the existing 100 mA fallback), and leaving the fallback takes three good readings in a row. Entering it on a missing reading is logged once. The D1946 path is unchanged. The driver keeps its armed=0 default: on the iPhone 5 it reports VBUS and the input limit, and logs the limit it would set without writing it. Tested on an iPhone5,2: VBUS online and the 100 mA limit read, no write. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/power/supply/apple-pmu-charger.c | 267 +++++++++++++++++------ 1 file changed, 204 insertions(+), 63 deletions(-) diff --git a/drivers/power/supply/apple-pmu-charger.c b/drivers/power/supply/apple-pmu-charger.c index cf265c512f3bc5..a2e89c1b1fc510 100644 --- a/drivers/power/supply/apple-pmu-charger.c +++ b/drivers/power/supply/apple-pmu-charger.c @@ -40,6 +40,11 @@ * - Above 45 C on the battery gauge it drops to 100 mA, and stays there * until below 40 C. Missing/failed temperature also selects this fallback. * iBEC's charge table ends at 45 C. This is derating, not charge inhibition. + * On the D1972 a reading outside -20..+70 C counts as missing, and it + * takes three cool readings in a row to leave the fallback. + * + * The temperature is the battery gauge's ("battery", POWER_SUPPLY_PROP_TEMP), + * on every chip; this driver reads no PMU ADC channel. */ #include #include @@ -58,11 +63,8 @@ #define PMU_STATUS0_VBUS BIT(6) #define PMU_INSUSP0 0x1b /* bit 2: input suspend */ #define PMU_INSUSP1 0x1c /* bit 7: input suspend */ -#define PMU_ILIM 0x3d /* the only register written */ #define PMU_ICHG 0x3f /* charge current setting */ -#define ILIM_MIN_CODE 0x02 /* < 100 mA; also the PMU's own sag value */ -#define ILIM_STEP 8 /* codes per ramp step, 100 mA */ #define ILIM_STEP_MS 10 #define ILIM_HARD_MAX_MA 2100 #define ILIM_DEFAULT_MA 1000 @@ -71,9 +73,106 @@ #define HOT_DECI_C 450 #define COOL_DECI_C 400 +/* + * temp_guard (D1972 / iPhone 5): the battery temperature is the gauge's, over + * HDQ. A reading outside -20..+70 C is no reading at all, and leaving the + * 100 mA fallback takes COOL_SAMPLES cool readings in a row, so neither a + * corrupt word nor a single good one between failures moves the limit up. + */ +#define GUARD_MIN_DECI_C (-200) +#define GUARD_MAX_DECI_C 700 +#define COOL_SAMPLES 3 + +struct pmu_chg_chip { + const char *name; + u8 status_reg; + u8 vbus_mask; + u8 ilim_reg; + u8 min_code; /* < 100 mA; also the PMU's own VBUS-sag drop value */ + u8 ramp_step; /* codes per ramp step (~100 mA) */ + unsigned int max_ma; + u8 (*ma_to_code)(unsigned int ma); + unsigned int (*code_to_ma)(u8 code); + bool temp_guard; +}; + +/* D1946: iBEC's encoding, 0x9ff0c618..0x9ff0c662 (register 0x3d) */ +static u8 d1946_ma_to_code(unsigned int ma) +{ + unsigned int code; + + ma = min_t(unsigned int, ma, ILIM_HARD_MAX_MA); + if (ma < 100) + return 0x02; + code = (8 * ma - 600) / 100; + if (code >= 0x73) + return code - 4; + if (code > 0x6e) + return 0x6e; + if (code >= 0x4b) + return code - 2; + if (code > 0x48) + return 0x48; + return code; +} + +static unsigned int d1946_code_to_ma(u8 code) +{ + return code <= 0x02 ? 100 : (code * 100 + 600) / 8; +} + +/* + * D1972 (iPhone 5, S5L8950X): register 0x3f. + * AppleD1972PMUPowerSource (14G61 0x810e9bf4..0x810e9c2f): linear 10 mA/LSB + * from 70 mA (code = (mA - 70) / 10; < 70 mA suspends, > 2619 mA clamps to + * 0xff). On VBUS sag the PMU drops 0x3f back to 0x03 (100 mA, checked at + * 0x810e99e6). Online is status register 0x0a bit 6 (0x810e9ec8), as on D1946. + */ +static u8 d1972_ma_to_code(unsigned int ma) +{ + ma = min_t(unsigned int, ma, ILIM_HARD_MAX_MA); + if (ma < 100) + return 0x03; + return (ma - 70) / 10; +} + +static unsigned int d1972_code_to_ma(u8 code) +{ + return code <= 0x03 ? 100 : 70 + code * 10; +} + +static const struct pmu_chg_chip pmu_chg_d1946 = { + .name = "d1946", + .status_reg = PMU_STATUS0, + .vbus_mask = PMU_STATUS0_VBUS, + .ilim_reg = 0x3d, + .min_code = 0x02, + .ramp_step = 8, + .max_ma = ILIM_HARD_MAX_MA, + .ma_to_code = d1946_ma_to_code, + .code_to_ma = d1946_code_to_ma, +}; + +static const struct pmu_chg_chip pmu_chg_d1972 = { + .name = "d1972", + .status_reg = PMU_STATUS0, + .vbus_mask = PMU_STATUS0_VBUS, + .ilim_reg = 0x3f, + .min_code = 0x03, + .ramp_step = 10, + .max_ma = ILIM_HARD_MAX_MA, + .ma_to_code = d1972_ma_to_code, + .code_to_ma = d1972_code_to_ma, + .temp_guard = true, +}; + +static bool d1972_armed; +module_param(d1972_armed, bool, 0644); +MODULE_PARM_DESC(d1972_armed, "enable D1972 charger writes (default off)"); + static bool armed = true; module_param(armed, bool, 0644); -MODULE_PARM_DESC(armed, "write 0x3d (default on; off: log only)"); +MODULE_PARM_DESC(armed, "enable D1946 charger writes (default on)"); static int max_input_ma = ILIM_DEFAULT_MA; module_param(max_input_ma, int, 0644); @@ -82,52 +181,33 @@ MODULE_PARM_DESC(max_input_ma, "ceiling for input_current_limit, 100..2100 mA (d struct pmu_chg { struct device *dev; struct regmap *map; + const struct pmu_chg_chip *chip; struct power_supply *psy; struct delayed_work work; struct mutex lock; /* everything below */ unsigned int req_ma; /* asked for: default or input_current_limit */ - u8 probe_code; /* 0x3d as iBEC left it */ + u8 probe_code; /* ILIM register as iBoot left it */ u8 last_written; /* 0 = nothing written while online */ u8 ceiling; /* after a sag, until unplugged; 0xff = none */ bool online; bool was_armed; bool hot; + u8 cool_samples; /* temp_guard: cool readings in a row */ u8 logged_code; /* last "would set" logged, to say it once */ }; -/* iBEC's encoding, 0x9ff0c618..0x9ff0c662 */ -static u8 pmu_chg_ma_to_code(unsigned int ma) -{ - unsigned int code; - - ma = min_t(unsigned int, ma, ILIM_HARD_MAX_MA); - if (ma < 100) - return ILIM_MIN_CODE; - code = (8 * ma - 600) / 100; - if (code >= 0x73) - return code - 4; - if (code > 0x6e) - return 0x6e; - if (code >= 0x4b) - return code - 2; - if (code > 0x48) - return 0x48; - return code; -} - -/* The nominal current of a code, for the log only. */ -static unsigned int pmu_chg_code_to_ma(u8 code) +static bool pmu_chg_armed(struct pmu_chg *c) { - return code <= ILIM_MIN_CODE ? 100 : (code * 100 + 600) / 8; + return c->chip == &pmu_chg_d1972 ? READ_ONCE(d1972_armed) : READ_ONCE(armed); } static int pmu_chg_write(struct pmu_chg *c, unsigned int reg, u8 val) { int ret; - if (reg != PMU_ILIM) { + if (reg != c->chip->ilim_reg) { dev_err(c->dev, "refusing PMU write 0x%02x = 0x%02x: only 0x%02x is ours\n", - reg, val, PMU_ILIM); + reg, val, c->chip->ilim_reg); return -EPERM; } ret = regmap_write(c->map, reg, val); @@ -153,8 +233,10 @@ static void pmu_chg_log_vbus(struct pmu_chg *c, u8 ilim, bool is_armed) int ret; u8 val; - dev_info(c->dev, "VBUS on: 0x3d = 0x%02x, %s\n", ilim, + dev_info(c->dev, "VBUS on: 0x%02x = 0x%02x, %s\n", c->chip->ilim_reg, ilim, is_armed ? "armed" : "disarmed"); + if (c->chip != &pmu_chg_d1946) + return; for (i = 0; i < ARRAY_SIZE(regs); i++) { ret = pmu_chg_read(c, regs[i], &val); if (ret) @@ -167,42 +249,90 @@ static void pmu_chg_log_vbus(struct pmu_chg *c, u8 ilim, bool is_armed) static void pmu_chg_sagged(struct pmu_chg *c, u8 at) { - c->ceiling = max_t(int, ILIM_MIN_CODE, at - ILIM_STEP); + c->ceiling = max_t(int, c->chip->min_code, at - c->chip->ramp_step); dev_warn(c->dev, "VBUS sagged at 0x%02x: limiting USB input current to %u mA until unplugged\n", - at, pmu_chg_code_to_ma(c->ceiling)); + at, c->chip->code_to_ma(c->ceiling)); } -/* Ramp 0x3d from cur up to target, 8 codes every 10 ms, watching for a sag. */ +/* Ramp ILIM from cur up to target, ramp_step codes every 10 ms, watching for a sag. */ static void pmu_chg_ramp(struct pmu_chg *c, u8 cur, u8 target) { while (cur < target) { - u8 next = min_t(int, cur + ILIM_STEP, target), rb; + u8 next = min_t(int, cur + c->chip->ramp_step, target), rb; - if (pmu_chg_write(c, PMU_ILIM, next)) + if (pmu_chg_write(c, c->chip->ilim_reg, next)) return; msleep(ILIM_STEP_MS); - if (pmu_chg_read(c, PMU_ILIM, &rb)) + if (pmu_chg_read(c, c->chip->ilim_reg, &rb)) return; - if (rb == ILIM_MIN_CODE && next > ILIM_MIN_CODE) { + if (rb == c->chip->min_code && next > c->chip->min_code) { pmu_chg_sagged(c, next); if (c->ceiling < next) - pmu_chg_write(c, PMU_ILIM, c->ceiling); + pmu_chg_write(c, c->chip->ilim_reg, c->ceiling); return; } if (rb != next) { - dev_warn(c->dev, "0x3d reads 0x%02x after writing 0x%02x; stopping the ramp\n", - rb, next); + dev_warn(c->dev, "0x%02x reads 0x%02x after writing 0x%02x; stopping the ramp\n", + c->chip->ilim_reg, rb, next); return; } cur = rb; } } +static bool pmu_chg_battery_hot_guarded(struct pmu_chg *c) +{ + union power_supply_propval t = {}; + struct power_supply *bat = power_supply_get_by_name("battery"); + int ret = -ENODEV; + + if (bat) { + ret = power_supply_get_property(bat, POWER_SUPPLY_PROP_TEMP, &t); + power_supply_put(bat); + if (!ret && (t.intval < GUARD_MIN_DECI_C || t.intval > GUARD_MAX_DECI_C)) + ret = -ERANGE; + } + + if (ret) { + /* no reading: the 100 mA fallback, and the cool count starts over */ + if (!c->hot) + dev_warn(c->dev, "battery temperature unavailable (%d%s): input limited to 100 mA\n", + ret == -ERANGE ? t.intval : ret, + ret == -ERANGE ? " deci-C, out of range" : ""); + c->hot = true; + c->cool_samples = 0; + return true; + } + + if (t.intval > HOT_DECI_C) { + if (!c->hot) + dev_warn(c->dev, "battery at %s%d.%d C: input limited to 100 mA\n", + t.intval < 0 ? "-" : "", abs(t.intval) / 10, abs(t.intval) % 10); + c->hot = true; + c->cool_samples = 0; + } else if (c->hot) { + if (t.intval < COOL_DECI_C && ++c->cool_samples >= COOL_SAMPLES) { + c->hot = false; + c->cool_samples = 0; + dev_info(c->dev, "battery back to %s%d.%d C (%d readings in a row)\n", + t.intval < 0 ? "-" : "", abs(t.intval) / 10, + abs(t.intval) % 10, COOL_SAMPLES); + } else if (t.intval >= COOL_DECI_C) { + c->cool_samples = 0; + } + } + return c->hot; +} + static bool pmu_chg_battery_hot(struct pmu_chg *c) { union power_supply_propval t; - struct power_supply *bat = power_supply_get_by_name("battery"); + struct power_supply *bat; + if (c->chip->temp_guard) + return pmu_chg_battery_hot_guarded(c); + + bat = power_supply_get_by_name("battery"); if (!bat) { c->hot = true; return true; @@ -230,35 +360,37 @@ static bool pmu_chg_battery_hot(struct pmu_chg *c) static u8 pmu_chg_target(struct pmu_chg *c) { unsigned int ma = min_t(unsigned int, c->req_ma, - clamp(READ_ONCE(max_input_ma), 100, ILIM_HARD_MAX_MA)); - u8 code = pmu_chg_ma_to_code(ma); + clamp(READ_ONCE(max_input_ma), 100, (int)c->chip->max_ma)); + u8 code = c->chip->ma_to_code(ma); if (c->ceiling != 0xff) code = min(code, c->ceiling); if (pmu_chg_battery_hot(c)) - code = ILIM_MIN_CODE; + code = c->chip->min_code; return code; } static void pmu_chg_work(struct work_struct *w) { struct pmu_chg *c = container_of(to_delayed_work(w), struct pmu_chg, work); - bool is_armed = READ_ONCE(armed), online, changed = false; + bool is_armed = pmu_chg_armed(c), online, changed = false; u8 st, cur, target; mutex_lock(&c->lock); if (c->was_armed && !is_armed) { - if (pmu_chg_write(c, PMU_ILIM, c->probe_code)) + if (pmu_chg_write(c, c->chip->ilim_reg, c->probe_code)) goto out; /* Leave restoration pending for the next poll. */ - dev_info(c->dev, "disarmed: 0x3d back to 0x%02x\n", c->probe_code); + dev_info(c->dev, "disarmed: 0x%02x back to 0x%02x\n", + c->chip->ilim_reg, c->probe_code); c->last_written = 0; c->logged_code = 0; c->was_armed = false; goto out; } - if (pmu_chg_read(c, PMU_STATUS0, &st) || pmu_chg_read(c, PMU_ILIM, &cur)) + if (pmu_chg_read(c, c->chip->status_reg, &st) || + pmu_chg_read(c, c->chip->ilim_reg, &cur)) goto out; - online = st & PMU_STATUS0_VBUS; + online = !!(st & c->chip->vbus_mask); changed = online != c->online; c->online = online; if (changed) { @@ -276,8 +408,9 @@ static void pmu_chg_work(struct work_struct *w) target = pmu_chg_target(c); if (!is_armed) { if (cur != target && target != c->logged_code) { - dev_info(c->dev, "disarmed: would set 0x3d 0x%02x -> 0x%02x (%u mA)\n", - cur, target, pmu_chg_code_to_ma(target)); + dev_info(c->dev, "disarmed: would set 0x%02x 0x%02x -> 0x%02x (%u mA)\n", + c->chip->ilim_reg, cur, target, + c->chip->code_to_ma(target)); c->logged_code = target; } goto out; @@ -285,14 +418,14 @@ static void pmu_chg_work(struct work_struct *w) c->was_armed = true; /* steady state: the PMU dropped what we set, so the source sagged */ - if (cur == ILIM_MIN_CODE && c->last_written > ILIM_MIN_CODE) { + if (cur == c->chip->min_code && c->last_written > c->chip->min_code) { pmu_chg_sagged(c, c->last_written); target = min(target, c->ceiling); } if (cur < target) pmu_chg_ramp(c, cur, target); else if (cur > target) - pmu_chg_write(c, PMU_ILIM, target); + pmu_chg_write(c, c->chip->ilim_reg, target); out: mutex_unlock(&c->lock); if (changed) @@ -325,7 +458,7 @@ static int pmu_chg_set(struct power_supply *psy, enum power_supply_property psp, if (psp != POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT) return -EINVAL; - if (ma < 100 || ma > clamp(READ_ONCE(max_input_ma), 100, ILIM_HARD_MAX_MA)) + if (ma < 100 || ma > clamp(READ_ONCE(max_input_ma), 100, (int)c->chip->max_ma)) return -ERANGE; mutex_lock(&c->lock); c->req_ma = ma; @@ -360,25 +493,31 @@ static const struct power_supply_desc pmu_chg_desc = { static int pmu_chg_probe(struct platform_device *pdev) { struct apple_pmu_i2c *pmu = dev_get_drvdata(pdev->dev.parent); + const struct pmu_chg_chip *chip = of_device_get_match_data(&pdev->dev); struct power_supply_config cfg = {}; struct pmu_chg *c; u8 st; int ret; + if (!chip) + return -ENODEV; + c = devm_kzalloc(&pdev->dev, sizeof(*c), GFP_KERNEL); if (!c) return -ENOMEM; c->dev = &pdev->dev; c->map = pmu->regmap; + c->chip = chip; c->req_ma = ILIM_DEFAULT_MA; c->ceiling = 0xff; mutex_init(&c->lock); - if (pmu_chg_read(c, PMU_ILIM, &c->probe_code) || pmu_chg_read(c, PMU_STATUS0, &st)) + if (pmu_chg_read(c, chip->ilim_reg, &c->probe_code) || + pmu_chg_read(c, chip->status_reg, &st)) return -EIO; - c->online = st & PMU_STATUS0_VBUS; + c->online = !!(st & chip->vbus_mask); if (c->online) - pmu_chg_log_vbus(c, c->probe_code, READ_ONCE(armed)); + pmu_chg_log_vbus(c, c->probe_code, pmu_chg_armed(c)); cfg.drv_data = c; cfg.of_node = pdev->dev.of_node; @@ -393,14 +532,16 @@ static int pmu_chg_probe(struct platform_device *pdev) if (ret) return ret; schedule_delayed_work(&c->work, msecs_to_jiffies(POLL_MS)); - dev_info(&pdev->dev, "0x3d = 0x%02x (%u mA) at probe, VBUS %s, %s\n", - c->probe_code, pmu_chg_code_to_ma(c->probe_code), - c->online ? "on" : "off", armed ? "armed" : "disarmed (log only)"); + dev_info(&pdev->dev, "%s: 0x%02x = 0x%02x (%u mA) at probe, VBUS %s, %s\n", + chip->name, chip->ilim_reg, c->probe_code, + chip->code_to_ma(c->probe_code), + c->online ? "on" : "off", pmu_chg_armed(c) ? "armed" : "disarmed (log only)"); return 0; } static const struct of_device_id pmu_chg_of_match[] = { - { .compatible = "apple,pmu-d1946-charger" }, + { .compatible = "apple,pmu-d1946-charger", .data = &pmu_chg_d1946 }, + { .compatible = "apple,pmu-d1972-charger", .data = &pmu_chg_d1972 }, { } }; MODULE_DEVICE_TABLE(of, pmu_chg_of_match); @@ -414,5 +555,5 @@ static struct platform_driver pmu_chg_driver = { }; module_platform_driver(pmu_chg_driver); -MODULE_DESCRIPTION("D1946 PMU USB input current limit (iPad mini 1)"); +MODULE_DESCRIPTION("Apple Dialog PMU (D1946/D1972) USB input current limit"); MODULE_LICENSE("GPL"); From 809f0a73ea99ec00e9acf5abe22b349ea966e785 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:59 +0100 Subject: [PATCH 14/43] backlight: Add the Apple LM3534 and DWI backlight MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The iPhone 5's D1972 PMU has no WLED strings, unlike the A5's D1946 and the A5X's D1974. Its panel backlight is an external TI LM3534 on I2C0 (0x63), whose brightness comes over the SoC's DWI block (0x3f107000, version 1). Add apple-lm3534, after AppleLMBacklight and AppleS5L8940XDWI (iPhone5,2 iOS 10.3.4): - enable and disable with LM3534 register 0x10 bit 0, keeping the other bits iBoot set, and wait 600 us after enabling; - send 11-bit brightness (0..2047) on the DWI sync channel: +0x14 = 0xa0000000 | level, then +0x10 = 0x71 once busy (bit 0) is clear. Tested on an iPhone5,2: "LM3534 reg 0x10=0x03 (on), DWI v1 attached", and a brightness of 300 is written and read back. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/video/backlight/Kconfig | 9 + drivers/video/backlight/Makefile | 1 + drivers/video/backlight/apple-lm3534.c | 245 +++++++++++++++++++++++++ 3 files changed, 255 insertions(+) create mode 100644 drivers/video/backlight/apple-lm3534.c diff --git a/drivers/video/backlight/Kconfig b/drivers/video/backlight/Kconfig index 361b50ea226ee7..b5ddc2c7ba3196 100644 --- a/drivers/video/backlight/Kconfig +++ b/drivers/video/backlight/Kconfig @@ -458,6 +458,15 @@ config BACKLIGHT_APPLE_PMU_WLED The iPad mini 1's backlight, driven by the white-LED strings of its D1946 PMU, as /sys/class/backlight/apple-pmu-wled (0..2047). +config BACKLIGHT_APPLE_LM3534 + tristate "Apple TI LM3534 + DWI backlight (iPhone 5 / N42)" + depends on I2C && OF + select REGMAP_I2C + help + Backlight driver for Apple S5L8950X devices (iPhone 5) using an + external TI LM3534 LED driver over I2C0 for enable control and the + SoC DWI block for 11-bit brightness updates (0..2047). + config BACKLIGHT_GPIO tristate "Generic GPIO based Backlight Driver" depends on GPIOLIB || COMPILE_TEST diff --git a/drivers/video/backlight/Makefile b/drivers/video/backlight/Makefile index 050be5fcab7df9..9547c361a9bd07 100644 --- a/drivers/video/backlight/Makefile +++ b/drivers/video/backlight/Makefile @@ -30,6 +30,7 @@ obj-$(CONFIG_BACKLIGHT_DA903X) += da903x_bl.o obj-$(CONFIG_BACKLIGHT_DA9052) += da9052_bl.o obj-$(CONFIG_BACKLIGHT_EP93XX) += ep93xx_bl.o obj-$(CONFIG_BACKLIGHT_APPLE_PMU_WLED) += apple-pmu-wled.o +obj-$(CONFIG_BACKLIGHT_APPLE_LM3534) += apple-lm3534.o obj-$(CONFIG_BACKLIGHT_GPIO) += gpio_backlight.o obj-$(CONFIG_BACKLIGHT_HP680) += hp680_bl.o obj-$(CONFIG_BACKLIGHT_HP700) += jornada720_bl.o diff --git a/drivers/video/backlight/apple-lm3534.c b/drivers/video/backlight/apple-lm3534.c new file mode 100644 index 00000000000000..a14c32cbe20fe3 --- /dev/null +++ b/drivers/video/backlight/apple-lm3534.c @@ -0,0 +1,245 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * TI LM3534 backlight driver with Apple S5L DWI brightness updates (iPhone 5 / N42). + * + * On N42 (S5L8950X), the Dialog D1972 PMU has no white-LED strings; the display + * backlight is driven by an external TI LM3534 on I2C0 (0x63, ADT "backlight,lm3534", + * using-LM3534 = 1) paired with the SoC's DWI block (0x3f107000, version = 1): + * + * - Enable/disable (AppleLMBacklight, 14G61 0x80e0c914): I2C register 0x10 + * bit 0 switches the output; enabling is followed by a 600 us delay. + * Other bits of 0x10 (boost/OVP/DWI mode set up by iBoot) are preserved. + * - Brightness (AppleS5L8940XDWI::sendWLED, 14G61 0x812d2860): 11-bit level + * 0..2047 encoded for DWI version 1 as (0xa0000000 | (level & 0x7ff)), + * written to DWI+0x14 after polling DWI+0x10 bit 0 clear, then triggered + * by writing 0x71 to DWI+0x10. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define LM3534_REG_ENABLE 0x10 +#define LM3534_ENABLE_BIT BIT(0) +#define LM3534_ENABLE_DELAY_US 600 + +#define LM3534_MAX_BRIGHTNESS 2047 +#define LM3534_DEFAULT_BRIGHTNESS 1024 + +#define DWI_SYNC_CTRL 0x10 +#define DWI_SYNC_DATA 0x14 +#define DWI_CTRL_BUSY BIT(0) +#define DWI_CTRL_TRIGGER 0x71 + +struct apple_lm3534 { + struct device *dev; + struct regmap *regmap; + void __iomem *dwi_base; + struct clk *dwi_clk; + u32 dwi_version; + bool enabled; +}; + +static const struct regmap_config apple_lm3534_regmap_config = { + .reg_bits = 8, + .val_bits = 8, + .max_register = 0xff, +}; + +static u32 apple_dwi_encode_wled(u32 level, u32 version) +{ + level &= 0x7ff; + if (version == 0) + return 0x20000000u | ((level & 0x3u) << 9) | (level >> 2); + return 0xa0000000u | level; +} + +static int apple_lm3534_dwi_send(struct apple_lm3534 *bl, u32 level) +{ + u32 val, word; + int ret; + + if (!bl->dwi_base) + return 0; + + ret = readl_poll_timeout(bl->dwi_base + DWI_SYNC_CTRL, val, + !(val & DWI_CTRL_BUSY), 10, 10000); + if (ret) { + dev_warn_ratelimited(bl->dev, "DWI busy timeout (ctrl=0x%08x)\n", val); + return ret; + } + + word = apple_dwi_encode_wled(level, bl->dwi_version); + writel(word, bl->dwi_base + DWI_SYNC_DATA); + writel(DWI_CTRL_TRIGGER, bl->dwi_base + DWI_SYNC_CTRL); + return 0; +} + +static int apple_lm3534_set_enable(struct apple_lm3534 *bl, bool enable) +{ + int ret; + + if (bl->enabled == enable) + return 0; + + ret = regmap_update_bits(bl->regmap, LM3534_REG_ENABLE, + LM3534_ENABLE_BIT, + enable ? LM3534_ENABLE_BIT : 0); + if (ret) + return ret; + + if (enable) + usleep_range(LM3534_ENABLE_DELAY_US, LM3534_ENABLE_DELAY_US + 200); + + bl->enabled = enable; + return 0; +} + +static int apple_lm3534_update_status(struct backlight_device *bd) +{ + struct apple_lm3534 *bl = bl_get_data(bd); + int level = backlight_get_brightness(bd); + int ret; + + if (!level) + return apple_lm3534_set_enable(bl, false); + + ret = apple_lm3534_set_enable(bl, true); + if (ret) + return ret; + + return apple_lm3534_dwi_send(bl, level); +} + +static const struct backlight_ops apple_lm3534_ops = { + .options = BL_CORE_SUSPENDRESUME, + .update_status = apple_lm3534_update_status, +}; + +static void apple_lm3534_dwi_clk_cleanup(void *clk) +{ + clk_disable_unprepare(clk); + clk_put(clk); +} + +static int apple_lm3534_attach_dwi(struct apple_lm3534 *bl) +{ + struct device_node *dwi_np; + struct resource res; + int ret; + + dwi_np = of_parse_phandle(bl->dev->of_node, "apple,dwi", 0); + if (!dwi_np) { + dev_warn(bl->dev, "no apple,dwi phandle: only on/off control available\n"); + return 0; + } + + bl->dwi_version = 1; + of_property_read_u32(dwi_np, "apple,dwi-version", &bl->dwi_version); + + ret = of_address_to_resource(dwi_np, 0, &res); + if (ret) { + of_node_put(dwi_np); + return ret; + } + + bl->dwi_base = devm_ioremap_resource(bl->dev, &res); + if (IS_ERR(bl->dwi_base)) { + of_node_put(dwi_np); + return PTR_ERR(bl->dwi_base); + } + + bl->dwi_clk = of_clk_get(dwi_np, 0); + of_node_put(dwi_np); + if (IS_ERR(bl->dwi_clk)) { + ret = PTR_ERR(bl->dwi_clk); + if (ret == -ENOENT) { + bl->dwi_clk = NULL; + return 0; + } + return dev_err_probe(bl->dev, ret, "failed to get DWI clock\n"); + } + + ret = clk_prepare_enable(bl->dwi_clk); + if (ret) { + clk_put(bl->dwi_clk); + bl->dwi_clk = NULL; + return ret; + } + + return devm_add_action_or_reset(bl->dev, apple_lm3534_dwi_clk_cleanup, + bl->dwi_clk); +} + +static int apple_lm3534_probe(struct i2c_client *i2c) +{ + struct backlight_properties props = {}; + struct backlight_device *bd; + struct apple_lm3534 *bl; + unsigned int reg_en = 0; + u32 def_level = LM3534_DEFAULT_BRIGHTNESS; + int ret; + + bl = devm_kzalloc(&i2c->dev, sizeof(*bl), GFP_KERNEL); + if (!bl) + return -ENOMEM; + + bl->dev = &i2c->dev; + bl->regmap = devm_regmap_init_i2c(i2c, &apple_lm3534_regmap_config); + if (IS_ERR(bl->regmap)) + return PTR_ERR(bl->regmap); + + ret = apple_lm3534_attach_dwi(bl); + if (ret) + return ret; + + ret = regmap_read(bl->regmap, LM3534_REG_ENABLE, ®_en); + if (ret) + return dev_err_probe(&i2c->dev, ret, "failed to read LM3534 enable reg\n"); + + bl->enabled = !!(reg_en & LM3534_ENABLE_BIT); + of_property_read_u32(i2c->dev.of_node, "default-brightness-level", &def_level); + if (def_level > LM3534_MAX_BRIGHTNESS) + def_level = LM3534_MAX_BRIGHTNESS; + + props.type = BACKLIGHT_RAW; + props.scale = BACKLIGHT_SCALE_NON_LINEAR; + props.max_brightness = LM3534_MAX_BRIGHTNESS; + props.brightness = bl->enabled ? def_level : 0; + props.power = bl->enabled ? BACKLIGHT_POWER_ON : BACKLIGHT_POWER_OFF; + + bd = devm_backlight_device_register(&i2c->dev, "apple-lm3534", &i2c->dev, bl, + &apple_lm3534_ops, &props); + if (IS_ERR(bd)) + return PTR_ERR(bd); + + i2c_set_clientdata(i2c, bd); + dev_info(&i2c->dev, "LM3534 reg 0x10=0x%02x (%s), DWI v%u %s\n", + reg_en, bl->enabled ? "on" : "off", bl->dwi_version, + bl->dwi_base ? "attached" : "absent"); + return 0; +} + +static const struct of_device_id apple_lm3534_of_match[] = { + { .compatible = "apple,lm3534-backlight" }, + { } +}; +MODULE_DEVICE_TABLE(of, apple_lm3534_of_match); + +static struct i2c_driver apple_lm3534_driver = { + .driver = { + .name = "apple-lm3534", + .of_match_table = apple_lm3534_of_match, + }, + .probe = apple_lm3534_probe, +}; +module_i2c_driver(apple_lm3534_driver); + +MODULE_DESCRIPTION("Apple TI LM3534 + DWI display backlight driver"); +MODULE_LICENSE("GPL"); From 2592debcb59b7de89d3244e5a766e416351028ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:59 +0100 Subject: [PATCH 15/43] ARM: configs: orchard_applearmv7: Enable the LM3534 backlight MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The iPhone 5's backlight needs it. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/configs/orchard_applearmv7_defconfig | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm/configs/orchard_applearmv7_defconfig b/arch/arm/configs/orchard_applearmv7_defconfig index 2c2acb6449b991..37c318f58ee0a2 100644 --- a/arch/arm/configs/orchard_applearmv7_defconfig +++ b/arch/arm/configs/orchard_applearmv7_defconfig @@ -520,6 +520,7 @@ CONFIG_BACKLIGHT_CLASS_DEVICE=y CONFIG_BACKLIGHT_PWM=y CONFIG_BACKLIGHT_AS3711=y CONFIG_BACKLIGHT_APPLE_PMU_WLED=y +CONFIG_BACKLIGHT_APPLE_LM3534=y CONFIG_BACKLIGHT_GPIO=y CONFIG_FRAMEBUFFER_CONSOLE_LEGACY_ACCELERATION=y CONFIG_FRAMEBUFFER_CONSOLE_ROTATION=y From 34e5bb1ba0ea8b10309bbfad4241610b124b8d86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:43:59 +0100 Subject: [PATCH 16/43] power: supply: apple-hdq-battery: Use Apple's HDQ transaction on the S5L8950X MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On the iPhone 5 most bq27540 reads failed ("no answer for 0x14") and the rest decoded to garbage: 65404 mV (0xff7c), and temperatures of 6272 C and -119 C (0xffab, 0x05ff) that the charger then acted on. The driver took "the last 8 frames" after a fixed 4.5 ms sleep, never checked the echo and read 16-bit values without a consistency check, so a missing or extra frame came through as a valid reading. Add "apple,s5l8950x-hdq-battery", which runs the transaction the way the N42 iBEC (12H321) and iOS AppleHDQGasGaugeControl-109.30.4 (_sendBreak, _hdqRead8, hdqRead16) do: - break: UCON bit 4 held for 200 us and cleared by hand, 40 us, drain; - a 0 is sent as 0xC0 (not 0xE0), a 1 as 0xFE; - each echoed frame is read back with a deadline and must equal what was sent; then 8 gauge frames, where a frame >= 0xF9 is a 1; frames with a UERSTAT error are dropped like iBEC's uart_getc does; - 8-bit reads get 4 tries 70 us apart, and 16-bit values are read hi, lo, hi and taken only when both hi reads agree (10 tries). A refresh reads into temporaries, rejects values no bq27540 reports (2500..5000 mV, -40..+90 C, at most 100%, ...), and commits all of them together. After a failure the bus rests for 5 s and the last good values are served for up to 30 s, so one bad transaction never reaches a consumer. Each failure or rejection logs one line with the raw frames and their UERSTAT bytes. The A5 boards ("apple,s5l8940x-hdq-battery") keep the original path. Tested on an iPhone5,2: 100%, 4229 mV, -84 mA, 25.9 C, 1448/1450 mAh (design 1440), 160 cycles. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/power/supply/apple-hdq-battery.c | 317 ++++++++++++++++++++++- 1 file changed, 315 insertions(+), 2 deletions(-) diff --git a/drivers/power/supply/apple-hdq-battery.c b/drivers/power/supply/apple-hdq-battery.c index 785bc0072f11a1..3ae2a1080c7efc 100644 --- a/drivers/power/supply/apple-hdq-battery.c +++ b/drivers/power/supply/apple-hdq-battery.c @@ -19,11 +19,28 @@ * Only reads (command bit 7 clear) are ever sent: register numbers are the * bq27541 family's standard commands, 16 bits as two 8-bit reads. * README ("Battery gauge") has the summary. + * + * The iPhone 5 (S5L8950X, N42) uses the transaction exactly as Apple writes + * it, in its iBEC (12H321, 0xbff143b4 / 0xbff14554 / 0xbff14248) and in iOS + * (AppleHDQGasGaugeControl 109.30.4: _sendBreak, _hdqRead8, hdqRead16): + * + * - break: UCON bit 4 set, 200 us, cleared by hand, 40 us, RX drained; + * - a 0 is sent as 0xC0 (start + six low bits, ~121 us), a 1 as 0xFE; + * - the 8 echoed frames are read back one by one and must equal what was + * sent, then 8 more are the gauge's: a frame of 0xF9 or more is a 1. + * Frames with a receive error (UERSTAT) are dropped, as iBEC does; + * - one 8-bit read is tried up to 4 times, 70 us apart (iOS); + * - a 16-bit value is read hi, lo, hi and taken only when both hi reads + * agree, up to 10 times (iBEC and iOS alike). + * + * That path is selected by "apple,s5l8950x-hdq-battery"; the A5 boards keep + * the original one unchanged. */ #include #include #include #include +#include #include #include #include @@ -36,6 +53,7 @@ #define UFCON 0x08 #define UTRSTAT 0x10 #define UTRSTAT_RXRDY BIT(0) /* Apple's UFSTAT layout differs from Samsung's */ +#define UERSTAT 0x14 /* error of the frame at the RX FIFO head */ #define UTXH 0x20 #define URXH 0x24 #define UBRDIV 0x28 @@ -60,6 +78,39 @@ #define BQ_SOC 0x2c /* % */ #define BQ_DCAP 0x3c /* mAh */ +struct hdq_variant { + bool apple_txn; /* iBEC/iOS transaction (S5L8950X) */ +}; + +static const struct hdq_variant hdq_s5l8940x = { .apple_txn = false }; +static const struct hdq_variant hdq_s5l8950x = { .apple_txn = true }; + +/* Apple transaction (S5L8950X path) */ +#define HDQ_TX1 0xFE +#define HDQ_TX0 0xC0 +#define HDQ_RX1_MIN 0xF9 +#define HDQ_BREAK_US 200 +#define HDQ_BREAK_REC_US 40 +#define HDQ_READ8_TRIES 4 +#define HDQ_READ8_GAP_US 70 +#define HDQ_READ16_TRIES 10 +#define HDQ_TXN_DEADLINE_US 10000 /* 16 frames are ~4 ms */ +#define HDQ_TRACE_LEN 24 /* 16 frames + dropped error frames */ +#define HDQ_STALE_OK (30 * HZ) /* last good values stay served */ + +/* the last failed (or rejected) 8-bit transaction, for the log */ +struct hdq_trace { + u8 reg; + u8 n; + const char *why; + u8 rx[HDQ_TRACE_LEN]; + u8 err[HDQ_TRACE_LEN]; +}; + +struct hdq_regs { + int soc, volt, ai, temp, rm, fcc, flags, cyct, dcap; +}; + struct hdq_battery { struct device *dev; void __iomem *base; @@ -68,6 +119,12 @@ struct hdq_battery { unsigned long stamp; /* jiffies of the last refresh */ int soc, volt, ai, temp, rm, fcc, flags, cyct, dcap; bool valid; + /* S5L8950X path only */ + const struct hdq_variant *var; + unsigned long fail_stamp; /* jiffies of the last failed refresh */ + int fail_ret; + unsigned int fails, retries; + struct hdq_trace trace; }; static void hdq_drain(struct hdq_battery *b) @@ -120,6 +177,235 @@ static int hdq_read16(struct hdq_battery *b, u8 reg) return -EIO; } +/* --- S5L8950X: Apple's transaction ------------------------------------- */ + +static void hdq_apple_drain(struct hdq_battery *b) +{ + int i; + + for (i = 0; i < 512 && (readl(b->base + UTRSTAT) & UTRSTAT_RXRDY); i++) { + readl(b->base + UERSTAT); + readl(b->base + URXH); + } +} + +/* iBEC 0xbff14554, iOS _sendBreak: the break bit is held and cleared by hand */ +static void hdq_apple_break(struct hdq_battery *b) +{ + writel(readl(b->base + UCON) | UCON_SBREAK, b->base + UCON); + udelay(HDQ_BREAK_US); + writel(readl(b->base + UCON) & ~UCON_SBREAK, b->base + UCON); + udelay(HDQ_BREAK_REC_US); + hdq_apple_drain(b); +} + +/* one frame and its UERSTAT (read first, as iBEC does), or -ETIMEDOUT */ +static int hdq_apple_rx(struct hdq_battery *b, ktime_t deadline, u8 *c, u8 *err) +{ + for (;;) { + if (readl(b->base + UTRSTAT) & UTRSTAT_RXRDY) { + *err = readl(b->base + UERSTAT) & 0xff; + *c = readl(b->base + URXH) & 0xff; + return 0; + } + if (ktime_after(ktime_get(), deadline)) + return -ETIMEDOUT; + /* the 16-deep FIFO holds a whole transaction */ + usleep_range(100, 200); + } +} + +/* one transaction: break, 8 command bits, their echo, the gauge's 8 bits */ +static int hdq_apple_txn8(struct hdq_battery *b, u8 reg, u8 *val) +{ + struct hdq_trace *t = &b->trace; + ktime_t deadline; + u8 tx[8], c, e; + int i, got = 0, v = 0; + + t->reg = reg; + t->n = 0; + t->why = NULL; + for (i = 0; i < 8; i++) /* LSB first; bit 7 clear: read */ + tx[i] = ((reg >> i) & 1) ? HDQ_TX1 : HDQ_TX0; + + hdq_apple_break(b); + for (i = 0; i < 8; i++) + writel(tx[i], b->base + UTXH); + + deadline = ktime_add_us(ktime_get(), HDQ_TXN_DEADLINE_US); + while (got < 16) { + if (t->n >= HDQ_TRACE_LEN) { + t->why = "too many error frames"; + return -EIO; + } + if (hdq_apple_rx(b, deadline, &c, &e)) { + t->why = got < 8 ? "echo timeout" : "no answer"; + return -EIO; + } + t->rx[t->n] = c; + t->err[t->n] = e; + t->n++; + if (e) + continue; /* dropped, as iBEC's uart_getc does */ + if (got < 8 && c != tx[got]) { + t->why = "echo mismatch"; + return -EIO; + } + if (got >= 8 && c >= HDQ_RX1_MIN) + v |= 1 << (got - 8); + got++; + } + *val = v; + return 0; +} + +/* iOS _hdqRead8 around it: up to 4 tries, 70 us apart */ +static int hdq_apple_read8(struct hdq_battery *b, u8 reg) +{ + u8 v; + int i; + + for (i = 0; i < HDQ_READ8_TRIES; i++) { + if (i) { + b->retries++; + udelay(HDQ_READ8_GAP_US); + } + if (!hdq_apple_txn8(b, reg, &v)) + return v; + } + return -EIO; +} + +/* iBEC 0xbff14248, iOS hdqRead16: hi, lo, hi again until both hi agree */ +static int hdq_apple_read16(struct hdq_battery *b, u8 reg) +{ + int hi, lo, hi2, i; + + for (i = 0; i < HDQ_READ16_TRIES; i++) { + if (i) { + b->retries++; + udelay(10); + } + hi = hdq_apple_read8(b, reg + 1); + if (hi < 0) + return hi; + lo = hdq_apple_read8(b, reg); + if (lo < 0) + return lo; + hi2 = hdq_apple_read8(b, reg + 1); + if (hi2 < 0) + return hi2; + if (hi == hi2) + return lo | hi << 8; + } + b->trace.reg = reg; + b->trace.why = "high byte unstable (hi lo hi)"; + b->trace.n = 3; + b->trace.rx[0] = hi; + b->trace.rx[1] = lo; + b->trace.rx[2] = hi2; + memset(b->trace.err, 0, 3); + return -EIO; +} + +/* a value no bq27540 reports means the wire lied, whatever the echo said */ +static const char *hdq_apple_implausible(const struct hdq_regs *r) +{ + if (r->soc > 100) + return "soc"; + if (r->volt < 2500 || r->volt > 5000) + return "volt"; + if (r->temp < 2731 - 400 || r->temp > 2731 + 900) /* -40..+90 C */ + return "temp"; + if (r->rm > 0x7fff || r->fcc > 0x7fff) + return "charge"; + if (r->dcap < 100 || r->dcap > 0x7fff) + return "dcap"; + if (r->cyct > 10000) + return "cycles"; + return NULL; +} + +/* + * Everything at once into temporaries, checked, then committed together. + * After a failure the bus is left alone for 5 s, and the last good values + * are served for up to 30 s, so one bad transaction reaches no consumer. + */ +static int hdq_apple_refresh(struct hdq_battery *b) +{ + struct hdq_regs r; + struct { u8 reg; int *dst; } m[] = { + { BQ_SOC, &r.soc }, { BQ_VOLT, &r.volt }, { BQ_AI, &r.ai }, + { BQ_TEMP, &r.temp }, { BQ_RM, &r.rm }, { BQ_FCC, &r.fcc }, + { BQ_FLAGS, &r.flags }, { BQ_CYCT, &r.cyct }, { BQ_DCAP, &r.dcap }, + }; + const struct hdq_trace *t = &b->trace; + const char *bad; + int i, v; + + if (b->valid && time_before(jiffies, b->stamp + 5 * HZ)) + return 0; + if (b->fail_ret && time_before(jiffies, b->fail_stamp + 5 * HZ)) + goto stale; + + for (i = 0; i < ARRAY_SIZE(m); i++) { + v = hdq_apple_read16(b, m[i].reg); + if (v < 0) { + b->fails++; + dev_warn_ratelimited(b->dev, + "refresh failed: reg %#04x (byte %#04x) %s; rx %u: %*ph; uerstat: %*ph; fails %u retries %u\n", + m[i].reg, t->reg, t->why ?: "?", t->n, t->n, t->rx, + t->n, t->err, b->fails, b->retries); + b->fail_ret = v; + goto failed; + } + *m[i].dst = v; + } + + bad = hdq_apple_implausible(&r); + if (bad) { + b->fails++; + dev_warn_ratelimited(b->dev, + "refresh rejected (%s): soc %04x volt %04x ai %04x temp %04x rm %04x fcc %04x flags %04x cyc %04x dcap %04x; fails %u retries %u\n", + bad, r.soc, r.volt, r.ai, r.temp, r.rm, r.fcc, r.flags, + r.cyct, r.dcap, b->fails, b->retries); + b->fail_ret = -EIO; + goto failed; + } + + b->soc = r.soc; + b->volt = r.volt; + b->ai = (s16)r.ai; + b->temp = r.temp; + b->rm = r.rm; + b->fcc = r.fcc; + b->flags = r.flags; + b->cyct = r.cyct; + b->dcap = r.dcap; + b->stamp = jiffies; + b->valid = true; + b->fail_ret = 0; + return 0; + +failed: + b->fail_stamp = jiffies; +stale: + if (b->valid && time_before(jiffies, b->stamp + HDQ_STALE_OK)) + return 0; + return b->fail_ret; +} + +/* UART5 as the boot chain left it, and whether the break bit clears itself */ +static void hdq_apple_probe_log(struct hdq_battery *b) +{ + u32 ulcon = readl(b->base + ULCON), ucon = readl(b->base + UCON); + u32 ufcon = readl(b->base + UFCON), ubrdiv = readl(b->base + UBRDIV); + + dev_dbg(b->dev, "UART5 as found: ULCON %#x UCON %#x UFCON %#x UBRDIV %#x\n", + ulcon, ucon, ufcon, ubrdiv); +} + /* everything at once, at most every 5 s: a 16-bit read is ~10 ms of bus */ static int hdq_refresh(struct hdq_battery *b) { @@ -130,6 +416,8 @@ static int hdq_refresh(struct hdq_battery *b) }; int i, v; + if (b->var->apple_txn) + return hdq_apple_refresh(b); if (b->valid && time_before(jiffies, b->stamp + 5 * HZ)) return 0; for (i = 0; i < ARRAY_SIZE(r); i++) { @@ -236,6 +524,9 @@ static int hdq_probe(struct platform_device *pdev) if (!b) return -ENOMEM; b->dev = &pdev->dev; + b->var = of_device_get_match_data(&pdev->dev); + if (!b->var) + b->var = &hdq_s5l8940x; mutex_init(&b->lock); b->base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(b->base)) @@ -246,17 +537,38 @@ static int hdq_probe(struct platform_device *pdev) if (IS_ERR(clk)) return dev_err_probe(&pdev->dev, PTR_ERR(clk), "UART5 power\n"); + if (b->var->apple_txn) + hdq_apple_probe_log(b); + writel(HDQ_ULCON, b->base + ULCON); writel(HDQ_UFCON, b->base + UFCON); writel(HDQ_UBRDIV, b->base + UBRDIV); writel(0, b->base + UFRACVAL); writel(HDQ_UCON, b->base + UCON); + if (b->var->apple_txn) { + /* does this UART end a break by itself? Apple never relies on it */ + writel(HDQ_UCON | UCON_SBREAK, b->base + UCON); + udelay(HDQ_BREAK_US); + dev_dbg(&pdev->dev, "break bit %s after %d us\n", + readl(b->base + UCON) & UCON_SBREAK ? "still set" : "cleared by the UART", + HDQ_BREAK_US); + writel(HDQ_UCON, b->base + UCON); + udelay(HDQ_BREAK_REC_US); + hdq_apple_drain(b); + } + mutex_lock(&b->lock); soc = hdq_refresh(b) ? -1 : b->soc; mutex_unlock(&b->lock); if (soc < 0) dev_warn(&pdev->dev, "the gauge does not answer yet\n"); + else if (b->var->apple_txn) + dev_info(&pdev->dev, "bq27540: %d%%, %d mV, %d mA, %s%d.%d C, %d/%d mAh (design %d), %d cycles, flags %#06x, retries %u\n", + b->soc, b->volt, b->ai, b->temp < 2731 ? "-" : "", + abs(b->temp - 2731) / 10, abs(b->temp - 2731) % 10, + b->rm, b->fcc, b->dcap, + b->cyct, b->flags, b->retries); else dev_info(&pdev->dev, "bq27540: %d%%, %d mV, %d mA, %d/%d mAh, %d cycles\n", b->soc, b->volt, b->ai, b->rm, b->fcc, b->cyct); @@ -268,7 +580,8 @@ static int hdq_probe(struct platform_device *pdev) } static const struct of_device_id hdq_of_match[] = { - { .compatible = "apple,s5l8940x-hdq-battery" }, + { .compatible = "apple,s5l8950x-hdq-battery", .data = &hdq_s5l8950x }, + { .compatible = "apple,s5l8940x-hdq-battery", .data = &hdq_s5l8940x }, { } }; MODULE_DEVICE_TABLE(of, hdq_of_match); @@ -282,5 +595,5 @@ static struct platform_driver hdq_driver = { }; module_platform_driver(hdq_driver); -MODULE_DESCRIPTION("bq27540 gas gauge on HDQ through UART5 (iPad mini 1)"); +MODULE_DESCRIPTION("bq27540 gas gauge on HDQ through UART5 (A5 iPads, iPhone 5)"); MODULE_LICENSE("GPL"); From e4e500d76eec8476df285f05ed19b0a24e343728 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:44:00 +0100 Subject: [PATCH 17/43] Input: apple-z2: Boot an N1 digitizer in the kernel when the DT names its firmware MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On the iPad mini the digitizer is booted from userspace: Project Cascadia's z2-boot uploads the mtprops' firmware and calibration through /dev/hx-touch and then hands the chip to this driver. The iPhone 5 has the same iOS driver class, AppleMultitouchN1SPI, so the kernel can run that sequence itself and the panel works with no daemon. When the node has firmware-name, a work item does iOS 8.4.1's bootload: - a reset, then the HBPP check; - the firmware packet, unchanged; - the proximity and panel calibration, from the boot loader's apple,z2-prox-cal-blob and apple,z2-cal-blob properties, or from apple/z2-prox-cal.bin and apple/z2-cal.bin when the DT has none; - performCalibSeq, with apple,fll-mval, apple,ref-clk-div-val and apple,clk32-clock-enable-val written raw, as iOS 10.3.4's MTSPIBootloader_N1 does; - EXECUTE. Then it does what iOS does next: wake, device info, the GETs (d9 gives the surface) and SET bf/af. The bf value is a module parameter because it differs per device. If the boot fails, the chip is powered off and /dev/hx-touch is released. Boards without firmware-name keep the userspace path unchanged. Also add an spi_device_id table so the SPI core stops warning. The bootload steps and the first frames are logged at debug level. Tested on an iPhone5,2: firmware (64340 bytes) and calibration accepted, family 0x57, a 5000 x 8900 surface, and with a finger on the screen 526 interrupts and one-touch frames whose coordinates moved. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/input/touchscreen/apple-z2.c | 73 +++++++++++++++++++++++++--- 1 file changed, 67 insertions(+), 6 deletions(-) diff --git a/drivers/input/touchscreen/apple-z2.c b/drivers/input/touchscreen/apple-z2.c index ce919d5b062613..4561cb806f87fe 100644 --- a/drivers/input/touchscreen/apple-z2.c +++ b/drivers/input/touchscreen/apple-z2.c @@ -89,6 +89,8 @@ struct hx_touch_data { struct completion irq_done; struct work_struct boot_work; const char *firmware_name; + bool raw_packet; + u32 ref_clk_div; u32 execute_addr; u32 cal_addr; u32 fll_mval; @@ -768,7 +770,7 @@ static int hx_touch_hbpp_upload(struct hx_touch_data *hxt, const u8 *packet, } static int hx_touch_hbpp_cal_data(struct hx_touch_data *hxt, - const struct firmware *cal) + const struct firmware *cal, u32 addr) { const u8 ack[] = { 0x1a, 0xa1 }; u8 *pkt = hxt->tx_data; @@ -781,7 +783,7 @@ static int hx_touch_hbpp_cal_data(struct hx_touch_data *hxt, padded = ALIGN(len, 4); put_unaligned_be32(0x18e13001, pkt); put_unaligned_be16(padded / 4, pkt + 4); - hx_touch_hbpp_put32(pkt + 6, hxt->cal_addr + off); + hx_touch_hbpp_put32(pkt + 6, addr + off); put_unaligned_be16(hx_touch_sum16(pkt + 4, 6), pkt + 10); sum = 0; @@ -875,7 +877,7 @@ static int hx_touch_n1_calibrate(struct hx_touch_data *hxt) u32 addr, value; } regs[] = { { 0x10003060, hxt->fll_mval }, /* FLL M value */ - { 0x1000305c, 0x20 }, /* reference clock divider */ + { 0x1000305c, hxt->ref_clk_div }, /* reference clock divider */ { 0x10003058, 6 }, { 0x10003000, 3 }, /* constant calibration */ { 0x10003518, 1 }, /* clk32 enable */ @@ -1025,6 +1027,32 @@ static int hx_touch_n1_start_scan(struct hx_touch_data *hxt) return 0; } +/* The bootloader can supply per-unit calibration directly in the DT. */ +static int hx_touch_n42_cal(struct hx_touch_data *hxt, const char *prop, + const char *name, u32 addr, size_t limit) +{ + struct device *dev = &hxt->spi->dev; + const struct firmware *file = NULL; + struct firmware blob = {}; + int len, ret; + + blob.data = of_get_property(dev->of_node, prop, &len); + if (blob.data && len > 0 && memchr_inv(blob.data, 0, len)) { + blob.size = len; + } else { + ret = firmware_request_nowarn(&file, name, dev); + if (ret) + return ret == -ENOENT ? 0 : ret; + blob = *file; + } + if (!blob.size || blob.size > limit) + ret = -EINVAL; + else + ret = hx_touch_hbpp_cal_data(hxt, &blob, addr); + release_firmware(file); + return ret; +} + static int hx_touch_n1_boot(struct hx_touch_data *hxt, const u8 *packet, size_t len, const struct firmware *cal) { @@ -1056,9 +1084,17 @@ static int hx_touch_n1_boot(struct hx_touch_data *hxt, const u8 *packet, ret = hx_touch_hbpp_upload(hxt, packet, len); if (ret) return ret; - /* P105 has no prox-calibration in its ADT. */ - if (cal) { - ret = hx_touch_hbpp_cal_data(hxt, cal); + if (hxt->raw_packet) { + ret = hx_touch_n42_cal(hxt, "apple,z2-prox-cal-blob", + "apple/z2-prox-cal.bin", 0x10009600, 128); + if (ret) + return ret; + ret = hx_touch_n42_cal(hxt, "apple,z2-cal-blob", "apple/z2-cal.bin", + hxt->cal_addr, 0x600); + if (ret) + return ret; + } else if (cal) { + ret = hx_touch_hbpp_cal_data(hxt, cal, hxt->cal_addr); if (ret) return ret; } @@ -1082,6 +1118,25 @@ static void hx_touch_boot_work(struct work_struct *work) ret = request_firmware(&fw, hxt->firmware_name, dev); if (ret) return; + if (hxt->raw_packet) { + ret = -EINVAL; + if (fw->size >= 20 && fw->size <= SZ_128K && + !memcmp(fw->data, "\x18\xe1\x30\x01", 4)) { + ret = hx_touch_power_on(hxt); + if (!ret) { + ret = hx_touch_n1_boot(hxt, fw->data, fw->size, NULL); + if (ret) + hx_touch_power_off(hxt); + } + } + release_firmware(fw); + if (ret) { + dev_err(dev, "touch controller boot failed: %pe\n", ERR_PTR(ret)); + return; + } + packet = NULL; + goto ready; + } len = hx_touch_decode_mtprops(fw, &packet); release_firmware(fw); if (len < 0) { @@ -1111,6 +1166,7 @@ static void hx_touch_boot_work(struct work_struct *work) goto release_cal; } + ready: mutex_lock(&hxt->mutex); hxt->ready = 1; hx_touch_read_all_reports(hxt); @@ -1193,6 +1249,9 @@ static int hx_touch_spi_probe(struct spi_device *spi) if (device_get_match_data(&spi->dev)) { struct device_node *np = spi->dev.of_node; + hxt->raw_packet = of_device_is_compatible(np, "apple,n42-z2-multitouch"); + hxt->ref_clk_div = 0x20; + of_property_read_u32(np, "apple,ref-clk-div-val", &hxt->ref_clk_div); if (of_property_read_string(np, "firmware-name", &hxt->firmware_name) || of_property_read_u32(np, "apple,firmware-execute-address", &hxt->execute_addr) || of_property_read_u32(np, "apple,calibration-address", &hxt->cal_addr) || @@ -1322,6 +1381,7 @@ static void hx_touch_spi_remove(struct spi_device *spi) static const bool hx_touch_n1 = true; static const struct of_device_id hx_touch_of_match[] = { + { .compatible = "apple,n42-z2-multitouch", .data = &hx_touch_n1 }, { .compatible = "apple,p105-z2-multitouch", .data = &hx_touch_n1 }, { .compatible = "apple,z2-multitouch" }, { }, @@ -1329,6 +1389,7 @@ static const struct of_device_id hx_touch_of_match[] = { MODULE_DEVICE_TABLE(of, hx_touch_of_match); static const struct spi_device_id hx_touch_spi_ids[] = { + { "n42-z2-multitouch" }, { "p105-z2-multitouch" }, { "z2-multitouch" }, { } From e51de1b45b5d9e30203846f6c11ced10b3acc9c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:44:00 +0100 Subject: [PATCH 18/43] ARM: dts: apple: iPhone 5: Describe the peripherals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add what the N41 and N42 share to s5l8950x-5.dtsi, from the iPhone5,2 iOS 8.4.1 (12H321) ADT and the 10.3.4 (14G61) ADT and kernelcache: - gpio-keys: Home, Hold, Volume Up and Down, and the ringer switch; - I2C0: the D1972 PMU (0x74) with its charger, the touch power switches and WL_REG_ON; the LM3534 backlight (0x63) and the DWI block; - I2C1: the LIS3DSH accelerometer and AK8963 compass (no driver binds them yet); - SPI1: the Gen1 Z2 touch controller, its 32768 Hz PWM clock, and the firmware name and clock values that let the kernel boot it; - UART3: the BCM4334 Bluetooth; - UART5 as HDQ for the bq27540 gauge, with Apple's transaction; - EHCI with the BCM4334 Wi-Fi on HSIC port 4; - the CLCD and DSIM, disabled until there is a display driver. Each consumer's PMGR gate is enabled next to it. The I2C controllers take their gates as their clock, so the driver holds them from probe. The wifi0, bluetooth0 and touchscreen0 aliases let the boot loader fill in the unit's MAC and Bluetooth addresses and its touch calibration. Without the Wi-Fi address brcmfmac would use the NVRAM placeholder 02:00:00:00:00:00. Tested on an iPhone5,2: WPA2 on 5 GHz with DHCP, DNS and HTTP; the Bluetooth patchram loads; the gauge, charger, backlight and touch work as their driver commits describe; the buttons probe. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 398 ++++++++++++++++++++++++ 1 file changed, 398 insertions(+) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index 0d8858f3ece075..0a68f210c29579 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -13,6 +13,56 @@ / { aliases { serial0 = &uart6; + bluetooth0 = &bluetooth; + touchscreen0 = &touchscreen; + wifi0 = &wifi; + }; + + /* + * Physical buttons and mute switch (ADT /buttons): active-low on SoC + * GPIOs 0..4, identical layout to P105 (iPad mini 1). + * Codes: KEY_HOMEPAGE 172, KEY_POWER 116, KEY_VOLUMEUP 115, + * KEY_VOLUMEDOWN 114, EV_SW 5, SW_MUTE_DEVICE 14. + */ + gpio-keys { + compatible = "gpio-keys"; + autorepeat; + + home { + label = "Home"; + gpios = <&gpio 0 1>; + linux,code = <172>; + debounce-interval = <20>; + }; + + hold { + label = "Hold"; + gpios = <&gpio 1 1>; + linux,code = <116>; + debounce-interval = <20>; + }; + + volume-up { + label = "Volume Up"; + gpios = <&gpio 2 1>; + linux,code = <115>; + debounce-interval = <20>; + }; + + volume-down { + label = "Volume Down"; + gpios = <&gpio 3 1>; + linux,code = <114>; + debounce-interval = <20>; + }; + + ringer-switch { + label = "Ringer Switch"; + gpios = <&gpio 4 1>; + linux,input-type = <5>; + linux,code = <14>; + debounce-interval = <50>; + }; }; }; @@ -28,3 +78,351 @@ &uart6 { status = "okay"; }; + +&gpio { + /* + * UART3 (Bluetooth): ADT function-tx = 0x0400 (pin 32), function-rts = + * 0x0402 (pin 34), so TX=32, RX=33, RTS=34, CTS=35. + */ + uart3_pins: uart3-pins { + pins = "gpio32", "gpio33", "gpio34", "gpio35"; + function = "periph"; + }; +}; + +/* + * The PMGR gates of the consumers below (s5l8950x.dtsi keeps every gate + * disabled until a board has a consumer for it). Each consumer holds its + * gate from probe: I2C, SPI and HDQ enable their clock at probe, the + * LM3534 backlight enables the DWI's, and the UART3 serial port its own + * while the Bluetooth line discipline has it open. + */ +&i2c0_ps { + status = "okay"; +}; + +&i2c1_ps { + status = "okay"; +}; + +&spi1_ps { + status = "okay"; +}; + +&uart3_ps { + status = "okay"; +}; + +&uart5_ps { + status = "okay"; +}; + +/* + * UART3: BCM4334 Bluetooth half (ADT uart3/bluetooth, "bluetooth,n88"). + * function-power_enable = PMU GPIO 8 (0x68 + 8 = 0x70) + * function-bt_wake = SoC GPIO 7 (0x0007) + * Patchram: "BCM4334B1 37.4 MHz Centennial Murata" -> brcm/BCM4334B0.hcd. + * local-bd-address is filled at boot by m1n1 via the bluetooth0 alias. + */ +&uart3 { + pinctrl-names = "default"; + pinctrl-0 = <&uart3_pins>; + status = "okay"; + + bluetooth: bluetooth { + compatible = "brcm,bcm4334-bt"; + shutdown-gpios = <&pmu 8 0>; + device-wakeup-gpios = <&gpio 7 0>; + max-speed = <1500000>; + local-bd-address = [00 00 00 00 00 00]; + }; +}; + +/* + * Attach Wi-Fi WL_REG_ON (PMU GPIO 10 = reg 0x72) to the shared S5L8950X + * USB/HSIC PHY defined in s5l8950x.dtsi. + */ +&otgphy { + hsic-supply = <&wlan_reg_on>; +}; + +&soc { + /* + * DWI power-state switch (PMGR device-clocks index 0x4d -> 0xf101134). + * SPI1/UART3/UART5/I2C* power-state gates come from s5l8950x.dtsi. + */ + dwi_ps: dwi-ps@f101134 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf101134 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "dwi_ps"; + }; + + /* + * Touch 32768 Hz reference clock: PWM channel 2 (live ADT + * /arm-io/pwm/grape-clk, reg = 2, default-hz = 32768; multi-touch + * function-clock_enable = Cmwp). PMGR gate is index 0x49 = 0xf101124. + * + * Note: the vibrator (live ADT /arm-io/pwm/vibrator, PWM ch 1, + * default-hz = 32000, enable = SoC GPIO 95 = 0x0b07) shares this + * 0x33500000 MMIO window and is deferred until PWM is split into a + * shared provider. + */ + touchclk: touchclk@3500000 { + compatible = "apple,s5l8940x-pwm-clk"; + #clock-cells = <0>; + reg = <0x3500000 0x1000>, <0xf101124 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "touchclk"; + clock-frequency = <32768>; + apple,pwm-channel = <2>; + }; + + /* + * Digital Wire Interface (live ADT /arm-io/dwi, version = 1): carries + * 11-bit brightness commands to the external TI LM3534 backlight. + */ + dwi: dwi@f107000 { + compatible = "apple,s5l8950x-dwi", "apple,s5l8940x-dwi"; + reg = <0xf107000 0x1000>; + clocks = <&dwi_ps>; + apple,dwi-version = <1>; + }; + + /* + * I2C0: Dialog D1972 PMU (0x74), TI LM3534 backlight (0x63), plus + * audio/gyro/tristar (deferred). Confirmed from live 12H321 ADT. + */ + i2c0: i2c@3200000 { + compatible = "apple,s5l8940x-i2c"; + reg = <0x3200000 0x1000>; + clock-frequency = <100000>; + interrupts = <18>; + clocks = <&i2c0_ps>; + clock-names = "i2c"; + #address-cells = <1>; + #size-cells = <0>; + status = "okay"; + + pmu: pmu@74 { + compatible = "apple,pmu-d1972"; + reg = <0x74>; + system-power-controller; + gpio-controller; + #gpio-cells = <2>; + #address-cells = <1>; + #size-cells = <0>; + + /* + * Live ADT multi-touch function-power_ana = 0x020c (LDO 12): + * AppleD1972PMU LDO table (0x810ece34) gives en_reg = 0x22, + * en_mask = 0x04. Whether the scan also needs LDO 15 (0x22 + * bit 0x40), as on the iPad mini 1, is not known yet. + */ + touch_ana: touch_ana@22 { + compatible = "apple,pmu-pwrsw"; + reg = <0x22>; + mask = <0x04>; + enable = <0x04>; + }; + + /* + * Live ADT multi-touch function-power_ldo = 0x0213 (LDO 19): + * AppleD1972PMU LDO table gives en_reg = 0x23, en_mask = 0x40. + */ + touch_ldo: touch_ldo@23 { + compatible = "apple,pmu-pwrsw"; + reg = <0x23>; + mask = <0x40>; + enable = <0x40>; + }; + + /* + * BCM4334 WL_REG_ON: live ADT wlan function-device_reset is + * PMU GPIO 10 (0x68 + 10 = 0x72), bit 1 is output level. + */ + wlan_reg_on: wlan_reg_on@72 { + compatible = "apple,pmu-pwrsw"; + reg = <0x72>; + mask = <0x02>; + enable = <0x02>; + }; + + /* + * D1972 USB input current limit (register 0x3f, 10 mA/LSB + * from 70 mA; VBUS online = 0x0a bit 6; sag = 0x03). + * Log-only until apple_pmu_charger.armed=1. + */ + charger@3f { + compatible = "apple,pmu-d1972-charger"; + reg = <0x3f>; + }; + }; + + /* + * External TI LM3534 display backlight (live ADT "backlight,lm3534", + * using-LM3534 = 1): enable via I2C reg 0x10 bit 0, 11-bit + * brightness via DWI block. + */ + backlight: lm3534@63 { + compatible = "apple,lm3534-backlight"; + reg = <0x63>; + apple,dwi = <&dwi>; + }; + }; + + /* + * I2C1: motion sensors (LIS3DSH accelerometer @ 0x1d, AK8963 compass @ 0x0c). + */ + i2c1: i2c@3300000 { + compatible = "apple,s5l8940x-i2c"; + reg = <0x3300000 0x1000>; + clock-frequency = <100000>; + interrupts = <19>; + clocks = <&i2c1_ps>; + clock-names = "i2c"; + #address-cells = <1>; + #size-cells = <0>; + status = "okay"; + + accelerometer@1d { + compatible = "st,lis3dsh-accel"; + reg = <0x1d>; + }; + + compass@c { + compatible = "asahi-kasei,ak8963"; + reg = <0x0c>; + }; + }; + + /* + * SPI1: Gen1 Z2 multi-touch controller (live ADT multi-touch,n41; + * AppleMultitouchN1SPI C1F57,1, Family 0x57, 25x10, 5000x8900, N42.mtprops). + * GPIOs (port << 8 | pin): + * function-enable_cs = 0x0601 -> SoC GPIO 49 + * function-reset = 0x1c07 -> SoC GPIO 231 + * ATTN interrupt = 0xc9 -> SoC GPIO 201 (active-low) + */ + spi1: spi@2100000 { + compatible = "apple,s5l8940x-spi"; + reg = <0x2100000 0x1000>; + interrupts = <29>; + clocks = <&spi1_ps>; + #address-cells = <1>; + #size-cells = <0>; + status = "okay"; + + /* + * The kernel boots the digitizer, as iOS 8.4.1's + * AppleMultitouchN1SPI does. firmware-name is the "Constructed + * Firmware" of the C1F57,1 entry in the firmware's N42.mtprops. + * The panel and prox calibration come from the boot loader + * (ADT multi-touch-calibration and prox-calibration, copied + * through the touchscreen0 alias). The clock values are those + * of the "AppleMultitouchSPI - C1,N41" personality: fll-mval + * 6099, ref-clk-div-val 2, clk32-clock-enable-val 1. + */ + touchscreen: touch@0 { + compatible = "apple,n42-z2-multitouch"; + reg = <0>; + spi-max-frequency = <5000000>; + generation = <1>; + firmware-name = "apple/z2-n42.bin"; + apple,fll-mval = <0x17d3>; + apple,ref-clk-div-val = <2>; + apple,firmware-execute-address = <0x10003400>; + apple,calibration-address = <0x10009000>; + apple,scan-start-report = [9b 0b 0b 02]; + hv-supply = <&touch_ana>; + core-supply = <&touch_ldo>; + reset-gpios = <&gpio 231 0>; + cs-gpios = <&gpio 49 0>; + irq-gpios = <&gpio 201 1>; + touchscreen-inverted-y; + clocks = <&touchclk>; + }; + }; + + /* + * UART5 as 1-wire HDQ for the TI bq27540 gas gauge (live ADT + * uart5/gas-gauge, pin 44 = 0x0504, PMGR gate uart5_ps @ 0xf10110c). + * Delete the disabled UART5 serial node from s5l8950x.dtsi so there + * is no duplicate unit-address at @2a00000. + */ + /delete-node/ serial@2a00000; + + /* + * s5l8950x: the driver runs Apple's own HDQ transaction here (iBEC + * and AppleHDQGasGaugeControl): 0xC0 for a 0, an echo check, 0xF9 + * threshold, hi-lo-hi 16-bit reads. + */ + battery: hdq@2a00000 { + compatible = "apple,s5l8950x-hdq-battery", "apple,s5l8940x-hdq-battery"; + reg = <0x2a00000 0x1000>; + clocks = <&uart5_ps>; + status = "okay"; + }; + + /* + * EHCI host for BCM4334 B3 Murata Wi-Fi (M=HEIN m=6.9 V=m, 0a5c:bd1a, + * centennial.trx + heineken-m-ms.txt) on HSIC port 4. + * Port 2 (cellular baseband) is intentionally masked out. + */ + ehci: usb@6400000 { + compatible = "apple,s5l8950x-ehci", "apple,s5l8940x-ehci", + "generic-ehci"; + reg = <0x6400000 0x10000>; + interrupts = <12>; + phys = <&otgphy 1>; + phy-names = "usb"; + apple,hsic-ports = <0x8>; + #address-cells = <1>; + #size-cells = <0>; + status = "okay"; + + /* + * brcm,bcm4329-fmac lets brcmfmac read local-mac-address from + * this node; m1n1 fills it from the ADT's mac-address-wifi0 + * through the wifi0 alias (otherwise the NVRAM placeholder + * 02:00:00:00:00:00 is the MAC). + */ + wifi: wifi@4 { + compatible = "usba5c,bd1a", "brcm,bcm4329-fmac"; + reg = <4>; + /* Live ADT wlan: HOST_READY 0x0606 = 54, DEVICE_READY 0x0701 = 57 */ + apple,host-ready-gpios = <&gpio 54 0>; + apple,device-ready-gpios = <&gpio 57 0>; + }; + }; + + /* + * Display pipeline (live AppleMobileCLCD: 640x1136, stride 2560, BGRA / + * a8r8g8b8, PixelClock 102.6 MHz; lcd,pinot reset GPIO 202, LDO 13). + * First-stage display uses framebuffer0 (simple-framebuffer) in + * s5l8950x.dtsi; CLCD and MIPI-DSIM stay disabled until KMS bring-up. + */ + clcd: display-controller@a104000 { + compatible = "apple,s5l8950x-clcd", "apple,s5l8940x-clcd"; + reg = <0xa104000 0x1000>, <0x9200000 0x1000>; + status = "disabled"; + }; + + dsim: dsi@9500000 { + compatible = "apple,s5l8950x-mipi-dsim", "apple,s5l8940x-mipi-dsim", + "samsung,mipi-dsim-1"; + reg = <0x9500000 0x1000>; + interrupts = <41>; + #address-cells = <1>; + #size-cells = <0>; + apple,lanes = <4>; + status = "disabled"; + + panel@0 { + compatible = "apple,lcd-pinot"; + reg = <0>; + status = "disabled"; + }; + }; +}; From d593bce32ccd474f335ad381d31b655e56832c45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:02:51 +0100 Subject: [PATCH 19/43] dt-bindings: input: Describe the N42 Z2 touchscreen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- .../touchscreen/apple,p105-z2-multitouch.yaml | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/Documentation/devicetree/bindings/input/touchscreen/apple,p105-z2-multitouch.yaml b/Documentation/devicetree/bindings/input/touchscreen/apple,p105-z2-multitouch.yaml index 6366261e5799d6..b27edd46162987 100644 --- a/Documentation/devicetree/bindings/input/touchscreen/apple,p105-z2-multitouch.yaml +++ b/Documentation/devicetree/bindings/input/touchscreen/apple,p105-z2-multitouch.yaml @@ -4,7 +4,7 @@ $id: http://devicetree.org/schemas/input/touchscreen/apple,p105-z2-multitouch.yaml# $schema: http://devicetree.org/meta-schemas/core.yaml# -title: Apple P105 Z2 N1 touchscreen +title: Apple Z2 N1 touchscreen maintainers: - Alexandre Figueiredo <17xande@gmail.com> @@ -15,7 +15,9 @@ allOf: properties: compatible: - const: apple,p105-z2-multitouch + enum: + - apple,n42-z2-multitouch + - apple,p105-z2-multitouch reg: maxItems: 1 @@ -43,7 +45,7 @@ properties: firmware-name: maxItems: 1 - description: mtprops file containing the preconstructed HBPP DATA packet + description: HBPP DATA packet on N42 or an mtprops file containing it on P105 generation: $ref: /schemas/types.yaml#/definitions/uint32 @@ -62,6 +64,21 @@ properties: $ref: /schemas/types.yaml#/definitions/uint32 description: Frequency-locked loop multiplier used to calibrate the digitizer + apple,ref-clk-div-val: + $ref: /schemas/types.yaml#/definitions/uint32 + description: Reference clock divider for the digitizer calibration + default: 32 + + apple,z2-prox-cal-blob: + $ref: /schemas/types.yaml#/definitions/uint8-array + maxItems: 128 + description: Per-device proximity calibration supplied by the bootloader + + apple,z2-cal-blob: + $ref: /schemas/types.yaml#/definitions/uint8-array + maxItems: 1536 + description: Per-device panel calibration supplied by the bootloader + apple,scan-start-report: $ref: /schemas/types.yaml#/definitions/uint8-array minItems: 4 From 6e65bc8731e1bbc791ac02fad7256ecd0a418e96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:06:03 +0100 Subject: [PATCH 20/43] ARM: dts: apple: Correct the iPhone 5 DWI register address MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The N42 ADT places the brightness controller at 0xf700000. Use its register window to restore brightness after blanking. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index 0a68f210c29579..70f60010996959 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -180,12 +180,16 @@ }; /* - * Digital Wire Interface (live ADT /arm-io/dwi, version = 1): carries - * 11-bit brightness commands to the external TI LM3534 backlight. + * Digital Wire Interface (live ADT /arm-io/dwi@F700000, reg 0xf700000, + * version = 1): carries 11-bit brightness commands to the external TI + * LM3534 backlight. iBoot leaves it set up (+0x00 = 1, +0x04 = 0x78) + * with its last level in +0x14. 0xf107000 lies past the PMGR's range: + * no level ever reached the LM3534, and once dark the panel never lit + * again. */ - dwi: dwi@f107000 { + dwi: dwi@f700000 { compatible = "apple,s5l8950x-dwi", "apple,s5l8940x-dwi"; - reg = <0xf107000 0x1000>; + reg = <0xf700000 0x1000>; clocks = <&dwi_ps>; apple,dwi-version = <1>; }; From 0456d20e5c0c63c7de21bfee9dce45d21ea63cfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:44:00 +0100 Subject: [PATCH 21/43] dt-bindings: mtd: apple,h2fmi: Add the S5L8950X controller and its gates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add "apple,s5l8950x-fmi" for the A6 (iPhone 5) H2FMI, which the driver runs read-only, and an optional clocks list for the PMGR power-state gates the controller needs. It is required on the S5L8950X, where a read of a gated block stalls the bus: ADT flash-controller0 clock-gates 0x14..0x18 (FMI0, FMI0-BCH, FMI1, FMI1-BCH, FMI-DLL). The A6 node must not list "apple,s5l8940x-fmi" as a fallback: a driver without the S5L8950X entry would bind it writable. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- .../devicetree/bindings/mtd/apple,h2fmi.yaml | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/Documentation/devicetree/bindings/mtd/apple,h2fmi.yaml b/Documentation/devicetree/bindings/mtd/apple,h2fmi.yaml index a60445d3b5f61b..1afa825403754e 100644 --- a/Documentation/devicetree/bindings/mtd/apple,h2fmi.yaml +++ b/Documentation/devicetree/bindings/mtd/apple,h2fmi.yaml @@ -10,13 +10,16 @@ maintainers: - Shayne Legault <8741557+shaynelegault@users.noreply.github.com> description: - The H2FMI controller drives the Hynix PPN packages used as boot storage on + The H2FMI controller drives the PPN packages used as boot storage on Apple S5L8940X-family devices. Each of its two buses has separate FMI, FMC - and ECC register windows. + and ECC register windows. The S5L8950X (A6) controller is driven + read-only and must not fall back to apple,s5l8940x-fmi. properties: compatible: - const: apple,s5l8940x-fmi + enum: + - apple,s5l8940x-fmi + - apple,s5l8950x-fmi reg: minItems: 6 @@ -26,11 +29,28 @@ properties: minItems: 2 maxItems: 2 + clocks: + description: + PMGR power-state gates the controller needs (on S5L8950X FMI0, + FMI0-BCH, FMI1, FMI1-BCH and FMI-DLL), switched on before any + register access. + minItems: 1 + maxItems: 5 + required: - compatible - reg - interrupts +allOf: + - if: + properties: + compatible: + const: apple,s5l8950x-fmi + then: + required: + - clocks + additionalProperties: false examples: From 6ee9f989fe54291651049baa970268d3d1f8a1da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:44:01 +0100 Subject: [PATCH 22/43] mtd: apple-h2fmi: Recognise the iPhone 5 SanDisk PPN package, read-only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The iPhone 5 (N42) carries a SanDisk 1Xnm64GeX2 PPN 1.5.5 package with the P105 16 GB address layout but 1056 instead of 1064 blocks per CAU (12H321 ADT flash-controller0/disk: caus 2, cau-bits 4, blocks-per-cau 1056, block-bits 11, page-address-bits 8, 256 MLC and 128 SLC pages, page-size 16448). Accept that profile, and add h2fmi_geometry_writable(): program and erase stay limited to the two P105 profiles they were measured on, so any other accepted package is read-only whatever the compatible says. Log the first 64 parameter bytes when a package is rejected, so a new profile can be added from one boot log. KUnit: h2fmi_n42_geometry_test; the P105 vectors are unchanged. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/devices/mtd-apple-h2fmi-test.c | 34 ++++++++++++++++++++++ drivers/mtd/devices/mtd-apple-h2fmi.c | 7 ++++- drivers/mtd/devices/mtd-apple-h2fmi.h | 25 ++++++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/drivers/mtd/devices/mtd-apple-h2fmi-test.c b/drivers/mtd/devices/mtd-apple-h2fmi-test.c index a8434b08c10af0..83be1db07ede1b 100644 --- a/drivers/mtd/devices/mtd-apple-h2fmi-test.c +++ b/drivers/mtd/devices/mtd-apple-h2fmi-test.c @@ -13,6 +13,11 @@ static const u32 ppn_64gb[] = { 8, 3, 2088, 12, 128, 64, 7, 1, 2, 16448, }; +/* iPhone 5 (N42) SanDisk package, from the live 12H321 ADT. */ +static const u32 ppn_n42[] = { + 2, 4, 1056, 11, 256, 128, 8, 1, 2, 16448, +}; + static void h2fmi_test_params(u8 *params, const u32 *fields) { int i; @@ -42,6 +47,34 @@ static void h2fmi_geometry_test(struct kunit *test) 70061654016ULL); } +/* The N42 profile parses, addresses like the P105 16 GB one and stays read-only. */ +static void h2fmi_n42_geometry_test(struct kunit *test) +{ + u8 params[H2FMI_PARAMS_SIZE]; + struct h2fmi_geometry g; + u32 row; + + h2fmi_test_params(params, ppn_n42); + KUNIT_ASSERT_EQ(test, h2fmi_parse_geometry(params, sizeof(params), &g), 0); + KUNIT_EXPECT_EQ(test, g.caus, 2U); + KUNIT_EXPECT_EQ(test, g.blocks, 1056U); + KUNIT_EXPECT_EQ(test, g.slc_pages, 128U); + KUNIT_EXPECT_FALSE(test, h2fmi_geometry_writable(&g)); + KUNIT_EXPECT_EQ(test, h2fmi_bad_block_bytes(&g), 132U); + KUNIT_ASSERT_EQ(test, h2fmi_page_row(&g, 1, 1055, 255, &row), 0); + KUNIT_EXPECT_EQ(test, row, 0xc1fffU); + KUNIT_EXPECT_EQ(test, h2fmi_page_row(&g, 0, 1056, 0, &row), -EINVAL); + KUNIT_ASSERT_EQ(test, h2fmi_slc_row(&g, 1, 1055, 127, &row), 0); + KUNIT_EXPECT_EQ(test, row, 0x8c1f7fU); + + h2fmi_test_params(params, ppn_16gb); + KUNIT_ASSERT_EQ(test, h2fmi_parse_geometry(params, sizeof(params), &g), 0); + KUNIT_EXPECT_TRUE(test, h2fmi_geometry_writable(&g)); + h2fmi_test_params(params, ppn_64gb); + KUNIT_ASSERT_EQ(test, h2fmi_parse_geometry(params, sizeof(params), &g), 0); + KUNIT_EXPECT_TRUE(test, h2fmi_geometry_writable(&g)); +} + static void h2fmi_invalid_geometry_test(struct kunit *test) { u8 params[H2FMI_PARAMS_SIZE]; @@ -290,6 +323,7 @@ static void h2fmi_sdr_facts_test(struct kunit *test) static struct kunit_case h2fmi_test_cases[] = { KUNIT_CASE(h2fmi_raw_write_ownership_test), KUNIT_CASE(h2fmi_geometry_test), + KUNIT_CASE(h2fmi_n42_geometry_test), KUNIT_CASE(h2fmi_invalid_geometry_test), KUNIT_CASE(h2fmi_row_test), KUNIT_CASE(h2fmi_erase_row_test), diff --git a/drivers/mtd/devices/mtd-apple-h2fmi.c b/drivers/mtd/devices/mtd-apple-h2fmi.c index 1a4fd736c76621..6d6fe2cc816016 100644 --- a/drivers/mtd/devices/mtd-apple-h2fmi.c +++ b/drivers/mtd/devices/mtd-apple-h2fmi.c @@ -841,9 +841,14 @@ static int h2fmi_read_geometry(struct h2fmi *fmi, struct h2fmi_bus *b) b->page, H2FMI_PARAMS_SIZE, &status); if (!ret && status != PPN_ST_GOOD) ret = -EIO; - if (!ret) + if (!ret) { ret = h2fmi_parse_geometry(b->page, H2FMI_PARAMS_SIZE, &b->geometry); + /* Keep what the package said, so a new profile can be added. */ + if (ret) + dev_err(fmi->dev, "unsupported PPN parameters: %*ph\n", + 64, b->page); + } mutex_unlock(&b->lock); return ret; } diff --git a/drivers/mtd/devices/mtd-apple-h2fmi.h b/drivers/mtd/devices/mtd-apple-h2fmi.h index 0639a2b0d95ac0..515a08ea19b76c 100644 --- a/drivers/mtd/devices/mtd-apple-h2fmi.h +++ b/drivers/mtd/devices/mtd-apple-h2fmi.h @@ -73,9 +73,34 @@ static inline int h2fmi_parse_geometry(const u8 *params, size_t len, *geometry = g; return 0; } + /* + * iPhone 5 (N42) SanDisk 1Xnm64GeX2, PPN 1.5.5: the P105 16 GB + * address layout with 1056 instead of 1064 blocks per CAU (live + * 12H321 ADT flash-controller0/disk: caus 2, cau-bits 4, + * blocks-per-cau 1056, block-bits 11, page-address-bits 8, 256 MLC + * and 128 SLC pages, page-size 16448). Read-only: see + * h2fmi_geometry_writable(). + */ + if (g.caus == 2 && g.cau_bits == 4 && g.blocks == 1056 && + g.block_bits == 11 && g.pages == 256 && g.slc_pages == 128 && + g.page_bits == 8) { + *geometry = g; + return 0; + } return -EOPNOTSUPP; } +/* + * Program and erase are offered only on the two P105 profiles they were + * measured on. Any other accepted profile is read-only whatever the + * platform compatible says. + */ +static inline bool h2fmi_geometry_writable(const struct h2fmi_geometry *g) +{ + return (g->caus == 2 && g->blocks == 1064) || + (g->caus == 8 && g->blocks == 2088); +} + static inline int h2fmi_page_row(const struct h2fmi_geometry *g, unsigned int cau, unsigned int block, unsigned int page, u32 *row) From 76ea237d6cf12c5a1458154968f7a7e8e71e654e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:44:02 +0100 Subject: [PATCH 23/43] mtd: apple-h2fmi: Add a read-only S5L8950X controller MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The A6 has the A5's H2FMI (12H321 ADT flash-controller0, "fmi,s5l8950x": the same six FMI/FMC/ECC windows at 0x31200000 and 0x31300000, IRQs 33 and 34). The boot chain lives on the same NAND, so it binds as "apple,s5l8950x-fmi" with match data that keeps every write path closed: - h2fmi_cmd_write(), the one place an opcode reaches FMC_CMD, refuses program (8A, 17), mutation status (79) and erase (6A D7) on a read-only instance, and NAND reset (FF) and set feature (EF, E7) where no SDR reset is allowed; - the MTDs have no MTD_WRITEABLE and no _write_oob, and the SFTL provider gets no program_page or erase_block; - h2fmi_program_page() and h2fmi_ppn_erase() return -EROFS. On the S5L8950X the packages are never reset to SDR, at probe or to recover a failed transaction, unless mtd_apple_h2fmi.sdr_reset=1: the driver runs on the DDR interface iBoot leaves, and a failed transaction stops it instead. The PMGR gates in the node's clocks are switched on before the first register read, since reading a gated block on the A6 stalls the bus without an abort. They are never switched off again, not by a failed probe and not by an unbind: the ADT lists the same ids as power gates, and switching them off drops the DDR and DLL state iBoot trained, which only a reboot restores. The held enable count also keeps clk_disable_unused away from them. P105 has no clocks in its node and keeps its behaviour. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/devices/Kconfig | 5 + drivers/mtd/devices/mtd-apple-h2fmi.c | 137 ++++++++++++++++++++++++-- 2 files changed, 133 insertions(+), 9 deletions(-) diff --git a/drivers/mtd/devices/Kconfig b/drivers/mtd/devices/Kconfig index 33b122241ea73d..353da04d244956 100644 --- a/drivers/mtd/devices/Kconfig +++ b/drivers/mtd/devices/Kconfig @@ -223,6 +223,11 @@ config MTD_APPLE_H2FMI reported geometry validates; the erase extent follows from that geometry. + On the A6 (S5L8950X, iPhone 5) the driver is read-only: no program, + erase or mutation-status command can be sent, nothing is offered + for writing, and the packages are not reset to SDR unless + mtd_apple_h2fmi.sdr_reset=1 is given. + If unsure, say N. config MTD_APPLE_H2FMI_FAULT_INJECT diff --git a/drivers/mtd/devices/mtd-apple-h2fmi.c b/drivers/mtd/devices/mtd-apple-h2fmi.c index 6d6fe2cc816016..44c79e27c694cb 100644 --- a/drivers/mtd/devices/mtd-apple-h2fmi.c +++ b/drivers/mtd/devices/mtd-apple-h2fmi.c @@ -30,6 +30,8 @@ * Logical-address translation and allocation belong to the FTL above. */ +#include +#include #include #include #include @@ -43,12 +45,41 @@ #include #include #include +#include #include +#include #include #include #include "mtd-apple-h2fmi.h" +/* + * Per-SoC policy. read_only: no program, erase or mutation-status command + * is ever sent, no MTD is writable and SFTL gets no program or erase + * callback. reset_needs_param: the packages are never reset to SDR (NAND + * reset 0xff, set feature 0xef), neither at probe nor to recover from a + * failed transaction, unless sdr_reset=1 is given; the driver then only + * runs on the DDR interface iBoot leaves. + */ +struct h2fmi_soc { + bool read_only; + bool reset_needs_param; +}; + +/* A5 (P105): the measured platform, writes and SDR recovery as before. */ +static const struct h2fmi_soc h2fmi_s5l8940x = { }; + +/* A6 (iPhone 5, N42): read-only bring-up. */ +static const struct h2fmi_soc h2fmi_s5l8950x = { + .read_only = true, + .reset_needs_param = true, +}; + +static bool sdr_reset; +module_param(sdr_reset, bool, 0444); +MODULE_PARM_DESC(sdr_reset, + "Allow a NAND reset to SDR on platforms that do not do it by default (S5L8950X)"); + #define H2FMI_BUSES 2 #define H2FMI_PAGE_MASK (H2FMI_PAGE_DATA - 1) @@ -176,8 +207,12 @@ struct h2fmi { struct platform_device *sftl; struct apple_ppn_ops ppn_ops; struct apple_ppn_access access; + struct clk_bulk_data *clks; + int nclks; bool reset_needed; /* a transaction failed; reset before the next */ unsigned int resets; + bool read_only; /* no program/erase command ever reaches a package */ + bool sdr_allowed; /* the packages may be reset to SDR */ }; /* @@ -208,6 +243,20 @@ static int h2fmi_cmd_write(struct h2fmi *fmi, struct h2fmi_bus *b, u8 op, u8 op2 { int i; + /* + * Read-only: program (8A, 17), its status (79) and erase (6A D7) + * never leave the controller. Without SDR permission neither does + * the reset (FF) or set feature (EF, E7) the SDR bring-up needs. + */ + if (fmi->read_only && (op == 0x8a || op == 0x17 || op == 0x79 || op == 0x6a)) { + dev_err(fmi->dev, "read-only: refusing NAND opcodes %02x %02x\n", op, op2); + return -EROFS; + } + if (!fmi->sdr_allowed && (op == 0xff || op == 0xef || op == 0xe7)) { + dev_err(fmi->dev, "no SDR reset on this platform: refusing NAND opcodes %02x %02x\n", + op, op2); + return -EPERM; + } for (i = 0; i < ARRAY_SIZE(h2fmi_ops); i++) if (h2fmi_ops[i][0] == op && h2fmi_ops[i][1] == op2) { writel(op | op2 << 8, b->fmc + FMC_CMD); @@ -712,6 +761,13 @@ static int h2fmi_recover(struct h2fmi *fmi) mutex_lock_nested(&fmi->bus[1].lock, SINGLE_DEPTH_NESTING); if (fmi->bus[0].failed || fmi->bus[1].failed) { ret = -EIO; + } else if (fmi->reset_needed && !fmi->sdr_allowed) { + /* Recovery is a reset to SDR, which this platform does not do. */ + for (i = 0; i < H2FMI_BUSES; i++) + fmi->bus[i].failed = true; + dev_err(fmi->dev, "PPN transaction failed and no reset is allowed, stopping\n"); + fmi->reset_needed = false; + ret = -EIO; } else if (fmi->reset_needed) { ret = fmi->resets++ < H2FMI_MAX_RESETS ? h2fmi_sdr_bringup(fmi, &fmi->bus[0].geometry) : -EIO; @@ -1017,6 +1073,8 @@ static int h2fmi_program_page(struct h2fmi *fmi, struct h2fmi_bus *b, u8 status, *expected; int ret; + if (fmi->read_only) + return -EROFS; if (!data || !oob) return -EINVAL; ret = h2fmi_page_row(&b->geometry, cau, block, page, &row); @@ -1260,6 +1318,8 @@ static int h2fmi_ppn_erase(void *priv, unsigned int bus, unsigned int cau, u8 status; int ret; + if (fmi->read_only) + return -EROFS; if (bus >= H2FMI_BUSES) return -EINVAL; b = &fmi->bus[bus]; @@ -1307,9 +1367,13 @@ static int h2fmi_register_sftl(struct h2fmi *fmi) /* The recovery supports the measured 64 GB and 16 GB profiles. */ if (!IS_ENABLED(CONFIG_MTD_APPLE_SFTL) || !((g->caus == 8 && g->blocks == 2088 && g->pages == 128 && g->slc_pages == 64) || - (g->caus == 2 && g->blocks == 1064 && g->pages == 256 && g->slc_pages == 128))) + (g->caus == 2 && g->blocks == 1064 && g->pages == 256 && g->slc_pages == 128) || + (g->caus == 2 && g->blocks == 1056 && g->pages == 256 && g->slc_pages == 128))) return 0; fmi->ppn_ops.read_page = h2fmi_ppn_read; + /* A read-only provider has neither program nor erase: SFTL stays read-only. */ + if (fmi->read_only) + goto publish; fmi->ppn_ops.program_page = h2fmi_ppn_program; /* * Erase follows the discovered geometry. SFTL verifies every erased @@ -1321,6 +1385,7 @@ static int h2fmi_register_sftl(struct h2fmi *fmi) dev_info(fmi->dev, "PPN geometry %u CAUs x %u blocks x %u pages has no valid erase extent; reclamation stays off\n", g->caus, g->blocks, g->pages); +publish: fmi->sftl = platform_device_register_data(fmi->dev, "apple-sftl", PLATFORM_DEVID_AUTO, &provider, sizeof(provider)); @@ -1484,8 +1549,9 @@ static int h2fmi_setup_mtd(struct h2fmi *fmi, int idx) mtd->type = MTD_NANDFLASH; /* Page metadata is MTD OOB. Pages are programmed whole, data and OOB - * together; there is no erase. */ - mtd->flags = MTD_WRITEABLE | MTD_NO_ERASE; + * together; there is no erase. A read-only instance has no write + * method at all, so the MTD core answers every write with an error. */ + mtd->flags = fmi->read_only ? MTD_NO_ERASE : MTD_WRITEABLE | MTD_NO_ERASE; mtd->erasesize = g->pages * H2FMI_PAGE_DATA; mtd->size = (u64)g->blocks * mtd->erasesize; mtd->writesize = H2FMI_PAGE_DATA; @@ -1503,26 +1569,70 @@ static int h2fmi_setup_mtd(struct h2fmi *fmi, int idx) /* _read_oob only: add_mtd_device() rejects a driver that has both. */ mtd->_read_oob = h2fmi_mtd_read_oob; - mtd->_write_oob = h2fmi_mtd_write_oob; + if (!fmi->read_only) + mtd->_write_oob = h2fmi_mtd_write_oob; mtd->_block_isbad = h2fmi_mtd_block_isbad; return mtd_device_register(mtd, NULL, 0); } +/* + * The PMGR gates listed in the node's clocks (S5L8950X: FMI0, FMI0-BCH, + * FMI1, FMI1-BCH, FMI-DLL) are switched on before the first register + * access: on the A6 a read of a gated block stalls the bus without an + * abort. Each gate's state as iBoot left it is logged. A node without + * clocks (P105) is unchanged: nothing is switched. + * + * They are never switched off again, not after a failed probe and not on + * unbind: the ADT lists the same ids as power gates, so switching them off + * would drop the DDR and DLL state iBoot trained, which only a reboot + * restores, and would turn any later access into a bus stall. The enable + * count is kept, so clk_disable_unused leaves them alone too. + */ +static int h2fmi_clocks(struct h2fmi *fmi) +{ + int i, ret; + + fmi->nclks = devm_clk_bulk_get_all(fmi->dev, &fmi->clks); + if (fmi->nclks < 0) + return dev_err_probe(fmi->dev, fmi->nclks, "PMGR gates\n"); + if (!fmi->nclks) + return 0; + for (i = 0; i < fmi->nclks; i++) + dev_dbg(fmi->dev, "PMGR gate %s was %s\n", + __clk_get_name(fmi->clks[i].clk), + __clk_is_enabled(fmi->clks[i].clk) ? "on" : "off"); + ret = clk_bulk_prepare_enable(fmi->nclks, fmi->clks); + if (ret) + return dev_err_probe(fmi->dev, ret, "enabling the PMGR gates\n"); + return 0; +} + static int h2fmi_probe(struct platform_device *pdev) { + const struct h2fmi_soc *soc; struct h2fmi *fmi; int i, ret; BUILD_BUG_ON(H2FMI_PAGE_DATA != (1 << H2FMI_PAGE_SHIFT)); BUILD_BUG_ON(H2FMI_PAGE_RAW != 16448); + soc = of_device_get_match_data(&pdev->dev); + if (!soc) + return -ENODEV; fmi = devm_kzalloc(&pdev->dev, sizeof(*fmi), GFP_KERNEL); if (!fmi) return -ENOMEM; fmi->dev = &pdev->dev; + /* Both guards hold from the first command on. */ + fmi->read_only = soc->read_only; + fmi->sdr_allowed = !soc->reset_needs_param || sdr_reset; apple_ppn_access_init(&fmi->access); + ret = h2fmi_clocks(fmi); + if (ret) + return ret; + /* Six regions, in the ADT's order: FMI, FMC, ECC for bus 0, then bus 1. */ for (i = 0; i < H2FMI_BUSES; i++) { struct h2fmi_bus *b = &fmi->bus[i]; @@ -1543,8 +1653,9 @@ static int h2fmi_probe(struct platform_device *pdev) return -ENOMEM; /* iBoot read the NAND to boot and leaves the block clocked and - * in DDR. Nothing here turns the clocks on. If the interface - * is not in DDR, the packages are reset and run in SDR. */ + * in DDR. Only gates named in the node are switched on (see + * h2fmi_clocks()). If the interface is not in DDR, the packages + * are reset and run in SDR where the platform allows it. */ dev_info(&pdev->dev, "bus %d: FMC_ON=0x%08x IF_CTRL=0x%08x\n", i, readl(b->fmc + FMC_ON), readl(b->fmc + FMC_IF_CTRL)); } @@ -1552,6 +1663,9 @@ static int h2fmi_probe(struct platform_device *pdev) /* Without iBoot's DDR state, bring both packages up in SDR first. */ if (readl(fmi->bus[0].fmc + FMC_ON) != FMC_ON_DDR || readl(fmi->bus[1].fmc + FMC_ON) != FMC_ON_DDR) { + if (!fmi->sdr_allowed) + return dev_err_probe(&pdev->dev, -ENODEV, + "interface not in DDR and no SDR reset allowed (mtd_apple_h2fmi.sdr_reset=1)\n"); mutex_lock(&fmi->bus[0].lock); mutex_lock_nested(&fmi->bus[1].lock, SINGLE_DEPTH_NESTING); ret = h2fmi_sdr_bringup(fmi, NULL); @@ -1572,6 +1686,8 @@ static int h2fmi_probe(struct platform_device *pdev) return dev_err_probe(&pdev->dev, -EINVAL, "PPN package geometries disagree\n"); } + if (!h2fmi_geometry_writable(&fmi->bus[0].geometry)) + fmi->read_only = true; fmi->ndies = H2FMI_BUSES * fmi->bus[0].geometry.caus; fmi->mtd = devm_kcalloc(&pdev->dev, fmi->ndies, sizeof(*fmi->mtd), GFP_KERNEL); fmi->die = devm_kcalloc(&pdev->dev, fmi->ndies, sizeof(*fmi->die), GFP_KERNEL); @@ -1597,9 +1713,10 @@ static int h2fmi_probe(struct platform_device *pdev) } platform_set_drvdata(pdev, fmi); - dev_info(&pdev->dev, "%u CAUs, %u blocks of %u KiB each\n", + dev_info(&pdev->dev, "%u CAUs, %u blocks of %u KiB each%s\n", fmi->ndies, fmi->bus[0].geometry.blocks, - fmi->mtd[0].erasesize / 1024); + fmi->mtd[0].erasesize / 1024, + fmi->read_only ? ", read-only" : ""); return 0; } @@ -1615,7 +1732,9 @@ static void h2fmi_remove(struct platform_device *pdev) } static const struct of_device_id h2fmi_of_match[] = { - { .compatible = "apple,s5l8940x-fmi" }, + { .compatible = "apple,s5l8940x-fmi", .data = &h2fmi_s5l8940x }, + /* No fallback to s5l8940x-fmi in the DT: an older driver would bind it writable. */ + { .compatible = "apple,s5l8950x-fmi", .data = &h2fmi_s5l8950x }, { } }; MODULE_DEVICE_TABLE(of, h2fmi_of_match); From 94767971a9ac8054289e6d89ef6eb884c2d821da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:44:02 +0100 Subject: [PATCH 24/43] mtd: apple-h2fmi: On the S5L8950X a clean (49) page is erased, as iBEC reads it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On the iPhone 5 the package reported 49 (clean) for the first page of a block the VFL lists, and h2fmi_ppn_read() failed it with -EIO because the data phase was not all FF. On the A5 an erased page always read back FF, and the driver insists on it, since erase and program verification rely on it. iBEC on the iPhone 5 (12H321, single-page PPN read at 0xbff09810, status switch at 0xbff09914) never looks at the data of a 49 page: 40 is good, 42 good with a refresh note, 43..45 an error, other 4x a failure, 49 "clean". Do the same on the read-only S5L8950X only: a 49 page reads as FF data and metadata in both the SFTL provider and the MTD read path. The flag is ignored unless the instance is read-only, so a writable driver keeps the strict check. The first eight such pages are logged at debug level with what the data phase held. P105 is unchanged. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/devices/mtd-apple-h2fmi.c | 46 +++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/drivers/mtd/devices/mtd-apple-h2fmi.c b/drivers/mtd/devices/mtd-apple-h2fmi.c index 44c79e27c694cb..a88a9ca6b38c23 100644 --- a/drivers/mtd/devices/mtd-apple-h2fmi.c +++ b/drivers/mtd/devices/mtd-apple-h2fmi.c @@ -64,6 +64,7 @@ struct h2fmi_soc { bool read_only; bool reset_needs_param; + bool clean_by_status; /* status 49 alone means erased (read-only only) */ }; /* A5 (P105): the measured platform, writes and SDR recovery as before. */ @@ -73,6 +74,7 @@ static const struct h2fmi_soc h2fmi_s5l8940x = { }; static const struct h2fmi_soc h2fmi_s5l8950x = { .read_only = true, .reset_needs_param = true, + .clean_by_status = true, }; static bool sdr_reset; @@ -213,6 +215,8 @@ struct h2fmi { unsigned int resets; bool read_only; /* no program/erase command ever reaches a package */ bool sdr_allowed; /* the packages may be reset to SDR */ + bool clean_by_status; /* a 49 page is erased whatever its data phase held */ + unsigned int clean_logged; }; /* @@ -1162,6 +1166,40 @@ static int h2fmi_mtd_write_oob(struct mtd_info *mtd, loff_t to, return ret; } +/* + * A page the package reports clean (49) whose data phase was not all FF. + * On the A5 an erased page always read back FF, and the driver insists on + * it, since erase and program verification rely on it. The iPhone 5's + * SanDisk package does not: its first boot read 49 with other bytes on a + * block the VFL lists. iBEC (N42 12H321, single-page PPN read at + * 0xbff09810, status switch at 0xbff09914) never looks at the data of a 49 + * page: 40 is good, 42 good with a refresh note, 43..45 an error, 49 + * "clean". Where clean_by_status is set (read-only S5L8950X only), do the + * same: the page is erased and its data and metadata read as FF. The first + * few such pages are logged with what the data phase really held. + * Caller holds b->lock. + */ +static bool h2fmi_clean_by_status(struct h2fmi *fmi, struct h2fmi_bus *b, u32 row) +{ + unsigned int i, ff = 0, zero = 0; + + if (!fmi->clean_by_status) + return false; + if (fmi->clean_logged < 8) { + fmi->clean_logged++; + for (i = 0; i < H2FMI_PAGE_RAW; i++) { + ff += b->page[i] == 0xff; + zero += !b->page[i]; + } + dev_dbg(fmi->dev, + "row %08x status 49 with data: %u FF, %u 00 of %u bytes, data %16ph meta %16ph; taken as erased (%u/8)\n", + row, ff, zero, H2FMI_PAGE_RAW, b->page, b->page + H2FMI_CHUNK_LO, + fmi->clean_logged); + } + memset(b->page, 0xff, H2FMI_PAGE_RAW); + return true; +} + static int h2fmi_read_page_at(struct mtd_info *mtd, loff_t from, u8 *data, u8 *oob, u8 *stp) { @@ -1191,7 +1229,8 @@ static int h2fmi_read_page_at(struct mtd_info *mtd, loff_t from, b->page, H2FMI_PAGE_RAW, &st); if (!ret && h2fmi_page_status(st) >= 0) { if (st == PPN_ST_ERASED && - memchr_inv(b->page, 0xff, H2FMI_PAGE_RAW)) + memchr_inv(b->page, 0xff, H2FMI_PAGE_RAW) && + !h2fmi_clean_by_status(fmi, b, row)) ret = -EBADMSG; else h2fmi_split_page(b->page, data, oob); @@ -1231,7 +1270,8 @@ static int h2fmi_ppn_read(void *priv, unsigned int bus, unsigned int cau, ret = h2fmi_read_transaction(fmi, b, 0x0a, 0x37, row, 4, b->page, H2FMI_PAGE_RAW, status); if (!ret && h2fmi_page_status(*status) >= 0) { - if (*status == PPN_ST_ERASED && memchr_inv(b->page, 0xff, H2FMI_PAGE_RAW)) + if (*status == PPN_ST_ERASED && memchr_inv(b->page, 0xff, H2FMI_PAGE_RAW) && + !h2fmi_clean_by_status(fmi, b, row)) ret = -EIO; else h2fmi_split_page(b->page, data, oob); @@ -1627,6 +1667,8 @@ static int h2fmi_probe(struct platform_device *pdev) /* Both guards hold from the first command on. */ fmi->read_only = soc->read_only; fmi->sdr_allowed = !soc->reset_needs_param || sdr_reset; + /* Only a driver that can never program may take the status alone. */ + fmi->clean_by_status = soc->clean_by_status && fmi->read_only; apple_ppn_access_init(&fmi->access); ret = h2fmi_clocks(fmi); From 86d2fb110851b2f0910869f8896648c859815cb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:44:02 +0100 Subject: [PATCH 25/43] mtd: apple-sftl: Add the iPhone 5 16 GB layout, read-only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The iPhone 5 (N42) runs the same 12H321 SwissPPNFTL as the P105 16 GB profile on a package with 1056 instead of 1064 blocks per CAU. Add a read-only (writer = false) profile for it. Buses, CAUs, blocks and pages come from the ADT. The VFL header on the phone reports 16 and 1046 FTL and VFL superblocks, and the VFL seed is at block 1055, lane 0. The other constants follow the P105 layout with its tail moved down by the block count; the loader checks each against the media and refuses a mismatch, and logs at debug level what the media holds at those checks (VFL member list, VFL header +10/+12/+14, context cursor). P105 loading is unchanged apart from those debug messages on its error paths. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/apple-sftl-core.c | 38 +++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c index 4a810908a1c057..c8520232632d06 100644 --- a/drivers/mtd/apple-sftl-core.c +++ b/drivers/mtd/apple-sftl-core.c @@ -107,9 +107,29 @@ static const struct sftl_geometry sftl_16gb = { .degrade_remnants = true, .hidden_tail_type2 = true, }; +/* + * iPhone 5 (N42) 16 GB SanDisk PPN, 12H321 on the media: the P105 16 GB + * layout (same 12H321 FTL) with 1056 instead of 1064 blocks + * per CAU. Read-only. Only buses, caus, blocks and pages are measured + * (live ADT flash-controller0/disk). subblocks, vfl_first, bootstrap and + * lpages are NOT measured: they assume the P105 tail (two VFL blocks at + * the top, seven blocks between them and the last superblock) moves down + * with the block count and that the exported size is the same 16 GB. The + * loader checks each against the media (VFL header +12/+14, member list, + * context cursor) and refuses on a mismatch, logging the media's value. + */ +static const struct sftl_geometry sftl_16gb_n42 = { + .buses = 2, .caus = 2, .lanes = 4, .blocks = 1056, .pages = 256, + .subblocks = 1046, .vfl_pages = 128, .vfl_first = 1054, + .bootstrap = { 1055, 1054 }, .nr_bootstrap = 2, + .map_batch = 16, + .disk_pages = 3906250, .lpages = 3906266, .summary_sequences = true, +}; + static const struct sftl_geometry *const sftl_geometries[] = { &sftl_64gb, &sftl_16gb, + &sftl_16gb_n42, }; struct sftl_run { @@ -520,8 +540,13 @@ static int sftl_vfl_members(struct apple_sftl *sftl) members[i].lane = row[2]; if (members[i].block < sftl->geo->vfl_first || members[i].block >= sftl->geo->blocks || - members[i].lane >= sftl->geo->lanes || row[3]) + members[i].lane >= sftl->geo->lanes || row[3]) { + dev_dbg(sftl->ppn->dev, + "VFL member %u: block %u lane %u (%02x), profile expects blocks %u..%u\n", + i, members[i].block, members[i].lane, row[3], + sftl->geo->vfl_first, sftl->geo->blocks - 1); return -EBADMSG; + } for (j = 0; j < i; j++) if (members[j].block == members[i].block && members[j].lane == members[i].lane) return -EBADMSG; @@ -672,8 +697,14 @@ static int sftl_vfl_load_refs(struct apple_sftl *sftl, struct sftl_vfl_scan *sca */ if (get_unaligned_le16(scan->sample + 10) != 16 || get_unaligned_le16(scan->sample + 12) != sftl->geo->subblocks || - get_unaligned_le16(scan->sample + 14) != sftl->geo->subblocks) + get_unaligned_le16(scan->sample + 14) != sftl->geo->subblocks) { + dev_dbg(sftl->ppn->dev, + "VFL header +10 %u, FTL superblocks %u, VFL superblocks %u; profile expects 16, %u\n", + get_unaligned_le16(scan->sample + 10), + get_unaligned_le16(scan->sample + 12), + get_unaligned_le16(scan->sample + 14), sftl->geo->subblocks); return -EOPNOTSUPP; + } for (lane = 0; lane < sftl->geo->lanes; lane++) { const struct sftl_vfl_slot *table; u16 ref = get_unaligned_le16(scan->sample + 0x200 + 32 * lane); @@ -1052,6 +1083,9 @@ static int sftl_decode_generation(struct apple_sftl *sftl, const struct sftl_rec */ if (cursor != sftl->geo->lpages || !map_records || (native && map_records % sftl->geo->map_batch)) { + dev_dbg(sftl->ppn->dev, + "context covers %u logical pages in %u records (native %d); profile expects %u in batches of %u\n", + cursor, map_records, native, sftl->geo->lpages, sftl->geo->map_batch); if (short_range) return -EBADMSG; /* A partial program or a native aggregate that lost its tail does From a620d6f3f26469e54f04a4b5dc40ec94ab6dc229 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:44:03 +0100 Subject: [PATCH 26/43] mtd: apple-sftl: Serve scattered LwVM partitions as read-only disks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On the iPhone 5 the SFTL loads the 16 GB medium read-only, but the LwVM parser adds only p1: "LwVM partition 2 is not contiguous, skipped". A Linux partition is one range of the disk, and iOS stores Data in 16 MiB chunks out of order. The SFTL block frontend owns the disk and already reads it one 4 KiB logical page at a time, so it can translate each page itself. After the main disk is added, read the LwVM header (and its copy in the last page of the first chunk if the CRC fails, as the parser does) and give every partition that block/partitions/lwvm.c skips because it is scattered its own disk, applesftllwvm

. Each page of a request is looked up in the chunk map, so a request can cross chunks in any order, and the size of the partition ends the last, partial chunk. These disks are read-only with no write path at all: writes end with -EROFS and other operations with -EOPNOTSUPP before the FTL is reached, no write cache or FUA is advertised, and reads share the parent's lock and buffer. They have a dynamic device number and no partition scan. Only profiles that opt in get them, and only on a read-only medium (a second view of a disk that is written would read stale pages). The N42 profile opts in. The P105 profiles do not, so the iPad mini 1 is unchanged whether its medium loads read-only or read-write. The decoder applies the parser's checks (signature, CRC, media size, 1..8 partitions, no entry in the header chunk or past the disk) and reports a partition with a hole, a doubled or out-of-range chunk instead of serving it. Contiguous layouts get no new disk and no new message. KUnit (apple-sftl-lwvm) covers the chunk size, contiguous, interleaved and partial-last-chunk layouts, broken partitions and rejected tables with synthetic headers. Tested on an iPhone5,2: applesftl0lwvm2 is Data, 13.5 GB in 803 chunks, readable (its contents are encrypted). Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/Kconfig | 6 + drivers/mtd/Makefile | 2 + drivers/mtd/apple-sftl-block.c | 247 ++++++++++++++++++++++- drivers/mtd/apple-sftl-core.c | 4 + drivers/mtd/apple-sftl-lwvm-test.c | 302 +++++++++++++++++++++++++++++ drivers/mtd/apple-sftl-lwvm.c | 171 ++++++++++++++++ drivers/mtd/apple-sftl-lwvm.h | 45 +++++ drivers/mtd/apple-sftl.h | 2 + 8 files changed, 771 insertions(+), 8 deletions(-) create mode 100644 drivers/mtd/apple-sftl-lwvm-test.c create mode 100644 drivers/mtd/apple-sftl-lwvm.c create mode 100644 drivers/mtd/apple-sftl-lwvm.h diff --git a/drivers/mtd/Kconfig b/drivers/mtd/Kconfig index 42e979b1784a1b..e408d40f41a5f5 100644 --- a/drivers/mtd/Kconfig +++ b/drivers/mtd/Kconfig @@ -209,6 +209,7 @@ config MTD_PARTITIONED_MASTER config MTD_APPLE_SFTL tristate "Apple PPN VFL/SwissPPNFTL translation" depends on BLOCK + select CRC32 help Recover the logical block medium stored in Apple VFL/SwissPPNFTL metadata on the measured 64 GB and 16 GB Hynix PPN layouts. The @@ -224,6 +225,11 @@ config MTD_APPLE_SFTL validates. Providers without a qualified erase operation return ENOSPC when their supply of blank blocks runs out. + On the iPhone 5 (N42) layout, which is read-only, every LwVM + partition that is stored in scattered chunks, and so is skipped by + the LwVM partition parser, becomes a read-only disk of its own, + applesftllwvm

. The other layouts are unchanged. + config MTD_APPLE_SFTL_KUNIT_TEST tristate "KUnit tests for Apple VFL/SwissPPNFTL" if !KUNIT_ALL_TESTS depends on KUNIT && MTD_APPLE_SFTL diff --git a/drivers/mtd/Makefile b/drivers/mtd/Makefile index 227eac233d55eb..d11d92d982389b 100644 --- a/drivers/mtd/Makefile +++ b/drivers/mtd/Makefile @@ -34,6 +34,8 @@ obj-$(CONFIG_MTD_HYPERBUS) += hyperbus/ obj-$(CONFIG_MTD_APPLE_SFTL) += apple-sftl.o apple-sftl-y := apple-sftl-core.o apple-sftl-block.o apple-sftl-reclaim.o apple-sftl-account.o apple-sftl-provider.o apple-sftl-vfl.o +apple-sftl-y += apple-sftl-lwvm.o obj-$(CONFIG_MTD_APPLE_SFTL_KUNIT_TEST) += apple-sftl-test.o obj-$(CONFIG_MTD_APPLE_SFTL_KUNIT_TEST) += apple-sftl-reclaim-test.o obj-$(CONFIG_MTD_APPLE_SFTL_KUNIT_TEST) += apple-sftl-account-test.o apple-sftl-provider-test.o apple-sftl-vfl-test.o +obj-$(CONFIG_MTD_APPLE_SFTL_KUNIT_TEST) += apple-sftl-lwvm-test.o diff --git a/drivers/mtd/apple-sftl-block.c b/drivers/mtd/apple-sftl-block.c index 148a245358663e..070f7bc7e9e7ae 100644 --- a/drivers/mtd/apple-sftl-block.c +++ b/drivers/mtd/apple-sftl-block.c @@ -13,10 +13,14 @@ #include #include "apple-sftl.h" +#include "apple-sftl-lwvm.h" #define SFTL_BLOCK_NAME "apple-sftl" #define SFTL_DISK_MINORS 16 #define SFTL_LOGICAL_BYTES 4096U +#define SFTL_LAYOUT_RUNS 64U + +struct sftl_piece; struct sftl_disk { struct apple_sftl *ftl; @@ -27,30 +31,52 @@ struct sftl_disk { unsigned int id; bool dead; bool writable; + struct sftl_piece *pieces[APPLE_SFTL_LWVM_MAX_PARTS]; +}; + +/* + * An LwVM partition stored in scattered chunks, which the partition parser + * skips. Its own read-only disk reads the parent's pages through the chunk + * map, under the parent's lock and with its buffer. There is no write path. + */ +struct sftl_piece { + struct sftl_disk *parent; + struct blk_mq_tag_set tags; + struct gendisk *disk; + struct apple_sftl_lwvm_part part; }; static DEFINE_IDA(sftl_disk_ids); static int sftl_major; -/* The blocking queue and this lock keep the preallocated buffer exclusive. */ -static int sftl_read_request(struct sftl_disk *sftl, struct request *request) +/* + * The blocking queue and this lock keep the preallocated buffer exclusive. + * A pieced partition passes its LwVM part: each 4 KiB page is looked up in + * the chunk map, so a request can cross chunks in any order. + */ +static int sftl_read_request(struct sftl_disk *sftl, struct request *request, + const struct apple_sftl_lwvm_part *part) { struct req_iterator iterator; struct bio_vec bvec; u64 position = (u64)blk_rq_pos(request) << SECTOR_SHIFT; u32 cached = U32_MAX; + int ret; rq_for_each_segment(bvec, request, iterator) { unsigned int done = 0; while (done < bvec.bv_len) { - u32 logical = position >> 12; - unsigned int offset = position & (SFTL_LOGICAL_BYTES - 1); - unsigned int length = min(bvec.bv_len - done, - SFTL_LOGICAL_BYTES - offset); + u64 source = position; + unsigned int offset, length; void *mapped; - int ret; + u32 logical; + if (part && apple_sftl_lwvm_map(part, position, &source)) + return -EIO; + logical = source >> 12; + offset = source & (SFTL_LOGICAL_BYTES - 1); + length = min(bvec.bv_len - done, SFTL_LOGICAL_BYTES - offset); if (logical != cached) { ret = apple_sftl_read(sftl->ftl, logical, sftl->buffer); if (ret) @@ -157,7 +183,7 @@ static blk_status_t sftl_queue_rq(struct blk_mq_hw_ctx *hctx, } else if (req_op(request) == REQ_OP_WRITE) { ret = sftl->writable ? sftl_write_request(sftl, request) : -EROFS; } else { - ret = sftl_read_request(sftl, request); + ret = sftl_read_request(sftl, request, NULL); } memalloc_noio_restore(noio_flags); mutex_unlock(&sftl->io_lock); @@ -166,14 +192,217 @@ static blk_status_t sftl_queue_rq(struct blk_mq_hw_ctx *hctx, return BLK_STS_OK; } +/* Reads only: anything else ends here and never reaches the FTL. */ +static blk_status_t sftl_piece_queue_rq(struct blk_mq_hw_ctx *hctx, + const struct blk_mq_queue_data *data) +{ + struct request *request = data->rq; + struct sftl_piece *piece = request->q->queuedata; + struct sftl_disk *sftl = piece->parent; + sector_t capacity = get_capacity(piece->disk); + unsigned int noio_flags; + int ret; + + if (req_op(request) != REQ_OP_READ) { + blk_mq_start_request(request); + ret = req_op(request) == REQ_OP_WRITE ? -EROFS : -EOPNOTSUPP; + blk_mq_end_request(request, errno_to_blk_status(ret)); + return BLK_STS_OK; + } + mutex_lock(&sftl->io_lock); + noio_flags = memalloc_noio_save(); + blk_mq_start_request(request); + if (sftl->dead) + ret = -ENODEV; + else if (blk_rq_pos(request) > capacity || + blk_rq_sectors(request) > capacity - blk_rq_pos(request)) + ret = -EIO; + else + ret = sftl_read_request(sftl, request, &piece->part); + memalloc_noio_restore(noio_flags); + mutex_unlock(&sftl->io_lock); + blk_mq_end_request(request, errno_to_blk_status(ret)); + return BLK_STS_OK; +} + static const struct blk_mq_ops sftl_mq_ops = { .queue_rq = sftl_queue_rq, }; +static const struct blk_mq_ops sftl_piece_mq_ops = { + .queue_rq = sftl_piece_queue_rq, +}; + static const struct block_device_operations sftl_block_ops = { .owner = THIS_MODULE, }; +/* Runs of disk chunks, "partition chunks@first disk chunk", 64 at most. */ +static void sftl_piece_layout(struct device *dev, const char *name, + const struct apple_sftl_lwvm_part *part) +{ + unsigned int k = 0, runs = 0, used = 0; + char line[112]; + + while (k < part->nr_chunks) { + unsigned int first = k; + + while (k + 1 < part->nr_chunks && part->chunk[k + 1] == part->chunk[k] + 1) + k++; + k++; + if (++runs > SFTL_LAYOUT_RUNS) + continue; + if (first + 1 == k) + used += scnprintf(line + used, sizeof(line) - used, " %u@%u", first, + part->chunk[first]); + else + used += scnprintf(line + used, sizeof(line) - used, " %u-%u@%u", first, + k - 1, part->chunk[first]); + if (used > sizeof(line) - 20 || k == part->nr_chunks || + runs == SFTL_LAYOUT_RUNS) { + dev_dbg(dev, "%s: chunks%s\n", name, line); + used = 0; + } + } + if (runs > SFTL_LAYOUT_RUNS) + dev_dbg(dev, "%s: %u more runs not shown\n", name, runs - SFTL_LAYOUT_RUNS); +} + +static void sftl_add_piece(struct platform_device *pdev, struct sftl_disk *sftl, + const struct apple_sftl_lwvm_part *part, unsigned int slot, + bool layout) +{ + struct queue_limits limits = { + .logical_block_size = SECTOR_SIZE, + .physical_block_size = SFTL_LOGICAL_BYTES, + .max_hw_sectors = 128, + }; + struct sftl_piece *piece; + struct gendisk *disk; + int ret; + + piece = kzalloc(sizeof(*piece), GFP_KERNEL); + if (!piece) { + ret = -ENOMEM; + goto warn; + } + piece->parent = sftl; + piece->part = *part; + ret = blk_mq_alloc_sq_tag_set(&piece->tags, &sftl_piece_mq_ops, 8, + BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_BLOCKING); + if (ret) + goto free_piece; + disk = blk_mq_alloc_disk(&piece->tags, &limits, piece); + if (IS_ERR(disk)) { + ret = PTR_ERR(disk); + goto free_tags; + } + piece->disk = disk; + /* No major and no minors: a dynamic device number, no partitions. */ + disk->flags |= GENHD_FL_NO_PART; + disk->fops = &sftl_block_ops; + disk->private_data = piece; + snprintf(disk->disk_name, DISK_NAME_LEN, "applesftl%ulwvm%u", sftl->id, slot); + set_capacity(disk, (part->end - part->begin) >> SECTOR_SHIFT); + set_disk_ro(disk, true); + ret = device_add_disk(&pdev->dev, disk, NULL); + if (ret) + goto put_disk; + sftl->pieces[slot - 1] = piece; + dev_info(&pdev->dev, "%s: LwVM partition %u \"%s\" %pUb, read-only, %llu bytes in %u chunks of %u KiB\n", + disk->disk_name, slot, part->name, part->guid, part->end - part->begin, + part->nr_chunks, 1U << (part->chunk_shift - 10)); + if (layout) { + dev_dbg(&pdev->dev, "%s: LwVM bytes %#llx-%#llx, attributes %#llx, %u map entries\n", + disk->disk_name, part->begin, part->end, part->attributes, part->mapped); + sftl_piece_layout(&pdev->dev, disk->disk_name, part); + } + return; + +put_disk: + put_disk(disk); +free_tags: + blk_mq_free_tag_set(&piece->tags); +free_piece: + kfree(piece); +warn: + dev_warn(&pdev->dev, "LwVM partition %u \"%s\" not added: %d\n", slot, part->name, ret); +} + +/* + * Give each scattered LwVM partition its own disk, on profiles that ask for + * it (the N42 one) and only on a read-only medium: a second view of a + * written disk would read stale pages. Every failure here leaves the main + * disk as it is. + */ +static void sftl_add_pieces(struct platform_device *pdev, struct sftl_disk *sftl, + const struct apple_sftl_info *info) +{ + u64 media = (u64)info->disk_pages * SFTL_LOGICAL_BYTES; + struct apple_sftl_lwvm *lwvm; + unsigned int noio_flags, i; + u8 *header; + int ret = -ENOMEM; + + if (!info->lwvm_pieces || sftl->writable) + return; + lwvm = kzalloc(sizeof(*lwvm), GFP_KERNEL); + header = kmalloc(SFTL_LOGICAL_BYTES, GFP_KERNEL); + if (!lwvm || !header) + goto out; + mutex_lock(&sftl->io_lock); + noio_flags = memalloc_noio_save(); + ret = apple_sftl_read(sftl->ftl, 0, header); + if (!ret) + ret = apple_sftl_lwvm_decode(header, media, lwvm); + /* As the partition parser: a damaged header falls back to its copy + * in the last page of the first chunk. + */ + if (ret == -EBADMSG) { + u32 copy = (1U << (apple_sftl_lwvm_chunk_shift(media) - 12)) - 1; + + ret = apple_sftl_read(sftl->ftl, copy, header); + if (!ret) + ret = apple_sftl_lwvm_decode(header, media, lwvm); + } + memalloc_noio_restore(noio_flags); + mutex_unlock(&sftl->io_lock); + if (ret) + goto out; + for (i = 0; i < lwvm->nr_parts; i++) { + const struct apple_sftl_lwvm_part *part = &lwvm->parts[i]; + + if (part->pieced) + sftl_add_piece(pdev, sftl, part, i + 1, info->unmeasured); + else if (part->error && info->unmeasured) + dev_info(&pdev->dev, "LwVM partition %u \"%s\" not served: map error %d, %u entries for %u chunks\n", + i + 1, part->name, part->error, part->mapped, part->nr_chunks); + } +out: + if (ret && ret != -ENOENT && info->unmeasured) + dev_info(&pdev->dev, "LwVM header not decoded (%d), no pieced partitions\n", ret); + kfree(header); + kfree(lwvm); +} + +/* Before the parent: their reads take its lock, buffer and FTL. */ +static void sftl_remove_pieces(struct sftl_disk *sftl) +{ + unsigned int i; + + for (i = 0; i < APPLE_SFTL_LWVM_MAX_PARTS; i++) { + struct sftl_piece *piece = sftl->pieces[i]; + + if (!piece) + continue; + del_gendisk(piece->disk); + put_disk(piece->disk); + blk_mq_free_tag_set(&piece->tags); + kfree(piece); + sftl->pieces[i] = NULL; + } +} + static int sftl_disk_probe(struct platform_device *pdev) { struct queue_limits limits = { @@ -262,6 +491,7 @@ static int sftl_disk_probe(struct platform_device *pdev) dev_info(&pdev->dev, "%s: %s, %u logical pages, sequence %llu\n", disk->disk_name, sftl->writable ? "read-write" : "read-only", info.disk_pages, info.sequence); + sftl_add_pieces(pdev, sftl, &info); return 0; put_disk: @@ -287,6 +517,7 @@ static void sftl_disk_remove(struct platform_device *pdev) mutex_lock(&sftl->io_lock); sftl->dead = true; mutex_unlock(&sftl->io_lock); + sftl_remove_pieces(sftl); /* del_gendisk freezes and drains the queue before the provider is freed. */ del_gendisk(sftl->disk); put_disk(sftl->disk); diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c index c8520232632d06..d3003e405c7c4c 100644 --- a/drivers/mtd/apple-sftl-core.c +++ b/drivers/mtd/apple-sftl-core.c @@ -78,6 +78,7 @@ struct sftl_geometry { bool summary_sequences; /* a summary may consume one sequence per chunk */ bool degrade_remnants; /* a context block with an unknown base only blocks writes */ bool hidden_tail_type2; /* iOS 9 writes the hidden tail as type 2, flag 1 */ + bool lwvm_pieces; /* serve scattered LwVM partitions as disks */ }; /* 64 GB Hynix PPN with 13G36 (iOS 9.3.5) on the media. */ @@ -124,6 +125,7 @@ static const struct sftl_geometry sftl_16gb_n42 = { .bootstrap = { 1055, 1054 }, .nr_bootstrap = 2, .map_batch = 16, .disk_pages = 3906250, .lpages = 3906266, .summary_sequences = true, + .lwvm_pieces = true, }; static const struct sftl_geometry *const sftl_geometries[] = { @@ -3256,6 +3258,8 @@ EXPORT_SYMBOL_GPL(apple_sftl_flush); void apple_sftl_get_info(struct apple_sftl *sftl, struct apple_sftl_info *info) { info->read_only = sftl->vfl_degraded || sftl->context_degraded || !sftl->geo->writer; + info->unmeasured = sftl->geo->unmeasured; + info->lwvm_pieces = sftl->geo->lwvm_pieces; info->logical_pages = sftl->geo->lpages; info->disk_pages = sftl->geo->disk_pages; info->nr_runs = sftl->nr_runs; diff --git a/drivers/mtd/apple-sftl-lwvm-test.c b/drivers/mtd/apple-sftl-lwvm-test.c new file mode 100644 index 00000000000000..cd174d51a18b29 --- /dev/null +++ b/drivers/mtd/apple-sftl-lwvm-test.c @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Synthetic LwVM headers: contiguous, interleaved and partial partitions. */ +#include +#include +#include +#include +#include + +#include "apple-sftl-lwvm.h" + +/* 8 MiB is the smallest LwVM disk: 1024 chunks of 8 KiB. */ +#define TEST_MEDIA (8ULL << 20) +#define TEST_CHUNK 8192ULL + +static const u8 test_signature[16] = { + 0x6a, 0x90, 0x88, 0xcf, 0x8a, 0xfd, 0x63, 0x0a, + 0xe3, 0x51, 0xe2, 0x48, 0x87, 0xe0, 0xb9, 0x8b, +}; + +struct lwvm_fixture { + u8 *header; + struct apple_sftl_lwvm *lwvm; +}; + +static void header_init(u8 *h, u64 media, u32 count) +{ + unsigned int k; + + memset(h, 0, APPLE_SFTL_LWVM_HEADER_BYTES); + memcpy(h, test_signature, sizeof(test_signature)); + put_unaligned_le64(media, h + 0x20); + put_unaligned_le32(count, h + 0x28); + /* iOS marks the header chunk f000 and free chunks f111. */ + put_unaligned_le16(0xf000, h + 0x800); + for (k = 1; k < APPLE_SFTL_LWVM_CHUNKS; k++) + put_unaligned_le16(0xf111, h + 0x800 + 2 * k); +} + +static void header_part(u8 *h, unsigned int i, u64 begin, u64 end, const char *name) +{ + u8 *entry = h + 0x200 + 0x80 * i; + unsigned int c; + + memset(entry + 16, 0x10 + i, 16); + put_unaligned_le64(begin, entry + 32); + put_unaligned_le64(end, entry + 40); + for (c = 0; name[c]; c++) + put_unaligned_le16(name[c], entry + 56 + 2 * c); +} + +static void header_map(u8 *h, unsigned int disk_chunk, unsigned int owner, unsigned int index) +{ + put_unaligned_le16(owner << 12 | index, h + 0x800 + 2 * disk_chunk); +} + +static void header_seal(u8 *h) +{ + put_unaligned_le32(0, h + 0x2c); + put_unaligned_le32(~crc32_le(~0, h, APPLE_SFTL_LWVM_HEADER_BYTES), h + 0x2c); +} + +static int lwvm_init(struct kunit *test) +{ + struct lwvm_fixture *f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, f); + f->header = kunit_kzalloc(test, APPLE_SFTL_LWVM_HEADER_BYTES, GFP_KERNEL); + f->lwvm = kunit_kzalloc(test, sizeof(*f->lwvm), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, f->header); + KUNIT_ASSERT_NOT_NULL(test, f->lwvm); + test->priv = f; + return 0; +} + +static u64 map(struct kunit *test, const struct apple_sftl_lwvm_part *part, u64 offset) +{ + u64 disk = U64_MAX; + + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_map(part, offset, &disk), 0); + return disk; +} + +static void lwvm_chunk_size(struct kunit *test) +{ + struct lwvm_fixture *f = test->priv; + + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_chunk_shift(TEST_MEDIA), 13); + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_chunk_shift(TEST_MEDIA - 512), 0); + /* iPhone 5 16 GB: 3906250 logical pages, 953 whole 16 MiB chunks. */ + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_chunk_shift(3906250ULL * 4096), 24); + + header_init(f->header, 3906250ULL * 4096, 1); + header_part(f->header, 0, 0, 3ULL << 24, "System"); + header_map(f->header, 1, 0, 0); + header_map(f->header, 2, 0, 1); + header_map(f->header, 3, 0, 2); + header_seal(f->header); + KUNIT_ASSERT_EQ(test, apple_sftl_lwvm_decode(f->header, 3906250ULL * 4096, f->lwvm), 0); + KUNIT_EXPECT_EQ(test, f->lwvm->chunks, 953); + KUNIT_EXPECT_EQ(test, f->lwvm->parts[0].nr_chunks, 3); + KUNIT_EXPECT_FALSE(test, f->lwvm->parts[0].pieced); +} + +/* In order and back to back: the partition parser adds these, never pieced. */ +static void lwvm_contiguous(struct kunit *test) +{ + struct lwvm_fixture *f = test->priv; + struct apple_sftl_lwvm_part *data = &f->lwvm->parts[1]; + + header_init(f->header, TEST_MEDIA, 2); + header_part(f->header, 0, 0, 2 * TEST_CHUNK, "System"); + header_part(f->header, 1, 2 * TEST_CHUNK, 5 * TEST_CHUNK, "Data"); + header_map(f->header, 1, 0, 0); + header_map(f->header, 2, 0, 1); + header_map(f->header, 3, 1, 0); + header_map(f->header, 4, 1, 1); + header_map(f->header, 5, 1, 2); + header_seal(f->header); + KUNIT_ASSERT_EQ(test, apple_sftl_lwvm_decode(f->header, TEST_MEDIA, f->lwvm), 0); + KUNIT_EXPECT_EQ(test, f->lwvm->nr_parts, 2); + KUNIT_EXPECT_STREQ(test, f->lwvm->parts[0].name, "System"); + KUNIT_EXPECT_STREQ(test, data->name, "Data"); + KUNIT_EXPECT_EQ(test, f->lwvm->parts[0].error, 0); + KUNIT_EXPECT_EQ(test, data->error, 0); + KUNIT_EXPECT_FALSE(test, f->lwvm->parts[0].pieced); + KUNIT_EXPECT_FALSE(test, data->pieced); + KUNIT_EXPECT_EQ(test, data->nr_chunks, 3); + KUNIT_EXPECT_EQ(test, map(test, data, 0), 3 * TEST_CHUNK); + KUNIT_EXPECT_EQ(test, map(test, data, 3 * TEST_CHUNK - 1), 6 * TEST_CHUNK - 1); +} + +/* + * System in order but with gaps, Data out of order between them. Pages on + * both sides of a chunk border land in unrelated disk chunks. + */ +static void lwvm_interleaved(struct kunit *test) +{ + struct lwvm_fixture *f = test->priv; + struct apple_sftl_lwvm_part *system = &f->lwvm->parts[0]; + struct apple_sftl_lwvm_part *data = &f->lwvm->parts[1]; + + header_init(f->header, TEST_MEDIA, 2); + header_part(f->header, 0, 0, 3 * TEST_CHUNK, "System"); + header_part(f->header, 1, 3 * TEST_CHUNK, 6 * TEST_CHUNK, "Data"); + header_map(f->header, 1, 0, 0); + header_map(f->header, 3, 0, 1); + header_map(f->header, 5, 0, 2); + header_map(f->header, 6, 1, 0); + header_map(f->header, 2, 1, 1); + header_map(f->header, 4, 1, 2); + header_seal(f->header); + KUNIT_ASSERT_EQ(test, apple_sftl_lwvm_decode(f->header, TEST_MEDIA, f->lwvm), 0); + KUNIT_EXPECT_TRUE(test, system->pieced); + KUNIT_EXPECT_TRUE(test, data->pieced); + KUNIT_EXPECT_EQ(test, data->mapped, 3); + + KUNIT_EXPECT_EQ(test, map(test, system, 0), 1 * TEST_CHUNK); + KUNIT_EXPECT_EQ(test, map(test, system, TEST_CHUNK - 4096), 2 * TEST_CHUNK - 4096); + KUNIT_EXPECT_EQ(test, map(test, system, TEST_CHUNK), 3 * TEST_CHUNK); + KUNIT_EXPECT_EQ(test, map(test, system, 2 * TEST_CHUNK + 512), 5 * TEST_CHUNK + 512); + + KUNIT_EXPECT_EQ(test, map(test, data, 0), 6 * TEST_CHUNK); + KUNIT_EXPECT_EQ(test, map(test, data, TEST_CHUNK - 1), 7 * TEST_CHUNK - 1); + KUNIT_EXPECT_EQ(test, map(test, data, TEST_CHUNK), 2 * TEST_CHUNK); + KUNIT_EXPECT_EQ(test, map(test, data, 2 * TEST_CHUNK - 4096), 3 * TEST_CHUNK - 4096); + KUNIT_EXPECT_EQ(test, map(test, data, 2 * TEST_CHUNK), 4 * TEST_CHUNK); + KUNIT_EXPECT_EQ(test, map(test, data, 3 * TEST_CHUNK - 1), 5 * TEST_CHUNK - 1); +} + +/* The last chunk is only half used: the size, not the chunk, ends the map. */ +static void lwvm_partial_last_chunk(struct kunit *test) +{ + struct lwvm_fixture *f = test->priv; + struct apple_sftl_lwvm_part *data = &f->lwvm->parts[0]; + u64 disk = 0; + + header_init(f->header, TEST_MEDIA, 1); + header_part(f->header, 0, 0x100000, 0x100000 + 2 * TEST_CHUNK + TEST_CHUNK / 2, "Data"); + header_map(f->header, 7, 0, 0); + header_map(f->header, 1, 0, 1); + header_map(f->header, 1023, 0, 2); + header_seal(f->header); + KUNIT_ASSERT_EQ(test, apple_sftl_lwvm_decode(f->header, TEST_MEDIA, f->lwvm), 0); + KUNIT_EXPECT_TRUE(test, data->pieced); + KUNIT_EXPECT_EQ(test, data->nr_chunks, 3); + KUNIT_EXPECT_EQ(test, map(test, data, TEST_CHUNK + 4096), TEST_CHUNK + 4096); + KUNIT_EXPECT_EQ(test, map(test, data, 2 * TEST_CHUNK), 1023 * TEST_CHUNK); + KUNIT_EXPECT_EQ(test, map(test, data, 2 * TEST_CHUNK + TEST_CHUNK / 2 - 1), + 1023 * TEST_CHUNK + TEST_CHUNK / 2 - 1); + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_map(data, 2 * TEST_CHUNK + TEST_CHUNK / 2, &disk), + -ERANGE); + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_map(data, U64_MAX, &disk), -ERANGE); +} + +/* A partition the map cannot serve is refused alone; the others stay. */ +static void lwvm_broken_partitions(struct kunit *test) +{ + struct lwvm_fixture *f = test->priv; + struct apple_sftl_lwvm *lwvm = f->lwvm; + u64 disk = 0; + + header_init(f->header, TEST_MEDIA, 5); + header_part(f->header, 0, 0, 2 * TEST_CHUNK, "Hole"); + header_part(f->header, 1, 0, 2 * TEST_CHUNK, "Twice"); + header_part(f->header, 2, 0, 1 * TEST_CHUNK, "Beyond"); + header_part(f->header, 3, 4096, 4096, "Empty"); + header_part(f->header, 4, 0, 2 * TEST_CHUNK, "Good"); + header_map(f->header, 10, 0, 1); + header_map(f->header, 11, 1, 0); + header_map(f->header, 12, 1, 0); + header_map(f->header, 13, 1, 1); + header_map(f->header, 14, 2, 0); + header_map(f->header, 15, 2, 1); + header_map(f->header, 21, 4, 0); + header_map(f->header, 20, 4, 1); + header_seal(f->header); + KUNIT_ASSERT_EQ(test, apple_sftl_lwvm_decode(f->header, TEST_MEDIA, lwvm), 0); + KUNIT_EXPECT_EQ(test, lwvm->parts[0].error, -ENODATA); + KUNIT_EXPECT_EQ(test, lwvm->parts[1].error, -EEXIST); + KUNIT_EXPECT_EQ(test, lwvm->parts[2].error, -ERANGE); + KUNIT_EXPECT_EQ(test, lwvm->parts[3].error, -EINVAL); + KUNIT_EXPECT_EQ(test, lwvm->parts[4].error, 0); + KUNIT_EXPECT_FALSE(test, lwvm->parts[0].pieced); + KUNIT_EXPECT_FALSE(test, lwvm->parts[1].pieced); + KUNIT_EXPECT_FALSE(test, lwvm->parts[2].pieced); + KUNIT_EXPECT_FALSE(test, lwvm->parts[3].pieced); + KUNIT_EXPECT_TRUE(test, lwvm->parts[4].pieced); + KUNIT_EXPECT_EQ(test, lwvm->parts[1].mapped, 3); + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_map(&lwvm->parts[0], TEST_CHUNK, &disk), -ERANGE); + KUNIT_EXPECT_EQ(test, map(test, &lwvm->parts[4], 0), 21 * TEST_CHUNK); + KUNIT_EXPECT_EQ(test, map(test, &lwvm->parts[4], TEST_CHUNK), 20 * TEST_CHUNK); +} + +/* Headers and maps that block/partitions/lwvm.c rejects as a whole. */ +static void lwvm_bad_tables(struct kunit *test) +{ + struct lwvm_fixture *f = test->priv; + u8 *h = f->header; + + header_init(h, TEST_MEDIA, 1); + header_part(h, 0, 0, TEST_CHUNK, "System"); + header_map(h, 1, 0, 0); + header_seal(h); + KUNIT_ASSERT_EQ(test, apple_sftl_lwvm_decode(h, TEST_MEDIA, f->lwvm), 0); + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_decode(h, TEST_MEDIA + TEST_CHUNK, f->lwvm), + -EBADMSG); + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_decode(h, TEST_MEDIA / 2, f->lwvm), -ENOENT); + h[100] ^= 1; + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_decode(h, TEST_MEDIA, f->lwvm), -EBADMSG); + h[0] ^= 1; + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_decode(h, TEST_MEDIA, f->lwvm), -ENOENT); + + header_init(h, TEST_MEDIA, 0); + header_seal(h); + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_decode(h, TEST_MEDIA, f->lwvm), -EBADMSG); + + /* An owner past the partition count. */ + header_init(h, TEST_MEDIA, 1); + header_part(h, 0, 0, TEST_CHUNK, "System"); + header_map(h, 1, 0, 0); + header_map(h, 2, 1, 0); + header_seal(h); + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_decode(h, TEST_MEDIA, f->lwvm), -EINVAL); + + /* A partition in the header chunk. */ + header_init(h, TEST_MEDIA, 1); + header_part(h, 0, 0, TEST_CHUNK, "System"); + header_map(h, 0, 0, 0); + header_seal(h); + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_decode(h, TEST_MEDIA, f->lwvm), -EINVAL); + + /* 16 KiB chunks: only 512 lie on the disk. */ + header_init(h, TEST_MEDIA + 4096, 1); + header_part(h, 0, 0, 16384, "System"); + header_map(h, 512, 0, 0); + header_seal(h); + KUNIT_EXPECT_EQ(test, apple_sftl_lwvm_decode(h, TEST_MEDIA + 4096, f->lwvm), -EINVAL); + header_map(h, 512, 0xf, 0x111); + header_map(h, 511, 0, 0); + header_seal(h); + KUNIT_ASSERT_EQ(test, apple_sftl_lwvm_decode(h, TEST_MEDIA + 4096, f->lwvm), 0); + KUNIT_EXPECT_EQ(test, f->lwvm->chunks, 512); + KUNIT_EXPECT_EQ(test, map(test, &f->lwvm->parts[0], 16383), 511 * 16384ULL + 16383); +} + +static struct kunit_case lwvm_cases[] = { + KUNIT_CASE(lwvm_chunk_size), + KUNIT_CASE(lwvm_contiguous), + KUNIT_CASE(lwvm_interleaved), + KUNIT_CASE(lwvm_partial_last_chunk), + KUNIT_CASE(lwvm_broken_partitions), + KUNIT_CASE(lwvm_bad_tables), + {} +}; + +static struct kunit_suite lwvm_suite = { + .name = "apple-sftl-lwvm", + .init = lwvm_init, + .test_cases = lwvm_cases, +}; +kunit_test_suite(lwvm_suite); +MODULE_LICENSE("GPL"); diff --git a/drivers/mtd/apple-sftl-lwvm.c b/drivers/mtd/apple-sftl-lwvm.c new file mode 100644 index 00000000000000..2f2c4967ffe665 --- /dev/null +++ b/drivers/mtd/apple-sftl-lwvm.c @@ -0,0 +1,171 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * LwVM partitions stored in pieces. + * + * block/partitions/lwvm.c adds each LwVM partition whose chunks are stored in + * order and back to back as an ordinary partition, and skips the others. + * This decoder reads the same header with the same checks and keeps, for + * every partition, the map from partition chunk to disk chunk, so the SFTL + * block frontend can serve a scattered partition read-only through it. + * + * A map entry is the partition index in the top four bits and the partition + * chunk in the low twelve; owner 0xf is the header chunk or a free chunk. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "apple-sftl-lwvm.h" + +#define LWVM_MEDIA_OFFSET 0x20 +#define LWVM_COUNT_OFFSET 0x28 +#define LWVM_CRC_OFFSET 0x2c +#define LWVM_PARTS_OFFSET 0x200 +#define LWVM_PART_BYTES 0x80 +#define LWVM_MAP_OFFSET 0x800 +#define LWVM_CHUNK_FREE 0xf +#define LWVM_NAME_CHARS 36 + +/* 6a9088cf-8afd-630a-e351-e24887e0b98b, the CRC-protected variant. */ +static const u8 lwvm_signature[16] = { + 0x6a, 0x90, 0x88, 0xcf, 0x8a, 0xfd, 0x63, 0x0a, + 0xe3, 0x51, 0xe2, 0x48, 0x87, 0xe0, 0xb9, 0x8b, +}; + +/* The chunk is the smallest power of two that splits the disk in 1024. */ +unsigned int apple_sftl_lwvm_chunk_shift(u64 media_bytes) +{ + if (media_bytes < 2ULL * APPLE_SFTL_LWVM_HEADER_BYTES * APPLE_SFTL_LWVM_CHUNKS) + return 0; + return fls64(DIV_ROUND_UP_ULL(media_bytes, APPLE_SFTL_LWVM_CHUNKS) - 1); +} +EXPORT_SYMBOL_GPL(apple_sftl_lwvm_chunk_shift); + +static bool lwvm_crc_ok(const u8 *header) +{ + static const u8 zero[4]; + u32 crc; + + crc = crc32_le(~0, header, LWVM_CRC_OFFSET); + crc = crc32_le(crc, zero, sizeof(zero)); + crc = crc32_le(crc, header + LWVM_CRC_OFFSET + 4, + APPLE_SFTL_LWVM_HEADER_BYTES - LWVM_CRC_OFFSET - 4); + return ~crc == get_unaligned_le32(header + LWVM_CRC_OFFSET); +} + +static void lwvm_part(const u8 *entry, unsigned int shift, struct apple_sftl_lwvm_part *part) +{ + unsigned int i; + + memcpy(part->guid, entry + 16, sizeof(part->guid)); + part->begin = get_unaligned_le64(entry + 32); + part->end = get_unaligned_le64(entry + 40); + part->attributes = get_unaligned_le64(entry + 48); + for (i = 0; i < LWVM_NAME_CHARS; i++) { + u16 c = get_unaligned_le16(entry + 56 + 2 * i); + + if (!c) + break; + part->name[i] = c < 0x80 && isprint(c) ? c : '!'; + } + part->name[i] = 0; + part->chunk_shift = shift; + memset(part->chunk, 0xff, sizeof(part->chunk)); + /* block/partitions/lwvm.c ignores these entries without a word. */ + if (part->end <= part->begin || (part->begin | part->end) & 511) { + part->error = -EINVAL; + return; + } + if (part->end - part->begin > (u64)APPLE_SFTL_LWVM_CHUNKS << shift) { + part->error = -EFBIG; + return; + } + part->nr_chunks = DIV_ROUND_UP_ULL(part->end - part->begin, 1ULL << shift); +} + +/* + * Returns -ENOENT without an LwVM signature, -EBADMSG for a header that fails + * its CRC, size or count check (try the copy), and -EINVAL for a map that + * block/partitions/lwvm.c rejects as a whole. + */ +int apple_sftl_lwvm_decode(const u8 *header, u64 media_bytes, struct apple_sftl_lwvm *lwvm) +{ + unsigned int shift = apple_sftl_lwvm_chunk_shift(media_bytes); + unsigned int i, k; + u32 count; + + if (!shift || memcmp(header, lwvm_signature, sizeof(lwvm_signature))) + return -ENOENT; + count = get_unaligned_le32(header + LWVM_COUNT_OFFSET); + if (!lwvm_crc_ok(header) || + get_unaligned_le64(header + LWVM_MEDIA_OFFSET) != media_bytes || + count < 1 || count > APPLE_SFTL_LWVM_MAX_PARTS) + return -EBADMSG; + + memset(lwvm, 0, sizeof(*lwvm)); + lwvm->media_bytes = media_bytes; + lwvm->chunk_shift = shift; + lwvm->chunks = media_bytes >> shift; + lwvm->nr_parts = count; + for (i = 0; i < count; i++) + lwvm_part(header + LWVM_PARTS_OFFSET + i * LWVM_PART_BYTES, shift, + &lwvm->parts[i]); + + for (k = 0; k < APPLE_SFTL_LWVM_CHUNKS; k++) { + u16 entry = get_unaligned_le16(header + LWVM_MAP_OFFSET + 2 * k); + unsigned int owner = entry >> 12, index = entry & 0xfff; + struct apple_sftl_lwvm_part *part; + + if (owner == LWVM_CHUNK_FREE) + continue; + if (!k || k >= lwvm->chunks || owner >= count) + return -EINVAL; + part = &lwvm->parts[owner]; + part->mapped++; + if (part->error) + continue; + if (index >= part->nr_chunks) + part->error = -ERANGE; + else if (part->chunk[index] != APPLE_SFTL_LWVM_NO_CHUNK) + part->error = -EEXIST; + else + part->chunk[index] = k; + } + + for (i = 0; i < count; i++) { + struct apple_sftl_lwvm_part *part = &lwvm->parts[i]; + bool in_order = true; + + if (part->error) + continue; + for (k = 0; k < part->nr_chunks; k++) { + if (part->chunk[k] == APPLE_SFTL_LWVM_NO_CHUNK) { + part->error = -ENODATA; + break; + } + if (part->chunk[k] != part->chunk[0] + k) + in_order = false; + } + part->pieced = !part->error && !in_order; + } + return 0; +} +EXPORT_SYMBOL_GPL(apple_sftl_lwvm_decode); + +/* Partition byte offset to disk byte offset, through the chunk map. */ +int apple_sftl_lwvm_map(const struct apple_sftl_lwvm_part *part, u64 offset, u64 *disk_offset) +{ + u64 mask = (1ULL << part->chunk_shift) - 1; + + if (part->error || offset >= part->end - part->begin) + return -ERANGE; + *disk_offset = ((u64)part->chunk[offset >> part->chunk_shift] << part->chunk_shift) | + (offset & mask); + return 0; +} +EXPORT_SYMBOL_GPL(apple_sftl_lwvm_map); diff --git a/drivers/mtd/apple-sftl-lwvm.h b/drivers/mtd/apple-sftl-lwvm.h new file mode 100644 index 00000000000000..a6df74d76ef35e --- /dev/null +++ b/drivers/mtd/apple-sftl-lwvm.h @@ -0,0 +1,45 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _APPLE_SFTL_LWVM_H +#define _APPLE_SFTL_LWVM_H + +#include + +#define APPLE_SFTL_LWVM_HEADER_BYTES 4096U +#define APPLE_SFTL_LWVM_CHUNKS 1024U +#define APPLE_SFTL_LWVM_MAX_PARTS 8U +#define APPLE_SFTL_LWVM_NO_CHUNK 0xffffU + +/* + * One LwVM partition. chunk[] maps each partition chunk to the disk chunk + * that stores it. error is 0 when every chunk is mapped exactly once, else + * why the map cannot serve the partition. pieced marks a valid partition + * that block/partitions/lwvm.c skips because it is not stored in order and + * back to back. + */ +struct apple_sftl_lwvm_part { + u64 begin; + u64 end; + u64 attributes; + u8 guid[16]; + char name[37]; + u8 chunk_shift; + bool pieced; + int error; + u32 nr_chunks; /* chunks the size needs, the last one can be partial */ + u32 mapped; /* map entries that name this partition */ + u16 chunk[APPLE_SFTL_LWVM_CHUNKS]; +}; + +struct apple_sftl_lwvm { + u64 media_bytes; + u32 chunks; /* whole chunks on the disk */ + u32 nr_parts; + u8 chunk_shift; + struct apple_sftl_lwvm_part parts[APPLE_SFTL_LWVM_MAX_PARTS]; +}; + +unsigned int apple_sftl_lwvm_chunk_shift(u64 media_bytes); +int apple_sftl_lwvm_decode(const u8 *header, u64 media_bytes, struct apple_sftl_lwvm *lwvm); +int apple_sftl_lwvm_map(const struct apple_sftl_lwvm_part *part, u64 offset, u64 *disk_offset); + +#endif diff --git a/drivers/mtd/apple-sftl.h b/drivers/mtd/apple-sftl.h index 6c16a6ae6fbdb8..e30e00ef9e3b6b 100644 --- a/drivers/mtd/apple-sftl.h +++ b/drivers/mtd/apple-sftl.h @@ -54,6 +54,8 @@ void apple_sftl_set_checkpoint_ops(struct apple_sftl *sftl, struct apple_sftl_info { bool read_only; + bool unmeasured; /* guessed profile: log what the load decided */ + bool lwvm_pieces; /* profile serves scattered LwVM partitions */ u32 logical_pages; u32 disk_pages; u32 nr_runs; From 9eeb7f3ccc6566732ce4a44e776a5ded828fbe45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:44:04 +0100 Subject: [PATCH 27/43] mtd: apple-sftl: Replay a repeated sequence in block order on the iPhone 5 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After iOS had written for about eight hours, the N42 read-only load stopped in the journal replay: record 1265 repeated the sequence of record 1264 and the strict "every sequence exactly once" rule refused it. 1265 records after the checkpoint is less than one superblock (4096 slots), so the repeat most likely sits where a block closed with a summary and the next one started. iOS does not appear to replay by a global sequence count. The 12H321 SwissFTL in iBEC (s_cxt_boot, s_cxt_scan_diff, s_scan_all_sb, s_btoc_read) loads the checkpoint, then scans superblocks and their block tables of contents, and on a uECC "exits early to be coherent" instead of failing. That is read from its strings and assertions, not decompiled. Under block-by-block replay a repeated sequence just means the later block's record is applied last. Do that on profiles with equal_sequences (only the N42 one): records with the same sequence are put in block order (the block's first sequence, then the position in it) and a record that repeats the previous sequence is applied without advancing the expected one. Each repeat is logged at debug level with both records. The P105 profiles still refuse a repeated sequence, and the new KUnit case checks both: the 16 GB fixture, now parametrised by block and superblock count, fails on P105 and loads on the N42 layout, with the repeated record readable. Tested on an iPhone5,2: the medium loads, and the System partition's HFS+ mounts read-only. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/apple-sftl-core.c | 51 ++++++++++++++++++- drivers/mtd/apple-sftl-test.c | 95 +++++++++++++++++++++++++++++------ 2 files changed, 128 insertions(+), 18 deletions(-) diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c index d3003e405c7c4c..e30f02cdd0c71c 100644 --- a/drivers/mtd/apple-sftl-core.c +++ b/drivers/mtd/apple-sftl-core.c @@ -78,6 +78,7 @@ struct sftl_geometry { bool summary_sequences; /* a summary may consume one sequence per chunk */ bool degrade_remnants; /* a context block with an unknown base only blocks writes */ bool hidden_tail_type2; /* iOS 9 writes the hidden tail as type 2, flag 1 */ + bool equal_sequences; /* replay a record that repeats the previous sequence */ bool lwvm_pieces; /* serve scattered LwVM partitions as disks */ }; @@ -125,7 +126,7 @@ static const struct sftl_geometry sftl_16gb_n42 = { .bootstrap = { 1055, 1054 }, .nr_bootstrap = 2, .map_batch = 16, .disk_pages = 3906250, .lpages = 3906266, .summary_sequences = true, - .lwvm_pieces = true, + .lwvm_pieces = true, .equal_sequences = true, }; static const struct sftl_geometry *const sftl_geometries[] = { @@ -198,6 +199,7 @@ struct apple_sftl { u8 stage_oob[APPLE_PPN_OOB_SIZE], move_oob[APPLE_PPN_OOB_SIZE]; struct mutex lock; /* serializes reads and the shared page buffer */ bool failed; + u32 nr_equal; /* journal records that repeated the previous sequence */ }; static u32 sftl_stride(const struct apple_sftl *sftl) @@ -1691,6 +1693,45 @@ static bool sftl_context_gap(const struct apple_sftl *sftl, const struct sftl_re (journal->items[low + count - 1].stamp & SFTL_SEQUENCE) == next - 1; } +/* The first sequence of the block that holds a record: the order iOS + * replays blocks in. + */ +static u64 sftl_record_head(const struct apple_sftl *sftl, const u8 *heads, + const struct sftl_record *record) +{ + return sftl_sequence(heads + record->address / sftl_stride(sftl) * SFTL_META); +} + +static bool sftl_record_after(const struct apple_sftl *sftl, const u8 *heads, + const struct sftl_record *a, const struct sftl_record *b) +{ + u64 head_a = sftl_record_head(sftl, heads, a), head_b = sftl_record_head(sftl, heads, b); + + return head_a > head_b || (head_a == head_b && a->address > b->address); +} + +/* + * Records that share a sequence are put in the order iOS replays them: + * by the first sequence of their block, then by position in it, so the + * later block's record is applied last. sort() is not stable; the runs + * are short, so an insertion pass over the sorted array is enough. + */ +static void sftl_order_equal(const struct apple_sftl *sftl, const u8 *heads, + struct sftl_records *journal) +{ + u32 i, j; + + for (i = 1; i < journal->count; i++) { + struct sftl_record record = journal->items[i]; + u64 sequence = record.stamp & SFTL_SEQUENCE; + + for (j = i; j && (journal->items[j - 1].stamp & SFTL_SEQUENCE) == sequence && + sftl_record_after(sftl, heads, &journal->items[j - 1], &record); j--) + journal->items[j] = journal->items[j - 1]; + journal->items[j] = record; + } +} + static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_records *journal) { u64 floor = sftl->checkpoint_sequence, expected = floor + 1; @@ -1800,14 +1841,20 @@ static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_re } } sort(journal->items, journal->count, sizeof(*journal->items), sftl_record_compare, NULL); + if (sftl->geo->equal_sequences) + sftl_order_equal(sftl, heads, journal); for (i = 0; i < journal->count; i++) { const struct sftl_record *record = &journal->items[i]; + const struct sftl_record *prev = i ? &journal->items[i - 1] : NULL; u64 sequence = record->stamp & SFTL_SEQUENCE; ret = -EBADMSG; if (sequence == expected + 4 && sftl_take_torn(sftl, expected - 1)) expected = sequence; - if (sequence != expected++) + if (sftl->geo->equal_sequences && prev && + sequence == (prev->stamp & SFTL_SEQUENCE)) + sftl->nr_equal++; + else if (sequence != expected++) goto out; /* Context and summary chunks, and padding, map nothing. */ if (sftl_kind(record) == 0x1f || sftl_kind(record) == 0x1c || diff --git a/drivers/mtd/apple-sftl-test.c b/drivers/mtd/apple-sftl-test.c index 95637f39e05292..3db8736514b70a 100644 --- a/drivers/mtd/apple-sftl-test.c +++ b/drivers/mtd/apple-sftl-test.c @@ -3449,10 +3449,16 @@ static void sftl_test_gc_preserves_last_sequences(struct kunit *test) #define T16_NEXT 6U /* first page follows the new block's summary */ #define T16_NEXT_LBA 3000U #define T16_REMNANT 7U /* a context block of an older format */ +#define T16_OPEN 6U /* open after the new block, all lanes */ +#define T16_OPEN_LBA 3000U +/* The same layout on the iPhone 5: 1056 blocks, 1046 superblocks. */ +#define N42_BLOCKS 1056U +#define N42_SUBBLOCKS 1046U struct t16_fixture { struct apple_ppn provider; struct apple_ppn_ops ops; + u16 blocks, subblocks; /* per CAU; the VFL is in the top two blocks */ u16 vfl_block; /* bank holding the VFL; the other is erased */ u16 range_records; /* range records in the context */ bool summary_own_span; /* the new block's span counts its summary */ @@ -3467,6 +3473,7 @@ struct t16_fixture { u32 hidden_key; /* two pages of type 2, flag 1 records, then data, after the new block */ u32 hidden_epoch_skew; /* added to the hidden records' user epoch */ bool hidden_last; /* only one such page, every record with hidden_key */ + bool open_repeat; /* an open block starts on the summary's last sequence */ }; /* Fixed records before the ranges: the native base, statistics and tables. */ @@ -3485,15 +3492,15 @@ static unsigned int t16_lanes(u32 block) return block == T16_NEW ? 3 : T16_LANES; } -static u16 t16_usage(unsigned int lane, u32 block) +static u16 t16_usage(const struct t16_fixture *f, unsigned int lane, u32 block) { if (!block) return 0xb002; if (block == T16_NEW && lane == 2) return 0xbffe; - if (block >= 1062) + if (block >= f->blocks - 2U) return 0xbff1; - if (block >= T16_SUBBLOCKS) + if (block >= f->subblocks) return 0xb003; return 0; } @@ -3509,7 +3516,7 @@ static void t16_meta(u8 *meta, u8 kind, u8 flags, u64 sequence, u32 key, u32 hig static int t16_vfl(struct t16_fixture *f, unsigned int lane, u32 block, unsigned int page, u8 *data, u8 *oob, u8 *status) { - u16 group = block == 1063 ? 0 : 1; + u16 group = block == f->blocks - 1U ? 0 : 1; unsigned int i; if (block != f->vfl_block || page > T16_LANES + 1) @@ -3525,10 +3532,10 @@ static int t16_vfl(struct t16_fixture *f, unsigned int lane, u32 block, put_unaligned_le32(U32_MAX, data); put_unaligned_le32(T16_DISK, data + 4); put_unaligned_le32(0x100000, data + 8); - put_unaligned_le16(T16_SUBBLOCKS, data + 12); - put_unaligned_le16(T16_SUBBLOCKS, data + 14); + put_unaligned_le16(f->subblocks, data + 12); + put_unaligned_le16(f->subblocks, data + 14); for (i = 0; i < 8; i++) { - put_unaligned_le16(i < 4 ? 1063 : 1062, data + 0x100 + 4 * i); + put_unaligned_le16(f->blocks - (i < 4 ? 1 : 2), data + 0x100 + 4 * i); data[0x100 + 4 * i + 2] = i % 4; } for (i = 0; i < T16_LANES; i++) @@ -3536,9 +3543,9 @@ static int t16_vfl(struct t16_fixture *f, unsigned int lane, u32 block, return 0; } oob[1] = page - 1; - for (i = 0; i < T16_BLOCKS; i++) - put_unaligned_le16(t16_usage(page - 1, i), data + 2 * i); - memset(data + 2 * T16_BLOCKS, 0xff, APPLE_PPN_PAGE_SIZE - 2 * T16_BLOCKS); + for (i = 0; i < f->blocks; i++) + put_unaligned_le16(t16_usage(f, page - 1, i), data + 2 * i); + memset(data + 2 * f->blocks, 0xff, APPLE_PPN_PAGE_SIZE - 2 * f->blocks); return 0; } @@ -3560,8 +3567,8 @@ static void t16_context_record(struct t16_fixture *f, u32 index, u8 *payload, u8 continue; subtype = groups[i].subtype; start = (index - first) * groups[i].entries; - entries = start >= T16_SUBBLOCKS ? 0 : - min_t(u32, groups[i].entries, T16_SUBBLOCKS - start); + entries = start >= f->subblocks ? 0 : + min_t(u32, groups[i].entries, f->subblocks - start); break; } t16_meta(meta, 0x1f, subtype, T16_CONTEXT_BASE + index, 0, U32_MAX); @@ -3571,7 +3578,7 @@ static void t16_context_record(struct t16_fixture *f, u32 index, u8 *payload, u8 put_unaligned_le32(1, payload); put_unaligned_le32(T16_CONTEXT, payload + 4); } else if (index == 3 && !f->legacy) { - put_unaligned_le32(T16_SUBBLOCKS, payload + 4096 - 4); + put_unaligned_le32(f->subblocks, payload + 4096 - 4); } else if (subtype == 3) { for (i = 0; i < entries; i++) { u32 block = start + i; @@ -3722,6 +3729,18 @@ static void t16_slot(struct t16_fixture *f, u32 block, u32 slot, u8 *payload, u8 put_unaligned_le32(T16_NEXT_LBA + slot, payload); t16_meta(meta, 1, 0, sequence, T16_NEXT_LBA + slot, sequence >> 16); } + /* + * The open block's first record repeats the last sequence the new + * block's summary counted; the next three continue from there. + */ + if (block == T16_OPEN && f->open_repeat && slot < 4) { + u64 sequence = T16_CONTEXT_BASE + 24 + f->range_records + t16_new_slots() + + T16_SUMMARY - 1 + slot; + + memset(payload, 'r', 4096); + put_unaligned_le32(T16_OPEN_LBA + slot, payload); + t16_meta(meta, 1, 0, sequence, T16_OPEN_LBA + slot, sequence >> 16); + } } static int t16_read_page(void *priv, unsigned int bus, unsigned int cau, @@ -3731,7 +3750,7 @@ static int t16_read_page(void *priv, unsigned int bus, unsigned int cau, struct t16_fixture *f = priv; unsigned int lane = cau * 2 + bus, width, index, chunk, i; - if (bus >= 2 || cau >= 2 || block >= T16_BLOCKS || + if (bus >= 2 || cau >= 2 || block >= f->blocks || page >= (context ? T16_PAGES / 2 : T16_PAGES)) return -EINVAL; memset(data, 0xff, APPLE_PPN_PAGE_SIZE); @@ -3739,12 +3758,12 @@ static int t16_read_page(void *priv, unsigned int bus, unsigned int cau, *status = 0x49; if (context) return t16_vfl(f, lane, block, page, data, oob, status); - if (block >= T16_SUBBLOCKS || t16_usage(lane, block)) + if (block >= f->subblocks || t16_usage(f, lane, block)) return 0; width = t16_lanes(block); /* Lanes of the superblock in order, the retired lane skipped. */ for (index = 0, i = 0; i < lane; i++) - if (!t16_usage(i, block)) + if (!t16_usage(f, i, block)) index++; for (chunk = 0; chunk < 4; chunk++) t16_slot(f, block, (page * width + index) * 4 + chunk, @@ -3765,6 +3784,8 @@ static struct t16_fixture *t16_fixture(struct kunit *test) .ops = &f->ops, .priv = f, .buses = 2, .caus = 2, .blocks = T16_BLOCKS, .pages = T16_PAGES, }; + f->blocks = T16_BLOCKS; + f->subblocks = T16_SUBBLOCKS; f->vfl_block = 1063; f->range_records = 32; f->new_block = true; @@ -4026,6 +4047,47 @@ static void sftl_test_16gb_context_rules(struct kunit *test) apple_sftl_free(sftl); } +/* + * On the iPhone 5 profile a record that repeats the previous sequence is + * replayed in block order and the journal goes on; the P105 16 GB profile + * still refuses the same medium. + */ +static void sftl_test_n42_repeated_sequence(struct kunit *test) +{ + struct t16_fixture *f = t16_fixture(test); + struct apple_sftl *sftl = NULL; + struct apple_sftl_info info; + u64 last; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->legacy = true; + last = t16_last(f); + f->open_repeat = true; + KUNIT_EXPECT_EQ(test, apple_sftl_load(&f->provider, &sftl), -EBADMSG); + KUNIT_EXPECT_PTR_EQ(test, sftl, NULL); + + f->provider.blocks = N42_BLOCKS; + f->blocks = N42_BLOCKS; + f->subblocks = N42_SUBBLOCKS; + f->vfl_block = N42_BLOCKS - 1; + f->open_repeat = false; + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); + apple_sftl_get_info(sftl, &info); + KUNIT_EXPECT_EQ(test, info.journal_sequence, last); + apple_sftl_free(sftl); + + f->open_repeat = true; + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); + apple_sftl_get_info(sftl, &info); + KUNIT_EXPECT_TRUE(test, info.read_only); + KUNIT_EXPECT_EQ(test, info.journal_sequence, last + 3); + t16_expect_page(test, sftl, T16_OPEN_LBA, 'r', T16_OPEN_LBA); + t16_expect_page(test, sftl, T16_OPEN_LBA + 3, 'r', T16_OPEN_LBA + 3); + t16_expect_page(test, sftl, T16_NEW_LBA + 3, 'n', T16_NEW_LBA + 3); + t16_expect_page(test, sftl, 0, 'o', 0); + apple_sftl_free(sftl); +} + static struct kunit_case apple_sftl_cases[] = { KUNIT_CASE(sftl_test_rotate_mounted), KUNIT_CASE(sftl_test_vfl_rotation_cuts), @@ -4094,6 +4156,7 @@ static struct kunit_case apple_sftl_cases[] = { KUNIT_CASE(sftl_test_16gb_context_remnant), KUNIT_CASE(sftl_test_16gb_reused_context_block), KUNIT_CASE(sftl_test_16gb_hidden_tail), + KUNIT_CASE(sftl_test_n42_repeated_sequence), {} }; From 3b67e5f660baa2933dca0af99995abc6adb65911 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Sun, 29 Nov 2026 14:44:04 +0100 Subject: [PATCH 28/43] ARM: dts: apple: s5l8950x: Describe the NAND controller; enable it on the iPhone 5 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the H2FMI flash controller from ADT /arm-io/flash-controller0 as "apple,s5l8950x-fmi" (read-only in the driver, no s5l8940x fallback): the six FMI/FMC/ECC windows at 0x1200000..0x1380000 and IRQs 33 and 34. The ADT's seventh window, the FMI DLL at 0x1000000, is not used. Its PMGR gates follow the ADT: clock-gates 0x14..0x18 map through the pmgr device-clocks table to power-state indices 0x32..0x36 ("FMI0", "FMI0-BCH", "FMI1", "FMI1-BCH", "FMI-DLL"), registers 0x3f1010c8 to 0x3f1010d8 (UART6's gate 0x25 -> index 0x44 -> 0x3f101110 checks the mapping). The gates are disabled with the controller, so that an unclaimed gate is never switched off by clk_disable_unused, and the iPhone 5 include enables them all. Tested on an iPhone5,2: SanDisk PPN, 2 buses x 2 CAUs x 1056 blocks; the SFTL loads and the System partition mounts read-only. N41's NAND stays disabled until an N41 is tested. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 29 +++++++++ arch/arm/boot/dts/apple/s5l8950x-n41.dts | 5 ++ arch/arm/boot/dts/apple/s5l8950x.dtsi | 81 ++++++++++++++++++++++++ 3 files changed, 115 insertions(+) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index 70f60010996959..28184df4e501bc 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -79,6 +79,35 @@ status = "okay"; }; +/* + * SanDisk 1Xnm64GeX2 PPN 1.5.5, 2 buses x 2 CAUs x 1056 blocks (12H321 + * ADT flash-controller0/disk), driven read-only. The boot chain lives in + * the same NAND (boot-from-nand 1), so nothing may write it blindly. + */ +&fmi0_ps { + status = "okay"; +}; + +&fmi0_bch_ps { + status = "okay"; +}; + +&fmi1_ps { + status = "okay"; +}; + +&fmi1_bch_ps { + status = "okay"; +}; + +&fmi_dll_ps { + status = "okay"; +}; + +&nand { + status = "okay"; +}; + &gpio { /* * UART3 (Bluetooth): ADT function-tx = 0x0400 (pin 32), function-rts = diff --git a/arch/arm/boot/dts/apple/s5l8950x-n41.dts b/arch/arm/boot/dts/apple/s5l8950x-n41.dts index d1b4f7622346e6..ca062d782c347b 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-n41.dts +++ b/arch/arm/boot/dts/apple/s5l8950x-n41.dts @@ -22,3 +22,8 @@ linux,initrd-end = <0x88000000>; }; }; + +/* No N41 has been tested, so keep NAND disabled until one is. */ +&nand { + status = "disabled"; +}; diff --git a/arch/arm/boot/dts/apple/s5l8950x.dtsi b/arch/arm/boot/dts/apple/s5l8950x.dtsi index 84d98ff6de92ff..787514c5af4737 100644 --- a/arch/arm/boot/dts/apple/s5l8950x.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x.dtsi @@ -217,6 +217,59 @@ status = "disabled"; }; + /* + * H2FMI gates: ADT flash-controller0 clock-gates <0x14 0x16 0x15 + * 0x17 0x18>, which the pmgr device-clocks table maps to + * power-state indices 0x32..0x36 ("FMI0", "FMI0-BCH", "FMI1", + * "FMI1-BCH", "FMI-DLL"). Disabled with the flash controller: + * only a board that enables the controller enables these, so + * an unclaimed gate is never switched off by clk_disable_unused. + */ + fmi0_ps: fmi0-ps@f1010c8 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf1010c8 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "fmi0_ps"; + status = "disabled"; + }; + + fmi0_bch_ps: fmi0-bch-ps@f1010cc { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf1010cc 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "fmi0_bch_ps"; + status = "disabled"; + }; + + fmi1_ps: fmi1-ps@f1010d0 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf1010d0 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "fmi1_ps"; + status = "disabled"; + }; + + fmi1_bch_ps: fmi1-bch-ps@f1010d4 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf1010d4 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "fmi1_bch_ps"; + status = "disabled"; + }; + + fmi_dll_ps: fmi-dll-ps@f1010d8 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf1010d8 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "fmi_dll_ps"; + status = "disabled"; + }; + uart1_ps: uart1-ps@f1010fc { compatible = "apple,s5l8940x-pmgr-clk-gate"; #clock-cells = <0>; @@ -380,6 +433,34 @@ status = "disabled"; }; + /* + * NAND: H2FMI driving two PPN packages, CE0 of each bus (ADT + * ce-bitmap 0x101, channels ce-map 0 and 8). ADT + * /arm-io/flash-controller0 ("fmi,s5l8950x", "fmi,s5l8920x"): + * FMI, FMC, ECC for bus 0, then bus 1, IRQs 33 and 34. The + * ADT's seventh window, the FMI DLL at 0x1000000 (0x10 bytes), + * is not used by the driver and not mapped. + * + * Read-only: "apple,s5l8950x-fmi" has no program or erase path + * and never resets the packages to SDR without + * mtd_apple_h2fmi.sdr_reset=1. Never add apple,s5l8940x-fmi as + * a fallback; a driver without the S5L8950X entry would bind it + * writable. + */ + nand: flash-controller@1200000 { + compatible = "apple,s5l8950x-fmi"; + reg = <0x1200000 0x1000>, /* FMI0 */ + <0x1240000 0x1000>, /* FMC0 */ + <0x1280000 0x1000>, /* ECC0 */ + <0x1300000 0x1000>, /* FMI1 */ + <0x1340000 0x1000>, /* FMC1 */ + <0x1380000 0x1000>; /* ECC1 */ + interrupts = <33>, <34>; + clocks = <&fmi0_ps>, <&fmi0_bch_ps>, <&fmi1_ps>, + <&fmi1_bch_ps>, <&fmi_dll_ps>; + status = "disabled"; + }; + /* * USB OTG PHY (ADT /arm-io/otgphyctrl + /arm-io/usb-complex). * Uses S5L8950X PMGR gates (+0x1084/+0x1088/+0x109c) and From 0963e67580371639c80288f837e89bd8a958a793 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:13:04 +0100 Subject: [PATCH 29/43] mtd: apple-sftl: Select LwVM diagnostics by geometry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use the N42 profile identity for the scattered-partition messages. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/apple-sftl-core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c index e30f02cdd0c71c..aab571df3b3437 100644 --- a/drivers/mtd/apple-sftl-core.c +++ b/drivers/mtd/apple-sftl-core.c @@ -3305,7 +3305,7 @@ EXPORT_SYMBOL_GPL(apple_sftl_flush); void apple_sftl_get_info(struct apple_sftl *sftl, struct apple_sftl_info *info) { info->read_only = sftl->vfl_degraded || sftl->context_degraded || !sftl->geo->writer; - info->unmeasured = sftl->geo->unmeasured; + info->unmeasured = sftl->geo == &sftl_16gb_n42; info->lwvm_pieces = sftl->geo->lwvm_pieces; info->logical_pages = sftl->geo->lpages; info->disk_pages = sftl->geo->disk_pages; From 756afd7ff3f80545bc91cdb5bac84f159557a605 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:19:11 +0100 Subject: [PATCH 30/43] mtd: apple-sftl: Derive the repeated sequence from the selected fixture MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Orchard models native and legacy 16 GB contexts separately. Generate the repeat at the end of the selected context and summary. The N42 replay case and the P105 native cases pass under ARM QEMU. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/apple-sftl-test.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/mtd/apple-sftl-test.c b/drivers/mtd/apple-sftl-test.c index 3db8736514b70a..bb0f7fa60037ed 100644 --- a/drivers/mtd/apple-sftl-test.c +++ b/drivers/mtd/apple-sftl-test.c @@ -3734,8 +3734,7 @@ static void t16_slot(struct t16_fixture *f, u32 block, u32 slot, u8 *payload, u8 * block's summary counted; the next three continue from there. */ if (block == T16_OPEN && f->open_repeat && slot < 4) { - u64 sequence = T16_CONTEXT_BASE + 24 + f->range_records + t16_new_slots() + - T16_SUMMARY - 1 + slot; + u64 sequence = t16_last(f) + slot; memset(payload, 'r', 4096); put_unaligned_le32(T16_OPEN_LBA + slot, payload); From 6a58a956e2f66f22d94dde9e9e756799ff1cb1d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:06:05 +0100 Subject: [PATCH 31/43] drm: apple-sgx: Run the A6's SGX543MP3 with its own microkernel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The iPhone 5's GPU (S5L8950X) is an SGX543MP3 with the A5's register layout, and the driver already counts cores from CORE_ID. iOS's A6 kext is a different build, though: class SGXDriver543RC2. Its microkernel is 0xdf0 bytes shorter, its PDS templates are smaller, and it has none of the A5's tables or the four extra buffers. Each offset this driver takes from the A5's kext therefore has another value or is gone. Move everything that depends on the build into struct sgx_variant, selected by compatible: - the sizes of __data and __const; - where the microkernel, the second code buffer and the boot program are; - the handler entry points; - the template offsets and sizes; - the USE addresses patched into the PDS programs; - the LIMM patches; - the boot program's two patched words; - the other cores' entry point; - BIF_MMU_CTRL; - whether the A5's tables exist. sgx_a5 keeps the existing values. sgx_a6 has the values read from the N42's 12H321 kernelcache: - initSGX 0x80ad0048; - loader 0x80ad5fb8; - setup 0x80ad66a0; - fill 0x80ad6cb0; - entries 0x80ad6688 and 0x80ad668c. Its initSGX makes the same register writes as the A5's, with three differences: - BIF_MMU_CTRL is 3, not 2; - no erratum 31195 bypass bits (the A6's ADT has no brn_31195); - USE_CODE_BASE_1 is not written. The A6's microkernel goes in its own file, apple/sgx543-s5l8950x.fw, in the same container format. Both kexts are build 12H321, so the firmware check compares the variant's section sizes. The driver is Project Cascadia's (rzxvx); the A5 side is unchanged. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/gpu/drm/apple-sgx/Kconfig | 10 +- drivers/gpu/drm/apple-sgx/apple_sgx.h | 2 + drivers/gpu/drm/apple-sgx/apple_sgx_hw.c | 352 ++++++++++++++++------- 3 files changed, 261 insertions(+), 103 deletions(-) diff --git a/drivers/gpu/drm/apple-sgx/Kconfig b/drivers/gpu/drm/apple-sgx/Kconfig index bc3c3cf056924c..8bcc99d9c11e78 100644 --- a/drivers/gpu/drm/apple-sgx/Kconfig +++ b/drivers/gpu/drm/apple-sgx/Kconfig @@ -1,6 +1,6 @@ # SPDX-License-Identifier: GPL-2.0-only config DRM_APPLE_SGX - tristate "Apple S5L8940X PowerVR SGX543MP2" + tristate "Apple S5L8940X/S5L8950X PowerVR SGX543MP2/MP3" depends on DRM depends on ARCH_APPLE_S5L || COMPILE_TEST depends on COMMON_CLK && OF @@ -9,9 +9,11 @@ config DRM_APPLE_SGX select DRM_KMS_HELPER select DRM_SCHED help - The GPU of the Apple A5 (S5L8940X/8942X), a PowerVR SGX543MP2. - Switches it on with the initialisation iOS runs, starts iOS's GPU - microkernel (from /lib/firmware/apple/sgx543.fw, which the user + The GPU of the Apple A5 (S5L8940X/8942X), a PowerVR SGX543MP2, + and of the A6 (S5L8950X), an SGX543MP3. Switches it on with the + initialisation iOS runs, starts iOS's GPU microkernel (from + /lib/firmware/apple/sgx543.fw on the A5 and + /lib/firmware/apple/sgx543-s5l8950x.fw on the A6, which the user takes out of their own IPSW), and offers a render node for Mesa and sgx2d: GEM buffers in the GPU's address space and renders queued to the microkernel; KMS on the boot framebuffer, which the diff --git a/drivers/gpu/drm/apple-sgx/apple_sgx.h b/drivers/gpu/drm/apple-sgx/apple_sgx.h index 870b6256e8e9e3..c897ebadc28b66 100644 --- a/drivers/gpu/drm/apple-sgx/apple_sgx.h +++ b/drivers/gpu/drm/apple-sgx/apple_sgx.h @@ -24,6 +24,7 @@ struct drm_file; struct drm_gem_object; struct page; struct resource; +struct sgx_variant; /* The register window: six 16 KiB banks -- bank 0 broadcast (write only: * a read hangs the bus), bank 1 the master, bank 2 + n core n. */ @@ -155,6 +156,7 @@ struct apple_sgx { resource_size_t size; struct clk_bulk_data *clks; int num_clks; + const struct sgx_variant *var; /* the kext build its microkernel is from */ unsigned int ncores; u32 core_id, core_rev; bool brn_31195; diff --git a/drivers/gpu/drm/apple-sgx/apple_sgx_hw.c b/drivers/gpu/drm/apple-sgx/apple_sgx_hw.c index 7f356bf3226d65..68e2b89fffcf64 100644 --- a/drivers/gpu/drm/apple-sgx/apple_sgx_hw.c +++ b/drivers/gpu/drm/apple-sgx/apple_sgx_hw.c @@ -46,6 +46,11 @@ * build takes it out of the user's own IPSW (scripts/extract-sgx-firmware.py) * into /lib/firmware/apple/sgx543.fw, and the offsets below are for that * exact 12H321 build, which the script checks by hash. + * + * The A6 (S5L8950X, an SGX543MP3) has the same register banks and the + * same initialisation, but its kext is another build (SGXDriver543RC2) with + * a microkernel of its own, apple/sgx543-s5l8950x.fw: what differs between + * the two builds is in struct sgx_variant. */ #include @@ -68,6 +73,7 @@ #include #include #include +#include #include #include #include @@ -172,10 +178,6 @@ /* ---- the firmware file (scripts/extract-sgx-firmware.py) --------------- */ -#define SGX_FW_NAME "apple/sgx543.fw" -#define SGX_FW_DATA_SIZE 0x16094 /* kext __DATA,__data */ -#define SGX_FW_CONST_SIZE 0x730 /* kext __TEXT,__const */ - struct sgx_fw_header { char magic[8]; /* "SGX543FW" */ __le32 version; /* 1 */ @@ -185,21 +187,13 @@ struct sgx_fw_header { char build[16]; /* "12H321" */ }; -/* In __data: the microkernel, its boot program, and tables. */ -#define UK_CODE_OFF 0x00060 -#define UK_CODE_SIZE 0x11f88 -#define UK_CODE2_OFF 0x11fe8 /* more USSE code */ -#define UK_CODE2_SIZE 0x3b58 -#define UK_BOOT_OFF 0x15b40 -#define UK_BOOT_SIZE 0x248 +/* In the A5's __data, after the boot program: its tables. */ #define UK_TAB_BASE 0x15d90 /* The code buffer: the boot program at 0, the microkernel at 0x1000 (iOS's - * this+0x6d0), and the entry points into the boot program for core 0 and for - * the others (0x80bfa068, 0x80bfa06c). */ + * this+0x6d0), and core 0's entry into the boot program (0x80bfa068). */ #define UK_START 0x1000 #define UK_ENTRY_CORE0 0x40 -#define UK_ENTRY_OTHERS 0x240 /* ---- commands: the DDK's kernel CCB (sgx_mkif_km.h), as iOS uses it ---- */ @@ -217,13 +211,14 @@ struct sgx_ccb_cmd { }; /* The handlers iOS hands the microkernel (this+0x72c..0x73c, computed at - * 0x80bfa448), as offsets into the microkernel. Which is which follows - * from where iOS sends them: TA and TRANSFER from the submit of the - * render and the transfer queue (slot 38 of the vtables at 0x80c02798 and - * 0x80c02898), POWER from deinitSGX (0x80bf4048) exactly as the DDK's - * SGXPrePowerState does it, HWPERF with the perf-counter selectors it - * copies into the host control block (0x80bfb1f0), and 0x738 for each - * context after a hardware recovery (0x80bf3f42), with cache control 6. */ + * 0x80bfa448), as offsets into the microkernel (struct sgx_variant). + * Which is which follows from where iOS sends them: TA and TRANSFER from + * the submit of the render and the transfer queue (slot 38 of the vtables + * at 0x80c02798 and 0x80c02898), POWER from deinitSGX (0x80bf4048) exactly + * as the DDK's SGXPrePowerState does it, HWPERF with the perf-counter + * selectors it copies into the host control block (0x80bfb1f0), and 0x738 + * for each context after a hardware recovery (0x80bf3f42), with cache + * control 6. */ enum sgx_cmd_type { SGX_CMD_TA, SGX_CMD_POWER, @@ -233,15 +228,116 @@ enum sgx_cmd_type { SGX_CMD_NUM }; -static const struct { - u32 off; - const char *name; -} uk_handlers[SGX_CMD_NUM] = { - [SGX_CMD_TA] = { 0x1fa8, "TA" }, - [SGX_CMD_POWER] = { 0x1bf0, "POWER" }, - [SGX_CMD_TRANSFER] = { 0x1e80, "TRANSFER" }, - [SGX_CMD_RECOVER] = { 0x21d0, "RECOVER" }, - [SGX_CMD_HWPERF] = { 0x21d8, "HWPERF" }, +static const char *const uk_handler_names[SGX_CMD_NUM] = { + [SGX_CMD_TA] = "TA", + [SGX_CMD_POWER] = "POWER", + [SGX_CMD_TRANSFER] = "TRANSFER", + [SGX_CMD_RECOVER] = "RECOVER", + [SGX_CMD_HWPERF] = "HWPERF", +}; + +/* The small PDS programs the loader copies out of __const. */ +enum { T_6D8, T_6E0, T_6E8, T_6F0, T_6F8, T_704, T_NUM }; + +/* + * What one kext build has where. Every number here is an offset into one + * exact build -- into __data, __const, the microkernel or its boot program + * -- so each is checked against that build's disassembly, not derived. + * + * The A5's (S5L8940X/8942X, class SGXDriver543, the P105's and the K93's + * 12H321 kernelcache) is the one the comments in this file quote addresses + * from. The A6's (S5L8950X, class SGXDriver543RC2, the N42's 12H321 + * kernelcache) is another build of the microkernel: its code is 0xdf0 + * bytes shorter, its templates smaller, and the A5's tables and four + * extra buffers are gone -- its loader (0x80ad5fb8) and setup (0x80ad66a0) + * allocate none of them, and initSGX (0x80ad0048) leaves USE_CODE_BASE_1 + * alone. Its initSGX writes the same registers in the same order but + * for BIF_MMU_CTRL (3 where the A5 has 2) and the SLC bypass (no erratum + * 31195 bits). The iOS addresses each value comes from are with it. + */ +struct sgx_variant { + const char *fw_name; + const char *kext; /* for messages */ + u32 data_size, const_size; /* kext __DATA,__data and __TEXT,__const */ + u32 code_off, code_size; /* the microkernel, in __data */ + u32 code2_off, code2_size; /* more USSE code, a buffer of its own */ + u32 boot_off, boot_size; /* the boot program, in __data */ + u32 entry_others; /* the other cores' entry into the boot program */ + u32 boot_core0, boot_core0_to; /* the boot program's word that sends core 0 + * on, and where in the microkernel */ + u32 handlers[SGX_CMD_NUM]; + struct { u16 off, size; } tmpl[T_NUM]; /* in __const */ + u32 pds_6e8; /* the 6e8 program's USE code */ + u32 pds_6f0[5]; /* the 6f0 program's, words 2, 3, 6, 7, 10 */ + u32 pds_6f8[4]; /* the 6f8 program's, words 4, 8, 12, 16 */ + u32 limm_6f0; /* the LIMM with the 6f0 program's address */ + u32 limm_n, limm_n_val; /* a LIMM with a small constant */ + u32 limm_pair[2]; /* LIMMs with 0x02800900, each followed at + * +0x18 by one with the 6f8 program's + * address >> 4 */ + u32 bif_mmu_ctrl; /* (MASTER_)BIF_MMU_CTRL */ + bool tables; /* the A5's tables and buffers 794-7a0 */ +}; + +/* SGXDriver543: loader 0x80bf9754, setup 0x80bfa080, fill 0x80bfa884. */ +static const struct sgx_variant sgx_a5 = { + .fw_name = "apple/sgx543.fw", + .kext = "SGXDriver543 (S5L8940X) 12H321", + .data_size = 0x16094, + .const_size = 0x730, + .code_off = 0x60, + .code_size = 0x11f88, + .code2_off = 0x11fe8, + .code2_size = 0x3b58, + .boot_off = 0x15b40, + .boot_size = 0x248, + .entry_others = 0x240, /* 0x80bfa06c */ + .boot_core0 = 0x70, + .boot_core0_to = 0x9d40, + .handlers = { 0x1fa8, 0x1bf0, 0x1e80, 0x21d0, 0x21d8 }, + .tmpl = { { 0x084, 0x18 }, { 0x09c, 0x38 }, { 0x0d4, 0x18 }, + { 0x0ec, 0x350 }, { 0x43c, 0x9c }, { 0x4d8, 0x258 } }, + .pds_6e8 = 0xc0, + .pds_6f0 = { 0x10d20, 0xd0d0, 0x4340, 0xac50, 0x1470 }, + .pds_6f8 = { 0xd3f0, 0x4510, 0x11190, 0xad20 }, + .limm_6f0 = 0xe0, + .limm_n = 0xf0, + .limm_n_val = 7, + .limm_pair = { 0x7f98, 0x86c8 }, + .bif_mmu_ctrl = 2, + .tables = true, +}; + +/* SGXDriver543RC2: initSGX 0x80ad0048 (clock helpers 0x80acfdd4 and + * 0x80acfe2c, the same as the A5's), loader 0x80ad5fb8, setup 0x80ad66a0 + * (handlers from the table at 0x80ad6bd0), fill 0x80ad6cb0, entries + * 0x80ad6688 / 0x80ad668c. */ +static const struct sgx_variant sgx_a6 = { + .fw_name = "apple/sgx543-s5l8950x.fw", + .kext = "SGXDriver543RC2 (S5L8950X) 12H321", + .data_size = 0x14eb4, + .const_size = 0x300, + .code_off = 0x60, + .code_size = 0x11198, + .code2_off = 0x111f8, + .code2_size = 0x3a88, + .boot_off = 0x14c80, + .boot_size = 0x188, + .entry_others = 0x180, + .boot_core0 = 0x60, + .boot_core0_to = 0x9690, + .handlers = { 0x19e8, 0x1630, 0x18c0, 0x1c10, 0x1c18 }, + .tmpl = { { 0x084, 0x18 }, { 0x09c, 0x38 }, { 0x0d4, 0x18 }, + { 0x0ec, 0x134 }, { 0x220, 0x9c }, { 0x2bc, 0x44 } }, + .pds_6e8 = 0xa0, + .pds_6f0 = { 0x10080, 0xc5f0, 0x3d80, 0xa5a0, 0xf00 }, + .pds_6f8 = { 0xc910, 0x3f50, 0x103d0, 0xa670 }, + .limm_6f0 = 0xc0, + .limm_n = 0xd0, + .limm_n_val = 6, + .limm_pair = { 0x7998, 0x80c8 }, + .bif_mmu_ctrl = 3, + .tables = false, }; /* POWER's Data[1], and what the microkernel sets in the power status when @@ -278,15 +374,17 @@ static const struct sgx_buf_desc { u8 pte; /* PTE_RO, PTE_SHARED or 0 */ u32 off; /* into __data or __const */ } sgx_buf_descs[B_NUM] = { - /* 0x80bf9754, the loader */ - [B_CODE] = { "code 6d4", UK_START + UK_CODE_SIZE, 0x1000, SRC_ZERO, PTE_RO }, - [B_PDS_6D8] = { "pds 6d8", 0x18, 0x1000, SRC_CONST, PTE_SHARED, 0x084 }, - [B_PDS_6E0] = { "pds 6e0", 0x38, 0x1000, SRC_CONST, PTE_SHARED, 0x09c }, - [B_PDS_6E8] = { "pds 6e8", 0x18, 0x1000, SRC_CONST, PTE_SHARED, 0x0d4 }, - [B_PDS_6F0] = { "pds 6f0", 0x350, 0x1000, SRC_CONST, PTE_SHARED, 0x0ec }, - [B_PDS_6F8] = { "pds 6f8", 0x9c, 0x1000, SRC_CONST, PTE_SHARED, 0x43c }, - [B_CODE2] = { "code 700", UK_CODE2_SIZE, 0x1000, SRC_DATA, PTE_RO, UK_CODE2_OFF }, - [B_PDS_704] = { "pds 704", 0x258, 0x1000, SRC_CONST, PTE_SHARED, 0x4d8 }, + /* 0x80bf9754, the loader; sizes and offsets of the code and the + * templates are the variant's (sgx_buf_desc()) */ + [B_CODE] = { "code 6d4", 0, 0x1000, SRC_ZERO, PTE_RO }, + [B_PDS_6D8] = { "pds 6d8", 0, 0x1000, SRC_CONST, PTE_SHARED }, + [B_PDS_6E0] = { "pds 6e0", 0, 0x1000, SRC_CONST, PTE_SHARED }, + [B_PDS_6E8] = { "pds 6e8", 0, 0x1000, SRC_CONST, PTE_SHARED }, + [B_PDS_6F0] = { "pds 6f0", 0, 0x1000, SRC_CONST, PTE_SHARED }, + [B_PDS_6F8] = { "pds 6f8", 0, 0x1000, SRC_CONST, PTE_SHARED }, + [B_CODE2] = { "code 700", 0, 0x1000, SRC_DATA, PTE_RO }, + [B_PDS_704] = { "pds 704", 0, 0x1000, SRC_CONST, PTE_SHARED }, + /* the A5's only, from here to 7a0 */ [B_TAB_784] = { "tab 784", 0xf0, 0x1000, SRC_DATA, PTE_RO, UK_TAB_BASE + 0x28 }, [B_TAB_78C] = { "tab 78c", 0x140, 0x1000, SRC_DATA, PTE_RO, UK_TAB_BASE + 0x118 }, /* 0x80bfa080, the setup */ @@ -315,6 +413,40 @@ static const struct sgx_buf_desc { [B_BLT_PARAM] = { "blt param", 0x8000, SZ_1M, SRC_ZERO, PTE_CC }, }; +/* A buffer as this kext build has it; size 0: it has none. */ +static struct sgx_buf_desc sgx_buf_desc(struct apple_sgx *sgx, enum sgx_buf_id id) +{ + const struct sgx_variant *v = sgx->var; + struct sgx_buf_desc d = sgx_buf_descs[id]; + + switch (id) { + case B_CODE: + d.size = UK_START + v->code_size; + break; + case B_CODE2: + d.size = v->code2_size; + d.off = v->code2_off; + break; + case B_PDS_6D8 ... B_PDS_6F8: + d.size = v->tmpl[T_6D8 + id - B_PDS_6D8].size; + d.off = v->tmpl[T_6D8 + id - B_PDS_6D8].off; + break; + case B_PDS_704: + d.size = v->tmpl[T_704].size; + d.off = v->tmpl[T_704].off; + break; + case B_TAB_784 ... B_TAB_78C: + case B_TAB_774 ... B_IDX_77C: + case B_794 ... B_7A0: + if (!v->tables) + d.size = 0; + break; + default: + break; + } + return d; +} + /* A clock-gating mode, as iOS writes it into every 2-bit field: 1 keeps the * clock on, 2 lets the hardware gate it. iOS uses 2 when auto clock gating * is enabled; bring-up wants 1. */ @@ -495,10 +627,12 @@ void apple_sgx_mmu_unmap(struct apple_sgx *sgx, u32 va, size_t size) static int sgx_buf_alloc(struct apple_sgx *sgx, enum sgx_buf_id id) { - const struct sgx_buf_desc *d = &sgx_buf_descs[id]; + const struct sgx_buf_desc desc = sgx_buf_desc(sgx, id), *d = &desc; struct sgx_buf *b = &sgx->buf[id]; int ret; + if (!d->size) + return 0; /* not in this kext build */ b->size = ALIGN(d->size, SGX_PAGE_SIZE); b->cpu = dmam_alloc_coherent(sgx->dev, b->size, &b->dma, GFP_KERNEL); if (!b->cpu) @@ -557,51 +691,61 @@ static u32 uk_at(struct apple_sgx *sgx, u32 off) static void sgx_uk_fill(struct apple_sgx *sgx, const u8 *data, const u8 *cnst) { + const struct sgx_variant *v = sgx->var; struct sgx_buf *b = sgx->buf; u32 *code = b[B_CODE].cpu, *uk = code + UK_START / 4; u32 *pds, *t, i; - static const struct { u32 off; u32 imm; } consts[] = { - { 0x0000, 0x01001000 }, { 0x0058, 0x00800900 }, { 0x00f0, 7 }, - { 0x7f98, 0x02800900 }, { 0x86c8, 0x02800900 }, + const struct { u32 off; u32 imm; } consts[] = { + { 0x0000, 0x01001000 }, { 0x0058, 0x00800900 }, + { v->limm_n, v->limm_n_val }, + { v->limm_pair[0], 0x02800900 }, { v->limm_pair[1], 0x02800900 }, }; /* Contents, as the loader and setup leave them. */ for (i = 0; i < B_NUM; i++) { - const struct sgx_buf_desc *d = &sgx_buf_descs[i]; + const struct sgx_buf_desc d = sgx_buf_desc(sgx, i); + if (!b[i].cpu) + continue; memset(b[i].cpu, 0, b[i].size); - if (d->src == SRC_DATA) - memcpy(b[i].cpu, data + d->off, d->size); - else if (d->src == SRC_CONST) - memcpy(b[i].cpu, cnst + d->off, d->size); + if (d.src == SRC_DATA) + memcpy(b[i].cpu, data + d.off, d.size); + else if (d.src == SRC_CONST) + memcpy(b[i].cpu, cnst + d.off, d.size); } - memcpy(code, data + UK_BOOT_OFF, UK_BOOT_SIZE); - memcpy(uk, data + UK_CODE_OFF, UK_CODE_SIZE); - for (i = 0; i < 24; i++) - b[B_IDX_77C].cpu[i] = i; + memcpy(code, data + v->boot_off, v->boot_size); + memcpy(uk, data + v->code_off, v->code_size); + if (v->tables) + for (i = 0; i < 24; i++) + b[B_IDX_77C].cpu[i] = i; /* The microkernel's LIMMs that carry addresses and constants - * (0x80bfa4e0-0x80bfa72c, 0x80bfac20-0x80bfad1c, 0x80bfae48-). */ + * (0x80bfa4e0-0x80bfa72c, 0x80bfac20-0x80bfad1c, 0x80bfae48-; the A6: + * 0x80ad6934-0x80ad6b70, 0x80ad6ffa-0x80ad711e). */ for (i = 0; i < ARRAY_SIZE(consts); i++) uk_set_limm(uk + consts[i].off / 4, consts[i].imm); uk_set_limm(uk + 0x010 / 4, b[B_PDS_6E0].va >> 4); uk_set_limm(uk + 0x018 / 4, b[B_740].va); uk_set_limm(uk + 0x060 / 4, b[B_PDS_6E8].va >> 4); - uk_set_limm(uk + 0x0e0 / 4, b[B_PDS_6F0].va & ~0xfu); - uk_set_limm(uk + 0x2b0 / 4, b[B_7A0].va); - uk_set_limm(uk + 0x340 / 4, b[B_79C].va); - uk_set_limm(uk + 0x390 / 4, b[B_794].va); - uk_set_limm(uk + 0x3b0 / 4, b[B_798].va); - uk_set_limm(uk + 0x588 / 4, b[B_TAB_774].va); - uk_set_limm(uk + 0x7fb0 / 4, b[B_PDS_6F8].va >> 4); - uk_set_limm(uk + 0x86e0 / 4, b[B_PDS_6F8].va >> 4); + uk_set_limm(uk + v->limm_6f0 / 4, b[B_PDS_6F0].va & ~0xfu); + if (v->tables) { + uk_set_limm(uk + 0x2b0 / 4, b[B_7A0].va); + uk_set_limm(uk + 0x340 / 4, b[B_79C].va); + uk_set_limm(uk + 0x390 / 4, b[B_794].va); + uk_set_limm(uk + 0x3b0 / 4, b[B_798].va); + uk_set_limm(uk + 0x588 / 4, b[B_TAB_774].va); + } + for (i = 0; i < ARRAY_SIZE(v->limm_pair); i++) + uk_set_limm(uk + (v->limm_pair[i] + 0x18) / 4, b[B_PDS_6F8].va >> 4); /* The boot program: where core 0 continues in the microkernel, and * where the others go into the second code buffer. */ - code[0x70 / 4] |= ((UK_START + 0x9d40) >> 3) & 0xfffff; - code[0x240 / 4] |= ((b[B_CODE2].va + 0x70 - b[B_CODE].va) >> 3) & 0xfffff; + code[v->boot_core0 / 4] |= ((UK_START + v->boot_core0_to) >> 3) & 0xfffff; + code[v->entry_others / 4] |= + ((b[B_CODE2].va + 0x70 - b[B_CODE].va) >> 3) & 0xfffff; - /* The PDS programs, pointed at microkernel entry points (0x80bfaa6a-). */ + /* The PDS programs, pointed at microkernel entry points (0x80bfaa6a-; + * the A6: 0x80ad6e92-0x80ad7172). */ pds = b[B_PDS_6D8].cpu; pds[0] = uk_use(sgx, uk_at(sgx, 0)); pds[1] = 1; @@ -613,34 +757,34 @@ static void sgx_uk_fill(struct apple_sgx *sgx, const u8 *data, const u8 *cnst) pds[4] = uk_use(sgx, uk_at(sgx, 0x90)); pds[5] = 1; pds = b[B_PDS_6E8].cpu; - pds[0] = uk_use(sgx, uk_at(sgx, 0xc0)); + pds[0] = uk_use(sgx, uk_at(sgx, v->pds_6e8)); pds[1] = 1; pds[2] = 0; pds = b[B_PDS_6F0].cpu; pds[0] = 0; pds[1] = 0x100; - pds[2] = uk_use(sgx, uk_at(sgx, 0x10d20)); - pds[3] = uk_use(sgx, uk_at(sgx, 0xd0d0)); + pds[2] = uk_use(sgx, uk_at(sgx, v->pds_6f0[0])); + pds[3] = uk_use(sgx, uk_at(sgx, v->pds_6f0[1])); pds[4] = 0x200; - pds[6] = uk_use(sgx, uk_at(sgx, 0x4340)); - pds[7] = uk_use(sgx, uk_at(sgx, 0xac50)); + pds[6] = uk_use(sgx, uk_at(sgx, v->pds_6f0[2])); + pds[7] = uk_use(sgx, uk_at(sgx, v->pds_6f0[3])); pds[8] = 1; pds[9] = 0; - pds[10] = uk_use(sgx, uk_at(sgx, 0x1470)); + pds[10] = uk_use(sgx, uk_at(sgx, v->pds_6f0[4])); pds = b[B_PDS_6F8].cpu; pds[0] = 0; pds[1] = 0x200; pds[2] = 0; pds[3] = 0x8000f; - pds[4] = uk_use(sgx, uk_at(sgx, 0xd3f0)); + pds[4] = uk_use(sgx, uk_at(sgx, v->pds_6f8[0])); pds[5] = 1; pds[6] = 0x240100; pds[7] = 0x420000; - pds[8] = uk_use(sgx, uk_at(sgx, 0x4510)); + pds[8] = uk_use(sgx, uk_at(sgx, v->pds_6f8[1])); pds[9] = 1; - pds[12] = uk_use(sgx, uk_at(sgx, 0x11190)); + pds[12] = uk_use(sgx, uk_at(sgx, v->pds_6f8[2])); pds[13] = 1; - pds[16] = uk_use(sgx, uk_at(sgx, 0xad20)); + pds[16] = uk_use(sgx, uk_at(sgx, v->pds_6f8[3])); pds[17] = 1; pds = b[B_PDS_704].cpu; pds[0] = 0; @@ -652,15 +796,17 @@ static void sgx_uk_fill(struct apple_sgx *sgx, const u8 *data, const u8 *cnst) pds[9] = 1; /* The blob's tables, linked up (0x80bfadde-0x80bfae20). */ - t = b[B_TAB_774].cpu; - t[0] |= b[B_TAB_784].va >> 4; - t[5] |= (b[B_TAB_784].va + 0x50) >> 4; - t[7] |= (b[B_TAB_784].va + 0xa0) >> 4; - t[3] |= b[B_IDX_77C].va; - t = b[B_TAB_784].cpu; - t[0x20 / 4] = 0x1000001; - t[0x70 / 4] = 0x1000101; - t[0xc0 / 4] = 0x1000231; + if (v->tables) { + t = b[B_TAB_774].cpu; + t[0] |= b[B_TAB_784].va >> 4; + t[5] |= (b[B_TAB_784].va + 0x50) >> 4; + t[7] |= (b[B_TAB_784].va + 0xa0) >> 4; + t[3] |= b[B_IDX_77C].va; + t = b[B_TAB_784].cpu; + t[0x20 / 4] = 0x1000001; + t[0x70 / 4] = 0x1000101; + t[0xc0 / 4] = 0x1000231; + } /* The block the microkernel finds through the LIMM at +0x18: the other * buffers and the page directory (0x80bfa898-). The timing and duty @@ -748,9 +894,10 @@ static void sgx_uk_regs(struct apple_sgx *sgx) sgx_write(sgx, SGX_BCAST + SGX_BIF_TILE1, 0xbeffe00); /* 0xe0000000-0xefffffff */ sgx_write(sgx, SGX_BCAST + SGX_BIF_TILE2, 0xcffff00); /* 0xf0000000-0xffffffff */ sgx_write(sgx, SGX_BCAST + SGX_BIF_CTRL_INVAL, 8); - sgx_write(sgx, SGX_MASTER_BIF_MMU_CTRL, 2); + /* 2 on the A5; the A6 adds bit 0 (the DDK's PREFETCHING_ON) */ + sgx_write(sgx, SGX_MASTER_BIF_MMU_CTRL, sgx->var->bif_mmu_ctrl); for (n = 0; n < sgx->ncores; n++) - sgx_write(sgx, SGX_CORE(n) + SGX_BIF_MMU_CTRL, 2); + sgx_write(sgx, SGX_CORE(n) + SGX_BIF_MMU_CTRL, sgx->var->bif_mmu_ctrl); sgx_write(sgx, SGX_MASTER_BIF_CTRL, 0); udelay(10); @@ -774,7 +921,7 @@ static void sgx_uk_regs(struct apple_sgx *sgx) sgx_write(sgx, SGX_MASTER_REG_414C, 0); for (n = 0; n < sgx->ncores; n++) { sgx_write(sgx, SGX_CORE(n) + SGX_BOOT_ENTRY, - (n ? UK_ENTRY_OTHERS : UK_ENTRY_CORE0) >> 3); + (n ? sgx->var->entry_others : UK_ENTRY_CORE0) >> 3); sgx_write(sgx, SGX_CORE(n) + SGX_BOOT_ENTRY + 0x14, 0); } @@ -795,7 +942,9 @@ static void sgx_uk_regs(struct apple_sgx *sgx) sgx_write(sgx, SGX_CORE(0) + SGX_EVENT_PDS_EXEC, b[B_PDS_6D8].va & ~0xfu); sgx_write(sgx, SGX_CORE(0) + SGX_EVENT_PDS_DATA, 1); sgx_write(sgx, SGX_CORE(0) + SGX_EVENT_PDS_INFO, 0x12001); - sgx_write(sgx, SGX_BCAST + SGX_USE_CODE_BASE(1), b[B_TAB_78C].va >> 6); + /* the A6's initSGX leaves this one alone: it has no 78c table */ + if (sgx->var->tables) + sgx_write(sgx, SGX_BCAST + SGX_USE_CODE_BASE(1), b[B_TAB_78C].va >> 6); sgx_write(sgx, SGX_BCAST + SGX_EVENT_KICKER, b[B_KICKER].va); sgx_write(sgx, SGX_BCAST + 0x630, 2); sgx_write(sgx, SGX_CORE(0) + 0xa58, 0x2200c000); @@ -804,27 +953,29 @@ static void sgx_uk_regs(struct apple_sgx *sgx) static int sgx_boot_ukernel(struct apple_sgx *sgx) { + const struct sgx_variant *v = sgx->var; const struct firmware *fw; const struct sgx_fw_header *h; u32 *host, val; unsigned int n; int ret; - ret = request_firmware(&fw, SGX_FW_NAME, sgx->dev); + ret = request_firmware(&fw, v->fw_name, sgx->dev); if (ret) { - dev_err(sgx->dev, "no %s (./cascadia a5 firmware): %d\n", - SGX_FW_NAME, ret); + dev_err(sgx->dev, "no %s (from the IPSW's kernelcache): %d\n", + v->fw_name, ret); return ret; } + /* Both kexts are 12H321's; the sizes tell them apart. */ h = (const void *)fw->data; if (fw->size < sizeof(*h) || memcmp(h->magic, "SGX543FW", 8) || le32_to_cpu(h->version) != 1 || - le32_to_cpu(h->data_size) != SGX_FW_DATA_SIZE || - le32_to_cpu(h->const_size) != SGX_FW_CONST_SIZE || - le32_to_cpu(h->data_off) + SGX_FW_DATA_SIZE > fw->size || - le32_to_cpu(h->const_off) + SGX_FW_CONST_SIZE > fw->size || + le32_to_cpu(h->data_size) != v->data_size || + le32_to_cpu(h->const_size) != v->const_size || + le32_to_cpu(h->data_off) + v->data_size > fw->size || + le32_to_cpu(h->const_off) + v->const_size > fw->size || strncmp(h->build, "12H321", sizeof(h->build))) { - dev_err(sgx->dev, "%s is not the 12H321 microkernel\n", SGX_FW_NAME); + dev_err(sgx->dev, "%s is not %s's microkernel\n", v->fw_name, v->kext); ret = -EINVAL; goto out; } @@ -1016,7 +1167,7 @@ static int sgx_send_cmd(struct apple_sgx *sgx, enum sgx_cmd_type type, cmd = (struct sgx_ccb_cmd *)sgx->buf[B_750].cpu + wo; memset(cmd, 0, sizeof(*cmd)); - cmd->service = (UK_START + uk_handlers[type].off) >> 3; + cmd->service = (UK_START + sgx->var->handlers[type]) >> 3; cmd->cache_control = cache_control; cmd->data[0] = data0; cmd->data[1] = data1; @@ -1037,7 +1188,7 @@ static int sgx_send_cmd(struct apple_sgx *sgx, enum sgx_cmd_type type, dev_info(sgx->dev, "command %s (cc 0x%x, data 0x%x 0x%x): %s after %lld us, CCB write %u read %u, " "core0 EVENT_STATUS 0x%08x\n", - uk_handlers[type].name, cache_control, data0, data1, + uk_handler_names[type], cache_control, data0, data1, ret ? "NOT TAKEN" : "taken", ktime_us_delta(ktime_get(), start), wo, READ_ONCE(ctl[1]), sgx_read(sgx, SGX_CORE(0) + SGX_EVENT_STATUS)); @@ -2378,6 +2529,7 @@ static int apple_sgx_probe(struct platform_device *pdev) spin_lock_init(&sgx->ccb_lock); spin_lock_init(&sgx->blt_lock); INIT_WORK(&sgx->boot_work, sgx_boot_work); + sgx->var = device_get_match_data(dev); sgx->brn_31195 = of_property_read_bool(dev->of_node, "apple,brn-31195"); ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32)); @@ -2475,7 +2627,8 @@ static void apple_sgx_remove(struct platform_device *pdev) } static const struct of_device_id apple_sgx_of_match[] = { - { .compatible = "apple,s5l8940x-sgx" }, + { .compatible = "apple,s5l8940x-sgx", .data = &sgx_a5 }, + { .compatible = "apple,s5l8950x-sgx", .data = &sgx_a6 }, { } }; MODULE_DEVICE_TABLE(of, apple_sgx_of_match); @@ -2493,5 +2646,6 @@ static struct platform_driver apple_sgx_driver = { module_platform_driver(apple_sgx_driver); MODULE_DESCRIPTION("Apple S5L8940X PowerVR SGX543MP2: microkernel, queues, render node"); -MODULE_FIRMWARE(SGX_FW_NAME); +MODULE_FIRMWARE("apple/sgx543.fw"); +MODULE_FIRMWARE("apple/sgx543-s5l8950x.fw"); MODULE_LICENSE("GPL"); From f38d44eea477fd0f2aed9e110ae370cd629d0475 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:06:30 +0100 Subject: [PATCH 32/43] ARM: dts: apple: Add the SGX543MP3 and its power states MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 13 +++++++ arch/arm/boot/dts/apple/s5l8950x.dtsi | 45 +++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index 28184df4e501bc..b5caf372c31f23 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -459,3 +459,16 @@ }; }; }; + +/* The GPU: drivers/gpu/drm/apple-sgx, its microkernel out of the IPSW. */ +&gfx_sys_ps { + status = "okay"; +}; + +&gfx_ps { + status = "okay"; +}; + +&sgx { + status = "okay"; +}; diff --git a/arch/arm/boot/dts/apple/s5l8950x.dtsi b/arch/arm/boot/dts/apple/s5l8950x.dtsi index 787514c5af4737..3300e39cb8bdbc 100644 --- a/arch/arm/boot/dts/apple/s5l8950x.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x.dtsi @@ -351,6 +351,51 @@ status = "disabled"; }; + /* + * The GPU's two power states, GFX_SYS then GFX: ADT pmgr + * device-clocks entry 0x2f, "GFX" (id 0x40, the sgx node's + * clock-gates <0x40 0x41>), lists ps indices 0x09 and 0x0a, + * the same two registers as on the S5L8940X/8942X. The + * other gate, "GFX-FAST" (0x41), has no power state. + * apple-sgx enables them in this order. + */ + gfx_sys_ps: gfx-sys-ps@f101024 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf101024 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "gfx_sys_ps"; + status = "disabled"; + }; + + gfx_ps: gfx-ps@f101028 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf101028 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "gfx_ps"; + status = "disabled"; + }; + + /* + * PowerVR SGX543MP3 (ADT /arm-io/sgx, "gpu,s5l8950x", IRQ 0x31; + * the ADT's second window, 0x3f10b000, is left out as on the + * A5). The A5's register layout: 16 KiB banks, 0 broadcast and + * write-only (a read hangs the bus), 1 the master, 2 + n core + * n. iOS's driver is another build (SGXDriver543RC2), so the + * microkernel is its own: apple/sgx543-s5l8950x.fw. No + * brn_31195 in this ADT node, and the A6's initSGX sets no + * erratum bypass bits. + */ + sgx: gpu@5100000 { + compatible = "apple,s5l8950x-sgx"; + reg = <0x5100000 0x18000>; + interrupts = <49>; + clocks = <&gfx_sys_ps>, <&gfx_ps>; + clock-names = "gfx_sys", "gfx"; + status = "disabled"; + }; + /* * GPIO / pinctrl block (ADT /arm-io/gpio, "gpio,s5l8950x", * "gpio,s5l8930x"): 29 ports = 232 pins, IRQ 119. From 9fc04ebee3fd59d764bb89c1d21d53f009a4c498 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:06:30 +0100 Subject: [PATCH 33/43] drm: apple-sgx: The A6's clock and render details layout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The A6's GPU runs at about 330 MHz, not the A5's 256.5 MHz. The microkernel's timer ticks once every HOST_UK_TIMER_CLOCK core clocks; it was told 256500 and ticked 6461 times in 5.02 s. That is 1287 ticks a second, times 256500 clocks, so 330.1 MHz. The A5's figure came the same way: 2500 ticks a second when told 102600, i.e. 256.5 MHz. Make the clock part of struct sgx_variant. The timer and APPLE_SGX_PARAM_CLOCK_KHZ take it from there. The A6's render details header is 8 bytes shorter: - entry 0 is at +0x18, not +0x20, and entry 1 is 0x84 bytes later (+0x9c); - the A6 microkernel reads the header at 0x14/0x18 where the A5's reads 0x1c/0x20; - the A6 kext's 3D block builder (0x80ad2798) puts details + 0x18 into the TA command; - its render-target init leaves entry 1's constants at +0x9c. Make the entry offset part of struct sgx_variant. The render queue writes the context into both entries there, and the poller reads entry 0's word 1. A submit's details must be large enough for that layout. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/gpu/drm/apple-sgx/apple_sgx.h | 18 ++++++++++----- drivers/gpu/drm/apple-sgx/apple_sgx_drm.c | 11 ++++----- drivers/gpu/drm/apple-sgx/apple_sgx_hw.c | 28 +++++++++++++++++++---- 3 files changed, 41 insertions(+), 16 deletions(-) diff --git a/drivers/gpu/drm/apple-sgx/apple_sgx.h b/drivers/gpu/drm/apple-sgx/apple_sgx.h index c897ebadc28b66..5802f62f54ca95 100644 --- a/drivers/gpu/drm/apple-sgx/apple_sgx.h +++ b/drivers/gpu/drm/apple-sgx/apple_sgx.h @@ -104,12 +104,13 @@ struct sgx_variant; #define SGX_TA_HEAP_END 0x97800000u #define SGX_TILED_VA_START 0xe0000000u -/* The GPU's core clock in kHz: PLL@0x18 (513 MHz) / 2, as measured -- the - * microkernel's timer ticked 2500 times a second when told 102600 kHz, and - * the USSEs run 2.0 G instructions a second, 8 a clock. (GFX-CLK, 513 / 5, - * is not the core's clock: docs/research/p105-gpu.md, "The GPU's clock, - * measured".) */ -#define SGX_CLOCK_KHZ 256500 +/* The GPU's core clock in kHz is the variant's (sgx->clock_khz): the + * microkernel's timer ticks once every HOST_UK_TIMER_CLOCK core clocks, so + * clock = ticks a second x the value it was given. The A5's: PLL@0x18 + * (513 MHz) / 2, as measured -- it ticked 2500 times a second when told + * 102600, and the USSEs run 2.0 G instructions a second, 8 a clock. + * (GFX-CLK, 513 / 5, is not the core's clock: docs/research/p105-gpu.md, + * "The GPU's clock, measured".) */ /* The DDK's SGXMKIF_CC_* (sgx_mkif_km.h): what a kernel CCB command asks * the microkernel to invalidate before it runs. */ @@ -157,6 +158,11 @@ struct apple_sgx { struct clk_bulk_data *clks; int num_clks; const struct sgx_variant *var; /* the kext build its microkernel is from */ + u32 clock_khz; /* the core's clock */ + /* the render details (the render target's, which the TA command names + * at +0x54): the hardware render context goes into both entries, and + * the microkernel sets entry 0's word 1 while a render runs */ + u32 det_ctx0, det_ctx1, det_busy, det_size; unsigned int ncores; u32 core_id, core_rev; bool brn_31195; diff --git a/drivers/gpu/drm/apple-sgx/apple_sgx_drm.c b/drivers/gpu/drm/apple-sgx/apple_sgx_drm.c index d2d6eafd8e1f07..f07ec8eb0e1a14 100644 --- a/drivers/gpu/drm/apple-sgx/apple_sgx_drm.c +++ b/drivers/gpu/drm/apple-sgx/apple_sgx_drm.c @@ -111,8 +111,6 @@ MODULE_PARM_DESC(inflight, "renders on the GPU at once, 2 (default) or 1"); #define SGX_MAX_REKICKS 5 -/* The render details are read up to here (+0xa4 is written). */ -#define SGX_DETAILS_SIZE 0xa8 #define SGX_MAX_BOS 4096 #define SGX_MAX_IN_SYNCS 256 #define SGX_MAX_BO_SIZE SZ_256M @@ -547,7 +545,7 @@ static int sgx_ioctl_get_param(struct drm_device *drm, void *data, struct drm_fi args->value = sgx->ncores; break; case APPLE_SGX_PARAM_CLOCK_KHZ: - args->value = SGX_CLOCK_KHZ; + args->value = sgx->clock_khz; break; case APPLE_SGX_PARAM_UKERNEL_UP: args->value = apple_sgx_up(sgx); @@ -752,7 +750,7 @@ static enum hrtimer_restart sgx_poll(struct hrtimer *timer) job = sdrm->active[0]; if (!job->ta_done && (s32)(READ_ONCE(*done) - job->seq) >= 0) job->ta_done = true; - if (job->ta_done && !READ_ONCE(job->details[0x24 / 4])) { + if (job->ta_done && !READ_ONCE(job->details[sdrm->sgx->det_busy / 4])) { fences[nfences++] = job->hw_fence; job->hw_fence = NULL; for (i = 1; i < sdrm->nactive; i++) @@ -1139,8 +1137,9 @@ static int sgx_ioctl_submit(struct drm_device *drm, void *data, struct drm_file job->details_obj = det; for (i = 0; i < job->bo_count; i++) listed |= job->bos[i] == det; - if (!listed || det->size < SGX_DETAILS_SIZE || - args->details_offset > det->size - SGX_DETAILS_SIZE) { + /* the render details are read up to the end of entry 1's first word */ + if (!listed || det->size < sdrm->sgx->det_size || + args->details_offset > det->size - sdrm->sgx->det_size) { ret = -EINVAL; goto out_job; } diff --git a/drivers/gpu/drm/apple-sgx/apple_sgx_hw.c b/drivers/gpu/drm/apple-sgx/apple_sgx_hw.c index 68e2b89fffcf64..5704f96c7d6160 100644 --- a/drivers/gpu/drm/apple-sgx/apple_sgx_hw.c +++ b/drivers/gpu/drm/apple-sgx/apple_sgx_hw.c @@ -277,6 +277,9 @@ struct sgx_variant { * address >> 4 */ u32 bif_mmu_ctrl; /* (MASTER_)BIF_MMU_CTRL */ bool tables; /* the A5's tables and buffers 794-7a0 */ + u32 clock_khz; /* the core's, measured (apple_sgx.h) */ + u32 details_entry; /* the render details' entry 0; entry 1 is + * 0x84 bytes on */ }; /* SGXDriver543: loader 0x80bf9754, setup 0x80bfa080, fill 0x80bfa884. */ @@ -306,6 +309,8 @@ static const struct sgx_variant sgx_a5 = { .limm_pair = { 0x7f98, 0x86c8 }, .bif_mmu_ctrl = 2, .tables = true, + .clock_khz = 256500, + .details_entry = 0x20, /* 0x80bf74f4; the TA command's +0x58 */ }; /* SGXDriver543RC2: initSGX 0x80ad0048 (clock helpers 0x80acfdd4 and @@ -338,6 +343,15 @@ static const struct sgx_variant sgx_a6 = { .limm_pair = { 0x7998, 0x80c8 }, .bif_mmu_ctrl = 3, .tables = false, + /* Told 256500, the timer ticked 6461 times in 5.02 s (flight + * sgx2d0, 2026-11-29): 1287 a second x 256500 clocks = 330.1 MHz. */ + .clock_khz = 330000, + /* the details' header is 8 bytes shorter: the A6's microkernel reads + * it at 0x14 and 0x18 where the A5's reads 0x1c and 0x20 (A5 uk + * 0x32d8, A6 0x2d18), the 3D block builder (0x80ad2798) puts + * details + 0x18 in the TA command, and the RT init leaves entry 1's + * constants at +0x9c + 8 */ + .details_entry = 0x18, }; /* POWER's Data[1], and what the microkernel sets in the power status when @@ -860,7 +874,7 @@ static void sgx_uk_fill(struct apple_sgx *sgx, const u8 *data, const u8 *cnst) * management stay off (sample rate 0, enable byte 0). */ t = b[B_HOST].cpu; t[HOST_HWR_SAMPLE_RATE] = 0x10; - t[HOST_UK_TIMER_CLOCK] = SGX_CLOCK_KHZ; + t[HOST_UK_TIMER_CLOCK] = sgx->clock_khz; t[0x98 / 4] = 0x44af2000; /* this+0x848, 1401.0 */ t[0x9c / 4] = 0x44af2000; @@ -1549,8 +1563,8 @@ int apple_sgx_render_queue(struct apple_sgx *sgx, const u32 *src, u32 len, u32 p cmd[0x64 / 4] |= 1; cmd[0x68 / 4] = done_va; cmd[0x6c / 4] = seq; - details[0x20 / 4] = cva; - details[0xa4 / 4] = cva; + details[sgx->det_ctx0 / 4] = cva; + details[sgx->det_ctx1 / 4] = cva; ctx[6] = pb; wmb(); WRITE_ONCE(ctl[0], (wo + size) & (SGX_TQ_CCB_SIZE - 1)); @@ -1569,7 +1583,8 @@ int apple_sgx_render_queue(struct apple_sgx *sgx, const u32 *src, u32 len, u32 p * it (the render details' +0x24, set when the TA starts, is 0). */ bool apple_sgx_render_waiting(struct apple_sgx *sgx, u32 at, const u32 *details) { - return READ_ONCE(sgx->buf[B_R_CTL].cpu[1]) == at && !READ_ONCE(details[0x24 / 4]); + return READ_ONCE(sgx->buf[B_R_CTL].cpu[1]) == at && + !READ_ONCE(details[sgx->det_busy / 4]); } /* TA again for the render queue. Now and then the microkernel takes the @@ -2530,6 +2545,11 @@ static int apple_sgx_probe(struct platform_device *pdev) spin_lock_init(&sgx->blt_lock); INIT_WORK(&sgx->boot_work, sgx_boot_work); sgx->var = device_get_match_data(dev); + sgx->clock_khz = sgx->var->clock_khz; + sgx->det_ctx0 = sgx->var->details_entry; + sgx->det_busy = sgx->det_ctx0 + 4; + sgx->det_ctx1 = sgx->det_ctx0 + 0x84; + sgx->det_size = sgx->det_ctx1 + 4; sgx->brn_31195 = of_property_read_bool(dev->of_node, "apple,brn-31195"); ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32)); From 23fa2bbcb68d2b4d7d2a2cc9346adebadcbed3ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:06:31 +0100 Subject: [PATCH 34/43] drm: apple-sgx: Flip and count vblanks at the A6 display pipe's VBI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Direct scanout on the N42 ran at 47.9 fps: each flip waited out a whole frame, most likely because the A5's line counter (0x39200054 >> 9) does not go round there. iOS's AppleH5PDisplayPipe (12H321) takes the pipe's VBI instead: general control at clcd reg 0 + 0x1000, interrupt enable +0x28 and status +0x2c (write 1 to clear), bit 0 the VBI, on the clcd node's interrupt index 0 (43; AppleMobileCLCD has index 1). Where the device tree names that window and interrupt, a flip queues the new layer base, the VBI writes it in the vertical blank and completes the flip, and the VBI is the vblank. No VBI within a frame and a millisecond: the base is written at once and the line-counter wait runs. apple_sgx.vbi=0 turns the path off. The A5's DT has neither, so it keeps today's path. debugfs: screen adds the VBI count and period, flips at a VBI or timed out, the interrupt registers and position samples; gpu (new) gives the renders done and the time the GPU had one. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 10 +- drivers/gpu/drm/apple-sgx/apple_sgx_drm.c | 35 ++++ drivers/gpu/drm/apple-sgx/apple_sgx_kms.c | 235 +++++++++++++++++++++- 3 files changed, 274 insertions(+), 6 deletions(-) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index b5caf372c31f23..9f6cf26950e32f 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -438,7 +438,15 @@ */ clcd: display-controller@a104000 { compatible = "apple,s5l8950x-clcd", "apple,s5l8940x-clcd"; - reg = <0xa104000 0x1000>, <0x9200000 0x1000>; + /* + * UI-0 (layer 0), the position, and the display pipe's general + * control (ADT clcd reg 0 is 0xa100000: AppleH4DisplayPipe's + * general control at +0x1000, UI-0 at +0x4000). Interrupt: + * the pipe's (its VBI), ADT clcd interrupts[0]; [1] (42) is + * AppleMobileCLCD's. + */ + reg = <0xa104000 0x1000>, <0x9200000 0x1000>, <0xa101000 0x1000>; + interrupts = <43>; status = "disabled"; }; diff --git a/drivers/gpu/drm/apple-sgx/apple_sgx_drm.c b/drivers/gpu/drm/apple-sgx/apple_sgx_drm.c index f07ec8eb0e1a14..def0613236e3db 100644 --- a/drivers/gpu/drm/apple-sgx/apple_sgx_drm.c +++ b/drivers/gpu/drm/apple-sgx/apple_sgx_drm.c @@ -56,6 +56,7 @@ * nothing. */ +#include #include #include #include @@ -63,6 +64,7 @@ #include #include #include +#include #include #include @@ -158,6 +160,11 @@ struct apple_sgx_drm { unsigned int kpb_boots; atomic_t submitted, done, timed_out; + + /* (debugfs gpu) the time some render was on the GPU, from its queueing + * to the poll that saw the last one done (job_lock) */ + ktime_t busy_since; + u64 busy_ns; }; struct apple_sgx_bo { @@ -759,6 +766,9 @@ static enum hrtimer_restart sgx_poll(struct hrtimer *timer) /* (the next one the oldest now: left unread from here) */ if (sdrm->nactive) sdrm->active[0]->kicked = ktime_get(); + else + sdrm->busy_ns += ktime_to_ns(ktime_sub(ktime_get(), + sdrm->busy_since)); continue; } if (!job->ta_done && rekick_ms && job->rekicks < SGX_MAX_REKICKS && @@ -906,6 +916,8 @@ static struct dma_fence *sgx_job_run(struct drm_sched_job *sched_job) job->kicked = ktime_get(); job->hw_fence = dma_fence_get(fence); first = !sdrm->nactive; + if (first) + sdrm->busy_since = job->kicked; if (!WARN_ON(sdrm->nactive >= SGX_MAX_INFLIGHT)) sdrm->active[sdrm->nactive++] = job; spin_unlock_irqrestore(&sdrm->job_lock, flags); @@ -948,6 +960,8 @@ static enum drm_gpu_sched_stat sgx_job_timedout(struct drm_sched_job *sched_job) sdrm->active[i]->hw_fence = NULL; sdrm->active[i] = NULL; } + if (sdrm->nactive) + sdrm->busy_ns += ktime_to_ns(ktime_sub(ktime_get(), sdrm->busy_since)); sdrm->nactive = 0; spin_unlock_irqrestore(&sdrm->job_lock, flags); @@ -1255,6 +1269,25 @@ void apple_sgx_drm_irq(struct apple_sgx *sgx) hrtimer_start(&sdrm->poll, 0, HRTIMER_MODE_REL_SOFT); } +/* debugfs apple-sgx/gpu: renders done and the time the GPU had one, so far + * (two reads around a run: GPU ms a frame, and busy %) */ +static int sgx_drm_gpu_show(struct seq_file *m, void *unused) +{ + struct apple_sgx_drm *sdrm = m->private; + unsigned long flags; + u64 ns; + + spin_lock_irqsave(&sdrm->job_lock, flags); + ns = sdrm->busy_ns; + if (sdrm->nactive) + ns += ktime_to_ns(ktime_sub(ktime_get(), sdrm->busy_since)); + spin_unlock_irqrestore(&sdrm->job_lock, flags); + seq_printf(m, "renders %u busy_us %llu now_us %lld\n", atomic_read(&sdrm->done), + div_u64(ns, NSEC_PER_USEC), ktime_to_us(ktime_get())); + return 0; +} +DEFINE_SHOW_ATTRIBUTE(sgx_drm_gpu); + bool apple_sgx_drm_busy(struct apple_sgx *sgx) { return sgx->drm && atomic_read(&sgx->drm->clients) > 0; @@ -1359,6 +1392,8 @@ int apple_sgx_drm_init(struct apple_sgx *sgx) drm_sched_fini(&sdrm->sched); return ret; } + if (sgx->debugfs) + debugfs_create_file("gpu", 0400, sgx->debugfs, sdrm, &sgx_drm_gpu_fops); drm_info(&sdrm->drm, "render node: buffers at GPU 0x%08x-0x%08x, code base 0x%08x\n", SGX_USER_VA_START, SGX_USER_VA_END, SGX_CODE_BASE); return 0; diff --git a/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c b/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c index 4ff58861d41975..b63a001749c486 100644 --- a/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c +++ b/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c @@ -30,6 +30,13 @@ * (damage without a flip), the overlay, a turned plane -- has the plane * copied onto the boot framebuffer whole and the layer pointed back at it. * + * Where the device tree also gives the display pipe's general control and + * its interrupt (the A6: the clcd node's third window and first + * interrupt), the vblank is the pipe's VBI, as iOS's AppleH4DisplayPipe + * takes it: a new layer base is written at the next VBI -- in the vertical + * blank -- and the flip is done there (its event, the buffer before let + * go). The line counter and the timer are for where there is no VBI. + * * Over the plane, the overlay (the render node's OVERLAY ioctl): a buffer * whose listed rectangles are blended over the plane in each copy that * reaches them, the same 2D job -- an on-screen control over whatever runs, @@ -39,12 +46,16 @@ #include #include #include +#include #include #include #include #include #include +#include #include +#include +#include #include #include @@ -84,6 +95,17 @@ #define SGX_CLCD_POS 0x54 #define SGX_CLCD_LINE_SHIFT 9 +/* (A6) the display pipe's general control (the clcd node's third window, + * 0x3a101000: AppleH4DisplayPipe's fRegisters + 0x1000), its interrupt + * enable and status (write 1 to clear), bit 0 the VBI -- iOS 8.4.1 N42 + * (12H321) AppleH5PDisplayPipe: enableVBI 0x80f50798, clearVBI 0x80f507f0, + * enable_interrupts 0x80f4d650, interruptFilter 0x80f4cb5c; the pipe's + * interrupt is its provider's (clcd's) index 0 (start_hardware 0x80f4be22), + * AppleMobileCLCD's index 1 */ +#define SGX_DP_INT_EN 0x28 +#define SGX_DP_INT_STAT 0x2c +#define SGX_DP_INT_VBI BIT(0) + /* (M49) off: every update copied onto the boot framebuffer, as before; * looked at in each update */ static bool direct_scanout = true; @@ -91,6 +113,12 @@ module_param(direct_scanout, bool, 0644); MODULE_PARM_DESC(direct_scanout, "show a flip to a contiguous buffer by moving the display's base, not copying it"); +/* (A6) off: the display pipe's VBI not used (the line counter and the + * timer, as on the A5); looked at in each flip and vblank enable */ +static bool vbi = true; +module_param(vbi, bool, 0644); +MODULE_PARM_DESC(vbi, "flips and vblanks at the display pipe's VBI interrupt, where there is one"); + struct apple_sgx_kms { struct apple_sgx *sgx; struct drm_simple_display_pipe pipe; @@ -108,6 +136,21 @@ struct apple_sgx_kms { /* updates shown by pointing the layer, by copies (debugfs screen) */ unsigned long n_pointed, n_copied; + /* (A6) the pipe's general control and VBI (0: none). Under vbi_lock: + * vbl_irq, the vblank is the VBI's (not the timer's); base_pending, + * base_pa to be written at the next VBI (flip_vbi: this commit's + * flip waits for that). For debugfs: VBIs, the time between the last + * two, flips done at a VBI and flips that waited a frame out. */ + void __iomem *dp; + int vbi_irq; + spinlock_t vbi_lock; + wait_queue_head_t vbi_wq; + bool vbl_irq, base_pending, flip_vbi; + dma_addr_t base_pa; + unsigned long n_vbi, n_at_vbi, n_timeout; + ktime_t vbi_last; + u32 vbi_period_us, vbi_min_us, vbi_max_us; + /* the overlay: its buffer, owner and rectangles (the plane's source * coordinates less its origin, out to 16 pixels); the lock keeps them * still through the copies of one commit */ @@ -241,13 +284,45 @@ static void sgx_kms_show(struct apple_sgx_kms *kms, const struct drm_plane_state drm_err_ratelimited(fb->dev, "the 2D engine's copy to the screen: %d\n", ret); } +/* The VBI on while anyone wants it: vblanks, or a base to write. A VBI + * left from before is cleared first, so that the next one is a vertical + * blank to come. Under vbi_lock. */ +static void sgx_kms_vbi_want(struct apple_sgx_kms *kms) +{ + bool want = kms->vbl_irq || kms->base_pending; + u32 en = readl(kms->dp + SGX_DP_INT_EN); + + if (!!(en & SGX_DP_INT_VBI) == want) + return; + if (want) + writel(SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_STAT); + writel(want ? en | SGX_DP_INT_VBI : en & ~SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_EN); +} + +static bool sgx_kms_use_vbi(struct apple_sgx_kms *kms) +{ + return kms->vbi_irq > 0 && READ_ONCE(vbi); +} + static void sgx_kms_point(struct apple_sgx_kms *kms, dma_addr_t pa) { + unsigned long flags; + if (pa == kms->shown) return; - writel(pa, kms->clcd + SGX_CLCD_L0_BASE); kms->shown = pa; kms->flipped = true; + kms->flip_vbi = sgx_kms_use_vbi(kms); + if (kms->flip_vbi) { + /* (written at the next VBI: sgx_kms_vbi) */ + spin_lock_irqsave(&kms->vbi_lock, flags); + kms->base_pa = pa; + kms->base_pending = true; + sgx_kms_vbi_want(kms); + spin_unlock_irqrestore(&kms->vbi_lock, flags); + return; + } + writel(pa, kms->clcd + SGX_CLCD_L0_BASE); } /* Whether the plane can be shown by pointing the layer at its buffer, and @@ -322,9 +397,29 @@ static void sgx_kms_wait_frame(struct apple_sgx_kms *kms) { u32 h = kms->sgx->fb_h, prev, line, us; u32 line_ns = div_u64(ktime_to_ns(kms->vblank_period), h); - ktime_t end = ktime_add(ktime_get(), ktime_add_us(kms->vblank_period, 200)); + ktime_t end; bool wrapped = false; + unsigned long flags; + + /* (A6) the base goes in at the next VBI; then the display no longer + * reads the buffer before. No VBI in a frame and a millisecond: the + * base written now, and a frame waited out as below. */ + if (kms->flip_vbi) { + if (wait_event_timeout(kms->vbi_wq, !READ_ONCE(kms->base_pending), + usecs_to_jiffies(ktime_to_us(kms->vblank_period) + 1000))) + return; + spin_lock_irqsave(&kms->vbi_lock, flags); + if (kms->base_pending) { + writel(kms->base_pa, kms->clcd + SGX_CLCD_L0_BASE); + kms->base_pending = false; + sgx_kms_vbi_want(kms); + } + kms->n_timeout++; + spin_unlock_irqrestore(&kms->vbi_lock, flags); + drm_err_ratelimited(kms->pipe.crtc.dev, "no display VBI in a frame: base written at once\n"); + } + end = ktime_add(ktime_get(), ktime_add_us(kms->vblank_period, 200)); prev = readl(kms->clcd_pos) >> SGX_CLCD_LINE_SHIFT; while (ktime_before(ktime_get(), end)) { line = readl(kms->clcd_pos) >> SGX_CLCD_LINE_SHIFT; @@ -368,10 +463,61 @@ static enum hrtimer_restart sgx_kms_vblank(struct hrtimer *timer) return HRTIMER_RESTART; } +/* (A6) The display pipe's VBI: the vertical blank. A base waiting goes + * in now (the display reads it from the frame to come; the buffer before + * is read no more), its flip done; the vblank counted. */ +static irqreturn_t sgx_kms_vbi(int irq, void *data) +{ + struct apple_sgx_kms *kms = data; + bool flipped = false, vbl; + ktime_t now; + s64 us; + + spin_lock(&kms->vbi_lock); + if (!(readl(kms->dp + SGX_DP_INT_STAT) & SGX_DP_INT_VBI)) { + spin_unlock(&kms->vbi_lock); + return IRQ_NONE; + } + writel(SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_STAT); + if (kms->base_pending) { + writel(kms->base_pa, kms->clcd + SGX_CLCD_L0_BASE); + kms->base_pending = false; + kms->n_at_vbi++; + flipped = true; + } + now = ktime_get(); + us = ktime_us_delta(now, kms->vbi_last); + /* (the time between two VBIs in a row: the refresh) */ + if (kms->n_vbi && us > 0 && us < 2 * ktime_to_us(kms->vblank_period)) { + kms->vbi_period_us = us; + kms->vbi_min_us = kms->vbi_min_us ? min_t(u32, kms->vbi_min_us, us) : us; + kms->vbi_max_us = max_t(u32, kms->vbi_max_us, us); + } + kms->vbi_last = now; + kms->n_vbi++; + vbl = kms->vbl_irq; + sgx_kms_vbi_want(kms); + spin_unlock(&kms->vbi_lock); + + if (flipped) + wake_up_all(&kms->vbi_wq); + if (vbl) + drm_crtc_handle_vblank(&kms->pipe.crtc); + return IRQ_HANDLED; +} + static int sgx_kms_enable_vblank(struct drm_simple_display_pipe *pipe) { struct apple_sgx_kms *kms = container_of(pipe, struct apple_sgx_kms, pipe); + unsigned long flags; + if (sgx_kms_use_vbi(kms)) { + spin_lock_irqsave(&kms->vbi_lock, flags); + kms->vbl_irq = true; + sgx_kms_vbi_want(kms); + spin_unlock_irqrestore(&kms->vbi_lock, flags); + return 0; + } hrtimer_start(&kms->vblank_timer, kms->vblank_period, HRTIMER_MODE_REL); return 0; } @@ -379,7 +525,14 @@ static int sgx_kms_enable_vblank(struct drm_simple_display_pipe *pipe) static void sgx_kms_disable_vblank(struct drm_simple_display_pipe *pipe) { struct apple_sgx_kms *kms = container_of(pipe, struct apple_sgx_kms, pipe); + unsigned long flags; + if (kms->vbi_irq > 0) { + spin_lock_irqsave(&kms->vbi_lock, flags); + kms->vbl_irq = false; + sgx_kms_vbi_want(kms); + spin_unlock_irqrestore(&kms->vbi_lock, flags); + } /* (under the vblank locks the timer's handler takes: not waited for) */ hrtimer_try_to_cancel(&kms->vblank_timer); } @@ -463,6 +616,24 @@ static const struct drm_mode_config_funcs sgx_kms_mode_config_funcs = { static void sgx_kms_overlay_drop(struct apple_sgx_kms *kms); +/* (A6) The VBI off and let go, before the vblanks are */ +static void sgx_kms_vbi_fini(struct drm_device *drm, void *data) +{ + struct apple_sgx_kms *kms = data; + unsigned long flags; + + spin_lock_irqsave(&kms->vbi_lock, flags); + kms->vbl_irq = false; + if (kms->base_pending) + writel(kms->base_pa, kms->clcd + SGX_CLCD_L0_BASE); + kms->base_pending = false; + writel(readl(kms->dp + SGX_DP_INT_EN) & ~SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_EN); + writel(SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_STAT); + spin_unlock_irqrestore(&kms->vbi_lock, flags); + free_irq(kms->vbi_irq, kms); + kms->vbi_irq = 0; +} + static void sgx_kms_fini(struct drm_device *drm, void *data) { struct apple_sgx_kms *kms = data; @@ -476,6 +647,8 @@ static void sgx_kms_fini(struct drm_device *drm, void *data) iounmap(kms->clcd); iounmap(kms->clcd_pos); } + if (kms->dp) + iounmap(kms->dp); } /* ---- the overlay ---------------------------------------------------------- */ @@ -625,6 +798,7 @@ void apple_sgx_kms_overlay_close(struct apple_sgx *sgx, struct drm_file *file) static int sgx_kms_screen_show(struct seq_file *m, void *unused) { struct apple_sgx_kms *kms = m->private; + int i; if (!kms->clcd) { seq_puts(m, "no display controller: updates copied\n"); @@ -633,6 +807,31 @@ static int sgx_kms_screen_show(struct seq_file *m, void *unused) seq_printf(m, "layer 0 base %pad (boot framebuffer %pad)\n", &kms->shown, &kms->boot_pa); seq_printf(m, "updates shown by pointing the layer %lu, by copies %lu\n", READ_ONCE(kms->n_pointed), READ_ONCE(kms->n_copied)); + if (kms->vbi_irq > 0) { + unsigned long flags; + u32 en, st; + + spin_lock_irqsave(&kms->vbi_lock, flags); + en = readl(kms->dp + SGX_DP_INT_EN); + st = readl(kms->dp + SGX_DP_INT_STAT); + spin_unlock_irqrestore(&kms->vbi_lock, flags); + seq_printf(m, "VBI irq %d%s: %lu VBIs, last period %u us (min %u, max %u); int enable 0x%08x status 0x%08x\n", + kms->vbi_irq, READ_ONCE(vbi) ? "" : " (off)", READ_ONCE(kms->n_vbi), + READ_ONCE(kms->vbi_period_us), READ_ONCE(kms->vbi_min_us), + READ_ONCE(kms->vbi_max_us), en, st); + seq_printf(m, "flips done at a VBI %lu, with no VBI in a frame %lu\n", + READ_ONCE(kms->n_at_vbi), READ_ONCE(kms->n_timeout)); + } else { + seq_puts(m, "no display VBI: flips wait on the line counter\n"); + } + /* (the line counter, a millisecond apart: on the A5 the line, 0 to + * the height - 1 over a frame, at bit 9) */ + seq_puts(m, "position (+0x54):"); + for (i = 0; i < 6; i++) { + seq_printf(m, " 0x%08x", readl(kms->clcd_pos)); + usleep_range(1000, 1100); + } + seq_putc(m, '\n'); return 0; } DEFINE_SHOW_ATTRIBUTE(sgx_kms_screen); @@ -647,13 +846,21 @@ static void sgx_kms_find_clcd(struct apple_sgx_kms *kms, const struct resource * return; kms->clcd = of_iomap(np, 0); kms->clcd_pos = of_iomap(np, 1); - of_node_put(np); if (kms->clcd && kms->clcd_pos && readl(kms->clcd + SGX_CLCD_L0_BASE) == fb->start && kms->sgx->fb_stride * 4 * kms->sgx->fb_h <= resource_size(fb)) { kms->boot_pa = fb->start; kms->shown = fb->start; + /* (A6) the pipe's general control and VBI, if named */ + kms->dp = of_iomap(np, 2); + kms->vbi_irq = kms->dp ? of_irq_get(np, 0) : 0; + if (kms->vbi_irq <= 0 && kms->dp) { + iounmap(kms->dp); + kms->dp = NULL; + } + of_node_put(np); return; } + of_node_put(np); if (kms->clcd) iounmap(kms->clcd); if (kms->clcd_pos) @@ -746,11 +953,29 @@ int apple_sgx_kms_init(struct drm_device *drm, struct apple_sgx *sgx) if (ret) return ret; drm_mode_config_reset(drm); + spin_lock_init(&kms->vbi_lock); + init_waitqueue_head(&kms->vbi_wq); sgx_kms_find_clcd(kms, &fb); + if (kms->vbi_irq > 0) { + /* (nothing enabled until a flip or vblank wants it) */ + writel(readl(kms->dp + SGX_DP_INT_EN) & ~SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_EN); + writel(SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_STAT); + ret = request_irq(kms->vbi_irq, sgx_kms_vbi, 0, "apple-sgx-vbi", kms); + if (ret) { + drm_warn(drm, "display VBI %d: %d; flips wait on the line counter\n", + kms->vbi_irq, ret); + kms->vbi_irq = 0; + } else { + ret = drmm_add_action_or_reset(drm, sgx_kms_vbi_fini, kms); + if (ret) + return ret; + } + } if (sgx->debugfs) debugfs_create_file("screen", 0400, sgx->debugfs, kms, &sgx_kms_screen_fops); sgx->kms = kms; - drm_info(drm, "screen: %ux%u at %pa, through the 2D engine%s\n", sgx->fb_w, sgx->fb_h, - &fb.start, kms->clcd ? " or the display's layer base" : ""); + drm_info(drm, "screen: %ux%u at %pa, through the 2D engine%s%s\n", sgx->fb_w, sgx->fb_h, + &fb.start, kms->clcd ? " or the display's layer base" : "", + kms->vbi_irq > 0 ? ", flips at the display's VBI" : ""); return 0; } From 4f7679c2fa99b0e236bed85c7778c96fa9159652 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:06:31 +0100 Subject: [PATCH 35/43] drm: apple-sgx: Hold a vblank reference across a VBI flip, wait 40 ms MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The flip's wait timed out in 2 jiffies (10-20 ms at HZ=100), so a flip committed early in a frame could miss its VBI and be written mid-frame. It is a hang guard only: 40 ms now. A flip holds a vblank reference until its VBI, so that the VBI is the vblank and the flip's event carries the count it landed on; the count is taken before the waiting commit is woken. As iOS's interruptFilter and enable_interrupts do, every raised bit is acknowledged and only the VBI is enabled. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/gpu/drm/apple-sgx/apple_sgx_kms.c | 113 ++++++++++++++-------- 1 file changed, 75 insertions(+), 38 deletions(-) diff --git a/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c b/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c index b63a001749c486..706ae95c424998 100644 --- a/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c +++ b/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c @@ -105,6 +105,8 @@ #define SGX_DP_INT_EN 0x28 #define SGX_DP_INT_STAT 0x2c #define SGX_DP_INT_VBI BIT(0) +/* how long a flip waits for the VBI before it writes the base itself */ +#define SGX_KMS_VBI_WAIT_MS 40 /* (M49) off: every update copied onto the boot framebuffer, as before; * looked at in each update */ @@ -138,14 +140,15 @@ struct apple_sgx_kms { /* (A6) the pipe's general control and VBI (0: none). Under vbi_lock: * vbl_irq, the vblank is the VBI's (not the timer's); base_pending, - * base_pa to be written at the next VBI (flip_vbi: this commit's - * flip waits for that). For debugfs: VBIs, the time between the last - * two, flips done at a VBI and flips that waited a frame out. */ + * base_pa to be written at the next VBI, base_vref with a vblank + * reference held for it, so that the VBI counts the vblank the flip + * lands on (flip_vbi: this commit's flip waits for that). For debugfs: VBIs, the time between the last + * two, flips done at a VBI and flips whose VBI did not come in time. */ void __iomem *dp; int vbi_irq; spinlock_t vbi_lock; wait_queue_head_t vbi_wq; - bool vbl_irq, base_pending, flip_vbi; + bool vbl_irq, base_pending, base_vref, flip_vbi; dma_addr_t base_pa; unsigned long n_vbi, n_at_vbi, n_timeout; ktime_t vbi_last; @@ -284,19 +287,20 @@ static void sgx_kms_show(struct apple_sgx_kms *kms, const struct drm_plane_state drm_err_ratelimited(fb->dev, "the 2D engine's copy to the screen: %d\n", ret); } -/* The VBI on while anyone wants it: vblanks, or a base to write. A VBI - * left from before is cleared first, so that the next one is a vertical - * blank to come. Under vbi_lock. */ +/* The VBI on while anyone wants it: vblanks, or a base to write; the + * pipe's other interrupts off (the enable register is the kernel's alone, + * as iOS's enable_interrupts keeps it). Whatever was raised before is + * cleared first, so that the next VBI is a vertical blank to come. Under + * vbi_lock. */ static void sgx_kms_vbi_want(struct apple_sgx_kms *kms) { - bool want = kms->vbl_irq || kms->base_pending; - u32 en = readl(kms->dp + SGX_DP_INT_EN); + u32 want = kms->vbl_irq || kms->base_pending ? SGX_DP_INT_VBI : 0; - if (!!(en & SGX_DP_INT_VBI) == want) + if (readl(kms->dp + SGX_DP_INT_EN) == want) return; if (want) - writel(SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_STAT); - writel(want ? en | SGX_DP_INT_VBI : en & ~SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_EN); + writel(~0u, kms->dp + SGX_DP_INT_STAT); + writel(want, kms->dp + SGX_DP_INT_EN); } static bool sgx_kms_use_vbi(struct apple_sgx_kms *kms) @@ -307,6 +311,7 @@ static bool sgx_kms_use_vbi(struct apple_sgx_kms *kms) static void sgx_kms_point(struct apple_sgx_kms *kms, dma_addr_t pa) { unsigned long flags; + bool ref, extra = false; if (pa == kms->shown) return; @@ -314,17 +319,38 @@ static void sgx_kms_point(struct apple_sgx_kms *kms, dma_addr_t pa) kms->flipped = true; kms->flip_vbi = sgx_kms_use_vbi(kms); if (kms->flip_vbi) { - /* (written at the next VBI: sgx_kms_vbi) */ + /* (written at the next VBI: sgx_kms_vbi; the vblanks on until + * then -- none for a CRTC going off) */ + ref = !drm_crtc_vblank_get(&kms->pipe.crtc); spin_lock_irqsave(&kms->vbi_lock, flags); kms->base_pa = pa; kms->base_pending = true; + if (ref && kms->base_vref) + extra = true; + else if (ref) + kms->base_vref = true; sgx_kms_vbi_want(kms); spin_unlock_irqrestore(&kms->vbi_lock, flags); + if (extra) + drm_crtc_vblank_put(&kms->pipe.crtc); return; } writel(pa, kms->clcd + SGX_CLCD_L0_BASE); } +/* The base waiting written now, its vblank reference let go (no VBI in + * time, or the end). Under vbi_lock; true: put the reference after. */ +static bool sgx_kms_base_now(struct apple_sgx_kms *kms) +{ + bool put = kms->base_vref; + + if (kms->base_pending) + writel(kms->base_pa, kms->clcd + SGX_CLCD_L0_BASE); + kms->base_pending = false; + kms->base_vref = false; + return put; +} + /* Whether the plane can be shown by pointing the layer at its buffer, and * where: a contiguous buffer, the screen's size from its origin and the * boot framebuffer's pitch, unturned, no overlay. Under ov_lock. */ @@ -402,21 +428,24 @@ static void sgx_kms_wait_frame(struct apple_sgx_kms *kms) unsigned long flags; /* (A6) the base goes in at the next VBI; then the display no longer - * reads the buffer before. No VBI in a frame and a millisecond: the - * base written now, and a frame waited out as below. */ + * reads the buffer before. No VBI in two frames and more (a guard + * against a hang only: jiffies are 10 ms here): the base written now, + * and a frame waited out as below. */ if (kms->flip_vbi) { + bool put; + if (wait_event_timeout(kms->vbi_wq, !READ_ONCE(kms->base_pending), - usecs_to_jiffies(ktime_to_us(kms->vblank_period) + 1000))) + msecs_to_jiffies(SGX_KMS_VBI_WAIT_MS) + 1)) return; spin_lock_irqsave(&kms->vbi_lock, flags); - if (kms->base_pending) { - writel(kms->base_pa, kms->clcd + SGX_CLCD_L0_BASE); - kms->base_pending = false; - sgx_kms_vbi_want(kms); - } + put = sgx_kms_base_now(kms); + sgx_kms_vbi_want(kms); kms->n_timeout++; spin_unlock_irqrestore(&kms->vbi_lock, flags); - drm_err_ratelimited(kms->pipe.crtc.dev, "no display VBI in a frame: base written at once\n"); + if (put) + drm_crtc_vblank_put(&kms->pipe.crtc); + drm_err_ratelimited(kms->pipe.crtc.dev, "no display VBI in %u ms: base written at once\n", + SGX_KMS_VBI_WAIT_MS); } end = ktime_add(ktime_get(), ktime_add_us(kms->vblank_period, 200)); @@ -469,19 +498,21 @@ static enum hrtimer_restart sgx_kms_vblank(struct hrtimer *timer) static irqreturn_t sgx_kms_vbi(int irq, void *data) { struct apple_sgx_kms *kms = data; - bool flipped = false, vbl; + bool flipped = false, put = false, vbl; ktime_t now; + u32 st; s64 us; spin_lock(&kms->vbi_lock); - if (!(readl(kms->dp + SGX_DP_INT_STAT) & SGX_DP_INT_VBI)) { + /* (every bit raised acknowledged, as iOS's interruptFilter does) */ + st = readl(kms->dp + SGX_DP_INT_STAT); + writel(st, kms->dp + SGX_DP_INT_STAT); + if (!(st & SGX_DP_INT_VBI)) { spin_unlock(&kms->vbi_lock); - return IRQ_NONE; + return st ? IRQ_HANDLED : IRQ_NONE; } - writel(SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_STAT); if (kms->base_pending) { - writel(kms->base_pa, kms->clcd + SGX_CLCD_L0_BASE); - kms->base_pending = false; + put = sgx_kms_base_now(kms); kms->n_at_vbi++; flipped = true; } @@ -499,10 +530,14 @@ static irqreturn_t sgx_kms_vbi(int irq, void *data) sgx_kms_vbi_want(kms); spin_unlock(&kms->vbi_lock); - if (flipped) - wake_up_all(&kms->vbi_wq); + /* (the count first: the flip's event, sent by the woken commit, + * carries it) */ if (vbl) drm_crtc_handle_vblank(&kms->pipe.crtc); + if (flipped) + wake_up_all(&kms->vbi_wq); + if (put) + drm_crtc_vblank_put(&kms->pipe.crtc); return IRQ_HANDLED; } @@ -622,15 +657,17 @@ static void sgx_kms_vbi_fini(struct drm_device *drm, void *data) struct apple_sgx_kms *kms = data; unsigned long flags; + bool put; + spin_lock_irqsave(&kms->vbi_lock, flags); kms->vbl_irq = false; - if (kms->base_pending) - writel(kms->base_pa, kms->clcd + SGX_CLCD_L0_BASE); - kms->base_pending = false; - writel(readl(kms->dp + SGX_DP_INT_EN) & ~SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_EN); - writel(SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_STAT); + put = sgx_kms_base_now(kms); + writel(0, kms->dp + SGX_DP_INT_EN); + writel(~0u, kms->dp + SGX_DP_INT_STAT); spin_unlock_irqrestore(&kms->vbi_lock, flags); free_irq(kms->vbi_irq, kms); + if (put) + drm_crtc_vblank_put(&kms->pipe.crtc); kms->vbi_irq = 0; } @@ -819,7 +856,7 @@ static int sgx_kms_screen_show(struct seq_file *m, void *unused) kms->vbi_irq, READ_ONCE(vbi) ? "" : " (off)", READ_ONCE(kms->n_vbi), READ_ONCE(kms->vbi_period_us), READ_ONCE(kms->vbi_min_us), READ_ONCE(kms->vbi_max_us), en, st); - seq_printf(m, "flips done at a VBI %lu, with no VBI in a frame %lu\n", + seq_printf(m, "flips done at a VBI %lu, with no VBI in time (written at once) %lu\n", READ_ONCE(kms->n_at_vbi), READ_ONCE(kms->n_timeout)); } else { seq_puts(m, "no display VBI: flips wait on the line counter\n"); @@ -958,8 +995,8 @@ int apple_sgx_kms_init(struct drm_device *drm, struct apple_sgx *sgx) sgx_kms_find_clcd(kms, &fb); if (kms->vbi_irq > 0) { /* (nothing enabled until a flip or vblank wants it) */ - writel(readl(kms->dp + SGX_DP_INT_EN) & ~SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_EN); - writel(SGX_DP_INT_VBI, kms->dp + SGX_DP_INT_STAT); + writel(0, kms->dp + SGX_DP_INT_EN); + writel(~0u, kms->dp + SGX_DP_INT_STAT); ret = request_irq(kms->vbi_irq, sgx_kms_vbi, 0, "apple-sgx-vbi", kms); if (ret) { drm_warn(drm, "display VBI %d: %d; flips wait on the line counter\n", From ce7b279abd18d33b055c296b760458f62d27b9b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:06:31 +0100 Subject: [PATCH 36/43] drm: apple-sgx: Complete a copied flip at the next VBI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A flip the display cannot point at (a buffer that is not contiguous, the screen's pitch and size) is shown by a copy onto the boot framebuffer. Its event went as soon as the copy was queued, so a compositor flipping client buffers that way (cage with weston-simple-egl) ran unpaced at ~370 frames a second, 1.3 cores busy. Where the display pipe's VBI is there, such a flip now completes at the next VBI, as a pointed one does; an async flip still completes at once. debugfs screen counts them. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/gpu/drm/apple-sgx/apple_sgx_kms.c | 42 ++++++++++++++++++++--- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c b/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c index 706ae95c424998..e521996de05c36 100644 --- a/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c +++ b/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c @@ -150,7 +150,11 @@ struct apple_sgx_kms { wait_queue_head_t vbi_wq; bool vbl_irq, base_pending, base_vref, flip_vbi; dma_addr_t base_pa; - unsigned long n_vbi, n_at_vbi, n_timeout; + /* copy_flip: this commit's flip went by a copy; its event waits for + * the next VBI (vbi_seq counts them) */ + bool copy_flip; + unsigned long vbi_seq; + unsigned long n_vbi, n_at_vbi, n_timeout, n_copy_paced; ktime_t vbi_last; u32 vbi_period_us, vbi_min_us, vbi_max_us; @@ -408,6 +412,12 @@ static void sgx_kms_update(struct drm_simple_display_pipe *pipe, kms->n_copied++; } else { kms->n_copied++; + /* (a flip shown by a copy is done at the vertical blank too, as + * a pointed one is -- not as soon as the copy is queued; an + * async flip is) */ + if (state->fb != old_state->fb && sgx_kms_use_vbi(kms) && + !pipe->crtc.state->async_flip) + kms->copy_flip = true; drm_atomic_helper_damage_iter_init(&iter, old_state, state); drm_atomic_for_each_plane_damage(&iter, &clip) sgx_kms_show(kms, state, &clip); @@ -419,6 +429,22 @@ static void sgx_kms_update(struct drm_simple_display_pipe *pipe, * (it takes the base there, or at once -- either way the buffer before is * no longer read): the line counter gone round and a line further, or a * frame's time, sleeping through most of it. */ +/* (A6) A flip shown by a copy: until the next VBI, the vblanks on until + * then. The same hang guard as a pointed flip's. */ +static void sgx_kms_wait_vbi(struct apple_sgx_kms *kms) +{ + bool ref = !drm_crtc_vblank_get(&kms->pipe.crtc); + unsigned long seq = READ_ONCE(kms->vbi_seq); + + if (wait_event_timeout(kms->vbi_wq, READ_ONCE(kms->vbi_seq) != seq, + msecs_to_jiffies(SGX_KMS_VBI_WAIT_MS) + 1)) + kms->n_copy_paced++; + else + kms->n_timeout++; + if (ref) + drm_crtc_vblank_put(&kms->pipe.crtc); +} + static void sgx_kms_wait_frame(struct apple_sgx_kms *kms) { u32 h = kms->sgx->fb_h, prev, line, us; @@ -498,7 +524,7 @@ static enum hrtimer_restart sgx_kms_vblank(struct hrtimer *timer) static irqreturn_t sgx_kms_vbi(int irq, void *data) { struct apple_sgx_kms *kms = data; - bool flipped = false, put = false, vbl; + bool put = false, vbl; ktime_t now; u32 st; s64 us; @@ -514,7 +540,6 @@ static irqreturn_t sgx_kms_vbi(int irq, void *data) if (kms->base_pending) { put = sgx_kms_base_now(kms); kms->n_at_vbi++; - flipped = true; } now = ktime_get(); us = ktime_us_delta(now, kms->vbi_last); @@ -526,6 +551,7 @@ static irqreturn_t sgx_kms_vbi(int irq, void *data) } kms->vbi_last = now; kms->n_vbi++; + kms->vbi_seq++; vbl = kms->vbl_irq; sgx_kms_vbi_want(kms); spin_unlock(&kms->vbi_lock); @@ -534,8 +560,8 @@ static irqreturn_t sgx_kms_vbi(int irq, void *data) * carries it) */ if (vbl) drm_crtc_handle_vblank(&kms->pipe.crtc); - if (flipped) - wake_up_all(&kms->vbi_wq); + /* (flips waiting for their base, and copy flips for the blank) */ + wake_up_all(&kms->vbi_wq); if (put) drm_crtc_vblank_put(&kms->pipe.crtc); return IRQ_HANDLED; @@ -608,6 +634,10 @@ static void sgx_kms_commit_tail(struct drm_atomic_state *state) sgx_kms_wait_frame(kms); kms->flipped = false; } + if (kms->copy_flip) { + sgx_kms_wait_vbi(kms); + kms->copy_flip = false; + } } for_each_new_crtc_in_state(state, crtc, crtc_state, i) { unsigned long flags; @@ -858,6 +888,8 @@ static int sgx_kms_screen_show(struct seq_file *m, void *unused) READ_ONCE(kms->vbi_max_us), en, st); seq_printf(m, "flips done at a VBI %lu, with no VBI in time (written at once) %lu\n", READ_ONCE(kms->n_at_vbi), READ_ONCE(kms->n_timeout)); + seq_printf(m, "flips by a copy, done at the next VBI %lu\n", + READ_ONCE(kms->n_copy_paced)); } else { seq_puts(m, "no display VBI: flips wait on the line counter\n"); } From 7218069d52944221a450be3665c78e1bbce23404 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:07:37 +0100 Subject: [PATCH 37/43] power: supply: apple-pmu-charger: Add the D1972 charging policy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Apply per-device calibration to the input current ramp, back off after VBUS sag and expose thermal charge limits. D1972 writes require explicit opt-in. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/power/supply/apple-pmu-charger.c | 807 +++++++++++++++++++---- 1 file changed, 685 insertions(+), 122 deletions(-) diff --git a/drivers/power/supply/apple-pmu-charger.c b/drivers/power/supply/apple-pmu-charger.c index a2e89c1b1fc510..3c42c927b57f1b 100644 --- a/drivers/power/supply/apple-pmu-charger.c +++ b/drivers/power/supply/apple-pmu-charger.c @@ -1,6 +1,9 @@ // SPDX-License-Identifier: GPL-2.0 /* - * The iPad mini 1's USB input current limit: D1946 PMU register 0x3d. + * USB charging on the Dialog PMUs of the iPad mini 1 (D1946) and the + * iPhone 5 (D1972). + * + * D1946 (iPad mini 1): the USB input current limit, register 0x3d. * * iBEC hands over with 0x3d at 0x02, about 100 mA, and nothing in Linux used * to raise it, so the iPad drained on any cable -- measured -386 mA on a @@ -19,43 +22,86 @@ * iOS (AppleD1946PMUPowerSource::handleInterrupt) both treat that as * "this source cannot give more" and back off 8 codes. So does this. * - * Online is 0x0a bit 6: 0x6b plugged, 0x03 or 0x23 not, the same for a host - * port and a charger -- telling those apart takes the D+/D- measurement on - * the PMU's ADC that iBEC makes, which is not here. Until it is, the - * target is 1000 mA (Cascadia's choice: iBEC's for a charger it does not - * know; a Mac's USB-C port gave it with no sag, +752 mA into the battery - * against +253 at 500), and a source that cannot give it sags: the limit - * then stays 8 codes under where it sagged until the cable comes out (a - * cable out and in again within the 1 s poll looks like a sag: 900 mA until - * the next time). More - * has to be asked for by hand: raise max_input_ma, then write - * input_current_limit. + * Online is 0x0a bit 6: 0x6b plugged, 0x03 or 0x23 not. The target is + * 1000 mA; a source that cannot give it sags, and the limit then stays 8 + * codes under where it sagged until the cable comes out. Above 45 C on the + * battery gauge (or with no reading) it drops to 100 mA until below 40 C. + * 0x3d is the only register written on the D1946. + * + * D1972 (iPhone 5): iOS 8.4.1 (12H321) splits the job between + * AppleD1972PMUPowerSource (AppleDialogPMU kext) and AppleARMPMUCharger / + * AppleARMPMUPowerSource (AppleARMPlatform kext). This file does what they + * do; the addresses are in that kernelcache. * - * The rules this file keeps: - * - 0x3d is the only register it writes. pmu_chg_write() refuses any - * other. It never reads 0x01..0x09: those clear on read. - * - It is armed by default (module parameter armed=0 turns it off); disarmed - * it writes nothing and logs what it would do. Disarming puts back the - * value it found at probe. Unbinding does not restore 0x3d. - * - Above 45 C on the battery gauge it drops to 100 mA, and stays there - * until below 40 C. Missing/failed temperature also selects this fallback. - * iBEC's charge table ends at 45 C. This is derating, not charge inhibition. - * On the D1972 a reading outside -20..+70 C counts as missing, and it - * takes three cool readings in a row to leave the fallback. + * - Input current limit, register 0x3f (setInputCurrentLimit, 0x80d1526c): + * a read-modify-write of 0x1b bit 2 (input suspend: set below 70 mA, + * cleared otherwise; 0x80d153a8), then 0x3f = (mA - 70) / 10, 0xff from + * 2620 mA. Before that the request is corrected by the unit's + * usb-input-limit-calibration from the ADT's /charger node (0x80d152c8, + * three 16.16 mA words: what 100, 500 and 1000 mA measured), at most + * +-15%. + * - What is asked for: the source's rating, capped by usb-input-limit-max + * (no such property on the N42: 1000 mA; 0x804cd2b4). iOS rates a + * standard host 100 mA until the USB stack configures (then what the + * host granted), a CDP 1500 mA, a DCP what it measures and an Apple + * brick by its ID (500/1000/1000/2100/2400 mA, 0x804cd128); all of the + * chargers end at the 1000 mA cap. Linux sees none of that yet, so the + * request is the cap; a host that cannot give it sags (below). + * - Ramp (0x804c9858 with the step 0x80d15488): 100 mA steps, each one + * after 0.1 ms per mA of the previous step (10 ms), rounded up to 10 mA. + * From nothing it first sets 100 mA, then ramps. + * - Sag (0x80d150e4, 0x804c7b8c, 0x804c7c50): the PMU drops 0x3f to 0x03 + * when VBUS sags. If 0x0f bit 0 is set, the last code was 0x0d or more + * and 0x3f reads 0x03 within 500 ms of a step, iOS caps the source 100 mA + * under the step ("limiting USB input current to %lu mA") for 300 s, + * and drops the cap when the cable goes (0x804c8eb4). + * - Charge current, register 0x43, 30 mA/LSB (0x80d151d4): the charge + * limit, never above what 0x43 held at start (0x80d15000: 0x1e, 900 mA + * on the N42). The limit is charge-limits[AppleChargeRateLimitIndex] + * (ADT /charger <900 570 420 270>; the index is thermal policy from + * userspace, here charge_control_limit), lowered by a ChargeTable when + * one is supplied (0x804c8f80) -- the N42 has none. 0x45 bits 5:0 x 30 + * is the charge current in use (0x80d15234; iOS "ChargerConfiguration"). + * - Charge end and charge timer (0x804ca78c, every 60 s update): with the + * cable in and the gauge not charging, 0x0b bit 3 (done) below 95% and + * within 15 h of attach sets 0x1b bit 2 and re-evaluates the source + * (0x80d15760); what clears the bit again in iOS was not found, here + * the input limit is re-applied after 100 ms; 0x0f bit 5 (timer expired) for 300 s, below 90% (or + * below 95% within 15 h), restarts the timer by writing 0x46 & 0x08 and + * then 0x46 back (0x80d15714). + * - 0x0b bit 4 is the PMU's own battery-temperature verdict + * ("HighOrLowTemperature", 0x80d15684); iOS only reports it. * - * The temperature is the battery gauge's ("battery", POWER_SUPPLY_PROP_TEMP), - * on every chip; this driver reads no PMU ADC channel. + * Only on Linux: no PMU interrupt reaches this driver, so it polls status + * 0x0a..0x11 (the block iOS reads, 0x80d10c98) once a second, every 100 ms + * inside a sag window. A drop to 0x03 outside the window re-ramps from + * 100 mA, with the window applying to each new step. And the gauge guard: + * a battery reading above 45 C, outside -20..70 C or missing sets the charge + * limit to 0 (the action a ChargeTable takes outside its range) until three + * readings in a row are under 40 C. iOS never writes 0x43 = 0 on this unit, + * so what code 0 does in the PMU is unverified. The guard is checked every + * poll; the charge current is rewritten when it flips. + * + * Common rules: + * - Nothing is written until armed (module parameter, default off); until + * then the driver logs what it would set. Disarming puts back what it + * found at probe. + * - pmu_chg_write() refuses every register outside the chip's list (D1946: + * 0x3d; D1972: 0x3f, 0x43, 0x46 and only bit 2 of 0x1b). The event + * registers 0x01..0x09, which clear on read, are never read. */ #include #include #include #include +#include #include #include #include #include #include #include +#include #include #include @@ -73,16 +119,40 @@ #define HOT_DECI_C 450 #define COOL_DECI_C 400 -/* - * temp_guard (D1972 / iPhone 5): the battery temperature is the gauge's, over - * HDQ. A reading outside -20..+70 C is no reading at all, and leaving the - * 100 mA fallback takes COOL_SAMPLES cool readings in a row, so neither a - * corrupt word nor a single good one between failures moves the limit up. - */ +/* D1972 gauge guard: outside -20..+70 C is no reading; three cool readings leave it. */ #define GUARD_MIN_DECI_C (-200) #define GUARD_MAX_DECI_C 700 #define COOL_SAMPLES 3 +/* D1972 registers and status bits (status block 0x0a..0x11 = s[0..7]) */ +#define D1972_SUSPEND 0x1b +#define D1972_SUSPEND_USB BIT(2) +#define D1972_ILIM 0x3f +#define D1972_ICHG 0x43 +#define D1972_ICHG_NOW 0x45 +#define D1972_CHG_TIMER 0x46 +#define D1972_NSTATUS 8 +#define D1972_S0_VBUS BIT(6) /* s[0] = 0x0a */ +#define D1972_S1_CHARGING (BIT(1) | BIT(2)) /* s[1] = 0x0b */ +#define D1972_S1_CHG_END BIT(3) +#define D1972_S1_TEMP BIT(4) +#define D1972_S3_ILIM_REG BIT(5) /* s[3] = 0x0d */ +#define D1972_S5_ILIM_ACT BIT(0) /* s[5] = 0x0f */ +#define D1972_S5_CHG_TO BIT(5) + +#define D1972_ILIM_MAX_MA 2620 /* 0x80d15480 */ +#define D1972_ILIM_SAGGED 0x03 +#define D1972_SAG_MIN_CODE 0x0d +#define D1972_ICHG_LSB_MA 30 +#define D1972_ICHG_MASK 0x3f +#define D1972_SAG_WINDOW_MS 500 +#define D1972_BACKOFF_S 300 +#define D1972_UPDATE_S 60 +#define D1972_DEBOUNCE_MS 100 +#define D1972_SAG_POLL_MS 100 +#define D1972_TO_HOLD_S 300 +#define D1972_RECHARGE_S 54000 + struct pmu_chg_chip { const char *name; u8 status_reg; @@ -93,7 +163,7 @@ struct pmu_chg_chip { unsigned int max_ma; u8 (*ma_to_code)(unsigned int ma); unsigned int (*code_to_ma)(u8 code); - bool temp_guard; + bool ios_policy; /* D1972: AppleD1972PMUPowerSource + AppleARMPMUCharger */ }; /* D1946: iBEC's encoding, 0x9ff0c618..0x9ff0c662 (register 0x3d) */ @@ -121,24 +191,10 @@ static unsigned int d1946_code_to_ma(u8 code) return code <= 0x02 ? 100 : (code * 100 + 600) / 8; } -/* - * D1972 (iPhone 5, S5L8950X): register 0x3f. - * AppleD1972PMUPowerSource (14G61 0x810e9bf4..0x810e9c2f): linear 10 mA/LSB - * from 70 mA (code = (mA - 70) / 10; < 70 mA suspends, > 2619 mA clamps to - * 0xff). On VBUS sag the PMU drops 0x3f back to 0x03 (100 mA, checked at - * 0x810e99e6). Online is status register 0x0a bit 6 (0x810e9ec8), as on D1946. - */ -static u8 d1972_ma_to_code(unsigned int ma) -{ - ma = min_t(unsigned int, ma, ILIM_HARD_MAX_MA); - if (ma < 100) - return 0x03; - return (ma - 70) / 10; -} - +/* D1972 register 0x3f: (mA - 70) / 10, so a code is 70 + 10 * code mA. */ static unsigned int d1972_code_to_ma(u8 code) { - return code <= 0x03 ? 100 : 70 + code * 10; + return 70 + code * 10; } static const struct pmu_chg_chip pmu_chg_d1946 = { @@ -156,14 +212,12 @@ static const struct pmu_chg_chip pmu_chg_d1946 = { static const struct pmu_chg_chip pmu_chg_d1972 = { .name = "d1972", .status_reg = PMU_STATUS0, - .vbus_mask = PMU_STATUS0_VBUS, - .ilim_reg = 0x3f, - .min_code = 0x03, - .ramp_step = 10, - .max_ma = ILIM_HARD_MAX_MA, - .ma_to_code = d1972_ma_to_code, + .vbus_mask = D1972_S0_VBUS, + .ilim_reg = D1972_ILIM, + .min_code = D1972_ILIM_SAGGED, + .max_ma = D1972_ILIM_MAX_MA, .code_to_ma = d1972_code_to_ma, - .temp_guard = true, + .ios_policy = true, }; static bool d1972_armed; @@ -188,12 +242,37 @@ struct pmu_chg { unsigned int req_ma; /* asked for: default or input_current_limit */ u8 probe_code; /* ILIM register as iBoot left it */ u8 last_written; /* 0 = nothing written while online */ - u8 ceiling; /* after a sag, until unplugged; 0xff = none */ + u8 ceiling; /* D1946: after a sag, until unplugged; 0xff = none */ bool online; bool was_armed; bool hot; - u8 cool_samples; /* temp_guard: cool readings in a row */ + u8 cool_samples; /* D1972 gauge guard: cool readings in a row */ u8 logged_code; /* last "would set" logged, to say it once */ + + /* D1972 */ + u32 cal[3]; /* usb-input-limit-calibration, 16.16 mA */ + bool has_cal; + u32 limits[4]; /* charge-limits, mA */ + unsigned int nlimits; + unsigned int limit_idx; /* AppleChargeRateLimitIndex */ + unsigned int ilim_max_ma; /* usb-input-limit-max */ + u8 ichg_cap; /* 0x43 bits 5:0 at probe */ + u8 probe_ichg; /* 0x43 at probe */ + bool probe_suspend; /* 0x1b bit 2 at probe */ + u8 status[D1972_NSTATUS]; /* 0x0a..0x11 */ + unsigned int cur_ma; /* input limit last set; 0 = none yet */ + unsigned int step_ma; /* size of the last step */ + unsigned long step_at; /* jiffies of the last set */ + unsigned int backoff_ma; /* sag cap; 0 = none */ + unsigned long backoff_at; + unsigned long attach_at; /* 0 = no cable */ + unsigned long to_at; /* charge timer seen expired; 0 = not */ + unsigned long update_at; /* next charger update */ + bool update_now; + u8 last_ilim; /* last 0x3f written */ + u8 logged_ichg; + unsigned int logged_ma; + bool chg_end, chg_to, tfault; /* last logged status */ }; static bool pmu_chg_armed(struct pmu_chg *c) @@ -201,17 +280,24 @@ static bool pmu_chg_armed(struct pmu_chg *c) return c->chip == &pmu_chg_d1972 ? READ_ONCE(d1972_armed) : READ_ONCE(armed); } +static bool pmu_chg_writable(struct pmu_chg *c, unsigned int reg) +{ + if (reg == c->chip->ilim_reg) + return true; + return c->chip->ios_policy && + (reg == D1972_ICHG || reg == D1972_CHG_TIMER); +} + static int pmu_chg_write(struct pmu_chg *c, unsigned int reg, u8 val) { int ret; - if (reg != c->chip->ilim_reg) { - dev_err(c->dev, "refusing PMU write 0x%02x = 0x%02x: only 0x%02x is ours\n", - reg, val, c->chip->ilim_reg); + if (!pmu_chg_writable(c, reg)) { + dev_err(c->dev, "refusing PMU write 0x%02x = 0x%02x\n", reg, val); return -EPERM; } ret = regmap_write(c->map, reg, val); - if (!ret) + if (!ret && reg == c->chip->ilim_reg) c->last_written = val; return ret; } @@ -247,6 +333,13 @@ static void pmu_chg_log_vbus(struct pmu_chg *c, u8 ilim, bool is_armed) } } +/* The only bit of 0x1b this driver touches: the USB input suspend. */ +static int d1972_set_suspend(struct pmu_chg *c, bool suspend) +{ + return regmap_update_bits(c->map, D1972_SUSPEND, D1972_SUSPEND_USB, + suspend ? D1972_SUSPEND_USB : 0); +} + static void pmu_chg_sagged(struct pmu_chg *c, u8 at) { c->ceiling = max_t(int, c->chip->min_code, at - c->chip->ramp_step); @@ -254,7 +347,7 @@ static void pmu_chg_sagged(struct pmu_chg *c, u8 at) at, c->chip->code_to_ma(c->ceiling)); } -/* Ramp ILIM from cur up to target, ramp_step codes every 10 ms, watching for a sag. */ +/* D1946: ramp ILIM from cur up to target, ramp_step codes every 10 ms, watching for a sag. */ static void pmu_chg_ramp(struct pmu_chg *c, u8 cur, u8 target) { while (cur < target) { @@ -280,87 +373,91 @@ static void pmu_chg_ramp(struct pmu_chg *c, u8 cur, u8 target) } } -static bool pmu_chg_battery_hot_guarded(struct pmu_chg *c) +static int pmu_chg_battery_prop(enum power_supply_property psp, int *val) { - union power_supply_propval t = {}; + union power_supply_propval v = {}; struct power_supply *bat = power_supply_get_by_name("battery"); - int ret = -ENODEV; + int ret; - if (bat) { - ret = power_supply_get_property(bat, POWER_SUPPLY_PROP_TEMP, &t); - power_supply_put(bat); - if (!ret && (t.intval < GUARD_MIN_DECI_C || t.intval > GUARD_MAX_DECI_C)) - ret = -ERANGE; - } + if (!bat) + return -ENODEV; + ret = power_supply_get_property(bat, psp, &v); + power_supply_put(bat); + if (!ret) + *val = v.intval; + return ret; +} + +/* D1972 gauge guard (Linux only, see the top of the file). */ +static bool pmu_chg_battery_hot_guarded(struct pmu_chg *c) +{ + int t = 0; + int ret = pmu_chg_battery_prop(POWER_SUPPLY_PROP_TEMP, &t); + + if (!ret && (t < GUARD_MIN_DECI_C || t > GUARD_MAX_DECI_C)) + ret = -ERANGE; if (ret) { - /* no reading: the 100 mA fallback, and the cool count starts over */ + /* no reading: the guard holds, and the cool count starts over */ if (!c->hot) - dev_warn(c->dev, "battery temperature unavailable (%d%s): input limited to 100 mA\n", - ret == -ERANGE ? t.intval : ret, + dev_warn(c->dev, "battery temperature unavailable (%d%s): charge limit 0\n", + ret == -ERANGE ? t : ret, ret == -ERANGE ? " deci-C, out of range" : ""); c->hot = true; c->cool_samples = 0; return true; } - if (t.intval > HOT_DECI_C) { + if (t > HOT_DECI_C) { if (!c->hot) - dev_warn(c->dev, "battery at %s%d.%d C: input limited to 100 mA\n", - t.intval < 0 ? "-" : "", abs(t.intval) / 10, abs(t.intval) % 10); + dev_warn(c->dev, "battery at %s%d.%d C: charge limit 0\n", + t < 0 ? "-" : "", abs(t) / 10, abs(t) % 10); c->hot = true; c->cool_samples = 0; } else if (c->hot) { - if (t.intval < COOL_DECI_C && ++c->cool_samples >= COOL_SAMPLES) { + if (t < COOL_DECI_C && ++c->cool_samples >= COOL_SAMPLES) { c->hot = false; c->cool_samples = 0; dev_info(c->dev, "battery back to %s%d.%d C (%d readings in a row)\n", - t.intval < 0 ? "-" : "", abs(t.intval) / 10, - abs(t.intval) % 10, COOL_SAMPLES); - } else if (t.intval >= COOL_DECI_C) { + t < 0 ? "-" : "", abs(t) / 10, abs(t) % 10, COOL_SAMPLES); + } else if (t >= COOL_DECI_C) { c->cool_samples = 0; } } return c->hot; } +/* D1946: above 45 C, or no reading, the input limit drops to 100 mA until below 40 C. */ static bool pmu_chg_battery_hot(struct pmu_chg *c) { - union power_supply_propval t; - struct power_supply *bat; - - if (c->chip->temp_guard) - return pmu_chg_battery_hot_guarded(c); + int t; - bat = power_supply_get_by_name("battery"); - if (!bat) { + if (pmu_chg_battery_prop(POWER_SUPPLY_PROP_TEMP, &t)) { + /* Missing temperature is not permission to raise the input limit. */ c->hot = true; - return true; - } - if (power_supply_get_property(bat, POWER_SUPPLY_PROP_TEMP, &t)) { - /* Missing temperature is not permission to raise the input limit. - * Keep the existing hysteresis before accepting a cool sample again. - * The minimum input profile is derating, not proven charge cutoff. - */ + } else if (!c->hot && t > HOT_DECI_C) { c->hot = true; - } else { - if (!c->hot && t.intval > HOT_DECI_C) { - c->hot = true; - dev_warn(c->dev, "battery at %d.%d C: input limited to 100 mA\n", - t.intval / 10, t.intval % 10); - } else if (c->hot && t.intval < COOL_DECI_C) { - c->hot = false; - dev_info(c->dev, "battery back to %d.%d C\n", t.intval / 10, t.intval % 10); - } + dev_warn(c->dev, "battery at %d.%d C: input limited to 100 mA\n", + t / 10, t % 10); + } else if (c->hot && t < COOL_DECI_C) { + c->hot = false; + dev_info(c->dev, "battery back to %d.%d C\n", t / 10, t % 10); } - power_supply_put(bat); return c->hot; } +static unsigned int pmu_chg_ceiling_ma(struct pmu_chg *c) +{ + unsigned int ma = clamp(READ_ONCE(max_input_ma), 100, (int)c->chip->max_ma); + + if (c->chip->ios_policy) + ma = min(ma, c->ilim_max_ma); + return ma; +} + static u8 pmu_chg_target(struct pmu_chg *c) { - unsigned int ma = min_t(unsigned int, c->req_ma, - clamp(READ_ONCE(max_input_ma), 100, (int)c->chip->max_ma)); + unsigned int ma = min(c->req_ma, pmu_chg_ceiling_ma(c)); u8 code = c->chip->ma_to_code(ma); if (c->ceiling != 0xff) @@ -370,13 +467,378 @@ static u8 pmu_chg_target(struct pmu_chg *c) return code; } +/* + * ---- D1972 ---- + */ + +/* + * AppleD1972PMUPowerSource 0x80d152c8: the 0x3f code for mA, after the + * unit's calibration. cal[0] is what 100 mA measured, cal[1] and cal[2] + * what 500 and 1000 mA measured, all 16.16 mA. + */ +static u8 d1972_ilim_code(const struct pmu_chg *c, unsigned int ma, bool *suspend) +{ + if (c->has_cal) { + unsigned int adj = 0; + + if (ma < 330 && c->cal[0]) { + unsigned int at100 = (c->cal[0] + 0xffff) >> 16; + + if (at100 != 100) + adj = ma + 100 - at100; + } else if (ma >= 330 && c->cal[1] && c->cal[2]) { + s32 span = c->cal[2] - c->cal[1]; + s32 per500 = span / 500; + s32 num = (s32)(ma * 0x10000 - c->cal[1] + span); + + if (per500) + adj = (s32)div64_s64((s64)num << 16, per500) >> 16; + } + if (adj) { + if (adj > ma * 115 / 100) + ma = ma * 115 / 100; + else if (adj < ma * 85 / 100) + ma = ma * 85 / 100; + else + ma = adj; + } + } + *suspend = ma < 70; + if (ma >= D1972_ILIM_MAX_MA) + return 0xff; + if (ma < 70) + return 0; + return (ma * 10 - 700) / 100; +} + +/* AppleD1972PMUPowerSource 0x80d15488: one ramp step from cur towards target. */ +static unsigned int d1972_step(unsigned int cur, unsigned int target, unsigned int max_step) +{ + unsigned int ma; + + if (target < cur) { + ma = cur - min(cur - target, max_step); + if (ma < 100) + return 0; + if (ma < 200) + return 100; + if (ma >= D1972_ILIM_MAX_MA) + return 70 + 0xff * 10; + return 70 + (ma - 70) / 10 * 10; + } + ma = min(cur + max_step, target); + if (cur < 100) + return 100; + if (ma > D1972_ILIM_MAX_MA) + return D1972_ILIM_MAX_MA; + return DIV_ROUND_UP(ma, 10) * 10; +} + +/* setInputCurrentLimit, 0x80d1526c: 0x1b bit 2, then 0x3f. */ +static int d1972_set_ilim(struct pmu_chg *c, unsigned int ma) +{ + bool suspend; + u8 code = d1972_ilim_code(c, ma, &suspend); + int ret; + + ret = d1972_set_suspend(c, suspend); + if (!ret) + ret = pmu_chg_write(c, D1972_ILIM, code); + if (ret) { + dev_err(c->dev, "failed to set input current limit to %umA: %d\n", ma, ret); + return ret; + } + c->last_ilim = code; + c->step_ma = ma > c->cur_ma ? ma - c->cur_ma : c->cur_ma - ma; + c->cur_ma = ma; + c->step_at = jiffies; + return 0; +} + +static int d1972_read_status(struct pmu_chg *c) +{ + int i, ret; + + /* iOS reads the block in one go; single reads are the proven path here */ + for (i = 0; i < D1972_NSTATUS; i++) { + ret = pmu_chg_read(c, PMU_STATUS0 + i, &c->status[i]); + if (ret) { + dev_err_ratelimited(c->dev, "status 0x%02x read failed: %d\n", + PMU_STATUS0 + i, ret); + return ret; + } + } + return 0; +} + +/* What the source is asked for: the cap (see the top of the file), or 100 mA with no cable. */ +static unsigned int d1972_target_ma(struct pmu_chg *c) +{ + unsigned int ma = c->online ? min(c->req_ma, pmu_chg_ceiling_ma(c)) : 100; + + if (c->backoff_ma && c->backoff_ma < ma) + ma = c->backoff_ma; + return ma; +} + +/* + * handleInterrupt 0x80d150e4 + 0x804c7b8c: a sag is 0x0f bit 0, a last code + * of 0x0d or more and 0x3f back at 0x03. Inside 500 ms of a step it caps + * the source 100 mA under that step for 300 s. + */ +static bool d1972_check_sag(struct pmu_chg *c) +{ + u8 rb; + + if (!(c->status[5] & D1972_S5_ILIM_ACT) || c->last_ilim < D1972_SAG_MIN_CODE) + return false; + if (pmu_chg_read(c, D1972_ILIM, &rb) || rb != D1972_ILIM_SAGGED) + return false; + + c->last_ilim = D1972_ILIM_SAGGED; + if (c->cur_ma > 100 && + time_before(jiffies, c->step_at + msecs_to_jiffies(D1972_SAG_WINDOW_MS))) { + /* the ramp then sets the cap: a step down from the current limit */ + unsigned int cap = d1972_step(c->cur_ma, 100, 100); + + if (cap != c->backoff_ma) { + c->backoff_ma = cap; + dev_warn(c->dev, "limiting USB input current to %u mA\n", cap); + } + c->backoff_at = jiffies; + } else { + /* the PMU holds 100 mA now: ramp again from there */ + dev_info(c->dev, "0x3f dropped to 0x03 at %u mA outside a step: ramping again\n", + c->cur_ma); + c->cur_ma = 100; + c->step_ma = 100; + } + return true; +} + +/* 0x804c9858: towards the target in steps, checking for a sag after each one. */ +static void d1972_ramp(struct pmu_chg *c) +{ + unsigned int target, next; + int guard = 64; + + if (!c->cur_ma) { + /* from nothing: 100 mA first, then the ramp after the debounce */ + target = d1972_target_ma(c); + if (d1972_set_ilim(c, target < 100 ? 0 : 100)) + return; + c->step_ma = 100; + msleep(D1972_DEBOUNCE_MS); + } + + while (guard--) { + target = d1972_target_ma(c); + if (c->cur_ma == target) + return; + if (target > c->cur_ma) { + next = d1972_step(c->cur_ma, target, 100); + } else if ((c->status[3] & D1972_S3_ILIM_REG) && + (c->status[5] & D1972_S5_ILIM_ACT)) { + /* in input regulation: down in 100 mA steps */ + next = max(d1972_step(c->cur_ma, 100, 100), 100U); + } else { + next = target; + } + if (d1972_set_ilim(c, next)) + return; + msleep(max(DIV_ROUND_UP(c->step_ma, 10), 1U)); + if (d1972_read_status(c)) + return; + d1972_check_sag(c); + } + dev_warn(c->dev, "input limit ramp did not settle at %u mA\n", c->cur_ma); +} + +/* 0x804c940c / 0x80d151d4: the charge current, 30 mA steps, capped by 0x43 at start. */ +static u8 d1972_ichg_code(struct pmu_chg *c) +{ + unsigned int ma = c->nlimits ? c->limits[min(c->limit_idx, c->nlimits - 1)] : UINT_MAX; + u8 code; + + if (c->hot) /* gauge guard, evaluated once per poll in d1972_work() */ + ma = 0; + code = ma > 0x762 ? D1972_ICHG_MASK : ma / D1972_ICHG_LSB_MA; + return min(code, c->ichg_cap); +} + +/* 0x804ca78c: restart a finished charge or an expired charge timer. */ +static void d1972_recharge(struct pmu_chg *c) +{ + bool end = c->status[1] & D1972_S1_CHG_END; + bool to = c->status[5] & D1972_S5_CHG_TO; + unsigned long now = jiffies; + int soc, st; + + if ((!end && !to) || !c->cur_ma) + return; + if (!pmu_chg_battery_prop(POWER_SUPPLY_PROP_STATUS, &st) && + st == POWER_SUPPLY_STATUS_CHARGING) + return; + if (pmu_chg_battery_prop(POWER_SUPPLY_PROP_CAPACITY, &soc)) + return; + + if (to) { + if (!c->to_at) + c->to_at = now | 1; + if (soc >= 90 && + (soc >= 95 || !c->attach_at || + time_after_eq(now, c->attach_at + D1972_RECHARGE_S * HZ))) + return; + if (time_after(now, c->to_at + D1972_TO_HOLD_S * HZ)) { + u8 v; + + dev_info(c->dev, "charge timer expired at %d%%: restarting it\n", soc); + if (!pmu_chg_read(c, D1972_CHG_TIMER, &v) && + !pmu_chg_write(c, D1972_CHG_TIMER, v & 0x08)) + pmu_chg_write(c, D1972_CHG_TIMER, v); + c->to_at = 0; + } + return; + } + + if (soc >= 95 || !c->attach_at || + time_after_eq(now, c->attach_at + D1972_RECHARGE_S * HZ)) + return; + dev_info(c->dev, "charge done at %d%%: starting a new charge\n", soc); + if (d1972_set_suspend(c, true)) + return; + msleep(D1972_DEBOUNCE_MS); + d1972_set_ilim(c, c->cur_ma); /* clears 0x1b bit 2 again */ +} + +static void d1972_log_status(struct pmu_chg *c) +{ + bool end = c->status[1] & D1972_S1_CHG_END; + bool to = c->status[5] & D1972_S5_CHG_TO; + bool tfault = c->status[1] & D1972_S1_TEMP; + + if (tfault != c->tfault) + dev_info(c->dev, "PMU battery temperature %s\n", + tfault ? "out of the charging range (HighOrLowTemperature)" : "back in range"); + if (end != c->chg_end) + dev_info(c->dev, "charge %s\n", end ? "done" : "no longer done"); + if (to != c->chg_to) + dev_info(c->dev, "charge timer %s\n", to ? "expired" : "running"); + c->tfault = tfault; + c->chg_end = end; + c->chg_to = to; +} + +static void d1972_disarm(struct pmu_chg *c) +{ + if (pmu_chg_write(c, D1972_ICHG, c->probe_ichg) || + d1972_set_suspend(c, c->probe_suspend) || + pmu_chg_write(c, D1972_ILIM, c->probe_code)) + return; /* restoration stays pending for the next poll */ + dev_info(c->dev, "disarmed: 0x3f, 0x43 and 0x1b bit 2 back to 0x%02x, 0x%02x, %d\n", + c->probe_code, c->probe_ichg, c->probe_suspend); + c->was_armed = false; + c->cur_ma = 0; + c->logged_ma = 0; + c->logged_code = 0; + c->logged_ichg = 0; + c->update_now = true; +} + +/* returns the delay to the next poll */ +static unsigned int d1972_work(struct pmu_chg *c, bool *changed) +{ + bool is_armed = pmu_chg_armed(c), online, update, was_hot; + unsigned int target; + u8 ichg; + + if (c->was_armed && !is_armed) { + d1972_disarm(c); + return POLL_MS; + } + if (d1972_read_status(c)) + return POLL_MS; + d1972_log_status(c); + + was_hot = c->hot; + if (pmu_chg_battery_hot_guarded(c) != was_hot) + c->update_now = true; /* rewrite the charge current now */ + + online = !!(c->status[0] & D1972_S0_VBUS); + *changed = online != c->online; + c->online = online; + if (*changed) { + /* 0x804c8eb4: a new cable starts without a cap */ + c->backoff_ma = 0; + c->to_at = 0; + c->attach_at = online ? jiffies | 1 : 0; + c->update_now = true; + } + + target = d1972_target_ma(c); + if (!is_armed) { + bool s; + u8 code = d1972_ilim_code(c, target, &s); + + ichg = d1972_ichg_code(c); + if (online && (code != c->logged_code || ichg != c->logged_ichg)) { + dev_info(c->dev, "disarmed: would set 0x43 = 0x%02x (%u mA charge), 0x3f = 0x%02x (%u mA asked, %u mA set)\n", + ichg, ichg * D1972_ICHG_LSB_MA, code, target, + d1972_code_to_ma(code)); + c->logged_code = code; + c->logged_ichg = ichg; + } + return POLL_MS; + } + c->was_armed = true; + + if (c->backoff_ma && + time_after(jiffies, c->backoff_at + D1972_BACKOFF_S * HZ)) { + dev_info(c->dev, "USB input current cap of %u mA expired\n", c->backoff_ma); + c->backoff_ma = 0; + } + + /* the charger update (0x804c940c): charge current first, then the input limit */ + update = c->update_now || time_after_eq(jiffies, c->update_at); + if (update) { + c->update_now = false; + c->update_at = jiffies + D1972_UPDATE_S * HZ; + ichg = d1972_ichg_code(c); + if (!pmu_chg_write(c, D1972_ICHG, ichg) && ichg != c->logged_ichg) { + dev_info(c->dev, "charge current %u mA (0x43 = 0x%02x)\n", + ichg * D1972_ICHG_LSB_MA, ichg); + c->logged_ichg = ichg; + } + } + + if (c->cur_ma) + d1972_check_sag(c); + d1972_ramp(c); + if (update && online) + d1972_recharge(c); + + if (c->cur_ma != c->logged_ma) { + dev_info(c->dev, "USB input current limit %u mA (0x3f = 0x%02x)\n", + c->cur_ma, c->last_ilim); + c->logged_ma = c->cur_ma; + } + if (time_before(jiffies, c->step_at + msecs_to_jiffies(D1972_SAG_WINDOW_MS))) + return D1972_SAG_POLL_MS; + return POLL_MS; +} + static void pmu_chg_work(struct work_struct *w) { struct pmu_chg *c = container_of(to_delayed_work(w), struct pmu_chg, work); bool is_armed = pmu_chg_armed(c), online, changed = false; + unsigned int delay = POLL_MS; u8 st, cur, target; mutex_lock(&c->lock); + if (c->chip->ios_policy) { + delay = d1972_work(c, &changed); + goto out; + } if (c->was_armed && !is_armed) { if (pmu_chg_write(c, c->chip->ilim_reg, c->probe_code)) goto out; /* Leave restoration pending for the next poll. */ @@ -430,13 +892,14 @@ static void pmu_chg_work(struct work_struct *w) mutex_unlock(&c->lock); if (changed) power_supply_changed(c->psy); - schedule_delayed_work(&c->work, msecs_to_jiffies(POLL_MS)); + schedule_delayed_work(&c->work, msecs_to_jiffies(delay)); } static int pmu_chg_get(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct pmu_chg *c = power_supply_get_drvdata(psy); + u8 v; switch (psp) { case POWER_SUPPLY_PROP_ONLINE: @@ -445,6 +908,18 @@ static int pmu_chg_get(struct power_supply *psy, enum power_supply_property psp, case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: val->intval = c->req_ma * 1000; return 0; + case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT: + /* 0x80d15234: 0x45 bits 5:0 x 30 mA */ + if (pmu_chg_read(c, D1972_ICHG_NOW, &v)) + return -EIO; + val->intval = (v & D1972_ICHG_MASK) * D1972_ICHG_LSB_MA * 1000; + return 0; + case POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT: + val->intval = c->limit_idx; + return 0; + case POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT_MAX: + val->intval = c->nlimits ? c->nlimits - 1 : 0; + return 0; default: return -EINVAL; } @@ -456,21 +931,34 @@ static int pmu_chg_set(struct power_supply *psy, enum power_supply_property psp, struct pmu_chg *c = power_supply_get_drvdata(psy); int ma = val->intval / 1000; - if (psp != POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT) + switch (psp) { + case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: + if (ma < 100 || ma > pmu_chg_ceiling_ma(c)) + return -ERANGE; + mutex_lock(&c->lock); + c->req_ma = ma; + c->logged_code = 0; + mutex_unlock(&c->lock); + break; + case POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT: + if (val->intval < 0 || (unsigned int)val->intval >= max(c->nlimits, 1U)) + return -ERANGE; + mutex_lock(&c->lock); + c->limit_idx = val->intval; + c->update_now = true; + mutex_unlock(&c->lock); + break; + default: return -EINVAL; - if (ma < 100 || ma > clamp(READ_ONCE(max_input_ma), 100, (int)c->chip->max_ma)) - return -ERANGE; - mutex_lock(&c->lock); - c->req_ma = ma; - c->logged_code = 0; - mutex_unlock(&c->lock); + } mod_delayed_work(system_wq, &c->work, 0); return 0; } static int pmu_chg_writeable(struct power_supply *psy, enum power_supply_property psp) { - return psp == POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT; + return psp == POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT || + psp == POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT; } static enum power_supply_property pmu_chg_props[] = { @@ -478,6 +966,14 @@ static enum power_supply_property pmu_chg_props[] = { POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, }; +static enum power_supply_property d1972_props[] = { + POWER_SUPPLY_PROP_ONLINE, + POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, + POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT, + POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT, + POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT_MAX, +}; + static char *pmu_chg_supplied_to[] = { "battery" }; static const struct power_supply_desc pmu_chg_desc = { @@ -490,6 +986,57 @@ static const struct power_supply_desc pmu_chg_desc = { .property_is_writeable = pmu_chg_writeable, }; +static const struct power_supply_desc d1972_desc = { + .name = "apple-pmu-usb", + .type = POWER_SUPPLY_TYPE_USB, + .properties = d1972_props, + .num_properties = ARRAY_SIZE(d1972_props), + .get_property = pmu_chg_get, + .set_property = pmu_chg_set, + .property_is_writeable = pmu_chg_writeable, +}; + +/* + * The ADT's /charger node: usb-input-limit-calibration is per unit (raw ADT + * bytes, little-endian, as the bootloader copies them; absent = none, as in + * iOS), charge-limits and usb-input-limit-max are per board. + */ +static int d1972_probe(struct pmu_chg *c) +{ + struct device_node *np = c->dev->of_node; + const u8 *cal; + int len, n; + u8 v; + + cal = of_get_property(np, "apple,usb-input-limit-calibration", &len); + if (cal && len >= 12) { + c->cal[0] = get_unaligned_le32(cal); + c->cal[1] = get_unaligned_le32(cal + 4); + c->cal[2] = get_unaligned_le32(cal + 8); + c->has_cal = c->cal[0] || c->cal[1] || c->cal[2]; + } + + n = of_property_count_u32_elems(np, "apple,charge-limits"); + if (n > 0) { + c->nlimits = min_t(int, n, ARRAY_SIZE(c->limits)); + of_property_read_u32_array(np, "apple,charge-limits", c->limits, c->nlimits); + } + + c->ilim_max_ma = ILIM_DEFAULT_MA; + of_property_read_u32(np, "apple,usb-input-limit-max", &c->ilim_max_ma); + c->ilim_max_ma = clamp_t(unsigned int, c->ilim_max_ma, 100, D1972_ILIM_MAX_MA - 1); + + /* 0x80d15000: the charge-current cap is what 0x43 holds now, 0x1f if unreadable */ + if (pmu_chg_read(c, D1972_ICHG, &c->probe_ichg)) + return -EIO; + c->ichg_cap = c->probe_ichg & D1972_ICHG_MASK; + if (pmu_chg_read(c, D1972_SUSPEND, &v)) + return -EIO; + c->probe_suspend = v & D1972_SUSPEND_USB; + c->update_at = jiffies; + return 0; +} + static int pmu_chg_probe(struct platform_device *pdev) { struct apple_pmu_i2c *pmu = dev_get_drvdata(pdev->dev.parent); @@ -516,6 +1063,14 @@ static int pmu_chg_probe(struct platform_device *pdev) pmu_chg_read(c, chip->status_reg, &st)) return -EIO; c->online = !!(st & chip->vbus_mask); + if (chip->ios_policy) { + ret = d1972_probe(c); + if (ret) + return ret; + c->req_ma = c->ilim_max_ma; + c->attach_at = c->online ? jiffies | 1 : 0; + c->update_now = true; + } if (c->online) pmu_chg_log_vbus(c, c->probe_code, pmu_chg_armed(c)); @@ -523,7 +1078,8 @@ static int pmu_chg_probe(struct platform_device *pdev) cfg.of_node = pdev->dev.of_node; cfg.supplied_to = pmu_chg_supplied_to; cfg.num_supplicants = ARRAY_SIZE(pmu_chg_supplied_to); - c->psy = devm_power_supply_register(&pdev->dev, &pmu_chg_desc, &cfg); + c->psy = devm_power_supply_register(&pdev->dev, + chip->ios_policy ? &d1972_desc : &pmu_chg_desc, &cfg); if (IS_ERR(c->psy)) return PTR_ERR(c->psy); platform_set_drvdata(pdev, c); @@ -532,10 +1088,17 @@ static int pmu_chg_probe(struct platform_device *pdev) if (ret) return ret; schedule_delayed_work(&c->work, msecs_to_jiffies(POLL_MS)); - dev_info(&pdev->dev, "%s: 0x%02x = 0x%02x (%u mA) at probe, VBUS %s, %s\n", - chip->name, chip->ilim_reg, c->probe_code, - chip->code_to_ma(c->probe_code), - c->online ? "on" : "off", pmu_chg_armed(c) ? "armed" : "disarmed (log only)"); + if (chip->ios_policy) + dev_info(&pdev->dev, "%s: 0x3f = 0x%02x, 0x43 = 0x%02x, 0x1b bit 2 = %d at probe; VBUS %s; calibration %08x %08x %08x%s; input max %u mA; %s\n", + chip->name, c->probe_code, c->probe_ichg, c->probe_suspend, + c->online ? "on" : "off", c->cal[0], c->cal[1], c->cal[2], + c->has_cal ? "" : " (none)", c->ilim_max_ma, + pmu_chg_armed(c) ? "armed" : "disarmed (log only)"); + else + dev_info(&pdev->dev, "%s: 0x%02x = 0x%02x (%u mA) at probe, VBUS %s, %s\n", + chip->name, chip->ilim_reg, c->probe_code, + chip->code_to_ma(c->probe_code), + c->online ? "on" : "off", pmu_chg_armed(c) ? "armed" : "disarmed (log only)"); return 0; } @@ -555,5 +1118,5 @@ static struct platform_driver pmu_chg_driver = { }; module_platform_driver(pmu_chg_driver); -MODULE_DESCRIPTION("Apple Dialog PMU (D1946/D1972) USB input current limit"); +MODULE_DESCRIPTION("Apple Dialog PMU (D1946/D1972) USB charging"); MODULE_LICENSE("GPL"); From 998f6cff5bb3fa64344289a60316c918881c61a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:07:37 +0100 Subject: [PATCH 38/43] ARM: dts: apple: n42: Give the charger its charge limits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ADT's /charger node has charge-limits = <900 570 420 270> (mA), the charge currents iOS picks between by thermal index. Pass them to the D1972 charger. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index 9f6cf26950e32f..fa9af0376e6c5c 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -283,13 +283,16 @@ }; /* - * D1972 USB input current limit (register 0x3f, 10 mA/LSB - * from 70 mA; VBUS online = 0x0a bit 6; sag = 0x03). - * Log-only until apple_pmu_charger.armed=1. + * D1972 charger: USB input current limit (0x3f), charge + * current (0x43). charge-limits is the ADT /charger + * property; the unit's usb-input-limit-calibration comes + * from the bootloader. Log-only until + * apple_pmu_charger.armed=1. */ charger@3f { compatible = "apple,pmu-d1972-charger"; reg = <0x3f>; + apple,charge-limits = <900 570 420 270>; }; }; From 1c61e769428ef6db144f52dd292519e1a6f02de6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:07:38 +0100 Subject: [PATCH 39/43] iio: gyro: Support the AP3GDL with device ID 0xd5 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/iio/gyro/st_gyro.h | 1 + drivers/iio/gyro/st_gyro_core.c | 72 +++++++++++++++++++++++++++++++++ drivers/iio/gyro/st_gyro_i2c.c | 5 +++ 3 files changed, 78 insertions(+) diff --git a/drivers/iio/gyro/st_gyro.h b/drivers/iio/gyro/st_gyro.h index f5332b6a02bc1f..cbe7c12cbf7d8e 100644 --- a/drivers/iio/gyro/st_gyro.h +++ b/drivers/iio/gyro/st_gyro.h @@ -19,6 +19,7 @@ #define LSM330DL_GYRO_DEV_NAME "lsm330dl_gyro" #define LSM330DLC_GYRO_DEV_NAME "lsm330dlc_gyro" #define L3GD20_GYRO_DEV_NAME "l3gd20" +#define AP3GDL_D5_GYRO_DEV_NAME "ap3gdl-d5" #define L3GD20H_GYRO_DEV_NAME "l3gd20h" #define L3G4IS_GYRO_DEV_NAME "l3g4is_ui" #define LSM330_GYRO_DEV_NAME "lsm330_gyro" diff --git a/drivers/iio/gyro/st_gyro_core.c b/drivers/iio/gyro/st_gyro_core.c index eaa35da42b332b..84baed1ad429b0 100644 --- a/drivers/iio/gyro/st_gyro_core.c +++ b/drivers/iio/gyro/st_gyro_core.c @@ -219,6 +219,78 @@ static const struct st_sensor_settings st_gyro_sensors_settings[] = { .multi_read_bit = true, .bootime = 2, }, + { + .wai = 0xd5, + .wai_addr = ST_SENSORS_DEFAULT_WAI_ADDRESS, + .sensors_supported = { AP3GDL_D5_GYRO_DEV_NAME }, + .ch = (struct iio_chan_spec *)st_gyro_16bit_channels, + .odr = { + .addr = 0x20, + .mask = 0xc0, + .odr_avl = { + { .hz = 95, .value = 0x00, }, + { .hz = 190, .value = 0x01, }, + { .hz = 380, .value = 0x02, }, + { .hz = 760, .value = 0x03, }, + }, + }, + .pw = { + .addr = 0x20, + .mask = 0x08, + .value_on = ST_SENSORS_DEFAULT_POWER_ON_VALUE, + .value_off = ST_SENSORS_DEFAULT_POWER_OFF_VALUE, + }, + .enable_axis = { + .addr = ST_SENSORS_DEFAULT_AXIS_ADDR, + .mask = ST_SENSORS_DEFAULT_AXIS_MASK, + }, + .fs = { + .addr = 0x23, + .mask = 0x30, + .fs_avl = { + [0] = { + .num = ST_GYRO_FS_AVL_250DPS, + .value = 0x00, + .gain = IIO_DEGREE_TO_RAD(8750), + }, + [1] = { + .num = ST_GYRO_FS_AVL_500DPS, + .value = 0x01, + .gain = IIO_DEGREE_TO_RAD(17500), + }, + [2] = { + .num = ST_GYRO_FS_AVL_2000DPS, + .value = 0x02, + .gain = IIO_DEGREE_TO_RAD(70000), + }, + }, + }, + .bdu = { + .addr = 0x23, + .mask = 0x80, + }, + .drdy_irq = { + .int2 = { + .addr = 0x22, + .mask = 0x08, + }, + /* + * The sensor has IHL (active low) and open + * drain settings, but only for INT1 and not + * for the DRDY line on INT2. + */ + .stat_drdy = { + .addr = ST_SENSORS_DEFAULT_STAT_ADDR, + .mask = 0x07, + }, + }, + .sim = { + .addr = 0x23, + .value = BIT(0), + }, + .multi_read_bit = true, + .bootime = 2, + }, { .wai = 0xd4, .wai_addr = ST_SENSORS_DEFAULT_WAI_ADDRESS, diff --git a/drivers/iio/gyro/st_gyro_i2c.c b/drivers/iio/gyro/st_gyro_i2c.c index 5a10a3556ab054..b852db40881eea 100644 --- a/drivers/iio/gyro/st_gyro_i2c.c +++ b/drivers/iio/gyro/st_gyro_i2c.c @@ -38,6 +38,10 @@ static const struct of_device_id st_gyro_of_match[] = { .compatible = "st,l3gd20-gyro", .data = L3GD20_GYRO_DEV_NAME, }, + { + .compatible = "apple,ap3gdl-d5", + .data = AP3GDL_D5_GYRO_DEV_NAME, + }, { .compatible = "st,l3gd20h-gyro", .data = L3GD20H_GYRO_DEV_NAME, @@ -98,6 +102,7 @@ static const struct i2c_device_id st_gyro_id_table[] = { { LSM330DL_GYRO_DEV_NAME }, { LSM330DLC_GYRO_DEV_NAME }, { L3GD20_GYRO_DEV_NAME }, + { AP3GDL_D5_GYRO_DEV_NAME }, { L3GD20H_GYRO_DEV_NAME }, { L3G4IS_GYRO_DEV_NAME }, { LSM330_GYRO_DEV_NAME }, From 01e2792f3dbe1cce28b1849a7a58c7982bc0d0d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:07:56 +0100 Subject: [PATCH 40/43] ARM: dts: apple: Describe the iPhone 5 gyroscope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index fa9af0376e6c5c..0d32282c29f060 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -10,6 +10,8 @@ #include "s5l8950x.dtsi" +#include + / { aliases { serial0 = &uart6; @@ -238,6 +240,20 @@ #size-cells = <0>; status = "okay"; + gyroscope@6a { + compatible = "apple,ap3gdl-d5"; + reg = <0x6a>; + interrupt-parent = <&gpio>; + /* The ST binding puts INT2 (data ready) first. */ + interrupts = <67 IRQ_TYPE_LEVEL_HIGH>, + <225 IRQ_TYPE_LEVEL_HIGH>; + st,drdy-int-pin = <2>; + mount-matrix = "-1", "0", "0", + "0", "1", "0", + "0", "0", "-1"; + status = "okay"; + }; + pmu: pmu@74 { compatible = "apple,pmu-d1972"; reg = <0x74>; From c1dcc96dcbb50a3ee50ab0122bd5be29871c5236 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:07:56 +0100 Subject: [PATCH 41/43] dt-bindings: iio: Describe the Apple AP3GDL gyroscope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- Documentation/devicetree/bindings/iio/st,st-sensors.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/iio/st,st-sensors.yaml b/Documentation/devicetree/bindings/iio/st,st-sensors.yaml index 71c1ee33a393e6..10db033518821c 100644 --- a/Documentation/devicetree/bindings/iio/st,st-sensors.yaml +++ b/Documentation/devicetree/bindings/iio/st,st-sensors.yaml @@ -56,6 +56,7 @@ properties: enum: - st,l3g4200d-gyro - st,l3g4is-gyro + - apple,ap3gdl-d5 - st,l3gd20-gyro - st,l3gd20h-gyro - st,lsm330-gyro From 52bd5e434c5fc19a929d1908d093d331e1a42bdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:07:57 +0100 Subject: [PATCH 42/43] ARM: apple: Pet the S5L watchdog from Linux MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Register the wdt-version 1 watchdog (the 24 MHz counter that is already the clocksource) as a watchdog device, so a hung system is reset within the timeout and a healthy one runs for ever: the kernel pets it from boot until userspace (systemd's RuntimeWatchdogSec=) opens /dev/watchdog. A ping moves BITE_TIME to CUR_TIME + timeout; CUR_TIME is never written, being the clocksource. The comparator fires when the counter reaches BITE_TIME, not while it is above it (iBoot enables RESET_EN with CUR_TIME at 0x80000000 and a small BITE_TIME), so a bite past the 32-bit wrap is correct and timeouts go up to 178 s. On the A6, ENABLE stays set: the counter only runs with it. It is started at boot whatever the boot loader armed, with no way out: this hardware has no power off, so a halt ends in the bite as well. The restart path keeps its own bite. apple_wdt_timeout= (60 s) sets the timeout; 0 leaves the watchdog as the boot loader left it. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/mach-apple/apple_wdt_clkevt.c | 110 +++++++++++++++++++++++++ 1 file changed, 110 insertions(+) diff --git a/arch/arm/mach-apple/apple_wdt_clkevt.c b/arch/arm/mach-apple/apple_wdt_clkevt.c index 6863ba9ba95481..5ef2b36245a60d 100644 --- a/arch/arm/mach-apple/apple_wdt_clkevt.c +++ b/arch/arm/mach-apple/apple_wdt_clkevt.c @@ -48,6 +48,7 @@ #include #include #include +#include #include #include @@ -292,3 +293,112 @@ static int __init apple_wdt_restart_init(void) return 0; } device_initcall(apple_wdt_restart_init); + +/* + * The watchdog as a watchdog: /dev/watchdog for systemd (RuntimeWatchdogSec=) + * and the kernel's own pinger until userspace opens it, so a healthy system + * runs for ever and a hung one is reset -- into iOS, on a phone started from + * it -- within the timeout, with no button pressed. + * + * A ping moves the bite forward: BITE_TIME = CUR_TIME + timeout. CUR_TIME is + * never written: it is the clocksource. The comparator fires when the counter + * reaches BITE_TIME, not while it is above it (iBoot enables RESET_EN with + * CUR_TIME at 0x80000000 and a small BITE_TIME, and nothing resets), so a bite + * past the 32-bit wrap (about every 179 s) is simply where the counter gets to + * after wrapping; the reboot notifier above relies on the same. Timeouts stop + * at 178 s, one turn of the counter. + * + * It is started at boot whatever the boot loader left (m1n1 hands over with a + * window armed), and it has no way out: a poweroff or halt, which this + * hardware cannot do, ends in the bite too. apple_wdt_timeout=0 on the + * command line leaves the watchdog as the boot loader left it, for debugging. + */ +static unsigned int apple_wdt_timeout = 60; +core_param(apple_wdt_timeout, apple_wdt_timeout, uint, 0444); + +static u32 apple_wdt_ctrl_on(void) +{ + /* the A6's counter only runs with ENABLE (see apple_wdt_map()) */ + return of_machine_is_compatible("apple,s5l8950x") ? WDT_CTRL_ENABLE : 0; +} + +static int apple_wdt_ping(struct watchdog_device *wdd) +{ + u32 now = readl_relaxed(wdt_base + WDT_CUR_TIME); + + writel(now + wdd->timeout * APPLE_WDT_REF_HZ, wdt_base + WDT_BITE_TIME); + return 0; +} + +static int apple_wdt_start(struct watchdog_device *wdd) +{ + apple_wdt_ping(wdd); + writel(apple_wdt_ctrl_on() | WDT_CTRL_RESET_EN, wdt_base + WDT_CTRL); + (void)readl(wdt_base + WDT_CTRL); + return 0; +} + +static int apple_wdt_stop(struct watchdog_device *wdd) +{ + writel(apple_wdt_ctrl_on(), wdt_base + WDT_CTRL); + (void)readl(wdt_base + WDT_CTRL); + return 0; +} + +static int apple_wdt_set_timeout(struct watchdog_device *wdd, unsigned int timeout) +{ + wdd->timeout = timeout; + return apple_wdt_ping(wdd); +} + +static const struct watchdog_ops apple_wdt_ops = { + .owner = THIS_MODULE, + .start = apple_wdt_start, + .stop = apple_wdt_stop, + .ping = apple_wdt_ping, + .set_timeout = apple_wdt_set_timeout, +}; + +static const struct watchdog_info apple_wdt_info = { + .identity = "Apple S5L wdt-version 1", + .options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE, +}; + +static struct watchdog_device apple_wdt_wdd = { + .info = &apple_wdt_info, + .ops = &apple_wdt_ops, + .min_timeout = 1, + .max_timeout = U32_MAX / APPLE_WDT_REF_HZ, /* 178 s */ +}; + +static int __init apple_wdt_watchdog_init(void) +{ + u32 ctrl; + int ret; + + if (!wdt_base) + return 0; + ctrl = readl_relaxed(wdt_base + WDT_CTRL); + if (!apple_wdt_timeout) { + pr_info("watchdog: left as the boot loader left it (CTRL %#x)\n", ctrl); + return 0; + } + apple_wdt_wdd.timeout = clamp(apple_wdt_timeout, apple_wdt_wdd.min_timeout, + apple_wdt_wdd.max_timeout); + watchdog_set_nowayout(&apple_wdt_wdd, true); + /* No watchdog_stop_on_reboot(): a halt or poweroff must still end in the + * bite, and a restart keeps the 10 s net the reboot notifier arms. */ + apple_wdt_start(&apple_wdt_wdd); + set_bit(WDOG_HW_RUNNING, &apple_wdt_wdd.status); + ret = watchdog_register_device(&apple_wdt_wdd); + if (ret) { + /* nobody would pet it: back to what the boot loader left */ + writel(ctrl, wdt_base + WDT_CTRL); + pr_err("watchdog: not registered (%d); CTRL back to %#x\n", ret, ctrl); + return 0; + } + pr_info("watchdog: armed, %u s, petted by the kernel until userspace opens /dev/watchdog (boot CTRL %#x)\n", + apple_wdt_wdd.timeout, ctrl); + return 0; +} +device_initcall(apple_wdt_watchdog_init); From 0b9c97a14e21d8eecac6d960db332b54f55bbe0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:07:57 +0100 Subject: [PATCH 43/43] ARM: apple: Power off and halt through the S5L watchdog too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The board has no way to cut its own power, so a power off halted and waited for the watchdog's timeout. A phone booted from iOS that powers off belongs back in iOS: restart through the watchdog at once, as a low-priority power-off handler that a real one would replace. Halt and power off also get the 10 s net the reboot notifier arms for a restart. For the flights, a ping whose bite lies past the counter's 32-bit wrap is logged, and debugfs apple-wdt/state shows the counter, the bite and CTRL. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/mach-apple/apple_wdt_clkevt.c | 39 ++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/arch/arm/mach-apple/apple_wdt_clkevt.c b/arch/arm/mach-apple/apple_wdt_clkevt.c index 5ef2b36245a60d..27fc1397cffe46 100644 --- a/arch/arm/mach-apple/apple_wdt_clkevt.c +++ b/arch/arm/mach-apple/apple_wdt_clkevt.c @@ -37,6 +37,7 @@ #define pr_fmt(fmt) "apple-wdt: " fmt #include +#include #include #include #include @@ -47,6 +48,7 @@ #include #include #include +#include #include #include @@ -260,18 +262,30 @@ static int apple_wdt_restart(struct sys_off_data *data) */ static int apple_wdt_reboot_notify(struct notifier_block *nb, unsigned long action, void *data) { - if (action == SYS_RESTART) { + if (action == SYS_RESTART || action == SYS_POWER_OFF || action == SYS_HALT) { u32 now = readl_relaxed(wdt_base + WDT_CUR_TIME); u32 ctrl = of_machine_is_compatible("apple,s5l8950x") ? (WDT_CTRL_ENABLE | WDT_CTRL_RESET_EN) : WDT_CTRL_RESET_EN; writel_relaxed(now + 10 * APPLE_WDT_REF_HZ, wdt_base + WDT_BITE_TIME); writel(ctrl, wdt_base + WDT_CTRL); - pr_info("restart: the watchdog will reset the machine in 10 s at the latest\n"); + pr_info("%s: the watchdog will reset the machine in 10 s at the latest\n", + action == SYS_RESTART ? "restart" : action == SYS_POWER_OFF ? "power off" : "halt"); } return NOTIFY_DONE; } +/* + * Power off: this board has no way to cut its own power, and a phone booted + * from iOS that "powers off" belongs back in iOS. So a power off is the + * restart, at once -- at a low priority, so a real power-off driver wins. + */ +static int apple_wdt_power_off(struct sys_off_data *data) +{ + pr_emerg("power off: no power-off control here; restarting through the watchdog\n"); + return apple_wdt_restart(data); +} + static struct notifier_block apple_wdt_reboot_nb = { .notifier_call = apple_wdt_reboot_notify, .priority = INT_MAX, /* before anything else gets to hang */ @@ -290,6 +304,10 @@ static int __init apple_wdt_restart_init(void) pr_err("no restart handler: %ld\n", PTR_ERR(h)); else pr_info("restart through the watchdog's bite\n"); + h = register_sys_off_handler(SYS_OFF_MODE_POWER_OFF, SYS_OFF_PRIO_LOW, + apple_wdt_power_off, NULL); + if (IS_ERR(h)) + pr_err("no power-off handler: %ld\n", PTR_ERR(h)); return 0; } device_initcall(apple_wdt_restart_init); @@ -325,10 +343,23 @@ static u32 apple_wdt_ctrl_on(void) static int apple_wdt_ping(struct watchdog_device *wdd) { u32 now = readl_relaxed(wdt_base + WDT_CUR_TIME); + u32 bite = now + wdd->timeout * APPLE_WDT_REF_HZ; - writel(now + wdd->timeout * APPLE_WDT_REF_HZ, wdt_base + WDT_BITE_TIME); + writel(bite, wdt_base + WDT_BITE_TIME); + /* the bite lies past the counter's wrap: said once per turn or so */ + if (bite < now) + pr_info("watchdog: ping across the wrap: CUR %#010x BITE %#010x\n", now, bite); + return 0; +} + +/* debugfs apple-wdt/state: the counter, the bite and CTRL, for the flights */ +static int apple_wdt_state_show(struct seq_file *s, void *unused) +{ + seq_printf(s, "cur %#010x bite %#010x ctrl %#x\n", readl_relaxed(wdt_base + WDT_CUR_TIME), + readl_relaxed(wdt_base + WDT_BITE_TIME), readl_relaxed(wdt_base + WDT_CTRL)); return 0; } +DEFINE_SHOW_ATTRIBUTE(apple_wdt_state); static int apple_wdt_start(struct watchdog_device *wdd) { @@ -399,6 +430,8 @@ static int __init apple_wdt_watchdog_init(void) } pr_info("watchdog: armed, %u s, petted by the kernel until userspace opens /dev/watchdog (boot CTRL %#x)\n", apple_wdt_wdd.timeout, ctrl); + debugfs_create_file("state", 0444, debugfs_create_dir("apple-wdt", NULL), NULL, + &apple_wdt_state_fops); return 0; } device_initcall(apple_wdt_watchdog_init);