From e09501b09648744de1930cc3c3100b01b2bf8d48 Mon Sep 17 00:00:00 2001 From: Henrik Klee Date: Fri, 20 Nov 2026 05:37:35 +0800 Subject: [PATCH 1/7] docs: P105 NAND: Orchard's stack with #93 as the base, Cascadia's tested write-failure handling and 16 GB support ported on top Compares Shayne Legault's merged H2FMI/apple-sftl stack and draft #93 with rzxvx's apple_ppn/apple_ftl in Project Cascadia ad28ba4, and lists what each side keeps, what is ported and in which order it is qualified. Assisted-by: LLM --- docs/bring-up/p105-nand-merge-proposal.md | 145 ++++++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 docs/bring-up/p105-nand-merge-proposal.md diff --git a/docs/bring-up/p105-nand-merge-proposal.md b/docs/bring-up/p105-nand-merge-proposal.md new file mode 100644 index 00000000..6e8f27f2 --- /dev/null +++ b/docs/bring-up/p105-nand-merge-proposal.md @@ -0,0 +1,145 @@ +# P105 NAND: two drivers, one proposal + +State: proposal. Nothing here changes what the kernel builds. Henrik decides +which way the P105's NAND support goes; the combined driver is not written yet. + +The iPad mini 1 (P105) stores iOS's disk on PPN NAND behind two H2FMI buses, +through Apple's VFL and SwissPPNFTL, with LwVM partitions on top. Two +independent Linux implementations exist for it: + +- **Orchard's stack**, by Shayne Legault: `kernel/patches/armv7/mtd` 0001-0005 + (H2FMI geometry, verified page programming, the provider interface, the + VFL/SwissPPNFTL reader and append writes) and `armv7/block` 0001 (LwVM + partitions), merged on orchard main. His open draft + [#93](https://github.com/OrchardLinux/orchard/pull/93) + (`shaynelegault/hardware` `p105/08-ftl-reclamation`, bd8916c876) adds + 0006-0016: checkpoint encoding and GC planning, live-page copy, VFL bank + rotation, native context pages, recovery of interrupted saves, provider + event accounting, native allocation order, H2FMI erase with verification + and raw-program exclusion. Kernel branch: `shaynelegault/linux` + `p105/08-ftl-reclamation-armv7` (46a828ddef). +- **Cascadia's driver**, by rzxvx: `drivers/mtd/nand/apple` at Cascadia + ad28ba4 (`apple_ppn`, a PIO controller driver, and `apple_ftl` with + `sftl_*`, the FTL reader and writer), written from Cascadia's behavioural + spec (`devices/a5/docs/research/p105-nand-spec.md`); its format findings + and first write path credit crystal-lized's iPhone 5 work. Orchard imports + it as `kernel/patches/import/cascadia/0018`, with `APPLE_PPN` off. + +## The headline + +The two drivers so far cover **different P105s**. Cascadia's runs on the +16 GB package (2 CAUs per CE, 1064 blocks per CAU, 256 pages per block) with +iOS 8.4.1 (12H321) on the media; its `check_params` refuses anything else. +Orchard's SFTL layer runs on the 64 GB package (8 CAUs per bus, 2088 blocks +per CAU, 128 pages per block) and models iOS 9.3.5 (13G36); its H2FMI layer +reads both package profiles, but the FTL registers only for the 64 GB one. +Neither alone serves every P105. + +**Proposal: Orchard's stack as the base (H2FMI provider, apple-sftl, +LwVM partitions, then #93), with Cascadia's 16 GB / iOS 8.4.1 support and its +device-proven write-path failure handling ported in as separate commits under +rzxvx's authorship.** Details below. + +## Feature comparison + +| | Orchard: merged (0001-0005, block 0001) | Orchard: #93 (0006-0016, draft) | Cascadia ad28ba4 | +|---|---|---|---| +| Controller | Cascadia's earlier `mtd-apple-h2fmi`, extended: geometry from both packages' parameters, 4 row cycles, page status before data, bus stops on transport errors | adds block erase with status checks and readback of all 128 pages and their OOB; drains and refuses raw MTD programs while SFTL owns the map | own PIO driver `apple_ppn`: power-state feature `0x180` after every reset, 4-byte rows, burst transmit config, bad-block tables; claims its register windows (`request_mem_region`) | +| Package | 16 GB and 64 GB at the H2FMI level; FTL 64 GB only | same | 16 GB only | +| iOS on the media | 13G36 (iOS 9.3.5) is the model | 13G36 storage code is the reference, byte for byte | 12H321 (iOS 8.4.1) only; the NAND install refuses other builds | +| Read | VFL contexts and lane tables, saved SFTL ranges, journal replay incl. summaries and open stripes with holes; whole disk `applesftlN` | unchanged; incomplete native batches give a read-only disk | VFL context, context superblock, tree, replay; `ftl0` plus one block device per LwVM volume (`ftl0pN`) | +| Partitions | generic `block/partitions/lwvm.c` (contiguous partitions, PARTUUID/PARTNAME) | unchanged | LwVM parsed inside the driver; Cascadia's `nand-volume` tool resizes HFS and writes a new header, checked by iOS's own validator in Unicorn | +| Append | blank VFL blocks, native record metadata and summary pages, page blank-checked before use and read back after; mappings published only after verification; flush/FUA wait for verified writes | unchanged | one frontier superblock, BTOC at close, partial pages and siblings | +| In-place overwrite (rewriting an LBA) | yes, out of place by appending; read-modify-write for partial sectors, up to four 4 KiB pages per program | unchanged | yes, remap to the frontier | +| Reclamation / GC | none: freed space is never reused, `ENOSPC` once blank blocks run out (`devices/p105/device.toml` `reclaims = false`) | yes: victim selection by native rules (clean/dirty pools, wear), live-page copy with readback, donor erase only after checkpoint readback and a full fresh reload; **disabled on the P105** until erase and accounting are qualified | yes: up to `SFTL_MAX_VICTIMS` closed superblocks, fewest valid first; live LBAs moved, commit, then erase; tree compaction when the map fragments | +| Checkpoint / context write-back in iOS's format | none: Apple's map, contexts and VFL bootstrap left in place; recovery replays the appended records | native context and range records, 24-page checkpoint, VFL bank rotation (4 replicas), statistics pages sampled in native order; byte-compared against 13G36's storage code run in emulation; disabled on the P105 | context written to a fresh superblock and verified page by page, older contexts and victims erased afterwards; "Linux writes the normal form" of the tree; the spec-gaps doc lists where iOS's own output differs (e.g. a BTOC `user` field) | +| iOS boots after Linux wrote | untested | emulation only (13G36 foreground GC replay, provider bytes) | yes, "checked many times" on 8.4.1 (Cascadia's `p105-nand-other-ios.md`), incl. the full volume cycle below | +| Failure handling | a failed program, uncertain completion or readback mismatch stops all I/O on that bus; disk read-only if the replayed journal does not end at the allocation floor | ambiguous erase or failed verification stops the writer instance; recovery of interrupted saves and partial lane retirement, read-only when the newer mapping is not provable | program/erase failure: the superblock is given up for the session (type 1, nothing valid, VFL untouched) and its live data moved to a new frontier; failed spare erases try the next spare; torn page found at mount: superblock given up (`give_up_torn`); a stopped writer refuses writes and the checkpoint | +| Power-loss recovery | fresh recovery replays appended records, including a data prefix whose summary was cut off | KUnit power cuts at all 25 save boundaries, between the old context's lane erases, after each of 76 rotation steps; 95 incomplete save prefixes and 15 partial retirements on a RAM overlay of captured pages | replay of an unclosed frontier; offline crash-replay tests on an overlay of the `w0c` dump; the 2026-11-16 incident (below) recovered on the device | +| Fault injection | KUnit mock provider | KUnit synthetic media with readback faults, ambiguous erase, reservation failure, sequence exhaustion | `CONFIG_APPLE_PPN_FAULT_INJECT`: program/erase failures injected on the device under ext4 writes (`tools/nand-faults/faults.sh`) | +| Write gating | none in the kernel; the installer decides (`runtime/recovery/storage-fence`) | raw MTD programs refused while SFTL owns the disk | `apple_ppn.allow_write`, `apple_ftl.enable_write`, `write_volume=Linux`; System, Data and effaceable volumes always refuse | +| Tests | KUnit: H2FMI parameter parsing and row encoding, SFTL recovery, journal/trim ordering, replica disagreement, torn summaries, append writer (26 tests in a v6.12 KUnit kernel) | 72 sanitizer cases, 209 map round trips, 66 relocation differentials; firmware differential on 600 block tables, 341 captured donors, 552 provider bytes | offline `nandtest` on the `w0c` dump (spec section 8.1 read checks; writer on an overlay that enforces erase-before-program and page order: close, commit, crash replay, reclaim, tree compaction, remount); device ladder rungs 1-5 | +| Device evidence | device captures gave the geometry and logical-page cross-checks; earlier bounded programming gave protocol evidence; this exact kernel revision has not run on a P105 (`storage_read`/`storage_write` untested) | read-only capture procedure and `compare_erase.py`; no physical erase or checkpoint write yet | one 16 GB iPad mini on 8.4.1: whole-device read with 0 errors; on 2026-11-16 backup, LwVM remove, HFS grow, shrink, create, ext4 fill through the FTL and a daily PC-less boot from the NAND volume, iOS and `fsck_hfs` clean after each step | + +The 2026-11-16 incident in Cascadia's record: an old userspace tool reset the +controller through `/dev/mem` while `apple_ppn` was programming; a page tore, +the writer gave the superblock up, four spare erases timed out and the writer +stopped before any commit. Recovery (`tools/nand-recover`) gave the torn +superblock up and erased the spares; iOS and `e2fsck` were clean afterwards. +The fixes were `give_up_torn` at mount, `request_mem_region`, and +`IO_STRICT_DEVMEM` in Cascadia's config. Orchard's #93 0016 closes the +in-kernel half of the same hazard (raw MTD programs refused while SFTL owns +the map); `/dev/mem` access stays open in Orchard's config +(`STRICT_DEVMEM` is off). + +## Why Orchard's stack as the base + +- It is already the platform's NAND path, in upstream form: one controller + driver (H2FMI) with a provider interface, the FTL as a separate MTD user, + LwVM as an ordinary partition parser, no command-line gates. That matches + the final-stack rules (no gates in shared drivers, storage protection in + the installer). +- Its controller and reader already handle both packages' geometry from + their parameters; Cascadia's would need the 64 GB layout added everywhere + (`NCAU`, `check_params`, bank order, 256 vs 128 pages per block). +- #93 models iOS's own allocation, wear, statistics and context layout and + checks them against Apple's code. Cascadia's writer produces contexts iOS + 8.4.1 accepts, with documented differences from iOS's own output. +- Two controller drivers for one block cannot share the hardware; keeping one + avoids a second register-level implementation to maintain. + +The cost: Orchard's writer has no device evidence yet, and Cascadia's does. +The ports below are chosen to carry that evidence over. + +## What to port from Cascadia (authored by rzxvx, one commit each) + +1. **16 GB geometry in apple-sftl**: the four-bank order `(bus 0, cau 0), + (bus 1, cau 0), (bus 0, cau 1), (bus 1, cau 1)`, 256 pages per block, nb 4 + or 8 BTOC sizes as Cascadia reads them, so the reader registers on both + packages. Source: `sftl_mount.c`, `sftl.h`, spec-gaps corrections. +2. **iOS 8.4.1 (12H321) context compatibility**: run the reader against + Cascadia's `w0c` dump (private, like Orchard's captures) and compare the + native context encoder of #93 with Cascadia's `sftl_context_write`/ + `sftl_format.c` output, which iOS 8.4.1 is known to boot from. Port any + field 12H321 needs that 13G36 does not. +3. **Session give-up of a failed superblock** (`mark_bad`, `frontier_fail`, + `take_spare` trying the next spare) into the append writer, instead of + stopping the whole bus on the first program failure. The VFL stays + untouched; iOS retires a really bad block itself. +4. **Torn open superblock at mount** (`give_up_torn`): live data moved, the + superblock left with nothing valid and listed for erase, so neither Linux + nor iOS programs into it before an erase. +5. **Controller facts from `apple_ppn`** where H2FMI lacks them: the power + state set after every reset, the transmit burst configuration, the + bad-block table reads, and claiming the register windows. +6. **On-device fault injection** as a test-only provider option (Kconfig, + default n), so the failure paths above can be exercised on a tablet, not + only on synthetic media. + +Not ported: the command-line write gates (the installer is the gate), the +in-driver LwVM parser (block/partitions/lwvm.c already does it; Cascadia's +`nand-volume` resizing belongs with the installer's LwVM writer in +`src/orchard/lwvm.py`), and `apple_ppn` as a second controller driver. + +## What stays from Orchard's side (authored by Shayne Legault) + +All of `armv7/mtd` 0001-0005 and `armv7/block` 0001 as merged, and #93's +0006-0016 as he lands them: checkpoint encoding, live-page copy, reclamation +in the write path, VFL rotation, native context pages, interrupted-save +recovery, provider accounting, native allocation order, verified erase and +raw-program exclusion. + +## Order and evidence before anything is enabled + +1. Land #93 as it stands (its own review); P105 erase stays off. +2. Ports 1 and 5, then read-only device runs on both a 16 GB and a 64 GB + P105: the whole disk read and compared with a raw dump. +3. Ports 3, 4 and 6; fault-injection runs on a 16 GB P105 against a + disposable Linux volume, as Cascadia did. +4. Port 2, then writes with reclamation on the 16 GB P105 (8.4.1), a cold + iOS boot and `fsck_hfs` after each step, as in Cascadia's 2026-11-16 + cycle; then the 64 GB P105 (9.3.5) once #93's erase qualification is done. + +Cascadia's import stays in the series meanwhile, so its files remain +available; `APPLE_PPN` stays off. Drop 0018 from the platform only when the +ports are in. From aa504dad69f8f90e06758dd32405f3cdc7e0af76 Mon Sep 17 00:00:00 2001 From: Henrik Klee Date: Fri, 20 Nov 2026 06:03:05 +0800 Subject: [PATCH 2/7] kernel: P105 NAND: read the 16 GB package as well as the 64 GB one The P105's translation layer registered only on the 64 GB NAND package. Port Cascadia's 16 GB layout into it (patch 0018, authored by rzxvx): four banks of 1064 blocks of 256 pages, 1055 superblocks, the VFL in blocks 1062/1063, iOS 8.4.1's context and summary rules. A 16 GB P105 now gets a read-only applesftl disk of 16,000,000,000 bytes. 0017 first moves #93's fixed 64 GB constants into a geometry descriptor, unchanged in behaviour for the 64 GB package. KUnit gains a synthetic 16 GB medium (3 cases); all 84 apple-sftl and apple-h2fmi cases pass. Untested on hardware. Assisted-by: LLM --- ...escribe-the-package-geometry-at-runt.patch | 1261 +++++++++++++++++ ...apple-sftl-Read-the-16-GB-PPN-layout.patch | 685 +++++++++ 2 files changed, 1946 insertions(+) create mode 100644 kernel/patches/armv7/mtd/0017-mtd-apple-sftl-Describe-the-package-geometry-at-runt.patch create mode 100644 kernel/patches/armv7/mtd/0018-mtd-apple-sftl-Read-the-16-GB-PPN-layout.patch diff --git a/kernel/patches/armv7/mtd/0017-mtd-apple-sftl-Describe-the-package-geometry-at-runt.patch b/kernel/patches/armv7/mtd/0017-mtd-apple-sftl-Describe-the-package-geometry-at-runt.patch new file mode 100644 index 00000000..ca4bc7ad --- /dev/null +++ b/kernel/patches/armv7/mtd/0017-mtd-apple-sftl-Describe-the-package-geometry-at-runt.patch @@ -0,0 +1,1261 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Henrik Klee +Date: Fri, 20 Nov 2026 05:53:29 +0800 +Subject: [PATCH 17/18] mtd: apple-sftl: Describe the package geometry at + runtime + +The translation layer fixes the measured 64 GB package in compile-time +constants: 16 lanes, 128 pages per block, 2088 physical blocks, 2086 +superblocks, the VFL bootstrap block 2087 and members from block 2056, +64 SLC pages per VFL bank and 15625016 logical pages. The 16 GB P105 +package uses the same VFL and SwissPPNFTL structures with other values, +so a second package cannot be added without touching every bound. + +Select a geometry descriptor from the provider's bus, CAU, block and +page counts and derive the address stride, provider size, slot counts and +range sentinel from it. Arrays keep the 64 GB maxima. The native context +tag check gains a variant that sizes the block table, user sequence and +read count sections from the superblock count; the 64 GB layout it +produces is unchanged. + +The writer, reclamation, VFL rotation and snapshots keep the 64 GB +address layout of the reclaim and accounting code. A descriptor states +whether that writer is modelled for it; one that is not exposes its disk +read-only. + +The 64 GB descriptor reproduces every previous constant. No functional +change. + +Assisted-by: LLM +--- + drivers/mtd/apple-sftl-account.c | 40 +++- + drivers/mtd/apple-sftl-account.h | 1 + + drivers/mtd/apple-sftl-core.c | 388 ++++++++++++++++++------------- + 3 files changed, 259 insertions(+), 170 deletions(-) + +diff --git a/drivers/mtd/apple-sftl-account.c b/drivers/mtd/apple-sftl-account.c +index a8d50fa7b..d272552ec 100644 +--- a/drivers/mtd/apple-sftl-account.c ++++ b/drivers/mtd/apple-sftl-account.c +@@ -22,38 +22,58 @@ + #define SFTL_SB_PER_RECORD (APPLE_SFTL_CHUNK / SFTL_SB_ENTRY_BYTES) + #define SFTL_MAX_WEAR 0xffff + +-bool apple_sftl_native_context_tag(u32 index, const u8 *meta) ++/* Records per native section: every section fills whole 4-record pages. */ ++static u32 sftl_section_records(u32 subblocks, u32 per_record) ++{ ++ return round_up(DIV_ROUND_UP(subblocks, per_record), 4); ++} ++ ++/* ++ * The fixed native records are, in order: base (4), statistics (4), block ++ * table, closed-block user sequences and read counts, each sized from the ++ * superblock count. Range records follow them. ++ */ ++bool apple_sftl_native_context_tag_for(u32 subblocks, u32 index, const u8 *meta) + { ++ u32 sb_start = SFTL_SB_START; ++ u32 user_start = sb_start + sftl_section_records(subblocks, SFTL_SB_PER_RECORD); ++ u32 read_start = user_start + sftl_section_records(subblocks, APPLE_SFTL_CHUNK / 16); ++ u32 end = read_start + sftl_section_records(subblocks, APPLE_SFTL_CHUNK / 4); + u32 start = 0, entries = 0, stride = 0; + u8 subtype; + + if (index < SFTL_STATS_START) + subtype = 1; +- else if (index < SFTL_SB_START) ++ else if (index < sb_start) + subtype = 2; +- else if (index < SFTL_USER_SEQ_START) { ++ else if (index < user_start) { + subtype = 3; + stride = SFTL_SB_PER_RECORD; +- start = (index - SFTL_SB_START) * stride; +- } else if (index < SFTL_READ_COUNT_START) { ++ start = (index - sb_start) * stride; ++ } else if (index < read_start) { + subtype = 5; + stride = APPLE_SFTL_CHUNK / 16; +- start = (index - SFTL_USER_SEQ_START) * stride; +- } else if (index < APPLE_SFTL_ACCOUNT_RECORDS) { ++ start = (index - user_start) * stride; ++ } else if (index < end) { + subtype = 6; + stride = APPLE_SFTL_CHUNK / 4; +- start = (index - SFTL_READ_COUNT_START) * stride; ++ start = (index - read_start) * stride; + } else { + subtype = 4; + } +- if (start < APPLE_SFTL_SUBBLOCKS) +- entries = min(stride, APPLE_SFTL_SUBBLOCKS - start); ++ if (start < subblocks) ++ entries = min(stride, subblocks - start); + return meta && meta[0] == 0x1f && meta[1] == subtype && + get_unaligned_le16(meta + 8) == start && + get_unaligned_le16(meta + 10) == entries && + get_unaligned_le32(meta + 12) == U32_MAX; + } + ++bool apple_sftl_native_context_tag(u32 index, const u8 *meta) ++{ ++ return apple_sftl_native_context_tag_for(APPLE_SFTL_SUBBLOCKS, index, meta); ++} ++ + /* Native close (0x8108bd60) samples the user sequence high word once per + * footer run. Lengths and skipped U32_MAX values do not enter the mean. + */ +diff --git a/drivers/mtd/apple-sftl-account.h b/drivers/mtd/apple-sftl-account.h +index ad079aafc..8ecc75e23 100644 +--- a/drivers/mtd/apple-sftl-account.h ++++ b/drivers/mtd/apple-sftl-account.h +@@ -57,6 +57,7 @@ struct apple_sftl_runtime_stats { + int apple_sftl_account_refresh(struct apple_sftl_checkpoint *image, + const struct apple_sftl_runtime_stats *runtime); + bool apple_sftl_native_context_tag(u32 index, const u8 *meta); ++bool apple_sftl_native_context_tag_for(u32 subblocks, u32 index, const u8 *meta); + + void apple_sftl_summarize_user_seq(struct apple_sftl_user_seq *out, const u8 *runs, u32 count); + int apple_sftl_account_user_seq(struct apple_sftl_snapshot *snapshot, +diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c +index 857de8b84..a3a9918d0 100644 +--- a/drivers/mtd/apple-sftl-core.c ++++ b/drivers/mtd/apple-sftl-core.c +@@ -25,13 +25,12 @@ + #include "apple-sftl-reclaim.h" + #include "apple-sftl-account.h" + +-#define SFTL_LPAGES 15625016U +-#define SFTL_DISK_PAGES 15625000U +-#define SFTL_BLOCKS 2088U +-#define SFTL_SUBBLOCKS 2086U +-#define SFTL_LANES 16U +-#define SFTL_STRIDE 8192U +-#define SFTL_PROVIDER (SFTL_SUBBLOCKS * SFTL_STRIDE) ++/* Array bounds: the largest supported package. */ ++#define SFTL_MAX_BLOCKS 2088U ++#define SFTL_MAX_SUBBLOCKS 2086U ++#define SFTL_MAX_LANES 16U ++#define SFTL_MAX_VFL_PAGES 128U ++#define SFTL_MAX_PROVIDER (SFTL_MAX_SUBBLOCKS * 8192U) + #define SFTL_UNMAPPED U32_MAX + #define SFTL_SEQUENCE GENMASK_ULL(47, 0) + #define SFTL_MAX_CONTEXTS 16U +@@ -52,6 +51,38 @@ enum sftl_block_role { + #define SFTL_FOOTER_BYTES (SFTL_FOOTER_CHUNKS * SFTL_CHUNK) + #define SFTL_GC_MAP_BYTES (8U * 1024 * 1024) /* per map, on the measured 512 MiB P105 */ + ++/* ++ * One measured package and the storage format on it. A lane is one CAU of ++ * one bus, lane = cau * 2 + bus. A superblock is the same physical block in ++ * every lane that the VFL lists for the FTL; its addresses step through the ++ * lanes in order, four logical pages per physical page. ++ */ ++struct sftl_geometry { ++ u16 buses, caus, lanes; ++ u16 blocks; /* physical blocks per CAU */ ++ u16 pages; /* MLC pages per block */ ++ u16 subblocks; /* FTL superblocks, VFL header +12 and +14 */ ++ u16 vfl_pages; /* SLC pages in one VFL bank member */ ++ u16 vfl_first; /* lowest physical block of a VFL member */ ++ u16 bootstrap; /* block whose page zero seeds the member list */ ++ u16 map_batch; /* native map records are a multiple of this */ ++ 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 */ ++}; ++ ++/* 64 GB Hynix PPN with 13G36 (iOS 9.3.5) on the media. */ ++static const struct sftl_geometry sftl_64gb = { ++ .buses = 2, .caus = 8, .lanes = 16, .blocks = 2088, .pages = 128, ++ .subblocks = 2086, .vfl_pages = 64, .vfl_first = 2056, .bootstrap = 2087, ++ .map_batch = APPLE_SFTL_NATIVE_MAP_BATCH, ++ .disk_pages = 15625000, .lpages = 15625016, .writer = true, ++}; ++ ++static const struct sftl_geometry *const sftl_geometries[] = { ++ &sftl_64gb, ++}; ++ + struct sftl_run { + struct rb_node node; + u32 start, end, provider; +@@ -70,25 +101,26 @@ struct sftl_records { + + struct apple_sftl { + struct apple_ppn *ppn; ++ const struct sftl_geometry *geo; + struct apple_sftl_vfl_source vfl_source; + bool vfl_degraded, context_degraded, native_context; +- u8 roles[SFTL_SUBBLOCKS], block_flags[SFTL_SUBBLOCKS]; +- u16 wear[SFTL_SUBBLOCKS]; ++ u8 roles[SFTL_MAX_SUBBLOCKS], block_flags[SFTL_MAX_SUBBLOCKS]; ++ u16 wear[SFTL_MAX_SUBBLOCKS]; + struct rb_root runs; + struct sftl_records context; + struct apple_sftl_user_seq *closed_user_seq; + u32 nr_runs; +- u16 lanes[SFTL_BLOCKS]; +- DECLARE_BITMAP(reserved, SFTL_BLOCKS); +- DECLARE_BITMAP(vfl_reserved, SFTL_BLOCKS); +- DECLARE_BITMAP(unknown_lane_flags, SFTL_BLOCKS); +- DECLARE_BITMAP(checkpoint_used, SFTL_BLOCKS); +- DECLARE_BITMAP(old_closed, SFTL_BLOCKS); ++ u16 lanes[SFTL_MAX_BLOCKS]; ++ DECLARE_BITMAP(reserved, SFTL_MAX_BLOCKS); ++ DECLARE_BITMAP(vfl_reserved, SFTL_MAX_BLOCKS); ++ DECLARE_BITMAP(unknown_lane_flags, SFTL_MAX_BLOCKS); ++ DECLARE_BITMAP(checkpoint_used, SFTL_MAX_BLOCKS); ++ DECLARE_BITMAP(old_closed, SFTL_MAX_BLOCKS); + u64 checkpoint_start; + u64 checkpoint_sequence, sequence, journal_sequence; +- DECLARE_BITMAP(candidates, SFTL_BLOCKS); +- DECLARE_BITMAP(fallback_occupied, SFTL_SUBBLOCKS); +- DECLARE_BITMAP(used, SFTL_BLOCKS); ++ DECLARE_BITMAP(candidates, SFTL_MAX_BLOCKS); ++ DECLARE_BITMAP(fallback_occupied, SFTL_MAX_SUBBLOCKS); ++ DECLARE_BITMAP(used, SFTL_MAX_BLOCKS); + u32 next_candidate, append_block, append_position, append_capacity, spare; + const struct apple_sftl_checkpoint_ops *checkpoint_ops; + void *checkpoint_priv; +@@ -102,6 +134,22 @@ struct apple_sftl { + bool failed; + }; + ++static u32 sftl_stride(const struct apple_sftl *sftl) ++{ ++ return sftl->geo->lanes * sftl->geo->pages * 4; ++} ++ ++static u32 sftl_provider(const struct apple_sftl *sftl) ++{ ++ return sftl->geo->subblocks * sftl_stride(sftl); ++} ++ ++/* Logical page slots in a block written on the given lanes. */ ++static u32 sftl_slots(const struct apple_sftl *sftl, u16 lanes) ++{ ++ return hweight16(lanes) * sftl->geo->pages * 4; ++} ++ + static u64 sftl_sequence(const u8 *meta) + { + return get_unaligned_le64(meta) >> 16; +@@ -156,18 +204,18 @@ static int sftl_translate(struct apple_sftl *sftl, u32 address, + unsigned int lane, wanted, count; + u16 bitmap; + +- if (address >= SFTL_PROVIDER) ++ if (address >= sftl_provider(sftl)) + return -ERANGE; + *chunk = address & 3; +- *block = address / SFTL_STRIDE; +- offset = (address % SFTL_STRIDE) / 4; ++ *block = address / sftl_stride(sftl); ++ offset = (address % sftl_stride(sftl)) / 4; + bitmap = sftl->lanes[*block]; + count = hweight16(bitmap); +- if (!count || offset / count >= 128) ++ if (!count || offset / count >= sftl->geo->pages) + return -ERANGE; + *page = offset / count; + wanted = offset % count; +- for (lane = 0; lane < SFTL_LANES; lane++) { ++ for (lane = 0; lane < sftl->geo->lanes; lane++) { + if (!(bitmap & BIT(lane))) + continue; + if (!wanted--) +@@ -228,9 +276,9 @@ static int sftl_add_run(struct apple_sftl *sftl, u32 start, u32 end, u32 provide + { + struct sftl_run *run; + +- if (start >= end || end > SFTL_LPAGES || ++ if (start >= end || end > sftl->geo->lpages || + (provider != SFTL_UNMAPPED && +- (provider >= SFTL_PROVIDER || end - start > SFTL_PROVIDER - provider))) ++ (provider >= sftl_provider(sftl) || end - start > sftl_provider(sftl) - provider))) + return -EBADMSG; + run = kmalloc(sizeof(*run), GFP_KERNEL); + if (!run) +@@ -304,15 +352,15 @@ static int sftl_replace(struct apple_sftl *sftl, u32 start, u32 length, u32 addr + u32 end; + int ret; + +- if (!length || start >= SFTL_LPAGES || length > SFTL_LPAGES - start || ++ if (!length || start >= sftl->geo->lpages || length > sftl->geo->lpages - start || + (address != SFTL_UNMAPPED && +- (address >= SFTL_PROVIDER || length > SFTL_PROVIDER - address))) ++ (address >= sftl_provider(sftl) || length > sftl_provider(sftl) - address))) + return -EBADMSG; + end = start + length; + ret = sftl_split(sftl, start); + if (ret) + return ret; +- if (end < SFTL_LPAGES) { ++ if (end < sftl->geo->lpages) { + ret = sftl_split(sftl, end); + if (ret) + return ret; +@@ -344,10 +392,10 @@ static int sftl_record_add(struct sftl_records *records, u64 stamp, + struct sftl_record *new; + u32 capacity; + +- if (records->count == SFTL_PROVIDER) ++ if (records->count == SFTL_MAX_PROVIDER) + return -E2BIG; + if (records->count == records->capacity) { +- capacity = min_t(u32, max(records->capacity * 2, 256U), SFTL_PROVIDER); ++ capacity = min_t(u32, max(records->capacity * 2, 256U), SFTL_MAX_PROVIDER); + new = kvrealloc(records->items, array_size(capacity, sizeof(*new)), + GFP_KERNEL); + if (!new) +@@ -369,7 +417,6 @@ static int sftl_record_compare(const void *a, const void *b) + return left < right ? -1 : left > right; + } + +-#define SFTL_VFL_PAGES 64 + #define SFTL_VFL_COPIES 4 + #define SFTL_VFL_HEADER 0xff + +@@ -379,7 +426,7 @@ struct sftl_vfl_slot { + }; + + struct sftl_vfl_scan { +- struct sftl_vfl_slot slots[2][SFTL_VFL_PAGES]; ++ struct sftl_vfl_slot slots[2][SFTL_MAX_VFL_PAGES]; + u8 sample[APPLE_PPN_PAGE_SIZE + APPLE_PPN_OOB_SIZE]; + u8 reference_data[APPLE_PPN_PAGE_SIZE]; + }; +@@ -394,9 +441,10 @@ static int sftl_vfl_members(struct apple_sftl *sftl) + /* An interrupted erase can remove the usual lane-zero seed. Search only + * page zero in the measured bootstrap block for a surviving member list. + */ +- for (lane = 0; lane < SFTL_LANES; lane++) { ++ for (lane = 0; lane < sftl->geo->lanes; lane++) { + ret = sftl->ppn->ops->read_page(sftl->ppn->priv, lane & 1, lane >> 1, +- 2087, 0, true, sftl->page, sftl->oob, &status); ++ sftl->geo->bootstrap, 0, true, sftl->page, ++ sftl->oob, &status); + if (ret) + return ret; + /* Some nonmembers report 45 at the bootstrap coordinate. Once +@@ -412,15 +460,16 @@ static int sftl_vfl_members(struct apple_sftl *sftl) + !sftl_erased(sftl->oob, sizeof(sftl->oob))) + return -EBADMSG; + } +- if (lane == SFTL_LANES) ++ if (lane == sftl->geo->lanes) + return -EBADMSG; + for (i = 0; i < 8; i++) { + const u8 *row = sftl->page + 0x100 + 4 * i; + + members[i].block = get_unaligned_le16(row); + members[i].lane = row[2]; +- if (members[i].block < 2056 || members[i].block >= SFTL_BLOCKS || +- members[i].lane >= SFTL_LANES || row[3]) ++ if (members[i].block < sftl->geo->vfl_first || ++ members[i].block >= sftl->geo->blocks || ++ members[i].lane >= sftl->geo->lanes || row[3]) + return -EBADMSG; + for (j = 0; j < i; j++) + if (members[j].block == members[i].block && members[j].lane == members[i].lane) +@@ -429,7 +478,7 @@ static int sftl_vfl_members(struct apple_sftl *sftl) + } + if (lane) { + for (i = 0; i < 8; i++) +- if (members[i].lane == lane && members[i].block == 2087) ++ if (members[i].lane == lane && members[i].block == sftl->geo->bootstrap) + return 0; + return -EBADMSG; + } +@@ -484,7 +533,7 @@ static int sftl_vfl_read_slot(struct apple_sftl *sftl, struct sftl_vfl_scan *sca + row[2] != m->lane || row[3]) + return -EBADMSG; + } +- } else if (!page || slot->tag >= SFTL_LANES || sftl->oob[2]) { ++ } else if (!page || slot->tag >= sftl->geo->lanes || sftl->oob[2]) { + return -EBADMSG; + } + memcpy(scan->sample, sftl->page, APPLE_PPN_PAGE_SIZE); +@@ -522,7 +571,7 @@ static int sftl_vfl_index(struct apple_sftl *sftl, struct sftl_vfl_scan *scan) + int ret; + + for (group = 0; group < 2; group++) { +- for (page = 0; page < SFTL_VFL_PAGES; page++) { ++ for (page = 0; page < sftl->geo->vfl_pages; page++) { + struct sftl_vfl_slot *slot = &scan->slots[group][page]; + + ret = sftl_vfl_read_slot(sftl, scan, group, page, slot); +@@ -536,7 +585,7 @@ static int sftl_vfl_index(struct apple_sftl *sftl, struct sftl_vfl_scan *scan) + if (group && slot->age <= scan->slots[0][0].age) { + u32 other = scan->slots[0][0].age - slot->age; + +- if (other < SFTL_VFL_PAGES && scan->slots[0][other].copies) ++ if (other < sftl->geo->vfl_pages && scan->slots[0][other].copies) + return -EBADMSG; + } + if (slot->copies != 0xf) { +@@ -571,15 +620,15 @@ static int sftl_vfl_load_refs(struct apple_sftl *sftl, struct sftl_vfl_scan *sca + * (+14). An older, smaller FTL is a different address space. + */ + if (get_unaligned_le16(scan->sample + 10) != 16 || +- get_unaligned_le16(scan->sample + 12) != SFTL_SUBBLOCKS || +- get_unaligned_le16(scan->sample + 14) != SFTL_SUBBLOCKS) ++ get_unaligned_le16(scan->sample + 12) != sftl->geo->subblocks || ++ get_unaligned_le16(scan->sample + 14) != sftl->geo->subblocks) + return -EOPNOTSUPP; +- for (lane = 0; lane < SFTL_LANES; lane++) { ++ for (lane = 0; lane < sftl->geo->lanes; lane++) { + const struct sftl_vfl_slot *table; + u16 ref = get_unaligned_le16(scan->sample + 0x200 + 32 * lane); + u16 row = ref & 0x7fff; + +- if (row >= SFTL_VFL_PAGES) ++ if (row >= sftl->geo->vfl_pages) + return -EBADMSG; + table = &scan->slots[ref >> 15][row]; + /* A stale reference can point at the same lane in a later bank cycle. */ +@@ -593,7 +642,7 @@ static int sftl_vfl_load_refs(struct apple_sftl *sftl, struct sftl_vfl_scan *sca + static int sftl_vfl_same_table(struct apple_sftl *sftl, struct sftl_vfl_scan *scan, + u16 ref, unsigned int group, unsigned int page) + { +- unsigned int block; ++ unsigned int block, subblocks = sftl->geo->subblocks, blocks = sftl->geo->blocks; + int ret; + + ret = sftl_vfl_reread(sftl, scan, ref >> 15, ref & 0x7fff); +@@ -603,14 +652,14 @@ static int sftl_vfl_same_table(struct apple_sftl *sftl, struct sftl_vfl_scan *sc + ret = sftl_vfl_reread(sftl, scan, group, page); + if (ret) + return ret; +- if (memcmp(scan->reference_data, scan->sample, 2 * SFTL_SUBBLOCKS) || +- memcmp(scan->reference_data + 2 * SFTL_BLOCKS, scan->sample + 2 * SFTL_BLOCKS, +- APPLE_PPN_PAGE_SIZE - 2 * SFTL_BLOCKS)) ++ if (memcmp(scan->reference_data, scan->sample, 2 * subblocks) || ++ memcmp(scan->reference_data + 2 * blocks, scan->sample + 2 * blocks, ++ APPLE_PPN_PAGE_SIZE - 2 * blocks)) + return -EBADMSG; + /* Two trailing physical indices are outside every supported FTL + * address. Older inactive marker flags can differ during rotation. + */ +- for (block = SFTL_SUBBLOCKS; block < SFTL_BLOCKS; block++) { ++ for (block = subblocks; block < blocks; block++) { + u16 old = get_unaligned_le16(scan->reference_data + 2 * block); + u16 new = get_unaligned_le16(scan->sample + 2 * block); + +@@ -628,12 +677,12 @@ static int sftl_vfl_check_tail(struct apple_sftl *sftl, struct sftl_vfl_scan *sc + const u16 *refs) + { + const struct apple_sftl_vfl_source *source = &sftl->vfl_source; +- u16 other[SFTL_LANES]; ++ u16 other[SFTL_MAX_LANES]; + unsigned int group, page, lane; + int ret; + + for (group = 0; group < 2; group++) +- for (page = 0; page < SFTL_VFL_PAGES; page++) { ++ for (page = 0; page < sftl->geo->vfl_pages; page++) { + const struct sftl_vfl_slot *slot = &scan->slots[group][page]; + + if (!slot->copies || slot->age > source->age || +@@ -651,7 +700,7 @@ static int sftl_vfl_check_tail(struct apple_sftl *sftl, struct sftl_vfl_scan *sc + ret = sftl_vfl_load_refs(sftl, scan, group, page, other); + if (ret) + return ret; +- for (lane = 0; lane < SFTL_LANES; lane++) { ++ for (lane = 0; lane < sftl->geo->lanes; lane++) { + if (other[lane] == refs[lane]) + continue; + ret = sftl_vfl_same_table(sftl, scan, refs[lane], +@@ -667,7 +716,7 @@ static int sftl_vfl(struct apple_sftl *sftl) + { + const struct apple_sftl_vfl_source *source = &sftl->vfl_source; + struct sftl_vfl_scan *scan; +- u16 refs[SFTL_LANES]; ++ u16 refs[SFTL_MAX_LANES]; + unsigned int lane, block; + int ret; + +@@ -686,7 +735,7 @@ static int sftl_vfl(struct apple_sftl *sftl) + ret = sftl_vfl_check_tail(sftl, scan, refs); + if (ret) + goto out; +- for (lane = 0; lane < SFTL_LANES; lane++) { ++ for (lane = 0; lane < sftl->geo->lanes; lane++) { + u16 ref = refs[lane]; + + if (!source->page && (ref >> 15) != source->group) +@@ -694,7 +743,7 @@ static int sftl_vfl(struct apple_sftl *sftl) + ret = sftl_vfl_reread(sftl, scan, ref >> 15, ref & 0x7fff); + if (ret) + goto out; +- for (block = 0; block < SFTL_BLOCKS; block++) { ++ for (block = 0; block < sftl->geo->blocks; block++) { + u16 value = get_unaligned_le16(scan->sample + block * 2); + + if (!(value & BIT(15))) { +@@ -735,7 +784,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) ++ if (!sftl || !ops || !ops->erase || !ops->program || !sftl->geo->writer) + return -EOPNOTSUPP; + cold = kvzalloc(sizeof(*cold), GFP_NOIO); + if (!cold) +@@ -753,12 +802,13 @@ int apple_sftl_rotate_vfl(struct apple_sftl *sftl, const struct apple_sftl_vfl_o + if (ret) + goto out; + cold->ppn = sftl->ppn; ++ cold->geo = sftl->geo; + cold->page = sftl->page; + ret = sftl_vfl(cold); + if (ret) + goto out; + if (cold->vfl_degraded || cold->vfl_source.group == sftl->vfl_source.group || +- cold->vfl_source.page != SFTL_LANES + 1 || ++ cold->vfl_source.page != sftl->geo->lanes + 1 || + cold->vfl_source.age >= sftl->vfl_source.age || + memcmp(cold->vfl_source.members, sftl->vfl_source.members, sizeof(sftl->vfl_source.members)) || + memcmp(cold->lanes, sftl->lanes, sizeof(sftl->lanes)) || +@@ -788,7 +838,7 @@ static int sftl_context_names(struct apple_sftl *sftl, const u8 *payload, + for (i = 0; i < names; i++) { + u32 name = get_unaligned_le32(payload + 4 + i * 4); + +- if (!name || name >= SFTL_SUBBLOCKS) ++ if (!name || name >= sftl->geo->subblocks) + return -EBADMSG; + if (test_bit(name, sftl->reserved)) + continue; +@@ -814,13 +864,13 @@ 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) + { +- u32 value = get_unaligned_le32(payload + 4), offset; ++ u32 value = get_unaligned_le32(payload + 4), offset, lpages = sftl->geo->lpages; + + if (value == U32_MAX) +- return *cursor == SFTL_LPAGES && get_unaligned_le32(payload) == U32_MAX ? ++ return *cursor == lpages && get_unaligned_le32(payload) == U32_MAX ? + 0 : -EBADMSG; + if (value != 0xfffffff0 || get_unaligned_le32(payload) != *cursor || +- *cursor == SFTL_LPAGES) ++ *cursor == lpages) + return -EBADMSG; + + for (offset = 8; offset < SFTL_CHUNK; offset += 8) { +@@ -830,9 +880,9 @@ static int sftl_load_ranges(struct apple_sftl *sftl, const u8 *payload, u32 *cur + value = get_unaligned_le32(payload + offset); + if (value == U32_MAX) + break; +- if (!length || length > SFTL_LPAGES - *cursor) ++ if (!length || length > lpages - *cursor) + return -EBADMSG; +- if (value == BIT(fls(SFTL_PROVIDER * 2 - 1) - 1) - 1) ++ if (value == BIT(fls(sftl_provider(sftl) * 2 - 1) - 1) - 1) + value = SFTL_UNMAPPED; + ret = sftl_add_run(sftl, *cursor, *cursor + length, value); + if (ret) +@@ -842,7 +892,7 @@ static int sftl_load_ranges(struct apple_sftl *sftl, const u8 *payload, u32 *cur + /* A save interrupted between programs can end only after complete + * 511-pair fragments until the whole logical address space is covered. + */ +- if (offset != SFTL_CHUNK && *cursor < SFTL_LPAGES) ++ if (offset != SFTL_CHUNK && *cursor < lpages) + *short_range = true; + return offset == 8 ? -EBADMSG : 0; + } +@@ -881,7 +931,8 @@ static int sftl_load_block_roles(struct apple_sftl *sftl, const u8 *meta, const + static int sftl_decode_generation(struct apple_sftl *sftl, const struct sftl_records *records, + u32 first, u32 end, unsigned long *named) + { +- u32 cursor = 0, map_records = 0, i, previous_order = 0; ++ u32 cursor = 0, map_records = 0, i, previous_order = 0, stride = sftl_stride(sftl); ++ u32 subblocks = sftl->geo->subblocks; + u64 first_sequence = records->items[first].stamp & SFTL_SEQUENCE; + bool base_tags = true, at_base = false, native = false, short_range = false; + +@@ -908,29 +959,29 @@ static int sftl_decode_generation(struct apple_sftl *sftl, const struct sftl_rec + + if (subtype != 1 || !names || names > SFTL_MAX_CONTEXTS) + return -EBADMSG; +- at_base = !(record->address % SFTL_STRIDE) && +- get_unaligned_le32(payload + 4) == record->address / SFTL_STRIDE; ++ at_base = !(record->address % stride) && ++ get_unaligned_le32(payload + 4) == record->address / stride; + for (k = 0; k < names; k++) { + u32 block = get_unaligned_le32(payload + 4 + k * 4); + +- if (!block || block >= SFTL_SUBBLOCKS || ++ if (!block || block >= subblocks || + !test_bit(block, sftl->reserved) || test_bit(block, named)) + return -EBADMSG; + __set_bit(block, named); + } + } +- if (!test_bit(record->address / SFTL_STRIDE, named)) ++ if (!test_bit(record->address / stride, named)) + return -EBADMSG; + if (index < 4 && subtype == 1) { +- base_tags &= apple_sftl_native_context_tag(index, meta); ++ base_tags &= apple_sftl_native_context_tag_for(subblocks, index, meta); + if (index == 3) { + if (!at_base || !base_tags || +- get_unaligned_le32(payload + SFTL_CHUNK - 4) != SFTL_SUBBLOCKS) ++ get_unaligned_le32(payload + SFTL_CHUNK - 4) != subblocks) + return -EBADMSG; + native = true; + } + } +- if (native && !apple_sftl_native_context_tag(index, meta)) ++ if (native && !apple_sftl_native_context_tag_for(subblocks, index, meta)) + return -EBADMSG; + if (native && subtype == 3) { + ret = sftl_load_block_roles(sftl, meta, payload, true); +@@ -948,8 +999,8 @@ static int sftl_decode_generation(struct apple_sftl *sftl, const struct sftl_rec + /* cxtNextBatch pads the measured native map in groups of 64. Coverage + * alone can become complete many pages before the final batch does. + */ +- if (cursor != SFTL_LPAGES || !map_records || +- (native && map_records % APPLE_SFTL_NATIVE_MAP_BATCH)) { ++ if (cursor != sftl->geo->lpages || !map_records || ++ (native && map_records % sftl->geo->map_batch)) { + if (short_range) + return -EBADMSG; + /* A partial program or a native aggregate that lost its tail does +@@ -976,10 +1027,10 @@ static int sftl_check_context_remnant(struct apple_sftl *sftl, u32 block, u64 se + + if (!streams) + return -EBADMSG; +- for (pos = 0; pos < streams * 128; pos++) { ++ for (pos = 0; pos < streams * sftl->geo->pages; pos++) { + u16 lane = BIT(pos % streams); + unsigned int chunk; +- int ret = sftl_read_address(sftl, block * SFTL_STRIDE + pos * 4, &chunk); ++ int ret = sftl_read_address(sftl, block * sftl_stride(sftl) + pos * 4, &chunk); + + if (ret) { + if (ret == -EBADMSG) +@@ -1001,14 +1052,15 @@ static int sftl_check_context_remnant(struct apple_sftl *sftl, u32 block, u64 se + if (!pos && (!get_unaligned_le32(sftl->page) || + get_unaligned_le32(sftl->page) > SFTL_MAX_CONTEXTS || + get_unaligned_le32(sftl->page + 4) != block || +- get_unaligned_le32(sftl->page + APPLE_PPN_PAGE_SIZE - 4) != SFTL_SUBBLOCKS)) ++ get_unaligned_le32(sftl->page + APPLE_PPN_PAGE_SIZE - 4) != sftl->geo->subblocks)) + return -EBADMSG; + for (j = 0; j < 4; j++) { + const u8 *meta = sftl->oob + SFTL_META * j; + u32 offset = 4 * pos + j; + u64 sequence = sftl_sequence(meta); + +- if (!apple_sftl_native_context_tag(offset, meta) || sequence <= offset || ++ if (!apple_sftl_native_context_tag_for(sftl->geo->subblocks, offset, meta) || ++ sequence <= offset || + sequence >= selected || (base && sequence - offset != base)) + return -EBADMSG; + base = sequence - offset; +@@ -1024,13 +1076,14 @@ static void sftl_mark_mapped(struct apple_sftl *sftl, unsigned long *blocks); + static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_records *journal) + { + struct sftl_records records = {}; +- DECLARE_BITMAP(gapped, SFTL_SUBBLOCKS) = {}; +- DECLARE_BITMAP(named, SFTL_SUBBLOCKS); ++ DECLARE_BITMAP(gapped, SFTL_MAX_SUBBLOCKS) = {}; ++ DECLARE_BITMAP(named, SFTL_MAX_SUBBLOCKS); + u16 pending[SFTL_MAX_CONTEXTS]; + u32 count = 0, block, at, i, first = 0, end, chunk, oldest; ++ u32 stride = sftl_stride(sftl), subblocks = sftl->geo->subblocks; + int ret = -EBADMSG; + +- for (block = 1; block < SFTL_SUBBLOCKS; block++) { ++ for (block = 1; block < subblocks; block++) { + if (heads[block * SFTL_META] != 0x1f) + continue; + if (count == SFTL_MAX_CONTEXTS) +@@ -1045,7 +1098,7 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + + block = pending[at]; + lanes = hweight16(sftl->lanes[block]); +- pages = lanes * 128; ++ pages = lanes * sftl->geo->pages; + if (!pages) { + ret = -EBADMSG; + goto out; +@@ -1054,7 +1107,7 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + u16 lane = BIT(position % lanes); + bool empty = false; + +- ret = sftl_read_address(sftl, block * SFTL_STRIDE + position * 4, &chunk); ++ ret = sftl_read_address(sftl, block * stride + position * 4, &chunk); + if (ret) + goto out; + if (sftl_erased(sftl->oob, sizeof(sftl->oob))) { +@@ -1094,7 +1147,7 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + goto out; + } + ret = sftl_record_add(&records, sftl_stamp(meta), 0, +- block * SFTL_STRIDE + position * 4 + chunk); ++ block * stride + position * 4 + chunk); + if (ret) + goto out; + } +@@ -1116,7 +1169,7 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + + if (sftl_flags(r) == 1 && !(r->address & 3)) + break; +- if (!test_bit(r->address / SFTL_STRIDE, gapped)) ++ if (!test_bit(r->address / stride, gapped)) + goto out; + } + if (oldest == records.count) +@@ -1149,7 +1202,7 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + u32 checked = 0; + u64 selected = records.items[first].stamp & SFTL_SEQUENCE; + +- for (block = 0; block < SFTL_SUBBLOCKS; block++) { ++ for (block = 0; block < subblocks; block++) { + if (sftl->roles[block] != SFTL_CONTEXT) + continue; + if (test_bit(block, sftl->checkpoint_used) || test_bit(block, sftl->vfl_reserved)) { +@@ -1172,7 +1225,7 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + } + } + for (i = 0; i < records.count; i++) { +- block = records.items[i].address / SFTL_STRIDE; ++ block = records.items[i].address / stride; + if (test_bit(block, gapped)) { + if (i >= first || (sftl->native_context ? + sftl->roles[block] != SFTL_CONTEXT : !test_bit(block, named))) { +@@ -1201,8 +1254,8 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + goto out; + } + start = get_unaligned_le16(meta + 8); +- if (start < SFTL_SUBBLOCKS && !(start % (SFTL_CHUNK / 8)) && +- apple_sftl_native_context_tag(8 + start / (SFTL_CHUNK / 8), meta)) ++ if (start < subblocks && !(start % (SFTL_CHUNK / 8)) && ++ apple_sftl_native_context_tag_for(subblocks, 8 + start / (SFTL_CHUNK / 8), meta)) + sftl_load_block_roles(sftl, meta, sftl->page + chunk * SFTL_CHUNK, false); + } + /* Retain the selected generation's opaque records for later snapshots. */ +@@ -1235,25 +1288,25 @@ static int sftl_context(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + return ret; + } + +-static bool sftl_user_epoch_valid(const u8 *meta, u64 sequence) ++static bool sftl_user_epoch_valid(const struct apple_sftl *sftl, const u8 *meta, u64 sequence) + { + u32 user_epoch = get_unaligned_le32(meta + 12); + + /* Relocation restamps the weave sequence and retains the original user epoch. */ +- if (meta[0] == 1 && !meta[1] && get_unaligned_le32(meta + 8) < SFTL_LPAGES) ++ if (meta[0] == 1 && !meta[1] && get_unaligned_le32(meta + 8) < sftl->geo->lpages) + return user_epoch <= sequence >> 16; + return user_epoch == sequence >> 16; + } + +-static int sftl_add_journal(struct sftl_records *journal, const u8 *meta, +- u32 address, u64 checkpoint) ++static int sftl_add_journal(const struct apple_sftl *sftl, struct sftl_records *journal, ++ const u8 *meta, u32 address, u64 checkpoint) + { + u64 sequence = sftl_sequence(meta); + + if (sequence <= checkpoint || sftl_erased(meta, SFTL_META)) + return 0; + if ((meta[0] != 1 && meta[0] != 2) || +- !sftl_user_epoch_valid(meta, sequence) || ++ !sftl_user_epoch_valid(sftl, meta, sequence) || + (meta[0] == 1 ? meta[1] > 1 : meta[1] != 0)) + return -EBADMSG; + return sftl_record_add(journal, sftl_stamp(meta), get_unaligned_le32(meta + 8), address); +@@ -1266,7 +1319,7 @@ static int sftl_remember_user_seq(struct apple_sftl *sftl, u32 block, const u8 * + sftl_flags(&sftl->context.items[3]) != 1) + return 0; + if (!sftl->closed_user_seq) { +- sftl->closed_user_seq = kvzalloc(SFTL_SUBBLOCKS * sizeof(*sftl->closed_user_seq), ++ sftl->closed_user_seq = kvzalloc(SFTL_MAX_SUBBLOCKS * sizeof(*sftl->closed_user_seq), + GFP_NOIO); + if (!sftl->closed_user_seq) + return -ENOMEM; +@@ -1304,7 +1357,7 @@ static int sftl_footer(struct apple_sftl *sftl, const u8 *head, u32 block, + if (!footer) + return -ENOMEM; + for (index = 0; index < chunks / 4; index++) { +- ret = sftl_read_address(sftl, block * SFTL_STRIDE + ++ ret = sftl_read_address(sftl, block * sftl_stride(sftl) + + (pages - chunks / 4 + index) * 4, &chunk); + if (ret) + goto out; +@@ -1334,7 +1387,7 @@ static int sftl_footer(struct apple_sftl *sftl, const u8 *head, u32 block, + for (offset = 0; offset < length; offset++, position++) { + u64 sequence = base + relative + offset; + u32 actual_key = key >= 0xffff0000 ? key : key + offset; +- u32 address = block * SFTL_STRIDE + position; ++ u32 address = block * sftl_stride(sftl) + position; + u8 meta[16]; + + if (sequence <= sftl->checkpoint_sequence) +@@ -1358,12 +1411,12 @@ static int sftl_footer(struct apple_sftl *sftl, const u8 *head, u32 block, + meta[1] = head[1]; + put_unaligned_le64(sequence << 16 | get_unaligned_le16(meta), meta); + put_unaligned_le32(actual_key, meta + 8); +- if (!meta[1] && actual_key < SFTL_LPAGES) ++ if (!meta[1] && actual_key < sftl->geo->lpages) + memcpy(meta + 12, footer + index + 4, sizeof(u32)); + else + put_unaligned_le32(sequence >> 16, meta + 12); + } +- ret = sftl_add_journal(journal, meta, address, sftl->checkpoint_sequence); ++ ret = sftl_add_journal(sftl, journal, meta, address, sftl->checkpoint_sequence); + if (ret) + goto out; + } +@@ -1428,19 +1481,19 @@ static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + { + u64 floor = sftl->checkpoint_sequence, expected = floor + 1; + u32 nr_context = journal->count; +- u32 block, position, i, pages; ++ u32 block, position, i, pages, stride = sftl_stride(sftl); + unsigned int chunk; + int ret; + +- for (block = 1; block < SFTL_SUBBLOCKS; block++) { ++ for (block = 1; block < sftl->geo->subblocks; block++) { + const u8 *head = heads + block * SFTL_META; + bool complete_prefix = true, partial_footer = false; + u64 base = sftl_sequence(head), next = base; + + if (head[0] != 1 && head[0] != 2) + continue; +- pages = hweight16(sftl->lanes[block]) * 128; +- ret = sftl_read_address(sftl, block * SFTL_STRIDE + (pages - 1) * 4, &chunk); ++ pages = hweight16(sftl->lanes[block]) * sftl->geo->pages; ++ ret = sftl_read_address(sftl, block * stride + (pages - 1) * 4, &chunk); + if (ret) + goto out; + if (sftl->oob[0] == 0x1c) { +@@ -1455,7 +1508,7 @@ static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + goto out; + } + for (position = 0; position < pages; position++) { +- ret = sftl_read_address(sftl, block * SFTL_STRIDE + position * 4, &chunk); ++ ret = sftl_read_address(sftl, block * stride + position * 4, &chunk); + if (ret) + goto out; + if (sftl_erased(sftl->oob, sizeof(sftl->oob)) && +@@ -1469,7 +1522,7 @@ static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + u64 sequence = sftl_sequence(meta); + + if (meta[0] != 1 || meta[1] || sequence < next || +- !sftl_user_epoch_valid(meta, sequence)) ++ !sftl_user_epoch_valid(sftl, meta, sequence)) + complete_prefix = false; + /* A checkpoint occupies its own sequence numbers between pages. */ + if (complete_prefix && sequence > next && +@@ -1498,8 +1551,8 @@ static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + goto out; + } + for (chunk = 0; chunk < 4; chunk++) { +- ret = sftl_add_journal(journal, sftl->oob + chunk * SFTL_META, +- block * SFTL_STRIDE + position * 4 + chunk, ++ ret = sftl_add_journal(sftl, journal, sftl->oob + chunk * SFTL_META, ++ block * stride + position * 4 + chunk, + sftl->checkpoint_sequence); + if (ret) + goto out; +@@ -1566,8 +1619,8 @@ static void sftl_mark_mapped(struct apple_sftl *sftl, unsigned long *blocks) + + if (run->provider == SFTL_UNMAPPED) + continue; +- end = (run->provider + run->end - run->start - 1) / SFTL_STRIDE; +- for (block = run->provider / SFTL_STRIDE; block <= end; block++) ++ end = (run->provider + run->end - run->start - 1) / sftl_stride(sftl); ++ for (block = run->provider / sftl_stride(sftl); block <= end; block++) + __set_bit(block, blocks); + } + } +@@ -1575,6 +1628,7 @@ static void sftl_mark_mapped(struct apple_sftl *sftl, unsigned long *blocks) + int apple_sftl_load(struct apple_ppn *provider, struct apple_sftl **out) + { + struct apple_sftl *sftl; ++ const struct sftl_geometry *geo = NULL; + struct sftl_records journal = {}; + u8 *heads; + u32 block; +@@ -1584,33 +1638,41 @@ int apple_sftl_load(struct apple_ppn *provider, struct apple_sftl **out) + if (!out) + return -EINVAL; + *out = NULL; +- if (!provider || !provider->ops || !provider->ops->read_page || +- provider->buses != 2 || provider->caus != 8 || +- provider->blocks != SFTL_BLOCKS || provider->pages != 128) ++ if (!provider || !provider->ops || !provider->ops->read_page) ++ return -EOPNOTSUPP; ++ for (block = 0; block < ARRAY_SIZE(sftl_geometries); block++) { ++ const struct sftl_geometry *g = sftl_geometries[block]; ++ ++ if (provider->buses == g->buses && provider->caus == g->caus && ++ provider->blocks == g->blocks && provider->pages == g->pages) ++ geo = g; ++ } ++ if (!geo) + return -EOPNOTSUPP; + sftl = kzalloc(sizeof(*sftl), GFP_KERNEL); + if (!sftl) + return -ENOMEM; + sftl->ppn = provider; ++ sftl->geo = geo; + sftl->runs = RB_ROOT; + sftl->append_block = U32_MAX; + sftl->next_candidate = 1; + sftl->spare = U32_MAX; + mutex_init(&sftl->lock); + sftl->page = kmalloc(APPLE_PPN_PAGE_SIZE, GFP_KERNEL); +- heads = kcalloc(SFTL_BLOCKS, SFTL_META, GFP_KERNEL); ++ heads = kcalloc(geo->blocks, SFTL_META, GFP_KERNEL); + if (!sftl->page || !heads) { + ret = -ENOMEM; + goto failed; + } +- memset(heads, 0xff, SFTL_BLOCKS * SFTL_META); ++ memset(heads, 0xff, geo->blocks * SFTL_META); + ret = sftl_vfl(sftl); + if (ret) + goto failed; +- for (block = 1; block < SFTL_SUBBLOCKS; block++) { ++ for (block = 1; block < geo->subblocks; block++) { + if (!sftl->lanes[block]) + continue; +- ret = sftl_read_address(sftl, block * SFTL_STRIDE, &chunk); ++ ret = sftl_read_address(sftl, block * sftl_stride(sftl), &chunk); + if (ret) + goto failed; + if (sftl_erased(sftl->oob, sizeof(sftl->oob))) { +@@ -1666,7 +1728,7 @@ int apple_sftl_read(struct apple_sftl *sftl, u32 logical_page, u8 *data) + const u8 *meta; + int ret = 0; + +- if (!sftl || !data || logical_page >= SFTL_LPAGES) ++ if (!sftl || !data || logical_page >= sftl->geo->lpages) + return -EINVAL; + mutex_lock(&sftl->lock); + if (sftl->failed) { +@@ -1706,7 +1768,7 @@ static int sftl_writer_prepare(struct apple_sftl *sftl) + { + u32 block; + +- if (sftl->vfl_degraded || sftl->context_degraded) ++ if (sftl->vfl_degraded || sftl->context_degraded || !sftl->geo->writer) + return -EROFS; + if (sftl->writer_prepared) + return 0; +@@ -1717,12 +1779,11 @@ static int sftl_writer_prepare(struct apple_sftl *sftl) + sftl->footer = kvzalloc(SFTL_FOOTER_BYTES, GFP_KERNEL); + if (!sftl->footer) + return -ENOMEM; +- for (block = 0; block < SFTL_BLOCKS; block++) +- if (test_bit(block, sftl->reserved) || test_bit(block, sftl->vfl_reserved)) ++ 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); +- __set_bit(SFTL_SUBBLOCKS, sftl->used); +- __set_bit(SFTL_SUBBLOCKS + 1, sftl->used); + sftl_mark_mapped(sftl, sftl->used); + sftl->writer_prepared = true; + return 0; +@@ -1755,7 +1816,7 @@ static void sftl_copy_map(struct apple_sftl *sftl, struct apple_sftl_snapshot *s + static int sftl_verify_closed(struct apple_sftl *sftl, struct apple_sftl_gc_block *victim, + unsigned long deadline, bool relocate) + { +- u32 first = victim->block * SFTL_STRIDE, capacity = hweight16(victim->lanes) * 512; ++ 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]; +@@ -1800,7 +1861,7 @@ static int sftl_verify_closed(struct apple_sftl *sftl, struct apple_sftl_gc_bloc + if ((!position && relative) || relative < previous_end || relative >= span || + length > span - relative || length > capacity - chunks - position) + return -EBADMSG; +- if (key >= SFTL_LPAGES || length > SFTL_LPAGES - key) ++ if (key >= sftl->geo->lpages || length > sftl->geo->lpages - key) + return -EOPNOTSUPP; + for (j = 0; j < length; j++, position++) { + u64 seq = base + relative + j; +@@ -1819,7 +1880,7 @@ 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(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 +@@ -1836,7 +1897,7 @@ static int sftl_verify_closed(struct apple_sftl *sftl, struct apple_sftl_gc_bloc + static int sftl_block_blank(struct apple_sftl *sftl, u32 block, unsigned long deadline, + bool *blank) + { +- u32 capacity = hweight16(sftl->lanes[block]) * 512, pos; ++ u32 capacity = sftl_slots(sftl, sftl->lanes[block]), pos; + unsigned int chunk; + int ret; + +@@ -1844,7 +1905,7 @@ static int sftl_block_blank(struct apple_sftl *sftl, u32 block, unsigned long de + for (pos = 0; pos < capacity; pos += 4) { + if (time_after_eq(jiffies, deadline)) + return -ETIMEDOUT; +- ret = sftl_read_address(sftl, block * SFTL_STRIDE + pos, &chunk); ++ ret = sftl_read_address(sftl, block * sftl_stride(sftl) + pos, &chunk); + if (ret) + return ret; + if (!sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE) || +@@ -1877,7 +1938,7 @@ static int sftl_erase_verified(struct apple_sftl *sftl, u32 block, unsigned long + bool blank; + int ret; + +- for (lane = 0; lane < SFTL_LANES; lane++) { ++ for (lane = 0; lane < sftl->geo->lanes; lane++) { + if (!(sftl->lanes[block] & BIT(lane))) + continue; + if (time_after_eq(jiffies, deadline)) +@@ -1903,8 +1964,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 32 physical blocks can contain native bootstrap members. */ +- for (block = 1; block < SFTL_BLOCKS - 32; block++) { ++ /* The top physical blocks can contain native bootstrap members. */ ++ for (block = 1; block < sftl->geo->vfl_first; block++) { + struct apple_sftl_gc_block victim = { + .block = block, .lanes = sftl->lanes[block], .closed = true, + }; +@@ -1979,7 +2040,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_BLOCKS - 32 && ++ return !sftl->native_context || (block < sftl->geo->vfl_first && + !test_bit(block, sftl->unknown_lane_flags)); + } + +@@ -1991,7 +2052,7 @@ static int sftl_check_landing(struct apple_sftl *sftl, u32 block, unsigned long + /* A cached spare was either positively free or was erased and checked + * in this transaction after verifying an ordinary closed donor. + */ +- if (!block || block >= SFTL_SUBBLOCKS || !sftl->lanes[block] || ++ if (!block || block >= sftl->geo->subblocks || !sftl->lanes[block] || + !sftl_native_data_site(sftl, block) || + (sftl->native_context && sftl->roles[block] != SFTL_CLEAN_FREE && + sftl->roles[block] != SFTL_CLOSED_DATA && sftl->roles[block] != SFTL_DIRTY_FREE) || +@@ -2008,7 +2069,7 @@ static int sftl_take_blank(struct apple_sftl *sftl, u32 *out, unsigned long dead + bool blank; + int ret; + +- while (sftl->next_candidate < SFTL_SUBBLOCKS) { ++ while (sftl->next_candidate < sftl->geo->subblocks) { + block = sftl->next_candidate++; + if (!test_bit(block, sftl->candidates) || test_bit(block, sftl->used) || + !sftl_native_data_site(sftl, block) || +@@ -2034,7 +2095,7 @@ static int sftl_take_blank(struct apple_sftl *sftl, u32 *out, unsigned long dead + static void sftl_open_block(struct apple_sftl *sftl, u32 block) + { + sftl->append_block = block; +- sftl->append_capacity = hweight16(sftl->lanes[block]) * 512 - SFTL_FOOTER_CHUNKS; ++ 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; +@@ -2123,7 +2184,7 @@ static int sftl_move_program(void *priv, u32 address, const struct apple_sftl_gc + + if (time_after_eq(jiffies, move->deadline)) + return -ETIMEDOUT; +- if (address != sftl->append_block * SFTL_STRIDE + sftl->append_position || ++ if (address != sftl->append_block * sftl_stride(sftl) + sftl->append_position || + sftl->append_position + 4 > sftl->append_capacity) + return -ERANGE; + ret = sftl_program_address(sftl, address, page->data, page->oob); +@@ -2176,7 +2237,7 @@ static void sftl_adopt_checkpoint(struct apple_sftl *sftl, struct apple_sftl *co + memcpy(sftl->checkpoint_used, cold->checkpoint_used, sizeof(sftl->checkpoint_used)); + memcpy(sftl->old_closed, cold->old_closed, sizeof(sftl->old_closed)); + memcpy(sftl->unknown_lane_flags, cold->unknown_lane_flags, sizeof(sftl->unknown_lane_flags)); +- for (block = 0; block < SFTL_BLOCKS; block++) ++ for (block = 0; block < sftl->geo->blocks; block++) + if (test_bit(block, sftl->reserved) || test_bit(block, sftl->vfl_reserved) || + test_bit(block, sftl->checkpoint_used)) + __set_bit(block, sftl->used); +@@ -2188,7 +2249,7 @@ 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_BLOCKS - 32 && sftl->lanes[block] && ++ block && block < sftl->geo->vfl_first && 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); + } +@@ -2209,7 +2270,7 @@ static int sftl_native_sites(struct apple_sftl *sftl, const struct apple_sftl_sn + 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]) || +- sftl->context.items[0].address != prior[0] * SFTL_STRIDE) ++ sftl->context.items[0].address != prior[0] * sftl_stride(sftl)) + return -EOPNOTSUPP; + for (i = 0; i < saved->nr_runs; i++) { + const struct apple_sftl_extent *r = &saved->runs[i]; +@@ -2217,20 +2278,20 @@ 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; ++ end = (r->provider + r->length - 1) / sftl_stride(sftl); + for (j = 0; j < 2; j++) +- if ((r->provider / SFTL_STRIDE <= fresh[j] && fresh[j] <= end) || +- (r->provider / SFTL_STRIDE <= prior[j] && prior[j] <= end)) ++ 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; +- slots = hweight16(sftl->lanes[prior[0]]) * 512; ++ slots = sftl_slots(sftl, sftl->lanes[prior[0]]); + if (!length || length % 4 || length > slots) + return -EOPNOTSUPP; + for (i = 0; i < slots; i += 4) { + if (time_after_eq(jiffies, deadline)) + return -ETIMEDOUT; +- ret = sftl_read_address(sftl, prior[0] * SFTL_STRIDE + i, &chunk); ++ ret = sftl_read_address(sftl, prior[0] * sftl_stride(sftl) + i, &chunk); + if (ret) + return ret; + if (i >= length) { +@@ -2321,7 +2382,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_BLOCKS - 32; block++) { ++ for (block = 1; block < sftl->geo->vfl_first; block++) { + struct apple_sftl_gc_block victim = { + .block = block, .lanes = sftl->lanes[block], .closed = true, + }; +@@ -2341,7 +2402,8 @@ static int sftl_compact(struct apple_sftl *sftl, u32 landing, unsigned long dead + } + if (ret) + goto out; +- ret = apple_sftl_gc_plan(before, &victim, &destination, SFTL_MAX_CONTEXTS * SFTL_STRIDE, ++ ret = apple_sftl_gc_plan(before, &victim, &destination, ++ SFTL_MAX_CONTEXTS * sftl_stride(sftl), + SFTL_GC_MAP_BYTES, &gc); + if (ret == -ENOSPC || ret == -EOVERFLOW) { + ret = -ENOSPC; +@@ -2352,8 +2414,8 @@ 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 > hweight16(destination.lanes) * 512 - SFTL_FOOTER_CHUNKS || +- slots >= hweight16(victim.lanes) * 512 - SFTL_FOOTER_CHUNKS) { ++ slots + 4 > sftl_slots(sftl, destination.lanes) - SFTL_FOOTER_CHUNKS || ++ slots >= sftl_slots(sftl, victim.lanes) - SFTL_FOOTER_CHUNKS) { + apple_sftl_gc_free(gc); + gc = NULL; + ret = -ENOSPC; +@@ -2365,7 +2427,8 @@ static int sftl_compact(struct apple_sftl *sftl, u32 landing, unsigned long dead + ret = sftl_native_sites(sftl, before, blocks, &retiring, deadline); + if (!ret) + ret = apple_sftl_gc_prepare_native(gc, sftl->checkpoint_ops->prepare_native, +- sftl->checkpoint_priv, blocks, hweight16(sftl->lanes[blocks[0]]) * 512); ++ sftl->checkpoint_priv, blocks, ++ sftl_slots(sftl, sftl->lanes[blocks[0]])); + } else { + ret = sftl->checkpoint_ops->reserve(sftl->checkpoint_priv, blocks, &nr); + } +@@ -2378,7 +2441,7 @@ static int sftl_compact(struct apple_sftl *sftl, u32 landing, unsigned long dead + for (i = 0; i < nr; i++) { + u32 k; + +- if (!blocks[i] || blocks[i] >= SFTL_SUBBLOCKS || blocks[i] == block || ++ if (!blocks[i] || blocks[i] >= sftl->geo->subblocks || blocks[i] == block || + blocks[i] == landing || (!fresh && !test_bit(blocks[i], sftl->reserved))) { + ret = -EINVAL; + goto out; +@@ -2433,7 +2496,7 @@ static int sftl_compact(struct apple_sftl *sftl, u32 landing, unsigned long dead + */ + 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 || ++ 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])) { +@@ -2499,7 +2562,7 @@ 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_BLOCKS - 32; block++) ++ for (block = 1; block < sftl->geo->vfl_first; block++) + if (sftl_closed_candidate(sftl, block) && test_bit(block, sftl->checkpoint_used)) + return true; + return false; +@@ -2586,7 +2649,7 @@ static int sftl_claim_block(struct apple_sftl *sftl) + for (i = 0; i < count; i++) { + u32 b = fresh[i]; + +- if (!b || b >= SFTL_BLOCKS - 32 || !sftl->lanes[b] || ++ if (!b || b >= sftl->geo->vfl_first || !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) || +@@ -2644,7 +2707,7 @@ static int sftl_close_block(struct apple_sftl *sftl) + for (chunk = 0; chunk < 4; chunk++) + memcpy(sftl->oob + chunk * SFTL_META, meta, SFTL_META); + for (index = 0; index < SFTL_FOOTER_CHUNKS / 4; index++) { +- u32 address = sftl->append_block * SFTL_STRIDE + ++ u32 address = sftl->append_block * sftl_stride(sftl) + + sftl->append_capacity + index * 4; + + ret = sftl_program_address(sftl, address, +@@ -2668,8 +2731,8 @@ int apple_sftl_write(struct apple_sftl *sftl, u32 logical_page, + unsigned int chunk; + int ret; + +- if (!sftl || !data || !count || count > 4 || logical_page >= SFTL_DISK_PAGES || +- count > SFTL_DISK_PAGES - logical_page) ++ 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); + if (sftl->failed) { +@@ -2692,7 +2755,7 @@ int apple_sftl_write(struct apple_sftl *sftl, u32 logical_page, + ret = -EOVERFLOW; + goto out; + } +- address = sftl->append_block * SFTL_STRIDE + sftl->append_position; ++ address = sftl->append_block * sftl_stride(sftl) + sftl->append_position; + first_sequence = sftl->sequence + 1; + for (chunk = 0; chunk < 4; chunk++) { + unsigned int index = min(chunk, count - 1); +@@ -2746,9 +2809,9 @@ 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; +- info->logical_pages = SFTL_LPAGES; +- info->disk_pages = SFTL_DISK_PAGES; ++ info->read_only = sftl->vfl_degraded || sftl->context_degraded || !sftl->geo->writer; ++ info->logical_pages = sftl->geo->lpages; ++ info->disk_pages = sftl->geo->disk_pages; + info->nr_runs = sftl->nr_runs; + info->checkpoint_sequence = sftl->checkpoint_sequence; + info->sequence = sftl->sequence; +@@ -2832,6 +2895,11 @@ 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) { ++ *out = NULL; ++ return -EOPNOTSUPP; ++ } + mutex_lock(&sftl->lock); + ret = sftl_snapshot_locked(sftl, max_bytes, out); + mutex_unlock(&sftl->lock); diff --git a/kernel/patches/armv7/mtd/0018-mtd-apple-sftl-Read-the-16-GB-PPN-layout.patch b/kernel/patches/armv7/mtd/0018-mtd-apple-sftl-Read-the-16-GB-PPN-layout.patch new file mode 100644 index 00000000..dc5d9bbc --- /dev/null +++ b/kernel/patches/armv7/mtd/0018-mtd-apple-sftl-Read-the-16-GB-PPN-layout.patch @@ -0,0 +1,685 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: rzxvx +Date: Fri, 20 Nov 2026 06:00:28 +0800 +Subject: [PATCH 18/18] mtd: apple-sftl: Read the 16 GB PPN layout + +The iPad mini 1 ships with a 16 GB or a 64 GB Hynix PPN package. The +translation layer only registers on the 64 GB one. Add the 16 GB layout +as Cascadia measured it on a 16 GB P105 with 12H321 (iOS 8.4.1): + +- two CAUs per bus, 1064 blocks of 256 pages; the FTL sees four banks in + the order (bus 0, cau 0), (bus 1, cau 0), (bus 0, cau 1), (bus 1, cau 1), + which is the provider's lane order; +- 1055 superblocks of 4096 slots, striped dense over the banks a VFL + table lists for each superblock; +- the VFL in blocks 1062 and 1063 of every bank, 128 SLC pages each; the + older bank can be erased, so page zero of either block can seed the + member list; +- 3906250 exported and 16 hidden logical pages, the 1055-entry block, + user sequence and read count sections of a native context; +- at least 32 range records in multiples of 16, as iOS writes the tree; +- summaries of 4 or 8 chunks, whose span can include the summary's own + chunks ("+nb"): those sequences are accounted to the summary so the + journal stays contiguous. + +Padding records (key 0xffff0000) map nothing on either layout. + +H2FMI registers the provider for both profiles. The 16 GB disk is +read-only: Cascadia's writer, checkpoint and reclamation for this layout +are not ported here. + +Add a synthetic 16 GB medium to the KUnit tests: a VFL in either bank, a +native 56-record context, a closed block from before the checkpoint and a +closed block after it on three banks with a padded run and a summary that +counts its own chunks. + +Ported from Cascadia (https://github.com/rzxvx/Project-Cascadia) commits +0feb4a7 ("a5: PPN NAND driver and Swiss FTL, written from the spec"), +6a67fe8 ("a5: FTL: read a context tree of any length"), 3f09b61 ("a5: +NAND: context tree length as iOS writes it; replay log of 64; rung 9 +notes") and b1d85d7 ("a5: NAND spec: ladder results, long context trees, +page transmit"), files sftl.h and sftl_mount.c and +devices/a5/docs/research/p105-nand-spec.md sections 3 and 4, as of +Cascadia ad28ba4. Format findings on this package credit crystal-lized's +iPhone 5 work. + +Assisted-by: LLM +--- + Documentation/driver-api/mtd/apple-sftl.rst | 24 +- + drivers/mtd/Kconfig | 5 +- + drivers/mtd/apple-sftl-core.c | 108 ++++-- + drivers/mtd/apple-sftl-test.c | 353 ++++++++++++++++++++ + drivers/mtd/devices/mtd-apple-h2fmi.c | 7 +- + 5 files changed, 457 insertions(+), 40 deletions(-) + +diff --git a/Documentation/driver-api/mtd/apple-sftl.rst b/Documentation/driver-api/mtd/apple-sftl.rst +index d683385bd..9661f0bde 100644 +--- a/Documentation/driver-api/mtd/apple-sftl.rst ++++ b/Documentation/driver-api/mtd/apple-sftl.rst +@@ -11,9 +11,20 @@ address view. The controller serializes each complete transaction. + Supported format + ---------------- + +-This implementation supports the measured 64 GB Hynix PPN profile with two +-buses and eight CAUs per bus. Each CAU has 2,088 blocks of 128 pages. Profile +-selection uses discovered geometry. Other layouts return ``-EOPNOTSUPP``. ++This implementation supports two measured Hynix PPN profiles, each with two ++buses. The 64 GB package has eight CAUs per bus, each with 2,088 blocks of 128 ++pages, and carries 13G36 (iOS 9.3.5) storage. The 16 GB package has two CAUs ++per bus, each with 1,064 blocks of 256 pages, and carries 12H321 (iOS 8.4.1) ++storage; its lanes are ordered (bus 0, CAU 0), (bus 1, CAU 0), (bus 0, CAU 1), ++(bus 1, CAU 1). Profile selection uses discovered geometry. Other layouts ++return ``-EOPNOTSUPP``. The 16 GB profile is read-only: its writer, ++reclamation and checkpoint formats are not modelled. ++ ++The 16 GB profile seeds the VFL member list from page zero of block 1063 or, ++when that bank is erased, block 1062. Its contexts have 1,055 superblocks and ++at least 32 range records in multiples of 16. Its summaries are 4 or 8 chunks ++and can count their own chunks in the sequence span; replay accounts for ++those sequences. On both profiles, padding records map nothing. + + Recovery selects four agreeing VFL checkpoint copies and checks each + replicated lane table. A VFL superblock has an 8,192-unit address stride; +@@ -27,9 +38,10 @@ Open blocks are scanned completely because an interrupted stripe may leave an + erased lane before another completed lane. Summary allocation spans also + preserve the next sequence floor when it exceeds the last visible record. + +-The map has 15,625,016 entries, including sixteen internal keys. The block +-device exposes 15,625,000 entries, or 64,000,000,000 bytes, with 512-byte +-sector reads and optional read-modify-write sector updates. Linux's disk name ++The 64 GB map has 15,625,016 entries, including sixteen internal keys. The ++block device exposes 15,625,000 entries, or 64,000,000,000 bytes; on the 16 GB ++profile 3,906,266 and 3,906,250 entries, or 16,000,000,000 bytes. The disk has ++512-byte sector reads and optional read-modify-write sector updates. Linux's disk name + is ``applesftlN``. LwVM and filesystem interpretation happen above this + logical provider. Encrypted partition contents remain ciphertext. + +diff --git a/drivers/mtd/Kconfig b/drivers/mtd/Kconfig +index d1bba09ee..7bebb81ee 100644 +--- a/drivers/mtd/Kconfig ++++ b/drivers/mtd/Kconfig +@@ -211,8 +211,9 @@ config MTD_APPLE_SFTL + depends on BLOCK + help + Recover the logical block medium stored in Apple VFL/SwissPPNFTL +- metadata on the measured 64 GB Hynix PPN layout. The H2FMI driver +- supplies canonical page reads through its aggregate PPN provider. ++ metadata on the measured 64 GB and 16 GB Hynix PPN layouts. The ++ H2FMI driver supplies canonical page reads through its aggregate PPN ++ provider. The 16 GB layout is read-only. + Recovery can expose a complete older generation read-only after an + interrupted native save. Unsupported geometry, conflicting replicas + and unaccounted journal gaps stop recovery. +diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c +index a3a9918d0..9e0e5ed72 100644 +--- a/drivers/mtd/apple-sftl-core.c ++++ b/drivers/mtd/apple-sftl-core.c +@@ -1,6 +1,7 @@ + // SPDX-License-Identifier: GPL-2.0-only + /* +- * Apple VFL/SwissPPNFTL recovery and append for the measured 64 GB PPN layout. ++ * Apple VFL/SwissPPNFTL recovery for the measured 16 GB and 64 GB PPN layouts, ++ * and append for the 64 GB layout. + * + * Format and replay rules are ported from Orchard's P105 Python reference + * (ftl_map.py, ftl_load.py, ftl_log.py and ftl_append.py). It was checked +@@ -36,6 +37,7 @@ + #define SFTL_MAX_CONTEXTS 16U + #define SFTL_META 16U + #define SFTL_CHUNK 4096U ++#define SFTL_PAD 0xffff0000U + #define SFTL_TRIM 0xffff0001U + /* cxtSaveSB serializes the role in byte zero of each 8-byte block entry. */ + enum sftl_block_role { +@@ -64,23 +66,44 @@ struct sftl_geometry { + u16 subblocks; /* FTL superblocks, VFL header +12 and +14 */ + u16 vfl_pages; /* SLC pages in one VFL bank member */ + u16 vfl_first; /* lowest physical block of a VFL member */ +- u16 bootstrap; /* block whose page zero seeds the member list */ ++ 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 */ + 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 */ ++ bool summary_sequences; /* a summary may consume one sequence per chunk */ + }; + + /* 64 GB Hynix PPN with 13G36 (iOS 9.3.5) on the media. */ + static const struct sftl_geometry sftl_64gb = { + .buses = 2, .caus = 8, .lanes = 16, .blocks = 2088, .pages = 128, +- .subblocks = 2086, .vfl_pages = 64, .vfl_first = 2056, .bootstrap = 2087, ++ .subblocks = 2086, .vfl_pages = 64, .vfl_first = 2056, ++ .bootstrap = { 2087 }, .nr_bootstrap = 1, + .map_batch = APPLE_SFTL_NATIVE_MAP_BATCH, + .disk_pages = 15625000, .lpages = 15625016, .writer = true, + }; + ++/* ++ * 16 GB Hynix PPN with 12H321 (iOS 8.4.1) on the media, as Cascadia ++ * measured it: two CAUs per bus, 1064 blocks of 256 pages, banks in the ++ * order (bus 0, cau 0), (bus 1, cau 0), (bus 0, cau 1), (bus 1, cau 1), ++ * 1055 superblocks of 4096 slots, the VFL in blocks 1062 and 1063 of every ++ * bank, 3906250 exported and 16 hidden logical pages. A context has at ++ * least 32 range records, rounded up to a multiple of 16, and a summary of ++ * 4 or 8 chunks may count its own chunks in its sequence span. ++ */ ++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, ++ .disk_pages = 3906250, .lpages = 3906266, .summary_sequences = true, ++}; ++ + static const struct sftl_geometry *const sftl_geometries[] = { + &sftl_64gb, ++ &sftl_16gb, + }; + + struct sftl_run { +@@ -434,33 +457,40 @@ struct sftl_vfl_scan { + static int sftl_vfl_members(struct apple_sftl *sftl) + { + struct apple_sftl_vfl_member *members = sftl->vfl_source.members; +- unsigned int lane, i, j; ++ unsigned int lane = 0, i, j, seed; ++ u16 block = 0; + u8 status; + int ret; + + /* An interrupted erase can remove the usual lane-zero seed. Search only +- * page zero in the measured bootstrap block for a surviving member list. ++ * page zero in the measured bootstrap blocks for a surviving member list. ++ * Where both VFL banks are bootstrap blocks, the older one may be erased. + */ +- for (lane = 0; lane < sftl->geo->lanes; lane++) { +- ret = sftl->ppn->ops->read_page(sftl->ppn->priv, lane & 1, lane >> 1, +- sftl->geo->bootstrap, 0, true, sftl->page, +- sftl->oob, &status); +- if (ret) +- return ret; +- /* Some nonmembers report 45 at the bootstrap coordinate. Once +- * discovered, every actual member is reread with strict status. +- */ +- if (status == 0x45) +- continue; +- if (status != 0x40 && status != 0x49) +- return -EIO; +- if (status == 0x40 && get_unaligned_le32(sftl->oob) == 0x00ffff20) ++ for (seed = 0; seed < sftl->geo->nr_bootstrap; seed++) { ++ block = sftl->geo->bootstrap[seed]; ++ for (lane = 0; lane < sftl->geo->lanes; lane++) { ++ 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 ++ * discovered, every actual member is reread with strict status. ++ */ ++ if (status == 0x45) ++ continue; ++ if (status != 0x40 && status != 0x49) ++ return -EIO; ++ if (status == 0x40 && get_unaligned_le32(sftl->oob) == 0x00ffff20) ++ break; ++ if (!sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE) || ++ !sftl_erased(sftl->oob, sizeof(sftl->oob))) ++ return -EBADMSG; ++ } ++ if (lane < sftl->geo->lanes) + break; +- if (!sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE) || +- !sftl_erased(sftl->oob, sizeof(sftl->oob))) +- return -EBADMSG; + } +- if (lane == sftl->geo->lanes) ++ if (seed == sftl->geo->nr_bootstrap) + return -EBADMSG; + for (i = 0; i < 8; i++) { + const u8 *row = sftl->page + 0x100 + 4 * i; +@@ -476,9 +506,9 @@ static int sftl_vfl_members(struct apple_sftl *sftl) + return -EBADMSG; + __set_bit(members[i].block, sftl->vfl_reserved); + } +- if (lane) { ++ if (lane || seed) { + for (i = 0; i < 8; i++) +- if (members[i].lane == lane && members[i].block == sftl->geo->bootstrap) ++ if (members[i].lane == lane && members[i].block == block) + return 0; + return -EBADMSG; + } +@@ -1421,10 +1451,28 @@ static int sftl_footer(struct apple_sftl *sftl, const u8 *head, u32 block, + goto out; + } + } +- if (terminated && position == pages * 4 - chunks) +- ret = sftl_remember_user_seq(sftl, block, footer, index / SFTL_META); +- else ++ if (!terminated || position != pages * 4 - chunks) { + ret = -EBADMSG; ++ goto out; ++ } ++ /* 12H321 summaries can count their own chunks after the last run. The ++ * sequences belong to the summary and to no record of another block. ++ */ ++ if (sftl->geo->summary_sequences && span == relative_end + chunks) { ++ u32 address = block * sftl_stride(sftl) + pages * 4 - chunks, k; ++ ++ for (k = 0; k < chunks; k++) { ++ u64 sequence = base + relative_end + k; ++ ++ if (sequence <= sftl->checkpoint_sequence) ++ continue; ++ ret = sftl_record_add(journal, (u64)0x1c << 56 | sequence, U32_MAX, ++ address + k); ++ if (ret) ++ goto out; ++ } ++ } ++ ret = sftl_remember_user_seq(sftl, block, footer, index / SFTL_META); + out: + kfree(footer); + return ret; +@@ -1567,7 +1615,9 @@ static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + ret = -EBADMSG; + if (sequence != expected++) + goto out; +- if (sftl_kind(record) == 0x1f) ++ /* Context and summary chunks, and padding, map nothing. */ ++ if (sftl_kind(record) == 0x1f || sftl_kind(record) == 0x1c || ++ record->key == SFTL_PAD) + continue; + if (sftl_kind(record) == 2 && record->key == SFTL_TRIM) { + const u8 *payload; +diff --git a/drivers/mtd/apple-sftl-test.c b/drivers/mtd/apple-sftl-test.c +index a11071b79..c7f1df4c8 100644 +--- a/drivers/mtd/apple-sftl-test.c ++++ b/drivers/mtd/apple-sftl-test.c +@@ -3119,6 +3119,356 @@ static void sftl_test_gc_preserves_last_sequences(struct kunit *test) + apple_sftl_checkpoint_free(f->checkpoint); + } + ++/* ++ * Synthetic 16 GB medium: two CAUs per bus, 1064 blocks of 256 pages, four ++ * lanes, 1055 superblocks of 4096 slots. No captured device bytes. ++ */ ++#define T16_LANES 4U ++#define T16_PAGES 256U ++#define T16_BLOCKS 1064U ++#define T16_SUBBLOCKS 1055U ++#define T16_STRIDE (T16_LANES * T16_PAGES * 4) ++#define T16_LPAGES 3906266U ++#define T16_DISK 3906250U ++#define T16_UNMAPPED 0x7fffffU ++#define T16_CONTEXT 1U ++#define T16_CONTEXT_BASE 1000000ULL ++#define T16_RECORDS 56U /* 24 fixed, 32 range records */ ++#define T16_OLD 2U /* closed before the checkpoint */ ++#define T16_OLD_BASE 100ULL ++#define T16_NEW 5U /* closed after it, lane 2 retired */ ++#define T16_NEW_LBA 2000U ++#define T16_NEW_RUN 10U ++#define T16_SUMMARY 4U ++ ++struct t16_fixture { ++ struct apple_ppn provider; ++ struct apple_ppn_ops ops; ++ 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 */ ++ bool new_block; ++}; ++ ++static unsigned int t16_lanes(u32 block) ++{ ++ return block == T16_NEW ? 3 : T16_LANES; ++} ++ ++static u16 t16_usage(unsigned int lane, u32 block) ++{ ++ if (!block) ++ return 0xb002; ++ if (block == T16_NEW && lane == 2) ++ return 0xbffe; ++ if (block >= 1062) ++ return 0xbff1; ++ if (block >= T16_SUBBLOCKS) ++ return 0xb003; ++ return 0; ++} ++ ++static void t16_meta(u8 *meta, u8 kind, u8 flags, u64 sequence, u32 key, u32 high) ++{ ++ put_unaligned_le64(sequence << 16 | (u16)flags << 8 | kind, meta); ++ put_unaligned_le32(key, meta + 8); ++ put_unaligned_le32(high, meta + 12); ++} ++ ++/* The VFL bank: header at page 0, lane tables at 1..4, the checkpoint at 5. */ ++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; ++ unsigned int i; ++ ++ if (block != f->vfl_block || page > T16_LANES + 1) ++ return 0; ++ *status = 0x40; ++ memset(data, 0, APPLE_PPN_PAGE_SIZE); ++ memset(oob, 0, APPLE_PPN_OOB_SIZE); ++ oob[0] = 0x20; ++ put_unaligned_le32(0xfffffff0 - page, oob + 4); ++ if (!page || page == T16_LANES + 1) { ++ oob[1] = 0xff; ++ oob[2] = 0xff; ++ 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); ++ for (i = 0; i < 8; i++) { ++ put_unaligned_le16(i < 4 ? 1063 : 1062, data + 0x100 + 4 * i); ++ data[0x100 + 4 * i + 2] = i % 4; ++ } ++ for (i = 0; i < T16_LANES; i++) ++ put_unaligned_le16(group << 15 | (i + 1), data + 0x200 + 32 * i); ++ 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); ++ return 0; ++} ++ ++static void t16_context_record(struct t16_fixture *f, u32 index, u8 *payload, u8 *meta) ++{ ++ static const struct { ++ u8 subtype, records; ++ u16 entries; ++ } groups[] = { { 1, 4, 0 }, { 2, 4, 0 }, { 3, 4, 512 }, { 5, 8, 256 }, { 6, 4, 1024 } }; ++ u32 i, first = 0, start = 0, entries = 0; ++ u8 subtype = 4; ++ ++ memset(payload, 0, 4096); ++ for (i = 0; i < ARRAY_SIZE(groups); first += groups[i++].records) { ++ if (index >= first + groups[i].records) ++ 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); ++ break; ++ } ++ t16_meta(meta, 0x1f, subtype, T16_CONTEXT_BASE + index, 0, U32_MAX); ++ put_unaligned_le16(start, meta + 8); ++ put_unaligned_le16(entries, meta + 10); ++ if (index == 0) { ++ put_unaligned_le32(1, payload); ++ put_unaligned_le32(T16_CONTEXT, payload + 4); ++ } else if (index == 3) { ++ put_unaligned_le32(T16_SUBBLOCKS, payload + 4096 - 4); ++ } else if (subtype == 3) { ++ for (i = 0; i < entries; i++) { ++ u32 block = start + i; ++ ++ payload[8 * i] = block == T16_CONTEXT ? 7 : block == T16_OLD ? 3 : ++ block == 0 ? 8 : 9; ++ if (block == T16_OLD) ++ put_unaligned_le16(1024, payload + 8 * i + 2); ++ } ++ } else if (subtype == 4 && index == 24) { ++ /* LBAs 0..1023 live in the old block; the rest is unmapped. */ ++ put_unaligned_le32(0, payload); ++ put_unaligned_le32(0xfffffff0, payload + 4); ++ put_unaligned_le32(T16_OLD * T16_STRIDE, payload + 8); ++ put_unaligned_le32(1024, payload + 12); ++ put_unaligned_le32(T16_UNMAPPED, payload + 16); ++ put_unaligned_le32(T16_LPAGES - 1024, payload + 20); ++ put_unaligned_le32(U32_MAX, payload + 24); ++ } else if (subtype == 4) { ++ memset(payload, 0xff, 8); ++ } ++} ++ ++static u32 t16_new_slots(void) ++{ ++ return 3 * T16_PAGES * 4 - T16_SUMMARY; ++} ++ ++/* Address slot -> contents of the old, new and context blocks. */ ++static void t16_slot(struct t16_fixture *f, u32 block, u32 slot, u8 *payload, u8 *meta) ++{ ++ u32 slots = t16_lanes(block) * T16_PAGES * 4; ++ ++ memset(payload, 0xff, 4096); ++ memset(meta, 0xff, 16); ++ if (block == T16_CONTEXT) { ++ if (slot < 24 + f->range_records) ++ t16_context_record(f, slot, payload, meta); ++ return; ++ } ++ if (block == T16_OLD) { ++ if (slot >= slots - T16_SUMMARY) { ++ t16_meta(meta, 0x1c, T16_SUMMARY << 1, T16_OLD_BASE, ++ slots - T16_SUMMARY, 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(0, payload + 4); ++ put_unaligned_le32(0, payload + 8); ++ put_unaligned_le32(slots - T16_SUMMARY, payload + 12); ++ } ++ return; ++ } ++ memset(payload, 'o' + slot % 7, 4096); ++ put_unaligned_le32(slot, payload); ++ t16_meta(meta, 1, 0, T16_OLD_BASE + slot, slot, 0); ++ return; ++ } ++ if (block == T16_NEW && f->new_block) { ++ u64 base = T16_CONTEXT_BASE + 24 + f->range_records; ++ ++ if (slot >= t16_new_slots()) { ++ u32 index = slot - t16_new_slots(); ++ ++ t16_meta(meta, 0x1c, T16_SUMMARY << 1, base, ++ t16_new_slots() + (f->summary_own_span ? T16_SUMMARY : 0), 0); ++ put_unaligned_le16(T16_SUMMARY, meta + 12); ++ put_unaligned_le16(0xffff, meta + 14); ++ memset(payload, 0, 4096); ++ if (!index) { ++ /* One data run, then padding up to the summary. */ ++ put_unaligned_le32(0, payload); ++ put_unaligned_le32(base >> 16, payload + 4); ++ put_unaligned_le32(T16_NEW_LBA, payload + 8); ++ put_unaligned_le32(T16_NEW_RUN, payload + 12); ++ put_unaligned_le32(T16_NEW_RUN, payload + 16); ++ put_unaligned_le32(base >> 16, payload + 20); ++ put_unaligned_le32(0xffff0000, payload + 24); ++ put_unaligned_le32(t16_new_slots() - T16_NEW_RUN, payload + 28); ++ } ++ return; ++ } ++ if (slot < T16_NEW_RUN) { ++ memset(payload, 'n', 4096); ++ put_unaligned_le32(T16_NEW_LBA + slot, payload); ++ t16_meta(meta, 1, 0, base + slot, T16_NEW_LBA + slot, (base + slot) >> 16); ++ } else { ++ memset(payload, 0, 4096); ++ t16_meta(meta, 1, 0, base + slot, 0xffff0000, (base + slot) >> 16); ++ } ++ } ++} ++ ++static int t16_read_page(void *priv, unsigned int bus, unsigned int cau, ++ unsigned int block, unsigned int page, bool context, ++ u8 *data, u8 *oob, u8 *status) ++{ ++ struct t16_fixture *f = priv; ++ unsigned int lane = cau * 2 + bus, width, index, chunk, i; ++ ++ if (bus >= 2 || cau >= 2 || block >= T16_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(f, lane, block, page, data, oob, status); ++ if (block >= T16_SUBBLOCKS || t16_usage(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)) ++ index++; ++ for (chunk = 0; chunk < 4; chunk++) ++ t16_slot(f, block, (page * width + index) * 4 + chunk, ++ data + chunk * 4096, oob + chunk * 16); ++ if (memchr_inv(oob, 0xff, APPLE_PPN_OOB_SIZE)) ++ *status = 0x40; ++ return 0; ++} ++ ++static struct t16_fixture *t16_fixture(struct kunit *test) ++{ ++ struct t16_fixture *f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); ++ ++ if (!f) ++ return NULL; ++ f->ops.read_page = t16_read_page; ++ f->provider = (struct apple_ppn) { ++ .ops = &f->ops, .priv = f, .buses = 2, .caus = 2, ++ .blocks = T16_BLOCKS, .pages = T16_PAGES, ++ }; ++ f->vfl_block = 1063; ++ f->range_records = 32; ++ f->new_block = true; ++ f->summary_own_span = true; ++ return f; ++} ++ ++static void t16_expect_page(struct kunit *test, struct apple_sftl *sftl, u32 lba, ++ u8 fill, u32 first_word) ++{ ++ 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_EQ(test, get_unaligned_le32(data), first_word); ++ KUNIT_EXPECT_EQ(test, data[4], fill); ++ KUNIT_EXPECT_EQ(test, data[4095], fill); ++} ++ ++/* The reader registers on the 16 GB layout, read-only, through a summary ++ * that counts its own chunks and a padded run, and exposes 16 GB. ++ */ ++static void sftl_test_16gb_medium(struct kunit *test) ++{ ++ struct t16_fixture *f = t16_fixture(test); ++ struct apple_sftl *sftl = NULL; ++ struct apple_sftl_info info; ++ u8 *data = kunit_kmalloc(test, 4096, GFP_KERNEL); ++ ++ KUNIT_ASSERT_NOT_NULL(test, f); ++ KUNIT_ASSERT_NOT_NULL(test, data); ++ 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.disk_pages, T16_DISK); ++ KUNIT_EXPECT_EQ(test, info.logical_pages, T16_LPAGES); ++ KUNIT_EXPECT_EQ(test, info.checkpoint_sequence, T16_CONTEXT_BASE + T16_RECORDS - 1); ++ KUNIT_EXPECT_EQ(test, info.journal_sequence, ++ T16_CONTEXT_BASE + T16_RECORDS + t16_new_slots() + T16_SUMMARY - 1); ++ t16_expect_page(test, sftl, 0, 'o', 0); ++ t16_expect_page(test, sftl, 1023, 'o' + 1023 % 7, 1023); ++ t16_expect_page(test, sftl, T16_NEW_LBA + 3, 'n', T16_NEW_LBA + 3); ++ KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, 1500, data), 0); ++ KUNIT_EXPECT_TRUE(test, !memchr_inv(data, 0, 4096)); ++ KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, T16_LPAGES - 1, data), 0); ++ KUNIT_EXPECT_EQ(test, apple_sftl_read(sftl, T16_LPAGES, data), -EINVAL); ++ memset(data, 'w', 4096); ++ KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, 0, data, 1), -EROFS); ++ t16_expect_page(test, sftl, 0, 'o', 0); ++ apple_sftl_free(sftl); ++} ++ ++/* When bank 1063 is erased, the member list comes from bank 1062. */ ++static void sftl_test_16gb_second_bootstrap(struct kunit *test) ++{ ++ struct t16_fixture *f = t16_fixture(test); ++ struct apple_sftl *sftl = NULL; ++ ++ KUNIT_ASSERT_NOT_NULL(test, f); ++ f->vfl_block = 1062; ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ t16_expect_page(test, sftl, T16_NEW_LBA, 'n', T16_NEW_LBA); ++ apple_sftl_free(sftl); ++ f->vfl_block = 0; ++ KUNIT_EXPECT_EQ(test, apple_sftl_load(&f->provider, &sftl), -EBADMSG); ++ KUNIT_EXPECT_PTR_EQ(test, sftl, NULL); ++} ++ ++/* 12H321 range records come in multiples of 16; a summary span that counts ++ * its own chunks is accounted only when exactly those chunks are missing. ++ */ ++static void sftl_test_16gb_context_rules(struct kunit *test) ++{ ++ struct t16_fixture *f = t16_fixture(test); ++ struct apple_sftl *sftl = NULL; ++ struct apple_sftl_info info; ++ ++ KUNIT_ASSERT_NOT_NULL(test, f); ++ f->range_records = 48; ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ apple_sftl_free(sftl); ++ /* A context cut inside its range records leaves no generation. */ ++ f->range_records = 40; ++ KUNIT_EXPECT_LT(test, apple_sftl_load(&f->provider, &sftl), 0); ++ f->range_records = 32; ++ /* Without the summary's own span the sequence ends at the last pad. */ ++ f->summary_own_span = 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, ++ T16_CONTEXT_BASE + T16_RECORDS + t16_new_slots() - 1); ++ apple_sftl_free(sftl); ++} ++ + static struct kunit_case apple_sftl_cases[] = { + KUNIT_CASE(sftl_test_rotate_mounted), + KUNIT_CASE(sftl_test_vfl_rotation_cuts), +@@ -3173,6 +3523,9 @@ static struct kunit_case apple_sftl_cases[] = { + KUNIT_CASE(sftl_test_preserve_footer_allocation_floor), + KUNIT_CASE(sftl_test_reject_other_geometry), + KUNIT_CASE(sftl_test_reject_inactive_lane_gap), ++ KUNIT_CASE(sftl_test_16gb_medium), ++ KUNIT_CASE(sftl_test_16gb_second_bootstrap), ++ KUNIT_CASE(sftl_test_16gb_context_rules), + {} + }; + +diff --git a/drivers/mtd/devices/mtd-apple-h2fmi.c b/drivers/mtd/devices/mtd-apple-h2fmi.c +index 0f9b0d1b4..64b85132b 100644 +--- a/drivers/mtd/devices/mtd-apple-h2fmi.c ++++ b/drivers/mtd/devices/mtd-apple-h2fmi.c +@@ -745,9 +745,10 @@ static int h2fmi_register_sftl(struct h2fmi *fmi) + .pages = g->pages, + }; + +- /* This recovery implementation supports the measured 64 GB profile. */ +- if (!IS_ENABLED(CONFIG_MTD_APPLE_SFTL) || g->caus != 8 || +- g->blocks != 2088 || g->pages != 128 || g->slc_pages != 64) ++ /* 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))) + return 0; + fmi->ppn_ops.read_page = h2fmi_ppn_read; + fmi->ppn_ops.program_page = h2fmi_ppn_program; From 410d3f09995e28a5470ad5d71810763628d3a721 Mon Sep 17 00:00:00 2001 From: Henrik Klee Date: Fri, 20 Nov 2026 06:13:17 +0800 Subject: [PATCH 3/7] kernel: P105 NAND: SDR bring-up from Cascadia's controller driver H2FMI only worked in the DDR interface iBoot leaves and refused to probe otherwise. Patch 0019 (authored by rzxvx) ports Cascadia's controller facts into it: the SDR bring-up order with the power state set after the NAND reset, the measured timing, firmware and bad-block table reads, and SDR page transfers as one start per 4112-byte unit. The DDR path is unchanged; nothing on today's boot chain takes the SDR path yet. The armv7 config turns on STRICT_DEVMEM and IO_STRICT_DEVMEM, so /dev/mem can no longer reach the NAND controller's registers that H2FMI claims. Cascadia added this after a user-space tool reset the controller in the middle of a program and tore a page (its 2026-11-16 incident). KUnit: 85 cases pass. Untested on hardware. Assisted-by: LLM --- kernel/configs/apple-armv7/config | 4 +- ...Bring-the-PPN-packages-up-in-SDR-wit.patch | 724 ++++++++++++++++++ 2 files changed, 727 insertions(+), 1 deletion(-) create mode 100644 kernel/patches/armv7/mtd/0019-mtd-apple-h2fmi-Bring-the-PPN-packages-up-in-SDR-wit.patch diff --git a/kernel/configs/apple-armv7/config b/kernel/configs/apple-armv7/config index 29ee1bc6..3ff0ab70 100644 --- a/kernel/configs/apple-armv7/config +++ b/kernel/configs/apple-armv7/config @@ -834,6 +834,7 @@ CONFIG_FLATMEM_MANUAL=y CONFIG_FLATMEM=y CONFIG_ARCH_KEEP_MEMBLOCK=y CONFIG_MEMORY_ISOLATION=y +CONFIG_EXCLUSIVE_SYSTEM_RAM=y CONFIG_COMPACTION=y CONFIG_COMPACT_UNEVICTABLE_DEFAULT=1 # CONFIG_PAGE_REPORTING is not set @@ -7829,7 +7830,8 @@ CONFIG_PROBE_EVENTS=y # CONFIG_PREEMPTIRQ_DELAY_TEST is not set # CONFIG_RV is not set # CONFIG_SAMPLES is not set -# CONFIG_STRICT_DEVMEM is not set +CONFIG_STRICT_DEVMEM=y +CONFIG_IO_STRICT_DEVMEM=y # # arm Debugging diff --git a/kernel/patches/armv7/mtd/0019-mtd-apple-h2fmi-Bring-the-PPN-packages-up-in-SDR-wit.patch b/kernel/patches/armv7/mtd/0019-mtd-apple-h2fmi-Bring-the-PPN-packages-up-in-SDR-wit.patch new file mode 100644 index 00000000..2a467885 --- /dev/null +++ b/kernel/patches/armv7/mtd/0019-mtd-apple-h2fmi-Bring-the-PPN-packages-up-in-SDR-wit.patch @@ -0,0 +1,724 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: rzxvx +Date: Fri, 20 Nov 2026 06:09:45 +0800 +Subject: [PATCH] mtd: apple-h2fmi: Bring the PPN packages up in SDR without + iBoot's DDR + +H2FMI runs the packages in the DDR interface iBoot leaves behind and +refuses to probe otherwise. Cascadia's PIO driver resets the packages +and runs them in SDR, and read and wrote a whole 16 GB P105 that way. +Port its controller facts into H2FMI for the case where FMC_ON is not +DDR at probe: + +- the bring-up order of Cascadia's specification section 2.9: software + reset of both buses and the ECC window's init register, a NAND reset + of the populated CE, the low-power interface timing, read ID (PPN 1.5), + the parameters, then feature 0x180 set to the asynchronous state on + each CE once both are reset (without it every array read fails), the + measured working timing 0x23210, the firmware version and the + bad-block table of every CAU (feature 0x84 | cau << 8, one bit per + block); +- SDR operations: a software reset before and after each, status polls + completing on FMI status bit 8, a full 8-byte address for page reads, + and pages moved as four 4112-byte units of four 1028-byte sectors, + one start per unit, for both receive and transmit; the page is clocked + out on any status but a general error. + +The DDR path is unchanged. Register windows are already claimed through +devm_platform_ioremap_resource(), which Cascadia added to its driver +after a user-space tool reset the controller during a program; the +platform config also needs IO_STRICT_DEVMEM for /dev/mem to respect +that claim. + +KUnit covers the ID check, the bad-block table feature and size on both +profiles, and the full read address. + +Ported from Cascadia (https://github.com/rzxvx/Project-Cascadia) commits +0ae0c1b ("a5: PPN: bring-up fixes from the first device run (rung 1 not +passed)"), 710b586 ("a5: PPN: bring-up and read path as spec section +2.9; consecutive reads work"), c62a31e ("a5: NAND rung 2: reserved-block +test module, unit-shaped page transmit, SLC program") and b54a707 ("a5: +apple_ppn: claim the FMI register windows (request_mem_region)"), file +apple_ppn.c and devices/a5/docs/research/p105-nand-spec.md sections 1 +and 2, as of Cascadia ad28ba4. The controller findings credit +crystal-lized's iPhone 5 work. + +Assisted-by: LLM +--- + drivers/mtd/devices/Kconfig | 2 + + drivers/mtd/devices/mtd-apple-h2fmi-test.c | 37 ++ + drivers/mtd/devices/mtd-apple-h2fmi.c | 452 ++++++++++++++++++++- + drivers/mtd/devices/mtd-apple-h2fmi.h | 41 ++ + 4 files changed, 529 insertions(+), 3 deletions(-) + +diff --git a/drivers/mtd/devices/Kconfig b/drivers/mtd/devices/Kconfig +index a43defee2..33ab36b71 100644 +--- a/drivers/mtd/devices/Kconfig ++++ b/drivers/mtd/devices/Kconfig +@@ -214,6 +214,8 @@ config MTD_APPLE_H2FMI + driving the Hynix PPN packages the iPad mini 1 boots iOS from. The + package does its own ECC, so this is a plain MTD and not a raw-NAND + driver. One MTD per CAU; geometry is read from each package. ++ The driver keeps the DDR interface iBoot leaves; without it, it ++ resets the packages and runs them in SDR. + + Pages are programmed whole, only when they read back erased, and + each program is verified by reading it back. The aggregate PPN +diff --git a/drivers/mtd/devices/mtd-apple-h2fmi-test.c b/drivers/mtd/devices/mtd-apple-h2fmi-test.c +index cb0d60e87..e842057fa 100644 +--- a/drivers/mtd/devices/mtd-apple-h2fmi-test.c ++++ b/drivers/mtd/devices/mtd-apple-h2fmi-test.c +@@ -237,6 +237,42 @@ static void h2fmi_raw_write_ownership_test(struct kunit *test) + apple_ppn_release_sftl(&access); + } + ++/* SDR bring-up facts from Cascadia's PIO driver for both package profiles. */ ++static void h2fmi_sdr_facts_test(struct kunit *test) ++{ ++ static const u8 ppn_155[H2FMI_ID_SIZE] = { 'P', 'P', 'N', 1, 5, 5, 0, 0 }; ++ u8 params[H2FMI_PARAMS_SIZE], id[H2FMI_ID_SIZE]; ++ struct h2fmi_geometry g; ++ u32 addr0, addr1; ++ ++ KUNIT_EXPECT_TRUE(test, h2fmi_ppn_id(ppn_155)); ++ memcpy(id, ppn_155, sizeof(id)); ++ id[5] = 7; ++ KUNIT_EXPECT_TRUE(test, h2fmi_ppn_id(id)); ++ id[4] = 4; ++ KUNIT_EXPECT_FALSE(test, h2fmi_ppn_id(id)); ++ memcpy(id, ppn_155, sizeof(id)); ++ id[2] = 'X'; ++ KUNIT_EXPECT_FALSE(test, h2fmi_ppn_id(id)); ++ ++ h2fmi_test_params(params, ppn_16gb); ++ KUNIT_ASSERT_EQ(test, h2fmi_parse_geometry(params, sizeof(params), &g), 0); ++ KUNIT_EXPECT_EQ(test, h2fmi_bad_block_bytes(&g), 133U); ++ h2fmi_test_params(params, ppn_64gb); ++ KUNIT_ASSERT_EQ(test, h2fmi_parse_geometry(params, sizeof(params), &g), 0); ++ KUNIT_EXPECT_EQ(test, h2fmi_bad_block_bytes(&g), 261U); ++ KUNIT_EXPECT_EQ(test, h2fmi_bad_block_feature(0), 0x84); ++ KUNIT_EXPECT_EQ(test, h2fmi_bad_block_feature(7), 0x784); ++ ++ /* 0A <16448, column 0, row> 37 */ ++ h2fmi_full_address(0xc27ff, &addr0, &addr1); ++ KUNIT_EXPECT_EQ(test, addr0, 0x4040U); ++ KUNIT_EXPECT_EQ(test, addr1, 0xc27ffU); ++ /* Four units of four sectors carry the whole raw page. */ ++ KUNIT_EXPECT_EQ(test, 4 * H2FMI_SDR_SECTOR, H2FMI_CHUNK_RAW); ++ KUNIT_EXPECT_EQ(test, H2FMI_CHUNKS * H2FMI_CHUNK_RAW, H2FMI_PAGE_RAW); ++} ++ + static struct kunit_case h2fmi_test_cases[] = { + KUNIT_CASE(h2fmi_raw_write_ownership_test), + KUNIT_CASE(h2fmi_geometry_test), +@@ -247,6 +283,7 @@ static struct kunit_case h2fmi_test_cases[] = { + KUNIT_CASE(h2fmi_status_test), + KUNIT_CASE(h2fmi_slc_row_test), + KUNIT_CASE(h2fmi_program_status_test), ++ KUNIT_CASE(h2fmi_sdr_facts_test), + {} + }; + +diff --git a/drivers/mtd/devices/mtd-apple-h2fmi.c b/drivers/mtd/devices/mtd-apple-h2fmi.c +index 64b85132b..947158ebd 100644 +--- a/drivers/mtd/devices/mtd-apple-h2fmi.c ++++ b/drivers/mtd/devices/mtd-apple-h2fmi.c +@@ -12,7 +12,9 @@ + * Every register use and every command sequence here comes from iBEC's own + * disassembly (H2fmi.c, H2fmi_ppn.c, fmiss_ppn.c) by way of the userspace tool + * this is a port of, tools/nand/ppn.c, which read the whole NAND bit-for-bit +- * repeatably. docs/research/p105-nand.md is the notebook. ++ * repeatably. docs/research/p105-nand.md is the notebook. When iBoot did not ++ * leave the interface in DDR, the SDR bring-up and transfer shapes follow ++ * Project Cascadia's PIO driver (apple_ppn.c) and its specification. + * + * Geometry is read from each PPN package before registering any MTDs. + * The supported packages have one CE per bus and either two or eight CAUs. +@@ -36,6 +38,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -73,6 +76,13 @@ + #define FMC_STATUS 0x44 + #define FMC_NAND_STATUS 0x48 + #define FMC_STATUS_MASK 0x4c ++#define FMC_ADDR1 0x1c ++ ++#define ECC_INIT 0x14 /* FMI + 0x80014 */ ++#define FMI_ALL_EVENTS 0x10f ++#define FMI_POLL_DONE BIT(8) ++#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. */ +@@ -87,6 +97,11 @@ static const u8 h2fmi_ops[][2] = { + { 0x17, 0x00 }, /* PPN program confirm */ + { 0x79, 0x00 }, /* PPN mutation status */ + { 0x6a, 0xd7 }, /* PPN erase, one normal row */ ++ { 0xff, 0x00 }, /* NAND reset (SDR bring-up) */ ++ { 0x90, 0x00 }, /* read ID (SDR bring-up) */ ++ { 0xee, 0xe7 }, /* PPN get feature */ ++ { 0xef, 0x00 }, /* PPN set feature, address phase */ ++ { 0xe7, 0x00 }, /* PPN set feature confirm */ + }; + + struct h2fmi_bus { +@@ -96,6 +111,8 @@ struct h2fmi_bus { + struct mutex lock; /* one command sequence on this bus at a time */ + u8 *page; /* one raw page; only touched under lock */ + 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 */ + }; + +@@ -299,6 +316,378 @@ static void h2fmi_device_reset(struct h2fmi_bus *b, u32 on, u32 if_ctrl) + writel(if_ctrl, b->fmc + FMC_IF_CTRL); + } + ++/* ++ * SDR operation. Cascadia's driver resets the package and runs it in SDR, ++ * where every operation starts and ends with a software reset of the bus, ++ * a status poll completes on FMI status bit 8 and a page moves as four ++ * units of 4112 bytes, each one start of four 1028-byte sectors. A page read ++ * sends the full address and clocks the page out unless the package reports ++ * a general error. ++ */ ++static void h2fmi_sdr_reset(struct h2fmi_bus *b) ++{ ++ writel(6, b->fmi + FMI_CONTROL); ++ writel(FMC_ON_SDR, b->fmc + FMC_ON); ++ writel(b->if_ctrl, b->fmc + FMC_IF_CTRL); ++} ++ ++static void h2fmi_sdr_clear(struct h2fmi_bus *b) ++{ ++ writel(0, b->fmc + FMC_INTMASK); ++ writel(0, b->fmi + FMI_INTEN); ++ writel(0x31ffff, b->fmc + FMC_STATUS); ++ writel(FMI_ALL_EVENTS, b->fmi + FMI_STATUS); ++} ++ ++static int h2fmi_sdr_poll(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *status) ++{ ++ ktime_t end = ktime_add_us(ktime_get(), 2000000); ++ ++ h2fmi_sdr_clear(b); ++ writel(b->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); ++ while (!(readl(b->fmi + FMI_STATUS) & FMI_POLL_DONE)) { ++ if (ktime_after(ktime_get(), end)) { ++ writel(0, b->fmc + FMC_RW_CTRL); ++ writel(b->if_ctrl, b->fmc + FMC_IF_CTRL); ++ dev_err(fmi->dev, "SDR status timeout\n"); ++ return -ETIMEDOUT; ++ } ++ cpu_relax(); ++ } ++ *status = readl(b->fmc + FMC_NAND_STATUS); ++ writel(FMI_POLL_DONE, b->fmi + FMI_STATUS); ++ writel(0, b->fmc + FMC_RW_CTRL); ++ writel(b->if_ctrl, b->fmc + FMC_IF_CTRL); ++ return 0; ++} ++ ++/* Operation status (77 7D) and its poll. */ ++static int h2fmi_sdr_status(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *status) ++{ ++ int ret = h2fmi_cmd_write(fmi, b, 0x77, 0x7d); ++ ++ if (ret) ++ return ret; ++ writel(3, b->fmc + FMC_RW_CTRL); ++ ret = h2fmi_wait(fmi, b->fmc, FMC_STATUS, 3, 3); ++ return ret ? ret : h2fmi_sdr_poll(fmi, b, status); ++} ++ ++static int h2fmi_sdr_fifo(struct h2fmi *fmi, struct h2fmi_bus *b) ++{ ++ u32 v; ++ int ret; ++ ++ ret = readl_poll_timeout(b->fmi + FMI_DMA_STATUS, v, v & 0x18, 0, 100000); ++ if (ret) ++ dev_err(fmi->dev, "SDR PIO timeout: FMI+0x1c = 0x%08x\n", v); ++ return ret; ++} ++ ++/* One start per 4112-byte unit: four sectors of 1028 bytes. */ ++static void h2fmi_sdr_unit_start(struct h2fmi_bus *b, bool transmit) ++{ ++ h2fmi_sdr_clear(b); ++ writel(5, b->fmi + FMI_CONFIG); ++ writel(H2FMI_SDR_SECTOR << 8 | 4, b->fmi + FMI_PIO_CONFIG); ++ writel(transmit ? 5 : 3, b->fmi + FMI_CONTROL); ++} ++ ++/* The units arrive in the stream order of the raw page. */ ++static int h2fmi_sdr_receive(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *raw) ++{ ++ unsigned int sector, word; ++ int ret; ++ ++ for (sector = 0; sector < H2FMI_PAGE_RAW / H2FMI_SDR_SECTOR; sector++) { ++ u8 *p = raw + sector * H2FMI_SDR_SECTOR; ++ ++ if (!(sector % 4)) ++ h2fmi_sdr_unit_start(b, false); ++ ret = h2fmi_sdr_fifo(fmi, b); ++ if (ret) ++ return ret; ++ for (word = 0; word < H2FMI_SDR_SECTOR; word += 4) ++ put_unaligned_le32(readl(b->fmi + FMI_DATA), p + word); ++ } ++ return 0; ++} ++ ++/* Transmit mirrors the receive; each unit ends with the done bit. */ ++static int h2fmi_sdr_transmit(struct h2fmi *fmi, struct h2fmi_bus *b, const u8 *raw) ++{ ++ unsigned int sector, word; ++ int ret; ++ ++ for (sector = 0; sector < H2FMI_PAGE_RAW / H2FMI_SDR_SECTOR; sector++) { ++ const u8 *p = raw + sector * H2FMI_SDR_SECTOR; ++ ++ if (!(sector % 4)) ++ h2fmi_sdr_unit_start(b, true); ++ ret = h2fmi_sdr_fifo(fmi, b); ++ if (ret) ++ return ret; ++ for (word = 0; word < H2FMI_SDR_SECTOR; word += 4) ++ writel(get_unaligned_le32(p + word), b->fmi + FMI_DATA); ++ if (sector % 4 == 3) { ++ ret = h2fmi_wait(fmi, b->fmi, FMI_STATUS, 2, 2); ++ if (ret) ++ return ret; ++ } ++ } ++ return 0; ++} ++ ++/* One transfer of at most 1024 bytes, as feature data moves. */ ++static int h2fmi_sdr_burst(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *buf, u32 bytes, ++ bool transmit) ++{ ++ u32 word; ++ int ret; ++ ++ writel(5, b->fmi + FMI_CONFIG); ++ writel((bytes << 8 & 0x7fc00) | 1, b->fmi + FMI_PIO_CONFIG); ++ writel(transmit ? 5 : 3, b->fmi + FMI_CONTROL); ++ ret = h2fmi_sdr_fifo(fmi, b); ++ if (ret) ++ return ret; ++ for (word = 0; word < bytes; word += 4) { ++ if (transmit) ++ writel(get_unaligned_le32(buf + word), b->fmi + FMI_DATA); ++ else ++ put_unaligned_le32(readl(b->fmi + FMI_DATA), buf + word); ++ } ++ return transmit ? h2fmi_wait(fmi, b->fmi, FMI_STATUS, 2, 2) : 0; ++} ++ ++static int h2fmi_cmd_addr(struct h2fmi *fmi, struct h2fmi_bus *b, u8 op, u32 addr, int naddr) ++{ ++ int ret = h2fmi_cmd_write(fmi, b, op, 0); ++ ++ if (ret) ++ return ret; ++ writel(addr, b->fmc + FMC_ADDR0); ++ writel((naddr + 7) & 7, b->fmc + FMC_ADDRNUM); ++ writel(9, b->fmc + FMC_RW_CTRL); ++ return h2fmi_wait(fmi, b->fmc, FMC_STATUS, 9, 9); ++} ++ ++/* Parameters (92 97) or a feature (EE E7): status, 7A, data, 77. A tail ++ * shorter than a word moves as one more 4-byte transfer. ++ */ ++static int h2fmi_sdr_get(struct h2fmi *fmi, struct h2fmi_bus *b, u8 op, u8 op2, u32 address, ++ int naddr, u8 *buf, u32 length) ++{ ++ u32 done = 0; ++ u8 status = 0; ++ int ret; ++ ++ writel(1u << H2FMI_CE, b->fmc + FMC_CE_CTRL); ++ h2fmi_sdr_clear(b); ++ ret = h2fmi_cmd_addr_cmd(fmi, b, op, op2, address, naddr); ++ if (!ret) ++ ret = h2fmi_sdr_status(fmi, b, &status); ++ if (!ret && status != PPN_ST_GOOD) ++ ret = -EIO; ++ if (!ret) ++ ret = h2fmi_cmd1(fmi, b, 0x7a); ++ while (!ret && done < length) { ++ u32 bytes = min_t(u32, length - done, 0x400); ++ u8 tail[4]; ++ ++ if (bytes >= 4) { ++ bytes &= ~3u; ++ ret = h2fmi_sdr_burst(fmi, b, buf + done, bytes, false); ++ } else { ++ ret = h2fmi_sdr_burst(fmi, b, tail, 4, false); ++ memcpy(buf + done, tail, bytes); ++ } ++ done += bytes; ++ } ++ writel(6, b->fmi + FMI_CONTROL); ++ if (!ret) ++ ret = h2fmi_cmd1(fmi, b, 0x77); ++ writel(0, b->fmc + FMC_CE_CTRL); ++ return ret; ++} ++ ++/* Set feature: EF and two address bytes, one word out, E7, status, 77. */ ++static int h2fmi_sdr_set(struct h2fmi *fmi, struct h2fmi_bus *b, u16 feature, u32 value) ++{ ++ u8 word[4], status = 0; ++ int ret; ++ ++ put_unaligned_le32(value, word); ++ writel(1u << H2FMI_CE, b->fmc + FMC_CE_CTRL); ++ writel(6, b->fmi + FMI_CONTROL); ++ ret = h2fmi_cmd_addr(fmi, b, 0xef, feature, 2); ++ if (!ret) { ++ h2fmi_sdr_clear(b); ++ ret = h2fmi_sdr_burst(fmi, b, word, sizeof(word), true); ++ } ++ if (!ret) ++ ret = h2fmi_cmd1(fmi, b, 0xe7); ++ if (!ret) ++ ret = h2fmi_sdr_status(fmi, b, &status); ++ 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_sdr_reset(b); ++ return ret; ++} ++ ++static int h2fmi_sdr_id(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *id) ++{ ++ u32 v; ++ int ret; ++ ++ writel(1u << H2FMI_CE, b->fmc + FMC_CE_CTRL); ++ h2fmi_sdr_clear(b); ++ ret = h2fmi_cmd_addr(fmi, b, 0x90, 0, 1); ++ if (!ret) { ++ writel(0, b->fmi + FMI_CONFIG); ++ writel(H2FMI_ID_SIZE << 8 | 1, b->fmi + FMI_PIO_CONFIG); ++ writel(3, b->fmi + FMI_CONTROL); ++ ret = readl_poll_timeout(b->fmi + FMI_STATUS, v, v & 2, 0, 100000); ++ } ++ if (!ret) { ++ put_unaligned_le32(readl(b->fmi + FMI_DATA), id); ++ put_unaligned_le32(readl(b->fmi + FMI_DATA), id + 4); ++ } ++ writel(0, b->fmc + FMC_CE_CTRL); ++ h2fmi_sdr_reset(b); ++ return ret; ++} ++ ++/* ++ * Bring both packages up in SDR in the order Cascadia's driver read the ++ * whole 16 GB device with: software resets, the ECC window's init register, ++ * a NAND reset of the populated CE at the low-power timing, read ID, the ++ * parameters, the asynchronous power state on each CE once both are reset ++ * (without it every array read fails), the working timing, the firmware ++ * version and every CAU's bad-block table. Caller holds both bus locks. ++ */ ++static int h2fmi_sdr_bringup(struct h2fmi *fmi) ++{ ++ struct h2fmi_geometry g; ++ u8 id[H2FMI_ID_SIZE], firmware[H2FMI_FIRMWARE_SIZE]; ++ unsigned int i, cau; ++ int ret; ++ ++ for (i = 0; i < H2FMI_BUSES; i++) { ++ struct h2fmi_bus *b = &fmi->bus[i]; ++ ++ b->sdr = true; ++ b->if_ctrl = 0; ++ h2fmi_sdr_reset(b); ++ writel(0, b->ecc + ECC_INIT); ++ } ++ for (i = 0; i < H2FMI_BUSES; i++) { ++ struct h2fmi_bus *b = &fmi->bus[i]; ++ ++ writel(1u << H2FMI_CE, b->fmc + FMC_CE_CTRL); ++ udelay(10); ++ ret = h2fmi_cmd1(fmi, b, 0xff); ++ writel(0, b->fmc + FMC_CE_CTRL); ++ if (ret) ++ return ret; ++ msleep(50); ++ b->if_ctrl = H2FMI_IF_CTRL_LOW_POWER; ++ writel(b->if_ctrl, b->fmc + FMC_IF_CTRL); ++ ret = h2fmi_sdr_id(fmi, b, id); ++ if (ret) ++ return ret; ++ if (!h2fmi_ppn_id(id)) { ++ dev_err(fmi->dev, "bus %u: ID %*ph is not PPN 1.5\n", i, H2FMI_ID_SIZE, id); ++ return -ENODEV; ++ } ++ } ++ ret = h2fmi_sdr_get(fmi, &fmi->bus[0], 0x92, 0x97, 0, 1, fmi->bus[0].page, ++ H2FMI_PARAMS_SIZE); ++ if (!ret) ++ ret = h2fmi_parse_geometry(fmi->bus[0].page, H2FMI_PARAMS_SIZE, &g); ++ if (ret) ++ return ret; ++ for (i = 0; i < H2FMI_BUSES; i++) { ++ ret = h2fmi_sdr_set(fmi, &fmi->bus[i], H2FMI_FEATURE_POWER, H2FMI_POWER_ASYNC); ++ if (ret) { ++ dev_err(fmi->dev, "bus %u: power state: %d\n", i, ret); ++ return ret; ++ } ++ } ++ for (i = 0; i < H2FMI_BUSES; i++) { ++ fmi->bus[i].if_ctrl = H2FMI_IF_CTRL_SDR; ++ writel(H2FMI_IF_CTRL_SDR, fmi->bus[i].fmc + FMC_IF_CTRL); ++ } ++ ret = h2fmi_sdr_get(fmi, &fmi->bus[0], 0xee, 0xe7, H2FMI_FEATURE_FIRMWARE, 2, ++ firmware, sizeof(firmware)); ++ if (ret) ++ return ret; ++ for (i = 0; i < H2FMI_BUSES; i++) ++ for (cau = 0; cau < g.caus; cau++) { ++ ret = h2fmi_sdr_get(fmi, &fmi->bus[i], 0xee, 0xe7, ++ h2fmi_bad_block_feature(cau), 2, fmi->bus[i].page, ++ h2fmi_bad_block_bytes(&g)); ++ if (ret) { ++ dev_err(fmi->dev, "bus %u CAU %u: bad-block table: %d\n", ++ i, cau, ret); ++ return ret; ++ } ++ } ++ dev_info(fmi->dev, "PPN %*ph, firmware %*pE, SDR\n", H2FMI_ID_SIZE, id, ++ H2FMI_FIRMWARE_SIZE, firmware); ++ return 0; ++} ++ ++/* Caller holds b->lock. A page read in SDR, or the parameters. */ ++static int h2fmi_sdr_read(struct h2fmi *fmi, struct h2fmi_bus *b, u8 op, u32 row, ++ u8 *buffer, u32 length, u8 *status) ++{ ++ u32 addr0, addr1; ++ int ret, end_ret = 0; ++ ++ if (op == 0x92) { ++ h2fmi_sdr_reset(b); ++ ret = h2fmi_sdr_get(fmi, b, 0x92, 0x97, 0, 1, buffer, length); ++ *status = ret ? 0 : PPN_ST_GOOD; ++ h2fmi_sdr_reset(b); ++ return ret; ++ } ++ if (length != H2FMI_PAGE_RAW) ++ return -EINVAL; ++ h2fmi_full_address(row, &addr0, &addr1); ++ h2fmi_sdr_reset(b); ++ writel(1u << H2FMI_CE, b->fmc + FMC_CE_CTRL); ++ h2fmi_sdr_clear(b); ++ ret = h2fmi_cmd_write(fmi, b, 0x0a, 0x37); ++ if (!ret) { ++ writel(addr0, b->fmc + FMC_ADDR0); ++ writel(addr1, b->fmc + FMC_ADDR1); ++ writel((8 + 7) & 7, b->fmc + FMC_ADDRNUM); ++ writel(0xb, b->fmc + FMC_RW_CTRL); ++ ret = h2fmi_wait(fmi, b->fmc, FMC_STATUS, 0xb, 0xb); ++ } ++ if (!ret) ++ ret = h2fmi_sdr_status(fmi, b, status); ++ /* The package has committed to the data unless it reports a general error. */ ++ if (!ret && !(*status & BIT(4))) { ++ ret = h2fmi_cmd1(fmi, b, 0x7a); ++ if (!ret) ++ ret = h2fmi_sdr_receive(fmi, b, buffer); ++ end_ret = h2fmi_cmd1(fmi, b, 0x77); ++ } ++ writel(0, b->fmc + FMC_CE_CTRL); ++ h2fmi_sdr_reset(b); ++ return ret ? ret : end_ret; ++} ++ + /* Caller holds b->lock. All exits release CE and restore inherited state. */ + static int h2fmi_read_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, + u8 op, u8 op2, u32 address, int naddr, +@@ -310,6 +699,12 @@ static int h2fmi_read_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, + *status = 0; + if (b->failed) + return -EIO; ++ if (b->sdr) { ++ ret = h2fmi_sdr_read(fmi, b, op, address, buffer, length, status); ++ if (ret) ++ b->failed = true; ++ return ret; ++ } + on = readl(b->fmc + FMC_ON); + if_ctrl = readl(b->fmc + FMC_IF_CTRL); + if (on != 5) +@@ -447,6 +842,26 @@ static int h2fmi_program_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, + + if (b->failed) + return -EIO; ++ if (b->sdr) { ++ /* The confirm follows the last unit with no stop in between. */ ++ h2fmi_sdr_reset(b); ++ writel(1u << H2FMI_CE, b->fmc + FMC_CE_CTRL); ++ h2fmi_sdr_clear(b); ++ ret = h2fmi_write_address(fmi, b, row); ++ if (!ret) ++ ret = h2fmi_sdr_transmit(fmi, b, raw); ++ if (!ret) ++ ret = h2fmi_cmd1(fmi, b, 0x17); ++ if (!ret) ++ ret = h2fmi_cmd1(fmi, b, 0x79); ++ if (!ret) ++ ret = h2fmi_sdr_poll(fmi, b, &status); ++ if (!ret) ++ ret = h2fmi_program_status(status); ++ 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) +@@ -467,6 +882,7 @@ static int h2fmi_program_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, + ret = h2fmi_program_status(status); + writel(0, b->fmc + FMC_CE_CTRL); + h2fmi_device_reset(b, on, if_ctrl); ++done: + if (ret) { + b->failed = true; + dev_err(fmi->dev, "PPN program row %08x: status %02x, error %d\n", +@@ -672,6 +1088,23 @@ static int h2fmi_erase_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, u32 r + + 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) +@@ -688,6 +1121,7 @@ static int h2fmi_erase_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, u32 r + ret = h2fmi_cmd1(fmi, b, 0x77); + 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); +@@ -976,12 +1410,24 @@ 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 it on: if iBoot did not, the +- * state this driver would have to restore is not known. */ ++ * in DDR. Nothing here turns the clocks on. If the interface ++ * is not in DDR, the packages are reset and run in SDR. */ + 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)); + } + ++ /* 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) { ++ mutex_lock(&fmi->bus[0].lock); ++ mutex_lock_nested(&fmi->bus[1].lock, SINGLE_DEPTH_NESTING); ++ ret = h2fmi_sdr_bringup(fmi); ++ mutex_unlock(&fmi->bus[1].lock); ++ mutex_unlock(&fmi->bus[0].lock); ++ if (ret) ++ return dev_err_probe(&pdev->dev, ret, "PPN SDR bring-up failed\n"); ++ } ++ + /* Query both packages before publishing any part of the inventory. */ + for (i = 0; i < H2FMI_BUSES; i++) { + ret = h2fmi_read_geometry(fmi, &fmi->bus[i]); +diff --git a/drivers/mtd/devices/mtd-apple-h2fmi.h b/drivers/mtd/devices/mtd-apple-h2fmi.h +index 1ebcade9d..93502b3e0 100644 +--- a/drivers/mtd/devices/mtd-apple-h2fmi.h ++++ b/drivers/mtd/devices/mtd-apple-h2fmi.h +@@ -3,6 +3,7 @@ + #define MTD_APPLE_H2FMI_H + + #include ++#include + #include + #include + #include +@@ -141,6 +142,46 @@ static inline bool h2fmi_raw_page_erased(u8 status, const u8 *raw) + return status == PPN_ST_ERASED && !memchr_inv(raw, 0xff, H2FMI_PAGE_RAW); + } + ++/* ++ * 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 ++ * feature 0x180 selects the asynchronous interface, then runs at the working ++ * timing measured on the P105 (dc 2, rs 3, rh 2, ws 1, wh 0). ++ */ ++#define H2FMI_IF_CTRL_LOW_POWER 0xffff ++#define H2FMI_IF_CTRL_SDR 0x23210 ++#define H2FMI_FEATURE_POWER 0x0180 ++#define H2FMI_POWER_ASYNC 2 ++#define H2FMI_FEATURE_FIRMWARE 0x9080 ++#define H2FMI_FIRMWARE_SIZE 16 ++#define H2FMI_FEATURE_BAD_BLOCKS 0x84 ++#define H2FMI_ID_SIZE 8 ++#define H2FMI_SDR_SECTOR 1028 /* a page unit moves as four sectors */ ++ ++/* Read ID answers "PPN" and the protocol version; both packages are PPN 1.5. */ ++static inline bool h2fmi_ppn_id(const u8 *id) ++{ ++ return !memcmp(id, "PPN", 3) && id[3] == 1 && id[4] == 5; ++} ++ ++/* Feature 0x84 | cau << 8 returns one bit per block of that CAU. */ ++static inline u32 h2fmi_bad_block_bytes(const struct h2fmi_geometry *g) ++{ ++ return DIV_ROUND_UP(g->blocks, 8); ++} ++ ++static inline u16 h2fmi_bad_block_feature(unsigned int cau) ++{ ++ return H2FMI_FEATURE_BAD_BLOCKS | cau << 8; ++} ++ ++/* An SDR page read sends the full address: u16 byte count, u16 column, row. */ ++static inline void h2fmi_full_address(u32 row, u32 *addr0, u32 *addr1) ++{ ++ *addr0 = H2FMI_PAGE_RAW; ++ *addr1 = row; ++} ++ + /* CMD 79 reports ready at bit 6 and program failure at bits 0 and 4. */ + static inline int h2fmi_program_status(u8 status) + { From ad97f0002b7ebcaf7af4d3b21d476e1ec92ee85e Mon Sep 17 00:00:00 2001 From: Henrik Klee Date: Fri, 20 Nov 2026 06:27:47 +0800 Subject: [PATCH 4/7] kernel: P105 NAND: survive a failed program instead of stopping A failed program stopped the P105's NAND writer and every later I/O on that bus. Patch 0021 (authored by rzxvx) ports Cascadia's session give-up: the failed block is abandoned, its live pages move to a new block, and the write completes there; after eight failures in a session the writer still stops. 0020 lets H2FMI reset the packages after a failed transaction instead of refusing all further I/O, which the give-up needs because every superblock spans both buses. Torn pages still stop the writer until the next patch. KUnit: 87 cases pass (the old stop-on-failure cases now assert the give-up). Untested on hardware. Assisted-by: LLM --- ...Reset-the-packages-after-a-failed-tr.patch | 251 +++++++ ...-Give-up-a-block-whose-program-fails.patch | 659 ++++++++++++++++++ 2 files changed, 910 insertions(+) create mode 100644 kernel/patches/armv7/mtd/0020-mtd-apple-h2fmi-Reset-the-packages-after-a-failed-tr.patch create mode 100644 kernel/patches/armv7/mtd/0021-mtd-apple-sftl-Give-up-a-block-whose-program-fails.patch diff --git a/kernel/patches/armv7/mtd/0020-mtd-apple-h2fmi-Reset-the-packages-after-a-failed-tr.patch b/kernel/patches/armv7/mtd/0020-mtd-apple-h2fmi-Reset-the-packages-after-a-failed-tr.patch new file mode 100644 index 00000000..6831ad63 --- /dev/null +++ b/kernel/patches/armv7/mtd/0020-mtd-apple-h2fmi-Reset-the-packages-after-a-failed-tr.patch @@ -0,0 +1,251 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Henrik Klee +Date: Fri, 20 Nov 2026 06:14:57 +0800 +Subject: [PATCH 20/21] mtd: apple-h2fmi: Reset the packages after a failed + transaction + +Any failed H2FMI transaction marks its bus failed for the life of the +driver instance. That keeps a writer from guessing after an uncertain +program, but it also leaves nothing to recover with: a translation +layer that wants to give up one failed block and move its data to +another (the next patch) has no bus left to program on, because every +superblock spans both buses. + +iBEC recovers from a general error by resetting the packages and +running the bring-up again, and Cascadia's driver does the same after a +failed read or program. Do that here: a failed transaction still +returns its error and leaves the outcome to the caller, but the next +transaction on either bus first resets both packages through the SDR +bring-up and checks that their parameters still describe the geometry +in use. The packages then stay in SDR. A failed reset, or more than +eight resets in one driver instance, stops all I/O as before. + +This changes the contract the H2FMI provider gave its users since the +first program patch: I/O after a failure is no longer refused. The SFTL +writer keeps its own failure state; raw MTD programs still only write +pages that read back erased and verify each by readback. + +Assisted-by: LLM +--- + drivers/mtd/devices/mtd-apple-h2fmi.c | 95 +++++++++++++++++++++++---- + 1 file changed, 82 insertions(+), 13 deletions(-) + +diff --git a/drivers/mtd/devices/mtd-apple-h2fmi.c b/drivers/mtd/devices/mtd-apple-h2fmi.c +index 947158ebd..6431bd7e7 100644 +--- a/drivers/mtd/devices/mtd-apple-h2fmi.c ++++ b/drivers/mtd/devices/mtd-apple-h2fmi.c +@@ -25,7 +25,8 @@ + * + * Pages are read and programmed whole, data and metadata together. The + * raw MTD devices provide no erase. A page is only programmed when it +- * reads back erased, and every program is read back and compared. ++ * reads back erased, and every program is read back and compared. After a ++ * failed transaction the packages are reset before the next one. + * Logical-address translation and allocation belong to the FTL above. + */ + +@@ -116,6 +117,9 @@ struct h2fmi_bus { + bool failed; /* block further I/O in this driver instance */ + }; + ++/* Resets after failed transactions in one driver instance. */ ++#define H2FMI_MAX_RESETS 8 ++ + struct h2fmi_die { + struct h2fmi *fmi; + u8 bus; +@@ -135,6 +139,8 @@ struct h2fmi { + struct platform_device *sftl; + struct apple_ppn_ops ppn_ops; + struct apple_ppn_access access; ++ bool reset_needed; /* a transaction failed; reset before the next */ ++ unsigned int resets; + }; + + /* +@@ -573,8 +579,9 @@ static int h2fmi_sdr_id(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *id) + * parameters, the asynchronous power state on each CE once both are reset + * (without it every array read fails), the working timing, the firmware + * version and every CAU's bad-block table. Caller holds both bus locks. ++ * After a failure, expect is the geometry already in use. + */ +-static int h2fmi_sdr_bringup(struct h2fmi *fmi) ++static int h2fmi_sdr_bringup(struct h2fmi *fmi, const struct h2fmi_geometry *expect) + { + struct h2fmi_geometry g; + u8 id[H2FMI_ID_SIZE], firmware[H2FMI_FIRMWARE_SIZE]; +@@ -615,6 +622,9 @@ static int h2fmi_sdr_bringup(struct h2fmi *fmi) + ret = h2fmi_parse_geometry(fmi->bus[0].page, H2FMI_PARAMS_SIZE, &g); + if (ret) + return ret; ++ /* After a failure, the parameters must describe the package in use. */ ++ if (expect && memcmp(expect, &g, sizeof(g))) ++ return -ENODEV; + for (i = 0; i < H2FMI_BUSES; i++) { + ret = h2fmi_sdr_set(fmi, &fmi->bus[i], H2FMI_FEATURE_POWER, H2FMI_POWER_ASYNC); + if (ret) { +@@ -646,6 +656,55 @@ static int h2fmi_sdr_bringup(struct h2fmi *fmi) + return 0; + } + ++/* ++ * A failed transaction leaves the package state unknown. iBEC and Cascadia ++ * recover by resetting the packages and running the bring-up again; the ++ * failed operation itself is still reported. Caller holds b->lock. ++ */ ++static void h2fmi_fail(struct h2fmi *fmi) ++{ ++ WRITE_ONCE(fmi->reset_needed, true); ++} ++ ++static int h2fmi_recover(struct h2fmi *fmi) ++{ ++ unsigned int i; ++ int ret = 0; ++ ++ mutex_lock(&fmi->bus[0].lock); ++ 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) { ++ ret = fmi->resets++ < H2FMI_MAX_RESETS ? ++ h2fmi_sdr_bringup(fmi, &fmi->bus[0].geometry) : -EIO; ++ for (i = 0; ret && i < H2FMI_BUSES; i++) ++ fmi->bus[i].failed = true; ++ if (ret) ++ dev_err(fmi->dev, "PPN reset %u failed (%d), stopping\n", fmi->resets, ret); ++ else ++ dev_warn(fmi->dev, "PPN packages reset after a failed transaction (%u)\n", ++ fmi->resets); ++ fmi->reset_needed = false; ++ } ++ mutex_unlock(&fmi->bus[1].lock); ++ mutex_unlock(&fmi->bus[0].lock); ++ return ret; ++} ++ ++/* 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); ++ ++ if (ret) ++ return ret; ++ } ++ mutex_lock(&b->lock); ++ return 0; ++} ++ + /* Caller holds b->lock. A page read in SDR, or the parameters. */ + static int h2fmi_sdr_read(struct h2fmi *fmi, struct h2fmi_bus *b, u8 op, u32 row, + u8 *buffer, u32 length, u8 *status) +@@ -702,7 +761,7 @@ static int h2fmi_read_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, + if (b->sdr) { + ret = h2fmi_sdr_read(fmi, b, op, address, buffer, length, status); + if (ret) +- b->failed = true; ++ h2fmi_fail(fmi); + return ret; + } + on = readl(b->fmc + FMC_ON); +@@ -729,7 +788,7 @@ static int h2fmi_read_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, + writel(0, b->fmc + FMC_CE_CTRL); + h2fmi_device_reset(b, on, if_ctrl); + if (ret || end_ret) { +- b->failed = true; ++ h2fmi_fail(fmi); + return ret ? ret : end_ret; + } + return 0; +@@ -832,7 +891,7 @@ static int h2fmi_write_status(struct h2fmi *fmi, struct h2fmi_bus *b, u8 *status + return h2fmi_poll_status(fmi, b, status); + } + +-/* Caller holds the bus lock. A failed mutation permanently stops this bus. */ ++/* Caller holds the bus lock. A failed mutation resets the packages first. */ + static int h2fmi_program_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, + u32 row, const u8 *raw) + { +@@ -884,7 +943,7 @@ static int h2fmi_program_transaction(struct h2fmi *fmi, struct h2fmi_bus *b, + h2fmi_device_reset(b, on, if_ctrl); + done: + if (ret) { +- b->failed = true; ++ h2fmi_fail(fmi); + dev_err(fmi->dev, "PPN program row %08x: status %02x, error %d\n", + row, status, ret); + } +@@ -928,7 +987,11 @@ static int h2fmi_program_page(struct h2fmi *fmi, struct h2fmi_bus *b, + if (!expected) + return -ENOMEM; + h2fmi_join_page(expected, data, oob); +- mutex_lock(&b->lock); ++ 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) +@@ -944,7 +1007,7 @@ static int h2fmi_program_page(struct h2fmi *fmi, struct h2fmi_bus *b, + b->page, H2FMI_PAGE_RAW, &status); + if (ret || status != PPN_ST_GOOD || + memcmp(b->page, expected, H2FMI_PAGE_RAW)) { +- b->failed = true; ++ h2fmi_fail(fmi); + ret = ret ? ret : -EIO; + dev_err(fmi->dev, "PPN readback row %08x: status %02x, error %d\n", + row, status, ret); +@@ -1007,7 +1070,9 @@ static int h2fmi_read_page_at(struct mtd_info *mtd, loff_t from, + if (ret) + return ret; + +- mutex_lock(&b->lock); ++ ret = h2fmi_lock(fmi, b); ++ if (ret) ++ return ret; + /* Supported PPN 1.5 packages require four row cycles, even when the + * fourth byte is zero. This is independent of the geometry's width. + */ +@@ -1049,7 +1114,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); +- mutex_lock(&b->lock); ++ ret = h2fmi_lock(fmi, b); ++ if (ret) ++ return ret; + ret = h2fmi_read_transaction(fmi, b, 0x0a, 0x37, row, 4, + b->page, H2FMI_PAGE_RAW, status); + if (!ret && h2fmi_page_status(*status) >= 0) { +@@ -1147,7 +1214,9 @@ static int h2fmi_ppn_erase(void *priv, unsigned int bus, unsigned int cau, + if (ret) + return ret; + +- mutex_lock(&b->lock); ++ 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, +@@ -1159,7 +1228,7 @@ static int h2fmi_ppn_erase(void *priv, unsigned int bus, unsigned int cau, + } + } + if (ret) +- b->failed = true; ++ h2fmi_fail(fmi); + mutex_unlock(&b->lock); + return ret; + } +@@ -1421,7 +1490,7 @@ static int h2fmi_probe(struct platform_device *pdev) + readl(fmi->bus[1].fmc + FMC_ON) != FMC_ON_DDR) { + mutex_lock(&fmi->bus[0].lock); + mutex_lock_nested(&fmi->bus[1].lock, SINGLE_DEPTH_NESTING); +- ret = h2fmi_sdr_bringup(fmi); ++ ret = h2fmi_sdr_bringup(fmi, NULL); + mutex_unlock(&fmi->bus[1].lock); + mutex_unlock(&fmi->bus[0].lock); + if (ret) diff --git a/kernel/patches/armv7/mtd/0021-mtd-apple-sftl-Give-up-a-block-whose-program-fails.patch b/kernel/patches/armv7/mtd/0021-mtd-apple-sftl-Give-up-a-block-whose-program-fails.patch new file mode 100644 index 00000000..e3b23282 --- /dev/null +++ b/kernel/patches/armv7/mtd/0021-mtd-apple-sftl-Give-up-a-block-whose-program-fails.patch @@ -0,0 +1,659 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: rzxvx +Date: Fri, 20 Nov 2026 06:25:40 +0800 +Subject: [PATCH 21/21] mtd: apple-sftl: Give up a block whose program fails + +A failed program stops the append writer and, with H2FMI, every later +I/O on the bus. Cascadia's writer instead gives the superblock up for +the session and carries on, and that path ran on a 16 GB P105 under +injected program and erase failures with iOS clean afterwards. + +Port it into the append writer. On a failed data or summary program: + +- program nothing more into the block and do not close it; +- move every logical page the map still places there to a new append + block with a fresh sequence, keeping the record type and, for + relocated user data, the user epoch, as reclamation does; the failed + request follows with the highest sequences; +- a failed page that reads back erased consumed nothing, so its + sequences are offered again and the journal stays contiguous; one + that reads back exactly as programmed keeps its records and + sequences; +- a further failure gives up the new block as well and the move starts + over from the map, up to eight failures per session; without blank + blocks the request returns -ENOSPC and the move resumes with the next + request. + +A torn page still stops the writer, because a fresh load rejects it; +the next patch handles torn pages at load. The VFL is never touched: a +really bad block meets its next failure under iOS, which retires it. +Relocation inside reclamation keeps its own stop-on-failure rule. + +Cascadia also records the given-up superblock as awaiting erase with +nothing valid in its next context commit. The append writer writes no +checkpoint on the P105, so the block stays an open block on the medium +whose records are all superseded. + +The KUnit tests that asserted the old stop-on-failure behaviour now +assert the give-up: a blank failed page, a block with live pages, a +failure on every block until no blank block is left, a page that landed +despite a failed completion, and failed summary pages that move all 480 +pages of a full block. + +Ported from Cascadia (https://github.com/rzxvx/Project-Cascadia) commit +c2958e1 ("a5: FTL writer: survive program and erase failures (spec +4.9)"), file sftl_write.c (mark_bad, take_spare, frontier_fail) and +devices/a5/docs/research/p105-nand-spec.md section 4.9, as of Cascadia +ad28ba4. + +Assisted-by: LLM +--- + Documentation/driver-api/mtd/apple-sftl.rst | 20 +- + drivers/mtd/apple-sftl-core.c | 289 +++++++++++++++++--- + drivers/mtd/apple-sftl-test.c | 126 +++++++-- + 3 files changed, 369 insertions(+), 66 deletions(-) + +diff --git a/Documentation/driver-api/mtd/apple-sftl.rst b/Documentation/driver-api/mtd/apple-sftl.rst +index 9661f0bde..0a8c5d624 100644 +--- a/Documentation/driver-api/mtd/apple-sftl.rst ++++ b/Documentation/driver-api/mtd/apple-sftl.rst +@@ -87,8 +87,24 @@ The recovered allocation floor can exceed the last visible journal record. + This implementation retains its contiguous journal replay rule, so a mismatch + keeps the disk read-only and returns ``-EOPNOTSUPP`` before any program. + Native forward-gap handling requires a separate recovery change with format- +-specific fixtures. A program or map-publication error stops subsequent I/O; a +-fresh loader must determine which complete records reached the medium. ++specific fixtures. A map-publication error stops subsequent I/O; a fresh ++loader must determine which complete records reached the medium. ++ ++Program failures ++---------------- ++ ++A failed data or summary program gives its block up for the session, as ++Cascadia's writer does: nothing more is programmed into it and it is not ++closed. Every logical page the map still places in that block moves to a new ++append block with a fresh sequence, keeping its type and, for relocated user ++data, its user epoch; the failed request follows. A failed page that reads ++back erased consumed nothing, so its sequences are offered again; one that ++reads back exactly as programmed keeps its records and sequences. A torn page ++stops the writer. A further failure gives up the new block too; after eight ++failures in one session the writer stops. The VFL is never changed: a really ++bad block fails again under iOS, which retires it. Without blank blocks the ++request returns ``-ENOSPC`` and the move resumes with the next request. ++Relocation during reclamation still stops on any failure. + + The block frontend preserves untouched sectors in partial 4 KiB updates and + groups up to four logical pages per program. Every acknowledged write has +diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c +index 9e0e5ed72..8bed81b59 100644 +--- a/drivers/mtd/apple-sftl-core.c ++++ b/drivers/mtd/apple-sftl-core.c +@@ -9,6 +9,7 @@ + * or device data. Unsupported formats fail before a block device is created. + */ + #include ++#include + #include + #include + #include +@@ -49,6 +50,8 @@ enum sftl_block_role { + }; + + #define SFTL_FOOTER_CHUNKS 32U ++#define SFTL_FAIL_MAX 8U /* program failures per session before the writer stops */ ++#define SFTL_RETRY 1 /* the block was given up: offer the page again */ + #define SFTL_CLAIM_TIMEOUT (500U * HZ) + #define SFTL_FOOTER_BYTES (SFTL_FOOTER_CHUNKS * SFTL_CHUNK) + #define SFTL_GC_MAP_BYTES (8U * 1024 * 1024) /* per map, on the measured 512 MiB P105 */ +@@ -153,6 +156,14 @@ struct apple_sftl { + bool writer_prepared; + u8 *page; + u8 oob[APPLE_PPN_OOB_SIZE]; ++ /* Blocks given up after a failed program in this session. Their live ++ * data moves to the append point; they are never programmed again. ++ */ ++ DECLARE_BITMAP(abandoned, SFTL_MAX_BLOCKS); ++ u32 failures; ++ bool evacuate; ++ 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; + }; +@@ -1763,6 +1774,8 @@ void apple_sftl_free(struct apple_sftl *sftl) + return; + sftl_clear_runs(sftl); + kvfree(sftl->footer); ++ kvfree(sftl->stage); ++ kvfree(sftl->move); + kvfree(sftl->context.items); + kvfree(sftl->closed_user_seq); + kfree(sftl->page); +@@ -1827,7 +1840,9 @@ static int sftl_writer_prepare(struct apple_sftl *sftl) + if (!sftl->ppn->ops->program_page) + return -EROFS; + sftl->footer = kvzalloc(SFTL_FOOTER_BYTES, GFP_KERNEL); +- if (!sftl->footer) ++ 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) || +@@ -2741,6 +2756,9 @@ void apple_sftl_set_checkpoint_ops(struct apple_sftl *sftl, + } + 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 int sftl_close_block(struct apple_sftl *sftl) + { + u64 span = sftl->sequence - sftl->append_base + 1; +@@ -2755,16 +2773,17 @@ static int sftl_close_block(struct apple_sftl *sftl) + put_unaligned_le16(SFTL_FOOTER_CHUNKS, meta + 12); + put_unaligned_le16(0xffff, meta + 14); + for (chunk = 0; chunk < 4; chunk++) +- memcpy(sftl->oob + chunk * SFTL_META, meta, SFTL_META); ++ memcpy(sftl->stage_oob + chunk * SFTL_META, meta, SFTL_META); + for (index = 0; index < SFTL_FOOTER_CHUNKS / 4; index++) { + u32 address = sftl->append_block * sftl_stride(sftl) + + sftl->append_capacity + index * 4; ++ const u8 *data = sftl->footer + index * APPLE_PPN_PAGE_SIZE; + +- ret = sftl_program_address(sftl, address, +- sftl->footer + index * APPLE_PPN_PAGE_SIZE, +- sftl->oob); ++ 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 ret; ++ return sftl_give_up(sftl, address, data, sftl->stage_oob, ret) == SFTL_RETRY ? ++ 0 : -EIO; + } + ret = sftl_remember_user_seq(sftl, sftl->append_block, sftl->footer, sftl->footer_runs); + if (ret) +@@ -2773,11 +2792,225 @@ static int sftl_close_block(struct apple_sftl *sftl) + return 0; + } + ++/* ++ * Program failures (Cascadia's specification, section 4.9): program nothing ++ * more into the block in this session and do not close it. Every live page ++ * the map places there moves to the append point with a new sequence, ++ * keeping its type and, for relocated user data, its user epoch, as ++ * reclamation does. The VFL is never touched; a really bad block meets its ++ * next failure under iOS, which retires it. ++ * ++ * A failed page that reads back erased consumed nothing, so its sequences ++ * are offered again. One that reads back exactly as programmed holds valid ++ * records, so its sequences stay used. Anything else is a torn page, which ++ * a fresh load rejects; the writer stops. ++ */ ++static int sftl_give_up(struct apple_sftl *sftl, u32 address, const u8 *data, ++ const u8 *oob, int err) ++{ ++ u32 block = sftl->append_block; ++ unsigned int chunk; ++ bool blank, landed; ++ int ret; ++ ++ if (err == -EINVAL || err == -ERANGE || ++sftl->failures > SFTL_FAIL_MAX) ++ goto stop; ++ ret = sftl_read_address(sftl, address, &chunk); ++ blank = !ret && sftl_erased(sftl->oob, sizeof(sftl->oob)) && ++ sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE); ++ landed = !ret && !memcmp(sftl->oob, oob, sizeof(sftl->oob)) && ++ !memcmp(sftl->page, data, APPLE_PPN_PAGE_SIZE); ++ if (!blank && !landed) ++ goto stop; ++ if (landed && oob[0] != 0x1c) { ++ sftl->sequence += 4; ++ sftl->journal_sequence = sftl->sequence; ++ } ++ dev_warn(sftl->ppn->dev, "program at %#x failed (%d): block %u given up\n", ++ address, err, block); ++ __set_bit(block, sftl->abandoned); ++ sftl->append_block = U32_MAX; ++ sftl->evacuate = true; ++ return SFTL_RETRY; ++stop: ++ sftl->failed = true; ++ return err; ++} ++ ++/* Stamp a page for the append point. A relocated type-1 user page keeps ++ * 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) ++{ ++ 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] && ++ get_unaligned_le32(meta + 8) < sftl->geo->lpages; ++ ++ put_unaligned_le64(sequence << 16 | get_unaligned_le16(meta), meta); ++ if (!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. ++ */ ++static int sftl_append_once(struct apple_sftl *sftl, const u8 *page, u8 *oob, bool relocated) ++{ ++ unsigned int chunk; ++ u32 address; ++ int ret; ++ ++ 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; ++ } ++ 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) { ++ ret = sftl_close_block(sftl); ++ if (ret) ++ sftl->failed = true; ++ } ++ 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) ++{ ++ 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)) ++ continue; ++ for (a = from; a <= to; a++) { ++ if (keys) ++ keys[n] = run->start + a - first; ++ n++; ++ } ++ } ++ } ++ if (pass || !n) ++ break; ++ keys = kvmalloc_array(n, sizeof(*keys), GFP_NOIO); ++ if (!keys) ++ return -ENOMEM; ++ n = 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) ++{ ++ 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) ++ return -EBADMSG; ++ ret = sftl_read_address(sftl, run->provider + key - run->start, &chunk); ++ if (ret) ++ return ret; ++ meta = sftl->oob + chunk * SFTL_META; ++ if ((meta[0] != 1 && meta[0] != 2) || get_unaligned_le32(meta + 8) != key) ++ 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) ++{ ++ u32 *keys = NULL, count = 0, i; ++ int ret = 0; ++ ++ 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; ++} ++ ++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); ++ } while (ret == SFTL_RETRY); ++ if (!ret) ++ ret = sftl_evacuate(sftl); ++ return ret; ++} ++ + int apple_sftl_write(struct apple_sftl *sftl, u32 logical_page, + const u8 *data, unsigned int count) + { +- u64 first_sequence; +- u32 address; + unsigned int chunk; + int ret; + +@@ -2796,47 +3029,13 @@ int apple_sftl_write(struct apple_sftl *sftl, u32 logical_page, + ret = sftl_writer_prepare(sftl); + if (ret) + goto out; +- if (sftl->append_block == U32_MAX) { +- ret = sftl_claim_block(sftl); +- if (ret) +- goto out; +- } +- if (sftl->sequence > SFTL_SEQUENCE - 4) { +- ret = -EOVERFLOW; +- goto out; +- } +- address = sftl->append_block * sftl_stride(sftl) + sftl->append_position; +- first_sequence = sftl->sequence + 1; + for (chunk = 0; chunk < 4; chunk++) { + unsigned int index = min(chunk, count - 1); + +- memcpy(sftl->page + chunk * SFTL_CHUNK, +- data + index * SFTL_CHUNK, SFTL_CHUNK); +- sftl_data_meta(sftl->oob + chunk * SFTL_META, +- first_sequence + chunk, logical_page + index); ++ 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); + } +- ret = sftl_program_address(sftl, address, sftl->page, sftl->oob); +- if (ret) +- goto failed; +- for (chunk = 0; chunk < 4; chunk++) { +- u32 key = logical_page + min(chunk, count - 1); +- +- ret = sftl_replace(sftl, key, 1, address + chunk); +- if (ret) +- goto failed; +- sftl_append_summary(sftl, sftl->oob + chunk * SFTL_META); +- } +- sftl->sequence += 4; +- sftl->journal_sequence = sftl->sequence; +- sftl->append_position += 4; +- if (sftl->append_position == sftl->append_capacity) { +- ret = sftl_close_block(sftl); +- if (ret) +- goto failed; +- } +- goto out; +-failed: +- sftl->failed = true; ++ ret = sftl_append(sftl, sftl->stage, sftl->stage_oob, false); + out: + mutex_unlock(&sftl->lock); + return ret; +diff --git a/drivers/mtd/apple-sftl-test.c b/drivers/mtd/apple-sftl-test.c +index c7f1df4c8..bc3ea9f8c 100644 +--- a/drivers/mtd/apple-sftl-test.c ++++ b/drivers/mtd/apple-sftl-test.c +@@ -70,6 +70,7 @@ struct sftl_fixture { + u16 vfl_tail_marker; + unsigned int programs; + unsigned int fail_program; ++ unsigned int fail_from; /* every program from this one fails */ + unsigned int tear_program; + unsigned int program_outside; + bool uncertain_program; +@@ -435,7 +436,8 @@ static int sftl_test_program_page(void *priv, unsigned int bus, unsigned int cau + if (sftl_test_written(f, slot, lane, page)) + return -EEXIST; + failure = f->programs == f->fail_program; +- if (failure && !f->uncertain_program) ++ if ((failure && !f->uncertain_program) || ++ (f->fail_from && f->programs >= f->fail_from)) + return -EIO; + if (!f->written[slot]) { + f->written[slot] = kunit_kcalloc(f->test, 16 * 128, +@@ -1037,37 +1039,112 @@ static void sftl_test_append_replay_full_lanes(struct kunit *test) + apple_sftl_free(sftl); + } + +-static void sftl_test_append_failure_stops_io(struct kunit *test) ++/* A failed program gives the block up for the session (Cascadia's ++ * section 4.9). Nothing reached the page, so its sequences are offered ++ * again at a fresh block and the journal stays contiguous. ++ */ ++static void sftl_test_append_failure_gives_up_block(struct kunit *test) + { + struct sftl_fixture *f = sftl_test_fixture(test, SFTL_NO_FAULT); + struct apple_sftl *sftl = NULL; ++ struct apple_sftl_info info; + u8 *data = kunit_kmalloc(test, 4096, GFP_KERNEL); +- unsigned int programs; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, data); + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); + f->fail_program = 1; + memset(data, 'F', 4096); +- KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, TEST_APPEND_BASE, data, 1), -EIO); +- programs = f->programs; +- KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, TEST_APPEND_BASE, data, 1), -EIO); +- KUNIT_EXPECT_EQ(test, apple_sftl_flush(sftl), -EIO); +- KUNIT_EXPECT_EQ(test, apple_sftl_read(sftl, 0, data), -EIO); +- KUNIT_EXPECT_EQ(test, f->programs, programs); ++ KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, TEST_APPEND_BASE, data, 1), 0); ++ KUNIT_EXPECT_EQ(test, f->programs, 2U); + KUNIT_EXPECT_EQ(test, f->program_outside, 0U); ++ KUNIT_EXPECT_NULL(test, sftl_test_written(f, 0, 0, 0)); ++ KUNIT_EXPECT_NOT_NULL(test, sftl_test_written(f, 1, 0, 0)); ++ KUNIT_EXPECT_EQ(test, apple_sftl_flush(sftl), 0); ++ apple_sftl_get_info(sftl, &info); ++ KUNIT_EXPECT_EQ(test, info.sequence, TEST_APPEND_FIRST + 3); ++ KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, TEST_APPEND_BASE, data), 0); ++ sftl_test_expect_fill(test, data, 'F'); + apple_sftl_free(sftl); + sftl = NULL; + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ apple_sftl_get_info(sftl, &info); ++ KUNIT_EXPECT_EQ(test, info.journal_sequence, TEST_APPEND_FIRST + 3); + KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, TEST_APPEND_BASE, data), 0); +- sftl_test_expect_fill(test, data, 0); ++ sftl_test_expect_fill(test, data, 'F'); ++ apple_sftl_free(sftl); ++} ++ ++/* Live pages already in the given-up block move ahead of the failed one. */ ++static void sftl_test_append_failure_moves_live_pages(struct kunit *test) ++{ ++ struct sftl_fixture *f = sftl_test_fixture(test, SFTL_NO_FAULT); ++ struct apple_sftl *sftl = NULL; ++ struct apple_sftl_info info; ++ u8 *data = kunit_kmalloc(test, 16384, GFP_KERNEL); ++ unsigned int program; ++ ++ KUNIT_ASSERT_NOT_NULL(test, f); ++ KUNIT_ASSERT_NOT_NULL(test, data); ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ f->fail_program = 4; ++ for (program = 0; program < 4; program++) { ++ memset(data, 'a' + program, 16384); ++ KUNIT_ASSERT_EQ(test, apple_sftl_write(sftl, TEST_APPEND_BASE + program * 4, ++ data, 4), 0); ++ } ++ /* Three moved pages, then the failed one, at the next block. */ ++ KUNIT_EXPECT_EQ(test, f->programs, 8U); ++ KUNIT_EXPECT_NOT_NULL(test, sftl_test_written(f, 1, 0, 3)); ++ KUNIT_EXPECT_NULL(test, sftl_test_written(f, 1, 0, 4)); ++ apple_sftl_get_info(sftl, &info); ++ KUNIT_EXPECT_EQ(test, info.sequence, TEST_APPEND_FIRST - 1 + 7 * 4); ++ apple_sftl_free(sftl); ++ sftl = NULL; ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ for (program = 0; program < 16; program++) { ++ KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, TEST_APPEND_BASE + program, data), 0); ++ sftl_test_expect_fill(test, data, 'a' + program / 4); ++ } ++ apple_sftl_free(sftl); ++} ++ ++/* Each block that fails is given up; without blank blocks the request fails, ++ * the data already written stays readable and a fresh load sees no gap. ++ */ ++static void sftl_test_append_failures_exhaust_blocks(struct kunit *test) ++{ ++ struct sftl_fixture *f = sftl_test_fixture(test, SFTL_NO_FAULT); ++ struct apple_sftl *sftl = NULL; ++ u8 *data = kunit_kmalloc(test, 4096, GFP_KERNEL); ++ ++ KUNIT_ASSERT_NOT_NULL(test, f); ++ KUNIT_ASSERT_NOT_NULL(test, data); ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ memset(data, 'E', 4096); ++ KUNIT_ASSERT_EQ(test, apple_sftl_write(sftl, TEST_APPEND_BASE, data, 1), 0); ++ f->fail_from = 2; ++ KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, TEST_APPEND_BASE + 1, data, 1), -ENOSPC); ++ KUNIT_EXPECT_EQ(test, f->programs, 4U); ++ KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, TEST_APPEND_BASE, data), 0); ++ sftl_test_expect_fill(test, data, 'E'); ++ apple_sftl_free(sftl); ++ sftl = NULL; ++ f->fail_from = 0; ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, TEST_APPEND_BASE, data), 0); ++ sftl_test_expect_fill(test, data, 'E'); + apple_sftl_free(sftl); + } + ++/* The page landed although completion failed: its records stay valid and ++ * their sequences are not offered again. ++ */ + static void sftl_test_append_uncertain_program_replays(struct kunit *test) + { + struct sftl_fixture *f = sftl_test_fixture(test, SFTL_NO_FAULT); + struct apple_sftl *sftl = NULL; ++ struct apple_sftl_info info; + u8 *data = kunit_kmalloc(test, 4096, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, f); +@@ -1076,12 +1153,16 @@ static void sftl_test_append_uncertain_program_replays(struct kunit *test) + f->fail_program = 1; + f->uncertain_program = true; + memset(data, 'U', 4096); +- KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, TEST_APPEND_BASE, data, 1), -EIO); +- KUNIT_EXPECT_EQ(test, apple_sftl_flush(sftl), -EIO); +- KUNIT_EXPECT_EQ(test, f->programs, 1U); ++ KUNIT_EXPECT_EQ(test, apple_sftl_write(sftl, TEST_APPEND_BASE, data, 1), 0); ++ KUNIT_EXPECT_EQ(test, apple_sftl_flush(sftl), 0); ++ KUNIT_EXPECT_EQ(test, f->programs, 2U); ++ apple_sftl_get_info(sftl, &info); ++ KUNIT_EXPECT_EQ(test, info.sequence, TEST_APPEND_FIRST + 7); + apple_sftl_free(sftl); + sftl = NULL; + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ apple_sftl_get_info(sftl, &info); ++ KUNIT_EXPECT_EQ(test, info.journal_sequence, TEST_APPEND_FIRST + 7); + KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, TEST_APPEND_BASE, data), 0); + sftl_test_expect_fill(test, data, 'U'); + apple_sftl_free(sftl); +@@ -1090,9 +1171,9 @@ static void sftl_test_append_uncertain_program_replays(struct kunit *test) + static void sftl_test_append_interrupted_footer_replays(struct kunit *test) + { + static const struct { +- unsigned int program; ++ unsigned int program, total; + bool uncertain; +- } stop[] = {{121, false}, {122, false}, {128, false}, {128, true}}; ++ } stop[] = {{121, 249, false}, {122, 250, false}, {128, 256, false}, {128, 256, true}}; + unsigned int index; + + for (index = 0; index < ARRAY_SIZE(stop); index++) { +@@ -1105,9 +1186,14 @@ static void sftl_test_append_interrupted_footer_replays(struct kunit *test) + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); + f->fail_program = stop[index].program; + f->uncertain_program = stop[index].uncertain; +- KUNIT_EXPECT_EQ(test, sftl_test_fill_append(sftl, data), -EIO); +- KUNIT_EXPECT_EQ(test, f->programs, stop[index].program); +- KUNIT_EXPECT_EQ(test, apple_sftl_flush(sftl), -EIO); ++ /* A failed summary page gives the block up: 480 live pages move ++ * to the next block, which closes with its own summary. ++ */ ++ KUNIT_EXPECT_EQ(test, sftl_test_fill_append(sftl, data), 0); ++ KUNIT_EXPECT_EQ(test, f->programs, stop[index].total); ++ KUNIT_EXPECT_EQ(test, apple_sftl_flush(sftl), 0); ++ KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, TEST_APPEND_BASE + 479, data), 0); ++ sftl_test_expect_fill(test, data, 120); + apple_sftl_free(sftl); + sftl = NULL; + KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); +@@ -3497,7 +3583,9 @@ static struct kunit_case apple_sftl_cases[] = { + KUNIT_CASE(sftl_test_append_replay_open), + KUNIT_CASE(sftl_test_append_replay_closed), + KUNIT_CASE(sftl_test_append_replay_full_lanes), +- KUNIT_CASE(sftl_test_append_failure_stops_io), ++ KUNIT_CASE(sftl_test_append_failure_gives_up_block), ++ KUNIT_CASE(sftl_test_append_failure_moves_live_pages), ++ KUNIT_CASE(sftl_test_append_failures_exhaust_blocks), + KUNIT_CASE(sftl_test_append_uncertain_program_replays), + KUNIT_CASE(sftl_test_append_interrupted_footer_replays), + KUNIT_CASE(sftl_test_append_torn_metadata_rejected), From b19a3301760fc43047aeb48a6fd40da03b81c4a1 Mon Sep 17 00:00:00 2001 From: Henrik Klee Date: Fri, 20 Nov 2026 06:36:04 +0800 Subject: [PATCH 5/7] kernel: P105 NAND: load a medium with a torn page and move off it A torn page at the end of an open block made the whole P105 medium unreadable. Patch 0022 (authored by rzxvx) ports Cascadia's give_up_torn: the load skips that one page and its four sequences, and the first write moves the block's live pages elsewhere. Only malformed metadata on the block's last programmed page counts as torn; read errors and unknown statuses still stop the load, as #93 decided. KUnit: 89 cases pass. Untested on hardware. Assisted-by: LLM --- ...tl-Give-up-a-torn-open-block-at-load.patch | 496 ++++++++++++++++++ 1 file changed, 496 insertions(+) create mode 100644 kernel/patches/armv7/mtd/0022-mtd-apple-sftl-Give-up-a-torn-open-block-at-load.patch diff --git a/kernel/patches/armv7/mtd/0022-mtd-apple-sftl-Give-up-a-torn-open-block-at-load.patch b/kernel/patches/armv7/mtd/0022-mtd-apple-sftl-Give-up-a-torn-open-block-at-load.patch new file mode 100644 index 00000000..cbc8164b --- /dev/null +++ b/kernel/patches/armv7/mtd/0022-mtd-apple-sftl-Give-up-a-torn-open-block-at-load.patch @@ -0,0 +1,496 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: rzxvx +Date: Fri, 20 Nov 2026 06:31:56 +0800 +Subject: [PATCH] mtd: apple-sftl: Give up a torn open block at load + +A program that fails or is cut short can leave a torn page at the end of +an open block. The loader rejects any malformed record, so the whole +medium becomes unreadable: Cascadia met exactly that on 2026-11-16, when +a user-space tool reset the controller during a program. Its fix, +give_up_torn, skips such a page at mount and gives the superblock up +before the writer continues. + +Port it: + +- at load, accept one torn page per open block when it is the block's + last programmed page: status good with metadata that is not a record, + or erased status over programmed bytes, including a torn first page; +- let the journal miss exactly that page's four sequences, after the + last record before it, and reserve them when nothing follows; +- before the first write, give every torn block up like a failed one, + moving its live pages to the append point; +- a torn data page in a failed program is now given up too, keeping its + four sequences used. + +Read errors, refresh and unknown statuses still stop recovery, as does +a torn page followed by another programmed page and a torn summary. +Cascadia's walk skips any page that does not read with a good status; +here only malformed metadata counts, because #93 rejects unknown +statuses deliberately and what a cut-short PPN program reads back as +has not been observed. + +Cascadia also lists the superblock as awaiting erase in its next +commit, so iOS does not program into it. The append writer writes no +checkpoint on the P105; the torn block stays an open block. + +KUnit: the torn-metadata case now expects the data page to be given up +and reloaded; new cases cover a torn page left by something else, the +move at the first write, a second reload with the hole in the middle, +and a torn page followed by another. The relocation case that corrupted +the landing block's last page now corrupts the page before it, which is +still rejected. + +Ported from Cascadia (https://github.com/rzxvx/Project-Cascadia) commits +7eaef71 ("a5: FTL: give up an SB with a torn page at writer start; +recovery module") and 131da0a ("a5: NAND: incident of 2026-11-16 and +the recovery procedure"), files sftl_mount.c (replay walk) and +sftl_write.c (give_up_torn), as of Cascadia ad28ba4. + +Assisted-by: LLM +--- + Documentation/driver-api/mtd/apple-sftl.rst | 19 ++- + drivers/mtd/apple-sftl-core.c | 151 ++++++++++++++++---- + drivers/mtd/apple-sftl-test.c | 109 +++++++++++++- + 3 files changed, 245 insertions(+), 34 deletions(-) + +diff --git a/Documentation/driver-api/mtd/apple-sftl.rst b/Documentation/driver-api/mtd/apple-sftl.rst +index 0a8c5d624..b043c3d9f 100644 +--- a/Documentation/driver-api/mtd/apple-sftl.rst ++++ b/Documentation/driver-api/mtd/apple-sftl.rst +@@ -99,13 +99,28 @@ closed. Every logical page the map still places in that block moves to a new + append block with a fresh sequence, keeping its type and, for relocated user + data, its user epoch; the failed request follows. A failed page that reads + back erased consumed nothing, so its sequences are offered again; one that +-reads back exactly as programmed keeps its records and sequences. A torn page +-stops the writer. A further failure gives up the new block too; after eight ++reads back exactly as programmed, or torn, keeps its sequences used. A torn ++summary page stops the writer. A further failure gives up the new block too; ++after eight + failures in one session the writer stops. The VFL is never changed: a really + bad block fails again under iOS, which retires it. Without blank blocks the + request returns ``-ENOSPC`` and the move resumes with the next request. + Relocation during reclamation still stops on any failure. + ++Torn pages at load ++------------------ ++ ++A program that failed or was cut short, for example by something else ++resetting the controller, can leave a torn page: status good but metadata ++that is not a record, or erased status over programmed bytes. Recovery ++accepts one torn page per open block when it is that block's last programmed ++page, and lets the journal miss exactly its four sequences, in the middle or ++at the end. Read errors, refresh and unknown statuses still stop recovery, as ++does a torn page followed by another programmed page or a torn summary. ++Before its first write the writer gives every such block up as above: its ++live pages move and the block is never programmed again. As with a failed ++program, no checkpoint records the block as awaiting erase. ++ + The block frontend preserves untouched sectors in partial 4 KiB updates and + groups up to four logical pages per program. Every acknowledged write has + completed readback. Flush and FUA use that same completion rule. There is no +diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c +index 8bed81b59..1d6eea065 100644 +--- a/drivers/mtd/apple-sftl-core.c ++++ b/drivers/mtd/apple-sftl-core.c +@@ -160,6 +160,13 @@ struct apple_sftl { + * data moves to the append point; they are never programmed again. + */ + DECLARE_BITMAP(abandoned, SFTL_MAX_BLOCKS); ++ /* Open blocks whose last programmed page did not read back at load. ++ * torn_after holds the sequence before each such page; its four ++ * sequences may be missing from the journal. ++ */ ++ DECLARE_BITMAP(torn, SFTL_MAX_BLOCKS); ++ u64 torn_after[SFTL_FAIL_MAX]; ++ u32 nr_torn; + u32 failures; + bool evacuate; + u8 *stage, *move; /* the page being appended, a page being moved */ +@@ -1339,6 +1346,16 @@ static bool sftl_user_epoch_valid(const struct apple_sftl *sftl, const u8 *meta, + return user_epoch == sequence >> 16; + } + ++static bool sftl_journal_meta(const struct apple_sftl *sftl, const u8 *meta) ++{ ++ u64 sequence = sftl_sequence(meta); ++ ++ return sftl_erased(meta, SFTL_META) || ++ ((meta[0] == 1 || meta[0] == 2) && ++ sftl_user_epoch_valid(sftl, meta, sequence) && ++ (meta[0] == 1 ? meta[1] <= 1 : meta[1] == 0)); ++} ++ + static int sftl_add_journal(const struct apple_sftl *sftl, struct sftl_records *journal, + const u8 *meta, u32 address, u64 checkpoint) + { +@@ -1346,13 +1363,51 @@ static int sftl_add_journal(const struct apple_sftl *sftl, struct sftl_records * + + if (sequence <= checkpoint || sftl_erased(meta, SFTL_META)) + return 0; +- if ((meta[0] != 1 && meta[0] != 2) || +- !sftl_user_epoch_valid(sftl, meta, sequence) || +- (meta[0] == 1 ? meta[1] > 1 : meta[1] != 0)) ++ if (!sftl_journal_meta(sftl, meta)) + return -EBADMSG; + return sftl_record_add(journal, sftl_stamp(meta), get_unaligned_le32(meta + 8), address); + } + ++/* ++ * Cascadia's give_up_torn, at load: a program that failed or was cut off ++ * can leave a page whose metadata is not a record, or an erased status ++ * over programmed bytes. Only the last programmed page of an open block ++ * may be such a page; what it held was never acknowledged or was written ++ * again elsewhere with higher sequences. Remember where its sequences ++ * began. Read errors, refresh and unknown statuses still stop recovery. ++ */ ++static int sftl_note_torn(struct apple_sftl *sftl, u32 block, u64 after) ++{ ++ if (test_bit(block, sftl->torn) || sftl->nr_torn == SFTL_FAIL_MAX) ++ return -EBADMSG; ++ __set_bit(block, sftl->torn); ++ sftl->torn_after[sftl->nr_torn++] = after; ++ return 0; ++} ++ ++/* A torn page's four sequences may be missing after the given sequence. */ ++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) { ++ sftl->torn_after[i] = U64_MAX; ++ return true; ++ } ++ return false; ++} ++ ++/* Read a page of an open block; one retry after a provider error. */ ++static int sftl_read_open(struct apple_sftl *sftl, u32 address, unsigned int *chunk) ++{ ++ int ret = sftl_read_address(sftl, address, chunk); ++ ++ if (ret && ret != -ENOMEM && ret != -ERANGE) ++ ret = sftl_read_address(sftl, address, chunk); ++ return ret; ++} ++ + 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. */ +@@ -1546,35 +1601,61 @@ static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + + for (block = 1; block < sftl->geo->subblocks; block++) { + const u8 *head = heads + block * SFTL_META; +- bool complete_prefix = true, partial_footer = false; +- u64 base = sftl_sequence(head), next = base; ++ 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_address(sftl, block * stride + (pages - 1) * 4, &chunk); +- if (ret) ++ ret = sftl_read_open(sftl, block * stride + (pages - 1) * 4, &chunk); ++ if (ret && ret != -EBADMSG) + goto out; +- if (sftl->oob[0] == 0x1c) { ++ if (!ret && sftl->oob[0] == 0x1c) { + ret = sftl_footer(sftl, head, block, pages, journal, &floor); + if (ret) + goto out; + continue; + } +- if (!sftl_erased(sftl->oob, sizeof(sftl->oob)) || +- !sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE)) { +- ret = -EBADMSG; +- goto out; ++ /* 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, sizeof(sftl->oob))) { ++ for (chunk = 0; chunk < 4; chunk++) ++ if (!sftl_journal_meta(sftl, sftl->oob + chunk * SFTL_META)) ++ break; ++ if (chunk == 4) { ++ ret = -EBADMSG; ++ goto out; ++ } + } + for (position = 0; position < pages; position++) { +- ret = sftl_read_address(sftl, block * stride + position * 4, &chunk); +- if (ret) ++ bool erased, records; ++ ++ ret = sftl_read_open(sftl, block * stride + position * 4, &chunk); ++ if (ret && ret != -EBADMSG) + goto out; +- if (sftl_erased(sftl->oob, sizeof(sftl->oob)) && +- !sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE)) { ++ erased = !ret && sftl_erased(sftl->oob, sizeof(sftl->oob)); ++ if (erased && !sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE)) ++ ret = -EBADMSG; ++ records = !ret && !erased && sftl->oob[0] != 0x1c; ++ for (chunk = 0; records && chunk < 4; chunk++) ++ if (!sftl_journal_meta(sftl, sftl->oob + chunk * SFTL_META)) ++ ret = -EBADMSG; ++ /* Nothing may follow a torn page in its block. */ ++ if (torn && (ret || !erased)) { + ret = -EBADMSG; + goto out; + } ++ if (ret) { ++ ret = sftl_note_torn(sftl, block, last); ++ if (ret) ++ goto out; ++ torn = true; ++ complete_prefix = false; ++ continue; ++ } ++ for (chunk = 0; records && chunk < 4; chunk++) ++ last = max(last, sftl_sequence(sftl->oob + chunk * SFTL_META)); + if (position < pages - SFTL_FOOTER_CHUNKS / 4) { + for (chunk = 0; chunk < 4; chunk++) { + const u8 *meta = sftl->oob + chunk * SFTL_META; +@@ -1624,6 +1705,8 @@ static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + u64 sequence = record->stamp & SFTL_SEQUENCE; + + ret = -EBADMSG; ++ if (sequence == expected + 4 && sftl_take_torn(sftl, expected - 1)) ++ expected = sequence; + if (sequence != expected++) + goto out; + /* Context and summary chunks, and padding, map nothing. */ +@@ -1663,6 +1746,9 @@ static int sftl_journal(struct apple_sftl *sftl, const u8 *heads, struct sftl_re + sftl->sequence = sequence; + } + sftl->journal_sequence = expected - 1; ++ /* A torn page after the last record keeps its sequences reserved. */ ++ if (sftl_take_torn(sftl, sftl->journal_sequence) && floor <= sftl->journal_sequence + 4) ++ sftl->journal_sequence += 4; + sftl->sequence = max(sftl->journal_sequence, floor); + ret = 0; + out: +@@ -1733,14 +1819,17 @@ int apple_sftl_load(struct apple_ppn *provider, struct apple_sftl **out) + for (block = 1; block < geo->subblocks; block++) { + if (!sftl->lanes[block]) + continue; +- ret = sftl_read_address(sftl, block * sftl_stride(sftl), &chunk); +- if (ret) ++ ret = sftl_read_open(sftl, block * sftl_stride(sftl), &chunk); ++ 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, sizeof(sftl->oob)) && ++ !sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE))) { ++ memset(heads + block * SFTL_META, 0, SFTL_META); ++ heads[block * SFTL_META] = 1; ++ continue; ++ } + if (sftl_erased(sftl->oob, sizeof(sftl->oob))) { +- if (!sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE)) { +- ret = -EBADMSG; +- goto failed; +- } + __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); +@@ -1850,6 +1939,12 @@ static int sftl_writer_prepare(struct apple_sftl *sftl) + __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; + } +@@ -2802,8 +2897,8 @@ static int sftl_close_block(struct apple_sftl *sftl) + * + * A failed page that reads back erased consumed nothing, so its sequences + * are offered again. One that reads back exactly as programmed holds valid +- * records, so its sequences stay used. Anything else is a torn page, which +- * a fresh load rejects; the writer stops. ++ * records, and a torn one is skipped by a fresh load; their sequences stay ++ * used. A torn summary page stops the writer. + */ + static int sftl_give_up(struct apple_sftl *sftl, u32 address, const u8 *data, + const u8 *oob, int err) +@@ -2820,9 +2915,13 @@ static int sftl_give_up(struct apple_sftl *sftl, u32 address, const u8 *data, + sftl_erased(sftl->page, APPLE_PPN_PAGE_SIZE); + landed = !ret && !memcmp(sftl->oob, oob, sizeof(sftl->oob)) && + !memcmp(sftl->page, data, APPLE_PPN_PAGE_SIZE); +- if (!blank && !landed) ++ /* A torn summary is not recognised at load. */ ++ if (!blank && !landed && oob[0] == 0x1c) + goto stop; +- if (landed && oob[0] != 0x1c) { ++ /* A torn data page is the block's last programmed page: a fresh load ++ * skips it and accounts its four sequences, which are not reused. ++ */ ++ if (!blank && oob[0] != 0x1c) { + sftl->sequence += 4; + sftl->journal_sequence = sftl->sequence; + } +diff --git a/drivers/mtd/apple-sftl-test.c b/drivers/mtd/apple-sftl-test.c +index bc3ea9f8c..87be0c43c 100644 +--- a/drivers/mtd/apple-sftl-test.c ++++ b/drivers/mtd/apple-sftl-test.c +@@ -1203,7 +1203,10 @@ static void sftl_test_append_interrupted_footer_replays(struct kunit *test) + } + } + +-static void sftl_test_append_torn_metadata_rejected(struct kunit *test) ++/* A torn data page gives its block up and a fresh load skips it. A torn ++ * summary page still stops the writer and the medium is rejected. ++ */ ++static void sftl_test_append_torn_metadata(struct kunit *test) + { + static const unsigned int torn[] = {1, 121}; + unsigned int index; +@@ -1211,6 +1214,7 @@ static void sftl_test_append_torn_metadata_rejected(struct kunit *test) + for (index = 0; index < ARRAY_SIZE(torn); index++) { + struct sftl_fixture *f = sftl_test_fixture(test, SFTL_NO_FAULT); + struct apple_sftl *sftl = NULL; ++ struct apple_sftl_info info; + u8 *data = kunit_kmalloc(test, 16384, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, f); +@@ -1220,17 +1224,104 @@ static void sftl_test_append_torn_metadata_rejected(struct kunit *test) + memset(data, 'T', 16384); + if (torn[index] == 1) + KUNIT_EXPECT_EQ(test, +- apple_sftl_write(sftl, TEST_APPEND_BASE, data, 1), -EIO); ++ apple_sftl_write(sftl, TEST_APPEND_BASE, data, 1), 0); + else + KUNIT_EXPECT_EQ(test, sftl_test_fill_append(sftl, data), -EIO); + apple_sftl_free(sftl); + sftl = NULL; +- KUNIT_EXPECT_LT(test, apple_sftl_load(&f->provider, &sftl), 0); +- KUNIT_EXPECT_PTR_EQ(test, sftl, NULL); ++ if (torn[index] != 1) { ++ KUNIT_EXPECT_LT(test, apple_sftl_load(&f->provider, &sftl), 0); ++ KUNIT_EXPECT_PTR_EQ(test, sftl, NULL); ++ continue; ++ } ++ /* The torn page's sequences are a hole the load accounts. */ ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ apple_sftl_get_info(sftl, &info); ++ KUNIT_EXPECT_FALSE(test, info.read_only); ++ KUNIT_EXPECT_EQ(test, info.journal_sequence, TEST_APPEND_FIRST + 7); ++ KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, TEST_APPEND_BASE, data), 0); ++ sftl_test_expect_fill(test, data, 'T'); + apple_sftl_free(sftl); + } + } + ++static void sftl_test_torn_page(struct sftl_fixture *f, unsigned int page) ++{ ++ struct sftl_test_page *torn = kunit_kmalloc(f->test, sizeof(*torn), GFP_KERNEL); ++ ++ KUNIT_ASSERT_NOT_NULL(f->test, torn); ++ memset(torn->data, 0x3c, sizeof(torn->data)); ++ memset(torn->oob, 0x5a, sizeof(torn->oob)); ++ KUNIT_ASSERT_EQ(f->test, sftl_test_program_page(f, 0, 0, 5, page, torn->data, torn->oob), 0); ++} ++ ++/* Cascadia's give_up_torn: something else cut a program short (its ++ * 2026-11-16 incident). The load keeps the open block read-write, the ++ * first write moves its live pages out, and later loads skip the page. ++ */ ++static void sftl_test_torn_page_at_load(struct kunit *test) ++{ ++ struct sftl_fixture *f = sftl_test_fixture(test, SFTL_NO_FAULT); ++ struct apple_sftl *sftl = NULL; ++ struct apple_sftl_info info; ++ u8 *data = kunit_kmalloc(test, 16384, GFP_KERNEL); ++ unsigned int i; ++ ++ KUNIT_ASSERT_NOT_NULL(test, f); ++ KUNIT_ASSERT_NOT_NULL(test, data); ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ for (i = 0; i < 2; i++) { ++ memset(data, 'p' + i, 16384); ++ KUNIT_ASSERT_EQ(test, apple_sftl_write(sftl, TEST_APPEND_BASE + i * 4, data, 4), 0); ++ } ++ apple_sftl_free(sftl); ++ sftl = NULL; ++ sftl_test_torn_page(f, 2); ++ ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ apple_sftl_get_info(sftl, &info); ++ KUNIT_EXPECT_FALSE(test, info.read_only); ++ KUNIT_EXPECT_EQ(test, info.journal_sequence, TEST_APPEND_FIRST + 11); ++ KUNIT_EXPECT_EQ(test, info.sequence, TEST_APPEND_FIRST + 11); ++ memset(data, 'q', 16384); ++ KUNIT_ASSERT_EQ(test, apple_sftl_write(sftl, TEST_APPEND_BASE + 8, data, 4), 0); ++ /* Two moved pages and the new one land in the next block. */ ++ KUNIT_EXPECT_NOT_NULL(test, sftl_test_written(f, 1, 0, 2)); ++ KUNIT_EXPECT_NULL(test, sftl_test_written(f, 1, 0, 3)); ++ KUNIT_EXPECT_NULL(test, sftl_test_written(f, 0, 0, 3)); ++ apple_sftl_free(sftl); ++ sftl = NULL; ++ ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ apple_sftl_get_info(sftl, &info); ++ KUNIT_EXPECT_EQ(test, info.journal_sequence, TEST_APPEND_FIRST + 23); ++ for (i = 0; i < 12; i++) { ++ KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, TEST_APPEND_BASE + i, data), 0); ++ sftl_test_expect_fill(test, data, i < 8 ? 'p' + i / 4 : 'q'); ++ } ++ apple_sftl_free(sftl); ++} ++ ++/* Only the last programmed page of an open block may be torn. */ ++static void sftl_test_torn_page_not_last(struct kunit *test) ++{ ++ struct sftl_fixture *f = sftl_test_fixture(test, SFTL_NO_FAULT); ++ struct apple_sftl *sftl = NULL; ++ u8 *data = kunit_kmalloc(test, 4096, GFP_KERNEL); ++ ++ KUNIT_ASSERT_NOT_NULL(test, f); ++ KUNIT_ASSERT_NOT_NULL(test, data); ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ memset(data, 'n', 4096); ++ KUNIT_ASSERT_EQ(test, apple_sftl_write(sftl, TEST_APPEND_BASE, data, 1), 0); ++ apple_sftl_free(sftl); ++ sftl = NULL; ++ sftl_test_torn_page(f, 1); ++ sftl_test_torn_page(f, 2); ++ KUNIT_EXPECT_EQ(test, apple_sftl_load(&f->provider, &sftl), -EBADMSG); ++ KUNIT_EXPECT_PTR_EQ(test, sftl, NULL); ++} ++ + static void sftl_test_append_scans_entire_candidate(struct kunit *test) + { + struct sftl_fixture *f = sftl_test_fixture(test, SFTL_NO_FAULT); +@@ -3159,9 +3250,13 @@ static void sftl_test_gc_relocation_stops_before_erase(struct kunit *test) + sftl_test_gc_relocated_data(test, sftl, data, 0); + apple_sftl_free(sftl); + if (modes[mode].copy_error) { +- struct sftl_test_page *page = sftl_test_written(f, 1, 0, 1); ++ /* A malformed last page is skipped as torn; a malformed ++ * page before a valid one is still rejected. ++ */ ++ struct sftl_test_page *page = sftl_test_written(f, 1, 0, 0); + + KUNIT_ASSERT_NOT_NULL(test, page); ++ KUNIT_ASSERT_NOT_NULL(test, sftl_test_written(f, 1, 0, 1)); + put_unaligned_le32(3, page->oob + 12); + KUNIT_EXPECT_EQ(test, apple_sftl_load(&f->provider, &sftl), -EBADMSG); + apple_sftl_free(sftl); +@@ -3588,7 +3683,9 @@ static struct kunit_case apple_sftl_cases[] = { + KUNIT_CASE(sftl_test_append_failures_exhaust_blocks), + KUNIT_CASE(sftl_test_append_uncertain_program_replays), + KUNIT_CASE(sftl_test_append_interrupted_footer_replays), +- KUNIT_CASE(sftl_test_append_torn_metadata_rejected), ++ KUNIT_CASE(sftl_test_append_torn_metadata), ++ KUNIT_CASE(sftl_test_torn_page_at_load), ++ KUNIT_CASE(sftl_test_torn_page_not_last), + KUNIT_CASE(sftl_test_append_scans_entire_candidate), + KUNIT_CASE(sftl_test_append_reserves_vfl_members), + KUNIT_CASE(sftl_test_append_closes_at_sequence_limit), From 0989cf61866a7b71f0d79a66b18c066212b6e32a Mon Sep 17 00:00:00 2001 From: Henrik Klee Date: Fri, 20 Nov 2026 06:38:33 +0800 Subject: [PATCH 6/7] kernel: P105 NAND: test-only failure injection; port status in the proposal Patch 0023 (authored by rzxvx) adds CONFIG_MTD_APPLE_H2FMI_FAULT_INJECT, default n: debugfs fault attributes make a page program fail before or after it reaches the NAND, or an erase fail, so the give-up paths can be exercised on a tablet as Cascadia did. KUnit gains Cascadia's fault script on synthetic media: 90 cases pass. The merge proposal now lists what each port became, compares #93's native context encoder with Cascadia's iOS 8.4.1 encoder field by field (port 2, offline: the w0c dump is private), and marks what needs a tablet or the dump in its order section. device.toml notes that the 16 GB read path is untested. Assisted-by: LLM --- devices/p105/device.toml | 3 +- docs/bring-up/p105-nand-merge-proposal.md | 85 ++++++- ...Add-test-only-program-and-erase-fail.patch | 232 ++++++++++++++++++ 3 files changed, 313 insertions(+), 7 deletions(-) create mode 100644 kernel/patches/armv7/mtd/0023-mtd-apple-h2fmi-Add-test-only-program-and-erase-fail.patch diff --git a/devices/p105/device.toml b/devices/p105/device.toml index c58077db..202468e6 100644 --- a/devices/p105/device.toml +++ b/devices/p105/device.toml @@ -51,7 +51,8 @@ gyroscope = "missing" light_sensor = "missing" touch_id = "missing" # The 64 GB P105 read current logical pages matching the physical captures. -# The PR #93 device trial used read-only internal volumes. +# The PR #93 device trial used read-only internal volumes. The 16 GB +# package's read-only layout (Cascadia's, mtd 0018) has not run on a tablet. storage_read = "working" storage_write = "untested" wifi = "untested" diff --git a/docs/bring-up/p105-nand-merge-proposal.md b/docs/bring-up/p105-nand-merge-proposal.md index 6e8f27f2..deefa8fa 100644 --- a/docs/bring-up/p105-nand-merge-proposal.md +++ b/docs/bring-up/p105-nand-merge-proposal.md @@ -1,7 +1,8 @@ # P105 NAND: two drivers, one proposal -State: proposal. Nothing here changes what the kernel builds. Henrik decides -which way the P105's NAND support goes; the combined driver is not written yet. +State: ports 1, 5, 3, 4 and 6 written on branch `p105-nand-fusion` as +`kernel/patches/armv7/mtd` 0017-0023 on top of #93 (now at 59bdee56); port 2 +compared offline only (below). None of it has run on a P105. The iPad mini 1 (P105) stores iOS's disk on PPN NAND behind two H2FMI buses, through Apple's VFL and SwissPPNFTL, with LwVM partitions on top. Two @@ -129,16 +130,88 @@ in the write path, VFL rotation, native context pages, interrupted-save recovery, provider accounting, native allocation order, verified erase and raw-program exclusion. +## What the ports became + +All patches leave #93's 0001-0016 untouched. Port patches are authored by +rzxvx and cite the Cascadia commits they come from; the two follow-ups that +change behaviour of Shayne's code are ours and say why. + +| patch | port | author | what it does | +|---|---|---|---| +| 0017 | (for 1) | ours | geometry descriptor instead of #93's fixed 64 GB constants; no functional change | +| 0018 | 1 | rzxvx | 16 GB layout (4 lanes, 1064 × 256, 1055 superblocks, VFL in 1062/1063, 3,906,250 pages); 12H321 tree batch 16, "+nb" summary spans, PAD records; H2FMI registers the provider for both profiles; the 16 GB disk is read-only | +| 0019 | 5 | rzxvx | SDR bring-up and SDR transfers in H2FMI when iBoot left no DDR state: NAND reset, power state 0x180 = 2 after it, timing 0x23210, firmware and bad-block table reads, one start per 4112-byte unit; the armv7 config gets `STRICT_DEVMEM` + `IO_STRICT_DEVMEM` (H2FMI already claims its windows) | +| 0020 | (for 3) | ours | H2FMI resets the packages after a failed transaction instead of refusing all later I/O (at most 8 resets) | +| 0021 | 3 | rzxvx | a failed data or summary program gives the block up: live pages move, the request follows, blank failed pages reuse their sequences; 8 failures per session stop the writer | +| 0022 | 4 | rzxvx | one torn last page per open block is skipped at load and its four sequences accounted; the first write moves the block's live pages out | +| 0023 | 6 | rzxvx | `CONFIG_MTD_APPLE_H2FMI_FAULT_INJECT` (default n): debugfs `apple-h2fmi/fail_program`, `fail_program_landed`, `fail_erase` | + +Not ported: Cascadia's "try the next spare" after a failed spare erase (#93's +verified erase stops on failure, and erase is off on the P105), and marking a +given-up or torn block as awaiting erase in the next context (the append +writer writes no checkpoint on the P105; the block stays an open block whose +records are all superseded). + +Where the ports change what #93's tests asserted: a failed program no longer +stops the writer (four cases rewritten to assert the give-up), a torn data page +no longer makes the medium unreadable, and the relocation case that corrupted +the landing block's last page now corrupts the page before it. Unknown read +statuses and refresh still stop recovery, as #93 decided; Cascadia's walk +would skip them. + +## Port 2: 12H321 against #93's native encoder (offline) + +Cascadia's `w0c` dump is private, so the reader did not run against it. The +comparison is between #93's native context encoder (`apple-sftl-reclaim.c` +`sftl_checkpoint_build`, `apple-sftl-account.c`) and Cascadia's +`sftl_ctx_build` / `sftl_context_write` / `frontier_close`, which iOS 8.4.1 +boots from. Same in both: context metadata (`0x1f`, section, sequence, +entry offset and count, `0xffffffff`), section order 1, 2, 3, 5, 6, 4, each +section padded to whole pages, 511 range pairs per record, the unmapped +sentinel, summary entry layout and the "+0" span a Linux close writes. + +| field | #93 (13G36 model) | Cascadia (12H321, iOS-accepted) | +|---|---|---| +| base record names | 2 (new context group and the reserved next site) | 1 (its own superblock) | +| range records | multiple of 64 (`cxtNextBatch`) | `max(32, roundup(used, 16))` | +| unused range record bytes | all `0xff` | two words `0xffffffff`, rest zero | +| statistics section | refreshed: ids 9-13, 37, 38 and live records 254 and 255 from the provider | copied unchanged from the replaced context | +| block roles 1 and 9 | 1 clean free, 9 dirty free | read as 1 awaiting erase, 9 erased; its own recovery found type-9 blocks with old data, which fits #93's reading | +| summary size | 32 chunks (flags `0x40`) | 4 or 8 chunks (flags 8 or 16), the only sizes on 12H321 media | +| summary padding | repeats the last page | PAD records (`0xffff0000`, type 1) up to the summary, no hole | +| user sequence tuple | per footer run, `U32_MAX` users skipped, count = samples | over all entries, count = entries | +| read counts | zeroed for a retired block | carried unchanged | +| context site | two-block group, any lanes | one superblock with all four banks | +| previous context | erased after the new one reloads | kept as the fallback, at most two | +| VFL table reference (reader) | u16, bit 15 = bank, low bits = page | u32 log position | + +Each row is a candidate for the 16 GB writer. Only the dump (or a 16 GB P105) +can say which 13G36 behaviours 12H321 tolerates; until then the 16 GB profile +stays read-only. + ## Order and evidence before anything is enabled 1. Land #93 as it stands (its own review); P105 erase stays off. -2. Ports 1 and 5, then read-only device runs on both a 16 GB and a 64 GB - P105: the whole disk read and compared with a raw dump. -3. Ports 3, 4 and 6; fault-injection runs on a 16 GB P105 against a - disposable Linux volume, as Cascadia did. +2. Ports 1 and 5 (0017-0019), then read-only device runs on both a 16 GB and + a 64 GB P105: the whole disk read and compared with a raw dump. + **Needs hardware:** a 16 GB P105 for the 16 GB reader at all (VFL in + either bank, the u16 table reference reading Cascadia's log positions, + statistics record tags, "+nb" spans and PAD replay are untested on real + 12H321 media); the SDR path of 0019 on either package (today's boot chain + leaves DDR, so it only runs after a failure, 0020). +3. Ports 3, 4 and 6 (0020-0023); fault-injection runs on a 16 GB P105 + against a disposable Linux volume, as Cascadia did. KUnit covers the + give-up and torn paths on synthetic 64 GB media only. + **Needs hardware:** the reset after a failed transaction (0020) and the + SDR transfers it switches to; what a cut-short PPN program reads back as + (0022 only recognises malformed metadata); the debugfs injection (0023) + on a tablet; iOS meeting a given-up or torn open block (never observed, + Cascadia's spec section 9). 4. Port 2, then writes with reclamation on the 16 GB P105 (8.4.1), a cold iOS boot and `fsck_hfs` after each step, as in Cascadia's 2026-11-16 cycle; then the 64 GB P105 (9.3.5) once #93's erase qualification is done. + **Needs the `w0c` dump or hardware:** every row of the port 2 table; the + 16 GB writer is not enabled until they are settled. Cascadia's import stays in the series meanwhile, so its files remain available; `APPLE_PPN` stays off. Drop 0018 from the platform only when the diff --git a/kernel/patches/armv7/mtd/0023-mtd-apple-h2fmi-Add-test-only-program-and-erase-fail.patch b/kernel/patches/armv7/mtd/0023-mtd-apple-h2fmi-Add-test-only-program-and-erase-fail.patch new file mode 100644 index 00000000..dc948f21 --- /dev/null +++ b/kernel/patches/armv7/mtd/0023-mtd-apple-h2fmi-Add-test-only-program-and-erase-fail.patch @@ -0,0 +1,232 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: rzxvx +Date: Fri, 20 Nov 2026 06:36:50 +0800 +Subject: [PATCH] mtd: apple-h2fmi: Add test-only program and erase failure + injection + +The translation layer's give-up paths can be exercised on synthetic +media, but Cascadia also ran them on a 16 GB P105: its driver makes the +Nth program fail, either before the page is programmed or after, and +the Nth erase fail, and a script writes files on ext4 meanwhile, then +checks them after a remount, with e2fsck and with iOS. + +Offer the same in H2FMI behind CONFIG_MTD_APPLE_H2FMI_FAULT_INJECT +(default n), through the kernel's fault-injection framework instead of +module parameters: debugfs apple-h2fmi/fail_program fails a program +before it starts, fail_program_landed reports failure after the page +was programmed and read back (and resets the packages as a real failure +does), and fail_erase fails an erase before it starts. Each takes the +usual attributes; interval N with times 1 fails the Nth operation. + +Add Cascadia's script as a KUnit case on synthetic media: a program +that fails before reaching the NAND, later one that lands but reports +failure, under a stream of writes; every write succeeds and the data +survive a fresh load with a writable journal. + +Ported from Cascadia (https://github.com/rzxvx/Project-Cascadia) commits +c0d5a20 ("a5: apple_ppn: test-only program/erase failure injection; +device fault script") and 9c6bac2 ("a5: apple_ppn: failure injection +only with CONFIG_APPLE_PPN_FAULT_INJECT (default n)"), files apple_ppn.c +and devices/a5/tools/nand-faults/faults.sh, as of Cascadia ad28ba4. + +Assisted-by: LLM +--- + drivers/mtd/apple-sftl-test.c | 43 +++++++++++++++++++ + drivers/mtd/devices/Kconfig | 14 ++++++ + drivers/mtd/devices/mtd-apple-h2fmi.c | 61 ++++++++++++++++++++++++++- + 3 files changed, 117 insertions(+), 1 deletion(-) + +diff --git a/drivers/mtd/apple-sftl-test.c b/drivers/mtd/apple-sftl-test.c +index 87be0c43c..e9ae55f46 100644 +--- a/drivers/mtd/apple-sftl-test.c ++++ b/drivers/mtd/apple-sftl-test.c +@@ -1168,6 +1168,48 @@ static void sftl_test_append_uncertain_program_replays(struct kunit *test) + apple_sftl_free(sftl); + } + ++/* Cascadia's device fault script (tools/nand-faults/faults.sh) on synthetic ++ * media: a program that fails before reaching the NAND, later one that ++ * lands but reports failure, each under a stream of writes. Every write ++ * succeeds, and the data survive a fresh load with a writable journal. ++ */ ++static void sftl_test_fault_ladder(struct kunit *test) ++{ ++ struct sftl_fixture *f = sftl_test_fixture(test, SFTL_NO_FAULT); ++ struct apple_sftl *sftl = NULL; ++ struct apple_sftl_info info; ++ u8 *data = kunit_kmalloc(test, 16384, GFP_KERNEL); ++ unsigned int page; ++ ++ KUNIT_ASSERT_NOT_NULL(test, f); ++ KUNIT_ASSERT_NOT_NULL(test, data); ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ f->fail_program = 6; ++ for (page = 0; page < 24; page++) { ++ if (page == 12) { ++ f->fail_program = f->programs + 4; ++ f->uncertain_program = true; ++ } ++ memset(data, 'A' + page, 16384); ++ KUNIT_ASSERT_EQ(test, apple_sftl_write(sftl, TEST_APPEND_BASE + page * 4, data, 4), 0); ++ } ++ /* Two blocks were given up; the third holds everything. */ ++ KUNIT_EXPECT_NOT_NULL(test, sftl_test_written(f, 2, 0, 23)); ++ KUNIT_EXPECT_NULL(test, sftl_test_written(f, 2, 0, 24)); ++ KUNIT_EXPECT_EQ(test, f->program_outside, 0U); ++ apple_sftl_free(sftl); ++ sftl = NULL; ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ apple_sftl_get_info(sftl, &info); ++ KUNIT_EXPECT_FALSE(test, info.read_only); ++ KUNIT_EXPECT_EQ(test, info.journal_sequence, info.sequence); ++ for (page = 0; page < 96; page++) { ++ KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, TEST_APPEND_BASE + page, data), 0); ++ sftl_test_expect_fill(test, data, 'A' + page / 4); ++ } ++ apple_sftl_free(sftl); ++} ++ + static void sftl_test_append_interrupted_footer_replays(struct kunit *test) + { + static const struct { +@@ -3682,6 +3724,7 @@ static struct kunit_case apple_sftl_cases[] = { + KUNIT_CASE(sftl_test_append_failure_moves_live_pages), + KUNIT_CASE(sftl_test_append_failures_exhaust_blocks), + KUNIT_CASE(sftl_test_append_uncertain_program_replays), ++ KUNIT_CASE(sftl_test_fault_ladder), + KUNIT_CASE(sftl_test_append_interrupted_footer_replays), + KUNIT_CASE(sftl_test_append_torn_metadata), + KUNIT_CASE(sftl_test_torn_page_at_load), +diff --git a/drivers/mtd/devices/Kconfig b/drivers/mtd/devices/Kconfig +index 33ab36b71..ef6a7facd 100644 +--- a/drivers/mtd/devices/Kconfig ++++ b/drivers/mtd/devices/Kconfig +@@ -224,6 +224,20 @@ config MTD_APPLE_H2FMI + + If unsure, say N. + ++config MTD_APPLE_H2FMI_FAULT_INJECT ++ bool "Test-only program and erase failure injection" ++ depends on MTD_APPLE_H2FMI && FAULT_INJECTION_DEBUG_FS ++ default n ++ help ++ Adds debugfs fault-injection attributes under apple-h2fmi/ that ++ make a page program fail before or after it reaches the NAND, or a ++ block erase fail, to exercise the translation layer's failure ++ handling on a tablet. A failure reported after programming resets ++ the packages as a real one does. ++ ++ Never enable this on a device whose NAND holds data you need. ++ Say N. ++ + config MTD_APPLE_H2FMI_KUNIT_TEST + tristate "KUnit tests for Apple H2FMI PPN geometry" if !KUNIT_ALL_TESTS + depends on KUNIT +diff --git a/drivers/mtd/devices/mtd-apple-h2fmi.c b/drivers/mtd/devices/mtd-apple-h2fmi.c +index 6431bd7e7..b24d13e90 100644 +--- a/drivers/mtd/devices/mtd-apple-h2fmi.c ++++ b/drivers/mtd/devices/mtd-apple-h2fmi.c +@@ -30,7 +30,9 @@ + * Logical-address translation and allocation belong to the FTL above. + */ + ++#include + #include ++#include + #include + #include + #include +@@ -120,6 +122,46 @@ struct h2fmi_bus { + /* Resets after failed transactions in one driver instance. */ + #define H2FMI_MAX_RESETS 8 + ++/* ++ * Test-only failure injection (CONFIG_MTD_APPLE_H2FMI_FAULT_INJECT), as ++ * Cascadia's driver offers it for exercising the translation layer's ++ * failure paths on a tablet: debugfs apple-h2fmi/fail_program makes a page ++ * program fail without programming, fail_program_landed reports failure ++ * after the page was programmed and read back, and fail_erase fails a ++ * block erase before it starts. Each takes the usual fault-injection ++ * attributes (probability, interval, times, ...). ++ */ ++#ifdef CONFIG_MTD_APPLE_H2FMI_FAULT_INJECT ++static DECLARE_FAULT_ATTR(h2fmi_fail_program); ++static DECLARE_FAULT_ATTR(h2fmi_fail_program_landed); ++static DECLARE_FAULT_ATTR(h2fmi_fail_erase); ++ ++static void h2fmi_remove_debugfs(void *dir) ++{ ++ debugfs_remove_recursive(dir); ++} ++ ++static int h2fmi_fault_init(struct device *dev) ++{ ++ struct dentry *dir = debugfs_create_dir("apple-h2fmi", NULL); ++ ++ fault_create_debugfs_attr("fail_program", dir, &h2fmi_fail_program); ++ fault_create_debugfs_attr("fail_program_landed", dir, &h2fmi_fail_program_landed); ++ fault_create_debugfs_attr("fail_erase", dir, &h2fmi_fail_erase); ++ dev_warn(dev, "test-only failure injection is built in\n"); ++ return devm_add_action_or_reset(dev, h2fmi_remove_debugfs, dir); ++} ++ ++#define h2fmi_inject(attr) should_fail(&(attr), 1) ++#else ++static int h2fmi_fault_init(struct device *dev) ++{ ++ return 0; ++} ++ ++#define h2fmi_inject(attr) false ++#endif ++ + struct h2fmi_die { + struct h2fmi *fmi; + u8 bus; +@@ -1000,6 +1042,11 @@ static int h2fmi_program_page(struct h2fmi *fmi, struct h2fmi_bus *b, + ret = -EEXIST; + goto out; + } ++ if (h2fmi_inject(h2fmi_fail_program)) { ++ dev_warn(fmi->dev, "PPN program row %08x: injected failure\n", row); ++ ret = -EIO; ++ goto out; ++ } + ret = h2fmi_program_transaction(fmi, b, row, expected); + if (ret) + goto out; +@@ -1013,6 +1060,12 @@ static int h2fmi_program_page(struct h2fmi *fmi, struct h2fmi_bus *b, + row, status, ret); + goto out; + } ++ if (h2fmi_inject(h2fmi_fail_program_landed)) { ++ dev_warn(fmi->dev, "PPN program row %08x: injected failure after programming\n", ++ row); ++ h2fmi_fail(fmi); ++ ret = -EIO; ++ } + out: + mutex_unlock(&b->lock); + kfree(expected); +@@ -1214,6 +1267,10 @@ static int h2fmi_ppn_erase(void *priv, unsigned int bus, unsigned int cau, + if (ret) + return ret; + ++ if (h2fmi_inject(h2fmi_fail_erase)) { ++ dev_warn(fmi->dev, "PPN erase row %08x: injected failure\n", row); ++ return -EIO; ++ } + ret = h2fmi_lock(fmi, b); + if (ret) + return ret; +@@ -1523,7 +1580,9 @@ static int h2fmi_probe(struct platform_device *pdev) + } + } + +- ret = h2fmi_register_sftl(fmi); ++ ret = h2fmi_fault_init(&pdev->dev); ++ if (!ret) ++ ret = h2fmi_register_sftl(fmi); + if (ret) { + for (i = 0; i < fmi->ndies; i++) + mtd_device_unregister(&fmi->mtd[i]); From 481406310e1dd497bceee97004a1a62f1402ef1c Mon Sep 17 00:00:00 2001 From: Shayne Legault <8741557+shaynelegault@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:41:19 -0600 Subject: [PATCH 7/7] kernel: p105: accept checkpointed subtype-1 data in open blocks Fusion patch 0022 treats native data with an older user epoch as a torn page. When another programmed page follows, SFTL aborts the map load with -EBADMSG. Accept the older epoch for subtype-1 disk data that the checkpoint already covers. The loader can skip those records during replay and still validate newer records. Add the ARM KUnit regression and record the 64 GB P105 comparison. All 954 ranges read by the iPad matched an independent reconstruction from raw flash captured during the same boot. Assisted-by: LLM Signed-off-by: Shayne Legault <8741557+shaynelegault@users.noreply.github.com> --- chips/s5l8942x.toml | 2 +- devices/p105/device.toml | 3 +- .../p105-sftl-device-qualification.md | 13 +++ ...ecognize-checkpointed-subtype-1-data.patch | 100 ++++++++++++++++++ 4 files changed, 116 insertions(+), 2 deletions(-) create mode 100644 kernel/patches/armv7/mtd/0024-mtd-apple-sftl-recognize-checkpointed-subtype-1-data.patch diff --git a/chips/s5l8942x.toml b/chips/s5l8942x.toml index 5f950616..f9b9875a 100644 --- a/chips/s5l8942x.toml +++ b/chips/s5l8942x.toml @@ -15,7 +15,7 @@ firmware = "P105 recipe for iOS 8.4.1 encrypted images (docs/bring-up/p105-firmw platform = "P105 on a Cascadia-based build" stages = "Project Cascadia P105 boot chain" reference_version = "Project Cascadia builds its A5 boot chain from 8.4.1 / 12H321" -nand_reads = "The 64 GB P105 has eight CAUs per bus, 2088 blocks per CAU and 128 normal pages per block. PR #93 matched 29 live logical pages to physical data and verified both LwVM headers (docs/bring-up/p105-sftl-device-qualification.md)." +nand_reads = "The 64 GB P105 has eight CAUs per bus, 2088 blocks per CAU and 128 normal pages per block. PR #93 matched 29 live logical pages to physical data and verified both LwVM headers. With the fusion fix, all 954 ranges of the logical disk matched an independent reconstruction from raw flash (docs/bring-up/p105-sftl-device-qualification.md)." nand_program = "The H2FMI driver programs complete PPN pages only into erased destinations, verifies full readback and leaves physical erase disabled pending qualification (docs/bring-up/p105-nand-program.md)." nand_checkpoint_gc = "The 64 GB P105 verified raw write exclusion and exposed both live statistics records through paired iOS. Counter continuity through shutdown and physical erase and reuse still need qualification (docs/bring-up/p105-sftl-device-qualification.md)." usb_phy = "P105 uses a 24 MHz reference; the proposed S5L8942X cold-handoff callbacks await an exact-revision boot (docs/bring-up/p105-usb-handoff.md)." diff --git a/devices/p105/device.toml b/devices/p105/device.toml index 202468e6..ee31e604 100644 --- a/devices/p105/device.toml +++ b/devices/p105/device.toml @@ -50,7 +50,8 @@ accelerometer = "missing" gyroscope = "missing" light_sensor = "missing" touch_id = "missing" -# The 64 GB P105 read current logical pages matching the physical captures. +# On the 64 GB P105, the whole logical disk matched an independent +# reconstruction from raw flash captured during the same boot. # The PR #93 device trial used read-only internal volumes. The 16 GB # package's read-only layout (Cascadia's, mtd 0018) has not run on a tablet. storage_read = "working" diff --git a/docs/bring-up/p105-sftl-device-qualification.md b/docs/bring-up/p105-sftl-device-qualification.md index 8dd4a9d7..20bc4eb4 100644 --- a/docs/bring-up/p105-sftl-device-qualification.md +++ b/docs/bring-up/p105-sftl-device-qualification.md @@ -118,6 +118,19 @@ hashes for 241 font files on System and 13 package manifests on Data. The file hashes stay on the measurement host for comparison after the erase trial and cold boot. +## Whole-disk read on 20 November 2026 + +The 64 GB P105 ran fusion `0989cf6` with the fix for checkpointed +subtype-1 pages. All 954 logical ranges read from the iPad matched +the SHA-256 hashes from an independent reconstruction of raw flash +captured during the same boot. The comparison covered 64,000,000,000 bytes. + +The iPad and the independent decoder found 13,474 map runs, up from +12,793 on 19 November. The checkpoint advanced from 189791520 to +189814460 and the journal from 189808092 to 189958336. Both runs +found 32 native context records. The same 29 live 4 KiB pages on +block 896 matched their earlier iOS Data hashes. + ## Repeating the checks Verify the running kernel notes against the measurement artifact and check diff --git a/kernel/patches/armv7/mtd/0024-mtd-apple-sftl-recognize-checkpointed-subtype-1-data.patch b/kernel/patches/armv7/mtd/0024-mtd-apple-sftl-recognize-checkpointed-subtype-1-data.patch new file mode 100644 index 00000000..f783c861 --- /dev/null +++ b/kernel/patches/armv7/mtd/0024-mtd-apple-sftl-recognize-checkpointed-subtype-1-data.patch @@ -0,0 +1,100 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Shayne Legault <8741557+shaynelegault@users.noreply.github.com> +Date: Thu, 19 Nov 2026 22:17:57 -0600 +Subject: [PATCH] mtd: apple-sftl: recognize checkpointed subtype-1 data in + open blocks + +The native 64 GB P105 journal can retain an older user epoch on subtype-1 data covered by the checkpoint. Treating such a record as torn causes the following programmed page to abort the entire load. + +Recognize this form only for exported data that predates or equals the checkpoint. Keep validating newer journal records and reject future user epochs. Exercise two adjacent native copies in the loader fixture. + +Assisted-by: LLM +Signed-off-by: Shayne Legault <8741557+shaynelegault@users.noreply.github.com> +--- + drivers/mtd/apple-sftl-core.c | 7 ++++++ + drivers/mtd/apple-sftl-test.c | 47 +++++++++++++++++++++++++++++++++++ + 2 files changed, 54 insertions(+) + +diff --git a/drivers/mtd/apple-sftl-core.c b/drivers/mtd/apple-sftl-core.c +index 1d6eea065..2d383ea65 100644 +--- a/drivers/mtd/apple-sftl-core.c ++++ b/drivers/mtd/apple-sftl-core.c +@@ -1350,6 +1350,13 @@ static bool sftl_journal_meta(const struct apple_sftl *sftl, const u8 *meta) + { + u64 sequence = sftl_sequence(meta); + ++ /* Native subtype-1 data covered by the checkpoint can retain an ++ * earlier user epoch. It occupies the page but is never replayed. ++ */ ++ if (meta[0] == 1 && meta[1] == 1 && sequence <= sftl->checkpoint_sequence && ++ get_unaligned_le32(meta + 8) < sftl->geo->disk_pages) ++ return get_unaligned_le32(meta + 12) <= sequence >> 16; ++ + return sftl_erased(meta, SFTL_META) || + ((meta[0] == 1 || meta[0] == 2) && + sftl_user_epoch_valid(sftl, meta, sequence) && +diff --git a/drivers/mtd/apple-sftl-test.c b/drivers/mtd/apple-sftl-test.c +index e9ae55f46..73a78b747 100644 +--- a/drivers/mtd/apple-sftl-test.c ++++ b/drivers/mtd/apple-sftl-test.c +@@ -1344,6 +1344,52 @@ static void sftl_test_torn_page_at_load(struct kunit *test) + apple_sftl_free(sftl); + } + ++/* A native open block can contain older subtype-1 copies on adjacent pages. */ ++static void sftl_test_checkpointed_open_copies(struct kunit *test) ++{ ++ struct sftl_fixture *f = sftl_test_fixture(test, SFTL_NO_FAULT); ++ struct sftl_test_page *page = kunit_kzalloc(test, sizeof(*page), GFP_KERNEL); ++ struct apple_sftl *sftl = NULL; ++ struct apple_sftl_info info; ++ unsigned int row, chunk; ++ ++ KUNIT_ASSERT_NOT_NULL(test, f); ++ KUNIT_ASSERT_NOT_NULL(test, page); ++ f->sequence_bias = 1ULL << 16; ++ for (row = 0; row < 2; row++) { ++ for (chunk = 0; chunk < 4; chunk++) { ++ u8 *meta = page->oob + 16 * chunk; ++ u32 slot = 4 * row + chunk; ++ ++ sftl_test_meta(meta, 1, 1, f->sequence_bias + 10 + slot, 2 + slot); ++ put_unaligned_le32(0, meta + 12); ++ } ++ KUNIT_ASSERT_EQ(test, sftl_test_program_page(f, 0, 0, 5, row, ++ page->data, page->oob), 0); ++ } ++ ++ KUNIT_ASSERT_EQ(test, apple_sftl_load(&f->provider, &sftl), 0); ++ apple_sftl_get_info(sftl, &info); ++ KUNIT_EXPECT_EQ(test, info.journal_sequence, f->sequence_bias + TEST_OPEN_FIRST + 3); ++ KUNIT_ASSERT_EQ(test, apple_sftl_read(sftl, 2, page->data), 0); ++ sftl_test_expect_fill(test, page->data, 'G'); ++ apple_sftl_free(sftl); ++ sftl = NULL; ++ ++ page = sftl_test_written(f, 0, 0, 0); ++ KUNIT_ASSERT_NOT_NULL(test, page); ++ /* An epoch from the future still invalidates the first page. */ ++ put_unaligned_le32(2, page->oob + 12); ++ KUNIT_EXPECT_EQ(test, apple_sftl_load(&f->provider, &sftl), -EBADMSG); ++ KUNIT_EXPECT_PTR_EQ(test, sftl, NULL); ++ ++ /* A newer record still has to pass full journal validation. */ ++ sftl_test_meta(page->oob, 1, 1, f->sequence_bias + TEST_OPEN_FIRST + 4, 2); ++ put_unaligned_le32(0, page->oob + 12); ++ KUNIT_EXPECT_EQ(test, apple_sftl_load(&f->provider, &sftl), -EBADMSG); ++ KUNIT_EXPECT_PTR_EQ(test, sftl, NULL); ++} ++ + /* Only the last programmed page of an open block may be torn. */ + static void sftl_test_torn_page_not_last(struct kunit *test) + { +@@ -3728,6 +3774,7 @@ static struct kunit_case apple_sftl_cases[] = { + KUNIT_CASE(sftl_test_append_interrupted_footer_replays), + KUNIT_CASE(sftl_test_append_torn_metadata), + KUNIT_CASE(sftl_test_torn_page_at_load), ++ KUNIT_CASE(sftl_test_checkpointed_open_copies), + KUNIT_CASE(sftl_test_torn_page_not_last), + KUNIT_CASE(sftl_test_append_scans_entire_candidate), + KUNIT_CASE(sftl_test_append_reserves_vfl_members),