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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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/59] 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 From 23b1c7a05c018faf32410d52171ce8b107b32a32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:13:37 +0100 Subject: [PATCH 38/59] dt-bindings: cpufreq: describe Apple S5L8950X performance 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 --- .../cpufreq/apple,s5l8950x-cpufreq.yaml | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Documentation/devicetree/bindings/cpufreq/apple,s5l8950x-cpufreq.yaml diff --git a/Documentation/devicetree/bindings/cpufreq/apple,s5l8950x-cpufreq.yaml b/Documentation/devicetree/bindings/cpufreq/apple,s5l8950x-cpufreq.yaml new file mode 100644 index 00000000000000..592fb526b5ed74 --- /dev/null +++ b/Documentation/devicetree/bindings/cpufreq/apple,s5l8950x-cpufreq.yaml @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/cpufreq/apple,s5l8950x-cpufreq.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple S5L8950X Swift CPU performance controller + +maintainers: + - Berkay Kösebay + +description: | + Both CPUs reference one operating-points-v2 table with opp-shared. + Each entry gives the frequency in opp-hz and the PMGR hardware slot in + opp-level. PMGR sequences the clock and calibrated voltage together. + AMC settings depend on whether the CPUs are in the boot slot. + +properties: + compatible: + const: apple,s5l8950x-cpufreq + + reg: + description: AMC register window + maxItems: 1 + + clocks: + description: 24 MHz PLL reference clock + maxItems: 1 + + apple,pmgr: + description: Syscon containing the PMGR performance table and selector + $ref: /schemas/types.yaml#/definitions/phandle + + apple,amc-high-values: + description: AMC settings for slots above the boot slot, in write order + $ref: /schemas/types.yaml#/definitions/uint32-array + items: + - description: Value at offset 0x20c + const: 0x20400100 + - description: Value at offset 0x438 + const: 0x100010ff + +required: + - compatible + - reg + - clocks + - apple,pmgr + - apple,amc-high-values + +additionalProperties: false + +examples: + - | + cpufreq@f800000 { + compatible = "apple,s5l8950x-cpufreq"; + reg = <0x0f800000 0x1000>; + clocks = <&refclk24mhz>; + apple,pmgr = <&pmgr>; + apple,amc-high-values = <0x20400100 0x100010ff>; + }; From 2d2bd8facaba1bb67b9fb8fcbba69f6aa7b07618 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:13:38 +0100 Subject: [PATCH 39/59] cpufreq: apple-s5l: scale the shared Swift CPU domain through PMGR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Validate OPP slots against the live firmware PLL table and capture the boot AMC settings only at the expected idle handoff. Preserve the SoC request and reconcile late completions before issuing another command. The Orchard defconfig selects ARCH_APPLE_S5L and inherits the default-y Swift driver. The CPUs require a shared PMGR transaction and AMC timing change, so generic cpufreq-dt must leave this SoC to the Apple driver. Boards can disable an OPP in the DT to lower the ceiling. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/cpufreq/Kconfig.arm | 12 + drivers/cpufreq/Makefile | 1 + drivers/cpufreq/apple-s5l-cpufreq.c | 349 +++++++++++++++++++++++++++ drivers/cpufreq/cpufreq-dt-platdev.c | 1 + 4 files changed, 363 insertions(+) create mode 100644 drivers/cpufreq/apple-s5l-cpufreq.c diff --git a/drivers/cpufreq/Kconfig.arm b/drivers/cpufreq/Kconfig.arm index 5f7e13e60c8023..587c06edf6faa0 100644 --- a/drivers/cpufreq/Kconfig.arm +++ b/drivers/cpufreq/Kconfig.arm @@ -15,6 +15,18 @@ config ARM_ALLWINNER_SUN50I_CPUFREQ_NVMEM To compile this driver as a module, choose M here: the module will be called sun50i-cpufreq-nvmem. +config ARM_APPLE_S5L_CPUFREQ + bool "Apple S5L8950X CPU frequency scaling" + depends on ARCH_APPLE_S5L + select MFD_SYSCON + select PM_OPP + default y + help + Scale both Swift CPUs in the shared S5L8950X performance domain + using the PMGR sequencer and firmware-programmed operating points. + The driver verifies each device tree frequency against the PMGR + slot before enabling frequency changes. + config ARM_APPLE_SOC_CPUFREQ tristate "Apple Silicon SoC CPUFreq support" depends on ARCH_APPLE || (COMPILE_TEST && 64BIT) diff --git a/drivers/cpufreq/Makefile b/drivers/cpufreq/Makefile index 0f184031dd123c..db47d5d6a4b8fd 100644 --- a/drivers/cpufreq/Makefile +++ b/drivers/cpufreq/Makefile @@ -52,6 +52,7 @@ obj-$(CONFIG_X86_AMD_FREQ_SENSITIVITY) += amd_freq_sensitivity.o ################################################################################## # ARM SoC drivers +obj-$(CONFIG_ARM_APPLE_S5L_CPUFREQ) += apple-s5l-cpufreq.o obj-$(CONFIG_ARM_APPLE_SOC_CPUFREQ) += apple-soc-cpufreq.o obj-$(CONFIG_ARM_ARMADA_37XX_CPUFREQ) += armada-37xx-cpufreq.o obj-$(CONFIG_ARM_ARMADA_8K_CPUFREQ) += armada-8k-cpufreq.o diff --git a/drivers/cpufreq/apple-s5l-cpufreq.c b/drivers/cpufreq/apple-s5l-cpufreq.c new file mode 100644 index 00000000000000..bc5c2003b70eb0 --- /dev/null +++ b/drivers/cpufreq/apple-s5l-cpufreq.c @@ -0,0 +1,349 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* CPU performance domain shared by the Apple A6 Swift cores. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PMGR_PLL(slot) (0x1400 + (slot) * 0x20) +#define PMGR_PERF_CTL 0x1700 +#define PERF_BUSY BIT(31) +#define PERF_CPU_REQUEST BIT(25) +#define PERF_CPU_A GENMASK(14, 12) +#define PERF_CPU_B GENMASK(18, 16) +#define PERF_CPU_C GENMASK(22, 20) +#define PERF_CPU_FIELDS (PERF_CPU_A | PERF_CPU_B | PERF_CPU_C) +#define AMC_FIRST 0x20c +#define AMC_SECOND 0x438 + +#define BOOT_SLOT 2 +#define NOMINAL_SLOT 4 +/* Software polling bound. The transition latency has not been measured. */ +#define IDLE_RETRIES 1000 + +struct s5l_cpufreq { + struct cpufreq_driver driver; + struct regmap *pmgr; + void __iomem *amc; + u32 low[2], high[2]; + u32 boot_fields; + unsigned int last_slot; + bool uncertain; + struct delayed_work readback; + struct mutex lock; + cpumask_t cpus; + unsigned int khz[NOMINAL_SLOT + 1]; + struct cpufreq_frequency_table *table; +}; + +static unsigned int s5l_fields(unsigned int slot) +{ + return FIELD_PREP(PERF_CPU_A, slot) | FIELD_PREP(PERF_CPU_B, slot) | + FIELD_PREP(PERF_CPU_C, slot); +} + +static int s5l_wait_idle(struct s5l_cpufreq *s, unsigned int *ctl) +{ + unsigned int first, i; + int ret; + + for (i = 0; i <= IDLE_RETRIES; i++) { + ret = regmap_read(s->pmgr, PMGR_PERF_CTL, &first); + if (ret) + return ret; + ret = regmap_read(s->pmgr, PMGR_PERF_CTL, ctl); + if (ret) + return ret; + if (!((first | *ctl) & PERF_BUSY)) + return 0; + if (i < IDLE_RETRIES) + udelay(1); + } + return -ETIMEDOUT; +} + +static void s5l_set_amc(struct s5l_cpufreq *s, unsigned int slot) +{ + const u32 *pair = slot == BOOT_SLOT ? s->low : s->high; + + writel(pair[0], s->amc + AMC_FIRST); + writel(pair[1], s->amc + AMC_SECOND); +} + +/* Never send another command while a previous command's outcome is unknown. */ +static int s5l_read_slot(struct s5l_cpufreq *s, unsigned int *slot) +{ + unsigned int ctl, fields; + int ret; + + ret = s5l_wait_idle(s, &ctl); + if (ret) + return ret; + + *slot = FIELD_GET(PERF_CPU_C, ctl); + if (*slot > NOMINAL_SLOT || !s->khz[*slot]) + return -EIO; + if (s->uncertain) { + fields = ctl & PERF_CPU_FIELDS; + if (fields != s5l_fields(*slot) && fields != s->boot_fields) + return -EIO; + s5l_set_amc(s, *slot); + s->last_slot = *slot; + s->uncertain = false; + } + return 0; +} + +static unsigned int s5l_get(unsigned int cpu) +{ + struct s5l_cpufreq *s = cpufreq_get_driver_data(); + unsigned int slot; + int ret; + + mutex_lock(&s->lock); + ret = s5l_read_slot(s, &slot); + mutex_unlock(&s->lock); + return ret ? 0 : s->khz[slot]; +} + +/* + * CPUFreq retains the old policy frequency on a failed target_index(). A + * late completion must reach the core even if the governor next requests + * that cached frequency and the core consequently skips target_index(). + */ +static void s5l_readback(struct work_struct *work) +{ + struct s5l_cpufreq *s = container_of(to_delayed_work(work), + struct s5l_cpufreq, readback); + unsigned int cpu = cpumask_any_and(&s->cpus, cpu_online_mask); + + if (cpu < nr_cpu_ids && cpufreq_get(cpu)) + return; + + schedule_delayed_work(&s->readback, HZ); +} + +static int s5l_target_index(struct cpufreq_policy *policy, unsigned int index) +{ + struct s5l_cpufreq *s = policy->driver_data; + unsigned int slot = s->table[index].driver_data; + unsigned int fields = s5l_fields(slot), ctl; + int ret; + + mutex_lock(&s->lock); + if (s->uncertain) { + unsigned int actual; + + ret = s5l_read_slot(s, &actual); + if (ret) + goto unlock; + } + + s5l_set_amc(s, slot); + ret = s5l_wait_idle(s, &ctl); + if (ret) { + /* No command issued: restore the settings for the old slot. */ + s5l_set_amc(s, s->last_slot); + goto fault; + } + ret = regmap_write_bits(s->pmgr, PMGR_PERF_CTL, + PERF_CPU_REQUEST | PERF_CPU_FIELDS, + PERF_CPU_REQUEST | fields); + if (ret) + goto fault; + ret = s5l_wait_idle(s, &ctl); + if (!ret && (ctl & PERF_CPU_FIELDS) != fields) + ret = -EIO; + if (ret) + goto fault; + + s->last_slot = slot; + goto unlock; + +fault: + /* A timed-out command can still land. Do not write a rollback. */ + s->uncertain = true; + schedule_delayed_work(&s->readback, 1); + pr_err_ratelimited("apple-s5l-cpufreq: request for slot %u failed (%d), awaiting idle selector\n", + slot, ret); +unlock: + mutex_unlock(&s->lock); + return ret; +} + +static int s5l_policy_init(struct cpufreq_policy *policy) +{ + struct s5l_cpufreq *s = cpufreq_get_driver_data(); + + if (!cpumask_test_cpu(policy->cpu, &s->cpus)) + return -ENODEV; + + cpumask_copy(policy->cpus, &s->cpus); + policy->driver_data = s; + policy->freq_table = s->table; + policy->dvfs_possible_from_any_cpu = true; + policy->cpuinfo.transition_latency = CPUFREQ_ETERNAL; + /* Use the core's normal governor interval for an unmeasured latency. */ + policy->transition_delay_us = USEC_PER_MSEC; + return 0; +} + +static const struct cpufreq_driver s5l_driver = { + .name = "apple-s5l", + .flags = CPUFREQ_IS_COOLING_DEV, + .init = s5l_policy_init, + .verify = cpufreq_generic_frequency_table_verify, + .get = s5l_get, + .target_index = s5l_target_index, + .attr = cpufreq_generic_attr, +}; + +static int s5l_validate_table(struct s5l_cpufreq *s, struct device *cpu, + unsigned long ref_hz) +{ + struct cpufreq_frequency_table *entry; + + cpufreq_for_each_valid_entry(entry, s->table) { + unsigned long hz = entry->frequency * 1000UL; + struct dev_pm_opp *opp; + unsigned int slot, pll, valid, mul, div; + int ret; + + opp = dev_pm_opp_find_freq_exact(cpu, hz, true); + if (IS_ERR(opp)) + return PTR_ERR(opp); + slot = dev_pm_opp_get_level(opp); + dev_pm_opp_put(opp); + if (slot < BOOT_SLOT || slot > NOMINAL_SLOT || s->khz[slot]) + return -EINVAL; + + ret = regmap_read(s->pmgr, PMGR_PLL(slot), &pll); + if (ret) + return ret; + ret = regmap_read(s->pmgr, PMGR_PLL(slot) + 4, &valid); + if (ret) + return ret; + mul = FIELD_GET(GENMASK(26, 18), pll) + 1; + div = (FIELD_GET(GENMASK(17, 9), pll) + 1) * + (FIELD_GET(GENMASK(8, 0), pll) + 1); + if (!(valid & 0xff) || (u64)ref_hz * mul != (u64)hz * div) + return dev_err_probe(cpu, -EINVAL, + "PMGR slot %u does not validate at %lu Hz\n", + slot, hz); + + s->khz[slot] = entry->frequency; + entry->driver_data = slot; + } + + return s->khz[BOOT_SLOT] == 600000 ? 0 : -EINVAL; +} + +static int s5l_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev, *cpu = get_cpu_device(0); + struct s5l_cpufreq *s; + struct clk *ref; + unsigned int ctl; + int ret; + + if (!cpu) + return -EPROBE_DEFER; + + s = devm_kzalloc(dev, sizeof(*s), GFP_KERNEL); + if (!s) + return -ENOMEM; + mutex_init(&s->lock); + INIT_DELAYED_WORK(&s->readback, s5l_readback); + s->pmgr = syscon_regmap_lookup_by_phandle(dev->of_node, "apple,pmgr"); + if (IS_ERR(s->pmgr)) + return dev_err_probe(dev, PTR_ERR(s->pmgr), "PMGR syscon\n"); + s->amc = devm_platform_ioremap_resource(pdev, 0); + if (IS_ERR(s->amc)) + return PTR_ERR(s->amc); + ref = devm_clk_get_enabled(dev, NULL); + if (IS_ERR(ref)) + return dev_err_probe(dev, PTR_ERR(ref), "PLL reference clock\n"); + ret = of_property_read_u32_array(dev->of_node, "apple,amc-high-values", + s->high, ARRAY_SIZE(s->high)); + if (ret) + return ret; + + ret = s5l_wait_idle(s, &ctl); + if (ret) + return dev_err_probe(dev, ret, "PMGR busy at handoff\n"); + s->last_slot = FIELD_GET(PERF_CPU_C, ctl); + if (s->last_slot != BOOT_SLOT) + return dev_err_probe(dev, -EINVAL, "unexpected handoff slot %u\n", + s->last_slot); + /* iBEC handoff only populates slot C. Save the actual AMC pair. */ + s->boot_fields = ctl & PERF_CPU_FIELDS; + s->low[0] = readl(s->amc + AMC_FIRST); + s->low[1] = readl(s->amc + AMC_SECOND); + + ret = dev_pm_opp_of_get_sharing_cpus(cpu, &s->cpus); + if (ret || !cpumask_equal(&s->cpus, cpu_possible_mask)) + return dev_err_probe(dev, ret ?: -EINVAL, "expected shared CPU OPP table\n"); + ret = dev_pm_opp_of_cpumask_add_table(&s->cpus); + if (ret) + return ret; + ret = dev_pm_opp_init_cpufreq_table(cpu, &s->table); + if (ret) + goto remove_opps; + ret = s5l_validate_table(s, cpu, clk_get_rate(ref)); + if (ret) + goto free_table; + + s->driver = s5l_driver; + s->driver.driver_data = s; + platform_set_drvdata(pdev, s); + ret = cpufreq_register_driver(&s->driver); + if (!ret) + return 0; + disable_delayed_work_sync(&s->readback); + +free_table: + dev_pm_opp_free_cpufreq_table(cpu, &s->table); +remove_opps: + dev_pm_opp_of_cpumask_remove_table(&s->cpus); + return ret; +} + +static void s5l_remove(struct platform_device *pdev) +{ + struct s5l_cpufreq *s = platform_get_drvdata(pdev); + + disable_delayed_work_sync(&s->readback); + cpufreq_unregister_driver(&s->driver); + dev_pm_opp_free_cpufreq_table(get_cpu_device(0), &s->table); + dev_pm_opp_of_cpumask_remove_table(&s->cpus); +} + +static const struct of_device_id s5l_of_match[] = { + { .compatible = "apple,s5l8950x-cpufreq" }, + {} +}; +MODULE_DEVICE_TABLE(of, s5l_of_match); + +static struct platform_driver s5l_cpufreq_driver = { + .probe = s5l_probe, + .remove = s5l_remove, + .driver = { + .name = "apple-s5l-cpufreq", + .of_match_table = s5l_of_match, + .suppress_bind_attrs = true, + }, +}; +builtin_platform_driver(s5l_cpufreq_driver); + +MODULE_DESCRIPTION("Apple S5L8950X shared CPU frequency scaling"); +MODULE_LICENSE("GPL"); diff --git a/drivers/cpufreq/cpufreq-dt-platdev.c b/drivers/cpufreq/cpufreq-dt-platdev.c index 18942bfe9c95f7..382293f87d2ea4 100644 --- a/drivers/cpufreq/cpufreq-dt-platdev.c +++ b/drivers/cpufreq/cpufreq-dt-platdev.c @@ -109,6 +109,7 @@ static const struct of_device_id blocklist[] __initconst = { { .compatible = "allwinner,sun50i-h700", }, { .compatible = "apple,arm-platform", }, + { .compatible = "apple,s5l8950x", }, { .compatible = "arm,vexpress", }, From 10f1b368af881bb52ff767a43be089b86746ca80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:13:38 +0100 Subject: [PATCH 40/59] ARM: dts: apple: Add the iPhone 5 shared CPU operating points MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Describe the nominal Swift states at 600, 840 and 1104 MHz. Leave the turbo slot unavailable. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x-5.dtsi | 40 +++++++++++++++++++++++++ arch/arm/boot/dts/apple/s5l8950x.dtsi | 9 ++++++ 2 files changed, 49 insertions(+) diff --git a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi index e9a625a53a1529..24851e775afcbe 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-5.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x-5.dtsi @@ -14,6 +14,34 @@ #include / { + cpu_opp_table: opp-table { + compatible = "operating-points-v2"; + opp-shared; + + opp-600000000 { + opp-hz = /bits/ 64 <600000000>; + opp-level = <2>; + }; + + opp-840000000 { + opp-hz = /bits/ 64 <840000000>; + opp-level = <3>; + }; + + opp-1104000000 { + opp-hz = /bits/ 64 <1104000000>; + opp-level = <4>; + }; + + /* Slot 5 requires SoC boost and a thermal time budget. */ + opp-1296000000 { + opp-hz = /bits/ 64 <1296000000>; + opp-level = <5>; + turbo-mode; + status = "disabled"; + }; + }; + aliases { serial0 = &uart6; bluetooth0 = &bluetooth; @@ -545,6 +573,18 @@ status = "okay"; }; +&cpu0 { + operating-points-v2 = <&cpu_opp_table>; +}; + +&cpu1 { + operating-points-v2 = <&cpu_opp_table>; +}; + +&cpufreq { + status = "okay"; +}; + &isp_ps { status = "okay"; }; diff --git a/arch/arm/boot/dts/apple/s5l8950x.dtsi b/arch/arm/boot/dts/apple/s5l8950x.dtsi index 11e5bdd90371eb..1d9c6d38e004a9 100644 --- a/arch/arm/boot/dts/apple/s5l8950x.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x.dtsi @@ -151,6 +151,15 @@ status = "disabled"; }; + cpufreq: cpufreq@f800000 { + compatible = "apple,s5l8950x-cpufreq"; + reg = <0x0f800000 0x1000>; + apple,pmgr = <&pmgr>; + apple,amc-high-values = <0x20400100 0x100010ff>; + clocks = <&refclk24mhz>; + status = "disabled"; + }; + /* * USB OTG gates (ADT usb-complex clock-gates; device-clocks * UPERF id 0x04 index 0x21, USB-OTG id 0x35 index 0x22, USBREG From 5fbd76480e1e8afd3314b347ddc9a47b23902617 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:20:34 +0100 Subject: [PATCH 41/59] usb: dwc2: Use buffer DMA and INCR16 bursts on the S5L8950X MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Match the A6 controller settings used during verified installer transfers. Descriptor DMA corrupted one-megabyte bulk transfers on the N42. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/usb/dwc2/params.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/drivers/usb/dwc2/params.c b/drivers/usb/dwc2/params.c index 97d1d24ff5017c..b90e633da22a7c 100644 --- a/drivers/usb/dwc2/params.c +++ b/drivers/usb/dwc2/params.c @@ -123,6 +123,20 @@ static void dwc2_set_s5l8940x_params(struct dwc2_hsotg *hsotg) p->no_clock_gating = true; } +/* + * Apple's A6 (iPhone 5). iOS 8.4.1 AppleSynopsysOTGDevice::doCoreInit writes + * GAHBCFG = ADT "ahb-burst" (0xe on N42) | DMAEn | GlblIntrMsk, i.e. buffer + * DMA with INCR16 bursts, and never sets DCFG.DescDMA. Do the same. + */ +static void dwc2_set_s5l8950x_params(struct dwc2_hsotg *hsotg) +{ + struct dwc2_core_params *p = &hsotg->params; + + dwc2_set_s5l8940x_params(hsotg); + p->ahbcfg = GAHBCFG_HBSTLEN_INCR16 << GAHBCFG_HBSTLEN_SHIFT; + p->g_dma_desc = false; +} + static void dwc2_set_socfpga_agilex_params(struct dwc2_hsotg *hsotg) { struct dwc2_core_params *p = &hsotg->params; @@ -336,6 +350,7 @@ const struct of_device_id dwc2_of_match_table[] = { { .compatible = "lantiq,arx100-usb", .data = &dwc2_set_ltq_ase_params }, { .compatible = "lantiq,xrx200-usb", .data = &dwc2_set_ltq_xrx200_params }, { .compatible = "lantiq,xrx300-usb", .data = &dwc2_set_ltq_xrx200_params }, + { .compatible = "apple,s5l8950x-dwc2", .data = dwc2_set_s5l8950x_params }, { .compatible = "apple,s5l8940x-dwc2", .data = dwc2_set_s5l8940x_params }, { .compatible = "snps,dwc2" }, { .compatible = "samsung,s3c6400-hsotg", From d9db37c3ec130e364eb99cdef1209ea3e61bc702 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:20:35 +0100 Subject: [PATCH 42/59] ARM: dts: apple: s5l8950x: Use the iOS DWC2 FIFO map MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit iOS 8.4.1 (AppleSynopsysOTGDevice::doCoreInit, N42) sets GRXFSIZ to 0x21b words, GNPTXFSIZ to 16 words, DIEPTXF1 to 64 words and DIEPTXF2-6 to 256 words. Each bulk IN endpoint then holds two high-speed packets; the old map gave every IN FIFO 128 words, a single packet. Use the iOS map, plus two 16-word FIFOs for interrupt endpoints. dwc2 gives each IN endpoint the smallest free FIFO that holds one packet, so bulk endpoints land in the 256-word FIFOs. Total: 539 + 16 + 1376 = 1931 of 2024 words. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- arch/arm/boot/dts/apple/s5l8950x.dtsi | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/arch/arm/boot/dts/apple/s5l8950x.dtsi b/arch/arm/boot/dts/apple/s5l8950x.dtsi index 1d9c6d38e004a9..7b0de51ff8fe7e 100644 --- a/arch/arm/boot/dts/apple/s5l8950x.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x.dtsi @@ -576,9 +576,15 @@ phys = <&otgphy 0>; phy-names = "usb2-phy"; dr_mode = "peripheral"; - g-rx-fifo-size = <512>; - g-np-tx-fifo-size = <128>; - g-tx-fifo-size = <128 128 128 128 128 128 128 128>; + /* + * The FIFO map iOS 8.4.1 programs (AppleSynopsysOTGDevice + * ::doCoreInit): GRXFSIZ 0x21b, GNPTXFSIZ 16, DIEPTXF1 64, + * DIEPTXF2-6 256 words, i.e. two HS bulk packets per IN + * endpoint. FIFOs 7 and 8 stay small for interrupt EPs. + */ + g-rx-fifo-size = <539>; + g-np-tx-fifo-size = <16>; + g-tx-fifo-size = <64 256 256 256 256 256 16 16>; status = "okay"; }; }; From 20dcd117fcbe23cc06210289e61e632dc8c6ffe0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:26:58 +0100 Subject: [PATCH 43/59] usb: gadget: f_ncm: Retry the timer flush while all IN requests are busy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ncm_tx_timeout() flushes the pending NTB through eth_start_xmit(NULL). When every IN request is queued on the controller, eth_start_xmit() returns NETDEV_TX_BUSY and the NTB stays pending: the timer is not re-armed and nothing else flushes it. The tail of a burst then waits for the next packet from the stack, which for a TCP sender that is out of data is a retransmission timeout. Re-arm the timer while the flush is refused, unless the port is suspended (eth_start_xmit() asks the host for a wakeup then). Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/usb/gadget/function/f_ncm.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/drivers/usb/gadget/function/f_ncm.c b/drivers/usb/gadget/function/f_ncm.c index 8e761249d672c7..2ae254ba859d3f 100644 --- a/drivers/usb/gadget/function/f_ncm.c +++ b/drivers/usb/gadget/function/f_ncm.c @@ -1154,8 +1154,17 @@ static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data) * XXX interface. * * This will call directly into u_ether's eth_start_xmit() + * + * eth_start_xmit() refuses the flush while every IN request + * is queued on the controller. Nothing else flushes the + * pending NTB then: the tail of a burst waits for the next + * packet from the stack, i.e. a TCP retransmit. Try again. */ - netdev->netdev_ops->ndo_start_xmit(NULL, netdev); + if (netdev->netdev_ops->ndo_start_xmit(NULL, netdev) == + NETDEV_TX_BUSY && !ncm->port.is_suspend) { + hrtimer_forward_now(data, TX_TIMEOUT_NSECS); + return HRTIMER_RESTART; + } } return HRTIMER_NORESTART; } From af7f0cd76f8341668525c28aed8b20c30b8498f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:18:32 +0100 Subject: [PATCH 44/59] dt-bindings: mtd: Describe S5L8950X CDMA channels and interrupts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM Signed-off-by: Berkay Kösebay --- .../devicetree/bindings/mtd/apple,h2fmi.yaml | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/Documentation/devicetree/bindings/mtd/apple,h2fmi.yaml b/Documentation/devicetree/bindings/mtd/apple,h2fmi.yaml index 1afa825403754e..0b4a2c3b6f0ac2 100644 --- a/Documentation/devicetree/bindings/mtd/apple,h2fmi.yaml +++ b/Documentation/devicetree/bindings/mtd/apple,h2fmi.yaml @@ -12,8 +12,8 @@ maintainers: description: 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. The S5L8950X (A6) controller is driven - read-only and must not fall back to apple,s5l8940x-fmi. + and ECC register windows. The S5L8950X (A6) controller uses different NAND commands + and must not fall back to apple,s5l8940x-fmi. properties: compatible: @@ -23,11 +23,11 @@ properties: reg: minItems: 6 - maxItems: 6 + maxItems: 7 interrupts: minItems: 2 - maxItems: 2 + maxItems: 6 clocks: description: @@ -35,7 +35,16 @@ properties: FMI0-BCH, FMI1, FMI1-BCH and FMI-DLL), switched on before any register access. minItems: 1 - maxItems: 5 + maxItems: 6 + + apple,dma-channels: + description: CDMA channel and request number for each FMI data FIFO + $ref: /schemas/types.yaml#/definitions/uint32-matrix + minItems: 2 + maxItems: 2 + items: + minItems: 2 + maxItems: 2 required: - compatible @@ -50,6 +59,15 @@ allOf: then: required: - clocks + else: + properties: + reg: + maxItems: 6 + interrupts: + maxItems: 2 + clocks: + maxItems: 5 + apple,dma-channels: false additionalProperties: false From 2295a7ca1a3c51f03259dc8fac27aca5713d0ecf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:18:32 +0100 Subject: [PATCH 45/59] mtd: apple-h2fmi: Use dual-bus CDMA transfers on the A6 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Queue reads and fenced SFTL programs on independent buses. Keep raw MTD read-only on the A6 and limit mutation to the verified geometry when configured. Keep A6 boards without a qualified N42 layout read-only, including N41. Matching the NAND geometry alone does not qualify those boards. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/devices/mtd-apple-h2fmi-test.c | 102 +- drivers/mtd/devices/mtd-apple-h2fmi.c | 2557 ++++++++++++++++++-- drivers/mtd/devices/mtd-apple-h2fmi.h | 210 +- include/linux/mtd/apple-ppn.h | 60 +- 4 files changed, 2741 insertions(+), 188 deletions(-) diff --git a/drivers/mtd/devices/mtd-apple-h2fmi-test.c b/drivers/mtd/devices/mtd-apple-h2fmi-test.c index 83be1db07ede1b..dcd2d21d8070ab 100644 --- a/drivers/mtd/devices/mtd-apple-h2fmi-test.c +++ b/drivers/mtd/devices/mtd-apple-h2fmi-test.c @@ -47,11 +47,14 @@ static void h2fmi_geometry_test(struct kunit *test) 70061654016ULL); } -/* The N42 profile parses, addresses like the P105 16 GB one and stays read-only. */ +/* The N42 profile parses, addresses like the P105 16 GB one, enforces its + * 0 / 1046..1055 program+erase fence, and stays read-only. + */ static void h2fmi_n42_geometry_test(struct kunit *test) { u8 params[H2FMI_PARAMS_SIZE]; struct h2fmi_geometry g; + unsigned int b; u32 row; h2fmi_test_params(params, ppn_n42); @@ -59,14 +62,37 @@ static void h2fmi_n42_geometry_test(struct kunit *test) 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_geometry_writable(&g), + (bool)IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE)); KUNIT_EXPECT_EQ(test, h2fmi_bad_block_bytes(&g), 132U); + KUNIT_EXPECT_EQ(test, h2fmi_program_block_limit(&g), 1046U); + KUNIT_EXPECT_EQ(test, h2fmi_erase_block_limit(&g), 1046U); 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); + /* Hard N42 fence: block 0 and BFN+VFL tail 1046..1055 refused on program & erase. */ + row = 0xdeadbeef; + KUNIT_EXPECT_EQ(test, h2fmi_program_row(&g, 0, 0, 0, &row), -EPERM); + KUNIT_EXPECT_EQ(test, h2fmi_erase_row(&g, 0, 0, &row), -EPERM); + for (b = 1046; b <= 1055; b++) { + KUNIT_EXPECT_EQ(test, h2fmi_program_row(&g, 0, b, 0, &row), -EPERM); + KUNIT_EXPECT_EQ(test, h2fmi_program_row(&g, 1, b, 255, &row), -EPERM); + KUNIT_EXPECT_EQ(test, h2fmi_erase_row(&g, 0, b, &row), -EPERM); + KUNIT_EXPECT_EQ(test, h2fmi_erase_row(&g, 1, b, &row), -EPERM); + } + KUNIT_EXPECT_EQ(test, h2fmi_program_row(&g, 0, 1056, 0, &row), -EINVAL); + KUNIT_EXPECT_EQ(test, h2fmi_erase_row(&g, 0, 1056, &row), -EINVAL); + KUNIT_EXPECT_EQ(test, row, 0xdeadbeefU); + KUNIT_ASSERT_EQ(test, h2fmi_program_row(&g, 0, 1, 0, &row), 0); + KUNIT_EXPECT_EQ(test, row, 0x100U); + KUNIT_ASSERT_EQ(test, h2fmi_program_row(&g, 1, 1045, 255, &row), 0); + KUNIT_EXPECT_EQ(test, row, 0xc15ffU); + KUNIT_ASSERT_EQ(test, h2fmi_erase_row(&g, 1, 1045, &row), 0); + KUNIT_EXPECT_EQ(test, row, 0xc1500U); + 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)); @@ -221,9 +247,29 @@ static void h2fmi_raw_page_erased_test(struct kunit *test) status == PPN_ST_ERASED); raw[H2FMI_CHUNK_LO] = 0xfe; KUNIT_EXPECT_FALSE(test, h2fmi_raw_page_erased(PPN_ST_ERASED, raw)); + /* Bounded SanDisk 0x49 check tolerates isolated erased-cell disturb. */ + KUNIT_EXPECT_TRUE(test, h2fmi_raw_page_erased_bounded(PPN_ST_ERASED, raw, + H2FMI_CLEAN_MAX_NON_FF_BYTES, + H2FMI_CLEAN_MAX_ZERO_BITS)); + KUNIT_EXPECT_FALSE(test, h2fmi_raw_page_erased_bounded(PPN_ST_GOOD, raw, + H2FMI_CLEAN_MAX_NON_FF_BYTES, + H2FMI_CLEAN_MAX_ZERO_BITS)); raw[H2FMI_CHUNK_LO] = 0xff; raw[H2FMI_PAGE_RAW - 1] = 0x7f; KUNIT_EXPECT_FALSE(test, h2fmi_raw_page_erased(PPN_ST_ERASED, raw)); + KUNIT_EXPECT_TRUE(test, h2fmi_raw_page_erased_bounded(PPN_ST_ERASED, raw, + H2FMI_CLEAN_MAX_NON_FF_BYTES, + H2FMI_CLEAN_MAX_ZERO_BITS)); + /* Exceeding bit or byte disturb budget (e.g. programmed/torn page) is rejected. */ + memset(raw, 0x00, 3); /* 24 zero bits > 16 */ + KUNIT_EXPECT_FALSE(test, h2fmi_raw_page_erased_bounded(PPN_ST_ERASED, raw, + H2FMI_CLEAN_MAX_NON_FF_BYTES, + H2FMI_CLEAN_MAX_ZERO_BITS)); + memset(raw, 0xff, 3); + memset(raw, 0xfe, H2FMI_CLEAN_MAX_NON_FF_BYTES + 1); /* 9 non-FF bytes > 8 */ + KUNIT_EXPECT_FALSE(test, h2fmi_raw_page_erased_bounded(PPN_ST_ERASED, raw, + H2FMI_CLEAN_MAX_NON_FF_BYTES, + H2FMI_CLEAN_MAX_ZERO_BITS)); } static void h2fmi_status_test(struct kunit *test) @@ -320,6 +366,57 @@ static void h2fmi_sdr_facts_test(struct kunit *test) KUNIT_EXPECT_EQ(test, H2FMI_CHUNKS * H2FMI_CHUNK_RAW, H2FMI_PAGE_RAW); } +/* The values iBEC 12H321 programs for an FMI page transfer. */ +static void h2fmi_cdma_test(struct kunit *test) +{ + __le32 cmds[16]; + u32 v = 0; + + /* dma_execute_cmd: request << 16, 4-byte words 0x8, burst 32 0x50, TX bit 1 */ + KUNIT_ASSERT_EQ(test, h2fmi_cdma_dcr(0, 4, 32, false, &v), 0); + KUNIT_EXPECT_EQ(test, v, 0x58U); + KUNIT_ASSERT_EQ(test, h2fmi_cdma_dcr(2, 4, 1, false, &v), 0); + KUNIT_EXPECT_EQ(test, v, 0x20008U); + KUNIT_ASSERT_EQ(test, h2fmi_cdma_dcr(2, 4, 32, true, &v), 0); + KUNIT_EXPECT_EQ(test, v, 0x2005aU); + KUNIT_ASSERT_EQ(test, h2fmi_cdma_dcr(1, 1, 8, false, &v), 0); + KUNIT_EXPECT_EQ(test, v, 0x10030U); + KUNIT_EXPECT_EQ(test, h2fmi_cdma_dcr(0, 3, 32, false, &v), -EINVAL); + KUNIT_EXPECT_EQ(test, h2fmi_cdma_dcr(0, 4, 3, false, &v), -EINVAL); + KUNIT_EXPECT_EQ(test, h2fmi_cdma_dcr(0x40, 4, 32, false, &v), -EINVAL); + KUNIT_EXPECT_EQ(test, CDMA_CSR_START, 0x0b1c0009U); + + /* dma_continue_async: one segment that halts, then a zero command */ + memset(cmds, 0xa5, sizeof(cmds)); + KUNIT_ASSERT_EQ(test, h2fmi_cdma_commands(cmds, 0x9f000000, 0x80123000, + H2FMI_DMA_BODY, false), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(cmds[0]), 0x9f000020U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(cmds[1]), 0x06000103U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(cmds[2]), 0x80123000U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(cmds[3]), 16384U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(cmds[8]), 0x9f000040U); + KUNIT_EXPECT_EQ(test, le32_to_cpu(cmds[9]), 0U); + KUNIT_ASSERT_EQ(test, h2fmi_cdma_commands(cmds, 0x9f000000, 0x80123000, + H2FMI_DMA_BODY, true), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(cmds[1]), 0x0b000103U); + KUNIT_EXPECT_EQ(test, h2fmi_cdma_commands(cmds, 0, 0, 0, false), -EINVAL); + KUNIT_EXPECT_EQ(test, h2fmi_cdma_commands(cmds, 0, 0, CDMA_SEGMENT_MAX + 1, + false), -EINVAL); + + /* FMI +0x34 in h2fmi_read_raw_page's two forms: sectors, then a short one */ + KUNIT_EXPECT_EQ(test, H2FMI_DMA_BODY + H2FMI_DMA_TAIL, H2FMI_PAGE_RAW); + KUNIT_ASSERT_EQ(test, h2fmi_data_size(H2FMI_DMA_BODY, &v), 0); + KUNIT_EXPECT_EQ(test, v, 0x40010U); + KUNIT_ASSERT_EQ(test, h2fmi_data_size(H2FMI_DMA_TAIL, &v), 0); + KUNIT_EXPECT_EQ(test, v, 0x4001U); + KUNIT_ASSERT_EQ(test, h2fmi_data_size(1024, &v), 0); + KUNIT_EXPECT_EQ(test, v, 0x40001U); + KUNIT_EXPECT_EQ(test, h2fmi_data_size(0, &v), -EINVAL); + KUNIT_EXPECT_EQ(test, h2fmi_data_size(62, &v), -EINVAL); + KUNIT_EXPECT_EQ(test, h2fmi_data_size(1028, &v), -EINVAL); + KUNIT_EXPECT_EQ(test, h2fmi_data_size(256 * 1024, &v), -EINVAL); +} + static struct kunit_case h2fmi_test_cases[] = { KUNIT_CASE(h2fmi_raw_write_ownership_test), KUNIT_CASE(h2fmi_geometry_test), @@ -332,6 +429,7 @@ static struct kunit_case h2fmi_test_cases[] = { KUNIT_CASE(h2fmi_slc_row_test), KUNIT_CASE(h2fmi_program_status_test), KUNIT_CASE(h2fmi_sdr_facts_test), + KUNIT_CASE(h2fmi_cdma_test), {} }; diff --git a/drivers/mtd/devices/mtd-apple-h2fmi.c b/drivers/mtd/devices/mtd-apple-h2fmi.c index 04b4820c149af2..6387d33a9c1db6 100644 --- a/drivers/mtd/devices/mtd-apple-h2fmi.c +++ b/drivers/mtd/devices/mtd-apple-h2fmi.c @@ -32,15 +32,22 @@ #include #include +#include #include #include +#include #include +#include #include #include #include #include +#include #include #include +#include +#include +#include #include #include #include @@ -49,7 +56,9 @@ #include #include #include +#include #include +#include #include "mtd-apple-h2fmi.h" @@ -70,13 +79,178 @@ struct h2fmi_soc { /* 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. */ +/* A6 uses a fenced SFTL writer and always exports read-only raw MTDs. */ static const struct h2fmi_soc h2fmi_s5l8950x = { - .read_only = true, + .read_only = !IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE), .no_sdr_reset = true, .clean_by_status = true, }; +/* + * Page data by CDMA instead of the PIO FIFO. Bit 0: page reads, the + * sequence of iBEC's raw page receive (h2fmi_read_raw_page). Bit 1: page + * programs, the same engine and FIFO in the other direction (iBEC only + * transmits through the FMI sequencer, so this pairing is inferred). + * Without the CDMA window and "apple,dma-channels" in the node, PIO. + * On by default since the iPhone 5 installs of 2026-11-30 ran reads and + * programs by CDMA (dma=3); 0 brings back PIO. + */ +#define H2FMI_DMA_READ BIT(0) +#define H2FMI_DMA_PROGRAM BIT(1) +static unsigned int dma = H2FMI_DMA_READ | H2FMI_DMA_PROGRAM; +module_param(dma, uint, 0644); +MODULE_PARM_DESC(dma, "Move page data by CDMA: bit 0 reads, bit 1 programs (0: PIO)"); + +static bool multi_read = true; +module_param(multi_read, bool, 0644); +MODULE_PARM_DESC(multi_read, "Use the N42 DDR PPN sequencer for batched reads"); +static ulong xfer_multi_reads, xfer_multi_read_pages, xfer_multi_read_us; +module_param(xfer_multi_reads, ulong, 0444); +module_param(xfer_multi_read_pages, ulong, 0444); +module_param(xfer_multi_read_us, ulong, 0444); + +/* Data-phase time and pages, [0] PIO and [1] CDMA, for measuring a flight. */ +static ulong xfer_read_us[2], xfer_read_pages[2], xfer_prog_us[2], xfer_prog_pages[2]; +module_param_array(xfer_read_us, ulong, NULL, 0644); +module_param_array(xfer_read_pages, ulong, NULL, 0644); +module_param_array(xfer_prog_us, ulong, NULL, 0644); +module_param_array(xfer_prog_pages, ulong, NULL, 0644); + +/* + * Status waits, [0] program/erase (79 and its 77/7D) and [1] reads: count, + * time and, for interrupt waits, misses (the interrupt did not come in time + * and the poll took over). Erases are counted apart from programs. + */ +static ulong xfer_wait_us[2], xfer_waits[2], xfer_irq_waits[2], xfer_irq_misses; +static ulong xfer_bus_resets; +static ulong xfer_erases, xfer_erase_us, xfer_stripes, xfer_stripe_pages, xfer_stripe_us; +module_param_array(xfer_wait_us, ulong, NULL, 0644); +module_param_array(xfer_waits, ulong, NULL, 0644); +module_param_array(xfer_irq_waits, ulong, NULL, 0644); +module_param(xfer_irq_misses, ulong, 0644); +module_param(xfer_bus_resets, ulong, 0444); +MODULE_PARM_DESC(xfer_bus_resets, "Controller gate pulses during DDR recovery"); +module_param(xfer_erases, ulong, 0644); +module_param(xfer_erase_us, ulong, 0644); +module_param(xfer_stripes, ulong, 0644); +module_param(xfer_stripe_pages, ulong, 0644); +module_param(xfer_stripe_us, ulong, 0644); +/* The buses can run at once (program_pages): counters are updated under this. */ +static DEFINE_SPINLOCK(h2fmi_stats_lock); + +static unsigned int xfer_multi_max_pages[2]; +module_param_array(xfer_multi_max_pages, uint, NULL, 0444); +MODULE_PARM_DESC(xfer_multi_max_pages, "Largest single-bus command in rows: program,read"); + +/* There are exactly two buses: each accrues the same intersection. Keep + * a single 64-bit total and take a coherent snapshot on 32-bit ARM. + */ +static u64 h2fmi_overlap_us; + +static int h2fmi_get_overlap(char *buffer, const struct kernel_param *kp) +{ + u64 us; + + spin_lock(&h2fmi_stats_lock); + us = h2fmi_overlap_us; + spin_unlock(&h2fmi_stats_lock); + return sysfs_emit(buffer, "%llu,%llu\n", us, us); +} + +static const struct kernel_param_ops h2fmi_overlap_ops = { + .get = h2fmi_get_overlap, +}; +module_param_cb(xfer_multi_overlap_us, &h2fmi_overlap_ops, NULL, 0444); +MODULE_PARM_DESC(xfer_multi_overlap_us, "Us with both multi commands outstanding: bus0,bus1"); + +struct h2fmi_command_time { + ktime_t submit, complete; +}; + +/* Wall time common to the two observed submit-to-completion intervals. + * Excludes software staging before submission, cleanup and recovery. + */ +static void h2fmi_count_overlap(const struct h2fmi_command_time *a, + const struct h2fmi_command_time *b) +{ + s64 us = ktime_us_delta(min(a->complete, b->complete), max(a->submit, b->submit)); + + if (us > 0) { + spin_lock(&h2fmi_stats_lock); + h2fmi_overlap_us += us; + spin_unlock(&h2fmi_stats_lock); + } +} + +static void h2fmi_count(ulong *us, ulong *n, ktime_t start) +{ + ulong delta = ktime_us_delta(ktime_get(), start); + + spin_lock(&h2fmi_stats_lock); + *us += delta; + (*n)++; + spin_unlock(&h2fmi_stats_lock); +} + +/* A5 verifies every program and erase. N42 can use package status alone. */ +static bool verify; +module_param(verify, bool, 0644); +MODULE_PARM_DESC(verify, "Verify N42 programs and erases by reading the NAND back"); + +/* + * Status waits on the FMC interrupt, as iBEC does (h2fmi_wait_status, + * 0xbff05b04, waits on an event the ISR at 0xbff060fc signals). Bit 0: + * program and erase status, bit 1: read status. 0: poll, the flown path. + * The interrupt is requested at probe only when this is non-zero at boot; + * the bits can be changed at runtime after that. A miss falls back to + * polling for the current comparison. + */ +#define H2FMI_IRQ_MUTATE BIT(0) +#define H2FMI_IRQ_READ BIT(1) +static unsigned int irq_wait; +module_param(irq_wait, uint, 0644); +MODULE_PARM_DESC(irq_wait, + "Wait for NAND status on the FMC interrupt: bit 0 program/erase, bit 1 reads (0: poll). Must be set at boot to request the interrupt"); +static unsigned int irq_wait_ms = 50; +module_param(irq_wait_ms, uint, 0644); +MODULE_PARM_DESC(irq_wait_ms, + "Milliseconds to wait for an interrupt before polling the current comparison"); + +/* program_pages: run bus 0 and bus 1 at once (1) or one after the other (0). */ +static bool parallel_buses = true; +module_param(parallel_buses, bool, 0644); +MODULE_PARM_DESC(parallel_buses, + "program_pages programs bus 0 and bus 1 at the same time (only used when SFTL's program_batch > 1)"); + +static bool multi_program = true; +module_param(multi_program, bool, 0644); +MODULE_PARM_DESC(multi_program, "Queue multiple N42 pages per bus (0: individual programs)"); +static ulong xfer_multi_programs, xfer_multi_pages, xfer_multi_us; +module_param(xfer_multi_programs, ulong, 0444); +module_param(xfer_multi_pages, ulong, 0444); +module_param(xfer_multi_us, ulong, 0444); + +#define H2FMI_QUEUE_MAX 32 +#define CDMA_CHAIN_ROWS 31 +#define SEQ_DEPTH 32 +#define SEQ_CMD 0x00 +#define SEQ_CMD_LEVEL 0x04 +#define SEQ_EVENT_DATA 0x10 +#define SEQ_ARG 0x14 +#define SEQ_ARG_LEVEL 0x18 +#define SEQ_EVENT 0x20 +#define SEQ_CLOCK 0x2c +#define SEQ_RESULT 0x30 +#define SEQ_RESULT_LEVEL 0x34 +#define SEQ_RAM 0x1000 +#define SEQ_CMD_RAM 0x2000 +#define SEQ_ARG_RAM 0x3000 +#define SEQ_SELECT 0x09000000 +#define SEQ_DATA 0x0b000000 +#define SEQ_DELAY 0x0e000000 +#define SEQ_ROW_STATUS 0x11000a04 +#define SEQ_WAIT_US 2000000 + #define H2FMI_BUSES 2 #define H2FMI_PAGE_MASK (H2FMI_PAGE_DATA - 1) @@ -106,6 +280,7 @@ static const struct h2fmi_soc h2fmi_s5l8950x = { #define FMC_STATUS 0x44 #define FMC_NAND_STATUS 0x48 #define FMC_STATUS_MASK 0x4c +#define FMC_DDR_TIMING0 0x70 /* three consecutive timing words */ #define FMC_ADDR1 0x1c #define ECC_INIT 0x14 /* FMI + 0x80014 */ @@ -114,8 +289,8 @@ static const struct h2fmi_soc h2fmi_s5l8950x = { #define FMC_ON_SDR 1 #define FMC_ON_DDR 5 -/* Every command sequence the driver issues. A sequence that is not listed - * does not run. Only the single-row final erase command is needed. */ +/* Direct FMC commands. The N42 sequencer and its fixed DDR list-clear + * transaction below also issue the package operations used by iBEC. */ static const u8 h2fmi_ops[][2] = { { 0x70, 0x00 }, /* read status */ { 0x92, 0x97 }, /* PPN device parameters */ @@ -134,16 +309,64 @@ static const u8 h2fmi_ops[][2] = { { 0xe7, 0x00 }, /* PPN set feature confirm */ }; +struct h2fmi_ddr_state { + u32 on, if_ctrl, timing[3]; + bool status_timeout; +}; + +/* DMA storage belongs to the bus, including during cancellation. */ +struct h2fmi_queue_dma { + __le32 rows[H2FMI_QUEUE_MAX]; + u8 meta[H2FMI_QUEUE_MAX][APPLE_PPN_OOB_SIZE]; +}; + +struct h2fmi_multi { + __le32 *desc[2]; /* data, metadata */ + dma_addr_t desc_addr[2], meta_addr; + u8 *meta; + dma_addr_t data_addr[4 * APPLE_PPN_READ_MAX_PER_BUS]; + u16 data_len[4 * APPLE_PPN_READ_MAX_PER_BUS]; + u32 row[APPLE_PPN_READ_MAX_PER_BUS]; +}; + +struct h2fmi_dma_irq { + int irq; + atomic_t armed; + struct completion done; +}; + struct h2fmi_bus { + struct h2fmi_dma_irq dma_irq[2]; + struct h2fmi_multi *multi; + void __iomem *gate; /* S5L8950X FMI PMGR gate */ void __iomem *fmi; void __iomem *fmc; void __iomem *ecc; struct mutex lock; /* one command sequence on this bus at a time */ u8 *page; /* one raw page; only touched under lock */ + __le32 *cmds; /* CDMA command list; NULL: PIO only */ + dma_addr_t cmds_bus; + u32 fifo; /* bus address of FMI_DATA */ + u32 dma_ch, dma_req; + void __iomem *seq; + unsigned int queue_depth; + u32 seq_clock, delay100, delay60; + bool seq_loaded; + struct h2fmi_queue_dma *queue; + dma_addr_t queue_bus, tx_desc_bus; + __le32 *tx_desc; + struct { + dma_addr_t addr; + u32 len; + } tx_segments[H2FMI_QUEUE_MAX * (DIV_ROUND_UP(H2FMI_PAGE_DATA, PAGE_SIZE) + 1)]; struct h2fmi_geometry geometry; u32 if_ctrl; /* SDR timing restored by every software reset */ bool sdr; /* this driver reset the package to SDR */ bool failed; /* block further I/O in this driver instance */ + int irq; /* FMC interrupt; 0: none requested */ + atomic_t irq_armed; /* winner masks the Linux IRQ line */ + u32 irq_status; /* FMI_STATUS as the ISR found it */ + struct completion irq_done; }; /* Resets after failed transactions in one driver instance. */ @@ -197,7 +420,9 @@ struct h2fmi_die { struct h2fmi { struct device *dev; + struct workqueue_struct *wq; /* independent bus requests */ struct h2fmi_bus bus[H2FMI_BUSES]; + void __iomem *cdma; struct mtd_info *mtd; struct h2fmi_die *die; unsigned int ndies; @@ -209,8 +434,9 @@ struct h2fmi { 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 n42; /* raw MTD is read-only on the iPhone 5 */ bool sdr_allowed; /* the packages may be reset to SDR */ - bool clean_by_status; /* a 49 page is erased whatever its data phase held */ + bool clean_by_status; /* a 49 page is erased within bounded disturb */ unsigned int clean_logged; }; @@ -236,7 +462,7 @@ static int h2fmi_wait(struct h2fmi *fmi, void __iomem *base, u32 off, /* * FMC_CMD holds the first command byte, and the second one in bits 15:8. - * Every command sequence passes through the opcode list above. + * Direct command helpers use the opcode list above. */ static int h2fmi_cmd_write(struct h2fmi *fmi, struct h2fmi_bus *b, u8 op, u8 op2) { @@ -302,41 +528,148 @@ static int h2fmi_cmd_addr_cmd(struct h2fmi *fmi, struct h2fmi_bus *b, return h2fmi_wait(fmi, b->fmc, FMC_STATUS, 0xb, 0xb); } +/* One disable per enable, whether the first IRQ or the waiter gets here first. */ +static bool h2fmi_mask_irq(int irq, atomic_t *armed) +{ + unsigned long flags; + bool masked; + + /* A level IRQ must not preempt its new mask owner before the disable. */ + local_irq_save(flags); + masked = atomic_xchg(armed, 0); + if (masked) + disable_irq_nosync(irq); + local_irq_restore(flags); + return masked; +} + +static irqreturn_t h2fmi_dma_irq(int irq, void *data) +{ + struct h2fmi_dma_irq *line = data; + + if (h2fmi_mask_irq(irq, &line->armed)) + complete(&line->done); + return IRQ_HANDLED; +} + +/* Level-triggered halt/error is left pending in CSR. The normal channel + * owner still acknowledges it, checks the residual and advances the chain. + */ +static void h2fmi_wait_dma_irq(struct h2fmi *fmi, struct h2fmi_bus *b, unsigned int stream, + unsigned int mask) +{ + struct h2fmi_dma_irq *line = &b->dma_irq[stream]; + void __iomem *ch = fmi->cdma + CDMA_CH(b->dma_ch + stream); + unsigned long signaled; + + if (!line->irq || !(READ_ONCE(irq_wait) & mask) || (readl(ch + CDMA_CSR) & CDMA_CSR_CLEAR)) + return; + reinit_completion(&line->done); + atomic_set(&line->armed, 1); + enable_irq(line->irq); + signaled = wait_for_completion_timeout(&line->done, + msecs_to_jiffies(clamp(READ_ONCE(irq_wait_ms), 1U, 2000U))); + h2fmi_mask_irq(line->irq, &line->armed); + synchronize_irq(line->irq); + if (!signaled || !(readl(ch + CDMA_CSR) & CDMA_CSR_CLEAR)) { + spin_lock(&h2fmi_stats_lock); + xfer_irq_misses++; + spin_unlock(&h2fmi_stats_lock); + } +} + +static irqreturn_t h2fmi_irq(int irq, void *data) +{ + struct h2fmi_bus *b = data; + + if (h2fmi_mask_irq(b->irq, &b->irq_armed)) { + /* iBEC saves bit 8 before W1C. The polling fallback also needs + * FMC bit 5, so only the waiter performs the Apple mask/W1C. + */ + WRITE_ONCE(b->irq_status, readl(b->fmi + FMI_STATUS)); + complete(&b->irq_done); + } + return IRQ_HANDLED; +} + +enum { H2FMI_WAIT_MUTATE, H2FMI_WAIT_READ }; + /* * h2fmi_ppn_get_operation_status + h2fmi_get_nand_status: 77 7D, then let the - * FMC poll the status byte until it is ready. iBEC waits on the interrupt; - * this polls FMC_STATUS bit 5, as the userspace tool does. + * FMC poll the status byte until it is ready. By default this polls + * FMC_STATUS bit 5, as the userspace tool does. With irq_wait it sleeps + * on the interrupt as iBEC does; the line is enabled only for that wait, so + * a polled wait never meets the handler. If the interrupt does not come + * with bit 8 before the deadline, poll the same comparison with the line masked. + * Recovery passes no transaction state and always polls the fresh comparator. */ -static int h2fmi_poll_status(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *st) +static int h2fmi_poll_status(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *st, + unsigned int kind, struct h2fmi_ddr_state *state) { + bool by_irq = state && b->irq && + (READ_ONCE(irq_wait) & (kind == H2FMI_WAIT_READ ? H2FMI_IRQ_READ : + H2FMI_IRQ_MUTATE)); + ktime_t start = ktime_get(); int ret; u32 v; h2fmi_clear_irqs(b); - writel(0x100, b->fmi + FMI_INTEN); + if (by_irq) { + reinit_completion(&b->irq_done); + WRITE_ONCE(b->irq_status, 0); + } + writel(FMI_POLL_DONE, b->fmi + FMI_INTEN); writel(readl(b->fmc + FMC_IF_CTRL) & ~0x100000u, b->fmc + FMC_IF_CTRL); writel(0x4040, b->fmc + FMC_STATUS_MASK); writel(0, b->fmc + FMC_DATANUM); writel(0x20, b->fmc + FMC_INTMASK); writel(0x50, b->fmc + FMC_RW_CTRL); + if (by_irq) { + atomic_set(&b->irq_armed, 1); + enable_irq(b->irq); + wait_for_completion_timeout(&b->irq_done, + msecs_to_jiffies(max(READ_ONCE(irq_wait_ms), 1U))); + h2fmi_mask_irq(b->irq, &b->irq_armed); + synchronize_irq(b->irq); + if (READ_ONCE(b->irq_status) & FMI_POLL_DONE) { + spin_lock(&h2fmi_stats_lock); + xfer_irq_waits[kind]++; + spin_unlock(&h2fmi_stats_lock); + goto ready; + } + /* Even an unrelated wake leaves the live FMC latch intact. */ + spin_lock(&h2fmi_stats_lock); + xfer_irq_misses++; + spin_unlock(&h2fmi_stats_lock); + } + ret = readl_poll_timeout(b->fmc + FMC_STATUS, v, v & 0x20, 0, 2000000); if (ret) { - dev_err(fmi->dev, "status timeout: FMC+0x44 0x%08x FMI+0xc 0x%08x byte 0x%02x\n", - v, readl(b->fmi + FMI_STATUS), - (u8)readl(b->fmc + FMC_NAND_STATUS)); + if (state) { + state->status_timeout = true; + dev_err(fmi->dev, "status timeout: FMC+0x44 0x%08x FMI+0xc 0x%08x byte 0x%02x\n", + v, readl(b->fmi + FMI_STATUS), + (u8)readl(b->fmc + FMC_NAND_STATUS)); + } writel(0, b->fmc + FMC_RW_CTRL); + if (b->gate) + writel(0, b->fmc + FMC_CE_CTRL); h2fmi_clear_irqs(b); return ret; } +ready: *st = readl(b->fmc + FMC_NAND_STATUS); writel(0, b->fmc + FMC_RW_CTRL); h2fmi_clear_irqs(b); + if (state) + h2fmi_count(&xfer_wait_us[kind], &xfer_waits[kind], start); return 0; } -static int h2fmi_status(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *st) +static int h2fmi_status(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *st, + unsigned int kind, struct h2fmi_ddr_state *state) { int ret = h2fmi_cmd_write(fmi, b, 0x77, 0x7d); @@ -346,7 +679,7 @@ static int h2fmi_status(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *st) ret = h2fmi_wait(fmi, b->fmc, FMC_STATUS, 3, 3); if (ret) return ret; - return h2fmi_poll_status(fmi, b, st); + return h2fmi_poll_status(fmi, b, st, kind, state); } static int h2fmi_pio_read(struct h2fmi *fmi, struct h2fmi_bus *b, @@ -366,13 +699,140 @@ static int h2fmi_pio_read(struct h2fmi *fmi, struct h2fmi_bus *b, return 0; } +static void h2fmi_cdma_clock(struct h2fmi *fmi, unsigned int channel, bool on) +{ + writel(BIT(channel % 32), + fmi->cdma + (on ? CDMA_CLK_ON : CDMA_CLK_OFF) + 4 * (channel / 32)); +} + +/* dma_cancel: stop a channel that is still running, and gate it. */ +static int h2fmi_cdma_cancel(struct h2fmi *fmi, unsigned int channel) +{ + void __iomem *ch = fmi->cdma + CDMA_CH(channel); + u32 v; + int ret = 0; + + h2fmi_cdma_clock(fmi, channel, true); + if ((readl(ch + CDMA_CSR) & CDMA_CSR_STATE) == CDMA_CSR_RUNNING) { + writel(CDMA_CSR_ABORT, ch + CDMA_CSR); + ret = readl_poll_timeout(ch + CDMA_CSR, v, + (v & CDMA_CSR_STATE) != CDMA_CSR_RUNNING, 0, 10000); + if (ret) + dev_err(fmi->dev, "CDMA channel %u did not stop: CSR %08x\n", + channel, v); + } + h2fmi_cdma_clock(fmi, channel, false); + return ret; +} + +static void h2fmi_cdma_start(struct h2fmi *fmi, unsigned int channel, u32 dcr, + u32 fifo, u32 len, dma_addr_t commands) +{ + void __iomem *ch = fmi->cdma + CDMA_CH(channel); + + h2fmi_cdma_clock(fmi, channel, true); + writel(CDMA_CSR_ABORT, ch + CDMA_CSR); + writel(dcr, ch + CDMA_DCR); + writel(fifo, ch + CDMA_DAR); + writel(len, ch + CDMA_DBR); + dma_wmb(); + writel(commands, ch + CDMA_CAR); + writel(CDMA_CSR_START, ch + CDMA_CSR); +} + +/* + * One run of page data between the FMI FIFO and memory, in iBEC's order + * (0xbff063ac): start the channel (dma_execute_cmd, dma_continue_async), + * start the FMI, wait for its last sector, then for the channel, which + * iBEC polls for 2 s with the interrupt masked. Caller holds b->lock and + * has mapped the memory. + */ +static int h2fmi_dma_run(struct h2fmi *fmi, struct h2fmi_bus *b, u32 addr, + u32 len, bool tx, u32 config, u32 burst) +{ + void __iomem *ch = fmi->cdma + CDMA_CH(b->dma_ch); + u32 dcr, size, csr = 0; + int ret; + + ret = h2fmi_cdma_dcr(b->dma_req, 4, burst, tx, &dcr); + if (!ret) + ret = h2fmi_data_size(len, &size); + if (!ret) + ret = h2fmi_cdma_commands(b->cmds, b->cmds_bus, addr, len, tx); + if (ret) + return ret; + + h2fmi_cdma_start(fmi, b->dma_ch, dcr, b->fifo, len, b->cmds_bus); + + writel(config, b->fmi + FMI_CONFIG); + writel(size, b->fmi + FMI_PIO_CONFIG); + writel(tx ? 5 : 3, b->fmi + FMI_CONTROL); + ret = h2fmi_wait(fmi, b->fmi, FMI_STATUS, 2, 2); + if (!ret) + ret = readl_poll_timeout(ch + CDMA_CSR, csr, + csr & (CDMA_CSR_ERROR | CDMA_CSR_HALTED), + 0, 2000000); + if (!ret && ((csr & CDMA_CSR_ERROR) || readl(ch + CDMA_DBR))) + ret = -EIO; + if (ret) { + dev_err(fmi->dev, + "CDMA channel %u %s %u bytes failed (%d): CSR %08x DCR %08x DBR %08x MAR %08x CAR %08x ERR %08x, FMI status %08x fifo %08x\n", + b->dma_ch, tx ? "to FMI" : "from FMI", len, ret, + readl(ch + CDMA_CSR), readl(ch + CDMA_DCR), + readl(ch + CDMA_DBR), readl(ch + CDMA_MAR), + readl(ch + CDMA_CAR), readl(ch + CDMA_ERR), + readl(b->fmi + FMI_STATUS), readl(b->fmi + FMI_DMA_STATUS)); + h2fmi_cdma_cancel(fmi, b->dma_ch); + return ret; + } + writel(CDMA_CSR_HALTED, ch + CDMA_CSR); + h2fmi_cdma_clock(fmi, b->dma_ch, false); + return 0; +} + +/* CDMA moves whole raw pages only, and only out of the linear map. */ +static bool h2fmi_dma_ok(struct h2fmi_bus *b, const u8 *buf, u32 len, + unsigned int direction) +{ + return (READ_ONCE(dma) & direction) && b->cmds && + len == H2FMI_PAGE_RAW && virt_addr_valid(buf) && + virt_addr_valid(buf + len - 1); +} + /* - * h2fmi_ppn_read_data_out: 7A, then the bytes by PIO in runs of at most 0x400. + * A raw page in, in the two runs of iBEC's h2fmi_read_raw_page + * (0xbff063ac): whole 1024-byte sectors with FMI_CONFIG 5 and bursts of 32 + * words, then the rest as one short sector with FMI_CONFIG 0 and + * single-word requests. iBEC takes the two lengths from its fmi state + * (+0x38 and +0x24 rounded up to words); here they are the 16384 and 64 + * bytes the PIO path already splits a page into. + */ +static int h2fmi_dma_page_in(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *buf) +{ + dma_addr_t addr; + int ret; + + addr = dma_map_single(fmi->dev, buf, H2FMI_PAGE_RAW, DMA_FROM_DEVICE); + if (dma_mapping_error(fmi->dev, addr)) + return -ENOMEM; + ret = h2fmi_dma_run(fmi, b, addr, H2FMI_DMA_BODY, false, 5, 32); + if (!ret) + ret = h2fmi_dma_run(fmi, b, addr + H2FMI_DMA_BODY, H2FMI_DMA_TAIL, + false, 0, 1); + dma_unmap_single(fmi->dev, addr, H2FMI_PAGE_RAW, DMA_FROM_DEVICE); + return ret; +} + +/* + * h2fmi_ppn_read_data_out: 7A, then the bytes: a whole page by CDMA where + * the node has it, else by PIO in runs of at most 0x400. * FMI_PIO_CONFIG is (bytes << 8) | sectors. */ static int h2fmi_data_out(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *buf, u32 len) { + bool by_dma = h2fmi_dma_ok(b, buf, len, H2FMI_DMA_READ); + ktime_t start; u32 off; int ret; @@ -380,6 +840,14 @@ static int h2fmi_data_out(struct h2fmi *fmi, struct h2fmi_bus *b, if (ret) return ret; + start = ktime_get(); + if (by_dma) { + ret = h2fmi_dma_page_in(fmi, b, buf); + if (ret) + return ret; + goto done; + } + for (off = 0; off < len; ) { u32 n = min_t(u32, len - off, 0x400); u32 nw = n < 4 ? 4 : n & ~3u; @@ -392,19 +860,50 @@ static int h2fmi_data_out(struct h2fmi *fmi, struct h2fmi_bus *b, return ret; off += nw; } +done: + if (len == H2FMI_PAGE_RAW) { + h2fmi_count(&xfer_read_us[by_dma], &xfer_read_pages[by_dma], start); + } return 0; } -/* - * h2fmi_device_reset without the PMGR pulse: stop the FMI and put the FMC back - * the way it was. iBoot leaves it in DDR (FMC_ON = 5) and that has to survive - * every sequence, because getting back to DDR afterwards needs a reboot. +static void h2fmi_save_ddr(struct h2fmi_bus *b, struct h2fmi_ddr_state *state) +{ + unsigned int i; + + state->on = readl(b->fmc + FMC_ON); + state->if_ctrl = readl(b->fmc + FMC_IF_CTRL); + state->status_timeout = false; + if (b->gate) + for (i = 0; i < ARRAY_SIZE(state->timing); i++) + state->timing[i] = readl(b->fmc + FMC_DDR_TIMING0 + i * sizeof(u32)); +} + +/* Normally just stop the FMI and restore the inherited interface. On a + * status timeout iBEC also pulses PMGR bit 31 and restores the DDR timings. */ -static void h2fmi_device_reset(struct h2fmi_bus *b, u32 on, u32 if_ctrl) +static void h2fmi_device_reset(struct h2fmi_bus *b, const struct h2fmi_ddr_state *state, + bool pulse) { + unsigned int i; + + if (pulse) { + b->seq_loaded = false; + writel(readl(b->gate) | BIT(31), b->gate); + readl(b->gate); + udelay(1); + writel(readl(b->gate) & ~BIT(31), b->gate); + readl(b->gate); + spin_lock(&h2fmi_stats_lock); + xfer_bus_resets++; + spin_unlock(&h2fmi_stats_lock); + } writel(6, b->fmi + FMI_CONTROL); - writel(on, b->fmc + FMC_ON); - writel(if_ctrl, b->fmc + FMC_IF_CTRL); + writel(state->on, b->fmc + FMC_ON); + if (pulse) + for (i = 0; i < ARRAY_SIZE(state->timing); i++) + writel(state->timing[i], b->fmc + FMC_DDR_TIMING0 + i * sizeof(u32)); + writel(state->if_ctrl, b->fmc + FMC_IF_CTRL); } /* @@ -751,6 +1250,50 @@ static void h2fmi_fail(struct h2fmi *fmi) WRITE_ONCE(fmi->reset_needed, true); } +/* The comparator timeout has already stopped RW_CTRL, dropped CE and + * cleared the latches. Verify CE0 with a fresh PPN operation-status cycle. + * Its response establishes communication only; the caller keeps its error. + */ +static int h2fmi_revalidate_bus(struct h2fmi *fmi, struct h2fmi_bus *b, + const struct h2fmi_ddr_state *state) +{ + u8 status; + int ret; + + h2fmi_device_reset(b, state, true); + h2fmi_clear_irqs(b); + writel(BIT(H2FMI_CE), b->fmc + FMC_CE_CTRL); + ret = h2fmi_status(fmi, b, &status, H2FMI_WAIT_READ, NULL); + if (!ret) { + ret = h2fmi_cmd1(fmi, b, 0x77); + if (!ret && (!(status & BIT(6)) || (status & BIT(4)))) + ret = -EIO; + } + writel(0, b->fmc + FMC_CE_CTRL); + h2fmi_device_reset(b, state, false); + return ret; +} + +static void h2fmi_finish_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, + const struct h2fmi_ddr_state *state, int ret) +{ + if (!b->sdr) { + if (state->status_timeout && b->gate) { + int err = h2fmi_revalidate_bus(fmi, b, state); + + if (!err) + return; + dev_err(fmi->dev, "bus %ld: DDR reset revalidation failed (%d)\n", + (long)(b - fmi->bus), err); + } else { + writel(0, b->fmc + FMC_CE_CTRL); + h2fmi_device_reset(b, state, false); + } + } + if (ret) + h2fmi_fail(fmi); +} + static int h2fmi_recover(struct h2fmi *fmi) { unsigned int i; @@ -787,13 +1330,16 @@ static int h2fmi_recover(struct h2fmi *fmi) /* Take a bus for one transaction, resetting the packages first if needed. */ static int h2fmi_lock(struct h2fmi *fmi, struct h2fmi_bus *b) { - if (READ_ONCE(fmi->reset_needed)) { - int ret = h2fmi_recover(fmi); + int ret; + mutex_lock(&b->lock); + while (READ_ONCE(fmi->reset_needed)) { + mutex_unlock(&b->lock); + ret = h2fmi_recover(fmi); if (ret) return ret; + mutex_lock(&b->lock); } - mutex_lock(&b->lock); return 0; } @@ -844,7 +1390,7 @@ static int h2fmi_read_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, u8 op, u8 op2, u32 address, int naddr, u8 *buffer, u32 length, u8 *status) { - u32 on, if_ctrl; + struct h2fmi_ddr_state state; int ret, end_ret; *status = 0; @@ -856,16 +1402,17 @@ static int h2fmi_read_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, h2fmi_fail(fmi); return ret; } - on = readl(b->fmc + FMC_ON); - if_ctrl = readl(b->fmc + FMC_IF_CTRL); - if (on != 5) + h2fmi_save_ddr(b, &state); + if (state.on != FMC_ON_DDR) { + h2fmi_fail(fmi); return -EIO; + } writel(1u << H2FMI_CE, b->fmc + FMC_CE_CTRL); h2fmi_clear_irqs(b); ret = h2fmi_cmd_addr_cmd(fmi, b, op, op2, address, naddr); if (!ret) - ret = h2fmi_status(fmi, b, status); + ret = h2fmi_status(fmi, b, status, H2FMI_WAIT_READ, &state); /* An error status has no data phase. Device parameters require GOOD; * normal pages also admit REFRESH and ERASED. Keep the status for the * MTD reader and bad-block query without copying a stale page buffer. @@ -874,16 +1421,15 @@ static int h2fmi_read_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, h2fmi_page_status(*status) >= 0)) ret = h2fmi_data_out(fmi, b, buffer, length); - /* Stop PIO before ending the operation, as in the parameter reader. */ - writel(6, b->fmi + FMI_CONTROL); - end_ret = h2fmi_cmd1(fmi, b, 0x77); - writel(0, b->fmc + FMC_CE_CTRL); - h2fmi_device_reset(b, on, if_ctrl); - if (ret || end_ret) { - h2fmi_fail(fmi); - return ret ? ret : end_ret; + /* A status timeout goes directly to controller recovery. */ + if (!(state.status_timeout && b->gate)) { + writel(6, b->fmi + FMI_CONTROL); + end_ret = h2fmi_cmd1(fmi, b, 0x77); + if (!ret) + ret = end_ret; } - return 0; + h2fmi_finish_transaction(fmi, b, &state, ret); + return ret; } static int h2fmi_read_geometry(struct h2fmi *fmi, struct h2fmi_bus *b) @@ -899,6 +1445,10 @@ static int h2fmi_read_geometry(struct h2fmi *fmi, struct h2fmi_bus *b) if (!ret) { ret = h2fmi_parse_geometry(b->page, H2FMI_PARAMS_SIZE, &b->geometry); + /* The 92/97 parameter page is P in iBEC 0xbff088da. */ + if (!ret) + b->queue_depth = min(get_unaligned_le32(b->page + 0xe4), + (u32)H2FMI_QUEUE_MAX); /* Keep what the package said, so a new profile can be added. */ if (ret) dev_err(fmi->dev, "unsupported PPN parameters: %*ph\n", @@ -947,16 +1497,34 @@ static int h2fmi_write_address(struct h2fmi *fmi, struct h2fmi_bus *b, /* Same PIO FIFO used by iBEC's feature writer, with CONTROL=5 for data in. * Every chunk must finish before the next one or the program confirm. + * With dma bit 1, CDMA fills the FIFO for the sixteen whole sectors: the + * channel, FIFO, FMI_CONFIG 5 and burst iBEC's fmiss_ppn_write_multi + * transmits with (0xbff0afda), started by CONTROL=5 as here. The last 64 + * bytes stay PIO. */ static int h2fmi_data_in(struct h2fmi *fmi, struct h2fmi_bus *b, const u8 *buffer, u32 length) { - u32 offset, index, value; + bool by_dma = h2fmi_dma_ok(b, buffer, length, H2FMI_DMA_PROGRAM); + ktime_t start = ktime_get(); + u32 offset = 0, index, value; int ret; if (!length || length & 3) return -EINVAL; - for (offset = 0; offset < length; ) { + if (by_dma) { + dma_addr_t addr = dma_map_single(fmi->dev, (void *)buffer, + H2FMI_DMA_BODY, DMA_TO_DEVICE); + + if (dma_mapping_error(fmi->dev, addr)) + return -ENOMEM; + ret = h2fmi_dma_run(fmi, b, addr, H2FMI_DMA_BODY, true, 5, 32); + dma_unmap_single(fmi->dev, addr, H2FMI_DMA_BODY, DMA_TO_DEVICE); + if (ret) + return ret; + offset = H2FMI_DMA_BODY; + } + for (; offset < length; ) { u32 bytes = min_t(u32, length - offset, 0x400); writel(5, b->fmi + FMI_CONFIG); @@ -975,24 +1543,28 @@ static int h2fmi_data_in(struct h2fmi *fmi, struct h2fmi_bus *b, return ret; offset += bytes; } + if (length == H2FMI_PAGE_RAW) { + h2fmi_count(&xfer_prog_us[by_dma], &xfer_prog_pages[by_dma], start); + } return 0; } /* Both page programming and the iBEC erase queue use status command 79. */ -static int h2fmi_write_status(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *status) +static int h2fmi_write_status(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *status, + struct h2fmi_ddr_state *state) { int ret = h2fmi_cmd1(fmi, b, 0x79); if (ret) return ret; - return h2fmi_poll_status(fmi, b, status); + return h2fmi_poll_status(fmi, b, status, H2FMI_WAIT_MUTATE, state); } -/* Caller holds the bus lock. A failed mutation resets the packages first. */ +/* Caller holds the bus lock through completion and any timeout recovery. */ static int h2fmi_program_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, u32 row, const u8 *raw) { - u32 on, if_ctrl; + struct h2fmi_ddr_state state; u8 status = 0; int ret; @@ -1018,10 +1590,11 @@ static int h2fmi_program_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, h2fmi_sdr_reset(b); goto done; } - on = readl(b->fmc + FMC_ON); - if_ctrl = readl(b->fmc + FMC_IF_CTRL); - if (on != 5) + h2fmi_save_ddr(b, &state); + if (state.on != FMC_ON_DDR) { + h2fmi_fail(fmi); return -EIO; + } writel(1u << H2FMI_CE, b->fmc + FMC_CE_CTRL); h2fmi_clear_irqs(b); ret = h2fmi_write_address(fmi, b, row); @@ -1030,17 +1603,15 @@ static int h2fmi_program_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, if (!ret) ret = h2fmi_cmd1(fmi, b, 0x17); if (!ret) - ret = h2fmi_write_status(fmi, b, &status); + ret = h2fmi_write_status(fmi, b, &status, &state); /* CMD 79 returns NAND write status, not the managed read result. * iBEC 12H321 tests failure bits 0 and 4 after ready bit 6. */ if (!ret) ret = h2fmi_program_status(status); - writel(0, b->fmc + FMC_CE_CTRL); - h2fmi_device_reset(b, on, if_ctrl); done: + h2fmi_finish_transaction(fmi, b, &state, ret); if (ret) { - h2fmi_fail(fmi); dev_err(fmi->dev, "PPN program row %08x: status %02x, error %d\n", row, status, ret); } @@ -1063,6 +1634,15 @@ static void h2fmi_join_page(u8 *raw, const u8 *data, const u8 *oob) } } +static bool h2fmi_page_erased(const struct h2fmi *fmi, u8 status, const u8 *raw) +{ + if (!fmi->clean_by_status) + return h2fmi_raw_page_erased(status, raw); + return h2fmi_raw_page_erased_bounded(status, raw, + H2FMI_CLEAN_MAX_NON_FF_BYTES, + H2FMI_CLEAN_MAX_ZERO_BITS); +} + /* Canonical data and metadata form one complete PPN program unit. */ static int h2fmi_program_page(struct h2fmi *fmi, struct h2fmi_bus *b, unsigned int cau, unsigned int block, @@ -1070,34 +1650,41 @@ static int h2fmi_program_page(struct h2fmi *fmi, struct h2fmi_bus *b, { u32 row; u8 status, *expected; + bool checked; int ret; if (fmi->read_only) return -EROFS; if (!data || !oob) return -EINVAL; - ret = h2fmi_page_row(&b->geometry, cau, block, page, &row); + /* Preserve the boot block, BFN/package tail and VFL blocks. */ + ret = h2fmi_program_row(&b->geometry, cau, block, page, &row); if (ret) return ret; - /* Preserve the boot block and both package-reserved tail blocks. */ - if (!block || block >= b->geometry.blocks - 2) - return -EPERM; expected = kmalloc(H2FMI_PAGE_RAW, GFP_KERNEL); if (!expected) return -ENOMEM; h2fmi_join_page(expected, data, oob); + /* Long SFTL jobs reach the NAND page by page: let the scheduler (and the + * watchdog's pinger) run between pages on a non-preemptible kernel. */ + cond_resched(); ret = h2fmi_lock(fmi, b); if (ret) { kfree(expected); return ret; } - ret = h2fmi_read_transaction(fmi, b, 0x0a, 0x37, row, 4, - b->page, H2FMI_PAGE_RAW, &status); - if (ret) - goto out; - if (!h2fmi_raw_page_erased(status, b->page)) { - ret = -EEXIST; - goto out; + /* verify=0: no blank check before and no read-back after; status 79 + * alone decides (h2fmi_program_transaction), as in iOS and iBEC. */ + checked = !fmi->n42 || READ_ONCE(verify); + if (checked) { + ret = h2fmi_read_transaction(fmi, b, 0x0a, 0x37, row, 4, + b->page, H2FMI_PAGE_RAW, &status); + if (ret) + goto out; + if (!h2fmi_page_erased(fmi, status, b->page)) { + ret = -EEXIST; + goto out; + } } if (h2fmi_inject(h2fmi_fail_program)) { dev_warn(fmi->dev, "PPN program row %08x: injected failure\n", row); @@ -1105,19 +1692,22 @@ static int h2fmi_program_page(struct h2fmi *fmi, struct h2fmi_bus *b, goto out; } ret = h2fmi_program_transaction(fmi, b, row, expected); - if (ret) - goto out; + if (ret || !checked) + goto landed; ret = h2fmi_read_transaction(fmi, b, 0x0a, 0x37, row, 4, b->page, H2FMI_PAGE_RAW, &status); if (ret || status != PPN_ST_GOOD || memcmp(b->page, expected, H2FMI_PAGE_RAW)) { - h2fmi_fail(fmi); - ret = ret ? ret : -EIO; + if (!ret) { + h2fmi_fail(fmi); + ret = -EIO; + } dev_err(fmi->dev, "PPN readback row %08x: status %02x, error %d\n", row, status, ret); goto out; } - if (h2fmi_inject(h2fmi_fail_program_landed)) { +landed: + if (!ret && h2fmi_inject(h2fmi_fail_program_landed)) { dev_warn(fmi->dev, "PPN program row %08x: injected failure after programming\n", row); h2fmi_fail(fmi); @@ -1165,31 +1755,43 @@ static int h2fmi_mtd_write_oob(struct mtd_info *mtd, loff_t to, * 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. + * SanDisk package reports erased status (0x49) directly (iBEC 12H321 + * 0xbff09908 and AppleSwissPPNFTL s_read.c 0x80dd52ba trust status without + * scanning payload bytes), and isolated erased pages can show single-bit + * read disturb (observed once across >2,500 Flight 1 0x49 reads: 16,447 of + * 16,448 FF bytes on block 164 lane 0 page 0). Where clean_by_status is + * set (S5L8950X), accept bounded erased-cell disturb and normalize the page + * to FF, while still refusing genuinely programmed or torn data that reports + * status 0x49. * 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; + bool bounded; if (!fmi->clean_by_status) return false; - if (fmi->clean_logged < 8) { - fmi->clean_logged++; + bounded = h2fmi_raw_page_erased_bounded(PPN_ST_ERASED, b->page, + H2FMI_CLEAN_MAX_NON_FF_BYTES, + H2FMI_CLEAN_MAX_ZERO_BITS); + if (!bounded || fmi->clean_logged < 8) { 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); + if (!bounded) { + dev_err(fmi->dev, + "row %08x status 49 rejected: %u FF, %u 00 of %u bytes, data %16ph meta %16ph\n", + row, ff, zero, H2FMI_PAGE_RAW, b->page, + b->page + H2FMI_CHUNK_LO); + return false; + } + fmi->clean_logged++; + dev_info(fmi->dev, + "row %08x status 49 with bounded disturb: %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; @@ -1214,6 +1816,9 @@ static int h2fmi_read_page_at(struct mtd_info *mtd, loff_t from, if (ret) return ret; + /* Long SFTL jobs reach the NAND page by page: let the scheduler (and the + * watchdog's pinger) run between pages on a non-preemptible kernel. */ + cond_resched(); ret = h2fmi_lock(fmi, b); if (ret) return ret; @@ -1259,6 +1864,9 @@ static int h2fmi_ppn_read(void *priv, unsigned int bus, unsigned int cau, /* Retired pages have no data phase. Never return a stale page buffer. */ memset(data, 0, H2FMI_PAGE_DATA); memset(oob, 0, H2FMI_PAGE_OOB); + /* Long SFTL jobs reach the NAND page by page: let the scheduler (and the + * watchdog's pinger) run between pages on a non-preemptible kernel. */ + cond_resched(); ret = h2fmi_lock(fmi, b); if (ret) return ret; @@ -1277,114 +1885,1533 @@ static int h2fmi_ppn_read(void *priv, unsigned int bus, unsigned int cau, return ret; } -static int h2fmi_ppn_program(void *priv, unsigned int bus, unsigned int cau, - unsigned int block, unsigned int page, - const u8 *data, const u8 *oob) +/* N42 iBEC 12H321, fmiss channel program RAM at 0xbff45248. */ +static const u32 h2fmi_seq_ram[] = { + 0x08000077, 0x0800007d, SEQ_DELAY, 0x0a004040, 0x14040048, + 0x08000079, SEQ_DELAY, 0x0a004040, 0x0cff0000, 0x0d000000, + 0x08000079, SEQ_DELAY, 0x0a015140, 0x14040048, + 0x10040020, 0x10040018, 0x1004001c, 0x10040014, 0x0f040010, + 0x0000000b, 0x12040044, 0x0000000b, 0x0000000b, 0x0f040044, + 0x0000000b, SEQ_DELAY | 1, + 0x10040018, 0x10040014, 0x0f040010, 9, 0x12040044, 9, 9, 0x0f040044, 9, + 0x0f040014, 0xb0, 0x10040018, 0x0f040020, 2, 0x0f040010, 9, + 0x12040044, 9, 9, 0x0f040044, 9, +}; + +static void h2fmi_seq_load(struct h2fmi_bus *b) { - struct h2fmi *fmi = priv; + unsigned int i; - if (bus >= H2FMI_BUSES) - return -EINVAL; - return h2fmi_program_page(fmi, &fmi->bus[bus], cau, block, page, data, oob); + lockdep_assert_held(&b->lock); + if (b->seq_loaded) + return; + for (i = 0; i < ARRAY_SIZE(h2fmi_seq_ram); i++) { + u32 word = h2fmi_seq_ram[i]; + + if (word == SEQ_DELAY) + word = b->delay100; + else if (word == (SEQ_DELAY | 1)) + word = b->delay60; + writel(word, b->seq + SEQ_RAM + 4 * i); + } + b->seq_loaded = true; } -/* - * The single-row iBEC erase queue sends 6A/D7, checks queue status (79) - * and operation status (77/7D), then ends the operation (77). Do not - * retry an uncertain erase. The caller holds the bus lock through readback. - */ -static int h2fmi_erase_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, u32 row) +/* Each transaction supplies its own entry mode and clears pending events. */ +static void h2fmi_seq_start(struct h2fmi_bus *b, u32 control) { - u32 on, if_ctrl; - u8 queued = 0, completed = 0; - int ret; - - if (b->failed) - return -EIO; - if (b->sdr) { - h2fmi_sdr_reset(b); - writel(1u << H2FMI_CE, b->fmc + FMC_CE_CTRL); - h2fmi_sdr_clear(b); - ret = h2fmi_cmd_addr_cmd(fmi, b, 0x6a, 0xd7, row, 4); - if (!ret) - ret = h2fmi_cmd1(fmi, b, 0x79); - if (!ret) - ret = h2fmi_sdr_poll(fmi, b, &queued); - if (!ret) - ret = h2fmi_sdr_status(fmi, b, &completed); - if (!ret) - ret = h2fmi_cmd1(fmi, b, 0x77); - writel(0, b->fmc + FMC_CE_CTRL); - h2fmi_sdr_reset(b); - goto done; - } - on = readl(b->fmc + FMC_ON); - if_ctrl = readl(b->fmc + FMC_IF_CTRL); - if (on != 5) - return -EIO; + writel(b->seq_clock, b->seq + SEQ_CLOCK); + writel(control, b->fmi + FMI_CONTROL); + writel(U32_MAX, b->seq + SEQ_EVENT); +} - writel(1u << H2FMI_CE, b->fmc + FMC_CE_CTRL); - h2fmi_clear_irqs(b); - ret = h2fmi_cmd_addr_cmd(fmi, b, 0x6a, 0xd7, row, 4); - if (!ret) - ret = h2fmi_write_status(fmi, b, &queued); - if (!ret) - ret = h2fmi_status(fmi, b, &completed); - if (!ret) - ret = h2fmi_cmd1(fmi, b, 0x77); +/* Both batch engines stop their DMA streams before resetting the controller. */ +static void h2fmi_seq_recover(struct h2fmi *fmi, struct h2fmi_bus *b, + const struct h2fmi_ddr_state *state) +{ + writel(0x300, b->fmi + FMI_CONTROL); + writel(0, b->fmc + FMC_RW_CTRL); writel(0, b->fmc + FMC_CE_CTRL); - h2fmi_device_reset(b, on, if_ctrl); -done: - if (!ret && (queued != PPN_ST_GOOD || completed != PPN_ST_GOOD)) { - dev_err(fmi->dev, "PPN erase row %08x: queue %02x, completion %02x\n", - row, queued, completed); - ret = -EIO; - } - return ret; + h2fmi_clear_irqs(b); + if (h2fmi_revalidate_bus(fmi, b, state)) + h2fmi_fail(fmi); } -static int h2fmi_ppn_erase(void *priv, unsigned int bus, unsigned int cau, - unsigned int block) -{ - struct h2fmi *fmi = priv; +struct h2fmi_read_job { + struct h2fmi_command_time time; + struct work_struct work; + struct h2fmi *fmi; struct h2fmi_bus *b; - unsigned int page; - u32 row; - u8 status; + struct apple_ppn_read *pages; + unsigned int n, segments, next_dma, cmd_level, arg_level, results; + void (*scatter)(void *); + void *scatter_ctx; + unsigned long deadline; + bool active[2]; int ret; +}; + +/* A logical data transfer can cross several 1 KiB hardware command lists. + * DBR describes the entire stream and is programmed only on first start. + */ +static void h2fmi_read_chain(struct h2fmi_read_job *j, unsigned int stream) +{ + struct h2fmi_multi *m = j->b->multi; + void __iomem *ch = j->fmi->cdma + CDMA_CH(j->b->dma_ch + stream); + __le32 *d = m->desc[stream]; + u32 base = m->desc_addr[stream]; + unsigned int count = stream ? 1 : min(j->segments - j->next_dma, (unsigned int)CDMA_CHAIN_ROWS); + unsigned int i; + + for (i = 0; i < count; i++, d += CDMA_CMD_SIZE / sizeof(*d)) { + u32 flags = CDMA_ATTR_RX << 24 | CDMA_CMD_MEM; + + if (i + 1 == count) + flags |= CDMA_CMD_LAST; + d[0] = cpu_to_le32(base + (i + 1) * CDMA_CMD_SIZE); + d[1] = cpu_to_le32(flags); + d[2] = cpu_to_le32(stream ? m->meta_addr : m->data_addr[j->next_dma]); + d[3] = cpu_to_le32(stream ? j->n * H2FMI_PAGE_OOB : m->data_len[j->next_dma++]); + } + d[1] = 0; + dma_wmb(); + writel(base, ch + CDMA_CAR); + writel(CDMA_CSR_START, ch + CDMA_CSR); +} + +static void h2fmi_read_dma_start(struct h2fmi_read_job *j, unsigned int stream) +{ + struct h2fmi_bus *b = j->b; + unsigned int channel = b->dma_ch + stream; + void __iomem *ch = j->fmi->cdma + CDMA_CH(channel); + + if (!(readl(j->fmi->cdma + CDMA_CLK_STATUS) & BIT(channel))) + h2fmi_cdma_clock(j->fmi, channel, true); + writel(CDMA_CSR_ABORT, ch + CDMA_CSR); + writel(((b->dma_req + stream) << 16) | (stream ? 0x28 : 0x38), ch + CDMA_DCR); + writel(b->fifo + 4 * stream, ch + CDMA_DAR); + writel(j->n * (stream ? H2FMI_PAGE_OOB : H2FMI_PAGE_DATA), ch + CDMA_DBR); + j->active[stream] = true; + h2fmi_read_chain(j, stream); +} + +static int h2fmi_read_dma_poll(struct h2fmi_read_job *j, unsigned int stream) +{ + unsigned int channel = j->b->dma_ch + stream; + void __iomem *ch = j->fmi->cdma + CDMA_CH(channel); + u32 csr; + + if (!j->active[stream]) + return 0; + csr = readl(ch + CDMA_CSR); + if (csr & (CDMA_CSR_ERROR | CDMA_CSR_CMD_IRQ)) + return -EIO; + if (!(csr & CDMA_CSR_HALTED)) + return 0; + writel(CDMA_CSR_HALTED, ch + CDMA_CSR); + if (!stream && j->next_dma < j->segments) { + h2fmi_read_chain(j, stream); + return 0; + } + if (readl(ch + CDMA_DBR)) + return -EIO; + h2fmi_cdma_clock(j->fmi, channel, false); + j->active[stream] = false; + return 0; +} + +static int h2fmi_read_service(struct h2fmi_read_job *j) +{ + if (readl(j->b->seq + SEQ_EVENT) & BIT(7)) + return -EIO; + if (time_after_eq(jiffies, j->deadline)) + return -ETIMEDOUT; + cond_resched(); + /* Data can stop at descriptor 31 while the sequencer waits for its + * FIFO to drain. Service that halt even inside a FIFO-space wait. + */ + return h2fmi_read_dma_poll(j, 0); +} + +static int h2fmi_read_push(struct h2fmi_read_job *j, unsigned int port, u32 word) +{ + void __iomem *seq = j->b->seq; + unsigned int *level = port == SEQ_ARG ? &j->arg_level : &j->cmd_level; + int ret; + + while (*level >= SEQ_DEPTH) { + *level = readl(seq + port + 4) & 0x3f; + if (*level < SEQ_DEPTH) + break; + ret = h2fmi_read_service(j); + if (ret) + return ret; + } + writel(word, seq + port); + (*level)++; + return 0; +} + +static int h2fmi_read_issue(struct h2fmi_read_job *j, unsigned int i) +{ + const u32 args[] = { 7, H2FMI_PAGE_RAW, j->b->multi->row[i], + i + 1 == j->n ? 0x370a : 0x3707 }; + unsigned int k; + int ret; + + ret = h2fmi_read_push(j, SEQ_CMD, SEQ_SELECT | BIT(H2FMI_CE)); + for (k = 0; !ret && k < ARRAY_SIZE(args); k++) + ret = h2fmi_read_push(j, SEQ_ARG, args[k]); + return ret ?: h2fmi_read_push(j, SEQ_CMD, 0x11000e0c); +} + +static int h2fmi_read_result(struct h2fmi_read_job *j, unsigned int i) +{ + struct apple_ppn_read *p = &j->pages[i]; + void __iomem *seq = j->b->seq; + int ret; + + while (!j->results) { + j->results = readl(seq + SEQ_RESULT_LEVEL) & 0x3f; + if (j->results) + break; + ret = h2fmi_read_service(j); + if (ret) + return ret; + } + p->status = readl(seq + SEQ_RESULT); + j->results--; + switch (p->status) { + case 0x40: + case 0x42: + case 0x44: + case 0x49: + p->ret = 0; + break; + default: + p->ret = -EBADMSG; + } + return p->status & BIT(4) ? -EIO : 0; +} + +static int h2fmi_read_output(struct h2fmi_read_job *j) +{ + struct h2fmi_bus *b = j->b; + /* Toggle DDR has no inter-unit delay (bff05ab4-bff05acc). */ + const u32 words[] = { + 0x11000005, b->delay100, 0x0800007a, b->delay60, + SEQ_DATA, SEQ_DATA, SEQ_DATA, SEQ_DATA, b->delay100, + }; + unsigned int i; + int ret; + + for (i = 0; i < ARRAY_SIZE(words); i++) { + ret = h2fmi_read_push(j, SEQ_CMD, words[i]); + if (ret) + return ret; + } + return 0; +} + +static int h2fmi_read_sequence(struct h2fmi_read_job *j) +{ + struct h2fmi_bus *b = j->b; + unsigned int issued = 0, consumed = 0, i, stream; + int ret; + + h2fmi_seq_load(b); + writel(6, b->fmi + FMI_CONTROL); + writel(0x2403, b->fmi + FMI_CONFIG); + writel(0x20840004, b->fmi + FMI_PIO_CONFIG); + h2fmi_seq_start(b, 0x5302); + j->time.submit = ktime_get(); + + j->deadline = jiffies + 2 * HZ; + for (i = 0; i < j->n; i++) { + while (issued < j->n && issued - i < SEQ_DEPTH) { + ret = h2fmi_read_issue(j, issued++); + if (ret) + return ret; + } + if (!i) { + h2fmi_read_dma_start(j, 0); + h2fmi_read_dma_start(j, 1); + if (j->scatter) + j->scatter(j->scatter_ctx); + } + ret = h2fmi_read_push(j, SEQ_CMD, SEQ_SELECT | BIT(H2FMI_CE)); + if (!ret && i >= SEQ_DEPTH) + ret = h2fmi_read_result(j, consumed++); + if (!ret) + ret = h2fmi_read_output(j); + if (ret) + return ret; + } + ret = h2fmi_read_push(j, SEQ_CMD, SEQ_SELECT | BIT(H2FMI_CE)); + if (!ret) + ret = h2fmi_read_push(j, SEQ_CMD, 0x08000077); + if (!ret) + ret = h2fmi_read_push(j, SEQ_CMD, SEQ_SELECT); + while (!ret && consumed < j->n) + ret = h2fmi_read_result(j, consumed++); + for (stream = 0; !ret && stream < 2; stream++) { + j->deadline = jiffies + 2 * HZ; + while (!ret && j->active[stream]) { + h2fmi_wait_dma_irq(j->fmi, b, stream, H2FMI_IRQ_READ); + ret = h2fmi_read_dma_poll(j, stream); + if (!ret && j->active[stream]) + ret = h2fmi_read_service(j); + } + } + return ret; +} + +static void h2fmi_read_bus(struct h2fmi_read_job *j) +{ + struct h2fmi_bus *b = j->b; + struct h2fmi_multi *m = b->multi; + struct h2fmi_ddr_state state; + unsigned int i, k; + int ret; + + ret = h2fmi_lock(j->fmi, b); + if (ret) + goto failed; + if (b->failed || b->sdr) { + ret = -EIO; + goto unlock; + } + for (i = 0; i < j->n; i++) { + struct apple_ppn_read *p = &j->pages[i]; + + ret = h2fmi_page_row(&b->geometry, p->cau, p->block, p->page, &m->row[i]); + if (ret) + goto unmap; + if (!p->target[0] && !p->target[1] && !p->target[2] && !p->target[3]) { + dma_addr_t addr = dma_map_page(j->fmi->dev, virt_to_page(p->data), + offset_in_page(p->data), H2FMI_PAGE_DATA, DMA_FROM_DEVICE); + + if (dma_mapping_error(j->fmi->dev, addr)) { + ret = -ENOMEM; + goto unmap; + } + m->data_len[j->segments] = H2FMI_PAGE_DATA; + m->data_addr[j->segments++] = addr; + continue; + } + for (k = 0; k < 4; k++) { + u8 *bounce = p->data ? p->data + k * 4096 : NULL; + struct page *dest = p->target[k] ?: virt_to_page(bounce); + unsigned int off = p->target[k] ? 0 : offset_in_page(bounce); + dma_addr_t addr = dma_map_page(j->fmi->dev, dest, off, 4096, DMA_FROM_DEVICE); + + if (dma_mapping_error(j->fmi->dev, addr)) { + ret = -ENOMEM; + goto unmap; + } + m->data_len[j->segments] = 4096; + m->data_addr[j->segments++] = addr; + } + } + h2fmi_save_ddr(b, &state); + ret = h2fmi_read_sequence(j); + j->time.complete = ktime_get(); + if (ret) { + for (i = 2; i-- > 0; ) + if (j->active[i] && h2fmi_cdma_cancel(j->fmi, b->dma_ch + i)) + b->failed = true; + h2fmi_seq_recover(j->fmi, b, &state); + } else { + dma_rmb(); + for (i = 0; i < j->n; i++) + memcpy(j->pages[i].oob, m->meta + i * H2FMI_PAGE_OOB, H2FMI_PAGE_OOB); + } +unmap: + for (i = 0; i < j->segments; i++) + dma_unmap_page(j->fmi->dev, m->data_addr[i], m->data_len[i], DMA_FROM_DEVICE); +unlock: + mutex_unlock(&b->lock); +failed: + j->ret = ret; + if (ret) + for (i = 0; i < j->n; i++) + j->pages[i].ret = ret; +} + +static void h2fmi_read_work(struct work_struct *work) +{ + struct h2fmi_read_job *j = container_of(work, struct h2fmi_read_job, work); + unsigned int noio = memalloc_noio_save(); + + h2fmi_read_bus(j); + memalloc_noio_restore(noio); +} + +static bool h2fmi_multi_read_enabled(void *priv) +{ + struct h2fmi *fmi = priv; + + return READ_ONCE(multi_read) && (READ_ONCE(dma) & H2FMI_DMA_READ) && + !READ_ONCE(fmi->bus[0].sdr) && !READ_ONCE(fmi->bus[1].sdr); +} + +static int h2fmi_ppn_read_overlap(void *priv, struct apple_ppn_read *pages, unsigned int n, + void (*scatter)(void *), void *ctx) +{ + struct h2fmi *fmi = priv; + struct h2fmi_read_job jobs[H2FMI_BUSES] = {}; + unsigned int bus, i; + ktime_t start = ktime_get(); + + if (!h2fmi_multi_read_enabled(fmi)) + return -EOPNOTSUPP; + if (!pages || !n || n > H2FMI_BUSES * APPLE_PPN_READ_MAX_PER_BUS) + return -EINVAL; + for (i = 0; i < n; i++) { + struct apple_ppn_read *p = &pages[i]; + struct h2fmi_read_job *j; + + bus = p->bus; + if (bus >= H2FMI_BUSES || (i && pages[i - 1].bus > bus) || !p->oob || + (!p->data && (!p->target[0] || !p->target[1] || !p->target[2] || !p->target[3]))) + return -EINVAL; + j = &jobs[bus]; + if (!j->n) { + j->b = &fmi->bus[bus]; + j->fmi = fmi; + j->pages = p; + } + if (++j->n > APPLE_PPN_READ_MAX_PER_BUS) + return -E2BIG; + p->status = 0; + p->ret = -ECANCELED; + } + jobs[!jobs[0].n].scatter = scatter; + jobs[!jobs[0].n].scatter_ctx = ctx; + if (jobs[0].n && jobs[1].n) { + INIT_WORK_ONSTACK(&jobs[1].work, h2fmi_read_work); + queue_work(fmi->wq, &jobs[1].work); + h2fmi_read_bus(&jobs[0]); + flush_work(&jobs[1].work); + destroy_work_on_stack(&jobs[1].work); + } else { + h2fmi_read_bus(jobs[0].n ? &jobs[0] : &jobs[1]); + } + h2fmi_count_overlap(&jobs[0].time, &jobs[1].time); + spin_lock(&h2fmi_stats_lock); + for (bus = 0; bus < H2FMI_BUSES; bus++) + if (jobs[bus].time.submit) + xfer_multi_max_pages[1] = max(xfer_multi_max_pages[1], jobs[bus].n); + xfer_multi_reads++; + xfer_multi_read_pages += n; + xfer_multi_read_us += ktime_us_delta(ktime_get(), start); + spin_unlock(&h2fmi_stats_lock); + return jobs[0].ret ?: jobs[1].ret; +} + +static int h2fmi_ppn_read_pages(void *priv, struct apple_ppn_read *pages, unsigned int n) +{ + return h2fmi_ppn_read_overlap(priv, pages, n, NULL, NULL); +} + +/* A sequencer exception can end the data stream before every row has + * produced bytes. In that case the caller retries the window individually. + * For exceptional rows of a completed stream use the canonical reader: + * it owns retirement, uECC and the bounded clean-status normalization. + */ +static int h2fmi_ppn_read_scan_pages(void *priv, struct apple_ppn_read *pages, unsigned int n) +{ + unsigned int i; + int ret = h2fmi_ppn_read_pages(priv, pages, n); + + if (ret) + return ret; + for (i = 0; i < n; i++) { + struct apple_ppn_read *p = &pages[i]; + + /* Status belongs to this row of a transport-complete command. + * These three VFL results carry the uncorrectable bit. A general + * error (0x51) has already taken the controller recovery path. + */ + if (p->status == 0x43 || p->status == PPN_ST_RETIRED || p->status == 0xc1) { + p->ret = -EBADMSG; + continue; + } + if (!p->ret && (p->status == PPN_ST_GOOD || p->status == PPN_ST_REFRESH || + (p->status == PPN_ST_ERASED && !memchr_inv(p->data, 0xff, H2FMI_PAGE_DATA) && + !memchr_inv(p->oob, 0xff, H2FMI_PAGE_OOB)))) + continue; + p->ret = h2fmi_ppn_read(priv, p->bus, p->cau, p->block, p->page, false, + p->data, p->oob, &p->status); + } + return 0; +} + +static int h2fmi_ppn_program(void *priv, unsigned int bus, unsigned int cau, + unsigned int block, unsigned int page, + const u8 *data, const u8 *oob) +{ + struct h2fmi *fmi = priv; + + if (bus >= H2FMI_BUSES) + return -EINVAL; + return h2fmi_program_page(fmi, &fmi->bus[bus], cau, block, page, data, oob); +} + +/* + * The single-row iBEC erase queue sends 6A/D7, checks queue status (79) + * and operation status (77/7D), then ends the operation (77). Do not + * retry an uncertain erase. The caller holds the bus lock through readback. + */ +static int h2fmi_erase_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, u32 row) +{ + struct h2fmi_ddr_state state; + u8 queued = 0, completed = 0; + int ret; + + if (b->failed) + return -EIO; + if (b->sdr) { + h2fmi_sdr_reset(b); + writel(1u << H2FMI_CE, b->fmc + FMC_CE_CTRL); + h2fmi_sdr_clear(b); + ret = h2fmi_cmd_addr_cmd(fmi, b, 0x6a, 0xd7, row, 4); + if (!ret) + ret = h2fmi_cmd1(fmi, b, 0x79); + if (!ret) + ret = h2fmi_sdr_poll(fmi, b, &queued); + if (!ret) + ret = h2fmi_sdr_status(fmi, b, &completed); + if (!ret) + ret = h2fmi_cmd1(fmi, b, 0x77); + writel(0, b->fmc + FMC_CE_CTRL); + h2fmi_sdr_reset(b); + goto done; + } + h2fmi_save_ddr(b, &state); + if (state.on != FMC_ON_DDR) { + h2fmi_fail(fmi); + return -EIO; + } + + writel(1u << H2FMI_CE, b->fmc + FMC_CE_CTRL); + h2fmi_clear_irqs(b); + ret = h2fmi_cmd_addr_cmd(fmi, b, 0x6a, 0xd7, row, 4); + if (!ret) + ret = h2fmi_write_status(fmi, b, &queued, &state); + if (!ret) + ret = h2fmi_status(fmi, b, &completed, H2FMI_WAIT_MUTATE, &state); + if (!ret) + ret = h2fmi_cmd1(fmi, b, 0x77); +done: + /* + * As the 12H321 iBEC's erase queue judges it (0xbff08204, 0xbff079a4): + * a status is taken once ready (40) is set, and the erase failed only + * if bit 4 (10) is set in the queue or the completion status. A queue + * status of 44 (bit 2 set) is a pass there. Every erased page is still + * read back afterwards. + */ + if (!ret && (!(queued & PPN_ST_GOOD) || (queued & 0x10) || + !(completed & PPN_ST_GOOD) || (completed & 0x10))) { + dev_err(fmi->dev, "PPN erase row %08x: queue %02x, completion %02x\n", + row, queued, completed); + ret = -EIO; + } else if (!ret && (queued != PPN_ST_GOOD || completed != PPN_ST_GOOD)) { + dev_dbg(fmi->dev, "PPN erase row %08x: queue %02x, completion %02x (pass)\n", + row, queued, completed); + } + h2fmi_finish_transaction(fmi, b, &state, ret); + return ret; +} + +static int h2fmi_ppn_erase(void *priv, unsigned int bus, unsigned int cau, + unsigned int block) +{ + struct h2fmi *fmi = priv; + struct h2fmi_bus *b; + unsigned int page; + ktime_t start; + u32 row; + u8 status; + int ret; + + if (fmi->read_only) + return -EROFS; + if (bus >= H2FMI_BUSES) + return -EINVAL; + b = &fmi->bus[bus]; + ret = h2fmi_erase_row(&b->geometry, cau, block, &row); + if (ret) + return ret; + + if (h2fmi_inject(h2fmi_fail_erase)) { + dev_warn(fmi->dev, "PPN erase row %08x: injected failure\n", row); + return -EIO; + } + /* Long SFTL jobs reach the NAND page by page: let the scheduler (and the + * watchdog's pinger) run between pages on a non-preemptible kernel. */ + cond_resched(); + ret = h2fmi_lock(fmi, b); + if (ret) + return ret; + start = ktime_get(); + ret = h2fmi_erase_transaction(fmi, b, row); + /* verify=0: the queue and completion statuses alone decide, as the + * PPNVFL erase (0x80de1a10) and iBEC's erase queue do. */ + for (page = 0; !ret && (!fmi->n42 || READ_ONCE(verify)) && page < b->geometry.pages; page++) { + ret = h2fmi_read_transaction(fmi, b, 0x0a, 0x37, row + page, 4, + b->page, H2FMI_PAGE_RAW, &status); + if (!ret && !h2fmi_page_erased(fmi, status, b->page)) { + h2fmi_fail(fmi); + dev_err(fmi->dev, "PPN erase readback row %08x: status %02x\n", + row + page, status); + ret = -EIO; + } + } + if (!ret) + h2fmi_count(&xfer_erase_us, &xfer_erases, start); + mutex_unlock(&b->lock); + return ret; +} + +struct h2fmi_erase_work { + struct work_struct work; + struct h2fmi *fmi; + unsigned long deadline; + unsigned int block, bus; + u16 lanes; + int ret; +}; + +static void h2fmi_erase_bus(struct h2fmi_erase_work *job) +{ + unsigned int lane; + + for (lane = job->bus; lane < 4; lane += 2) { + if (!(job->lanes & BIT(lane))) + continue; + if (time_after_eq(jiffies, job->deadline)) { + job->ret = -ETIMEDOUT; + return; + } + job->ret = h2fmi_ppn_erase(job->fmi, job->bus, lane >> 1, job->block); + if (job->ret) + return; + } +} + +static void h2fmi_erase_worker(struct work_struct *work) +{ + struct h2fmi_erase_work *job = container_of(work, struct h2fmi_erase_work, work); + unsigned int noio = memalloc_noio_save(); + + h2fmi_erase_bus(job); + memalloc_noio_restore(noio); +} + +static int h2fmi_erase_lanes(void *priv, unsigned int block, u16 lanes, unsigned long deadline) +{ + struct h2fmi *fmi = priv; + struct h2fmi_erase_work a = { .fmi = fmi, .deadline = deadline, .block = block, .lanes = lanes }; + struct h2fmi_erase_work b = a; + + if (!lanes || (lanes & ~0xf)) + return -EINVAL; + b.bus = 1; + if (fmi->wq && READ_ONCE(parallel_buses) && (lanes & 5) && (lanes & 10)) { + INIT_WORK_ONSTACK(&b.work, h2fmi_erase_worker); + queue_work(fmi->wq, &b.work); + h2fmi_erase_bus(&a); + flush_work(&b.work); + destroy_work_on_stack(&b.work); + } else { + h2fmi_erase_bus(&a); + if (!a.ret) + h2fmi_erase_bus(&b); + } + return a.ret ?: b.ret; +} + +struct h2fmi_batch { + struct h2fmi *fmi; + struct h2fmi_batch *peer; + struct h2fmi_command_time time; + struct apple_ppn_program *page[H2FMI_QUEUE_MAX]; + struct h2fmi_bus *b; + unsigned int n, done, cmd_level, arg_level; + unsigned int mapped, submitted; + int error; + struct h2fmi_ddr_state state; + ktime_t start; + bool started, payload, flagged, end_event, row_errors; +}; + +/* Data and metadata use separate descriptor pairs in the bus's four slots. + * The list borrows the data channel until prep completes. + */ +static int h2fmi_seq_dma_start(struct h2fmi *fmi, struct h2fmi_bus *b, + bool meta, dma_addr_t addr, u32 len, u32 burst) +{ + u32 offset = meta ? 2 * CDMA_CMD_SIZE : 0; + dma_addr_t commands = b->cmds_bus + offset; + u32 dcr; + int ret; + + ret = h2fmi_cdma_dcr(b->dma_req + meta, 4, burst, true, &dcr); + if (ret) + return ret; + ret = h2fmi_cdma_commands(b->cmds + offset / sizeof(__le32), commands, addr, len, true); + if (ret) + return ret; + h2fmi_cdma_start(fmi, b->dma_ch + meta, dcr, b->fifo + 4 * meta, len, commands); + return 0; +} + +static int h2fmi_seq_dma_wait(struct h2fmi *fmi, struct h2fmi_bus *b, unsigned int stream) +{ + unsigned int channel = b->dma_ch + stream; + void __iomem *ch = fmi->cdma + CDMA_CH(channel); + u32 csr; + int ret; + + h2fmi_wait_dma_irq(fmi, b, stream, H2FMI_IRQ_MUTATE); + ret = readl_poll_timeout(ch + CDMA_CSR, csr, + csr & CDMA_CSR_CLEAR, 5, SEQ_WAIT_US); + if (ret) + return ret; + if ((csr & CDMA_CSR_CLEAR) != CDMA_CSR_HALTED) + return -EIO; + writel(CDMA_CSR_HALTED, ch + CDMA_CSR); + if (readl(ch + CDMA_DBR)) + return -EIO; + h2fmi_cdma_clock(fmi, channel, false); + return 0; +} + +/* On a write exception the sequencer is stopped. Snapshot the unconsumed + * operands and commands, flush, discard its outstanding result, and replay + * (0xbff0bf84). N42 has just CE0: suppress its selects and status macros. + */ +static int h2fmi_seq_repair(struct h2fmi_batch *q) +{ + struct h2fmi_bus *b = q->b; + u32 args[32], cmds[32], ce, a, c, level; + unsigned int i; + int ret; + + ce = readl(b->fmc + FMC_CE_CTRL); + a = readl(b->seq + SEQ_ARG_LEVEL); + c = readl(b->seq + SEQ_CMD_LEVEL); + q->arg_level = a & 63; + q->cmd_level = c & 63; + if (ce != BIT(H2FMI_CE) || q->arg_level > 32 || q->cmd_level > 32) + return -EIO; + for (i = 0; i < q->arg_level; i++) + args[i] = readl(b->seq + SEQ_ARG_RAM + 4 * (((a >> 16) + i) & 31)); + for (i = 0; i < q->cmd_level; i++) + cmds[i] = readl(b->seq + SEQ_CMD_RAM + 4 * (((c >> 16) + i) & 31)); + + writel(readl(b->fmi + FMI_CONTROL) | 0x300, b->fmi + FMI_CONTROL); + ret = readl_poll_timeout(b->seq + SEQ_RESULT_LEVEL, level, level & 63, 5, SEQ_WAIT_US); + if (ret) + return ret; + readl(b->seq + SEQ_RESULT); + for (i = 0; i < q->arg_level; i++) + writel(args[i], b->seq + SEQ_ARG); + for (i = 0; i < q->cmd_level; i++) { + if (cmds[i] == SEQ_ROW_STATUS) + continue; + if (cmds[i] == (SEQ_SELECT | BIT(H2FMI_CE))) + cmds[i] = SEQ_SELECT; + writel(cmds[i], b->seq + SEQ_CMD); + } + return 0; +} + +/* Keep one mapping per source page until both streams have stopped. The + * block frontend's vm_map_ram alias resolves to the original bio pages. + */ +static int h2fmi_map_payload(struct h2fmi *fmi, struct h2fmi_batch *q) +{ + struct h2fmi_bus *b = q->b; + unsigned int i; + + for (i = 0; i < q->n; i++) { + const u8 *src = q->page[i]->data; + unsigned int left = APPLE_PPN_PAGE_SIZE; + + memcpy(b->queue->meta[i], q->page[i]->oob, APPLE_PPN_OOB_SIZE); + while (left) { + unsigned int off = offset_in_page(src), len = min_t(unsigned int, left, PAGE_SIZE - off); + struct page *page = is_vmalloc_addr(src) ? vmalloc_to_page(src) : virt_to_page(src); + dma_addr_t addr = dma_map_page(fmi->dev, page, off, len, DMA_TO_DEVICE); + + if (dma_mapping_error(fmi->dev, addr)) + return -ENOMEM; + b->tx_segments[q->mapped].addr = addr; + b->tx_segments[q->mapped++].len = len; + src += len; + left -= len; + } + } + return 0; +} + +static void h2fmi_tx_chain(struct h2fmi_batch *q) +{ + struct h2fmi_bus *b = q->b; + unsigned int n = min_t(unsigned int, CDMA_CHAIN_ROWS, q->mapped - q->submitted), i; + __le32 *d = b->tx_desc; + + for (i = 0; i < n; i++, d += CDMA_CMD_SIZE / sizeof(*d)) { + unsigned int seg = q->submitted++; + + d[0] = cpu_to_le32(b->tx_desc_bus + (i + 1) * CDMA_CMD_SIZE); + d[1] = cpu_to_le32((CDMA_ATTR_TX << 24) | CDMA_CMD_MEM | + (i + 1 == n ? CDMA_CMD_LAST : 0)); + d[2] = cpu_to_le32(b->tx_segments[seg].addr); + d[3] = cpu_to_le32(b->tx_segments[seg].len); + } + d[1] = 0; + dma_wmb(); +} + +/* The sequencer can block on data while the CPU waits for FIFO room. */ +static int h2fmi_tx_continue(struct h2fmi_batch *q) +{ + struct h2fmi_bus *b = q->b; + void __iomem *ch; + u32 csr; + + if (!q->payload || q->submitted >= q->mapped) + return 0; + ch = q->fmi->cdma + CDMA_CH(b->dma_ch); + csr = readl(ch + CDMA_CSR); + if (csr & (CDMA_CSR_ERROR | CDMA_CSR_CMD_IRQ)) + return -EIO; + if (csr & CDMA_CSR_HALTED) { + writel(CDMA_CSR_HALTED, ch + CDMA_CSR); + h2fmi_tx_chain(q); + writel(b->tx_desc_bus, ch + CDMA_CAR); + writel(CDMA_CSR_START, ch + CDMA_CSR); + } + return 0; +} + +/* fmiss_seq_take_status_and_yield (0xbff0ad98). Results precede the + * exception that stopped the FIFO. Without an event take at most one. + */ +static int h2fmi_seq_status(struct h2fmi_batch *q) +{ + struct h2fmi_bus *b = q->b; + u32 flags = readl(b->seq + SEQ_EVENT), event = 0, count; + bool abort = flags & BIT(7); + u8 status; + int ret = h2fmi_tx_continue(q); + + /* The other bus can halt at its descriptor boundary while this bus + * is waiting for FIFO room or collecting the last program results. + */ + if (q->peer && !q->peer->error) + q->peer->error = h2fmi_tx_continue(q->peer); + if (ret) + return ret; + + if (!abort && (flags & 1)) { + event = readl(b->seq + SEQ_EVENT_DATA) & 0xffffff; + writel(1, b->seq + SEQ_EVENT); + if (event == 0xff0001) + q->end_event = true; + else if ((event >> 16) != 1) + return -EIO; + } + + count = readl(b->seq + SEQ_RESULT_LEVEL) & 63; + if (count > 32 || count > q->n - q->done) + return -EIO; + if (!event && !abort) + count = min(count, 1U); + while (count--) { + status = readl(b->seq + SEQ_RESULT); + q->page[q->done++]->ret = h2fmi_program_status(status); + } + if (!abort && (event >> 16) != 1) + return 0; + status = event; + if (q->flagged || q->done == q->n) + return -EIO; + if ((status & BIT(4)) || !(status & BIT(0))) { + if (status & BIT(4)) + pr_err_ratelimited("h2fmi: general error on FIFO %#x CE mask %#x\n", + b->fifo, readl(b->fmc + FMC_CE_CTRL)); + q->page[q->done++]->ret = -EIO; + while (q->done < q->n) + q->page[q->done++]->ret = -ECANCELED; + q->row_errors = true; + return -EIO; + } + + /* The three package lists identify the actual affected rows. */ + q->page[q->done++]->ret = 0; + q->flagged = true; + return h2fmi_seq_repair(q); +} + +/* Check occupancy only when our upper bound reaches the 32-word depth. + * An exception handled during backpressure can change the pending push. + */ +static void h2fmi_seq_push(struct h2fmi_batch *q, unsigned int fifo, u32 word) +{ + bool cmd = fifo == SEQ_CMD; + u32 *level = cmd ? &q->cmd_level : &q->arg_level; + ktime_t deadline; + + if (q->error) + return; + if (*level >= 32) { + deadline = ktime_add_us(ktime_get(), SEQ_WAIT_US); + for (;;) { + *level = readl(q->b->seq + fifo + 4) & 63; + if (*level < 32) + break; + if (ktime_after(ktime_get(), deadline)) + q->error = -ETIMEDOUT; + else if (q->payload) + q->error = h2fmi_seq_status(q); + if (q->error) + return; + cond_resched(); + } + } + if (cmd && q->flagged) { + if (word == (SEQ_SELECT | BIT(H2FMI_CE))) + word = SEQ_SELECT; + else if (word == SEQ_ROW_STATUS) + word = SEQ_DELAY; + } + writel(word, q->b->seq + fifo); + (*level)++; +} + +static void h2fmi_multi_prep(struct h2fmi *fmi, struct h2fmi_batch *q) +{ + struct h2fmi_bus *b = q->b; + + h2fmi_seq_load(b); + writel(6, b->fmi + FMI_CONTROL); + h2fmi_seq_start(b, 0x100); + if (q->n == 1) { + /* iBEC branches past the address-list transfer for one row. */ + q->time.submit = ktime_get(); + return; + } + + q->error = h2fmi_seq_dma_start(fmi, b, false, b->queue_bus, 4 * q->n, 32); + if (q->error) + return; + q->time.submit = ktime_get(); + writel(5, b->fmi + FMI_CONFIG); + h2fmi_seq_push(q, SEQ_CMD, SEQ_SELECT | BIT(H2FMI_CE)); + h2fmi_seq_push(q, SEQ_ARG, (q->n << 8) | 0x87); + h2fmi_seq_push(q, SEQ_CMD, 0x1100230c); + h2fmi_seq_push(q, SEQ_CMD, 0x0f000034); + h2fmi_seq_push(q, SEQ_CMD, (4 * q->n << 8) | 1); + h2fmi_seq_push(q, SEQ_CMD, 0x10000004); + h2fmi_seq_push(q, SEQ_ARG, 0x5104); + h2fmi_seq_push(q, SEQ_CMD, SEQ_DELAY); + h2fmi_seq_push(q, SEQ_CMD, SEQ_DATA); + h2fmi_seq_push(q, SEQ_CMD, 0x080000b8); + h2fmi_seq_push(q, SEQ_CMD, 0x11000505); +} - if (fmi->read_only) - return -EROFS; - if (bus >= H2FMI_BUSES) - return -EINVAL; - b = &fmi->bus[bus]; - ret = h2fmi_erase_row(&b->geometry, cau, block, &row); +static int h2fmi_multi_prep_done(struct h2fmi *fmi, struct h2fmi_batch *q) +{ + struct h2fmi_bus *b = q->b; + u32 flags; + int ret; + + ret = readl_poll_timeout(b->seq + SEQ_EVENT, flags, flags & 0x81, 5, SEQ_WAIT_US); if (ret) return ret; - - if (h2fmi_inject(h2fmi_fail_erase)) { - dev_warn(fmi->dev, "PPN erase row %08x: injected failure\n", row); + writel(flags & 0x81, b->seq + SEQ_EVENT); + if (!(flags & 1)) + return -EIO; + if (readl(b->fmc + FMC_NAND_STATUS) & BIT(4)) { + dev_err(fmi->dev, "bus %td: general error during address prep, CE mask %#x\n", + b - fmi->bus, readl(b->fmc + FMC_CE_CTRL)); return -EIO; } - ret = h2fmi_lock(fmi, b); - if (ret) - return ret; - ret = h2fmi_erase_transaction(fmi, b, row); - for (page = 0; !ret && page < b->geometry.pages; page++) { - ret = h2fmi_read_transaction(fmi, b, 0x0a, 0x37, row + page, 4, - b->page, H2FMI_PAGE_RAW, &status); - if (!ret && !h2fmi_raw_page_erased(status, b->page)) { - dev_err(fmi->dev, "PPN erase readback row %08x: status %02x\n", - row + page, status); + writel(readl(b->fmi + FMI_CONTROL) | 0x100, b->fmi + FMI_CONTROL); + return h2fmi_seq_dma_wait(fmi, b, 0); +} + +static void h2fmi_multi_payload(struct h2fmi *fmi, struct h2fmi_batch *q) +{ + struct h2fmi_bus *b = q->b; + + writel(0x2403, b->fmi + FMI_CONFIG); + writel(0x20840004, b->fmi + FMI_PIO_CONFIG); + writel(3, b->fmc + FMC_ADDRNUM); + writel(0x5104, b->fmi + FMI_CONTROL); + h2fmi_tx_chain(q); + h2fmi_cdma_start(fmi, b->dma_ch, (b->dma_req << 16) | 0x3a, b->fifo, + q->n * APPLE_PPN_PAGE_SIZE, b->tx_desc_bus); + q->error = h2fmi_seq_dma_start(fmi, b, true, + b->queue_bus + offsetof(struct h2fmi_queue_dma, meta), + q->n * APPLE_PPN_OOB_SIZE, 4); + q->payload = true; +} + +/* Feed one row on each active bus before advancing to the next row. */ +static void h2fmi_multi_row(struct h2fmi_batch *q, unsigned int i) +{ + struct h2fmi_bus *b = q->b; + unsigned int k; + + h2fmi_seq_push(q, SEQ_CMD, SEQ_SELECT | BIT(H2FMI_CE)); + h2fmi_seq_push(q, SEQ_ARG, le32_to_cpu(b->queue->rows[i])); + h2fmi_seq_push(q, SEQ_ARG, i + 1 == q->n ? 0x8a : 0x87); + h2fmi_seq_push(q, SEQ_CMD, 0x11001a09); + for (k = 0; k < 4; k++) + h2fmi_seq_push(q, SEQ_CMD, SEQ_DATA); + h2fmi_seq_push(q, SEQ_CMD, 0x08000017); + if (!q->flagged) + h2fmi_seq_push(q, SEQ_CMD, SEQ_ROW_STATUS); + if (i + 1 == q->n) + h2fmi_seq_push(q, SEQ_CMD, 0x0cff0001); +} + +static int h2fmi_collect_rows(struct h2fmi_batch *q) +{ + ktime_t deadline = ktime_add_us(ktime_get(), SEQ_WAIT_US); + int ret; + + while (q->flagged ? !q->end_event : q->done < q->n) { + unsigned int before = q->done; + + ret = h2fmi_seq_status(q); + if (ret || (q->flagged ? q->end_event : q->done == q->n)) + return ret; + if (ktime_after(ktime_get(), deadline)) + return -ETIMEDOUT; + if (before == q->done) + usleep_range(5, 15); + } + return 0; +} + +/* Only this DDR error path may set feature 3380 without permission to + * reset the package to SDR. Neither the address nor the value is supplied + * by a caller. iBEC 0xbff07800, 0xbff0be06. + */ +static int h2fmi_clear_program_lists(struct h2fmi *fmi, struct h2fmi_bus *b, + struct h2fmi_ddr_state *state) +{ + __le32 one = cpu_to_le32(1); + u8 status; + int ret; + + writel(0, b->fmc + FMC_CE_CTRL); + writel(BIT(H2FMI_CE), b->fmc + FMC_CE_CTRL); + writel(6, b->fmi + FMI_CONTROL); + writel(0xef, b->fmc + FMC_CMD); + writel(0x3380, b->fmc + FMC_ADDR0); + writel(1, b->fmc + FMC_ADDRNUM); + writel(9, b->fmc + FMC_RW_CTRL); + ret = h2fmi_wait(fmi, b->fmc, FMC_STATUS, 9, 9); + if (!ret) { + h2fmi_clear_irqs(b); + ret = h2fmi_data_in(fmi, b, (const u8 *)&one, sizeof(one)); + } + if (!ret) { + writel(0xe7, b->fmc + FMC_CMD); + writel(1, b->fmc + FMC_RW_CTRL); + ret = h2fmi_wait(fmi, b->fmc, FMC_STATUS, 1, 1); + } + if (!ret) + ret = h2fmi_status(fmi, b, &status, H2FMI_WAIT_MUTATE, state); + if (!ret && status != PPN_ST_GOOD) + ret = -EIO; + if (!ret) + ret = h2fmi_cmd1(fmi, b, 0x77); + writel(6, b->fmi + FMI_CONTROL); + writel(0, b->fmc + FMC_CE_CTRL); + h2fmi_device_reset(b, state, true); + return ret; +} + +static int h2fmi_program_lists(struct h2fmi *fmi, struct h2fmi_batch *q, + struct h2fmi_ddr_state *state) +{ + static const u16 features[] = { 0x3080, 0x3280, 0x3180 }; + struct h2fmi_bus *b = q->b; + unsigned int f, i, j; + bool found = false; + int ret; + + writel(0x300, b->fmi + FMI_CONTROL); + h2fmi_device_reset(b, state, true); + for (f = 0; f < ARRAY_SIZE(features); f++) { + u32 count; + u8 status; + + writel(0, b->fmc + FMC_CE_CTRL); + writel(BIT(H2FMI_CE), b->fmc + FMC_CE_CTRL); + h2fmi_clear_irqs(b); + ret = h2fmi_cmd_addr_cmd(fmi, b, 0xee, 0xe7, features[f], 2); + if (!ret) + ret = h2fmi_status(fmi, b, &status, H2FMI_WAIT_MUTATE, state); + if (!ret && status != PPN_ST_GOOD) ret = -EIO; + if (!ret) + ret = h2fmi_data_out(fmi, b, b->page, 512); + writel(6, b->fmi + FMI_CONTROL); + if (!ret) + ret = h2fmi_cmd1(fmi, b, 0x77); + writel(0, b->fmc + FMC_CE_CTRL); + if (ret) + return ret; + + count = get_unaligned_le32(b->page); + if (count > 127) + return -EIO; + for (i = 0; i < count; i++) { + u32 row = get_unaligned_le32(b->page + 4 + 4 * i); + + for (j = 0; j < q->n; j++) { + if (le32_to_cpu(b->queue->rows[j]) != row) + continue; + if (!q->page[j]->ret || f != 1) + q->page[j]->ret = f == 1 ? -ECANCELED : -EIO; + found = true; + break; + } + if (j == q->n) + dev_warn(fmi->dev, "program list %04x: unrequested row %08x\n", + features[f], row); + } + } + ret = h2fmi_clear_program_lists(fmi, b, state); + return ret ?: (found ? 0 : -EIO); +} + +static bool h2fmi_multi_program_enabled(struct h2fmi_bus *b) +{ + return b->tx_desc && !READ_ONCE(b->sdr) && READ_ONCE(multi_program) && + !READ_ONCE(verify) && (READ_ONCE(dma) & H2FMI_DMA_PROGRAM) && + !IS_ENABLED(CONFIG_MTD_APPLE_H2FMI_FAULT_INJECT); +} + +/* Caller holds the bus lock. All targets must pass the single-page write + * fence before any DMA or sequencer command is submitted on this bus. + */ +static int h2fmi_multi_stage(struct h2fmi *fmi, struct h2fmi_batch *q) +{ + struct h2fmi_bus *b = q->b; + unsigned int i, j; + int ret; + + if (fmi->read_only || b->failed) + return fmi->read_only ? -EROFS : -EIO; + for (i = 0; i < q->n; i++) { + struct apple_ppn_program *p = q->page[i]; + u32 row; + + ret = h2fmi_program_row(&b->geometry, p->cau, p->block, p->page, &row); + if (!p->data || !p->oob) + ret = -EINVAL; + if (ret) { + for (j = 0; j < q->n; j++) + q->page[j]->ret = j == i ? ret : -ECANCELED; + q->row_errors = true; + return ret; } + b->queue->rows[i] = cpu_to_le32(row); + } + h2fmi_save_ddr(b, &q->state); + return q->state.on == FMC_ON_DDR ? 0 : -EIO; +} + +static void h2fmi_multi_finish(struct h2fmi *fmi, struct h2fmi_batch *q) +{ + struct h2fmi_bus *b = q->b; + int ret = q->error; + + if (!ret) + ret = h2fmi_collect_rows(q); + if (!ret) + ret = h2fmi_seq_dma_wait(fmi, b, 0); + if (!ret) + ret = h2fmi_seq_dma_wait(fmi, b, 1); + if (q->time.submit) + q->time.complete = ktime_get(); + if (ret) { + if (q->payload && h2fmi_cdma_cancel(fmi, b->dma_ch + 1)) + b->failed = true; + if (h2fmi_cdma_cancel(fmi, b->dma_ch)) + b->failed = true; + } else if (q->flagged) { + ret = h2fmi_program_lists(fmi, q, &q->state); } if (ret) - h2fmi_fail(fmi); - mutex_unlock(&b->lock); + h2fmi_seq_recover(fmi, b, &q->state); + + spin_lock(&h2fmi_stats_lock); + if (q->time.submit) + xfer_multi_max_pages[0] = max(xfer_multi_max_pages[0], q->n); + xfer_multi_programs++; + xfer_multi_pages += q->n; + xfer_multi_us += ktime_us_delta(ktime_get(), q->start); + spin_unlock(&h2fmi_stats_lock); + while (q->mapped) { + unsigned int seg = --q->mapped; + + dma_unmap_page(fmi->dev, b->tx_segments[seg].addr, b->tx_segments[seg].len, + DMA_TO_DEVICE); + } + q->error = ret; +} + +/* The pages of @pages on @bus, in order; after a failure the rest are cancelled. */ +static int h2fmi_program_bus(struct h2fmi *fmi, struct apple_ppn_program *pages, + unsigned int n, unsigned int bus) +{ + bool stop = false; + unsigned int i; + int ret = 0; + + for (i = 0; i < n; i++) { + struct apple_ppn_program *p = &pages[i]; + + if (p->bus != bus) + continue; + if (stop) { + p->ret = -ECANCELED; + continue; + } + p->ret = h2fmi_program_page(fmi, &fmi->bus[bus], p->cau, p->block, + p->page, p->data, p->oob); + if (p->ret) { + stop = true; + ret = ret ? ret : p->ret; + } + } + return ret; +} + +struct h2fmi_bus_work { + struct work_struct work; + struct h2fmi *fmi; + struct apple_ppn_program *pages; + unsigned int n, bus; +}; + +static void h2fmi_bus_work(struct work_struct *work) +{ + struct h2fmi_bus_work *w = container_of(work, struct h2fmi_bus_work, work); + /* This is block I/O: no allocation may wait on it. */ + unsigned int noio = memalloc_noio_save(); + + h2fmi_program_bus(w->fmi, w->pages, w->n, w->bus); + memalloc_noio_restore(noio); +} + +static void h2fmi_singles(struct h2fmi *fmi, struct h2fmi_batch *q) +{ + unsigned int i; + int ret = 0; + + for (i = 0; i < q->n; i++) { + struct apple_ppn_program *p = q->page[i]; + + if (ret) + p->ret = -ECANCELED; + else + ret = p->ret = h2fmi_program_page(fmi, q->b, p->cau, p->block, p->page, + p->data, p->oob); + } +} + +static void h2fmi_multi_submit(struct h2fmi *fmi, struct h2fmi_batch *q, unsigned int buses) +{ + unsigned int i, row, rows = 0; + + for (i = 0; i < buses; i++) { + q[i].start = ktime_get(); + q[i].error = h2fmi_multi_stage(fmi, &q[i]); + if (!q[i].error) { + q[i].started = true; + h2fmi_multi_prep(fmi, &q[i]); + } + } + for (i = 0; i < buses; i++) { + if (q[i].error) + continue; + q[i].error = h2fmi_map_payload(fmi, &q[i]); + if (!q[i].error && q[i].n > 1) + q[i].error = h2fmi_multi_prep_done(fmi, &q[i]); + if (!q[i].error) { + h2fmi_multi_payload(fmi, &q[i]); + h2fmi_multi_row(&q[i], 0); + rows = max(rows, q[i].n); + } + } + for (row = 1; row < rows; row++) + for (i = 0; i < buses; i++) + if (row < q[i].n && !q[i].error) + h2fmi_multi_row(&q[i], row); + for (i = 0; i < buses; i++) + if (!q[i].error) + h2fmi_seq_push(&q[i], SEQ_CMD, SEQ_SELECT); +} + +static void h2fmi_multi_wait(struct h2fmi *fmi, struct h2fmi_batch *q, unsigned int buses) +{ + unsigned int i; + + for (i = 0; i < buses; i++) + if (q[i].started) + h2fmi_multi_finish(fmi, &q[i]); +} + +/* One or both CE0 queues. With two buses the caller owns the mutexes in + * recovery order. Both prep lists go out before the first prep wait. Feed + * the first row as soon as its payload is ready, so that one sequencer + * can program while the CPU is packing the other bus's payload. Both + * deselects precede collection. + */ +static void h2fmi_run_queues(struct h2fmi *fmi, struct h2fmi_batch *q, unsigned int buses, + void (*prepare)(void *), void *ctx) +{ + unsigned int i, row; + int ret; + + for (;;) { + ret = h2fmi_lock(fmi, q[0].b); + if (ret) + goto failed; + if (buses == 1) + break; + mutex_lock_nested(&q[1].b->lock, SINGLE_DEPTH_NESTING); + if (!READ_ONCE(fmi->reset_needed)) + break; + mutex_unlock(&q[1].b->lock); + mutex_unlock(&q[0].b->lock); + } + for (i = 0; i < buses; i++) { + if (!h2fmi_multi_program_enabled(q[i].b)) { + /* Recovery or a parameter change selected individual programs. */ + if (buses == 2) + mutex_unlock(&q[1].b->lock); + mutex_unlock(&q[0].b->lock); + for (i = 0; i < buses; i++) + h2fmi_singles(fmi, &q[i]); + return; + } + } + if (buses == 2) { + q[0].peer = &q[1]; + q[1].peer = &q[0]; + } + h2fmi_multi_submit(fmi, q, buses); + if (prepare) + prepare(ctx); + h2fmi_multi_wait(fmi, q, buses); + if (buses == 2) { + h2fmi_count_overlap(&q[0].time, &q[1].time); + mutex_unlock(&q[1].b->lock); + } + mutex_unlock(&q[0].b->lock); +failed: + for (i = 0; i < buses; i++) + if ((ret || q[i].error) && !q[i].row_errors) + for (row = 0; row < q[i].n; row++) + q[i].page[row]->ret = ret ?: q[i].error; +} + +static void h2fmi_run_one(struct h2fmi *fmi, struct h2fmi_batch *q) +{ + if (q->n && h2fmi_multi_program_enabled(q->b)) + h2fmi_run_queues(fmi, q, 1, NULL, NULL); + else + h2fmi_singles(fmi, q); +} + +static void h2fmi_program_round(struct h2fmi *fmi, struct h2fmi_batch *q, + void (*prepare)(void *), void *ctx) +{ + unsigned int single; + struct h2fmi_bus_work w; + + if (!q[0].n || !q[1].n || !READ_ONCE(parallel_buses)) { + h2fmi_run_one(fmi, &q[0]); + h2fmi_run_one(fmi, &q[1]); + return; + } + if ((q[0].n > 1 && q[1].n > 1) || + (h2fmi_multi_program_enabled(q[0].b) && h2fmi_multi_program_enabled(q[1].b))) { + h2fmi_run_queues(fmi, q, 2, prepare, ctx); + return; + } + + /* A one-row tail uses the existing single-page transaction. */ + single = q[0].n == 1 ? 0 : 1; + if (fmi->wq) { + w.fmi = fmi; + w.bus = single; + w.pages = q[single].page[0]; + w.n = 1; + INIT_WORK_ONSTACK(&w.work, h2fmi_bus_work); + queue_work(fmi->wq, &w.work); + } else { + h2fmi_singles(fmi, &q[single]); + } + h2fmi_run_one(fmi, &q[!single]); + if (fmi->wq) { + flush_work(&w.work); + destroy_work_on_stack(&w.work); + } +} + +static void h2fmi_queue_pages(struct h2fmi *fmi, struct apple_ppn_program *pages, + unsigned int n, void (*prepare)(void *), void *ctx) +{ + unsigned int cursor[H2FMI_BUSES] = { }; + bool stopped[H2FMI_BUSES] = { }; + unsigned int bus, i; + + while (cursor[0] < n || cursor[1] < n) { + struct h2fmi_batch q[H2FMI_BUSES] = { }; + + for (bus = 0; bus < H2FMI_BUSES; bus++) { + struct h2fmi_bus *b = &fmi->bus[bus]; + unsigned int depth = h2fmi_multi_program_enabled(b) ? b->queue_depth : 1; + + q[bus].fmi = fmi; + q[bus].b = b; + while (cursor[bus] < n && q[bus].n < depth) { + struct apple_ppn_program *p = &pages[cursor[bus]++]; + + if (p->bus != bus) + continue; + if (stopped[bus]) + p->ret = -ECANCELED; + else + q[bus].page[q[bus].n++] = p; + } + } + h2fmi_program_round(fmi, q, prepare, ctx); + prepare = NULL; + for (bus = 0; bus < H2FMI_BUSES; bus++) + for (i = 0; i < q[bus].n; i++) + if (q[bus].page[i]->ret) + stopped[bus] = true; + } +} + +/* K5b queues both buses. K5a remains the individual-program fallback. */ +static int h2fmi_ppn_program_prepare(void *priv, struct apple_ppn_program *pages, + unsigned int n, void (*prepare)(void *), void *ctx) +{ + struct h2fmi *fmi = priv; + ktime_t start = ktime_get(); + unsigned int i, on = 0; + ulong us; + int ret = 0; + + if (!pages || !n) + return -EINVAL; + for (i = 0; i < n; i++) { + if (pages[i].bus >= H2FMI_BUSES) + ret = -EINVAL; + else + on |= BIT(pages[i].bus); + pages[i].ret = 0; + } + if (ret) { + for (i = 0; i < n; i++) + pages[i].ret = pages[i].bus >= H2FMI_BUSES ? ret : -ECANCELED; + return ret; + } + if (h2fmi_multi_program_enabled(&fmi->bus[0]) || h2fmi_multi_program_enabled(&fmi->bus[1])) { + h2fmi_queue_pages(fmi, pages, n, prepare, ctx); + } else if (on == (BIT(0) | BIT(1)) && READ_ONCE(parallel_buses) && fmi->wq) { + struct h2fmi_bus_work w = { .fmi = fmi, .pages = pages, .n = n, .bus = 1 }; + + INIT_WORK_ONSTACK(&w.work, h2fmi_bus_work); + queue_work(fmi->wq, &w.work); + h2fmi_program_bus(fmi, pages, n, 0); + flush_work(&w.work); + destroy_work_on_stack(&w.work); + } else { + for (i = 0; i < n; i++) { + if (ret) { + pages[i].ret = -ECANCELED; + continue; + } + pages[i].ret = h2fmi_program_page(fmi, &fmi->bus[pages[i].bus], + pages[i].cau, pages[i].block, + pages[i].page, pages[i].data, + pages[i].oob); + ret = pages[i].ret; + } + } + for (i = 0, ret = 0; i < n && !ret; i++) + ret = pages[i].ret; + us = ktime_us_delta(ktime_get(), start); + spin_lock(&h2fmi_stats_lock); + xfer_stripes++; + xfer_stripe_pages += n; + xfer_stripe_us += us; + spin_unlock(&h2fmi_stats_lock); return ret; } +static int h2fmi_ppn_program_pages(void *priv, struct apple_ppn_program *pages, unsigned int n) +{ + return h2fmi_ppn_program_prepare(priv, pages, n, NULL, NULL); +} + +static void h2fmi_destroy_wq(void *wq) +{ + destroy_workqueue(wq); +} + +/* SFTL skips its own blank check after an erase when this says so. */ +static bool h2fmi_ppn_status_only(void *priv) +{ + return !READ_ONCE(verify); +} + +static bool h2fmi_read_dma_init(struct h2fmi *fmi) +{ + struct device *dev = fmi->dev; + unsigned int i, stream; + + for (i = 0; i < H2FMI_BUSES; i++) { + struct h2fmi_bus *b = &fmi->bus[i]; + struct h2fmi_multi *m; + + if (!b->seq) + return false; + m = devm_kzalloc(dev, sizeof(*m), GFP_KERNEL); + if (!m) + return false; + for (stream = 0; stream < 2; stream++) { + m->desc[stream] = dmam_alloc_coherent(dev, 0x400, &m->desc_addr[stream], + GFP_KERNEL); + if (!m->desc[stream]) + return false; + } + m->meta = dmam_alloc_coherent(dev, APPLE_PPN_READ_MAX_PER_BUS * H2FMI_PAGE_OOB, + &m->meta_addr, GFP_KERNEL); + if (!m->meta) + return false; + b->multi = m; + } + return true; +} + static int h2fmi_register_sftl(struct h2fmi *fmi) { const struct h2fmi_geometry *g = &fmi->bus[0].geometry; @@ -1406,19 +3433,36 @@ static int h2fmi_register_sftl(struct h2fmi *fmi) (g->caus == 2 && g->blocks == 1056 && g->pages == 256 && g->slc_pages == 128))) return 0; fmi->ppn_ops.read_page = h2fmi_ppn_read; + if (fmi->n42) + fmi->wq = alloc_workqueue("h2fmi", WQ_MEM_RECLAIM | WQ_UNBOUND | WQ_HIGHPRI, 1); + if (fmi->wq && devm_add_action_or_reset(fmi->dev, h2fmi_destroy_wq, fmi->wq)) + fmi->wq = NULL; + if (fmi->wq && h2fmi_read_dma_init(fmi)) { + fmi->ppn_ops.read_pages = h2fmi_ppn_read_pages; + fmi->ppn_ops.read_pages_overlap = h2fmi_ppn_read_overlap; + fmi->ppn_ops.read_scan_pages = h2fmi_ppn_read_scan_pages; + fmi->ppn_ops.read_pages_enabled = h2fmi_multi_read_enabled; + } /* 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; + if (fmi->n42) { + fmi->ppn_ops.status_only = h2fmi_ppn_status_only; + fmi->ppn_ops.program_pages = h2fmi_ppn_program_pages; + fmi->ppn_ops.program_pages_prepare = h2fmi_ppn_program_prepare; + } /* * Erase follows the discovered geometry. SFTL verifies every erased * block blank in both views and checks its accounting before reuse. */ - if (h2fmi_erase_geometry_valid(g)) + if (h2fmi_erase_geometry_valid(g)) { fmi->ppn_ops.erase_block = h2fmi_ppn_erase; - else + if (fmi->n42 && g->blocks == H2FMI_N42_BLOCKS && g->caus == 2) + fmi->ppn_ops.erase_lanes = h2fmi_erase_lanes; + } else dev_info(fmi->dev, - "PPN geometry %u CAUs x %u blocks x %u pages has no valid erase extent; reclamation stays off\n", + "PPN geometry %u CAUs x %u blocks x %u pages: erase disabled; reclamation stays off\n", g->caus, g->blocks, g->pages); publish: fmi->sftl = platform_device_register_data(fmi->dev, "apple-sftl", @@ -1586,7 +3630,8 @@ static int h2fmi_setup_mtd(struct h2fmi *fmi, int idx) /* Page metadata is MTD OOB. Pages are programmed whole, data and OOB * 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->flags = (fmi->read_only || fmi->n42) ? + 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; @@ -1604,7 +3649,7 @@ 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; - if (!fmi->read_only) + if (!fmi->read_only && !fmi->n42) mtd->_write_oob = h2fmi_mtd_write_oob; mtd->_block_isbad = h2fmi_mtd_block_isbad; @@ -1634,15 +3679,149 @@ static int h2fmi_clocks(struct h2fmi *fmi) 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"); + dev_info(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; } +/* + * CDMA for page data: the node's seventh window and one + * pair per bus in "apple,dma-channels". Anything missing leaves PIO. + */ +static void h2fmi_dma_init(struct platform_device *pdev, struct h2fmi *fmi) +{ + struct device *dev = &pdev->dev; + struct resource *cdma, *res; + u32 pair[2 * H2FMI_BUSES]; + int i; + + cdma = platform_get_resource(pdev, IORESOURCE_MEM, H2FMI_BUSES * 3); + if (!cdma || of_property_read_u32_array(dev->of_node, "apple,dma-channels", + pair, ARRAY_SIZE(pair))) { + dev_info(dev, "no CDMA in the node: page data by PIO\n"); + return; + } + for (i = 0; i < H2FMI_BUSES; i++) + if (!pair[2 * i] || pair[2 * i + 1] > 0x3f || + CDMA_CH(pair[2 * i] + 1) > resource_size(cdma)) { + dev_warn(dev, "bad apple,dma-channels: page data by PIO\n"); + return; + } + if (dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32))) + return; + /* devm_ioremap, not _resource: the engine serves other blocks too. */ + fmi->cdma = devm_ioremap(dev, cdma->start, resource_size(cdma)); + if (!fmi->cdma) + return; + for (i = 0; i < H2FMI_BUSES; i++) { + struct h2fmi_bus *b = &fmi->bus[i]; + + res = platform_get_resource(pdev, IORESOURCE_MEM, i * 3); + b->fifo = res->start + FMI_DATA; + b->dma_ch = pair[2 * i]; + b->dma_req = pair[2 * i + 1]; + b->cmds = dmam_alloc_coherent(dev, 4 * CDMA_CMD_SIZE, &b->cmds_bus, + GFP_KERNEL); + if (!b->cmds) { + fmi->bus[0].cmds = NULL; + dev_warn(dev, "no CDMA command memory: page data by PIO\n"); + return; + } + dev_info(dev, "bus %d: CDMA channel %u, request %u, FIFO 0x%08x\n", + i, b->dma_ch, b->dma_req, b->fifo); + } + dev_info(dev, "CDMA channel clocks 0x%08x, dma=%u\n", + readl(fmi->cdma + CDMA_CLK_STATUS), dma); +} + +static void h2fmi_seq_init(struct platform_device *pdev, struct h2fmi *fmi, unsigned int bus) +{ + struct h2fmi_bus *b = &fmi->bus[bus]; + struct resource *cdma = platform_get_resource(pdev, IORESOURCE_MEM, H2FMI_BUSES * 3); + struct resource *base = platform_get_resource(pdev, IORESOURCE_MEM, bus * 3); + struct device *dev = fmi->dev; + + if (!b->gate || b->sdr || !b->cmds || + b->geometry.blocks != H2FMI_N42_BLOCKS || b->dma_ch != 5 + 2 * bus || + b->dma_req != 2 * bus || CDMA_CH(b->dma_ch + 2) > resource_size(cdma)) + return; + + b->seq = devm_ioremap(dev, base->start + 0xc0000, 0x4000); + if (!b->seq) { + dev_warn(dev, "bus %u: sequencer mapping failed, using single pages\n", bus); + return; + } + /* Keep the clock iBoot programmed. The N42 ADT identifies the FMI + * clock as 0x12a, arm-io/clock-frequencies[0x2a] = 256500000 Hz. + */ + b->seq_clock = readl(b->seq + SEQ_CLOCK) ?: 256500000; + b->delay100 = SEQ_DELAY | ((b->seq_clock / 1000) * 100 / 1000000); + b->delay60 = SEQ_DELAY | ((b->seq_clock / 1000) * 60 / 1000000); + + if (fmi->read_only || b->queue_depth < 2) + return; + b->queue = dmam_alloc_coherent(dev, sizeof(*b->queue), &b->queue_bus, GFP_KERNEL); + if (!b->queue) + goto fallback; + b->tx_desc = dmam_alloc_coherent(dev, 0x400, &b->tx_desc_bus, GFP_KERNEL); + if (!b->tx_desc) + goto fallback; + dev_info(dev, "bus %u: PPN program queue %u rows, sequencer clock %u Hz\n", + bus, b->queue_depth, b->seq_clock); + return; +fallback: + dev_warn(dev, "bus %u: multi-program allocation failed, using single pages\n", bus); +} + +/* + * The FMC interrupts (ADT: 33 for bus 0, 34 for bus 1), for irq_wait. They + * stay disabled except during an interrupt status wait. Without them the + * waits poll, as before. + */ +static void h2fmi_request_irqs(struct platform_device *pdev, struct h2fmi *fmi) +{ + int i, irq, ret; + + for (i = 0; i < H2FMI_BUSES; i++) { + struct h2fmi_bus *b = &fmi->bus[i]; + + unsigned int stream; + + for (stream = 0; b->seq && stream < 2; stream++) { + struct h2fmi_dma_irq *line = &b->dma_irq[stream]; + + irq = platform_get_irq_optional(pdev, 2 + i * 2 + stream); + if (irq <= 0) + continue; + init_completion(&line->done); + ret = devm_request_irq(&pdev->dev, irq, h2fmi_dma_irq, IRQF_NO_AUTOEN, + "h2fmi-cdma", line); + if (!ret) + line->irq = irq; + } + + irq = platform_get_irq_optional(pdev, i); + if (irq <= 0) { + dev_warn(&pdev->dev, "bus %d: no interrupt (%d); status waits poll\n", i, irq); + continue; + } + ret = devm_request_irq(&pdev->dev, irq, h2fmi_irq, IRQF_NO_AUTOEN, + i ? "h2fmi1" : "h2fmi0", b); + if (ret) { + dev_warn(&pdev->dev, "bus %d: interrupt %d not requested (%d); status waits poll\n", + i, irq, ret); + continue; + } + b->irq = irq; + dev_info(&pdev->dev, "bus %d: status waits on interrupt %d (irq_wait=%u)\n", + i, irq, irq_wait); + } +} + static int h2fmi_probe(struct platform_device *pdev) { const struct h2fmi_soc *soc; @@ -1659,11 +3838,15 @@ static int h2fmi_probe(struct platform_device *pdev) if (!fmi) return -ENOMEM; fmi->dev = &pdev->dev; + fmi->n42 = soc == &h2fmi_s5l8950x; /* Both guards hold from the first command on. */ - fmi->read_only = soc->read_only; + /* Only the N42 has a qualified A6 installation layout. */ + fmi->read_only = soc->read_only || + (fmi->n42 && !of_machine_is_compatible("apple,n42ap")); 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; + /* Bounded 0x49 disturb tolerance on SanDisk N42 (read-only or Step-1 test). */ + fmi->clean_by_status = soc->clean_by_status && + (fmi->read_only || IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE)); apple_ppn_access_init(&fmi->access); ret = h2fmi_clocks(fmi); @@ -1684,7 +3867,14 @@ static int h2fmi_probe(struct platform_device *pdev) if (IS_ERR(b->ecc)) return PTR_ERR(b->ecc); + if (soc == &h2fmi_s5l8950x) { + /* S5L8950X PMGR indices 0x32 (FMI0) and 0x34 (FMI1). */ + b->gate = devm_ioremap(&pdev->dev, 0x3f1010c8 + 8 * i, sizeof(u32)); + if (!b->gate) + return -ENOMEM; + } mutex_init(&b->lock); + init_completion(&b->irq_done); b->page = devm_kzalloc(&pdev->dev, H2FMI_PAGE_RAW, GFP_KERNEL); if (!b->page) return -ENOMEM; @@ -1697,6 +3887,8 @@ static int h2fmi_probe(struct platform_device *pdev) i, readl(b->fmc + FMC_ON), readl(b->fmc + FMC_IF_CTRL)); } + h2fmi_dma_init(pdev, fmi); + /* 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) { @@ -1723,8 +3915,15 @@ 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)) + if (!h2fmi_geometry_writable(&fmi->bus[0].geometry) || + fmi->n42 != (fmi->bus[0].geometry.blocks == H2FMI_N42_BLOCKS)) fmi->read_only = true; + if (fmi->n42) { + for (i = 0; i < H2FMI_BUSES; i++) + h2fmi_seq_init(pdev, fmi, i); + if (irq_wait) + h2fmi_request_irqs(pdev, fmi); + } 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); diff --git a/drivers/mtd/devices/mtd-apple-h2fmi.h b/drivers/mtd/devices/mtd-apple-h2fmi.h index 515a08ea19b76c..cf370322b7c0dd 100644 --- a/drivers/mtd/devices/mtd-apple-h2fmi.h +++ b/drivers/mtd/devices/mtd-apple-h2fmi.h @@ -2,6 +2,7 @@ #ifndef MTD_APPLE_H2FMI_H #define MTD_APPLE_H2FMI_H +#include #include #include #include @@ -92,13 +93,15 @@ static inline int h2fmi_parse_geometry(const u8 *params, size_t len, /* * 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. + * measured on, plus N42 (1056 blocks) when fenced writing is enabled. + * Any other accepted profile is read-only whatever the 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); + (g->caus == 8 && g->blocks == 2088) || + (IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) && + g->caus == 2 && g->blocks == 1056); } static inline int h2fmi_page_row(const struct h2fmi_geometry *g, @@ -112,8 +115,40 @@ static inline int h2fmi_page_row(const struct h2fmi_geometry *g, return 0; } -/* SLC-view bootstrap members may occupy any of the last 32 blocks. */ -#define H2FMI_BOOTSTRAP_BLOCKS 32 +/* SLC-view bootstrap members may occupy any of the last 32 blocks on P105. + * On N42 (1056 blocks per CAU), blocks 1046..1053 hold the 8-block BFN tail + * (effaceable/NVRAM/syscfg/firm) and 1054..1055 hold the VFL. + */ +#define H2FMI_BOOTSTRAP_BLOCKS 32 +#define H2FMI_N42_BLOCKS 1056U +#define H2FMI_N42_FTL_LIMIT 1046U + +/* Exclusive upper bound on physical blocks eligible for program or erase. */ +static inline u32 h2fmi_program_block_limit(const struct h2fmi_geometry *g) +{ + if (g->caus == 2 && g->blocks == H2FMI_N42_BLOCKS) + return H2FMI_N42_FTL_LIMIT; + return g->blocks > 2 ? g->blocks - 2 : 0; +} + +static inline u32 h2fmi_erase_block_limit(const struct h2fmi_geometry *g) +{ + if (g->caus == 2 && g->blocks == H2FMI_N42_BLOCKS) + return H2FMI_N42_FTL_LIMIT; + return g->blocks > H2FMI_BOOTSTRAP_BLOCKS ? + g->blocks - H2FMI_BOOTSTRAP_BLOCKS : 0; +} + +static inline int h2fmi_program_row(const struct h2fmi_geometry *g, + unsigned int cau, unsigned int block, + unsigned int page, u32 *row) +{ + if (cau >= g->caus || block >= g->blocks || page >= g->pages) + return -EINVAL; + if (!block || block >= h2fmi_program_block_limit(g)) + return -EPERM; + return h2fmi_page_row(g, cau, block, page, row); +} /* * A single-row erase clears one block of one CAU: the row of its first @@ -141,7 +176,7 @@ static inline int h2fmi_erase_row(const struct h2fmi_geometry *g, return -EOPNOTSUPP; if (cau >= g->caus || block >= g->blocks) return -EINVAL; - if (!block || block >= g->blocks - H2FMI_BOOTSTRAP_BLOCKS) + if (!block || block >= h2fmi_erase_block_limit(g)) return -EPERM; return h2fmi_page_row(g, cau, block, 0, row); } @@ -185,6 +220,40 @@ static inline bool h2fmi_raw_page_erased(u8 status, const u8 *raw) return status == PPN_ST_ERASED && !memchr_inv(raw, 0xff, H2FMI_PAGE_RAW); } +/* + * SanDisk 1Xnm64GeX2 (N42, PPN 1.5.5) reports erased pages via status 0x49 + * (iBEC 12H321 0xbff09908 and AppleSwissPPNFTL s_read.c 0x80dd52ba trust + * the status without scanning payload bytes), and isolated erased pages can + * show single-bit read disturb (observed once across >2,500 Flight 1 reads: + * 16,447/16,448 FF bytes on block 164 lane 0 page 0). Allow bounded erased- + * cell disturb when clean_by_status is enabled, while still rejecting + * genuinely programmed or torn data that reports status 0x49. + */ +#define H2FMI_CLEAN_MAX_NON_FF_BYTES 8U +#define H2FMI_CLEAN_MAX_ZERO_BITS 16U + +static inline bool h2fmi_raw_page_erased_bounded(u8 status, const u8 *raw, + unsigned int max_non_ff, + unsigned int max_zero_bits) +{ + unsigned int i, non_ff = 0, zero_bits = 0; + + if (status != PPN_ST_ERASED) + return false; + if (!max_non_ff) + return !memchr_inv(raw, 0xff, H2FMI_PAGE_RAW); + for (i = 0; i < H2FMI_PAGE_RAW; i++) { + if (raw[i] == 0xff) + continue; + if (++non_ff > max_non_ff) + return false; + zero_bits += hweight8((u8)~raw[i]); + if (zero_bits > max_zero_bits) + return false; + } + return true; +} + /* * SDR operation, as Cascadia's PIO driver runs the A5 controller after its own * NAND reset: the package is held at the low-power interface timing until @@ -231,4 +300,133 @@ static inline int h2fmi_program_status(u8 status) return (status & BIT(6)) && !(status & (BIT(0) | BIT(4))) ? 0 : -EIO; } +/* + * CDMA, the SoC's DMA engine, as iBEC's h2fmi drives it for page data + * (N42 iBEC 12H321: drivers/apple/cdma/cdma.c dma_execute_cmd 0xbff01c60, + * dma_continue_async 0xbff01f8c, dma_int_handler 0xbff022dc, dma_cancel + * 0xbff02458; H2fmi_dma_iboot.c h2fmi_dma_execute_async 0xbff06c44). + * A channel is a 0x1000 window at channel * 0x1000; window 0 holds the + * channel clock words. + */ +#define CDMA_CLK_ON 0x00 /* write a channel's bit: clock on */ +#define CDMA_CLK_OFF 0x08 /* write a channel's bit: clock off */ +#define CDMA_CLK_STATUS 0x10 +#define CDMA_CH(ch) (0x1000 * (ch)) +#define CDMA_CSR 0x00 +#define CDMA_DCR 0x04 +#define CDMA_DAR 0x08 /* the device FIFO, full bus address */ +#define CDMA_DBR 0x0c /* bytes left */ +#define CDMA_MAR 0x10 +#define CDMA_CAR 0x14 /* bus address of the first command */ +#define CDMA_ERR 0x18 +#define CDMA_CSR_RUN BIT(0) +#define CDMA_CSR_ABORT BIT(1) +#define CDMA_CSR_HALT_IE BIT(3) +#define CDMA_CSR_STATE (BIT(16) | BIT(17)) +#define CDMA_CSR_RUNNING BIT(16) +#define CDMA_CSR_ERROR BIT(18) +#define CDMA_CSR_HALTED BIT(19) /* the command list ran to its end */ +#define CDMA_CSR_CMD_IRQ BIT(20) +#define CDMA_CSR_CLEAR (BIT(18) | BIT(19) | BIT(20)) +/* cdma-version 5: attribute 0xb in the CSR and in memory-to-device commands, + * 6 in device-to-memory commands (iBEC's per-channel defaults). */ +#define CDMA_ATTR_CSR 0xb +#define CDMA_ATTR_TX 0xb +#define CDMA_ATTR_RX 0x6 +#define CDMA_CSR_START (CDMA_ATTR_CSR << 24 | CDMA_CSR_CLEAR | \ + CDMA_CSR_HALT_IE | CDMA_CSR_RUN) +#define CDMA_DCR_TX BIT(1) /* memory to device */ +#define CDMA_CMD_MEM 0x3 /* a memory segment */ +#define CDMA_CMD_LAST BIT(8) /* halt after this segment */ +#define CDMA_CMD_SIZE 32 +#define CDMA_SEGMENT_MAX 0x1000000 + +/* FMI data FIFO channels and request lines out of iBEC's table at + * 0xbff42c3c: FMI0 data 5/0 (meta 6/1), FMI1 data 7/2 (meta 8/3). */ +#define H2FMI_DMA_SECTOR 1024 +#define H2FMI_DMA_BODY 16384 /* sixteen sectors, burst 32 */ +/* h2fmi_wait_done (0xbff052d4) is (register, mask, value) and writes the + * value back; h2fmi_read_raw_page waits FMI +0xc for 2/2, then the channel. */ +#define H2FMI_DMA_TAIL (H2FMI_PAGE_RAW - H2FMI_DMA_BODY) + +/* DCR: request line, word size and burst as dma_execute_cmd encodes them. */ +static inline int h2fmi_cdma_dcr(u32 req, u32 word, u32 burst, bool tx, u32 *dcr) +{ + u32 v; + + if (req > 0x3f) + return -EINVAL; + switch (word) { + case 1: + v = 0x0; + break; + case 2: + v = 0x4; + break; + case 4: + v = 0x8; + break; + default: + return -EINVAL; + } + switch (burst) { + case 1: + break; + case 2: + v |= 0x10; + break; + case 4: + v |= 0x20; + break; + case 8: + v |= 0x30; + break; + case 16: + v |= 0x40; + break; + case 32: + v |= 0x50; + break; + default: + return -EINVAL; + } + *dcr = req << 16 | v | (tx ? CDMA_DCR_TX : 0); + return 0; +} + +/* + * One memory segment and the halt command behind it, as dma_continue_async + * lays them out: next command, control, bus address, length. cmds_bus is + * where the list itself sits. + */ +static inline int h2fmi_cdma_commands(__le32 *cmds, u32 cmds_bus, u32 addr, + u32 len, bool tx) +{ + if (!len || len > CDMA_SEGMENT_MAX) + return -EINVAL; + cmds[0] = cpu_to_le32(cmds_bus + CDMA_CMD_SIZE); + cmds[1] = cpu_to_le32((tx ? CDMA_ATTR_TX : CDMA_ATTR_RX) << 24 | + CDMA_CMD_LAST | CDMA_CMD_MEM); + cmds[2] = cpu_to_le32(addr); + cmds[3] = cpu_to_le32(len); + cmds[8] = cpu_to_le32(cmds_bus + 2 * CDMA_CMD_SIZE); + cmds[9] = 0; + return 0; +} + +/* FMI +0x34: whole 1024-byte sectors, or one short sector of whole words. */ +static inline int h2fmi_data_size(u32 bytes, u32 *reg) +{ + if (!bytes || bytes & 3) + return -EINVAL; + if (bytes < H2FMI_DMA_SECTOR) { + *reg = bytes << 8 | 1; + return 0; + } + if (bytes % H2FMI_DMA_SECTOR || bytes / H2FMI_DMA_SECTOR > 0xff) + return -EINVAL; + *reg = H2FMI_DMA_SECTOR << 8 | bytes / H2FMI_DMA_SECTOR; + return 0; +} + #endif diff --git a/include/linux/mtd/apple-ppn.h b/include/linux/mtd/apple-ppn.h index 44ce00b92ff581..a6eeadecb1c5a3 100644 --- a/include/linux/mtd/apple-ppn.h +++ b/include/linux/mtd/apple-ppn.h @@ -5,20 +5,57 @@ #include struct device; +struct page; struct apple_ppn_access; #define APPLE_PPN_PAGE_SIZE 16384 #define APPLE_PPN_OOB_SIZE 64 +/* N42 FIL has 128 records per bus, with independent commands on two buses. */ +#define APPLE_PPN_READ_MAX_PER_BUS 128 + +struct apple_ppn_read { + unsigned int bus, cau, block, page; + u8 *data, *oob; + struct page *target[4]; /* optional direct 4 KiB destinations */ + u8 status; /* raw PPN status, including refresh, retirement and clean */ + int ret; +}; + +/* One page of a program_pages call. ret is set by the provider. */ +struct apple_ppn_program { + unsigned int bus, cau, block, page; + const u8 *data, *oob; + int ret; +}; + /* All buffers have canonical data/OOB layout, including context reads. */ struct apple_ppn_ops { - /* Success means the complete page and metadata passed exact readback. */ + /* Success means the complete page and metadata passed exact readback, + * or, while status_only() is true, that the package reported the + * program good (as iOS's PPNVFL judges it). + */ int (*program_page)(void *priv, unsigned int bus, unsigned int cau, unsigned int block, unsigned int page, const u8 *data, const u8 *oob); int (*read_page)(void *priv, unsigned int bus, unsigned int cau, unsigned int block, unsigned int page, bool context, u8 *data, u8 *oob, u8 *status); + /* Optional normal-view reads, grouped by ascending bus. Each data + * buffer is a separate DMA-mappable full page. Zero means transport + * completed; inspect ret and status for every row. -EOPNOTSUPP + * means no command ran and the caller can use the single-page path. + */ + /* Optional live capability check for providers with a runtime switch. */ + bool (*read_pages_enabled)(void *priv); + int (*read_pages)(void *priv, struct apple_ppn_read *pages, unsigned int n); + /* N42 direct read. After submit, the issuing thread can scatter a + * previous, completed command while this command owns its DMA pages. + */ + int (*read_pages_overlap)(void *priv, struct apple_ppn_read *pages, unsigned int n, + void (*scatter)(void *), void *ctx); + /* Normal-view scan with canonical single-page status/error semantics. */ + int (*read_scan_pages)(void *priv, struct apple_ppn_read *pages, unsigned int n); /* Optional. Caller owns the complete physical erase extent in all views. * Success means one normal-view CAU/block was erased and every byte * of data and OOB read back blank. On failure the extent may have @@ -26,6 +63,27 @@ struct apple_ppn_ops { */ int (*erase_block)(void *priv, unsigned int bus, unsigned int cau, unsigned int block); + /* Optional N42 normal-view erase, serial per bus and parallel across buses. */ + int (*erase_lanes)(void *priv, unsigned int block, u16 lanes, unsigned long deadline); + /* Optional, read at every use. True: program and erase are judged by + * the package's status alone, with no read-back (the provider's + * verify switch is off). The caller then also skips its own blank + * check after an erase. NULL: false. + */ + bool (*status_only)(void *priv); + /* Optional. @n pages, each programmed as program_page would, with + * the same meaning of success. Pages on one bus go in array order; + * the buses may run at the same time. Every page's ret is set; after a + * failure on a bus its later pages are not attempted (-ECANCELED). + * Returns 0, or the error of the first failed page in array order. + */ + /* As program_pages, with an optional CPU-only preparation callback + * between hardware submit and wait. It can be omitted on fallback. + */ + int (*program_pages_prepare)(void *priv, struct apple_ppn_program *pages, + unsigned int n, void (*prepare)(void *), void *ctx); + int (*program_pages)(void *priv, struct apple_ppn_program *pages, + unsigned int n); }; struct apple_ppn { From 0cf2716e34415dc0da244c4bad866d6fc0263478 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:18:32 +0100 Subject: [PATCH 46/59] mtd: apple-sftl: Add fenced N42 installation and batched reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replay 12H321 metadata and checkpoint the fenced Linux partitions. Check the LwVM header pair before accepting installation changes. Limit writes to the validated allocation windows and keep write support off by default. Batch reads by CAU and reuse bounce buffers for partially mapped rows. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/Kconfig | 9 + drivers/mtd/apple-n42-close-test.h | 243 ++ drivers/mtd/apple-n42-lwvm-alloc.h | 471 +++ drivers/mtd/apple-n42-write-pattern.h | 82 + drivers/mtd/apple-sftl-account-test.c | 92 + drivers/mtd/apple-sftl-account.c | 288 +- drivers/mtd/apple-sftl-account.h | 8 + drivers/mtd/apple-sftl-block.c | 455 ++- drivers/mtd/apple-sftl-core.c | 5101 ++++++++++++++++++++++--- drivers/mtd/apple-sftl-provider.h | 16 + drivers/mtd/apple-sftl-reclaim-test.c | 81 + drivers/mtd/apple-sftl-reclaim.c | 171 +- drivers/mtd/apple-sftl-reclaim.h | 28 + drivers/mtd/apple-sftl-test-fixture.h | 30 +- drivers/mtd/apple-sftl-test.c | 1212 ++++++ drivers/mtd/apple-sftl.h | 72 + 16 files changed, 7755 insertions(+), 604 deletions(-) create mode 100644 drivers/mtd/apple-n42-close-test.h create mode 100644 drivers/mtd/apple-n42-lwvm-alloc.h create mode 100644 drivers/mtd/apple-n42-write-pattern.h diff --git a/drivers/mtd/Kconfig b/drivers/mtd/Kconfig index 4db4ec217d9ef7..f4e53f43dc30cf 100644 --- a/drivers/mtd/Kconfig +++ b/drivers/mtd/Kconfig @@ -230,6 +230,15 @@ config MTD_APPLE_SFTL read-only as partitions of a second disk, applesftlNlwvm, with their LwVM number, PARTUUID and name. +config MTD_APPLE_SFTL_N42_WRITE + bool "Fenced writes to N42 Linux LwVM partitions" + depends on MTD_APPLE_SFTL + help + Allow the SFTL writer on the iPhone 5 16 GB SanDisk geometry. + It accepts Linux and XBOOTLDR partition writes only inside the + verified N42 install windows. Other layouts are unsupported. + Raw MTD writes remain disabled. Say N for a read-only kernel. + config MTD_APPLE_SFTL_KUNIT_TEST tristate "KUnit tests for Apple VFL/SwissPPNFTL" if !KUNIT_ALL_TESTS depends on KUNIT && MTD_APPLE_SFTL diff --git a/drivers/mtd/apple-n42-close-test.h b/drivers/mtd/apple-n42-close-test.h new file mode 100644 index 00000000000000..c0905d8cd57e71 --- /dev/null +++ b/drivers/mtd/apple-n42-close-test.h @@ -0,0 +1,243 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _APPLE_N42_CLOSE_TEST_H +#define _APPLE_N42_CLOSE_TEST_H + +/* + * Rung-2 N42 write test: fill one freshly claimed superblock with the + * deterministic pattern until the writer closes it with its native 12H321 + * BTOC (0x1c summary, nb = 4/8/12/16 chunks, flags = nb << 1, +0 span). + * + * Shared verbatim by the debugfs close_test (apple-n42-map-audit.c), the + * KUnit suite and the host replay, so all three run the same operation. + * No core writer change: closing is the writer's own sftl_block_full() / + * sftl_close_block() path. The caller arms the hard LBA fence first. + */ + +#include +#include +#include +#include +#include + +#include "apple-sftl.h" +#include "apple-n42-write-pattern.h" + +#define N42_CLOSE_TEST_SEED 0x4e343232U /* "N422" */ +#define N42_CLOSE_BTOC_TYPE 0x1cU +#define N42_CLOSE_META 16U +#define N42_CLOSE_CHUNK 4096U + +struct n42_close_result { + u32 block; /* landing superblock the writer claimed and closed */ + u16 lanes; /* its lane mask */ + u32 slots; /* 4 KiB slots in it: lanes * pages * 4 */ + u32 written; /* logical pages written (multiple of 4) */ + u32 writes; /* apple_sftl_write() calls (4 pages each) */ + u32 nb; /* BTOC chunks: slots - written */ + u64 seq_before; /* writer sequence before the first page */ + u64 seq_after; /* writer sequence after the close */ + bool closed; + bool timed_out; + u32 fail_lba; /* LBA of a failed write, U32_MAX if none */ + int fail_err; +}; + +/* + * Write the pattern 4 pages per call from @start until the block the first + * call claimed is closed. Stops at the close: one more call would claim a + * second clean block. @stop (optional) is polled between calls; when it + * fires the block stays open (the step-1 state) and -ETIMEDOUT is returned. + */ +static inline int n42_close_fill(struct apple_sftl *ftl, struct apple_sftl_inspect *insp, + u8 *batch, u32 start, u32 end, u32 seed, + bool (*stop)(void *priv), void *priv, + struct n42_close_result *r) +{ + struct apple_sftl_info info; + u32 lba, j; + int ret; + + memset(r, 0, sizeof(*r)); + r->block = U32_MAX; + r->fail_lba = U32_MAX; + if (!ftl || !insp || !batch || start >= end || end - start < 4) + return -EINVAL; + ret = apple_sftl_inspect(ftl, 0, insp, NULL); + if (ret) + return ret; + /* Fresh claim only, and no torn-block evacuation: relocation would + * program pages outside the LBA fence. + */ + if (insp->append_block != U32_MAX || insp->nr_torn) + return -EBUSY; + apple_sftl_get_info(ftl, &info); + r->seq_before = info.sequence; + + for (lba = start; lba + 4 <= end; lba += 4) { + if (stop && stop(priv)) { + r->timed_out = true; + return -ETIMEDOUT; + } + for (j = 0; j < 4; j++) + n42_write_pattern_fill(batch + j * N42_WRITE_TEST_PAGE_BYTES, + lba + j, seed, lba - start + j); + ret = apple_sftl_write(ftl, lba, batch, 4); + if (ret) { + r->fail_lba = lba; + r->fail_err = ret; + return ret; + } + r->written += 4; + r->writes++; + ret = apple_sftl_inspect(ftl, 0, insp, NULL); + if (ret) + return ret; + if (r->block == U32_MAX) { + /* The first call claimed the landing block. */ + if (insp->append_block == U32_MAX || + insp->append_block >= insp->subblocks) + return -EBADMSG; + r->block = insp->append_block; + r->lanes = insp->block_lanes[r->block]; + r->slots = hweight16(r->lanes) * insp->pages * 4; + } + if (insp->append_block == U32_MAX) { + r->closed = true; + break; + } + /* Anything else (a given-up block, a moved append point) is a failure. */ + if (insp->append_block != r->block || insp->append_position != r->written) + return -EIO; + } + apple_sftl_get_info(ftl, &info); + r->seq_after = info.sequence; + if (!r->closed) + return -ENOSPC; + r->nb = r->slots - r->written; + if (r->nb < 4 || r->nb > 16 || r->nb % 4 || + r->seq_after - r->seq_before != r->written) + return -EBADMSG; + return 0; +} + +/* Read back @count pattern pages from @start through @ftl. */ +static inline int n42_close_verify(struct apple_sftl *ftl, u8 *rbuf, u32 start, u32 count, + u32 seed, u32 *matched, u32 *first_bad) +{ + u32 i; + int ret; + + *matched = 0; + *first_bad = U32_MAX; + for (i = 0; i < count; i++) { + ret = apple_sftl_read(ftl, start + i, rbuf); + if (ret || !n42_write_pattern_check(rbuf, start + i, seed, i, NULL, NULL)) { + if (*first_bad == U32_MAX) + *first_bad = start + i; + continue; + } + (*matched)++; + } + return *matched == count ? 0 : -EIO; +} + +struct n42_btoc_info { + u32 pages; /* BTOC program units read */ + u32 runs; /* footer runs */ + u32 run_total; /* sum of run lengths */ + u8 type, flags; + u16 nb; + u32 span; + u64 base; +}; + +/* Map a 4-chunk program unit of @block to (bus, cau, page) for @lanes. */ +static inline int n42_close_unit(u16 lanes, u32 pages, u32 unit, + unsigned int *bus, unsigned int *cau, unsigned int *page) +{ + unsigned int count = hweight16(lanes), wanted, lane; + + if (!count || unit / count >= pages) + return -ERANGE; + *page = unit / count; + wanted = unit % count; + for (lane = 0; lane < 4; lane++) { + if (!(lanes & BIT(lane))) + continue; + if (!wanted--) { + *bus = lane & 1; + *cau = lane >> 1; + return 0; + } + } + return -ERANGE; +} + +/* + * Read the BTOC of the closed block straight from flash (normal view) and + * check it is the native 12H321 form the writer was meant to produce: all + * 4 metas per page = 0x1c, flags nb << 1, base = seq_before + 1 (when + * @base is non-zero), span = written (+0), nb, 0xffff; footer runs cover + * exactly [start, start + written) in order with relative = key - start. + */ +static inline int n42_close_check_btoc(const struct apple_ppn *ppn, u16 lanes, u32 pages, + u32 block, u32 start, u32 written, u32 nb, u64 base, + u8 *data, u8 *oob, struct n42_btoc_info *bi) +{ + unsigned int bus, cau, page, c; + u32 unit, e, rel = 0, entries; + u8 status = 0; + int ret; + + memset(bi, 0, sizeof(*bi)); + if (!ppn || !ppn->ops || !ppn->ops->read_page || nb < 4 || nb > 16 || nb % 4 || + written % 4) + return -EINVAL; + for (unit = written / 4; unit < (written + nb) / 4; unit++) { + ret = n42_close_unit(lanes, pages, unit, &bus, &cau, &page); + if (ret) + return ret; + ret = ppn->ops->read_page(ppn->priv, bus, cau, block, page, false, + data, oob, &status); + if (ret) + return ret; + for (c = 0; c < 4; c++) { + const u8 *m = oob + c * N42_CLOSE_META; + + bi->type = m[0]; + bi->flags = m[1]; + bi->base = get_unaligned_le64(m) >> 16; + bi->span = get_unaligned_le32(m + 8); + bi->nb = get_unaligned_le16(m + 12); + if (m[0] != N42_CLOSE_BTOC_TYPE || m[1] != (u8)(nb << 1) || + bi->span != written || bi->nb != nb || + get_unaligned_le16(m + 14) != 0xffff || + (base && bi->base != base)) + return -EBADMSG; + } + /* Footer runs: (relative, high, key, length), 16 B each. */ + entries = APPLE_PPN_PAGE_SIZE / N42_CLOSE_META; + for (e = 0; e < entries; e++) { + const u8 *f = data + e * N42_CLOSE_META; + u32 len = get_unaligned_le32(f + 12); + + if (!len) { + if (memchr_inv(f, 0, APPLE_PPN_PAGE_SIZE - e * N42_CLOSE_META)) + return -EBADMSG; + break; + } + if (get_unaligned_le32(f) != rel || + get_unaligned_le32(f + 8) != start + rel) + return -EBADMSG; + rel += len; + bi->runs++; + } + bi->pages++; + if (e < entries) + break; + } + bi->run_total = rel; + return rel == written ? 0 : -EBADMSG; +} + +#endif diff --git a/drivers/mtd/apple-n42-lwvm-alloc.h b/drivers/mtd/apple-n42-lwvm-alloc.h new file mode 100644 index 00000000000000..eae7fdbf9a9bbb --- /dev/null +++ b/drivers/mtd/apple-n42-lwvm-alloc.h @@ -0,0 +1,471 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _APPLE_N42_LWVM_ALLOC_H +#define _APPLE_N42_LWVM_ALLOC_H + +/* + * Rung-4 N42 Linux LwVM partition: the header change and the block-device + * write fence derived from it. Shared by the kernel (apple-n42-map-audit.c + * lwvm_create, apple-sftl-block.c), KUnit and the host replay. + * + * n42_lwvm_allocate() is Orchard's tests/lwvm.py allocate_free() (after + * Shayne Legault's #94 allocate): one Linux entry (0fc63daf-..., name + * "Linux", no attributes) appended after the others, its virtual range after + * every other partition's, the free chunks mapped to it in order, the CRC + * recomputed, the result decoded again. Nothing else in the header changes; + * that is checked byte for byte. + * + * The N42 window is fixed: chunks 176..179 (16 MiB each), LBAs + * [720896, 737280), freed by iOS's own LwVM tail release (Data shrunk to + * 3 GiB, physical 180..371). They are the tail of the 36-chunk run 144..179 + * that Orchard's install plan does not use: its 512 MiB boot partition takes + * 144..175 and its root the long run 372..952. The entry's virtual range + * starts right after Data's new end, 5,605,498,880. + */ + +#include +#include +#include +#include +#include + +#include "apple-sftl-lwvm.h" + +#define N42_FS_FIRST_CHUNK 176U +#define N42_FS_CHUNKS 4U +#define N42_FS_CHUNK_LBAS 4096U +#define N42_FS_LBA_START (N42_FS_FIRST_CHUNK * N42_FS_CHUNK_LBAS) +#define N42_FS_LBA_END ((N42_FS_FIRST_CHUNK + N42_FS_CHUNKS) * N42_FS_CHUNK_LBAS) +#define N42_LWVM_PRIMARY_LBA 0U +#define N42_LWVM_BACKUP_LBA (N42_FS_CHUNK_LBAS - 1U) /* 16 MiB - 4 KiB */ +/* Data's end after the 3 GiB release; the only layout lwvm_create accepts. */ +#define N42_LWVM_DATA_END 5605498880ULL + +#define N42_LWVM_BYTES 4096U +#define N42_LWVM_ID 0x10U +#define N42_LWVM_MEDIA 0x20U +#define N42_LWVM_COUNT 0x28U +#define N42_LWVM_CRC 0x2cU +#define N42_LWVM_PARTS 0x200U +#define N42_LWVM_PART_BYTES 0x80U +#define N42_LWVM_MAX_PARTS 8U +#define N42_LWVM_MAP 0x800U +#define N42_LWVM_FREE 0xf111U +#define N42_LWVM_HEAD 0xf000U +#define N42_LWVM_PAST 0xf3ffU + +/* 0fc63daf-8483-4772-8e79-3d69d8477de4, network byte order as LwVM stores it. */ +static const u8 n42_lwvm_linux_type[16] = { + 0x0f, 0xc6, 0x3d, 0xaf, 0x84, 0x83, 0x47, 0x72, + 0x8e, 0x79, 0x3d, 0x69, 0xd8, 0x47, 0x7d, 0xe4, +}; + +/* Fixed PARTUUID of the N42 test partition: 4e34324c-696e-7578-8000-6e3432667331 */ +static const u8 n42_lwvm_fs_guid[16] = { + 0x4e, 0x34, 0x32, 0x4c, 0x69, 0x6e, 0x75, 0x78, + 0x80, 0x00, 0x6e, 0x34, 0x32, 0x66, 0x73, 0x31, +}; + +static inline u32 n42_lwvm_crc(const u8 *h) +{ + static const u8 zero[4]; + u32 crc = crc32_le(~0U, h, N42_LWVM_CRC); + + crc = crc32_le(crc, zero, sizeof(zero)); + crc = crc32_le(crc, h + N42_LWVM_CRC + 4, N42_LWVM_BYTES - N42_LWVM_CRC - 4); + return ~crc; +} + +static inline bool n42_lwvm_is_linux_entry(const u8 *entry) +{ + static const u8 name[12] = { 'L', 0, 'i', 0, 'n', 0, 'u', 0, 'x', 0, 0, 0 }; + + return !memcmp(entry, n42_lwvm_linux_type, 16) && !memcmp(entry + 56, name, sizeof(name)); +} + +/* + * Strict check of a header pair as Orchard's parse() does it: copies equal, + * signature/CRC/size/count (the kernel decoder), non-zero media identity, + * every partition fully and singly mapped with unique non-zero identities + * and disjoint 4 KiB-aligned virtual ranges, and only the known sentinels. + */ +/* + * iOS 8.4.1's limit on where a partition may end (LwVM FUN_80a71afc and the + * header check FUN_80a71f30, N42 kernelcache): the usable logical space is the + * media's chunk count less 8 chunks, after the header reserve of two blocks + * and 16 KiB. A header past it fails iOS's sanity check and iOS then waits + * for its root device forever (2026-11-30). + */ +static inline u64 n42_lwvm_ios_end(u64 media, unsigned int chunk_shift) +{ + u64 chunks = media >> chunk_shift; + + return chunks > 8 ? ((chunks - 8) << chunk_shift) + 2 * N42_LWVM_BYTES + 0x4000 : 0; +} + +static inline int n42_lwvm_check(const u8 *primary, const u8 *backup, u64 media, + struct apple_sftl_lwvm *lw) +{ + u32 i, j, k; + int ret; + + if (memcmp(primary, backup, N42_LWVM_BYTES)) + return -EUCLEAN; + ret = apple_sftl_lwvm_decode(primary, media, lw); + if (ret) + return ret; + if (!memchr_inv(primary + N42_LWVM_ID, 0, 16)) + return -EINVAL; + for (i = 0; i < lw->nr_parts; i++) { + const struct apple_sftl_lwvm_part *p = &lw->parts[i]; + const u8 *e = primary + N42_LWVM_PARTS + i * N42_LWVM_PART_BYTES; + + if (p->error || p->mapped != p->nr_chunks || !memchr_inv(e, 0, 16) || + !memchr_inv(p->guid, 0, 16) || p->begin < N42_LWVM_BYTES || + p->begin % N42_LWVM_BYTES || p->end % N42_LWVM_BYTES || p->end > media || + p->end > n42_lwvm_ios_end(media, lw->chunk_shift)) + return -EINVAL; + for (j = 0; j < i; j++) + if (!memcmp(p->guid, lw->parts[j].guid, 16) || + (p->begin < lw->parts[j].end && p->end > lw->parts[j].begin)) + return -EINVAL; + } + for (k = 0; k < APPLE_SFTL_LWVM_CHUNKS; k++) { + u16 w = get_unaligned_le16(primary + N42_LWVM_MAP + 2 * k); + + if (w >> 12 != 0xf) + continue; + if (!k ? w != N42_LWVM_HEAD : + k < lw->chunks ? w != N42_LWVM_FREE : w != N42_LWVM_PAST) + return -EINVAL; + } + return 0; +} + +/* + * Build in @out the header with a Linux entry over chunks + * [first, first + chunks). -EEXIST when exactly that Linux entry is already + * there (nothing to write), -ENOSPC when the chunks are not free or there is + * no descriptor or virtual room. + */ +static inline int n42_lwvm_allocate(const u8 *primary, const u8 *backup, u64 media, + u32 first, u32 chunks, const u8 *guid, u8 *out, + struct apple_sftl_lwvm *lw, u32 *slot_out) +{ + u64 chunk_bytes, begin = N42_LWVM_BYTES, end; + u32 count, i, k; + u8 *d; + int ret; + + ret = n42_lwvm_check(primary, backup, media, lw); + if (ret) + return ret; + chunk_bytes = 1ULL << lw->chunk_shift; + count = lw->nr_parts; + for (i = 0; i < count; i++) { + const struct apple_sftl_lwvm_part *p = &lw->parts[i]; + + if (n42_lwvm_is_linux_entry(primary + N42_LWVM_PARTS + i * N42_LWVM_PART_BYTES) && + !p->pieced && p->nr_chunks == chunks && p->chunk[0] == first) { + *slot_out = i; + return -EEXIST; + } + if (!memcmp(p->guid, guid, 16)) + return -EINVAL; + if (p->end > begin) + begin = p->end; + } + if (count >= N42_LWVM_MAX_PARTS || + memchr_inv(primary + N42_LWVM_PARTS + count * N42_LWVM_PART_BYTES, 0, N42_LWVM_PART_BYTES)) + return -ENOSPC; + if (!chunks || !first || first + chunks > lw->chunks || !memchr_inv(guid, 0, 16)) + return -EINVAL; + for (k = first; k < first + chunks; k++) + if (get_unaligned_le16(primary + N42_LWVM_MAP + 2 * k) != N42_LWVM_FREE) + return -ENOSPC; + begin = (begin + N42_LWVM_BYTES - 1) / N42_LWVM_BYTES * N42_LWVM_BYTES; + end = begin + (u64)chunks * chunk_bytes; + if (end > media) + return -ENOSPC; + + memcpy(out, primary, N42_LWVM_BYTES); + put_unaligned_le32(count + 1, out + N42_LWVM_COUNT); + d = out + N42_LWVM_PARTS + count * N42_LWVM_PART_BYTES; + memset(d, 0, N42_LWVM_PART_BYTES); + memcpy(d, n42_lwvm_linux_type, 16); + memcpy(d + 16, guid, 16); + put_unaligned_le64(begin, d + 32); + put_unaligned_le64(end, d + 40); + put_unaligned_le64(0, d + 48); + memcpy(d + 56, "L\0i\0n\0u\0x\0", 10); + for (i = 0; i < chunks; i++) + put_unaligned_le16(count << 12 | i, out + N42_LWVM_MAP + 2 * (first + i)); + put_unaligned_le32(n42_lwvm_crc(out), out + N42_LWVM_CRC); + + /* Parse the result again; only the expected bytes may differ. */ + ret = n42_lwvm_check(out, out, media, lw); + if (ret) + return ret; + if (lw->nr_parts != count + 1 || lw->parts[count].pieced || + lw->parts[count].nr_chunks != chunks || lw->parts[count].chunk[0] != first || + lw->parts[count].begin != begin || lw->parts[count].end != end) + return -EBADMSG; + for (k = 0; k < N42_LWVM_BYTES; k++) { + bool expected = (k >= N42_LWVM_COUNT && k < N42_LWVM_CRC + 4) || + (k >= (u32)(d - out) && k < (u32)(d - out) + N42_LWVM_PART_BYTES) || + (k >= N42_LWVM_MAP + 2 * first && k < N42_LWVM_MAP + 2 * (first + chunks)); + + if (!expected && out[k] != primary[k]) + return -EBADMSG; + } + *slot_out = count; + return 0; +} + +/* + * The released layout rung 4 was planned on: exactly System and Data, with + * Data ending at 5,605,498,880. -ESTALE for anything else (the header from + * before the release included), so a stale or foreign table is never + * extended. + */ +static inline int n42_lwvm_released_layout(const u8 *primary, u64 media, + struct apple_sftl_lwvm *lw) +{ + int ret = apple_sftl_lwvm_decode(primary, media, lw); + + if (ret) + return ret; + if (lw->nr_parts != 2 || lw->parts[1].end != N42_LWVM_DATA_END || + lw->parts[1].pieced || lw->parts[0].end > lw->parts[1].begin) + return -ESTALE; + return 0; +} + +/* + * The write fence for the block device: the LBA range of the one Linux + * entry stored in order inside chunks 176..179. -ENOENT when there is none. + */ +static inline int n42_lwvm_linux_range(const u8 *header, u64 media, struct apple_sftl_lwvm *lw, + u32 *start, u32 *end, u32 *slot) +{ + u32 i, found = 0, lbas_per_chunk; + int ret; + + ret = apple_sftl_lwvm_decode(header, media, lw); + if (ret) + return ret; + if (lw->chunk_shift < 12) + return -EINVAL; + lbas_per_chunk = 1U << (lw->chunk_shift - 12); + for (i = 0; i < lw->nr_parts; i++) { + const struct apple_sftl_lwvm_part *p = &lw->parts[i]; + + if (!n42_lwvm_is_linux_entry(header + N42_LWVM_PARTS + i * N42_LWVM_PART_BYTES)) + continue; + if (p->error || p->pieced || !p->nr_chunks || + p->end - p->begin != (u64)p->nr_chunks << lw->chunk_shift || + p->chunk[0] < N42_FS_FIRST_CHUNK || + p->chunk[0] + p->nr_chunks > N42_FS_FIRST_CHUNK + N42_FS_CHUNKS) + return -EPERM; + *start = p->chunk[0] * lbas_per_chunk; + *end = (p->chunk[0] + p->nr_chunks) * lbas_per_chunk; + *slot = i; + found++; + } + return found == 1 ? 0 : found ? -EEXIST : -ENOENT; +} + + +/* + * The Orchard install on N42 (boot + root, as Orchard's planner places them + * after the release): entries the host planned are added to the header + * exactly the way OrchardLinux/orchard's USB receiver takes them + * (boot/initramfs/recovery/orchard-install-usb.c do_plan_lwvm): the new + * header only adds entries over free chunks and changes nothing else, and + * each new entry is the planned partition over its chunks in order. + */ +#define N42_INSTALL_MAX_RANGES 4U + +/* bc13c2ff-59e6-4262-a352-b275fd6f7172, the XBOOTLDR boot partition. */ +static const u8 n42_lwvm_xbootldr_type[16] = { + 0xbc, 0x13, 0xc2, 0xff, 0x59, 0xe6, 0x42, 0x62, + 0xa3, 0x52, 0xb2, 0x75, 0xfd, 0x6f, 0x71, 0x72, +}; + +/* The physical windows a Linux entry may occupy: 144..179 and 372..952. */ +static inline bool n42_lwvm_install_window(u32 first, u32 chunks) +{ + return chunks && ((first >= 144 && first + chunks <= 180) || + (first >= 372 && first + chunks <= 953)); +} + +/* NEXT is OLD with entries added over free chunks and nothing else changed. */ +static inline bool n42_lwvm_only_adds(const u8 *old, const u8 *next, u32 *old_count, + u32 *new_count) +{ + u32 k; + + *old_count = get_unaligned_le32(old + N42_LWVM_COUNT); + *new_count = get_unaligned_le32(next + N42_LWVM_COUNT); + if (*old_count < 1 || *new_count <= *old_count || *new_count > N42_LWVM_MAX_PARTS || + get_unaligned_le32(next + N42_LWVM_CRC) != n42_lwvm_crc(next)) + return false; + if (memcmp(old, next, N42_LWVM_COUNT) || + memcmp(old + N42_LWVM_CRC + 4, next + N42_LWVM_CRC + 4, N42_LWVM_PARTS - N42_LWVM_CRC - 4) || + memcmp(old + N42_LWVM_PARTS, next + N42_LWVM_PARTS, *old_count * N42_LWVM_PART_BYTES) || + memcmp(old + N42_LWVM_PARTS + *new_count * N42_LWVM_PART_BYTES, + next + N42_LWVM_PARTS + *new_count * N42_LWVM_PART_BYTES, + N42_LWVM_MAP - N42_LWVM_PARTS - *new_count * N42_LWVM_PART_BYTES)) + return false; + for (k = 0; k < APPLE_SFTL_LWVM_CHUNKS; k++) { + u16 was = get_unaligned_le16(old + N42_LWVM_MAP + 2 * k); + u16 now = get_unaligned_le16(next + N42_LWVM_MAP + 2 * k); + + if (was == now) + continue; + if (was != N42_LWVM_FREE || (now >> 12) < *old_count || (now >> 12) >= *new_count) + return false; + } + return true; +} + +/* Entry NUMBER (1-based) is the partition GUID of TYPE over FIRST.., in order. */ +static inline bool n42_lwvm_entry_is(const u8 *h, u32 number, const u8 *type, const u8 *guid, + u32 first, u32 chunks, u64 chunk_bytes) +{ + const u8 *e = h + N42_LWVM_PARTS + (number - 1) * N42_LWVM_PART_BYTES; + u32 k, owned = 0; + + if (!number || number > N42_LWVM_MAX_PARTS || memcmp(e, type, 16) || memcmp(e + 16, guid, 16) || + get_unaligned_le64(e + 40) - get_unaligned_le64(e + 32) != (u64)chunks * chunk_bytes || + get_unaligned_le64(e + 48)) + return false; + for (k = 0; k < APPLE_SFTL_LWVM_CHUNKS; k++) { + u16 w = get_unaligned_le16(h + N42_LWVM_MAP + 2 * k); + + if (w >> 12 == 0xf || (w >> 12) != number - 1) + continue; + if (k < first || k >= first + chunks || (w & 0xfff) != k - first) + return false; + owned++; + } + return owned == chunks; +} + +struct n42_install_spec { + u32 boot_number, boot_first, boot_chunks; + u32 root_number, root_first, root_chunks; + u8 boot_guid[16], root_guid[16]; +}; + +/* + * Whether NEXT may replace OLD (both copies of OLD equal): it adds exactly + * the planned boot (XBOOTLDR) and root (Linux) entries, inside the N42 + * install windows, and passes the strict parse. + */ +static inline int n42_lwvm_install_check(const u8 *old, const u8 *old_backup, const u8 *next, + u64 media, const struct n42_install_spec *sp, + struct apple_sftl_lwvm *lw) +{ + u32 had, have; + u64 chunk_bytes; + int ret; + + ret = n42_lwvm_check(old, old_backup, media, lw); + if (ret) + return ret; + chunk_bytes = 1ULL << lw->chunk_shift; + if (!n42_lwvm_only_adds(old, next, &had, &have) || have != had + 2 || + get_unaligned_le64(next + N42_LWVM_MEDIA) != media) + return -EPERM; + if (sp->boot_number <= had || sp->boot_number > have || sp->root_number <= had || + sp->root_number > have || sp->boot_number == sp->root_number || + !n42_lwvm_install_window(sp->boot_first, sp->boot_chunks) || + !n42_lwvm_install_window(sp->root_first, sp->root_chunks) || + !n42_lwvm_entry_is(next, sp->boot_number, n42_lwvm_xbootldr_type, sp->boot_guid, + sp->boot_first, sp->boot_chunks, chunk_bytes) || + !n42_lwvm_entry_is(next, sp->root_number, n42_lwvm_linux_type, sp->root_guid, + sp->root_first, sp->root_chunks, chunk_bytes)) + return -EPERM; + return n42_lwvm_check(next, next, media, lw); +} + +/* + * The block-device write fence after the install: every Linux or XBOOTLDR + * entry, each contiguous and inside the install windows. -EPERM when such + * an entry lies anywhere else; -ENOENT when there is none. + */ +static inline int n42_lwvm_install_ranges(const u8 *header, u64 media, struct apple_sftl_lwvm *lw, + u32 (*ranges)[2], u32 *slots, u32 *nr) +{ + u32 i, lbas_per_chunk; + int ret; + + *nr = 0; + ret = apple_sftl_lwvm_decode(header, media, lw); + if (ret) + return ret; + if (lw->chunk_shift < 12) + return -EINVAL; + lbas_per_chunk = 1U << (lw->chunk_shift - 12); + for (i = 0; i < lw->nr_parts; i++) { + const struct apple_sftl_lwvm_part *p = &lw->parts[i]; + const u8 *e = header + N42_LWVM_PARTS + i * N42_LWVM_PART_BYTES; + + if (memcmp(e, n42_lwvm_linux_type, 16) && memcmp(e, n42_lwvm_xbootldr_type, 16)) + continue; + if (p->error || p->pieced || !p->nr_chunks || get_unaligned_le64(e + 48) || + p->end - p->begin != (u64)p->nr_chunks << lw->chunk_shift || + !n42_lwvm_install_window(p->chunk[0], p->nr_chunks) || + *nr == N42_INSTALL_MAX_RANGES) + return -EPERM; + ranges[*nr][0] = p->chunk[0] * lbas_per_chunk; + ranges[*nr][1] = (p->chunk[0] + p->nr_chunks) * lbas_per_chunk; + slots[*nr] = i + 1; + (*nr)++; + } + return *nr ? 0 : -ENOENT; +} + + +/* + * A header write through the block device, as Orchard's USB receiver makes + * it: the copy at the end of chunk 0 (LBA 4095) first, then the primary + * (LBA 0), each the host's new header. Allowed only when the pair now on the + * medium is sound and NEXT only adds Linux or XBOOTLDR entries over free + * chunks inside the install windows (the receiver's own rule, with the N42 + * windows on top), and, for the primary, NEXT is the copy just written. + * Rewriting the bytes already there is allowed too. + */ +static inline int n42_lwvm_header_write_ok(const u8 *primary, const u8 *backup, const u8 *next, + u32 lba, u64 media, struct apple_sftl_lwvm *lw) +{ + u32 ranges[N42_INSTALL_MAX_RANGES][2], slots[N42_INSTALL_MAX_RANGES], nr, had, have, i; + int ret; + + if (lba != N42_LWVM_PRIMARY_LBA && lba != N42_LWVM_BACKUP_LBA) + return -EINVAL; + if (!memcmp(lba ? backup : primary, next, N42_LWVM_BYTES)) + return 0; + if (lba == N42_LWVM_PRIMARY_LBA ? memcmp(backup, next, N42_LWVM_BYTES) : + memcmp(primary, backup, N42_LWVM_BYTES)) + return -EPERM; + ret = n42_lwvm_check(primary, primary, media, lw); + if (ret) + return ret; + if (!n42_lwvm_only_adds(primary, next, &had, &have) || + get_unaligned_le64(next + N42_LWVM_MEDIA) != media) + return -EPERM; + for (i = had; i < have; i++) { + const u8 *e = next + N42_LWVM_PARTS + i * N42_LWVM_PART_BYTES; + + if (memcmp(e, n42_lwvm_linux_type, 16) && memcmp(e, n42_lwvm_xbootldr_type, 16)) + return -EPERM; + } + ret = n42_lwvm_check(next, next, media, lw); + if (ret) + return ret; + return n42_lwvm_install_ranges(next, media, lw, ranges, slots, &nr); +} + + +#endif diff --git a/drivers/mtd/apple-n42-write-pattern.h b/drivers/mtd/apple-n42-write-pattern.h new file mode 100644 index 00000000000000..d91f4c60391ae8 --- /dev/null +++ b/drivers/mtd/apple-n42-write-pattern.h @@ -0,0 +1,82 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _APPLE_N42_WRITE_PATTERN_H +#define _APPLE_N42_WRITE_PATTERN_H + +#include +#include +#include +#include + +/* + * Step-1 N42 single-chunk fenced write test target: + * Live LwVM header (l0.bin, media 16,000,000,000 B, chunk_shift 24 = 16 MiB + * = 4,096 4 KiB logical pages/chunk) has 6 whole free chunks (947..952, + * owner 0xf / 0xf111) between Data (144..946) and trailing partial chunk 953. + * Chunk 950 sits in the middle (48 MiB clear of Data, 32 MiB clear of tail): + * LBA range [3,891,200 .. 3,895,295] (end exclusive 3,895,296). + */ +#define N42_WRITE_TEST_CHUNK 950U +#define N42_WRITE_TEST_CHUNK_SHIFT 24U +#define N42_WRITE_TEST_CHUNK_PAGES 4096U +#define N42_WRITE_TEST_LBA_START (N42_WRITE_TEST_CHUNK * N42_WRITE_TEST_CHUNK_PAGES) +#define N42_WRITE_TEST_LBA_END ((N42_WRITE_TEST_CHUNK + 1U) * N42_WRITE_TEST_CHUNK_PAGES) +#define N42_WRITE_TEST_DEFAULT_COUNT 16U +#define N42_WRITE_TEST_DEFAULT_SEED 0x4e343231U /* "N421" */ +#define N42_WRITE_TEST_PAGE_BYTES 4096U +#define N42_WRITE_TEST_MAGIC "N42WT001" +#define N42_WRITE_TEST_MAGIC_LEN 8U +#define N42_WRITE_TEST_HEADER_BYTES 24U +#define N42_WRITE_TEST_CRC_OFFSET (N42_WRITE_TEST_PAGE_BYTES - 4U) + +static inline u32 n42_write_pattern_crc(const u8 *page) +{ + return crc32_le(~0U, page, N42_WRITE_TEST_CRC_OFFSET) ^ ~0U; +} + +static inline u32 n42_write_pattern_word(u32 lba, u32 seed, u32 index, u32 k) +{ + return (lba * 2654435761U) ^ (seed + k * 0x9e3779b9U) ^ + ((index + 1U) * 0x85ebca6bU); +} + +static inline void n42_write_pattern_fill(u8 *page, u32 lba, u32 seed, u32 index) +{ + u32 off, k = 0; + + memcpy(page, N42_WRITE_TEST_MAGIC, N42_WRITE_TEST_MAGIC_LEN); + put_unaligned_le32(lba, page + 8); + put_unaligned_le32(seed, page + 12); + put_unaligned_le32(index, page + 16); + put_unaligned_le32(0, page + 20); + for (off = N42_WRITE_TEST_HEADER_BYTES; off < N42_WRITE_TEST_CRC_OFFSET; off += 4, k++) + put_unaligned_le32(n42_write_pattern_word(lba, seed, index, k), page + off); + put_unaligned_le32(n42_write_pattern_crc(page), page + N42_WRITE_TEST_CRC_OFFSET); +} + +static inline bool n42_write_pattern_check(const u8 *page, u32 lba, u32 seed, u32 index, + u32 *got_crc_out, u32 *want_crc_out) +{ + u32 off, k = 0, stored_crc, calc_crc; + + stored_crc = get_unaligned_le32(page + N42_WRITE_TEST_CRC_OFFSET); + calc_crc = n42_write_pattern_crc(page); + if (got_crc_out) + *got_crc_out = stored_crc; + if (want_crc_out) + *want_crc_out = calc_crc; + if (memcmp(page, N42_WRITE_TEST_MAGIC, N42_WRITE_TEST_MAGIC_LEN)) + return false; + if (get_unaligned_le32(page + 8) != lba || + get_unaligned_le32(page + 12) != seed || + get_unaligned_le32(page + 16) != index || + get_unaligned_le32(page + 20) != 0) + return false; + if (stored_crc != calc_crc) + return false; + for (off = N42_WRITE_TEST_HEADER_BYTES; off < N42_WRITE_TEST_CRC_OFFSET; off += 4, k++) + if (get_unaligned_le32(page + off) != n42_write_pattern_word(lba, seed, index, k)) + return false; + return true; +} + +#endif diff --git a/drivers/mtd/apple-sftl-account-test.c b/drivers/mtd/apple-sftl-account-test.c index bba306251e6b7e..25502fa5b45924 100644 --- a/drivers/mtd/apple-sftl-account-test.c +++ b/drivers/mtd/apple-sftl-account-test.c @@ -265,6 +265,97 @@ static void account_native_free_allocation(struct kunit *test) KUNIT_EXPECT_EQ(test, plan.landing, 7); } +static void account_16gb_n42_layout(struct kunit *test) +{ + struct apple_sftl_extent runs[] = { + { 0, 5, 2 * APPLE_SFTL_16GB_STRIDE }, + { 5, APPLE_SFTL_16GB_LOGICAL_PAGES - 6, APPLE_SFTL_NO_ADDRESS }, + { APPLE_SFTL_16GB_LOGICAL_PAGES - 1, 1, 1045 * APPLE_SFTL_16GB_STRIDE + 3 }, + }; + struct apple_sftl_snapshot map = { + .runs = runs, .nr_runs = ARRAY_SIZE(runs), + .subblocks = APPLE_SFTL_N42_SUBBLOCKS, + .stride = APPLE_SFTL_16GB_STRIDE, + .logical_pages = APPLE_SFTL_16GB_LOGICAL_PAGES, + }; + struct apple_sftl_checkpoint image = {}; + struct apple_sftl_snapshot runtime = {}; + struct apple_sftl_allocation plan = {}; + struct apple_sftl_runtime_stats counters = { + .valid = 6, .free = 10, .data = 5, .context = 1, .reserved = 1, + .stat37 = 15292, .stat38_before_shift = 16384U << 6, + }; + struct apple_sftl_user_seq *updates; + u8 footer[APPLE_SFTL_META] = { 0x1c, 8 }; + u32 ctx_one = 532, ctx_two[2] = { 532, 495 }; + u32 i; + u8 *donor, *reads, *stats; + + image.count = APPLE_SFTL_16GB_ACCOUNT_RECORDS + APPLE_SFTL_16GB_MAP_MIN; + image.records = kunit_kcalloc(test, image.count, sizeof(*image.records), GFP_KERNEL); + updates = kunit_kcalloc(test, APPLE_SFTL_N42_SUBBLOCKS, sizeof(*updates), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, image.records); + KUNIT_ASSERT_NOT_NULL(test, updates); + apple_sftl_test_native_prefix_for(image.records, APPLE_SFTL_N42_SUBBLOCKS); + for (i = APPLE_SFTL_16GB_ACCOUNT_RECORDS; i < image.count; i++) { + image.records[i].meta[0] = 0x1f; + image.records[i].meta[1] = 4; + put_unaligned_le32(U32_MAX, image.records[i].meta + 12); + } + runtime.opaque = image.records; + runtime.nr_opaque = APPLE_SFTL_16GB_ACCOUNT_RECORDS; + runtime.subblocks = APPLE_SFTL_N42_SUBBLOCKS; + + /* 1-site context validation (names=1 on 12H321). */ + image.records[9].data[(532 - 512) * 8] = 7; + image.records[8].data[495 * 8] = 7; + KUNIT_EXPECT_TRUE(test, apple_sftl_account_context_sites(&runtime, &ctx_one, 1)); + KUNIT_EXPECT_FALSE(test, apple_sftl_account_context_sites(&runtime, ctx_two, 2)); + + /* Allocator prefers clean block 685 (wear 243) and schedules dirty block 745 (wear 242). */ + image.records[9].data[(685 - 512) * 8] = 1; + put_unaligned_le16(243, image.records[9].data + (685 - 512) * 8 + 6); + image.records[9].data[(745 - 512) * 8] = 9; + put_unaligned_le16(242, image.records[9].data + (745 - 512) * 8 + 6); + KUNIT_ASSERT_EQ(test, apple_sftl_account_plan_allocation(&runtime, &plan), 0); + KUNIT_EXPECT_EQ(test, plan.landing, 685); + KUNIT_EXPECT_EQ(test, plan.nr_erase, 1); + KUNIT_EXPECT_EQ(test, plan.erase[0], 745); + + /* Map accounting on 1046 subblocks / 4096 stride / 3906266 lpages. */ + KUNIT_ASSERT_EQ(test, apple_sftl_account_map(&image, &map), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(image.records[8].data + 2 * 8 + 2), 5); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(image.records[10].data + (1045 - 1024) * 8 + 2), 1); + stats = image.records[4].data; + KUNIT_EXPECT_EQ(test, get_unaligned_le64(stats + TEST_VALID_STAT_OFFSET), 6ULL); + + /* Retire & release a 16 GB donor (clears read count in record 20..23). */ + donor = image.records[8].data + 10 * 8; + reads = image.records[20].data + 10 * 4; + donor[0] = 3; + donor[1] = 8; + put_unaligned_le16(240, donor + 6); + put_unaligned_le32(999, reads); + put_unaligned_le16(4, footer + 12); + put_unaligned_le16(0xffff, footer + 14); + KUNIT_ASSERT_EQ(test, apple_sftl_account_retire(&image, 10, footer), 0); + KUNIT_EXPECT_EQ(test, donor[0], (u8)9); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(reads), 0U); + KUNIT_ASSERT_EQ(test, apple_sftl_account_release(&image, 10, APPLE_SFTL_ERASED_DONOR), 0); + KUNIT_EXPECT_EQ(test, donor[0], (u8)1); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(donor + 6), 241); + KUNIT_ASSERT_EQ(test, apple_sftl_account_refresh(&image, &counters), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(stats + TEST_VALID_STAT_OFFSET + 16), 10ULL); + + /* User-sequence update lands in records 12..19 (not 16..27). */ + put_unaligned_le32(11, updates[10].data); + put_unaligned_le32(22, updates[10].data + 4); + put_unaligned_le32(16, updates[10].data + 8); + put_unaligned_le32(2, updates[10].data + 12); + KUNIT_ASSERT_EQ(test, apple_sftl_account_user_seq(&runtime, updates), 0); + KUNIT_EXPECT_MEMEQ(test, image.records[12].data + 10 * 16, updates[10].data, 16); +} + static struct kunit_case account_cases[] = { KUNIT_CASE(account_recompute_valid_lbas), KUNIT_CASE(account_invalid_layout_or_map), @@ -272,6 +363,7 @@ static struct kunit_case account_cases[] = { KUNIT_CASE(account_context_and_retired_donor), KUNIT_CASE(account_native_free_allocation), KUNIT_CASE(account_saved_counts_before_refresh), + KUNIT_CASE(account_16gb_n42_layout), {} }; diff --git a/drivers/mtd/apple-sftl-account.c b/drivers/mtd/apple-sftl-account.c index d572b16e695e5e..a33ba921708500 100644 --- a/drivers/mtd/apple-sftl-account.c +++ b/drivers/mtd/apple-sftl-account.c @@ -1,8 +1,9 @@ // SPDX-License-Identifier: GPL-2.0-only /* - * SwissPPNFTL accounting on 13G36 64 GB media. cxtSaveSB at 0x8108e7e4 - * serializes the resident valid-LBA count into bytes 2..3 of each entry. - * Stat 9 counts all valid LBAs, including internal keys past the disk end. + * SwissPPNFTL accounting on 13G36 64 GB and 12H321 16 GB media. cxtSaveSB + * (13G36 0x8108e7e4, 12H321 0x80dd1350) serializes the resident valid-LBA + * count into bytes 2..3 of each 8-byte entry. Stat 9 counts all valid LBAs, + * including internal keys past the disk end. */ #include #include @@ -16,8 +17,6 @@ #define SFTL_STATS_START 4 /* 64 GB writer accounting: 16 KiB pages */ #define SFTL_SB_START 8 -#define SFTL_USER_SEQ_START 16 -#define SFTL_READ_COUNT_START 28 #define SFTL_SB_ENTRY_BYTES 8 #define SFTL_SB_PER_RECORD (APPLE_SFTL_CHUNK / SFTL_SB_ENTRY_BYTES) #define SFTL_MAX_WEAR 0xffff @@ -28,6 +27,83 @@ static u32 sftl_section_records(u32 subblocks, u32 per_record, u32 lpp) return round_up(DIV_ROUND_UP(subblocks, per_record), lpp); } +bool apple_sftl_layout_for_subblocks(u32 subblocks, struct apple_sftl_layout *out) +{ + struct apple_sftl_layout layout = {}; + u32 sb_records, user_records, read_records; + + if (!out) + return false; + if (subblocks == APPLE_SFTL_SUBBLOCKS) { + layout.subblocks = subblocks; + layout.stride = APPLE_SFTL_STRIDE; + layout.lane_slots = 512; + layout.logical_pages = APPLE_SFTL_LOGICAL_PAGES; + layout.unmapped_sentinel = 0x1ffffffU; + layout.map_batch = APPLE_SFTL_NATIVE_MAP_BATCH; + layout.map_min = APPLE_SFTL_NATIVE_MAP_BATCH; + layout.context_names = 2; + layout.footer_max = 32; + } else if (subblocks == APPLE_SFTL_P105_16GB_SUBBLOCKS || + subblocks == APPLE_SFTL_N42_SUBBLOCKS) { + layout.subblocks = subblocks; + layout.stride = APPLE_SFTL_16GB_STRIDE; + layout.lane_slots = 1024; + layout.logical_pages = APPLE_SFTL_16GB_LOGICAL_PAGES; + layout.unmapped_sentinel = 0x7fffffU; + layout.map_batch = APPLE_SFTL_16GB_MAP_BATCH; + layout.map_min = APPLE_SFTL_16GB_MAP_MIN; + layout.context_names = 1; + layout.footer_max = 16; + } else { + return false; + } + sb_records = sftl_section_records(subblocks, SFTL_SB_PER_RECORD, 4); + user_records = sftl_section_records(subblocks, APPLE_SFTL_CHUNK / 16, 4); + read_records = sftl_section_records(subblocks, APPLE_SFTL_CHUNK / 4, 4); + layout.provider_limit = layout.subblocks * layout.stride; + layout.sb_start = SFTL_SB_START; + layout.user_seq_start = layout.sb_start + sb_records; + layout.read_count_start = layout.user_seq_start + user_records; + layout.opaque_records = layout.read_count_start + read_records; + *out = layout; + return true; +} +EXPORT_SYMBOL_GPL(apple_sftl_layout_for_subblocks); + +bool apple_sftl_snapshot_layout(const struct apple_sftl_snapshot *snapshot, + struct apple_sftl_layout *out) +{ + struct apple_sftl_layout layout; + + if (!snapshot || !out) + return false; + if (snapshot->subblocks) { + if (!apple_sftl_layout_for_subblocks(snapshot->subblocks, &layout)) + return false; + if ((snapshot->stride && snapshot->stride != layout.stride) || + (snapshot->logical_pages && + snapshot->logical_pages != layout.logical_pages)) + return false; + *out = layout; + return true; + } + if (snapshot->stride || snapshot->logical_pages) + return false; + if (snapshot->opaque && snapshot->nr_opaque >= 4 && + snapshot->opaque[3].meta[1] == 1) { + u32 tail = get_unaligned_le32(snapshot->opaque[3].data + + APPLE_SFTL_CHUNK - 4); + + if (apple_sftl_layout_for_subblocks(tail, &layout)) { + *out = layout; + return true; + } + } + return apple_sftl_layout_for_subblocks(APPLE_SFTL_SUBBLOCKS, out); +} +EXPORT_SYMBOL_GPL(apple_sftl_snapshot_layout); + /* * The fixed native records are, in order: base (one page), statistics (one * page), block table, closed-block user sequences and read counts, each sized @@ -110,16 +186,23 @@ void apple_sftl_summarize_user_seq(struct apple_sftl_user_seq *out, const u8 *ru } EXPORT_SYMBOL_GPL(apple_sftl_summarize_user_seq); -static bool sftl_native_prefix(const struct apple_sftl_context_record *records, u32 count) +static bool sftl_native_prefix_layout(const struct apple_sftl_context_record *records, + u32 count, struct apple_sftl_layout *out) { - u32 i; + struct apple_sftl_layout layout; + u32 tail, i; - if (!records || count < APPLE_SFTL_ACCOUNT_RECORDS || - get_unaligned_le32(records[3].data + APPLE_SFTL_CHUNK - 4) != APPLE_SFTL_SUBBLOCKS) + if (!records || count < 4) return false; - for (i = 0; i < APPLE_SFTL_ACCOUNT_RECORDS; i++) - if (!apple_sftl_native_context_tag(i, records[i].meta)) + tail = get_unaligned_le32(records[3].data + APPLE_SFTL_CHUNK - 4); + if (!apple_sftl_layout_for_subblocks(tail, &layout) || + count < layout.opaque_records) + return false; + for (i = 0; i < layout.opaque_records; i++) + if (!apple_sftl_native_context_tag_for(layout.subblocks, i, + records[i].meta)) return false; + *out = layout; return true; } @@ -155,10 +238,11 @@ static void sftl_add_dirty(struct sftl_free_block pool[], u32 block, u16 wear) pool[replace] = (struct sftl_free_block) { block, wear }; } -/* Healthy 13G36 free-block allocation at 0x810932f8. Firmware first - * replenishes the clean pool. It prefers a clean block within one wear - * count of the least worn free block, using the candidates from the scan - * before replenishment. A selected dirty block may already be in the pool. +/* Healthy native free-block allocation (13G36 0x810932f8, verified identical + * on 12H321). Firmware first replenishes the clean pool. It prefers a clean + * block within one wear count of the least worn free block, using the + * candidates from the scan before replenishment. A selected dirty block may + * already be in the pool. */ int apple_sftl_account_plan_allocation(const struct apple_sftl_snapshot *runtime, struct apple_sftl_allocation *plan) @@ -166,15 +250,18 @@ int apple_sftl_account_plan_allocation(const struct apple_sftl_snapshot *runtime struct sftl_free_block pool[APPLE_SFTL_CLEAN_POOL]; struct sftl_free_block clean = { U32_MAX, U32_MAX }, least = clean; struct apple_sftl_allocation result = {}; + struct apple_sftl_layout layout; u32 i, nr_clean = 0; bool erased = false; - if (!plan || !runtime || runtime->nr_opaque != APPLE_SFTL_ACCOUNT_RECORDS || - !sftl_native_prefix(runtime->opaque, runtime->nr_opaque)) + if (!plan || !runtime || + !sftl_native_prefix_layout(runtime->opaque, runtime->nr_opaque, &layout) || + runtime->nr_opaque != layout.opaque_records || + (runtime->subblocks && runtime->subblocks != layout.subblocks)) return -EINVAL; for (i = 0; i < ARRAY_SIZE(pool); i++) pool[i] = (struct sftl_free_block) { U32_MAX, SFTL_MAX_WEAR }; - for (i = 0; i < APPLE_SFTL_SUBBLOCKS; i++) { + for (i = 0; i < layout.subblocks; i++) { const u8 *entry = sftl_sb_entry(runtime->opaque, i); u32 wear = get_unaligned_le16(entry + 6); @@ -213,33 +300,53 @@ int apple_sftl_account_plan_allocation(const struct apple_sftl_snapshot *runtime } EXPORT_SYMBOL_GPL(apple_sftl_account_plan_allocation); -static bool sftl_account_context_pair(struct apple_sftl_context_record *records, u32 count, - const u32 blocks[2]) +static bool sftl_account_context_sites(struct apple_sftl_context_record *records, + u32 count, const u32 *blocks, u32 nr_blocks, + struct apple_sftl_layout *out) { - u32 i; + struct apple_sftl_layout layout; + u32 i, j; - if (!blocks || blocks[0] == blocks[1] || !sftl_native_prefix(records, count)) + if (!blocks || !sftl_native_prefix_layout(records, count, &layout) || + nr_blocks != layout.context_names) return false; - for (i = 0; i < 2; i++) { + for (i = 0; i < nr_blocks; i++) { const u8 *entry; - if (!blocks[i] || blocks[i] >= APPLE_SFTL_SUBBLOCKS) + if (!blocks[i] || blocks[i] >= layout.subblocks) return false; + for (j = 0; j < i; j++) + if (blocks[j] == blocks[i]) + return false; entry = sftl_sb_entry(records, blocks[i]); /* Recovery assigns class 7 to context (0x1f) at 0x8108d762. - * The context allocator independently assigns it at 0x810937a4. + * The context allocator independently assigns it at 0x810937a4 + * (12H321 s_sb_next_cur_cxt at 0x80dd6324). */ if (entry[0] != 7 || get_unaligned_le16(entry + 2)) return false; } + if (out) + *out = layout; return true; } +bool apple_sftl_account_context_sites(const struct apple_sftl_snapshot *snapshot, + const u32 *blocks, u32 nr_blocks) +{ + struct apple_sftl_layout layout; + + return snapshot && + sftl_account_context_sites(snapshot->opaque, snapshot->nr_opaque, + blocks, nr_blocks, &layout) && + snapshot->nr_opaque == layout.opaque_records; +} +EXPORT_SYMBOL_GPL(apple_sftl_account_context_sites); + bool apple_sftl_account_context_pair(const struct apple_sftl_snapshot *snapshot, const u32 blocks[2]) { - return snapshot && snapshot->nr_opaque == APPLE_SFTL_ACCOUNT_RECORDS && - sftl_account_context_pair(snapshot->opaque, snapshot->nr_opaque, blocks); + return apple_sftl_account_context_sites(snapshot, blocks, 2); } EXPORT_SYMBOL_GPL(apple_sftl_account_context_pair); @@ -251,30 +358,35 @@ bool apple_sftl_account_gc_image(const struct apple_sftl_snapshot *before, const struct apple_sftl_checkpoint *image, const u32 blocks[2], u32 donor, u32 landing, u32 live, u16 footer_chunks) { + struct apple_sftl_layout layout, img_layout; u32 block, old, i, seen = 0, reads_per_record = APPLE_SFTL_CHUNK / sizeof(u32); const u8 *old_source, *source, *destination, *reads; - if (!sftl_native_prefix(before->opaque, before->nr_opaque) || - image->count <= APPLE_SFTL_ACCOUNT_RECORDS || - !sftl_account_context_pair(image->records, image->count, blocks) || - !donor || donor >= APPLE_SFTL_SUBBLOCKS || !landing || landing >= APPLE_SFTL_SUBBLOCKS || - !live || footer_chunks < 4 || footer_chunks > 32 || footer_chunks % 4) + if (!before || !image || + !sftl_native_prefix_layout(before->opaque, before->nr_opaque, &layout) || + before->nr_opaque != layout.opaque_records || + image->count <= layout.opaque_records || + !sftl_account_context_sites(image->records, image->count, blocks, + layout.context_names, &img_layout) || + img_layout.subblocks != layout.subblocks || + !donor || donor >= layout.subblocks || !landing || landing >= layout.subblocks || + !live || footer_chunks < 4 || footer_chunks > layout.footer_max || footer_chunks % 4) return false; /* This bounded path retires one previously occupied context block. * The save names freshly allocated sites and still serializes the old * role/wear before any retirement, including when the old site is full. */ old = get_unaligned_le32(before->opaque[0].data + 4); - if (!old || old >= APPLE_SFTL_SUBBLOCKS || old == blocks[0] || old == blocks[1] || + if (!old || old >= layout.subblocks || sftl_sb_entry(before->opaque, old)[0] != 7 || get_unaligned_le16(sftl_sb_entry(before->opaque, old) + 6) == SFTL_MAX_WEAR || memcmp(sftl_sb_entry(before->opaque, old), sftl_sb_entry(image->records, old), 8)) return false; - for (i = 0; i < 2; i++) { + for (i = 0; i < layout.context_names; i++) { const u8 *prior = sftl_sb_entry(before->opaque, blocks[i]); const u8 *next = sftl_sb_entry(image->records, blocks[i]); - if (prior[0] != 1 || get_unaligned_le16(prior + 2) || + if (old == blocks[i] || prior[0] != 1 || get_unaligned_le16(prior + 2) || (i == 1 && get_unaligned_le16(prior + 6) == SFTL_MAX_WEAR) || get_unaligned_le16(prior + 6) != get_unaligned_le16(next + 6)) return false; @@ -282,7 +394,7 @@ bool apple_sftl_account_gc_image(const struct apple_sftl_snapshot *before, old_source = sftl_sb_entry(before->opaque, donor); source = sftl_sb_entry(image->records, donor); destination = sftl_sb_entry(image->records, landing); - reads = image->records[SFTL_READ_COUNT_START + donor / reads_per_record].data + + reads = image->records[layout.read_count_start + donor / reads_per_record].data + (donor % reads_per_record) * sizeof(u32); if (old_source[0] != 3 || source[0] != 9 || source[1] != old_source[1] || get_unaligned_le16(source + 6) == SFTL_MAX_WEAR || @@ -291,7 +403,7 @@ bool apple_sftl_account_gc_image(const struct apple_sftl_snapshot *before, get_unaligned_le16(source + 2) || get_unaligned_le32(reads) || destination[0] != 4 || destination[1] || get_unaligned_le16(destination + 2) != live) return false; - for (block = 0; block < APPLE_SFTL_SUBBLOCKS; block++) { + for (block = 0; block < layout.subblocks; block++) { const u8 *entry = sftl_sb_entry(image->records, block); if (entry[0] != 4) @@ -306,13 +418,15 @@ bool apple_sftl_account_gc_image(const struct apple_sftl_snapshot *before, int apple_sftl_account_user_seq(struct apple_sftl_snapshot *snapshot, const struct apple_sftl_user_seq *updates) { + struct apple_sftl_layout layout; u32 block, per_record = APPLE_SFTL_CHUNK / sizeof(*updates); - if (snapshot->nr_opaque != APPLE_SFTL_ACCOUNT_RECORDS || - !sftl_native_prefix(snapshot->opaque, snapshot->nr_opaque)) + if (!snapshot || !updates || + !sftl_native_prefix_layout(snapshot->opaque, snapshot->nr_opaque, &layout) || + snapshot->nr_opaque != layout.opaque_records) return -EBADMSG; - for (block = 0; block < APPLE_SFTL_SUBBLOCKS; block++) { - u32 record = SFTL_USER_SEQ_START + block / per_record; + for (block = 0; block < layout.subblocks; block++) { + u32 record = layout.user_seq_start + block / per_record; u32 offset = block % per_record * sizeof(*updates); /* A native close always has a nonzero sample count. */ @@ -323,16 +437,21 @@ int apple_sftl_account_user_seq(struct apple_sftl_snapshot *snapshot, return 0; } -static int sftl_account_layout(const struct apple_sftl_checkpoint *image) +static int sftl_account_layout(const struct apple_sftl_checkpoint *image, + struct apple_sftl_layout *out) { + struct apple_sftl_layout layout; u32 i; - if (image->count <= APPLE_SFTL_ACCOUNT_RECORDS || image->count % 4 || - !sftl_native_prefix(image->records, image->count)) + if (!image || !image->records || + !sftl_native_prefix_layout(image->records, image->count, &layout) || + image->count <= layout.opaque_records || image->count % 4) return -EOPNOTSUPP; - for (i = APPLE_SFTL_ACCOUNT_RECORDS; i < image->count; i++) - if (!apple_sftl_native_context_tag(i, image->records[i].meta)) + for (i = layout.opaque_records; i < image->count; i++) + if (!apple_sftl_native_context_tag_for(layout.subblocks, i, + image->records[i].meta)) return -EOPNOTSUPP; + *out = layout; return 0; } @@ -395,27 +514,31 @@ static u8 *sftl_stat(u8 *stats, u32 id) */ int apple_sftl_account_retire(struct apple_sftl_checkpoint *image, u32 block, const u8 *footer_meta) { + struct apple_sftl_layout layout; u32 reads_per_record = APPLE_SFTL_CHUNK / sizeof(u32); u8 *entry, *reads; u16 chunks; int ret; - if (!image || !image->records || !footer_meta || !block || block >= APPLE_SFTL_SUBBLOCKS) + if (!image || !image->records || !footer_meta || !block) return -EINVAL; - ret = sftl_account_layout(image); + ret = sftl_account_layout(image, &layout); if (ret) return ret; + if (block >= layout.subblocks) + return -EINVAL; chunks = get_unaligned_le16(footer_meta + 12); - if (footer_meta[0] != 0x1c || chunks < 4 || chunks > 32 || chunks % 4 || + if (footer_meta[0] != 0x1c || chunks < 4 || chunks > layout.footer_max || chunks % 4 || footer_meta[1] >> 1 != chunks || get_unaligned_le16(footer_meta + 14) != 0xffff) return -EOPNOTSUPP; entry = sftl_sb_entry(image->records, block); if (entry[0] != 3 || entry[1] != footer_meta[1] || get_unaligned_le16(entry + 2)) return -EOPNOTSUPP; - reads = image->records[SFTL_READ_COUNT_START + block / reads_per_record].data + + reads = image->records[layout.read_count_start + block / reads_per_record].data + (block % reads_per_record) * sizeof(u32); - /* At 0x81090ade final invalidation only updates the entry and runtime - * totals. A save can see the previous cached free and data statistics. + /* At 13G36 0x81090ade (12H321 0x80dd6644) final invalidation only + * updates the entry and runtime totals. A save can see the previous + * cached free and data statistics. */ entry[0] = 9; put_unaligned_le32(0, reads); @@ -426,16 +549,19 @@ EXPORT_SYMBOL_GPL(apple_sftl_account_retire); int apple_sftl_account_release(struct apple_sftl_checkpoint *image, u32 block, enum apple_sftl_release event) { + struct apple_sftl_layout layout; u8 *entry; u16 wear; int ret; - if (!image || !image->records || !block || block >= APPLE_SFTL_SUBBLOCKS || + if (!image || !image->records || !block || (event != APPLE_SFTL_ERASED_DONOR && event != APPLE_SFTL_RELEASED_CONTEXT)) return -EINVAL; - ret = sftl_account_layout(image); + ret = sftl_account_layout(image, &layout); if (ret) return ret; + if (block >= layout.subblocks) + return -EINVAL; entry = sftl_sb_entry(image->records, block); if (entry[0] != (event == APPLE_SFTL_ERASED_DONOR ? 9 : 7) || get_unaligned_le16(entry + 2)) @@ -443,8 +569,8 @@ int apple_sftl_account_release(struct apple_sftl_checkpoint *image, u32 block, wear = get_unaligned_le16(entry + 6); if (wear == SFTL_MAX_WEAR) return -EOVERFLOW; - /* 0x81093958 follows completed ordinary erase; 0x81093848 also - * counts release of an unused context, which requires no erase. + /* 13G36 0x81093958 (12H321 0x80dd650c) follows completed ordinary erase; + * 0x81093848 also counts release of an unused context, which requires no erase. */ entry[0] = 1; put_unaligned_le16(wear + 1, entry + 6); @@ -458,20 +584,21 @@ EXPORT_SYMBOL_GPL(apple_sftl_account_release); int apple_sftl_account_refresh(struct apple_sftl_checkpoint *image, const struct apple_sftl_runtime_stats *runtime) { + struct apple_sftl_layout layout; u8 *stats; int ret; if (!image || !image->records || !runtime) return -EINVAL; - ret = sftl_account_layout(image); + ret = sftl_account_layout(image, &layout); if (ret) return ret; stats = sftl_stats(image, NULL); if (!stats) return -EOPNOTSUPP; - if (runtime->valid > APPLE_SFTL_LOGICAL_PAGES || + if (runtime->valid > layout.logical_pages || (u64)runtime->free + runtime->data + runtime->context + runtime->reserved > - APPLE_SFTL_SUBBLOCKS) + layout.subblocks) return -EBADMSG; put_unaligned_le64(runtime->valid, sftl_stat(stats, 9)); put_unaligned_le64(runtime->free, sftl_stat(stats, 10)); @@ -484,7 +611,9 @@ int apple_sftl_account_refresh(struct apple_sftl_checkpoint *image, } EXPORT_SYMBOL_GPL(apple_sftl_account_refresh); -static int sftl_account_runs(const struct apple_sftl_snapshot *map, u16 *counts, u32 *total) +static int sftl_account_runs(const struct apple_sftl_snapshot *map, + const struct apple_sftl_layout *layout, + u16 *counts, u32 *total) { u32 cursor = 0, i; @@ -492,72 +621,77 @@ static int sftl_account_runs(const struct apple_sftl_snapshot *map, u16 *counts, const struct apple_sftl_extent *run = &map->runs[i]; u32 length = run->length, addr = run->provider; - if (run->logical != cursor || !length || length > APPLE_SFTL_LOGICAL_PAGES - cursor) + if (run->logical != cursor || !length || length > layout->logical_pages - cursor) return -EBADMSG; cursor += length; if (addr == APPLE_SFTL_NO_ADDRESS) continue; - if (addr >= APPLE_SFTL_SUBBLOCKS * APPLE_SFTL_STRIDE || - length > APPLE_SFTL_SUBBLOCKS * APPLE_SFTL_STRIDE - addr) + if (addr >= layout->provider_limit || + length > layout->provider_limit - addr) return -EBADMSG; *total += length; while (length) { - u32 block = addr / APPLE_SFTL_STRIDE; - u32 n = min(length, APPLE_SFTL_STRIDE - addr % APPLE_SFTL_STRIDE); + u32 block = addr / layout->stride; + u32 n = min(length, layout->stride - addr % layout->stride); - if (counts[block] > APPLE_SFTL_STRIDE - n) + if (counts[block] > layout->stride - n) return -EBADMSG; counts[block] += n; addr += n; length -= n; } } - return cursor == APPLE_SFTL_LOGICAL_PAGES ? 0 : -EBADMSG; + return cursor == layout->logical_pages ? 0 : -EBADMSG; } static int sftl_update_map_counts(struct apple_sftl_checkpoint *image, const struct apple_sftl_snapshot *map, bool preserve_cache) { + struct apple_sftl_layout layout; u32 old_total = 0, total = 0, block; u8 *valid, *stats; u16 *counts; int ret; - if (!image || !image->records || !map || !map->runs || !map->nr_runs || - map->nr_runs > APPLE_SFTL_LOGICAL_PAGES) + if (!image || !image->records || !map || !map->runs || !map->nr_runs) return -EINVAL; - ret = sftl_account_layout(image); + ret = sftl_account_layout(image, &layout); if (ret) return ret; + if (map->nr_runs > layout.logical_pages || + (map->subblocks && map->subblocks != layout.subblocks) || + (map->stride && map->stride != layout.stride) || + (map->logical_pages && map->logical_pages != layout.logical_pages)) + return -EINVAL; stats = sftl_stats(image, NULL); if (!stats) return -EOPNOTSUPP; valid = sftl_stat(stats, 9); - for (block = 0; block < APPLE_SFTL_SUBBLOCKS; block++) { + for (block = 0; block < layout.subblocks; block++) { u16 n = get_unaligned_le16(sftl_sb_entry(image->records, block) + 2); - if (n > APPLE_SFTL_STRIDE) + if (n > layout.stride) return -EBADMSG; old_total += n; } if (preserve_cache) { u32 id; - if (get_unaligned_le64(valid) > APPLE_SFTL_LOGICAL_PAGES) + if (get_unaligned_le64(valid) > layout.logical_pages) return -EBADMSG; for (id = 10; id <= 13; id++) - if (get_unaligned_le64(sftl_stat(stats, id)) > APPLE_SFTL_SUBBLOCKS) + if (get_unaligned_le64(sftl_stat(stats, id)) > layout.subblocks) return -EBADMSG; } else if (get_unaligned_le64(valid) != old_total) { return -EBADMSG; } - counts = kcalloc(APPLE_SFTL_SUBBLOCKS, sizeof(*counts), GFP_NOIO); + counts = kcalloc(layout.subblocks, sizeof(*counts), GFP_NOIO); if (!counts) return -ENOMEM; - ret = sftl_account_runs(map, counts, &total); + ret = sftl_account_runs(map, &layout, counts, &total); if (!ret) { - for (block = 0; block < APPLE_SFTL_SUBBLOCKS; block++) + for (block = 0; block < layout.subblocks; block++) put_unaligned_le16(counts[block], sftl_sb_entry(image->records, block) + 2); if (!preserve_cache) put_unaligned_le64(total, valid); diff --git a/drivers/mtd/apple-sftl-account.h b/drivers/mtd/apple-sftl-account.h index c0cdb976f6b932..e825afb2bf948d 100644 --- a/drivers/mtd/apple-sftl-account.h +++ b/drivers/mtd/apple-sftl-account.h @@ -5,6 +5,7 @@ #include #define APPLE_SFTL_ACCOUNT_RECORDS 32U +#define APPLE_SFTL_16GB_ACCOUNT_RECORDS 24U /* Native subtype 5 keeps one little-endian tuple per closed block. */ struct apple_sftl_user_seq { @@ -13,8 +14,13 @@ struct apple_sftl_user_seq { struct apple_sftl_checkpoint; struct apple_sftl_gc_io; +struct apple_sftl_layout; struct apple_sftl_snapshot; +bool apple_sftl_layout_for_subblocks(u32 subblocks, struct apple_sftl_layout *out); +bool apple_sftl_snapshot_layout(const struct apple_sftl_snapshot *snapshot, + struct apple_sftl_layout *out); + #define APPLE_SFTL_CLEAN_POOL 6 struct apple_sftl_allocation { @@ -31,6 +37,8 @@ int apple_sftl_account_plan_allocation(const struct apple_sftl_snapshot *runtime int apple_sftl_account_read_stats(struct apple_sftl_checkpoint *image, const struct apple_sftl_gc_io *io, void *priv); +bool apple_sftl_account_context_sites(const struct apple_sftl_snapshot *snapshot, + const u32 *blocks, u32 nr_blocks); bool apple_sftl_account_context_pair(const struct apple_sftl_snapshot *snapshot, const u32 blocks[2]); bool apple_sftl_account_gc_image(const struct apple_sftl_snapshot *before, const struct apple_sftl_checkpoint *image, const u32 blocks[2], diff --git a/drivers/mtd/apple-sftl-block.c b/drivers/mtd/apple-sftl-block.c index 11b028b286af16..f076e4ab89332c 100644 --- a/drivers/mtd/apple-sftl-block.c +++ b/drivers/mtd/apple-sftl-block.c @@ -9,28 +9,39 @@ #include #include #include +#include #include #include +#include +#include #include "apple-sftl.h" +#include "apple-sftl-provider.h" #include "apple-sftl-lwvm.h" +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) +#include "apple-n42-lwvm-alloc.h" +#endif #define SFTL_BLOCK_NAME "apple-sftl" #define SFTL_DISK_MINORS 16 #define SFTL_LOGICAL_BYTES 4096U +#define SFTL_IO_TIMEOUT (600U * HZ) struct sftl_view; struct sftl_disk { struct apple_sftl *ftl; + struct apple_ppn *provider; struct blk_mq_tag_set tags; struct gendisk *disk; struct mutex io_lock; /* serializes requests using buffer */ u8 *buffer; + struct page *write_source[APPLE_SFTL_WRITE_MAX]; unsigned int id; bool dead; bool writable; struct sftl_view *view; + bool n42_writable; }; /* @@ -49,12 +60,63 @@ struct sftl_view { static DEFINE_IDA(sftl_disk_ids); static int sftl_major; +/* + * A write that covers a 4 KiB logical page whole has nothing to preserve: + * with write_whole_skip_read the page is not read first (counted in + * write_reads_skipped / write_reads). + */ +static bool write_whole_skip_read = true; +module_param(write_whole_skip_read, bool, 0644); +MODULE_PARM_DESC(write_whole_skip_read, + "Do not read a 4 KiB logical page before a write that replaces it whole"); +static ulong write_reads, write_reads_skipped; +module_param(write_reads, ulong, 0644); +module_param(write_reads_skipped, ulong, 0644); + +#define SFTL_WRITE_SECTORS (APPLE_SFTL_WRITE_MAX * (SFTL_LOGICAL_BYTES >> SECTOR_SHIFT)) +/* Two full N42 bus commands, 2 MiB per bus. */ +#define SFTL_READ_SECTORS (2U * APPLE_PPN_READ_MAX_PER_BUS * (APPLE_PPN_PAGE_SIZE / SECTOR_SIZE)) +#define SFTL_MAX_SECTORS ((SFTL_READ_SECTORS > SFTL_WRITE_SECTORS) ? \ + SFTL_READ_SECTORS : SFTL_WRITE_SECTORS) +static unsigned int max_sectors = SFTL_MAX_SECTORS; +module_param(max_sectors, uint, 0444); +MODULE_PARM_DESC(max_sectors, "Largest request in 512-byte sectors (128..8192)"); + +static void sftl_set_limits(struct queue_limits *limits, bool discard) +{ + unsigned int sectors = clamp(max_sectors, 128U, SFTL_MAX_SECTORS); + + if (discard) { + /* A request holds one contiguous range in a native trim record. */ + limits->max_hw_discard_sectors = round_down(UINT_MAX >> SECTOR_SHIFT, + SFTL_LOGICAL_BYTES >> SECTOR_SHIFT); + limits->discard_granularity = SFTL_LOGICAL_BYTES; + } + limits->max_hw_sectors = sectors; + /* Allow adjacent bios to merge up to both bus queues even with the + * small readahead hint below. Otherwise blk_validate_limits() + * applies the generic 1280 KiB request cap. + */ + limits->max_user_sectors = sectors; + /* 4 KiB segments: enough of them to fill a whole request. */ + limits->max_segments = max_t(unsigned int, BLK_MAX_SEGMENTS, + sectors / (SFTL_LOGICAL_BYTES >> SECTOR_SHIFT)); + /* + * blk_apply_bdi_limits derives readahead from twice io_opt. One stripe + * (four 16 KiB NAND pages, 64 KiB) gives 128 KiB of readahead: io_opt at + * the request size gave 8 MiB, so every file access read 8 MiB from NAND + * and Omarchy-A on the iPhone 5 crawled and drained its battery + * (2026-11-30). Large requests still go whole up to max_hw_sectors. + */ + limits->io_opt = 4 * 16384; +} + /* * The blocking queue and this lock keep the preallocated buffer exclusive. * The view passes its map: each 4 KiB page is looked up in it, so a request * can cross chunks in any order. */ -static int sftl_read_request(struct sftl_disk *sftl, struct request *request, +static int sftl_read_view_request(struct sftl_disk *sftl, struct request *request, const struct apple_sftl_lwvm_view *view) { struct req_iterator iterator; @@ -105,14 +167,262 @@ static int sftl_read_request(struct sftl_disk *sftl, struct request *request, return 0; } -/* Preserve untouched sectors at both ends and collect up to four 4 KiB - * pages per physical program. Request segments can split a logical page. +/* Save a cursor at each logical page boundary. Rows may finish out of + * request order, and even a single 4 KiB chunk can span multiple bios. + */ +struct sftl_read_target { + struct bio *bio; + struct page *direct; + struct bvec_iter iter; + unsigned int offset, length; +}; + +static struct page *sftl_direct_page(void *priv, unsigned int index) +{ + struct sftl_read_target *targets = priv; + + return targets[index].direct; +} + +/* A bio can refer to the same physical page more than once. Keep all + * aliases on the bounce path, including aliases of a partial segment. + */ +static void sftl_read_destinations(struct request *rq, struct sftl_read_target *targets, + unsigned int n) +{ + DEFINE_XARRAY(seen); + struct req_iterator ri; + struct bio_vec bv; + unsigned int i; + + rq_for_each_segment(bv, rq, ri) { + unsigned long pfn = page_to_pfn(bv.bv_page); + void *entry = xa_mk_value(xa_load(&seen, pfn) ? 2 : 1); + + if (xa_is_err(xa_store(&seen, pfn, entry, GFP_NOIO))) + goto out; + } + for (i = 0; i < n; i++) { + struct sftl_read_target *t = &targets[i]; + + if (t->offset || t->length != 4096 || PAGE_SIZE != 4096) + continue; + bv = bio_iter_iovec(t->bio, t->iter); + if (!bv.bv_offset && bv.bv_len == 4096 && + xa_load(&seen, page_to_pfn(bv.bv_page)) == xa_mk_value(1)) + t->direct = bv.bv_page; + } +out: + xa_destroy(&seen); +} + +static void sftl_copy_read_chunk(void *priv, unsigned int index, const u8 *data) +{ + const struct sftl_read_target *target = (struct sftl_read_target *)priv + index; + struct bvec_iter iter = target->iter; + struct bio *bio = target->bio; + unsigned int left = target->length, offset = target->offset; + + while (left) { + struct bio_vec bv; + unsigned int n; + void *mapped; + + while (!iter.bi_size) { + bio = bio->bi_next; + iter = bio->bi_iter; + } + bv = bio_iter_iovec(bio, iter); + n = min(left, bv.bv_len); + mapped = kmap_local_page(bv.bv_page); + if (data) + memcpy(mapped + bv.bv_offset, data + offset, n); + else + memset(mapped + bv.bv_offset, 0, n); + kunmap_local(mapped); + bio_advance_iter_single(bio, &iter, n); + left -= n; + offset += n; + } +} + +static int sftl_read_request(struct sftl_disk *sftl, struct request *request) +{ + u64 pos = (u64)blk_rq_pos(request) << SECTOR_SHIFT; + unsigned int offset = pos & (SFTL_LOGICAL_BYTES - 1); + unsigned int left = blk_rq_bytes(request), n = DIV_ROUND_UP(offset + left, + SFTL_LOGICAL_BYTES); + struct sftl_read_target *targets; + struct bio *bio = request->bio; + struct bvec_iter iter; + unsigned int i; + u32 *logical; + int ret = -ENOMEM; + + if (n <= 1 || !apple_sftl_provider_can_batch(sftl->provider)) + return sftl_read_view_request(sftl, request, NULL); + targets = kvmalloc_array(n, sizeof(*targets), GFP_NOIO); + logical = kvmalloc_array(n, sizeof(*logical), GFP_NOIO); + if (!targets || !logical) + goto out; + iter = bio->bi_iter; + for (i = 0; i < n; i++) { + unsigned int length = min(left, SFTL_LOGICAL_BYTES - offset); + unsigned int advance = length; + + logical[i] = pos >> 12; + targets[i] = (struct sftl_read_target) { + .bio = bio, .iter = iter, .offset = offset, .length = length, + }; + while (advance) { + unsigned int bytes = min(advance, iter.bi_size); + + if (!bytes && !bio->bi_next) { + ret = -EIO; + goto out; + } + bio_advance_iter(bio, &iter, bytes); + advance -= bytes; + if (!iter.bi_size && bio->bi_next) { + bio = bio->bi_next; + iter = bio->bi_iter; + } + } + pos += length; + left -= length; + offset = 0; + } + if (sftl->provider->ops->read_pages_overlap) + sftl_read_destinations(request, targets, n); + ret = apple_sftl_read_targets(sftl->ftl, logical, n, sftl_copy_read_chunk, + sftl_direct_page, targets); +out: + kvfree(logical); + kvfree(targets); + if (ret == -EOPNOTSUPP || ret == -ENOMEM) + return sftl_read_view_request(sftl, request, NULL); + return ret; +} + +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) +/* + * N42 install: Orchard's USB receiver writes the host's new LwVM header + * through this disk, the copy at LBA 4095 first, then the primary at LBA 0. + * The write fence never covers those pages; such a write passes only when + * n42_lwvm_header_write_ok() takes it, behind a one-page fence of its own. + * After the primary the fence becomes the entries of the new header. + */ +static int sftl_n42_header_write(struct sftl_disk *sftl, u32 lba) +{ + struct device *dev = disk_to_dev(sftl->disk); + u32 ranges[N42_INSTALL_MAX_RANGES][2], slots[N42_INSTALL_MAX_RANGES], nr, keep[4][2], nr_keep, i; + struct apple_sftl_lwvm *lw; + struct apple_sftl_info info; + u8 *p, *b; + u64 media; + int ret; + + apple_sftl_get_info(sftl->ftl, &info); + media = (u64)info.disk_pages * SFTL_LOGICAL_BYTES; + lw = kvzalloc(sizeof(*lw), GFP_NOIO); + p = kmalloc(SFTL_LOGICAL_BYTES, GFP_NOIO); + b = kmalloc(SFTL_LOGICAL_BYTES, GFP_NOIO); + ret = lw && p && b ? 0 : -ENOMEM; + if (!ret) + ret = apple_sftl_read(sftl->ftl, N42_LWVM_PRIMARY_LBA, p); + if (!ret) + ret = apple_sftl_read(sftl->ftl, N42_LWVM_BACKUP_LBA, b); + if (!ret) + ret = n42_lwvm_header_write_ok(p, b, sftl->buffer, lba, media, lw); + if (ret) { + dev_warn(dev, "N42 install: LwVM header write to LBA %u refused (%d)\n", lba, ret); + ret = -EPERM; + goto out; + } + nr_keep = apple_sftl_get_write_fences(sftl->ftl, keep); + apple_sftl_set_write_fence(sftl->ftl, lba, lba + 1); + ret = apple_sftl_write(sftl->ftl, lba, sftl->buffer, 1); + apple_sftl_set_write_fences(sftl->ftl, (const u32 (*)[2])keep, nr_keep); + dev_info(dev, "N42 install: LwVM header %s (LBA %u) written: %d\n", + lba ? "copy" : "primary", lba, ret); + if (ret || lba) + goto out; + ret = n42_lwvm_install_ranges(sftl->buffer, media, lw, ranges, slots, &nr); + if (!ret) + ret = apple_sftl_set_write_fences(sftl->ftl, (const u32 (*)[2])ranges, nr); + for (i = 0; !ret && i < nr; i++) + dev_info(dev, "N42: write fence [%u,%u) = LwVM partition %u\n", + ranges[i][0], ranges[i][1], slots[i]); +out: + kfree(b); + kfree(p); + kvfree(lw); + return ret; +} +#endif + +static struct page *sftl_buffer_page(void *addr) +{ + return is_vmalloc_addr(addr) ? vmalloc_to_page(addr) : virt_to_page(addr); +} + +static int sftl_write_pages(struct sftl_disk *sftl, u32 first, unsigned int count) +{ + struct page **pages = sftl->write_source; + const u8 *data = sftl->buffer; + void *mapped = NULL; + unsigned int i; + int ret; + +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) + if (sftl->n42_writable && (first == 0 || (first <= 4095 && first + count > 4095))) { + if (count != 1) + return -EPERM; + if (pages[0]) + memcpy_from_page(sftl->buffer, pages[0], 0, SFTL_LOGICAL_BYTES); + return sftl_n42_header_write(sftl, first); + } +#endif + /* The bios own these pages until request completion. Present whole + * pages to the synchronous writer without copying the batch into the + * block bounce buffer before it is packed into the two bus DMAs. + */ + if (count >= APPLE_PPN_PAGE_SIZE / SFTL_LOGICAL_BYTES) { + for (i = 0; i < count; i++) { + if (pages[i]) + continue; + if (PAGE_SIZE != SFTL_LOGICAL_BYTES || !PAGE_ALIGNED(sftl->buffer)) + break; + /* RMW and split chunks already live in the bounce buffer. */ + pages[i] = sftl_buffer_page(sftl->buffer + i * SFTL_LOGICAL_BYTES); + } + if (i == count) + mapped = vm_map_ram(pages, count, NUMA_NO_NODE); + } + if (mapped) { + data = mapped; + } else { + for (i = 0; i < count; i++) + if (pages[i] && pages[i] != sftl_buffer_page(sftl->buffer + i * SFTL_LOGICAL_BYTES)) + memcpy_from_page(sftl->buffer + i * SFTL_LOGICAL_BYTES, + pages[i], 0, SFTL_LOGICAL_BYTES); + } + ret = apple_sftl_write_multi(sftl->ftl, first, data, count); + if (mapped) + vm_unmap_ram(mapped, count); + return ret; +} + +/* Preserve untouched sectors at both ends and collect up to one + * 4 MiB request (256 physical programs) per call. Request segments can + * split a logical page. */ static int sftl_write_request(struct sftl_disk *sftl, struct request *request) { struct req_iterator iterator; struct bio_vec bvec; u64 position = (u64)blk_rq_pos(request) << SECTOR_SHIFT; + u64 end = position + blk_rq_bytes(request); u32 cached = U32_MAX, first = 0; unsigned int count = 0; int ret; @@ -133,32 +443,45 @@ static int sftl_write_request(struct sftl_disk *sftl, struct request *request) void *mapped; if (logical != cached) { - if (count == 4) { - ret = apple_sftl_write(sftl->ftl, first, - sftl->buffer, count); + if (count == APPLE_SFTL_WRITE_MAX) { + ret = sftl_write_pages(sftl, first, count); if (ret) return ret; count = 0; } if (!count) first = logical; - ret = apple_sftl_read(sftl->ftl, logical, - sftl->buffer + count * SFTL_LOGICAL_BYTES); - if (ret) - return ret; - count++; + /* The request is contiguous: a page lying wholly + * inside it is replaced whole, however its + * segments split it. */ + if (READ_ONCE(write_whole_skip_read) && !offset && + end - position >= SFTL_LOGICAL_BYTES) { + write_reads_skipped++; + } else { + ret = apple_sftl_read(sftl->ftl, logical, + sftl->buffer + count * SFTL_LOGICAL_BYTES); + if (ret) + return ret; + write_reads++; + } + sftl->write_source[count++] = NULL; cached = logical; } - mapped = kmap_local_page(bvec.bv_page); - memcpy(sftl->buffer + (count - 1) * SFTL_LOGICAL_BYTES + offset, - mapped + bvec.bv_offset + done, length); - kunmap_local(mapped); + if (PAGE_SIZE == SFTL_LOGICAL_BYTES && length == PAGE_SIZE && + !bvec.bv_offset && !done) { + sftl->write_source[count - 1] = bvec.bv_page; + } else { + mapped = kmap_local_page(bvec.bv_page); + memcpy(sftl->buffer + (count - 1) * SFTL_LOGICAL_BYTES + offset, + mapped + bvec.bv_offset + done, length); + kunmap_local(mapped); + } done += length; position += length; } } if (count) { - ret = apple_sftl_write(sftl->ftl, first, sftl->buffer, count); + ret = sftl_write_pages(sftl, first, count); if (ret) return ret; } @@ -186,15 +509,26 @@ static blk_status_t sftl_queue_rq(struct blk_mq_hw_ctx *hctx, ret = -ENODEV; } else if (req_op(request) == REQ_OP_FLUSH) { ret = apple_sftl_flush(sftl->ftl); - } else if (req_op(request) != REQ_OP_READ && req_op(request) != REQ_OP_WRITE) { - ret = -EOPNOTSUPP; } else if (blk_rq_pos(request) > capacity || blk_rq_sectors(request) > capacity - blk_rq_pos(request)) { ret = -EIO; } else if (req_op(request) == REQ_OP_WRITE) { ret = sftl->writable ? sftl_write_request(sftl, request) : -EROFS; + } else if (req_op(request) == REQ_OP_DISCARD) { + unsigned int sectors_per_page = SFTL_LOGICAL_BYTES >> SECTOR_SHIFT; + + if (!sftl->writable) + ret = -EROFS; + else if (!IS_ALIGNED(blk_rq_pos(request) | blk_rq_sectors(request), + sectors_per_page)) + ret = -EINVAL; + else + ret = apple_sftl_trim(sftl->ftl, blk_rq_pos(request) / sectors_per_page, + blk_rq_sectors(request) / sectors_per_page); + } else if (req_op(request) == REQ_OP_READ) { + ret = sftl_read_request(sftl, request); } else { - ret = sftl_read_request(sftl, request, NULL); + ret = -EOPNOTSUPP; } memalloc_noio_restore(noio_flags); mutex_unlock(&sftl->io_lock); @@ -229,7 +563,7 @@ static blk_status_t sftl_view_queue_rq(struct blk_mq_hw_ctx *hctx, blk_rq_sectors(request) > capacity - blk_rq_pos(request)) ret = -EIO; else - ret = sftl_read_request(sftl, request, &view->map); + ret = sftl_read_view_request(sftl, request, &view->map); memalloc_noio_restore(noio_flags); mutex_unlock(&sftl->io_lock); blk_mq_end_request(request, errno_to_blk_status(ret)); @@ -378,13 +712,66 @@ static void sftl_remove_view(struct sftl_disk *sftl) kfree(view); sftl->view = NULL; } +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) +/* + * N42 write tests: the block device is writable, and the SFTL hard LBA + * fence is every Linux or XBOOTLDR LwVM entry inside the install windows, + * chunks 144..179 and 372..952 (the rung-4 test partition, Orchard's boot + * and root). None yet: the fence stays empty and every write fails. Torn + * blocks would be evacuated outside the fence, so they keep the disk + * read-only. With the rung-5 reclaim test the writer reuses blank + * dirty-free blocks and leaves the native clean pool to iOS. + */ +static bool sftl_n42_fs_writable(struct platform_device *pdev, struct sftl_disk *sftl, + const struct apple_sftl_info *info) +{ + struct apple_sftl_inspect *insp; + struct apple_sftl_lwvm *lw; + u8 *header; + u32 ranges[N42_INSTALL_MAX_RANGES][2], slots[N42_INSTALL_MAX_RANGES], nr = 0, i; + bool ok = false; + int ret; + + insp = kvzalloc(sizeof(*insp), GFP_KERNEL); + lw = kvzalloc(sizeof(*lw), GFP_KERNEL); + header = kmalloc(APPLE_SFTL_LWVM_HEADER_BYTES, GFP_KERNEL); + if (!insp || !lw || !header) + goto out; + if (apple_sftl_inspect(sftl->ftl, 0, insp, NULL) || (insp->nr_torn && !insp->torn_in_place) || + insp->vfl_degraded || insp->context_degraded) { + dev_warn(&pdev->dev, "N42: torn or degraded media, read-only\n"); + goto out; + } + ok = true; + ret = apple_sftl_read(sftl->ftl, N42_LWVM_PRIMARY_LBA, header); + if (!ret) + ret = n42_lwvm_install_ranges(header, (u64)info->disk_pages * SFTL_LOGICAL_BYTES, + lw, ranges, slots, &nr); + if (ret) { + apple_sftl_set_write_fence(sftl->ftl, 0, 0); + dev_info(&pdev->dev, "N42: no Linux LwVM entry in chunks 144..179 or 372..952 (%d), write fence empty\n", + ret); + goto out; + } + apple_sftl_set_write_fences(sftl->ftl, (const u32 (*)[2])ranges, nr); + for (i = 0; i < nr; i++) + dev_info(&pdev->dev, "N42: write fence [%u,%u) = LwVM partition %u\n", + ranges[i][0], ranges[i][1], slots[i]); + ret = apple_sftl_set_reuse_dirty(sftl->ftl, true); + dev_info(&pdev->dev, "N42: dirty-free reuse %s (%d)\n", ret ? "off" : "on", ret); +out: + kfree(header); + kvfree(lw); + kvfree(insp); + return ok; +} +#endif static int sftl_disk_probe(struct platform_device *pdev) { struct queue_limits limits = { .logical_block_size = SECTOR_SIZE, .physical_block_size = SFTL_LOGICAL_BYTES, - .max_hw_sectors = 128, }; struct apple_ppn *provider = dev_get_platdata(&pdev->dev); struct apple_sftl_info info; @@ -408,12 +795,14 @@ static int sftl_disk_probe(struct platform_device *pdev) if (!sftl) return -ENOMEM; mutex_init(&sftl->io_lock); - sftl->buffer = kmalloc(APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + sftl->provider = provider; + /* The provider accepts virtually contiguous page data. */ + sftl->buffer = kvmalloc(APPLE_SFTL_WRITE_MAX * SFTL_LOGICAL_BYTES, GFP_KERNEL); if (!sftl->buffer) { ret = -ENOMEM; goto free_state; } - ret = apple_sftl_load(provider, &sftl->ftl); + ret = apple_sftl_load_disk(provider, &sftl->ftl); if (ret) goto free_buffer; apple_sftl_get_info(sftl->ftl, &info); @@ -424,9 +813,14 @@ static int sftl_disk_probe(struct platform_device *pdev) /* Appending continues the journal; it must end where the map does. */ sftl->writable = provider->ops->program_page && !info.read_only && info.sequence == info.journal_sequence; +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) + if (info.n42_install && sftl->writable) + sftl->writable = sftl_n42_fs_writable(pdev, sftl, &info); +#endif if (info.read_only) dev_warn(&pdev->dev, "incomplete metadata publication, read-only\n"); - else if (provider->ops->program_page && !sftl->writable) + else if (provider->ops->program_page && !sftl->writable && + !(IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) && info.n42_install)) dev_warn(&pdev->dev, "journal ends before the allocation floor, read-only\n"); if (sftl->writable) limits.features |= BLK_FEAT_FUA; @@ -445,7 +839,10 @@ static int sftl_disk_probe(struct platform_device *pdev) * the bounded 500-second scan and synchronous data/footer programs. */ if (sftl->writable) - sftl->tags.timeout = 600U * HZ; + sftl->tags.timeout = SFTL_IO_TIMEOUT; + sftl->n42_writable = sftl->writable && info.n42_install && + IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE); + sftl_set_limits(&limits, sftl->n42_writable); disk = blk_mq_alloc_disk(&sftl->tags, &limits, sftl); if (IS_ERR(disk)) { ret = PTR_ERR(disk); @@ -467,6 +864,8 @@ static int sftl_disk_probe(struct platform_device *pdev) dev_info(&pdev->dev, "%s: %s, %u logical pages, sequence %llu\n", disk->disk_name, sftl->writable ? "read-write" : "read-only", info.disk_pages, info.sequence); + if (sftl->writable) + apple_sftl_start_gc(sftl->ftl, &sftl->io_lock); sftl_add_view(pdev, sftl, &info); return 0; @@ -480,7 +879,7 @@ static int sftl_disk_probe(struct platform_device *pdev) free_ftl: apple_sftl_free(sftl->ftl); free_buffer: - kfree(sftl->buffer); + kvfree(sftl->buffer); free_state: kfree(sftl); return ret; @@ -500,10 +899,12 @@ static void sftl_disk_remove(struct platform_device *pdev) blk_mq_free_tag_set(&sftl->tags); ida_free(&sftl_disk_ids, sftl->id); apple_sftl_free(sftl->ftl); - kfree(sftl->buffer); + kvfree(sftl->buffer); kfree(sftl); } + + static struct platform_driver sftl_driver = { .probe = sftl_disk_probe, .remove = sftl_disk_remove, diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c index 7fc0b9af70e832..67b431ee24c16f 100644 --- a/drivers/mtd/apple-sftl-core.c +++ b/drivers/mtd/apple-sftl-core.c @@ -9,10 +9,14 @@ * or device data. Unsupported formats fail before a block device is created. */ #include +#include #include #include #include #include +#include +#include +#include #include #include #include @@ -23,6 +27,7 @@ #include #include "apple-sftl.h" +#include "apple-sftl-provider.h" #include "apple-sftl-vfl.h" #include "apple-sftl-reclaim.h" #include "apple-sftl-account.h" @@ -43,8 +48,10 @@ /* cxtSaveSB serializes the role in byte zero of each 8-byte block entry. */ enum sftl_block_role { SFTL_CLEAN_FREE = 1, + SFTL_ERASE_PENDING = 2, SFTL_CLOSED_DATA = 3, SFTL_OPEN_DATA = 4, + SFTL_ABANDONED_DATA = 6, SFTL_CONTEXT = 7, SFTL_DIRTY_FREE = 9, }; @@ -73,6 +80,9 @@ struct sftl_geometry { u16 bootstrap[2]; /* blocks whose page zero can seed the member list */ u16 nr_bootstrap; u16 map_batch; /* native map records are a multiple of this */ + u8 opaque_records; /* native non-map records in a context generation */ + u8 context_names; /* context sites named in a native base record */ + u8 footer_max; /* maximum BTOC footer width in 4 KiB chunks */ u32 disk_pages; /* logical pages exported as the disk */ u32 lpages; /* logical pages including the hidden tail */ bool writer; /* append, reclamation and checkpoints are modelled */ @@ -88,6 +98,25 @@ struct sftl_geometry { * checkpoint would persist a wrong acceptance. */ bool equal_sequences; /* replay a record that repeats the previous sequence */ + /* + * A torn page iOS left in an open block stays where it is: 12H321's + * replay (s_cxt_replay_streams, 0x80dcf8c8) keeps the records before + * it, types the block 6 (never appended to) and moves nothing; the + * block is reclaimed once it holds no valid page (0x80dd65e4). + */ + bool torn_in_place; + /* + * A block the selected table saves as context may hold user data: + * 12H321 types superblocks from their own pages (0x80dd010c), erases + * stale context sites at boot and reuses them for data. + */ + bool stale_context_role; + /* + * Replay the journal as 12H321 does (sftl_journal_ios): blocks in + * order of their first sequence, four streams merged by sequence, + * gaps accepted, record validity from type and LBA alone. + */ + bool ios_replay; }; /* 64 GB Hynix PPN with 13G36 (iOS 9.3.5) on the media. */ @@ -96,6 +125,8 @@ static const struct sftl_geometry sftl_64gb = { .subblocks = 2086, .vfl_pages = 64, .vfl_first = 2056, .bootstrap = { 2087 }, .nr_bootstrap = 1, .map_batch = APPLE_SFTL_NATIVE_MAP_BATCH, + .opaque_records = APPLE_SFTL_ACCOUNT_RECORDS, + .context_names = 2, .footer_max = 32, .disk_pages = 15625000, .lpages = 15625016, .writer = true, .lpp = 4, }; @@ -112,7 +143,9 @@ static const struct sftl_geometry sftl_16gb = { .buses = 2, .caus = 2, .lanes = 4, .blocks = 1064, .pages = 256, .subblocks = 1055, .vfl_pages = 128, .vfl_first = 1062, .bootstrap = { 1063, 1062 }, .nr_bootstrap = 2, - .map_batch = 16, + .map_batch = APPLE_SFTL_16GB_MAP_BATCH, + .opaque_records = APPLE_SFTL_16GB_ACCOUNT_RECORDS, + .context_names = 1, .footer_max = 16, .disk_pages = 3906250, .lpages = 3906266, .summary_sequences = true, .degrade_remnants = true, .hidden_tail_type2 = true, .lpp = 4, .older_epoch_subtype1 = true, @@ -139,19 +172,16 @@ static const struct sftl_geometry sftl_32gb = { .bootstrap = { 2041 }, .nr_bootstrap = 1, .map_batch = APPLE_SFTL_NATIVE_MAP_BATCH, .disk_pages = 7812500, .lpages = 7812516, .hidden_tail_type2 = true, - .degrade_remnants = true, .lpp = 2, .reused_names = true, .moved_epochs = true, + .footer_max = 32, .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. + * iPhone 5 (N42) 16 GB SanDisk PPN, 12H321 on the media: 2 buses x 2 CAUs + * (4 lanes), 1056 blocks of 256 MLC / 128 SLC pages, 1046 superblocks of + * 4096 slots, 8-block BFN tail (1046..1053), VFL in blocks 1054..1055, + * 3906250 exported + 16 hidden logical pages, 24 opaque context records + * naming 1 context block, 45-TLV stats identical to 13G36, map batch 16 + * (min 32), BTOC footers 4/8/12/16 chunks. Writing requires the fenced N42 configuration. */ static const struct sftl_geometry sftl_16gb_n42 = { .n42_install = true, @@ -159,9 +189,14 @@ static const struct sftl_geometry sftl_16gb_n42 = { .buses = 2, .caus = 2, .lanes = 4, .blocks = 1056, .pages = 256, .subblocks = 1046, .vfl_pages = 128, .vfl_first = 1054, .bootstrap = { 1055, 1054 }, .nr_bootstrap = 2, - .map_batch = 16, - .disk_pages = 3906250, .lpages = 3906266, .summary_sequences = true, + .map_batch = APPLE_SFTL_16GB_MAP_BATCH, + .opaque_records = APPLE_SFTL_16GB_ACCOUNT_RECORDS, + .context_names = 1, .footer_max = 16, + .disk_pages = 3906250, .lpages = 3906266, + .writer = IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE), + .summary_sequences = true, .equal_sequences = true, + .torn_in_place = true, .stale_context_role = true, .ios_replay = true, }; static const struct sftl_geometry *const sftl_geometries[] = { @@ -187,7 +222,154 @@ struct sftl_records { u32 count, capacity; }; +#define SFTL_STRIPE_MAX 64 /* up to 32 program rows on each N42 bus */ + +#define SFTL_GC_BATCH 32U +#define SFTL_GC_TIMEOUT (15U * HZ) +#define SFTL_GC_SAVE_TIMEOUT (45U * HZ) +#define SFTL_GC_SAVES 4U +#define SFTL_N42_SAVES 8U + +/* Each reason has its own rate limit. Selection guards count once per block + * per recovered state; media checks count failed attempts. + */ +#define SFTL_GC_REFUSAL(reason) \ + static ulong gc_refused_##reason; \ + module_param(gc_refused_##reason, ulong, 0444); \ + static inline int gc_refuse_##reason(u32 block, int err) \ + { \ + gc_refused_##reason++; \ + pr_info_ratelimited("apple-sftl: gc refused " #reason " block=%u ret=%d\n", \ + block, err); \ + return err; \ + } + +SFTL_GC_REFUSAL(footer_header) +SFTL_GC_REFUSAL(footer_replica) +SFTL_GC_REFUSAL(footer_runs) +SFTL_GC_REFUSAL(record_kind) +SFTL_GC_REFUSAL(fallback) +SFTL_GC_REFUSAL(replay) +SFTL_GC_REFUSAL(lanes) +SFTL_GC_REFUSAL(quarantine) +SFTL_GC_REFUSAL(owner) +SFTL_GC_REFUSAL(vfl) +SFTL_GC_REFUSAL(wear) +SFTL_GC_REFUSAL(source_read) +SFTL_GC_REFUSAL(map) +SFTL_GC_REFUSAL(source_lba) +SFTL_GC_REFUSAL(landing) +SFTL_GC_REFUSAL(checkpoint) + +static int sftl_gc_read_error(u32 block, int err) +{ + if (err == -ERANGE) + return gc_refuse_lanes(block, err); + if (err == -EBADMSG || err == -EOPNOTSUPP) + return gc_refuse_source_read(block, err); + return err; +} + +enum sftl_media_kind { + SFTL_MEDIA_NONE, + SFTL_MEDIA_OPEN, + SFTL_MEDIA_CLOSED, + SFTL_MEDIA_DATA_FOOTER, /* closed with a readable type-1 or type-2 head */ +}; + +/* Media certification belongs to one cold scan and its selected generation. */ +struct sftl_reclaim_pool { + DECLARE_BITMAP(gc_pending, SFTL_MAX_SUBBLOCKS); /* pinned until verified save */ + DECLARE_BITMAP(gc_excluded, SFTL_MAX_SUBBLOCKS); /* selection guard already counted */ + DECLARE_BITMAP(gc_landings, SFTL_MAX_SUBBLOCKS); /* protected for the batch */ + DECLARE_BITMAP(gc_unsupported, SFTL_MAX_SUBBLOCKS); /* current donor state */ + u32 gc_site, gc_landing, gc_count; /* batch checkpoint and current copy destination */ + u64 oldest_base; + /* Complete, exclusive one-site fallbacks, newest first. */ + u16 fallback_sites[SFTL_MAX_CONTEXTS]; + u16 nr_fallback_sites; + /* Cold-scan evidence for the next checkpoint. Writes invalidate it. */ + u64 media_high[SFTL_MAX_SUBBLOCKS]; + u8 media_kind[SFTL_MAX_SUBBLOCKS]; + DECLARE_BITMAP(media_changed, SFTL_MAX_SUBBLOCKS); + u16 lanes[SFTL_MAX_SUBBLOCKS]; + DECLARE_BITMAP(unchecked, SFTL_MAX_SUBBLOCKS); /* proposed lanes until media proof */ + u32 valid[SFTL_MAX_SUBBLOCKS]; /* mapped 4 KiB pages, including replay */ + DECLARE_BITMAP(runtime_data, SFTL_MAX_SUBBLOCKS); /* closed, data-only provenance */ + DECLARE_BITMAP(runtime_retired, SFTL_MAX_SUBBLOCKS); + bool maps_complete; /* selected and every retained fallback decoded */ + DECLARE_BITMAP(boot_retired, SFTL_MAX_SUBBLOCKS); + DECLARE_BITMAP(saved_live, SFTL_MAX_SUBBLOCKS); + u32 context_site; /* zero until a suitable site is held */ + bool context_claimed, gc_claimed; +}; + +enum sftl_claim_owner { + SFTL_CLAIM_DATA, + SFTL_CLAIM_CONTEXT, + SFTL_CLAIM_GC_CONTEXT, + SFTL_CLAIM_LANDING, +}; + +/* On by default: without it an iPhone 5 install runs out of blank blocks (2026-11-30). */ +static bool reclaim = true; +module_param(reclaim, bool, 0444); +MODULE_PARM_DESC(reclaim, "Reserve checkpoint space and reclaim certified N42 data blocks"); + +static ulong reclaim_runtime_retired, reclaim_runtime_claimed; +module_param(reclaim_runtime_retired, ulong, 0444); +module_param(reclaim_runtime_claimed, ulong, 0444); +MODULE_PARM_DESC(reclaim_runtime_retired, "Closed N42 data blocks retired during writes"); +MODULE_PARM_DESC(reclaim_runtime_claimed, "Runtime-retired N42 blocks successfully erased for reuse"); + +static ulong gc_fallback_retired; +module_param(gc_fallback_retired, ulong, 0444); +MODULE_PARM_DESC(gc_fallback_retired, "Obsolete historical N42 context sites verified blank"); + +static ulong gc_victims, gc_pages_moved, gc_retired; +static ulong gc_unsupported_marked, gc_skipped_unsupported; +module_param(gc_unsupported_marked, ulong, 0444); +module_param(gc_skipped_unsupported, ulong, 0444); +MODULE_PARM_DESC(gc_unsupported_marked, "Donors marked after a block-specific collection failure"); +MODULE_PARM_DESC(gc_skipped_unsupported, "Victim selections that skipped at least one marked donor"); +module_param(gc_victims, ulong, 0444); +module_param(gc_pages_moved, ulong, 0444); +module_param(gc_retired, ulong, 0444); +MODULE_PARM_DESC(gc_victims, "N42 partial-block collection attempts"); +MODULE_PARM_DESC(gc_pages_moved, "Live 4 KiB pages relocated and verified"); +MODULE_PARM_DESC(gc_retired, "Collected donors released after checkpoint verification"); + +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) || \ + IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) +/* Shared by cold reopens in this boot, under the save lock. */ +static DEFINE_MUTEX(sftl_save_lock); +static unsigned int gc_saves, n42_saves; +#endif + +#define SFTL_SCAN_DEPTH 32 +struct sftl_scan_window { + unsigned int count; + struct apple_ppn_read rows[2 * SFTL_SCAN_DEPTH]; + u8 meta[2 * SFTL_SCAN_DEPTH][APPLE_PPN_OOB_SIZE]; +}; + +struct sftl_next_stripe { + u64 base; + u32 first, count, rows; + bool ready; + u8 oob[SFTL_STRIPE_MAX][APPLE_PPN_OOB_SIZE]; +}; + struct apple_sftl { + struct sftl_next_stripe *next_stripe; + /* Separate windows for sparse block heads/tails and walks inside a block. */ + struct sftl_scan_window *window[2]; + struct task_struct *gc_task; + struct mutex *disk_io_lock; /* excludes compound block/debugfs operations */ + wait_queue_head_t gc_wait; + atomic_t gc_wake; + unsigned long last_io; + unsigned long load_deadline; /* bounded GC verification reload only */ struct apple_ppn *ppn; const struct sftl_geometry *geo; struct apple_sftl_vfl_source vfl_source; @@ -214,8 +396,10 @@ struct apple_sftl { void *checkpoint_priv; u32 footer_runs; u64 append_base; + bool append_has_trim; u8 *footer; - bool writer_prepared; + bool writer_prepared, reuse_scan_pending, prune_requested; + bool tolerated; u8 *page; u8 oob[APPLE_PPN_OOB_SIZE]; u32 lpp, psize, osize; /* from the geometry: chunks, data and OOB bytes per page */ @@ -232,13 +416,72 @@ struct apple_sftl { u32 nr_torn; u32 failures; bool evacuate; + /* apple_sftl_read's copy of the last NAND page it read (read_cache): + * rcache_addr is its page-aligned provider address, U32_MAX when + * empty. A programmed page only changes through an erase, which + * empties it; so does a program at that address. + */ + u8 *rcache; + /* Two disjoint banks of DMA bounce buffers for overlapped reads. */ + u8 *read_data[4 * APPLE_PPN_READ_MAX_PER_BUS]; + u8 rcache_oob[APPLE_PPN_OOB_SIZE]; + u32 rcache_addr; + struct apple_ppn_program stripe_prog[SFTL_STRIPE_MAX]; + u8 stripe_oob[SFTL_STRIPE_MAX][APPLE_PPN_OOB_SIZE]; u8 *stage, *move; /* the page being appended, a page being moved */ 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 */ + bool write_fenced; + u32 write_fence_start; + u32 write_fence_end; + /* Further allowed ranges (apple_sftl_set_write_fences), after the first. */ + u32 write_fence_more[3][2]; + u32 nr_write_fence_more; +#if IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) + bool test_writer; +#endif + /* + * 12H321 blank dirty-free reuse (see sftl_reuse_blank_dirty): data and + * context sites come only from blocks erased here, never from the + * native clean pool. linux_erased marks them for the next save. + */ + struct sftl_reclaim_pool *pool; + bool reuse_dirty; + u32 reused; + /* sftl_journal_ios: blocks whose first page did not read (12H321 + * types them 2 or 9 unless their last page is a summary). + */ + DECLARE_BITMAP(head_unread, SFTL_MAX_BLOCKS); + DECLARE_BITMAP(linux_erased, SFTL_MAX_SUBBLOCKS); + DECLARE_BITMAP(fallback_live, SFTL_MAX_SUBBLOCKS); }; +static void sftl_set_role(struct apple_sftl *sftl, u32 block, u8 role) +{ + if (sftl->pool && sftl->roles[block] != role) + __clear_bit(block, sftl->pool->gc_unsupported); + sftl->roles[block] = role; +} + +static bool sftl_writer_enabled(const struct apple_sftl *sftl) +{ + if (sftl->lpp != 4) + return false; +#if IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) + if (sftl->test_writer) + return true; +#endif + return sftl->geo->writer && sftl->ppn->ops->program_page; +} + +/* Exclusive upper bound on superblocks eligible for FTL data/context writes. */ +static u32 sftl_data_limit(const struct apple_sftl *sftl) +{ + return min_t(u32, sftl->geo->subblocks, sftl->geo->vfl_first); +} + static u32 sftl_stride(const struct apple_sftl *sftl) { return sftl->geo->lanes * sftl->geo->pages * sftl->lpp; @@ -280,6 +523,35 @@ static bool sftl_erased(const void *data, size_t size) return !memchr_inv(data, 0xff, size); } +static int sftl_scan_read(struct apple_sftl *sftl, unsigned int bus, unsigned int cau, + unsigned int block, unsigned int page, bool context, bool replay, + u8 *data, u8 *oob, u8 *status) +{ + unsigned int w, i; + + for (w = 0; !context && w < ARRAY_SIZE(sftl->window); w++) { + struct sftl_scan_window *win = sftl->window[w]; + + for (i = 0; win && i < win->count; i++) { + struct apple_ppn_read *p = &win->rows[i]; + + if (p->block != block || p->bus != bus || p->cau != cau || p->page != page) + continue; + p->block = U32_MAX; /* a retry must go back to media */ + if (!replay && p->ret == -EBADMSG && + (p->status == 0x43 || p->status == 0x45 || p->status == 0xc1)) + goto single; /* preserve the strict reader's refusal policy */ + memcpy(data, p->data, APPLE_PPN_PAGE_SIZE); + memcpy(oob, p->oob, APPLE_PPN_OOB_SIZE); + *status = p->status; + return p->ret; + } + } +single: + return sftl->ppn->ops->read_page(sftl->ppn->priv, bus, cau, block, page, + context, data, oob, status); +} + static int sftl_read_page(struct apple_sftl *sftl, unsigned int bus, unsigned int cau, unsigned int block, unsigned int page, bool context, u8 *data, u8 *oob) @@ -287,8 +559,10 @@ static int sftl_read_page(struct apple_sftl *sftl, unsigned int bus, u8 status; int ret; - ret = sftl->ppn->ops->read_page(sftl->ppn->priv, bus, cau, block, - page, context, data, oob, &status); + if (sftl->load_deadline && time_after_eq(jiffies, sftl->load_deadline)) + return -ETIMEDOUT; + status = 0; + ret = sftl_scan_read(sftl, bus, cau, block, page, context, false, data, oob, &status); if (ret) return ret; /* Refresh requires a writer. A reader must not hide that requirement. */ @@ -331,6 +605,120 @@ static int sftl_translate(struct apple_sftl *sftl, u32 address, return 0; } +static bool sftl_can_prefetch(struct apple_sftl *sftl) +{ + return sftl->geo->n42_install && sftl->ppn->ops->read_scan_pages && + apple_sftl_provider_can_batch(sftl->ppn); +} + +/* Caller owns a read-only recovery pass. A missing buffer or transport + * failure leaves the original checked single-page path in control. + */ +static void sftl_prefetch(struct apple_sftl *sftl, unsigned int w, const u32 *addresses, + unsigned int n) +{ + struct sftl_scan_window *win = sftl->window[w]; + unsigned int bus, i, count = 0; + + if (!n || !sftl_can_prefetch(sftl)) + return; + if (!win) { + win = kvzalloc(sizeof(*win), GFP_NOIO); + if (!win) + return; + sftl->window[w] = win; + } + win->count = 0; + for (bus = 0; bus < 2; bus++) { + unsigned int rows = 0; + + for (i = 0; i < n && rows < SFTL_SCAN_DEPTH; i++) { + unsigned int b, cau, block, page, chunk; + struct apple_ppn_read *p = &win->rows[count]; + + if (sftl_translate(sftl, addresses[i], &b, &cau, &block, &page, &chunk) || + b != bus) + continue; + if (!p->data) { + p->data = kzalloc(APPLE_PPN_PAGE_SIZE, GFP_NOIO); + if (!p->data) + return; + } + p->bus = b; + p->cau = cau; + p->block = block; + p->page = page; + p->oob = win->meta[count++]; + rows++; + } + } + if (count && !sftl->ppn->ops->read_scan_pages(sftl->ppn->priv, win->rows, count)) + win->count = count; +} + +static void sftl_prefetch_linear(struct apple_sftl *sftl, u32 start, unsigned int pages) +{ + u32 addresses[2 * SFTL_SCAN_DEPTH]; + unsigned int i; + + if (!sftl_can_prefetch(sftl)) + return; + pages = min_t(unsigned int, pages, ARRAY_SIZE(addresses)); + for (i = 0; i < pages; i++) + addresses[i] = start + i * 4; + sftl_prefetch(sftl, 1, addresses, pages); +} + +/* Queue heads or tails in block order. Preserve the two independent + * 32-row bus limits when sparse lane tables put most heads on one bus. + */ +static u32 sftl_prefetch_blocks(struct apple_sftl *sftl, u32 block, const u8 *heads) +{ + u32 addresses[2 * SFTL_SCAN_DEPTH], n = 0; + unsigned int used[2] = {}; + + for (; block < sftl->geo->subblocks && n < ARRAY_SIZE(addresses); block++) { + u16 lanes = sftl->lanes[block]; + u32 addr = block * sftl_stride(sftl); + unsigned int bus; + + if (!lanes) + continue; + if (heads) { + u8 kind = heads[block * SFTL_META]; + + if (kind != 1 && kind != 2 && !test_bit(block, sftl->head_unread)) + continue; + addr += (hweight16(lanes) * sftl->geo->pages - 1) * 4; + bus = (fls(lanes) - 1) & 1; + } else { + bus = __ffs(lanes) & 1; + } + if (used[bus] == SFTL_SCAN_DEPTH) + break; + used[bus]++; + addresses[n++] = addr; + } + sftl_prefetch(sftl, 0, addresses, n); + return block; +} + +static void sftl_free_windows(struct apple_sftl *sftl) +{ + unsigned int w, i; + + for (w = 0; w < ARRAY_SIZE(sftl->window); w++) { + struct sftl_scan_window *win = sftl->window[w]; + + if (!win) + continue; + for (i = 0; i < ARRAY_SIZE(win->rows); i++) + kfree(win->rows[i].data); + kvfree(win); + sftl->window[w] = NULL; + } +} + static int sftl_read_address(struct apple_sftl *sftl, u32 address, unsigned int *chunk) { @@ -344,6 +732,18 @@ static int sftl_read_address(struct apple_sftl *sftl, u32 address, sftl->page, sftl->oob); } +/* The caller owns page/oob throughout a sequential record walk. */ +static int sftl_read_record(struct apple_sftl *sftl, u32 address, u32 *page, + unsigned int *chunk) +{ + if (round_down(address, sftl->lpp) == *page) { + *chunk = address % sftl->lpp; + return 0; + } + *page = round_down(address, sftl->lpp); + return sftl_read_address(sftl, address, chunk); +} + static struct sftl_run *sftl_find(struct apple_sftl *sftl, u32 logical) { struct rb_node *node = sftl->runs.rb_node; @@ -377,7 +777,8 @@ static void sftl_insert(struct apple_sftl *sftl, struct sftl_run *run) sftl->nr_runs++; } -static int sftl_add_run(struct apple_sftl *sftl, u32 start, u32 end, u32 provider) +static int sftl_add_run(struct apple_sftl *sftl, u32 start, u32 end, u32 provider, + unsigned long *fallback_refs) { struct sftl_run *run; @@ -385,6 +786,16 @@ static int sftl_add_run(struct apple_sftl *sftl, u32 start, u32 end, u32 provide (provider != SFTL_UNMAPPED && (provider >= sftl_provider(sftl) || end - start > sftl_provider(sftl) - provider))) return -EBADMSG; + /* Validate fallback ranges identically, without replacing the selected tree. */ + if (fallback_refs) { + if (provider != SFTL_UNMAPPED) { + u32 first = provider / sftl_stride(sftl); + u32 last = (provider + end - start - 1) / sftl_stride(sftl); + + bitmap_set(fallback_refs, first, last - first + 1); + } + return 0; + } run = kmalloc(sizeof(*run), GFP_KERNEL); if (!run) return -ENOMEM; @@ -450,6 +861,30 @@ static void sftl_merge(struct apple_sftl *sftl, struct sftl_run *run) } } +static void sftl_retire_runtime(struct apple_sftl *sftl, u32 block); + +static void sftl_count_range(struct apple_sftl *sftl, u32 address, u32 length, bool add) +{ + u32 stride = sftl_stride(sftl); + + if (address == SFTL_UNMAPPED) + return; + while (length) { + u32 block = address / stride, count = min(length, stride - address % stride); + + __clear_bit(block, sftl->pool->gc_unsupported); + if (add) { + sftl->pool->valid[block] += count; + } else { + sftl->pool->valid[block] -= count; + if (!sftl->pool->valid[block] && sftl->writer_prepared) + sftl_retire_runtime(sftl, block); + } + address += count; + length -= count; + } +} + static int sftl_replace(struct apple_sftl *sftl, u32 start, u32 length, u32 address) { struct sftl_run *run, *new; @@ -473,12 +908,19 @@ static int sftl_replace(struct apple_sftl *sftl, u32 start, u32 length, u32 addr new = kmalloc(sizeof(*new), GFP_KERNEL); if (!new) return -ENOMEM; + /* From here the map update cannot fail. Credit first when both spans + * touch the same block so it never transiently reaches zero. + */ + if (sftl->pool) + sftl_count_range(sftl, address, length, true); run = sftl_find(sftl, start); for (node = &run->node; node; node = next) { run = rb_entry(node, struct sftl_run, node); if (run->start >= end) break; next = rb_next(node); + if (sftl->pool) + sftl_count_range(sftl, run->provider, run->end - run->start, false); rb_erase(node, &sftl->runs); kfree(run); sftl->nr_runs--; @@ -551,9 +993,11 @@ static int sftl_vfl_members(struct apple_sftl *sftl) for (seed = 0; seed < sftl->geo->nr_bootstrap; seed++) { block = sftl->geo->bootstrap[seed]; for (lane = 0; lane < sftl->geo->lanes; lane++) { + status = 0; ret = sftl->ppn->ops->read_page(sftl->ppn->priv, lane & 1, lane >> 1, block, 0, true, sftl->page, sftl->oob, &status); + if (ret) return ret; /* Some nonmembers report 45 at the bootstrap coordinate. Once @@ -582,10 +1026,7 @@ static int sftl_vfl_members(struct apple_sftl *sftl) if (members[i].block < sftl->geo->vfl_first || members[i].block >= sftl->geo->blocks || 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++) @@ -688,6 +1129,8 @@ static int sftl_vfl_index(struct apple_sftl *sftl, struct sftl_vfl_scan *scan) int ret; for (group = 0; group < 2; group++) { + bool group_populated = false; + for (page = 0; page < sftl->geo->vfl_pages; page++) { struct sftl_vfl_slot *slot = &scan->slots[group][page]; @@ -696,10 +1139,12 @@ static int sftl_vfl_index(struct apple_sftl *sftl, struct sftl_vfl_scan *scan) return ret; if (!slot->copies) continue; + group_populated = true; if (!scan->slots[group][0].copies || (u64)slot->age + page != scan->slots[group][0].age) return -EBADMSG; - if (group && slot->age <= scan->slots[0][0].age) { + if (group && scan->slots[0][0].copies && + slot->age <= scan->slots[0][0].age) { u32 other = scan->slots[0][0].age - slot->age; if (other < sftl->geo->vfl_pages && scan->slots[0][other].copies) @@ -717,10 +1162,15 @@ static int sftl_vfl_index(struct apple_sftl *sftl, struct sftl_vfl_scan *scan) source->page = page; } } - if (scan->slots[group][0].copies != 0xf) + /* On 12H321 profiles (nr_bootstrap == 2), a completely erased + * standby VFL bank is healthy; only partial copies degrade VFL. + */ + if (scan->slots[group][0].copies != 0xf && + (group_populated || sftl->geo->nr_bootstrap < 2)) sftl->vfl_degraded = true; } - return have_checkpoint ? 0 : -EBADMSG; + return have_checkpoint ? 0 : + -EBADMSG; } static int sftl_vfl_load_refs(struct apple_sftl *sftl, struct sftl_vfl_scan *scan, @@ -739,11 +1189,7 @@ 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) { - 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++) { @@ -907,7 +1353,7 @@ int apple_sftl_rotate_vfl(struct apple_sftl *sftl, const struct apple_sftl_vfl_o bool started = false; int ret; - if (!sftl || !ops || !ops->erase || !ops->program || !sftl->geo->writer || sftl->lpp != 4) + if (!sftl || !ops || !ops->erase || !ops->program || !sftl_writer_enabled(sftl)) return -EOPNOTSUPP; cold = kvzalloc(sizeof(*cold), GFP_NOIO); if (!cold) @@ -926,6 +1372,9 @@ int apple_sftl_rotate_vfl(struct apple_sftl *sftl, const struct apple_sftl_vfl_o goto out; cold->ppn = sftl->ppn; cold->geo = sftl->geo; + cold->lpp = sftl->lpp; + cold->psize = sftl->psize; + cold->osize = sftl->osize; cold->page = sftl->page; ret = sftl_vfl(cold); if (ret) @@ -985,13 +1434,14 @@ static void sftl_clear_runs(struct apple_sftl *sftl) } static int sftl_load_ranges(struct apple_sftl *sftl, const u8 *payload, u32 *cursor, - bool *short_range) + bool *short_range, unsigned long *fallback_refs) { u32 value = get_unaligned_le32(payload + 4), offset, lpages = sftl->geo->lpages; if (value == U32_MAX) return *cursor == lpages && get_unaligned_le32(payload) == U32_MAX ? - 0 : -EBADMSG; + 0 : + -EBADMSG; if (value != 0xfffffff0 || get_unaligned_le32(payload) != *cursor || *cursor == lpages) return -EBADMSG; @@ -1007,7 +1457,7 @@ static int sftl_load_ranges(struct apple_sftl *sftl, const u8 *payload, u32 *cur return -EBADMSG; if (value == BIT(fls(sftl_provider(sftl) * 2 - 1) - 1) - 1) value = SFTL_UNMAPPED; - ret = sftl_add_run(sftl, *cursor, *cursor + length, value); + ret = sftl_add_run(sftl, *cursor, *cursor + length, value, fallback_refs); if (ret) return ret; *cursor += length; @@ -1017,7 +1467,8 @@ static int sftl_load_ranges(struct apple_sftl *sftl, const u8 *payload, u32 *cur */ if (offset != SFTL_CHUNK && *cursor < lpages) *short_range = true; - return offset == 8 ? -EBADMSG : 0; + return offset == 8 ? + -EBADMSG : 0; } /* Native initial allocation takes an erased free block. A blank head alone @@ -1034,15 +1485,28 @@ static int sftl_load_block_roles(struct apple_sftl *sftl, const u8 *meta, const u16 live = get_unaligned_le16(payload + 2); if (selected) { + if (sftl->pool) + __assign_bit(block, sftl->pool->saved_live, live != 0); + /* 12H321 saves a former context site it has since filled + * with data as context (its scan types it from its pages); + * live pages then make it data, as for a free role. + */ + if (role == SFTL_CONTEXT && live && sftl->geo->stale_context_role) { + role = 0; + } if (role == SFTL_CONTEXT && live) return -EBADMSG; if ((role == SFTL_CLEAN_FREE || role == SFTL_DIRTY_FREE) && live) role = 0; - sftl->roles[block] = role; + sftl_set_role(sftl, block, role); sftl->block_flags[block] = payload[1]; sftl->wear[block] = get_unaligned_le16(payload + 6); - } else if (role != SFTL_CLEAN_FREE || live) { - __set_bit(block, sftl->fallback_occupied); + } else { + if (role != SFTL_CLEAN_FREE || live) + __set_bit(block, sftl->fallback_occupied); + /* Dirty-free reuse may take a block the fallback also has blank. */ + if ((role != SFTL_CLEAN_FREE && role != SFTL_DIRTY_FREE) || live) + __set_bit(block, sftl->fallback_live); } block++; payload += 8; @@ -1050,12 +1514,25 @@ static int sftl_load_block_roles(struct apple_sftl *sftl, const u8 *meta, const return 0; } +/* The native format has no stored per-page CRC. Compute it from the image + * being committed and retain an exact byte comparison for the erase proof. + */ +static bool sftl_record_matches(const struct apple_sftl_context_record *want, + const u8 *meta, const u8 *data) +{ + return !memcmp(meta, want->meta, SFTL_META) && + crc32_le(~0U, data, SFTL_CHUNK) == crc32_le(~0U, want->data, SFTL_CHUNK) && + !memcmp(data, want->data, SFTL_CHUNK); +} + /* -ENODATA distinguishes a valid prefix from malformed records or a read error. */ static int sftl_decode_generation(struct apple_sftl *sftl, const struct sftl_records *records, - u32 first, u32 end, unsigned long *named) + u32 first, u32 end, unsigned long *named, + unsigned long *fallback_refs, + const struct apple_sftl_checkpoint *expected) { u32 cursor = 0, map_records = 0, i, previous_order = 0, stride = sftl_stride(sftl); - u32 subblocks = sftl->geo->subblocks; + u32 subblocks = sftl->geo->subblocks, page = U32_MAX; u64 first_sequence = records->items[first].stamp & SFTL_SEQUENCE; bool base_tags = true, at_base = false, native = false, short_range = false; @@ -1070,11 +1547,22 @@ static int sftl_decode_generation(struct apple_sftl *sftl, const struct sftl_rec order < previous_order || record->address % sftl->lpp != index % sftl->lpp) return -EBADMSG; previous_order = order; - ret = sftl_read_address(sftl, record->address, &chunk); + if (!(index % (4 * 2 * SFTL_SCAN_DEPTH)) && !(record->address & 3) && + sftl_can_prefetch(sftl)) { + u32 k = 1; + + while (k < 2 * SFTL_SCAN_DEPTH && k * 4 < end - i && + records->items[i + 4 * k].address == record->address + 4 * k) + k++; + sftl_prefetch_linear(sftl, record->address, k); + } + ret = sftl_read_record(sftl, record->address, &page, &chunk); if (ret) return ret; meta = sftl->oob + chunk * SFTL_META; payload = sftl->page + chunk * SFTL_CHUNK; + if (expected && !sftl_record_matches(&expected->records[index], meta, payload)) + return -EBADMSG; if (sftl_stamp(meta) != record->stamp) return -EBADMSG; if (!index) { @@ -1106,13 +1594,13 @@ static int sftl_decode_generation(struct apple_sftl *sftl, const struct sftl_rec } if (native && !apple_sftl_native_context_tag_lpp(subblocks, sftl->lpp, index, meta)) return -EBADMSG; - if (native && subtype == 3) { + if (native && subtype == 3 && !fallback_refs) { ret = sftl_load_block_roles(sftl, meta, payload, true); if (ret) return ret; } if (subtype == 4) { - ret = sftl_load_ranges(sftl, payload, &cursor, &short_range); + ret = sftl_load_ranges(sftl, payload, &cursor, &short_range, fallback_refs); if (ret) return ret; map_records++; @@ -1124,18 +1612,18 @@ 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 * not establish the next safe write sequence. Recover for reads. */ - if (native || records->items[end - 1].address % sftl->lpp != sftl->lpp - 1) + if (!fallback_refs && (native || records->items[end - 1].address % sftl->lpp != sftl->lpp - 1)) sftl->context_degraded = true; return -ENODATA; } + if (fallback_refs) + return native ? 0 : -EOPNOTSUPP; sftl->native_context = native; return 0; } @@ -1147,8 +1635,7 @@ static int sftl_decode_generation(struct apple_sftl *sftl, const struct sftl_rec */ static bool sftl_journal_meta(const struct apple_sftl *sftl, const u8 *meta); -static int sftl_check_context_remnant(struct apple_sftl *sftl, u32 block, u64 selected, - u64 checkpoint) +static int sftl_check_context_remnant(struct apple_sftl *sftl, u32 block, u64 selected, u64 checkpoint) { u32 streams = hweight16(sftl->lanes[block]), pos, j; u16 ended = 0; @@ -1179,6 +1666,18 @@ static int sftl_check_context_remnant(struct apple_sftl *sftl, u32 block, u64 se } if (ended & lane) return -EBADMSG; + /* + * 12H321 types every superblock from its own pages + * (s_cxt_scan_diff, 0x80dd010c), not from the saved table: a + * former context site that iOS erased at boot (it erases every + * type-7 block the loaded base does not name) and then filled + * with user data is a data block, and the journal replays it. + * Only the saved role still says context. + */ + if (!pos && sftl->geo->stale_context_role && + (sftl->oob[0] == 1 || sftl->oob[0] == 2)) { + return 0; + } if (!pos && (!get_unaligned_le32(sftl->page) || get_unaligned_le32(sftl->page) > SFTL_MAX_CONTEXTS || get_unaligned_le32(sftl->page + 4) != block || @@ -1239,6 +1738,24 @@ static int sftl_check_context_remnant(struct apple_sftl *sftl, u32 block, u64 se static void sftl_mark_mapped(struct apple_sftl *sftl, unsigned long *blocks); +/* The context scan read all pages (including the erased tail). The base + * must name only this site and every record must occupy its native offset. + * Distinct groups passing this test cannot share a physical site. + */ +static bool sftl_one_site(const struct apple_sftl *sftl, const struct sftl_records *records, + u32 first, u32 end, const unsigned long *named) +{ + u32 start = records->items[first].address, stride = sftl_stride(sftl), i; + + if (start % stride || bitmap_weight(named, SFTL_MAX_SUBBLOCKS) != 1 || + !test_bit(start / stride, named) || end - first > stride) + return false; + for (i = first; i < end; i++) + if (records->items[i].address != start + i - first) + return false; + return true; +} + static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_records *journal) { struct sftl_records records = {}; @@ -1252,8 +1769,9 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re for (block = 1; block < subblocks; block++) { if (heads[block * SFTL_META] != 0x1f) continue; - if (count == SFTL_MAX_CONTEXTS) + if (count == SFTL_MAX_CONTEXTS) { goto out; + } pending[count++] = block; __set_bit(block, sftl->reserved); } @@ -1281,6 +1799,8 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re u16 lane = BIT(position % lanes); bool empty = false; + if (!(position % (2 * SFTL_SCAN_DEPTH))) + sftl_prefetch_linear(sftl, block * stride + position * sftl->lpp, pages - position); ret = sftl_read_address(sftl, block * stride + position * sftl->lpp, &chunk); if (ret) goto out; @@ -1332,8 +1852,9 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re } } ret = -EBADMSG; - if (!records.count) + if (!records.count) { goto out; + } sort(records.items, records.count, sizeof(*records.items), sftl_record_compare, NULL); /* An interrupted lane-by-lane retirement can leave older fragments * without their base. They cannot provide a recovery root. @@ -1343,21 +1864,24 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re if (sftl_flags(r) == 1 && !(r->address % sftl->lpp)) break; - if (!test_bit(r->address / stride, gapped)) + if (!test_bit(r->address / stride, gapped)) { goto out; + } } - if (oldest == records.count) + if (oldest == records.count) { goto out; + } for (i = 1; i < records.count; i++) - if (!sftl_record_compare(&records.items[i - 1], &records.items[i])) + if (!sftl_record_compare(&records.items[i - 1], &records.items[i])) { goto out; + } for (end = records.count; end > oldest; end = first) { first = end - 1; while (first > oldest && (sftl_flags(&records.items[first]) != 1 || records.items[first].address % sftl->lpp)) first--; memset(named, 0, sizeof(named)); - ret = sftl_decode_generation(sftl, &records, first, end, named); + ret = sftl_decode_generation(sftl, &records, first, end, named, NULL, NULL); if (!ret) break; if (ret != -ENODATA) @@ -1434,6 +1958,46 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re 2 * sftl->lpp + start / (SFTL_CHUNK / 8), meta)) sftl_load_block_roles(sftl, meta, sftl->page + chunk * SFTL_CHUNK, false); } + /* Runtime retirement can cross the replay cutoff only with complete + * fallback maps. A short or unfamiliar generation withholds that path. + */ + if (sftl->pool && sftl->native_context && !sftl->context_degraded && + !oldest && end == records.count) { + unsigned long *refs = gapped; /* gap checks are complete */ + struct sftl_reclaim_pool *pool = sftl->pool; + bool exclusive = sftl_one_site(sftl, &records, first, end, named); + u32 stop = first; + + bitmap_zero(refs, SFTL_MAX_SUBBLOCKS); + while (stop) { + u32 base = stop - 1; + + while (base && (sftl_flags(&records.items[base]) != 1 || + (records.items[base].address & 3))) + base--; + bitmap_zero(named, SFTL_MAX_SUBBLOCKS); + if (sftl_decode_generation(sftl, &records, base, stop, named, + refs, NULL)) + break; + if (exclusive && sftl_one_site(sftl, &records, base, stop, named) && + pool->nr_fallback_sites < ARRAY_SIZE(pool->fallback_sites)) + pool->fallback_sites[pool->nr_fallback_sites++] = + records.items[base].address / stride; + else + exclusive = false; + bitmap_or(sftl->fallback_live, sftl->fallback_live, named, SFTL_MAX_SUBBLOCKS); + stop = base; + } + bitmap_or(sftl->fallback_live, sftl->fallback_live, refs, SFTL_MAX_SUBBLOCKS); + for (i = 0; i < pool->nr_fallback_sites; i++) + if (test_bit(pool->fallback_sites[i], refs)) + exclusive = false; + if (stop || !exclusive) + pool->nr_fallback_sites = 0; + sftl->pool->maps_complete = !stop; + if (!stop) + sftl->pool->oldest_base = records.items[0].stamp & SFTL_SEQUENCE; + } /* Retain the selected generation's opaque records for later snapshots. */ for (i = first; i < end; i++) { const struct sftl_record *record = &records.items[i]; @@ -1546,13 +2110,20 @@ static int sftl_note_torn(struct apple_sftl *sftl, u32 block, u64 after) return 0; } -/* A torn page's four sequences may be missing after the given sequence. */ +/* + * A torn page's four sequences may be missing after the given sequence. On a + * profile that leaves torn blocks in place, one whose records end before the + * loaded checkpoint (a newer save was made since) hides nothing and reserves + * nothing. + */ static bool sftl_take_torn(struct apple_sftl *sftl, u64 last) { u32 i; for (i = 0; i < sftl->nr_torn; i++) - if (sftl->torn_after[i] <= last) { + if (sftl->torn_after[i] <= last && + !(sftl->geo->torn_in_place && sftl->torn_after[i] && + sftl->torn_after[i] < sftl->checkpoint_sequence)) { sftl->torn_after[i] = U64_MAX; return true; } @@ -1572,7 +2143,7 @@ static int sftl_read_open(struct apple_sftl *sftl, u32 address, unsigned int *ch static int sftl_remember_user_seq(struct apple_sftl *sftl, u32 block, const u8 *footer, u32 runs) { /* Four base chunks identify the layout validated by sftl_decode_generation. */ - if (sftl->context.count != APPLE_SFTL_ACCOUNT_RECORDS || + if (sftl->lpp != 4 || sftl->context.count != sftl->geo->opaque_records || sftl_flags(&sftl->context.items[3]) != 1) return 0; if (!sftl->closed_user_seq) { @@ -1585,9 +2156,80 @@ static int sftl_remember_user_seq(struct apple_sftl *sftl, u32 block, const u8 * return 0; } +/* + * 12H321 journal replay (sftl_journal_ios). The records of one block, as + * its block TOC lists them (s_btoc_read, 0x80dcf0f8): a closed block's + * summary entries, or runs built from an open block's chunk metadata. + * A run is one LBA (or token) range with consecutive sequences; seq is + * absolute. Tokens: SFTL_TOK_UECC for a chunk the scan could not use, + * SFTL_TOK_BLANK for an erased chunk. + */ +#define SFTL_TOK_UECC 0xffffff00U +#define SFTL_TOK_BLANK 0xffffffffU +#define SFTL_IOS_STREAMS 4U /* min(4, S+0xebc = 6) in s_cxt_replay_streams */ +#define SFTL_IOS_BATCH 256U /* chunks per metadata batch in s_btoc_read */ +#define SFTL_IOS_BATCH_BLANKS 64U + +struct sftl_ios_run { + u64 seq; + u32 key, address, count; +}; + +struct sftl_ios_block { + u64 base, end; /* first sequence; base + span, or U64_MAX if open */ + u32 block, first, nr; /* runs[first .. first + nr) */ + bool closed; + bool runtime_data; + u8 flags; +}; + +struct sftl_ios_scan { + struct sftl_ios_run *runs; + u32 nr_runs, capacity; + struct sftl_ios_block *blocks; + u32 nr_blocks; + u64 threshold; /* the loaded context's base sequence */ + u64 high; /* highest sequence of a usable record */ + u64 block_high; /* includes tokens that can stop replay */ +}; + +static int sftl_ios_add(struct sftl_ios_scan *ios, u64 seq, u32 key, u32 address, u32 count) +{ + struct sftl_ios_run *new; + u32 capacity; + + if (ios->nr_runs == SFTL_MAX_PROVIDER) + return -E2BIG; + if (ios->nr_runs == ios->capacity) { + capacity = min_t(u32, max(ios->capacity * 2, 1024U), SFTL_MAX_PROVIDER); + new = kvrealloc(ios->runs, array_size(capacity, sizeof(*new)), GFP_KERNEL); + if (!new) + return -ENOMEM; + ios->runs = new; + ios->capacity = capacity; + } + ios->runs[ios->nr_runs++] = (struct sftl_ios_run) { + .seq = seq, .key = key, .address = address, .count = count, + }; + ios->block_high = max(ios->block_high, key < SFTL_TOK_UECC ? seq + count - 1 : seq); + if (key < SFTL_TOK_UECC) + ios->high = max(ios->high, seq + count - 1); + return 0; +} + +/* + * With ios set (12H321 replay), the summary's entries become the block's + * runs as they stand: s_btoc_read reads no chunk metadata of a closed + * block, so trim chunks are not checked here, and the summary's own + * sequences are no records. A block whose summary ends below the loaded + * context's base sequence is skipped, as s_cxt_replay_streams skips its + * diff entry. + */ static int sftl_footer(struct apple_sftl *sftl, const u8 *head, u32 block, - u32 pages, struct sftl_records *journal, u64 *floor) + u32 pages, struct sftl_records *journal, u64 *floor, + struct sftl_ios_scan *ios, bool tail_checked) { + bool covered = false; u8 footer_meta[16]; u8 *footer; u32 chunks, span, index, position = 0, relative_end = 0; @@ -1599,25 +2241,51 @@ static int sftl_footer(struct apple_sftl *sftl, const u8 *head, u32 block, memcpy(footer_meta, sftl->oob, sizeof(footer_meta)); base = sftl_sequence(footer_meta); chunks = get_unaligned_le16(footer_meta + 12); + if (reclaim && sftl->geo->n42_install && chunks == 0xffff) + chunks = footer_meta[1] >> 1; span = get_unaligned_le32(footer_meta + 8); + /* + * 12H321 takes a closed block's base from its summary alone + * (s_cxt_scan_diff); it never compares the first chunk, and refuses only + * a first entry with rel != 0 (checked below). iOS does close blocks + * whose first chunk is later than the summary's base: block 877, + * 2026-12-01, summary 0x3a77ce23, first chunk 0x3a77ce6b. The strict + * replay keeps requiring the two to agree. + */ if (chunks < sftl->lpp || chunks > 32 || chunks % sftl->lpp || footer_meta[1] >> 1 != chunks || get_unaligned_le16(footer_meta + 14) != 0xffff || - base != sftl_sequence(head) || !span || base + span > SFTL_SEQUENCE + 1) + (!ios && base != sftl_sequence(head)) || !span || base + span > SFTL_SEQUENCE + 1) return -EBADMSG; + if (ios && sftl->pool) { + sftl->pool->media_kind[block] = (head[0] == 1 || head[0] == 2) && base ? + SFTL_MEDIA_DATA_FOOTER : SFTL_MEDIA_CLOSED; + ios->block_high = base + span - 1; + } *floor = max(*floor, base + span - 1); if (base + span - 1 <= sftl->checkpoint_sequence) { - if (head[0] == 1 && base && base + span - 1 < sftl->checkpoint_start) + if (head[0] == 1 && base && base + span - 1 < + (sftl->pool ? sftl->pool->oldest_base : sftl->checkpoint_start)) __set_bit(block, sftl->old_closed); - return 0; + if (!ios || base + span < ios->threshold) + return 0; + covered = true; } footer = kmalloc(chunks * SFTL_CHUNK, GFP_KERNEL); if (!footer) return -ENOMEM; - for (index = 0; index < chunks / sftl->lpp; index++) { - ret = sftl_read_address(sftl, block * sftl_stride(sftl) + - (pages - chunks / sftl->lpp + index) * sftl->lpp, &chunk); - if (ret) - goto out; + /* A strict successful tail read already checked this physical page. + * The iOS scan also accepts refresh status; reread those tails with + * the original strict footer policy before consuming their contents. + */ + sftl_prefetch_linear(sftl, block * sftl_stride(sftl) + (pages - chunks / sftl->lpp) * sftl->lpp, + chunks / sftl->lpp - tail_checked); + for (index = chunks / sftl->lpp; index-- > 0;) { + if (!tail_checked || index != chunks / sftl->lpp - 1) { + ret = sftl_read_address(sftl, block * sftl_stride(sftl) + + (pages - chunks / sftl->lpp + index) * sftl->lpp, &chunk); + if (ret) + goto out; + } for (chunk = 0; chunk < sftl->lpp; chunk++) if (memcmp(footer_meta, sftl->oob + chunk * SFTL_META, SFTL_META)) { ret = -EBADMSG; @@ -1625,6 +2293,13 @@ static int sftl_footer(struct apple_sftl *sftl, const u8 *head, u32 block, } memcpy(footer + index * sftl->psize, sftl->page, sftl->psize); } + if (ios) + ios->blocks[ios->nr_blocks++] = (struct sftl_ios_block) { + .base = base, .end = base + span, .block = block, + .first = ios->nr_runs, .closed = true, .flags = footer_meta[1], + .runtime_data = sftl->pool && head[0] == 1 && head[1] <= 1 && + chunks <= sftl->geo->footer_max && base > ios->threshold, + }; for (index = 0; index < chunks * SFTL_CHUNK; index += 16) { u32 relative = get_unaligned_le32(footer + index); u32 key = get_unaligned_le32(footer + index + 8); @@ -1641,6 +2316,25 @@ static int sftl_footer(struct apple_sftl *sftl, const u8 *head, u32 block, goto out; } relative_end = relative + length; + if (ios) { + u32 address = block * sftl_stride(sftl) + position; + + /* s_btoc_read: "0 == btoc->weaveSeqAdd" (panic). */ + if ((!index && relative) || + (key < 0xffff0000 && key + (length - 1) < key)) { + ret = -EBADMSG; + goto out; + } + /* A trim or token can affect recovery without owning a mapping. */ + if (key >= sftl->geo->lpages || relative_end > span) + ios->blocks[ios->nr_blocks - 1].runtime_data = false; + ret = sftl_ios_add(ios, base + relative, key, address, length); + if (ret) + goto out; + ios->blocks[ios->nr_blocks - 1].nr++; + position += length; + continue; + } for (offset = 0; offset < length; offset++, position++) { u64 sequence = base + relative + offset; u32 actual_key = key >= 0xffff0000 ? key : key + offset; @@ -1683,13 +2377,12 @@ static int sftl_footer(struct apple_sftl *sftl, const u8 *head, u32 block, ret = -EBADMSG; goto out; } + if (ios && span != relative_end && span - relative_end != chunks) + ios->blocks[ios->nr_blocks - 1].runtime_data = false; /* 12H321 summaries can count their own chunks after the last run. The * sequences belong to the summary and to no record of another block. - * Media whose context is native (13G36, iOS 9) does not: there the - * next block's first page carries those sequences, as a 16 GB P105 - * on iOS 9.3.5 shows, so the summary takes none of them. */ - if (sftl->geo->summary_sequences && !sftl->native_context && + if (!ios && sftl->geo->summary_sequences && !sftl->native_context && span == relative_end + chunks) { u32 address = block * sftl_stride(sftl) + pages * sftl->lpp - chunks, k; @@ -1704,7 +2397,7 @@ static int sftl_footer(struct apple_sftl *sftl, const u8 *head, u32 block, goto out; } } - ret = sftl_remember_user_seq(sftl, block, footer, index / SFTL_META); + ret = covered ? 0 : sftl_remember_user_seq(sftl, block, footer, index / SFTL_META); out: kfree(footer); return ret; @@ -1714,13 +2407,15 @@ static bool sftl_partial_footer(struct apple_sftl *sftl, const u8 *head, u32 position, u32 pages, u64 span) { const u8 *meta = sftl->oob; + u16 chunks = get_unaligned_le16(meta + 12); unsigned int chunk; - if (position < pages - SFTL_FOOTER_CHUNKS / sftl->lpp || - meta[0] != 0x1c || meta[1] != SFTL_FOOTER_CHUNKS * 2 || + if (chunks < sftl->lpp || chunks > sftl->geo->footer_max || chunks % sftl->lpp || + (!sftl->geo->summary_sequences && chunks != SFTL_FOOTER_CHUNKS) || + position < pages - chunks / sftl->lpp || + meta[0] != 0x1c || meta[1] != chunks * 2 || sftl_sequence(meta) != sftl_sequence(head) || get_unaligned_le32(meta + 8) != span || - get_unaligned_le16(meta + 12) != SFTL_FOOTER_CHUNKS || get_unaligned_le16(meta + 14) != 0xffff) return false; for (chunk = 1; chunk < sftl->lpp; chunk++) @@ -1796,48 +2491,492 @@ static void sftl_order_equal(const struct apple_sftl *sftl, const u8 *heads, } } -static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_records *journal) + +/* + * One NAND page holds four 4 KiB logical pages. A sequential reader asks for + * them one by one; with read_cache the page is read once and the other three + * are served from the copy (counted in read_cache_hits / read_cache_misses). + */ +static bool read_cache = true; +module_param(read_cache, bool, 0644); +MODULE_PARM_DESC(read_cache, "Serve the four 4 KiB pages of a NAND page from one read"); +static ulong read_cache_hits, read_cache_misses; +module_param(read_cache_hits, ulong, 0644); +module_param(read_cache_misses, ulong, 0644); + +/* Up to two N42 package queues per write to the open block. */ +static unsigned int program_batch = SFTL_STRIPE_MAX; +module_param(program_batch, uint, 0644); +MODULE_PARM_DESC(program_batch, + "Maximum physical pages per user program batch (1..64)"); +static ulong stripes, stripe_pages, stripe_failures; +module_param(stripes, ulong, 0644); +module_param(stripe_pages, ulong, 0644); +module_param(stripe_failures, ulong, 0644); + +enum sftl_ios_page { SFTL_IOS_META, SFTL_IOS_BLANK, SFTL_IOS_UECC }; + +/* + * Read one page as 12H321's block scan sees it (s_btoc_scan_status_cb, + * 0x80dcf06c): an erased status makes every chunk blank and its bytes are + * not looked at; a page that does not decode makes every chunk a "uECC" + * token ("S_TOK_UECC vba:... status:..."); a good page, refresh requested + * or not, hands its metadata on. A provider that fails twice stops the + * load: that is a Linux read path problem, not a flash state. + */ +static int sftl_ios_read(struct apple_sftl *sftl, u32 address, enum sftl_ios_page *state, + unsigned int *chunk, bool *strict) { - u64 floor = sftl->checkpoint_sequence, expected = floor + 1; - u32 nr_context = journal->count; - u32 block, position, i, pages, stride = sftl_stride(sftl); - unsigned int chunk; + unsigned int bus, cau, block, page, tries; + u8 status = 0; int ret; - for (block = 1; block < sftl->geo->subblocks; block++) { - const u8 *head = heads + block * SFTL_META; - bool complete_prefix = true, partial_footer = false, torn = false; - u64 base = sftl_sequence(head), next = base, last = 0; + ret = sftl_translate(sftl, address, &bus, &cau, &block, &page, chunk); + if (ret) + return ret; + for (tries = 0; tries < 2; tries++) { + if (sftl->load_deadline && time_after_eq(jiffies, sftl->load_deadline)) + return -ETIMEDOUT; + status = 0; + ret = sftl_scan_read(sftl, bus, cau, block, page, false, true, sftl->page, sftl->oob, &status); + if (status == 0x49) { + *state = SFTL_IOS_BLANK; + return 0; + } + if (ret == -EBADMSG) { + *state = SFTL_IOS_UECC; + return 0; + } + if (!ret) { + if (status == 0x40 || status == 0x42) { + *state = SFTL_IOS_META; + if (strict) + *strict = status == 0x40; + return 0; + } + *state = SFTL_IOS_UECC; + return 0; + } + if (ret == -ENOMEM || ret == -ERANGE || ret == -EINVAL) + break; + } + return ret; +} - if (head[0] != 1 && head[0] != 2) - continue; - pages = hweight16(sftl->lanes[block]) * sftl->geo->pages; - ret = sftl_read_open(sftl, block * stride + (pages - 1) * sftl->lpp, &chunk); - if (ret && ret != -EBADMSG) - goto out; - if (!ret && sftl->oob[0] == 0x1c) { - ret = sftl_footer(sftl, head, block, pages, journal, &floor); +/* + * An open block's runs, as s_btoc_read builds them from chunk metadata + * read in batches of 256 chunks: + * - an erased chunk is SFTL_TOK_BLANK; + * - a chunk whose type is not 1 or 2, or whose LBA is at or past the + * logical page count and below 0xffff0000, is SFTL_TOK_UECC + * ("BTOC stomping lba"). The subtype (meta[1]) and the user word + * (meta[12..15]) are not looked at; the user word only feeds the + * block's user sequence statistics (0x80dce85c); + * - a run goes on while the LBA (or the same token) and the sequence go + * on; blanks join regardless of sequence; every uECC token is a run of + * its own. Token runs carry the block's first sequence; + * - the block's very last chunk starts a run that is never emitted, and a + * batch with exactly 64 blank chunks ends the scan, dropping the run + * still open. + * Nothing stops at a bad chunk: what follows is listed too. + */ +static int sftl_ios_open(struct apple_sftl *sftl, struct sftl_ios_scan *ios, const u8 *head, + u32 block, u32 pages) +{ + u32 stride = sftl_stride(sftl), slots = pages * 4, index, blanks = 0; + u64 base = sftl_sequence(head); + struct sftl_ios_block *entry = &ios->blocks[ios->nr_blocks++]; + struct { u64 start; u32 key, address, count; } run = {}; + enum sftl_ios_page state = SFTL_IOS_UECC; + unsigned int chunk; + int ret; + + *entry = (struct sftl_ios_block) { + .base = base, .end = U64_MAX, .block = block, .first = ios->nr_runs, + }; + for (index = 0; index < slots; index++) { + const u8 *meta = sftl->oob + (index % 4) * SFTL_META; + u64 seq = sftl_sequence(meta); + u32 key; + bool split; + + if (!(index % 4)) { + if (!(index % (4 * 2 * SFTL_SCAN_DEPTH))) + sftl_prefetch_linear(sftl, block * stride + index, (slots - index) / 4); + ret = sftl_ios_read(sftl, block * stride + index, &state, &chunk, NULL); if (ret) - goto out; - continue; + return ret; + seq = sftl_sequence(meta); } - /* A full block of records needs a summary. A last page that is - * torn is found by the scan below. - */ - if (!ret && !sftl_erased(sftl->oob, sftl->osize)) { - for (chunk = 0; chunk < sftl->lpp; chunk++) - if (!sftl_journal_meta(sftl, sftl->oob + chunk * SFTL_META)) - break; - if (chunk == sftl->lpp) { - ret = -EBADMSG; - goto out; + if (state == SFTL_IOS_BLANK) { + key = SFTL_TOK_BLANK; + } else if (state == SFTL_IOS_UECC) { + key = SFTL_TOK_UECC; + } else { + key = get_unaligned_le32(meta + 8); + if ((key >= sftl->geo->lpages && key < 0xffff0000) || + ((u8)(meta[0] - 1) > 1 && key != SFTL_TOK_BLANK)) + key = SFTL_TOK_UECC; + } + blanks += key == SFTL_TOK_BLANK; + split = index == slots - 1 || !run.count || + (run.key < 0xffff0000 && run.key + run.count != key) || + (run.key >= 0xffff0000 && run.key != key) || + (((run.start + run.count) & SFTL_SEQUENCE) != seq && run.key != SFTL_TOK_BLANK) || + run.key == SFTL_TOK_UECC; + if (split) { + if (run.count) { + u32 rel = run.key >= SFTL_TOK_UECC ? 0 : (u32)run.start - (u32)base; + + ret = sftl_ios_add(ios, base + rel, run.key, run.address, run.count); + if (ret) + return ret; + entry->nr++; } + run.start = seq; + run.key = key; + run.address = block * stride + index; + run.count = 1; + } else { + run.count++; } - for (position = 0; position < pages; position++) { - bool erased, records; - - ret = sftl_read_open(sftl, block * stride + position * sftl->lpp, &chunk); - if (ret && ret != -EBADMSG) + if ((index + 1) % SFTL_IOS_BATCH == 0) { + if (blanks == SFTL_IOS_BATCH_BLANKS) + break; + blanks = 0; + } + } + return 0; +} + +static int sftl_ios_block_compare(const void *a, const void *b) +{ + const struct sftl_ios_block *left = a, *right = b; + + if (left->base != right->base) + return left->base < right->base ? -1 : 1; + return left->block < right->block ? -1 : left->block > right->block; +} + +static int sftl_apply_trim(struct apple_sftl *sftl, const u8 *payload, u32 address) +{ + u32 count, offset; + int ret; + + count = get_unaligned_le32(payload); + if (count > (SFTL_CHUNK - 4) / 8) + return -EBADMSG; + for (offset = 0; offset < count; offset++) { + u32 start = get_unaligned_le32(payload + 4 + offset * 8); + u32 length = get_unaligned_le32(payload + 8 + offset * 8); + + if (!length) + continue; + ret = sftl_replace(sftl, start, length, SFTL_UNMAPPED); + if (ret) + return ret; + } + return 0; +} + +/* A trim chunk: s_cxt_replay_streams reads only the run's first chunk and + * skips it when the read does not decode. + */ +static int sftl_ios_trim(struct apple_sftl *sftl, u32 address) +{ + enum sftl_ios_page state; + unsigned int chunk; + int ret; + + ret = sftl_ios_read(sftl, address, &state, &chunk, NULL); + if (ret) + return ret; + if (state != SFTL_IOS_META) { + return 0; + } + return sftl_apply_trim(sftl, sftl->page + chunk * SFTL_CHUNK, address); +} + +/* + * s_cxt_replay_streams (0x80dcf8c8). The blocks (the diff list, sorted by + * first sequence in s_cxt_scan_diff 0x80dd010c) feed four streams; the run + * with the lowest sequence among the streams' current runs goes next. + * A stream takes the next block in list order when its block runs out; + * blocks whose summary ends below the context's base sequence are passed + * over. Per run: + * - data below the highest data end so far ("weaveSeq non-monotonic"): + * in an open block it becomes a uECC token ("treating as media + * error"), in a closed block it is applied ("ignoring the fact"); the + * panic there needs PE_i_can_has_debugger; + * - a sequence at or past a closed block's end panics ("weaveSeq exceeds + * block maximum"); + * - at or below the context's base sequence nothing is applied; a data, + * pad or trim run there after data was applied panics; + * - data is mapped, trims unmap, pads do nothing; once replay stopped, + * nothing more is applied; + * - a uECC token types its block 6 and, when no block is left to enter a + * stream, stops replay ("uECC in stream ...; exiting early to be + * coherent!"); a blank token only types its block 6. + * There is no check that sequences are contiguous: gaps replay as they + * are. The next write sequence is the highest of the context's and the + * highest data end. + */ +static int sftl_ios_replay(struct apple_sftl *sftl, struct sftl_ios_scan *ios) +{ + struct { struct sftl_ios_block *blk; u32 cursor, left; } slot[SFTL_IOS_STREAMS] = {}; + u32 next = 0, filled = 0, applied = 0, mono = 0, i; + u64 max_end = 0; + bool stopped = false; + int ret; + + sort(ios->blocks, ios->nr_blocks, sizeof(*ios->blocks), sftl_ios_block_compare, NULL); + while (filled < min(ios->nr_blocks, SFTL_IOS_STREAMS) && next < ios->nr_blocks) { + struct sftl_ios_block *blk = &ios->blocks[next++]; + + if (blk->end < ios->threshold) + continue; + slot[filled].blk = blk; + slot[filled].cursor = blk->first; + slot[filled++].left = blk->nr; + } + for (;;) { + const struct sftl_ios_run *run; + struct sftl_ios_block *blk; + u64 best = U64_MAX; + int pick = -1; + u32 key; + + for (i = 0; i < SFTL_IOS_STREAMS; i++) + if (slot[i].left && ios->runs[slot[i].cursor].seq < best) { + best = ios->runs[slot[i].cursor].seq; + pick = i; + } + if (pick < 0) + break; + run = &ios->runs[slot[pick].cursor]; + blk = slot[pick].blk; + key = run->key; + if (key < 0xffff0000 && run->seq < max_end) { + mono++; + if (!blk->closed) + key = SFTL_TOK_UECC; + } + if (run->seq >= blk->end) { + ret = -EBADMSG; + return ret; + } else if (run->seq <= ios->threshold) { + if (key != SFTL_TOK_UECC && key != SFTL_TOK_BLANK && applied) { + ret = -EBADMSG; + return ret; + } + } else if (key < 0xffff0000) { + if (!stopped) { + ret = sftl_replace(sftl, key, run->count, run->address); + if (ret) + return ret; + applied++; + } + } else if (key == SFTL_TOK_UECC) { + if (!test_bit(blk->block, sftl->torn)) { + __set_bit(blk->block, sftl->torn); + sftl->nr_torn++; + } + if (!stopped && next >= ios->nr_blocks) { + stopped = true; + } + } else if (key == SFTL_TRIM) { + if (!stopped) { + ret = sftl_ios_trim(sftl, run->address); + if (ret) + return ret; + } + } + if (key < 0xffff0000) + max_end = max(max_end, run->seq + run->count); + slot[pick].cursor++; + if (--slot[pick].left) + continue; + if (blk->runtime_data && !stopped) { + u32 block = blk->block; + u8 role = sftl->roles[block]; + + /* The BTOC closed a block that the older table may still + * describe as free. Every data run was applied above. + */ + if (role <= SFTL_OPEN_DATA || role == SFTL_DIRTY_FREE) { + __set_bit(block, sftl->pool->runtime_data); + sftl_set_role(sftl, block, SFTL_CLOSED_DATA); + sftl->block_flags[block] = blk->flags; + } + } + if (next >= ios->nr_blocks) + continue; + while (next < ios->nr_blocks && ios->blocks[next].end < ios->threshold) + next++; + if (next < ios->nr_blocks) { + slot[pick].blk = &ios->blocks[next]; + slot[pick].cursor = ios->blocks[next].first; + slot[pick].left = ios->blocks[next++].nr; + } + } + sftl->nr_equal = mono; + return 0; +} + +/* 0x80dd65e4: remove every still-mapped block from the scanned type-3/6 + * set after replay of both data and trims, including cross-superblock runs. + */ +static void sftl_retire_boot_data(struct apple_sftl *sftl) +{ + u32 block; + + for_each_set_bit(block, sftl->pool->boot_retired, sftl_data_limit(sftl)) { + u8 role = sftl->roles[block]; + + if (sftl->pool->valid[block] || sftl->tolerated || test_bit(block, sftl->reserved) || + test_bit(block, sftl->vfl_reserved) || role == 5 || + role == SFTL_CONTEXT || role == 8 || role > SFTL_DIRTY_FREE) { + __clear_bit(block, sftl->pool->boot_retired); + continue; + } + sftl_set_role(sftl, block, SFTL_DIRTY_FREE); + /* A verified old BTOC supplies the effective flags during certification. */ + sftl->block_flags[block] = 0; + } +} + +static int sftl_ios_scan_block(struct apple_sftl *sftl, struct sftl_ios_scan *ios, + const u8 *head, u32 block, u64 *floor) +{ + u32 pages, stride = sftl_stride(sftl); + bool unread = test_bit(block, sftl->head_unread), tail_checked = false; + enum sftl_ios_page state; + unsigned int chunk; + u8 summary[SFTL_META]; + int ret; + + ios->block_high = 0; + if (!sftl->lanes[block] || (!unread && head[0] != 1 && head[0] != 2)) + return 0; + pages = hweight16(sftl->lanes[block]) * sftl->geo->pages; + /* s_cxt_scan_diff: a good last chunk of type 0x1c closes the block. */ + ret = sftl_ios_read(sftl, block * stride + (pages - 1) * 4, &state, &chunk, &tail_checked); + if (ret) + return ret; + if (state == SFTL_IOS_META && sftl->oob[3 * SFTL_META] == 0x1c && + get_unaligned_le32(sftl->oob + 3 * SFTL_META + 8) < 0xfffffffe) { + if (unread) { + memcpy(summary, sftl->oob, sizeof(summary)); + head = summary; + } + ret = sftl_footer(sftl, head, block, pages, NULL, floor, ios, tail_checked); + if (ret) + return ret; + if (sftl->pool) { + sftl->pool->media_high[block] = ios->block_high; + __set_bit(block, sftl->pool->boot_retired); + } + return 0; + } + /* A first page that did not read: type 2 or 9, not replayed. */ + if (unread) + return 0; + ret = sftl_ios_open(sftl, ios, head, block, pages); + if (ret) + return ret; + /* An unclosed saved stream keeps its owner. The other open-scan + * entries are type 6 and will never be appended to. + */ + if (sftl->pool) { + sftl->pool->media_high[block] = ios->block_high; + sftl->pool->media_kind[block] = SFTL_MEDIA_OPEN; + if (sftl->roles[block] != SFTL_OPEN_DATA) + __set_bit(block, sftl->pool->boot_retired); + } + return 0; +} + +/* The journal on profiles that replay as 12H321 does (ios_replay). */ +static int sftl_journal_ios(struct apple_sftl *sftl, const u8 *heads) +{ + struct sftl_ios_scan ios = {}; + u64 floor = sftl->checkpoint_sequence; + u32 block, next = 1; + int ret; + + ios.threshold = sftl->context.count ? + sftl->context.items[0].stamp & SFTL_SEQUENCE : sftl->checkpoint_sequence; + ios.blocks = kvzalloc(array_size(sftl->geo->subblocks, sizeof(*ios.blocks)), GFP_KERNEL); + if (!ios.blocks) + return -ENOMEM; + for (block = 1; block < sftl->geo->subblocks; block++) { + if (block >= next && sftl_can_prefetch(sftl)) + next = sftl_prefetch_blocks(sftl, block, heads); + ret = sftl_ios_scan_block(sftl, &ios, heads + block * SFTL_META, block, + &floor); + if (ret) + goto out; + } + ret = sftl_ios_replay(sftl, &ios); + if (ret) + goto out; + if (sftl->pool) + sftl_retire_boot_data(sftl); + /* Every sequence on the medium stays used; iOS accepts the gaps. */ + sftl->journal_sequence = max(floor, ios.high); + sftl->sequence = sftl->journal_sequence; +out: + kvfree(ios.runs); + kvfree(ios.blocks); + return ret; +} + +static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_records *journal) +{ + u64 floor = sftl->checkpoint_sequence, expected = floor + 1; + u32 nr_context = journal->count; + u32 block, position, i, pages, stride = sftl_stride(sftl); + unsigned int chunk; + int ret; + + if (sftl->geo->ios_replay) + return sftl_journal_ios(sftl, heads); + + for (block = 1; block < sftl->geo->subblocks; block++) { + const u8 *head = heads + block * SFTL_META; + bool complete_prefix = true, partial_footer = false, torn = false; + u64 base = sftl_sequence(head), next = base, last = 0; + + if (head[0] != 1 && head[0] != 2) + continue; + pages = hweight16(sftl->lanes[block]) * sftl->geo->pages; + ret = sftl_read_open(sftl, block * stride + (pages - 1) * sftl->lpp, &chunk); + if (ret && ret != -EBADMSG) { + goto out; + } + if (!ret && sftl->oob[0] == 0x1c) { + ret = sftl_footer(sftl, head, block, pages, journal, &floor, NULL, true); + if (ret) + goto out; + continue; + } + /* A full block of records needs a summary. A last page that is + * torn is found by the scan below. + */ + if (!ret && !sftl_erased(sftl->oob, sftl->osize)) { + for (chunk = 0; chunk < sftl->lpp; chunk++) + if (!sftl_journal_meta(sftl, sftl->oob + chunk * SFTL_META)) + break; + if (chunk == sftl->lpp) { + ret = -EBADMSG; + goto out; + } + } + for (position = 0; position < pages; position++) { + bool erased, records; + + ret = sftl_read_open(sftl, block * stride + position * sftl->lpp, &chunk); + if (ret && ret != -EBADMSG) goto out; erased = !ret && sftl_erased(sftl->oob, sftl->osize); if (erased && !sftl_erased(sftl->page, sftl->psize)) @@ -1852,16 +2991,21 @@ static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_re goto out; } if (ret) { + ret = sftl_note_torn(sftl, block, last); - if (ret) + if (ret) { goto out; + } torn = true; complete_prefix = false; continue; } for (chunk = 0; records && chunk < sftl->lpp; chunk++) last = max(last, sftl_sequence(sftl->oob + chunk * SFTL_META)); - if (position < pages - SFTL_FOOTER_CHUNKS / sftl->lpp) { + if (erased && !partial_footer) + complete_prefix = false; + if (records && (sftl->geo->summary_sequences || + position < pages - SFTL_FOOTER_CHUNKS / sftl->lpp)) { for (chunk = 0; chunk < sftl->lpp; chunk++) { const u8 *meta = sftl->oob + chunk * SFTL_META; u64 sequence = sftl_sequence(meta); @@ -1915,11 +3059,19 @@ static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_re ret = -EBADMSG; if (sequence == expected + sftl->lpp && sftl_take_torn(sftl, expected - 1)) expected = sequence; + /* + * 12H321 on the iPhone 5 can repeat a sequence: the first boot + * after iOS had written for hours met two records with the same + * one. iOS replays block by block, so the record of the later + * block (sftl_order_equal) is applied last. Only on profiles that + * say so; the P105 profiles still refuse a repeat. + */ if (sftl->geo->equal_sequences && prev && - sequence == (prev->stamp & SFTL_SEQUENCE)) + sequence == (prev->stamp & SFTL_SEQUENCE)) { sftl->nr_equal++; - else if (sequence != expected++) + } else if (sequence != expected++) { goto out; + } /* Context and summary chunks, and padding, map nothing. */ if (sftl_kind(record) == 0x1f || sftl_kind(record) == 0x1c || record->key == SFTL_PAD) @@ -1939,12 +3091,14 @@ static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_re goto out; ret = -EBADMSG; if (sftl_stamp(sftl->oob + chunk * SFTL_META) != record->stamp || - get_unaligned_le32(sftl->oob + chunk * SFTL_META + 8) != record->key) + get_unaligned_le32(sftl->oob + chunk * SFTL_META + 8) != record->key) { goto out; + } payload = sftl->page + chunk * SFTL_CHUNK; count = get_unaligned_le32(payload); - if (count > (SFTL_CHUNK - 4) / 8) + if (count > (SFTL_CHUNK - 4) / 8) { goto out; + } for (offset = 0; offset < count; offset++) { u32 start = get_unaligned_le32(payload + 4 + offset * 8); u32 length = get_unaligned_le32(payload + 8 + offset * 8); @@ -1989,13 +3143,30 @@ static void sftl_mark_mapped(struct apple_sftl *sftl, unsigned long *blocks) } } -int apple_sftl_load(struct apple_ppn *provider, struct apple_sftl **out) +static void sftl_scan_reuse(struct apple_sftl *sftl); + +/* Revisit every possible root, changed or unread head, and block whose + * exclusive journal end could reach the selected generation's base. Open + * blocks have an unbounded end in the iOS four-stream merge. + */ +static bool sftl_prune_needs_head(const struct apple_sftl *prior, u32 block) +{ + return prior->pool->media_kind[block] == SFTL_MEDIA_OPEN || + test_bit(block, prior->reserved) || test_bit(block, prior->head_unread) || + test_bit(block, prior->pool->media_changed) || + prior->pool->media_high[block] + 1 >= + (prior->context.items[0].stamp & SFTL_SEQUENCE); +} + +static int sftl_load(struct apple_ppn *provider, struct apple_sftl **out, unsigned long deadline, + const struct apple_sftl *prior, bool defer_reclaim, u8 **prune_heads) { struct apple_sftl *sftl; const struct sftl_geometry *geo = NULL; struct sftl_records journal = {}; + ktime_t start = ktime_get(), vfl, heads_done, context, replay, end; u8 *heads; - u32 block; + u32 block, next = 1; unsigned int chunk; int ret; @@ -2018,6 +3189,7 @@ int apple_sftl_load(struct apple_ppn *provider, struct apple_sftl **out) sftl = kzalloc(sizeof(*sftl), GFP_KERNEL); if (!sftl) return -ENOMEM; + sftl->load_deadline = deadline; sftl->ppn = provider; sftl->geo = geo; sftl->lpp = geo->lpp; @@ -2027,8 +3199,10 @@ int apple_sftl_load(struct apple_ppn *provider, struct apple_sftl **out) sftl->append_block = U32_MAX; sftl->next_candidate = 1; sftl->spare = U32_MAX; + sftl->rcache_addr = U32_MAX; mutex_init(&sftl->lock); - sftl->page = kmalloc(APPLE_PPN_PAGE_SIZE, GFP_KERNEL); /* the largest page */ + init_waitqueue_head(&sftl->gc_wait); + sftl->page = kmalloc(APPLE_PPN_PAGE_SIZE, GFP_KERNEL); heads = kcalloc(geo->blocks, SFTL_META, GFP_KERNEL); if (!sftl->page || !heads) { ret = -ENOMEM; @@ -2036,17 +3210,36 @@ int apple_sftl_load(struct apple_ppn *provider, struct apple_sftl **out) } memset(heads, 0xff, geo->blocks * SFTL_META); ret = sftl_vfl(sftl); - if (ret) + if (ret) { goto failed; + } + /* For the pre-erase prune comparison the last complete load supplies + * sequence bounds. Re-read all possible roots, changed blocks and + * anything that could participate in replay. This temporary map is + * never adopted. A full reopen discovers all owners afresh. + */ + vfl = ktime_get(); for (block = 1; block < geo->subblocks; block++) { if (!sftl->lanes[block]) continue; + if (!prior && block >= next && sftl_can_prefetch(sftl)) + next = sftl_prefetch_blocks(sftl, block, NULL); + if (prior && !sftl_prune_needs_head(prior, block)) + continue; ret = sftl_read_open(sftl, block * sftl_stride(sftl), &chunk); - if (ret && ret != -EBADMSG) + if (ret && ret != -EBADMSG) { goto failed; + } /* A torn first page is scanned as an open block with no records. */ if (ret || (sftl_erased(sftl->oob, sftl->osize) && !sftl_erased(sftl->page, sftl->psize))) { + /* 12H321 types it 2 (uECC) or 9 (blank status); only a + * summary in its last page brings it into replay. + */ + if (geo->ios_replay) { + __set_bit(block, sftl->head_unread); + continue; + } memset(heads + block * SFTL_META, 0, SFTL_META); heads[block * SFTL_META] = 1; continue; @@ -2055,20 +3248,82 @@ int apple_sftl_load(struct apple_ppn *provider, struct apple_sftl **out) __set_bit(block, sftl->candidates); } else if (sftl->oob[0] == 0x1f || sftl->oob[0] == 1 || sftl->oob[0] == 2) { memcpy(heads + block * SFTL_META, sftl->oob, SFTL_META); + } else if (geo->ios_replay) { + /* s_cxt_scan_diff logs the type and makes the block type 2. */ + __set_bit(block, sftl->head_unread); } else { ret = -EOPNOTSUPP; goto failed; } } + heads_done = ktime_get(); + if (reclaim && geo->n42_install && sftl_writer_enabled(sftl) && + !sftl->vfl_degraded && provider->ops->erase_block) { + sftl->pool = kvzalloc(sizeof(*sftl->pool), GFP_KERNEL); + if (!sftl->pool) { + ret = -ENOMEM; + goto failed; + } + } ret = sftl_context(sftl, heads, &journal); - if (ret) + if (ret) { goto failed; + } + if (sftl->pool && (!sftl->native_context || sftl->context_degraded)) { + kvfree(sftl->pool); + sftl->pool = NULL; + } + /* Pruning needs an independent selection and the complete list of + * exclusive fallback sites. The GC decoder checks the live map and + * journal separately before the first erase. + */ + if (prune_heads) { + kvfree(journal.items); + *prune_heads = heads; + sftl_free_windows(sftl); + *out = sftl; + return 0; + } + if (sftl->pool) { + struct rb_node *node; + + for (node = rb_first(&sftl->runs); node; node = rb_next(node)) { + struct sftl_run *run = rb_entry(node, struct sftl_run, node); + + sftl_count_range(sftl, run->provider, run->end - run->start, true); + } + } /* A map entry superseded by journal replay still belongs to the saved map. */ + context = ktime_get(); ret = sftl_journal(sftl, heads, &journal); - if (ret) + if (ret) { goto failed; + } + /* + * Keep writes fenced until the block layer validates the LwVM entries. + */ + if (sftl->geo->n42_install && sftl_writer_enabled(sftl)) { + sftl->write_fenced = true; + sftl->write_fence_start = 0; + sftl->write_fence_end = 0; + sftl->nr_write_fence_more = 0; + } + replay = ktime_get(); + if (defer_reclaim && sftl->pool) { + sftl->reuse_scan_pending = true; + } else if (!deadline && sftl->pool) { + mutex_lock(&sftl->lock); + sftl_scan_reuse(sftl); + mutex_unlock(&sftl->lock); + } kvfree(journal.items); kfree(heads); + sftl_free_windows(sftl); + end = ktime_get(); + pr_info("apple-sftl: load ms vfl=%lld heads=%lld context=%lld replay=%lld reclaim=%lld total=%lld\n", + ktime_ms_delta(vfl, start), ktime_ms_delta(heads_done, vfl), + ktime_ms_delta(context, heads_done), ktime_ms_delta(replay, context), + ktime_ms_delta(end, replay), ktime_ms_delta(end, start)); *out = sftl; return 0; failed: @@ -2077,34 +3332,98 @@ int apple_sftl_load(struct apple_ppn *provider, struct apple_sftl **out) apple_sftl_free(sftl); return ret; } + +int apple_sftl_load(struct apple_ppn *provider, struct apple_sftl **out) +{ + return sftl_load(provider, out, 0, NULL, false, NULL); +} EXPORT_SYMBOL_GPL(apple_sftl_load); +int apple_sftl_load_disk(struct apple_ppn *provider, struct apple_sftl **out) +{ + return sftl_load(provider, out, 0, NULL, true, NULL); +} + void apple_sftl_free(struct apple_sftl *sftl) { + unsigned int i; + if (!sftl) return; + if (sftl->gc_task) + kthread_stop(sftl->gc_task); + sftl_free_windows(sftl); sftl_clear_runs(sftl); kvfree(sftl->footer); + kfree(sftl->next_stripe); kvfree(sftl->stage); + kvfree(sftl->rcache); + for (i = 0; i < ARRAY_SIZE(sftl->read_data); i++) + kfree(sftl->read_data[i]); kvfree(sftl->move); kvfree(sftl->context.items); kvfree(sftl->closed_user_seq); + kvfree(sftl->pool); kfree(sftl->page); kfree(sftl); } EXPORT_SYMBOL_GPL(apple_sftl_free); +/* Caller holds sftl->lock. The page at @address into the read cache. */ +static int sftl_read_cached(struct apple_sftl *sftl, u32 address, unsigned int *chunk, + const u8 **page, const u8 **oob) +{ + unsigned int bus, cau, block, pg; + u32 base = round_down(address, sftl->lpp); + int ret; + + if (!READ_ONCE(read_cache)) { + ret = sftl_read_address(sftl, address, chunk); + *page = sftl->page; + *oob = sftl->oob; + return ret; + } + if (!sftl->rcache) { + sftl->rcache = kvmalloc(APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + if (!sftl->rcache) { + ret = sftl_read_address(sftl, address, chunk); + *page = sftl->page; + *oob = sftl->oob; + return ret; + } + sftl->rcache_addr = U32_MAX; + } + *page = sftl->rcache; + *oob = sftl->rcache_oob; + if (sftl->rcache_addr == base) { + *chunk = address % sftl->lpp; + read_cache_hits++; + return 0; + } + sftl->rcache_addr = U32_MAX; + ret = sftl_translate(sftl, address, &bus, &cau, &block, &pg, chunk); + if (!ret) + ret = sftl_read_page(sftl, bus, cau, block, pg, false, + sftl->rcache, sftl->rcache_oob); + if (ret) + return ret; + sftl->rcache_addr = base; + read_cache_misses++; + return 0; +} + int apple_sftl_read(struct apple_sftl *sftl, u32 logical_page, u8 *data) { struct sftl_run *run; unsigned int chunk; u32 address; - const u8 *meta; + const u8 *meta, *page, *oob; int ret = 0; if (!sftl || !data || logical_page >= sftl->geo->lpages) return -EINVAL; mutex_lock(&sftl->lock); + sftl->last_io = jiffies; if (sftl->failed) { ret = -EIO; goto out; @@ -2119,17 +3438,19 @@ int apple_sftl_read(struct apple_sftl *sftl, u32 logical_page, u8 *data) goto out; } address = run->provider + logical_page - run->start; - ret = sftl_read_address(sftl, address, &chunk); - if (ret) + ret = sftl_read_cached(sftl, address, &chunk, &page, &oob); + if (ret) { goto failed; - meta = sftl->oob + chunk * SFTL_META; + } + meta = oob + chunk * SFTL_META; if ((meta[0] != 1 && meta[0] != 2) || get_unaligned_le32(meta + 8) != logical_page) { ret = -EBADMSG; goto failed; } - memcpy(data, sftl->page + chunk * SFTL_CHUNK, SFTL_CHUNK); + memcpy(data, page + chunk * SFTL_CHUNK, SFTL_CHUNK); goto out; failed: + sftl->rcache_addr = U32_MAX; sftl->failed = true; out: mutex_unlock(&sftl->lock); @@ -2137,41 +3458,372 @@ int apple_sftl_read(struct apple_sftl *sftl, u32 logical_page, u8 *data) } EXPORT_SYMBOL_GPL(apple_sftl_read); -/* Caller holds sftl->lock. Every candidate is checked in full before use. */ -static int sftl_writer_prepare(struct apple_sftl *sftl) -{ - u32 block; +/* Adjacent logical destinations in a single mapped row. The physical key sorts by bus, then by + * block and page, alternating CAUs for the same page index. N42 has one CE per bus and no host plane field. + */ +struct sftl_read_ref { + u16 bus, cau, block, page; + unsigned int index; + u16 chunk, chunks; +}; - if (sftl->vfl_degraded || sftl->context_degraded || !sftl->geo->writer) - return -EROFS; - if (sftl->writer_prepared) - return 0; - if (sftl->journal_sequence != sftl->sequence) - return -EOPNOTSUPP; - if (!sftl->ppn->ops->program_page) - return -EROFS; - sftl->footer = kvzalloc(SFTL_FOOTER_BYTES, GFP_KERNEL); - sftl->stage = kvmalloc(APPLE_PPN_PAGE_SIZE, GFP_KERNEL); - sftl->move = kvmalloc(APPLE_PPN_PAGE_SIZE, GFP_KERNEL); - if (!sftl->footer || !sftl->stage || !sftl->move) - return -ENOMEM; - for (block = 0; block < sftl->geo->blocks; block++) - if (test_bit(block, sftl->reserved) || test_bit(block, sftl->vfl_reserved) || - block >= sftl->geo->subblocks) - __set_bit(block, sftl->used); - __set_bit(0, sftl->used); - sftl_mark_mapped(sftl, sftl->used); - /* Move live data out of torn blocks before the first new write. */ - for_each_set_bit(block, sftl->torn, sftl->geo->blocks) { - __set_bit(block, sftl->used); - __set_bit(block, sftl->abandoned); - sftl->evacuate = true; - } - sftl->writer_prepared = true; - return 0; +static int sftl_cmp_read_ref(const void *a, const void *b) +{ + const struct sftl_read_ref *x = a, *y = b; + + if (x->bus != y->bus) + return (int)x->bus - y->bus; + if (x->block != y->block) + return (int)x->block - y->block; + if (x->page != y->page) + return (int)x->page - y->page; + return (int)x->cau - y->cau; } -/* Caller holds the live map lock or owns an unpublished cold loader. */ +struct sftl_read_slot { + unsigned int first, end; + u8 oob[APPLE_PPN_OOB_SIZE]; +}; + +struct sftl_read_range { + unsigned int next, end; +}; + +/* Fill one bus's part of a command. All chunks referencing a row share + * its data and OOB, including chunks far apart in the original request. + */ +static int sftl_collect_rows(struct sftl_read_range *range, const struct sftl_read_ref *refs, + struct apple_ppn_read *pages, struct sftl_read_slot *slots, u8 **buffers, + unsigned int *nr_buffers, apple_sftl_read_target target, void *priv) +{ + unsigned int n = 0; + + while (range->next < range->end && n < APPLE_PPN_READ_MAX_PER_BUS) { + const struct sftl_read_ref *r = &refs[range->next]; + struct apple_ppn_read *p = &pages[n]; + struct sftl_read_slot *slot = &slots[n]; + + slot->first = range->next++; + while (range->next < range->end && !sftl_cmp_read_ref(r, &refs[range->next])) + range->next++; + slot->end = range->next; + p->bus = r->bus; + p->cau = r->cau; + p->block = r->block; + p->page = r->page; + p->oob = slot->oob; + memset(p->target, 0, sizeof(p->target)); + if (target) { + unsigned int seen = 0, k, c; + + for (k = slot->first; k < slot->end; k++) + for (c = 0; c < refs[k].chunks; c++) { + unsigned int piece = refs[k].chunk + c; + + p->target[piece] = seen & BIT(piece) ? NULL : + target(priv, refs[k].index + c); + seen |= BIT(piece); + } + } + p->data = NULL; + if (!p->target[0] || !p->target[1] || !p->target[2] || !p->target[3]) { + /* A direct row consumes no slot. Retain only as many + * buffers as one command has needed at the same time. + */ + u8 **buf = &buffers[(*nr_buffers)++]; + + if (!*buf) { + *buf = kmalloc(APPLE_PPN_PAGE_SIZE, GFP_NOIO); + if (!*buf) + return -ENOMEM; + } + p->data = *buf; + } + n++; + } + return n; +} + +static int sftl_scatter_rows(struct apple_sftl *sftl, const struct sftl_read_ref *refs, + const struct apple_ppn_read *pages, const struct sftl_read_slot *slots, + unsigned int n, const u32 *logical, apple_sftl_copy_chunk copy, + void *priv) +{ + unsigned int i, k; + + for (i = 0; i < n; i++) { + const struct apple_ppn_read *p = &pages[i]; + + /* 42 and 44 still carry valid data. A clean or uECC result + * for a mapped user page cannot satisfy this request. + */ + if (p->ret || (p->status != 0x40 && p->status != 0x42 && p->status != 0x44)) + return p->ret ?: -EBADMSG; + for (k = slots[i].first; k < slots[i].end; k++) { + const struct sftl_read_ref *r = &refs[k]; + unsigned int c; + + for (c = 0; c < r->chunks; c++) { + unsigned int chunk = r->chunk + c, index = r->index + c; + const u8 *meta = p->oob + chunk * SFTL_META; + + if ((meta[0] != 1 && meta[0] != 2) || + get_unaligned_le32(meta + 8) != logical[index]) + return -EBADMSG; + if (!p->target[chunk]) + copy(priv, index, p->data + chunk * SFTL_CHUNK); + } + } + } + return 0; +} + +struct sftl_completed_read { + struct apple_sftl *sftl; + struct sftl_read_ref *refs; + struct apple_ppn_read *pages; + struct sftl_read_slot *slots; + const u32 *logical; + apple_sftl_copy_chunk copy; + void *priv; + unsigned int n; + int ret; +}; + +static void sftl_scatter_completed(void *priv) +{ + struct sftl_completed_read *done = priv; + + if (!done->n) + return; + done->ret = sftl_scatter_rows(done->sftl, done->refs, done->pages, done->slots, + done->n, done->logical, done->copy, done->priv); + done->n = 0; +} + +int apple_sftl_read_targets(struct apple_sftl *sftl, const u32 *logical, unsigned int count, + apple_sftl_copy_chunk copy, apple_sftl_read_target target, void *priv) +{ + struct sftl_completed_read done = { .sftl = sftl, .logical = logical, .copy = copy, .priv = priv }; + unsigned int banks, bank = 0; + struct sftl_read_range bus[2] = {}; + struct apple_ppn_read *pages = NULL; + struct sftl_read_slot *slots = NULL; + struct sftl_read_ref *refs; + struct sftl_run *run = NULL; + unsigned int i, used = 0, cap = 0; + int ret = 0; + + if (!sftl || !logical || !count || !copy) + return -EINVAL; + if (count == 1 || !sftl->ppn->ops->read_pages) + return -EOPNOTSUPP; + refs = kvmalloc_array(count, sizeof(*refs), GFP_NOIO); + if (!refs) + return -ENOMEM; + mutex_lock(&sftl->lock); + sftl->last_io = jiffies; + if (sftl->failed) { + ret = -EIO; + goto out; + } + for (i = 0; i < count; ) { + unsigned int b, cau, block, page, chunk, chunks = 1; + + if (logical[i] >= sftl->geo->lpages) { + ret = -EINVAL; + goto out; + } + if (!run || logical[i] < run->start || logical[i] >= run->end) + run = sftl_find(sftl, logical[i]); + if (!run) { + ret = -EBADMSG; + goto out; + } + if (run->provider == SFTL_UNMAPPED) { + copy(priv, i++, NULL); + continue; + } + ret = sftl_translate(sftl, run->provider + logical[i] - run->start, + &b, &cau, &block, &page, &chunk); + if (ret) + goto out; + /* A run maps linearly. Translate and sort the normal four + * consecutive chunks once, preserving fragmented destinations. + */ + while (chunks < 4 - chunk && chunks < count - i && + logical[i + chunks] == logical[i] + chunks && + logical[i + chunks] < run->end && logical[i + chunks] < sftl->geo->lpages) + chunks++; + refs[used++] = (struct sftl_read_ref) { + .bus = b, .cau = cau, .block = block, .page = page, + .index = i, .chunk = chunk, .chunks = chunks, + }; + bus[b].end++; + i += chunks; + } + if (!used) + goto out; + sort(refs, used, sizeof(*refs), sftl_cmp_read_ref, NULL); + if (!sftl_cmp_read_ref(&refs[0], &refs[used - 1])) { + ret = -EOPNOTSUPP; /* Let the caller use the K7 cache. */ + goto out; + } + bus[1].next = bus[0].end; + bus[1].end = used; + cap = min(used, 2U * APPLE_PPN_READ_MAX_PER_BUS); + banks = sftl->ppn->ops->read_pages_overlap && + max(bus[0].end, bus[1].end - bus[1].next) > APPLE_PPN_READ_MAX_PER_BUS ? 2 : 1; + if (!sftl->ppn->ops->read_pages_overlap) + target = NULL; + done.refs = refs; + pages = kvcalloc(cap * banks, sizeof(*pages), GFP_NOIO); + slots = kvmalloc_array(cap * banks, sizeof(*slots), GFP_NOIO); + if (!pages || !slots) { + ret = -ENOMEM; + goto out; + } + while (bus[0].next < bus[0].end || bus[1].next < bus[1].end) { + unsigned int off = bank * cap; + u8 **buffers = &sftl->read_data[bank * 2 * APPLE_PPN_READ_MAX_PER_BUS]; + unsigned int nr_buffers = 0; + int n0, n1; + + n0 = sftl_collect_rows(&bus[0], refs, pages + off, slots + off, + buffers, &nr_buffers, target, priv); + if (n0 < 0) { + ret = n0; + break; + } + n1 = sftl_collect_rows(&bus[1], refs, pages + off + n0, slots + off + n0, + buffers, &nr_buffers, target, priv); + if (n1 < 0) { + ret = n1; + break; + } + if (sftl->ppn->ops->read_pages_overlap) + ret = sftl->ppn->ops->read_pages_overlap(sftl->ppn->priv, pages + off, n0 + n1, + done.n ? sftl_scatter_completed : NULL, &done); + else + ret = apple_sftl_provider_read_pages(sftl->ppn, pages + off, n0 + n1); + sftl_scatter_completed(&done); /* early provider failure can skip the callback */ + if (ret || done.ret) + break; + done.pages = pages + off; + done.slots = slots + off; + done.n = n0 + n1; + if (banks == 1) { + sftl_scatter_completed(&done); + if (done.ret) + break; + } else { + bank ^= 1; + } + } + sftl_scatter_completed(&done); + ret = done.ret ?: ret; +out: + mutex_unlock(&sftl->lock); + kvfree(slots); + kvfree(pages); + kvfree(refs); + return ret; +} +int apple_sftl_read_multi(struct apple_sftl *sftl, const u32 *logical, unsigned int count, + apple_sftl_copy_chunk copy, void *priv) +{ + return apple_sftl_read_targets(sftl, logical, count, copy, NULL, priv); +} +EXPORT_SYMBOL_GPL(apple_sftl_read_multi); + +/* Caller holds sftl->lock. Every candidate is checked in full before use. */ +static int sftl_hold_context(struct apple_sftl *sftl, bool certify); + +static void sftl_gc_wake(struct apple_sftl *sftl) +{ + atomic_set(&sftl->gc_wake, 1); + wake_up(&sftl->gc_wait); +} + +/* Leave cold fallback generations pinned until a writer needs capacity. */ +static void sftl_request_prune(struct apple_sftl *sftl) +{ + if (sftl->gc_task && sftl->pool->nr_fallback_sites && !sftl->prune_requested) { + sftl->prune_requested = true; + sftl_gc_wake(sftl); + } +} + +static int sftl_prune_fallbacks(struct apple_sftl *sftl); + +static bool sftl_prune_ready(struct apple_sftl *sftl) +{ + return sftl->prune_requested && sftl->append_block == U32_MAX && + !sftl->pool->gc_count && sftl->pool->nr_fallback_sites; +} + +/* The host owns both I/O locks. Service pressure here before failing its + * write. A verified reopen replaces the pool, including the context site. + */ +static int sftl_prune_for_write(struct apple_sftl *sftl) +{ + int ret; + + sftl->prune_requested = false; + ret = sftl_prune_fallbacks(sftl); + return ret ?: sftl_hold_context(sftl, true); +} + +static int sftl_writer_prepare(struct apple_sftl *sftl, bool host_write) +{ + u32 block; + int ret; + + if (sftl->vfl_degraded || sftl->context_degraded || !sftl_writer_enabled(sftl) || + !sftl->ppn->ops->program_page) + return -EROFS; + if (!sftl->writer_prepared && sftl->journal_sequence != sftl->sequence) + return -EOPNOTSUPP; + if (sftl->reuse_scan_pending) + sftl_scan_reuse(sftl); + if (sftl->pool) { + ret = sftl_hold_context(sftl, true); + if (ret == -ENOSPC) { + sftl_request_prune(sftl); + /* Checkpoint preparation already holds sftl_save_lock. */ + if (host_write && sftl_prune_ready(sftl)) + ret = sftl_prune_for_write(sftl); + } + if (ret) + return ret; + } + if (sftl->writer_prepared) + return 0; + sftl->footer = kvzalloc(SFTL_FOOTER_BYTES, GFP_KERNEL); + sftl->stage = kvmalloc(APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + sftl->move = kvmalloc(APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + if (!sftl->footer || !sftl->stage || !sftl->move) + return -ENOMEM; + for (block = 0; block < sftl->geo->blocks; block++) + if (test_bit(block, sftl->reserved) || test_bit(block, sftl->vfl_reserved) || + block >= sftl->geo->subblocks) + __set_bit(block, sftl->used); + __set_bit(0, sftl->used); + sftl_mark_mapped(sftl, sftl->used); + /* Move live data out of torn blocks before the first new write, or, + * where the native FTL leaves them in place, never write to them. + */ + for_each_set_bit(block, sftl->torn, sftl->geo->blocks) { + __set_bit(block, sftl->used); + __set_bit(block, sftl->abandoned); + if (!sftl->geo->torn_in_place) + sftl->evacuate = true; + } + sftl->writer_prepared = true; + return 0; +} + +/* Caller holds the live map lock or owns an unpublished cold loader. */ static void sftl_copy_map(struct apple_sftl *sftl, struct apple_sftl_snapshot *snapshot) { struct rb_node *node; @@ -2189,60 +3841,126 @@ static void sftl_copy_map(struct apple_sftl *sftl, struct apple_sftl_snapshot *s snapshot->sequence = sftl->sequence; snapshot->journal_sequence = sftl->journal_sequence; snapshot->checkpoint_sequence = sftl->checkpoint_sequence; + snapshot->subblocks = sftl->geo->subblocks; + snapshot->stride = sftl_stride(sftl); + snapshot->logical_pages = sftl->geo->lpages; +} + +/* Every counted slot has a unique physical position in this BTOC. Equal + * totals prove it accounts for every map reference, including the hidden tail. + */ +static u32 sftl_gc_mapped_run(struct apple_sftl *sftl, u32 key, u32 address, u32 length) +{ + u32 matched = 0; + + while (length) { + const struct sftl_run *run = sftl_find(sftl, key); + u32 n; + + if (!run) + break; + n = min(length, run->end - key); + if (run->provider != SFTL_UNMAPPED && run->provider + key - run->start == address) + matched += n; + key += n; + address += n; + length -= n; + } + return matched; } -/* Verify the native summary against every chunk it describes. A cold loader - * can skip old footers, but their claimed sequence ceiling alone cannot - * authorize erase. Unknown record kinds remain on media. +/* The N42 transactional collector checks the BTOC against the map, then + * reads the mapped chunks. Immediate erase still needs the old per-chunk + * and replay-cutoff proof. */ static int sftl_verify_closed(struct apple_sftl *sftl, struct apple_sftl_gc_block *victim, - unsigned long deadline, bool relocate) + unsigned long deadline, bool relocate, u8 *footer, + u8 *media_flags) { u32 first = victim->block * sftl_stride(sftl), capacity = sftl_slots(sftl, victim->lanes); u32 chunks, span, i, position = 0, previous_end = 0; unsigned int chunk; u8 trailer[SFTL_META]; + bool gc = relocate && media_flags && sftl->pool; + u64 cutoff = sftl->checkpoint_start; + u32 matched = 0; u64 base; int ret; ret = sftl_read_address(sftl, first + capacity - 4, &chunk); if (ret) - return ret; + return gc ? sftl_gc_read_error(victim->block, ret) : ret; memcpy(trailer, sftl->oob, SFTL_META); chunks = get_unaligned_le16(trailer + 12); + if (media_flags && chunks == 0xffff) + chunks = trailer[1] >> 1; span = get_unaligned_le32(trailer + 8); base = sftl_sequence(trailer); - if (trailer[0] != 0x1c || chunks < 4 || chunks > SFTL_FOOTER_CHUNKS || + if (trailer[0] != 0x1c || chunks < 4 || chunks > sftl->geo->footer_max || chunks % 4 || trailer[1] >> 1 != chunks || - (sftl->native_context && ((trailer[1] & 1) || sftl->block_flags[victim->block] != trailer[1])) || + (sftl->native_context && !media_flags && + ((trailer[1] & 1) || sftl->block_flags[victim->block] != trailer[1])) || get_unaligned_le16(trailer + 14) != 0xffff || !base || !span || - base + span - 1 >= sftl->checkpoint_start) + base + span > SFTL_SEQUENCE + 1) + return gc ? gc_refuse_footer_header(victim->block, -EOPNOTSUPP) : -EOPNOTSUPP; + if (!gc && base + span - 1 >= cutoff) + return -EOPNOTSUPP; + /* A replacement supersedes the selected map and its replay together. + * A retained older base may still replay even an unmapped trim. + */ + if (gc && ((!cutoff && base + span >= sftl->pool->oldest_base) || + base + span - 1 > sftl->sequence)) + return gc_refuse_replay(victim->block, -EOPNOTSUPP); + /* 12H321 skips only an exclusive end strictly below the replay base. */ + if (!gc && media_flags && base + span >= cutoff) return -EOPNOTSUPP; for (i = 0; i < chunks; i += 4) { ret = sftl_read_address(sftl, first + capacity - chunks + i, &chunk); if (ret) - return ret; + return gc ? sftl_gc_read_error(victim->block, ret) : ret; for (chunk = 0; chunk < 4; chunk++) if (memcmp(sftl->oob + chunk * SFTL_META, trailer, SFTL_META)) - return -EBADMSG; - memcpy(sftl->footer + i * SFTL_CHUNK, sftl->page, APPLE_PPN_PAGE_SIZE); + return gc ? gc_refuse_footer_replica(victim->block, -EBADMSG) : -EBADMSG; + memcpy(footer + i * SFTL_CHUNK, sftl->page, APPLE_PPN_PAGE_SIZE); } for (i = 0; i < chunks * SFTL_CHUNK; i += SFTL_META) { - const u8 *entry = sftl->footer + i; + const u8 *entry = footer + i; u32 relative = get_unaligned_le32(entry), high = get_unaligned_le32(entry + 4); u32 key = get_unaligned_le32(entry + 8), length = get_unaligned_le32(entry + 12); u32 j; if (!length) { if (position != capacity - chunks) - return -EBADMSG; + return gc ? gc_refuse_footer_runs(victim->block, -EBADMSG) : -EBADMSG; + if (gc && matched != sftl->pool->valid[victim->block]) + return gc_refuse_map(victim->block, -EBADMSG); + if (media_flags) { + if (!gc && span != previous_end && span - previous_end != chunks) + return -EBADMSG; + *media_flags = (chunks << 1) | (trailer[1] & 1); + } victim->last_sequence = base + span - 1; victim->footer_chunks = chunks; return 0; } if ((!position && relative) || relative < previous_end || relative >= span || length > span - relative || length > capacity - chunks - position) - return -EBADMSG; + return gc ? gc_refuse_footer_runs(victim->block, -EBADMSG) : -EBADMSG; + if (gc) { + /* 0x80dd2ed0 walks the BTOC, reading payload only for + * still-mapped data. Pads and trims have no mapped LBA; + * their replay effect survives until the verified save. + */ + if (key < sftl->geo->lpages && length <= sftl->geo->lpages - key) + matched += sftl_gc_mapped_run(sftl, key, first + position, length); + else if (key == SFTL_TOK_UECC) + return gc_refuse_quarantine(victim->block, -EBADMSG); + else if (key != SFTL_PAD && key != SFTL_TRIM && key != SFTL_TOK_BLANK) + return gc_refuse_record_kind(victim->block, -EOPNOTSUPP); + position += length; + previous_end = relative + length; + continue; + } if (key >= sftl->geo->lpages || length > sftl->geo->lpages - key) return -EOPNOTSUPP; for (j = 0; j < length; j++, position++) { @@ -2262,18 +3980,19 @@ static int sftl_verify_closed(struct apple_sftl *sftl, struct apple_sftl_gc_bloc (relocate && meta[0] == 1 && meta[1] == 1)) return -EOPNOTSUPP; if (meta[0] != 1 || meta[1] > 1 || - sftl_sequence(meta) != seq || !sftl_user_epoch_valid(sftl, meta, seq) || + sftl_sequence(meta) != seq || + !sftl_user_epoch_valid(sftl, meta, seq) || get_unaligned_le32(meta + 8) != key + j || high > seq >> 16) return -EBADMSG; - /* Native media also has runs whose summary differs from individual - * user epochs. Leave them intact until that encoding is understood. + /* A move preserves the individual verified OOB epoch. Other + * users of this proof require agreement with the summary. */ if (get_unaligned_le32(meta + 12) != high) return -EOPNOTSUPP; } previous_end = relative + length; } - return -EBADMSG; + return gc ? gc_refuse_footer_runs(victim->block, -EBADMSG) : -EBADMSG; } static int sftl_block_blank(struct apple_sftl *sftl, u32 block, unsigned long deadline, @@ -2314,21 +4033,49 @@ static bool sftl_retired_candidate(struct apple_sftl *sftl, u32 block) sftl_closed_candidate(sftl, block) && !test_bit(block, sftl->checkpoint_used); } -static int sftl_erase_verified(struct apple_sftl *sftl, u32 block, unsigned long deadline) +static bool sftl_status_only(const struct apple_sftl *sftl) +{ + return sftl->ppn->ops->status_only && sftl->ppn->ops->status_only(sftl->ppn->priv); +} + +static int sftl_erase_verified(struct apple_sftl *sftl, u32 block, u16 lanes, + unsigned long deadline) { unsigned int lane; bool blank; int ret; - for (lane = 0; lane < sftl->geo->lanes; lane++) { - if (!(sftl->lanes[block] & BIT(lane))) - continue; - if (time_after_eq(jiffies, deadline)) - return -ETIMEDOUT; - ret = sftl->ppn->ops->erase_block(sftl->ppn->priv, lane & 1, lane >> 1, block); + if (!block || block >= sftl_data_limit(sftl) || !lanes || + lanes != sftl->lanes[block] || + (sftl->native_context && test_bit(block, sftl->unknown_lane_flags))) + return -EPERM; + if (sftl->pool) { + __clear_bit(block, sftl->pool->gc_unsupported); + __set_bit(block, sftl->pool->media_changed); + } + if (sftl->ppn->ops->erase_lanes) { + sftl->rcache_addr = U32_MAX; + ret = sftl->ppn->ops->erase_lanes(sftl->ppn->priv, block, lanes, deadline); if (ret) return ret; + } else { + for (lane = 0; lane < sftl->geo->lanes; lane++) { + if (!(lanes & BIT(lane))) + continue; + if (time_after_eq(jiffies, deadline)) + return -ETIMEDOUT; + sftl->rcache_addr = U32_MAX; + ret = sftl->ppn->ops->erase_block(sftl->ppn->priv, lane & 1, lane >> 1, block); + if (ret) + return ret; + } } + /* A provider that judges erases by status alone (verify=0) makes the + * read-back iOS's PPNVFL does not do either: the status decides. The + * two-page probe in sftl_reuse_blank_dirty still runs before this. + */ + if (sftl_status_only(sftl)) + return 0; ret = sftl_block_blank(sftl, block, deadline, &blank); return ret ? ret : (blank ? 0 : -EBADMSG); } @@ -2346,8 +4093,8 @@ static int sftl_reclaim_retired(struct apple_sftl *sftl, u32 *claimed, (sftl->native_context && (!sftl->checkpoint_ops || !sftl->checkpoint_ops->account_retired))) return -ENOSPC; - /* The top physical blocks can contain native bootstrap members. */ - for (block = 1; block < sftl->geo->vfl_first; block++) { + /* The top physical blocks can contain native bootstrap or BFN members. */ + for (block = 1; block < sftl_data_limit(sftl); block++) { struct apple_sftl_gc_block victim = { .block = block, .lanes = sftl->lanes[block], .closed = true, }; @@ -2384,7 +4131,7 @@ static int sftl_reclaim_retired(struct apple_sftl *sftl, u32 *claimed, ret = -EBADMSG; break; } - ret = sftl_verify_closed(sftl, &victim, deadline, false); + ret = sftl_verify_closed(sftl, &victim, deadline, false, sftl->footer, NULL); if (!ret) ret = apple_sftl_gc_plan_retired(&active, &saved, &victim, cold->checkpoint_start); @@ -2398,7 +4145,7 @@ static int sftl_reclaim_retired(struct apple_sftl *sftl, u32 *claimed, if (ret) break; __set_bit(block, sftl->used); - ret = sftl_erase_verified(sftl, block, deadline); + ret = sftl_erase_verified(sftl, block, victim.lanes, deadline); if (!ret && sftl->native_context) ret = sftl->checkpoint_ops->account_retired(sftl->checkpoint_priv, block, sftl->wear[block], sftl->wear[block] + 1, APPLE_SFTL_FINISH_RETIRED); @@ -2408,7 +4155,7 @@ static int sftl_reclaim_retired(struct apple_sftl *sftl, u32 *claimed, break; } if (sftl->native_context) { - sftl->roles[block] = SFTL_CLEAN_FREE; + sftl_set_role(sftl, block, SFTL_CLEAN_FREE); sftl->wear[block]++; } *claimed = block; @@ -2422,7 +4169,7 @@ static int sftl_reclaim_retired(struct apple_sftl *sftl, u32 *claimed, static bool sftl_native_data_site(struct apple_sftl *sftl, u32 block) { - return !sftl->native_context || (block < sftl->geo->vfl_first && + return !sftl->native_context || (block < sftl_data_limit(sftl) && !test_bit(block, sftl->unknown_lane_flags)); } @@ -2474,97 +4221,453 @@ static int sftl_take_blank(struct apple_sftl *sftl, u32 *out, unsigned long dead return -ENOSPC; } -static void sftl_open_block(struct apple_sftl *sftl, u32 block) +/* True when any live mapping points into @block. */ +static bool sftl_block_mapped(struct apple_sftl *sftl, u32 block) { - sftl->append_block = block; - sftl->append_capacity = sftl_slots(sftl, sftl->lanes[block]) - SFTL_FOOTER_CHUNKS; - sftl->append_position = 0; - sftl->append_base = sftl->sequence + 1; - sftl->footer_runs = 0; - memset(sftl->footer, 0, SFTL_FOOTER_BYTES); -} + u32 first = block * sftl_stride(sftl), last = first + sftl_stride(sftl); + struct rb_node *node; -static int sftl_program_address(struct apple_sftl *sftl, u32 address, - const u8 *data, const u8 *oob) -{ - unsigned int bus, cau, block, page, chunk; - int ret; + for (node = rb_first(&sftl->runs); node; node = rb_next(node)) { + const struct sftl_run *run = rb_entry(node, struct sftl_run, node); - ret = sftl_translate(sftl, address, &bus, &cau, &block, &page, &chunk); - if (ret) - return ret; - if (chunk) - return -EINVAL; - return sftl->ppn->ops->program_page(sftl->ppn->priv, bus, cau, - block, page, data, oob); + if (run->provider != SFTL_UNMAPPED && run->provider < last && + run->provider + (run->end - run->start) > first) + return true; + } + return false; } -/* A short request repeats its final logical page to fill the program unit. */ -static void sftl_data_meta(u8 *meta, u64 sequence, u32 logical_page) +static bool sftl_reuse_permitted(struct apple_sftl *sftl, u32 block) { - put_unaligned_le64(sequence << 16 | 1, meta); - put_unaligned_le32(logical_page, meta + 8); - put_unaligned_le32(sequence >> 16, meta + 12); + return sftl->lanes[block] && sftl_native_data_site(sftl, block) && + sftl->wear[block] < 0xfffe && !test_bit(block, sftl->reserved) && + !test_bit(block, sftl->vfl_reserved) && !test_bit(block, sftl->checkpoint_used) && + !test_bit(block, sftl->fallback_live) && !test_bit(block, sftl->abandoned) && + !test_bit(block, sftl->torn) && + (!sftl->pool || !test_bit(block, sftl->pool->saved_live)); } -static void sftl_append_summary(struct apple_sftl *sftl, const u8 *meta) +static bool sftl_reuse_available(struct apple_sftl *sftl, u32 block) { - u32 relative = sftl_sequence(meta) - sftl->append_base; - u32 high = get_unaligned_le32(meta + 12), key = get_unaligned_le32(meta + 8); - u8 *entry; - - if (sftl->footer_runs) { - u32 length; - - entry = sftl->footer + (sftl->footer_runs - 1) * SFTL_META; - length = get_unaligned_le32(entry + 12); - if (key < 0xffff0000 && get_unaligned_le32(entry + 4) == high && - get_unaligned_le32(entry) + length == relative && - get_unaligned_le32(entry + 8) + length == key) { - put_unaligned_le32(length + 1, entry + 12); - return; - } - } - entry = sftl->footer + sftl->footer_runs++ * SFTL_META; - put_unaligned_le32(relative, entry); - put_unaligned_le32(high, entry + 4); - put_unaligned_le32(key, entry + 8); - put_unaligned_le32(1, entry + 12); + return (sftl->roles[block] == SFTL_DIRTY_FREE || + (sftl->pool && sftl->roles[block] == SFTL_ERASE_PENDING && + test_bit(block, sftl->pool->runtime_retired))) && + !test_bit(block, sftl->used) && sftl_reuse_permitted(sftl, block); } -static int sftl_snapshot_locked(struct apple_sftl *sftl, size_t max_bytes, - struct apple_sftl_snapshot **out); +/* 0x80dd670c. Between checkpoints the RAM map is authoritative. A closed, + * data-only block published here or fully replayed has no independent trim + * or context record to preserve. Its final debit proves the payload obsolete + * once all saved maps also exclude it. The next checkpoint records the new + * owner and wear; until claim the old payload stays in place. + */ +static void sftl_retire_runtime(struct apple_sftl *sftl, u32 block) +{ + struct sftl_reclaim_pool *pool = sftl->pool; -struct sftl_move { - struct apple_sftl *sftl; - unsigned long deadline; -}; + if (!pool->maps_complete || sftl->tolerated || !block || + block >= sftl_data_limit(sftl) || test_bit(block, pool->gc_pending) || !test_bit(block, pool->runtime_data) || + sftl->roles[block] != SFTL_CLOSED_DATA || pool->valid[block] || + block == sftl->append_block || block == sftl->spare || block == pool->context_site || + !sftl_reuse_permitted(sftl, block)) + return; + sftl_set_role(sftl, block, sftl->block_flags[block] > 1 ? SFTL_DIRTY_FREE : SFTL_ERASE_PENDING); + __clear_bit(block, sftl->used); + __set_bit(block, pool->runtime_retired); + pool->lanes[block] = sftl->lanes[block]; + __clear_bit(block, pool->unchecked); + if (!(++reclaim_runtime_retired % 16)) + pr_info("apple-sftl: reclaim_runtime_retired=%lu reclaim_runtime_claimed=%lu\n", + reclaim_runtime_retired, reclaim_runtime_claimed); +} -static int sftl_move_read(void *priv, u32 address, struct apple_sftl_gc_page *page) +static int sftl_blank_ends(struct apple_sftl *sftl, u32 block, bool *blank) { - struct sftl_move *move = priv; - struct apple_sftl *sftl = move->sftl; + u32 first = block * sftl_stride(sftl), slots = sftl_slots(sftl, sftl->lanes[block]); unsigned int chunk; int ret; - if (time_after_eq(jiffies, move->deadline)) - return -ETIMEDOUT; - ret = sftl_read_address(sftl, address, &chunk); - if (ret) + ret = sftl_read_address(sftl, first, &chunk); + *blank = !ret && sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE) && + sftl_erased(sftl->oob, APPLE_PPN_OOB_SIZE); + if (!*blank) return ret; - memcpy(page->data, sftl->page, sizeof(page->data)); - memcpy(page->oob, sftl->oob, sizeof(page->oob)); - return 0; + ret = sftl_read_address(sftl, first + slots - 4, &chunk); + *blank = !ret && sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE) && + sftl_erased(sftl->oob, APPLE_PPN_OOB_SIZE); + return ret; } -static int sftl_move_program(void *priv, u32 address, const struct apple_sftl_gc_page *page) +/* Bound all maps the snapshotter accepts, including native batch and page padding. */ +static u32 sftl_max_save_slots(const struct apple_sftl *sftl) { - struct sftl_move *move = priv; - struct apple_sftl *sftl = move->sftl; - unsigned int chunk; + u32 runs = SFTL_GC_MAP_BYTES / sizeof(struct apple_sftl_extent); + u32 records = DIV_ROUND_UP(runs, (SFTL_CHUNK - 8) / 8); + + return round_up(sftl->geo->opaque_records + + round_up(max(records, 32U), (u32)sftl->geo->map_batch), 4U); +} + +/* A lane proposal is never an erase certificate. The lock covers validation, + * the reservation and the eventual ownership recheck. An unsupported site + * drops out of this generation's candidate list without consuming a claim. + */ +static bool sftl_certify_reuse(struct apple_sftl *sftl, u32 block, unsigned long deadline) +{ + struct sftl_reclaim_pool *pool = sftl->pool; + struct apple_sftl_gc_block victim = { + .block = block, .lanes = pool->lanes[block], .closed = true, + }; + bool blank; + u8 flags, *footer; int ret; - if (time_after_eq(jiffies, move->deadline)) + if (!victim.lanes || victim.lanes != sftl->lanes[block] || + !sftl_reuse_available(sftl, block) || pool->valid[block] || + sftl_block_mapped(sftl, block)) + goto reject; + if (!test_bit(block, pool->unchecked)) + return true; + + ret = sftl_blank_ends(sftl, block, &blank); + if (!ret && blank && !test_bit(block, pool->boot_retired)) + goto certified; + if (!ret && !blank && sftl->checkpoint_start && !sftl->tolerated && + test_bit(block, sftl->old_closed)) { + footer = kvmalloc(sftl->geo->footer_max * SFTL_CHUNK, GFP_NOIO); + if (!footer) + goto reject; + ret = sftl_verify_closed(sftl, &victim, deadline, false, footer, &flags); + kvfree(footer); + if (!ret) { + sftl->block_flags[block] = flags; + goto certified; + } + } +reject: + pool->lanes[block] = 0; + __clear_bit(block, pool->unchecked); + return false; +certified: + __clear_bit(block, pool->unchecked); + return true; +} + +static int sftl_hold_context(struct apple_sftl *sftl, bool certify) +{ + struct sftl_reclaim_pool *pool = sftl->pool; + u32 block, best, best_slots, need = sftl_max_save_slots(sftl); + unsigned long deadline = jiffies + SFTL_CLAIM_TIMEOUT; + + for (;;) { + if (!pool->context_site) { + best = best_slots = 0; + for (block = 1; block < sftl_data_limit(sftl); block++) { + u32 slots = sftl_slots(sftl, pool->lanes[block]); + + if (slots < need || slots < best_slots || + (slots == best_slots && sftl->wear[block] >= sftl->wear[best]) || + !sftl_reuse_available(sftl, block) || pool->valid[block]) + continue; + best = block; + best_slots = slots; + } + if (!best) + return -ENOSPC; + pool->context_site = best; + } + block = pool->context_site; + if (!certify || !test_bit(block, pool->unchecked) || + sftl_certify_reuse(sftl, block, deadline)) + return 0; + pool->context_site = 0; + if (time_after_eq(jiffies, deadline)) + return -ETIMEDOUT; + } +} + +static void sftl_scan_reuse(struct apple_sftl *sftl) +{ + struct sftl_reclaim_pool *pool = sftl->pool; + u32 block, candidates = 0; + + sftl->reuse_scan_pending = false; + for (block = 1; block < sftl_data_limit(sftl); block++) { + if (!sftl_reuse_available(sftl, block) || pool->valid[block]) + continue; + if (!((test_bit(block, sftl->candidates) || test_bit(block, sftl->head_unread)) && + !test_bit(block, pool->boot_retired)) && + !(sftl->checkpoint_start && !sftl->tolerated && test_bit(block, sftl->old_closed))) + continue; + pool->lanes[block] = sftl->lanes[block]; + __set_bit(block, pool->unchecked); + candidates++; + } + sftl_hold_context(sftl, false); + pr_info("apple-sftl: reclaim candidates=%u provisional_context=%u\n", + candidates, pool->context_site); +} + +/* + * 12H321's boot scan types every superblock from its first and last pages + * (s_cxt_scan_diff, 0x80dd010c): a blank first page gives type 9, and a + * type-9 block is erased again before reuse (s_sb erase 0x80dd650c: + * type 1, wear + 1). On the iPhone 5 the dirty-free pool is such erased + * blocks, not blocks holding a closed footer, so it is the free space a + * writer that leaves the native clean pool alone can take. With reclaim + * enabled, the claim also certifies obsolete data against its BTOC, + * and sftl_retire_runtime certifies newly obsolete data between saves. + * The lowest wear among eligible sites wins, as in the native allocator. + */ +static int sftl_reuse_pick(struct apple_sftl *sftl, u32 min_slots, u32 *out) +{ + u32 block, best = U32_MAX; + + if (!sftl->native_context || sftl->vfl_degraded || sftl->context_degraded || + !sftl->ppn->ops->erase_block) + return -EOPNOTSUPP; + for (block = 1; block < sftl_data_limit(sftl); block++) { + if (!sftl_reuse_available(sftl, block) || sftl_slots(sftl, sftl->lanes[block]) < min_slots || + (sftl->pool && (!sftl->pool->lanes[block] || + block == sftl->pool->context_site || block == sftl->pool->gc_site))) + continue; + if (best != U32_MAX && sftl->wear[block] >= sftl->wear[best]) + continue; + if (sftl_block_mapped(sftl, block)) + continue; + best = block; + } + if (best == U32_MAX) + return -ENOSPC; + *out = best; + return 0; +} + +/* + * Claim a certified site (or probe its ends in blank-only mode), erase the + * selected lanes, and account wear exactly once after successful verification. + */ +static int sftl_reuse_blank_dirty(struct apple_sftl *sftl, u32 *claimed, + unsigned long deadline, enum sftl_claim_owner owner) +{ + struct sftl_reclaim_pool *pool = sftl->pool; + u32 block; + bool blank; + int ret; + + for (;;) { + if (pool && owner == SFTL_CLAIM_LANDING) { + block = *claimed; + if (!block || block >= sftl_data_limit(sftl) || + block == pool->context_site || block == pool->gc_site) + return -ESTALE; + } else if (pool && owner != SFTL_CLAIM_DATA) { + block = owner == SFTL_CLAIM_CONTEXT ? pool->context_site : pool->gc_site; + if (!block) + return -ENOSPC; + if (owner == SFTL_CLAIM_CONTEXT ? pool->context_claimed : pool->gc_claimed) { + if (!test_bit(block, sftl->used) || + !test_bit(block, sftl->linux_erased) || + sftl->roles[block] != SFTL_CONTEXT || + pool->lanes[block] != sftl->lanes[block] || + sftl_block_mapped(sftl, block)) + return -ESTALE; + *claimed = block; + return 0; + } + } else { + ret = sftl_reuse_pick(sftl, 0, &block); + if (ret) + return ret; + } + if (pool && (!sftl_reuse_available(sftl, block) || + pool->lanes[block] != sftl->lanes[block] || + sftl_block_mapped(sftl, block))) + return -ESTALE; + if (pool && !sftl_certify_reuse(sftl, block, deadline)) { + if (owner != SFTL_CLAIM_DATA || time_after_eq(jiffies, deadline)) + return -ESTALE; + continue; + } + __set_bit(block, sftl->used); + if (pool) + break; + ret = sftl_blank_ends(sftl, block, &blank); + if (ret) { + sftl->failed = true; + return ret; + } + if (!blank) { + continue; + } + break; + } + ret = sftl_erase_verified(sftl, block, pool ? pool->lanes[block] : sftl->lanes[block], + deadline); + if (ret) { + /* A partial or unverified erase leaves reuse unproved. */ + sftl->failed = true; + return ret; + } + sftl_set_role(sftl, block, SFTL_CLEAN_FREE); + sftl->wear[block]++; + __set_bit(block, sftl->linux_erased); + if (pool) { + pool->media_kind[block] = SFTL_MEDIA_NONE; + pool->media_high[block] = 0; + sftl->block_flags[block] = 0; + __clear_bit(block, sftl->old_closed); + __clear_bit(block, sftl->candidates); + if (sftl->closed_user_seq) + memset(&sftl->closed_user_seq[block], 0, sizeof(*sftl->closed_user_seq)); + if (owner == SFTL_CLAIM_CONTEXT || owner == SFTL_CLAIM_GC_CONTEXT) { + if (owner == SFTL_CLAIM_CONTEXT) + pool->context_claimed = true; + else + pool->gc_claimed = true; + sftl_set_role(sftl, block, SFTL_CONTEXT); + } else { + sftl_set_role(sftl, block, SFTL_OPEN_DATA); + } + __clear_bit(block, pool->runtime_data); + if (test_and_clear_bit(block, pool->runtime_retired)) + reclaim_runtime_claimed++; + else + pr_debug("apple-sftl: reclaimed block=%u wear=%u\n", block, sftl->wear[block]); + } + sftl->reused++; + *claimed = block; + return 0; +} + +static u32 sftl_footer_chunks_for(u32 runs) +{ + u32 chunks = round_up(DIV_ROUND_UP(runs + 1, SFTL_CHUNK / SFTL_META), 4); + + return clamp_t(u32, chunks, 4U, 16U); +} + +static void sftl_open_block(struct apple_sftl *sftl, u32 block) +{ + u32 reserve = sftl->geo->summary_sequences ? 4 : SFTL_FOOTER_CHUNKS; + + sftl->append_block = block; + sftl->append_capacity = sftl_slots(sftl, sftl->lanes[block]) - reserve; + sftl->append_position = 0; + sftl->append_base = sftl->sequence + 1; + sftl->append_has_trim = false; + sftl->footer_runs = 0; + memset(sftl->footer, 0, SFTL_FOOTER_BYTES); +} + +/* Where a program at @address goes, if the medium allows one there. */ +static int sftl_program_target(struct apple_sftl *sftl, u32 address, + struct apple_ppn_program *to) +{ + unsigned int bus, cau, block, page, chunk; + int ret; + + ret = sftl_translate(sftl, address, &bus, &cau, &block, &page, &chunk); + if (ret) + return ret; + if (chunk) + return -EINVAL; + if (!block || block >= sftl->geo->subblocks || + test_bit(block, sftl->vfl_reserved) || + !(sftl->lanes[block] & BIT(cau * 2 + bus)) || + (sftl->native_context && (block >= sftl->geo->vfl_first || + test_bit(block, sftl->unknown_lane_flags)))) + return -EPERM; + if (sftl->pool) + __set_bit(block, sftl->pool->media_changed); + if (sftl->rcache_addr == round_down(address, sftl->lpp)) + sftl->rcache_addr = U32_MAX; + *to = (struct apple_ppn_program) { + .bus = bus, .cau = cau, .block = block, .page = page, + }; + return 0; +} + +static int sftl_program_address(struct apple_sftl *sftl, u32 address, + const u8 *data, const u8 *oob) +{ + struct apple_ppn_program to; + int ret; + + ret = sftl_program_target(sftl, address, &to); + if (ret) + return ret; + return sftl->ppn->ops->program_page(sftl->ppn->priv, to.bus, to.cau, + to.block, to.page, data, oob); +} + +/* A short request repeats its final logical page to fill the program unit. */ +static void sftl_data_meta(u8 *meta, u64 sequence, u32 logical_page) +{ + put_unaligned_le64(sequence << 16 | 1, meta); + put_unaligned_le32(logical_page, meta + 8); + put_unaligned_le32(sequence >> 16, meta + 12); +} + +static void sftl_append_summary(struct apple_sftl *sftl, const u8 *meta) +{ + u32 relative = sftl_sequence(meta) - sftl->append_base; + u32 high = get_unaligned_le32(meta + 12), key = get_unaligned_le32(meta + 8); + u8 *entry; + + if (sftl->footer_runs) { + u32 length; + + entry = sftl->footer + (sftl->footer_runs - 1) * SFTL_META; + length = get_unaligned_le32(entry + 12); + if (key < 0xffff0000 && get_unaligned_le32(entry + 4) == high && + get_unaligned_le32(entry) + length == relative && + get_unaligned_le32(entry + 8) + length == key) { + put_unaligned_le32(length + 1, entry + 12); + return; + } + } + entry = sftl->footer + sftl->footer_runs++ * SFTL_META; + put_unaligned_le32(relative, entry); + put_unaligned_le32(high, entry + 4); + put_unaligned_le32(key, entry + 8); + put_unaligned_le32(1, entry + 12); +} + +static int sftl_snapshot_locked(struct apple_sftl *sftl, size_t max_bytes, + struct apple_sftl_snapshot **out); + +struct sftl_move { + struct apple_sftl *sftl; + unsigned long deadline; + u32 context_pages_programmed; +}; + +static int sftl_move_read(void *priv, u32 address, struct apple_sftl_gc_page *page) +{ + struct sftl_move *move = priv; + struct apple_sftl *sftl = move->sftl; + unsigned int chunk; + int ret; + + if (time_after_eq(jiffies, move->deadline)) + return -ETIMEDOUT; + ret = sftl_read_address(sftl, address, &chunk); + if (ret) + return ret; + memcpy(page->data, sftl->page, sizeof(page->data)); + memcpy(page->oob, sftl->oob, sizeof(page->oob)); + return 0; +} + +static int sftl_move_program(void *priv, u32 address, const struct apple_sftl_gc_page *page) +{ + struct sftl_move *move = priv; + struct apple_sftl *sftl = move->sftl; + unsigned int chunk; + int ret; + + if (time_after_eq(jiffies, move->deadline)) return -ETIMEDOUT; if (address != sftl->append_block * sftl_stride(sftl) + sftl->append_position || sftl->append_position + 4 > sftl->append_capacity) @@ -2614,6 +4717,7 @@ static void sftl_adopt_checkpoint(struct apple_sftl *sftl, struct apple_sftl *co for (block = 0; block < ARRAY_SIZE(sftl->candidates); block++) sftl->candidates[block] &= cold->candidates[block]; memcpy(sftl->fallback_occupied, cold->fallback_occupied, sizeof(sftl->fallback_occupied)); + memcpy(sftl->fallback_live, cold->fallback_live, sizeof(sftl->fallback_live)); memcpy(sftl->reserved, cold->reserved, sizeof(sftl->reserved)); memcpy(sftl->vfl_reserved, cold->vfl_reserved, sizeof(sftl->vfl_reserved)); memcpy(sftl->checkpoint_used, cold->checkpoint_used, sizeof(sftl->checkpoint_used)); @@ -2623,6 +4727,14 @@ static void sftl_adopt_checkpoint(struct apple_sftl *sftl, struct apple_sftl *co if (test_bit(block, sftl->reserved) || test_bit(block, sftl->vfl_reserved) || test_bit(block, sftl->checkpoint_used)) __set_bit(block, sftl->used); + if (sftl->pool && cold->pool) { + *sftl->pool = *cold->pool; + sftl->tolerated |= cold->tolerated; + sftl->pool->context_site = 0; + sftl_hold_context(sftl, false); + } + if (sftl->pool) + bitmap_zero(sftl->pool->gc_unsupported, SFTL_MAX_SUBBLOCKS); } /* The native base lists capacity allocated to this generation. Retirement @@ -2631,29 +4743,35 @@ static void sftl_adopt_checkpoint(struct apple_sftl *sftl, struct apple_sftl *co static bool sftl_owns_context_block(struct apple_sftl *sftl, u32 block) { return !sftl->vfl_degraded && !sftl->context_degraded && - block && block < sftl->geo->vfl_first && sftl->lanes[block] && + block && block < sftl_data_limit(sftl) && sftl->lanes[block] && test_bit(block, sftl->reserved) && !test_bit(block, sftl->vfl_reserved) && !test_bit(block, sftl->unknown_lane_flags) && !test_bit(block, sftl->checkpoint_used); } static int sftl_native_sites(struct apple_sftl *sftl, const struct apple_sftl_snapshot *saved, - const u32 fresh[2], u32 *retiring, unsigned long deadline) + const u32 *fresh, u32 *retiring, unsigned long deadline) { const u8 *base = saved->opaque[0].data; - u64 length; - u32 prior[2], slots, i, j; + u64 length, start = sftl->pool ? sftl_sequence(saved->opaque[0].meta) : + sftl->checkpoint_start; + u32 prior[2] = {}, nr = sftl->geo->context_names, slots, i, j; unsigned int chunk; bool blank; int ret; - if (get_unaligned_le32(base) != 2 || !sftl->checkpoint_start) + if (!nr || nr > 2 || get_unaligned_le32(base) != nr || !start || + (!sftl->checkpoint_start && (!sftl->pool || !sftl->pool->maps_complete))) return -EOPNOTSUPP; - prior[0] = get_unaligned_le32(base + 4); - prior[1] = get_unaligned_le32(base + 8); - if (!apple_sftl_account_context_pair(saved, prior) || - !sftl_owns_context_block(sftl, prior[0]) || !sftl_owns_context_block(sftl, prior[1]) || + for (i = 0; i < nr; i++) + prior[i] = get_unaligned_le32(base + 4 + i * 4); + if (!apple_sftl_account_context_sites(saved, prior, nr) || sftl->context.items[0].address != prior[0] * sftl_stride(sftl)) return -EOPNOTSUPP; + for (i = 0; i < nr; i++) + if (!sftl_owns_context_block(sftl, prior[i]) || + (sftl->pool && (test_bit(prior[i], sftl->fallback_live) || + sftl->wear[prior[i]] >= 0xfffe))) + return -EOPNOTSUPP; for (i = 0; i < saved->nr_runs; i++) { const struct apple_sftl_extent *r = &saved->runs[i]; u32 end; @@ -2661,12 +4779,12 @@ static int sftl_native_sites(struct apple_sftl *sftl, const struct apple_sftl_sn if (r->provider == SFTL_UNMAPPED) continue; end = (r->provider + r->length - 1) / sftl_stride(sftl); - for (j = 0; j < 2; j++) + for (j = 0; j < nr; j++) if ((r->provider / sftl_stride(sftl) <= fresh[j] && fresh[j] <= end) || (r->provider / sftl_stride(sftl) <= prior[j] && prior[j] <= end)) return -EBADMSG; } - length = sftl->checkpoint_sequence - sftl->checkpoint_start + 1; + length = sftl->checkpoint_sequence - start + 1; slots = sftl_slots(sftl, sftl->lanes[prior[0]]); if (!length || length % 4 || length > slots) return -EOPNOTSUPP; @@ -2686,17 +4804,19 @@ static int sftl_native_sites(struct apple_sftl *sftl, const struct apple_sftl_sn const u8 *meta = sftl->oob + j * SFTL_META; if (meta[0] != 0x1f || !meta[1] || meta[1] > 6 || - sftl_sequence(meta) != sftl->checkpoint_start + i + j) + sftl_sequence(meta) != start + i + j) return -EOPNOTSUPP; } } /* Require a single occupied old site and check all the fresh capacity - * before the first data copy. The unused old reservation is left alone. + * before the first data copy. Any unused old reservation is left alone. */ - ret = sftl_block_blank(sftl, prior[1], deadline, &blank); - if (ret || !blank) - return ret ? ret : -EOPNOTSUPP; - for (i = 0; i < 2; i++) { + if (nr == 2) { + ret = sftl_block_blank(sftl, prior[1], deadline, &blank); + if (ret || !blank) + return ret ? ret : -EOPNOTSUPP; + } + for (i = 0; i < nr; i++) { ret = sftl_block_blank(sftl, fresh[i], deadline, &blank); if (ret || !blank) return ret ? ret : -EOPNOTSUPP; @@ -2708,10 +4828,14 @@ static int sftl_native_sites(struct apple_sftl *sftl, const struct apple_sftl_sn static int sftl_context_program(void *priv, u32 address, const struct apple_sftl_gc_page *page) { struct sftl_move *move = priv; + int ret; if (time_after_eq(jiffies, move->deadline)) return -ETIMEDOUT; - return sftl_program_address(move->sftl, address, page->data, page->oob); + ret = sftl_program_address(move->sftl, address, page->data, page->oob); + if (!ret) + move->context_pages_programmed++; + return ret; } static int sftl_context_stats(void *priv, u32 id, u8 *data, size_t bytes) @@ -2764,7 +4888,7 @@ static int sftl_compact(struct apple_sftl *sftl, u32 landing, unsigned long dead u32 blocks[SFTL_MAX_CONTEXTS], nr = ARRAY_SIZE(blocks), block, slots, i, retiring = 0; int ret = -ENOSPC; - for (block = 1; block < sftl->geo->vfl_first; block++) { + for (block = 1; block < sftl_data_limit(sftl); block++) { struct apple_sftl_gc_block victim = { .block = block, .lanes = sftl->lanes[block], .closed = true, }; @@ -2777,7 +4901,7 @@ static int sftl_compact(struct apple_sftl *sftl, u32 landing, unsigned long dead if (ret) goto out; } - ret = sftl_verify_closed(sftl, &victim, deadline, true); + ret = sftl_verify_closed(sftl, &victim, deadline, true, sftl->footer, NULL); if (ret == -EOPNOTSUPP) { ret = -ENOSPC; continue; @@ -2796,16 +4920,17 @@ static int sftl_compact(struct apple_sftl *sftl, u32 landing, unsigned long dead slots = apple_sftl_gc_copy_chunks(gc); /* Keep at least a page for this request, and gain usable capacity. */ if (!slots || !apple_sftl_gc_has_sequence_room(gc, 4) || - slots + 4 > sftl_slots(sftl, destination.lanes) - SFTL_FOOTER_CHUNKS || - slots >= sftl_slots(sftl, victim.lanes) - SFTL_FOOTER_CHUNKS) { + slots + 4 > sftl_slots(sftl, destination.lanes) - sftl->geo->footer_max || + slots >= sftl_slots(sftl, victim.lanes) - sftl->geo->footer_max) { apple_sftl_gc_free(gc); gc = NULL; ret = -ENOSPC; continue; } if (sftl->checkpoint_ops->prepare_native) { - nr = 2; - memcpy(blocks, fresh, nr * sizeof(*fresh)); + nr = sftl->geo->context_names; + blocks[0] = fresh[0]; + blocks[1] = nr > 1 ? fresh[1] : 0; ret = sftl_native_sites(sftl, before, blocks, &retiring, deadline); if (!ret) ret = apple_sftl_gc_prepare_native(gc, sftl->checkpoint_ops->prepare_native, @@ -2873,28 +4998,28 @@ static int sftl_compact(struct apple_sftl *sftl, u32 landing, unsigned long dead goto failed; if (sftl->checkpoint_ops->prepare_native) { /* The new map has now been recovered with the fallback intact. - * Verify its physical location and both reservations before - * retiring the old context. Reload again before releasing data. + * Verify its physical location and reservations before retiring + * the old context. Reload again before releasing data. */ if (!cold->native_context || cold->roles[landing] != SFTL_OPEN_DATA || cold->roles[block] != SFTL_DIRTY_FREE || cold->context.items[0].address != blocks[0] * sftl_stride(sftl) || cold->roles[retiring] != SFTL_CONTEXT || !sftl_owns_context_block(cold, retiring) || !sftl_owns_context_block(cold, blocks[0]) || - !sftl_owns_context_block(cold, blocks[1])) { + (nr > 1 && !sftl_owns_context_block(cold, blocks[1]))) { ret = -EBADMSG; goto failed; } - ret = sftl_erase_verified(sftl, retiring, deadline); + ret = sftl_erase_verified(sftl, retiring, sftl->lanes[retiring], deadline); if (ret) goto failed; /* The persisted table precedes retirement. Reconcile only * the private runtime copy after the old erase succeeds. - * The unused tail of the new group needs no physical erase. + * Any unused tail of the new group needs no physical erase. */ ret = apple_sftl_account_release(readback, retiring, APPLE_SFTL_RELEASED_CONTEXT); - if (!ret) + if (!ret && nr > 1) ret = apple_sftl_account_release(readback, blocks[1], APPLE_SFTL_RELEASED_CONTEXT); if (ret) @@ -2910,14 +5035,15 @@ static int sftl_compact(struct apple_sftl *sftl, u32 landing, unsigned long dead ret = -EBADMSG; goto failed; } - ret = sftl_erase_verified(sftl, block, deadline); + ret = sftl_erase_verified(sftl, block, victim.lanes, deadline); if (ret) goto failed; if (sftl->native_context) { ret = apple_sftl_account_release(readback, block, APPLE_SFTL_ERASED_DONOR); if (!ret) ret = sftl->checkpoint_ops->finish_native(sftl->checkpoint_priv, - readback, retiring, blocks[1], block); + readback, retiring, + nr > 1 ? blocks[1] : 0, block); if (ret) goto failed; } @@ -2944,12 +5070,14 @@ static bool sftl_can_compact(struct apple_sftl *sftl) if (!sftl->checkpoint_ops || !sftl->ppn->ops->erase_block || (!sftl->checkpoint_ops->prepare_native && !sftl->checkpoint_ops->install)) return false; - for (block = 1; block < sftl->geo->vfl_first; block++) + for (block = 1; block < sftl_data_limit(sftl); block++) if (sftl_closed_candidate(sftl, block) && test_bit(block, sftl->checkpoint_used)) return true; return false; } +static int sftl_gc_claim(struct apple_sftl *sftl, unsigned long deadline); + static int sftl_claim_data_block(struct apple_sftl *sftl, bool compact, const u32 *fresh, unsigned long deadline) { @@ -2964,6 +5092,12 @@ static int sftl_claim_data_block(struct apple_sftl *sftl, bool compact, const u3 sftl->failed = true; return ret; } + } else if (sftl->pool) { + return sftl_gc_claim(sftl, deadline); + } else if (sftl->reuse_dirty) { + ret = sftl_reuse_blank_dirty(sftl, &block, deadline, SFTL_CLAIM_DATA); + if (ret) + return ret; } else { ret = sftl_take_blank(sftl, &block, deadline); if (ret == -ENOSPC && !sftl->failed) @@ -3012,9 +5146,19 @@ static int sftl_claim_block(struct apple_sftl *sftl) { unsigned long deadline = jiffies + SFTL_CLAIM_TIMEOUT; bool compact = sftl_can_compact(sftl); - u32 fresh[2], count = ARRAY_SIZE(fresh), i; + u32 fresh[2] = {}, nr = sftl->geo->context_names, count = nr, i; int ret; + /* The one-site writer manages its own landing and checkpoint capacity. */ + if (sftl->pool) { + ret = sftl_claim_data_block(sftl, false, NULL, deadline); + if (ret != -ENOSPC || !sftl_prune_ready(sftl)) + return ret; + ret = sftl_prune_for_write(sftl); + if (ret) + return ret; + return sftl_claim_data_block(sftl, false, NULL, deadline); + } if (!compact || !sftl->native_context) return sftl_claim_data_block(sftl, compact, NULL, deadline); /* A healthy compacting writer needs space for both user data and a @@ -3026,12 +5170,13 @@ static int sftl_claim_block(struct apple_sftl *sftl) return sftl_claim_data_block(sftl, false, NULL, deadline); if (ret) return ret; - if (count != ARRAY_SIZE(fresh) || fresh[0] == fresh[1]) + if (!nr || nr > ARRAY_SIZE(fresh) || count != nr || + (nr > 1 && fresh[0] == fresh[1])) return -EBADMSG; for (i = 0; i < count; i++) { u32 b = fresh[i]; - if (!b || b >= sftl->geo->vfl_first || !sftl->lanes[b] || + if (!b || b >= sftl_data_limit(sftl) || !sftl->lanes[b] || sftl->roles[b] != SFTL_CLEAN_FREE || !test_bit(b, sftl->candidates) || test_bit(b, sftl->used) || test_bit(b, sftl->checkpoint_used) || test_bit(b, sftl->reserved) || test_bit(b, sftl->vfl_reserved) || @@ -3076,27 +5221,68 @@ EXPORT_SYMBOL_GPL(apple_sftl_set_checkpoint_ops); static int sftl_give_up(struct apple_sftl *sftl, u32 address, const u8 *data, const u8 *oob, int err); +static bool sftl_block_full(const struct apple_sftl *sftl) +{ + if (!sftl->geo->summary_sequences) + return sftl->append_position == sftl->append_capacity; + return sftl->append_position + sftl_footer_chunks_for(sftl->footer_runs + 4) >= + sftl_slots(sftl, sftl->lanes[sftl->append_block]); +} + static int sftl_close_block(struct apple_sftl *sftl) { u64 span = sftl->sequence - sftl->append_base + 1; + u32 slots = sftl_slots(sftl, sftl->lanes[sftl->append_block]); + u16 footer_chunks = slots - sftl->append_position; + u32 block = sftl->append_block; u8 meta[SFTL_META]; unsigned int chunk, index; int ret; if (!span || span > U32_MAX) return -EOVERFLOW; - put_unaligned_le64(sftl->append_base << 16 | 0x401c, meta); + if (footer_chunks < 4 || footer_chunks > sftl->geo->footer_max || footer_chunks % 4) + return -EINVAL; + put_unaligned_le64(sftl->append_base << 16 | (u16)(footer_chunks << 1) << 8 | 0x1c, meta); put_unaligned_le32(span, meta + 8); - put_unaligned_le16(SFTL_FOOTER_CHUNKS, meta + 12); + put_unaligned_le16(footer_chunks, meta + 12); put_unaligned_le16(0xffff, meta + 14); for (chunk = 0; chunk < 4; chunk++) memcpy(sftl->stage_oob + chunk * SFTL_META, meta, SFTL_META); - for (index = 0; index < SFTL_FOOTER_CHUNKS / 4; index++) { + /* The last physical page publishes the BTOC at boot. Finish the + * prefix before allowing that page onto either bus. + */ + for (index = 0; index < footer_chunks / 4; index++) { u32 address = sftl->append_block * sftl_stride(sftl) + - sftl->append_capacity + index * 4; + sftl->append_position + index * 4; const u8 *data = sftl->footer + index * APPLE_PPN_PAGE_SIZE; - ret = sftl_program_address(sftl, address, data, sftl->stage_oob); + if (sftl->geo->n42_install && sftl->ppn->ops->program_pages) { + struct apple_ppn_program footer[4]; + unsigned int k, n = max_t(int, 1, footer_chunks / 4 - index - 1); + + if (n > ARRAY_SIZE(footer)) + return -EINVAL; + for (k = 0; k < n; k++) { + ret = sftl_program_target(sftl, address + 4 * k, &footer[k]); + if (ret) + return ret; + footer[k].data = data + k * APPLE_PPN_PAGE_SIZE; + footer[k].oob = sftl->stage_oob; + } + ret = sftl->ppn->ops->program_pages(sftl->ppn->priv, footer, n); + if (ret) { + for (k = 0; k < n && !footer[k].ret; k++) + ; + if (k < n) { + address += 4 * k; + data = footer[k].data; + } + } + index += n - 1; + } else { + ret = sftl_program_address(sftl, address, data, sftl->stage_oob); + } /* A summary consumes no sequence. A given-up block moves its data. */ if (ret) return sftl_give_up(sftl, address, data, sftl->stage_oob, ret) == SFTL_RETRY ? @@ -3106,6 +5292,22 @@ static int sftl_close_block(struct apple_sftl *sftl) if (ret) return ret; sftl->append_block = U32_MAX; + if (sftl->pool) { + if (sftl->prune_requested) + sftl_gc_wake(sftl); + sftl_set_role(sftl, block, SFTL_CLOSED_DATA); + sftl->block_flags[block] = meta[1]; + if (sftl->append_has_trim) { + /* Zero valid data pages cannot retire a replayable trim. + * GC can collect it through a verified replacement context. + */ + sftl->pool->media_kind[block] = SFTL_MEDIA_DATA_FOOTER; + __clear_bit(block, sftl->pool->runtime_data); + } else { + __set_bit(block, sftl->pool->runtime_data); + sftl_retire_runtime(sftl, block); + } + } return 0; } @@ -3150,6 +5352,8 @@ static int sftl_give_up(struct apple_sftl *sftl, u32 address, const u8 *data, dev_warn(sftl->ppn->dev, "program at %#x failed (%d): block %u given up\n", address, err, block); __set_bit(block, sftl->abandoned); + if (sftl->pool) + sftl_set_role(sftl, block, SFTL_ABANDONED_DATA); sftl->append_block = U32_MAX; sftl->evacuate = true; return SFTL_RETRY; @@ -3162,57 +5366,53 @@ static int sftl_give_up(struct apple_sftl *sftl, u32 address, const u8 *data, * the user epoch it was first written with; every other record carries the * epoch of its new sequence. */ -static void sftl_stamp_page(struct apple_sftl *sftl, u8 *oob, bool relocated) +static void sftl_stamp_page_at(struct apple_sftl *sftl, u8 *oob, bool relocated, bool gc, u64 base) { unsigned int chunk; for (chunk = 0; chunk < 4; chunk++) { u8 *meta = oob + chunk * SFTL_META; - u64 sequence = sftl->sequence + 1 + chunk; - bool keep = relocated && meta[0] == 1 && !meta[1] && + u64 sequence = base + 1 + chunk; + bool keep = relocated && meta[0] == 1 && (!meta[1] || (sftl->pool && meta[1] == 1)) && get_unaligned_le32(meta + 8) < sftl->geo->lpages; put_unaligned_le64(sequence << 16 | get_unaligned_le16(meta), meta); - if (!keep) + if (!gc && !keep) put_unaligned_le32(sequence >> 16, meta + 12); } } -/* - * Program one page at the append point and publish it. SFTL_RETRY means the - * block was given up and the page must be offered again after evacuation. +/* A page programmed at the append point (@address) goes into the map and + * the block's summary; the block closes when it is full. */ -static int sftl_append_once(struct apple_sftl *sftl, const u8 *page, u8 *oob, bool relocated) +static int sftl_publish_page(struct apple_sftl *sftl, u32 address, const u8 *oob, + const u8 *page) { unsigned int chunk; - u32 address; - int ret; + int ret = 0; - if (sftl->append_block == U32_MAX) { - ret = sftl_claim_block(sftl); - if (ret) - return ret; - } - if (sftl->sequence > SFTL_SEQUENCE - 4) - return -EOVERFLOW; - sftl_stamp_page(sftl, oob, relocated); - address = sftl->append_block * sftl_stride(sftl) + sftl->append_position; - ret = sftl_program_address(sftl, address, page, oob); - if (ret) - return sftl_give_up(sftl, address, page, oob, ret); - for (chunk = 0; chunk < 4; chunk++) { - ret = sftl_replace(sftl, get_unaligned_le32(oob + chunk * SFTL_META + 8), 1, - address + chunk); - if (ret) { - sftl->failed = true; - return ret; + if (get_unaligned_le32(oob + 8) == SFTL_TRIM) { + /* The writer follows the trim chunk with three pads. */ + sftl->append_has_trim = true; + ret = sftl_apply_trim(sftl, page, address); + } else { + for (chunk = 0; chunk < 4; chunk++) { + ret = sftl_replace(sftl, get_unaligned_le32(oob + chunk * SFTL_META + 8), + 1, address + chunk); + if (ret) + break; } - sftl_append_summary(sftl, oob + chunk * SFTL_META); } + if (ret) { + sftl->failed = true; + return ret; + } + for (chunk = 0; chunk < 4; chunk++) + sftl_append_summary(sftl, oob + chunk * SFTL_META); sftl->sequence += 4; sftl->journal_sequence = sftl->sequence; sftl->append_position += 4; - if (sftl->append_position == sftl->append_capacity) { + if (sftl_block_full(sftl)) { ret = sftl_close_block(sftl); if (ret) sftl->failed = true; @@ -3220,26 +5420,109 @@ static int sftl_append_once(struct apple_sftl *sftl, const u8 *page, u8 *oob, bo return ret; } -/* Logical pages the map still places in given-up blocks, in logical order. */ -static int sftl_collect_abandoned(struct apple_sftl *sftl, u32 **out, u32 *count) +static int sftl_check_move(struct apple_sftl *sftl, u32 address, const u8 *page, + const u8 *oob, u32 victim) { - u32 stride = sftl_stride(sftl), n = 0, pass, *keys = NULL; - struct rb_node *node; + unsigned int i, chunk; + int ret = 0; - for (pass = 0; pass < 2; pass++) { - for (node = rb_first(&sftl->runs); node; node = rb_next(node)) { - const struct sftl_run *run = rb_entry(node, struct sftl_run, node); - u32 first, last, block; + if (!sftl_status_only(sftl)) { + ret = sftl_read_address(sftl, address, &chunk); + if (ret || memcmp(page, sftl->page, APPLE_PPN_PAGE_SIZE) || + memcmp(oob, sftl->oob, APPLE_PPN_OOB_SIZE)) + goto failed; + } + /* verify=0 trusts program status for the destination. Both modes + * recheck the source mapping under the lock before publication. + */ + for (i = 0; i < 4; i++) { + u32 key = get_unaligned_le32(oob + i * SFTL_META + 8); + struct sftl_run *r = sftl_find(sftl, key); - if (run->provider == SFTL_UNMAPPED) - continue; - first = run->provider; - last = run->provider + run->end - run->start - 1; + if (!r || r->provider == SFTL_UNMAPPED || + (r->provider + key - r->start) / sftl_stride(sftl) != victim) + goto failed; + } + return 0; +failed: + sftl->failed = true; + return ret ?: -EBADMSG; +} + +/* + * Program one page at the append point and publish it. SFTL_RETRY means the + * block was given up and the page must be offered again after evacuation. + */ +static int sftl_append_once(struct apple_sftl *sftl, const u8 *page, u8 *oob, + bool relocated, u32 victim) +{ + u32 address; + int ret; + + if (sftl->append_block == U32_MAX) { + if (relocated && sftl->pool) { + u32 landing; + + /* Evacuation already owns move/move_oob. Do not start + * foreground GC inside that page's append. + */ + ret = sftl_reuse_blank_dirty(sftl, &landing, jiffies + SFTL_CLAIM_TIMEOUT, + SFTL_CLAIM_DATA); + if (!ret) + sftl_open_block(sftl, landing); + } else { + ret = sftl_claim_block(sftl); + } + if (ret) + return ret; + } + if (sftl->sequence > SFTL_SEQUENCE - 4) + return -EOVERFLOW; + sftl_stamp_page_at(sftl, oob, relocated, victim != 0, sftl->sequence); + address = sftl->append_block * sftl_stride(sftl) + sftl->append_position; + if (!relocated && sftl->geo->n42_install && sftl->ppn->ops->program_pages && + READ_ONCE(program_batch) > 1) { + struct apple_ppn_program row; + + ret = sftl_program_target(sftl, address, &row); + if (!ret) { + row.data = page; + row.oob = oob; + ret = sftl->ppn->ops->program_pages(sftl->ppn->priv, &row, 1); + } + } else { + ret = sftl_program_address(sftl, address, page, oob); + } + if (ret) + return sftl_give_up(sftl, address, page, oob, ret); + if (victim) { + ret = sftl_check_move(sftl, address, page, oob, victim); + if (ret) + return ret; + } + return sftl_publish_page(sftl, address, oob, page); +} + +/* Gather live LBAs of a single GC victim or all given-up blocks, in logical order. */ +static int sftl_collect_keys(struct apple_sftl *sftl, u32 victim, u32 **out, u32 *count) +{ + u32 stride = sftl_stride(sftl), n = 0, pass, *keys = NULL; + struct rb_node *node; + + for (pass = 0; pass < 2; pass++) { + for (node = rb_first(&sftl->runs); node; node = rb_next(node)) { + const struct sftl_run *run = rb_entry(node, struct sftl_run, node); + u32 first, last, block; + + if (run->provider == SFTL_UNMAPPED) + continue; + first = run->provider; + last = run->provider + run->end - run->start - 1; for (block = first / stride; block <= last / stride; block++) { u32 from = max(first, block * stride); u32 to = min(last, block * stride + stride - 1), a; - if (!test_bit(block, sftl->abandoned)) + if (victim ? block != victim : !test_bit(block, sftl->abandoned)) continue; for (a = from; a <= to; a++) { if (keys) @@ -3255,134 +5538,1942 @@ static int sftl_collect_abandoned(struct apple_sftl *sftl, u32 **out, u32 *count return -ENOMEM; n = 0; } - *out = keys; - *count = n; - return 0; + *out = keys; + *count = n; + return 0; +} + +/* Read up to four live pages for relocation; a short tail repeats the last. */ +static int sftl_load_move(struct apple_sftl *sftl, const u32 *keys, u32 count, u32 first, u32 victim) +{ + unsigned int c, chunk; + int ret; + + for (c = 0; c < 4; c++) { + u32 key = keys[min(first + c, count - 1)]; + const struct sftl_run *run = sftl_find(sftl, key); + const u8 *meta; + + if (!run || run->provider == SFTL_UNMAPPED || + (victim && (run->provider + key - run->start) / sftl_stride(sftl) != victim)) + return victim ? gc_refuse_map(victim, -EBADMSG) : -EBADMSG; + ret = sftl_read_address(sftl, run->provider + key - run->start, &chunk); + if (ret) + return victim ? sftl_gc_read_error(victim, ret) : ret; + meta = sftl->oob + chunk * SFTL_META; + if (meta[0] != 1 && meta[0] != 2) + return victim ? gc_refuse_record_kind(victim, -EBADMSG) : -EBADMSG; + if (get_unaligned_le32(meta + 8) != key) + return victim ? gc_refuse_source_lba(victim, -EBADMSG) : -EBADMSG; + memcpy(sftl->move + c * SFTL_CHUNK, sftl->page + chunk * SFTL_CHUNK, SFTL_CHUNK); + memcpy(sftl->move_oob + c * SFTL_META, meta, SFTL_META); + /* s_write_stamp_relocated_meta (12H321): keep the subtype, + * LBA and user word; type 2 denotes the final internal LBA. + */ + if (victim) + sftl->move_oob[c * SFTL_META] = key == sftl->geo->lpages - 1 ? 2 : 1; + } + return 0; +} + +/* Move everything out of the given-up blocks. Another failure gives up the + * new block as well and starts over from the map. + */ +static int sftl_evacuate(struct apple_sftl *sftl) +{ + u32 *keys = NULL, count = 0, i; + int ret = 0; + + while (sftl->evacuate && !ret) { + sftl->evacuate = false; + kvfree(keys); + ret = sftl_collect_keys(sftl, 0, &keys, &count); + for (i = 0; !ret && i < count && !sftl->evacuate; i += 4) { + ret = sftl_load_move(sftl, keys, count, i, 0); + if (ret) { + sftl->failed = true; + break; + } + ret = sftl_append_once(sftl, sftl->move, sftl->move_oob, true, 0); + if (ret == SFTL_RETRY) + ret = 0; + } + } + /* Leave unfinished work for the next request unless the writer stopped. */ + if (ret && !sftl->failed) + sftl->evacuate = true; + kvfree(keys); + return ret; +} + +static int sftl_append(struct apple_sftl *sftl, const u8 *page, u8 *oob, bool relocated) +{ + int ret; + + do { + ret = sftl_evacuate(sftl); + if (!ret) + ret = sftl_append_once(sftl, page, oob, relocated, 0); + } while (ret == SFTL_RETRY); + if (!ret) + ret = sftl_evacuate(sftl); + return ret; +} + +/* The existing evacuation mover packs four live LBAs into a NAND page. + * Pack multiple donors into the same append stream. Its summary and the + * caller's staged host page remain private to their respective buffers. + */ +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) || \ + IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) +static int sftl_gc_save(struct apple_sftl *sftl); + +/* A native data header and closed footer can supersede an old saved data + * role. Physical ownership, read failures and older recovery roots still win. + */ +static bool sftl_gc_excluded(struct apple_sftl *sftl, u32 block) +{ + struct sftl_reclaim_pool *pool = sftl->pool; + bool counted = test_bit(block, pool->gc_excluded); + u8 role = sftl->roles[block]; + + if (!sftl->lanes[block] || test_bit(block, sftl->unknown_lane_flags)) { + if (!counted) + gc_refuse_lanes(block, -ERANGE); + } else if (test_bit(block, sftl->abandoned) || test_bit(block, sftl->head_unread) || + test_bit(block, sftl->torn)) { + if (!counted) + gc_refuse_quarantine(block, -EOPNOTSUPP); + } else if (sftl->wear[block] >= 0xfffe) { + if (!counted) + gc_refuse_wear(block, -EOPNOTSUPP); + } else if (test_bit(block, sftl->vfl_reserved)) { + if (!counted) + gc_refuse_vfl(block, -EOPNOTSUPP); + } else if (test_bit(block, sftl->reserved) || role == 5 || role == SFTL_CONTEXT || role == 8 || role > SFTL_DIRTY_FREE || + (!test_bit(block, pool->runtime_data) && + pool->media_kind[block] != SFTL_MEDIA_DATA_FOOTER)) { + if (!counted) + gc_refuse_owner(block, -EOPNOTSUPP); + } else if (test_bit(block, sftl->fallback_live)) { + if (!counted) + gc_refuse_fallback(block, -EOPNOTSUPP); + } else { + return false; + } + __set_bit(block, pool->gc_excluded); + return true; +} + +static u32 sftl_gc_pick(struct apple_sftl *sftl, u32 room) +{ + struct sftl_reclaim_pool *pool = sftl->pool; + u32 block, best = 0, min_score = U32_MAX; + bool skipped = false; + + for (block = 1; block < sftl_data_limit(sftl); block++) { + u32 capacity = sftl_slots(sftl, sftl->lanes[block]); + u32 valid = pool->valid[block], score; + + if (!test_bit(block, pool->runtime_data) && + pool->media_kind[block] != SFTL_MEDIA_DATA_FOOTER && + sftl->roles[block] != SFTL_CLOSED_DATA) + continue; + if (test_bit(block, pool->gc_pending) || test_bit(block, pool->gc_landings) || + block == sftl->append_block || block == pool->gc_site || + block == pool->context_site || block == sftl->spare || + sftl_gc_excluded(sftl, block)) + continue; + if (round_up(valid, 4U) > room || + valid >= capacity || + (!valid && pool->lanes[block] && sftl_reuse_available(sftl, block))) + continue; + if (test_bit(block, pool->gc_unsupported)) { + skipped = true; + continue; + } + score = valid * sftl_stride(sftl) / capacity; + if (score < min_score || (score == min_score && sftl->wear[block] < sftl->wear[best])) { + best = block; + min_score = score; + } + } + if (skipped) + gc_skipped_unsupported++; + return best; +} + +static unsigned int sftl_stripe_room(struct apple_sftl *sftl, unsigned int want); +static int sftl_append_stripe(struct apple_sftl *sftl, u32 logical_page, const u8 *data, + unsigned int count, unsigned int m, unsigned int *written, + u32 victim); + +static int sftl_gc_move_victim(struct apple_sftl *sftl, u32 block, unsigned long deadline) +{ + struct sftl_reclaim_pool *pool = sftl->pool; + struct apple_sftl_gc_block donor = { + .block = block, .lanes = sftl->lanes[block], .closed = true, + }; + unsigned long started = jiffies; + u32 before = pool->valid[block], moved = 0, count, *keys = NULL; + u8 *batch = NULL, *footer, flags = sftl->block_flags[block]; + int ret = 0; + + gc_victims++; + if (!sftl->checkpoint_start || !test_bit(block, pool->runtime_data) || + !test_bit(block, sftl->linux_erased)) { + footer = kvmalloc(sftl->geo->footer_max * SFTL_CHUNK, GFP_NOIO); + if (!footer) { + ret = -ENOMEM; + goto out; + } + ret = sftl_verify_closed(sftl, &donor, deadline, true, footer, &flags); + kvfree(footer); + if (ret) + goto check_donor; + } + ret = sftl_collect_keys(sftl, block, &keys, &count); + if (ret) + goto out; + if (count != before) { + ret = gc_refuse_map(block, -EBADMSG); + goto check_donor; + } + /* Suppress runtime retirement even for replay-only donors until their + * last replacement and the batched context have both been verified. + */ + __set_bit(block, pool->gc_pending); + while (moved < count) { + unsigned int m = sftl_stripe_room(sftl, min(DIV_ROUND_UP(count - moved, 4U), + READ_ONCE(program_batch))); + unsigned int k, written = 0; + + if (time_after_eq(jiffies, deadline)) { + ret = -ETIMEDOUT; + break; + } + if (m && !batch) + batch = kvmalloc_array(min_t(u32, SFTL_STRIPE_MAX, DIV_ROUND_UP(count, 4U)), + APPLE_PPN_PAGE_SIZE, GFP_NOIO); + if (m && batch) { + for (k = 0; k < m; k++) { + ret = sftl_load_move(sftl, keys, count, moved + 4 * k, block); + if (ret) + break; + memcpy(batch + k * APPLE_PPN_PAGE_SIZE, sftl->move, APPLE_PPN_PAGE_SIZE); + memcpy(sftl->stripe_oob[k], sftl->move_oob, APPLE_PPN_OOB_SIZE); + } + if (ret) + break; + ret = sftl_append_stripe(sftl, 0, batch, count - moved, m, &written, block); + if (ret) + goto landing_error; + if (written) { + moved += written; + continue; + } + } + ret = sftl_load_move(sftl, keys, count, moved, block); + if (ret) + break; + ret = sftl_append_once(sftl, sftl->move, sftl->move_oob, true, block); + if (ret) { +landing_error: + if (ret == -EBADMSG || ret == -ERANGE || ret == -EOPNOTSUPP) + gc_refuse_landing(block, ret); + goto unpin; + } + moved += min(4U, count - moved); + } + if (!ret && (pool->valid[block] || sftl_block_mapped(sftl, block))) + ret = gc_refuse_map(block, -EBADMSG); + if (!ret) { + sftl->block_flags[block] = flags; + pool->gc_count++; + goto out; + } +check_donor: + /* Only the donor's format, metadata or mapped address rules it out. + * Resource, transport and landing failures say nothing about it. + */ + if (ret == -EOPNOTSUPP || ret == -EBADMSG || ret == -ERANGE) { + __set_bit(block, pool->gc_unsupported); + gc_unsupported_marked++; + } +unpin: + __clear_bit(block, pool->gc_pending); +out: + kvfree(batch); + kvfree(keys); + gc_pages_moved += moved; + if (!(gc_victims % 64)) + pr_debug("apple-sftl: gc block=%u valid=%u moved=%u ms=%u ret=%d\n", + block, before, moved, jiffies_to_msecs(jiffies - started), ret); + return ret; +} + +/* At most one completed victim per service, with a deadline across rejected + * candidates as well. The append mutex protects the shared page and footer. + */ +static int sftl_gc_service(struct apple_sftl *sftl, unsigned long deadline) +{ + struct sftl_reclaim_pool *pool = sftl->pool; + u32 capacity, room, block; + int ret; + + if (!pool || !pool->gc_landing || pool->gc_landing != sftl->append_block || + pool->gc_count >= SFTL_GC_BATCH || sftl->failed || sftl->evacuate) + return 0; + capacity = sftl_slots(sftl, sftl->lanes[pool->gc_landing]); + room = capacity - sftl->append_position; + if (room < sftl->geo->footer_max + 4) + goto done; + room -= sftl->geo->footer_max + 4; + while ((block = sftl_gc_pick(sftl, room))) { + ret = sftl_gc_move_victim(sftl, block, deadline); + if (!ret) + return 0; + if (ret == SFTL_RETRY) + return -EIO; + if (sftl->failed) + return ret; + /* A deadline after some copies leaves the donor intact and + * smaller. Its next pass gathers keys from the current map. + */ + if (ret == -ETIMEDOUT) + return 0; + if (!test_bit(block, pool->gc_unsupported)) + return ret; + if (time_after_eq(jiffies, deadline)) + return 0; + } +done: + pool->gc_landing = 0; + return 0; +} + +struct sftl_gc_space { + u32 proposed, certified, next, context; +}; + +/* Include the final context, exclude the GC reservation. A proposal only + * contributes to the upper bound. Only certified slots can admit a write. + */ +static struct sftl_gc_space sftl_gc_space(struct apple_sftl *sftl) +{ + struct sftl_reclaim_pool *pool = sftl->pool; + struct sftl_gc_space space = {}; + u32 block, free = 0, site = 0, site_slots = 0; + + for (block = 1; block < sftl_data_limit(sftl); block++) { + u32 slots = sftl_slots(sftl, pool->lanes[block]); + + if (block == pool->gc_site || !slots || + pool->lanes[block] != sftl->lanes[block] || + !sftl_reuse_available(sftl, block) || pool->valid[block]) + continue; + space.proposed += slots; + if (!test_bit(block, pool->unchecked)) + space.certified += slots; + else if (!space.next || sftl->wear[block] < sftl->wear[space.next]) + space.next = block; + if (block == pool->context_site) + continue; + free++; + if (slots >= sftl_max_save_slots(sftl) && + (slots > site_slots || (slots == site_slots && sftl->wear[block] < sftl->wear[site]))) { + site = block; + site_slots = slots; + } + } + space.context = free >= 2 ? site : 0; + return space; +} + +/* Validate only as much media as this admission decision depends on. */ +static bool sftl_gc_has_space(struct apple_sftl *sftl, u32 need, unsigned long deadline) +{ + struct sftl_gc_space space; + + for (;;) { + space = sftl_gc_space(sftl); + if (space.certified >= need) + return true; + if (space.proposed < need || !space.next || time_after_eq(jiffies, deadline)) + return false; + sftl_certify_reuse(sftl, space.next, deadline); + } +} + +static bool sftl_gc_allowed(struct apple_sftl *sftl) +{ + return sftl->pool->maps_complete && !sftl->tolerated && + READ_ONCE(gc_saves) < SFTL_GC_SAVES && + READ_ONCE(n42_saves) < SFTL_N42_SAVES - 1; +} + +/* Only the seven-block floor is certified in a host claim. Work toward + * the four-block margin one candidate per lock hold, then reserve a save + * site and use the open Linux landing for relocation under pressure. + */ +static void sftl_gc_prepare_landing(struct apple_sftl *sftl) +{ + struct sftl_reclaim_pool *pool = sftl->pool; + unsigned long deadline = jiffies + SFTL_CLAIM_TIMEOUT; + struct sftl_gc_space space; + u32 block = sftl->append_block, nominal = sftl_stride(sftl), site; + + if (!sftl->writer_prepared || block == U32_MAX || !sftl_gc_allowed(sftl) || + test_bit(block, pool->gc_landings) || !test_bit(block, sftl->linux_erased)) + return; + space = sftl_gc_space(sftl); + if (space.certified >= 11 * nominal) + return; + if (space.proposed >= 11 * nominal && space.next) { + sftl_certify_reuse(sftl, space.next, deadline); + sftl_gc_wake(sftl); + return; + } + /* This writer has consumed the four-block margin above the floor. */ + sftl_request_prune(sftl); + if (!pool->gc_site) { + site = space.context; + if (!site) + return; + if (space.proposed >= 7 * nominal + sftl_slots(sftl, pool->lanes[site]) && + space.certified < 7 * nominal + sftl_slots(sftl, pool->lanes[site]) && space.next) { + sftl_certify_reuse(sftl, space.next, deadline); + sftl_gc_wake(sftl); + return; + } + if (!sftl_certify_reuse(sftl, site, deadline)) { + sftl_gc_wake(sftl); + return; + } + pool->gc_site = site; + if (sftl_gc_space(sftl).certified < 7 * nominal) { + pool->gc_site = 0; + return; + } + } + pool->gc_landing = block; + __set_bit(block, pool->gc_landings); + sftl_gc_wake(sftl); +} + +static int sftl_gc_thread(void *arg) +{ + struct apple_sftl *sftl = arg; + unsigned int noio = memalloc_noio_save(); + + while (!kthread_should_stop()) { + struct sftl_reclaim_pool *pool; + bool wake; + int ret = 0; + + wait_event_interruptible_timeout(sftl->gc_wait, + kthread_should_stop() || atomic_read(&sftl->gc_wake), 2 * HZ); + if (kthread_should_stop()) + break; + mutex_lock(sftl->disk_io_lock); + mutex_lock(&sftl->lock); + wake = atomic_xchg(&sftl->gc_wake, 0); + pool = sftl->pool; + if (sftl->failed || sftl->evacuate || + (sftl->write_fenced && !sftl->nr_write_fence_more && + sftl->write_fence_start >= sftl->write_fence_end) || + (!wake && time_before(jiffies, sftl->last_io + 2 * HZ))) + goto unlock; + if (sftl->reuse_scan_pending) { + sftl_scan_reuse(sftl); + sftl_gc_wake(sftl); + } else if (sftl->prune_requested && sftl->append_block == U32_MAX && + !pool->gc_count) { + sftl->prune_requested = false; + if (pool->nr_fallback_sites) + ret = sftl_prune_fallbacks(sftl); + } else if (pool->gc_count >= SFTL_GC_BATCH) { + ret = sftl_gc_save(sftl); + } else if (pool->gc_landing && pool->gc_landing == sftl->append_block) { + u32 before = pool->gc_count; + + ret = sftl_gc_service(sftl, jiffies + SFTL_GC_TIMEOUT); + if (!ret && pool->gc_count != before) + sftl_gc_wake(sftl); + } else { + sftl_gc_prepare_landing(sftl); + } + if (ret) + pr_warn_ratelimited("apple-sftl: background maintenance failed (%d)\n", ret); +unlock: + mutex_unlock(&sftl->lock); + mutex_unlock(sftl->disk_io_lock); + cond_resched(); + } + memalloc_noio_restore(noio); + return 0; +} + +static int sftl_gc_claim(struct apple_sftl *sftl, unsigned long deadline) +{ + struct sftl_reclaim_pool *pool = sftl->pool; + u32 block, slots, site, credit = 0, nominal = sftl_stride(sftl); + u32 floor = 7 * nominal, landing, previous, need, victim; + unsigned long copy_deadline; + bool pressure, mandatory, saved = false; + int ret; + +again: + if (time_after_eq(jiffies, deadline)) + return -ETIMEDOUT; + if (sftl->gc_task) { + ret = sftl_reuse_pick(sftl, 0, &landing); + if (!ret) { + slots = sftl_slots(sftl, sftl->lanes[landing]); + if (!sftl_certify_reuse(sftl, landing, deadline)) + goto again; + if (sftl_gc_has_space(sftl, slots + floor, deadline)) { + ret = sftl_reuse_blank_dirty(sftl, &landing, deadline, SFTL_CLAIM_LANDING); + if (!ret) { + sftl_open_block(sftl, landing); + if (sftl_gc_space(sftl).certified < 11 * nominal) + sftl_gc_wake(sftl); + } + return ret; + } + } else if (ret != -ENOSPC) { + return ret; + } + /* Normal admission could not preserve the seven-block floor. */ + sftl_request_prune(sftl); + } + pressure = sftl_gc_allowed(sftl) && + (sftl->gc_task || !sftl_gc_has_space(sftl, 4 + 17 * nominal, deadline)); + site = pressure && !pool->gc_site ? sftl_gc_space(sftl).context : 0; + if (site) { + if (!sftl_certify_reuse(sftl, site, deadline)) + goto again; + pool->gc_site = site; + } + ret = sftl_reuse_pick(sftl, 0, &landing); + if (ret && ret != -ENOSPC) + return ret; + slots = ret ? 0 : sftl_slots(sftl, sftl->lanes[landing]); + if (!ret && pressure && pool->gc_site) { + victim = sftl_gc_pick(sftl, nominal - sftl->geo->footer_max - 4); + need = victim ? round_up(pool->valid[victim], 4U) + sftl->geo->footer_max + 4 : 0; + if (slots < need && !sftl_reuse_pick(sftl, need, &landing)) + slots = sftl_slots(sftl, sftl->lanes[landing]); + } + /* Charge the whole new landing at admission. Even the last host page + * in its tail must leave seven nominal blocks, including final_site. + */ + if (!ret && !sftl_certify_reuse(sftl, landing, deadline)) { + if (site) + pool->gc_site = 0; + goto again; + } + mandatory = !sftl_gc_has_space(sftl, slots + floor, deadline); + if (pool->gc_count && (ret == -ENOSPC || mandatory || (!sftl->gc_task && pool->gc_count >= SFTL_GC_BATCH))) { + ret = sftl_gc_save(sftl); + if (ret) + return ret; + saved = true; + deadline = jiffies + SFTL_CLAIM_TIMEOUT; + goto again; + } + if (ret) + return ret; + if (mandatory && (saved || !pressure || !pool->gc_site || + !sftl_gc_pick(sftl, slots - sftl->geo->footer_max - 4))) + return -ENOSPC; + + ret = sftl_reuse_blank_dirty(sftl, &landing, deadline, SFTL_CLAIM_LANDING); + if (ret) + return ret; + sftl_open_block(sftl, landing); + if (!pressure || !pool->gc_site) + return 0; + pool->gc_landing = landing; + __set_bit(landing, pool->gc_landings); + copy_deadline = jiffies + SFTL_GC_TIMEOUT; + if (!mandatory) { + if (!sftl->gc_task) + return sftl_gc_service(sftl, copy_deadline); + sftl_gc_wake(sftl); + return 0; + } + + /* A cold start can already be below the floor. Copy into a distinct + * landing while the host waits. Only verified, released capacity can + * admit its write. As in sftl_compact, the verified stream keeps its + * cursor and BTOC across the save; later runs have new weave sequences. + */ + do { + previous = pool->gc_count; + ret = sftl_gc_service(sftl, copy_deadline); + if (ret) + goto park; + } while (pool->gc_count != previous && pool->gc_count < SFTL_GC_BATCH && + !time_after_eq(jiffies, copy_deadline)); + for_each_set_bit(block, pool->gc_pending, sftl_data_limit(sftl)) + credit += sftl_slots(sftl, sftl->lanes[block]); + if (!pool->gc_count || !sftl_gc_has_space(sftl, floor - min(floor, credit), deadline)) { + ret = -ENOSPC; + goto park; + } + ret = sftl_gc_save(sftl); + if (!ret && sftl_gc_has_space(sftl, floor, deadline)) + return 0; + if (!ret) + ret = -ENOSPC; +park: + /* No host record was staged here. A partly filled GC stream remains + * readable/replayable; relinquish its tail so the final save can run. + */ + if (sftl->append_block == landing) { + sftl->append_block = U32_MAX; + if (sftl->append_position) + sftl_set_role(sftl, landing, SFTL_ABANDONED_DATA); + else + sftl_set_role(sftl, landing, SFTL_CLEAN_FREE); + } + return ret; +} +#else +static int sftl_prune_fallbacks(struct apple_sftl *sftl) +{ + return 0; +} + +static int sftl_gc_service(struct apple_sftl *sftl, unsigned long deadline) +{ + return 0; +} + +static int sftl_gc_claim(struct apple_sftl *sftl, unsigned long deadline) +{ + u32 block; + int ret = sftl_reuse_blank_dirty(sftl, &block, deadline, SFTL_CLAIM_DATA); + + if (!ret) + sftl_open_block(sftl, block); + return ret; +} +#endif + +void apple_sftl_start_gc(struct apple_sftl *sftl, struct mutex *disk_io_lock) +{ +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) || IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) + struct task_struct *task; + + mutex_lock(&sftl->lock); + if (sftl->pool) { + sftl->disk_io_lock = disk_io_lock; + atomic_set(&sftl->gc_wake, 1); + task = kthread_run(sftl_gc_thread, sftl, "apple-sftl-gc"); + if (!IS_ERR(task)) + sftl->gc_task = task; + else + pr_warn("apple-sftl: GC thread unavailable (%ld)\n", PTR_ERR(task)); + } + mutex_unlock(&sftl->lock); +#endif +} + +static bool sftl_fence_range_allows(u32 start, u32 end, u32 logical_page, unsigned int count) +{ + return start < end && logical_page >= start && logical_page < end && + count <= end - logical_page; +} + +static bool sftl_fence_allows(struct apple_sftl *sftl, u32 logical_page, unsigned int count) +{ + u32 i; + + if (sftl_fence_range_allows(sftl->write_fence_start, sftl->write_fence_end, + logical_page, count)) + return true; + for (i = 0; i < sftl->nr_write_fence_more; i++) + if (sftl_fence_range_allows(sftl->write_fence_more[i][0], + sftl->write_fence_more[i][1], logical_page, count)) + return true; + return false; +} + +/* Caller holds sftl->lock and checked the fence. One NAND page, 1..4 logical pages. */ +static int sftl_write_page(struct apple_sftl *sftl, u32 logical_page, + const u8 *data, unsigned int count) +{ + unsigned int chunk; + int ret; + + if (sftl->failed) + return -EIO; + if (sftl->sequence > SFTL_SEQUENCE - 4) + return -EOVERFLOW; + ret = sftl_writer_prepare(sftl, true); + if (ret) + return ret; + for (chunk = 0; chunk < 4; chunk++) { + unsigned int index = min(chunk, count - 1); + + memcpy(sftl->stage + chunk * SFTL_CHUNK, data + index * SFTL_CHUNK, SFTL_CHUNK); + sftl_data_meta(sftl->stage_oob + chunk * SFTL_META, 0, logical_page + index); + } + return sftl_append(sftl, sftl->stage, sftl->stage_oob, false); +} + +/* + * How many whole pages a stripe may take at the append point: at most + * @want, in lane order in the open block, none of them past the point where + * the block must close (the last one may close it), and nothing pending. + * 0 or 1: write page by page. + */ +static unsigned int sftl_stripe_room(struct apple_sftl *sftl, unsigned int want) +{ + u32 block = sftl->append_block, slots; + unsigned int m; + + if (want < 2 || !sftl->ppn->ops->program_pages || block == U32_MAX || + sftl->evacuate || sftl->failed || !sftl->writer_prepared) + return 0; + m = min_t(unsigned int, want, SFTL_STRIPE_MAX); + if (!sftl->geo->n42_install) + m = min3(m, 4U, (unsigned int)hweight16(sftl->lanes[block])); + if (sftl->sequence > SFTL_SEQUENCE - 4ULL * m - 4) + return 0; + slots = sftl_slots(sftl, sftl->lanes[block]); + for (; m >= 2; m--) { + u32 before_last = sftl->append_position + 4 * (m - 1); + + /* After m - 1 pages the block must still be open. */ + if (!sftl->geo->summary_sequences) { + if (before_last < sftl->append_capacity) + break; + } else if (before_last + sftl_footer_chunks_for(sftl->footer_runs + 4 * m) < slots) { + break; + } + } + return m >= 2 ? m : 0; +} + +static void sftl_pack_next_stripe(void *priv) +{ + struct sftl_next_stripe *next = priv; + unsigned int i, c; + + for (i = 0; i < next->rows; i++) { + for (c = 0; c < 4; c++) { + u64 seq = next->base + 4 * i + c + 1; + u32 key = next->first + min(4 * i + c, next->count - 1); + + sftl_data_meta(next->oob[i] + c * SFTL_META, seq, key); + } + } + next->ready = true; +} + +/* + * Program @m pages of user data at the append point at once. On success + * they are published in order, exactly as m single appends would be. + * If any fails, a later page may still have landed: every sequence of the + * stripe is spent, nothing of it is published, the block is given up as + * for a single failed page, and *written stays 0 so the caller writes all + * of it again page by page (after the evacuation). iOS replays a blank + * page in an open block as a blank token and a torn one as uECC, and the + * new copies carry higher sequences. + */ +static int sftl_append_stripe(struct apple_sftl *sftl, u32 logical_page, const u8 *data, + unsigned int count, unsigned int m, unsigned int *written, + u32 victim) +{ + struct apple_ppn_program *prog = sftl->stripe_prog; + u32 first = sftl->append_block * sftl_stride(sftl) + sftl->append_position; + u64 base = sftl->sequence; + struct sftl_next_stripe *next = sftl->next_stripe; + bool packed = !victim && next && next->ready && next->first == logical_page && + next->base == base && next->count == count && next->rows >= m; + unsigned int k, chunk, failed; + int ret, rr; + + *written = 0; + for (k = 0; k < m; k++) { + unsigned int left = count - 4 * k, n = min(left, 4U); + u8 *oob = sftl->stripe_oob[k]; + const u8 *page = data + 4 * k * SFTL_CHUNK; + + ret = sftl_program_target(sftl, first + 4 * k, &prog[k]); + if (ret) { + m = k; + break; + } + if (!victim && n < 4) { + /* The last page of a short write repeats its last logical page. */ + for (chunk = 0; chunk < 4; chunk++) + memcpy(sftl->stage + chunk * SFTL_CHUNK, + page + min(chunk, n - 1) * SFTL_CHUNK, SFTL_CHUNK); + page = sftl->stage; + } + if (packed) { + memcpy(oob, next->oob[k], APPLE_PPN_OOB_SIZE); + } else { + for (chunk = 0; !victim && chunk < 4; chunk++) + sftl_data_meta(oob + chunk * SFTL_META, 0, + logical_page + 4 * k + min(chunk, n - 1)); + sftl_stamp_page_at(sftl, oob, !!victim, !!victim, base + 4 * k); + } + prog[k].data = page; + prog[k].oob = oob; + prog[k].ret = 0; + } + if (m < 2) + return 0; /* page by page from here */ + if (!victim && count > 4 * m && sftl->ppn->ops->program_pages_prepare) { + if (!next) + next = sftl->next_stripe = kzalloc(sizeof(*next), GFP_NOIO); + if (next) { + next->base = base + 4 * m; + next->first = logical_page + 4 * m; + next->count = count - 4 * m; + next->rows = min_t(unsigned int, SFTL_STRIPE_MAX, DIV_ROUND_UP(next->count, 4)); + /* The callback is optional when hardware selects singles. */ + next->ready = false; + ret = sftl->ppn->ops->program_pages_prepare(sftl->ppn->priv, prog, m, + sftl_pack_next_stripe, next); + goto completed; + } + } + ret = sftl->ppn->ops->program_pages(sftl->ppn->priv, prog, m); +completed: + if (!ret) { + stripes++; + stripe_pages += m; + for (k = 0; victim && k < m; k++) { + ret = sftl_check_move(sftl, first + 4 * k, prog[k].data, prog[k].oob, victim); + if (ret) { + sftl->sequence = sftl->journal_sequence = base + 4ULL * m; + return ret; + } + } + for (k = 0; k < m; k++) { + ret = sftl_publish_page(sftl, first + 4 * k, sftl->stripe_oob[k], prog[k].data); + if (ret) { + sftl->sequence = sftl->journal_sequence = base + 4ULL * m; + return ret; + } + } + *written = min(count, 4 * m); + return 0; + } + stripe_failures++; + for (failed = 0; failed < m && !prog[failed].ret; failed++) + ; + if (failed == m) + failed = 0; + rr = sftl_give_up(sftl, first + 4 * failed, prog[failed].data, prog[failed].oob, + prog[failed].ret ? prog[failed].ret : ret); + if (sftl->sequence < base + 4ULL * m) { + sftl->sequence = base + 4ULL * m; + sftl->journal_sequence = sftl->sequence; + } + return !victim && rr == SFTL_RETRY ? 0 : rr; +} + +int apple_sftl_write(struct apple_sftl *sftl, u32 logical_page, + const u8 *data, unsigned int count) +{ + int ret; + + if (!sftl || !data || !count || count > 4 || logical_page >= sftl->geo->disk_pages || + count > sftl->geo->disk_pages - logical_page) + return -EINVAL; + mutex_lock(&sftl->lock); + sftl->last_io = jiffies; + if (sftl->write_fenced && !sftl_fence_allows(sftl, logical_page, count)) + ret = -EPERM; + else { + ret = sftl->gc_task ? 0 : sftl_gc_service(sftl, jiffies + SFTL_GC_TIMEOUT); + if (!ret) + ret = sftl_write_page(sftl, logical_page, data, count); + } + mutex_unlock(&sftl->lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sftl_write); + +/* + * Up to APPLE_SFTL_WRITE_MAX consecutive logical pages, four to a NAND page + * from @logical_page on, as that many apple_sftl_write calls would write + * them. With program_batch > 1 whole runs of pages go out as stripes. + */ +int apple_sftl_write_multi(struct apple_sftl *sftl, u32 logical_page, + const u8 *data, unsigned int count) +{ + unsigned int done = 0, written, n, m; + int ret = 0; + + if (!sftl || !data || !count || count > APPLE_SFTL_WRITE_MAX || + logical_page >= sftl->geo->disk_pages || + count > sftl->geo->disk_pages - logical_page) + return -EINVAL; + mutex_lock(&sftl->lock); + sftl->last_io = jiffies; + if (sftl->write_fenced && !sftl_fence_allows(sftl, logical_page, count)) { + ret = -EPERM; + goto out; + } + ret = sftl->gc_task ? 0 : sftl_gc_service(sftl, jiffies + SFTL_GC_TIMEOUT); + while (!ret && done < count) { + n = min(count - done, 4U); + m = sftl_stripe_room(sftl, min(DIV_ROUND_UP(count - done, 4U), + READ_ONCE(program_batch))); + written = 0; + if (m) + ret = sftl_append_stripe(sftl, logical_page + done, + data + done * SFTL_CHUNK, count - done, m, + &written, 0); + if (!ret && !written) { + ret = sftl_write_page(sftl, logical_page + done, + data + done * SFTL_CHUNK, n); + written = n; + } + done += written; + } +out: + mutex_unlock(&sftl->lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sftl_write_multi); + +int apple_sftl_trim(struct apple_sftl *sftl, u32 logical_page, unsigned int count) +{ + u8 oob[APPLE_PPN_OOB_SIZE]; + struct sftl_run *run; + unsigned int i; + int ret; + + if (!sftl || !count || logical_page >= sftl->geo->disk_pages || + count > sftl->geo->disk_pages - logical_page) + return -EINVAL; + if (!sftl->geo->n42_install) + return -EOPNOTSUPP; + mutex_lock(&sftl->lock); + sftl->last_io = jiffies; + if (!sftl->write_fenced || !sftl_fence_allows(sftl, logical_page, count)) { + ret = -EPERM; + goto out; + } + if (sftl->failed) { + ret = -EIO; + goto out; + } + run = sftl_find(sftl, logical_page); + if (run && run->provider == SFTL_UNMAPPED && count <= run->end - logical_page) { + ret = 0; + goto out; + } + ret = sftl_writer_prepare(sftl, true); + if (ret) + goto out; + /* 12H321 0x80dd79ac: count followed by (start, length) in 4 KiB + * LBAs. Use a single range and pad the remaining program unit: an + * open-block replay reads only the first chunk of adjacent trims. + */ + memset(sftl->stage, 0, APPLE_PPN_PAGE_SIZE); + put_unaligned_le32(1, sftl->stage); + put_unaligned_le32(logical_page, sftl->stage + 4); + put_unaligned_le32(count, sftl->stage + 8); + for (i = 0; i < 4; i++) + sftl_data_meta(oob + i * SFTL_META, 0, i ? SFTL_PAD : SFTL_TRIM); + oob[0] = 2; + ret = sftl_append(sftl, sftl->stage, oob, false); +out: + mutex_unlock(&sftl->lock); + return ret; +} + +int apple_sftl_flush(struct apple_sftl *sftl) +{ + int ret; + + if (!sftl) + return -EINVAL; + mutex_lock(&sftl->lock); + /* Each program is complete and verified before apple_sftl_write returns. */ + ret = sftl->failed ? -EIO : 0; + mutex_unlock(&sftl->lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sftl_flush); + +/* + * Restrict logical writes on this SFTL instance strictly to [start, end). + * Passing start >= end (e.g. 0, 0) sets an empty fence that refuses every + * write with -EPERM. Once fenced, the fence stays active for the lifetime + * of the instance. + */ +void apple_sftl_set_write_fence(struct apple_sftl *sftl, u32 start, u32 end) +{ + if (!sftl) + return; + mutex_lock(&sftl->lock); + sftl->write_fenced = true; + sftl->write_fence_start = start; + sftl->write_fence_end = end; + sftl->nr_write_fence_more = 0; + mutex_unlock(&sftl->lock); +} +EXPORT_SYMBOL_GPL(apple_sftl_set_write_fence); + +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) || \ + IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) +/* + * Rung 3: a program-only native checkpoint (12H321 1-site profile). + * + * The live map and the loaded context prefix become one new generation in a + * verified blank clean-free block; the previous context block is not erased. + * This is the state iOS itself is in between cxtSaveBase and the erase of the + * old sites (0x80dd10e0 -> 0x80dd1864). At boot, 12H321 picks the base with + * the highest sequence and erases every context block it does not name + * (0x80dd07ac), so the old block is reclaimed by iOS (docs/a6/n42-cxt-lifecycle-re.md). + * + * The saved table follows the media: a clean-free or open-data entry whose + * block now holds data (written after the old checkpoint, by iOS or by + * Linux) becomes closed data, with the summary flags when it has one, and + * an open-data entry that is still open keeps its stream. Valid counts and + * stat 9 come from the map (apple_sftl_account_map); other cached statistics, + * wear and read counts are kept, as iOS keeps them across a save. + * + * A block erased here (dirty-free reuse) saves its new wear, and if it is + * still blank it is saved clean, as 0x80dd650c leaves it after an erase; the + * boot scan keeps a blank block whose saved role is 1 clean (s_cxt_boot). + */ +static int sftl_ckpt_reconcile(struct apple_sftl *sftl, struct apple_sftl_snapshot *snap, + const struct apple_sftl_layout *layout, u32 skip, + struct apple_sftl_checkpoint_report *rep) +{ + u32 stride = sftl_stride(sftl), per_record = SFTL_CHUNK / 8, block; + unsigned int chunk; + int ret; + + for (block = 1; block < layout->subblocks; block++) { + u8 *e = snap->opaque[layout->sb_start + block / per_record].data + + (block % per_record) * 8; + u32 slots, tail; + bool fresh; + + if (sftl->pool && test_bit(block, sftl->pool->gc_pending)) { + u32 per = SFTL_CHUNK / sizeof(u32); + u8 *reads = snap->opaque[layout->read_count_start + block / per].data; + + if (sftl->pool->valid[block] || sftl_block_mapped(sftl, block)) + return -EBADMSG; + put_unaligned_le32(0, reads + (block % per) * sizeof(u32)); + e[0] = SFTL_DIRTY_FREE; + e[1] = sftl->block_flags[block]; + put_unaligned_le16(sftl->wear[block], e + 6); + continue; + } + if (sftl->pool && test_bit(block, sftl->linux_erased)) { + u32 per = SFTL_CHUNK / sizeof(u32); + u8 *reads = snap->opaque[layout->read_count_start + block / per].data; + u32 seq_per = SFTL_CHUNK / sizeof(struct apple_sftl_user_seq); + u8 *seq = snap->opaque[layout->user_seq_start + block / seq_per].data; + + e[0] = sftl->roles[block]; + e[1] = sftl->block_flags[block]; + put_unaligned_le16(sftl->wear[block], e + 6); + put_unaligned_le32(0, reads + (block % per) * sizeof(u32)); + /* A closed block has a fresh summary from sftl_close_block. */ + if (e[0] == SFTL_CLOSED_DATA) + rep->reconciled_closed++; + else + memset(seq + (block % seq_per) * sizeof(struct apple_sftl_user_seq), + 0, sizeof(struct apple_sftl_user_seq)); + /* checkpoint_build derives all valid counts from the live map. */ + continue; + } + + if (sftl->pool && (test_bit(block, sftl->pool->boot_retired) || + test_bit(block, sftl->pool->runtime_retired))) { + e[0] = sftl->roles[block]; + e[1] = sftl->block_flags[block]; + continue; + } + + /* + * A block the old table saves as context that starts with a data + * record is a former context site iOS refilled with data; its + * boot scan types it closed data, so save it that way. + */ + if (e[0] == SFTL_CONTEXT && sftl->geo->stale_context_role && block != skip && + sftl->lanes[block] && block < sftl_data_limit(sftl)) { + ret = sftl_read_address(sftl, block * stride, &chunk); + if (ret) + return ret; + if (sftl->oob[0] == 1 || sftl->oob[0] == 2) { + slots = sftl_slots(sftl, sftl->lanes[block]); + ret = sftl_read_address(sftl, block * stride + slots - 4, &chunk); + if (ret) + return ret; + e[0] = SFTL_CLOSED_DATA; + e[1] = sftl->oob[0] == 0x1c ? sftl->oob[1] : 0; + rep->reconciled_closed++; + } + continue; + } + if ((e[0] != SFTL_CLEAN_FREE && e[0] != SFTL_OPEN_DATA && + e[0] != SFTL_DIRTY_FREE && e[0] != 2) || block == skip || + !sftl->lanes[block] || block >= sftl_data_limit(sftl)) + continue; + if (test_bit(block, sftl->linux_erased)) + put_unaligned_le16(sftl->wear[block], e + 6); + ret = sftl_read_address(sftl, block * stride, &chunk); + if (ret) + return ret; + if (sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE) && + sftl_erased(sftl->oob, APPLE_PPN_OOB_SIZE)) { + if (e[0] == SFTL_OPEN_DATA) + return -EBADMSG; /* a saved stream must have data */ + if (test_bit(block, sftl->linux_erased) && e[0] == SFTL_DIRTY_FREE) { + e[0] = SFTL_CLEAN_FREE; + e[1] = 0; + } + continue; + } + /* Data written after the old checkpoint starts past its sequence; + * a dirty block's obsolete data starts before it. + */ + fresh = sftl_sequence(sftl->oob) > sftl->checkpoint_sequence; + if (e[0] != SFTL_OPEN_DATA && !fresh) { + if (e[0] == SFTL_CLEAN_FREE) + return -EBADMSG; /* a clean block with old data */ + continue; + } + if (sftl->oob[0] != 1 && sftl->oob[0] != 2) + return -EBADMSG; /* only data may start a data block */ + slots = sftl_slots(sftl, sftl->lanes[block]); + tail = block * stride + slots - 4; + ret = sftl_read_address(sftl, tail, &chunk); + if (ret) + return ret; + if (sftl->oob[0] == 0x1c) { + e[0] = SFTL_CLOSED_DATA; + e[1] = sftl->oob[1]; + rep->reconciled_closed++; + } else if (e[0] != SFTL_OPEN_DATA) { + /* Open after the old checkpoint, as 12H321's boot scan types it. */ + e[0] = SFTL_CLOSED_DATA; + e[1] = 0; + rep->reconciled_open++; + } + } + return 0; +} + +/* + * A single writer holds the map lock from relocation through retirement. + * The cold scan recorded a sequence bound for every journal block. Recheck + * the media of any block programmed or erased since that scan (status-only + * programs need not have had readback). If every bound precedes the new + * base, boot replay cannot apply a data run, trim or stop token. Thus the + * independently decoded checkpoint IS the recovered map, including every + * relocated LBA. Unknown bounds or changed VFL ownership need cold recovery. + */ +static int sftl_gc_check_journal(struct apple_sftl *live, struct apple_sftl *cold, + u32 old_site, u32 new_site, u64 base) +{ + struct sftl_ios_block entry; + struct sftl_ios_scan scan = { .threshold = base, .blocks = &entry }; + struct sftl_reclaim_pool *pool = cold->pool; + u64 floor = cold->checkpoint_sequence; + u32 block, next = 0; + int ret = 0; + + for (block = 1; block < cold->geo->subblocks; block++) { + u8 head[SFTL_META], kind; + unsigned int chunk; + + if (block == old_site || block == new_site) + continue; + if (test_bit(block, live->pool->media_changed)) { + if (block >= next && sftl_can_prefetch(cold)) { + u32 heads[2 * SFTL_SCAN_DEPTH], n = 0; + + for (next = block; next < cold->geo->subblocks && n < ARRAY_SIZE(heads); next++) + if (next != old_site && next != new_site && + test_bit(next, live->pool->media_changed)) + heads[n++] = next * sftl_stride(cold); + sftl_prefetch(cold, 0, heads, n); + } + ret = sftl_read_open(cold, block * sftl_stride(cold), &chunk); + if (ret) + break; + memcpy(head, cold->oob, sizeof(head)); + if (head[0] == 1 || head[0] == 2) { + scan.nr_blocks = scan.nr_runs = 0; + ret = sftl_ios_scan_block(cold, &scan, head, block, &floor); + if (ret) + break; + } else if (!sftl_erased(cold->oob, sizeof(cold->oob)) || + !sftl_erased(cold->page, APPLE_PPN_PAGE_SIZE)) { + ret = -EBADMSG; + break; + } + } else { + pool->media_high[block] = live->pool->media_high[block]; + pool->media_kind[block] = live->pool->media_kind[block]; + } + if (pool->media_high[block] >= base) { + ret = -EBADMSG; + break; + } + kind = pool->media_kind[block]; + if (kind == SFTL_MEDIA_DATA_FOOTER && pool->media_high[block] < pool->oldest_base) + __set_bit(block, cold->old_closed); + if (kind != SFTL_MEDIA_NONE && + (kind != SFTL_MEDIA_OPEN || cold->roles[block] != SFTL_OPEN_DATA)) + __set_bit(block, pool->boot_retired); + } + kvfree(scan.runs); + if (!ret) + sftl_retire_boot_data(cold); + return ret; +} + +static bool sftl_vfl_matches(const struct apple_sftl *live, const struct apple_sftl *cold) +{ + return !cold->vfl_degraded && !memcmp(cold->lanes, live->lanes, sizeof(live->lanes)) && + bitmap_equal(cold->vfl_reserved, live->vfl_reserved, SFTL_MAX_BLOCKS) && + bitmap_equal(cold->unknown_lane_flags, live->unknown_lane_flags, SFTL_MAX_BLOCKS); +} + +static int sftl_gc_check_vfl(struct apple_sftl *live, struct apple_sftl *cold) +{ + int ret; + + memset(cold->lanes, 0, sizeof(cold->lanes)); + bitmap_zero(cold->vfl_reserved, SFTL_MAX_BLOCKS); + bitmap_zero(cold->unknown_lane_flags, SFTL_MAX_BLOCKS); + ret = sftl_vfl(cold); + if (ret) + return ret; + return sftl_vfl_matches(live, cold) ? 0 : -ESTALE; +} + +struct sftl_prune_scan { + struct apple_sftl *roots; + u8 *heads; +}; + +/* The root scan also read every block that could replay. Restore the cold + * scan's evidence for untouched blocks below the base, then replay the + * rest normally. Removing older roots changes the cutoff for old_closed. + */ +static int sftl_prune_replay(struct apple_sftl *live, struct apple_sftl *cold, + const struct sftl_prune_scan *scan) +{ + struct sftl_reclaim_pool *pool = cold->pool; + u32 block; + + if (!bitmap_equal(cold->reserved, scan->roots->reserved, SFTL_MAX_BLOCKS)) + return -ESTALE; + bitmap_copy(cold->head_unread, scan->roots->head_unread, SFTL_MAX_BLOCKS); + for (block = 1; block < cold->geo->subblocks; block++) { + u8 kind; + + if (sftl_prune_needs_head(live, block)) { + __assign_bit(block, cold->candidates, test_bit(block, scan->roots->candidates)); + continue; + } + pool->media_high[block] = live->pool->media_high[block]; + kind = pool->media_kind[block] = live->pool->media_kind[block]; + if (kind == SFTL_MEDIA_DATA_FOOTER) { + unsigned int chunk; + int ret; + + /* Only a type-1 head earns this bit in cold recovery. */ + if (test_bit(block, live->old_closed)) { + __set_bit(block, cold->old_closed); + } else { + ret = sftl_read_address(cold, block * sftl_stride(cold), &chunk); + if (ret) + return ret; + if (cold->oob[0] != 1 && cold->oob[0] != 2) + return -ESTALE; + __assign_bit(block, cold->old_closed, cold->oob[0] == 1); + } + } + if (kind != SFTL_MEDIA_NONE && + (kind != SFTL_MEDIA_OPEN || cold->roles[block] != SFTL_OPEN_DATA)) + __set_bit(block, pool->boot_retired); + } + return sftl_journal_ios(cold, scan->heads); +} + +/* Prepare the post-retirement state privately. GC keeps older fallbacks + * pinned. Pruning verified every exclusive fallback and will erase them all. + * Publish this state only after the erases and post-erase checks succeed. + */ +static int sftl_gc_load_new(struct apple_sftl *live, const struct apple_sftl_checkpoint *image, + u32 old_site, u32 new_site, unsigned long deadline, + const struct sftl_prune_scan *prune, struct apple_sftl **out) +{ + DECLARE_BITMAP(named, SFTL_MAX_SUBBLOCKS) = {}; + struct sftl_records records = {}; + struct apple_sftl *cold; + struct rb_node *node; + u32 i, first = new_site * sftl_stride(live); + int ret = -ENOMEM; + + if (!live->pool->maps_complete || live->tolerated || live->failures || + !live->pool->oldest_base || get_unaligned_le32(image->records[0].data) != 1) + return -EOPNOTSUPP; + cold = kzalloc(sizeof(*cold), GFP_NOIO); + if (!cold) + return -ENOMEM; + cold->ppn = live->ppn; + cold->geo = live->geo; + cold->lpp = live->lpp; + cold->psize = live->psize; + cold->osize = live->osize; + cold->load_deadline = deadline ?: 1; + cold->append_block = cold->spare = U32_MAX; + cold->page = kmalloc(APPLE_PPN_PAGE_SIZE, GFP_NOIO); + cold->pool = kvzalloc(sizeof(*cold->pool), GFP_NOIO); + if (!cold->page || !cold->pool) + goto out; + ret = sftl_gc_check_vfl(live, cold); + if (ret) + goto out; + __set_bit(new_site, cold->reserved); + for (i = 0; i < image->count; i++) { + u64 stamp = sftl_stamp(image->records[i].meta); + + ret = sftl_record_add(&records, stamp, 0, first + i); + if (ret) + goto out; + if (i < live->geo->opaque_records) { + ret = sftl_record_add(&cold->context, stamp, 0, first + i); + if (ret) + goto out; + } + } + ret = sftl_decode_generation(cold, &records, 0, records.count, named, NULL, image); + if (ret) + goto out; + sftl_mark_mapped(cold, cold->checkpoint_used); + for (node = rb_first(&cold->runs); node; node = rb_next(node)) { + struct sftl_run *run = rb_entry(node, struct sftl_run, node); + + sftl_count_range(cold, run->provider, run->end - run->start, true); + } + bitmap_copy(cold->candidates, live->candidates, SFTL_MAX_BLOCKS); + if (!prune) { + bitmap_copy(cold->fallback_live, live->fallback_live, SFTL_MAX_SUBBLOCKS); + bitmap_copy(cold->fallback_occupied, live->fallback_occupied, SFTL_MAX_SUBBLOCKS); + } + for (i = 0; i < cold->geo->subblocks; i++) { + if (cold->roles[i] == SFTL_CONTEXT) { + if ((i != new_site && !test_bit(i, live->reserved)) || + test_bit(i, cold->checkpoint_used) || test_bit(i, cold->vfl_reserved) || + test_bit(i, cold->unknown_lane_flags)) { + ret = -ESTALE; + goto out; + } + __set_bit(i, cold->reserved); + } else if (!prune && test_bit(i, live->reserved) && test_bit(i, live->fallback_live)) { + __set_bit(i, cold->reserved); + } + } + cold->sequence = cold->journal_sequence = cold->checkpoint_sequence = image->sequence; + cold->checkpoint_start = (prune || live->checkpoint_start) ? image->first_sequence : 0; + cold->pool->maps_complete = true; + cold->pool->oldest_base = cold->checkpoint_start ?: live->pool->oldest_base; + if (prune) + ret = sftl_prune_replay(live, cold, prune); + else + ret = sftl_gc_check_journal(live, cold, old_site, new_site, image->first_sequence); + sftl_free_windows(cold); + if (!ret) { + *out = cold; + cold = NULL; + } +out: + kvfree(records.items); + apple_sftl_free(cold); + return ret; +} + +/* A later erase must not have disturbed any page of the replacement. */ +static int sftl_gc_check_image(struct apple_sftl *cold, const struct apple_sftl_checkpoint *image, + u32 site) +{ + u32 i, page = U32_MAX, start = site * sftl_stride(cold); + unsigned int chunk; + int ret; + + for (i = 0; i < image->count; i++) { + ret = sftl_read_record(cold, start + i, &page, &chunk); + if (ret) + return ret; + if (!sftl_record_matches(&image->records[i], cold->oob + chunk * SFTL_META, + cold->page + chunk * SFTL_CHUNK)) + return -EBADMSG; + } + return 0; +} + +static bool sftl_gc_map_matches(const struct apple_sftl *cold, + const struct apple_sftl_snapshot *expected) +{ + struct rb_node *node; + u32 i = 0; + + if (cold->nr_runs != expected->nr_runs) + return false; + for (node = rb_first(&cold->runs); node; node = rb_next(node)) { + const struct sftl_run *run = rb_entry(node, struct sftl_run, node); + const struct apple_sftl_extent *want = &expected->runs[i++]; + + if (run->start != want->logical || run->end - run->start != want->length || + run->provider != want->provider) + return false; + } + return true; } -/* Read up to four live pages for relocation; a short tail repeats the last. */ -static int sftl_load_move(struct apple_sftl *sftl, const u32 *keys, u32 count, u32 first) +static int sftl_snapshot_raw(struct apple_sftl *sftl, size_t max_bytes, + struct apple_sftl_snapshot **out); + +static int sftl_prune_compare(struct apple_sftl *live, struct apple_sftl *cold, + const struct apple_sftl_snapshot *snap) { - unsigned int c, chunk; + u32 i, page = U32_MAX; + unsigned int chunk; int ret; - for (c = 0; c < 4; c++) { - u32 key = keys[min(first + c, count - 1)]; - const struct sftl_run *run = sftl_find(sftl, key); - const u8 *meta; - - if (!run || run->provider == SFTL_UNMAPPED) - return -EBADMSG; - ret = sftl_read_address(sftl, run->provider + key - run->start, &chunk); + if (!cold->pool || !cold->pool->maps_complete || cold->tolerated || + cold->context_degraded || !sftl_vfl_matches(live, cold) || + cold->checkpoint_sequence != snap->checkpoint_sequence || + cold->sequence != snap->sequence || cold->journal_sequence != snap->journal_sequence || + cold->context.count != snap->nr_opaque || !sftl_gc_map_matches(cold, snap)) + return -ESTALE; + for (i = 0; i < cold->context.count; i++) { + u32 address = cold->context.items[i].address; + + if (address != live->context.items[i].address) + return -ESTALE; + ret = sftl_read_record(cold, address, &page, &chunk); if (ret) return ret; - meta = sftl->oob + chunk * SFTL_META; - if ((meta[0] != 1 && meta[0] != 2) || get_unaligned_le32(meta + 8) != key) + if (!sftl_record_matches(&snap->opaque[i], cold->oob + chunk * SFTL_META, + cold->page + chunk * SFTL_CHUNK)) return -EBADMSG; - memcpy(sftl->move + c * SFTL_CHUNK, sftl->page + chunk * SFTL_CHUNK, SFTL_CHUNK); - memcpy(sftl->move_oob + c * SFTL_META, meta, SFTL_META); } return 0; } -/* Move everything out of the given-up blocks. Another failure gives up the - * new block as well and starts over from the map. - */ -static int sftl_evacuate(struct apple_sftl *sftl) +static int sftl_prune_reopen(struct apple_sftl *live, const struct apple_sftl_snapshot *snap, + unsigned long deadline, bool before_erase, struct apple_sftl **out) { - u32 *keys = NULL, count = 0, i; - int ret = 0; + int ret = sftl_load(live->ppn, out, deadline ?: 1, before_erase ? live : NULL, + false, NULL); - while (sftl->evacuate && !ret) { - sftl->evacuate = false; - kvfree(keys); - ret = sftl_collect_abandoned(sftl, &keys, &count); - for (i = 0; !ret && i < count && !sftl->evacuate; i += 4) { - ret = sftl_load_move(sftl, keys, count, i); - if (ret) { - sftl->failed = true; - break; - } - ret = sftl_append_once(sftl, sftl->move, sftl->move_oob, true); - if (ret == SFTL_RETRY) - ret = 0; - } - } - /* Leave unfinished work for the next request unless the writer stopped. */ - if (ret && !sftl->failed) - sftl->evacuate = true; - kvfree(keys); - return ret; + return ret ?: sftl_prune_compare(live, *out, snap); } -static int sftl_append(struct apple_sftl *sftl, const u8 *page, u8 *oob, bool relocated) +/* 0x80dd10e0: retire obsolete context sites only after a newer verified + * generation exists. Never clear a fallback bit to manufacture free space. + * A fresh load or ordinary checkpoint adoption supplies this one-shot list. + */ +static int sftl_prune_fallbacks(struct apple_sftl *sftl) { - int ret; + struct sftl_reclaim_pool *pool = sftl->pool; + struct apple_sftl_snapshot *snap = NULL; + struct apple_sftl *cold = NULL; + struct apple_sftl_checkpoint image = {}; + u32 active, cached = U32_MAX; + unsigned int chunk; + u16 sites[SFTL_MAX_CONTEXTS], nr = pool->nr_fallback_sites; + unsigned long deadline = jiffies + SFTL_CLAIM_TIMEOUT; + u32 i, block; + struct sftl_prune_scan scan = {}; + bool blank, pinned = false, targeted = true; + int ret = 0; - do { - ret = sftl_evacuate(sftl); + memcpy(sites, pool->fallback_sites, nr * sizeof(*sites)); + pool->nr_fallback_sites = 0; + if (!pool->maps_complete || sftl->failed || sftl->tolerated || sftl->failures || + sftl->append_block != U32_MAX || pool->gc_count || + sftl->journal_sequence != sftl->sequence) + return 0; + for_each_set_bit(block, sftl->fallback_live, sftl_data_limit(sftl)) + if (pool->media_kind[block] == SFTL_MEDIA_DATA_FOOTER) { + pinned = true; + break; + } + if (!pinned) + return 0; + for (i = 0; i < nr; i++) { + block = sites[i]; + if (!sftl_owns_context_block(sftl, block) || sftl->roles[block] != SFTL_CONTEXT || + sftl->wear[block] >= 0xfffe || pool->valid[block] || + test_bit(block, sftl->abandoned) || test_bit(block, sftl->torn) || + test_bit(block, pool->saved_live)) + return 0; + } + mutex_lock(&sftl_save_lock); + ret = sftl_snapshot_raw(sftl, SFTL_GC_MAP_BYTES, &snap); + if (ret) + goto out; +retry_before: + if (targeted) + ret = sftl_load(sftl->ppn, &cold, deadline ?: 1, sftl, false, &scan.heads); + else + ret = sftl_prune_reopen(sftl, snap, deadline, true, &cold); + if (ret) + goto before_error; + if (!cold->pool || !cold->pool->maps_complete || cold->context_degraded || + !sftl_vfl_matches(sftl, cold) || !cold->native_context || !cold->context.count || + cold->context.items[0].stamp != sftl->context.items[0].stamp || + cold->checkpoint_sequence != snap->checkpoint_sequence || + cold->pool->nr_fallback_sites != nr || + memcmp(sites, cold->pool->fallback_sites, nr * sizeof(*sites))) { + ret = -ESTALE; + goto before_error; + } + /* The independently selected one-site generation is contiguous. + * Preserve the actual encoded map, including its batching/padding, for + * the same exact post-erase comparison as a newly staged GC image. + */ + active = cold->context.items[0].address / sftl_stride(cold); + image.first_sequence = cold->context.items[0].stamp & SFTL_SEQUENCE; + image.sequence = cold->checkpoint_sequence; + if (image.sequence < image.first_sequence || + image.sequence - image.first_sequence >= sftl_slots(cold, cold->lanes[active])) { + ret = -ESTALE; + goto before_error; + } + image.count = image.sequence - image.first_sequence + 1; + image.records = kvmalloc_array(image.count, sizeof(*image.records), GFP_NOIO); + if (!image.records) { + ret = -ENOMEM; + goto before_error; + } + for (i = 0; i < image.count; i++) { + ret = sftl_read_record(cold, active * sftl_stride(cold) + i, &cached, &chunk); + if (ret) + goto before_error; + memcpy(image.records[i].data, cold->page + chunk * SFTL_CHUNK, SFTL_CHUNK); + memcpy(image.records[i].meta, cold->oob + chunk * SFTL_META, SFTL_META); + } + if (targeted) { + /* All obsolete sites are still intact. Build the private state + * for their removal, then compare it with the original snapshot. + */ + /* Keep the head classification, release the duplicate map. */ + sftl_clear_runs(cold); + scan.roots = cold; + cold = NULL; + ret = sftl_gc_load_new(sftl, &image, 0, active, deadline, &scan, &cold); + apple_sftl_free(scan.roots); + kfree(scan.heads); + scan.heads = NULL; if (!ret) - ret = sftl_append_once(sftl, page, oob, relocated); - } while (ret == SFTL_RETRY); - if (!ret) - ret = sftl_evacuate(sftl); + ret = sftl_prune_compare(sftl, cold, snap); + if (ret) + goto before_error; + } else { + apple_sftl_free(cold); + cold = NULL; + } + for (i = nr; i; i--) { + block = sites[i - 1]; + ret = sftl_erase_verified(sftl, block, sftl->lanes[block], deadline); + if (!ret) + ret = sftl_block_blank(sftl, block, deadline, &blank); + if (ret || !blank) { + ret = ret ?: -EBADMSG; + goto fail_stop; + } + } + if (targeted) { + ret = sftl_gc_check_vfl(sftl, cold); + if (!ret) + ret = sftl_gc_check_image(cold, &image, active); + if (ret) { + pr_warn("apple-sftl: prune targeted check failed after erase (%d), reopening\n", ret); + apple_sftl_free(cold); + cold = NULL; + targeted = false; + } + } + if (!targeted) { + ret = sftl_prune_reopen(sftl, snap, deadline, false, &cold); + if (!ret) + ret = sftl_gc_check_image(cold, &image, active); + } + if (ret || cold->checkpoint_start != (cold->context.items[0].stamp & SFTL_SEQUENCE)) { + ret = ret ?: -ESTALE; + goto fail_stop; + } + sftl_scan_reuse(cold); + sftl_adopt_checkpoint(sftl, cold); + for (i = 0; i < nr; i++) { + block = sites[i]; + sftl_set_role(sftl, block, SFTL_CLEAN_FREE); + sftl->wear[block]++; + sftl->block_flags[block] = 0; + __set_bit(block, sftl->linux_erased); + } + gc_fallback_retired += nr; + pr_info("apple-sftl: prune verify=%s retired=%u\n", targeted ? "targeted" : "full", nr); + goto out; +before_error: + if (targeted) { + pr_warn("apple-sftl: prune targeted check failed before erase (%d), reopening\n", ret); + apple_sftl_free(cold); + cold = NULL; + kvfree(image.records); + image.records = NULL; + cached = U32_MAX; + kfree(scan.heads); + scan.heads = NULL; + targeted = false; + goto retry_before; + } + goto out; +fail_stop: + sftl->failed = true; +out: + mutex_unlock(&sftl_save_lock); + kvfree(image.records); + apple_sftl_free(cold); + apple_sftl_snapshot_free(snap); return ret; } -int apple_sftl_write(struct apple_sftl *sftl, u32 logical_page, - const u8 *data, unsigned int count) +static int sftl_write_checkpoint_locked(struct apple_sftl *sftl, + struct apple_sftl_checkpoint_report *rep, bool gc) { - unsigned int chunk; + struct sftl_move move = { + .sftl = sftl, .deadline = jiffies + (gc ? SFTL_GC_SAVE_TIMEOUT : SFTL_CLAIM_TIMEOUT), + }; + struct apple_sftl_checkpoint *image = NULL, *readback = NULL; + struct apple_sftl_snapshot *snap = NULL, *cold_snap = NULL; + struct apple_sftl_layout layout; + struct apple_sftl *cold = NULL; + u32 stride, new_ctx = U32_MAX; + u32 old_site, block, pass, final_site; + u8 *e; + bool targeted = gc; + ktime_t verify_start = 0; + s64 before_erase_ms = 0; int ret; - if (!sftl || !data || !count || count > 4 || logical_page >= sftl->geo->disk_pages || - count > sftl->geo->disk_pages - logical_page) - return -EINVAL; - /* The append path is written for four chunks a page. */ - if (sftl->lpp != 4 || !sftl->geo->writer) - return -EROFS; - mutex_lock(&sftl->lock); + memset(rep, 0, sizeof(*rep)); + rep->old_ctx = U32_MAX; + rep->new_ctx = U32_MAX; + if (sftl->pool && (n42_saves >= SFTL_N42_SAVES || (gc && (gc_saves >= SFTL_GC_SAVES || + n42_saves >= SFTL_N42_SAVES - 1)))) + return -ENOSPC; + stride = sftl_stride(sftl); if (sftl->failed) { ret = -EIO; goto out; } - if (sftl->sequence > SFTL_SEQUENCE - 4) { - ret = -EOVERFLOW; + if (!sftl->native_context || sftl->geo->context_names != 1 || + (sftl->nr_torn && !sftl->geo->torn_in_place) || + sftl->evacuate || (!gc && sftl->append_block != U32_MAX) || + sftl->journal_sequence != sftl->sequence || !sftl->context.count || + !apple_sftl_layout_for_subblocks(sftl->geo->subblocks, &layout)) { + ret = -EOPNOTSUPP; goto out; } - ret = sftl_writer_prepare(sftl); + ret = sftl_writer_prepare(sftl, false); if (ret) goto out; - for (chunk = 0; chunk < 4; chunk++) { - unsigned int index = min(chunk, count - 1); + final_site = sftl->pool ? sftl->pool->context_site : 0; + rep->old_ctx = sftl->context.items[0].address / stride; + rep->old_ckpt_seq = sftl->checkpoint_sequence; + rep->seq_before = sftl->sequence; + ret = sftl_snapshot_locked(sftl, SFTL_GC_MAP_BYTES, &snap); + if (ret) + goto out; + if (snap->nr_opaque != layout.opaque_records || + get_unaligned_le32(snap->opaque[0].data) != 1 || + get_unaligned_le32(snap->opaque[0].data + 4) != rep->old_ctx) { + ret = -EBADMSG; + goto out; + } + /* + * A verified blank clean-free block (every page checked), or with + * dirty-free reuse a block erased here, so the native clean pool is + * left to iOS. + */ + if (sftl->pool || sftl->reuse_dirty) + ret = sftl_reuse_blank_dirty(sftl, &new_ctx, move.deadline, + gc ? SFTL_CLAIM_GC_CONTEXT : SFTL_CLAIM_CONTEXT); + else + ret = sftl_take_blank(sftl, &new_ctx, move.deadline); + if (ret) + goto out; + rep->new_ctx = new_ctx; + e = snap->opaque[layout.sb_start + new_ctx / (SFTL_CHUNK / 8)].data + + (new_ctx % (SFTL_CHUNK / 8)) * 8; + if ((e[0] != SFTL_CLEAN_FREE && + !(e[0] == SFTL_DIRTY_FREE && test_bit(new_ctx, sftl->linux_erased)) && + !(sftl->pool && sftl->roles[new_ctx] == SFTL_CONTEXT && + (gc ? new_ctx == sftl->pool->gc_site : + sftl->pool->context_claimed && new_ctx == final_site))) || + new_ctx == rep->old_ctx) { + ret = -EBADMSG; + goto out; + } + if (gc) { + ret = sftl_native_sites(sftl, snap, &new_ctx, &old_site, move.deadline); + if (ret || old_site != rep->old_ctx) { + ret = ret ?: -EBADMSG; + goto out; + } + } + ret = sftl_ckpt_reconcile(sftl, snap, &layout, new_ctx, rep); + if (ret) + goto out; + e[0] = SFTL_CONTEXT; + e[1] = 0; + if (test_bit(new_ctx, sftl->linux_erased)) + put_unaligned_le16(sftl->wear[new_ctx], e + 6); + ret = apple_sftl_checkpoint_build(snap, &new_ctx, 1, + sftl_slots(sftl, sftl->lanes[new_ctx]), &image); + if (ret) + goto out; + rep->nr_records = image->count; + rep->nr_pages = image->count / 4; + rep->nr_runs = snap->nr_runs; + if (sftl->pool) { + n42_saves++; + if (gc) + gc_saves++; + } + ret = apple_sftl_checkpoint_stage(image, new_ctx, sftl->lanes[new_ctx], + &sftl_context_io, &move, &readback); + if (!ret && (readback->count != image->count || + memcmp(readback->records, image->records, + array_size(image->count, sizeof(*image->records))))) + ret = -EBADMSG; + if (ret) { + /* No recovery path may accept a partial program. A failed + * readback after the last program can be checked independently. + */ + if (!gc || move.context_pages_programmed != rep->nr_pages) + goto failed; + pr_warn("apple-sftl: GC checkpoint stage readback failed (%d), verifying by full recovery\n", + ret); + targeted = false; + } + /* The new records consumed their sequences. */ + sftl->sequence = image->sequence; + sftl->journal_sequence = image->sequence; + + /* The next load must select the new generation with the identical map. */ + verify_start = ktime_get(); + for (pass = 0; ; pass++) { +retry_verify: + if (targeted && pass) { + ret = sftl_gc_check_vfl(sftl, cold); + if (!ret) + ret = sftl_gc_check_image(cold, image, new_ctx); + if (!ret) + break; + } else if (targeted) { + ret = sftl_gc_load_new(sftl, image, old_site, new_ctx, move.deadline, + NULL, &cold); + } else { + ret = sftl_load(sftl->ppn, &cold, gc ? (move.deadline ?: 1) : 0, NULL, + false, NULL); + if (!ret && gc) + ret = sftl_gc_check_image(cold, image, new_ctx); + } + if (!ret && !gc) + ret = sftl_snapshot_locked(cold, SFTL_GC_MAP_BYTES, &cold_snap); + if (ret) + goto verify_error; + if (!cold->native_context || cold->vfl_degraded || cold->context_degraded || + (sftl->pool && (!cold->pool || + memcmp(sftl->lanes, cold->lanes, sizeof(sftl->lanes)))) || + (gc && (memcmp(sftl->vfl_reserved, cold->vfl_reserved, sizeof(sftl->vfl_reserved)) || + memcmp(sftl->unknown_lane_flags, cold->unknown_lane_flags, + sizeof(sftl->unknown_lane_flags)))) || + (gc && (!cold->pool->maps_complete || cold->tolerated || + (sftl->append_block != U32_MAX && + cold->roles[sftl->append_block] != SFTL_OPEN_DATA))) || + cold->checkpoint_sequence != image->sequence || + cold->sequence != image->sequence || cold->journal_sequence != image->sequence || + cold->context.items[0].address != new_ctx * stride || + cold->roles[new_ctx] != SFTL_CONTEXT || cold->roles[rep->old_ctx] != SFTL_CONTEXT || + (gc ? !sftl_gc_map_matches(cold, snap) : + (cold_snap->nr_runs != snap->nr_runs || + memcmp(cold_snap->runs, snap->runs, array_size(snap->nr_runs, sizeof(*snap->runs)))))) { + ret = -EBADMSG; + goto verify_error; + } + if (!gc || pass) + break; + /* Recover the replacement with the old base intact. Only its + * exclusive one-site generation was proved by native_sites. + */ + if (!sftl_owns_context_block(cold, old_site) || + !sftl_owns_context_block(cold, new_ctx)) { + ret = -EBADMSG; + goto verify_error; + } + before_erase_ms = ktime_ms_delta(ktime_get(), verify_start); + ret = sftl_erase_verified(sftl, old_site, cold->lanes[old_site], move.deadline); + if (ret) + goto failed; + verify_start = ktime_get(); + if (!targeted) { + apple_sftl_free(cold); + cold = NULL; + } + continue; +verify_error: + if (!targeted) + goto failed; + pr_warn("apple-sftl: GC checkpoint check failed (%d, pass %u), verifying by full recovery\n", + ret, pass + 1); + apple_sftl_snapshot_free(cold_snap); + cold_snap = NULL; + apple_sftl_free(cold); + cold = NULL; + targeted = false; + goto retry_verify; + } + if (gc) { + bool blank; - memcpy(sftl->stage + chunk * SFTL_CHUNK, data + index * SFTL_CHUNK, SFTL_CHUNK); - sftl_data_meta(sftl->stage_oob + chunk * SFTL_META, 0, logical_page + index); + /* sftl_erase_verified checked every lane's erase status before + * the second verification pass. Probe both ends of the old site + * before publishing the replacement checkpoint. + */ + ret = sftl_blank_ends(sftl, old_site, &blank); + if (ret) + goto failed; + if (!blank) + goto bad; + for_each_set_bit(block, sftl->pool->gc_pending, sftl_data_limit(sftl)) + if (cold->pool->valid[block] || cold->roles[block] != SFTL_DIRTY_FREE || + !sftl_reuse_permitted(cold, block)) + goto bad; + /* Same media under the write lock, same lanes, verified replacement. + * Carry untouched erase certificates, rechecking all new owners. + */ + for (block = 1; block < sftl_data_limit(sftl); block++) { + if (sftl->pool->lanes[block] != cold->lanes[block] || + cold->pool->valid[block] || !sftl_reuse_available(sftl, block) || + !sftl_reuse_permitted(cold, block)) + continue; + if (test_bit(block, sftl->pool->runtime_retired) && + cold->roles[block] == sftl->roles[block]) + __set_bit(block, cold->pool->runtime_retired); + if (sftl_reuse_available(cold, block)) { + cold->pool->lanes[block] = cold->lanes[block]; + __assign_bit(block, cold->pool->unchecked, + test_bit(block, sftl->pool->unchecked)); + } + } + if (!cold->pool->lanes[final_site]) + goto bad; + for_each_set_bit(block, sftl->pool->gc_pending, sftl_data_limit(sftl)) { + sftl_set_role(cold, block, SFTL_CLOSED_DATA); + cold->block_flags[block] = sftl->block_flags[block]; + __set_bit(block, cold->pool->runtime_data); + __clear_bit(block, cold->pool->boot_retired); + sftl_retire_runtime(cold, block); + if (!test_bit(block, cold->pool->runtime_retired)) + goto bad; + } + } + rep->new_ckpt_seq = cold->checkpoint_sequence; + rep->seq_after = cold->sequence; + if (gc) { + for_each_set_bit(block, sftl->pool->gc_pending, sftl_data_limit(sftl)) + __clear_bit(block, sftl->used); + gc_retired += sftl->pool->gc_count; + pr_info("apple-sftl: GC checkpoint verify=%s before_erase_ms=%lld after_erase_ms=%lld donors=%u\n", + targeted ? "targeted" : "full", before_erase_ms, + ktime_ms_delta(ktime_get(), verify_start), sftl->pool->gc_count); } - ret = sftl_append(sftl, sftl->stage, sftl->stage_oob, false); + sftl_adopt_checkpoint(sftl, cold); + if (sftl->pool) + bitmap_zero(sftl->linux_erased, SFTL_MAX_SUBBLOCKS); + if (gc) { + sftl->pool->context_site = final_site; + /* The replacement table preceded retirement of the old site. + * Carry its successful erase into the next ordinary checkpoint. + */ + sftl_set_role(sftl, old_site, SFTL_CLEAN_FREE); + sftl->block_flags[old_site] = 0; + sftl->wear[old_site]++; + __set_bit(old_site, sftl->linux_erased); + } + __set_bit(new_ctx, sftl->used); + ret = 0; + goto out; +bad: + ret = -EBADMSG; +failed: + /* A partly written or unverified generation: no more writes this session. */ + sftl->failed = true; out: - mutex_unlock(&sftl->lock); + apple_sftl_snapshot_free(cold_snap); + apple_sftl_free(cold); + apple_sftl_checkpoint_free(readback); + apple_sftl_checkpoint_free(image); + apple_sftl_snapshot_free(snap); + return ret; } -EXPORT_SYMBOL_GPL(apple_sftl_write); -int apple_sftl_flush(struct apple_sftl *sftl) +static int sftl_gc_save(struct apple_sftl *sftl) { + struct apple_sftl_checkpoint_report report; int ret; - if (!sftl) + mutex_lock(&sftl_save_lock); + ret = sftl_write_checkpoint_locked(sftl, &report, true); + if (ret == -EOPNOTSUPP || ret == -EBADMSG || ret == -ERANGE) + gc_refuse_checkpoint(report.new_ctx == U32_MAX ? sftl->pool->gc_site : report.new_ctx, ret); + mutex_unlock(&sftl_save_lock); + return ret; +} + +int apple_sftl_write_checkpoint(struct apple_sftl *sftl, + struct apple_sftl_checkpoint_report *rep) +{ + int ret; + + if (!sftl || !rep) return -EINVAL; mutex_lock(&sftl->lock); - /* Each program is complete and verified before apple_sftl_write returns. */ - ret = sftl->failed ? -EIO : 0; + if (sftl->pool) + mutex_lock(&sftl_save_lock); + ret = sftl_write_checkpoint_locked(sftl, rep, false); + if (sftl->pool) + mutex_unlock(&sftl_save_lock); mutex_unlock(&sftl->lock); return ret; } -EXPORT_SYMBOL_GPL(apple_sftl_flush); +EXPORT_SYMBOL_GPL(apple_sftl_write_checkpoint); +#endif 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->read_only = sftl->vfl_degraded || sftl->context_degraded || !sftl_writer_enabled(sftl); + info->tolerated = sftl->tolerated; info->n42_install = sftl->geo->n42_install; info->logical_pages = sftl->geo->lpages; info->disk_pages = sftl->geo->disk_pages; @@ -3393,12 +7484,87 @@ void apple_sftl_get_info(struct apple_sftl *sftl, struct apple_sftl_info *info) } EXPORT_SYMBOL_GPL(apple_sftl_get_info); -static int sftl_snapshot_locked(struct apple_sftl *sftl, size_t max_bytes, +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) || \ + IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) +/* + * Turn on 12H321 blank dirty-free reuse for this instance (iPhone 5 rung 5): + * new data blocks and checkpoint sites come only from saved dirty-free + * blocks that read blank, are erased here and verified. The separate + * reclaim parameter enables certified reuse and transactional collection. + */ +int apple_sftl_set_reuse_dirty(struct apple_sftl *sftl, bool enable) +{ + int ret = 0; + + if (!sftl) + return -EINVAL; + mutex_lock(&sftl->lock); + if (enable && (!sftl->native_context || sftl->geo->context_names != 1 || + !sftl->geo->summary_sequences || !sftl->ppn->ops->erase_block || + sftl->checkpoint_ops)) + ret = -EOPNOTSUPP; + else + sftl->reuse_dirty = enable; + mutex_unlock(&sftl->lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sftl_set_reuse_dirty); + +/* Up to four allowed ranges; a request must lie inside one of them. */ +int apple_sftl_set_write_fences(struct apple_sftl *sftl, const u32 (*ranges)[2], u32 nr) +{ + u32 i; + + if (!sftl || nr > 4) + return -EINVAL; + mutex_lock(&sftl->lock); + sftl->write_fenced = true; + sftl->write_fence_start = nr ? ranges[0][0] : 0; + sftl->write_fence_end = nr ? ranges[0][1] : 0; + sftl->nr_write_fence_more = nr ? nr - 1 : 0; + for (i = 1; i < nr; i++) { + sftl->write_fence_more[i - 1][0] = ranges[i][0]; + sftl->write_fence_more[i - 1][1] = ranges[i][1]; + } + mutex_unlock(&sftl->lock); + return 0; +} +EXPORT_SYMBOL_GPL(apple_sftl_set_write_fences); + +u32 apple_sftl_get_write_fences(struct apple_sftl *sftl, u32 (*ranges)[2]) +{ + u32 i, nr; + + mutex_lock(&sftl->lock); + ranges[0][0] = sftl->write_fence_start; + ranges[0][1] = sftl->write_fence_end; + for (i = 0; i < sftl->nr_write_fence_more; i++) { + ranges[i + 1][0] = sftl->write_fence_more[i][0]; + ranges[i + 1][1] = sftl->write_fence_more[i][1]; + } + nr = 1 + sftl->nr_write_fence_more; + mutex_unlock(&sftl->lock); + return nr; +} +EXPORT_SYMBOL_GPL(apple_sftl_get_write_fences); + +#endif + +#if IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) +void apple_sftl_test_enable_writer(struct apple_sftl *sftl) +{ + if (sftl) + sftl->test_writer = true; +} +EXPORT_SYMBOL_GPL(apple_sftl_test_enable_writer); +#endif + +static int sftl_snapshot_raw(struct apple_sftl *sftl, size_t max_bytes, struct apple_sftl_snapshot **out) { struct apple_sftl_snapshot *snapshot; size_t map_bytes, context_bytes; - u32 i = 0; + u32 i = 0, page = U32_MAX; unsigned int chunk; int ret = 0; @@ -3433,7 +7599,7 @@ static int sftl_snapshot_locked(struct apple_sftl *sftl, size_t max_bytes, const struct sftl_record *reference = &sftl->context.items[i]; struct apple_sftl_context_record *record = &snapshot->opaque[i]; - ret = sftl_read_address(sftl, reference->address, &chunk); + ret = sftl_read_record(sftl, reference->address, &page, &chunk); if (ret) { sftl->failed = true; goto failed; @@ -3447,11 +7613,6 @@ static int sftl_snapshot_locked(struct apple_sftl *sftl, size_t max_bytes, memcpy(record->data, sftl->page + chunk * SFTL_CHUNK, SFTL_CHUNK); } snapshot->nr_opaque = sftl->context.count; - if (sftl->closed_user_seq) { - ret = apple_sftl_account_user_seq(snapshot, sftl->closed_user_seq); - if (ret) - goto failed; - } *out = snapshot; goto unlock; failed: @@ -3459,6 +7620,22 @@ static int sftl_snapshot_locked(struct apple_sftl *sftl, size_t max_bytes, unlock: return ret; } + +static int sftl_snapshot_locked(struct apple_sftl *sftl, size_t max_bytes, + struct apple_sftl_snapshot **out) +{ + int ret = sftl_snapshot_raw(sftl, max_bytes, out); + + if (!ret && sftl->closed_user_seq) { + ret = apple_sftl_account_user_seq(*out, sftl->closed_user_seq); + if (ret) { + apple_sftl_snapshot_free(*out); + *out = NULL; + } + } + return ret; +} + int apple_sftl_snapshot(struct apple_sftl *sftl, size_t max_bytes, struct apple_sftl_snapshot **out) { @@ -3469,8 +7646,8 @@ int apple_sftl_snapshot(struct apple_sftl *sftl, size_t max_bytes, *out = NULL; return -EINVAL; } - /* Snapshot extents use the 64 GB address layout of the reclaim planner. */ - if (!sftl->geo->writer) { + /* Snapshot extents use the modelled 64 GB or 16 GB address layouts. */ + if (!sftl->geo->writer && !sftl->geo->summary_sequences) { *out = NULL; return -EOPNOTSUPP; } @@ -3480,3 +7657,69 @@ int apple_sftl_snapshot(struct apple_sftl *sftl, size_t max_bytes, return ret; } EXPORT_SYMBOL_GPL(apple_sftl_snapshot); + +/* + * Read-only diagnostic inspection of any loaded geometry, including profiles + * whose writer is not modelled yet (16 GB 12H321) and degraded VFL states + * where the second VFL bank is erased. Never modifies media or writer state. + */ +int apple_sftl_inspect(struct apple_sftl *sftl, size_t max_bytes, + struct apple_sftl_inspect *info, + struct apple_sftl_snapshot **snapshot_out) +{ + u32 block; + int ret = 0; + + if (!sftl || !info) + return -EINVAL; + if (snapshot_out) + *snapshot_out = NULL; + memset(info, 0, sizeof(*info)); + + mutex_lock(&sftl->lock); + if (sftl->failed) { + ret = -EIO; + goto unlock; + } + info->vfl_source = sftl->vfl_source; + info->buses = sftl->geo->buses; + info->caus = sftl->geo->caus; + info->lanes = sftl->geo->lanes; + info->blocks = sftl->geo->blocks; + info->pages = sftl->geo->pages; + info->subblocks = sftl->geo->subblocks; + info->vfl_pages = sftl->geo->vfl_pages; + info->vfl_first = sftl->geo->vfl_first; + info->map_batch = sftl->geo->map_batch; + info->stride = sftl_stride(sftl); + info->disk_pages = sftl->geo->disk_pages; + info->lpages = sftl->geo->lpages; + info->nr_equal = sftl->nr_equal; + info->nr_torn = sftl->nr_torn; + info->torn_in_place = sftl->geo->torn_in_place; + info->append_block = sftl->append_block; + info->append_position = sftl->append_position; + info->checkpoint_start = sftl->checkpoint_start; + info->vfl_degraded = sftl->vfl_degraded; + info->context_degraded = sftl->context_degraded; + info->native_context = sftl->native_context; + memcpy(info->block_lanes, sftl->lanes, + sftl->geo->blocks * sizeof(info->block_lanes[0])); + memcpy(info->roles, sftl->roles, sftl->geo->subblocks); + memcpy(info->block_flags, sftl->block_flags, sftl->geo->subblocks); + memcpy(info->wear, sftl->wear, + sftl->geo->subblocks * sizeof(info->wear[0])); + for (block = 1; block < sftl->geo->subblocks; block++) { + if (!test_bit(block, sftl->reserved) && + sftl->roles[block] != SFTL_CONTEXT) + continue; + if (info->nr_context_blocks < ARRAY_SIZE(info->context_blocks)) + info->context_blocks[info->nr_context_blocks++] = block; + } + if (snapshot_out) + ret = sftl_snapshot_locked(sftl, max_bytes, snapshot_out); +unlock: + mutex_unlock(&sftl->lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sftl_inspect); diff --git a/drivers/mtd/apple-sftl-provider.h b/drivers/mtd/apple-sftl-provider.h index 7169109255e704..a46c30b464ea8f 100644 --- a/drivers/mtd/apple-sftl-provider.h +++ b/drivers/mtd/apple-sftl-provider.h @@ -2,8 +2,24 @@ #ifndef _APPLE_SFTL_PROVIDER_H #define _APPLE_SFTL_PROVIDER_H +#include +#include #include +static inline bool apple_sftl_provider_can_batch(const struct apple_ppn *ppn) +{ + return ppn->ops->read_pages && (!ppn->ops->read_pages_enabled || + ppn->ops->read_pages_enabled(ppn->priv)); +} + +static inline int apple_sftl_provider_read_pages(struct apple_ppn *ppn, + struct apple_ppn_read *pages, unsigned int n) +{ + if (!ppn->ops->read_pages) + return -EOPNOTSUPP; + return ppn->ops->read_pages(ppn->priv, pages, n); +} + /* IOFlashStorage-730 provider records from the 64 GB P105. Start zeroed. * The provider must serialize updates/snapshots, observe every event since * the seed and call apple_sftl_provider_lost() if that continuity is lost. diff --git a/drivers/mtd/apple-sftl-reclaim-test.c b/drivers/mtd/apple-sftl-reclaim-test.c index 969af6857e8a29..3b2d9cedd5ec29 100644 --- a/drivers/mtd/apple-sftl-reclaim-test.c +++ b/drivers/mtd/apple-sftl-reclaim-test.c @@ -6,7 +6,9 @@ #include #include +#include "apple-sftl-account.h" #include "apple-sftl-reclaim.h" +#include "apple-sftl-test-fixture.h" static void reclaim_source(struct apple_sftl_snapshot *snapshot, struct apple_sftl_context_record *opaque, @@ -456,6 +458,84 @@ static void reclaim_copy_live_pages(struct kunit *test) } } +static void reclaim_16gb_n42_checkpoint_and_gc(struct kunit *test) +{ + struct apple_sftl_context_record *opaque; + struct apple_sftl_extent runs[2], recovered_runs[2]; + struct apple_sftl_snapshot snapshot = {}, recovered; + struct apple_sftl_checkpoint *image = NULL; + struct apple_sftl_gc *gc = NULL; + struct apple_sftl_gc_block victim = { + .block = 4, .lanes = 0xf, .footer_chunks = 4, .closed = true, .last_sequence = 199, + }; + struct apple_sftl_gc_block dest = { .block = 7, .lanes = 0xf, .blank = true }; + const struct apple_sftl_gc_copy *copy; + u32 ctx_block = 532; + + opaque = kunit_kcalloc(test, APPLE_SFTL_16GB_ACCOUNT_RECORDS, + sizeof(*opaque), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, opaque); + apple_sftl_test_native_prefix_for(opaque, APPLE_SFTL_N42_SUBBLOCKS); + put_unaligned_le32(1, opaque[0].data); + put_unaligned_le32(495, opaque[0].data + 4); + opaque[8].data[4 * 8] = 3; + opaque[8].data[4 * 8 + 1] = 8; + opaque[8].data[7 * 8] = 1; + opaque[8].data[495 * 8] = 7; + opaque[9].data[(532 - 512) * 8] = 1; + + /* Place a live extent near the end of the 4096-slot block (past slot 2048, + * verifying lane_slots=1024 rather than 64 GB's 512). + */ + runs[0] = (struct apple_sftl_extent) { + .logical = 0, .length = 2, + .provider = 4 * APPLE_SFTL_16GB_STRIDE + 4088, + }; + runs[1] = (struct apple_sftl_extent) { + .logical = 2, .length = APPLE_SFTL_16GB_LOGICAL_PAGES - 2, + .provider = APPLE_SFTL_NO_ADDRESS, + }; + snapshot = (struct apple_sftl_snapshot) { + .runs = runs, .nr_runs = ARRAY_SIZE(runs), + .opaque = opaque, .nr_opaque = APPLE_SFTL_16GB_ACCOUNT_RECORDS, + .sequence = 200, .checkpoint_sequence = 100, .journal_sequence = 200, + .subblocks = APPLE_SFTL_N42_SUBBLOCKS, + .stride = APPLE_SFTL_16GB_STRIDE, + .logical_pages = APPLE_SFTL_16GB_LOGICAL_PAGES, + }; + KUNIT_ASSERT_EQ(test, apple_sftl_checkpoint_build(&snapshot, &ctx_block, 1, 64, &image), 0); + /* 24 opaque + min 32 map records (batch 16) = 56 records. */ + KUNIT_EXPECT_EQ(test, image->count, 56U); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(image->records[0].data), 1U); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(image->records[0].data + 4), 532U); + /* Unmapped sentinel on 16 GB must be 0x7fffff. */ + KUNIT_EXPECT_EQ(test, get_unaligned_le32(image->records[24].data + 16), 0x7fffffU); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(image->records[25].data), U32_MAX); + apple_sftl_checkpoint_free(image); + image = NULL; + + /* Plan and verify a 16 GB GC transaction (24 opaque records = 98,688 B). */ + KUNIT_ASSERT_EQ(test, apple_sftl_gc_plan(&snapshot, &victim, &dest, 64, 131072, &gc), 0); + copy = apple_sftl_gc_next_copy(gc); + KUNIT_ASSERT_NOT_NULL(test, copy); + KUNIT_EXPECT_EQ(test, copy->source, 4 * APPLE_SFTL_16GB_STRIDE + 4088); + KUNIT_EXPECT_EQ(test, copy->destination, 7 * APPLE_SFTL_16GB_STRIDE + 2); + KUNIT_ASSERT_EQ(test, apple_sftl_gc_copy_done(gc, copy, 204), 0); + KUNIT_ASSERT_EQ(test, apple_sftl_gc_checkpoint(gc, &ctx_block, 1, &image), 0); + KUNIT_EXPECT_EQ(test, image->count, 56U); + KUNIT_ASSERT_EQ(test, apple_sftl_gc_checkpoint_done(gc, image), 0); + memcpy(recovered_runs, runs, sizeof(runs)); + recovered_runs[0].provider = 7 * APPLE_SFTL_16GB_STRIDE + 2; + recovered = snapshot; + recovered.runs = recovered_runs; + recovered.sequence = image->sequence; + recovered.journal_sequence = image->sequence; + recovered.checkpoint_sequence = image->sequence; + KUNIT_ASSERT_EQ(test, apple_sftl_gc_recovered(gc, &recovered), 0); + apple_sftl_checkpoint_free(image); + apple_sftl_gc_free(gc); +} + static struct kunit_case reclaim_cases[] = { KUNIT_CASE(reclaim_copy_live_pages), KUNIT_CASE(reclaim_metadata_vector), @@ -466,6 +546,7 @@ static struct kunit_case reclaim_cases[] = { KUNIT_CASE(reclaim_gc_transaction), KUNIT_CASE(reclaim_gc_fail_stop), KUNIT_CASE(reclaim_obsolete_history_needs_checkpoint), + KUNIT_CASE(reclaim_16gb_n42_checkpoint_and_gc), {} }; diff --git a/drivers/mtd/apple-sftl-reclaim.c b/drivers/mtd/apple-sftl-reclaim.c index 70ebba4e4873ad..2ab562641d35d1 100644 --- a/drivers/mtd/apple-sftl-reclaim.c +++ b/drivers/mtd/apple-sftl-reclaim.c @@ -20,12 +20,11 @@ #include "apple-sftl-account.h" #define SFTL_SEQUENCE GENMASK_ULL(47, 0) -#define SFTL_PROVIDER (APPLE_SFTL_SUBBLOCKS * APPLE_SFTL_STRIDE) #define SFTL_PAIRS ((APPLE_SFTL_CHUNK - 8) / 8) #define SFTL_MAX_RECORDS (16U * APPLE_SFTL_STRIDE) -#define SFTL_UNMAPPED 0x1ffffffU struct apple_sftl_gc { + struct apple_sftl_layout layout; struct apple_sftl_snapshot snapshot; struct apple_sftl_gc_copy *copies; struct apple_sftl_checkpoint *checkpoint; @@ -50,12 +49,15 @@ int apple_sftl_context_meta(u8 *meta, u8 subtype, u64 sequence, } EXPORT_SYMBOL_GPL(apple_sftl_context_meta); -static int sftl_check_map(const struct apple_sftl_snapshot *snapshot) +static int sftl_check_map(const struct apple_sftl_snapshot *snapshot, + struct apple_sftl_layout *out) { + struct apple_sftl_layout layout; u32 cursor = 0, i; if (!snapshot || !snapshot->runs || !snapshot->nr_runs || - snapshot->nr_runs > APPLE_SFTL_LOGICAL_PAGES || + !apple_sftl_snapshot_layout(snapshot, &layout) || + snapshot->nr_runs > layout.logical_pages || snapshot->checkpoint_sequence > snapshot->sequence || snapshot->journal_sequence > snapshot->sequence || snapshot->sequence > SFTL_SEQUENCE) @@ -64,17 +66,22 @@ static int sftl_check_map(const struct apple_sftl_snapshot *snapshot) const struct apple_sftl_extent *run = &snapshot->runs[i]; if (run->logical != cursor || !run->length || - run->length > APPLE_SFTL_LOGICAL_PAGES - cursor || + run->length > layout.logical_pages - cursor || (run->provider != APPLE_SFTL_NO_ADDRESS && - (run->provider >= SFTL_PROVIDER || - run->length > SFTL_PROVIDER - run->provider))) + (run->provider >= layout.provider_limit || + run->length > layout.provider_limit - run->provider))) return -EBADMSG; cursor += run->length; } - return cursor == APPLE_SFTL_LOGICAL_PAGES ? 0 : -EBADMSG; + if (cursor != layout.logical_pages) + return -EBADMSG; + if (out) + *out = layout; + return 0; } -static int sftl_check_context(const struct apple_sftl_snapshot *snapshot) +static int sftl_check_context(const struct apple_sftl_snapshot *snapshot, + const struct apple_sftl_layout *layout) { u32 i, previous = 0, names; @@ -92,9 +99,9 @@ static int sftl_check_context(const struct apple_sftl_snapshot *snapshot) * when its geometry or accounting prefix is damaged. */ if (snapshot->nr_opaque >= 4 && snapshot->opaque[3].meta[1] == 1 && - (snapshot->nr_opaque != APPLE_SFTL_ACCOUNT_RECORDS || + (snapshot->nr_opaque != layout->opaque_records || get_unaligned_le32(snapshot->opaque[3].data + APPLE_SFTL_CHUNK - 4) != - APPLE_SFTL_SUBBLOCKS)) + layout->subblocks)) return -EOPNOTSUPP; names = get_unaligned_le32(snapshot->opaque[0].data); if (!names || names > 16) @@ -102,20 +109,23 @@ static int sftl_check_context(const struct apple_sftl_snapshot *snapshot) return 0; } -static bool sftl_native_context(const struct apple_sftl_snapshot *snapshot) +static bool sftl_native_context(const struct apple_sftl_snapshot *snapshot, + const struct apple_sftl_layout *layout) { const struct apple_sftl_context_record *base = snapshot->opaque; return snapshot->nr_opaque >= 4 && base[0].meta[1] == 1 && base[1].meta[1] == 1 && base[2].meta[1] == 1 && base[3].meta[1] == 1 && - get_unaligned_le32(base[3].data + APPLE_SFTL_CHUNK - 4) == APPLE_SFTL_SUBBLOCKS; + get_unaligned_le32(base[3].data + APPLE_SFTL_CHUNK - 4) == layout->subblocks; } static int sftl_checkpoint_count(const struct apple_sftl_snapshot *snapshot, - u32 max_records, u32 *count) + u32 max_records, struct apple_sftl_layout *layout_out, + u32 *count) { + struct apple_sftl_layout layout; u32 records; - int ret = sftl_check_map(snapshot); + int ret = sftl_check_map(snapshot, &layout); if (ret) return ret; @@ -123,20 +133,25 @@ static int sftl_checkpoint_count(const struct apple_sftl_snapshot *snapshot, snapshot->nr_opaque > SFTL_MAX_RECORDS || !max_records || max_records > SFTL_MAX_RECORDS) return -EINVAL; - ret = sftl_check_context(snapshot); + ret = sftl_check_context(snapshot, &layout); if (ret) return ret; records = (snapshot->nr_runs + SFTL_PAIRS - 1) / SFTL_PAIRS; - /* cxtNextBatch pads the measured 64 GB range stream to whole batches. */ - if (sftl_native_context(snapshot)) - records = (records + APPLE_SFTL_NATIVE_MAP_BATCH - 1) & - ~(APPLE_SFTL_NATIVE_MAP_BATCH - 1); + /* cxtNextBatch pads native range streams to whole batches with a + * profile-specific floor (64 on 13G36 64 GB; min 32, batch 16 on 12H321 16 GB). + */ + if (sftl_native_context(snapshot, &layout)) { + records = max(records, layout.map_min); + records = (records + layout.map_batch - 1) & ~(layout.map_batch - 1); + } records += snapshot->nr_opaque; records = (records + 3) & ~3U; if (records > max_records) return -ENOSPC; if (records > SFTL_SEQUENCE - snapshot->sequence) return -EOVERFLOW; + if (layout_out) + *layout_out = layout; *count = records; return 0; } @@ -165,19 +180,20 @@ static int sftl_checkpoint_build(const struct apple_sftl_snapshot *snapshot, bool preserve_cached_stats, struct apple_sftl_checkpoint **out) { struct apple_sftl_checkpoint *checkpoint; + struct apple_sftl_layout layout; u32 count, i, j, cursor = 0, run = 0, old_names; int ret; if (!out) return -EINVAL; *out = NULL; - ret = sftl_checkpoint_count(snapshot, max_records, &count); + ret = sftl_checkpoint_count(snapshot, max_records, &layout, &count); if (ret) return ret; if (!blocks || !nr_blocks || nr_blocks > 16) return -EINVAL; for (i = 0; i < nr_blocks; i++) { - if (!blocks[i] || blocks[i] >= APPLE_SFTL_SUBBLOCKS) + if (!blocks[i] || blocks[i] >= layout.subblocks) return -EINVAL; for (j = 0; j < i; j++) if (blocks[j] == blocks[i]) @@ -224,13 +240,13 @@ static int sftl_checkpoint_build(const struct apple_sftl_snapshot *snapshot, u32 address = extent->provider; if (address == APPLE_SFTL_NO_ADDRESS) - address = SFTL_UNMAPPED; + address = layout.unmapped_sentinel; put_unaligned_le32(address, record->data + 8 + j * 8); put_unaligned_le32(extent->length, record->data + 12 + j * 8); cursor += extent->length; } } - if (sftl_native_context(snapshot)) { + if (sftl_native_context(snapshot, &layout)) { ret = preserve_cached_stats ? apple_sftl_account_saved_map(checkpoint, snapshot) : apple_sftl_account_map(checkpoint, snapshot); if (ret) { @@ -265,9 +281,10 @@ static void sftl_gc_run(struct apple_sftl_snapshot *map, u32 logical, }; } -static bool sftl_gc_block_valid(const struct apple_sftl_gc_block *block) +static bool sftl_gc_block_valid(const struct apple_sftl_gc_block *block, + const struct apple_sftl_layout *layout) { - return block && block->block && block->block < APPLE_SFTL_SUBBLOCKS && + return block && block->block && block->block < layout->subblocks && block->lanes && !block->reserved && block->last_sequence <= SFTL_SEQUENCE; } @@ -276,6 +293,7 @@ int apple_sftl_gc_plan(const struct apple_sftl_snapshot *snapshot, const struct apple_sftl_gc_block *destination, u32 max_records, size_t max_bytes, struct apple_sftl_gc **out) { + struct apple_sftl_layout layout; struct apple_sftl_gc *gc; u32 start, end, dest, capacity, copied = 0, i, count, footer; size_t map_bytes, copy_bytes, opaque_bytes; @@ -284,29 +302,29 @@ int apple_sftl_gc_plan(const struct apple_sftl_snapshot *snapshot, if (!out) return -EINVAL; *out = NULL; - ret = sftl_checkpoint_count(snapshot, max_records, &count); + ret = sftl_checkpoint_count(snapshot, max_records, &layout, &count); if (ret) return ret; if (snapshot->sequence != snapshot->journal_sequence) return -EOPNOTSUPP; - if (!sftl_gc_block_valid(victim) || !sftl_gc_block_valid(destination) || + if (!sftl_gc_block_valid(victim, &layout) || !sftl_gc_block_valid(destination, &layout) || victim->blank || !victim->closed || !destination->blank || destination->last_sequence || victim->block == destination->block || victim->last_sequence > snapshot->sequence) return -EINVAL; - footer = victim->footer_chunks ? victim->footer_chunks : 32; - if (footer < 4 || footer > 32 || footer % 4) + footer = victim->footer_chunks ? victim->footer_chunks : layout.footer_max; + if (footer < 4 || footer > layout.footer_max || footer % 4) return -EINVAL; - start = victim->block * APPLE_SFTL_STRIDE; - end = start + hweight16(victim->lanes) * 512; - dest = destination->block * APPLE_SFTL_STRIDE; - /* Eight native footer pages remain available when the destination closes. */ - capacity = hweight16(destination->lanes) * 512 - 32; + start = victim->block * layout.stride; + end = start + hweight16(victim->lanes) * layout.lane_slots; + dest = destination->block * layout.stride; + /* Reserve the profile's maximum footer width when the destination closes. */ + capacity = hweight16(destination->lanes) * layout.lane_slots - layout.footer_max; for (i = 0; i < snapshot->nr_runs; i++) { const struct apple_sftl_extent *run = &snapshot->runs[i]; if (run->provider != APPLE_SFTL_NO_ADDRESS && - sftl_overlap(run->provider, run->length, dest, dest + APPLE_SFTL_STRIDE)) + sftl_overlap(run->provider, run->length, dest, dest + layout.stride)) return -EBADMSG; } map_bytes = array_size(snapshot->nr_runs * 3, sizeof(*gc->snapshot.runs)); @@ -318,9 +336,13 @@ int apple_sftl_gc_plan(const struct apple_sftl_snapshot *snapshot, gc = kzalloc(sizeof(*gc), GFP_KERNEL); if (!gc) return -ENOMEM; + gc->layout = layout; gc->snapshot.sequence = snapshot->sequence; gc->snapshot.checkpoint_sequence = snapshot->checkpoint_sequence; gc->snapshot.journal_sequence = snapshot->journal_sequence; + gc->snapshot.subblocks = layout.subblocks; + gc->snapshot.stride = layout.stride; + gc->snapshot.logical_pages = layout.logical_pages; gc->max_records = max_records; gc->victim = victim->block; gc->footer_chunks = victim->footer_chunks; @@ -343,8 +365,8 @@ int apple_sftl_gc_plan(const struct apple_sftl_snapshot *snapshot, u32 before, live, offset, address = run->provider; if (address != APPLE_SFTL_NO_ADDRESS && - sftl_overlap(address, run->length, start, start + APPLE_SFTL_STRIDE) && - min(address + run->length, start + APPLE_SFTL_STRIDE) > end - footer) { + sftl_overlap(address, run->length, start, start + layout.stride) && + min(address + run->length, start + layout.stride) > end - footer) { ret = -EBADMSG; goto failed; } @@ -394,7 +416,7 @@ int apple_sftl_gc_plan(const struct apple_sftl_snapshot *snapshot, } gc->snapshot.sequence += copied; gc->snapshot.journal_sequence += copied; - ret = sftl_checkpoint_count(&gc->snapshot, max_records, &count); + ret = sftl_checkpoint_count(&gc->snapshot, max_records, NULL, &count); if (ret) goto failed; gc->stage = gc->nr_copies ? APPLE_SFTL_GC_COPY : APPLE_SFTL_GC_CHECKPOINT; @@ -435,7 +457,7 @@ bool apple_sftl_gc_has_sequence_room(const struct apple_sftl_gc *gc, u32 pending { u32 count; - if (!gc || sftl_checkpoint_count(&gc->snapshot, gc->max_records, &count)) + if (!gc || sftl_checkpoint_count(&gc->snapshot, gc->max_records, NULL, &count)) return false; return pending <= SFTL_SEQUENCE - gc->snapshot.sequence - count; } @@ -495,7 +517,8 @@ static int sftl_checkpoint_stage(const struct apple_sftl_checkpoint *image, { struct apple_sftl_checkpoint *copy; struct apple_sftl_gc_page *pages; - u32 capacity = hweight16(lanes) * 512, start = block * APPLE_SFTL_STRIDE; + struct apple_sftl_layout layout; + u32 capacity, start; u32 i, j, order = 0; bool native; int ret; @@ -504,29 +527,43 @@ static int sftl_checkpoint_stage(const struct apple_sftl_checkpoint *image, return -EINVAL; *readback = NULL; if (!image || !image->records || !image->count || image->count % 4 || - !block || block >= APPLE_SFTL_SUBBLOCKS || image->count > capacity || - !image->first_sequence || image->sequence > SFTL_SEQUENCE || + !block || !image->first_sequence || image->sequence > SFTL_SEQUENCE || image->first_sequence > image->sequence || image->sequence - image->first_sequence != image->count - 1 || !io || !io->read || !io->program) return -EINVAL; + native = image->records[3].meta[1] == 1; + if (gc) { + layout = gc->layout; + } else if (native) { + u32 tail = get_unaligned_le32(image->records[3].data + APPLE_SFTL_CHUNK - 4); + + if (!apple_sftl_layout_for_subblocks(tail, &layout)) + return -EBADMSG; + } else { + apple_sftl_layout_for_subblocks(APPLE_SFTL_SUBBLOCKS, &layout); + } + capacity = hweight16(lanes) * layout.lane_slots; + start = block * layout.stride; + if (block >= layout.subblocks || image->count > capacity) + return -EINVAL; if (image->records[0].meta[1] != 1 || image->records[image->count - 1].meta[1] != 4 || !get_unaligned_le32(image->records[0].data) || get_unaligned_le32(image->records[0].data) > 16 || get_unaligned_le32(image->records[0].data + 4) != block) return -EBADMSG; - native = image->records[3].meta[1] == 1; - if (native && (image->count <= APPLE_SFTL_ACCOUNT_RECORDS || - (image->count - APPLE_SFTL_ACCOUNT_RECORDS) % APPLE_SFTL_NATIVE_MAP_BATCH || + if (native && (image->count < layout.opaque_records + layout.map_min || + (image->count - layout.opaque_records) % layout.map_batch || get_unaligned_le32(image->records[3].data + APPLE_SFTL_CHUNK - 4) != - APPLE_SFTL_SUBBLOCKS)) + layout.subblocks)) return -EBADMSG; for (i = 0; i < image->count; i++) { const u8 *meta = image->records[i].meta; u32 group = meta[1] == 4 ? 7 : meta[1]; - if (group < order || (native && !apple_sftl_native_context_tag(i, meta))) + if (group < order || + (native && !apple_sftl_native_context_tag_for(layout.subblocks, i, meta))) return -EBADMSG; order = group; if (meta[0] != 0x1f || !meta[1] || meta[1] > 6 || @@ -638,7 +675,7 @@ int apple_sftl_gc_relocate(struct apple_sftl_gc *gc, return -ENOMEM; src = &pages[0]; dst = &pages[1]; - address = gc->destination * APPLE_SFTL_STRIDE; + address = gc->destination * gc->layout.stride; sequence = gc->copied_sequence; repeat = 1 + gc->padding; for (i = 0; i < gc->nr_copies; i++) { @@ -725,8 +762,8 @@ int apple_sftl_gc_prepare_native(struct apple_sftl_gc *gc, ret = prepare(priv, staged.opaque, staged.nr_opaque, &staged, gc->victim, gc->destination, blocks); if (!ret) - ret = sftl_checkpoint_build(&staged, blocks, 2, min(gc->max_records, capacity), - true, &image); + ret = sftl_checkpoint_build(&staged, blocks, gc->layout.context_names, + min(gc->max_records, capacity), true, &image); if (!ret && !apple_sftl_account_gc_image(&gc->snapshot, image, blocks, gc->victim, gc->destination, apple_sftl_gc_copy_chunks(gc) - gc->padding, @@ -810,7 +847,8 @@ int apple_sftl_gc_checkpoint_done(struct apple_sftl_gc *gc, EXPORT_SYMBOL_GPL(apple_sftl_gc_checkpoint_done); static bool sftl_maps_equal(const struct apple_sftl_snapshot *expected, - const struct apple_sftl_snapshot *recovered) + const struct apple_sftl_snapshot *recovered, + const struct apple_sftl_layout *layout) { u32 wanted = 0, found = 0, offset = 0, length; @@ -834,7 +872,7 @@ static bool sftl_maps_equal(const struct apple_sftl_snapshot *expected, if (offset == b->logical + b->length) found++; } - return offset == APPLE_SFTL_LOGICAL_PAGES; + return offset == layout->logical_pages; } /* @@ -847,16 +885,21 @@ int apple_sftl_gc_plan_retired(const struct apple_sftl_snapshot *active, const struct apple_sftl_gc_block *victim, u64 checkpoint_start) { + struct apple_sftl_layout active_layout, cold_layout; u32 i, first; int ret; - ret = sftl_check_map(active); + ret = sftl_check_map(active, &active_layout); if (ret) return ret; - ret = sftl_check_map(cold); + ret = sftl_check_map(cold, &cold_layout); if (ret) return ret; - if (!sftl_gc_block_valid(victim) || !victim->closed || victim->blank || + if (active_layout.subblocks != cold_layout.subblocks || + active_layout.stride != cold_layout.stride || + active_layout.logical_pages != cold_layout.logical_pages) + return -EBADMSG; + if (!sftl_gc_block_valid(victim, &cold_layout) || !victim->closed || victim->blank || !checkpoint_start || checkpoint_start > cold->checkpoint_sequence || victim->last_sequence >= checkpoint_start) return -EOPNOTSUPP; @@ -864,14 +907,14 @@ int apple_sftl_gc_plan_retired(const struct apple_sftl_snapshot *active, active->checkpoint_sequence != cold->checkpoint_sequence || active->journal_sequence != active->sequence || cold->journal_sequence != cold->sequence || - !sftl_maps_equal(active, cold)) + !sftl_maps_equal(active, cold, &cold_layout)) return -EBADMSG; - first = victim->block * APPLE_SFTL_STRIDE; + first = victim->block * cold_layout.stride; for (i = 0; i < cold->nr_runs; i++) { const struct apple_sftl_extent *run = &cold->runs[i]; if (run->provider != APPLE_SFTL_NO_ADDRESS && - sftl_overlap(run->provider, run->length, first, first + APPLE_SFTL_STRIDE)) + sftl_overlap(run->provider, run->length, first, first + cold_layout.stride)) return -EOPNOTSUPP; } return 0; @@ -880,21 +923,25 @@ int apple_sftl_gc_plan_retired(const struct apple_sftl_snapshot *active, int apple_sftl_gc_recovered(struct apple_sftl_gc *gc, const struct apple_sftl_snapshot *recovered) { + struct apple_sftl_layout layout; int ret; if (!gc || (gc->stage != APPLE_SFTL_GC_RECOVERY && gc->stage != APPLE_SFTL_GC_VERIFIED)) return -EINVAL; - ret = sftl_check_map(recovered); + ret = sftl_check_map(recovered, &layout); if (ret) goto failed; - if (recovered->checkpoint_sequence != gc->checkpoint->sequence || + if (layout.subblocks != gc->layout.subblocks || + layout.stride != gc->layout.stride || + layout.logical_pages != gc->layout.logical_pages || + recovered->checkpoint_sequence != gc->checkpoint->sequence || recovered->sequence != gc->checkpoint->sequence || recovered->journal_sequence != recovered->sequence || recovered->checkpoint_sequence <= gc->retire_sequence) { ret = -EBADMSG; goto failed; } - if (!sftl_maps_equal(&gc->snapshot, recovered)) { + if (!sftl_maps_equal(&gc->snapshot, recovered, &gc->layout)) { ret = -EBADMSG; goto failed; } diff --git a/drivers/mtd/apple-sftl-reclaim.h b/drivers/mtd/apple-sftl-reclaim.h index a13ff96b9755b6..cbf033fc3dbec6 100644 --- a/drivers/mtd/apple-sftl-reclaim.h +++ b/drivers/mtd/apple-sftl-reclaim.h @@ -7,13 +7,37 @@ #define APPLE_SFTL_CHUNK 4096U #define APPLE_SFTL_META 16U #define APPLE_SFTL_NATIVE_MAP_BATCH 64U +#define APPLE_SFTL_16GB_MAP_BATCH 16U +#define APPLE_SFTL_16GB_MAP_MIN 32U #define APPLE_SFTL_STRIDE 8192U +#define APPLE_SFTL_16GB_STRIDE 4096U #define APPLE_SFTL_SUBBLOCKS 2086U +#define APPLE_SFTL_P105_16GB_SUBBLOCKS 1055U +#define APPLE_SFTL_N42_SUBBLOCKS 1046U #define APPLE_SFTL_LOGICAL_PAGES 15625016U +#define APPLE_SFTL_16GB_LOGICAL_PAGES 3906266U #define APPLE_SFTL_NO_ADDRESS ((u32)~0U) struct apple_sftl; +/* Measured native checkpoint and accounting layout for a supported profile. */ +struct apple_sftl_layout { + u32 subblocks; + u32 stride; + u32 lane_slots; + u32 logical_pages; + u32 provider_limit; + u32 unmapped_sentinel; + u32 opaque_records; + u32 sb_start; + u32 user_seq_start; + u32 read_count_start; + u32 map_batch; + u32 map_min; + u32 context_names; + u32 footer_max; +}; + struct apple_sftl_extent { u32 logical, length, provider; }; @@ -29,6 +53,10 @@ struct apple_sftl_snapshot { struct apple_sftl_context_record *opaque; u32 nr_runs, nr_opaque; u64 sequence, checkpoint_sequence, journal_sequence; + /* Zero defaults to the 64 GB 13G36 geometry (or the native base tail). */ + u16 subblocks; + u16 stride; + u32 logical_pages; }; struct apple_sftl_checkpoint { diff --git a/drivers/mtd/apple-sftl-test-fixture.h b/drivers/mtd/apple-sftl-test-fixture.h index 16d65b6a2db7fa..793064b8dca621 100644 --- a/drivers/mtd/apple-sftl-test-fixture.h +++ b/drivers/mtd/apple-sftl-test-fixture.h @@ -6,16 +6,22 @@ #include #include "apple-sftl-reclaim.h" -/* Populate the measured layout in 32 zeroed synthetic records. Callers place - * these in their own generation and supply its context block addresses. +/* Populate the measured native prefix for either 64 GB (2086 subblocks, 32 + * records) or 16 GB 12H321 (1046/1055 subblocks, 24 records). */ -static inline void apple_sftl_test_native_prefix(struct apple_sftl_context_record *records) +static inline void apple_sftl_test_native_prefix_for(struct apple_sftl_context_record *records, + u32 subblocks) { - static const struct { + const struct { u8 subtype, chunks; u16 entries; - } groups[] = { { 1, 4, 0 }, { 2, 4, 0 }, { 3, 8, 512 }, - { 5, 12, 256 }, { 6, 4, 1024 } }; + } groups[] = { + { 1, 4, 0 }, + { 2, 4, 0 }, + { 3, round_up(DIV_ROUND_UP(subblocks, 512), 4), 512 }, + { 5, round_up(DIV_ROUND_UP(subblocks, 256), 4), 256 }, + { 6, round_up(DIV_ROUND_UP(subblocks, 1024), 4), 1024 }, + }; u32 i, pos, j, cursor = 0; u8 *stats; @@ -23,8 +29,8 @@ static inline void apple_sftl_test_native_prefix(struct apple_sftl_context_recor for (j = 0; j < groups[i].chunks; j++) { u8 *meta = records[cursor++].meta; u32 start = j * groups[i].entries; - u16 n = start >= APPLE_SFTL_SUBBLOCKS ? 0 : - min_t(u32, groups[i].entries, APPLE_SFTL_SUBBLOCKS - start); + u16 n = start >= subblocks ? 0 : + min_t(u32, groups[i].entries, subblocks - start); meta[0] = 0x1f; meta[1] = groups[i].subtype; @@ -35,7 +41,7 @@ static inline void apple_sftl_test_native_prefix(struct apple_sftl_context_recor } put_unaligned_le32(1, records[0].data); put_unaligned_le32(1, records[0].data + 4); - put_unaligned_le32(APPLE_SFTL_SUBBLOCKS, records[3].data + APPLE_SFTL_CHUNK - 4); + put_unaligned_le32(subblocks, records[3].data + APPLE_SFTL_CHUNK - 4); stats = records[4].data; put_unaligned_le32(45, stats); pos = 4; @@ -47,4 +53,10 @@ static inline void apple_sftl_test_native_prefix(struct apple_sftl_context_recor pos += 8 + words * 4; } } + +/* Populate the measured 64 GB layout in 32 zeroed synthetic records. */ +static inline void apple_sftl_test_native_prefix(struct apple_sftl_context_record *records) +{ + apple_sftl_test_native_prefix_for(records, APPLE_SFTL_SUBBLOCKS); +} #endif diff --git a/drivers/mtd/apple-sftl-test.c b/drivers/mtd/apple-sftl-test.c index 9ce7420714cb0e..53ba429d70bb9e 100644 --- a/drivers/mtd/apple-sftl-test.c +++ b/drivers/mtd/apple-sftl-test.c @@ -9,10 +9,14 @@ #include #include "apple-sftl.h" +#include "apple-sftl-account.h" #include "apple-sftl-provider.h" #include "apple-sftl-reclaim.h" #include "apple-sftl-test-fixture.h" #include "apple-sftl-vfl.h" +#include "apple-n42-write-pattern.h" +#include "apple-n42-close-test.h" +#include "apple-n42-lwvm-alloc.h" #define TEST_LOGICAL_PAGES 15625016U #define TEST_STRIDE 8192U @@ -3558,6 +3562,18 @@ struct t16_fixture { 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 */ + /* 12H321 replay cases: chunks of open blocks (T16_OPEN and above). */ + const struct t16_chunk *chunks; + u32 nr_chunks; + u32 uecc_block, uecc_position; /* position + 1 reads status 44 */ +}; + +struct t16_chunk { + u32 block, slot; + u8 kind, flags, fill; + u64 seq; + u32 key, user; + u32 trim_start, trim_length; }; /* Fixed records before the ranges: the native base, statistics and tables. */ @@ -3905,6 +3921,24 @@ static void t16_slot(struct t16_fixture *f, u32 block, u32 slot, u8 *payload, u8 put_unaligned_le32(T16_OPEN_LBA + slot, payload); t16_meta(meta, 1, 0, sequence, T16_OPEN_LBA + slot, sequence >> 16); } + if (block >= T16_OPEN) { + u32 i; + + for (i = 0; i < f->nr_chunks; i++) { + const struct t16_chunk *c = &f->chunks[i]; + + if (c->block != block || c->slot != slot) + continue; + memset(payload, c->fill, 4096); + put_unaligned_le32(c->key, payload); + if (c->key == 0xffff0001) { + put_unaligned_le32(1, payload); + put_unaligned_le32(c->trim_start, payload + 4); + put_unaligned_le32(c->trim_length, payload + 8); + } + t16_meta(meta, c->kind, c->flags, c->seq, c->key, c->user); + } + } } static int t16_read_page(void *priv, unsigned int bus, unsigned int cau, @@ -3934,6 +3968,9 @@ static int t16_read_page(void *priv, unsigned int bus, unsigned int cau, data + chunk * 4096, oob + chunk * 16); if (memchr_inv(oob, 0xff, APPLE_PPN_OOB_SIZE)) *status = 0x40; + /* A page that does not decode: H2FMI hands back its status alone. */ + if (block == f->uecc_block && page * width + index + 1 == f->uecc_position) + *status = 0x44; return 0; } @@ -4418,6 +4455,7 @@ static void sftl_test_n42_repeated_sequence(struct kunit *test) KUNIT_EXPECT_EQ(test, apple_sftl_load(&f->provider, &sftl), -EBADMSG); KUNIT_EXPECT_PTR_EQ(test, sftl, NULL); + f->legacy = true; f->provider.blocks = N42_BLOCKS; f->blocks = N42_BLOCKS; f->subblocks = N42_SUBBLOCKS; @@ -4440,6 +4478,1168 @@ static void sftl_test_n42_repeated_sequence(struct kunit *test) apple_sftl_free(sftl); } +/* The iPhone 5 geometry on the 16 GB fixture. */ +static void t16_n42(struct t16_fixture *f) +{ + f->legacy = true; + f->provider.blocks = N42_BLOCKS; + f->blocks = N42_BLOCKS; + f->subblocks = N42_SUBBLOCKS; + f->vfl_block = N42_BLOCKS - 1; +} + +static struct apple_sftl_inspect *t16_inspect(struct kunit *test, struct apple_sftl *sftl) +{ + struct apple_sftl_inspect *insp = kunit_kzalloc(test, sizeof(*insp), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, insp); + KUNIT_ASSERT_EQ(test, apple_sftl_inspect(sftl, 0, insp, NULL), 0); + return insp; +} + +static void t16_expect_unmapped(struct kunit *test, struct apple_sftl *sftl, u32 lba) +{ + u8 *data = kunit_kmalloc(test, 4096, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, data); + KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, lba, data), 0); + KUNIT_EXPECT_TRUE(test, !memchr_inv(data, 0, 4096)); +} + +/* + * 12H321 garbage collection copies data with subtype 1 and keeps the + * original write's user epoch; after the checkpoint such copies replay + * like any data (s_btoc_read checks neither). A kind-2 subtype-1 chunk with + * a real LBA is data too; the later copy of the hidden LBA wins. The P105 + * 16 GB profile keeps refusing the medium. + */ +static void sftl_test_n42_ios_relocated_copy(struct kunit *test) +{ + struct t16_fixture *f = t16_fixture(test); + struct apple_sftl *sftl = NULL; + struct apple_sftl_info info; + u64 s = t16_last(f) + 1; + const struct t16_chunk chunks[] = { + { T16_OPEN, 0, 1, 1, 'm', s + 0, T16_NEW_LBA + 0, 3 }, + { T16_OPEN, 1, 1, 1, 'm', s + 1, T16_NEW_LBA + 1, 3 }, + { T16_OPEN, 2, 1, 1, 'm', s + 2, T16_NEW_LBA + 2, 3 }, + { T16_OPEN, 3, 1, 1, 'm', s + 3, T16_NEW_LBA + 3, 3 }, + { T16_OPEN, 4, 2, 1, 'g', s + 4, T16_LPAGES - 1, (s + 4) >> 16 }, + { T16_OPEN, 5, 2, 1, 'h', s + 5, T16_LPAGES - 1, (s + 5) >> 16 }, + }; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_LT(test, 3U, (u32)(s >> 16)); + f->chunks = chunks; + f->nr_chunks = ARRAY_SIZE(chunks); + KUNIT_EXPECT_EQ(test, apple_sftl_load(&f->provider, &sftl), -EBADMSG); + KUNIT_EXPECT_PTR_EQ(test, sftl, NULL); + + t16_n42(f); + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); + apple_sftl_get_info(sftl, &info); + KUNIT_EXPECT_FALSE(test, info.tolerated); + KUNIT_EXPECT_EQ(test, info.journal_sequence, s + 5); + KUNIT_EXPECT_EQ(test, info.sequence, s + 5); + KUNIT_EXPECT_EQ(test, t16_inspect(test, sftl)->nr_torn, 0U); + t16_expect_page(test, sftl, T16_NEW_LBA, 'm', T16_NEW_LBA); + t16_expect_page(test, sftl, T16_NEW_LBA + 3, 'm', T16_NEW_LBA + 3); + t16_expect_page(test, sftl, T16_NEW_LBA + 4, 'n', T16_NEW_LBA + 4); + t16_expect_page(test, sftl, T16_LPAGES - 1, 'h', T16_LPAGES - 1); + t16_expect_page(test, sftl, 0, 'o', 0); + apple_sftl_free(sftl); +} + +/* + * Sequence gaps replay as they are (s_cxt_replay_streams has no contiguity + * check): here 568 sequences are missing before an open block that also + * holds a trim. The next write goes after the highest sequence. + */ +static void sftl_test_n42_ios_gap(struct kunit *test) +{ + struct t16_fixture *f = t16_fixture(test); + struct apple_sftl *sftl = NULL; + struct apple_sftl_info info; + u64 s = t16_last(f) + 1 + 568; + const struct t16_chunk chunks[] = { + { T16_OPEN, 0, 1, 0, 'p', s + 0, T16_OPEN_LBA + 0, (s + 0) >> 16 }, + { T16_OPEN, 1, 1, 0, 'p', s + 1, T16_OPEN_LBA + 1, (s + 1) >> 16 }, + { T16_OPEN, 2, 1, 0, 'p', s + 2, T16_OPEN_LBA + 2, (s + 2) >> 16 }, + { T16_OPEN, 3, 1, 0, 'p', s + 3, T16_OPEN_LBA + 3, (s + 3) >> 16 }, + { T16_OPEN, 4, 2, 0, 0, s + 4, 0xffff0001, (s + 4) >> 16, T16_NEW_LBA + 5, 1 }, + }; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->chunks = chunks; + f->nr_chunks = ARRAY_SIZE(chunks); + KUNIT_EXPECT_EQ(test, apple_sftl_load(&f->provider, &sftl), -EBADMSG); + KUNIT_EXPECT_PTR_EQ(test, sftl, NULL); + + t16_n42(f); + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); + apple_sftl_get_info(sftl, &info); + KUNIT_EXPECT_FALSE(test, info.tolerated); + KUNIT_EXPECT_EQ(test, info.journal_sequence, s + 4); + KUNIT_EXPECT_EQ(test, info.sequence, s + 4); + t16_expect_page(test, sftl, T16_OPEN_LBA, 'p', T16_OPEN_LBA); + t16_expect_page(test, sftl, T16_OPEN_LBA + 3, 'p', T16_OPEN_LBA + 3); + t16_expect_page(test, sftl, T16_NEW_LBA + 4, 'n', T16_NEW_LBA + 4); + t16_expect_unmapped(test, sftl, T16_NEW_LBA + 5); + t16_expect_page(test, sftl, T16_NEW_LBA + 6, 'n', T16_NEW_LBA + 6); + apple_sftl_free(sftl); +} + +/* + * Two copies of one LBA in two open blocks: the higher sequence wins, not + * the block replayed last, nor the newer user epoch. + */ +static void sftl_test_n42_ios_conflict_order(struct kunit *test) +{ + struct t16_fixture *f = t16_fixture(test); + struct apple_sftl *sftl = NULL; + struct apple_sftl_info info; + u64 s = t16_last(f) + 1; + const struct t16_chunk chunks[] = { + { T16_OPEN + 1, 0, 1, 0, 'a', s + 0, 3100, (s + 0) >> 16 }, + { T16_OPEN + 1, 1, 1, 0, 'a', s + 1, 3101, (s + 1) >> 16 }, + { T16_OPEN + 1, 2, 1, 0, 'a', s + 2, 3102, (s + 2) >> 16 }, + { T16_OPEN + 1, 3, 1, 0, 'a', s + 3, 3103, (s + 3) >> 16 }, + { T16_OPEN + 1, 4, 1, 1, 'z', s + 20, 3200, 1 }, + { T16_OPEN, 0, 1, 0, 'y', s + 4, 3200, (s + 4) >> 16 }, + { T16_OPEN, 1, 1, 0, 'b', s + 5, 3300, (s + 5) >> 16 }, + { T16_OPEN, 2, 1, 0, 'b', s + 6, 3301, (s + 6) >> 16 }, + { T16_OPEN, 3, 1, 0, 'b', s + 7, 3302, (s + 7) >> 16 }, + }; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->chunks = chunks; + f->nr_chunks = ARRAY_SIZE(chunks); + t16_n42(f); + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); + apple_sftl_get_info(sftl, &info); + KUNIT_EXPECT_EQ(test, info.journal_sequence, s + 20); + KUNIT_EXPECT_EQ(test, t16_inspect(test, sftl)->nr_equal, 0U); + t16_expect_page(test, sftl, 3200, 'z', 3200); + t16_expect_page(test, sftl, 3103, 'a', 3103); + t16_expect_page(test, sftl, 3302, 'b', 3302); + apple_sftl_free(sftl); +} + +/* + * Data in an open block below the highest data end so far is a media error + * ("weaveSeq non-monotonic, treating as media error"): not applied, and + * with no block left to enter a stream, replay stops there. + */ +static void sftl_test_n42_ios_non_monotonic(struct kunit *test) +{ + struct t16_fixture *f = t16_fixture(test); + struct apple_sftl *sftl = NULL; + struct apple_sftl_info info; + struct apple_sftl_inspect *insp; + u64 s = t16_last(f) + 1; + const struct t16_chunk chunks[] = { + { T16_OPEN + 1, 0, 1, 0, 'a', s + 0, 3100, (s + 0) >> 16 }, + { T16_OPEN + 1, 1, 1, 0, 'a', s + 1, 3101, (s + 1) >> 16 }, + { T16_OPEN + 1, 2, 1, 0, 'a', s + 2, 3102, (s + 2) >> 16 }, + { T16_OPEN + 1, 3, 1, 0, 'a', s + 3, 3103, (s + 3) >> 16 }, + { T16_OPEN, 0, 1, 0, 'x', s + 2, 3400, (s + 2) >> 16 }, + { T16_OPEN, 1, 1, 0, 'x', s + 3, 3401, (s + 3) >> 16 }, + { T16_OPEN, 2, 1, 0, 'w', s + 10, 3500, (s + 10) >> 16 }, + }; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->chunks = chunks; + f->nr_chunks = ARRAY_SIZE(chunks); + t16_n42(f); + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); + apple_sftl_get_info(sftl, &info); + insp = t16_inspect(test, sftl); + KUNIT_EXPECT_EQ(test, insp->nr_equal, 1U); + KUNIT_EXPECT_EQ(test, insp->nr_torn, 1U); + KUNIT_EXPECT_EQ(test, info.journal_sequence, s + 10); + t16_expect_page(test, sftl, 3100, 'a', 3100); + t16_expect_page(test, sftl, 3103, 'a', 3103); + t16_expect_unmapped(test, sftl, 3400); + t16_expect_unmapped(test, sftl, 3401); + t16_expect_unmapped(test, sftl, 3500); + apple_sftl_free(sftl); +} + +/* + * A page that does not decode, then more data in the same open block. The + * load goes on. With every block already in a stream the uECC token stops + * replay ("exiting early to be coherent"); with blocks still to come it is + * passed over and the data after it is applied. + */ +static void sftl_test_n42_ios_uecc_then_data(struct kunit *test) +{ + struct t16_fixture *f = t16_fixture(test); + struct apple_sftl *sftl = NULL; + struct apple_sftl_info info; + u64 s = t16_last(f) + 1; + struct t16_chunk *chunks = kunit_kcalloc(test, 20, sizeof(*chunks), GFP_KERNEL); + u32 i; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, chunks); + for (i = 0; i < 8; i++) + chunks[i] = (struct t16_chunk) { T16_OPEN, i, 1, 0, 'p', s + i, 3000 + i, + (s + i) >> 16 }; + for (i = 12; i < 16; i++) + chunks[i - 4] = (struct t16_chunk) { T16_OPEN, i, 1, 0, 'q', s + i, 3000 + i, + (s + i) >> 16 }; + f->chunks = chunks; + f->nr_chunks = 12; + f->uecc_block = T16_OPEN; + f->uecc_position = 3; + KUNIT_EXPECT_LT(test, apple_sftl_load(&f->provider, &sftl), 0); + KUNIT_EXPECT_PTR_EQ(test, sftl, NULL); + + t16_n42(f); + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); + apple_sftl_get_info(sftl, &info); + KUNIT_EXPECT_FALSE(test, info.tolerated); + KUNIT_EXPECT_EQ(test, info.journal_sequence, s + 15); + KUNIT_EXPECT_EQ(test, t16_inspect(test, sftl)->nr_torn, 1U); + t16_expect_page(test, sftl, 3000, 'p', 3000); + t16_expect_page(test, sftl, 3007, 'p', 3007); + t16_expect_unmapped(test, sftl, 3012); + t16_expect_unmapped(test, sftl, 3015); + apple_sftl_free(sftl); + + /* Four more open blocks after it: the token no longer ends replay. */ + for (i = 0; i < 4; i++) + chunks[12 + i] = (struct t16_chunk) { T16_OPEN + 1 + i, 0, 1, 0, 'e', + s + 20 + i, 3600 + i, (s + 20 + i) >> 16 }; + f->nr_chunks = 16; + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); + apple_sftl_get_info(sftl, &info); + KUNIT_EXPECT_EQ(test, info.journal_sequence, s + 23); + KUNIT_EXPECT_EQ(test, t16_inspect(test, sftl)->nr_torn, 1U); + t16_expect_page(test, sftl, 3007, 'p', 3007); + t16_expect_page(test, sftl, 3012, 'q', 3012); + t16_expect_page(test, sftl, 3015, 'q', 3015); + t16_expect_page(test, sftl, 3600, 'e', 3600); + t16_expect_page(test, sftl, 3603, 'e', 3603); + apple_sftl_free(sftl); +} + +/* + * On N42 12H321, a cleanly erased standby VFL bank (block 1054) is healthy + * (vfl_degraded == false) while sftl_16gb_n42 stays read-only by default. + */ +static void sftl_test_n42_vfl_single_bank_healthy(struct kunit *test) +{ + struct t16_fixture *f = t16_fixture(test); + struct apple_sftl *sftl = NULL; + struct apple_sftl_info info; + struct apple_sftl_inspect *insp; + u8 *data = kunit_kzalloc(test, 4096, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, data); + insp = kunit_kzalloc(test, sizeof(*insp), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, insp); + f->provider.blocks = N42_BLOCKS; + f->blocks = N42_BLOCKS; + f->subblocks = N42_SUBBLOCKS; + f->vfl_block = N42_BLOCKS - 1; + 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_ASSERT_EQ(test, apple_sftl_inspect(sftl, 0, insp, NULL), 0); + KUNIT_EXPECT_FALSE(test, insp->vfl_degraded); + KUNIT_EXPECT_FALSE(test, insp->context_degraded); + KUNIT_EXPECT_TRUE(test, insp->native_context); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, 0, data, 1), -EROFS); + apple_sftl_free(sftl); +} + +/* Writable in-RAM N42 12H321 fixture for append/close and 1-site native GC. */ +#define N42W_CTX_OLD 2U +#define N42W_DONOR 3U +#define N42W_LANDING 4U +#define N42W_CTX_NEW 5U +#define N42W_APPEND 6U +#define N42W_SLOTS 5U /* blocks 2..6 stored in RAM */ + +struct n42_wpage { + bool written; + u8 data[APPLE_PPN_PAGE_SIZE]; + u8 oob[APPLE_PPN_OOB_SIZE]; +}; + +struct n42_wfix { + struct t16_fixture base; + struct n42_wpage *pages[N42W_SLOTS][4]; /* [block - 2][lane][256] */ + bool fenced; + u32 erases, programs, prepare_calls, stats_calls, finish_calls; + bool finish_ok; +}; + +static int n42w_slot(unsigned int block) +{ + if (block < N42W_CTX_OLD || block >= N42W_CTX_OLD + N42W_SLOTS) + return -1; + return block - N42W_CTX_OLD; +} + +static int n42w_read(void *priv, unsigned int bus, unsigned int cau, + unsigned int block, unsigned int page, bool context, + u8 *data, u8 *oob, u8 *status) +{ + struct n42_wfix *w = priv; + unsigned int lane = cau * 2 + bus; + int slot; + + if (bus >= 2 || cau >= 2 || block >= N42_BLOCKS || + page >= (context ? T16_PAGES / 2 : T16_PAGES)) + return -EINVAL; + memset(data, 0xff, APPLE_PPN_PAGE_SIZE); + memset(oob, 0xff, APPLE_PPN_OOB_SIZE); + *status = 0x49; + if (context) + return t16_vfl(&w->base, lane, block, page, data, oob, status); + slot = n42w_slot(block); + if (slot < 0 || !w->pages[slot][lane][page].written) + return 0; + memcpy(data, w->pages[slot][lane][page].data, APPLE_PPN_PAGE_SIZE); + memcpy(oob, w->pages[slot][lane][page].oob, APPLE_PPN_OOB_SIZE); + *status = 0x40; + return 0; +} + +static int n42w_program(void *priv, unsigned int bus, unsigned int cau, + unsigned int block, unsigned int page, + const u8 *data, const u8 *oob) +{ + struct n42_wfix *w = priv; + unsigned int lane = cau * 2 + bus; + int slot; + + if (!block || block >= N42_SUBBLOCKS || bus >= 2 || cau >= 2 || page >= T16_PAGES) { + w->fenced = true; + return -EPERM; + } + slot = n42w_slot(block); + if (slot < 0 || w->pages[slot][lane][page].written) + return -EIO; + memcpy(w->pages[slot][lane][page].data, data, APPLE_PPN_PAGE_SIZE); + memcpy(w->pages[slot][lane][page].oob, oob, APPLE_PPN_OOB_SIZE); + w->pages[slot][lane][page].written = true; + w->programs++; + return 0; +} + +static int n42w_erase(void *priv, unsigned int bus, unsigned int cau, unsigned int block) +{ + struct n42_wfix *w = priv; + unsigned int lane = cau * 2 + bus; + int slot; + + if (!block || block >= N42_SUBBLOCKS || bus >= 2 || cau >= 2) { + w->fenced = true; + return -EPERM; + } + slot = n42w_slot(block); + if (slot < 0) + return -EPERM; + memset(w->pages[slot][lane], 0, T16_PAGES * sizeof(*w->pages[slot][lane])); + w->erases++; + return 0; +} + +static int n42w_reserve(void *priv, u32 *blocks, u32 *nr_blocks) +{ + if (*nr_blocks < 1) + return -ENOSPC; + blocks[0] = N42W_CTX_NEW; + *nr_blocks = 1; + return 0; +} + +static int n42w_prepare_native(void *priv, struct apple_sftl_context_record *opaque, + u32 nr_opaque, const struct apple_sftl_snapshot *map, + u32 victim, u32 landing, const u32 blocks[2]) +{ + struct n42_wfix *w = priv; + + w->prepare_calls++; + if (nr_opaque != APPLE_SFTL_16GB_ACCOUNT_RECORDS || blocks[0] != N42W_CTX_NEW || + victim != N42W_DONOR || landing != N42W_LANDING) + return -EINVAL; + opaque[8].data[N42W_CTX_NEW * 8] = 7; + opaque[8].data[N42W_DONOR * 8] = 9; + put_unaligned_le32(0, opaque[20].data + N42W_DONOR * 4); + opaque[8].data[N42W_LANDING * 8] = 4; + opaque[8].data[N42W_LANDING * 8 + 1] = 0; + return 0; +} + +static int n42w_read_stats(void *priv, u32 id, u8 *data, size_t bytes) +{ + struct n42_wfix *w = priv; + + w->stats_calls++; + if ((id == 255 && bytes != 88) || (id == 254 && bytes != 464) || + (id != 255 && id != 254)) + return -EINVAL; + memset(data, (u8)id, bytes); + return bytes; +} + +static int n42w_finish_native(void *priv, const struct apple_sftl_checkpoint *runtime, + u32 old_context, u32 unused_context, u32 donor) +{ + struct n42_wfix *w = priv; + + w->finish_calls++; + w->finish_ok = old_context == N42W_CTX_OLD && unused_context == 0 && + donor == N42W_DONOR && + runtime->records[8].data[old_context * 8] == 1 && + runtime->records[8].data[donor * 8] == 1; + return w->finish_ok ? 0 : -EINVAL; +} + +static const struct apple_sftl_checkpoint_ops n42w_gc_ops = { + .reserve = n42w_reserve, + .prepare_native = n42w_prepare_native, + .read_native_stats = n42w_read_stats, + .finish_native = n42w_finish_native, +}; + +static void n42w_kvfree(void *ptr) +{ + kvfree(ptr); +} + +/* + * Exercise the 16 GB 12H321 writer model on N42: 1-site native GC compaction + * (24 opaque + 32 map, old-context erase, donor erase), then append + nb=4 + * BTOC close on a 3-lane partial block (verifying 0xbffe lane is untouched) + * and cold reload. + */ +static void sftl_test_n42_writer_append_and_gc(struct kunit *test) +{ + struct n42_wfix *w = kunit_kzalloc(test, sizeof(*w), GFP_KERNEL); + struct apple_sftl_context_record *ctx; + struct apple_sftl *sftl = NULL, *cold = NULL; + struct apple_sftl_info info; + u8 *buf, *footer; + u32 i, j; + + KUNIT_ASSERT_NOT_NULL(test, w); + ctx = kvzalloc(56 * sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, n42w_kvfree, ctx), 0); + buf = kunit_kzalloc(test, APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + footer = kunit_kzalloc(test, APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + KUNIT_ASSERT_NOT_NULL(test, footer); + for (i = 0; i < N42W_SLOTS; i++) { + for (j = 0; j < 4; j++) { + w->pages[i][j] = kvcalloc(T16_PAGES, sizeof(*w->pages[i][j]), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, w->pages[i][j]); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, n42w_kvfree, + w->pages[i][j]), 0); + } + } + + w->base.blocks = N42_BLOCKS; + w->base.subblocks = N42_SUBBLOCKS; + w->base.vfl_block = N42_BLOCKS - 1; + w->base.ops.read_page = n42w_read; + w->base.ops.erase_block = n42w_erase; + w->base.provider = (struct apple_ppn) { + .ops = &w->base.ops, .priv = w, .buses = 2, .caus = 2, + .blocks = N42_BLOCKS, .pages = T16_PAGES, + }; + + /* Build a real 12H321 24-opaque + 32-map native checkpoint in block N42W_CTX_OLD. */ + apple_sftl_test_native_prefix_for(ctx, N42_SUBBLOCKS); + put_unaligned_le32(1, ctx[0].data); + put_unaligned_le32(N42W_CTX_OLD, ctx[0].data + 4); + for (i = 0; i < N42_SUBBLOCKS; i++) { + u8 *e = ctx[8 + i / 512].data + (i % 512) * 8; + + e[0] = i == 0 ? 8 : i == N42W_CTX_OLD ? 7 : i == N42W_DONOR ? 3 : + (i == N42W_LANDING || i == N42W_CTX_NEW || i == N42W_APPEND) ? 1 : 8; + } + ctx[8].data[N42W_DONOR * 8 + 1] = 0x08; + put_unaligned_le16(4, ctx[8].data + N42W_DONOR * 8 + 2); + put_unaligned_le64(4ULL, ctx[4].data + 4 + 8 * 16 + 8); /* stat 9 = 4 */ + for (i = 0; i < 24; i++) + apple_sftl_context_meta(ctx[i].meta, ctx[i].meta[1], 10000 + i, + get_unaligned_le16(ctx[i].meta + 8), + get_unaligned_le16(ctx[i].meta + 10)); + for (i = 24; i < 56; i++) { + memset(ctx[i].data, 0xff, 4096); + apple_sftl_context_meta(ctx[i].meta, 4, 10000 + i, 0, 0); + } + /* Map LBAs 0..3 into N42W_DONOR slots 0..3; rest unmapped (0x7fffff). */ + put_unaligned_le32(0, ctx[24].data); + put_unaligned_le32(0xfffffff0, ctx[24].data + 4); + put_unaligned_le32(N42W_DONOR * T16_STRIDE, ctx[24].data + 8); + put_unaligned_le32(4, ctx[24].data + 12); + put_unaligned_le32(T16_UNMAPPED, ctx[24].data + 16); + put_unaligned_le32(T16_LPAGES - 4, ctx[24].data + 20); + for (i = 0; i < 56; i += 4) { + struct n42_wpage *p = &w->pages[N42W_CTX_OLD - 2][(i / 4) % 4][(i / 4) / 4]; + + for (j = 0; j < 4; j++) { + memcpy(p->data + j * 4096, ctx[i + j].data, 4096); + memcpy(p->oob + j * 16, ctx[i + j].meta, 16); + } + p->written = true; + } + + /* Populate N42W_DONOR (pre-checkpoint closed block, nb=4 BTOC, 4 live chunks). */ + for (i = 0; i < 4092; i += 4) { + struct n42_wpage *p = &w->pages[N42W_DONOR - 2][(i / 4) % 4][(i / 4) / 4]; + + for (j = 0; j < 4; j++) { + u32 slot = i + j; + u64 seq = 1000 + slot; + + memset(p->data + j * 4096, 'd', 4096); + put_unaligned_le32(slot, p->data + j * 4096); + t16_meta(p->oob + j * 16, 1, 0, seq, slot, seq >> 16); + } + p->written = true; + } + put_unaligned_le32(0, footer); + put_unaligned_le32(0, footer + 4); + put_unaligned_le32(0, footer + 8); + put_unaligned_le32(4092, footer + 12); + { + struct n42_wpage *p = &w->pages[N42W_DONOR - 2][3][255]; + + memcpy(p->data, footer, APPLE_PPN_PAGE_SIZE); + for (j = 0; j < 4; j++) { + t16_meta(p->oob + j * 16, 0x1c, 0x08, 1000, 4092, 0); + put_unaligned_le16(4, p->oob + j * 16 + 12); + put_unaligned_le16(0xffff, p->oob + j * 16 + 14); + } + p->written = true; + } + + /* Occupy N42W_APPEND so only N42W_LANDING (4) and N42W_CTX_NEW (5) are blank. + * Note t16_usage() marks lane 2 of block 4 (T16_NEW == N42W_LANDING) as 0xbffe, + * so N42W_LANDING is a 3-lane partial block (3072 slots = 768 pages). + */ + w->pages[N42W_APPEND - 2][0][0].written = true; + for (j = 0; j < 4; j++) + t16_meta(w->pages[N42W_APPEND - 2][0][0].oob + j * 16, 1, 0, 500 + j, j, 0); + + /* This fixture supplies its own checkpoint and GC operations. Attach + * its writer after load so it exercises that path independently of + * the automatic reclaim pool. + */ + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &sftl), 0); + w->base.ops.program_page = n42w_program; + apple_sftl_test_enable_writer(sftl); + apple_sftl_set_write_fence(sftl, 500, 5084); + apple_sftl_set_checkpoint_ops(sftl, &n42w_gc_ops, w); + memset(buf, 'W', APPLE_PPN_PAGE_SIZE); + put_unaligned_le32(0xbeef1234U, buf); + KUNIT_ASSERT_EQ(test, apple_sftl_write(sftl, 500, buf, 1), 0); + KUNIT_EXPECT_EQ(test, w->prepare_calls, 1U); + KUNIT_EXPECT_EQ(test, w->stats_calls, 2U); + KUNIT_EXPECT_EQ(test, w->finish_calls, 1U); + KUNIT_EXPECT_TRUE(test, w->finish_ok); + KUNIT_EXPECT_EQ(test, w->erases, 8U); /* 4 lanes of CTX_OLD + 4 lanes of DONOR */ + KUNIT_EXPECT_FALSE(test, w->fenced); + + /* Fill the remaining slots of 4-lane N42W_LANDING (4092 - 8 = 4084 chunks = 1021 pages) + * so it closes cleanly with nb=4 (flags=0x08). Also verify retired lane 2 (0xbffe) + * of 3-lane N42W_CTX_NEW (block 5 == T16_NEW) was never programmed during checkpoint! + */ + for (i = 0; i < 1021; i++) { + for (j = 0; j < 4; j++) { + memset(buf + j * 4096, 's', 4096); + put_unaligned_le32(1000 + i * 4 + j, buf + j * 4096); + } + KUNIT_ASSERT_EQ(test, apple_sftl_write(sftl, 1000 + i * 4, buf, 4), 0); + } + /* Retired lane 2 (0xbffe) of 3-lane context block N42W_CTX_NEW must stay blank. */ + for (i = 0; i < T16_PAGES; i++) + KUNIT_EXPECT_FALSE(test, w->pages[N42W_CTX_NEW - 2][2][i].written); + /* Last page of N42W_LANDING (lane 3, page 255) holds the nb=4 BTOC. */ + KUNIT_EXPECT_EQ(test, w->pages[N42W_LANDING - 2][3][255].oob[0], (u8)0x1c); + KUNIT_EXPECT_EQ(test, w->pages[N42W_LANDING - 2][3][255].oob[1], (u8)0x08); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(w->pages[N42W_LANDING - 2][3][255].oob + 12), 4U); + KUNIT_EXPECT_FALSE(test, w->fenced); + apple_sftl_free(sftl); + + /* Cold reload and verify relocated donor data + newly appended data! */ + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &cold), 0); + apple_sftl_get_info(cold, &info); + KUNIT_EXPECT_EQ(test, info.read_only, !IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE)); + KUNIT_EXPECT_EQ(test, info.checkpoint_sequence, 10055ULL + 4 + 56); + t16_expect_page(test, cold, 0, 'd', 0); + t16_expect_page(test, cold, 3, 'd', 3); + t16_expect_page(test, cold, 500, 'W', 0xbeef1234U); + t16_expect_page(test, cold, 1000, 's', 1000); + t16_expect_page(test, cold, 1000 + 1020 * 4 + 3, 's', 1000 + 1020 * 4 + 3); + apple_sftl_free(cold); +} + +/* + * Step-1 fenced single-chunk write test coverage: + * - Default empty fence [0, 0) refuses every LBA with -EPERM. + * - Armed chunk-950 fence [3891200, 3895296) refuses every LBA outside + * (including 0, start-1, end, and boundary-spanning writes) with -EPERM. + * - Program-only provider (erase_block == NULL) writes 16 deterministic + * pattern pages inside the fence, flushes, disarms back to empty (-EPERM), + * reads back byte-for-byte, and cold-reloads with zero torn records. + */ +static void sftl_test_n42_write_fence_and_pattern(struct kunit *test) +{ + struct n42_wfix *w = kunit_kzalloc(test, sizeof(*w), GFP_KERNEL); + struct apple_sftl_context_record *ctx; + struct apple_sftl *sftl = NULL, *cold = NULL; + struct apple_sftl_info info; + struct apple_sftl_inspect *insp; + u8 *batch, *rbuf; + u32 i, j, got_crc = 0, want_crc = 0; + + KUNIT_ASSERT_NOT_NULL(test, w); + ctx = kvzalloc(56 * sizeof(*ctx), GFP_KERNEL); + insp = kvzalloc(sizeof(*insp), GFP_KERNEL); + batch = kunit_kmalloc(test, APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + rbuf = kunit_kmalloc(test, N42_WRITE_TEST_PAGE_BYTES, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + KUNIT_ASSERT_NOT_NULL(test, insp); + KUNIT_ASSERT_NOT_NULL(test, batch); + KUNIT_ASSERT_NOT_NULL(test, rbuf); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, n42w_kvfree, ctx), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, n42w_kvfree, insp), 0); + for (i = 0; i < N42W_SLOTS; i++) { + for (j = 0; j < 4; j++) { + w->pages[i][j] = kvcalloc(T16_PAGES, sizeof(*w->pages[i][j]), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, w->pages[i][j]); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, n42w_kvfree, + w->pages[i][j]), 0); + } + } + + w->base.blocks = N42_BLOCKS; + w->base.subblocks = N42_SUBBLOCKS; + w->base.vfl_block = N42_BLOCKS - 1; + w->base.ops.read_page = n42w_read; + w->base.ops.program_page = n42w_program; + w->base.ops.erase_block = NULL; /* Step-1: program-only, no erase! */ + w->base.provider = (struct apple_ppn) { + .ops = &w->base.ops, .priv = w, .buses = 2, .caus = 2, + .blocks = N42_BLOCKS, .pages = T16_PAGES, + }; + + apple_sftl_test_native_prefix_for(ctx, N42_SUBBLOCKS); + put_unaligned_le32(1, ctx[0].data); + put_unaligned_le32(N42W_CTX_OLD, ctx[0].data + 4); + for (i = 0; i < N42_SUBBLOCKS; i++) { + u8 *e = ctx[8 + i / 512].data + (i % 512) * 8; + + e[0] = i == 0 ? 8 : i == N42W_CTX_OLD ? 7 : i == N42W_APPEND ? 1 : 9; + } + for (i = 0; i < 24; i++) + apple_sftl_context_meta(ctx[i].meta, ctx[i].meta[1], 10000 + i, + get_unaligned_le16(ctx[i].meta + 8), + get_unaligned_le16(ctx[i].meta + 10)); + for (i = 24; i < 56; i++) { + memset(ctx[i].data, 0xff, 4096); + apple_sftl_context_meta(ctx[i].meta, 4, 10000 + i, 0, 0); + } + put_unaligned_le32(0, ctx[24].data); + put_unaligned_le32(0xfffffff0, ctx[24].data + 4); + put_unaligned_le32(T16_UNMAPPED, ctx[24].data + 8); + put_unaligned_le32(T16_LPAGES, ctx[24].data + 12); + for (i = 0; i < 56; i += 4) { + struct n42_wpage *p = &w->pages[N42W_CTX_OLD - 2][(i / 4) % 4][(i / 4) / 4]; + + for (j = 0; j < 4; j++) { + memcpy(p->data + j * 4096, ctx[i + j].data, 4096); + memcpy(p->oob + j * 16, ctx[i + j].meta, 16); + } + p->written = true; + } + + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &sftl), 0); + apple_sftl_test_enable_writer(sftl); + + /* Empty fence (default under CONFIG_MTD_APPLE_SFTL_N42_WRITE): -EPERM everywhere. */ + apple_sftl_set_write_fence(sftl, 0, 0); + memset(batch, 0x55, APPLE_PPN_PAGE_SIZE); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, 0, batch, 1), -EPERM); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, 4095, batch, 1), -EPERM); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, N42_WRITE_TEST_LBA_START, batch, 1), -EPERM); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, N42_WRITE_TEST_LBA_END - 1, batch, 1), -EPERM); + KUNIT_EXPECT_EQ(test, w->programs, 0U); + + /* Arm chunk-950 fence [3891200, 3895296): outside & spanning writes MUST return -EPERM. */ + apple_sftl_set_write_fence(sftl, N42_WRITE_TEST_LBA_START, N42_WRITE_TEST_LBA_END); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, 0, batch, 1), -EPERM); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, N42_WRITE_TEST_LBA_START - 1, batch, 1), -EPERM); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, N42_WRITE_TEST_LBA_START - 2, batch, 4), -EPERM); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, N42_WRITE_TEST_LBA_END, batch, 1), -EPERM); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, N42_WRITE_TEST_LBA_END - 2, batch, 4), -EPERM); + KUNIT_EXPECT_EQ(test, w->programs, 0U); + + /* Write 16 deterministic pages (4 physical pages) into the fenced range. */ + for (i = 0; i < N42_WRITE_TEST_DEFAULT_COUNT; i += 4) { + for (j = 0; j < 4; j++) + n42_write_pattern_fill(batch + j * N42_WRITE_TEST_PAGE_BYTES, + N42_WRITE_TEST_LBA_START + i + j, + N42_WRITE_TEST_DEFAULT_SEED, i + j); + KUNIT_ASSERT_EQ(test, + apple_sftl_write(sftl, N42_WRITE_TEST_LBA_START + i, batch, 4), 0); + } + KUNIT_ASSERT_EQ(test, apple_sftl_flush(sftl), 0); + KUNIT_EXPECT_EQ(test, w->programs, 4U); + KUNIT_EXPECT_EQ(test, w->erases, 0U); + KUNIT_EXPECT_FALSE(test, w->fenced); + + /* Disarm back to empty fence: writes inside chunk 950 are refused again. */ + apple_sftl_set_write_fence(sftl, 0, 0); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, N42_WRITE_TEST_LBA_START, batch, 1), -EPERM); + KUNIT_EXPECT_EQ(test, w->programs, 4U); + + KUNIT_ASSERT_EQ(test, apple_sftl_inspect(sftl, 0, insp, NULL), 0); + KUNIT_EXPECT_EQ(test, insp->append_block, N42W_APPEND); + KUNIT_EXPECT_EQ(test, insp->append_position, N42_WRITE_TEST_DEFAULT_COUNT); + KUNIT_EXPECT_EQ(test, insp->nr_torn, 0U); + KUNIT_EXPECT_FALSE(test, insp->vfl_degraded); + KUNIT_EXPECT_FALSE(test, insp->context_degraded); + + /* Verify in-session readback of all 16 pages. */ + for (i = 0; i < N42_WRITE_TEST_DEFAULT_COUNT; i++) { + u32 lba = N42_WRITE_TEST_LBA_START + i; + + KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, lba, rbuf), 0); + KUNIT_EXPECT_TRUE(test, + n42_write_pattern_check(rbuf, lba, N42_WRITE_TEST_DEFAULT_SEED, + i, &got_crc, &want_crc)); + KUNIT_EXPECT_EQ(test, got_crc, want_crc); + } + apple_sftl_free(sftl); + + /* Cold reload (simulating next Linux boot) and verify all 16 pages + zero torn records. */ + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &cold), 0); + apple_sftl_get_info(cold, &info); + KUNIT_ASSERT_EQ(test, apple_sftl_inspect(cold, 0, insp, NULL), 0); + KUNIT_EXPECT_EQ(test, info.sequence, 10055ULL + N42_WRITE_TEST_DEFAULT_COUNT); + KUNIT_EXPECT_EQ(test, info.journal_sequence, info.sequence); + KUNIT_EXPECT_EQ(test, insp->nr_torn, 0U); + KUNIT_EXPECT_FALSE(test, insp->vfl_degraded); + KUNIT_EXPECT_FALSE(test, insp->context_degraded); + for (i = 0; i < N42_WRITE_TEST_DEFAULT_COUNT; i++) { + u32 lba = N42_WRITE_TEST_LBA_START + i; + + KUNIT_ASSERT_EQ(test, apple_sftl_read(cold, lba, rbuf), 0); + KUNIT_EXPECT_TRUE(test, + n42_write_pattern_check(rbuf, lba, N42_WRITE_TEST_DEFAULT_SEED, + i, &got_crc, &want_crc)); + } + /* Also confirm a flipped byte is caught by the pattern verifier. */ + rbuf[100] ^= 0x01; + KUNIT_EXPECT_FALSE(test, + n42_write_pattern_check(rbuf, N42_WRITE_TEST_LBA_START + 15, + N42_WRITE_TEST_DEFAULT_SEED, 15, + &got_crc, &want_crc)); + apple_sftl_free(cold); +} + +/* + * Fixture shared by the rung-2 cases: 16 GB N42 media with the context in + * block 2 (role 7), block 6 the only clean-free (role 1) block, the rest + * dirty-free; program-only provider (no erase). + */ +static struct n42_wfix *n42w_close_fixture_with(struct kunit *test, bool spare) +{ + struct n42_wfix *w = kunit_kzalloc(test, sizeof(*w), GFP_KERNEL); + struct apple_sftl_context_record *ctx; + u32 i, j; + + KUNIT_ASSERT_NOT_NULL(test, w); + ctx = kvzalloc(56 * sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, n42w_kvfree, ctx), 0); + for (i = 0; i < N42W_SLOTS; i++) { + for (j = 0; j < 4; j++) { + w->pages[i][j] = kvcalloc(T16_PAGES, sizeof(*w->pages[i][j]), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, w->pages[i][j]); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, n42w_kvfree, + w->pages[i][j]), 0); + } + } + w->base.blocks = N42_BLOCKS; + w->base.subblocks = N42_SUBBLOCKS; + w->base.vfl_block = N42_BLOCKS - 1; + w->base.ops.read_page = n42w_read; + w->base.ops.program_page = n42w_program; + w->base.ops.erase_block = NULL; + w->base.provider = (struct apple_ppn) { + .ops = &w->base.ops, .priv = w, .buses = 2, .caus = 2, + .blocks = N42_BLOCKS, .pages = T16_PAGES, + }; + + apple_sftl_test_native_prefix_for(ctx, N42_SUBBLOCKS); + put_unaligned_le32(1, ctx[0].data); + put_unaligned_le32(N42W_CTX_OLD, ctx[0].data + 4); + for (i = 0; i < N42_SUBBLOCKS; i++) { + u8 *e = ctx[8 + i / 512].data + (i % 512) * 8; + + e[0] = i == 0 ? 8 : i == N42W_CTX_OLD ? 7 : i == N42W_APPEND ? 1 : + spare && i == N42W_CTX_NEW ? 1 : 9; + } + for (i = 0; i < 24; i++) + apple_sftl_context_meta(ctx[i].meta, ctx[i].meta[1], 10000 + i, + get_unaligned_le16(ctx[i].meta + 8), + get_unaligned_le16(ctx[i].meta + 10)); + for (i = 24; i < 56; i++) { + memset(ctx[i].data, 0xff, 4096); + apple_sftl_context_meta(ctx[i].meta, 4, 10000 + i, 0, 0); + } + put_unaligned_le32(0, ctx[24].data); + put_unaligned_le32(0xfffffff0, ctx[24].data + 4); + put_unaligned_le32(T16_UNMAPPED, ctx[24].data + 8); + put_unaligned_le32(T16_LPAGES, ctx[24].data + 12); + for (i = 0; i < 56; i += 4) { + struct n42_wpage *p = &w->pages[N42W_CTX_OLD - 2][(i / 4) % 4][(i / 4) / 4]; + + for (j = 0; j < 4; j++) { + memcpy(p->data + j * 4096, ctx[i + j].data, 4096); + memcpy(p->oob + j * 16, ctx[i + j].meta, 16); + } + p->written = true; + } + return w; +} + +static struct n42_wfix *n42w_close_fixture(struct kunit *test) +{ + return n42w_close_fixture_with(test, false); +} + +/* + * Rung 2: n42_close_fill() (the code debugfs close_test runs) fills chunk + * 950 until the writer closes block 6 with a native nb=4 BTOC and stops: + * 1023 data programs + 1 BTOC program, no erase, append point closed. The + * BTOC bytes read from flash and a cold reload of all 4092 pages match. + */ +static void sftl_test_n42_close_btoc(struct kunit *test) +{ + struct n42_wfix *w = n42w_close_fixture(test); + struct apple_sftl *sftl = NULL, *cold = NULL; + struct apple_sftl_info info; + struct apple_sftl_inspect *insp; + struct n42_close_result r; + struct n42_btoc_info bi; + u8 *batch, *rbuf, oob[APPLE_PPN_OOB_SIZE]; + u32 matched, bad; + + insp = kvzalloc(sizeof(*insp), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, insp); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, n42w_kvfree, insp), 0); + batch = kunit_kmalloc(test, APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + rbuf = kunit_kmalloc(test, APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, batch); + KUNIT_ASSERT_NOT_NULL(test, rbuf); + + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &sftl), 0); + apple_sftl_test_enable_writer(sftl); + + /* Empty fence: the fill is refused before anything is programmed. */ + apple_sftl_set_write_fence(sftl, 0, 0); + KUNIT_EXPECT_EQ(test, n42_close_fill(sftl, insp, batch, N42_WRITE_TEST_LBA_START, + N42_WRITE_TEST_LBA_END, N42_CLOSE_TEST_SEED, + NULL, NULL, &r), -EPERM); + KUNIT_EXPECT_EQ(test, w->programs, 0U); + + apple_sftl_set_write_fence(sftl, N42_WRITE_TEST_LBA_START, N42_WRITE_TEST_LBA_END); + KUNIT_ASSERT_EQ(test, n42_close_fill(sftl, insp, batch, N42_WRITE_TEST_LBA_START, + N42_WRITE_TEST_LBA_END, N42_CLOSE_TEST_SEED, + NULL, NULL, &r), 0); + apple_sftl_set_write_fence(sftl, 0, 0); + KUNIT_EXPECT_TRUE(test, r.closed); + KUNIT_EXPECT_EQ(test, r.block, N42W_APPEND); + KUNIT_EXPECT_EQ(test, r.lanes, (u16)0xf); + KUNIT_EXPECT_EQ(test, r.slots, 4096U); + KUNIT_EXPECT_EQ(test, r.written, 4092U); + KUNIT_EXPECT_EQ(test, r.writes, 1023U); + KUNIT_EXPECT_EQ(test, r.nb, 4U); + KUNIT_EXPECT_EQ(test, r.seq_after - r.seq_before, 4092ULL); + KUNIT_EXPECT_EQ(test, w->programs, 1024U); + KUNIT_EXPECT_EQ(test, w->erases, 0U); + KUNIT_EXPECT_FALSE(test, w->fenced); + KUNIT_ASSERT_EQ(test, apple_sftl_inspect(sftl, 0, insp, NULL), 0); + KUNIT_EXPECT_EQ(test, insp->append_block, U32_MAX); + /* Stopped at the close: the disarmed fence refuses one more page. */ + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, N42_WRITE_TEST_LBA_END - 4, batch, 4), -EPERM); + KUNIT_EXPECT_EQ(test, w->programs, 1024U); + + KUNIT_EXPECT_EQ(test, n42_close_check_btoc(&w->base.provider, r.lanes, T16_PAGES, + r.block, N42_WRITE_TEST_LBA_START, r.written, + r.nb, r.seq_before + 1, rbuf, oob, &bi), 0); + KUNIT_EXPECT_EQ(test, bi.flags, (u8)0x08); + KUNIT_EXPECT_EQ(test, bi.span, 4092U); + KUNIT_EXPECT_EQ(test, bi.run_total, 4092U); + /* A wrong BTOC base sequence is caught. */ + KUNIT_EXPECT_NE(test, n42_close_check_btoc(&w->base.provider, r.lanes, T16_PAGES, + r.block, N42_WRITE_TEST_LBA_START, r.written, + r.nb, r.seq_before + 2, rbuf, oob, &bi), 0); + apple_sftl_free(sftl); + + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &cold), 0); + apple_sftl_get_info(cold, &info); + KUNIT_ASSERT_EQ(test, apple_sftl_inspect(cold, 0, insp, NULL), 0); + KUNIT_EXPECT_EQ(test, info.sequence, r.seq_after); + KUNIT_EXPECT_EQ(test, info.journal_sequence, info.sequence); + KUNIT_EXPECT_EQ(test, insp->nr_torn, 0U); + KUNIT_EXPECT_EQ(test, insp->append_block, U32_MAX); + KUNIT_EXPECT_EQ(test, n42_close_verify(cold, rbuf, N42_WRITE_TEST_LBA_START, r.written, + N42_CLOSE_TEST_SEED, &matched, &bad), 0); + KUNIT_EXPECT_EQ(test, matched, 4092U); + /* The step-1 seed no longer matches the overwritten first pages. */ + KUNIT_EXPECT_NE(test, n42_close_verify(cold, rbuf, N42_WRITE_TEST_LBA_START, 16, + N42_WRITE_TEST_DEFAULT_SEED, &matched, &bad), 0); + apple_sftl_free(cold); +} + +/* Rung 2: a narrower armed fence stops the fill with -EPERM, nothing past it. */ +static void sftl_test_n42_close_fence_stops(struct kunit *test) +{ + struct n42_wfix *w = n42w_close_fixture(test); + struct apple_sftl *sftl = NULL; + struct apple_sftl_inspect *insp; + struct n42_close_result r; + u8 *batch; + + insp = kvzalloc(sizeof(*insp), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, insp); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, n42w_kvfree, insp), 0); + batch = kunit_kmalloc(test, APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, batch); + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &sftl), 0); + apple_sftl_test_enable_writer(sftl); + apple_sftl_set_write_fence(sftl, N42_WRITE_TEST_LBA_START, N42_WRITE_TEST_LBA_START + 64); + KUNIT_EXPECT_EQ(test, n42_close_fill(sftl, insp, batch, N42_WRITE_TEST_LBA_START, + N42_WRITE_TEST_LBA_END, N42_CLOSE_TEST_SEED, + NULL, NULL, &r), -EPERM); + KUNIT_EXPECT_EQ(test, r.fail_lba, N42_WRITE_TEST_LBA_START + 64); + KUNIT_EXPECT_EQ(test, r.written, 64U); + KUNIT_EXPECT_FALSE(test, r.closed); + KUNIT_EXPECT_EQ(test, w->programs, 16U); + KUNIT_EXPECT_FALSE(test, w->fenced); + /* A second fill refuses: the block is already open. */ + apple_sftl_set_write_fence(sftl, N42_WRITE_TEST_LBA_START, N42_WRITE_TEST_LBA_END); + KUNIT_EXPECT_EQ(test, n42_close_fill(sftl, insp, batch, N42_WRITE_TEST_LBA_START, + N42_WRITE_TEST_LBA_END, N42_CLOSE_TEST_SEED, + NULL, NULL, &r), -EBUSY); + KUNIT_EXPECT_EQ(test, w->programs, 16U); + apple_sftl_free(sftl); +} + +/* + * Rung 3: after a rung-2 close on one boot, apple_sftl_write_checkpoint() on + * the next writes one native generation into the other clean block, + * program only. A cold load selects it (base names it, roles 7/7/3, the + * same map, every page), and after the old context block is erased (as + * 12H321's boot does for an unnamed context) the media still loads. + */ +static void sftl_test_n42_checkpoint_program_only(struct kunit *test) +{ + struct n42_wfix *w = n42w_close_fixture_with(test, true); + struct apple_sftl *sftl = NULL, *cold = NULL; + struct apple_sftl_checkpoint_report rep; + struct apple_sftl_info info; + struct apple_sftl_inspect *insp; + struct n42_close_result r; + u8 *batch, *rbuf; + u32 matched, bad, programs, lane; + + insp = kvzalloc(sizeof(*insp), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, insp); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, n42w_kvfree, insp), 0); + batch = kunit_kmalloc(test, APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + rbuf = kunit_kmalloc(test, APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, batch); + KUNIT_ASSERT_NOT_NULL(test, rbuf); + + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &sftl), 0); + apple_sftl_test_enable_writer(sftl); + apple_sftl_set_write_fence(sftl, N42_WRITE_TEST_LBA_START, N42_WRITE_TEST_LBA_END); + KUNIT_ASSERT_EQ(test, n42_close_fill(sftl, insp, batch, N42_WRITE_TEST_LBA_START, + N42_WRITE_TEST_LBA_END, N42_CLOSE_TEST_SEED, + NULL, NULL, &r), 0); + apple_sftl_free(sftl); + + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &sftl), 0); + apple_sftl_test_enable_writer(sftl); + programs = w->programs; + KUNIT_ASSERT_EQ(test, apple_sftl_write_checkpoint(sftl, &rep), 0); + KUNIT_EXPECT_EQ(test, rep.old_ctx, N42W_CTX_OLD); + KUNIT_EXPECT_NE(test, rep.new_ctx, r.block); + KUNIT_EXPECT_TRUE(test, rep.new_ctx == N42W_CTX_NEW || rep.new_ctx == N42W_APPEND); + KUNIT_EXPECT_EQ(test, rep.reconciled_closed, 1U); + KUNIT_EXPECT_EQ(test, rep.nr_records, 56U); + KUNIT_EXPECT_EQ(test, w->programs - programs, rep.nr_pages); + KUNIT_EXPECT_EQ(test, w->erases, 0U); + KUNIT_EXPECT_FALSE(test, w->fenced); + KUNIT_EXPECT_EQ(test, rep.new_ckpt_seq, rep.seq_before + rep.nr_records); + /* A second checkpoint has no clean block left: refused, nothing programmed. */ + programs = w->programs; + KUNIT_EXPECT_EQ(test, apple_sftl_write_checkpoint(sftl, &rep), -ENOSPC); + KUNIT_EXPECT_EQ(test, w->programs, programs); + apple_sftl_free(sftl); + + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &cold), 0); + apple_sftl_get_info(cold, &info); + KUNIT_ASSERT_EQ(test, apple_sftl_inspect(cold, 0, insp, NULL), 0); + KUNIT_EXPECT_EQ(test, info.checkpoint_sequence, r.seq_after + 56); + KUNIT_EXPECT_EQ(test, info.sequence, info.checkpoint_sequence); + KUNIT_EXPECT_FALSE(test, insp->context_degraded); + KUNIT_EXPECT_EQ(test, insp->nr_torn, 0U); + KUNIT_EXPECT_EQ(test, insp->roles[N42W_CTX_OLD], 7); + KUNIT_EXPECT_EQ(test, insp->roles[r.block], 3); + KUNIT_EXPECT_EQ(test, n42_close_verify(cold, rbuf, N42_WRITE_TEST_LBA_START, r.written, + N42_CLOSE_TEST_SEED, &matched, &bad), 0); + apple_sftl_free(cold); + cold = NULL; + + for (lane = 0; lane < 4; lane++) + KUNIT_ASSERT_EQ(test, n42w_erase(w, lane & 1, lane >> 1, N42W_CTX_OLD), 0); + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &cold), 0); + apple_sftl_get_info(cold, &info); + KUNIT_EXPECT_EQ(test, info.checkpoint_sequence, r.seq_after + 56); + KUNIT_EXPECT_EQ(test, n42_close_verify(cold, rbuf, N42_WRITE_TEST_LBA_START, r.written, + N42_CLOSE_TEST_SEED, &matched, &bad), 0); + apple_sftl_free(cold); +} + +/* + * Rung 4: a synthetic N42 LwVM header (System + Data, chunks 947..952 free, + * 0xf3ff past the last whole chunk) gets the Linux entry from + * n42_lwvm_allocate(); only the count, CRC, one descriptor and six map + * words change; the fence derived from it is exactly LBAs [3878912,3903488). + * Written through the fixture (backup then primary, one-LBA fences), a cold + * load reads both copies back and derives the same fence. Writes outside the + * partition fence are refused. + */ +static void n42w_lwvm_header(u8 *h) +{ + static const u8 sig[16] = { 0x6a, 0x90, 0x88, 0xcf, 0x8a, 0xfd, 0x63, 0x0a, + 0xe3, 0x51, 0xe2, 0x48, 0x87, 0xe0, 0xb9, 0x8b }; + static const u8 hfs[16] = { 0x48, 0x46, 0x53, 0x00, 0x00, 0x00, 0x11, 0xaa, + 0xaa, 0x11, 0x00, 0x30, 0x65, 0x43, 0xec, 0xac }; + u32 k; + + memset(h, 0, 4096); + memcpy(h, sig, 16); + memset(h + 0x10, 0x5a, 16); + put_unaligned_le64(16000000000ULL, h + 0x20); + put_unaligned_le32(2, h + 0x28); + memcpy(h + 0x200, hfs, 16); + memset(h + 0x210, 0x11, 16); + put_unaligned_le64(0x6000, h + 0x220); + put_unaligned_le64(0x8e1d2000, h + 0x228); + memcpy(h + 0x238, "S\0y\0s\0", 6); + memcpy(h + 0x280, hfs, 16); + memset(h + 0x290, 0x22, 16); + put_unaligned_le64(0x8e1d2000, h + 0x2a0); + put_unaligned_le64(N42_LWVM_DATA_END, h + 0x2a8); + memcpy(h + 0x2b8, "D\0a\0t\0a\0", 8); + put_unaligned_le16(0xf000, h + 0x800); + /* + * After the 3 GiB release: System 143 chunks at 1..143 (2.3 GB), Data + * 192 chunks at 180..371; 144..179 and 372..952 free. + */ + for (k = 1; k < 1024; k++) { + u16 w = k < 144 ? (0 << 12 | (k - 1)) : + k >= 180 && k < 372 ? (1 << 12 | (k - 180)) : + k < 953 ? 0xf111 : 0xf3ff; + put_unaligned_le16(w, h + 0x800 + 2 * k); + } + put_unaligned_le32(n42_lwvm_crc(h), h + 0x2c); +} + +static void sftl_test_n42_lwvm_partition_fence(struct kunit *test) +{ + struct n42_wfix *w = n42w_close_fixture_with(test, true); + struct apple_sftl *sftl = NULL, *cold = NULL; + struct apple_sftl_lwvm *lw; + u8 *h, *out, *rb; + u32 slot = 0, start = 0, end = 0, k, diff = 0; + const u64 media = 16000000000ULL; + + lw = kvzalloc(sizeof(*lw), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, lw); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, n42w_kvfree, lw), 0); + h = kunit_kmalloc(test, 4096, GFP_KERNEL); + out = kunit_kmalloc(test, 4096, GFP_KERNEL); + rb = kunit_kmalloc(test, APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, h); + KUNIT_ASSERT_NOT_NULL(test, out); + KUNIT_ASSERT_NOT_NULL(test, rb); + + n42w_lwvm_header(h); + KUNIT_ASSERT_EQ(test, n42_lwvm_check(h, h, media, lw), 0); + KUNIT_EXPECT_EQ(test, n42_lwvm_released_layout(h, media, lw), 0); + KUNIT_EXPECT_EQ(test, n42_lwvm_linux_range(h, media, lw, &start, &end, &slot), -ENOENT); + KUNIT_ASSERT_EQ(test, n42_lwvm_allocate(h, h, media, N42_FS_FIRST_CHUNK, N42_FS_CHUNKS, + n42_lwvm_fs_guid, out, lw, &slot), 0); + KUNIT_EXPECT_EQ(test, slot, 2U); + for (k = 0; k < 4096; k++) + diff += out[k] != h[k]; + KUNIT_EXPECT_LE(test, diff, 8U + 128U + 12U); + KUNIT_ASSERT_EQ(test, n42_lwvm_linux_range(out, media, lw, &start, &end, &slot), 0); + KUNIT_EXPECT_EQ(test, start, N42_FS_LBA_START); + KUNIT_EXPECT_EQ(test, end, N42_FS_LBA_END); + KUNIT_EXPECT_EQ(test, n42_lwvm_allocate(out, out, media, N42_FS_FIRST_CHUNK, N42_FS_CHUNKS, + n42_lwvm_fs_guid, rb, lw, &slot), -EEXIST); + KUNIT_EXPECT_EQ(test, n42_lwvm_allocate(h, out, media, N42_FS_FIRST_CHUNK, N42_FS_CHUNKS, + n42_lwvm_fs_guid, rb, lw, &slot), -EUCLEAN); + KUNIT_EXPECT_EQ(test, n42_lwvm_allocate(h, h, media, 177, N42_FS_CHUNKS, + n42_lwvm_fs_guid, rb, lw, &slot), -ENOSPC); + KUNIT_EXPECT_EQ(test, n42_lwvm_released_layout(out, media, lw), -ESTALE); + memcpy(rb, h, 4096); + put_unaligned_le64(N42_LWVM_DATA_END + (16ULL << 20), rb + 0x2a8); + put_unaligned_le16(1 << 12 | 192, rb + 0x800 + 2 * 372); + put_unaligned_le32(n42_lwvm_crc(rb), rb + 0x2c); + KUNIT_EXPECT_EQ(test, n42_lwvm_check(rb, rb, media, lw), 0); + KUNIT_EXPECT_EQ(test, n42_lwvm_released_layout(rb, media, lw), -ESTALE); + + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &sftl), 0); + apple_sftl_test_enable_writer(sftl); + apple_sftl_set_write_fence(sftl, N42_LWVM_BACKUP_LBA, N42_LWVM_BACKUP_LBA + 1); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, N42_LWVM_PRIMARY_LBA, out, 1), -EPERM); + KUNIT_ASSERT_EQ(test, apple_sftl_write(sftl, N42_LWVM_BACKUP_LBA, out, 1), 0); + apple_sftl_set_write_fence(sftl, N42_LWVM_PRIMARY_LBA, N42_LWVM_PRIMARY_LBA + 1); + KUNIT_ASSERT_EQ(test, apple_sftl_write(sftl, N42_LWVM_PRIMARY_LBA, out, 1), 0); + apple_sftl_set_write_fence(sftl, start, end); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, 0, out, 1), -EPERM); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, start - 1, out, 1), -EPERM); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, end, out, 1), -EPERM); + memset(rb, 0xa5, 4 * 4096); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, start, rb, 4), 0); + KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, end - 1, rb, 1), 0); + KUNIT_EXPECT_EQ(test, w->programs, 4U); + KUNIT_EXPECT_EQ(test, w->erases, 0U); + KUNIT_EXPECT_FALSE(test, w->fenced); + apple_sftl_free(sftl); + + KUNIT_ASSERT_EQ(test, apple_sftl_load(&w->base.provider, &cold), 0); + KUNIT_ASSERT_EQ(test, apple_sftl_read(cold, N42_LWVM_BACKUP_LBA, rb), 0); + KUNIT_EXPECT_EQ(test, memcmp(rb, out, 4096), 0); + KUNIT_ASSERT_EQ(test, apple_sftl_read(cold, N42_LWVM_PRIMARY_LBA, rb), 0); + KUNIT_EXPECT_EQ(test, memcmp(rb, out, 4096), 0); + KUNIT_EXPECT_EQ(test, n42_lwvm_linux_range(rb, media, lw, &start, &end, &slot), 0); + KUNIT_EXPECT_EQ(test, start, N42_FS_LBA_START); + KUNIT_ASSERT_EQ(test, apple_sftl_read(cold, end - 1, rb), 0); + KUNIT_EXPECT_EQ(test, rb[100], 0xa5); + apple_sftl_free(cold); +} + static struct kunit_case apple_sftl_cases[] = { KUNIT_CASE(sftl_test_rotate_mounted), KUNIT_CASE(sftl_test_vfl_rotation_cuts), @@ -4516,6 +5716,18 @@ static struct kunit_case apple_sftl_cases[] = { KUNIT_CASE(sftl_test_16gb_closed_trim_flag1), KUNIT_CASE(sftl_test_16gb_hidden_tail), KUNIT_CASE(sftl_test_n42_repeated_sequence), + KUNIT_CASE(sftl_test_n42_ios_relocated_copy), + KUNIT_CASE(sftl_test_n42_ios_gap), + KUNIT_CASE(sftl_test_n42_ios_conflict_order), + KUNIT_CASE(sftl_test_n42_ios_non_monotonic), + KUNIT_CASE(sftl_test_n42_ios_uecc_then_data), + KUNIT_CASE(sftl_test_n42_vfl_single_bank_healthy), + KUNIT_CASE(sftl_test_n42_writer_append_and_gc), + KUNIT_CASE(sftl_test_n42_write_fence_and_pattern), + KUNIT_CASE(sftl_test_n42_close_btoc), + KUNIT_CASE(sftl_test_n42_close_fence_stops), + KUNIT_CASE(sftl_test_n42_checkpoint_program_only), + KUNIT_CASE(sftl_test_n42_lwvm_partition_fence), {} }; diff --git a/drivers/mtd/apple-sftl.h b/drivers/mtd/apple-sftl.h index 205e7ce060def8..e206d51e0b21cf 100644 --- a/drivers/mtd/apple-sftl.h +++ b/drivers/mtd/apple-sftl.h @@ -6,8 +6,10 @@ #include #include "apple-sftl-reclaim.h" +#include "apple-sftl-vfl.h" struct apple_sftl; +struct mutex; enum apple_sftl_retired_phase { APPLE_SFTL_PREPARE_RETIRED, @@ -55,6 +57,7 @@ void apple_sftl_set_checkpoint_ops(struct apple_sftl *sftl, struct apple_sftl_info { bool n42_install; bool read_only; + bool tolerated; /* diag_journal loaded past an anomaly: no checkpoint */ u32 logical_pages; u32 disk_pages; u32 nr_runs; @@ -63,12 +66,81 @@ struct apple_sftl_info { u64 journal_sequence; }; +int apple_sftl_load_disk(struct apple_ppn *provider, struct apple_sftl **out); +void apple_sftl_start_gc(struct apple_sftl *sftl, struct mutex *disk_io_lock); int apple_sftl_load(struct apple_ppn *provider, struct apple_sftl **out); void apple_sftl_free(struct apple_sftl *sftl); int apple_sftl_read(struct apple_sftl *sftl, u32 logical_page, u8 *data); +/* Scatter a completed 4 KiB chunk to request slot @index. NULL means zeros. */ +typedef void (*apple_sftl_copy_chunk)(void *priv, unsigned int index, const u8 *data); +typedef struct page *(*apple_sftl_read_target)(void *priv, unsigned int index); +int apple_sftl_read_targets(struct apple_sftl *sftl, const u32 *logical, unsigned int count, + apple_sftl_copy_chunk copy, apple_sftl_read_target target, void *priv); +int apple_sftl_read_multi(struct apple_sftl *sftl, const u32 *logical, unsigned int count, + apple_sftl_copy_chunk copy, void *priv); int apple_sftl_write(struct apple_sftl *sftl, u32 logical_page, const u8 *data, unsigned int count); +#define APPLE_SFTL_WRITE_MAX 1024 /* 4 MiB of 4 KiB logical pages */ +int apple_sftl_write_multi(struct apple_sftl *sftl, u32 logical_page, + const u8 *data, unsigned int count); +int apple_sftl_trim(struct apple_sftl *sftl, u32 logical_page, unsigned int count); int apple_sftl_flush(struct apple_sftl *sftl); +void apple_sftl_set_write_fence(struct apple_sftl *sftl, u32 start, u32 end); +int apple_sftl_set_write_fences(struct apple_sftl *sftl, const u32 (*ranges)[2], u32 nr); +u32 apple_sftl_get_write_fences(struct apple_sftl *sftl, u32 (*ranges)[2]); void apple_sftl_get_info(struct apple_sftl *sftl, struct apple_sftl_info *info); +struct apple_sftl_inspect { + struct apple_sftl_vfl_source vfl_source; + u16 buses, caus, lanes; + u16 blocks, pages, subblocks; + u16 vfl_pages, vfl_first, map_batch; + u32 stride, disk_pages, lpages; + u32 nr_equal, nr_torn; + u32 append_block, append_position; + u64 checkpoint_start; + bool vfl_degraded, context_degraded, native_context; + bool torn_in_place; /* torn blocks are left as they are, never evacuated */ + u16 block_lanes[2088]; + u8 roles[2086]; + u8 block_flags[2086]; + u16 wear[2086]; + u32 context_blocks[16]; + u32 nr_context_blocks; +}; + +int apple_sftl_inspect(struct apple_sftl *sftl, size_t max_bytes, + struct apple_sftl_inspect *info, + struct apple_sftl_snapshot **snapshot_out); + + +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) || \ + IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) +struct apple_sftl_checkpoint_report { + u32 old_ctx; + u32 new_ctx; + u32 nr_records; + u32 nr_pages; + u32 nr_runs; + u32 reconciled_closed; + u32 reconciled_open; + u64 old_ckpt_seq; + u64 new_ckpt_seq; + u64 seq_before; + u64 seq_after; +}; + +int apple_sftl_write_checkpoint(struct apple_sftl *sftl, + struct apple_sftl_checkpoint_report *report); +#endif + +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) || \ + IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) +int apple_sftl_set_reuse_dirty(struct apple_sftl *sftl, bool enable); +#endif + +#if IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) +void apple_sftl_test_enable_writer(struct apple_sftl *sftl); +#endif + #endif From fb1802023c93211dc899e584866682ffcb660d61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 18:18:33 +0100 Subject: [PATCH 47/59] ARM: dts: apple: Wire the iPhone 5 NAND CDMA engine 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-n42.dts | 4 ++++ arch/arm/boot/dts/apple/s5l8950x.dtsi | 17 ++++++++++------- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/arch/arm/boot/dts/apple/s5l8950x-n42.dts b/arch/arm/boot/dts/apple/s5l8950x-n42.dts index 57acd61ab757f3..1e23b2ce452638 100644 --- a/arch/arm/boot/dts/apple/s5l8950x-n42.dts +++ b/arch/arm/boot/dts/apple/s5l8950x-n42.dts @@ -27,3 +27,7 @@ linux,initrd-end = <0x88000000>; }; }; + +&cdma_ps { + status = "okay"; +}; diff --git a/arch/arm/boot/dts/apple/s5l8950x.dtsi b/arch/arm/boot/dts/apple/s5l8950x.dtsi index 7b0de51ff8fe7e..30ed7f81252342 100644 --- a/arch/arm/boot/dts/apple/s5l8950x.dtsi +++ b/arch/arm/boot/dts/apple/s5l8950x.dtsi @@ -204,10 +204,7 @@ * latch", gadget start -EIO) although no USB gate is among * them. An unregistered gate keeps the state iBoot left. */ - /* - * CDMA (ADT id 0x31, index 0x1f). No Linux driver claims it yet, - * so no board should enable it: it must stay as iBoot left it. - */ + /* CDMA clock gate, enabled on boards using the NAND sequencer. */ cdma_ps: cdma-ps@f10107c { compatible = "apple,s5l8940x-pmgr-clk-gate"; #clock-cells = <0>; @@ -540,13 +537,19 @@ <0x1280000 0x1000>, /* ECC0 */ <0x1300000 0x1000>, /* FMI1 */ <0x1340000 0x1000>, /* FMC1 */ - <0x1380000 0x1000>; /* ECC1 */ - interrupts = <33>, <34>; + <0x1380000 0x1000>, /* ECC1 */ + <0x7000000 0x2d000>; /* CDMA */ + /* AppleCDMA uses interrupt index channel - 1 (12H321 + * 0x80b30a64..0x80b30a7a). ADT cdma index 0 is AIC 51. + */ + interrupts = <33>, <34>, <55>, <56>, <57>, <58>; clocks = <&fmi0_ps>, <&fmi0_bch_ps>, <&fmi1_ps>, - <&fmi1_bch_ps>, <&fmi_dll_ps>; + <&fmi1_bch_ps>, <&fmi_dll_ps>, <&cdma_ps>; + apple,dma-channels = <5 0>, <7 2>; status = "disabled"; }; + /* * USB OTG PHY (ADT /arm-io/otgphyctrl + /arm-io/usb-complex). * Uses S5L8950X PMGR gates (+0x1084/+0x1088/+0x109c) and From 4b1d785f12062d1313508f575fd7e6a3585ddaaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Tue, 1 Dec 2026 22:36:58 +0100 Subject: [PATCH 48/59] ARM: configs: enable fenced N42 Linux partition writes in Orchard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The installer uses the Orchard ARMv7 defconfig. Select the partition-scoped SFTL writer so an accepted N42 Linux partition can receive the release. Raw MTD and iOS partitions retain their existing restrictions. 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 55d68b10e74f18..a2b841ced344fb 100644 --- a/arch/arm/configs/orchard_applearmv7_defconfig +++ b/arch/arm/configs/orchard_applearmv7_defconfig @@ -139,6 +139,7 @@ CONFIG_IMX_SCMI_MISC_DRV=y CONFIG_MTD=y CONFIG_MTD_CMDLINE_PARTS=y CONFIG_MTD_APPLE_SFTL=y +CONFIG_MTD_APPLE_SFTL_N42_WRITE=y CONFIG_MTD_CFI=y CONFIG_MTD_CFI_INTELEXT=y CONFIG_MTD_PHYSMAP=y From b4c256b9656953b4a8440c24901cd38951a37a1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Wed, 2 Dec 2026 16:32:41 +0100 Subject: [PATCH 49/59] mtd: apple-sftl: expose fenced N42 padding and shutdown checkpoints 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/mtd/apple-sftl-block.c | 103 +++++++++++++++++++++++++++++++++ drivers/mtd/apple-sftl-core.c | 28 +++++++++ drivers/mtd/apple-sftl.h | 1 + 3 files changed, 132 insertions(+) diff --git a/drivers/mtd/apple-sftl-block.c b/drivers/mtd/apple-sftl-block.c index f076e4ab89332c..d1bd44b265f0e9 100644 --- a/drivers/mtd/apple-sftl-block.c +++ b/drivers/mtd/apple-sftl-block.c @@ -2,6 +2,7 @@ /* Block frontend for Apple's VFL/SwissPPNFTL logical medium. */ #include #include +#include #include #include #include @@ -42,6 +43,11 @@ struct sftl_disk { bool writable; struct sftl_view *view; bool n42_writable; +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) + struct dentry *ctl_dir; + unsigned int checkpoints; + char ctl_status[384]; +#endif }; /* @@ -713,6 +719,94 @@ static void sftl_remove_view(struct sftl_disk *sftl) sftl->view = NULL; } #if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) +static ssize_t install_ctl_read(struct file *file, char __user *out, size_t count, + loff_t *pos) +{ + struct sftl_disk *disk = file->private_data; + ssize_t ret; + + mutex_lock(&disk->io_lock); + ret = simple_read_from_buffer(out, count, pos, disk->ctl_status, + strlen(disk->ctl_status)); + mutex_unlock(&disk->io_lock); + return ret; +} + +static ssize_t install_ctl_write(struct file *file, const char __user *in, size_t count, + loff_t *pos) +{ + struct sftl_disk *disk = file->private_data; + struct apple_sftl_checkpoint_report rep = {}; + struct apple_sftl_info info; + char input[128], *cmd; + u32 lba = 0, pages = 0; + bool pad; + int ret; + + if (!capable(CAP_SYS_ADMIN)) + return -EPERM; + if (!count || count >= sizeof(input)) + return -EINVAL; + if (copy_from_user(input, in, count)) + return -EFAULT; + if (memchr(input, 0, count)) + return -EINVAL; + input[count] = 0; + cmd = strim(input); + pad = str_has_prefix(cmd, "pad "); + if (pad) { + if (kstrtou32(skip_spaces(cmd + 4), 0, &lba)) + return -EINVAL; + } else if (strcmp(cmd, "checkpoint")) { + return -EINVAL; + } + + mutex_lock(&disk->io_lock); + apple_sftl_get_info(disk->ftl, &info); + if (disk->dead || !disk->n42_writable || info.read_only) + ret = -EROFS; + else if (pad) + ret = apple_sftl_pad_open_block(disk->ftl, lba, disk->buffer, &pages); + else if (info.tolerated) + ret = -EPERM; + else if (disk->checkpoints >= 8) + ret = -EMLINK; + else { + ret = apple_sftl_write_checkpoint(disk->ftl, &rep); + if (!ret) + disk->checkpoints++; + } + apple_sftl_get_info(disk->ftl, &info); + if (pad) + scnprintf(disk->ctl_status, sizeof(disk->ctl_status), + "pad: from %u rewrote %u pages, closed=%d ret=%d\n", + lba, pages, !ret || ret == -EALREADY, ret); + else + scnprintf(disk->ctl_status, sizeof(disk->ctl_status), + "checkpoint: ret=%d ctx %u -> %u records=%u pages=%u runs=%u reconciled closed=%u open=%u ckpt %llu -> %llu (#%u this boot)\n", + ret, rep.old_ctx, rep.new_ctx, rep.nr_records, rep.nr_pages, + rep.nr_runs, rep.reconciled_closed, rep.reconciled_open, + rep.old_ckpt_seq, rep.new_ckpt_seq, disk->checkpoints); + { + size_t len = strlen(disk->ctl_status); + + scnprintf(disk->ctl_status + len, sizeof(disk->ctl_status) - len, + "RESULT: %s (%s %d) seq=%llu ckpt=%llu\n", + ret ? "FAIL" : "PASS", pad ? "pad" : "checkpoint", ret, + info.sequence, info.checkpoint_sequence); + } + mutex_unlock(&disk->io_lock); + return ret ? ret : count; +} + +static const struct file_operations install_ctl_fops = { + .owner = THIS_MODULE, + .open = simple_open, + .read = install_ctl_read, + .write = install_ctl_write, + .llseek = default_llseek, +}; + /* * N42 write tests: the block device is writable, and the SFTL hard LBA * fence is every Linux or XBOOTLDR LwVM entry inside the install windows, @@ -866,6 +960,12 @@ static int sftl_disk_probe(struct platform_device *pdev) info.disk_pages, info.sequence); if (sftl->writable) apple_sftl_start_gc(sftl->ftl, &sftl->io_lock); +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) + if (info.n42_install) { + sftl->ctl_dir = debugfs_create_dir("n42_sftl", NULL); + debugfs_create_file("install_ctl", 0600, sftl->ctl_dir, sftl, &install_ctl_fops); + } +#endif sftl_add_view(pdev, sftl, &info); return 0; @@ -889,6 +989,9 @@ static void sftl_disk_remove(struct platform_device *pdev) { struct sftl_disk *sftl = platform_get_drvdata(pdev); +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) + debugfs_remove_recursive(sftl->ctl_dir); +#endif mutex_lock(&sftl->io_lock); sftl->dead = true; mutex_unlock(&sftl->io_lock); diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c index 67b431ee24c16f..b940223773462e 100644 --- a/drivers/mtd/apple-sftl-core.c +++ b/drivers/mtd/apple-sftl-core.c @@ -7451,6 +7451,34 @@ static int sftl_gc_save(struct apple_sftl *sftl) return ret; } +/* Caller holds the disk I/O lock, also taken by background GC. Use only + * ordinary fenced writes, rewriting each logical page with its own bytes. + */ +int apple_sftl_pad_open_block(struct apple_sftl *sftl, u32 lba, u8 *page, u32 *pages) +{ + bool open; + int ret; + + *pages = 0; + for (;;) { + mutex_lock(&sftl->lock); + open = sftl->append_block != U32_MAX; + mutex_unlock(&sftl->lock); + if (!open) + return *pages ? 0 : -EALREADY; + if (*pages >= 4096) + return -ENOSPC; + ret = apple_sftl_read(sftl, lba, page); + if (!ret) + ret = apple_sftl_write(sftl, lba, page, 1); + if (ret) + return ret; + (*pages)++; + lba++; + } +} +EXPORT_SYMBOL_GPL(apple_sftl_pad_open_block); + int apple_sftl_write_checkpoint(struct apple_sftl *sftl, struct apple_sftl_checkpoint_report *rep) { diff --git a/drivers/mtd/apple-sftl.h b/drivers/mtd/apple-sftl.h index e206d51e0b21cf..9150264584325c 100644 --- a/drivers/mtd/apple-sftl.h +++ b/drivers/mtd/apple-sftl.h @@ -130,6 +130,7 @@ struct apple_sftl_checkpoint_report { u64 seq_after; }; +int apple_sftl_pad_open_block(struct apple_sftl *sftl, u32 lba, u8 *page, u32 *pages); int apple_sftl_write_checkpoint(struct apple_sftl *sftl, struct apple_sftl_checkpoint_report *report); #endif From 3c7f1d95431809d3ca170a7dc5c123c70a882dd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Wed, 2 Dec 2026 20:54:17 +0100 Subject: [PATCH 50/59] ARM: configs: orchard_applearmv7: enable phram for the live ADT MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit m1n1 hands the 32-bit kernel Apple's live device tree as a phram region labelled adt; Orchard's install receiver reads the device's ECID there. 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 a2b841ced344fb..7c7c15f22bed26 100644 --- a/arch/arm/configs/orchard_applearmv7_defconfig +++ b/arch/arm/configs/orchard_applearmv7_defconfig @@ -137,6 +137,7 @@ CONFIG_TRUSTED_FOUNDATIONS=y CONFIG_EFI_CAPSULE_LOADER=m CONFIG_IMX_SCMI_MISC_DRV=y CONFIG_MTD=y +CONFIG_MTD_PHRAM=y CONFIG_MTD_CMDLINE_PARTS=y CONFIG_MTD_APPLE_SFTL=y CONFIG_MTD_APPLE_SFTL_N42_WRITE=y From 1bd0874c2b1b7dfdf01db4b4fac49d189e93d007 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Wed, 2 Dec 2026 21:26:15 +0100 Subject: [PATCH 51/59] mtd: apple-sftl: N42: let the install release Data's LwVM tail as iOS does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After iOS shrinks Data's filesystem to 3 GiB (resize-hfs-n42), its LwVM table still gives Data the restore's whole tail. The install may now write, in the header that adds its Linux entries or alone, iOS's own release of that tail (n42_lwvm_release: Data ends at 5,605,498,880, its chunks past that are free, the CRC again). It is taken only from the restore's two-entry table, and only when Data's HFS+ volume header, read from the flash through the table, gives a filesystem that fits. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/apple-n42-lwvm-alloc.h | 49 ++++++++++++++++++++ drivers/mtd/apple-sftl-block.c | 73 ++++++++++++++++++++++++++++-- 2 files changed, 119 insertions(+), 3 deletions(-) diff --git a/drivers/mtd/apple-n42-lwvm-alloc.h b/drivers/mtd/apple-n42-lwvm-alloc.h index eae7fdbf9a9bbb..345ccd3571f574 100644 --- a/drivers/mtd/apple-n42-lwvm-alloc.h +++ b/drivers/mtd/apple-n42-lwvm-alloc.h @@ -39,6 +39,9 @@ #define N42_LWVM_BACKUP_LBA (N42_FS_CHUNK_LBAS - 1U) /* 16 MiB - 4 KiB */ /* Data's end after the 3 GiB release; the only layout lwvm_create accepts. */ #define N42_LWVM_DATA_END 5605498880ULL +/* Data's end as the 12H321 restore leaves it (2,384,273,408 + 13,470,220,288). */ +#define N42_LWVM_DATA_ORIGINAL_END 15854493696ULL + #define N42_LWVM_BYTES 4096U #define N42_LWVM_ID 0x10U @@ -75,6 +78,52 @@ static inline u32 n42_lwvm_crc(const u8 *h) return ~crc; } +/* + * iOS's own LwVM tail release for a Data filesystem shrunk to 3 GiB, byte for + * byte (resize-hfs-n42 n42_release_header, Shayne Legault, MIT; the header + * AppleLwVM writes): Data's end lowered to N42_LWVM_DATA_END, every Data + * chunk past it marked free, the CRC again. Nothing else changes. BEFORE must + * be the restore's two-entry layout, else -ESTALE. The caller checks that + * Data's filesystem fits before the header is written. + */ +static inline int n42_lwvm_release(const u8 *before, u8 *after, u64 media, + struct apple_sftl_lwvm *lw) +{ + u32 keep, k; + int ret = apple_sftl_lwvm_decode(before, media, lw); + + if (ret) + return ret; + if (lw->nr_parts != 2 || lw->parts[1].pieced || + lw->parts[1].end != N42_LWVM_DATA_ORIGINAL_END || + lw->parts[1].begin >= N42_LWVM_DATA_END || + (N42_LWVM_DATA_END - lw->parts[1].begin) & ((1ULL << lw->chunk_shift) - 1)) + return -ESTALE; + keep = (N42_LWVM_DATA_END - lw->parts[1].begin) >> lw->chunk_shift; + memcpy(after, before, N42_LWVM_BYTES); + put_unaligned_le64(N42_LWVM_DATA_END, after + N42_LWVM_PARTS + N42_LWVM_PART_BYTES + 40); + for (k = 1; k < APPLE_SFTL_LWVM_CHUNKS; k++) { + u16 w = get_unaligned_le16(after + N42_LWVM_MAP + 2 * k); + + if ((w >> 12) == 1 && (w & 0x3ff) >= keep) + put_unaligned_le16(N42_LWVM_FREE, after + N42_LWVM_MAP + 2 * k); + } + put_unaligned_le32(n42_lwvm_crc(after), after + N42_LWVM_CRC); + ret = apple_sftl_lwvm_decode(after, media, lw); + if (ret) + return ret; + return lw->nr_parts == 2 && lw->parts[1].end == N42_LWVM_DATA_END && + !lw->parts[1].pieced ? 0 : -EINVAL; +} + +/* Data's end in HEADER (entry 2), or 0 when it has fewer entries. */ +static inline u64 n42_lwvm_data_end(const u8 *header) +{ + if (get_unaligned_le32(header + N42_LWVM_COUNT) < 2) + return 0; + return get_unaligned_le64(header + N42_LWVM_PARTS + N42_LWVM_PART_BYTES + 40); +} + static inline bool n42_lwvm_is_linux_entry(const u8 *entry) { static const u8 name[12] = { 'L', 0, 'i', 0, 'n', 0, 'u', 0, 'x', 0, 0, 0 }; diff --git a/drivers/mtd/apple-sftl-block.c b/drivers/mtd/apple-sftl-block.c index d1bd44b265f0e9..5eefc991592a19 100644 --- a/drivers/mtd/apple-sftl-block.c +++ b/drivers/mtd/apple-sftl-block.c @@ -318,13 +318,41 @@ static int sftl_read_request(struct sftl_disk *sftl, struct request *request) * n42_lwvm_header_write_ok() takes it, behind a one-page fence of its own. * After the primary the fence becomes the entries of the new header. */ +/* + * The size Data's own HFS+/HFSX volume header gives (block size times total + * blocks), read from the flash through LWVM's map of Data (entry 2): what a + * tail release must keep. 0 when it can't be read or isn't HFS. + */ +static u64 sftl_n42_data_fs_bytes(struct sftl_disk *sftl, const struct apple_sftl_lwvm *lw) +{ + u64 disk; + u8 *page; + u64 bytes = 0; + const u8 *v; + + if (lw->nr_parts < 2 || apple_sftl_lwvm_map(&lw->parts[1], 1024, &disk)) + return 0; + page = kmalloc(SFTL_LOGICAL_BYTES, GFP_NOIO); + if (!page) + return 0; + if (!apple_sftl_read(sftl->ftl, disk / SFTL_LOGICAL_BYTES, page)) { + v = page + disk % SFTL_LOGICAL_BYTES; + if (disk % SFTL_LOGICAL_BYTES + 512 <= SFTL_LOGICAL_BYTES && + (get_unaligned_be16(v) == 0x4858 || get_unaligned_be16(v) == 0x482b)) + bytes = (u64)get_unaligned_be32(v + 40) * get_unaligned_be32(v + 44); + } + kfree(page); + return bytes; +} + static int sftl_n42_header_write(struct sftl_disk *sftl, u32 lba) { struct device *dev = disk_to_dev(sftl->disk); u32 ranges[N42_INSTALL_MAX_RANGES][2], slots[N42_INSTALL_MAX_RANGES], nr, keep[4][2], nr_keep, i; struct apple_sftl_lwvm *lw; struct apple_sftl_info info; - u8 *p, *b; + u8 *p, *b, *released = NULL; + bool release_only = false; u64 media; int ret; @@ -338,8 +366,41 @@ static int sftl_n42_header_write(struct sftl_disk *sftl, u32 lba) ret = apple_sftl_read(sftl->ftl, N42_LWVM_PRIMARY_LBA, p); if (!ret) ret = apple_sftl_read(sftl->ftl, N42_LWVM_BACKUP_LBA, b); - if (!ret) - ret = n42_lwvm_header_write_ok(p, b, sftl->buffer, lba, media, lw); + /* + * iOS shrank Data to 3 GiB (resize-hfs-n42) and left the LwVM table as + * the restore wrote it: the host releases Data's tail here, in the same + * header as its Linux entries or alone. The header must start from + * iOS's own release of the table on the flash (n42_lwvm_release), and + * Data's filesystem, read from the flash, must fit the released size. + */ + if (!ret && n42_lwvm_data_end(p) == N42_LWVM_DATA_ORIGINAL_END && + n42_lwvm_data_end(sftl->buffer) == N42_LWVM_DATA_END) { + u64 fs; + + released = kmalloc(N42_LWVM_BYTES, GFP_NOIO); + ret = released ? n42_lwvm_release(p, released, media, lw) : -ENOMEM; + fs = ret ? 0 : sftl_n42_data_fs_bytes(sftl, lw); + if (!ret && (!fs || fs > N42_LWVM_DATA_END - lw->parts[1].begin)) { + dev_warn(dev, "N42 install: Data's filesystem (%llu bytes) does not fit the released 3 GiB\n", fs); + ret = -EPERM; + } + release_only = !ret && !memcmp(sftl->buffer, released, N42_LWVM_BYTES); + if (!ret) + dev_info(dev, "N42 install: releasing Data's LwVM tail (filesystem %llu bytes)%s\n", + fs, release_only ? ", no Linux entries yet" : ""); + } + if (!ret && release_only) + /* The copy first over an unchanged pair, then the primary over that copy. */ + ret = !memcmp(lba ? p : b, lba ? b : sftl->buffer, N42_LWVM_BYTES) ? 0 : -EPERM; + else if (!ret) + /* + * With a release, the pair on the flash counts as iOS's release: + * for the copy both halves are; for the primary the copy just + * written stands as it is. + */ + ret = n42_lwvm_header_write_ok(released ?: p, + released && lba ? released : b, + sftl->buffer, lba, media, lw); if (ret) { dev_warn(dev, "N42 install: LwVM header write to LBA %u refused (%d)\n", lba, ret); ret = -EPERM; @@ -353,6 +414,11 @@ static int sftl_n42_header_write(struct sftl_disk *sftl, u32 lba) lba ? "copy" : "primary", lba, ret); if (ret || lba) goto out; + if (release_only) { + /* Released and nothing added: the fence stays empty. */ + apple_sftl_set_write_fence(sftl->ftl, 0, 0); + goto out; + } ret = n42_lwvm_install_ranges(sftl->buffer, media, lw, ranges, slots, &nr); if (!ret) ret = apple_sftl_set_write_fences(sftl->ftl, (const u32 (*)[2])ranges, nr); @@ -360,6 +426,7 @@ static int sftl_n42_header_write(struct sftl_disk *sftl, u32 lba) dev_info(dev, "N42: write fence [%u,%u) = LwVM partition %u\n", ranges[i][0], ranges[i][1], slots[i]); out: + kfree(released); kfree(b); kfree(p); kvfree(lw); From 3e2ef21ec1372a29c62c9edbfd602590032ea94e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Wed, 2 Dec 2026 21:57:21 +0100 Subject: [PATCH 52/59] mtd: apple-sftl: N42: release from the restore's pieced Data MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 12H321 restore maps Data in two physical runs, which the decoder marks pieced; the release took that for a foreign layout (-ESTALE). After the release Data's first 3 GiB lie in one run, which is checked. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/apple-n42-lwvm-alloc.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/mtd/apple-n42-lwvm-alloc.h b/drivers/mtd/apple-n42-lwvm-alloc.h index 345ccd3571f574..4aede133c49069 100644 --- a/drivers/mtd/apple-n42-lwvm-alloc.h +++ b/drivers/mtd/apple-n42-lwvm-alloc.h @@ -94,7 +94,8 @@ static inline int n42_lwvm_release(const u8 *before, u8 *after, u64 media, if (ret) return ret; - if (lw->nr_parts != 2 || lw->parts[1].pieced || + /* The restore leaves Data in two physical runs (pieced): that is its layout. */ + if (lw->nr_parts != 2 || lw->parts[1].end != N42_LWVM_DATA_ORIGINAL_END || lw->parts[1].begin >= N42_LWVM_DATA_END || (N42_LWVM_DATA_END - lw->parts[1].begin) & ((1ULL << lw->chunk_shift) - 1)) From adbb98b36e06f3b465f875d66cf0fc10a8a571b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Wed, 2 Dec 2026 22:03:44 +0100 Subject: [PATCH 53/59] mtd: apple-sftl: N42: Data is encrypted; iOS's shrink check is the gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit iOS encrypts the Data partition block by block, so its HFSX header reads as ciphertext from Linux and the fit check refused every release. A readable header must still fit; otherwise the installer's iOS-side verify-shrink, required before kDFU, is what allows the release. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/apple-sftl-block.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/drivers/mtd/apple-sftl-block.c b/drivers/mtd/apple-sftl-block.c index 5eefc991592a19..a98c924c4663e1 100644 --- a/drivers/mtd/apple-sftl-block.c +++ b/drivers/mtd/apple-sftl-block.c @@ -379,15 +379,23 @@ static int sftl_n42_header_write(struct sftl_disk *sftl, u32 lba) released = kmalloc(N42_LWVM_BYTES, GFP_NOIO); ret = released ? n42_lwvm_release(p, released, media, lw) : -ENOMEM; + /* + * iOS encrypts Data block by block (its key is in the effaceable + * storage), so its HFSX header is usually unreadable here: then + * iOS's own check before the install (resize-hfs-n42 + * verify-shrink, which the installer requires) is the gate. A + * readable header must fit. + */ fs = ret ? 0 : sftl_n42_data_fs_bytes(sftl, lw); - if (!ret && (!fs || fs > N42_LWVM_DATA_END - lw->parts[1].begin)) { + if (!ret && fs > N42_LWVM_DATA_END - lw->parts[1].begin) { dev_warn(dev, "N42 install: Data's filesystem (%llu bytes) does not fit the released 3 GiB\n", fs); ret = -EPERM; } release_only = !ret && !memcmp(sftl->buffer, released, N42_LWVM_BYTES); if (!ret) - dev_info(dev, "N42 install: releasing Data's LwVM tail (filesystem %llu bytes)%s\n", - fs, release_only ? ", no Linux entries yet" : ""); + dev_info(dev, "N42 install: releasing Data's LwVM tail (filesystem %s)%s\n", + fs ? "readable, fits" : "encrypted, checked by iOS", + release_only ? ", no Linux entries yet" : ""); } if (!ret && release_only) /* The copy first over an unchanged pair, then the primary over that copy. */ From 2af115b1d1c1d74e7215d48863a0d9f87f20fd4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Wed, 2 Dec 2026 11:42:39 +0100 Subject: [PATCH 54/59] mtd: apple-sftl: derive the BTOC base from the first record 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/mtd/apple-sftl-btoc-test.h | 78 ++++++++++++++++++++++++++++++ drivers/mtd/apple-sftl-core.c | 48 ++++++++++++++++-- 2 files changed, 122 insertions(+), 4 deletions(-) create mode 100644 drivers/mtd/apple-sftl-btoc-test.h diff --git a/drivers/mtd/apple-sftl-btoc-test.h b/drivers/mtd/apple-sftl-btoc-test.h new file mode 100644 index 00000000000000..af84dd710d37c7 --- /dev/null +++ b/drivers/mtd/apple-sftl-btoc-test.h @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Private append-cursor tests. The checkpoint writer hands the verified + * recovered sequence to adopt_checkpoint while the landing is still open. + */ +#include + +static void sftl_test_btoc_checkpoint(struct kunit *test, bool populated, + u8 kind, u32 key) +{ + struct apple_sftl *live, *cold; + u8 oob[APPLE_PPN_OOB_SIZE] = {}; + unsigned int chunk; + u64 sequence = 980930082; + + live = kunit_kzalloc(test, sizeof(*live), GFP_KERNEL); + cold = kunit_kzalloc(test, sizeof(*cold), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, live); + KUNIT_ASSERT_NOT_NULL(test, cold); + live->geo = &sftl_16gb_n42; + live->footer = kunit_kzalloc(test, SFTL_FOOTER_BYTES, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, live->footer); + live->sequence = sequence; + live->lanes[4] = 15; + sftl_open_block(live, 4); + if (populated) { + for (chunk = 0; chunk < 4; chunk++) { + sftl_data_meta(oob, ++sequence, 128 + chunk); + sftl_append_summary(live, oob); + } + live->append_position = 4; + } + /* A zero-valid donor leaves the mandatory-GC landing empty. */ + cold->sequence = sequence + 72; + cold->checkpoint_sequence = cold->journal_sequence = cold->sequence; + sftl_adopt_checkpoint(live, cold); + for (chunk = 0; chunk < 4; chunk++) { + u8 *meta = oob + chunk * SFTL_META; + + meta[0] = kind; + put_unaligned_le32(key, meta + 8); + } + sftl_stamp_page_at(live, oob, kind == 1, false, live->sequence); + for (chunk = 0; chunk < 4; chunk++) + sftl_append_summary(live, oob + chunk * SFTL_META); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(live->footer), 0U); + KUNIT_EXPECT_EQ(test, live->append_base, + populated ? 980930083ULL : cold->sequence + 1); + if (populated) + KUNIT_EXPECT_EQ(test, get_unaligned_le32(live->footer + SFTL_META), 76U); +} + +static void sftl_test_empty_gc_landing_after_save(struct kunit *test) +{ + sftl_test_btoc_checkpoint(test, false, 1, 0x174000); +} + +static void sftl_test_trim_first_after_save(struct kunit *test) +{ + sftl_test_btoc_checkpoint(test, false, 2, SFTL_TRIM); +} + +static void sftl_test_populated_gc_landing_after_save(struct kunit *test) +{ + sftl_test_btoc_checkpoint(test, true, 1, 256); +} + +static struct kunit_case sftl_btoc_cases[] = { + KUNIT_CASE(sftl_test_empty_gc_landing_after_save), + KUNIT_CASE(sftl_test_trim_first_after_save), + KUNIT_CASE(sftl_test_populated_gc_landing_after_save), + {} +}; + +static struct kunit_suite sftl_btoc_suite = { + .name = "apple-sftl-btoc", + .test_cases = sftl_btoc_cases, +}; +kunit_test_suite(sftl_btoc_suite); diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c index b940223773462e..69ae793a7a30ce 100644 --- a/drivers/mtd/apple-sftl-core.c +++ b/drivers/mtd/apple-sftl-core.c @@ -4554,7 +4554,7 @@ static void sftl_open_block(struct apple_sftl *sftl, u32 block) sftl->append_block = block; sftl->append_capacity = sftl_slots(sftl, sftl->lanes[block]) - reserve; sftl->append_position = 0; - sftl->append_base = sftl->sequence + 1; + sftl->append_base = 0; /* The first programmed record establishes the base. */ sftl->append_has_trim = false; sftl->footer_runs = 0; memset(sftl->footer, 0, SFTL_FOOTER_BYTES); @@ -4611,10 +4611,13 @@ static void sftl_data_meta(u8 *meta, u64 sequence, u32 logical_page) static void sftl_append_summary(struct apple_sftl *sftl, const u8 *meta) { - u32 relative = sftl_sequence(meta) - sftl->append_base; + u32 relative; u32 high = get_unaligned_le32(meta + 12), key = get_unaligned_le32(meta + 8); u8 *entry; + if (!sftl->footer_runs) + sftl->append_base = sftl_sequence(meta); + relative = sftl_sequence(meta) - sftl->append_base; if (sftl->footer_runs) { u32 length; @@ -5229,6 +5232,36 @@ static bool sftl_block_full(const struct apple_sftl *sftl) sftl_slots(sftl, sftl->lanes[sftl->append_block]); } +/* Check the complete serialized run list before programming even the first + * summary page. A checkpoint may introduce sequence gaps inside a block. + */ +static bool sftl_summary_valid(struct apple_sftl *sftl, u32 chunks, u64 span) +{ + u32 i, end = 0, position = 0; + const u8 *entry = sftl->footer; + + if (!sftl->append_base || !span || span > U32_MAX || + sftl->sequence > SFTL_SEQUENCE || !sftl->footer_runs || + sftl->footer_runs >= chunks * (SFTL_CHUNK / SFTL_META) || + get_unaligned_le32(entry)) + return false; + for (i = 0; i < sftl->footer_runs; i++, entry += SFTL_META) { + u32 rel = get_unaligned_le32(entry); + u32 key = get_unaligned_le32(entry + 8); + u32 length = get_unaligned_le32(entry + 12); + + if (!length || rel < end || rel >= span || length > span - rel || + length > sftl->append_position - position) + return false; + if (key != SFTL_TRIM && key != SFTL_PAD && + (key >= sftl->geo->lpages || length > sftl->geo->lpages - key)) + return false; + position += length; + end = rel + length; + } + return position == sftl->append_position && !get_unaligned_le32(entry + 12); +} + static int sftl_close_block(struct apple_sftl *sftl) { u64 span = sftl->sequence - sftl->append_base + 1; @@ -5239,10 +5272,13 @@ static int sftl_close_block(struct apple_sftl *sftl) unsigned int chunk, index; int ret; - if (!span || span > U32_MAX) - return -EOVERFLOW; if (footer_chunks < 4 || footer_chunks > sftl->geo->footer_max || footer_chunks % 4) return -EINVAL; + if (!sftl_summary_valid(sftl, footer_chunks, span)) { + pr_err("apple-sftl: refusing BTOC block=%u base=%llu span=%llu runs=%u position=%u\n", + block, sftl->append_base, span, sftl->footer_runs, sftl->append_position); + return -EBADMSG; + } put_unaligned_le64(sftl->append_base << 16 | (u16)(footer_chunks << 1) << 8 | 0x1c, meta); put_unaligned_le32(span, meta + 8); put_unaligned_le16(footer_chunks, meta + 12); @@ -7751,3 +7787,7 @@ int apple_sftl_inspect(struct apple_sftl *sftl, size_t max_bytes, return ret; } EXPORT_SYMBOL_GPL(apple_sftl_inspect); + +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_KUNIT_TEST) && !defined(APPLE_SFTL_HOST_TEST) +#include "apple-sftl-btoc-test.h" +#endif From 8b79e0f417453f0ceb8d914d2996bb6119d7a0ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Wed, 2 Dec 2026 11:49:33 +0100 Subject: [PATCH 55/59] mtd: apple-sftl: exercise invalid BTOC runs and termination 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/mtd/apple-sftl-btoc-test.h | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/drivers/mtd/apple-sftl-btoc-test.h b/drivers/mtd/apple-sftl-btoc-test.h index af84dd710d37c7..bcbf7c6a0737b0 100644 --- a/drivers/mtd/apple-sftl-btoc-test.h +++ b/drivers/mtd/apple-sftl-btoc-test.h @@ -64,9 +64,38 @@ static void sftl_test_populated_gc_landing_after_save(struct kunit *test) sftl_test_btoc_checkpoint(test, true, 1, 256); } +static void sftl_test_btoc_close_invariants(struct kunit *test) +{ + struct apple_sftl *s = kunit_kzalloc(test, sizeof(*s), GFP_KERNEL); + u8 entries[3 * SFTL_META] = {}; + + KUNIT_ASSERT_NOT_NULL(test, s); + s->geo = &sftl_16gb_n42; + s->append_base = 100; + s->sequence = 179; + s->append_position = 8; + s->footer_runs = 2; + s->footer = entries; + put_unaligned_le32(4, entries + 12); + put_unaligned_le32(76, entries + 16); + put_unaligned_le32(4, entries + 28); + KUNIT_EXPECT_TRUE(test, sftl_summary_valid(s, 4, 80)); + put_unaligned_le32(72, entries); + KUNIT_EXPECT_FALSE(test, sftl_summary_valid(s, 4, 80)); + put_unaligned_le32(0, entries); + put_unaligned_le32(80, entries + 16); + KUNIT_EXPECT_FALSE(test, sftl_summary_valid(s, 4, 80)); + put_unaligned_le32(3, entries + 16); + KUNIT_EXPECT_FALSE(test, sftl_summary_valid(s, 4, 80)); + put_unaligned_le32(76, entries + 16); + put_unaligned_le32(1, entries + 44); + KUNIT_EXPECT_FALSE(test, sftl_summary_valid(s, 4, 80)); +} + static struct kunit_case sftl_btoc_cases[] = { KUNIT_CASE(sftl_test_empty_gc_landing_after_save), KUNIT_CASE(sftl_test_trim_first_after_save), + KUNIT_CASE(sftl_test_btoc_close_invariants), KUNIT_CASE(sftl_test_populated_gc_landing_after_save), {} }; From 43a4559d96207cc156721609e6d65fd589fae5a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Wed, 2 Dec 2026 11:55:27 +0100 Subject: [PATCH 56/59] mtd: apple-sftl: reproduce mandatory GC on sparse synthetic NAND 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/mtd/apple-sftl-gc-media-test.h | 239 +++++++++++++++++++++++++ drivers/mtd/apple-sftl-test.c | 4 + 2 files changed, 243 insertions(+) create mode 100644 drivers/mtd/apple-sftl-gc-media-test.h diff --git a/drivers/mtd/apple-sftl-gc-media-test.h b/drivers/mtd/apple-sftl-gc-media-test.h new file mode 100644 index 00000000000000..2655dafdae18d4 --- /dev/null +++ b/drivers/mtd/apple-sftl-gc-media-test.h @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* A sparse writable NAND model. Only programmed rows allocate RAM. */ +#include + +struct gc_test_flash { + struct t16_fixture t; + struct xarray rows; + struct apple_sftl_context_record *context; + u8 erased[N42_SUBBLOCKS]; + bool incident; + u32 programs, erases, first_host_block; +}; + +static const u32 gc_test_victim[] = { 877, 1000 }; +static const u64 gc_test_base[] = { 980930083, 981080805 }; +#define GC_TEST_CXT 982000000ULL +#define GC_TEST_HOST 0x174000 + +static void gc_test_release(void *arg) +{ + struct gc_test_flash *f = arg; + struct n42_wpage *row; + unsigned long i; + + xa_for_each(&f->rows, i, row) + kvfree(row); + xa_destroy(&f->rows); + kvfree(f->context); +} + +static u32 gc_test_row(u32 block, u32 lane, u32 pg) +{ + return (block * T16_PAGES + pg) * 4 + lane; +} + +static int gc_test_read(void *arg, unsigned int bus, unsigned int cau, unsigned int b, + unsigned int pg, bool slc, u8 *data, u8 *oob, u8 *status) +{ + struct gc_test_flash *f = arg; + u32 lane = cau * 2 + bus, row = pg * 4 + lane, i, n; + struct n42_wpage *p; + + memset(data, 0xff, APPLE_PPN_PAGE_SIZE); + memset(oob, 0xff, APPLE_PPN_OOB_SIZE); + *status = 0x49; + if (slc) + return t16_vfl(&f->t, lane, b, pg, data, oob, status); + if (b >= N42_SUBBLOCKS || pg >= T16_PAGES || lane >= 4) + return -EINVAL; + p = xa_load(&f->rows, gc_test_row(b, lane, pg)); + if (p) { + memcpy(data, p->data, APPLE_PPN_PAGE_SIZE); + memcpy(oob, p->oob, APPLE_PPN_OOB_SIZE); + } else if (f->erased[b] & BIT(lane)) { + return 0; + } else if (b == 2 && row < 14) { + for (i = 0; i < 4; i++) { + memcpy(data + i * 4096, f->context[4 * row + i].data, 4096); + memcpy(oob + i * 16, f->context[4 * row + i].meta, 16); + } + } else if (!f->incident && b == 22 && !row) { + for (i = 0; i < 4; i++) + t16_meta(oob + i * 16, 1, 0, GC_TEST_CXT + 56 + i, i, + (GC_TEST_CXT + 56 + i) >> 16); + } else { + for (n = 0; n < (f->incident ? 2 : 1); n++) + if (b == gc_test_victim[n]) + break; + if (n == (f->incident ? 2 : 1)) + return 0; + if (row < 1023) { + for (i = 0; i < 4; i++) { + u32 slot = row * 4 + i; + u64 seq = gc_test_base[n] + (f->incident ? 72 : 0) + slot; + + t16_meta(oob + i * 16, 1, 0, seq, 4 * n + slot, seq >> 16); + put_unaligned_le32(b * T16_STRIDE + slot, data + i * 4096); + } + } else { + memset(data, 0, APPLE_PPN_PAGE_SIZE); + put_unaligned_le32(f->incident ? 72 : 0, data); + put_unaligned_le32(gc_test_base[n] >> 16, data + 4); + put_unaligned_le32(4 * n, data + 8); + put_unaligned_le32(4092, data + 12); + for (i = 0; i < 4; i++) { + t16_meta(oob + i * 16, 0x1c, 8, gc_test_base[n], + 4092 + (f->incident ? 72 : 0), 0xffff0004); + } + } + } + *status = 0x40; + return 0; +} + +static int gc_test_program(void *arg, unsigned int bus, unsigned int cau, unsigned int b, + unsigned int pg, const u8 *data, const u8 *oob) +{ + struct gc_test_flash *f = arg; + u32 lane = cau * 2 + bus; + struct n42_wpage *row; + int ret; + + if (b >= N42_SUBBLOCKS || !(f->erased[b] & BIT(lane))) + return -EPERM; + row = kvmalloc(sizeof(*row), GFP_KERNEL); + if (!row) + return -ENOMEM; + memcpy(row->data, data, APPLE_PPN_PAGE_SIZE); + memcpy(row->oob, oob, APPLE_PPN_OOB_SIZE); + ret = xa_insert(&f->rows, gc_test_row(b, lane, pg), row, GFP_KERNEL); + if (ret) { + kvfree(row); + return ret; + } + f->programs++; + if (oob[0] == 1 && get_unaligned_le32(oob + 8) == GC_TEST_HOST) + f->first_host_block = b; + return 0; +} + +static int gc_test_erase(void *arg, unsigned int bus, unsigned int cau, unsigned int b) +{ + struct gc_test_flash *f = arg; + u32 lane = cau * 2 + bus, pg; + + if (b != 2 && (b < 10 || b > 17) && b != 877 && b != 1000) + return -EPERM; + for (pg = 0; pg < T16_PAGES; pg++) + kvfree(xa_erase(&f->rows, gc_test_row(b, lane, pg))); + f->erased[b] |= BIT(lane); + f->erases++; + return 0; +} + +static struct gc_test_flash *gc_test_medium(struct kunit *test, bool incident) +{ + struct gc_test_flash *f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); + struct apple_sftl_context_record *ctx; + u32 i, n = incident ? 2 : 1; + u8 *map; + + KUNIT_ASSERT_NOT_NULL(test, f); + xa_init(&f->rows); + f->context = kvzalloc(56 * sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, f->context); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, gc_test_release, f), 0); + f->incident = incident; + f->t.blocks = N42_BLOCKS; + f->t.subblocks = N42_SUBBLOCKS; + f->t.vfl_block = N42_BLOCKS - 1; + f->t.ops.read_page = gc_test_read; + f->t.ops.program_page = gc_test_program; + f->t.ops.erase_block = gc_test_erase; + f->t.provider = (struct apple_ppn) { + .ops = &f->t.ops, .priv = f, .buses = 2, .caus = 2, + .blocks = N42_BLOCKS, .pages = T16_PAGES, + }; + ctx = f->context; + apple_sftl_test_native_prefix_for(ctx, N42_SUBBLOCKS); + put_unaligned_le32(2, ctx[0].data + 4); + for (i = 0; i < N42_SUBBLOCKS; i++) { + u8 *e = ctx[8 + i / 512].data + (i % 512) * 8; + + e[0] = i == 2 ? 7 : i >= 10 && i <= 17 ? 9 : 8; + if (i == 877 || (incident && i == 1000)) { + e[0] = 3; + e[1] = 8; + put_unaligned_le16(4, e + 2); + } + if (!incident && i == 22) + e[0] = 3; + } + put_unaligned_le64(4 * n, ctx[4].data + 4 + 8 * 16 + 8); + for (i = 0; i < 56; i++) { + if (i >= 24) { + memset(ctx[i].data, 0xff, 4096); + apple_sftl_context_meta(ctx[i].meta, 4, GC_TEST_CXT + i, 0, 0); + } else { + apple_sftl_context_meta(ctx[i].meta, ctx[i].meta[1], GC_TEST_CXT + i, + get_unaligned_le16(ctx[i].meta + 8), + get_unaligned_le16(ctx[i].meta + 10)); + } + } + map = ctx[24].data; + put_unaligned_le32(0, map); + put_unaligned_le32(0xfffffff0, map + 4); + for (i = 0; i < n; i++) { + put_unaligned_le32(gc_test_victim[i] * T16_STRIDE, map + 8 + i * 8); + put_unaligned_le32(4, map + 12 + i * 8); + } + put_unaligned_le32(T16_UNMAPPED, map + 8 + n * 8); + put_unaligned_le32(T16_LPAGES - 4 * n, map + 12 + n * 8); + return f; +} + +static void gc_test_free_ftl(void *arg) +{ + apple_sftl_free(arg); +} + +static void sftl_test_mandatory_gc_empty_save_close(struct kunit *test) +{ + struct gc_test_flash *f = gc_test_medium(test, false); + struct apple_sftl *s; + struct apple_sftl_info info; + struct n42_wpage *tail, *head; + u8 *buf = kunit_kzalloc(test, APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + u32 i; + + KUNIT_ASSERT_NOT_NULL(test, buf); + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->t.provider, &s), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, gc_test_free_ftl, s), 0); + apple_sftl_set_write_fence(s, GC_TEST_HOST, GC_TEST_HOST + 4096); + KUNIT_ASSERT_EQ(test, apple_sftl_write(s, GC_TEST_HOST, buf, 4), 0); + apple_sftl_get_info(s, &info); + KUNIT_ASSERT_GT(test, info.checkpoint_sequence, GC_TEST_CXT + 55); + KUNIT_ASSERT_EQ(test, info.sequence, info.checkpoint_sequence + 4); + for (i = 4; i < 4092; i += 4) + KUNIT_ASSERT_EQ(test, apple_sftl_write(s, GC_TEST_HOST + i, buf, 4), 0); + tail = xa_load(&f->rows, gc_test_row(f->first_host_block, 3, 255)); + head = xa_load(&f->rows, gc_test_row(f->first_host_block, 0, 0)); + KUNIT_ASSERT_NOT_NULL(test, tail); + KUNIT_ASSERT_NOT_NULL(test, head); + KUNIT_ASSERT_EQ(test, tail->oob[0], (u8)0x1c); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(tail->data), 0U); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(tail->oob) >> 16, + get_unaligned_le64(head->oob) >> 16); +} + +static struct kunit_case sftl_gc_media_cases[] = { + KUNIT_CASE(sftl_test_mandatory_gc_empty_save_close), + {} +}; + +static struct kunit_suite sftl_gc_media_suite = { + .name = "apple-sftl-gc-media", + .test_cases = sftl_gc_media_cases, +}; +kunit_test_suite(sftl_gc_media_suite); diff --git a/drivers/mtd/apple-sftl-test.c b/drivers/mtd/apple-sftl-test.c index 53ba429d70bb9e..f47948c81cd911 100644 --- a/drivers/mtd/apple-sftl-test.c +++ b/drivers/mtd/apple-sftl-test.c @@ -5739,3 +5739,7 @@ static struct kunit_suite apple_sftl_suite = { kunit_test_suite(apple_sftl_suite); MODULE_LICENSE("GPL"); + +#if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_RECLAIM_TEST) || IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) +#include "apple-sftl-gc-media-test.h" +#endif From a4465fc30f4915bd0725baabc50bf6d4f678158c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Wed, 2 Dec 2026 15:13:30 +0100 Subject: [PATCH 57/59] mtd: apple-sftl: audit published N42 summaries before enabling writes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Walk the VFL-listed tails independent of the checkpoint cutoff. Validate the replicated summary and its runs, and quarantine the writer if a footer is invalid or unreadable. Expose the same locked physical scan on the parent disk for read-only inspection after a workload. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/apple-sftl-block.c | 29 ++++++- drivers/mtd/apple-sftl-btoc-audit.h | 116 ++++++++++++++++++++++++++++ drivers/mtd/apple-sftl-core.c | 31 ++++---- drivers/mtd/apple-sftl-test.c | 33 +++++++- drivers/mtd/apple-sftl.h | 5 ++ 5 files changed, 197 insertions(+), 17 deletions(-) create mode 100644 drivers/mtd/apple-sftl-btoc-audit.h diff --git a/drivers/mtd/apple-sftl-block.c b/drivers/mtd/apple-sftl-block.c index a98c924c4663e1..1565ba3d711831 100644 --- a/drivers/mtd/apple-sftl-block.c +++ b/drivers/mtd/apple-sftl-block.c @@ -659,6 +659,33 @@ static const struct blk_mq_ops sftl_view_mq_ops = { .queue_rq = sftl_view_queue_rq, }; +static ssize_t btoc_audit_show(struct device *dev, struct device_attribute *attr, char *buf) +{ + struct gendisk *disk = dev_to_disk(dev); + struct sftl_disk *s = disk->private_data; + struct apple_sftl_btoc_audit audit; + int ret; + + mutex_lock(&s->io_lock); + ret = s->dead ? -ENODEV : apple_sftl_btoc_audit(s->ftl, &audit); + if (!ret && audit.flagged) { + s->writable = false; + set_disk_ro(disk, true); + } + mutex_unlock(&s->io_lock); + if (ret) + return ret; + return sysfs_emit(buf, "listed=%u closed=%u flagged=%u\n", + audit.listed, audit.closed, audit.flagged); +} +static DEVICE_ATTR_RO(btoc_audit); + +static struct attribute *sftl_n42_attrs[] = { + &dev_attr_btoc_audit.attr, + NULL, +}; +ATTRIBUTE_GROUPS(sftl_n42); + static const struct block_device_operations sftl_block_ops = { .owner = THIS_MODULE, }; @@ -1027,7 +1054,7 @@ static int sftl_disk_probe(struct platform_device *pdev) set_capacity(disk, (sector_t)info.disk_pages * (SFTL_LOGICAL_BYTES / SECTOR_SIZE)); set_disk_ro(disk, !sftl->writable); platform_set_drvdata(pdev, sftl); - ret = device_add_disk(&pdev->dev, disk, NULL); + ret = device_add_disk(&pdev->dev, disk, info.n42_install ? sftl_n42_groups : NULL); if (ret) goto put_disk; dev_info(&pdev->dev, "%s: %s, %u logical pages, sequence %llu\n", diff --git a/drivers/mtd/apple-sftl-btoc-audit.h b/drivers/mtd/apple-sftl-btoc-audit.h new file mode 100644 index 00000000000000..65d4f1c23840bc --- /dev/null +++ b/drivers/mtd/apple-sftl-btoc-audit.h @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* This scan follows physical publication (the last chunk), independently + * of the selected checkpoint, the first data page and the journal cutoff. + */ +static int sftl_btoc_read_row(struct apple_sftl *s, u32 addr, u8 *status) +{ + unsigned int bus, cau, block, page, chunk; + int ret = sftl_translate(s, addr, &bus, &cau, &block, &page, &chunk); + + if (ret) + return ret; + *status = 0; + ret = s->ppn->ops->read_page(s->ppn->priv, bus, cau, block, page, false, + s->page, s->oob, status); + if (ret) + return ret; + if (*status != 0x40 && *status != 0x42 && *status != 0x49) + return -EBADMSG; + return 0; +} + +static int sftl_audit_footer(struct apple_sftl *s, u32 block, u32 *closed) +{ + u32 slots = sftl_slots(s, s->lanes[block]), start = block * sftl_stride(s); + u32 width, pos, span, used = 0, end = 0, i; + u8 tail[SFTL_META], status; + bool terminated = false; + int ret; + + ret = sftl_btoc_read_row(s, start + slots - 4, &status); + if (ret) + return ret; + memcpy(tail, s->oob + 3 * SFTL_META, sizeof(tail)); + if (status == 0x49 || tail[0] != 0x1c) + return 0; + + (*closed)++; + width = get_unaligned_le16(tail + 12); + if (width == U16_MAX) + width = tail[1] >> 1; + span = get_unaligned_le32(tail + 8); + if (!width || width % 4 || width > SFTL_FOOTER_CHUNKS || width >= slots || + width != tail[1] >> 1 || get_unaligned_le16(tail + 14) != U16_MAX || + !span || sftl_sequence(tail) + span > SFTL_SEQUENCE + 1) + return -EBADMSG; + + for (pos = slots - width; pos < slots; pos += 4) { + if (width != 4) { + ret = sftl_btoc_read_row(s, start + pos, &status); + if (ret) + return ret; + } + if (status == 0x49) + return -EBADMSG; + for (i = 0; i < 4; i++) + if (memcmp(tail, s->oob + i * SFTL_META, sizeof(tail))) + return -EBADMSG; + if (pos == slots - width && get_unaligned_le32(s->page)) { + __set_bit(block, s->btoc_bad_first); + pr_err("apple-sftl: BAD_FIRST_REL block=%u base=%llu rel=%u\n", + block, sftl_sequence(tail), get_unaligned_le32(s->page)); + return -EBADMSG; + } + for (i = 0; !terminated && i < APPLE_PPN_PAGE_SIZE; i += SFTL_META) { + const u8 *entry = s->page + i; + u32 rel = get_unaligned_le32(entry); + u32 key = get_unaligned_le32(entry + 8); + u32 count = get_unaligned_le32(entry + 12); + + if (!count) { + terminated = true; + break; + } + if (rel < end || rel >= span || count > span - rel || + count > slots - width - used || + (key < SFTL_PAD && (key >= s->geo->lpages || + count > s->geo->lpages - key))) + return -EBADMSG; + used += count; + end = rel + count; + } + } + return terminated ? 0 : -EBADMSG; +} + +static void sftl_btoc_audit_locked(struct apple_sftl *s, struct apple_sftl_btoc_audit *audit) +{ + u32 b; + + memset(audit, 0, sizeof(*audit)); + for (b = 1; b < s->geo->subblocks; b++) { + int ret; + + if (!s->lanes[b]) + continue; + audit->listed++; + ret = sftl_audit_footer(s, b, &audit->closed); + if (ret) { + audit->flagged++; + s->btoc_read_only = true; + pr_err("apple-sftl: BTOC audit block=%u rc=%d; writes disabled\n", b, ret); + } + cond_resched(); + } +} + +int apple_sftl_btoc_audit(struct apple_sftl *s, struct apple_sftl_btoc_audit *audit) +{ + if (!s || !s->geo->n42_install) + return -EOPNOTSUPP; + mutex_lock(&s->lock); + sftl_btoc_audit_locked(s, audit); + mutex_unlock(&s->lock); + return 0; +} +EXPORT_SYMBOL_GPL(apple_sftl_btoc_audit); diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c index 69ae793a7a30ce..c856d3b35af035 100644 --- a/drivers/mtd/apple-sftl-core.c +++ b/drivers/mtd/apple-sftl-core.c @@ -361,6 +361,8 @@ struct sftl_next_stripe { }; struct apple_sftl { + bool btoc_read_only; + DECLARE_BITMAP(btoc_bad_first, SFTL_MAX_SUBBLOCKS); struct sftl_next_stripe *next_stripe; /* Separate windows for sparse block heads/tails and walks inside a block. */ struct sftl_scan_window *window[2]; @@ -467,7 +469,7 @@ static void sftl_set_role(struct apple_sftl *sftl, u32 block, u8 role) static bool sftl_writer_enabled(const struct apple_sftl *sftl) { - if (sftl->lpp != 4) + if (sftl->btoc_read_only || sftl->lpp != 4) return false; #if IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) if (sftl->test_writer) @@ -2140,6 +2142,8 @@ static int sftl_read_open(struct apple_sftl *sftl, u32 address, unsigned int *ch return ret; } +#include "apple-sftl-btoc-audit.h" + static int sftl_remember_user_seq(struct apple_sftl *sftl, u32 block, const u8 *footer, u32 runs) { /* Four base chunks identify the layout validated by sftl_decode_generation. */ @@ -2241,17 +2245,10 @@ static int sftl_footer(struct apple_sftl *sftl, const u8 *head, u32 block, memcpy(footer_meta, sftl->oob, sizeof(footer_meta)); base = sftl_sequence(footer_meta); chunks = get_unaligned_le16(footer_meta + 12); - if (reclaim && sftl->geo->n42_install && chunks == 0xffff) + if (ios && chunks == 0xffff) chunks = footer_meta[1] >> 1; span = get_unaligned_le32(footer_meta + 8); - /* - * 12H321 takes a closed block's base from its summary alone - * (s_cxt_scan_diff); it never compares the first chunk, and refuses only - * a first entry with rel != 0 (checked below). iOS does close blocks - * whose first chunk is later than the summary's base: block 877, - * 2026-12-01, summary 0x3a77ce23, first chunk 0x3a77ce6b. The strict - * replay keeps requiring the two to agree. - */ + /* 12H321 takes the base from the published footer. */ if (chunks < sftl->lpp || chunks > 32 || chunks % sftl->lpp || footer_meta[1] >> 1 != chunks || get_unaligned_le16(footer_meta + 14) != 0xffff || (!ios && base != sftl_sequence(head)) || !span || base + span > SFTL_SEQUENCE + 1) @@ -2320,7 +2317,8 @@ static int sftl_footer(struct apple_sftl *sftl, const u8 *head, u32 block, u32 address = block * sftl_stride(sftl) + position; /* s_btoc_read: "0 == btoc->weaveSeqAdd" (panic). */ - if ((!index && relative) || + if ((!index && relative && !(test_bit(block, sftl->btoc_bad_first) && + (head[0] == 1 || head[0] == 2) && sftl_sequence(head) == base + relative)) || (key < 0xffff0000 && key + (length - 1) < key)) { ret = -EBADMSG; goto out; @@ -3257,6 +3255,11 @@ static int sftl_load(struct apple_ppn *provider, struct apple_sftl **out, unsign } } heads_done = ktime_get(); + if (!deadline && geo->n42_install) { + struct apple_sftl_btoc_audit audit; + + sftl_btoc_audit_locked(sftl, &audit); + } if (reclaim && geo->n42_install && sftl_writer_enabled(sftl) && !sftl->vfl_degraded && provider->ops->erase_block) { sftl->pool = kvzalloc(sizeof(*sftl->pool), GFP_KERNEL); @@ -5857,6 +5860,8 @@ static int sftl_gc_service(struct apple_sftl *sftl, unsigned long deadline) u32 capacity, room, block; int ret; + if (sftl->btoc_read_only) + return -EROFS; if (!pool || !pool->gc_landing || pool->gc_landing != sftl->append_block || pool->gc_count >= SFTL_GC_BATCH || sftl->failed || sftl->evacuate) return 0; @@ -6015,7 +6020,7 @@ static int sftl_gc_thread(void *arg) mutex_lock(&sftl->lock); wake = atomic_xchg(&sftl->gc_wake, 0); pool = sftl->pool; - if (sftl->failed || sftl->evacuate || + if (sftl->btoc_read_only || sftl->failed || sftl->evacuate || (sftl->write_fenced && !sftl->nr_write_fence_more && sftl->write_fence_start >= sftl->write_fence_end) || (!wake && time_before(jiffies, sftl->last_io + 2 * HZ))) @@ -6271,7 +6276,7 @@ static unsigned int sftl_stripe_room(struct apple_sftl *sftl, unsigned int want) u32 block = sftl->append_block, slots; unsigned int m; - if (want < 2 || !sftl->ppn->ops->program_pages || block == U32_MAX || + if (sftl->btoc_read_only || want < 2 || !sftl->ppn->ops->program_pages || block == U32_MAX || sftl->evacuate || sftl->failed || !sftl->writer_prepared) return 0; m = min_t(unsigned int, want, SFTL_STRIPE_MAX); diff --git a/drivers/mtd/apple-sftl-test.c b/drivers/mtd/apple-sftl-test.c index f47948c81cd911..d2de935e625db7 100644 --- a/drivers/mtd/apple-sftl-test.c +++ b/drivers/mtd/apple-sftl-test.c @@ -3530,6 +3530,7 @@ static void sftl_test_gc_preserves_last_sequences(struct kunit *test) #define N42_SUBBLOCKS 1046U struct t16_fixture { + bool bad_first_rel; struct apple_ppn provider; struct apple_ppn_ops ops; u16 blocks, subblocks; /* per CAU; the VFL is in the top two blocks */ @@ -3730,12 +3731,12 @@ static void t16_slot(struct t16_fixture *f, u32 block, u32 slot, u8 *payload, u8 if (block == T16_OLD) { if (slot >= slots - T16_SUMMARY) { t16_meta(meta, 0x1c, T16_SUMMARY << 1, T16_OLD_BASE, - slots - T16_SUMMARY, 0); + slots - T16_SUMMARY + (f->bad_first_rel ? 72 : 0), 0); put_unaligned_le16(T16_SUMMARY, meta + 12); put_unaligned_le16(0xffff, meta + 14); memset(payload, 0, 4096); if (slot == slots - T16_SUMMARY) { - put_unaligned_le32(0, payload); + put_unaligned_le32(f->bad_first_rel ? 72 : 0, payload); put_unaligned_le32(0, payload + 4); put_unaligned_le32(0, payload + 8); put_unaligned_le32(slots - T16_SUMMARY, payload + 12); @@ -3744,7 +3745,7 @@ static void t16_slot(struct t16_fixture *f, u32 block, u32 slot, u8 *payload, u8 } memset(payload, 'o' + slot % 7, 4096); put_unaligned_le32(slot, payload); - t16_meta(meta, 1, 0, T16_OLD_BASE + slot, slot, 0); + t16_meta(meta, 1, 0, T16_OLD_BASE + slot + (f->bad_first_rel ? 72 : 0), slot, 0); return; } if (block == T16_NEW && f->new_block) { @@ -4436,6 +4437,31 @@ static void sftl_test_16gb_context_rules(struct kunit *test) apple_sftl_free(sftl); } +/* A native-looking run below the replay cutoff must still disable writes. */ +static void sftl_test_n42_covered_bad_first_rel(struct kunit *test) +{ + struct t16_fixture *f = t16_fixture(test); + struct apple_sftl_btoc_audit audit; + struct apple_sftl_info info; + struct apple_sftl *s; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->provider.blocks = f->blocks = N42_BLOCKS; + f->subblocks = N42_SUBBLOCKS; + f->vfl_block = N42_BLOCKS - 1; + f->legacy = true; + f->bad_first_rel = true; + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &s), 0); + apple_sftl_test_enable_writer(s); + apple_sftl_get_info(s, &info); + KUNIT_EXPECT_TRUE(test, info.read_only); + KUNIT_EXPECT_EQ(test, apple_sftl_btoc_audit(s, &audit), 0); + KUNIT_EXPECT_EQ(test, audit.flagged, 1U); + KUNIT_EXPECT_GE(test, audit.closed, 2U); + t16_expect_page(test, s, 0, 'o', 0); + apple_sftl_free(s); +} + /* * 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 @@ -5715,6 +5741,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_covered_bad_first_rel), KUNIT_CASE(sftl_test_n42_repeated_sequence), KUNIT_CASE(sftl_test_n42_ios_relocated_copy), KUNIT_CASE(sftl_test_n42_ios_gap), diff --git a/drivers/mtd/apple-sftl.h b/drivers/mtd/apple-sftl.h index 9150264584325c..4af513d12043fd 100644 --- a/drivers/mtd/apple-sftl.h +++ b/drivers/mtd/apple-sftl.h @@ -68,6 +68,11 @@ struct apple_sftl_info { int apple_sftl_load_disk(struct apple_ppn *provider, struct apple_sftl **out); void apple_sftl_start_gc(struct apple_sftl *sftl, struct mutex *disk_io_lock); +struct apple_sftl_btoc_audit { + u32 listed, closed, flagged; +}; + +int apple_sftl_btoc_audit(struct apple_sftl *sftl, struct apple_sftl_btoc_audit *audit); int apple_sftl_load(struct apple_ppn *provider, struct apple_sftl **out); void apple_sftl_free(struct apple_sftl *sftl); int apple_sftl_read(struct apple_sftl *sftl, u32 logical_page, u8 *data); From 80490a017d30712ce61a91fdd536959c3d76372c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Fri, 4 Dec 2026 12:29:26 +0100 Subject: [PATCH 58/59] mtd: apple-sftl: collect for as long as N42 writes need space MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The writer allowed four collection checkpoints per boot, and each one also counted against the eight explicit checkpoints. Under sustained writes background collection stopped after 4 x 32 donors, the free pool reached the seven-block floor and the host claim failed with -ENOSPC (BLK_STS_NOSPC) while ext4 still had 1.7 GB free. 12H321 has no such limit: its write path runs 0x80dd381c before every chunk and repeats the collection step until free space is above the floor again. - Collection saves are neither capped nor counted. The 8-per-boot guard applies to explicit (shutdown, install) checkpoints only. A new read-only gc_saves parameter counts collection saves. - A mandatory claim that saved pending donors may collect again; it fails only when that save released no capacity, or when there is no victim or save site. One batch that cannot restore the floor still parks and fails its claim. - 12H321 retires a context site as clean free and counts it as free space at once (0x80dd07ac, 0x80dd6370). The dirty-free writer leaves type 1 to iOS, so each collection save used to take one block out of the reusable pool for the rest of the boot. Keep type 1 on media, and let the writer reuse such a site from the next save on. Saved-live donors are still released only by a verified checkpoint. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/apple-sftl-core.c | 60 ++++++++++++++++++++++++++++------- 1 file changed, 48 insertions(+), 12 deletions(-) diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c index c856d3b35af035..9e5bcfea50416a 100644 --- a/drivers/mtd/apple-sftl-core.c +++ b/drivers/mtd/apple-sftl-core.c @@ -227,7 +227,9 @@ struct sftl_records { #define SFTL_GC_BATCH 32U #define SFTL_GC_TIMEOUT (15U * HZ) #define SFTL_GC_SAVE_TIMEOUT (45U * HZ) -#define SFTL_GC_SAVES 4U +/* Explicit (shutdown, install) checkpoints per boot. Collection saves are + * not counted: 12H321 collects for as long as a write needs space. + */ #define SFTL_N42_SAVES 8U /* Each reason has its own rate limit. Selection guards count once per block @@ -339,11 +341,15 @@ MODULE_PARM_DESC(gc_victims, "N42 partial-block collection attempts"); MODULE_PARM_DESC(gc_pages_moved, "Live 4 KiB pages relocated and verified"); MODULE_PARM_DESC(gc_retired, "Collected donors released after checkpoint verification"); +static ulong gc_saves; +module_param(gc_saves, ulong, 0444); +MODULE_PARM_DESC(gc_saves, "Verified collection checkpoints saved this boot"); + #if IS_ENABLED(CONFIG_MTD_APPLE_SFTL_N42_WRITE) || \ IS_ENABLED(CONFIG_KUNIT) || defined(APPLE_SFTL_HOST_TEST) /* Shared by cold reopens in this boot, under the save lock. */ static DEFINE_MUTEX(sftl_save_lock); -static unsigned int gc_saves, n42_saves; +static unsigned int n42_saves; #endif #define SFTL_SCAN_DEPTH 32 @@ -457,6 +463,8 @@ struct apple_sftl { */ DECLARE_BITMAP(head_unread, SFTL_MAX_BLOCKS); DECLARE_BITMAP(linux_erased, SFTL_MAX_SUBBLOCKS); + /* Context sites a collection save retired and returned to the pool. */ + DECLARE_BITMAP(returned_sites, SFTL_MAX_SUBBLOCKS); DECLARE_BITMAP(fallback_live, SFTL_MAX_SUBBLOCKS); }; @@ -4254,7 +4262,9 @@ static bool sftl_reuse_available(struct apple_sftl *sftl, u32 block) { return (sftl->roles[block] == SFTL_DIRTY_FREE || (sftl->pool && sftl->roles[block] == SFTL_ERASE_PENDING && - test_bit(block, sftl->pool->runtime_retired))) && + test_bit(block, sftl->pool->runtime_retired)) || + (sftl->pool && sftl->roles[block] == SFTL_CLEAN_FREE && + test_bit(block, sftl->returned_sites))) && !test_bit(block, sftl->used) && sftl_reuse_permitted(sftl, block); } @@ -5948,9 +5958,7 @@ static bool sftl_gc_has_space(struct apple_sftl *sftl, u32 need, unsigned long d static bool sftl_gc_allowed(struct apple_sftl *sftl) { - return sftl->pool->maps_complete && !sftl->tolerated && - READ_ONCE(gc_saves) < SFTL_GC_SAVES && - READ_ONCE(n42_saves) < SFTL_N42_SAVES - 1; + return sftl->pool->maps_complete && !sftl->tolerated; } /* Only the seven-block floor is certified in a host claim. Work toward @@ -6061,7 +6069,7 @@ static int sftl_gc_claim(struct apple_sftl *sftl, unsigned long deadline) u32 block, slots, site, credit = 0, nominal = sftl_stride(sftl); u32 floor = 7 * nominal, landing, previous, need, victim; unsigned long copy_deadline; - bool pressure, mandatory, saved = false; + bool pressure, mandatory, stalled = false; int ret; again: @@ -6116,16 +6124,20 @@ static int sftl_gc_claim(struct apple_sftl *sftl, unsigned long deadline) } mandatory = !sftl_gc_has_space(sftl, slots + floor, deadline); if (pool->gc_count && (ret == -ENOSPC || mandatory || (!sftl->gc_task && pool->gc_count >= SFTL_GC_BATCH))) { + previous = sftl_gc_space(sftl).certified; ret = sftl_gc_save(sftl); if (ret) return ret; - saved = true; + /* 0x80dd381c steps while below the floor; each step frees its + * victim. Stop only when a released batch freed nothing. + */ + stalled = sftl_gc_space(sftl).certified <= previous; deadline = jiffies + SFTL_CLAIM_TIMEOUT; goto again; } if (ret) return ret; - if (mandatory && (saved || !pressure || !pool->gc_site || + if (mandatory && (stalled || !pressure || !pool->gc_site || !sftl_gc_pick(sftl, slots - sftl->geo->footer_max - 4))) return -ENOSPC; @@ -6149,6 +6161,8 @@ static int sftl_gc_claim(struct apple_sftl *sftl, unsigned long deadline) * landing while the host waits. Only verified, released capacity can * admit its write. As in sftl_compact, the verified stream keeps its * cursor and BTOC across the save; later runs have new weave sequences. + * A batch that cannot restore the floor parks and fails this claim; + * a later claim collects again while saves keep releasing capacity. */ do { previous = pool->gc_count; @@ -7217,8 +7231,7 @@ static int sftl_write_checkpoint_locked(struct apple_sftl *sftl, memset(rep, 0, sizeof(*rep)); rep->old_ctx = U32_MAX; rep->new_ctx = U32_MAX; - if (sftl->pool && (n42_saves >= SFTL_N42_SAVES || (gc && (gc_saves >= SFTL_GC_SAVES || - n42_saves >= SFTL_N42_SAVES - 1)))) + if (sftl->pool && !gc && n42_saves >= SFTL_N42_SAVES) return -ENOSPC; stride = sftl_stride(sftl); if (sftl->failed) { @@ -7295,9 +7308,10 @@ static int sftl_write_checkpoint_locked(struct apple_sftl *sftl, rep->nr_pages = image->count / 4; rep->nr_runs = snap->nr_runs; if (sftl->pool) { - n42_saves++; if (gc) gc_saves++; + else + n42_saves++; } ret = apple_sftl_checkpoint_stage(image, new_ctx, sftl->lanes[new_ctx], &sftl_context_io, &move, &readback); @@ -7455,11 +7469,33 @@ static int sftl_write_checkpoint_locked(struct apple_sftl *sftl, sftl->pool->context_site = final_site; /* The replacement table preceded retirement of the old site. * Carry its successful erase into the next ordinary checkpoint. + * 12H321 retires a context site as clean free (type 1, wear + 1) + * and counts it as free space at once (0x80dd07ac, 0x80dd6370). + * The dirty-free writer leaves type 1 to iOS, so without + * returned_sites every collection save would shrink the reusable + * pool by one block. */ sftl_set_role(sftl, old_site, SFTL_CLEAN_FREE); sftl->block_flags[old_site] = 0; sftl->wear[old_site]++; __set_bit(old_site, sftl->linux_erased); + __set_bit(old_site, sftl->returned_sites); + /* The adopted pool proposes only boot candidates. Arm returned + * sites from the save after their retirement on, once no saved + * table names them context; reuse certifies and erases them. + */ + for_each_set_bit(block, sftl->returned_sites, sftl_data_limit(sftl)) { + if (sftl->roles[block] != SFTL_CLEAN_FREE || sftl->pool->valid[block]) { + __clear_bit(block, sftl->returned_sites); + continue; + } + if (block == old_site || sftl->pool->lanes[block] || + !sftl_reuse_permitted(sftl, block)) + continue; + __clear_bit(block, sftl->used); + sftl->pool->lanes[block] = sftl->lanes[block]; + __set_bit(block, sftl->pool->unchecked); + } } __set_bit(new_ctx, sftl->used); ret = 0; From 8887361e119733ad0f6a51c2ed4fe34dcebf2954 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Berkay=20K=C3=B6sebay?= Date: Fri, 4 Dec 2026 12:29:26 +0100 Subject: [PATCH 59/59] mtd: apple-sftl: test collection beyond the per-boot checkpoint budget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Make the sparse NAND model's dirty-free pool configurable and replay the fill, trim and refill load that ran the phone out of space. 40 rounds alternate between two regions, and every third round rewrites half a region to leave partly valid donors. Every write must succeed with at least 12 collection saves in one boot. A cold load must return the last copy of every page and no flagged summary, both before and after the shutdown pad and explicit checkpoint. On the previous writer the case fails with -ENOSPC in round 9. Assisted-by: LLM Signed-off-by: Berkay Kösebay --- drivers/mtd/apple-sftl-gc-media-test.h | 121 ++++++++++++++++++++++++- 1 file changed, 117 insertions(+), 4 deletions(-) diff --git a/drivers/mtd/apple-sftl-gc-media-test.h b/drivers/mtd/apple-sftl-gc-media-test.h index 2655dafdae18d4..da9a6a5bbfef49 100644 --- a/drivers/mtd/apple-sftl-gc-media-test.h +++ b/drivers/mtd/apple-sftl-gc-media-test.h @@ -8,7 +8,7 @@ struct gc_test_flash { struct apple_sftl_context_record *context; u8 erased[N42_SUBBLOCKS]; bool incident; - u32 programs, erases, first_host_block; + u32 programs, erases, first_host_block, free_last; }; static const u32 gc_test_victim[] = { 877, 1000 }; @@ -123,7 +123,7 @@ static int gc_test_erase(void *arg, unsigned int bus, unsigned int cau, unsigned struct gc_test_flash *f = arg; u32 lane = cau * 2 + bus, pg; - if (b != 2 && (b < 10 || b > 17) && b != 877 && b != 1000) + if (b != 2 && (b < 10 || b > f->free_last) && b != 877 && b != 1000) return -EPERM; for (pg = 0; pg < T16_PAGES; pg++) kvfree(xa_erase(&f->rows, gc_test_row(b, lane, pg))); @@ -132,7 +132,8 @@ static int gc_test_erase(void *arg, unsigned int bus, unsigned int cau, unsigned return 0; } -static struct gc_test_flash *gc_test_medium(struct kunit *test, bool incident) +static struct gc_test_flash *gc_test_medium_free(struct kunit *test, bool incident, + u32 free_last) { struct gc_test_flash *f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); struct apple_sftl_context_record *ctx; @@ -145,6 +146,7 @@ static struct gc_test_flash *gc_test_medium(struct kunit *test, bool incident) KUNIT_ASSERT_NOT_NULL(test, f->context); KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, gc_test_release, f), 0); f->incident = incident; + f->free_last = free_last; f->t.blocks = N42_BLOCKS; f->t.subblocks = N42_SUBBLOCKS; f->t.vfl_block = N42_BLOCKS - 1; @@ -161,7 +163,7 @@ static struct gc_test_flash *gc_test_medium(struct kunit *test, bool incident) for (i = 0; i < N42_SUBBLOCKS; i++) { u8 *e = ctx[8 + i / 512].data + (i % 512) * 8; - e[0] = i == 2 ? 7 : i >= 10 && i <= 17 ? 9 : 8; + e[0] = i == 2 ? 7 : i >= 10 && i <= free_last ? 9 : 8; if (i == 877 || (incident && i == 1000)) { e[0] = 3; e[1] = 8; @@ -193,6 +195,11 @@ static struct gc_test_flash *gc_test_medium(struct kunit *test, bool incident) return f; } +static struct gc_test_flash *gc_test_medium(struct kunit *test, bool incident) +{ + return gc_test_medium_free(test, incident, 17); +} + static void gc_test_free_ftl(void *arg) { apple_sftl_free(arg); @@ -227,8 +234,114 @@ static void sftl_test_mandatory_gc_empty_save_close(struct kunit *test) get_unaligned_le64(head->oob) >> 16); } +#define GC_TEST_REGION 4092U +#define GC_TEST_ROUNDS 40U + +static void gc_test_fill(u8 *buf, u32 lba, u32 round) +{ + u32 i; + + for (i = 0; i < 4; i++) { + put_unaligned_le32(lba + i, buf + i * 4096); + put_unaligned_le32(round, buf + i * 4096 + 4); + } +} + +/* A load of @f returns the last round written to every 4-page group. */ +static void gc_test_check(struct kunit *test, struct gc_test_flash *f, u8 *buf, + u8 (*last)[GC_TEST_REGION / 4]) +{ + struct apple_sftl_btoc_audit audit; + struct apple_sftl *cold; + u32 r, i, lba; + + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->t.provider, &cold), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, gc_test_free_ftl, cold), 0); + KUNIT_ASSERT_EQ(test, apple_sftl_btoc_audit(cold, &audit), 0); + KUNIT_EXPECT_EQ(test, audit.flagged, 0U); + for (r = 0; r < 2; r++) { + for (i = 0; i < GC_TEST_REGION; i += 4) { + lba = GC_TEST_HOST + r * 4096 + i + (i / 4) % 4; + KUNIT_ASSERT_EQ(test, apple_sftl_read(cold, lba, buf), 0); + KUNIT_ASSERT_EQ(test, get_unaligned_le32(buf), lba); + KUNIT_ASSERT_EQ(test, get_unaligned_le32(buf + 4), (u32)last[r][i / 4]); + } + } +} + +/* + * The 2026-12-04 gcfrag flight: fill, trim, refill. Every block written + * before a save is saved live, so after its trim only a verified + * collection checkpoint can release it. With a free pool at the floor each + * refill needs a collection round. The writer refused the fifth round + * (four collection saves per boot) and the host write failed with ENOSPC. + * Collection must continue for as long as writes need space, more rounds + * than the eight explicit checkpoints a boot allows, and a cold load must + * return the last copy of every page. + */ +static void sftl_test_gc_rounds_unbounded(struct kunit *test) +{ + struct gc_test_flash *f = gc_test_medium_free(test, false, 23); + struct apple_sftl_checkpoint_report rep; + struct apple_sftl_btoc_audit audit; + struct apple_sftl *s; + struct apple_sftl_info info; + u8 *buf = kunit_kzalloc(test, APPLE_PPN_PAGE_SIZE, GFP_KERNEL); + u8 (*last)[GC_TEST_REGION / 4] = kunit_kzalloc(test, 2 * GC_TEST_REGION / 4, GFP_KERNEL); + u32 round, r, len, lba, i, pages, saves = 0; + u64 checkpoint; + int ret; + + KUNIT_ASSERT_NOT_NULL(test, buf); + KUNIT_ASSERT_NOT_NULL(test, last); + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->t.provider, &s), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, gc_test_free_ftl, s), 0); + apple_sftl_set_write_fence(s, GC_TEST_HOST, GC_TEST_HOST + 2 * 4096); + apple_sftl_get_info(s, &info); + checkpoint = info.checkpoint_sequence; + for (round = 0; round < GC_TEST_ROUNDS; round++) { + /* Every third round rewrites half a region without a trim and + * leaves partly valid donors that collection must copy. + */ + bool partial = round % 3 == 2; + + r = round % 2; + len = partial ? GC_TEST_REGION / 2 : GC_TEST_REGION; + if (round >= 2 && !partial) + KUNIT_ASSERT_EQ(test, apple_sftl_trim(s, GC_TEST_HOST + r * 4096, + GC_TEST_REGION), 0); + for (i = 0; i < len; i += 4) { + lba = GC_TEST_HOST + r * 4096 + i; + gc_test_fill(buf, lba, round); + KUNIT_ASSERT_EQ_MSG(test, apple_sftl_write(s, lba, buf, 4), 0, + "round %u lba %u after %u collection saves", round, + lba, saves); + last[r][i / 4] = round; + } + apple_sftl_get_info(s, &info); + if (info.checkpoint_sequence != checkpoint) + saves++; + checkpoint = info.checkpoint_sequence; + } + kunit_info(test, "%u collection saves, %u erases\n", saves, f->erases); + KUNIT_EXPECT_GE(test, saves, 12U); + KUNIT_EXPECT_GE(test, f->erases, saves); + + /* Recovery without a shutdown checkpoint replays the open stream. */ + gc_test_check(test, f, buf, last); + + /* Shutdown: pad any open block and write the explicit checkpoint. */ + ret = apple_sftl_pad_open_block(s, GC_TEST_HOST, buf, &pages); + KUNIT_ASSERT_TRUE_MSG(test, !ret || ret == -EALREADY, "pad %d", ret); + KUNIT_ASSERT_EQ(test, apple_sftl_write_checkpoint(s, &rep), 0); + KUNIT_ASSERT_EQ(test, apple_sftl_btoc_audit(s, &audit), 0); + KUNIT_EXPECT_EQ(test, audit.flagged, 0U); + gc_test_check(test, f, buf, last); +} + static struct kunit_case sftl_gc_media_cases[] = { KUNIT_CASE(sftl_test_mandatory_gc_empty_save_close), + KUNIT_CASE_SLOW(sftl_test_gc_rounds_unbounded), {} };