From b63f4ba93789c77287ce575c533c57a745e3f019 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 01/37] 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 d76d731a6afc4a87e5f80ac95d63777443dd2da5 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 02/37] 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 77fead475816a7b4d82e5babde5d3a088b1803c9 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 03/37] 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..df11961ac0f7cd --- /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 (0x3f700000, 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 0300f534b5a7fdbfad793e859bd0d84b7f19b37b 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 04/37] 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 8bb1bdafb0cf49..55d68b10e74f18 100644 --- a/arch/arm/configs/orchard_applearmv7_defconfig +++ b/arch/arm/configs/orchard_applearmv7_defconfig @@ -522,6 +522,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 e2099a0223d4a19c0c3374a6e798e48f07a22879 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 05/37] 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 5d5d7853eacc75ffb4c5c75b74943fdad66629b1 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 06/37] Input: apple-z2: Boot the N42 with the in-kernel N1 loader MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The P105 already uploads its N1 firmware in the kernel. The N42 supplies a raw HBPP firmware packet and separate proximity and panel calibration blobs. Load the blobs from the DT or firmware files, and take the reference clock divider from apple,ref-clk-div-val. The scan-start SET report (0xbf) takes its value from the per-board apple,scan-start-report property. 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 1e5bd28bafde71..b060b0895ef84f 100644 --- a/drivers/input/touchscreen/apple-z2.c +++ b/drivers/input/touchscreen/apple-z2.c @@ -91,6 +91,8 @@ struct hx_touch_data { struct delayed_work lost_work; unsigned lost_frame; const char *firmware_name; + bool raw_packet; + u32 ref_clk_div; u32 execute_addr; u32 cal_addr; u32 fll_mval; @@ -819,7 +821,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; @@ -832,7 +834,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; @@ -926,7 +928,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 */ @@ -1076,6 +1078,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) { @@ -1107,9 +1135,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; } @@ -1133,6 +1169,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) { @@ -1162,6 +1217,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); @@ -1245,6 +1301,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) || @@ -1379,6 +1438,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" }, { }, @@ -1386,6 +1446,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 29045abcbb8e4ac9de9a35eea86ecee3ce7e1a3f 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 07/37] 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 | 402 ++++++++++++++++++++++++ 1 file changed, 402 insertions(+) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index 0d8858f3ece075..f5700a87df45e1 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,355 @@ &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@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@f700000 { + compatible = "apple,s5l8950x-dwi", "apple,s5l8940x-dwi"; + reg = <0xf700000 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.d1972_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 0b8d3eb53db893ce0ab32aaf58f787be6ab811e7 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 08/37] 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 f981ec9837662e140ae78321d503a6b412d9c42b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Fri, 4 Dec 2026 13:23:23 +0100 Subject: [PATCH 09/37] ARM: dts: apple: iPhone 5: Report the ringer switch as KEY_MUTE MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Report the side switch the way the iPad mini (P105) and iPad 2 (K93) do: KEY_MUTE while on silent instead of the SW_MUTE_DEVICE switch event, so desktops that bind the mute key (Omarchy's mute switch handler) act on it. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index f5700a87df45e1..c89be3a107e1a8 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -59,8 +59,7 @@ ringer-switch { label = "Ringer Switch"; gpios = <&gpio 4 1>; - linux,input-type = <5>; - linux,code = <14>; + linux,code = <113>; /* KEY_MUTE, held while on silent */ debounce-interval = <50>; }; }; From b429a8214302d16d660aa33c3410eccd75f804ee 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 10/37] 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 8752d2a9708959b94899411d9b31d3574f1f0bf1 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 11/37] 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 411a71ac319795ed20bf5ac4dd849b80b66229d4 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 12/37] 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: 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 | 4 + drivers/mtd/devices/mtd-apple-h2fmi.c | 132 ++++++++++++++++++++++++-- 2 files changed, 127 insertions(+), 9 deletions(-) diff --git a/drivers/mtd/devices/Kconfig b/drivers/mtd/devices/Kconfig index f4be1b409392be..9ed5f748179254 100644 --- a/drivers/mtd/devices/Kconfig +++ b/drivers/mtd/devices/Kconfig @@ -223,6 +223,10 @@ 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 never reset to SDR. + If unsure, say N. config MTD_APPLE_H2FMI_P105_CAPTURE diff --git a/drivers/mtd/devices/mtd-apple-h2fmi.c b/drivers/mtd/devices/mtd-apple-h2fmi.c index 6d6fe2cc816016..8c654b51299eef 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,36 @@ #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. no_sdr_reset: the packages are never reset to SDR (NAND + * reset 0xff, set feature 0xef), neither at probe nor to recover from a + * failed transaction. The driver only + * runs on the DDR interface iBoot leaves. + */ +struct h2fmi_soc { + bool read_only; + bool no_sdr_reset; +}; + +/* 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, + .no_sdr_reset = true, +}; + #define H2FMI_BUSES 2 #define H2FMI_PAGE_MASK (H2FMI_PAGE_DATA - 1) @@ -176,8 +202,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 +238,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 +756,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 +1068,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 +1313,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 +1362,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 +1380,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 +1544,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 +1564,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->no_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 +1648,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 +1658,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\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 +1681,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 +1708,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 +1727,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 9bd0f0cf666ec9795634a96609e7212fbcf218a4 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 13/37] 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 8c654b51299eef..04b4820c149af2 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 no_sdr_reset; + 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, .no_sdr_reset = true, + .clean_by_status = true, }; #define H2FMI_BUSES 2 @@ -208,6 +210,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; }; /* @@ -1157,6 +1161,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) { @@ -1186,7 +1224,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); @@ -1226,7 +1265,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); @@ -1622,6 +1662,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->no_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 d951831e9e1b21668152b98e0d818b659f1ae603 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 14/37] 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 | 42 +++++++++++++++++++++++++++++++++-- drivers/mtd/apple-sftl.h | 1 + 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c index d4877223288dbe..7ac77725431845 100644 --- a/drivers/mtd/apple-sftl-core.c +++ b/drivers/mtd/apple-sftl-core.c @@ -63,6 +63,7 @@ enum sftl_block_role { * lanes in order, four logical pages per physical page. */ struct sftl_geometry { + bool n42_install; /* N42 16 GB installation layout */ u16 buses, caus, lanes; u16 blocks; /* physical blocks per CAU */ u16 pages; /* MLC pages per block */ @@ -140,10 +141,32 @@ static const struct sftl_geometry sftl_32gb = { .degrade_remnants = true, .lpp = 2, .reused_names = true, .moved_epochs = 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 = { + .n42_install = true, + .lpp = 4, + .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_32gb, + &sftl_16gb_n42, }; struct sftl_run { @@ -555,8 +578,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; @@ -707,8 +735,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); @@ -1087,6 +1121,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 @@ -3298,6 +3335,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->n42_install = sftl->geo->n42_install; 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.h b/drivers/mtd/apple-sftl.h index 6c16a6ae6fbdb8..205e7ce060def8 100644 --- a/drivers/mtd/apple-sftl.h +++ b/drivers/mtd/apple-sftl.h @@ -53,6 +53,7 @@ void apple_sftl_set_checkpoint_ops(struct apple_sftl *sftl, const struct apple_sftl_checkpoint_ops *ops, void *priv); struct apple_sftl_info { + bool n42_install; bool read_only; u32 logical_pages; u32 disk_pages; From 2978a192df450754805150490537cf142e9da538 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 15/37] 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 | 50 +++++++++++++++++- drivers/mtd/apple-sftl-test.c | 95 +++++++++++++++++++++++++++++------ 2 files changed, 128 insertions(+), 17 deletions(-) diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c index 7ac77725431845..7fc0b9af70e832 100644 --- a/drivers/mtd/apple-sftl-core.c +++ b/drivers/mtd/apple-sftl-core.c @@ -87,6 +87,7 @@ struct sftl_geometry { * the device: it is read-only, while a 64 GB * checkpoint would persist a wrong acceptance. */ + bool equal_sequences; /* replay a record that repeats the previous sequence */ }; /* 64 GB Hynix PPN with 13G36 (iOS 9.3.5) on the media. */ @@ -160,6 +161,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, + .equal_sequences = true, }; static const struct sftl_geometry *const sftl_geometries[] = { @@ -234,6 +236,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) @@ -1754,6 +1757,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; @@ -1863,14 +1905,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 + sftl->lpp && 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 a266329fe5a417..6b5d6868a8ff6d 100644 --- a/drivers/mtd/apple-sftl-test.c +++ b/drivers/mtd/apple-sftl-test.c @@ -3519,10 +3519,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 */ @@ -3551,6 +3557,7 @@ struct t16_fixture { bool trim_bad_count; /* the first TRIM above the checkpoint claims too many ranges */ bool trim_last; /* omit ordinary records after the TRIM slots */ bool closed_trim; /* one TRIM after the data run in the new closed block */ + bool open_repeat; /* an open block starts on the summary's last sequence */ }; /* Fixed records before the ranges: the native base, statistics and tables. */ @@ -3569,15 +3576,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; } @@ -3593,7 +3600,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) @@ -3609,10 +3616,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++) @@ -3620,9 +3627,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; } @@ -3644,8 +3651,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); @@ -3655,7 +3662,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; @@ -3887,6 +3894,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, @@ -3896,7 +3915,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); @@ -3904,12 +3923,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, @@ -3930,6 +3949,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; @@ -4379,6 +4400,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), @@ -4454,6 +4516,7 @@ static struct kunit_case apple_sftl_cases[] = { KUNIT_CASE(sftl_test_16gb_trim_flag1), KUNIT_CASE(sftl_test_16gb_closed_trim_flag1), KUNIT_CASE(sftl_test_16gb_hidden_tail), + KUNIT_CASE(sftl_test_n42_repeated_sequence), {} }; From 70b7dd0a9a8b5e775012868d9d9d2de3462fc410 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 16/37] 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. Both N41 and N42 enable the same read-only controller. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 29 +++++++++ arch/arm/boot/dts/apple/s5l8950x.dtsi | 80 +++++++++++++++++++++++++ 2 files changed, 109 insertions(+) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index c89be3a107e1a8..e7c76d227d43b2 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -78,6 +78,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.dtsi b/arch/arm/boot/dts/apple/s5l8950x.dtsi index 84d98ff6de92ff..30ea2cbef07d5e 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,33 @@ 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. 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 0fe1ae7fdc4b65ef7a6d7158b738f0dce39176bc 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 17/37] 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 6b5d6868a8ff6d..9ce7420714cb0e 100644 --- a/drivers/mtd/apple-sftl-test.c +++ b/drivers/mtd/apple-sftl-test.c @@ -3899,8 +3899,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 48186062aab3a09408a177d404c9012ccd837c58 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 18/37] 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 | 354 ++++++++++++++++------- 3 files changed, 262 insertions(+), 104 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 ce22b65d1e7640..cc8c3c25f4befa 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)); @@ -2387,6 +2538,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)); @@ -2484,7 +2636,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); @@ -2501,6 +2654,7 @@ 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_DESCRIPTION("Apple S5L8940X SGX543MP2 and S5L8950X SGX543MP3: microkernel, queues, render node"); +MODULE_FIRMWARE("apple/sgx543.fw"); +MODULE_FIRMWARE("apple/sgx543-s5l8950x.fw"); MODULE_LICENSE("GPL"); From 2158bcaec5cd80991de472d9f0a1e64ab1483e2d 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 19/37] 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 The A6 ADT lists the GPU at offset 0x5100000, interrupt 49. Its PMGR device-clocks table places GFX_SYS and GFX at power-state indices 9 and 10. Describe both gates in enable order and select the SGX543MP3 compatible so the driver loads the A6 microkernel. 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 e7c76d227d43b2..64de4ef8864ff0 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -458,3 +458,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 30ea2cbef07d5e..1f0f85b764572f 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 a9081149dcc2c0eeb3cdd5f7100da8beef9b0bea 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 20/37] 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 cc8c3c25f4befa..8ae906fd55db09 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 @@ -2539,6 +2554,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 7f2499b67a579a6bead1de094782b20874ac2b4d 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 21/37] 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. 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 --- drivers/gpu/drm/apple-sgx/apple_sgx_drm.c | 35 ++++ drivers/gpu/drm/apple-sgx/apple_sgx_kms.c | 229 +++++++++++++++++++++- 2 files changed, 259 insertions(+), 5 deletions(-) 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 62796f168f3e6e..dd16990bd87ae4 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; @@ -108,6 +130,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 +278,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; +} + 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 +391,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 +457,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 +519,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 +610,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 +641,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 +792,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 +801,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: %lu VBIs, last period %u us (min %u, max %u); int enable 0x%08x status 0x%08x\n", + kms->vbi_irq, 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 +840,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 +947,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 656b58cf501ba213ecfdb9c3dec6a3993f5989cc 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 22/37] ARM: dts: apple: Describe the iPhone 5 display-pipe VBI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The N42 CLCD ADT gives the pipe interrupt at index zero and locates its general control registers at offset 0x1000 from the display base. Supply both resources so the display driver can latch a flip at vblank. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index 64de4ef8864ff0..af46b9e9620b2a 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -437,7 +437,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"; }; From c85f444543b0b956ef9e8e0398e537c0f8c1785c 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 23/37] 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 dd16990bd87ae4..2eb995d29ede44 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 */ @@ -132,14 +134,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; @@ -278,19 +281,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) @@ -301,6 +305,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; @@ -308,17 +313,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. */ @@ -396,21 +422,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)); @@ -463,19 +492,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; } @@ -493,10 +524,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; } @@ -616,15 +651,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; } @@ -813,7 +850,7 @@ static int sgx_kms_screen_show(struct seq_file *m, void *unused) kms->vbi_irq, 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"); @@ -952,8 +989,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 2c04f6e504c6738594f2b3ea31464853652d22b1 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 24/37] 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 2eb995d29ede44..ca4718f4a09f81 100644 --- a/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c +++ b/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c @@ -144,7 +144,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; @@ -402,6 +406,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); @@ -413,6 +423,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; @@ -492,7 +518,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; @@ -508,7 +534,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); @@ -520,6 +545,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); @@ -528,8 +554,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; @@ -602,6 +628,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; @@ -852,6 +882,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 47ee7d2631c5dd8e735d1989f5fa4bde0e96f62f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Fri, 4 Dec 2026 10:13:19 +0100 Subject: [PATCH 25/37] drm: apple-sgx: Keep the layer on a re-committed buffer; never show an uncopied boot framebuffer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A commit that changes only the output's transform re-commits the same framebuffer. The update pointed the layer at a buffer only when the framebuffer changed, so this commit went back to copies: the whole plane onto the boot framebuffer through the 2D engine, then the layer pointed there. Point at the buffer whenever it can be shown directly. When the copy fails (the 2D engine is down without a microkernel), leave the layer where it is. Pointing it at the boot framebuffer showed what the bootloader drew there, the boot logo, for as long as the screen was turned. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/gpu/drm/apple-sgx/apple_sgx_kms.c | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c b/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c index ca4718f4a09f81..29461db9ccc598 100644 --- a/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c +++ b/drivers/gpu/drm/apple-sgx/apple_sgx_kms.c @@ -253,8 +253,8 @@ static bool sgx_kms_over(struct apple_sgx_kms *kms, const struct drm_plane_state * same), the overlay blended over it in the same job. Its edges go out to * 16 pixels in the framebuffer's x, and in its y too when that is the * screen's x. Under ov_lock. */ -static void sgx_kms_show(struct apple_sgx_kms *kms, const struct drm_plane_state *state, - const struct drm_rect *clip) +static int sgx_kms_show(struct apple_sgx_kms *kms, const struct drm_plane_state *state, + const struct drm_rect *clip) { struct drm_framebuffer *fb = state->fb; unsigned int rot = ilog2(state->rotation & DRM_MODE_ROTATE_MASK); @@ -272,7 +272,7 @@ static void sgx_kms_show(struct apple_sgx_kms *kms, const struct drm_plane_state r.y2 = round_up(r.y2, SGX_KMS_ALIGN_PX); } if (!drm_rect_intersect(&r, &src)) - return; + return 0; /* where it lands: the plane's source turned onto the screen */ on = r; drm_rect_translate(&on, -sx, -sy); @@ -283,6 +283,7 @@ static void sgx_kms_show(struct apple_sgx_kms *kms, const struct drm_plane_state sgx_kms_over(kms, state, &r, &over) ? &over : NULL); if (ret) drm_err_ratelimited(fb->dev, "the 2D engine's copy to the screen: %d\n", ret); + return ret; } /* The VBI on while anyone wants it: vblanks, or a base to write; the @@ -369,7 +370,9 @@ static bool sgx_kms_direct(struct apple_sgx_kms *kms, const struct drm_plane_sta } /* Back to copies: the whole plane onto the boot framebuffer, then the - * layer pointed at it once the copy is done. Under ov_lock. */ + * layer pointed at it once the copy is done. A copy that failed (the 2D + * engine down: no microkernel) leaves the layer where it is: the boot + * framebuffer still holds what the bootloader drew. Under ov_lock. */ static void sgx_kms_to_boot(struct apple_sgx_kms *kms, const struct drm_plane_state *state) { struct drm_rect all = drm_plane_state_src(state); @@ -378,8 +381,10 @@ static void sgx_kms_to_boot(struct apple_sgx_kms *kms, const struct drm_plane_st all.y1 >>= 16; all.x2 >>= 16; all.y2 >>= 16; - sgx_kms_show(kms, state, &all); - apple_sgx_blt_sync(kms->sgx); + if (sgx_kms_show(kms, state, &all)) + return; + if (apple_sgx_blt_sync(kms->sgx)) + return; sgx_kms_point(kms, kms->boot_pa); } @@ -398,7 +403,9 @@ static void sgx_kms_update(struct drm_simple_display_pipe *pipe, if (!state->fb || !state->visible || !pipe->crtc.state->active) return; mutex_lock(&kms->ov_lock); - if (state->fb != old_state->fb && sgx_kms_direct(kms, state, &pa)) { + /* (the same framebuffer again, e.g. a commit that changes only the + * output's transform, stays pointed at; no copy) */ + if (sgx_kms_direct(kms, state, &pa)) { sgx_kms_point(kms, pa); kms->n_pointed++; } else if (kms->clcd && kms->shown != kms->boot_pa) { From 46bdca79d2df56099bf9040703fe70815a14ad47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Fri, 4 Dec 2026 10:13:20 +0100 Subject: [PATCH 26/37] drm: apple-sgx: Start the microkernel on first open when autoboot found no firmware MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The built-in driver probes before the root filesystem is mounted, so autoboot's request for apple/sgx543-s5l8950x.fw fails with -ENOENT on an installed system and the GPU stays down for the whole session: no render node, no 2D engine. The first client already starts the microkernel when autoboot is off; let it also retry after autoboot failed for want of the firmware. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/gpu/drm/apple-sgx/apple_sgx_drm.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple-sgx/apple_sgx_drm.c b/drivers/gpu/drm/apple-sgx/apple_sgx_drm.c index def0613236e3db..4330b2b33fabf1 100644 --- a/drivers/gpu/drm/apple-sgx/apple_sgx_drm.c +++ b/drivers/gpu/drm/apple-sgx/apple_sgx_drm.c @@ -1194,9 +1194,16 @@ static int sgx_open(struct drm_device *drm, struct drm_file *file) struct apple_sgx_file *fpriv; int ret; - /* with autoboot off, the first client starts the microkernel */ + /* + * With autoboot off, the first client starts the microkernel. So does + * the first client after an autoboot that found no firmware: a built-in + * driver probes before the root filesystem, where the firmware is, is + * mounted. (Not under other clients: a boot rebuilds the queues.) + */ flush_work(&sgx->boot_work); - if (!apple_sgx_up(sgx) && !READ_ONCE(sgx->boot_result)) + if (!apple_sgx_up(sgx) && (!READ_ONCE(sgx->boot_result) || + (READ_ONCE(sgx->boot_result) == -ENOENT && + !apple_sgx_drm_busy(sgx)))) apple_sgx_restart(sgx); fpriv = kzalloc(sizeof(*fpriv), GFP_KERNEL); From 8931e036e9842baa9ef0476d295d9b48e52f7ec1 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 27/37] 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 | 800 +++++++++++++++++++---- 1 file changed, 678 insertions(+), 122 deletions(-) diff --git a/drivers/power/supply/apple-pmu-charger.c b/drivers/power/supply/apple-pmu-charger.c index a2e89c1b1fc510..c8bb3c0dcee95a 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: + * - D1972 writes require d1972_armed (default off). D1946 uses armed + * (default on). Disarming puts back what the driver + * found at probe. + * - pmu_chg_write() admits 0x3d on D1946 and 0x3f, 0x43 and 0x46 on + * D1972. d1972_set_suspend() updates 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,371 @@ 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) { + int adj = ma; + + if (ma < 330 && c->cal[0]) { + int at100 = (c->cal[0] + 0xffff) >> 16; + + if (at100 != 100) + adj = (int)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; + } + ma = clamp(adj, (int)ma * 85 / 100, (int)ma * 115 / 100); + } + *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 +885,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 +901,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 +924,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 +959,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 +979,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 +1056,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 +1071,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 +1081,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 +1111,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 d328ece48338d20cf9edf8f78821674f6397b924 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 28/37] 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 af46b9e9620b2a..8725604b4ff686 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -282,13 +282,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.d1972_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.d1972_armed=1. */ charger@3f { compatible = "apple,pmu-d1972-charger"; reg = <0x3f>; + apple,charge-limits = <900 570 420 270>; }; }; From dea32178ac898abfa06e0bb7aae3885416edfadb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Fri, 4 Dec 2026 13:32:07 +0100 Subject: [PATCH 29/37] power: supply: apple-pmu-charger: Charge the iPhone 5 by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The D1972 driver follows the iOS charging policy for the input current ramp, sag backoff and charge limit, and guards the battery temperature. Charging with this policy has been verified on the iPhone 5. Drop the arming switch so the driver applies the policy from probe. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 4 +- drivers/power/supply/apple-pmu-charger.c | 56 +++--------------------- 2 files changed, 8 insertions(+), 52 deletions(-) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index 8725604b4ff686..68ab20f58625eb 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -285,8 +285,8 @@ * 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.d1972_armed=1. + * from the bootloader. The D1972 charges by default + * following the iOS policy. */ charger@3f { compatible = "apple,pmu-d1972-charger"; diff --git a/drivers/power/supply/apple-pmu-charger.c b/drivers/power/supply/apple-pmu-charger.c index c8bb3c0dcee95a..295acf2c990aa8 100644 --- a/drivers/power/supply/apple-pmu-charger.c +++ b/drivers/power/supply/apple-pmu-charger.c @@ -83,9 +83,8 @@ * poll; the charge current is rewritten when it flips. * * Common rules: - * - D1972 writes require d1972_armed (default off). D1946 uses armed - * (default on). Disarming puts back what the driver - * found at probe. + * - D1972 follows the iOS charging policy from probe. D1946 uses armed + * (default on). Disarming D1946 restores the input limit found at probe. * - pmu_chg_write() admits 0x3d on D1946 and 0x3f, 0x43 and 0x46 on * D1972. d1972_set_suspend() updates only bit 2 of 0x1b. The event * registers 0x01..0x09, which clear on read, are never read. @@ -220,10 +219,6 @@ static const struct pmu_chg_chip pmu_chg_d1972 = { .ios_policy = 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, "enable D1946 charger writes (default on)"); @@ -277,7 +272,7 @@ struct pmu_chg { static bool pmu_chg_armed(struct pmu_chg *c) { - return c->chip == &pmu_chg_d1972 ? READ_ONCE(d1972_armed) : READ_ONCE(armed); + return c->chip == &pmu_chg_d1972 || READ_ONCE(armed); } static bool pmu_chg_writable(struct pmu_chg *c, unsigned int reg) @@ -722,33 +717,12 @@ static void d1972_log_status(struct pmu_chg *c) 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; + bool online, update, was_hot; 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); @@ -768,23 +742,6 @@ static unsigned int d1972_work(struct pmu_chg *c, bool *changed) 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); @@ -1082,11 +1039,10 @@ static int pmu_chg_probe(struct platform_device *pdev) return ret; schedule_delayed_work(&c->work, msecs_to_jiffies(POLL_MS)); 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", + 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; armed\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)"); + c->has_cal ? "" : " (none)", c->ilim_max_ma); 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, From 1602dcf43ff0e1165a7a977734fc53f6b9f026c6 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 30/37] dt-bindings: iio: Describe the Apple AP3GDL gyroscope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The N42 has an ST-compatible gyroscope with Apple's AP3GDL register layout and a WHO_AM_I value of 0xd5. The existing L3GD20 compatible expects 0xd4. 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..3d1600e03d293f 100644 --- a/Documentation/devicetree/bindings/iio/st,st-sensors.yaml +++ b/Documentation/devicetree/bindings/iio/st,st-sensors.yaml @@ -54,6 +54,7 @@ properties: - silan,sc7a20 - description: STMicroelectronics Gyroscopes enum: + - apple,ap3gdl-d5 - st,l3g4200d-gyro - st,l3g4is-gyro - st,l3gd20-gyro From e333de11ca5d3b6cb215a9e346cf69ec1ab4d978 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 31/37] iio: gyro: Support the AP3GDL with device ID 0xd5 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The N42 gyroscope returns 0xd5 at WHO_AM_I. Apple's AP3GDL driver groups it with the 0xd4 L3GD20, and the same register layout produces three-axis samples on the phone. Give it a distinct ID so probe can validate the measured part. 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..19fb7d26c59521 100644 --- a/drivers/iio/gyro/st_gyro.h +++ b/drivers/iio/gyro/st_gyro.h @@ -14,6 +14,7 @@ #include #include +#define AP3GDL_D5_GYRO_DEV_NAME "ap3gdl-d5" #define L3G4200D_GYRO_DEV_NAME "l3g4200d" #define LSM330D_GYRO_DEV_NAME "lsm330d_gyro" #define LSM330DL_GYRO_DEV_NAME "lsm330dl_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..0b151f290f04d4 100644 --- a/drivers/iio/gyro/st_gyro_i2c.c +++ b/drivers/iio/gyro/st_gyro_i2c.c @@ -18,6 +18,10 @@ #include "st_gyro.h" static const struct of_device_id st_gyro_of_match[] = { + { + .compatible = "apple,ap3gdl-d5", + .data = AP3GDL_D5_GYRO_DEV_NAME, + }, { .compatible = "st,l3g4200d-gyro", .data = L3G4200D_GYRO_DEV_NAME, @@ -93,6 +97,7 @@ static int st_gyro_i2c_probe(struct i2c_client *client) } static const struct i2c_device_id st_gyro_id_table[] = { + { AP3GDL_D5_GYRO_DEV_NAME }, { L3G4200D_GYRO_DEV_NAME }, { LSM330D_GYRO_DEV_NAME }, { LSM330DL_GYRO_DEV_NAME }, From f95eb4126d7b27b4f32443166b48b4eaab794d58 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 32/37] ARM: dts: apple: Describe the iPhone 5 gyroscope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Take the mount matrix and the two level-high interrupts from the gyro node in the live N42 12H321 ADT. GPIO 225 is INT1 and GPIO 67 is INT2. Apple uses INT2 for FIFO timestamps. List it first for the ST driver's data-ready interrupt. 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 68ab20f58625eb..beefd3b3ed51ca 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; @@ -237,6 +239,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 e39a389435ab1b0df1baa718b96250bcc50695a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:10:07 +0100 Subject: [PATCH 33/37] pinctrl: s5l8940x: select GPIO IRQ support used by the controller 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/pinctrl/Kconfig | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/pinctrl/Kconfig b/drivers/pinctrl/Kconfig index acf77c49debcde..ceda9402d7e7e1 100644 --- a/drivers/pinctrl/Kconfig +++ b/drivers/pinctrl/Kconfig @@ -620,7 +620,8 @@ source "drivers/pinctrl/vt8500/Kconfig" config PINCTRL_S5L8940X_GPIO tristate "Apple S5L8940X (A5) GPIO/pinctrl driver" - depends on OF + depends on OF && GPIOLIB + select GPIOLIB_IRQCHIP select PINMUX select PINCONF select GENERIC_PINCONF From 4cbed358185fa2411d71d327ee5630fcaa175213 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:10:08 +0100 Subject: [PATCH 34/37] Input: apple-z2: Pace N42 reads and restart a stalled scan MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Advance the sequence on empty replies. Retry after a millisecond and drain a full batch from work context. Recover a stuck ATTN by restarting the digitizer and release active slots before recovery. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/input/touchscreen/apple-z2.c | 193 ++++++++++++++++++++++++--- 1 file changed, 178 insertions(+), 15 deletions(-) diff --git a/drivers/input/touchscreen/apple-z2.c b/drivers/input/touchscreen/apple-z2.c index b060b0895ef84f..01d9ab2b40616a 100644 --- a/drivers/input/touchscreen/apple-z2.c +++ b/drivers/input/touchscreen/apple-z2.c @@ -87,9 +87,11 @@ struct hx_touch_data { struct regulator *regu_core; struct regulator *regu_pmuclk; struct completion irq_done; - struct work_struct boot_work; + struct delayed_work boot_work; struct delayed_work lost_work; unsigned lost_frame; + struct work_struct drain_work; + bool recovering; const char *firmware_name; bool raw_packet; u32 ref_clk_div; @@ -232,10 +234,16 @@ static int hx_touch_xfer(struct hx_touch_data *hxt, const u8 *tx, u8 *rx, unsign ret = gpiod_direction_output(hxt->gpiod_cs, 0); if (ret) return ret; - usleep_range(1000, 1200); + if (hxt->spi->cs_setup.value) + spi_delay_exec(&hxt->spi->cs_setup, &xfer); + else + usleep_range(1000, 1200); ret = spi_sync_transfer(hxt->spi, &xfer, 1); + if (hxt->spi->cs_hold.value) + spi_delay_exec(&hxt->spi->cs_hold, &xfer); cs_ret = gpiod_direction_output(hxt->gpiod_cs, 1); - usleep_range(1000, 1200); + if (!hxt->spi->cs_hold.value) + usleep_range(1000, 1200); return ret ?: cs_ret; } @@ -329,6 +337,142 @@ static int hx_touch_read_report(struct hx_touch_data *hxt) return 0; } +static int hx_touch_query_length(struct hx_touch_data *hxt, u8 seq) +{ + u8 *q = hxt->tx_data, *r = hxt->rx_data; + int ret; + + memset(q, 0, 16); + q[0] = 0xeb; + q[1] = seq; + put_unaligned_le16(hx_touch_sum16(q, 14), q + 14); + ret = hx_touch_xfer(hxt, q, r, 16); + if(ret) + return ret; + if((r[0] & 0xf0) != 0xe0 || get_unaligned_le16(r + 14) != hx_touch_sum16(r, 14)) + return -EBADMSG; + return get_unaligned_le16(r + 1); +} + +static int hx_touch_n42_read_report(struct hx_touch_data *hxt, u8 seq, bool retry) +{ + u8 *q = hxt->tx_data, *r = hxt->rx_data, query[16]; + unsigned n, plen; + int len, ret; + + /* After a failed exchange iOS primes the pipeline with a second + * same-sequence length command (0x80717c10). */ + if(retry) { + len = hx_touch_query_length(hxt, seq); + if(len < 0) + return len; + } + len = hx_touch_query_length(hxt, seq); + if(len <= 0 || len > Z2_MAX_PACKET) { + hxt_trace(hxt, "q %u: %16ph (length %d)\n", seq, r, len); + if(len > Z2_MAX_PACKET) + return -EMSGSIZE; + return len; /* zero is a successful, empty exchange */ + } + + /* iOS has a configurable mid-read IOSleep at 0x80717c48. Give the + * controller at least 1 ms with CS high before requesting the data. + * hx_touch_xfer already waits this long on boards without CS timings. */ + memcpy(query, r, sizeof(query)); + if(hxt->spi->cs_hold.value) + usleep_range(1000, 1200); + + n = len + 5; + memset(q, 0, n); + q[0] = 0xeb; + q[1] = seq; + q[2] = 1; + put_unaligned_le16(hx_touch_sum16(q, 3), q + n - 2); + ret = hx_touch_xfer(hxt, q, r, n); + if(ret) + return ret; + + /* Keep printk outside the query-to-data interval. */ + hxt_trace(hxt, "q %u: %16ph d: %*ph (%u)\n", seq, query, min(n, 16u), r, n); + plen = get_unaligned_le16(r + 2); + if((r[0] != 0xea && r[0] != 0xeb) || r[1] != seq || + (hx_touch_sum16(r, 5) & 0xff) || plen < 2 || plen + 5 > n) + return -EBADMSG; + if(hx_touch_sum16(r + 5, plen - 2) != get_unaligned_le16(r + plen + 3)) + return -EBADMSG; + + hx_touch_process_report(hxt, r + 5, plen - 2); + hxt->nframes++; + return 1; +} + +static int hx_touch_next_report(struct hx_touch_data *hxt) +{ + int ret, attempt; + + /* Host IRQ 0x807172f4 supplies five retries. 0x80717cfa waits 1 ms + * before retrying. A valid zero length also advances the sequence. */ + for(attempt = 0; attempt <= 5; attempt++) { + if(attempt) { + hxt->nretries++; + usleep_range(1000, 1200); + } + ret = hx_touch_n42_read_report(hxt, 1 + hxt->read_tag, attempt != 0); + if(ret >= 0) { + hxt->read_tag = !hxt->read_tag; + break; + } + } + return ret; +} + +/* Called with mutex held. The ATTN GPIO is logically active when low. */ +static void hx_touch_n42_drain(struct hx_touch_data *hxt) +{ + int i, ret = 0; + + for(i = 0; i < 16; i++) { + ret = hx_touch_next_report(hxt); + if(ret < 0) + break; + if(ret <= 0) + usleep_range(1000, 1200); + if(gpiod_get_value(hxt->gpiod_irq) <= 0) + return; + } + + if(hxt->removed) + return; + if(ret > 0) { + /* Yield after a full batch. A still-asserted ATTN has no new edge. */ + schedule_work(&hxt->drain_work); + return; + } + + if(!hxt->recovering) + dev_warn_ratelimited(&hxt->spi->dev, + "frame stalled (%d, %5ph), restarting digitizer\n", + ret, hxt->rx_data); + hxt->recovering = true; + hxt->ready = 0; + for (i = 0; i < hxt->input_dev->mt->num_slots; i++) { + input_mt_slot(hxt->input_dev, i); + input_mt_report_slot_state(hxt->input_dev, MT_TOOL_FINGER, false); + } + input_mt_sync_frame(hxt->input_dev); + input_sync(hxt->input_dev); + schedule_delayed_work(&hxt->boot_work, msecs_to_jiffies(1000)); +} + +static void hx_touch_drain_work(struct work_struct *work) +{ + struct hx_touch_data *hxt = container_of(work, struct hx_touch_data, drain_work); + + guard(mutex)(&hxt->mutex); + if(!hxt->removed && hxt->ready && gpiod_get_value(hxt->gpiod_irq) > 0) + hx_touch_n42_drain(hxt); +} + /* Read while ATTN stays asserted: the interrupt is on its falling edge, and * a frame left unread leaves the line low with no edge to come -- which is * also why a failed read does not end the loop while the line is down. */ @@ -336,6 +480,11 @@ static void hx_touch_read_all_reports(struct hx_touch_data *hxt) { int i, ret; + if (hxt->raw_packet) { + hx_touch_n42_drain(hxt); + return; + } + for(i = 0; i < 16; i++) { ret = hx_touch_read_report(hxt); if(ret && ret != -ENOENT) { @@ -1160,15 +1309,17 @@ static int hx_touch_n1_boot(struct hx_touch_data *hxt, const u8 *packet, static void hx_touch_boot_work(struct work_struct *work) { - struct hx_touch_data *hxt = container_of(work, struct hx_touch_data, boot_work); + struct hx_touch_data *hxt = container_of(to_delayed_work(work), struct hx_touch_data, boot_work); struct device *dev = &hxt->spi->dev; const struct firmware *fw, *cal = NULL; u8 *packet; int len, ret; + if (hxt->raw_packet && hxt->powered) + hx_touch_power_off(hxt); ret = request_firmware(&fw, hxt->firmware_name, dev); if (ret) - return; + goto failed; if (hxt->raw_packet) { ret = -EINVAL; if (fw->size >= 20 && fw->size <= SZ_128K && @@ -1181,10 +1332,8 @@ static void hx_touch_boot_work(struct work_struct *work) } } release_firmware(fw); - if (ret) { - dev_err(dev, "touch controller boot failed: %pe\n", ERR_PTR(ret)); - return; - } + if (ret) + goto failed; packet = NULL; goto ready; } @@ -1217,10 +1366,13 @@ static void hx_touch_boot_work(struct work_struct *work) goto release_cal; } - ready: +ready: mutex_lock(&hxt->mutex); + hxt->read_tag = 0; hxt->ready = 1; hx_touch_read_all_reports(hxt); + if (hxt->ready) + hxt->recovering = false; mutex_unlock(&hxt->mutex); dev_info(dev, "touch controller ready\n"); @@ -1228,8 +1380,14 @@ static void hx_touch_boot_work(struct work_struct *work) release_firmware(cal); free_packet: kvfree(packet); - if (ret) - dev_err(dev, "touch controller boot failed: %pe\n", ERR_PTR(ret)); +failed: + if (ret) { + dev_err_ratelimited(dev, "touch controller boot failed: %pe\n", ERR_PTR(ret)); + mutex_lock(&hxt->mutex); + if (hxt->recovering && !hxt->removed) + schedule_delayed_work(&hxt->boot_work, msecs_to_jiffies(1000)); + mutex_unlock(&hxt->mutex); + } } static int hx_touch_spi_create_touch_input(struct hx_touch_data *hxt) @@ -1394,8 +1552,9 @@ static int hx_touch_spi_probe(struct spi_device *spi) return ret; if (hxt->firmware_name) { - INIT_WORK(&hxt->boot_work, hx_touch_boot_work); - schedule_work(&hxt->boot_work); + INIT_WORK(&hxt->drain_work, hx_touch_drain_work); + INIT_DELAYED_WORK(&hxt->boot_work, hx_touch_boot_work); + schedule_delayed_work(&hxt->boot_work, 0); return 0; } @@ -1417,7 +1576,11 @@ static void hx_touch_spi_remove(struct spi_device *spi) struct hx_touch_data *hxt = spi_get_drvdata(spi); if (hxt->firmware_name) { - cancel_work_sync(&hxt->boot_work); + mutex_lock(&hxt->mutex); + hxt->removed = true; + mutex_unlock(&hxt->mutex); + cancel_delayed_work_sync(&hxt->boot_work); + cancel_work_sync(&hxt->drain_work); if (hxt->powered) hx_touch_power_off(hxt); return; From 78af4d680a921a938c962a496d4a719ea2b5a178 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:10:08 +0100 Subject: [PATCH 35/37] ARM: dts: apple: Set the iPhone 5 touchscreen CS delays 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 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index beefd3b3ed51ca..75af4f90ffa670 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -377,6 +377,8 @@ */ touchscreen: touch@0 { compatible = "apple,n42-z2-multitouch"; + spi-cs-setup-delay-ns = <10000>; + spi-cs-hold-delay-ns = <10000>; reg = <0>; spi-max-frequency = <5000000>; generation = <1>; From de871d594c50a0934ddee2d307f9071573ffb8c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:10:09 +0100 Subject: [PATCH 36/37] media: apple-h4isp: support the iPhone 5 cameras MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The N42 and K93 use the same H4ISP firmware. Match the A6 separately to select the set-files and MIPI receiver settings from the sensor, module and board IDs reported to AppleH4CamIn. Retry detection with the alternate enable polarity when no sensor answers. Read the modes with CH_CAMERA_CONFIG_GET on first open. Only the low half of the rate word is the frame rate. The firmware puts 0x100 or 0x200 in the high half for the rear and front sensors respectively. Support the board's optional focus supply and strobe power enable. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/media/platform/apple/Kconfig | 13 +- drivers/media/platform/apple/apple-h4isp.c | 393 +++++++++++++++++++-- 2 files changed, 373 insertions(+), 33 deletions(-) diff --git a/drivers/media/platform/apple/Kconfig b/drivers/media/platform/apple/Kconfig index bc3be0df3015d7..db4fdbc5fc4c5c 100644 --- a/drivers/media/platform/apple/Kconfig +++ b/drivers/media/platform/apple/Kconfig @@ -3,7 +3,7 @@ comment "Apple media platform drivers" config VIDEO_APPLE_H4ISP - tristate "Apple A5 H4 camera ISP (the iPad 2's cameras)" + tristate "Apple A5/A6 H4 camera ISP (the iPad 2's and iPhone 5's cameras)" depends on V4L_PLATFORM_DRIVERS depends on VIDEO_DEV depends on ARCH_APPLE_S5L || COMPILE_TEST @@ -11,8 +11,9 @@ config VIDEO_APPLE_H4ISP select VIDEOBUF2_DMA_SG select GENERIC_ALLOCATOR help - The camera ISP of the Apple A5 (S5L8940X): a CPU of its own that - runs Apple's firmware behind an IOMMU, drives the iPad 2's rear - and front cameras and writes YUYV frames. Two V4L2 capture - devices, one a camera. Needs apple/h4isp-firmware.bin and the - sensors' set-files from iOS. + The camera ISP of the Apple A5 (S5L8940X) and A6 (S5L8950X): a + CPU of its own that runs Apple's firmware behind an IOMMU, drives + the iPad 2's or the iPhone 5's rear and front cameras and writes + YUYV frames. Two V4L2 capture devices, one a camera. Needs the + ISP's firmware (apple/h4isp-firmware.bin, the same on both) and + the sensors' set-files from iOS. diff --git a/drivers/media/platform/apple/apple-h4isp.c b/drivers/media/platform/apple/apple-h4isp.c index 3114b7669d7fbe..555193b58aa501 100644 --- a/drivers/media/platform/apple/apple-h4isp.c +++ b/drivers/media/platform/apple/apple-h4isp.c @@ -41,6 +41,17 @@ * (H4ISPServices' H4ISPFIRMWARE section) and, a sensor, its set-file * apple/h4isp-setfile-.bin (from the H4ISPSETFILE * section) -- ./cascadia k93 firmware takes them out of the IPSW. + * + * The iPhone 5 (N42, Apple A6, S5L8950X) has the same ISP, IOMMU and + * AppleH4CamIn, and the same firmware, byte for byte. + * Its differences are the match data's: sensor-type 9; the set-file iOS's + * H4ISPServices would pick, by the sensor's and its module's IDs, named as + * iOS names it (apple/h4isp-setfile-.bin); MIPI receiver settings chosen by the + * sensors' IDs; a sensor's enable polarity flipped once when no sensor + * answers, as iOS does (each of the two costs one more boot of the ISP); + * the lens actuator's supply and the flash's power enable; and the modes + * taken from the firmware instead of a table: the first open of either node + * boots the ISP once to read them. */ #include @@ -170,6 +181,7 @@ #define H4ISP_MAX_BUFS VB2_MAX_FRAME /* vb2's least: buffer indexes */ #define H4ISP_BUFS 8 /* what a REQBUFS gets at most */ #define H4ISP_TAG(cam, idx) (0x4000 | (cam) << 8 | (idx)) +#define H4ISP_MAX_MODES 16 /* modes a sensor offers, read from the firmware */ static bool fw_log; module_param(fw_log, bool, 0644); @@ -202,6 +214,9 @@ static const struct h4isp_size h4isp_front_sizes[] = { { 640, 480, 0, 0x1df5 }, /* of 656x488, 29.96 fps */ }; +/* what a camera whose modes come from the firmware reports until they do */ +static const struct h4isp_size h4isp_unknown_size = { 640, 480, 0, 30 * 256 }; + static const struct h4isp_cam_desc h4isp_cam_descs[H4ISP_CAMS] = { { "rear", "Rear camera", V4L2_CAMERA_ORIENTATION_BACK, h4isp_rear_sizes, ARRAY_SIZE(h4isp_rear_sizes) }, @@ -209,6 +224,20 @@ static const struct h4isp_cam_desc h4isp_cam_descs[H4ISP_CAMS] = { h4isp_front_sizes, ARRAY_SIZE(h4isp_front_sizes) }, }; +struct h4isp; + +/* what differs between the SoCs and boards the ISP is in */ +struct h4isp_variant { + const char *setfile; /* a printf format: the sensor's ID */ + /* or iOS's choice of set-file, by the sensor's and its module's IDs */ + const char *(*setfile_name)(struct h4isp *isp, unsigned int ch); + bool retry_polarity; /* no sensor: its enable's polarity flipped, once */ + u32 sensor_type; /* the ADT's, unless the DT says otherwise */ + bool modes_from_fw; /* sizes from the firmware's modes, not a table */ + /* the receivers' setting for a camera (ISP_MIPI); none: ISP_MIPI_CONFIG */ + u32 (*mipi_config)(struct h4isp *isp, unsigned int ch); +}; + /* memory the ISP sees: coherent, at one address of its own */ struct h4isp_mem { struct list_head list; @@ -235,12 +264,14 @@ struct h4isp_buf { u32 size; }; -struct h4isp; - struct h4isp_cam { struct h4isp *isp; unsigned int ch; /* the firmware's channel */ const struct h4isp_cam_desc *desc; + /* the sizes it offers: the desc's table, or read from the firmware */ + const struct h4isp_size *sizes; + unsigned int nsizes; + struct h4isp_size fw_sizes[H4ISP_MAX_MODES]; struct video_device vdev; struct vb2_queue queue; struct v4l2_ctrl_handler ctrls; @@ -265,6 +296,7 @@ struct h4isp_cam { struct h4isp { struct device *dev; + const struct h4isp_variant *variant; void __iomem *regs; void __iomem *dart; void __iomem *ps; @@ -272,11 +304,17 @@ struct h4isp { int dart_irq; struct clk *clk; struct regulator *vdd; + struct regulator *focus; /* the lens actuator's, if there is one */ struct pinctrl *pinctrl; struct pinctrl_state *pins_active; struct pinctrl_state *pins_idle; struct gpio_desc *enable[H4ISP_CAMS]; + struct gpio_desc *strobe_power; /* the flash's power enable, if any */ u32 sensor_type; + u32 mipi[H4ISP_CAMS]; /* the receivers' settings this boot */ + bool reboot; /* the sensors found ask for another boot */ + bool polarity_flipped[H4ISP_CAMS]; + bool discovered; /* the modes are read from the firmware */ /* the IOMMU: its page tables, one after the other, and its dummy page */ u32 *pt; @@ -318,6 +356,7 @@ struct h4isp { u32 sensor_id[H4ISP_CAMS]; u32 nmodes[H4ISP_CAMS]; + u32 module[H4ISP_CAMS][2]; /* CH_INFO_GET's +0x14 and +0x18 */ struct dentry *debugfs; u32 dbg_answer[CMD_WORDS]; @@ -865,8 +904,9 @@ static void h4isp_flush_pending(struct h4isp *isp, struct h4isp_cam *cam) /* * The sensors (iOS's EnableSensor): their clock pins to the peripheral - * function, 1 ms, each sensor's enable, 5 ms. Off, the reverse, the clock - * pins driven low as iBoot leaves them. + * function, 1 ms, the rear sensor's enable, the flash's power enable where + * there is one (N42: AppleH4CamIn 0x809faa7c), the front sensor's, 5 ms. + * Off, the reverse, the clock pins driven low as iBoot leaves them. */ static void h4isp_sensors(struct h4isp *isp, bool on) { @@ -876,12 +916,14 @@ static void h4isp_sensors(struct h4isp *isp, bool on) if (isp->pins_active) pinctrl_select_state(isp->pinctrl, isp->pins_active); usleep_range(1000, 2000); - for (i = 0; i < H4ISP_CAMS; i++) - gpiod_set_value_cansleep(isp->enable[i], 1); + gpiod_set_value_cansleep(isp->enable[0], 1); + gpiod_set_value_cansleep(isp->strobe_power, 1); + gpiod_set_value_cansleep(isp->enable[1], 1); usleep_range(5000, 6000); } else { for (i = 0; i < H4ISP_CAMS; i++) gpiod_set_value_cansleep(isp->enable[i], 0); + gpiod_set_value_cansleep(isp->strobe_power, 0); if (isp->pins_idle) pinctrl_select_state(isp->pinctrl, isp->pins_idle); } @@ -986,8 +1028,8 @@ static int h4isp_handshake(struct h4isp *isp) for (i = 0; i < 8; i++) writel(0, isp->regs + ISP_MBOX(i)); writel(~0u, isp->regs + ISP_IRQ_CLEAR); - writel(ISP_MIPI_CONFIG, isp->regs + ISP_MIPI(0)); - writel(ISP_MIPI_CONFIG, isp->regs + ISP_MIPI(1)); + writel(isp->mipi[0], isp->regs + ISP_MIPI(0)); + writel(isp->mipi[1], isp->regs + ISP_MIPI(1)); writel(VA_FW | BIT(31), isp->regs + ISP_BOOT); writel(1, isp->regs + ISP_RUN); @@ -1045,6 +1087,7 @@ static int h4isp_handshake(struct h4isp *isp) } static void h4isp_power_down(struct h4isp *isp); +static void h4isp_fill_fmt(const struct h4isp_size *s, struct v4l2_pix_format *f); /* a sensor's set-file, by its ID; without one the firmware's defaults */ static void h4isp_setfile(struct h4isp *isp, unsigned int ch) @@ -1052,9 +1095,20 @@ static void h4isp_setfile(struct h4isp *isp, unsigned int ch) const struct firmware *fw; struct h4isp_mem *m; u32 p[CMD_WORDS] = { }; - char name[40]; - - snprintf(name, sizeof(name), "apple/h4isp-setfile-%04x.bin", isp->sensor_id[ch]); + const char *which; + char name[48]; + + if (isp->variant->setfile_name) { + which = isp->variant->setfile_name(isp, ch); + if (!which) { + dev_warn(isp->dev, "camera %u: no set-file for sensor %#x, modules %u %u\n", + ch, isp->sensor_id[ch], isp->module[ch][0], isp->module[ch][1]); + return; + } + snprintf(name, sizeof(name), "apple/h4isp-setfile-%s.bin", which); + } else { + snprintf(name, sizeof(name), isp->variant->setfile, isp->sensor_id[ch]); + } if (request_firmware(&fw, name, isp->dev)) { dev_warn(isp->dev, "no %s: camera %u keeps the firmware's defaults\n", name, ch); return; @@ -1082,7 +1136,7 @@ static int h4isp_power_up(struct h4isp *isp) return 0; ret = request_firmware(&fw, H4ISP_FIRMWARE, isp->dev); if (ret) { - dev_err(isp->dev, "no %s (./cascadia k93 firmware takes it out of the IPSW)\n", + dev_err(isp->dev, "no %s (iOS's H4ISPServices H4ISPFIRMWARE section)\n", H4ISP_FIRMWARE); return ret; } @@ -1091,14 +1145,24 @@ static int h4isp_power_up(struct h4isp *isp) release_firmware(fw); return -EINVAL; } + isp->reboot = false; + for (ch = 0; ch < H4ISP_CAMS; ch++) + isp->mipi[ch] = isp->variant->mipi_config ? + isp->variant->mipi_config(isp, ch) : ISP_MIPI_CONFIG; ret = regulator_enable(isp->vdd); if (ret) goto err_fw; usleep_range(5000, 6000); + if (isp->focus) { + ret = regulator_enable(isp->focus); + if (ret) + goto err_vdd; + usleep_range(1000, 2000); + } ret = clk_prepare_enable(isp->clk); if (ret) - goto err_vdd; + goto err_focus; h4isp_reset(isp); h4isp_sensors(isp, true); writel(0, isp->regs + ISP_RUN); @@ -1147,12 +1211,29 @@ static int h4isp_power_up(struct h4isp *isp) p[2] = ch; if (h4isp_cmd(isp, CMD_CH_INFO_GET, p, 0xa8, 1000)) continue; + if (isp->variant->modes_from_fw && isp->sensor_id[ch] != p[0x20 / 4]) + dev_info(isp->dev, "camera %u: sensor %#x, %u modes, modules %u %u\n", ch, + p[0x20 / 4], p[0x60 / 4], p[0x14 / 4], p[0x18 / 4]); isp->sensor_id[ch] = p[0x20 / 4]; isp->nmodes[ch] = p[0x60 / 4]; + isp->module[ch][0] = p[0x14 / 4] & 0xffff; + isp->module[ch][1] = p[0x18 / 4] & 0xffff; dev_dbg(isp->dev, "camera %u: sensor %#x, %u modes, modules %u %u\n", ch, isp->sensor_id[ch], isp->nmodes[ch], p[0x14 / 4], p[0x18 / 4]); if (isp->nmodes[ch]) h4isp_setfile(isp, ch); + else if (isp->variant->retry_polarity && isp->enable[ch] && + !isp->polarity_flipped[ch]) { + /* iOS's ISP_InitialSensorDetection (12H321 N42 0x809feee8) */ + dev_info(isp->dev, "camera %u: no sensor, its enable's polarity flipped\n", + ch); + gpiod_toggle_active_low(isp->enable[ch]); + isp->polarity_flipped[ch] = true; + isp->reboot = true; + } + if (isp->variant->mipi_config && + isp->variant->mipi_config(isp, ch) != isp->mipi[ch]) + isp->reboot = true; } return 0; @@ -1161,6 +1242,9 @@ static int h4isp_power_up(struct h4isp *isp) release_firmware(fw); h4isp_power_down(isp); return ret; +err_focus: + if (isp->focus) + regulator_disable(isp->focus); err_vdd: regulator_disable(isp->vdd); err_fw: @@ -1195,6 +1279,8 @@ static void h4isp_power_down(struct h4isp *isp) isp->on = false; spin_unlock_irq(&isp->dart_lock); clk_disable_unprepare(isp->clk); + if (isp->focus) + regulator_disable(isp->focus); regulator_disable(isp->vdd); } else { spin_unlock_irq(&isp->dart_lock); @@ -1204,6 +1290,188 @@ static void h4isp_power_down(struct h4isp *isp) isp->io = isp->buf_h2t = isp->buf_t2h = isp->sharedmalloc = isp->io_t2h = NULL; } +/* + * The A6's receivers, set by the sensors' IDs as iOS sets them before it + * starts the ISP's CPU (12H321 N42 AppleH4CamIn 0x809fad74). An ID not yet + * known (0) gets iOS's default, 0x1201: so does every sensor on its first + * boot, which reads the IDs; h4isp_power_up_settled() then boots it again. + */ +static u32 h4isp_mipi_s5l8950x(struct h4isp *isp, unsigned int ch) +{ + u32 id = isp->sensor_id[ch]; + + if (ch == 0) { + if (isp->sensor_type == 8 || id == 0x5650 || id == 0x5651) + return 0xb01; + switch (id) { + case 0x145: + return 0x1b01; + case 0x149: + case 0x5690: + case 0x9760: + case 0x9762: + return 0xe01; + } + return 0x1201; + } + if (id == 0x9762) + return 0xe01; + if (id == 0x9760) + return isp->sensor_type == 9 || isp->sensor_type == 0x12 ? 0x1101 : 0xe01; + return 0x1201; +} + +/* + * The set-file iOS loads for a sensor, by its name in H4ISPServices' + * H4ISPSETFILE section: 12H321 N42 H4ISPServices 0x2942df60, by + * the sensor's ID, the ADT's sensor-type and the module's two IDs -- + * CH_INFO_GET's +0x18 ("m1") and +0x14 ("m2"), as AppleH4CamIn's + * ISP_InitialSensorDetection (0x809feee8) hands them to user space. The + * K93's two are among them: 0x9726 (1, 1) 1011_04XX, 0x7739 (1, 1) 0011_01XX. + */ +static const char *h4isp_setfile_name(struct h4isp *isp, unsigned int ch) +{ + u32 id = isp->sensor_id[ch], type = isp->sensor_type; + u32 m1 = isp->module[ch][1], m2 = isp->module[ch][0]; + u32 sb = (m1 & 3) << 2 | (m2 & 3), bit = BIT(sb); + + switch (id) { + case 0x145: + return sb == 5 ? "8111_01XX" : sb == 9 ? "8112_01XX" : + sb == 10 ? "8122_01XX" : "8121_01XX"; + case 0x149: + if (m1 == 3) + return m2 == 2 ? "8423_01XX" : "8413_01XX"; + return m1 == 1 && m2 == 2 ? "8421_01XX" : "8411_01XX"; + case 0x5650: + case 0x5651: + return sb == 5 || sb == 13 ? "5213_01XX" : sb == 9 ? "5212_01XX" : + sb == 10 ? "5222_01XX" : "5223_01XX"; + case 0x5690: + if (type == 0x10) + return m1 == 1 ? "6921_01XX" : "6922_01XX"; + return m1 == 1 ? "6521_01XX" : "6522_01XX"; + case 0x7736: + case 0x7739: + if (type == 7) + return sb <= 14 && !(bit & 0x2262) && (bit & 0x4404) ? + "2122_02XX" : "2111_01XX"; + if (id == 0x7736) + return "0222_02XX"; + if (type == 6) + return sb <= 14 && (bit & 0x2222) ? "0011_01XX" : "0022_02XX"; + if (sb <= 14 && (bit & 0x2222)) + return "0211_01XX"; + return sb == 6 ? "0221_01XX" : "0222_02XX"; + case 0x9726: + if (sb <= 13 && (bit & 0x2222)) + return "1011_04XX"; + return sb == 11 ? "1032_04XX" : "1031_04XX"; + case 0x9760: + return m1 == 3 ? "4413_02XX" : "4441_02XX"; + case 0x9762: /* iOS compares the first module ID's upper bits here */ + return m1 >> 4 == 3 ? "7653_01XX" : m1 >> 4 == 2 ? "7652_01XX" : "7651_01XX"; + } + return NULL; +} + +/* + * Powered up as the sensors found ask for: the receivers their IDs want, an + * enable's polarity flipped. Each asks for one boot more at most. + */ +static int h4isp_power_up_settled(struct h4isp *isp) +{ + unsigned int boot; + int ret; + + for (boot = 0; ; boot++) { + ret = h4isp_power_up(isp); + if (ret || !isp->reboot) + return ret; + if (boot == 2) { + isp->reboot = false; /* up as it is: never torn down later */ + return 0; + } + dev_info(isp->dev, "sensors %#x and %#x: booting again\n", + isp->sensor_id[0], isp->sensor_id[1]); + h4isp_power_down(isp); + } +} + +/* + * The sizes a camera offers, from its sensor's modes (CH_CAMERA_CONFIG_GET): + * each mode cut to whole multiples of 16, as the K93's table cuts its modes. + * The default is the largest no bigger than 1280x720, else the first. + */ +static void h4isp_read_modes(struct h4isp_cam *cam) +{ + struct h4isp *isp = cam->isp; + unsigned int i, n = 0, def = 0; + u32 p[CMD_WORDS]; + + for (i = 0; i < isp->nmodes[cam->ch] && n < H4ISP_MAX_MODES; i++) { + struct h4isp_size *s = &cam->fw_sizes[n]; + u32 w, h, fps; + + memset(p, 0, sizeof(p)); + p[2] = cam->ch; + p[3] = i; + if (h4isp_cmd(isp, CMD_CH_CAMERA_CONFIG_GET, p, 0x60, 1000)) + break; + w = p[4] & 0xffff; + h = p[4] >> 16; + /* + * The rate, 8.8 fixed point, is the word's low half: the A6's + * firmware sets its high half too (0x100 on the rear camera, + * 0x200 on the front one), the A5's leaves it zero. + */ + fps = p[7] & 0xffff; + dev_info(isp->dev, "%s camera: mode %u, %ux%u at %u.%02u fps, pool %u\n", + cam->desc->name, i, w, h, fps / 256, (fps % 256) * 100 / 256, p[8]); + if (w < 16 || h < 16 || !fps) + continue; + s->width = w & ~15; + s->height = h & ~15; + s->mode = i; + s->fps256 = fps; + n++; + } + if (!n) + return; + for (i = 0; i < n; i++) { + u32 area = cam->fw_sizes[i].width * cam->fw_sizes[i].height; + u32 best = cam->fw_sizes[def].width * cam->fw_sizes[def].height; + + if (area <= 1280 * 720 && (area > best || best > 1280 * 720)) + def = i; + } + cam->sizes = cam->fw_sizes; + cam->size = &cam->fw_sizes[def]; + h4isp_fill_fmt(cam->size, &cam->fmt); + /* the ioctls read nsizes without the ISP's lock: the sizes first */ + smp_store_release(&cam->nsizes, n); +} + +/* + * The modes, where they come from the firmware: the ISP booted once, both + * sensors asked, powered down again. Until it works, the nodes offer none. + */ +static void h4isp_discover(struct h4isp *isp) +{ + unsigned int ch; + + lockdep_assert_held(&isp->lock); + if (isp->discovered || isp->streaming) + return; + if (h4isp_power_up_settled(isp)) + return; + for (ch = 0; ch < H4ISP_CAMS; ch++) + if (!READ_ONCE(isp->cams[ch].nsizes)) + h4isp_read_modes(&isp->cams[ch]); + h4isp_power_down(isp); + isp->discovered = true; +} + /* --- a camera's channel ----------------------------------------------------- */ /* @@ -1538,7 +1806,12 @@ static int h4isp_start_streaming(struct vb2_queue *q, unsigned int count) ret = -EBUSY; goto err; } - ret = h4isp_power_up(isp); + if (!READ_ONCE(cam->nsizes)) { + dev_err(isp->dev, "the %s camera's modes are not known\n", cam->desc->name); + ret = -ENODEV; + goto err; + } + ret = h4isp_power_up_settled(isp); if (ret) goto err; ret = h4isp_ch_config(cam); @@ -1623,9 +1896,17 @@ static void h4isp_fill_fmt(const struct h4isp_size *s, struct v4l2_pix_format *f f->xfer_func = V4L2_XFER_FUNC_SRGB; } +/* the camera's sizes, none until they are known */ +static unsigned int h4isp_nsizes(struct h4isp_cam *cam) +{ + return smp_load_acquire(&cam->nsizes); +} + static const struct h4isp_size *h4isp_find_size(struct h4isp_cam *cam, u32 w, u32 h) { - return v4l2_find_nearest_size(cam->desc->sizes, cam->desc->nsizes, width, height, w, h); + unsigned int n = h4isp_nsizes(cam); + + return n ? v4l2_find_nearest_size(cam->sizes, n, width, height, w, h) : NULL; } static int h4isp_querycap(struct file *file, void *fh, struct v4l2_capability *cap) @@ -1656,8 +1937,11 @@ static int h4isp_g_fmt(struct file *file, void *fh, struct v4l2_format *f) static int h4isp_try_fmt(struct file *file, void *fh, struct v4l2_format *f) { struct h4isp_cam *cam = video_drvdata(file); + const struct h4isp_size *s = h4isp_find_size(cam, f->fmt.pix.width, f->fmt.pix.height); - h4isp_fill_fmt(h4isp_find_size(cam, f->fmt.pix.width, f->fmt.pix.height), &f->fmt.pix); + if (!s) + return -ENODEV; + h4isp_fill_fmt(s, &f->fmt.pix); return 0; } @@ -1669,6 +1953,8 @@ static int h4isp_s_fmt(struct file *file, void *fh, struct v4l2_format *f) if (vb2_is_busy(&cam->queue)) return -EBUSY; s = h4isp_find_size(cam, f->fmt.pix.width, f->fmt.pix.height); + if (!s) + return -ENODEV; h4isp_fill_fmt(s, &f->fmt.pix); cam->fmt = f->fmt.pix; cam->size = s; @@ -1679,23 +1965,23 @@ static int h4isp_enum_framesizes(struct file *file, void *fh, struct v4l2_frmsiz { struct h4isp_cam *cam = video_drvdata(file); - if (fs->pixel_format != V4L2_PIX_FMT_YUYV || fs->index >= cam->desc->nsizes) + if (fs->pixel_format != V4L2_PIX_FMT_YUYV || fs->index >= h4isp_nsizes(cam)) return -EINVAL; fs->type = V4L2_FRMSIZE_TYPE_DISCRETE; - fs->discrete.width = cam->desc->sizes[fs->index].width; - fs->discrete.height = cam->desc->sizes[fs->index].height; + fs->discrete.width = cam->sizes[fs->index].width; + fs->discrete.height = cam->sizes[fs->index].height; return 0; } static int h4isp_enum_frameintervals(struct file *file, void *fh, struct v4l2_frmivalenum *fi) { struct h4isp_cam *cam = video_drvdata(file); - unsigned int i; + unsigned int i, n = h4isp_nsizes(cam); if (fi->pixel_format != V4L2_PIX_FMT_YUYV || fi->index) return -EINVAL; - for (i = 0; i < cam->desc->nsizes; i++) { - const struct h4isp_size *s = &cam->desc->sizes[i]; + for (i = 0; i < n; i++) { + const struct h4isp_size *s = &cam->sizes[i]; if (s->width == fi->width && s->height == fi->height) { fi->type = V4L2_FRMIVAL_TYPE_DISCRETE; @@ -1770,9 +2056,25 @@ static const struct v4l2_ioctl_ops h4isp_ioctl_ops = { .vidioc_unsubscribe_event = v4l2_event_unsubscribe, }; +/* where the modes come from the firmware, the first open reads them */ +static int h4isp_open(struct file *file) +{ + struct h4isp_cam *cam = video_drvdata(file); + struct h4isp *isp = cam->isp; + int ret; + + ret = v4l2_fh_open(file); + if (ret || !isp->variant->modes_from_fw) + return ret; + mutex_lock(&isp->lock); + h4isp_discover(isp); + mutex_unlock(&isp->lock); + return 0; +} + static const struct v4l2_file_operations h4isp_fops = { .owner = THIS_MODULE, - .open = v4l2_fh_open, + .open = h4isp_open, .release = vb2_fop_release, .read = vb2_fop_read, .poll = vb2_fop_poll, @@ -1823,7 +2125,16 @@ static int h4isp_cam_register(struct h4isp *isp, unsigned int ch) cam->isp = isp; cam->ch = ch; cam->desc = &h4isp_cam_descs[ch]; - cam->size = &cam->desc->sizes[0]; + if (isp->variant->modes_from_fw) { + /* nothing offered until the firmware's modes are read */ + cam->sizes = cam->fw_sizes; + cam->nsizes = 0; + cam->size = &h4isp_unknown_size; + } else { + cam->sizes = cam->desc->sizes; + cam->nsizes = cam->desc->nsizes; + cam->size = &cam->sizes[0]; + } h4isp_fill_fmt(cam->size, &cam->fmt); mutex_init(&cam->lock); INIT_LIST_HEAD(&cam->pending); @@ -2016,6 +2327,9 @@ static int h4isp_probe(struct platform_device *pdev) if (!isp) return -ENOMEM; isp->dev = dev; + isp->variant = of_device_get_match_data(dev); + if (!isp->variant) + return -ENODEV; platform_set_drvdata(pdev, isp); isp->regs = devm_platform_ioremap_resource_byname(pdev, "isp"); @@ -2042,6 +2356,12 @@ static int h4isp_probe(struct platform_device *pdev) isp->vdd = devm_regulator_get(dev, "vdd"); if (IS_ERR(isp->vdd)) return dev_err_probe(dev, PTR_ERR(isp->vdd), "no sensor supply\n"); + isp->focus = devm_regulator_get_optional(dev, "focus"); + if (IS_ERR(isp->focus)) { + if (PTR_ERR(isp->focus) != -ENODEV) + return dev_err_probe(dev, PTR_ERR(isp->focus), "no lens supply\n"); + isp->focus = NULL; + } isp->pinctrl = devm_pinctrl_get(dev); if (IS_ERR(isp->pinctrl)) { if (PTR_ERR(isp->pinctrl) == -EPROBE_DEFER) @@ -2059,7 +2379,10 @@ static int h4isp_probe(struct platform_device *pdev) isp->enable[1] = devm_gpiod_get_optional(dev, "front-enable", GPIOD_OUT_LOW); if (IS_ERR(isp->enable[1])) return dev_err_probe(dev, PTR_ERR(isp->enable[1]), "no front enable\n"); - isp->sensor_type = 6; + isp->strobe_power = devm_gpiod_get_optional(dev, "strobe-power", GPIOD_OUT_LOW); + if (IS_ERR(isp->strobe_power)) + return dev_err_probe(dev, PTR_ERR(isp->strobe_power), "no flash power enable\n"); + isp->sensor_type = isp->variant->sensor_type; of_property_read_u32(dev->of_node, "apple,sensor-type", &isp->sensor_type); ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32)); @@ -2136,8 +2459,24 @@ static void h4isp_remove(struct platform_device *pdev) v4l2_device_unregister(&isp->v4l2); } +/* the iPad 2 (K93): the A5 */ +static const struct h4isp_variant h4isp_s5l8940x = { + .setfile = "apple/h4isp-setfile-%04x.bin", + .sensor_type = 6, +}; + +/* the iPhone 5 (N42): the A6 */ +static const struct h4isp_variant h4isp_s5l8950x = { + .setfile_name = h4isp_setfile_name, + .retry_polarity = true, + .sensor_type = 9, + .modes_from_fw = true, + .mipi_config = h4isp_mipi_s5l8950x, +}; + static const struct of_device_id h4isp_of_match[] = { - { .compatible = "apple,s5l8940x-isp" }, + { .compatible = "apple,s5l8940x-isp", .data = &h4isp_s5l8940x }, + { .compatible = "apple,s5l8950x-isp", .data = &h4isp_s5l8950x }, { } }; MODULE_DEVICE_TABLE(of, h4isp_of_match); @@ -2152,6 +2491,6 @@ static struct platform_driver h4isp_driver = { }; module_platform_driver(h4isp_driver); -MODULE_DESCRIPTION("Apple A5 (S5L8940X) H4 camera ISP: the iPad 2's cameras"); +MODULE_DESCRIPTION("Apple A5/A6 H4 camera ISP: the iPad 2's and the iPhone 5's cameras"); MODULE_LICENSE("GPL"); MODULE_FIRMWARE(H4ISP_FIRMWARE); From 750bb118e8eb96487a540f00682be0868a70b9ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:11:25 +0100 Subject: [PATCH 37/37] ARM: dts: apple: Describe the iPhone 5 cameras and their ISP 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 | 67 +++++++++++++++++++++++++ arch/arm/boot/dts/apple/s5l8950x.dtsi | 33 ++++++++++++ 2 files changed, 100 insertions(+) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index 75af4f90ffa670..e9a625a53a1529 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -10,6 +10,7 @@ #include "s5l8950x.dtsi" +#include #include / { @@ -20,6 +21,19 @@ wifi0 = &wifi; }; + /* + * The live ADT + * isp function-cam0_ldo is SoC GPIO 0x0406 = 38, an external LDO's + * enable, active high; AppleH4CamIn switches it for sensor-type 9. + */ + camera_vdd: regulator-camera { + compatible = "regulator-fixed"; + regulator-name = "camera-cam0-ldo"; + gpio = <&gpio 38 GPIO_ACTIVE_HIGH>; + enable-active-high; + startup-delay-us = <1000>; + }; + /* * Physical buttons and mute switch (ADT /buttons): active-low on SoC * GPIOs 0..4, identical layout to P105 (iPad mini 1). @@ -118,6 +132,21 @@ pins = "gpio32", "gpio33", "gpio34", "gpio35"; function = "periph"; }; + + /* + * The camera sensors' clocks: ADT isp function-sensor_extclk 0x0903 + * (pin 75) and function-sensor_extclk2 0x0905 (pin 77), the + * peripheral function while the ISP runs, GPIO (low) otherwise. + */ + camera_clk_pins: camera-clk-pins { + pins = "gpio75", "gpio77"; + function = "periph"; + }; + + camera_clk_idle: camera-clk-idle { + pins = "gpio75", "gpio77"; + function = "gpio"; + }; }; /* @@ -309,6 +338,20 @@ reg = <0x3f>; apple,charge-limits = <900 570 420 270>; }; + + /* + * The rear camera's lens actuator: ADT isp + * function-focus_ldo = PMU 0x0303 (LDO 3). 12H321's + * AppleD1972PMU LDO table (0x80d17ec8, 12 bytes an + * entry) gives LDO 3: 1.8 V base, 50 mV steps, + * voltage register 0x30, enable register 0x21 bit 0x02. + */ + focus_ldo: focus_ldo@21 { + compatible = "apple,pmu-pwrsw"; + reg = <0x21>; + mask = <0x02>; + enable = <0x02>; + }; }; /* @@ -486,6 +529,7 @@ status = "disabled"; }; }; + }; /* The GPU: drivers/gpu/drm/apple-sgx, its microkernel out of the IPSW. */ @@ -500,3 +544,26 @@ &sgx { status = "okay"; }; + +&isp_ps { + status = "okay"; +}; + +/* + * Sensor enables: function-sensor_shutdown 0x0902 (74) and _2 0x0904 + * (76), active high (the ADT flags' polarity byte is 0, as on the + * active-high cam0_ldo; the active-low resets and chip selects have + * 1). function-strobe_pwr_en 0x0b06 (94): iOS raises it with them. + */ +&isp { + vdd-supply = <&camera_vdd>; + focus-supply = <&focus_ldo>; + pinctrl-names = "active", "idle"; + pinctrl-0 = <&camera_clk_pins>; + pinctrl-1 = <&camera_clk_idle>; + rear-enable-gpios = <&gpio 74 GPIO_ACTIVE_HIGH>; + front-enable-gpios = <&gpio 76 GPIO_ACTIVE_HIGH>; + strobe-power-gpios = <&gpio 94 GPIO_ACTIVE_HIGH>; + apple,sensor-type = <9>; + status = "okay"; +}; diff --git a/arch/arm/boot/dts/apple/s5l8950x.dtsi b/arch/arm/boot/dts/apple/s5l8950x.dtsi index 1f0f85b764572f..11e5bdd90371eb 100644 --- a/arch/arm/boot/dts/apple/s5l8950x.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x.dtsi @@ -351,6 +351,39 @@ status = "disabled"; }; + /* + * HPERF-ISP, the ISP's and dart-rt's power state: the ADT pmgr + * device-clocks give ISP (0x65) and DART-RT (0x64) no state of their + * own, only the parent HPERF-ISP (0x0a), state 0x14 -> 0xf101050. + * Its parent HPERF-RT (0x104c/0x1060) is the display's too, on. + */ + isp_ps: isp-ps@f101050 { + compatible = "apple,s5l8940x-pmgr-clk-gate"; + #clock-cells = <0>; + reg = <0xf101050 0x4>; + clocks = <&refclk24mhz>; + clock-output-names = "isp_ps"; + status = "disabled"; + }; + + /* + * The H4 ISP (ADT isp, "isp,s5l8940x", IRQ 7) behind + * dart-rt (IRQ 117). "ps" is the register whose bit + * 31 resets the ISP: HPERF-ISP's own, as on the A5. The ADT's + * function-device_reset (ARST 0x12) would be 0xf101048 if iOS passes + * it to the PMGR's reset (0x80daf094) unchanged. + */ + isp: isp@a000000 { + compatible = "apple,s5l8950x-isp"; + reg = <0xa000000 0x100000>, <0xa400000 0x2000>, + <0xf101050 0x4>; + reg-names = "isp", "dart", "ps"; + interrupts = <7>, <117>; + interrupt-names = "isp", "dart"; + clocks = <&isp_ps>; + 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