Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

docs: driver review, ten read-only audits (input, storage, GPU, camera, audio, Wi-Fi x2, loader, policy)

shimoku230762c0176a
diff --git a/docs/driver-review/adsp-battery-cpufreq.md b/docs/driver-review/adsp-battery-cpufreq.md
new file mode 100644
index 0000000..32b224c
--- /dev/null
+++ b/docs/driver-review/adsp-battery-cpufreq.md
@@ -0,0 +1,294 @@
+# Driver review: audio DSP loader, battery, CPU frequency
+
+## Scope and method
+
+Files read in full (paths under `xnu/files/`):
+
+| File | Lines |
+|---|---|
+| `bsd/dev/hakios.adsp.c` | 3244 |
+| `bsd/dev/hakios.battery.c` | 198 |
+| `iokit/Kernel/hakios.battery.cpp` | 230 |
+| `bsd/dev/hakios.cpufreq.c` | 597 |
+
+Context also read: the callers `bsd/dev/hakios.input.c:217-226`, `osfmk/arm64/loader_return.c:377-379,445,492`, the consumer `bsd/dev/hakios.torch.c:454`, and the lock declarations in `hakios.wifi.c:190-192`. Nothing from the modem files was analysed.
+
+Method: read-only, line-by-line. For every value that the DSP, the always-on processor (AOP) or the firmware files supply (SMEM entry headers, SMP2P words, GLINK queue messages, QRTR and APR payloads, battmgr answers, MDT/ELF segment headers, the AOP mailbox descriptor, the command database) I traced how it becomes a size, an offset, a loop bound or an index. For every wait loop I noted the bound and the timeout action. Nothing was built or run, and no hardware facts were assumed. Where severity depends on silicon behaviour the finding says NEEDS-HARDWARE.
+
+Threat model used: the DSP (and AOP) can write arbitrary bytes into the shared memory it shares with us, and so can stale state left by an earlier kernel or Android.
+
+## Findings
+
+| ID | Severity | Confidence | Where | One line |
+|---|---|---|---|---|
+| F1 | High | CONFIRMED | adsp.c:2012-2023, 2058, 2099, 2150 | GLINK message length wraps to 0: the listener livelocks holding `glink_lock`; the stop path then hangs |
+| F2 | High | CONFIRMED | adsp.c:408, 424, 1861-1867, 1907, 1940 | SMEM item size underflows and offsets are unchecked: GLINK queues are accessed outside the SMEM window |
+| F3 | Medium | CONFIRMED | adsp.c:2488, 2495, 2515 | APR payload length underflows: 256-byte out-of-bounds read, leaked to handlers and the log |
+| F4 | Medium | CONFIRMED | adsp.c:2400, 2420 | QRTR `at + size > length` wraps: out-of-bounds read |
+| F5 | Medium | CONFIRMED (severity NEEDS-HARDWARE) | battery.c:98-110, 139; adsp.c:2752-2808; torch.c:454 | Battery temperature has no freshness or range check, and the flashlight thermal guard consumes it |
+| F6 | Medium | CONFIRMED | adsp.c:686 | `box + size > aoss.size` can overflow: mailbox writes outside the mapped block |
+| F7 | Low-Med | CONFIRMED (a), PLAUSIBLE (b) | adsp.c:1145-1159, 1096-1099, 1123 | Firmware-file cleanup frees with the wrong size; mixed-source free; tiny `.mdt` read |
+| F8 | Low | CONFIRMED | adsp.c:1257, 1594-1596 | Our SMP2P item is zeroed (340 bytes) at an unvalidated SMEM offset |
+| F9 | Low | PLAUSIBLE | adsp.c:1371-1374, 900 | Panic way-back path calls `rails(0)`, which takes a mutex |
+| F10 | Low | PLAUSIBLE | adsp.c:1893-1909, 2004-2010 | No read barrier between loading the DSP's queue head and its payload |
+| F11 | Low | CONFIRMED | adsp.c:1407-1430, 1982-1983, 2916-2925 | Leaks: header page every start, GLINK intent buffers never freed |
+| F12 | Low | PLAUSIBLE | adsp.c:2514-2519, 2575-2582 | `apr_answer` is published with no ordering |
+| F13 | Low | CONFIRMED | cpufreq.c:573, 588-590 | `cpufreq=2` (any value) also starts `membench=2` |
+| F14 | Low | PLAUSIBLE | cpufreq.c:557-587 | `cpufreq=1` / `ddr=1` have no platform check, unlike `adsp=1` |
+| F15 | Low | CONFIRMED | cpufreq.c:358, 366 | Command-DB bounds checks are dead or off by 0x50 (diagnostic mode) |
+| F16 | Low | CONFIRMED | battery.c:134, 139; battery.cpp:118, 130 | DSP-supplied values: signed overflow in `+50` rounding, negative to unsigned casts |
+| F17 | Low | PLAUSIBLE | battery.c:188-189 | Shared struct can straddle the single mapped 16 KB page |
+| F18 | Low | NEEDS-HARDWARE | adsp.c:1654 vs 1367 | IPCC GLINK enable bit set at start, never cleared at shutdown |
+
+## Details
+
+### F1 - GLINK length arithmetic wraps; zero-length message livelocks `glink_pump` (High, CONFIRMED)
+
+`glink_pump()` computes the message length from DSP-written fields in 32-bit arithmetic:
+
+- `adsp.c:2012`: `length += message.param2;` (OPEN)
+- `adsp.c:2014`: `length += 8 * message.param2;` (INTENT)
+- `adsp.c:2020`: `length = 16 + words[0];` (DATA, DATA_MORE)
+- `adsp.c:2022-2023`: `length = (length + 7) & ~7u;` then `if (length > glink.theirs_size - 8)`
+
+Failure scenarios (the DSP writes one 8-byte or 16-byte message into its own queue):
+
+1. OPEN with `param2 = 0xFFFFFFF8`, or DATA with `words[0] = 0xFFFFFFF0`, or INTENT with `param2 = 0x1FFFFFFF`: `length` wraps to exactly 0. The size check passes and `waiting < length` is false. The handler then calls `glink_advance(length)` (2058, 2150, 2111) which moves the tail by 0. The `while (glink.up && !glink.broken)` loop at 2004 sees the same message again, forever. For DATA the drop path at 2148 also prints a line every iteration. For OPEN each pass sends another OPEN_ACK until our queue is full.
+2. INTENT with `param2 = 0x20000001`: `8*param2` wraps to 8, so `length = 16` and the check passes. The loop at 2099 then runs 536,870,913 iterations of `glink_peek` (8 byte-wise SMEM reads each) plus a 64-entry scan.
+
+`glink_pump()` runs with `glink_lock` held (`link_thread` at 2870-2871, `glink_send` at 2225-2231). Consequences:
+
+- The link thread spins at 100% on one core.
+- Every `glink_send` caller (QRTR, APR, battmgr, sound, mic) blocks in `lck_mtx_lock` with no timeout.
+- `link_stop()` (called from `dsp_shutdown`, reached from `hakios_adsp_stop`, `loader_return.c:445`) waits 2 s, then does `lck_mtx_lock(&glink_lock)` at 2914 and blocks forever. The orderly return to the loader never completes.
+
+Fix (compute in 64 bits and reject non-progress):
+
+```diff
+- uint32_t waiting = glink_waiting(), length = sizeof(message);
++ uint32_t waiting = glink_waiting();
++ uint64_t length = sizeof(message);
+ ...
+- length += message.param2;
++ length += message.param2; /* now 64-bit: cannot wrap */
+ ...
+- length += 8 * message.param2;
++ length += 8ull * message.param2;
+ ...
+- length = 16 + words[0];
++ length = 16ull + words[0];
+ }
+- length = (length + 7) & ~7u;
+- if (length > glink.theirs_size - 8) {
++ length = (length + 7) & ~7ull;
++ if (length < sizeof(message) || length > glink.theirs_size - 8) {
+```
+
+Also make the INTENT loop `for (i = 0; i < message.param2 && 8 + 8*(uint64_t)(i+1) <= length; i++)`.
+
+### F2 - SMEM entry size underflows and offset is never bounded; GLINK queues are accessed without bounds checks (High, CONFIRMED)
+
+`smem_items()` builds each item's extent from DSP-writable entry headers:
+
+- `adsp.c:408` and `adsp.c:424`: `found[count].size = entry.size - entry.padding_data;` (`padding_data` is a uint16 and `entry.size` a uint32, with no `padding_data <= size` check; an underflow yields about 4 GB).
+- `adsp.c:407`, `adsp.c:423`: `found[count].offset = partition + at + sizeof(entry) + entry.padding_header` (up to 64 KB past the entry; never compared with `SMEM_SIZE` or the partition end).
+
+`glink_find()` (1861-1867) accepts item 480 (created by the DSP itself, see the comment at step_survey 959) if `size >= 1024 && !(size & 7)`. It then uses the values raw, with no `smem_peek`-style window check:
+
+- `adsp.c:1907`: `smem[glink.theirs + (at + i) % glink.theirs_size]`
+- `adsp.c:1932`, `1940`: `queue[(head + i) % glink.ours_size] = ...` (a write)
+- `smem_word(glink.descriptor + ...)` and `smem_poke(...)` are likewise unbounded.
+
+Scenario: the DSP writes entry header item=480, `size=0x400`, `padding_data=0x408`. The size becomes 0xFFFFFFF8, which passes `glink_find`. The head/tail checks (`< theirs_size`, 1895 and 1922) now accept any 32-bit value. The first `glink_peek` reads `smem + theirs + up to 4 GB` and the link thread takes a data abort, which is a kernel panic. Even without the wrap, `offset + size` can exceed the mapped 2 MB window (padding_header adds up to 64 KB) and writes from `glink_put` land outside it. Items 478/479 have the same problem, because the DSP can edit their headers too.
+
+Fix:
+
+```diff
+ /* in smem_items(), both loops */
+- found[count].size = entry.size - entry.padding_data;
++ if (entry.padding_data > entry.size || entry.padding_header > header.size ||
++ (uint64_t)off + entry.size > partition + header.size) break; /* off = computed offset */
++ found[count].size = entry.size - entry.padding_data;
+```
+
+And in `glink_find()` add `(uint64_t)x + size <= SMEM_SIZE` for each of the three items.
+
+### F3 - APR payload length underflows (Medium, CONFIRMED)
+
+`adsp.c:2488`: `payload = (header.size < length ? header.size : length) - header_length;`. `header_length` is 20..60 (validated against `length`); `header.size` is a DSP-written uint16 and is not validated against `header_length`. If `header.size < header_length` (for example `size = 0`) the subtraction wraps to about 4 billion.
+
+The wrapped `payload` is then used at:
+
+- `adsp.c:2495-2497`: `memcpy(words, data + header_length, payload < sizeof(words) ? payload : sizeof(words))` copies 256 bytes from a packet that may be only 20 bytes long, which is a heap over-read of up to 236 bytes. It is passed to the sound and mic event handlers with length 256.
+- `adsp.c:2509`: the same for the first 16 bytes, which are printed.
+- `adsp.c:2515-2516`: the over-read bytes go into `apr_answer.words`, with `apr_answer.length = payload` (about 4 G). `hakios_adsp_apr` copies those words to its caller (2581), and `step_apr` prints `apr_answer.words[i]` (3082-3083).
+
+Result: kernel heap contents leak to the log and the handlers, and the read can fault if the packet sits at the end of a mapping.
+
+Fix:
+
+```diff
+- payload = (header.size < length ? header.size : length) - header_length;
++ {
++ uint32_t total = header.size < length ? header.size : length;
++ if (total < header_length) { printf("adsp: apr: size %u below header %u: dropped\n", total, header_length); return; }
++ payload = total - header_length;
++ }
+```
+
+### F4 - QRTR datagram size check wraps (Medium, CONFIRMED)
+
+`adsp.c:2400`: `if (header.size == 0 || at + header.size > length)`. `at` (32 or `16 + data[3]`) and `header.size` (a DSP-supplied uint32, read at 2382 or 2388) are both uint32, so `header.size = 0xFFFFFFF0` wraps the sum to a small number and the datagram is accepted. At 2420, `memcpy(&control, data + at, header.size < sizeof(control) ? header.size : sizeof(control))` then copies 20 bytes from `data + at`. With a v1 header in a 32-byte packet that reads 20 bytes past the `kalloc_data(sizeof(*packet) + length)` element. For the v3 header `at` can be up to 271 bytes past `length`. The over-read bytes become `control->words`, which are stored in `qrtr_servers[]` (2343-2346) and printed.
+
+Fix:
+
+```diff
+- if (header.size == 0 || at + header.size > length) {
++ if (header.size == 0 || at > length || header.size > length - at) {
+```
+
+### F5 - Battery temperature: no freshness or range handling, consumed by the flashlight thermal guard (Medium, CONFIRMED; real-world severity NEEDS-HARDWARE)
+
+- `battery.c:139`: `battery_temperature_c = (b->temperature_hundredths + 50) / 100;` (DSP path). `battery.c:104`: `battery_temperature_c = sample.temperature_c;` (loader path). Neither has a timestamp or a range check.
+- `hakios_battery_temperature()` (47-51) returns the last value forever.
+- `torch.c:454`: `if (hakios_battery_temperature() >= HOTTEST_BATTERY_C)` is the only check of the battery temperature.
+
+Staleness paths, all traced:
+
+1. `battmgr_thread` leaves its loop for good when the DSP closes PMIC_RTR_ADSP_APPS (`adsp.c:2752`, `channel->open=false` at 2184) or `glink.up` clears, and is never restarted (2807-2808). The last temperature stays.
+2. If any of the seven `battmgr_get` calls fails, `good` is false and nothing is reported (2765): the old value stays, with only a log line.
+3. `battery_poll` failure (`battery.c:95-99`) only increments `battery_failures`.
+
+The unknown value is -273, which is below 45, so the guard treats "unknown" and "stale" as safe.
+
+Range: `temperature_hundredths` comes straight from a DSP uint32 cast to int32 (2781). For `0x7FFFFFFF` the `+ 50` is signed overflow (undefined behaviour; in practice it wraps negative), so a garbage or lying DSP reads as cold, not hot.
+
+Fix:
+
+```diff
+ /* battery.c */
++static uint64_t battery_temp_at; /* mach_absolute_time of last good report */
+ int hakios_battery_temperature(void) {
+- return battery_temperature_c;
++ return (mach_absolute_time() - battery_temp_at < FRESH_TICKS) ? battery_temperature_c : -273;
+ }
+- battery_temperature_c = (b->temperature_hundredths + 50) / 100;
++ battery_temperature_c = (int)(((int64_t)b->temperature_hundredths + 50) / 100);
++ battery_temp_at = mach_absolute_time();
+```
+
+and make the torch guard fail closed on -273 if the board is known to have a battery. Whether fail-closed is right depends on policy, so I only flag it.
+
+### F6 - AOP mailbox bounds check overflows (Medium, CONFIRMED)
+
+`adsp.c:686`: `if (size < QMP_MESSAGE + 4 || box < 0x3c || box + size > aoss.size || (box & 3))`. `box` and `size` are uint32 read from the AOP's message RAM (684-685), and `aoss.size` is 0x400. With `box = 0x3fc` and `size = 0xFFFFFF00` the sum is 0x2FC and the check passes. `mailbox_send` then writes `aoss.base + our_box + 4 + 4*i` for 16 words (749-752), which goes from 0x400 to 0x43f, outside the mapped block, into whatever the neighbouring AOSS registers are (NEEDS-HARDWARE for the effect). The AOP is a remote processor, so this value is untrusted input. (The same pattern exists in `hakios.wifi.c`; not reviewed here.)
+
+Fix: `|| size > aoss.size - box` after `box < 0x3c || box >= aoss.size`.
+
+### F7 - Firmware image bookkeeping (Low-Medium)
+
+(a) CONFIRMED. `adsp.c:1145` stores the header's `file_size` in `image.segment[n].file_size`. The file was allocated with `attributes.va_data_size` (`root_file`, 1003). On a size mismatch (1156-1159) the code does `image.segments++` so the file is released, but `image_forget()` (1098) calls `kfree_data(data, image.segment[s].file_size)`, which is the header's value, not the allocation size. With a wrong `adsp.bNN` on the root file system, the clean "has N bytes, the header says M" failure becomes a `kfree_data` size mismatch (a zone panic or heap corruption). Fix: store the real `file_size` (`image.segment[n].file_size = file_size;`) before `goto fail`, or keep a separate allocation size.
+
+(b) PLAUSIBLE. `from_root` (1053) is set when any one file came from `/fw` on the root. `image_forget()` then frees all files, including `image.header` and segments that came from the small image (`hakios_image_file`, 1043), which are not `kalloc` memory. This needs a partly populated small image (header there, a segment missing, taken from root). Fix: track the source per file (a flag per segment and for the header).
+
+(c) CONFIRMED but trivial. `adsp.c:1123`: `memcmp(header, "\177ELF\1", 5)` is evaluated before any size check, so a 1..4 byte `adsp.mdt` over-reads up to 4 bytes (and the print at 1124 reads `header[0..3]`).
+
+Checked fine in the same function: segment window checks (1138-1139) correctly bound `paddr`, `file_size` and `memory_size` in 64 bits against `[0x86700000, +64 MB)`, and `count <= MAX_SEGMENTS` bounds `image.segment[]`.
+
+### F8 - Our SMP2P item is written at an unvalidated offset (Low, CONFIRMED)
+
+`our_item_find()` (1252-1258) accepts item 429 if `size >= sizeof(struct smp2p)`, where `size` is the F2-underflowable value, and returns the raw offset. `step_our_item()` then does `for (at < 340) smem_poke(our_item + at, 0)` (1594-1596) and several more pokes, with no `smem_peek` bounds check first (unlike `dsp_listen` and `dsp_ask_to_stop`, which peek first). A stale or corrupt entry for item 429 (padding_header up to 64 KB, or size underflowed) makes the kernel write 340 bytes outside the item. That is either a data abort past the 2 MB window or corruption of other processors' SMEM items. At this step the DSP has been shut down, so the source is stale state from an earlier run. Fix: reuse the F2 validation and `if (!smem_peek(our_item, &ours, sizeof ours)) return false;` before the zeroing loop.
+
+### F9 - Panic way-back path takes a mutex (Low, PLAUSIBLE)
+
+`hakios_adsp_quiesce()` (3141-3150) sets `leaving` and calls `dsp_shutdown()`. `mailbox_send` honours `leaving` (no lock), but `rails(0)` (1371-1374) unconditionally does `lck_mtx_lock(&hakios_rsc_lock)` at line 900, with interrupts off and the other CPUs stopped. If a stopped CPU held `hakios_rsc_lock` (the modem driver `hakios.mpss.c:899,959` takes the same lock), the panic return hangs and the loader never gets control back. The window is small: `rails_asked` is only true until the DSP says "handover" (about 40 ms after start) or after a failed give-back. Fix: `if (!leaving) lck_mtx_lock(...)` as `mailbox_send` does, and skip `hold()` (it is already skipped when `leaving`).
+
+Related note: `ddr_rpmh_write` in cpufreq.c (465-507) drives the same TCS 0 with no `hakios_rsc_lock`. That is safe today because `ddr_raise` runs at the start of `hakios_input_init` before any DSP driver exists, and `hakios_ddr_quiesce` runs with the other CPUs stopped. A CPU stopped mid-`rails()` leaves the TCS busy and the vote is skipped after a 200 ms wait. This is latent only.
+
+### F10 - No read barrier between queue head and payload (Low, PLAUSIBLE, NEEDS-HARDWARE)
+
+`glink_waiting()` (1893) loads the DSP's head with `rd()`. This is a plain `ldr` with only a compiler barrier. `glink_pump` then reads the payload with byte loads from the same Normal-NC (VM_WIMG_WCOMB) mapping (1907). There is no `dmb ld` between them (a control dependency does not order loads), so on a weakly ordered core the payload loads can be satisfied before the head load and show stale bytes (zeros or an old message). The result is a mis-parsed message, and an unknown command sets `glink.broken` (2192-2196), which permanently stops the link. The producer side is correct (`settle()` before the head update in `glink_put`, 1943). Whether the core reorders here is NEEDS-HARDWARE. Fix: `__asm__ volatile("dmb ishld" ::: "memory");` after reading the head in `glink_waiting`. `battery_snapshot()` already does this correctly (`battery.c:81,83`).
+
+### F11 - Leaks (Low, CONFIRMED)
+
+- `step_header` (1407) allocates a page with `kmem_alloc` and never frees it, on any return path. The comment does not say why. Linux keeps the metadata buffer until after `auth_and_reset`, so it may be deliberate until that point, but nothing releases it afterwards. This is 16 KB per start; the code runs once per boot with `adsp=1`, but `adsp_step` and `adsp_again` re-runs repeat it.
+- `glink_offer` (1982-1983) allocates intent buffers (up to about 115 KB at the default sizes, up to 24 x 64 KB per channel when the DSP requests sizes). `link_stop` frees queued packets (2920-2923) but never `our_intents[].data`. When the size at a slot differs from the previous one, the old pointer is overwritten (1982-1983) and leaked.
+- `step_image` returns false on a misaligned segment (1464-1467) without `image_forget()`; it is freed on the next `step_firmware` only.
+
+### F12 - `apr_answer` is published without ordering (Low, PLAUSIBLE)
+
+The link thread fills `apr_answer.words/length/opcode/token` and then sets `there = true` (2514-2519). `hakios_adsp_apr` polls `there` and `token`, then `memcpy`s the words (2575-2581). Only `there` is `volatile`, and volatile gives no ordering with the other (non-volatile) fields. There is no `dmb`, no atomic release or acquire. On arm64 the reader can see `there` and `token` before `words`, and so copy a stale or half-written answer. The one-answer-at-a-time design (`apr_lock`) limits exposure. Compare `battmgr`, which does this correctly with `os_atomic_inc(..., release)` / `os_atomic_load(..., acquire)` (2692, 2700-2706). Fix: use `os_atomic_store(&apr_answer.there, true, release)` and `os_atomic_load(&apr_answer.there, acquire)`.
+
+### F13 - `cpufreq=2` also starts the all-core memory benchmark (Low, CONFIRMED)
+
+`cpufreq.c:572-573` reads `cpufreq` into `enabled`. At 588: `if (PE_parse_boot_argn("membench", &enabled, ...) && enabled == 1) {...} else if (enabled == 2)`. When `membench` is absent the parse leaves `enabled` unchanged, so the `else if` tests the `cpufreq` value. With `cpufreq=2` (accepted as "on" by `cpufreq_wanted`), 8 threads each allocate 2 x 16 MB and run a spin-wait rendezvous. Fix: use a separate variable for `membench`.
+
+### F14 - cpufreq/ddr have no platform check (Low, PLAUSIBLE)
+
+`hakios_cpufreq_init` runs unconditionally from `hakios_input_init` (`hakios.input.c:217`). `adsp=1` refuses to run unless `pe_arm_get_soc_base_phys() == HAKIOS_SOC_BASE` (`adsp.c:3209`). The cpufreq code instead relies only on the boot-arg: `cpufreq=1` maps and reads EPSS at 0x18591000 and the RSC at 0x18220000 (95-106, 390-400); `ddr=1` does the same without needing `cpufreq`. The file header says the addresses are the phone's. On QEMU or any other board those addresses are unrelated MMIO or RAM, so the first access is likely an external abort (panic). The effect is not traced, since QEMU's memory map is outside this repository. Fix: the same `pe_arm_get_soc_base_phys()` gate at the top of `hakios_cpufreq_init`.
+
+### F15 - Command-database bounds checks are dead or off by 0x50 (Low, CONFIRMED; diagnostic code)
+
+`cpufreq.c:358` and `452`: `slave->header_offset >= CMD_DB_SIZE - 0x1000` is never true, because `header_offset` is a uint16 (max 0xFFFF < 0x1F000). The entry array is still inside the window (max 0xFFFF + 0x90 + 512 x 24 < 0x20000), so that one is only a dead check. At `cpufreq.c:366` the check is `slave->data_offset + entry[i].offset + sizeof(aux) < CMD_DB_SIZE - 0x40`, but the read is `db->data + that`, and `data` starts at +0x90. The read can end at 0x20050, which is 0x50 bytes past the mapped 0x20000. Compare the correct check in `adsp.c:852` (`> CMD_DB_SIZE - 0x1000`, ending before 0x1F090). The command database is written by the boot firmware, so the practical risk is low, and the code only runs with `ddr=1`. Fix: use the check of `adsp.c:852`.
+
+### F16 - Arithmetic on DSP-supplied battery values (Low, CONFIRMED)
+
+DSP words become `int32_t` at `adsp.c:2778-2791` with no range check. Then:
+
+- `battery.c:134`: `(b->percent_hundredths + 50) / 100` is signed overflow for values above INT32_MAX-50 (undefined behaviour; it wraps negative in practice and the clamp turns 100% into 0%). The same is at `battery.c:139` and `battery.cpp:118, 225`.
+- `battery.cpp:130`: `setVoltage((unsigned)(b->voltage_uv / 1000))`, a negative value becomes about 4 million mV.
+- `battery.cpp:133`: `number("Temperature", ...)` stores negative values in a 32-bit unsigned OSNumber. Whether powerd reads it as signed is unverified.
+
+No crash path: the divisors are constants, so there is no division by zero. Fix: do the rounding in `int64_t`, and clamp voltage, current and temperature to plausible ranges and reject the sample otherwise.
+
+### F17 - Shared battery struct can straddle the mapped page (Low, PLAUSIBLE)
+
+`battery.c:188-189` maps one 16 KB page, `ml_io_map(shared_pa & ~0x3fff, 0x4000)`, and points `shared_battery` at `page + (shared_pa & 0x3fff)`. Nothing checks that the offset plus `sizeof(struct loader_battery)` (56 bytes) stays inside the page, and `sample.size` is only checked as a minimum (96). The boot-arg comes from the loader, so this is a robustness issue. Fix: reject `(shared_pa & 0x3fff) + sizeof(*shared_battery) > LOADER_PAGE_SIZE`.
+
+### F18 - IPCC GLINK enable bit is never cleared (Low, NEEDS-HARDWARE)
+
+`step_start` enables the LPASS doorbell for both SMP2P and GLINK (`adsp.c:1653-1654`). `dsp_shutdown` disables only SMP2P (`1367`). Nothing disables GLINK, including on the failed-start paths (1657-1679). The effect of leaving a stale enable in the IPCC, after the DSP is off and rails are given back, is a hardware matter.
+
+## Checked and found fine
+
+Every wait loop has a bound, and a stated action at the bound:
+
+- `mailbox_wait` (655-664): 1000 ms each. On timeout `mailbox_open` takes our link and channel down again (700-722). `mailbox_send` takes the message back (755-758).
+- `rails()` completion wait (925-931): 100 ms. The TCS is cleaned up and `false` is returned. The busy-TCS pre-check (902-907) is under `hakios_rsc_lock`.
+- `step_start` watch (1685-1729): `adsp_wait` seconds (default 10), shortened to 3 s after "up". `adsp_wait` times 1000000ull cannot overflow. On timeout or `DSP_FATAL` the step fails, and `steps_over()` shuts the DSP down (3108-3109), because `dsp_started` is already true. The DSP is not left running on this path.
+- `dsp_ask_to_stop` (1328-1334): 5 s (2 s when leaving). On timeout it takes our stop bit back (1339) and `dsp_shutdown` still goes on to the TrustZone shutdown.
+- `scm()` (1229): at most 100 retries on `SCM_INTERRUPTED`. Both the return value and the answer are checked by all four callers. `answer` is initialised to `~0` so a failure cannot read as success.
+- `our_item_make` hardware spinlock (1513-1520): about 1 s, released on every exit (1556).
+- `glink_send` (2230-2263): 5000 x 1 ms with the mutex dropped around the sleep. `battmgr_get`: 1000 ms. `hakios_adsp_apr`: `ms`. `step_link`: 5 s. `battmgr_stop` and `link_stop`: 2 s each.
+- `doorbells()` and the pre-start doorbell drain: 8 iterations.
+- cpufreq `ddr_rpmh_write`: 2000 x 100 us at both waits. `load_thread` and `bench_all` waits are diagnostic and by design.
+
+Start and stop sequencing:
+
+- The stop sequence order (ask the DSP, TrustZone shutdown, tell the AOP "off", give back rails) is what the file header says (`dsp_shutdown`, 1348-1376). `link_stop` runs first, so the link thread is no longer a second reader of SMEM when `dsp_ask_to_stop` runs.
+- Error mid-start: failed `rails()` and failed `mailbox_send` and failed AUTH_AND_RESET each release the rails and the `dsp_lock` (1657-1679). A failed `mailbox_open` leaves the mailbox in its previous state.
+- A `hakios_adsp_stop` that arrives while `step_start` is mid-flight cannot miss a started DSP: `dsp_started` is set under `dsp_lock`, and the panic path re-checks `dsp_started` (3144).
+- `dsp_words`' static `at` and `smem_item`'s static `found[256]` are only used concurrently if `dsp_words` has never found item 443. Once the DSP is up, `at` is cached and `link_thread` does not call `smem_item`.
+
+Memory-safety items traced and fine:
+
+- `smem_peek` bounds the read in 64-bit (`offset + size`). `smem_partition` checks `table.count <= 64`, `entry.offset + entry.size` in 64-bit, and the `$TOC`/`$PRT` magics. `smem_items` loops always progress (at least 16 bytes) and are bounded by the 2 MB window; the cached-side loop guards `step_back` with `cacheline` being a power of two and `entry.size > at`. SMP2P entries are used only with `i < min(valid, 16)`. SMP2P `smem_poke` offsets are at most 336 + 4 inside the 340 bytes that `smem_peek` validated first. Crash-reason text is clamped to 80 bytes and zeroed first.
+- `rail_position` (825-877): the command-DB entry array and data reads are inside the 0x20000 window (`CMD_DB_SIZE - 0x1000` check at 852). `levels[160]` cannot overflow (at most about 124 bytes).
+- GLINK: head and tail are validated against the queue sizes at each use (`glink_waiting` 1895, `glink_room` 1922); `glink_peek` and `glink_advance` take the modulus. OPEN names are clamped to 32 bytes plus a terminating zero. DATA copies are bounded by `our_intents[].size - fill`, `intent < our_intent_count <= 24`, and the received packet is allocated at `fill` bytes. `glink_offer` is capped at 0x10000 bytes x 24 intents. `their_intents` insertion is bounded to 64.
+- battmgr: `battmgr_input` copies at most `sizeof(m)` into a zeroed struct; `battmgr_get` requires `length >= sizeof(m)`; the answer is published with release/acquire atomics. Only `get` opcodes are sent, so there are no SCM, setting or limit writes to the charger. With `battery=1` battmgr refuses to start (2822), so the two writers of the `battery_*` globals are never both active.
+- Firmware loading: the MDT header is bounded to `PAGE_SIZE`, `count <= 48`, `52 + 32*count <= size`, the hashes size is cross-checked, every segment is checked in 64-bit against the reserved window, and the 8-byte alignment is checked before writing (1464). Writes and read-back stay inside `[0x86700000, +64 MB)`. `memcpy` of the header into the SCM page is bounded by the header's `PAGE_SIZE` check. The cache is cleaned (`dc civac`) and `dsb`'d before the SCM call. SCM `MEM_SETUP` is passed the exact window and the computed image size (at most 64 MB).
+- Barriers: `settle()` (dsb sy) before every IPCC doorbell and before every queue head update; `(void)rd()` after the mailbox message; `battery_snapshot` seqlock uses `dmb ishld` correctly and retries a bounded 4 times.
+- Locks: `glink_lock`, `dsp_lock`, `apr_lock`, `say_lock` are all mutexes; the only sleeps under a lock are `sleep_*` inside mutex sections (legal). Nested orders found: `dsp_lock` then `hakios_rsc_lock` or `hakios_aop_mailbox_lock`, and `dsp_lock` then `glink_lock` (via `link_stop`). The reverse orders do not occur in this file, and `hakios.wifi.c` does not take `hakios_rsc_lock`. `qrtr_input` and `apr_input` are called without `glink_lock` held, so their `glink_send` calls do not self-deadlock.
+- cpufreq: the value written to hardware is a table row index chosen from rows 0..39 only (`EPSS_TABLE_ROWS`); the table read stays below 0x1A0, inside the 0x1000 domain window. The selection rule (strictly increasing frequency) cannot pick an out-of-table row. No boot-arg or user-space interface selects a row: `cpufreq=` is on/off only, and there is no sysctl or ioctl in these files that writes frequency. `domain_of` returns 0..2, matching `cores[EPSS_DOMAINS]`. `ddr_vote` is range-checked to 1..0x3fff (`ddr_raise`, 527), `ddr_rest` is clamped to 0x3fff, and `ddr_rest=0` means "no request" (documented: slow loader USB, nothing unsafe is traced). `load_thread`'s buffer logic is safe, and `100 * busy / (now - then)` cannot divide by zero after a >= 1 ms delay.
+- battery: every sysctl is `CTLFLAG_RD` over plain `int`, so user space can read but not write (the `kern.hakios` node itself is `CTLFLAG_RW`, with no handler). No division by a variable exists anywhere in these files. `HakiosBatteryReport` validates both `size` and `b->size`, and all OSObject allocations (the adapter dictionary, the numbers) are released on every path read; `attach` and `start` failure paths release or detach.
+- Boot-args in the audio DSP file (`adsp`, `adsp_step`, `adsp_wait`, `adsp_listen`, `adsp_pause`, `adsp_new`, `adsp_keep`, `adsp_again`, `adsp_return`, `battmgr`): all parsed into uint32 with defaults. Only `adsp=1` or `adsp_step` start anything, and the platform check is at 3209. `adsp_listen * 1000` can wrap only for values above 4,294,967 (a harmless short wait).
+
+## Not checked
+
+- The Wi-Fi, modem and shared helper implementations in `hakios.wifi.c`, `hakios.mpss.c` (the same QMP mailbox, SMEM and RPMh pattern appears there; F6 applies to `hakios.wifi.c` at the same lines, unverified).
+- The consumers of `hakios_adsp_apr` and the APR event handlers (`hakios.sound.c`, `hakios.mic.c`), including whether a handler called from the link thread can wait for an answer that only that thread can deliver.
+- `hakios_image_file` (`hakios.image.c`), i.e. what memory the small-image pointers refer to, which F7(b) depends on.
+- IOKit internals: `IOPMPowerSource::updateStatus()` being called before `attach`/`start` (`battery.cpp:212`), and `OSNumber` signedness as read by powerd.
+- Hardware facts, all NEEDS-HARDWARE: that EPSS has 40 rows, its register layout, and thermal limiting of the top row (I found no software thermal path for the CPUs in these files); RPMh command timing and what clearing a TCS while a request is in flight does; whether `ml_io_map` returns NULL on failure (none of `smem`, `cmd_db`, `dsp_memory`, `ipcc.base` is checked for NULL); cache and WC-mapping coherence of the reserved DSP memory against the kernel's own linear map; TrustZone behaviour on a failed AUTH_AND_RESET (whether a PAS shutdown is needed).
+- The loader side of the battery cache (`xnuloader`) and the QEMU build.
+- Not built or run; all findings are from reading the code.
diff --git a/docs/driver-review/camera-haptic-torch.md b/docs/driver-review/camera-haptic-torch.md
new file mode 100644
index 0000000..8700a16
--- /dev/null
+++ b/docs/driver-review/camera-haptic-torch.md
@@ -0,0 +1,227 @@
+# Driver review: camera, haptics, torch
+
+## Scope and method
+
+Read-only audit. Files read in full unless noted.
+
+| File | Lines | Read |
+|---|---|---|
+| xnu/files/bsd/dev/hakios.torch.c | 763 | all |
+| xnu/files/bsd/dev/hakios.haptic.c | 1005 | all |
+| xnu/files/bsd/dev/hakios.camera.c | 4264 | all except 1568-1750 only skimmed (read-only RPMh/SMMU/PLL printers) |
+| xnu/files/bsd/sys/hakios.camera.h | - | all (user ABI) |
+| userland/src/camera_device.c (1280-1420), camera_isp.c (840-1033) | - | the parts that talk to the kernel node and parse the `.isp` file |
+| tools/camsensor.py, tools/camtuning.py | - | header comments and pack lines only (to learn the on-disk format) |
+| hakios.buttons.c (spmi lock), loader_return.c (quiesce call site), hakios.wifi.c (`hakios_wifi_file`) | - | the few lines needed |
+
+Method: traced every user-reachable entry (torch `write`/`read`, haptic `write`, camera `open`/`close`/`read`/`write`; none of the three nodes has an ioctl, all use `eno_ioctl`/`eno_mmap`) end to end; followed every table-derived length and count; checked every polling loop for a bound; checked lock use between the service thread and the file operations; checked each boot-arg. Nothing was built or run. No hardware facts are asserted: where an outcome depends on how the chip behaves it is marked NEEDS-HARDWARE.
+
+## Findings
+
+| id | severity | confidence | file:line | one line |
+|---|---|---|---|---|
+| CAM-1 | high | CONFIRMED | hakios.camera.c:3873-3884 vs 3363-3376, 3401-3425 | `camdev_read` copies from `ring` with no reference held; the capture thread frees `ring` under it (use-after-free read, or panic in `dc civac`) |
+| CAM-2 | medium | CONFIRMED | hakios.camera.c:3969-3978, 4019-4035, 3379-3384, 3500-3503, 4000 | any process (node is 0666) picks sensor and any table mode, so can force a huge kernel allocation or a permanent camera shutdown |
+| TORCH-1 | medium | CONFIRMED (code path); effect NEEDS-HARDWARE | hakios.torch.c:330, 506-511, 605-633 | the "light off" path is blocked by the sticky `broken` flag, so after one failed write the LED stays on with no monitoring and no timer |
+| TORCH-2 | medium | CONFIRMED (code path); effect NEEDS-HARDWARE | hakios.torch.c:487-499, 697-717, 632, 750 | `lit` is set only after all enabling writes succeed; a write that lands but fails read-back leaves the LED possibly on with `lit == false`, so nothing turns it off |
+| HAPTIC-1 | medium | CONFIRMED (code path); effect NEEDS-HARDWARE | hakios.haptic.c:961-971, 570-580 | haptic=5 starts serving the motor even when the waveform file did not load |
+| CAM-3 | low | PLAUSIBLE / NEEDS-HARDWARE | hakios.camera.c:2989 vs 1830, 3003, 3066 | lens-motor supply is not given back if RPMh did not report "done" in time, unlike the CX/MX rails |
+| CAM-4 | low | CONFIRMED | hakios.camera.c:1218-1225, 1269 vs 2708-2710 | power-sequence delays from the table are not clamped (sensor-register delays are): up to ~71 min with rails on, or in the panic path |
+| CAM-5 | low | CONFIRMED (arithmetic), PLAUSIBLE (reach) | hakios.camera.c:3316, 3347, 4053, 4036, 3436, 2197 | mode fields from the table only partly range-checked: `frame_length < 40` underflows, width/height unbounded |
+| CAM-6 | low | CONFIRMED | hakios.camera.c:3906-3938 | `keep_picture` has no lock: two writers interleave into the same `keep` buffer and header |
+| HAPTIC-2 | low | PLAUSIBLE | hakios.haptic.c:847-866 | the 1 s cap applies per vibration; back-to-back taps from user writes have no rest or duty limit, only the chip's fault flags |
+| TORCH-3 | low | CONFIRMED | hakios.torch.c:585-590, 608-618 | the 30 s cap is "ask anew": an unprivileged writer that writes 0 then a level again keeps the light on indefinitely |
+| DEV-1 | info | CONFIRMED | torch.c:575, haptic.c:828, camera.c:4000 | all three nodes are mode 0666: any process can use the camera, torch and motor, so user-space permission prompts are the only gate |
+
+## Details
+
+### CAM-1 camera read vs. session end: use-after-free of the frame ring
+
+`camdev_read` marks a place READING under `ios_lock`, drops the lock at 3869, then reads the globals `ring`, `ring_place_bytes` and `ring_frame_bytes` with no lock and copies the frame:
+
+```
+3873 vm_offset_t at = ring + (uint64_t)b * ring_place_bytes;
+3879 for (vm_offset_t line = at & ~63ul; line < at + n; line += 64) dc civac
+3884 error = uiomove((caddr_t)at, (int)n, uio);
+```
+
+The capture thread ends a session in `ios_stop()` (3401): it sets every place FREE under the lock (3405-3407, which also overwrites READING), then, without waiting for any reader, runs `titan_down(); power_down(); ring_free();` and `ring_free()` does `kmem_free(kernel_map, ring, ring_bytes)` and `ring = 0` (3370-3374). Nothing counts readers, so a reader mid-copy keeps a pointer into freed memory.
+
+Ways the session ends while a reader is copying (a 12 MB frame is copied in milliseconds, and the code itself logs the time at 3891):
+- another process writes `HAKIOS_CAMERA_SENSOR` (3969-3978): `ios_switch_to` is seen by the loop at 3512, `ios_stop` runs within about 1 ms;
+- no read activity for `IDLE_MS` (1000 ms, 3526): `ios_last_read` is only refreshed at the start of a read (3810, 3843) and at its end (3899), not during the copy, so a reader that is descheduled or stuck in page faults on a big user buffer for 1 s is declared idle;
+- any fault (`healthy()`, SMMU fault, 1.5 s without a frame, an exposure write NACK) -> `give_up` -> `ios_stop`.
+
+Result: `dc civac` on the unmapped VA (a cache-maintenance fault from kernel code with no recovery handler) -> kernel panic; if the range was reused (the next `ring_alloc`, or any other kmem allocation) `uiomove` copies unrelated kernel memory out to user space; if `ring` was already zeroed, `at` is a near-NULL address. Reachable by any process that can open the 0666 node.
+
+Fix (sketch):
+```
++ static unsigned ios_readers; /* under ios_lock */
+ camdev_read: under ios_lock, after choosing b:
+- place[b].state = PLACE_READING;
++ place[b].state = PLACE_READING; ios_readers++;
++ snapshot at/n/ring_frame_bytes into locals here, still under the lock
+ ... at the end (the existing lock at 3895):
++ ios_readers--; wakeup(&ios_readers);
+ ios_stop(), before ring_free():
++ lck_mtx_lock(&ios_lock);
++ while (ios_readers != 0) msleep(&ios_readers, &ios_lock, PZERO, "hakios-camera-drain", NULL);
++ lck_mtx_unlock(&ios_lock);
+```
+Also refresh `ios_last_read` while `ios_readers != 0` in the idle test.
+
+### CAM-2 unprivileged control of sensor and mode; permanent shutdown
+
+`HAKIOS_CAMERA_SENSOR` accepts any sensor index (< 4) and any mode number `c.b` (3969-3978). `ios_select()` honours an explicit mode directly: the 4:3 / 31 fps / 13 MP filter at 4019-4032 only runs when `mode_n >= ctab->modes`; an explicit mode is accepted if it passes the checks at 4035 (lanes, data type 0x2b, `width % 4`, fps and frame length non-zero). `ios_start()` then calls `ring_alloc(RAW10_STRIDE(width) * height)` (3436) for `RING = 3` places (3254, 3383) of kernel memory. If a table has a full-resolution mode (the S5KHM2SD is a 108 MP sensor; the tables are not in the repository, so NEEDS-HARDWARE/IMAGE for the actual sizes) this is hundreds of MB per session from an unprivileged process, and each session start repeats it.
+
+Consequences of failure are permanent: a failed `ring_alloc` or any other step in `ios_start` returns false -> `give_up("the camera did not start")` (3500-3503); `ios_select` failing for a sensor with no `.tab` in `fw/` (the build only installs tabs for module files present in `fw-camera/`, userland/build.sh:392-400) -> `give_up("a sensor that cannot be used")` (4091-4093). `broken` is never cleared (except in quiesce), every later open/read returns EIO (3785, 3816). The same holds for one transient NACK: `exposure_write` -> `give_up` (3356-3358, 3593-3595), `sensor_table` has no retry (2703), whereas the PMIC and chip-ID reads retry (697, 1432).
+
+Fix (sketch):
+```
+ camdev_write, HAKIOS_CAMERA_SENSOR:
+- ios_switch_mode = c.b;
++ ios_switch_mode = c.b; /* and in ios_select(): */
+ ios_select(), for an explicit mode_n also require
++ pixels <= 13000000 && fps_milli <= 31000
+ ios_select failure / ios_start failure for a switch requested from user space:
+- give_up(...)
++ fall back to the previous sensor/mode; only give_up on hardware faults
+ devfs_make_node(..., 0666, ...) -> 0660 with a group the media daemon is in
+```
+
+### TORCH-1 the off path is gated by the sticky `broken` flag
+
+`put()` begins with `if (broken || !allowed || ...) { give_up(...); return false; }` (330-333) and every failure inside `put()` calls `give_up()`, which sets `broken` (308-314). `dark()` is a chain of four `put*` calls (506-507) joined by `&&`. So:
+
+1. light is lit (`lit == true`), user asks a different level, `light()` -> `put_bits(FLASH_ITARGET0)` writes but the read-back differs (or the read fails) -> `broken = true`, `light()` returns false.
+2. `serve()` breaks out (605) and runs the last-ditch `if (lit) (void)dark();` (632-634). `dark()` -> `put_bits(FLASH_EN_LED_CTRL, 1, 0)` -> `get()` works (reads are not gated) -> value differs -> `put()` sees `broken` -> false. The channel stays enabled.
+3. The thread says "the light is given up on" and terminates (636, 723). From here nothing checks fault flags, battery temperature or the time limit; the LED stays on at the last current until `hakios_torch_quiesce()` at the run's end (which does reset `broken = false`, 751).
+
+The same happens when `dark()` itself loses a write mid-chain (cut path 612-614, trouble path 625: dark runs first, so a failed first step blocks the remaining steps). The retry at 632 is dead code in exactly the situations it is there for. Contrast with camera.c, whose off path uses a `force` argument (`pm8008_put(..., true)` at 813, `pgpio_put(..., true)`) for the same reason.
+
+Cheap trigger: none needed beyond one dropped/failed SPMI transfer; user space only has to change the level while lit (any process, 0666).
+
+NEEDS-HARDWARE: whether a LED stays lit after a failed read-back, and what it dissipates, is not derivable here (the file's own comment says Android's torch has no safety timer, 125 mA channel 0).
+
+Fix (sketch):
+```
+-static bool put(uint8_t reg, uint8_t value)
++static bool put(uint8_t reg, uint8_t value, bool force)
+- if (broken || !allowed || ...
++ if ((broken && !force) || !allowed || ...
+ dark(): use force=true for every write, and do not stop at the first failure (try all four, retry each up to 3 times)
+ serve() end: if (lit) { dark(); } with the forced path; also keep calling dark() every 100 ms until it succeeds or the run ends
+```
+
+### TORCH-2 `lit` is set after the enabling writes
+
+`light()` sets `lit = true` only at line 498, after `put(FLASH_MODULE_EN, 0x80)` and `put_bits(FLASH_EN_LED_CTRL, 1, 1)` (495-497). If the module-enable write lands and the channel write lands but fails its read-back (or the read fails), `put()` returns false, `lit` stays false, `broken` is set. Then:
+- level 2 (697): `light(1000)` false -> the whole `if` is skipped, no `dark()` at all (713);
+- level 3: `serve()` end `if (lit)` skipped (632);
+- `hakios_torch_quiesce()` `if (lit)` skipped (750); it only prints "(NOT DARK)" (762) and does not act on it.
+
+The module/channel may therefore stay enabled and unmonitored. NEEDS-HARDWARE for whether the chip actually lights in that state.
+
+Fix: set `lit = true` before the first enabling write (before `put(FLASH_MODULE_EN, ...)`), and let `dark()` clear it only on success; make quiesce call `dark()` when the read-back says not dark.
+
+### HAPTIC-1 haptic=5 serves without waveforms after a load failure
+
+```
+961 if (level >= 3 && configure() && load_waveforms() && level == 4) { ... play_effect }
+969 } else if (level == 5 && !broken) { serve(); }
+```
+`load_waveforms()` returns false without `give_up()` when the file is missing, shorter than 8 bytes, or its checksum does not add up (570-580). For level 5 the `else if` is then taken and `serve()` starts the motor service (waveform 1 for taps, 11 looped) although Android's waveforms were never written to the chip's RAM (the header comment promises "configured and loaded as for 3"). Effects played from RAM that holds whatever the chip had after reset/Android: NEEDS-HARDWARE (strength and length of such a waveform are unknown; the gain and the 1 s cap still apply).
+
+Fix:
+```
+- } else if (level == 5 && !broken) {
++ } else if (level == 5 && !broken && loaded) {
+```
+with `loaded` set by `configure() && load_waveforms()` evaluated separately from `level == 4`, and `give_up("the waveforms are not loaded")` on that path.
+
+### CAM-3 lens-motor supply vote not tracked on timeout
+
+`rails()` records the vote before asking (`rails_voted |= on;`, 1830) so a request that RPMh finishes after our 100 ms poll is still given back. `vaf()` records it only on success: `vaf_voted = on && done;` (2989). In `af_up()`, `if (!vaf(true)) return;` (3003) leaves `vaf_voted == false`, so `af_down()` (3066) never sends the off request, and quiesce does not know about it either. If the WRITE_WAITED commands were accepted but completion was not seen in 100 ms (rpmh_write 1796-1806), the DW9800's supply stays on. NEEDS-HARDWARE (whether a late completion happens).
+
+Fix: `vaf_voted |= on; ... if (!on) vaf_voted = !done;`, i.e. set it before the write like `rails()`.
+
+### CAM-4 power-sequence delays are not clamped
+
+`power_step()` ends with `sensor_delay(e->delay_us)` (1269). `delay_us` is a 32-bit field of the table (camsensor.py:131 packs `d * 1000` into a `<I`), `sensor_delay()` sleeps `us / 1000` ms (up to 4,294,967 ms) and the sensor-register path is clamped at 100 ms (2708-2710) but this one is not. A corrupt or odd table keeps the rails/MCLK up for the whole delay during power-up; in `power_down()` under `leaving` (panic path) `wait_ms` becomes `spin_us` (141-147) and spins with interrupts as they are. The table comes from the system image built by this repo's tool, so this is robustness, not an attack.
+
+Fix: `sensor_delay(us > 100000 ? 100000 : us)`.
+
+### CAM-5 mode fields only partly validated
+
+`ios_select()` checks lanes, data type, `width % 4`, fps and frame_length != 0 (4035-4036) but:
+- `frame_length < EXPOSURE_MARGIN (40)` makes `ios_ask.lines = frame_length - EXPOSURE_MARGIN` (4053) wrap to ~4G (clamped later at 3311) and `*frame_lines - EXPOSURE_MARGIN` (3316) wrap so the final clamp of `lines` is skipped; `exposure_write` default branch computes `extra = frame_lines - ios_mode->frame_length` (3347), which wraps if `shortest > FRAME_LINES_MAX`.
+- width/height have no upper bound: `RAW10_STRIDE(width) * ios_mode->height` is 32-bit (3436; also `frames_alloc` 2084 and 3161) and wraps; the SMMU mapping (sized from the ring) and the IFE's real write size then disagree, the SMMU refuses the overflow (so this is a fault, not corruption). In `smmu_up()` a mapping above 1 GiB gives `thirds > 512` and `second[... + t]` (2197) writes past the second-level page into the third-level pages of the same allocation (SMMU table corruption, not a heap overflow).
+
+Reachable only through the table (or CAM-2's mode selection). Fix: reject modes with `frame_length <= EXPOSURE_MARGIN`, `width > 16384`, `height > 16384` in `ios_select()` and `capture_sensor()`.
+
+### CAM-6 `keep_picture` unserialised
+
+`HAKIOS_CAMERA_KEEP` (3959-3960 -> 3906) does `bzero(keep header)`, fills the header, `uiomove`s into `keep + 4096` and updates `loader_recording[]` with no lock. Two writers (any process) interleave: header of one picture over the data of the other, `frames = 1`. Memory-safe (same bounds, `want <= keep_bytes` is checked at 3914). Fix: take `ios_lock` (or a dedicated mutex) around the body.
+
+### HAPTIC-2 no duty-cycle limit across taps
+
+`HAPTIC_MAX_MS` (349) limits one LOOP state, followed by an equal rest (906-910). A TAP (waveform 1, 856-859) has no rest: iOS (or any process writing to the 0666 node) writing a burst, 30 ms of silence, another burst ... starts a new tap each time `onset_us` changes (847). Only the chip's fault flags (checked every 50 ms, 925-929) stop it. PLAUSIBLE; whether this can overheat the motor is NEEDS-HARDWARE.
+
+### TORCH-3 30 s cap restarts on request
+
+`waiting_for_off` is cleared when `wanted == 0` is sampled (585-587) and `since` restarts when `applied` goes from 0 to nonzero (593-596). Any writer that writes `0`, waits more than the 20 ms poll, then writes a level re-arms the light for another `max_secs`. The cap is therefore a per-request cap, not a limit; the fault/temperature checks (100 ms) stay active. Informational unless the intent was a hard on-time limit.
+
+### DEV-1 device node permissions
+
+`devfs_make_node(..., 0666, ...)` for hakios-torch (575), hakios-haptic (828) and hakios-camera (4000). Anything that can open a device node gets frames, light and vibration. This is the precondition for CAM-1, CAM-2, CAM-6, HAPTIC-2 and TORCH-3 being reachable by unprivileged code.
+
+## Checked and found fine
+
+Torch
+- `torch_write` (520-533): loop reads exactly 4 bytes per `uiomove`, value clamped to 1000 (529), the current is then computed in `light()` as `125000 * permille / 1000` (no 32-bit overflow: max 1.25e8) and clamped twice (`code > ANDROID_ITARGET` 484). Nothing user-set reaches the ITARGET register unclamped. A trailing 1-3 bytes are left unconsumed (write returns short), no memory issue.
+- `torch_read` (539-544): `uiomove` of `MIN(4, resid)` from a local; no leak.
+- Register allow-list in `put()` (303-305, 327-333), read-back of every write (349-358), arbiter channel re-check before each write (335-338), `flash.id` check, mapping sizes: `ARB_CHANNEL(n)` and `ARB_OWNER(n)` at n <= 511 are inside the 0x1100/0x1000 mappings, observer `0x80 * 511 + 0x1c` is inside 0x10000, write channel mapped 0x1000.
+- `spmi_read_once`/`show_registers`/`trouble` buffers (`r[8]`, `more[8]`, `latched[2]`, `data[2]`) sized for the counts used; `count - 1` with count 1-8 only.
+- Every polling loop has a bound: `wait_done` 2 ms, retries 3, serve loop 20 ms steps, level-2 loop `secs`.
+- Boot-args: `torch` (clamped 1-3, 731-734), `torch_max_s` (1..120, 687), `torch_secs` (1..max, 694); `now - since >= max_secs * 1000ull` (608) is 64-bit.
+- `hakios_spmi_lock` is a spin lock held for at most one transfer (<= 2 ms); not held across `say`/sleep.
+- Light is switched off in the cut path (612) and the trouble path (625) in the right order (dark before give_up), and on quiesce (750-752).
+
+Haptic
+- `haptic_write` (689-727): 512-byte stack buffer, `bytes` capped to that and made even (698-701), `uiomove` size matches; `-(int32_t)samples[i]` cannot overflow in 32 bits; shared state is `volatile` 64/32-bit, a lost update of `heard_peak` is benign. No path blocks.
+- `load_waveforms` (563-621): size >= 8 checked before any index; checksum over the file; writes `file + 4 + at` in chunks of at most 32 with `n = min(32, length - at)` so never past `size`; read-back compared chunk-wise with a 64-byte local; `length = size - 4` cannot underflow. The chip's RAM capacity is NEEDS-HARDWARE, but a too-large file fails the compare and gives up.
+- I2C by hand: clock stretch bound 100 x 5 us (216), bus_take restores the pins when the bus is not at rest, no unbounded loop; register read buffers sized to counts (1, 2); `regs_read` leaves caller buffers initialised (callers zero them).
+- LOOP vibration stop path: cut at `HAPTIC_MAX_MS` (902-908); a stop that fails -> `give_up` -> reset pin low (352-359), which does not depend on I2C; a failed gain write or health check also gives up. Exits from `serve()` all go through `broken`. `gain_for` cannot exceed Android's 0x80 (814-816).
+- Boot-args: `haptic` (clamped 5, 985), `haptic_effect` (1..10, 965).
+- Quiesce puts the chip in reset (997-1003).
+
+Camera, kernel side
+- Sensor table parse (`ctab_load` 1106-1143, `ctab_block` 1146-1161, `ctab_find`): magic, `size >= sizeof(head)`, `modes` 1..16, `at + 12 > end` before each power block header, `ctab_tables + 4 > end`; every block is re-checked `at + 12 + n * 12 <= end` before use (`n * sizeof` is 64-bit so it does not wrap; the pointer arithmetic can only exceed `end` by < 51 GB, no wrap at kernel VAs); the mode array is covered by the `ctab_power` check. `sizeof(struct ctab_entry)` is 12 and `ctab_mode` 48, matching camsensor.py's packing.
+- `sensor_table` (2676-2714): operation/address/data widths validated per entry (2689), `out[4]` always enough, per-entry delay clamped to 100 ms. `read_chip_id`: `in` forced to 1-4 so `id[4]` is safe, `out` is 1 or 2.
+- All table-driven power kinds are validated (`power_step` 1233-1268): MCLK only 0/19200/24000, supply kinds only 1-3, others -> give up; the voltage written to an LDO can only be the one in `sensors[]` (`sensor_ldo`/`pm8008_put` allow-lists 645-653, 688-691; arrays indexed with `n <= 7`).
+- Register write allow-lists: camcc (875-879), PM8008i, PMIC GPIO 3 (555-559); read-backs on all of them; off paths for camera use `force` and always run to the end (`power_down`, `ldo_off`).
+- Every polling loop is bounded: `wait_done`, `wait_bits`, `wait_reg`, SMMU TLB sync (2222), clock branches (1986), `rpmh_write` (100 ms), `ios_session` (frame timeout 1.5 s, 3521), `wait_standby`, `bus_unwedge`, `capture_tpg` (2 s), `capture_sensor` (5 s).
+- User commands (`camdev_write` 3942-3981): fixed 24-byte struct, size checked first; `HAKIOS_CAMERA_SENSOR` index bounds-checked (3970); EXPOSURE values are unclamped when stored but clamped before use in all three consumers (3480, 3591, 3705, 3728); FOCUS clamped to 1023 in `af_move` (3039). `keep_picture` bounds: `bytes != 0`, `d` 1-3, `stride * height <= 2 * bytes` in 64-bit, `want <= keep_bytes`, copy size `min(bytes, resid)`.
+- `camdev_read` header: `bzero(&f)` before filling, `MIN(sizeof(f), resid)`, so no uninitialised bytes leave; place indexes `b < RING`; state reads/writes under `ios_lock`, the lock is not held across `uiomove`/`msleep` misuse (msleep releases it).
+- Locking between ioctl-side and capture thread: shared `place[]`, `ios_ask`, `ios_given` are under `ios_lock`; `ios_switch_to`/`ios_open` etc are volatile flags; lock order is always (ios_lock) or (hakios_smmu_lock) or (spmi spin), never nested with each other. The one gap is CAM-1.
+- Single reader: a reader cannot be handed the place that is being programmed for the next frame (the next place is the lowest-sequence non-READING place, the reader takes the highest unread), so I found no tearing with one reader; with two simultaneous readers I did not prove either way.
+- IFE DMA is confined by an SMMU context that maps only the ring (or `frames_bytes`); the order in `ios_stop` stops the write master (`paths_down`), tears the SMMU context down and only then frees memory. Cache maintenance (`dc civac` before reads, `dsb sy`) is present where the CPU reads DMA memory.
+- Idle timeout and frame timeout: a stalled sensor ends the session in 1.5 s (3521-3525).
+- Boot-args: `cam` (clamped 0-5), `cam_sensor` (string compared against the fixed names, cannot index out of range), `cam_mode` (checked against `modes` in both paths), `cam_frames` (1..300), `cam_fake_fps` (1..30), `cam_keep_mb` (<= 64), `cam_settle` (masked to a byte), `cam_vblank` (<= 0x3fff), `cam_gain`/`cam_shutter` clamped before the registers are written (3091-3103, `exposure_limits`). `cam_after` is unclamped, `secs * 1000` wraps for absurd values: trusted boot-arg.
+- `RPMh` command DB parse (`rpmh_resource`): `slave->count > 512` skipped, data offsets checked against the mapping, `levels[]` filled up to `max` only.
+
+Camera, user-space side
+- `isp_load_tuning` / `tune_set` (camera_isp.c:880-960): size window 8 B..16 MB, every count (`n <= 6`, `ccts <= 6`, `refs <= 16`) is checked before it is used as a loop bound or array index, every read is preceded by an `end - p` check, `memcpy(t->ref, p, refs * 12)` fits `ref[16][3]`. Gamma lookup is clamped to 0..4095 (line 411), so a NaN or huge gain from a bad file cannot index out of range. File and descriptor are released on every error path.
+- `camera_device.c` worker: header size handshake and read sizes match the kernel's `ring_frame_bytes`; EIO stops the worker.
+
+## Not checked
+
+- The cellular modem, QMI, IPA (out of scope).
+- Hardware facts: register layouts, timings, safe LED current and motor limits, whether reset stops the motor, whether RAM survives a soft reset, RPMh completion timing, SMMU attribute encodings (`CAM_PTE`, `SMMU_MAIR0`): not derivable from the repository.
+- The sensor tables and the `.isp` files themselves (`fw-camera/` is not in the tree): mode sizes, delays, lane assignments are assumed from tools/camsensor.py's description. `camsensor.py` and `camtuning.py` parsing of the vendor files (host-side tools) was not reviewed, only their output format.
+- The 1568-1750 stretch of hakios.camera.c (read-only `show_*` printers) and `userland/src/camera_isp.c` outside the tuning loader (demosaic, AE, AWB) and `camera_test.c`, `camera_avtest.m`: not read for safety.
+- `hakios_wifi_file()`/`image_file()` (hakios.wifi.c): assumed to return a stable read-only pointer into the image; ownership and alignment not verified.
+- `ml_io_map_unmappable` failure mode in `rpmh_resource` (cmd_db NULL dereference if the mapping fails): not verified.
+- Behaviour with two simultaneous camera readers beyond what is said above; behaviour when `psci_smp_stop_others()` leaves a stopped CPU holding `ios_lock` or `hakios_smmu_lock` (the quiesce paths skip those locks when `leaving`, torch/haptic/camera all do).
+- Interplay with the audio DSP driver's use of the RPMh TCS 0 and with hakios.speaker.c / buttons for shared pins and the SPMI arbiter beyond the spin lock.
+- userland/src/inject_media.c (writes the torch node) and the camera ISP's float handling.
diff --git a/docs/driver-review/gpu-display.md b/docs/driver-review/gpu-display.md
new file mode 100644
index 0000000..5add9a3
--- /dev/null
+++ b/docs/driver-review/gpu-display.md
@@ -0,0 +1,198 @@
+# GPU and display driver review
+
+## Scope and method
+
+Read-only review of the user-reachable surface of the GPU and display code. Nothing was built or run; the XNU source tree itself is not in this repository (only `xnu/files` overlays), so XNU API behaviour is not verified here.
+
+| File | Lines |
+|---|---|
+| `xnu/files/bsd/dev/hakios.adreno.c` | 3843 |
+| `xnu/files/iokit/Kernel/hakios.gpu.cpp` | 1192 |
+| `xnu/files/iokit/Kernel/MiniIOMobileFramebuffer.cpp` | 1531 |
+| `xnu/files/iokit/Kernel/MiniIOSurface.cpp` | 1814 |
+| `xnu/files/iokit/Kernel/MiniIOSurface.h` | 174 |
+
+Method: read all of `hakios.gpu.cpp`, `MiniIOSurface.cpp/.h` and `MiniIOMobileFramebuffer.cpp` end to end; in `hakios.adreno.c` read the register helpers, SMMU/page-table code, ring and submit code, the "GPU kept on" API (lines 3157-3520), firmware parsing, boot-arg parsing and the init path. The bring-up steps (clocks, RPMh, TrustZone) were skimmed only. Each finding below was traced from an entry point (IOKit external method) to the faulty line. Hardware effects are labelled NEEDS-HARDWARE.
+
+## Findings
+
+| id | severity | confidence | location | summary |
+|---|---|---|---|---|
+| G1 | High | CONFIRMED | adreno.c:2399-2404,2569-2571; gpu.cpp:928-944 | User command buffers go to the GPU unvalidated, in the same SMMU context as the kernel's ring and fence page, mapped writable; no register protection |
+| G2 | High | CONFIRMED | MiniIOSurface.cpp:574-613; MiniIOMobileFramebuffer.cpp:738,786-787 | Surface geometry (row stride, element height, wrapped size) is not checked against the allocation; the display reads past the surface |
+| G3 | Medium | CONFIRMED | gpu.cpp:1139-1149,189-215 | Any client can latch the "GPU stopped answering" flag forever by waiting on a fence that was never issued |
+| G4 | Medium | PLAUSIBLE | gpu.cpp:463-508,189-209 | freeBuffer() drops the lock inside gpuWait() while the buffer is still live: concurrent close of the same handle can free it twice |
+| G5 | Medium | CONFIRMED | MiniIOMobileFramebuffer.cpp:733-745,608-613 | Destination rectangle from the swap request is not clipped; int32 arithmetic and a multi-billion-iteration row loop |
+| G6 | Medium | CONFIRMED | gpu.cpp:698,1037-1045; MiniIOSurface.cpp:598-615 | No per-client or global memory caps on wired buffers/surfaces; kHakiosShow allocates rowBytes*height unbounded |
+| G7 | Low | CONFIRMED | MiniIOSurface.cpp:1203-1211 | Read of a freed MiniIOSurface in methodCreate() when the reply buffer is too small |
+| G8 | Medium | PLAUSIBLE | MiniIOMobileFramebuffer.cpp:1256-1274 vs 1213-1219 | vsync thread sends to a notification port that registerNotificationPort() can release concurrently |
+| G9 | Low-Medium | CONFIRMED (absence of check) | MiniIOSurface.cpp:1255,731; gpu.cpp:782; all initWithTask | Surfaces are looked up (and mapped, and handed to the GPU) by small sequential ID with no ownership or privilege check |
+| G10 | Low | CONFIRMED | MiniIOMobileFramebuffer.cpp:750-770 | Allocation-failure path leaves fBlendRowSize=0 while helper arrays exist; a later free uses the wrong size |
+| G11 | Low | CONFIRMED | gpu.cpp:871-872,986-987 | Submit with only non-CMD_BUF commands logs uninitialised stack words |
+| G12 | Low | CONFIRMED | adreno.c:1836-1837,1810 | GMU firmware block address+size is 32-bit and can wrap in range checks (image is trusted, so hardening only) |
+| G13 | Low | CONFIRMED | adreno.c:3314-3336,3352-3364 | GPU address free list has no double-free check; TLB sync result ignored |
+| G14 | Low | CONFIRMED | gpu.cpp:253-265 | Signed overflow in millisecondsUntil() on user-supplied seconds (effect bounded by the 5 s cap) |
+| G15 | Low | CONFIRMED | adreno.c:3460-3466 | hakios_gpu_submit() busy-waits up to ~2 s with the global GPU lock held when the ring is full |
+| G16 | Low | NEEDS-HARDWARE | adreno.c:2399; MiniIOMobileFramebuffer.cpp (drawLayer) | CPU caches are cleaned before the GPU runs but never invalidated before the CPU reads what the GPU wrote |
+| G17 | Low | PLAUSIBLE | gpu.cpp:538-575 | A request racing clientClose() can create a buffer after the cleanup loop; free() does not release it |
+
+## Details
+
+### G1 No command-stream validation; kernel GPU memory shares the user address space (High, CONFIRMED)
+
+- `hakios.gpu.cpp:928-944` accepts any buffer/offset/size for a command buffer and passes the GPU address to `hakios_gpu_submit()` (`hakios.adreno.c:3479-3484`) as an indirect-buffer packet. The only checks are alignment and `offset+size <= b->size`. Contents are never inspected.
+- `hakios.adreno.c:2395-2396` states that the register-protection setup of Linux's hw_init was deliberately left out ("less ... the protection of registers against user programs' commands"). A search of the file finds only `CP_PROTECT_STATUS` (a read); no protect table is ever written.
+- The kernel's own ring (`CORE_RING_ADDRESS 0x01000000`), the fence/timing scratch page (`CORE_SCRATCH_ADDRESS 0x01200000`) and, during bring-up, the target page are created by `block_new(..., PTE_CORE)` (lines 2569, 2571, 2895) in `core_space`, the same context that user buffers are mapped into (`hakios_gpu_map`, line 3342). `PTE_CORE` has the "unprivileged" bit and is not read-only. User buffers start at `GPU_ADDRESSES_START 0x20000000` in the same tables.
+- Failure scenario: a client builds a command buffer whose packets write to the fixed ring or fence addresses, or to another client's buffers (all clients share one address space; the file header admits this). Effects: forged fence completion (so `freeBuffer()`/`reap()` release memory the GPU still uses), a corrupted ring (the kernel's next commands are replaced), cross-client reads and writes of pixel buffers, and a command stream that never completes (no hang recovery exists; `gGPUReported` then stays set). Which GPU registers a user packet can reach with no protect table is NEEDS-HARDWARE.
+- Suggested fix (outline): map ring, scratch and microcode with the privileged attribute so unprivileged GPU accesses to them fault; write a CP_PROTECT table as Linux does; give each client its own SMMU context or at least IOVA ranges, as the header already lists as future work; add a hang timeout and reset.
+
+```
+-#define PTE_CORE (PTE_GMU | PTE_UNPRIVILEGED)
++#define PTE_CORE_USER (PTE_GMU | PTE_UNPRIVILEGED) /* user buffers */
++#define PTE_CORE_KERNEL PTE_GMU /* ring, scratch, sqe */
+```
+(and use `PTE_CORE_KERNEL` in `step_core_space`/`step_frame`; privilege semantics are NEEDS-HARDWARE).
+
+### G2 Surface geometry not validated against the allocation (High, CONFIRMED)
+
+Path: `IOSurfaceRootUserClient::methodCreate` (user dictionary) -> `surfaceCreate()` -> later `IOMobileFramebufferUserClient` SwapEnd -> `present()` -> `show()` -> `drawLayer()`/`record()`. The framebuffer trusts `s->info.bytesPerRow`, `info.width/height` and `pixels()`.
+
+What is checked at creation (`MiniIOSurface.cpp`):
+- width/height <= 16384, element sizes <= 255, `needed = bpr * ceil(height / eh)` (line 580) must fit in `alloc` and <= 512 MB.
+
+What is not:
+1. No minimum for `IOSurfaceBytesPerRow` (line 574): a stride smaller than `width * bytesPerElement` is accepted. `drawLayer` (MiniIOMobileFramebuffer.cpp:738) only checks the source rectangle against `info.width/height`, then reads `sy*stride + sx*4 .. + sw*4` per row, so the last row ends beyond `allocSize`.
+2. The row count used for the size is `ceil(height/eh)` but the display reads `height` rows. With `IOSurfaceElementHeight` > 1 the allocation is smaller than `height * bytesPerRow`, by up to a factor of 255.
+3. Wrapped client memory (lines 608-613): after `alloc` was raised to `needed`, it is overwritten by `IOSurfaceAllocSize` as given (possibly smaller than needed, or zero) with no re-check and no 512 MB limit. `kpixels` then points into a kernel mapping of exactly `alloc` bytes while `info` still claims the larger geometry.
+4. Multi-plane case: `p->size = p->bytesPerRow * rows` (line 539) is 32-bit and can wrap; plane width/height are not capped (only the top-level ones are); `p->offset` is taken from the caller.
+
+Failure: the presenter thread reads kernel memory past the surface (kernel panic if the range is unmapped; otherwise adjacent kernel data is rendered to the panel and, with `rec_secs`, into the recording). Needs any process that can open the surface and framebuffer user clients; neither does a privilege check (G9).
+
+Suggested fix:
+```
+ bpr = dictNumber(props, "IOSurfaceBytesPerRow", 0);
++minRow = alignUp((uint64_t)((width + ew - 1) / ew) * bpe, 1);
++if (bpr != 0 && bpr < minRow) return NULL;
+...
+-needed = (uint64_t) bpr * ((height + eh - 1) / eh);
++needed = (uint64_t) bpr * height; /* the display reads `height` rows */
+...
+ } else {
+- alloc = dictNumber(props, "IOSurfaceAllocSize", (uint32_t) needed);
++ if (alloc > MINISURF_MAX_ALLOC) { ...release; return NULL; }
+ }
+```
+and in `drawLayer()` refuse any surface where `info.offset + (uint64_t)(info.height-1)*bytesPerRow + (uint64_t)info.width*4 > info.allocSize`; compute plane sizes in 64-bit and cap them.
+
+### G3 Any client can latch the GPU-stopped flag (Medium, CONFIRMED)
+
+`externalMethod` case `kMsmWaitFence` (gpu.cpp:1139-1149) passes the fence number from the request straight to `gpuWait()`; `hakios_gpu_done()` (adreno.c:3375-3381) compares with a signed difference, so a fence number ahead of the last issued one is never "done". The wait time comes from the caller's timeout, capped at 5000 ms (`millisecondsUntil`). In `gpuWait` (lines 210-213), a wait of >= 1000 ms that fails sets `gGPUReported = true` and calls `hakios_gpu_report()`. The flag is never cleared (searched), and `gpuWait()` returns false immediately while it is set (line 203).
+
+Effect for all clients afterwards: every wait fails at once, the display presents half-drawn surfaces (`MiniIOSurfaceDrawn` false), and `freeBuffer()` treats any buffer the GPU is still busy with as stuck and keeps its memory and GPU address permanently (lines 480-490).
+
+Suggested fix: reject fences greater than `hakios_gpu_last()` in `kMsmWaitFence`, and set the latch only for a fence that has really been issued:
+```
+ case kMsmWaitFence:
++ if ((int32_t)(r.waitFence.fence - hakios_gpu_last()) > 0) { ret = kIOReturnBadArgument; break; }
+```
+
+### G4 Lock dropped inside freeBuffer() while the buffer is still live (Medium, PLAUSIBLE)
+
+`freeBuffer()` (gpu.cpp:467-468) calls `gpuWait(b->fence, 1000)` when all 64 `fLeft` slots are taken; `gpuWait` unlocks `gGPULock` (lines 206-208) around `delay_for_interval`. During that window `b->memory` is still non-NULL and the handle is valid, so a second thread issuing `kDrmGemClose` (line 1163) for the same handle (or `clientClose`) enters `freeBuffer()` for the same buffer. Both then do the same `hakios_gpu_unmap`/`hakios_gpu_address_free`/`memory->release()`/`MiniIOSurfaceDrop`, and `fBufferCount--`/`fBufferBytes` are decremented twice. `hakios_gpu_address_free` has no overlap check (G13), so a double free corrupts the address free list. Needs 64 submissions' worth of busy buffers closed early plus two racing threads, hence PLAUSIBLE.
+
+Suggested fix: mark the buffer as being freed before any unlock:
+```
++struct gpu_buffer * b ... ; save = *b; b->memory = NULL; b->surface = NULL; /* handle gone */
++/* operate on `save` from here on */
+```
+(or set a `closing` flag that `buffer()` honours).
+
+### G5 Destination rectangle from the swap request is unclipped (Medium, CONFIRMED)
+
+`drawLayer()` takes `dst[]` (x, y, w, h as int32) straight from the swap structure (`swap + SWAP_DEST(layer)`). Only `dw <= 0 || dh <= 0` selects defaults (line 733). `py0 = dy*panelH/H`, `py1 = (dy+dh)*panelH/H` (lines 743-745) where `dy+dh` is computed in 32 bits first (signed overflow). Only `py1 <= py0` is rejected, and `drawRows()` iterates `for (y = y0; y < y1; y++)` with a `continue` for rows outside the panel (lines 608-613), so a rectangle spanning about 2 billion rows costs seconds of CPU per frame in the presenter thread; the helper threads split the same range. Panel memory writes themselves are bounded by the `y` and `cx0/cx1` clipping.
+
+Suggested fix: clamp `py0/py1` to `[0, fPanelHeight]` (and `px0/px1` to the panel width) immediately after computing them, and compute `dx+dw`, `dy+dh` in int64.
+
+### G6 No resource limits on wired memory (Medium, CONFIRMED)
+
+- `gemNew` (gpu.cpp:698): each buffer is limited to 256 MB and each client to 8192 handles, but `fBufferBytes` is only used for logging; there is no byte cap per client or in total. The GPU address pool (3.5 GB) is shared by all clients, so one client can also exhaust it.
+- `surfaceCreate` (MiniIOSurface.cpp:598-615): up to 512 MB each, 16384 table slots, `gSurfaceBytes` tracked but not limited. Memory is wired kernel memory.
+- `HakiosGPUUserClient::show` (gpu.cpp:1037-1045): `size = rowBytes * height` with `rowBytes` a free 32-bit value (only `>= 4*width` is checked) and height up to 4096, passed to `IOMallocData()` and then `copyin()`. Size can reach tens of terabytes; large-but-satisfiable values wire memory. This selector also works when the GPU is not ready (line 1103).
+
+Suggested fix: cap `rowBytes` (e.g. `<= 4 * 4096`... use `rowBytes <= 64 * width` or an absolute 1 MB), add per-client and global byte budgets enforced in `newBuffer()` and `surfaceCreate()`.
+
+### G7 Use of a freed surface in methodCreate() (Low, CONFIRMED)
+
+At MiniIOSurface.cpp:1201-1207: `addRef(s)` takes a hold; if `returnSurface()` fails (the caller's output buffer is smaller than the result, a caller-controlled condition: line 1059), `dropRef(ref)` runs, then `surfaceUnhold(s)` drops the creator's hold, `holders` reaches zero and `s->release()` frees the object. Line 1211 then reads `s->info.allocSize` after the unlock. Only a stale read that selects the logging block, but it is a use-after-free on a heap object whose state the caller influences indirectly.
+Fix: copy `allocSize` into a local before `surfaceUnhold(s)`.
+
+### G8 Notification port released while the vsync thread may still send to it (Medium, PLAUSIBLE)
+
+`vsync()` (MiniIOMobileFramebuffer.cpp:1256-1274) copies `fPorts[kFBNotifyVSync]` into an async reference under `fLock`, unlocks, then calls `sendAsyncResult64WithOptions`. `registerNotificationPort()` (1213-1219) swaps the port under the lock but releases the old one outside it. A client that re-registers the port while the timer fires can leave the thread sending to a released port. Whether `sendAsyncResult64WithOptions` takes its own reference is XNU behaviour not verifiable here.
+Fix: hold the lock across the send, or take a port reference in `vsync()` and drop it afterwards.
+
+### G9 No privilege or ownership checks (Low-Medium, CONFIRMED absence)
+
+`initWithTask` of all three user clients (gpu.cpp:438, MiniIOSurface.cpp:921, MiniIOMobileFramebuffer.cpp:1145) accept any task. `methodLookup` (MiniIOSurface.cpp:1255) maps any existing surface by its integer ID (IDs are sequential from 1 up to 16383 and reused; `gSurfaceNext`), `kHakiosSurface` (gpu.cpp:782) hands any surface's pixels to the GPU, and `SwapEnd` accepts any surface ID. Any process that can open these services can therefore read or overwrite other processes' pixel buffers and drive the panel. If the intended design is that the sandbox gates these services, this is by design; it should be documented.
+Related, needs verification against XNU: freed big-surface memory is kept and re-issued to later surfaces (`surfaceMemoryBack`, lines 228-231) on the strength of `getRetainCount() == 1`, which counts IOKit references only, not duplicate VM mappings that a process may have made of the shared memory.
+
+### G10 fBlendRow allocation-failure path (Low, CONFIRMED)
+
+MiniIOMobileFramebuffer.cpp:750-770: on a failed `IONew` the code frees `fBlendRow` and sets `fBlendRowSize = 0`, but the helper arrays that did get allocated (with the new, larger size) remain; the next growth runs `IODelete(fHelperBlend[i], uint32_t, fBlendRowSize)` with size 0. Keep a separate size per allocation or free all arrays on failure.
+
+### G11 Uninitialised words logged (Low, CONFIRMED)
+
+gpu.cpp:871-872: `addresses[]`/`words[]` are uninitialised; if every command has `type != MSM_SUBMIT_CMD_BUF`, `count` is 0 and the first four submissions log `addresses[0]`, `words[0]` (lines 985-988), exposing stack bytes to the kernel log. Also a zero-command submission is passed to the ring. Fix: `memset` the arrays and reject `count == 0`.
+
+### G12 GMU firmware block arithmetic (Low, CONFIRMED)
+
+adreno.c:1836-1837: `block.address + block.size <= gmu_blocks[i].address + gmu_blocks[i].size` is evaluated in 32 bits; a wrapping block passes the check and `memcpy` (line 1838) writes `block.size` bytes into a block that is smaller. Same pattern at line 1810 (`in_tcm(block.address + block.size - 1)`). The file is part of the signed-by-nobody boot image, so this is hardening against a corrupt or malicious image. Compute in `uint64_t`, and also check `block.size <= remaining file size` before copying (the loop at 1756 does check the end of the file).
+
+### G13 Address allocator and TLB invalidate (Low, CONFIRMED)
+
+`hakios_gpu_address_free()` (adreno.c:3314-3336) merges by position only; freeing a range that is already free (see G4) or overlapping silently corrupts the list, and when the 1024-entry table is full the range is dropped. `hakios_gpu_unmap()` (3362) polls `TLBSTATUS` at most 1000 times and ignores the result; the memory is released by the caller immediately afterwards, so a context whose invalidate did not complete could still translate to freed pages (NEEDS-HARDWARE).
+
+### G14 Signed overflow (Low, CONFIRMED)
+
+gpu.cpp:260: `when->seconds * (int64_t) NSEC_PER_SEC` overflows for caller-supplied seconds. The wait is still capped at `GPU_PATIENCE_MS`, so the effect is a wrong timeout, not unbounded.
+
+### G15 Long poll with the global lock held (Low, CONFIRMED)
+
+adreno.c:3460-3466: up to 20000 iterations of `sleep_us(100)` with `gGPULock` held (caller `submit()`), blocking every other GPU request for about two seconds when the ring is full (which a client can cause, see G1).
+
+### G16 Cache maintenance direction (Low, NEEDS-HARDWARE)
+
+Before each submission buffers are cleaned and invalidated (`dc civac`, adreno.c:1219-1222 via gpu.cpp:922). After the GPU finishes, CPU readers (display `drawLayer`, `record`) do not invalidate the surface memory. Page-table attributes for GPU accesses are non-cacheable (`PTE_CACHED` is never set in `PTE_CORE`, adreno.c:1177,2399). Whether stale CPU cache lines for surface pages can reappear between submit and completion depends on prefetching and on the bus's coherency, which cannot be established from the repository.
+
+### G17 Close racing a request (Low, PLAUSIBLE)
+
+`clientClose()` (gpu.cpp:538-565) walks `fBuffers` once with the lock dropped inside `gpuWait`; `free()` (567-575) frees the table without releasing any buffer still present. A request that creates a buffer in the gap leaks its memory descriptor and GPU address. IOKit's own serialisation of close against in-flight calls was not verified.
+
+## Checked and found fine
+
+- `externalMethod` input handling in `hakios.gpu.cpp` (1095-1107): the structure size is bounded by `sizeof(r)`, the union is zeroed before the copy, output is clamped to the input size and copied from the zeroed union, so no uninitialised data goes back.
+- `submit()` array bounds: `nr_cmds <= 128` and `nr_bos <= 8192` are checked before the `IONew`/`copyin` size multiplication (no overflow possible), `submit_idx < nr_bos` is checked, `submit_offset + size <= b->size` is computed in 64-bit, size and offset are 4-byte aligned, `nr_relocs != 0` is rejected, `addresses[]/words[]` are bounded by 128, the error path unlocks and frees both allocations.
+- Ring arithmetic in `hakios_gpu_submit()`/`ring()`/`ring_send()` (adreno.c:2486-2519,3456-3497): fixed packet words (20) plus 4 per IB is below the `26 + 4*count` reservation; wrap-around flushes both halves; free space formula is correct for an empty and a full ring; fence slots (`GPU_TIMES_AT + 16*slot + 8*end`) stay inside the scratch page; the fence compare is wrap-safe for issued fences.
+- `gemNew`: size rounding via `round_page_64` cannot wrap to a nonzero value (a wrap gives 0 and is rejected); the kept-buffer path matches size and flags, rewrites the handle slot completely (`bzero`) and keeps counters balanced; `keep()` cannot dereference a NULL victim while the byte accounting is balanced.
+- Buffer lifetime across create/free: `freeBuffer`/`reap` release the descriptor and the surface hold exactly once on every branch except the G4 race; the "stuck" branches deliberately leak one reference, and the IOSurface variant retains the parent memory before releasing the sub-range, which keeps the pages alive.
+- `newBuffer`: address and handle are returned on failure, the partial mapping is unmapped, and the allocation size is page-granular; `IOSubMemoryDescriptor` range creation is done on `[PAGE_SIZE, PAGE_SIZE + round_page(allocSize))`, which fits inside the memory allocated for non-wrapped surfaces (`PAGE_SIZE + alloc` with `alloc` page-aligned); wrapped surfaces are refused by `surfaceBuffer`.
+- `clientMemoryForType`: the descriptor is retained under the lock and only the buffer's own range is exposed (surface buffers expose the pixel range, not the shared-state page).
+- Lock order: `gGPULock` is taken before `gSurfaceLock` (via `MiniIOSurfaceDrop`) and nothing takes them the other way round; `gSurfaceKeptLock` is a leaf.
+- `MiniIOSurface` per-client operations: `findRef` requires the caller's own reference; `copyValue`/`removeValue` require a NUL-terminated key; `setBulkAttachments` copies at most 0x65 bytes into the 0x70-byte area with the input length checked to 0x88; `returnSurface` checks the output size against `planeCount` (maximum 4, fits the planes array); use counts cannot go negative.
+- Page-table code (`space_map`, `space_next`, `space_commit`): the 39-bit check, 1024-table limit, table flush before the SMMU sees entries and use of `dsb` after `dc civac` look correct; the `static` spare-page allocator is always called under `gGPULock` after bring-up.
+- `drawLayer`/`drawRows` for in-rectangle reads: the source rectangle is bounded by `info.width/height` (int32 sum overflow cannot yield an accepted value), column indices are bounded by the panel width, blended reads of column `c+1` only happen when `c+1 < sw`; panel writes are clipped to the panel rows and `cx0..cx1`.
+- `MiniIOMobileFramebufferShow` (display driver side of `kHakiosShow`): row/column clipping against `vinfo` is correct given `rowBytes >= 4*width` (the allocation size is the problem, see G6).
+- Swap queue (`present`/`presenter`/`show`): slots are indexed modulo `SWAP_QUEUE`, surface holds are taken in `present` and dropped once by the presenter, the timeout path returns without leaking a hold.
+- Boot-arg parsing in `hakios_adreno_init()`: `adreno_only` is range-checked, `last_step` is clamped to `STEPS`, shift counts are at most 22, the `what[]` index is in range; `gpu_cached`, `gpu_keep`, `touch_lat`, `surftrace*`, `surf_clear` and the framebuffer tunables only select behaviour (`fb_threads`, `fb_queue`, `fb_hz`, `rec_step` are range-checked before use). `rec_mb` is not range-checked (a boot-arg only, outside the user attack surface).
+- Firmware loading in `step_gmu_space`/`zap_header`/`step_core_space`/`step_zap_load`: sizes from the file are bounded (`<= PAGE_SIZE` for the mdt header, `<= 0x40000` for the SQE image, `<= 0x1000` for the zap segment, `block.value <= 0x100000` and block count limited to 12 for the GMU) except the 32-bit arithmetic in G12; ELF header fields are checked against the file size before use.
+- Unbounded polling loops: all register polls in the files read are counted loops (`wait_for`, the GMU start poll, `ring_run`, `hakios_gpu_stop`); the user-facing waits are bounded by `GPU_PATIENCE_MS`.
+
+## Not checked
+
+- The bring-up steps' register sequences (clocks, RPMh, TrustZone/SCM calls, GMU message queue code `hfi_*`, steps 1-12 and 16-17 beyond skimming), and the quiesce/stop path (`gpu_block_stop`, 2960-3150) other than its interaction with `gpu_kept`.
+- Whether XNU zero-fills `IOBufferMemoryDescriptor` memory (the code relies on it), what `IOSubMemoryDescriptor::withSubRange` does with out-of-range arguments, how `OSUnserializeXML` treats size and NUL termination, whether the user mapping of a client's input descriptor is a copy or the live user memory (a double-fetch question for `methodCreate`/`setValue`), and cache attributes of user mappings requested through `IOConnectMapMemory`.
+- Whether IOKit serialises `clientClose()` against calls in flight (G17), and whether a user mapping of kernel-shared memory can outlive the `IOMemoryMap` (G9, second part).
+- Hardware behaviour: which GPU registers user packets can reach without a protect table, what the SMMU/GBIF coherency model is, and the SMMU TLB timing (G1, G13, G16).
+- `hakios.image.c` (`hakios_image_file`) and the callers outside this group (`HakiosGPUStart/Stop` call sites, `loader_return.c`).
+- Userland (`userland/src/eagl.c`, `tools/mesa/hakios-drm`) and the display_probe code (`adreno.c:3568-3703`; it only reads and writes two clock-enable bits).
+- Cellular modem code (out of scope).
diff --git a/docs/driver-review/input.md b/docs/driver-review/input.md
new file mode 100644
index 0000000..75475ef
--- /dev/null
+++ b/docs/driver-review/input.md
@@ -0,0 +1,191 @@
+# Driver review: input and touch
+
+## Scope and method
+
+Read-only audit; this is the only file written.
+
+| File (under xnu/files/bsd/) | Lines | Read |
+|---|---|---|
+| dev/hakios.input.c | 228 | all |
+| dev/hakios.goodix.c | 1515 | all, except the array in hakios.focaltech_fw.h (only its header: `FOCALTECH_FW_LENGTH 116448`, declared as `focaltech_fw[FOCALTECH_FW_LENGTH]`) |
+| dev/hakios.buttons.c | 583 | all |
+| dev/hakios.virtio_input.c | 365 | all |
+| sys/hakios.input.h | 125 | all |
+
+Method: traced the producer path (goodix/focaltech/buttons/virtio thread -> `hakios_touch_post` -> `touch_queue` -> `touch_read` -> `uiomove`), every length that comes from a chip, the SPI engine, the command database or the firmware blob, every polling loop, every boot-arg. Cross-checked the shared hardware (RPMh TCS 0, GCC vote register, SPMI arbiter) against the other drivers in `dev/` by grep. The XNU kernel source itself is not in this tree, so behaviour of kernel primitives (`ml_io_map`, `delay_for_interval`, `uiomove`, `PE_parse_boot_argn`) is assumed to be standard. Nothing was built or run. No hardware facts are asserted beyond what the repository's own comments say.
+
+Confidence: CONFIRMED = path traced end to end in the source; PLAUSIBLE = mechanism is in the source but depends on timing or an input I cannot show occurs; NEEDS-HARDWARE = the code is as described but the effect depends on chip behaviour.
+
+## Findings
+
+| Id | Severity | Confidence | Where | One line |
+|---|---|---|---|---|
+| F1 | Medium | PLAUSIBLE | goodix.c:203-239 | `rpmh_write` uses RPMh TCS 0 without `hakios_rsc_lock`, which adsp.c and mpss.c take for the same TCS |
+| F2 | Medium | CONFIRMED (effect NEEDS-HARDWARE) | goodix.c:1353 | `io_supply_on()` result ignored; analog supply and pins are driven anyway, and a failed bring-up leaves everything powered |
+| F3 | Medium | CONFIRMED | input.c:213 | `/dev/hakios-touch` is mode 0666: any process can forge touches and buttons (including Lock) and read everyone's touches |
+| F4 | Low | CONFIRMED | input.c:170-176 | A record is dequeued before `uiomove`; a failed copy-out loses it |
+| F5 | Low | CONFIRMED | input.c:162-181 | `read()` with fewer than 24 bytes blocks for data, then returns 0 (EOF) without consuming anything |
+| F6 | Medium | CONFIRMED (absence); effect NEEDS-HARDWARE | goodix.c:1155-1161 | FocalTech firmware download is bounded but never verified before the application is started |
+| F7 | Low | PLAUSIBLE | goodix.c:1222-1227 | FocalTech coordinates are not clamped before mirroring: x above max-1 underflows |
+| F8 | Low | PLAUSIBLE | virtio_input.c:260-263 | No load barrier between reading `used->idx` and reading the ring entry and event |
+| F9 | Low | CONFIRMED | virtio_input.c:286-312 | Page from `kmem_alloc` leaked, device left half-initialised, on the two failure returns |
+| F10 | Low | NEEDS-HARDWARE | goodix.c:1410-1419 | Bit-bang fallback's second attempt drives the pin that the first attempt used as input |
+
+Counts: 6 CONFIRMED (F2, F3, F4, F5, F6, F9), 3 PLAUSIBLE (F1, F7, F8), 1 NEEDS-HARDWARE (F10). No memory-safety bug (out-of-bounds, overflow, info leak) was found in the queue or in the SPI buffers; see "Checked and found fine".
+
+## Details
+
+### F1. RPMh TCS 0 used without the shared lock (goodix.c:203-239)
+
+`rpmh_write()` programs command slots in TCS 0 of the application processor's DRV2 (`TCS(reg)` is `rsc + 0xd00 + reg`, goodix.c:122), with no lock. hakios.adsp.c programs the same TCS 0 (`RPMH_TCS 0`, adsp.c:821, 912-937) and mpss.c does too (mpss.c:899-937, 959-991), and both take `hakios_rsc_lock` (defined at wifi.c:192) for exactly this reason (the comment at wifi.c:192 and adsp.c:112 says the sequencer is shared). goodix.c does not reference `hakios_rsc_lock` anywhere.
+
+Scenario: `hakios_input_init()` starts the goodix thread (input.c:219) before adsp/modem init (input.c:226-227). The goodix thread calls `io_supply_on()` -> `rpmh_write()` at the start of `bring_up()`. If the audio-DSP or modem thread reaches its own `rails()` request while that is in flight, the two threads interleave writes of MSGID/ADDR/DATA, ENABLE and TRIGGER on one TCS. The worst outcome is a request mixing one driver's address with the other's data on a power rail (lcx/lmx level, or ldoc2 voltage). The window is short (the goodix request happens within milliseconds of the thread's start), so the likelihood depends on how soon the other threads get that far: PLAUSIBLE.
+
+Fix:
+```
++extern lck_mtx_t hakios_rsc_lock;
+ static bool rpmh_write(...) {
++ lck_mtx_lock(&hakios_rsc_lock);
+ ...
+- return done;
++ lck_mtx_unlock(&hakios_rsc_lock); /* and on the early "stay busy" return */
++ return done;
+```
+(`<kern/locks.h>` is needed; goodix.c does not include it today.)
+
+### F2. I/O supply failure ignored; failed bring-up leaves hardware on (goodix.c:1348-1357, 1454-1458)
+
+`power_on()` calls `io_supply_on();` and discards the bool (line 1353). That function returns false when the command database has no `ldoc2` (goodix.c:250-253) or when the TCS stays busy or the request times out (rpmh_write). The code then switches the analog supply on (`gpio_output(PIN_AVDD, true...)`, line 1355), configures the reset and interrupt pins as driven outputs/pull-ups (1351-1352), and goes on to drive SPI pins towards a chip whose I/O rail may be off. Whether back-powering or damage can occur is NEEDS-HARDWARE; the ignored error is CONFIRMED.
+
+Related error path: when `bring_up()` fails the thread prints and calls `thread_terminate` (1454-1458) with AVDD still high, the GCC clock votes still set, and the five `ml_io_map` mappings (1448-1452) never released. Small and one-time, but the chip is left powered with no driver.
+
+Fix:
+```
+- io_supply_on();
+- sleep_ms(3);
++ if (!io_supply_on()) { return false; } /* make power_on() return bool; bring_up() then reports and returns false before touching AVDD */
+```
+and, in the failure path, drive `PIN_AVDD` low and clear the votes.
+
+### F3. Device node is world read/write (input.c:213)
+
+`devfs_make_node(..., UID_ROOT, GID_WHEEL, 0666, "hakios-touch")`; `touch_open` (143-147) does no check. Any process that can open the node (subject to whatever sandbox the iOS userland applies; not examined here) can:
+- `write()` records: forged DOWN/MOVE/UP samples and `HAKIOS_BUTTON_DOWN/UP` with `finger = HAKIOS_BUTTON_LOCK`, which backboardd turns into the power key (inject.c:871-879). Only the five-finger exit is protected (it counts driver fingers only, input.c:130).
+- `read()`: steal the real touch stream (any reader takes records away from backboardd, since there is one shared queue with no exclusive open).
+
+Whether this matters depends on the iOS sandbox profile for third-party apps; in the kernel there is no restriction.
+
+Fix: `0600` (or `0660` with a dedicated group) and, if backboardd runs as another user, set that uid/gid in `devfs_make_node`; optionally make `touch_open` return `EBUSY` for a second opener.
+
+### F4. Record lost when copy-out fails (input.c:170-176)
+
+```
+t = touch_queue[touch_head++ % TOUCH_QUEUE];
+lck_mtx_unlock(&touch_lock);
+error = uiomove((caddr_t)&t, sizeof(t), uio);
+```
+`touch_head` is advanced before the copy. If `uiomove` fails (a user buffer that is partly unmapped, or one the process unmaps concurrently), the sample is gone; if `moved > 0` the function returns 0 and the failure is invisible. A lost UP or DOWN leaves the consumer's finger state stale (inject.c:818-821 ignores non-DOWN events for fingers it believes are up, and keeps a finger down until an UP). Same effect, from the producer side, when the 512-record ring overflows: `touch_head++` at input.c:115-117 drops the oldest record whatever its type. That second case is by design ("nobody reads") and only noted.
+
+Fix: peek first, advance after success (single-reader assumption) or push the record back:
+```
+- t = touch_queue[touch_head++ % TOUCH_QUEUE];
++ t = touch_queue[touch_head % TOUCH_QUEUE];
+ unlock; error = uiomove(...); lock;
+- if (error) break;
++ if (error) break;
++ touch_head++; /* only if it is still the same record: with two readers, re-check head */
+```
+
+### F5. Short read returns EOF (input.c:162-181)
+
+The first loop waits until the queue is non-empty regardless of the buffer size. The second loop requires `uio_resid(uio) >= sizeof(t)` (24). With a buffer of 1..23 bytes, `read()` blocks until a sample exists, then returns 0 with nothing consumed, which a caller reads as end of file; callers that retry spin at 100% CPU because the queue stays non-empty. The shipping consumer reads exactly 24 bytes (inject.c:950), so there is no current victim.
+
+Fix: at entry `if (uio_resid(uio) < (user_ssize_t)sizeof(struct hakios_touch)) return EINVAL;`.
+
+### F6. Touch-controller firmware download is bounded but not verified (goodix.c:1101-1124, 1155-1161)
+
+What is bounded: `focaltech_write_pram()` loops `offset < len` in 32-byte chunks, with the last chunk shortened (1106-1110); `len` is `FOCALTECH_FW_LENGTH` (116448, a multiple of 32), the array is declared with exactly that size, and the transfer buffer (71 bytes) holds the largest frame (7 + 32). The 24-bit PRAM address in `addr_bytes` cannot wrap (116448 < 2^24). The sequence is only entered after `focaltech_enter_boot_rom()` has read back the boot ID 0x56 0x62 with a valid CRC (1076-1094).
+
+What is missing: nothing checks the blob or what the chip received before `focaltech_start_app()` makes the boot ROM jump to it (1161). There is no checksum/length/magic check of `focaltech_fw` against a value fixed at build time, no read-back or on-chip check of the written PRAM, and the only per-chunk check is the status byte `rx[3] & 0xa0` (focaltech_write 1000-1001), which is the busy/CRC-error bit of the transfer, not of the content. A corrupted source blob or a dropped/duplicated chunk (retried up to 3 times by `focaltech_write`) is started as is. This download also runs automatically on every cold start where the runtime ID is not yet valid (1144-1167), and again up to three times in total if bring-up falls back to the pin-driven bus (chip_probe is re-run, 1402-1420).
+
+Whether this PRAM download can leave a persistent bad state in the chip's flash is not answerable from the sources here: NEEDS-HARDWARE. The comments (1096-1100) describe it as a RAM upload only.
+
+Fix: generate a CRC-32 (or SHA-256) of the blob next to `FOCALTECH_FW_LENGTH` in hakios.focaltech_fw.h and compare before the first write:
+```
++ if (crc32(0, focaltech_fw, FOCALTECH_FW_LENGTH) != FOCALTECH_FW_CRC) { printf(...); return false; }
+```
+and, if the boot ROM offers a checksum command (the vendor flow does, per its own source; I did not verify here), run it before `focaltech_start_app()`.
+
+### F7. FocalTech coordinates not clamped before mirroring (goodix.c:1222-1227)
+
+`x` is built from a 15-bit field (up to 32767, goodix.c:1265-1268) and the panel size is 10800 (1246). The code's own comment (1191-1192) calls the values 15-bit sub-pixel values. In `focaltech_contact_update` there is no clamp: with `touch_flip` 1 or 3, `x = max_report_x - 1 - x` wraps to about 4.29e9 when `x > 10799`, and `(uint64_t)x * 65535 / 10799` truncated to `uint32_t` is an unrelated number; `touch_post` only clamps values above 65535, so the touch can land anywhere. Without flip, the result exceeds 65535 and is clamped, so only the flip case is wrong. The Goodix path does clamp (`x >= max_x ? 65535 : ...`, line 819). Whether the chip ever reports above the panel size is NEEDS-HARDWARE, hence PLAUSIBLE.
+
+Fix: `if (x > max_report_x - 1) x = max_report_x - 1;` (same for y) before the `switch (flip)`.
+
+### F8. Missing load barrier on the virtio used ring (virtio_input.c:260-263)
+
+```
+while (d->seen != *(volatile uint16_t *)&d->used->idx) {
+ uint32_t id = d->used->ring[d->seen++ % QUEUE_SIZE].id % QUEUE_SIZE;
+ input_event(d, &d->events[id]);
+```
+The loads of `ring[]` and of `events[id]` are not ordered after the load of `idx` (the ring address depends on `d->seen`, not on the idx load; a control dependency does not order loads on arm64). The return path does have `dmb ish` before `avail->idx++` (265-267). Effect: on a host where the device model runs on another core with weak ordering (QEMU under KVM/HVF), a stale ring entry or event can be read, giving a repeated or wrong sample. Not reproduced; PLAUSIBLE. QEMU-only code (boot-arg `virtio_input=1`).
+
+Fix: `__builtin_arm_dmb(0x9); /* ISHLD */` after the `idx` read inside the loop, before touching `ring`/`events`. (The ring's `id` is already reduced `% QUEUE_SIZE`, so a bad value cannot index out of `events`.)
+
+### F9. Page leak and half-initialised device on attach failure (virtio_input.c:286-312)
+
+`input_attach` takes a page (286), then returns false at 305 ("features refused") and 312 (queue too small) without `kmem_free` and without resetting the device status (it stays at `FEATURES_OK` or lower, never `FAILED`). The caller just skips the slot (354). Cost: one 4 KiB page per failing slot, at boot, under QEMU only. Fix: `kmem_free(kernel_map, page, PAGE_SIZE); reg_write(d, VIRTIO_STATUS, 0x80);` before each `return false`.
+
+### F10. Bit-bang fallback may drive a chip output (goodix.c:1410-1419)
+
+If the serial engine path gets no answer, the driver tries twice by hand: first MOSI=gpio53 out / MISO=gpio52 in, then the reverse, because "which of the two data pins is the input is not written down anywhere" (its own comment). On the second attempt `bitbang_init()` configures gpio52 as a driven output (1413-1415, 565-568). If gpio52 is the chip's MISO output, two drivers fight on one line; the comment at lines 80-83 names 52 as MISO. Duration is short (one probe) but nothing limits the current beyond pin drive strength set at 6 mA. NEEDS-HARDWARE. Fix: probe the second orientation only with the former output pin as a pulled input and read-only for one cycle, or drop the swap now that the pin roles are documented in the same file.
+
+## Checked and found fine
+
+Queue and user space (hakios.input.c, hakios.input.h):
+- `struct hakios_touch` is 8+4+4+4+4 = 24 bytes, natural alignment, no padding. Every queue slot is fully written in `touch_post` (time, type, finger, x, y) before it is published under `touch_lock`; the static array is zero-initialised. `touch_read` copies a stack copy of one whole record: nothing uninitialised reaches user space.
+- Ring arithmetic: `TOUCH_QUEUE` is 512, `head`/`tail` are `uint32_t` free-running counters, indexed `% 512`; 2^32 is a multiple of 512, so wrap-around is exact. `tail - head == 512` is the full test and is correct across wrap; overflow drops the oldest, never writes past the array.
+- Locking: all `head`/`tail`/`fingers_down` accesses are under `touch_lock` (mutex); `msleep` releases it atomically so there is no lost wakeup; `wakeup` after unlock is fine. `touch_post` takes a mutex and calls thread_call APIs: it must not be called from interrupt context, which the header says, and none of the producers (goodix thread, buttons thread, virtio thread_call) does.
+- `touch_write` validates `type` in 1..5 before posting and clamps x, y to 65535 in `touch_post`; `finger` is unbounded in the queue but `count_fingers` ignores `finger >= 32` and driver-only posting is required for the exit combo; the consumer bounds `f >= MAX_FINGERS` (inject.c:818).
+- `count_fingers`: shifts guarded by `finger >= 32`; `thread_call_enter_delayed`/`cancel` under the lock are safe; `exit_call` is allocated before any driver starts (input.c:216-219).
+- `latency_lines()` is only called with the lock held; `hakios_tl` uses a 192-byte buffer with `vsnprintf`.
+
+Goodix chip path:
+- `goodix_read`/`goodix_write` reject lengths above 1024; `spi_tx`/`spi_rx` are 8+1024 bytes and the largest frame is 8+1024 / 5+1024. All callers pass constants or values bounded before the call.
+- `goodix_probe`: the chip-supplied description length is checked (`40 <= length < 1024`) before the second read; the five-list walk checks `offset >= length` before each `info[offset]`; the following reads at `offset+44..47`, `offset+122+16..19` are guarded by `offset + 48 + 2 <= length` and `offset + 122 + 20 + 2 <= length`; the version string prints use precision (`%.6s`, `%.8s`) on a non-terminated 28-byte buffer, and the offsets stay inside it. The 16-bit-sum check is weak, but the addresses taken from it (`touch_address`, `command_address`) are only used as SPI register addresses of the chip itself.
+- `goodix_poll`: `report` is 90 bytes; the first read is 26, the second `8 + 8*count + 2` with `count <= 10` (guard at line 862), maximum 90; `count` 11..15 is refused at line 885 after the header checksum. The ack write is a single zero byte.
+- `goodix_report`: finger id >= 10 skipped; `x * 65535 / max_x` cannot overflow `uint32_t` because `x < max_x <= 65535` is tested first; `max_x`/`max_y` come from `le16` and are only adopted if non-zero.
+- `goodix_command`: fixed 16-byte buffers, 6x6 bounded attempts, and `command_address == 0` is rejected.
+- `geni_transfer`: 200 ms deadline; busy-wait before start bounded (2000 x 100 us, then cancel/abort in `geni_recover`, itself bounded to 2 x 2000 x 100 us); `geni_drain` never writes beyond `length` (guarded by `*received < length`), and the unsigned underflow of `bytes` when `words == 0` is not used because the loop runs zero times; transfer lengths (<= 1032) fit the 24-bit TRANS_LEN registers; `fifo_depth >= 4` is checked before `fifo_depth - 3`, `- 2`.
+- Other polling loops all have counters: `rpmh_wait` (2000 x 100 us), the TCS-idle wait (2000), GCC clock wait (1000 x 10 us), SE clock configuration wait (500 x 10 us), `focaltech_wait_valid` (5 x 200 ms), `focaltech_enter_boot_rom` (3 attempts), `focaltech_read` (3 attempts), `goodix_command` (36 looks). The main loop is intentionally endless and sleeps `poll_us` per tick.
+- `rpmh_address`: the check `header_offset >= CMD_DB_SIZE - 0x1000` is vacuous for a `uint16_t`, but the largest possible access is 0x90 + 0xffff + 512 x 24 = 0x13090, inside the 0x20000 mapping, so there is no out-of-range read from a corrupt database. `count > 512` is skipped.
+- `rpmh_write` is only called with `count == 3` and 3-element arrays; `(1u << count) - 1` is in range.
+- `rcg_rate`: 64-bit intermediate, `cfg >> 8 & 7` indexes an 8-entry table, division guarded by `if (n)`.
+- Global `GCC_VOTE` (gcc + 0x52008) is only touched by this driver in the tree (grep over `dev/hakios.*.c`), so the read-modify-write at 310/340 has no other writer. The TLMM per-pin registers used here are not used by other drivers for these pins (not exhaustively checked for every pin number).
+- Boot-args: `touchscreen` (1508), `touch_flip` (1511, a mask or a switch value with no out-of-range effect), `touch_poll_us` (range-checked 250..100000 else 8000; `1000000 / poll_us` and `80000 / poll_us` cannot divide by zero; `idle_looks` becomes 0 above 80000 us, which means "look every tick", harmless), `touch_spi_hz` (100 kHz..10 MHz else 1 MHz; the 12-bit divider cannot overflow for the sources this code can pick, <= 600 MHz / 100 kHz = 6000 would, but the chosen source is the lowest preset >= 4 MHz or the crystal, so in practice <= 192), `touch_rate` (only the value 480 acts), `touch_lat`, `touch_flip`. All use `PE_parse_boot_argn` with a 4-byte target.
+- FocalTech: `focaltech_read` length bounded by `transfer_length > sizeof(focaltech_tx)` (callers pass 1, 2 or 62; the check could wrap for `length` near 2^32, but no caller can pass that); `focaltech_report` reads at most `report[2+6*9+4] = report[60]` of the 62-byte buffer; the read is CRC-checked before use; `focaltech_write_pram` frames never exceed 7+32. The boot-ROM entry is gated on reading back the boot ID, so the firmware blob is not sent to a chip that does not answer as the FT3680 boot ROM (this is also what protects a Goodix phone if the strap detection is wrong).
+
+Buttons (hakios.buttons.c):
+- `spmi_read` takes `count` 1..8 from constant callers (1, 2, 8) and writes `bytes[i]` for `i < count` into buffers of matching size (`is[2]`, `r[8]`, `c[8]`, `&status`); `data[1]` is read only for `count > 4`.
+- Channel numbers come from the arbiter's table (`n < channels <= 512`); `ARB_CHANNEL(n)` max 0x10fc < `ARB_CORE_SIZE` 0x1100, `ARB_OWNER(n)` max 0xefc < 0x1000, observer offset `0x80 * 511 + 0x1c` < 0x10000. The version is checked (`>= 5`, `< 7`) before anything else is read.
+- The SPMI spin lock is held for at most the 2 ms read timeout, with only MMIO and `mach_absolute_time` inside; nothing sleeps under it. Lock order: `spmi_lock` is a leaf; `touch_lock` is taken after it is dropped.
+- Only register reads go to the PMICs (as the file comment says); the single write is the arbiter's command word.
+- State (`power`, `volume_*`, `bus`) is touched by the one buttons thread only. `status & PON_KPDPWR` converts to `bool` by non-zero test, so 0x80 is true.
+- The "held at start is not believed until seen released" logic matches the comments; the thread ends with `thread_terminate` on all paths.
+
+virtio_input.c:
+- `used->ring[...].id % QUEUE_SIZE` bounds the event index; `seen`, `avail->idx` are `uint16_t` and 65536 is a multiple of 64, so wrap-around is exact; the `avail` update has a `dmb ish` before the index bump and one before the notify.
+- `command_key`: `name[32]`, `length < 31` guard, NUL written at `name[length]` with `length <= 31`; the key table index is checked against `sizeof(plain) - 1`; the keyboard-typed name is only passed to `ustacks_now` through `%s`/a string argument.
+- Static state (`name`, `shift`, ...) is shared by the up-to-four devices but only touched from `input_poll`, which re-arms itself after finishing, so it never runs concurrently with itself.
+
+## Not checked
+
+- Anything outside the five files: the consumer side (userland/src/inject.c) beyond the finger bounds check; `loader_log_line`/`loader_log_putc` (whether they are safe to call while holding `touch_lock`, input.c:124); `loader_return()` and what happens to the endless polling thread when the run ends (the touch thread has no stop flag and keeps polling hardware: goodix.c:1472-1499).
+- The kernel's behaviour for `ml_io_map` failure: all `ml_io_map` results are used unchecked (goodix.c:1448-1452, buttons.c:458-460, virtio_input.c:342). Whether it can return 0 here needs the XNU source.
+- Any register layout, timing or strap meaning (TLMM, GCC, GENI, RPMh, SPMI arbiter, Goodix Berlin command format, FocalTech boot ROM protocol, PIN_GOODIX_ID/PIN_FOCALTECH_ID being valid for this board) beyond internal consistency with the repository's comments.
+- Whether a Goodix finger lift is always reported as a status with the touch bit and zero count: if the chip instead reports status 0, `goodix_poll` returns at line 857 without posting UP and the finger stays down. NEEDS-HARDWARE; a hand test is noted in the buttons comment but not for this.
+- The content of `focaltech_fw` (706 KB array) and its provenance.
+- Whether the PRAM download can touch persistent flash, and whether the vendor flow's own integrity step exists in the boot ROM.
+- The iOS sandbox profile for `/dev/hakios-touch` (F3 impact).
+- Build correctness (flags of `kmem_alloc`, `__builtin_arm_dmb` use) and the other drivers in the tree, other than reading the lines named above for `hakios_rsc_lock`.
diff --git a/docs/driver-review/loader.md b/docs/driver-review/loader.md
new file mode 100644
index 0000000..6d5d11f
--- /dev/null
+++ b/docs/driver-review/loader.md
@@ -0,0 +1,314 @@
+# Review: boot loader (xnuloader/loader.c)
+
+## Scope and method
+
+Files read (read-only; nothing built, nothing run, no git state touched):
+
+| file | lines |
+|---|---|
+| xnuloader/loader.c | 4135 (read in full for the parts below; the UFS survey/GPT diagnostics 1100-1440 and the battery/charger code only skimmed) |
+| xnuloader/efi.h | 298 (struct layouts, EFI_FILE_INFO offset, allocate_pages/free_pages signatures) |
+| xnuloader/mkpayload.py | 59 (payload producer: are text entries NUL-terminated, what does `size` mean) |
+| tools/mkesp.py | 96 (payload validator on the host side) |
+| docs/uefi-boot.md | read for what the doc claims about the payload region |
+
+Method: traced the USB command path (usb_command_loop / usb_poll_command -> fb_command), then every user of host-controlled
+bytes (command text, `download:` size and data, the payload header/entries, the payload's cmdline), then
+load_payload_from_volume(), block_poll()/block_start(), the memory-map code, the device-tree writer and the kernel
+command-line assembly. Each finding below was traced from input to effect in the source; where an effect depends on
+hardware or firmware behaviour that this repository does not state, the confidence is NEEDS-HARDWARE.
+
+Threat-model note that affects every severity below. The USB host chooses the payload, and the payload contains the
+kernel that the loader then jumps to (and the cmdline, including `ufs_write=1`, `ufs_native=`, `physbase`). A hostile host
+therefore already has code execution at EL1 with the MMU off and direct UFS controller access through `ufs_native=`. Memory-safety
+flaws in payload parsing are consequently robustness/brick-avoidance problems (a malformed or truncated payload corrupting
+the loader, the kernel window or boot_args; a wedged loader), not privilege escalations over a trusted loader. The same holds
+for block_write's guard: it protects darwin's first 2042368 blocks and the other partitions against a buggy kernel, not against a
+malicious one. I rate with that in mind. Findings that matter even for a benign host (wrong state, truncated file,
+stale data) are rated higher than ones that need a deliberately lying payload.
+
+## Findings
+
+| id | severity | confidence | where | one line |
+|---|---|---|---|---|
+| L1 | medium | CONFIRMED | loader.c:2255, 3627, 3630, 3548 | "busy" is `running_live != NULL`, but running_live is NULL for any kernel without a kernel_live block; then download/oem run/oem ramdisk are accepted while the kernel runs |
+| L2 | medium | CONFIRMED | loader.c:4005-4016, 4123 | failed volume read frees the pages but leaves a valid XNUP header there; efi_main then boots the torn payload |
+| L3 | medium | NEEDS-HARDWARE | loader.c:3997-4001, 3679, 3188 | volume load claims only `pages` of the file, but `download:` and the panic-log memset use the whole 63/64 MiB |
+| L4 | low-medium | CONFIRMED | loader.c:2523-2551, 2832-2833, 3993 | payload header size and entry sizes are never checked against the file/region; ramdisk memcpy can read up to 4 GiB past the payload |
+| L5 | low-medium | CONFIRMED | loader.c:2751-2827 | Mach-O segment extents unchecked (vmaddr+vmsize wrap, filesize>vmsize, cmdsize 0, fileoff): arbitrary physical writes before the kernel starts |
+| L6 | low | CONFIRMED | loader.c:2787-2812 | `rdres` (resident_rd_size) has no upper bound; rounding and `dt_pa` arithmetic can wrap |
+| L7 | low | CONFIRMED | loader.c:398-408, 2809, 3049, 3287 | device-tree writer has no bound; dt_len never compared with the 64 KiB reserved; boot_args sits right after it and is written first |
+| L8 | low | CONFIRMED / NEEDS-HARDWARE | loader.c:3600-3606, 3647, 3685, 3696-3701 | `download:` to the resident area accepts >= 4 GiB but replies with 32 bits; received count `r` is not clamped to `want` |
+| L9 | low | CONFIRMED | loader.c:3664-3667, 3694-3710 | `oem ramdisk none` leaves the ramdisk download armed; a failed `download:` leaves a half-overwritten payload with a valid header |
+| L10 | low | CONFIRMED | loader.c:2868-2871, 1984, 2988 | flags that are not reset per run: hc_requested, block_probe_requested, block_enabled (stale page and ufs_shared_pa offered to a run that did not ask) |
+| L11 | low | CONFIRMED | loader.c:266, 1391, 1406, 1877, 1894 | every locate_handle_buffer() result is leaked (no free_pool anywhere); find_log_partition() runs on every log write |
+| L12 | low | PLAUSIBLE | loader.c:2090-2094 | block_poll takes bounds (parts, blocks, block_size, read twice) from the kernel-writable shared page; the write guard itself uses loader-private state and is sound |
+
+No finding lets the USB host write outside the documented regions through the command parser itself: `download:` is bounded to
+PAYLOAD_BASE..+63 MiB or to the resident area (L8 covers the one assumption it makes).
+
+## Details
+
+### L1 (medium, CONFIRMED) busy state is lost when the kernel has no kernel_live block
+
+- Code: `running_live = live;` (loader.c:2255, in run_on_other_cpu) and `int busy = running_live != NULL;` (3627).
+ `live` is `kernel_live`, which run_kernel sets only if it finds KERNEL_LIVE_MAGIC while scanning the loaded kernel
+ (2891-2898); otherwise it stays NULL and is passed on at 3329.
+- Scenario: payload with `usb`, cmdline `bootcpu=N` (kernel on another core) and a kernel image that does not contain the
+ magic (older kernel, the QEMU hello kernel). run_on_other_cpu still polls the host every pass (`usb_poll_command()` at
+ 2348, which only checks `USB == NULL`). fb_command is entered with busy == 0, so:
+ - `download:` writes to PAYLOAD_BASE or, after `oem ramdisk`, over the resident root image at win_base+0x08000000 while that
+ kernel is running and using it as its root device;
+ - `oem run` re-enters run_kernel: it memsets and rewrites the kernel segments under the running kernel and overwrites
+ loader_ctx (the saved return context of the first run), so the first kernel's return lands in the wrong frame;
+ - `oem stop` does nothing (3636 requires busy), so the run cannot be ended from the host;
+ - usb_wait's 3 s give-up (3548) is also keyed to running_live != NULL, so a nested `download:` whose host goes quiet blocks the
+ watcher forever (it only pets the watchdog), and the kernel's return is never noticed.
+- Fix (text diff):
+ ```
+ -static const struct kernel_live *running_live;
+ +static const struct kernel_live *running_live;
+ +static int run_active; /* set for the whole of run_on_other_cpu(), live block or not */
+ ...run_on_other_cpu():
+ - running_live = live;
+ + running_live = live; run_active = 1;
+ ...
+ - running_live = NULL;
+ + running_live = NULL; run_active = 0;
+ ...fb_command():
+ - int busy = running_live != NULL;
+ + int busy = run_active;
+ ... "oem stop": if (busy && running_live) ...
+ ... "oem log": if (busy && running_live) compose_live_log(...); else compose_logs(NULL, 0);
+ ...usb_wait(): if (run_active && ...) return -1;
+ ```
+
+### L2 (medium, CONFIRMED) a failed or short volume read leaves a valid payload header behind
+
+- Code: loader.c:4002-4009. The first 1 MiB chunk is read to PAYLOAD_BASE (so `magic == XNUP` is already in memory); if a later
+ `file->read` fails or returns 0, the code sets the note, calls `BS->free_pages(PAYLOAD_BASE, pages)` and returns 0. Nothing clears
+ the header and free_pages does not scrub. efi_main then calls `parse_payload(&pi, 0)` (4123), which only tests
+ `ph->magic == PAYLOAD_MAGIC` at PAYLOAD_BASE (2519) and returns 1.
+- Scenario: a payload.bin larger than 1 MiB on a flaky card/USB stick, or a volume that returns an error on the second read.
+ Screen says "payload: none in memory, and ... could not be read to its end" (4096), yet the loader goes on to run_kernel with the
+ truncated payload (the kernel Mach-O or ramdisk is cut off, the rest of it is whatever the freed pages held) or enters the USB
+ loop. The same applies to the `magic != XNUP` path only if the header was valid, which it is not, so that path is fine.
+- Fix:
+ ```
+ if (EFI_ERROR(file->read(...)) || chunk == 0) {
+ volume_payload_note = "...could not be read to its end";
+ + ((struct payload_header *)PAYLOAD_BASE)->magic = 0;
+ BS->free_pages(PAYLOAD_BASE, pages);
+ goto close;
+ ```
+ Also validate `ph->size` there (see L4).
+- Handle handling in this function is otherwise right: every path after a successful `open` reaches `close:` exactly once; `root` is
+ closed on the open-failure return; no double close; pages are freed on every failure after allocation.
+
+### L3 (medium, NEEDS-HARDWARE) volume load claims only the file's pages, the rest of the region is used anyway
+
+- Code: `pages = (size + 0xfff) / 0x1000; allocate_pages(AllocateAddress, ..., pages, &address)` (3997-3998), i.e. only the bytes
+ of the file. But `download:` writes up to `PAYLOAD_MAX_SIZE - 0x100000` (3679-3680) at PAYLOAD_BASE, run_kernel zeroes the
+ panic log at PANIC_LOG_BASE = PAYLOAD_BASE+63 MiB, 512 KiB (3187-3188), and choose_window() assumes the whole 64 MiB is outside any
+ allocation (2669, 2685-2691). docs/uefi-boot.md:47-51 says "the loader's payload region is 64 MiB"; with the shim or QEMU the
+ region is placed and (per the comment at 42) reserved in the memory map; in the volume case the success of AllocateAddress
+ implies the region was NOT reserved.
+- Scenario: payload.bin (say 15 MiB) from a volume, with a `usb` entry. usb_start() then allocates two 1 MiB transfer buffers
+ (3516-3517), and other drivers allocate; any of them may land in the unclaimed 48 MiB. A following `download:` of a larger
+ payload overwrites them mid-transfer (corrupt data or wedged USB), and the panic-log memset zeroes whatever lives at
+ 0xF3F00000. Whether the firmware's allocator hands out those pages is firmware behaviour: not stated in this repository.
+- Fix: claim the whole region when the loader will use it, e.g. allocate `PAYLOAD_MAX_SIZE >> 12` pages (fall back to the file's
+ pages and refuse `usb` mode / panic log if the full claim fails), or at least claim PANIC_LOG_BASE separately.
+
+### L4 (low-medium, CONFIRMED) payload sizes are never validated against the payload
+
+- parse_payload (2523-2551) and payload_kernel_version (4037-4048): `pend = p + ph->size` is only used to stop the walk;
+ `ph->size` is not compared with the file size (volume: 3993 checks only `size >= 8` and `<= 63 MiB`), nor with
+ PAYLOAD_MAX_SIZE, and no entry is checked for `p + sizeof(entry) + e->size <= pend`.
+- Arithmetic itself (what you asked for): `e->size` is uint32_t and `15` is int, so `(e->size + 15) & ~15u` is evaluated in 32 bits.
+ For `e->size` in 0xFFFFFFF1..0xFFFFFFFF it wraps to 0 and `p` advances 24 bytes (no loop, no hang; the next "entry" is parsed out of
+ the current entry's data). For 0x...F0 or below `p += 24 + up to 4 GiB` in 64-bit pointer arithmetic: cannot wrap, the loop condition
+ `p + 24 <= pend` then ends the walk. Both are safe from loops; neither rejects the entry. (tools/mkesp.py:49-50 uses Python
+ integers, so for those sizes it parses differently from the loader.)
+- Effects: (a) `pi->ramdisk = p + 24; pi->ramdisk_size = e->size` (2534-2535) is used as `memcpy((void *)rd_pa, pi.ramdisk, pi.ramdisk_size)` (2833).
+ The destination is bounded (2813 checks the window), the source is not: a ramdisk entry claiming up to 4 GiB reads beyond the payload
+ into whatever follows (stale RAM, the loader's own image, possibly unmapped or device memory -> exception -> reset). The
+ kernel-version walk and the banner read the same stale memory. (b) With `ph->size` larger than the file, an entry walk without a
+ terminator continues through unclaimed memory (fresh AllocatePages memory is not zeroed).
+- Names that are not NUL-terminated within 16 bytes: str_eq stops at the literal's NUL, so lookups never read past the 24-byte header;
+ only the verbose `print("%s", e->name)` (2531) runs on into the size field and data until a NUL (bounded by log_buf's check in put_char).
+- Text values (`cmdline`, `kernel.ver`, `physbase`, `rdres`, `checkpoint`): mkpayload.py always appends a NUL inside the entry and pads, but the
+ loader does not check it. Reads of an unterminated value run to the next NUL anywhere in memory. All writes derived from them are
+ bounded: the cmdline copy by `n < BOOT_LINE_LENGTH - 1`, hakios_kver by `n + need < BOOT_LINE_LENGTH - 1` with `need` from the same str_len.
+ `parse_number` wraps silently on long digit strings (no overflow trap) and returns 0 when there are no digits; no memory effect.
+- Fix: in load_payload_from_volume, `if (ph->size > size - 8) fail`; in parse_payload and payload_kernel_version bound `pend` by a
+ caller-supplied limit (volume size, or the download size recorded at `download:` time; fall back to PAYLOAD_MAX_SIZE - 1 MiB) and add
+ `if ((uint64_t)e->size > (uint64_t)(pend - (p + sizeof(*e)))) break;` with the 64-bit rounding
+ `(((uint64_t)e->size + 15) & ~15ULL)`; for `ramdisk`/`kernel` require the whole entry inside; for text entries require a NUL within `e->size`.
+
+### L5 (low-medium, CONFIRMED) Mach-O segments are loaded without bounds
+
+- Code: first pass 2751-2767, load pass 2820-2827. `vm_hi = sg->vmaddr + sg->vmsize` can wrap; `vm_lo` is only compared with the low
+ limit; the load does `memset(vmaddr + slide, 0, vmsize); memcpy(vmaddr + slide, kernel + fileoff, filesize)` with no check that
+ `vmaddr+vmsize` is inside `[kern_lo, kern_hi)` (it is not if it wrapped), that `filesize <= vmsize` (a larger file size writes past
+ kern_hi into the resident image, device tree or boot_args), or that `fileoff + filesize` is inside the payload. `lc->cmdsize == 0`
+ keeps `lc` in place for `ncmds` (up to 2^32) iterations; `ncmds`/`cmdsize` are not checked against `sizeofcmds` or the payload. LC_UNIXTHREAD
+ reads 17 words without checking cmdsize.
+- Scenario: a payload whose kernel is truncated, corrupt or made for another link layout; or a second segment with a high vmaddr. The
+ loader writes into physical memory outside the window it claimed (its own image, UEFI, the payload being read), and the failure is a reset
+ or a silent corruption, not a diagnostic.
+- Fix: after the extent pass `if (vm_hi < vm_lo || kern_hi > win_base + win_size) fail;` and per segment require
+ `filesize <= vmsize`, `vmaddr >= vm_lo`, `vmaddr + vmsize <= vm_hi` (no wrap), `fileoff + filesize <= kernel_len` (needs L4's
+ entry bound), and `cmdsize >= sizeof(struct load_command)` and `cmdsize <= sizeofcmds - consumed`.
+
+### L6 (low, CONFIRMED) resident image size from `rdres` is unbounded
+
+- Code: `if (pi.resident_rd != 0) resident_rd_size = pi.resident_rd;` (2787-2789), then `res_size = (resident_rd_size + 0x3fff) & ~0x3fff` (2792),
+ `dt_pa = rd1_pa + rd1_size` (2808), `top`, and the check `win_size < top - phys_base + 0x4000000` (2813). The `download:` path caps the size at
+ `win_size - OFFSET - RESERVE` (3685), the `rdres` path does not. For `rdres` >= 2^64 - 0x3fff the rounding wraps to 0
+ (resident entry with size 0, kernel starts without a root). For `rdres` near 2^64 - 0x108000000, `rd1_pa + rd1_size` wraps, `top - phys_base`
+ becomes small, the 2813 check passes and the device tree and boot_args are written at a wrapped `dt_pa` inside the kernel's own segments.
+ The value also persists in `resident_rd_size` for later runs (it is a static), even when the next payload has no `rdres`.
+- The overlap check itself is right for what it covers: `kern_hi + rd_size > res_pa` (2794) uses 64-bit values from sizes that are bounded by 2813
+ except for the wrap above.
+- Fix: `if (resident_rd_size > win_size - RESIDENT_RD_OFFSET - RESIDENT_RD_RESERVE) fail;` right after the assignment (and check
+ `win_size > OFFSET + RESERVE` first).
+
+### L7 (low, CONFIRMED) device-tree writer has no bound
+
+- Code: dt_prop (399-408) writes `36 + ((len+3)&~3)` bytes at `w->cur` without comparing with an end; `dt_len` is computed at 3287 and never compared with
+ `dt_max = 0x10000` (2809), the space reserved before boot_args (`ba_pa = dt_pa + dt_max`). boot_args is memset and fully filled
+ (2921-3045) BEFORE the tree is written (3049...), so an oversized tree silently overwrites commandLine, bootFlags etc. Names of 32 or more
+ characters would run into the length field (memcpy of `str_len(name)` bytes into a 32-byte field).
+- Bound on actual content: everything except identity.h is constant (8 KiB NVRAM image + a few KB, at most 8 cpu nodes). identity.h is generated
+ from the builder's own IPSW (not in the repository, see build.sh/mkidentity.py), so its size cannot be established here; `mkidentity.py` copies
+ property values without a size limit, names are Apple's (31 chars). Probability low, consequence a corrupt boot with no message.
+- Depth: counts[16], deepest nesting used is 3: fine. `dt_prop_padded`'s 64-byte `field` takes at most 17 characters + the 32-byte size: fine.
+- Fix: give dt_writer an `end` pointer, make dt_prop refuse (set an `overflow` flag) when `cur + 36 + padded > end`, and
+ `if (w.overflow || dt_len > dt_max) { print("device tree too big\n"); return 0; }` before using it.
+
+### L8 (low, CONFIRMED / NEEDS-HARDWARE) `download:` size reply and chunk accounting
+
+- 32-bit reply: fb_reply_data (3600-3606) prints only the low 32 bits. The resident-area limit (3685) is `win_size - 0x08000000 - 0x30000000`, up to
+ 0x148000000 (win_size max 6 GiB, 2704). A host asking for `download:100000000` .. limit is accepted and answered `DATA00000000`; the loader waits for
+ the full count while the host sends none, then the next command is swallowed as data (into the resident area) and the transfer ends "short download".
+ `getvar:max-download-size` says 0xffffffff in this mode (3647) even though the real limit can be lower or higher. Fix: `if (limit > 0xffffffffULL) limit = 0xffffffffULL;`
+ and advertise `limit`.
+- r not clamped (NEEDS-HARDWARE): `r = usb_rx(usb_rx_buf, want)` then `memcpy(dest + got, usb_rx_buf, r)` (3696-3701) and `got += r`. If the controller ever
+ reports more than `want` (a USB 3 burst delivering more than the request; not stated anywhere in this repository), the memcpy runs past `total`,
+ and past `limit` at the end of the region, and reads past the 1 MiB receive buffer. Fix: `if (r > (int64_t)want) r = (int64_t)want;`.
+- `parse_number` on `download:`: overflow wraps (17+ hex digits), "no digits" gives 0 -> "bad size". Wrapped values are small and are used consistently as
+ `total`, so there is no memory effect, only a surprising size.
+
+### L9 (low, CONFIRMED) command-state slips
+
+- `oem ramdisk none` (3664-3667) returns after clearing resident_rd_size but does not clear `download_to_ramdisk`. Sequence `oem ramdisk`, `oem ramdisk none`,
+ `download:<payload>`: the payload goes over the resident area (and `resident_rd_size = total`, the next kernel gets the payload file as md0) instead of
+ to PAYLOAD_BASE. Fix: `download_to_ramdisk = 0;` in that branch.
+- A `download:` to PAYLOAD_BASE writes straight over the live payload (3700). If it fails ("short download", cable event, 3703-3710) the old header may still be
+ valid but its entries/tail are a mix of new and old data; `oem run` then parses that. Fix: zero `ph->magic` at the start of the download and write it
+ back only when `got == total`.
+- Parser/command state otherwise: `oem stop` when idle is a no-op; `oem run` when not busy runs; `reboot`, `oem hang`, `upload`, `oem log` while busy are by design.
+ After OTHER_CPU_HUNG (3336-3342) run_on_other_cpu has cleared running_live, so the loader reports idle and accepts `download:`/`oem run` while a hung kernel
+ may still be alive on its core; the only warning for a core left running (3373-3380) is on the came-back path. PLAUSIBLE: add a "kernel_may_be_alive" flag, set on
+ HUNG, that makes fb_command refuse download/run/ramdisk until `reboot`.
+
+### L10 (low, CONFIRMED) flags that outlive the run that set them
+
+- run_kernel resets gamut_p3, block_write_requested and block_write_part per run (2849-2853) with the comment that the loader stays resident. Three
+ similar states are not reset: `hc_requested |= ...` (2871; only |= exists, never `= 0`), `block_probe_requested |=` (2868), and `block_enabled` (set at 1984, never
+ cleared). Effect: a run that asks for `ufs=2` after one that had `ufs_native=1` gets the kernel-owned transfer list offered (1966, 1768) without asking; a run
+ that does NOT ask for ufs=2 after one that did still gets `ufs_shared_pa=0x...` appended to its command line (2988) and is still served by block_poll
+ (2345-2349) from the stale page (read-only: block_write_part is -1 so writes are refused; `write_part_plus_one` in the stale page still says otherwise, so a
+ kernel would try and be refused).
+- Fix: `hc_requested = 0; block_probe_requested = 0; block_enabled = 0;` next to 2849-2853.
+
+### L11 (low, CONFIRMED) pool leak
+
+- `BS->locate_handle_buffer` allocates the handle array from the pool; `free_pool` is not called anywhere in loader.c (it is only declared in efi.h:50). Sites: 266
+ (find_log_partition, called from every write_logs; flush_log runs every 2 s for 24 s of each other-core run, 2285-2294), 1391/1406 (ufs_survey), 1877/1894 (block_start).
+ A phone with ~100 GPT partitions leaks ~0.8 KB per call, order of 10 KB per run, with the loader resident across many runs. Fix: `BS->free_pool(handles)` after use.
+
+### L12 (low, PLAUSIBLE) block_poll relies on kernel-writable fields for bounds
+
+- Code: 2090-2094 reads `block_shared.parts`, `block_shared.part[part].block_size` (twice: once in the `count <=` test, once for `bytes`) and `.blocks` from the page the kernel can
+ write (it is the kernel's mailbox, same page, 8 KB aligned). The write guard is not among them and is sound: `block_write_part` and `BLOCK_WRITE_FIRST` are loader statics, `lba + count`
+ is checked by subtraction (no overflow: `count <= 4 MiB / block_size`), there is exactly one `write_blocks` for the kernel (2123), the other is the logdump write (361), and
+ block_start sets block_write_part only for the entry that passes block_is_darwin (1927-1929). What a kernel that corrupts the page (a stray store, or a data race against the
+ re-read of block_size between 2090 and 2094) can do: pass `bytes > BLOCK_BUFFER_SIZE` to read_blocks/write_blocks (write beyond or read from beyond block_buffer) or an `lba`
+ past the end of darwin (then only UEFI's own partition bound stops it, as the comment at 1454 says).
+- Fix: keep a loader-private copy (`static uint32_t priv_block_size[]; static uint64_t priv_blocks[]`) or read them from `block_bios[part]->media` (block_size, last_block + 1), and read each once into locals.
+
+## Checked and found fine
+
+Command parser
+- usb_command_loop (3835-3857) and usb_poll_command (3802-3832): the receive is 511 bytes into a 1 MiB buffer (3516), the copy into `cmd[128]` is clamped to 127 and NUL-terminated both places
+ (3828-3830, 3850-3854); a longer command is truncated, not overflowed. No command takes an argument longer than 127 bytes (the longest is a number).
+- starts_with (3610-3618) never reads past the NUL of `s`; prefix matching is loose ("oem runX" runs, "rebootfoo" reboots) but harmless. `cmd + 9`, `cmd + 7`, `cmd + 11`, `c[8]`, `c[9]`, `c[11]` accesses happen only after
+ the prefix matched, so they read at most the NUL.
+- `getvar:` replies: fb_reply copies at most 63 text characters into usb_tx_buf (1 MiB); the `screen` reply goes through print and restores log_len; log_buf[log_len] is in range
+ because put_char keeps log_len <= sizeof-1 (177).
+- `download:` bounds: PAYLOAD_BASE target limited to 0x03f00000 = PAYLOAD_MAX_SIZE - 1 MiB (never touches the panic-log MiB) and equal to the advertised max-download-size; ramdisk target limited
+ to `win_size - 0x08000000 - 0x30000000` with `win_size > OFFSET + RESERVE` verified at `oem ramdisk` time (3671) and win_size never shrinking (choose_window returns early once set);
+ `total == 0` and `total > limit` rejected before any write; `to_ramdisk` consumed once (3681-3683); resident_rd_size zeroed before a ramdisk transfer and set only on full success (3687, 3704-3706).
+- `oem ramdisk`, `oem run`, `oem selftest`, `oem hang`, `oem recording`, `oem sound`, `oem clearscreen`, `oem memmap` are refused while busy (3630-3633) when `busy` is true (see L1 for when it is not).
+ `oem ramdisk none` while busy is also refused because it begins with "oem ramdisk".
+- parse_number (2498-2510): no digits -> 0; invalid character stops; arithmetic wraps without UB (unsigned); callers: download size (checked afterwards), checkpoint (only compared with 999 and stored), physbase, rdres.
+- `oem run [N]`: `arg = cmd + 7` is within the command; checkpoint 999 maps to the self-test path as `oem selftest` does.
+- upload: `staged_len` chunks of at most 1 MiB copied into usb_tx_buf (3714-3720); out_buf is 2 MiB and staged_len is clamped by compose_logs (312-314) and compose_live_log's PUT (1011-1018)
+ with `n <= room` invariant (n starts at log_len <= 32767); the log text written to logdump is at most about 2 MiB - 8 KiB + 4 KiB rounding, below sizeof(out_buf).
+
+Payload parsing
+- Termination: every iteration advances `p` by at least 24 bytes (size wrap gives 0 padding, not negative); no infinite loop; no 64-bit pointer wrap. Entry header is fully inside `[p, pend)`
+ before it is read (`p + 24 <= pend`).
+- str_eq against literals never reads beyond the literal's length + 1, so a name without a NUL in 16 bytes is not over-read by matching.
+- The cmdline scans in run_kernel (2854-2873, 2899-2906, 2937-2939, 2959-2960, 2975-2977) test `c[-1]` only for `c > pi.cmdline` (via `c == pi.cmdline ||`), and never read past a NUL.
+ `loader_return_after=` digit loop stops at NUL; `kernel_budget` can wrap with 20+ digits (only effect: stops petting the watchdog sooner).
+- mkpayload.py NUL-terminates every text entry inside the entry's size and pads to 16; its header size covers the 24-byte terminator; mkesp.py's PAYLOAD_LIMIT equals the loader's
+ `PAYLOAD_MAX_SIZE - 0x100000`.
+
+Volume loader (load_payload_from_volume, 3962-4022)
+- Size: read from get_info at offset 8 (efi.h:207 documents it), `size >= 8` and `<= 63 MiB` enforced before allocation; `pages` rounded up correctly; `info` is 512 bytes (only a short file name is returned; a
+ BUFFER_TOO_SMALL would just fail into the "cannot be read" note).
+- The read loop reads at most 1 MiB at a time at `PAYLOAD_BASE + done`, handles short reads, stops on `chunk == 0`, and never exceeds `size`.
+- Close paths: `root->close` on open failure; `file`/`root` closed exactly once at `close:` on all later paths (including success); no handle leaked and none closed twice; the pages are freed on both
+ read failure and bad magic; success keeps them on purpose. (The one defect on these paths is the stale header, L2.)
+
+Block service
+- Only one kernel-reachable `write_blocks` (2123) and it is behind `block_write_part >= 0 && part == block_write_part && lba >= BLOCK_WRITE_FIRST`; `lba + count` overflow is excluded by `count <= blocks - lba`;
+ `bytes = count * block_size` cannot exceed 4 MiB given the same block_size; unknown `op` touches nothing (2144-2146); division by a zero block_size yields 0 on AArch64 and the request is refused.
+- block_write_part is the index of the entry in `block_shared.part[]` at the time block_is_darwin passed (1927-1928, before `parts++`); units are appended after the partitions so indices do not shift; limits:
+ `parts + nunits < 160`, `nunits <= 16`. block_is_darwin requires exact name "darwin" (7 bytes compared, ufs_name maps non-ASCII to '?'), both GUIDs, start/end LBA, unit 0, block size 4096, block count, not read-only.
+ A second partition cannot pass it (unique GUID).
+- Per-run reset of block_write_requested/block_write_part (2852-2853) holds; a run without `ufs_write=1` has writes refused even if the page is stale (L10 notes the page contents).
+- The tally reset (1973) and the answer/mailbox handshake (request volatile, dmb before `answered`) are consistent.
+
+Memory map / window
+- choose_window's exclusion of PAYLOAD_BASE..+64 MiB (2685-2691) is correct for all four overlap shapes; the unsigned `pay_lo - lo` only matters where `pay_lo > lo` is also tested. A descriptor that
+ ends inside the payload region is dropped rather than trimmed (loses memory, never overlaps). `claim` goes through AllocateAddress, so the firmware refuses overlap; `best_size >> 12 == 0` fails cleanly.
+- `win_size < top - phys_base + 64 MiB` (2813) is the single check that makes the DT, boot_args, kernel and payload ramdisk copies land inside the window, given kern_hi is sane (L5) and the resident size
+ is bounded (L6).
+- print_memory_map: `totals[d->type]` guarded by `type < 16`; `get_memory_map` failure is handled; a 64 KiB static buffer is used.
+
+Command line (BOOT_LINE_LENGTH 608)
+- All base pieces (2964-2987) and the two `*_shared_pa=0x%016x` pieces (2993-3013) check `n < BOOT_LINE_LENGTH - 1` per character, so none can write past index 606; ba was memset to 0, so index 607 stays NUL.
+- hakios_kver (3015-3031): `need = 12 + strlen + 1`, tested with `n + need < 607` before any byte is written; the copy writes at most `need` bytes (the loop stops at a space, so possibly fewer); the else branch
+ prints the warning and writes nothing. No overflow, no uninitialised read. The cmdline tail (3037-3044) is bounded by the same limit; the truncation warning prints `str_len(rest)` correctly and the
+ `print` arguments are cast to uint64_t as print's `%d`/`%x` require. A value with a tab or other whitespace in kernel.ver is passed through (only ' ' ends it); whether the kernel's boot-arg parser treats
+ those as separators is not in this repository (no isargsep found), so not decided here.
+- The loader's own `ufs_write=1` / `ufs_native=` detection requires a preceding space or start of line; the kernel could accept other separators, which can only make the loader stricter (writes refused), not looser.
+
+Device tree
+- Depth never exceeds 3; `dt_prop_padded` field is 64 bytes for strings of at most 17 characters; per-property copy uses the same padded length as the memset; names written by the loader itself are all < 32 characters.
+
+## Not checked
+
+- Hardware behaviour: whether PAYLOAD_BASE..+64 MiB is free or reserved on the phone, whether the USB controller can return `bytes_completed > requested`, how Qualcomm's block I/O bounds a partition, cache state of the
+ panic-log region that run_kernel zeroes (3188) with the data cache on while the cache-clean loop (3309-3320) only covers some memory-map types (NEEDS-HARDWARE; not traced).
+- identity.h is not in the tree (generated from the builder's IPSW), so the device tree's real size and the property names/lengths could not be measured (L7).
+- The kernel-supplied fields: kernel_live (log/log_len/log_head/log_ring pointers and offsets, recording and sound pointers and lengths up to 1 GiB used by `upload` and write_logs, loader_ctx log pointer/length printed
+ unclamped when there is no log partition). They come from the kernel the host chose, so I treated them as trusted (see the threat-model note).
+- USB device protocol details of the Qualcomm stack (usb_start, descriptors, handle_event semantics), the UFS host-controller take-back code (hc_*), the charger/battery code, the Block I/O 2 probe, ramfb/fw_cfg code (QEMU only),
+ the assembly (loader_save_ctx, return stubs, other_cpu_entry), the watchdog SMC code and the exception hook. Only skimmed or not read.
+- The ufs_survey/ufs_check_gpt/ufs_dump_super diagnostics read flash-controlled GPT/liblp data; I looked at their size arithmetic (all reads stay inside the 1 MiB ufs_buffer) but did not audit them line by line.
+- docs/ and Makefile/qemu scripts beyond what is quoted above; tools/darwin-write.py (the build side of the darwin identity constants).
diff --git a/docs/driver-review/policy-glue.md b/docs/driver-review/policy-glue.md
new file mode 100644
index 0000000..ca0621d
--- /dev/null
+++ b/docs/driver-review/policy-glue.md
@@ -0,0 +1,374 @@
+# Review: security-policy stand-ins and the kernel surface the port adds
+
+## Scope and method
+
+Read-only audit. Nothing was built or run; no file other than this one was written.
+
+Files read in full (line counts):
+
+| File | Lines |
+|---|---|
+| xnu/files/bsd/kern/kern_minimac.c | 369 |
+| xnu/files/libkern/amfi/miniamfi.c | 264 |
+| xnu/files/libkern/amfi/miniamfi_entitlements.cpp | 123 |
+| xnu/files/iokit/Kernel/MiniAppleKeyStore.cpp | 335 |
+| xnu/files/iokit/Kernel/GenericARMPE.cpp | 407 |
+| xnu/files/iokit/Kernel/MiniIONetworkStack.cpp | 114 |
+| xnu/files/iokit/Kernel/MiniDrivers.h | 21 |
+| xnu/files/osfmk/arm64/loader_return.c (the loader-return code) | 597 |
+| xnu/files/osfmk/arm64/user_exception_trace.c | 440 |
+| xnu/hakios.patch (all 73 hunks' files, every hunk read) | 3242 |
+
+Also read, for the surface questions: the devfs/sysctl registration and the user-facing handlers in
+bsd/dev/hakios.{input,audio,mic,camera,haptic,torch,sparse,virtio_blk,ufs,apfs_check,sound,speaker,guard}.c and
+bsd/miscfs/apfs/apfs_vfsops.c (the three sysctls). The modem files (mpss, qmi, nas, ipa, cell) were skipped as
+instructed.
+
+Method. For each stub I traced who calls it and what the caller does with the answer. For each patch hunk I read the
+unchanged Apple function around it. Apple's original code was read with `git show c54f35ca...:<path>` (read-only) from
+the XNU checkout that lives in WSL (`/home/shimoku/hakios/xnu-src/xnu-8796.121.2`), because this Windows tree has no
+`xnu-src`. Line numbers of the form "Apple file:N" are in that original file; "patch:N" are lines of
+xnu/hakios.patch; everything else is a line of the file named.
+
+Overlap: the sound/input/camera reviewers (docs/driver-review/sound.md, input.md, camera-haptic-torch.md) found P2 and
+P3's touch/audio/mic parts independently; I re-derived them because the question asked for every device node, and I
+cross-reference instead of repeating their detail. P1, P4, P5, P6, P7 are not in those documents.
+
+## Findings
+
+| id | severity | confidence | where | one line |
+|---|---|---|---|---|
+| P1 | High | CONFIRMED | patch:518-606 (Apple kern_exec.c:3097, 3107-3111, 3132-3135, 3591, 3985) | any process becomes uid 0 with `posix_spawn` persona OVERRIDE: the entitlement check and the persona lookup were removed, nothing replaced them |
+| P2 | High (effect on hardware), Medium (as a bug) | CONFIRMED trace / NEEDS-HARDWARE effect | hakios.audio.c:259-275, hakios.sound.c:1267/1272/1279, hakios.speaker.c:897/914 | unprivileged ioctl value wraps in `below + extra`: loudest level past `sound_below`, speaker guard blinded, watcher thread stuck (same as sound.md S-01/S-02) |
+| P3 | Medium | CONFIRMED (mode) | hakios.input.c:213, hakios.audio.c:343, hakios.mic.c:1732, hakios.camera.c:4000, hakios.haptic.c:828, hakios.torch.c:575 | six device nodes are mode 0666: any process can read the microphone and camera, read and forge every touch and button |
+| P4 | Medium | CONFIRMED (hunk) / PLAUSIBLE (reach) | patch:828-839 (kern_priv.c) | `PRIV_NET_PRIVILEGED_SOCKET_DELEGATE` returned 0 for every credential, before the MAC deny policies; the reason given in the comment is stale |
+| P5 | Low | CONFIRMED | patch:853-859 (kern_sig.c), user_exception_trace.c:112-145 | `user_abort_trace()` prints from `pthread_kill(SIGABRT)` with no boot-arg gate, unlike its sibling |
+| P6 | Low | PLAUSIBLE | patch:726-742 (Apple kern_exec.c:6639) | the "do not bump the pid version" exception is keyed on the process name `xpcproxy` only |
+| P7 | Low | PLAUSIBLE | kern_minimac.c:169-224 | Sandbox request 4 answers for any pid, from memory the target process can rewrite |
+
+Counts: 4 CONFIRMED (P1, P3, P4, P5), 1 CONFIRMED trace with NEEDS-HARDWARE effect (P2), 2 PLAUSIBLE (P6, P7).
+
+Once P1 holds, every "root required" statement below (sysctls, raw storage nodes) stops being a boundary for a
+process that can call `posix_spawn`; I note that where it matters.
+
+## P1. Any process can become root: persona check removed (High, CONFIRMED)
+
+Where. patch:518-606, which changes `spawn_validate_persona()` and `spawn_persona_adopt()` in bsd/kern/kern_exec.c.
+
+What Apple's code did (Apple kern_exec.c:3092-3166, called from 3591 and 3985):
+
+- `spawn_validate_persona()` returned EPERM unless the caller held `PERSONA_MGMT_ENTITLEMENT`
+ (3097-3099), and ESRCH if the persona did not exist (3107-3111).
+- `spawn_persona_adopt()` then applied `pspi_uid`, `pspi_gid` and the groups from the caller's `posix_spawn` argument
+ to the child's credential (3139-3159).
+- The sibling argument `posix_cred_info` is guarded differently: `kauth_cred_issuser()` or EPERM (Apple
+ kern_exec.c:3604-3607).
+
+What the patch does. Both guards are deleted (patch:522-524, 543-547, 556-558). When the persona does not exist
+(which is always the case here) the new branch at patch:566-606 sets the uid, gid and groups from the caller's request
+on the child with `proc_update_label()` and returns 0.
+
+Failure scenario. Any process, at any uid, with no entitlement and no signature, calls `posix_spawn` with a persona
+attribute (`posix_spawnattr_set_persona_np`, flags OVERRIDE, `posix_spawnattr_set_persona_uid_np(attr, 0)`) for any
+path. The child is created with uid 0, gid and groups of the caller's choosing. Nothing in the spawn path checks the
+caller. The patch's own comment says this is what Sileo relies on to become root ("Sileo asks posix_spawn for persona
+99 with OVERRIDE and uid 0 ... that is how it runs apt and dpkg"). The comment justifies the removal with "the
+entitlement is one nobody carries here (nothing is signed, AMFI is a stub)".
+
+Why that justification is out of date. miniamfi_entitlements.cpp now answers entitlement queries from the entitlements
+in the program's own signature, `IOCurrentTaskHasEntitlement()` reaches it (iokit/Kernel/IOUserClient.cpp:1507,
+iokit/bsddev/IOKitBSDInit.cpp:1495-1559), and the sibling hunk in the same file keeps the check for bindfs
+(patch:964-973). So the entitlement route works now; the unconditional removal is not needed for Sileo, whose binary
+can carry `com.apple.private.persona-mgmt` in an ldid signature.
+
+Consequences. A root child can open /dev/rufs_* and /dev/rvblk0 (see the table below), set `kern.exec_inject`, call
+`reboot(2)` (which now returns to the loader, see halt_all_cpus in patch:2199-2211), and so on.
+
+Fix (text only):
+
+```
+ spawn_validate_persona(struct _posix_spawn_persona_info *px_persona)
+ {
+ int error = 0;
+ struct persona *persona = NULL;
+
++ if (!IOCurrentTaskHasEntitlement(PERSONA_MGMT_ENTITLEMENT)) {
++ return EPERM;
++ }
+ if (px_persona->pspi_flags & POSIX_SPAWN_PERSONA_GROUPS) {
+```
+
+and sign Sileo (and anything else that must do this) with that entitlement. Keep the `persona == NULL` branch in
+`spawn_persona_adopt()`, which is only reachable after the check.
+
+## P2. Unprivileged volume ioctl wraps uint32: loudest level, guard blinded, thread stuck (CONFIRMED trace, NEEDS-HARDWARE effect)
+
+Same defect as sound.md S-01/S-02; traced again here because the node is part of the user-reachable surface.
+
+Trace. `HAKIOS_AUDIO_SET_VOLUME` (hakios.audio.c:259-275, node mode 0666 at :343) stores any `uint32` `below`
+(`volume_below = volume->below`, :268) with no range test. The sound watcher (hakios.sound.c:1253-1279) computes
+`below + extra` in `uint32_t` (default `below` is 240) and passes it to `hakios_speaker_volume()` and `guard_level()`.
+In `hakios_speaker_volume()` (hakios.speaker.c:897 and :914) `target = a->volume_at + below` wraps again.
+
+With `extra = 0xFFFFFF0F` the sum is `0xFFFFFFFF`:
+
+- `guard_level(0xFFFFFFFF)` is `HAKIOS_GUARD_SILENT` (hakios.sound.c:1214-1216, `guard_as` defaults to UINT32_MAX), so
+ in hakios.guard.c:160 `to_speaker = 0`: no power limit, only the full-scale clip at :225.
+- `target = volume_at - 1`. `set_volume()` clamps up to `volume_at` (hakios.speaker.c:707-709) and stores the
+ clamped value in `a->volume`, so `a->volume == target` never holds (:919). The `for (;;)` at :909 never ends (with
+ `step_ms == 1` the fault check at :928 is skipped), and the watcher thread never reaches `hakios_speaker_stop()`.
+
+Failure scenario (sound=4 boot-arg, phone): any process does the ioctl `{below = 0xFFFFFF0F, muted = 0}` and writes
+non-silent frames. The amplifiers go to Android's loudest level, the guard computes zero speaker power, and the
+amplifiers are never powered down. Whether Android's level without the guard damages the speakers is NEEDS-HARDWARE.
+
+Fix: see sound.md S-01 (clamp `below` at the ioctl, saturating add in sound.c and speaker.c); and fix P3 for this node.
+
+## P3. Six device nodes are world read/write (Medium, CONFIRMED for the mode)
+
+Every node the port creates, with mode and owner:
+
+| Node | Created at | Mode, owner | What an unprivileged opener can do |
+|---|---|---|---|
+| /dev/hakios-touch | hakios.input.c:213 | 0666 root:wheel | read every touch sample (and consume them: one shared queue, `touch_read` pops); write forged DOWN/MOVE/UP and button events, including Lock/Home/Volume (`touch_write`, :184-200; only real-driver fingers count towards the five-finger exit, :87-107) |
+| /dev/hakios-audio | hakios.audio.c:343 | 0666 root:wheel | inject audio into the speaker path; set or reset volume and mute (P2) |
+| /dev/hakios-mic | hakios.mic.c:1732 | 0666 root:wheel | `mic_dev_open` (:1522) switches the DSP microphone path on; `mic_dev_read` returns live samples to any reader; two readers split the stream (no lock on `ring_read`, memory-safe) |
+| /dev/hakios-camera | hakios.camera.c:4000 | 0666 root:wheel | `camdev_read` (:3803) starts the sensor and returns frames; `camdev_write` sets exposure, focus, sensor, and fills the "picture for the host" buffer that the loader hands out (`keep_picture`, :3906-3940, bounded by `want <= keep_bytes`) |
+| /dev/hakios-haptic | hakios.haptic.c:828 | 0666 root:wheel | drive the vibration motor (`haptic_write`) |
+| /dev/hakios-torch | hakios.torch.c:575 | 0666 root:wheel | light the flashlight (`torch_write`; level clamped to 1000, the driver has a 30 s limit) |
+| /dev/ufs_* , /dev/rufs_* | hakios.ufs.c:1517, 1522 | 0640 root:operator | raw phone storage, read only (see below) |
+| /dev/rvblk0, /dev/rrvblk0 | hakios.virtio_blk.c:516-518 | 0600 root:operator | QEMU disk image |
+| /dev/rsp0 | hakios.sparse.c:270 | 0600 root:operator | part of an image, block device |
+| /dev/md*, /dev/rmd* | Apple bsd/dev/memdev.c:686-697 (unchanged) | 0600 root:operator | RAM disks, including the second image added at patch:1713-1723 |
+
+Can an unprivileged process read the phone's raw storage? Not directly: /dev/ufs_* and /dev/rufs_* are 0640
+root:operator (owner root, group operator read-only; on iOS the group has only root in it), /dev/rvblk0 and /dev/rsp0
+are 0600. With P1, any process can reach root and therefore all of them. The write path to /dev/rufs_darwin is bounded
+(see "Checked and found fine").
+
+The code does no check of its own in any `d_open` (`touch_open`, `audio_open`, `mic_dev_open`, `camdev_open`,
+`haptic_open`, `torch_open`); file mode is the only gate. Whether the iOS sandbox adds one is out of reach here (the
+Sandbox is a stub that allows everything, kern_minimac.c:230-242).
+
+Fix: create these nodes 0600 root:wheel, or 0660 with the group of the one daemon that uses each (backboardd for touch,
+mediaserverd for audio, mic, camera, haptic, torch), or test an entitlement in `d_open`, for example in touch_open:
+
+```
+ static int
+ touch_open(...)
+ {
+- return 0;
++ return IOCurrentTaskHasEntitlement("com.apple.hakios.touch") || suser(kauth_cred_get(), NULL) == 0 ? 0 : EPERM;
+ }
+```
+
+## P4. A privilege that was refused is now granted to everyone, before the deny policies (Medium)
+
+Where. patch:828-839, `priv_check_cred()` in bsd/kern/kern_priv.c:
+
+```
+if (priv == PRIV_NET_PRIVILEGED_SOCKET_DELEGATE) { return 0; }
+```
+
+placed before `mac_priv_check()` (Apple kern_priv.c:89-94), so no MAC policy can deny it, and for every credential, not
+just mobile.
+
+What it enables. The privilege is the gate for socket delegation: `so_set_effective_pid()`/`so_set_effective_uuid()`
+when the target is not the caller (Apple uipc_socket.c:8111-8117, :8235), `socket_delegate()` (Apple
+uipc_syscalls.c:270-276), NECP client delegation (necp_client.c:6917, necp.c:6847), and the Skywalk delegate checks
+(fsw.c:973, nx_netif.c:1575). With the hunk any process can attribute its sockets to any other pid and executable UUID,
+so per-process network policy, statistics and accounting see the victim instead of the caller.
+
+The stated reason is stale. The comment says no process carries an entitlement. Today miniamfi_entitlements.cpp reads the
+entitlements from each program's signature, and kern_minimac.c:290 already maps this very privilege to
+`com.apple.private.network.socket-delegate`; trustd, nsurlsessiond and mediaserverd carry it in their Apple signatures.
+So the hunk is redundant and makes the stub's entry dead code. (kern_minimac.c:253-258 says the NECP refusal "costs
+nothing"; with this hunk the macro is never refused, so that comment and this hunk cannot both describe the current
+tree.)
+
+Reach is PLAUSIBLE only because I did not run it: whether anything in this port enforces NECP policy per app was not
+examined.
+
+Fix: delete the hunk. The entitlement path in `minisandbox_priv_grant()` grants the privilege to the daemons that hold
+the entitlement.
+
+## P5. An unconditional kernel printf on a user-controlled path (Low, CONFIRMED)
+
+patch:853-859 adds, in `__pthread_kill()`:
+
+```
+if (signum == SIGABRT) { user_abort_trace(); }
+```
+
+`user_abort_trace()` (user_exception_trace.c:112-145) has no gate. Its sibling `user_exception_trace()` returns at once
+unless the boot-arg `systrace` is set (:48); `ustacks` is boot-arg driven. The file's header says the facility is on
+"with boot-arg systrace set".
+
+Failure scenario. A process ignores SIGABRT (`signal(SIGABRT, SIG_IGN)`) and calls `pthread_kill(pthread_self(),
+SIGABRT)` in a loop. Each call does one `printf` of up to 24 return addresses, plus the process name (which the process
+chooses: its executable's last path component, so it can embed newlines). That goes to the console (video console and
+UART, which the loader comments call very slow), to the kernel message buffer, and from there into the loader's log
+(which keeps the first 256 KB and the last 1 MB, loader_return.c:30-38): the log's evidence is pushed out and the CPUs
+that printf are slowed. Not a memory-safety problem: the frame walk is bounded (24 frames, monotonic, `copyin`).
+
+Fix:
+
+```
+ void
+ user_abort_trace(void)
+ {
+ thread_t thread = current_thread();
++ if (!user_exception_trace_enabled) {
++ return;
++ }
+```
+
+## P6. Pid-version bump skipped by process name only (Low, PLAUSIBLE)
+
+patch:726-742 skips `proc_setpidversion()` in `exec_handle_sugid()` (Apple kern_exec.c:6639) when
+`strncmp(p->p_comm, "xpcproxy", ...) == 0`. At that point `p_comm` is still the name of the image that is exec'ing
+(`set_proc_name()` runs later, Apple kern_exec.c:1924, after `exec_handle_sugid` at 1581). So the exception applies to
+any process whose comm is `xpcproxy`, for any exec it does, not only the exec into the service xpcproxy was spawned
+for. A process inherits the comm through fork, and a user can name a program `xpcproxy`.
+
+The pid version in the audit token is what makes a daemon that holds an audit token notice an exec; without the bump a
+process called xpcproxy can send an XPC message as itself, exec an entitled system binary, and the daemon's later
+entitlement check on the unchanged token resolves to the new image (the classic exec race). On this port the same
+effect is already cheaper through a self-written signature (the AMFI stub reads entitlements without validation), so
+the practical gain is small; but the hunk regresses a property the kernel otherwise keeps. Reach depends on daemon
+behaviour I did not examine, hence PLAUSIBLE.
+
+Fix: also require the spawn that created the process to be launchd's, for example only skip when `p->p_ppid == 1` and
+the target is not xpcproxy itself, or mark xpcproxy's spawn with a posix_spawn flag that the kernel records in the
+`proc`, and test that instead of the name.
+
+## P7. Sandbox request 4: container of any pid, read from memory the process owns (Low, PLAUSIBLE)
+
+kern_minimac.c:147-225 answers `sandbox_container_path_for_pid()` for any `args.pid` the caller names (:173-176): no
+check of the caller's credential, of its relation to the target, or of an entitlement. The answer is taken by scanning
+the target's exec strings for `CFFIXED_USER_HOME=` in its live user stack (:196-222). That memory is writable by the
+target after exec, and at exec time it is whatever environment the parent passed.
+
+Failure scenario. Process A rewrites the `CFFIXED_USER_HOME=` string in its own stack (or execs itself with the
+variable set). A daemon that asks the kernel "what is A's container" (the call exists for exactly that) gets the path A
+chose, for example another application's data container, and may then read or write there on A's behalf. A different
+process learns the container path of any other process. The kernel side is memory-safe: `strnlen` and `s + len < end`
+bound the scan, `len < args.size` bounds the copyout, the map is referenced, and the page-rounded copy covers `argslen`.
+
+The comment (kern_minimac.c:137-142) says the environment is where the container comes from, so this is by design; what
+the comment does not say is that the answer is exposed for other pids and that the source is mutable. Which user-space
+daemons use the answer for an access decision was not examined.
+
+Fix, if it matters: cache the string in `struct proc` at exec time (the kernel already walks the strings in
+`exec_extract_strings`) instead of re-reading the stack, and require `kauth_cred_getuid` equality or
+`PRIV_...` for pid != caller.
+
+## Checked and found fine
+
+Policy stand-ins
+
+- AMFI (miniamfi.c): `vnode_check_signature` sets CS_SIGNED and, for ad hoc signatures, CS_PLATFORM_BINARY, and returns 0
+ (:45-62). That is stated at kern_minimac.c:11-17. The consequences I traced: `task_conversion_eval_internal` (Apple
+ ipc_tt.c:2489) lets a platform binary resolve other platform binaries' task ports, and `F_ASSERT_BG_ACCESS` (Apple
+ kern_descrip.c:5048) is platform-only; both are therefore open to any ad hoc signed program, which anyone can make.
+ By design; noted so that nobody reads "platform" as a trust statement.
+- The trust-cache and OSEntitlements tables answer "not found" or "unsupported" everywhere except the three
+ `...WithProc` queries, which read the program's signature (miniamfi.c:93-124); only the `WithProc` variants are called
+ by the kernel (IOKitBSDInit.cpp:1495/1526/1559, IOUserClient.cpp:1507). No stub answers "yes" for an entitlement the
+ signature lacks; an absent signature has none (`cs_entitlements_blob_get` returns NULL when CS_SIGNED is unset, Apple
+ kern_cs.c:1725-1727).
+- `copy_entitlements` (miniamfi_entitlements.cpp:32-64): rejects `length <= sizeof(CS_GenericBlob)`, copies
+ `length - 8` into a buffer of `+1` and terminates it. Notes, not findings: the plist is re-parsed on every query
+ (no cache), and its size is bounded only by the code-signature blob limit.
+- dyld policy request 0x5a and boot-arg query 0x60 (miniamfi.c:89-111): fixed 8-byte copyout to the address the caller
+ gives; `copyin` of exactly 16 bytes; everything else is ENOPOLICY. It answers "allow everything" to every process,
+ including DYLD_* variables and interposing for restricted programs; that is the purpose (kern_minimac.c:64-69).
+- Sandbox (kern_minimac.c:230-242): every request except 4 returns 0 and writes nothing. A caller of an "issue
+ extension" style request then reads an unwritten out buffer in user space; stated in the file's header.
+- `minisandbox_priv_grant` (:318-349): consulted only after the root test (Apple kern_priv.c:104-119); the entitlement
+ is read from the current process and only when `cred == kauth_cred_get()`; PRIV_WORK_INTERVAL is granted to all
+ (:325, needed by UIKit; it gates `WORK_INTERVAL_OPERATION_CREATE2`, Apple sys_work_interval.c:71, and the effect of the
+ work-interval classes needs a workload id, which I did not trace). The table maps privileges to entitlements that a
+ user can write into their own signature (no validation: stated at miniamfi_entitlements.cpp:4-9), so for non-root
+ these privileges are as strong as the signature a user chooses. Log lines are bounded (32 privileges).
+- AppleKeyStore (MiniAppleKeyStore.cpp): answers "no passcode, unlocked" for state; lock, unlock and `UnlockBag`
+ return success for any input, which is the right answer for a device with no passcode and, since no
+ change-passcode selector exists (`kIOReturnUnsupported`, :314), no caller can set one. Wrap/unwrap are a reversible XOR
+ (:173-181) and the file says so. Bounds: wrap needs `1..64` bytes into `wrapped[72]` (:261-277); unwrap
+ `9..72` into `key[64]` (:285-290); DER buffers `der[128]` hold 91 and 30 bytes; `scalarOutputCount` and
+ `structureOutputSize` are checked before writes. The user client has no task check, but nothing it returns or does is
+ secret or persistent.
+- Data protection: the APFS port implements no protection class and `apfs_vnop_ioctl` returns ENOTTY
+ (apfs_vnops.c:1190-1197), so `F_SETPROTECTIONCLASS`-style callers get "unsupported", not success.
+- MiniIONetworkStack: a service, an openable user client, `setProperties` refuses (:85-94); the open logs the registry
+ state; no state is shared.
+- GenericARMPE: CPU nubs are indexed only after `number >= MAX_CPUS` is excluded (:234); `reg` length checked (:77);
+ `cpus[]` is static; the thread-call lambda touches only `cpus[]` and the topology. The device tree is the loader's.
+
+Surface
+
+- Every sysctl the port adds (grep over xnu/files; the modem files were not read):
+ - writable: `kern.exec_inject` (root; see below), `kern.hakios_switch_root` (pid 1 and root, once, input
+ `< 512` bytes, hakios.apfs_check.c:1753-1766), `kern.apfs_synthetic` (explicit `suser`, `newlen < MAXPATHLEN`,
+ NUL-terminated, apfs_vfsops.c:660-671), `kern.apfs_stats` (write zeroes the counters, root through the sysctl
+ layer), `kern.hakios.var_save`, `kern.hakios.var_busy`, `kern.hakios.ufs_native` (`sysctl_io_number`, a small state
+ machine, root).
+ - read-only: `kern.hakios.version`, `kern.hakios.battery_*`, `kern.hakios.ufs_*` counters, `kern.hakios_memory`
+ (apfs_vfsops.c:474-478).
+ - none uses CTLFLAG_ANYBODY (grep), and Apple's `sysctl_root` demands `proc_suser` for any write to an OID without it
+ (Apple kern_newsysctl.c:1737-1745). So all writes need uid 0, which P1 makes available to any process.
+- `kern.exec_inject` (patch:625-677): `SYSCTL_STRING(... exec_inject_conf, 512)`; Apple's `sysctl_io_string` refuses
+ `newlen >= 512` and terminates at `newlen` (kern_newsysctl.c:530-536), so the buffer always has a NUL. The parser
+ advances at least one byte per iteration or exits at NUL; the append test `used + 1 + liblen < size` leaves room for
+ the `:` and the NUL; `inject_env` is 512 bytes, the same size as the buffer; matching is on the file's basename with an
+ exact length compare. An unprivileged user can only get the library into a process they run themselves by naming it;
+ that gives them nothing they lack. The variable is added after the caller's own environment, so a caller-supplied
+ `DYLD_INSERT_LIBRARIES` comes first.
+- bindfs exemption (patch:964-973): the entitlement test remains (and can now be satisfied from a signature); the extra
+ `pid == 1` clause only matters to a process that is pid 1, which stays launchd after init execs it. Mounting still
+ needs root.
+- Raw-storage write path (hakios.ufs.c:566-625, 823-857): block aligned, only the one partition selected by the
+ `ufs_write=1` boot-arg, from `UFS_WRITE_FIRST` on, `offset` and `len` checked against the partition size in uint64,
+ the character open of that partition clears FWRITE before the open check but the node mode (0640, owner root) still
+ decides who may open it for writing, and one writer at a time through the `var_busy` claim.
+- Camera, mic, audio, haptic, torch handlers: every `uiomove` length is bounded by the destination size (`audio_write`
+ chunks to the stack buffer; `mic_dev_read` `n <= RING_FRAMES`; `camdev_read` `n <= ring_frame_bytes`; `haptic_write`
+ 256 samples; `torch_write` clamps to 1000); exposure and focus values are clamped before they reach registers
+ (`exposure_limits` :3306, `af_move` :3039).
+- User-visible patch hunks, regression check: `mdevrw` (patch:311-321) keeps the original treatment of a negative offset
+ (root-only, Apple's behaviour); `km.c` TIOCSCTTY refusal only affects the console; work-interval cases 6-8
+ (patch:924-939) return 0 only for CoreAudio threads, otherwise the old ENOTSUP; vm_unix.c shared-region hunk
+ (patch:1442-1462) adds an accept branch for a volume mounted directly inside Preboot's Cryptexes (root-only mount; the
+ `va_uid == 0` owner check at Apple vm_unix.c:2475 still applies earlier) and keeps `vnode_put` balanced in all three
+ arms; `percpu_foreach_secondary` rewrite is integer arithmetic with the same bounds; `halt_all_cpus` and
+ `kdp_machine_reboot_type` call `loader_return()` first, which returns at once if no loader stub exists; the
+ `systrace`, `applog`, `regtrace`, `exec_trace` hooks are boot-arg gated and bounded (`copyinstr` into 160- and 32-byte
+ buffers, at most 6 mib words); `startup.c` declares `minimac_policy_init` inside `#if CONFIG_VNGUARD` while the call is
+ outside it (a RELEASE configuration without vnguard would not compile; DEVELOPMENT builds are unaffected).
+- Loader return (loader_return.c, start.s hunk patch:2392-2631): the stub address and the PA-VA offset are read from
+ `loader_stub_slot`, which the loader patches in the kernel image and nothing user-reachable writes;
+ `loader_jump` rejects `t0sz` outside 25..33 or a stub that does not fit under it, so `loader_l1[stub >> 30]` is
+ below 512; the ring arithmetic keeps every index below `LOADER_LOG_SIZE`; the early exception vectors branch to the
+ loader only while VBAR holds a physical address and spin as before when no stub was patched. The kernel does not check
+ the slot's magic or that the stub lies outside the kernel, and it acts on `loader_live.stop` as soon as it is
+ non-zero; both are writable only by the loader or by whoever has kernel memory. The loader in turn trusts the
+ `loader_recording`/`loader_sound` physical addresses and lengths (at most 1 GB) that the kernel writes; the
+ only user-influenced writer is the camera's `keep_picture`, which stores the address of its own buffer.
+ Minor: `loader_return_entered` is tested and set without an atomic, so two processors reaching `loader_jump`
+ together (a panic and the five-finger exit) could both pass it; `psci_smp_stop_others()` runs first and I did not trace
+ its handling of that.
+
+## Not checked
+
+- IOKit user clients of MiniIOSurface.cpp, MiniIOMobileFramebuffer.cpp, hakios.gpu.cpp, hakios.wlan.cpp,
+ hakios.battery.cpp (external methods, shared memory): outside the file list given to me.
+- bsd/miscfs/ramfs and apfs vnode operations: how ownership, setuid bits and `access` are enforced there (ramfs stores
+ `va_mode & ALLPERMS`, ramfs.c:152, 1032).
+- What iOS user space does with the stub answers: whether cfprefsd, lsd or containermanagerd use P7's container path
+ for an access decision; whether dyld honours DYLD_* for setuid programs given the allow-all AMFI answer; whether this
+ port ships any setuid-root program; whether `task_for_pid` is otherwise gated for ad hoc signed callers.
+- Behaviour on hardware: P2's effect on the speakers, whether the Sandbox stub's `0` for unknown requests produces
+ usable values in `libsystem_sandbox`.
+- gic_v3_irq.c, psci_smp.c, generic_arm64_support.c, minicrypto, the cellular files, xnuloader's USB side.
+- The scheduler hunks for slower cores (sched_prim.c, machine_routines.c): read, not analysed for correctness; they
+ are policy, not privilege.
diff --git a/docs/driver-review/sound.md b/docs/driver-review/sound.md
new file mode 100644
index 0000000..59f9ff1
--- /dev/null
+++ b/docs/driver-review/sound.md
@@ -0,0 +1,255 @@
+# Driver review: sound path (speakers, microphone, /dev/hakios-audio)
+
+Read-only audit; nothing was built, run or changed except this file.
+
+## Scope and method
+
+Files (all under `xnu/files/bsd/dev/` unless noted):
+
+| file | lines |
+|---|---|
+| hakios.audio.c | 354 |
+| hakios.sound.c | 1518 |
+| hakios.speaker.c | 1211 |
+| hakios.mic.c | 1847 |
+| hakios.virtio_sound.c | 406 |
+| `userland/src/audio_plugin.c` (writer/reader side, volume control) | 1041 |
+
+Also read because the sound path depends on them (not in the group, so only the parts the sound path uses):
+`xnu/files/bsd/sys/hakios.audio.h`, `hakios.guard.c` (the guard that limits what the amplifiers get), and in `hakios.adsp.c`
+only `root_file()`/`hakios_adsp_fw_file()` (loader of aw882xx_acf.bin) and `apr_input()`/`hakios_adsp_apr()`.
+
+Method: whole-file reading of the five kernel files and the I/O and volume parts of the plug-in; each finding traced from
+the input (user write/ioctl/read, file contents, DSP event, boot-arg) to the faulty operation. Tracing of arithmetic was
+done by hand (uint32 wrap points worked out with concrete numbers). Nothing was executed, and the real
+aw882xx_acf.bin is not in the repository, so file-driven findings are traced against the parser only.
+Hardware facts (register layouts, what level is safe for the amplifier) are not asserted; where a consequence
+depends on them the finding says NEEDS-HARDWARE.
+
+Severity is about the effect if the trigger happens; confidence is as defined in the task (CONFIRMED = path traced end to end).
+
+## Findings
+
+| id | severity | confidence | file:line | one line |
+|---|---|---|---|---|
+| S-01 | High | CONFIRMED (effect on hardware: NEEDS-HARDWARE) | audio.c:268, sound.c:1267/1272/1279, speaker.c:897-941, guard.c:160 | unclamped user `below` can make the volume fade loop spin forever at Android's loudest level while the guard is told "amplifiers off" |
+| S-02 | Medium | CONFIRMED | audio.c:268, sound.c:1267/1279 | `below + extra` wraps: any local user can lift the level to Android's maximum, past `sound_below` |
+| S-03 | Medium | CONFIRMED | speaker.c:478-479, 484, 495 | monitor-table bounds check done in uint32: crafted ACF makes the row pointer go up to 3.5 GB out of the file buffer |
+| S-04 | Medium | PLAUSIBLE | speaker.c:688-696, 1033-1065, sound.c:1346 | `hakios_speaker_stop()` gives up on the first failed I2C read, leaves both amplifiers up, and its caller then stops the TDM clock |
+| S-05 | Medium | PLAUSIBLE | speaker.c:623-646, 1068-1080 | `power_down_now()` clears `started` even when its power-down write was not acknowledged; the panic quiesce then skips the amplifier that is still on |
+| S-06 | Medium | CONFIRMED | mic.c:1737-1778 | mic=4: a bring-up that fails without setting `broken` is retried forever (no failure count), re-toggling the codec reset and the DSP votes |
+| S-07 | Low | CONFIRMED | sound.c:635, 693-706 | page tables for the DSP's SMMU context are allocated at every `space_on()` and never freed (12 KB per recording in mic=4) |
+| S-08 | Medium | PLAUSIBLE (mode CONFIRMED; reach depends on iOS sandbox) | audio.c:343, mic.c:1732, 1524-1534 | both device nodes are 0666; any process can start the microphone, steal/split its samples, set the volume or mute; open state is a flag, not a count |
+| S-09 | Low | PLAUSIBLE | mic.c:719, 727 | SoundWire read id cycles through 0; an empty (zero) FIFO word matches id 0 and is returned as a successful read of 0 |
+| S-10 | Low | NEEDS-HARDWARE | mic.c:704-710 | `swr_write()` waits for FIFO room at most 10 ms and then writes anyway; the result is always `true` |
+| S-11 | Low | NEEDS-HARDWARE | sound.c:719, mic.c:1614-1617 | DSP-written mic buffer is only invalidated after the DSP has used it; dirty zero-fill lines are never cleaned first |
+| S-12 | Low | PLAUSIBLE | virtio_sound.c:249-251 | used-ring entry read without a load barrier, and its `id` trusted as an index into `tx_free[]`/the shared area |
+| S-13 | Low | CONFIRMED (file outside this group) | hakios.adsp.c:2488-2495 | `payload` underflows when the DSP's `header.size` < header length; 256 bytes are then copied from beyond the packet |
+| S-14 | Low | PLAUSIBLE | audio_plugin.c:282, 788-793 | a NaN volume passes the clamp, `lround(NaN)` gives `below` 0 and `muted` 0: loudest |
+| S-15 | Low | CONFIRMED | sound.c:1195-1199, mic.c:1644 | a period whose submission to the DSP fails is never re-submitted: the stream starves one period at a time |
+| S-16 | Low | CONFIRMED | mic.c:1597 | mic=1..3 `listen(false)` ignores `stopping`: `hakios_mic_dsp_down()` can block for `mic_secs` (up to 600 s) |
+
+## Details
+
+### S-01 High CONFIRMED (hardware effect NEEDS-HARDWARE)
+
+Unclamped `below` from user space reaches `hakios_speaker_volume()`, whose fade loop can never finish, and it also makes the guard think the amplifiers are off.
+
+Chain:
+
+1. `audio.c:268` `volume_below = volume->below;` ioctl `HAKIOS_AUDIO_SET_VOLUME` stores any uint32; the node is mode 0666 (`audio.c:343`), no privilege test, no range test.
+2. `sound.c:1253-1272` (watch thread) takes it as `extra` and does `guard_level(below + extra)` (1272) and `hakios_speaker_volume(below + extra, 1)` (1267, 1279). `below` is `sound_below`, default 240. The sum is uint32 and wraps.
+3. `speaker.c:897` and `:914`: `uint32_t target = a->volume_at + below;` wraps again. Take `extra = 0xFFFFFF0F` (so `below + extra = 0xFFFFFFFF`): `target = volume_at - 1`, which is *below* `volume_at`. With the profile's level (the header comment says Android's is -2.1 dB, so `volume_at` is about 17, never 0) the clamp `if (target > VOLUME_LOWEST)` does not trigger.
+4. `speaker.c:919` `if (a->volume == target) continue;` can never be true: `set_volume()` (707-709) raises every request to `volume_at`, so `a->volume` bottoms out at `volume_at` and `target` stays under it. The `for (;;)` at 909 sees `moved = true` forever: one I2C write plus read-back and a 1 ms wait per round, two log lines each. There is no `stopping` check and, with `step_ms = 1`, not even the status check (928 needs `step_ms >= 10`). The watcher thread is stuck, so no silence timeout, no fault polling and no `hakios_speaker_stop()` happens. Only `take_down()` at the run's end breaks it, because it calls `hakios_speaker_stop()` after 3 s and a failed/`broken` write makes the loop return.
+5. At the same time step 2's `guard_level(0xFFFFFFFF)` equals `HAKIOS_GUARD_SILENT` (`guard_level()` takes `min(level, guard_as)` and `guard_as` defaults to UINT32_MAX). In `hakios.guard.c:160` that means `to_speaker = 0` (no power limit) and at `:225` the peak ceiling stays at full scale: the guard only clips. Any `s` in `[2^32 - volume_at, 2^32 - 1]` is blind in the same way, because `amplitude(2 * attenuation)` wraps to a huge index and returns 0.
+
+Failure scenario: `ioctl(fd, HAKIOS_AUDIO_SET_VOLUME, {below = 0xFFFFFF0F, muted = 0})` from any process, then any non-silent write to the same node (or iOS playing anything). The amplifiers are faded to Android's loudest level, the speaker guard is off, and the thread that should turn them off after three seconds of silence is in an endless I2C loop. Whether that level without the guard can hurt the speakers is NEEDS-HARDWARE (the guard exists "for want of the DSP's speaker protection", per `hakios.audio.h`).
+
+Fix (three independent layers; do all):
+
+```diff
+--- hakios.audio.c audio_ioctl
++#define HAKIOS_AUDIO_BELOW_MAX (90 * 8) /* the amplifiers' own floor: speaker.c VOLUME_LOWEST */
+ lck_mtx_lock(&audio_lock);
+- volume_below = volume->below;
++ volume_below = volume->below > HAKIOS_AUDIO_BELOW_MAX ? HAKIOS_AUDIO_BELOW_MAX : volume->below;
+--- hakios.sound.c watch()
+- hakios_speaker_volume(below + extra, 1)
++ hakios_speaker_volume(below_total, 1) /* uint32 below_total = below > 720 ? 720 : below; below_total += extra (extra already <= 720) */
+--- hakios.speaker.c hakios_speaker_volume
+- uint32_t target = a->volume_at + below;
++ uint32_t target = a->volume_at + (below > VOLUME_LOWEST ? VOLUME_LOWEST : below); /* (both loops) */
+ /* and make the loop finish: */
+- if (a->volume == target) continue;
++ if (a->volume == target || target < a->volume_at) continue; /* (target is already clamped, belt and braces) */
+```
+Also give the guard a value that cannot collide with the sentinel (`guard_level()` should clamp to `HAKIOS_GUARD_SILENT - 1`), and add an iteration limit (about 2 * VOLUME_LOWEST / 1 steps) to the fade loop.
+
+### S-02 Medium CONFIRMED
+
+Same cause as S-01: `sound.c:1267, 1279` computes `below + extra` in uint32 with `extra` from user space. `extra = 2^32 - 240` (with `below = 240`) gives 0, so `hakios_speaker_volume(0, 1)` fades to `volume_at`, Android's level, 30 dB louder than the cap (the code's default `below = 240` eighths; the header comment says 160) that `sound_below` is documented to be ("sound_below, which stays the loudest", `sound.c:31-32`; `hakios.audio.h:34-36`). Here the guard still sees the true level (`guard_level(0)`), so its power and peak limits apply; the cap that the operator set at boot does not. Whether Android's level is safe for this phone is NEEDS-HARDWARE; the cap bypass itself is certain. The fix of S-01 (clamp `extra`, saturating add) closes it.
+
+### S-03 Medium CONFIRMED
+
+`acf_monitor()` bounds check in 32-bit arithmetic, `speaker.c:478-479`:
+
+```c
+temp_at + temp_count * temp_size > length || vbat_at + vbat_count * vbat_size > length
+```
+`temp_count` is checked `<= 8` but `temp_size` has only a lower bound (`>= 12`). All three are uint32, so `temp_count = 8, temp_size = 0x20000000, temp_at = 0x48` gives `8 * 0x20000000 = 0` (mod 2^32), the check passes, and the loop at 483-493 reads `row = block + temp_at + i * temp_size` for i up to 7: reads from `block + 0xE0000048`, 3.5 GB past a buffer of at most 1 MB (`acf_profiles()` limits the file to 0x100000). Also `temp_at = 0xFFFFFFFC, count 1, size 12` wraps to 8 and passes (row at `block + 4 GB`). The same holds for `vbat_*` at 494-504. The byte-sum checksum (469-471, 478) is trivial to satisfy for whoever crafts the file. Effect: synchronous data abort (kernel panic) in `hakios_speaker_prepare()` at the first sound=3/4 start, or, if the address happens to be mapped, garbage reductions in `temp_rows/vbat_rows`. The file comes from the system image, so the realistic trigger is a corrupted or hostile image rather than a remote attacker; but this is the loader the task asked about and the only parser step whose bounds are not sound (the others are fine, see below).
+
+Fix:
+```diff
+- temp_at + temp_count * temp_size > length || vbat_at + vbat_count * vbat_size > length) {
++ (uint64_t)temp_at + (uint64_t)temp_count * temp_size > length ||
++ (uint64_t)vbat_at + (uint64_t)vbat_count * vbat_size > length) {
+```
+and loop with `(uint64_t)i * temp_size`. Also saturate the `less` additions at 502 (`uint16_t` wrap, a file with a large `vmax` turns a big reduction into a small one).
+
+### S-04 Medium PLAUSIBLE
+
+`hakios_speaker_stop()` abandons the sequence on the first failure and does not power anything down:
+
+- `speaker.c:688-696` `sysctrl()`: if `get()` (an I2C read) fails it returns false and does *not* call `power_down_now()` (only `put()` does).
+- `speaker.c:1045-1061` `hakios_speaker_stop()`: `return;` on every failed step (1046, 1051, 1055, 1059). The `return` is inside the loop over the two amplifiers, so a failure at amplifier 0 leaves amplifier 1 untouched (still started, unmuted, volume as it was) and amplifier 0 half-way (e.g. ULS-muted, volume stepped but not powered down).
+- Callers: `sound.c:1299` (watcher, after silence; `on = false` is set regardless) and `sound.c:1346` (`take_down()`), which ignores the failure and goes on to `stream_off()` and `afe_off()` (`sound.c:1347-1348`), i.e. stops the TDM clock the amplifiers are locked to.
+
+Scenario: one NACK or "bus not at rest" (`bus_take()` returning false: SDA or SCL read low, `speaker.c:272`) during the final stop. Result: amplifier(s) left with power-down off, no bit clock, nothing retrying. In the watcher case the next `hakios_speaker_start()` restarts the sequence, so only the run-end case is permanent. How an Awinic amplifier behaves without a clock is NEEDS-HARDWARE.
+
+Fix: make `hakios_speaker_stop()` finish every amplifier regardless of earlier ones and fall back to the unconditional power-down:
+```diff
+- if (!sysctrl(a, SYSCTRL_ULS_HMUTE, true)) { return; }
++ if (!sysctrl(a, SYSCTRL_ULS_HMUTE, true)) { power_down_now("stop: could not mute"); return; }
+ ... (same for the other `return;` lines)
+```
+and let `take_down()` check a returned bool / `hakios_speaker_quiesce()` after a failed stop.
+
+### S-05 Medium PLAUSIBLE
+
+`power_down_now()` (`speaker.c:623-646`) sets `broken = true` first and `a->started = false` at 644 after the write, whether or not the write and read-back at 639 were acknowledged (the failure only logs "NOT ACKNOWLEDGED", 640). After that:
+
+- `put()`, `sysctrl()`, `hakios_speaker_stop()` all return at once on `broken` (654, 692, 1035): nothing retries.
+- `hakios_speaker_quiesce()` (1068-1080) returns early when no amplifier has `started` set (`any` false), so the panic path of `hakios_sound_quiesce()` does not even try.
+
+Scenario: an I2C fault (bus not at rest, NACK) in the very moment a fault is handled leaves an amplifier powered with the code believing it is off. Also in a panic: other CPUs are halted wherever they were, possibly with SCL or SDA held low by an interrupted bit-bang transfer; `bus_take()` then refuses to touch the bus (272-278) and `quiesce` gets no power-down through, and there is no bus-recovery (clocking out up to nine pulses) anywhere. Hardware behaviour of the frozen bus is NEEDS-HARDWARE, the bookkeeping error is not.
+
+Fix: keep `started` true when the power-down write failed (`if (ok) a->started = false;`), let `quiesce` run when `broken && any prepared amplifier is not known off`, and add a bus-recovery step (SCL pulses with SDA released, then STOP) before giving up in `bus_take()`.
+
+### S-06 Medium CONFIRMED
+
+mic=4 retry loop, `mic.c:1737-1778`. `failed = broken;` (1761) is the only failure signal counted (`++failures >= 3`, 1770). But `path_up()` fails *without* setting `broken` in several places: `clocks_on()` false (1696-1699), `codec_wait() == 0` (1704-1706), `bolero_look()` unknown version (1118), `dsp_path_on()`/`dsp_port_on()` (APR refusal), `datapath_on()` returning false after a failed `swr_read()` (1001-1003), and `listen()` returning early on a refused RUN (1565-1569). In all of those `failed` is false, the code prints "ended", runs `undo()` and loops: `ios_wants` is still 1 while iOS keeps the device open, so it immediately starts another attempt. Each attempt is `clocks_on` (DSP votes and clock commands, up to 1 s per unanswered command), the codec reset pulse on GPIO 83, pins, SoundWire master bring-up, `codec_wait()` (200 ms) and the undo of all of it, indefinitely, with lines suppressed by `quiet` after the first. `recordings` grows without limit.
+
+Scenario: codec or DSP not answering (the case the retry cap was written for) while the audio server holds the input open: the cap never fires.
+
+Fix:
+```diff
+- if (path_up()) {
+- listen(true);
+- }
+- failed = broken;
++ bool up = path_up();
++ if (up) { listen(true); }
++ failed = broken || !up || (listen produced no samples, e.g. reads_done == 0);
+```
+(then the existing `failures >= 3` and the "wait until iOS closes" logic apply).
+
+### S-07 Low CONFIRMED
+
+`sound.c:635` `kmem_alloc(... &space.tables, 3 * 4096 ...)` in `space_on()`; `space_off()` (693-706) and the rest of the file never free it (`grep kmem_free`: no hits in the five files). `shared_get()` calls `space_on()` whenever `space_users == 0` and `!space.on` (725-730). With mic=4 and no sound=N every iOS recording takes and gives back the last user (`hakios_audio_dsp_memory()` / `_put()`), so each recording leaks 12 KB of wired kernel memory and overwrites the pointer. The same happens after the TLB-wait timeout return at 672-675 (tables allocated, `space.on` false, next call allocates again). Not freeing while the context could still be walked is safe (the pointer is simply lost); fix: keep one allocation (`if (space.tables == 0) kmem_alloc(...)`) and re-zero it, or free it in `space_off()` after the context is switched off and the TLB invalidated.
+
+### S-08 Medium PLAUSIBLE (mode CONFIRMED, effect depends on sandboxing, which I did not examine)
+
+`audio.c:343` and `mic.c:1732` create the nodes with mode 0666. In XNU file permissions are the only gate in the kernel for `open()` (a sandbox profile may add more).
+
+- Microphone: opening `/dev/hakios-mic` sets `ios_wants = 1` (mic.c:1524-1526), which makes the for_ios thread power the codec path up and fill `ring`; any reader gets the audio (`mic_dev_read`, 1484-1519). Two readers split the stream. The ring is not cleared between sessions (only reset in the thread, 1752-1754, which races with a reader that starts at open).
+- `ios_wants` is a single flag: `mic_dev_close` sets it to 0 (1532). If any other process opens and closes the node (or XNU calls `d_close` for a close that is not the last: I could not confirm from this tree which, the XNU `spec_close` source is not in the repository), the audio server's recording path is taken down while it still reads.
+- `/dev/hakios-audio`: any process can inject audio and call `HAKIOS_AUDIO_SET_VOLUME` (mute, unmute, S-01/S-02). Each ioctl also logs through `printf` (audio.c:272) and, in sound.c, `say()` to the loader log (1258), so a loop of ioctls floods a log that "keeps its beginning and its end".
+
+Memory safety of the concurrent readers was checked and is fine (all indices are taken modulo the ring size and every copy length is clamped; at worst a reader gets torn or repeated audio).
+
+Fix: create both nodes `0600`/root:wheel (or a dedicated group of the audio server), refcount opens (`ios_wants` as a counter or open-exclusive with `EBUSY`), rate-limit the ioctl logging.
+
+### S-09 Low PLAUSIBLE
+
+`mic.c:719` `read_id = read_id < 14 ? read_id + 1 : 0;` so ids 0..14 are used, and 727 accepts `((answer >> 8) & 0xf) == read_id`. When `read_id == 0` (every 15th read) and the FIFO is empty, `answer = swr_rd(SWRM_CMD_FIFO_RD_FIFO)` at 726 (read after the 10 ms wait without checking that the FIFO has data) is likely 0, whose id field is 0: the read "succeeds" with value 0. `codec_bits()`/`codec_put()` then compare against it. The same wrap exists for `write_id`, harmlessly. That an empty FIFO reads 0 is NEEDS-HARDWARE. Fix: count ids 1..14 (`read_id = read_id >= 14 ? 1 : read_id + 1`), and test the FIFO level (`>> 16 & 0x1f`) again before using `answer`.
+
+### S-10 Low NEEDS-HARDWARE
+
+`swr_write()` (`mic.c:700-711`): `for (i < 20 && fifo_level >= 16) spin_us(500)` then writes the command regardless and returns true. Callers `port_config()` (972-982), `to_all()`, `broadcast()` and `codec_put(..., check = 0)` ignore the result. If the command FIFO stays full for 10 ms the write is lost without a trace and the SoundWire data port is left half-configured. Fix: return false after the wait times out and propagate.
+
+### S-11 Low NEEDS-HARDWARE
+
+The DSP writes into `buffer + BUFFER_BYTES` (`sound.c:766`, memory from `kmem_alloc(... KMA_ZERO ...)` at 719, normal cacheable memory; the SMMU PTEs use MAIR attribute 0, 0x44 = non-cacheable, `AUDIO_PTE` at 526 with `SMMU_MAIR0` at 523). The CPU invalidates a period only *after* the DSP reports it done (`dc ivac`, `mic.c:1614-1617`). Nothing cleans/invalidates these lines before the first `ASM_DATA_CMD_READ_V2`, although the zero fill left them dirty in the CPU cache (the file does `dc civac` for its page tables at `sound.c:646` and `dc cvac` for the speaker periods, so the pattern is known). A later eviction of a dirty zero line would overwrite DSP-written data in memory and the `ivac` would then read the zeros. Visible effect: occasional zeroed samples in the first periods. Whether the DSP's stream is I/O-coherent (which would make the whole thing moot) is NEEDS-HARDWARE. Fix: `dc civac` over `[buffer + BUFFER_BYTES, +MIC_BYTES)` plus `dsb sy` in `hakios_audio_dsp_memory()` before returning.
+
+### S-12 Low PLAUSIBLE (QEMU only)
+
+`virtio_sound.c:249-251`: `tx_free[tx_free_count++] = (uint16_t)(tx.used->ring[tx.seen++ % QUEUE_SIZE].id / 2);` after reading `used->idx`: (a) no load-acquire/`dmb ishld` between the `idx` load and the ring load, which ARM may reorder when the device runs on another host thread (KVM/HVF); (b) the device-written `id` is used unchecked as a buffer number, `buffer = shared + OFFSET_TX + n` (254), and the number of entries is not compared with `TX_BUFFERS`: a misbehaving device writes up to 1932 bytes at an arbitrary offset or overruns `tx_free[32]`. QEMU is trusted here, so this is hardening. Fix: `__builtin_arm_dmb(0x9)` (ISHLD) after the `idx` load; `if (id / 2 >= TX_BUFFERS || tx_free_count >= TX_BUFFERS) break;`.
+
+### S-13 Low CONFIRMED (hakios.adsp.c, outside this group; reported for its owner)
+
+`hakios.adsp.c:2488` `payload = (header.size < length ? header.size : length) - header_length;`. `header_length <= length` is checked (2484) but `header.size` (set by the DSP) is not compared with `header_length`. With `header.size < header_length`, `payload` underflows to about 4 GB. Then `memcpy(words, data + header_length, min(payload, 256))` (2495) and `memcpy(apr_answer.words, ..., 2515)` copy 256 bytes from beyond the received packet (over-read of the glink receive buffer), `apr_answer.length = payload` is huge, and handlers receive length 256 with nonsense words (the handlers in sound.c/mic.c test `length` against 16/24 and index only within it, so they are safe in themselves). The DSP is firmware we start ourselves, so the trigger is a firmware bug or a corrupted glink packet. Fix: `if (header.size < header_length) return;` and clamp the copy to `length - header_length`.
+
+### S-14 Low PLAUSIBLE
+
+`audio_plugin.c:788-793`: `wanted < 0 ? 0 : wanted > 1 ? 1 : wanted` lets NaN through (both comparisons false); `db_to_scalar()` (271-276) does the same. `volume_to_kernel()` (282) then builds `{ lround(-scalar_to_db(NaN) * 8) , NaN <= 0 }`: `lround(NaN)` is unspecified, in practice 0 or `LONG_MIN`, both give `below = 0` after the uint32 cast, and `muted` is false: loudest instead of muted. A CoreAudio client can set the property. S-01's kernel-side clamp does not cover this (0 is in range), so check `isnan()` in the plug-in (`wanted = isnan(wanted) ? 0 : ...`).
+
+### S-15 Low CONFIRMED
+
+Periods are re-submitted only when the DSP says it has finished the previous submission of that period. `sound.c:1194-1199` (feeder) counts a failed `period_write()` in `failed++` and moves on; `mic.c:1644` `(void)mic_read(next);`. `hakios_adsp_apr(..., ms = 0, ...)` returns false when the glink send fails or the channel is not open (`hakios.adsp.c:2536, 2555-2557`). That period never comes back (no event is ever generated for it), so after eight failures the stream is permanently empty: speakers play silence from the DSP's own underflow handling, and the mic loop spins in `sleep_ms(2)` until iOS closes the device (the "no read has come back" guard at `mic.c:1601` only counts while `reads_done == 0`). Fix: keep a "pending" bitmask of periods that failed to submit and retry them in the loop.
+
+### S-16 Low CONFIRMED (test configuration)
+
+`mic.c:1597`: the end condition is `(for_ios ? (!ios_wants || stopping) : elapsed_ms >= mic_secs * 1000ull) || broken`. For mic=1..3 `stopping` is ignored, but `hakios_mic_dsp_down()` (1839-1847) sets `stopping` and then waits on `mic_lock`, which `mic_thread` holds through the whole `listen(false)`. So the DSP shutdown at the run's end is delayed by up to `mic_secs` (clamped to 600). Fix: test `stopping` in both branches.
+
+## Checked and found fine
+
+hakios.audio.c
+- `audio_write()`: 4 KB stack buffer, chunk length rounded to whole frames and clamped to the buffer, `uiomove` length cast safe, tail of fewer than 4 bytes dropped (not copied uninitialised), error from `uiomove` returned.
+- `audio_record()`: bound `rec_used + sizeof(block) + bytes > rec_size` includes the block header; `rec_frames_max` / `rec_size` computed in uint64; `rec_sound` clamped to 1200 s; memory zeroed (`KMA_ZERO`), header written before `loader_sound[]` is published; `loader_sound[1]` updated under `audio_lock`.
+- Locking: `audio_lock` is a mutex; the sink is called under it and must not sleep, and neither `ios_sink` nor `sound_play` does; lock order is `audio_lock` -> `sound_lock`/nothing, never the reverse (`sound.c` takes `audio_lock` only in `hakios_audio_set_sink`/`hakios_audio_volume` without holding `sound_lock`, except `sound_thread` which takes `sound_lock` -> `audio_lock`; no path takes them the other way round). `audio_report` is re-armed under the lock and its divisions are guarded (`lasted >= 1 s`).
+- `audio_play()` when the sink is replaced by NULL (take_down) is correct; sinks return `taken <= count` so `stretch_lost` cannot underflow.
+
+hakios.virtio_sound.c
+- Ring arithmetic: `RING_FRAMES` is a power of two and indices are free-running uint32, so `ring_tail - ring_head` and `% RING_FRAMES` stay consistent through wrap; room/`taken` computation cannot exceed the ring.
+- Shared-area layout: desc/avail/used of both queues, the control request/answer (0x1000/0x1800, answer at most 260 bytes) and the 32 transmit buffers (1932 bytes each) do not overlap and fit in `SHARED_SIZE` (0x14000); descriptor lengths match the `tx_buffer` fields; `QUEUE_SIZE` checked against `QUEUE_NUM_MAX`; stream count clamped to `MAX_STREAMS` and the answer buffer is sized for it.
+- `control_request()` wait is bounded (1000 x 1 ms); only used during attach. DMA memory from `kmem_alloc_contig`, physical address from `kvtophys`, `dmb ish` between ring entry and index and before notify.
+- Failure paths in `sound_attach()` leak the shared area and leave the device configured (boot time, QEMU only; not worth a finding).
+
+hakios.sound.c
+- SMMU page-table construction: all indices (`root[0]`, `second[0]`, `third[0..23]`) are constants inside one table; `SHARED_BYTES / 4096` entries fit; tables cleaned with `dc civac` + `dsb` before the context is enabled; `used[256]` is indexed with `s2cr & 0xff`; `contexts` from `idr1 & 0xff` bounds the context search; IDR-derived geometry is validated against 1 MB before use; `space_find()` refuses to touch a context or match register that is in use.
+- Speaker period cache maintenance: `period_fill()` and `period_fill_ios()` clean every line of the period (`dc cvac` loop over `PERIOD_BYTES`, then `dsb sy`) after the guard has processed it and before submission; periods are refilled only after the DSP has returned them.
+- Ring between `ios_sink` (producer, serialized by `audio_lock`) and `period_fill_ios` (single consumer): free-running volatile indices, power-of-two size, data written before `ring_head` with `OSMemoryBarrier`, consumer reads `ring_head` before the data; `ring_tail` advanced after the copy; `available` can never exceed the ring.
+- `events()`: payload length tested before `payload[3]`; bit index from the DSP's token only sets bits in a mask, extra bits are cleared by the receivers.
+- Every wait loop is bounded: `play()` (2 s after end, 1 s first period), TLB wait 100 ms, `take_down()` 3 s, `pin_activity` fixed 20000 reads, APR waits 1 s. Stop ordering in `take_down()`: amplifiers stop before the stream closes, the stream closes before the region is unmapped, the region is unmapped before the SMMU context is restored; the shared buffer is deliberately never freed (no use after free).
+- AFE parameter packets (`afe_service_param`, `afe_port_param`): payload at most 44 bytes into a 64-byte area, all sizes constant.
+- Boot-args: `sound` clamped to 4; `sound_gain` clamped to `HAKIOS_GUARD_MAX_GAIN` (12 dB) in both places; `sound_secs` clamped to 3 for the test-tone levels; `sound_below`, `sound_pause`, `sound_guard_as` are accepted as given (operator test knobs: 0 means Android's own level; only level 1 uses an unclamped `seconds * 1000`, which wraps for more than 4.29 million seconds).
+
+hakios.speaker.c
+- ACF loader `acf_profiles()`: file size 0x50..1 MB; table `at + entry_size <= size` in uint64; `entries` 1..64 and stride at least 0x30 so every field read (up to offset 40) stays in the entry; per-entry `offset + length <= size` in uint64 before the data is touched (for the monitor entries `length` is replaced by 0 on failure); `count <= 64` with `profile[64][2]`; `data_length == 4 + 4 * count` makes the uint32 wrap in `ACF_BLOCK_HEADER + data_length` unusable; checksum loop stays inside `length`; registers 0 and 0x70 and above (fuse registers, soft reset) are refused before the `(uint8_t)` truncation at line 785 (so no register number from the file is truncated into a forbidden one); register 0x04 keeps the power-down/mute bits as read, 0x08 TX enable cleared, 0x05 (volume) is set to the lowest right after the profile, 0x50 recomputed from the fuses; `volume_at` decode cannot reach 0x300+ and values at or above `VOLUME_LOWEST` are refused.
+- `set_volume()` clamps both ways (never below Android's level in loudness, never above -90 dB attenuation) and the register encoding (`volume / 48 << 6 | volume % 48`, at most 0x3c0) fits the 10-bit field. Start refuses on an unlocked PLL or any fault bit; the amplifier stays muted and at the lowest volume until the feedback is on; every register write is read back and a mismatch powers both down.
+- I2C bit-bang: clock-stretch wait bounded (100 half bits), STATUS_TRIES bounded, `bus_take()` refuses a busy bus and gives the pins back as found; `spin_us` used in the panic path (no sleeping).
+- Monitor: `looks`-based division by 1..3, `per_eighth` division guarded by `less != 0`, tables at most 8 rows, row index -1 handled. (Gap rows between temperature ranges return the previous row; at the very first reading a gap yields no reduction, which mirrors the table, not a bug I can show.)
+- `rpmh_address()`: `header_offset` is a uint16, so even the maximum plus 512 entries stays inside the 128 KB mapping; the bounds test there is vacuous but harmless.
+
+hakios.mic.c
+- `mic_events()`: period index from the token tested `< MIC_PERIODS` before use; `length >= 24` before `payload[0]`/`payload[4]`; DSP-reported size clamped to `MIC_PERIOD_FRAMES` before the copy and the `int16_t stereo[480]` use.
+- Mic buffer geometry: `bytes >= MIC_PERIODS * 4096` checked; each period uses the first 1920 bytes of its own page; invalidation covers exactly `MIC_PERIOD_BYTES`; no overlap with the speaker periods (separate pages).
+- `/dev/hakios-mic` read path: ring is zeroed (`Z_ZERO`), all copies are `min(want, avail, RING_FRAMES - at)` with `at = read % RING_FRAMES`, `uiomove` length cast fits int, an `avail` underflow from a racing second reader is caught by the `> RING_MOST` branch; `ring_put()` publishes `ring_written` with release ordering and the reader loads it with acquire; the ring is never freed.
+- Bring-up/undo: restore functions clear `broken` first so put-back writes happen; undo is the reverse of bring-up and is idempotent (flags per resource), so the second call from `hakios_mic_dsp_down()` is harmless; `mic_lock` and `hakios_smmu_lock` are always taken in that order.
+- All tables (SoundWire, codec, macro registers) are compile-time constants; no length or offset comes from a file or user. Polling loops bounded: SoundWire link 100 x 510 us, `codec_wait()` 200 ms, FIFO waits 20 x 500 us, `swr_read()` 4 tries.
+- Boot-args: `mic` clamped to 4, `mic_secs` to 1..600, `mic_input` masked with 0x0f; `mic_adc`, `mic_main`, `mic_test`, `mic_tap` are test switches with no size effect.
+
+userland/src/audio_plugin.c
+- Output writes are whole frames (`frames * 4`) of the stream's own format, and the non-blocking handling is consistent with the kernel (which never blocks); input read is `frames * 2` bytes into a mono 16-bit buffer, short reads zero-filled; the silent-input memset uses the stream's own channel count; volume is clamped to 0..1 before the ioctl (except NaN, S-14).
+
+## Not checked
+
+- hakios.guard.c beyond the parts the sound path calls (`block()` read for the sentinel and attenuation handling; no review of its fixed-point arithmetic, filter stability or overflow of the Q30 products).
+- Other drivers that share the SMMU lock or the I2C/TLMM pins: hakios.wifi.c, hakios.camera.c, hakios.haptic.c, hakios.torch.c; whether any of them touches GPIO 12/13 while the speaker code holds the pins (the speaker code has no lock at all against another I2C user; only the sound thread, `take_down()` and the optional `speaker_probe` thread use it).
+- hakios.adsp.c apart from `root_file()`, `hakios_adsp_apr()`, `apr_input()` (glink, firmware loading, the answer buffer's lack of synchronisation between the link thread and the waiter).
+- What a real aw882xx_acf.bin looks like (not in the repository) and whether the registers in a genuine profile are safe; Awinic register semantics, safe amplifier limits, the behaviour of the amplifier with no bit clock (NEEDS-HARDWARE in S-01, S-02, S-04, S-05).
+- SMMU/MAIR/I/O-coherency behaviour of the audio stream (S-11), SoundWire FIFO semantics (S-09, S-10).
+- XNU's `spec_close` last-close behaviour and any MAC/sandbox policy on `/dev/hakios-*` (not in the tree; affects S-08).
+- QEMU's virtio-sound device behaviour; the audio_plugin.c property/object plumbing outside I/O and volume.
+- Timing, latency and audio quality (underflow behaviour of the 160 ms DSP queue, the 5 ms virtio poll).
+- Nothing was built or executed; no sanitizer or fuzzing was run on the ACF parser.
diff --git a/docs/driver-review/storage.md b/docs/driver-review/storage.md
new file mode 100644
index 0000000..2bc3765
--- /dev/null
+++ b/docs/driver-review/storage.md
@@ -0,0 +1,290 @@
+# Storage and the write guard: review
+
+Read-only audit, no source file changed, nothing built. Evidence is file:line in the tree as it stood on 2026-10-26/27.
+
+## Scope
+
+Kernel, `xnu/files/bsd/dev/`:
+
+| file | lines |
+|---|---|
+| hakios.ufs.c | 1654 |
+| hakios.ufshc.c | 1333 |
+| hakios.ufshc.h | 32 |
+| hakios.sparse.c | 281 |
+| hakios.virtio_blk.c | 530 |
+| hakios.apfs_check.c | 1872 |
+| hakios.image.c | 187 |
+| hakios.guard.c | 315 (this is the speaker limiter, not a write guard) |
+
+Headers read: `xnu/files/bsd/sys/hakios.virtio_blk.h`, `hakios.sparse.h`, `hakios.apfs_check.h`, `hakios.audio.h` (two defines).
+
+Loader: `xnuloader/loader.c`, the block service (lines 1440-2160: `BLOCK_*`, `block_is_darwin`, `block_start`, `block_poll`, hc_take_back), the boot-arg parse (2840-2873), `write_logs` and `find_log_partition` (240-380), and the watch loop that calls them (2236-2365). The only two `write_blocks` call sites in the loader are 361 (logdump) and 2123 (darwin).
+
+APFS read path, because `hakios.image.c` and `hakios.apfs_check.c` sit on it: `xnu/files/bsd/miscfs/apfs/apfs_lib.c` lines 100-1700 (blocks, node_parse/node_entry, omap, nx_open, vol_open, seek/cursor, xfields, inode, readdir) and 2020-4062 (xattr, extents, stream_plan/fetch, decmpfs header and tables, read_cfile_attr/rsrc, read_plain). Also all of `apfs_write.c`, `apfs_store.c`, and the mount/write-relevant lines of `apfs_vfsops.c` and `apfs_vnops.c` (grep for FWRITE, MNT_RDONLY, dev.write).
+
+Method: read every function end to end on the write path (cwrite -> ufs_write -> ufs_request -> mailbox -> block_poll -> UEFI BlockIo) and on the strategy/completion path of the UFS host controller, then the other places that could reach storage (grep for `write_blocks`, `0x1d84000`, `UTRLDBR`, `VNOP_STRATEGY`, `B_WRITE`, `FWRITE`, `dev.write`). Arithmetic was checked by hand for wrap on every length and offset. The XNU source tree (`xnu-src/`) is not present on this machine, so anything that depends on XNU behaviour (spec_open, spec_strategy, PE_parse_boot_argn) is stated as an assumption.
+
+## Summary
+
+The write guard held against every route I tried (section "The write guard: routes tried"). No finding below lets a write reach anything but `darwin` from block 2042368 on, with `ufs_write=1`. The one documented exception to "only darwin" is the loader's own log write into `logdump` (F7), which is in `docs/install.md:11` and `tools/provenance.allow:28`.
+
+12 findings: 6 CONFIRMED, 5 PLAUSIBLE, 1 NEEDS-HARDWARE. None is high. Two are medium (F1, F2).
+
+## Findings
+
+| id | severity | confidence | where | one line |
+|---|---|---|---|---|
+| F1 | medium | PLAUSIBLE | loader.c:370-372, 2285-2294, 2345 | `write_logs` reads the log back into `block_buffer`, the kernel's mailbox buffer, while the kernel is running |
+| F2 | medium | CONFIRMED | ufshc.c:650-662, 572-579, 802-823 | after one slot times out, every other in-flight slot of the same read waits its own 10 s: N x 10 s |
+| F3 | low | CONFIRMED | ufs.c:452-460 | `static bounce` allocated outside the lock: leak, and one reader can copy out of the wrong buffer |
+| F4 | low | CONFIRMED | ufs.c:1307 | `crc32(0, h, header_size)` with a header size straight from disk over a 4096-byte buffer |
+| F5 | low | CONFIRMED | sparse.c:85-89, 231, 245-252 | slot not checked against `sparse_present`; header size checks wrap |
+| F6 | low | PLAUSIBLE | virtio_blk.c:241-254 | timed-out request stays on the queue; the next request can take the stale completion |
+| F7 | info | CONFIRMED | loader.c:331-361, 263-286 | the loader writes `logdump` without `ufs_write=1`, identified by name only |
+| F8 | low | PLAUSIBLE | loader.c:2869 vs ufs.c:1535 | duplicated `ufs_write=` : loader ORs all, kernel takes the first |
+| F9 | low | NEEDS-HARDWARE | ufshc.c:887-910, 1063-1066 | up to ~2 s with interrupts off when the doorbell never clears |
+| F10 | low | PLAUSIBLE | ufs.c:704, 736-747 | `ufs_bsize[]` is changed under a mounted device by the 512-and-back dance of `spec_open` |
+| F11 | low | PLAUSIBLE | ufs.c:1094, 534-555, 970-978 | `hakios_ufs_read_partition` range check wraps; `ufs_read` has no partition bound on the native path |
+| F12 | low | CONFIRMED | apfs_lib.c:1063 vs 1107 | `block_count` of the chosen superblock replaces block 0's without the device-size check |
+
+## Details
+
+### F1 - the log write-back shares the mailbox buffer with the kernel (medium, PLAUSIBLE)
+
+- `loader.c:370-372`: `rs = bio->read_blocks(..., 0, len, block_buffer); same = ... memcmp(block_buffer, out_buf, len)`.
+- `block_buffer` is also the kernel's data buffer (`loader.c:298`, handed out as `buffer_pa` at 1982).
+- `write_logs` is called from `flush_log()` at 2276 and 2293. On redwood `log_other_cpu = 1` (544), so while the kernel runs on the other core, every 2 s for the first `NOTE_SECONDS` (24 s, line 937) core 0 runs `flush_log()` before it calls `block_poll()` (2345).
+- Failure: the kernel has been answered for a read of N bytes (the answer is posted at the end of `block_poll`) and is copying out of the buffer (`ufs.c:384-385`). Core 0 enters `write_logs` and its `read_blocks` overwrites `block_buffer[0..len)` with the log. The kernel copies log bytes as file or APFS metadata and gets success: silent wrong data. The reverse order (kernel `memcpy` into the buffer for a write while `read_blocks` lands) is not caught by the loader's own read-back check, because `want = ufs_crc32(block_buffer, bytes)` at 2122 is taken after the damage; but writes normally happen at the end of a run, outside the 24 s.
+- Why only PLAUSIBLE: the window is the time between the answer and the end of the kernel's copy (microseconds to a few ms), and `write_logs` spends ms in `write_blocks` before it reads back, so the copy is usually over. Needs a trace to see it. With `ufs_native=1` the log write is skipped (`hc_list_is_uefis()` false, 353) so the window does not exist there.
+- Fix: do not use `block_buffer` for the log read-back.
+
+```
+-static uint8_t block_buffer[BLOCK_BUFFER_SIZE] ...
++static uint8_t block_buffer[BLOCK_BUFFER_SIZE] ...; /* kernel's mailbox only */
++static uint8_t log_verify[2 * 1024 * 1024 + 8192] __attribute__((aligned(0x2000)));
+ ...
+- if (len <= sizeof(block_buffer)) {
+- rs = bio->read_blocks(bio, bio->media->media_id, 0, len, block_buffer);
+- same = !EFI_ERROR(rs) && memcmp(block_buffer, out_buf, len) == 0;
++ if (len <= sizeof(log_verify)) {
++ rs = bio->read_blocks(bio, bio->media->media_id, 0, len, log_verify);
++ flush_dcache((uint64_t)(uintptr_t)log_verify, (uint64_t)(uintptr_t)log_verify + len);
++ same = !EFI_ERROR(rs) && memcmp(log_verify, out_buf, len) == 0;
+```
+
+(or simply skip the read-back when `block_enabled` and the kernel is running).
+
+### F2 - a dead controller blocks one read for N x 10 s (medium, CONFIRMED by trace)
+
+- `ufshc.c:650-662`: the sleeping wait in `hc_complete` leaves only when `hc_done & bit` is set or its own 10 s (`TIMEOUT_MS`) have passed since its own `started`. It never looks at `hc_dead`.
+- `hc_off()` (572-579) sets `hc_dead` and wakes only `&hc_free`, not the slots' waiters.
+- `ufshc_read` (802-823) completes its queue strictly in order, and each `hc_complete` call gets a fresh `started`.
+- Scenario: the device stops answering with 31 slots in flight (a read of 8 MB with the default 256 KB slot buffer). Slot 1 times out after 10 s, `hc_dead` is set, slot 2 then waits another 10 s, and so on: up to 310 s before `ufshc_read` returns ETIMEDOUT, so `ufs_read` (534-555) cannot even start its fallback through the loader (which is itself 20 s). The caller is a pager or vnode thread; the kernel heartbeat the loader watches is on other threads, but the I/O is stuck for minutes.
+- Fix: end the wait for everyone once the path is off.
+
+```
+ while ((hc_done & bit) == 0) {
+ (void)msleep(s, &hc_lock, PRIBIO, "ufshc-io", &second);
+ us = hc_us_since(started);
+- if ((hc_done & bit) == 0 && us > TIMEOUT_MS * 1000ULL) {
++ if ((hc_done & bit) == 0 && (hc_dead || us > TIMEOUT_MS * 1000ULL)) {
+```
+
+and in `hc_off()` after `hc_dead = true` take `hc_lock` and `wakeup(&hc_slots[i])` for the bits of `hc_waiting` (or loop `for i in 0..SLOTS`). The slot is not given back either way (as now).
+
+### F3 - `bounce` allocated outside the lock (low, CONFIRMED)
+
+- `ufs.c:452-460`: `static uint8_t *bounce; if (bounce == NULL) { bounce = kalloc_data(ufs_buffer_size, Z_WAITOK); ...}` runs before `lck_mtx_lock(&ufs_lock)` at 461.
+- Two threads whose first request is an unaligned or partial-block read both see NULL and both allocate. One buffer (4 MB) is leaked. Worse, the later store changes the pointer while the other thread may already be between `ufs_request(..., bounce, ...)` (485) and `memcpy(dst, bounce + skip, take)` (487): it reads from the new, never-filled buffer and returns zeros or stale data with `error == 0`.
+- Window: only the first unaligned read of the run, and only if two threads are there at once (a mount and `ufs_check`, say). `ufs_native_map` makes a read in `hakios_ufs_init` when `ufs_native=` is set, which fills `bounce` early on that path; without it nothing does.
+- Fix: allocate under the lock.
+
+```
+- if (bounce == NULL) {
+- bounce = kalloc_data(ufs_buffer_size, Z_WAITOK);
+- if (bounce == NULL) {
+- return ENOMEM;
+- }
+- }
+ lck_mtx_lock(&ufs_lock);
++ if (bounce == NULL) {
++ bounce = kalloc_data(ufs_buffer_size, Z_WAITOK);
++ if (bounce == NULL) {
++ lck_mtx_unlock(&ufs_lock);
++ return ENOMEM;
++ }
++ }
+```
+
+(or allocate it once in `hakios_ufs_init`).
+
+### F4 - GPT header size from disk used as a length (low, CONFIRMED, debug boot-arg only)
+
+- `ufs.c:1300-1307`, in `ufs_native_check` (only with `ufs_native_check=1`): `h = kalloc_data(4096)`, filled with block 1 of a unit; `got = crc32(0, h, *(uint32_t *)(h + 12));`. Offset 12 of a GPT header is `HeaderSize`, 4 bytes from the flash.
+- Failure: a header with `HeaderSize` above 4096 (corrupt flash, or a unit whose block 1 is not a GPT but starts with "EFI PART" followed by junk) makes `crc32` read up to 4 GiB past a 4 KB heap object: a data abort in a bsd_init thread, or an info leak into the log line. The loader bounds the same field (`loader.c:1267`: `header_size < 92 || header_size > sizeof(header)`).
+- Fix:
+
+```
+ want = *(uint32_t *)(h + 16);
+ *(uint32_t *)(h + 16) = 0;
+- got = crc32(0, h, *(uint32_t *)(h + 12));
++ {
++ uint32_t hs = *(uint32_t *)(h + 12);
++ got = (hs >= 92 && hs <= 4096) ? crc32(0, h, hs) : ~want;
++ }
+```
+
+Also the same function leaks `h`, `ufs_cmp_x` and `ufs_cmp_y` on its early `no memory` return (1282-1285); test code only.
+
+### F5 - sparse image: unchecked slot, wrapping header checks (low, CONFIRMED)
+
+- `sparse.c:85-89`: `memcpy(&slot, sparse_table + blk * 4, ...); if (slot == 0) return NULL; return sparse_data + (uint64_t)(slot - 1) * sparse_block_size;`. `slot` is never compared with `sparse_present`, which init validated only as a count (251).
+- Failure: a table entry above `sparse_present` (a truncated or hand-made image) makes `sparse_strategy` (134) `memcpy` from up to 4G x `sparse_block_size` beyond the image: either a data abort or other kernel memory returned to the reader of `/dev/rsp0`. This is the same data path the APFS mount takes.
+- The header checks at 231 and 251-252 can also wrap: `off + sizeof(*hdr) > size` with `off` near 2^64 (boot-arg), and `off + hdr->sh_data_off + sparse_present * sparse_block_size` and `sparse_block_count * 4` with 64-bit values from the image. `sparse_strategy` (113) multiplies `sparse_block_count * sparse_block_size` unchecked as well.
+- The image is built by `tools/apfs/mksparse.py` on the host, so this is robustness, not an attack surface; it turns a bad image into a panic instead of an error message.
+- Fix:
+
+```
+ slot = ...;
+- if (slot == 0) {
++ if (slot == 0 || slot > sparse_present) {
+ return NULL;
+ }
+```
+
+and in `hakios_sparse_init` replace the two range tests by a helper that checks each term with `x > size - y` style comparisons, plus `sparse_block_count > UINT64_MAX / sparse_block_size` and `UINT64_MAX / 4`.
+
+### F6 - virtio-blk: a timed-out request is left on the queue (low, PLAUSIBLE, QEMU only)
+
+- `virtio_blk.c:247-252`: after 10 s without an answer the function returns EIO and unlocks, but the descriptor chain and `avail->idx` stay published, `d->seen` is not advanced, and the caller is free to reuse or free `data`.
+- Failure: if QEMU answers late it DMAs into the caller's old buffer (freed or reused), and the next `blk_read` finds `used->idx != seen` at once (243) and returns before its own data has arrived, with `status` possibly set by the old request. Needs a QEMU that stalls for 10 s.
+- Fix: on timeout set `blk_ready = false` (the device is off from now on, like `ufs_dead`), or reset the device (`reg_write(d, VIRTIO_STATUS, 0)`) before returning.
+
+### F7 - the loader writes `logdump` by default, identified by name (info, CONFIRMED)
+
+- `loader.c:361`: `ws = bio->write_blocks(bio, bio->media->media_id, 0, len, out_buf);`, from `write_logs()` at the end of every run (also 560, 2276, 2293, 3296, 3341, 3351, 3427, 4125). No `ufs_write=1` is needed.
+- The partition is found by name only (`find_log_partition`, 263-286: UTF-16 compare with `logdump`); no GUID, no LBA range, no size check, no check that the name is unique. Bounds come from UEFI's partition BlockIo (a write longer than the partition fails whole).
+- This is documented (`docs/install.md:11`, `tools/provenance.allow:28`), but it is not "only darwin". If the promise is meant literally, say so in the README, or give `logdump` the same treatment as `block_is_darwin` (type and unique GUID, start and end LBA, size, `len <= bytes`).
+
+### F8 - duplicate `ufs_write=` arguments (low, PLAUSIBLE)
+
+- Loader: `loader.c:2869` uses `|=` over every occurrence of `ufs_write=1`. Kernel: `ufs.c:1535` `PE_parse_boot_argn("ufs_write", &check, ...) && check == 1`, which (as far as I know of XNU, source not here) takes the first occurrence.
+- `ufs_write=1 ... ufs_write=0`: loader enables, kernel enables: writes are on although the last word said off. `ufs_write=0 ... ufs_write=1`: loader on, kernel off: no writes (safe). Both sides need to say yes, so this can only turn writes on when a first `=1` is present; a tool that appends `ufs_write=0` to switch writes off will not.
+- Fix, loader: take only the first occurrence.
+
+```
+- block_write_requested |= starts_with(c, "ufs_write=1") && (c == pi.cmdline || c[-1] == ' ') && ...
++ if (!write_seen && starts_with(c, "ufs_write=") && (c == pi.cmdline || c[-1] == ' ')) {
++ write_seen = 1;
++ block_write_requested = starts_with(c, "ufs_write=1") && (c[11] == 0 || c[11] == ' ');
++ }
+```
+
+### F9 - interrupts off for up to ~2 s when the doorbell does not clear (low, NEEDS-HARDWARE)
+
+- `ufshc.c:1063-1066`: `lck_mtx_lock(&hc_lock); istate = ml_set_interrupts_enabled(FALSE); hc_put_back(&r);`. `hc_put_back` (887-927) spins with `yield` up to 1 s for the doorbell (893-896), up to 1 s again after UTRLCLR (899-901), and 5 ms for the run bit, all with interrupts off. `ufs_native_out` reaches it from the read-failure path (`ufs.c:552`) after the kernel's own 2 s sleeping wait (1060-1062).
+- Failure: with a device that never answers, one core spends ~2 s with interrupts masked. Whether that is acceptable (scheduler or interrupt-latency checks in this kernel configuration, GIC, the loader's heartbeat) I cannot tell from the repository.
+- Fix (only if the hang test shows trouble): spin with interrupts on until the first loop is over, mask them only for the writes of UTRLBA/UTRLRSR.
+
+### F10 - the block size under a mounted device changes briefly (low, PLAUSIBLE)
+
+- `ufs.c:746`: `DKIOCSETBLOCKSIZE` stores into the global `ufs_bsize[part]`, and `ufs_strategy` (704) computes `offset = buf_blkno(bp) * ufs_bsize[part]` with whatever it reads. The comment at 737-741 says `spec_open()` sets 512 and then back on each open.
+- Failure: while a filesystem is mounted on `/dev/ufs_darwin` (blkno counted in 4096-byte blocks), any other open of the block node (a `dd`, `mount`, a second mount) runs `spec_open`'s 512-and-back; a strategy call in between reads 8x too early and returns that data with success.
+- Only PLAUSIBLE: depends on what `spec_open` does in this XNU (not in the tree), and Apple's own `dkstrategy` has the same shape (per-minor `bdevBlockSize`). The window is two ioctls wide.
+- Fix: keep the mounted block size apart from the transient one (remember the value set by a non-512 call and ignore a 512 set that is followed by a restore), or hold a lock around both in `ufs_ioctl` and `ufs_strategy` (which does not close the window by itself).
+
+### F11 - range checks that wrap, and no partition bound in `ufs_read` (low, PLAUSIBLE)
+
+- `ufs.c:1094`: `if (offset + len > ufs_part_bytes(part)) return EINVAL;` wraps for `offset` near 2^64. Only caller today is `hakios.mpss.c:3610` with offset 0 and a size from `ufs_part_bytes`, so not reachable now.
+- `ufs_read` (534-555) does not check the range at all; its callers clamp (strategy 703-714, cread 799-807). `ufs_check` (970-978) and `ufs_bench` (1025-1029) do not: `ufs_check` reads `ufs_references[r].bytes` from any partition whose name matches, regardless of its size. Through the loader an out-of-range read is refused (`loader.c:2090-2091`, written without wrap: `count <= blocks - lba`), but the native path has no bound (`ufshc_read` knows no unit size, `ufs.c:505`), so a short partition would be hashed together with the one after it. Reads only; no write consequence.
+- Fix: a single bound check in `ufs_read` itself:
+
+```
+ static int
+ ufs_read(uint32_t part, uint64_t offset, uint8_t *dst, uint64_t len)
+ {
++ uint64_t size = ufs_part_bytes(part);
++ if (offset > size || len > size - offset) {
++ return EINVAL;
++ }
+```
+
+and the same form at 1094.
+
+### F12 - `block_count` replaced without the device-size check (low, CONFIRMED)
+
+- `apfs_lib.c:1063` checks `nx->block_count * bs > nx->dev.size` for block 0's count (the multiplication itself can wrap for `block_count >= 2^48`), then `1107` sets `nx->block_count = le64(blk + 40)` from the chosen checkpoint superblock with no check. `nx_block` (373) then trusts it.
+- Failure: a superblock that claims more blocks than the device holds lets `nx_block` ask the device for addresses past its end (the device refuses: `mem_read` in `hakios.image.c:40` returns EIO, `ufs_strategy` returns EINVAL), so a damaged volume gives I/O errors rather than a clean "container larger than device"; and a count of 0 or below 16 is accepted at that point. No memory-safety effect found; `nx_block_unlocked` (292) cannot underflow because `addr < block_count` is checked first.
+- Fix: after 1107, repeat `block_count < 16 || block_count > UINT64_MAX / bs || (dev.size != 0 && block_count * bs > dev.size)` and fail with EIO; use `block_count > dev.size / bs` instead of the multiplication at 1063.
+
+## The write guard: routes tried
+
+Each of these was traced to the line that refuses it, or to the reason there is no path.
+
+1. **Write to another partition through `/dev/rufs_NAME`**. `ufs_copen` (660-666) drops FWRITE only when `minor == ufs_write_part`; every other partition goes to `ufs_open` and is refused at 652 (EROFS). `ufs_cwrite` (830) and `ufs_write` (571) both refuse `part != ufs_write_part`. The loader refuses again at `loader.c:2103` (`part != block_write_part`).
+2. **Write through the block nodes `/dev/ufs_NAME`**. `ufs_open` refuses FWRITE (652); `ufs_strategy` refuses a buffer without B_READ (698). `DKIOCISWRITABLE` says 0. The block `bdevsw` has no `d_dump`, `eno_dump`.
+3. **mknod with a chosen minor** (root only; the devices are 0640 root:operator). Minor beyond the table or a whole-unit entry: `ufs_open` 649; `ufs_cwrite` 830 needs `part == ufs_write_part`, which init sets only to an entry with `BLOCK_PART_UNIT` clear (1550).
+4. **Overflow in the range check**. `ufs_write` 576-581 checks `offset > ufs_part_bytes` first and then `len > ufs_part_bytes - offset`: no wrap; `offset / nbs < UFS_WRITE_FIRST` is exact; `ufs_part_bytes = blocks * block_size` is `5242875 * 4096` (init pins both, 1559-1561). Loader 2090-2091 is `lba < blocks && count <= blocks - lba`, written without wrap, and `count <= BLOCK_BUFFER_SIZE / block_size`. Write branch at 2103 adds `lba >= BLOCK_WRITE_FIRST`. The two constants agree: 2042368 (ufs.c:78, loader.c:1480), and the kernel also refuses a page whose `write_first` differs (1538).
+5. **Negative or huge offsets and sizes from user space**. `ufs_cwrite` 839: negative `uio_offset` is EINVAL, then offset and resid must be multiples of 4096; the loop (846-861) moves at most `ufs_buffer_size` per round (`(int)want` cannot truncate), and `ufs_write` re-checks every chunk. `bytes = count * block_size` in `ufs_request` is at most `ufs_buffer_size` because `count <= per`.
+6. **32/64-bit truncation**. `(uint32_t)minor(dev)` and the table index are 32-bit; `ufs_write_part` is an int set from `i < parts <= 160`. LBA, count, offset are `uint64_t` end to end (ask.lba/count are 64-bit). `ufs_crc32` takes `uint64_t`. `buf_setresid` casts are on 32-bit buf counts.
+7. **Index confusion kernel/loader**. Both sides index the same `part[]` of the same page. The loader sets `block_write_part = block_shared.parts` before `block_shared.parts++` (loader.c:1927-1930), so it is the index of that entry; units are appended after the partitions (1936-1951), so no whole-unit entry can alias the writable index. The kernel accepts the offer only if `i == offered - 1` and the entry is named `darwin`, not a unit, on unit 0, LBA 25374720, 5242875 blocks of 4096 (1542-1563). The loader's own identity test (1822-1855) adds both GUIDs, end LBA, and `!read_only`.
+8. **TOCTOU between check and write**. The loader copies `part/lba/count/op` into locals once (2084-2087) before any test and uses the locals. The kernel holds `ufs_lock` for the whole request and `ufs_write_mtx` for the whole write. The page is mapped only into the kernel. The one thing that can touch the data buffer meanwhile is `write_logs` (F1).
+9. **Per-run state**. `block_write_requested` and `block_write_part` are reset at each run (2852-2853); the counters at 1973; `write_part_plus_one` is zero unless `block_is_darwin` passed in this run (1974-1977), and the page is zeroed at the start of `block_start` (1874).
+10. **Other writers in the kernel files**. `virtio_blk.c`: request type is the constant `VIRTIO_BLK_T_IN` (77, 194); open refuses FWRITE (274); strategy refuses writes (300); the cdev write is `eno_rdwrt` (408). `sparse.c`: same (66, 104, 190-191). `hakios.image.c`: only memory, no device. The APFS file system: mounts read only always (`apfs_vfsops.c:1168` sets MNT_RDONLY, 1232 refuses a write upgrade with EROFS, 1279 opens with FREAD only), opens for write refused (`apfs_vnops.c:1106`).
+11. **`apfs_check=7` and `=8`** (`hakios.apfs_check.c:1145-1330, 1360-1493`) open a node named by `apfs_dev=` with FWRITE and write blocks with `VNOP_STRATEGY` (1065). On `ufs_darwin` the open fails (652); on `rufs_darwin` the open succeeds (660) but it is a character node and a buffer sent to it never reaches `ufs_cwrite`: the char `cdevsw` has `d_strategy = eno_strat` (885), and `bdevsw[cmajor]` is by default `eno_strat` as well (assumed, XNU not here). Even if strategy did reach `ufs_strategy` it refuses at 698. Apfs_write.c adds its own refusals (`dev.write == NULL` for every mount, sealed/snapshot/system volumes, the three-deep bound at 99-103, 164-194). Cannot reach the flash by this route.
+12. **The kernel's own UFS controller driver cannot write**. Commands are only made by `hc_make_read` (READ(10)) and `hc_make_tur` (329-361). `hc_refusal` (253-311) refuses data direction host-to-device and 3 (261), non-SCSI UPIUs (268), the W flag (271), well-known LUNs (278), LUNs outside the mask (281), and every SCSI operation not on the list (285-310), and checks that the CDB length equals the UPIU length (294). `hc_place` writes into a slot only a command that passes, reads the first 32 bytes and the descriptor back and checks again before the doorbell (481-515). `hc_whitelist_selftest` (367-456) runs 33 made-up commands first. The doorbell is rung only at 533, from `hc_ring`, and nothing else in the tree touches `0x1d84000` or `UTRLDBR` (grep). LBA is 32-bit with an explicit `first + blocks > 0xffffffff` refusal (765).
+13. **The loader does not write the controller** except to take UEFI's list back (`hc_wr` at 1729-1752); `write_blocks` appears at two places only (361 logdump, 2123 darwin).
+14. **Timeout and failure do not turn into a different write**. `ufs_dead` (350) makes every later request EIO; a late answer is ignored; the loader's write is self-verified by CRC of the read-back (2120-2134). A failure of `ufs_native_out` before a write (`ufs.c:601`, return ignored) only makes the loader refuse with ACCESS_DENIED at 2095-2101, because `hc_list_is_uefis()` is false, so the ignored return is harmless.
+15. **Boot-arg**. Writes need `ufs=2` and `ufs_write=1` on the loader's command line, matching `ufs_write=1` in the kernel's, `ufs_shared_pa` from the loader, and all identity checks. The loader requires `ufs_write=1` followed by NUL or space (2869-2870) and the kernel requires value 1 exactly (1535), so `ufs_write=10` or `=1x` does not enable it on the loader side. Both sides must agree, so the stricter wins. A hand-written `ufs_shared_pa=` pointing at a forged page only fakes the kernel's half: the loader's guard (a separate copy of the check) is the one that matters and is not reachable that way. (Duplicate arguments: F8.)
+
+## Checked and found fine
+
+UFS host controller (`hakios.ufshc.c`):
+
+- Slot accounting: `hc_free` is a bitmap under `hc_lock`; `hc_take` waits only when something may free a slot (`hc_in && !hc_dead`); `hc_give` is skipped only for a slot that timed out, which is then never used again (its DMA buffer is persistent kernel memory, never freed, so a late DMA cannot land in freed memory).
+- Doorbell: rung with interrupts off, with the list checked (`UTRLBA`, `UTRLBAU`, run bit, slot free, `take_back == 0`, `hc_in`, not closed or dead) in the same critical section (527-537); `hc_write` brackets with `dsb sy`.
+- Completion: the response is read after the doorbell bit clears and a `dsb`; checks OCS, response type, tag, response code and status (671-674); a TEST UNIT READY accepts CHECK CONDITION only in the proof.
+- DMA: slot buffers from `kmem_alloc_contig` (page aligned), flushed (DC CIVAC) before the doorbell and again before the copy-out; PRD entry count bounded by `ucd_size` (1154-1157, with `PRD_MAX` 256 KB and the 4 MB buffer limit at 1145); descriptor and UCD alignments checked at probe.
+- `ufshc_read`: `q[SLOTS]` is 32 entries and the inner loop is guarded by `tail - head < SLOTS`; `take <= blocks*BLOCK - skip`; the `memcpy` out of a slot is only done when `error == 0`; no uninitialised slot data is copied out on error paths.
+- Poller thread: `hc_waiting`, `hc_done` and `hc_poller_asleep` only change under `hc_lock`; a lost wakeup is bounded by the 1 s `msleep` timeout; a timed-out waiter clears its own `hc_waiting` bit so a stale poller snapshot sets `hc_done` only for a slot that is never reused.
+- Lock order: `ufs_write_mtx` -> `ufs_lock` -> `hc_lock`; the sysctl paths take `ufs_write_mtx` or `ufs_lock` alone; no path takes them the other way round. Nothing sleeps while holding a spin lock (there are none); the interrupt-off sections call no blocking function.
+- Switch in/out: `ufshc_switch_in` refuses unless UEFI's list is the one in the controller, the doorbell is 0, the list runs and is ready, and the loader has not asked for it back (967-985); the undo path is `hc_put_back`; `ufshc_switch_out` sets `hc_in = false` first, so no new doorbell can follow.
+
+UFS mailbox (`hakios.ufs.c`) and loader service:
+
+- Request/answer protocol: the request fields are written, `dmb sy`, then `request`; the answer is read after `answered == seq` and another `dmb sy`; the loader's `answer` struct is one cache line and is cleaned only after `answered` is stored (2156-2159). `ufs_seq` starts at the page's `answered`. Request, answer and table are in different 128-byte aligned blocks (static assert at 139).
+- Timeout: 20 s with a yield-then-sleep poll; sets `ufs_dead`, returns EIO; every later call returns EIO at once (307). The mutex is held for those 20 s, so other readers wait, then get EIO.
+- Buffer bounds: `per = ufs_buffer_size / nbs`, `count <= per`, `take <= len`; `memcpy(ufs_buffer, src, bytes)` and the copy-out are bounded by `bytes <= ufs_buffer_size`. The loader guarantees `0 < block_size <= BLOCK_BUFFER_SIZE` (1883, 1906), so `per >= 1` and the chunk loops always advance.
+- `ufs_strategy` (687-721): negative `blkno` becomes a huge unsigned offset and is refused as EINVAL; `offset + len` cannot wrap after `offset < size`; the residual is computed in 32 bits from a 32-bit count.
+- `ufs_cread`: reads are chunked to the bounce size, clamped to the partition, copied out only after a successful read of exactly that many bytes (no uninitialised bytes leave).
+- `ufs_cwrite`: nothing of the driver is held while user memory is touched; a failed chunk rewinds the uio (858-859) so the byte count is not claimed.
+- Claim of the store: `kern.hakios.var_busy` is root-only (no CTLFLAG_ANYBODY), held under `ufs_write_mtx`, taken over only from a pid that `proc_find` cannot find; `var_save` handshake transitions are all validated (241-249).
+- Native map (`ufs_native_map`): `n < BLOCK_MAX_UNITS`, `unit < 8` before `1u << unit`, block size 4096 and `EFI PART` required for each unit before it is accepted; `kfree_data` pairs match allocations.
+- Boot-args in `hakios_ufs_init`: `ufs_shared_pa`, `ufs_write`, `ufs_native`, `ufs_native_check`, `ufs_native_bench`, `ufs_bench`, `ufs_check` are all read into `uint32_t` / `uint64_t`; `check` is reset before the `ufs_check` read (1640); the page is validated for magic, version, size and `parts <= 160` before use (1489-1494).
+
+`hakios.image.c` and the APFS read path it uses:
+
+- `mem_read` (40) is wrap-free (`off > length || len > length - off`).
+- `apfs_file`: in-place path checks `addr <= length / block_size && fsize <= length - addr * block_size` (115-116), no wrap; the `kept[]` table has 64 entries and the full case is tested before the copy is made (122); the `kept[i].data` store is last; `nx`/`vol` are freed on every path (`out:`); a failed `apfs_nx_open` frees `nx` in the callee and the caller NULLs it. `fsize` is limited to 256 MB before any allocation (108). `apfs_nx_close` before `nx->block_size` is read at 119 is fine: `apfs_nx_close` does not clear `block_size` (1146-1174).
+- `node_parse` / `node_entry` (522-613): the table of contents, key and value areas are each checked to lie inside the block with subtraction-form comparisons; `nkeys` is bounded by `bs / entry size`; root nodes reserve the btree_info; ghost values handled; `(uint16_t)` truncations of `key_size` and `val_size` shorten and cannot lengthen.
+- `omap_find`, `seek_to`, `fext_seek`, `apfs_cursor_next`: tree depth bounded by `APFS_MAX_LEVELS` on every descent, so a cyclic tree ends in EIO; key and value lengths are checked before every read of fixed offsets.
+- `apfs_nx_open`: block size must be a power of two within limits; descriptor area checked to lie inside the container; superblock chosen by checksum and xid.
+- `apfs_readdir`, `apfs_xattr_list`: names are bounded by `sizeof(name)` (256) before the copy and the terminator is written at `name_len - 1 <= 255`.
+- `xfields_find`: every field is checked against the record length with 32-bit arithmetic, `off` stays below `len <= 65535`.
+- Extents: `apfs_read_stream` and `stream_plan`: `end = off + len` cannot wrap because `len <= stream_size - off`; `logical >= end` ends the loop before `logical + length` is formed; `phys`/`length` are checked against `block_count`; `stream_fetch` writes only inside `[0, covered)`; run `at + len <= covered`.
+- Compressed files: the piece index is checked against `piece_count` with 64-bit arithmetic (3640), so a header `size` that truncates the 32-bit count only makes reads fail; every `memcpy` into the caller's buffer is bounded (`direct` requires `len - *out >= want`; read-ahead index bounded by `APFS_RA_PIECES`); the parallel helper (`apfs_vfsops.c:839-919`) runs every item even after an error, so the `j->error` fields the read-ahead looks at are always written; stored (0xFF) and raw pieces are clamped to `dst_len`.
+- `apfs_write.c`: `blocks_are_free_ground` has no wrap (`count > block_count - start`); `apfs_write_in_place` checks `off > ino.size || len > ino.size - off`, refuses holes, compressed files, shared extents, and reads back every block.
+- `apfs_store.c`: header, slot size and payload bounds are checked with subtraction-form comparisons; `head_unpack` bounds `bytes` by `payload_max`.
+
+`hakios.guard.c` (speaker limiter): all 64-bit intermediates stay below 2^63 (largest: the high-pass filter terms, about 2^58); `2 * attenuation` can wrap in 32 bits but only toward a smaller attenuation, i.e. a more conservative limit; `amplitude()` stops once the value is 0; `isqrt`, `headroom` and `hakios_guard_decibels` have no division by zero or out-of-range table index (index is 4 bits, table has 17 entries); frames per block are at most 1024 against `work[2048]`. No findings.
+
+## Not checked
+
+- `tools/darwin-write.py`, `tools/userdata-carve.py`, `userland/src/var_store.c` (user-space side of the store: the kernel half is covered), the RAM disk (`md`) devices.
+- XNU itself: `spec_open`, `spec_strategy`, `physio`, `PE_parse_boot_argn` and `PE_parse_boot_arg_str` (prefix and duplicate rules), `kalloc_data` limits for very large sizes, the `buf_*` layer. These are named as assumptions where they matter (F8, F10, route 11).
+- Parts of `apfs_lib.c` not on the read path of the two files: names hashing (1755-1950, only skimmed), `scratch_*`, `batch_group` arithmetic beyond the bounds already quoted, `apfs_deflate`/`zbitmap` wrappers and libzbitmap itself (the 12-line `apfs_zbitmap.c` calls it; only the caller's `n > dst_len` check was read), and the rest of `apfs_vfsops.c`/`apfs_vnops.c`.
+- Hardware facts: UFSHCI register semantics (UTRLCLR written with 0, completion notification register, PRD byte-count field width), UEFI UFSDxe behaviour on a hung device, and cache attribute mixing (the kernel maps the loader's page write-combining and the loader uses it cacheable with explicit cleans; this works by design here but I did not prove it for every field).
+- Whether the kernel configuration masks or traps long interrupt-off sections (F9).
+- Dynamic behaviour: nothing was run, no log read; F1, F3, F6 and F10 need a trace to move from PLAUSIBLE.
+- The modem and cellular files (mpss, qmi, nas, ipa) are out of scope and were not read; `hakios.mpss.c:3592-3610` was looked at only as a caller of `hakios_ufs_read_partition`.
diff --git a/docs/driver-review/wifi-bringup.md b/docs/driver-review/wifi-bringup.md
new file mode 100644
index 0000000..da6bfc8
--- /dev/null
+++ b/docs/driver-review/wifi-bringup.md
@@ -0,0 +1,212 @@
+# Wi-Fi bring-up review: hakios.wifi.c
+
+## Scope and method
+
+- File: `xnu/files/bsd/dev/hakios.wifi.c`, 4394 lines, read in full, line by line.
+- A few lines of context were read in other files to size the impact of a finding. They were not audited:
+ `xnu/files/bsd/sys/hakios.qrtr.h`, `xnu/files/bsd/dev/hakios.qmi.c` (the receive path only), `userland/build.sh` (how `fw/network` is installed), and a grep for users of `hakios_wifi_say`, `hakios_wifi_tell` and `passphrase`.
+- Modem code was not examined.
+- Method: manual tracing of every value that comes from a remote processor or the firmware (SMEM partition and item headers, SMP2P, the QMP descriptor, GLINK queue words, QRTR headers, MDT/ELF header, QMI-reported register window) to its first use as a size, offset or index. Wait loops, error paths, locks, the shutdown path, the log functions and boot-arg parsing were traced the same way.
+- Nothing was built or run. Findings carry CONFIRMED (traced end to end in the source), PLAUSIBLE, or NEEDS-HARDWARE. "Remote" below means the DSP, the AOP or the radio firmware, and the shared memory is writable by them by design.
+
+## Findings
+
+| id | severity | confidence | where | one line |
+|----|----------|------------|-------|----------|
+| W1 | HIGH | CONFIRMED | 2470-2488, 2519-2523, 2586-2599 | GLINK message length overflows uint32 to 0; the message is never consumed and `glink_pump()` loops forever with `glink_lock` held, which also wedges shutdown |
+| W2 | HIGH | CONFIRMED | 571-572, 587-589, 2312-2318, 2358-2363, 2388-2396 | SMEM item offset and size are not checked against the partition or the 2 MB mapping; the GLINK queues index the mapping with remote-chosen extents |
+| W3 | MEDIUM | CONFIRMED | 866, 1480, 1562-1566 | the AOP's mailbox `box + size <= 0x400` check wraps in uint32, so `our_box` can lie outside the mapped block |
+| W4 | LOW | CONFIRMED | 2915, 2935, 3251 | QRTR `at + header.size > length` wraps; the receiver is handed a huge length and a pointer that is not inside the packet |
+| W5 | MEDIUM | PLAUSIBLE / NEEDS-HARDWARE | 3086-3091, 3974-3977 | a DSP that says "err-fatal" is only logged; the driver is not stopped and `hakios_wifi_dsp_is_up()` still says yes |
+| W6 | LOW | PLAUSIBLE | 604-620, 657-661, 3035, 3217 | state shared by the link thread and the main thread without a lock: static `found[256]`, static `at`, `link_thread_is` |
+| W7 | LOW | CONFIRMED | 3437-3466 | step 16 maps `size` bytes at a firmware-given address with no upper bound, and does not check the map result |
+| W8 | LOW | CONFIRMED | 1894-1897, 1832-1836, 2440-2442, 399, 502, 1889 | error-path leaks (25 MB mapping, a page per start, intent buffers) and unchecked `ml_io_map*` results |
+| W9 | LOW | NEEDS-HARDWARE | 2146-2156, 1810-1856, 4149-4163 | errors between step 8 and `dsp_started = true` never ask TrustZone to shut the image down; a panic in a small window is not cleaned up |
+| W10 | LOW | PLAUSIBLE | 4104-4113 | the end-of-run stop waits at most 40 s for the start thread, then shuts the DSP down under it |
+| W11 | LOW | PLAUSIBLE | 2602-2614 | the list of received packets and the intents' DONE_REUSE have no bound; a flooding DSP can use unbounded memory while the link thread is slow |
+| W12 | LOW | NEEDS-HARDWARE | 2469-2475, 2358-2363 | no load barrier between reading the DSP's queue head and reading the payload |
+| W13 | LOW | CONFIRMED | 4016, 4048-4052, 4080 | `wifi_mac` is a boot-arg although the file's own text says boot-args are echoed and printed with a panic; the passphrase length is logged |
+
+Counts: 7 CONFIRMED (W1, W2, W3, W4, W7, W8, W13), 4 PLAUSIBLE (W5, W6, W10, W11; W5 also depends on hardware), 2 NEEDS-HARDWARE (W9, W12). Severity: 2 HIGH (W1, W2), 2 MEDIUM (W3, W5), 9 LOW.
+
+## Details
+
+### W1 GLINK length overflow: an endless loop under `glink_lock` (HIGH, CONFIRMED)
+
+`glink_pump()` (line 2470) works out the message length in a `uint32_t` from fields of the DSP's own message.
+- Line 2470: `uint32_t ... length = sizeof(message)`.
+- Line 2477: OPEN, `length += message.param2`.
+- Line 2479: INTENT, `length += 8 * message.param2`.
+- Line 2485: DATA/DATA_MORE, `length = 16 + words[0]`.
+- Line 2487: `length = (length + 7) & ~7u`.
+- Line 2488: the only check is `length > glink.theirs_size - 8`.
+
+All three sums wrap. With OPEN `param2 = 0xfffffff8`, `length = 8 + 0xfffffff8 = 0`, and `(0 + 7) & ~7 = 0`, so both of these pass:
+- `0 > theirs_size - 8` is false;
+- `waiting < 0` is false.
+
+The `GLINK_OPEN` case then runs `glink_advance(0)` (line 2522), which stores the tail it just read, and breaks. The queue has not moved, `waiting` is still at least 8, and the `while (glink.up && !glink.broken)` loop (line 2469) reads the same message again, forever. The same happens with DATA and `words[0] = 0xfffffff0`. The intent is invalid, so the message is dropped with `glink_advance(0)` at line 2594, and again nothing is consumed.
+
+A third variant is INTENT with `param2 = 0x20000000`. Then `8 * param2` is 0 and `length` is 8, but the loop at line 2546 runs 536 million times with `glink_peek` inside it, reading past the message. It runs only if `param1 == glink.their_channel`.
+
+Consequences, all traced:
+- The link thread spins at 100% CPU holding `glink_lock`. The OPEN path prints one log line per turn (line 2524), which floods the log and the loader log.
+- `glink_send()` takes `glink_lock` (line 2671), so every QRTR sender (the driver, step 14 and step 15) blocks for good.
+- Shutdown cannot finish. `dsp_shutdown()` calls `hakios_lx_stop()`, which sends through `glink_send` and blocks. Even without that, `link_stop()` waits 2 s (line 3125) and then does `lck_mtx_lock(&glink_lock)` (line 3132), which never returns. TrustZone is never asked to shut the DSP down, and the next kernel finds it running.
+
+A crashed or hostile DSP can produce this by writing one 8-byte message into its queue.
+
+Fix (sketch):
+```
+- uint32_t waiting = glink_waiting(), length = sizeof(message);
++ uint32_t waiting = glink_waiting();
++ uint64_t length = sizeof(message);
+ ...
+- length += 8 * message.param2;
++ length += 8ull * message.param2;
+ ...
+- length = 16 + words[0];
++ length = 16ull + words[0];
+ }
+- length = (length + 7) & ~7u;
+- if (length > glink.theirs_size - 8) {
++ length = (length + 7) & ~7ull;
++ if (length < sizeof(message) || length > glink.theirs_size - 8) {
+ ... glink.broken = true; return;
+ }
+```
+Also bound the INTENT loop by `length / 8 - 1` rather than `param2`, and consider a per-call iteration cap in the pump so that a DSP that never stops writing cannot hold the lock indefinitely.
+
+### W2 SMEM item extents unchecked: remote-chosen offsets and sizes index the mapping (HIGH, CONFIRMED)
+
+`smem_items()` builds `found[].offset` and `.size` from the entries in the partition. The partition is in shared memory, and the DSP makes item 480 itself when it starts (see the comment at line 2230).
+- Bottom entries (lines 571-572): `offset = partition + at + sizeof(entry) + entry.padding_header`, `size = entry.size - entry.padding_data`.
+ - Both paddings are `uint16_t` fields from memory.
+ - `padding_data > entry.size` makes `size` wrap to about 4 GB.
+ - The only bound is `entry.size > header.size` (line 566). Nothing checks that `at + 16 + padding_header + size` stays inside `header.size`, or inside `SMEM_SIZE`.
+- Top entries (lines 587-589) have the same `entry.size - entry.padding_data` wrap. Their offset is bounded (`entry.size <= at`).
+
+Consumers trust the result:
+- `glink_find()` (line 2312) accepts any `ours_size` or `theirs_size` that is a multiple of 8 and at least 1024. A wrapped `0xfffffff8` passes.
+- `glink_waiting()` (line 2349) only compares head and tail with `theirs_size`. Both words are in the DSP-writable descriptor.
+- `glink_peek()` (line 2361) reads `smem[glink.theirs + (at + i) % theirs_size]` and `glink_put()` (line 2396) writes `queue[(head + i) % ours_size]`. Neither has any bound against the 2 MB mapping.
+- A DSP that publishes item 480 with `size = 0x400, padding_data = 0x408` gets `theirs_size = 0xfffffff8`, then a head word of 0x7ffffff8 is "valid". The next `glink_peek` reads far outside the mapping, which is a kernel data abort (panic). For item 479 (`ours`), `glink_put` writes the kernel's message bytes at the same kind of unchecked offset.
+- `smem_poke()` (line 515) has no bound check at all. `step_our_item()` pokes `our_item + 0..340` (line 2059) and `dsp_listen()` and `dsp_ask_to_stop()` poke into `our_item`. `our_item_find()` (line 1603) only checks `size >= sizeof(struct smp2p)`, and for a bottom entry that wrapped, this passes with an offset that can lie past the mapping.
+
+`smem_peek()` itself is safe (it checks `offset + size > SMEM_SIZE`). The unsafe parts are `smem_word()`, `smem_poke()`, `glink_peek()` and `glink_put()`.
+
+Fix (sketch), in `smem_items()` before using `entry`:
+```
++ if ((uint32_t)entry.padding_data + entry.padding_header > entry.size ||
++ at + sizeof(entry) + entry.padding_header + entry.size > header.free_uncached) { break; }
+```
+For top entries require `entry.padding_data <= entry.size`. Then, in `smem_item()` and `glink_find()`, reject any item with `offset + size > SMEM_SIZE`. Make `smem_poke()` and `smem_word()` check `offset + 4 <= SMEM_SIZE` and return false (or ignore) otherwise.
+
+### W3 QMP mailbox bounds wrap (MEDIUM, CONFIRMED)
+
+- `step_mailbox_open_locked()` line 1480: `if (size < QMP_MESSAGE + 4 || box < 0x3c || box + size > aoss.size || (box & 3))`.
+- `step_mailbox()` line 866 has the same check.
+
+`box` and `size` are read from the AOP's message memory (`get()` at 1478-1479). Both are `uint32_t`. `box = 0x100000` and `size = 0xffff0000` sum to 0 and pass. `our_box = 0x100000` is accepted (line 1488 or 1523). `mailbox_send_locked()` then does `rd(aoss.base + our_box)` and 16 `wr(aoss.base + our_box + 4 + 4*i, ...)` (lines 1557-1564). The mapping is 0x400 bytes (line 804). This is a read and write outside the mapping, at an offset chosen by the AOP. In `step_mailbox` it is a read only. The AOP is more trusted than the DSP, but its message memory is remote input all the same.
+
+Fix:
+```
+- if (size < QMP_MESSAGE + 4 || box < 0x3c || box + size > aoss.size || (box & 3)) {
++ if (size < QMP_MESSAGE + 4 || box < 0x3c || box > aoss.size || size > aoss.size - box || (box & 3)) {
+```
+(the same in `step_mailbox`).
+
+### W4 QRTR size check wraps (LOW, CONFIRMED)
+
+Line 2915: `if (header.size == 0 || at + header.size > length)`. Both `at` and `header.size` are `uint32_t`. With a v1 header (`at = 32`) a `header.size >= 0xffffffe0` makes the sum wrap to a small value and the datagram is accepted. For a v2 header `at` is 16..271 and the same holds for `size >= 0x100000000 - at`.
+- `receive(context, ..., data + at, header.size)` (line 2948) is called with a length of about 4 GB and a pointer that may run past the packet allocation (the packet is `sizeof(*packet) + fill` bytes).
+- The QMI path is protected: `qmi_receive` at `hakios.qmi.c:686` rejects `length > largest + QMI_HEADER_SIZE`.
+- `wlfw_receive()` (line 3248) clamps to 64 bytes, so it over-reads at most 64 bytes of adjacent heap into `wlfw_answer_bytes`. Only step 14 with `wifi_ask=1` prints it (line 3520).
+- For control messages, line 2935 copies `min(header.size, 20)` bytes from `data + at` (up to 20 bytes beyond the packet).
+
+Impact is a small heap over-read from remote-chosen sizes. Fix: `if (header.size == 0 || header.size > length || at > length - header.size)`.
+
+### W5 A crashed DSP is not reported to the driver (MEDIUM, PLAUSIBLE / NEEDS-HARDWARE)
+
+`link_thread()` (lines 3086-3091) prints once when the DSP's "slave-kernel" word has bit 0 ("err-fatal") and keeps pumping. `hakios_wifi_dsp_is_up()` (line 3974) returns `dsp_started && glink.open`, with no fatal state. Nothing stops the driver, or marks the link broken, so `glink_send()` waits 5 s per call and the driver's own threads keep running.
+
+The file's own comment (lines 3332-3339) records that a phone reset without a word when the driver's thread "was then still writing ring pointers into registers that had stopped answering". After an err-fatal the radio's registers are in the same state. Whether that is the same fault could not be settled from the repository: NEEDS-HARDWARE.
+
+Fix (sketch): add a `static volatile bool dsp_dead`, set it in `link_thread` (and in `dsp_listen`) when `DSP_FATAL` is seen, make `hakios_wifi_dsp_is_up()` return false, make `glink_send()` return `ENOTCONN` at once, and ask the driver to stop (`hakios_lx_stop()` from the shutdown path is already in place).
+
+### W6 State shared across threads without a lock (LOW, PLAUSIBLE)
+
+- `smem_item()` (line 604) uses one `static struct smem_item found[256]`, filled and then searched with no lock. It is called from the link thread (`show_crash_reason()` at 3089, and `dsp_words()` while `at == 0`) and from the main thread (`our_item_find()` in `dsp_ask_to_stop()` during shutdown, `glink_reset()`). If two scans overlap, a match in one can return the offset of an entry that the other has overwritten, and `smem_poke()` then writes at the wrong place. Window: a DSP crash message at the same moment as a shutdown, which is narrow. Fix: make `found` a stack or per-caller array, or take `hakios_smem_alloc_lock` around the scan.
+- `dsp_words()` caches `at` in a function static (line 657) written by both threads (harmless today because the value is idempotent).
+- `link_thread_is` (lines 3035 and 3217) holds a `thread_t` that has been deallocated once the thread has ended. `qrtr_close()` compares `current_thread()` against it to decide whether to wait on `qrtr_calling`. If the address is reused by a new thread, that thread skips the wait and a callback that is running can use a closed port. It is set after `kernel_thread_start` returns, so the first moments are also unprotected. Fix: clear it when `link_runs` goes false.
+
+### W7 Step 16 trusts the firmware's register window (LOW, CONFIRMED)
+
+Lines 3437-3454: `address` (from `hakios_wlfw_registers`, i.e. what the Wi-Fi firmware told over QMI) is bounded only by `<= 0xffffffff`, and `size` only by `>= 3 * RADIO_WINDOW`. The step maps `ml_io_map_unmappable(radio.phys, radio.size, VM_WIMG_IO)` (line 3454), checks nothing about the result, and reads seven words at fixed offsets below `3 * RADIO_WINDOW`. A firmware that reports another physical address makes the kernel read there (a protected region ends the kernel, as the comment at 3384-3395 says). It only runs with `wifi_radio_read=1`. Fix: require `size == 0x200000` (or `<= 0x200000`), `address + size <= 0x100000000`, and a non-zero map result.
+
+### W8 Error-path leaks and unchecked map results (LOW, CONFIRMED)
+
+- `step_image()` lines 1894-1897 return false on a misaligned segment without `ml_io_unmap()` of the 25 MB mapping made at 1889. A step that fails here and is retried leaks address space. Fix: break out and fall through to the unmap.
+- `step_header()` allocates one page per start with `kmem_alloc` (line 1832) that is "never freed" (the comment says so), including on every failure path after it. One page per start attempt.
+- `glink_offer()` lines 2440-2442: when `our_intents[i].data != NULL` and `size != size`, a new buffer replaces the pointer and the old one is leaked. The size comes from the DSP's INTENT_REQUEST (line 2576), and `our_intent_count` is reset by every `step_link`. Bounded at 24 buffers of 64 KB per link restart.
+- `need()` (line 399), `smem_peek()` (line 502), `step_image()` (line 1889) and `step_registers()` (line 3454) use the result of `ml_io_map*` without a check. If the call returns 0 on failure (not verified, see Not checked), the next access is a load from a low address.
+
+### W9 Half-started TrustZone state (LOW, NEEDS-HARDWARE)
+
+- Step 8 ends with TrustZone holding the image header and the memory window (`INIT_IMAGE`, `MEM_SETUP`). If step 9, 10 or 11 then fails before `AUTH_AND_RESET` succeeds, `steps_over()` only shuts down when `dsp_started` (line 4152-4157), so `PAS_SHUTDOWN` is never called for that peripheral. The AUTH failure path (line 2150-2154) tells the AOP "off" but does not call `PAS_SHUTDOWN` either. The file's own history (lines 69-77) says a wrong TrustZone shutdown state stopped the DSP from starting again. Whether TrustZone needs the shutdown after a failed start, as Linux's remoteproc error path does, cannot be told from the sources here.
+- `dsp_started` is set only at line 2156, after the SMC returns, a `printf` inside `scm()` (which takes `say_lock` and prints to the console) and the code after it. A panic on another processor inside that window makes `hakios_wifi_quiesce()` return at line 4135 with the DSP running and not stopped. The window is a few milliseconds at most.
+
+Fix (sketch): set a `dsp_starting` flag before the SMC and let `quiesce` and `steps_over` treat it as started; call `PAS_SHUTDOWN` on every failure after step 8 succeeded.
+
+### W10 The end-of-run stop does not wait for the start thread for long enough (LOW, PLAUSIBLE)
+
+`hakios_wifi_stop()` (lines 4107-4109) waits `whole_runs` for 40 s and then goes on regardless. With `wifi=1` the thread can still be inside step 15 (the driver start, calibration alone is 7 s, and the file's own comment documents a 12 s join). Shutting the DSP down under a driver that is still starting is the "registers stop answering" case at lines 3332-3339. Fix: either wait without a bound (the thread's own steps all have bounds) or set a "stop wanted" flag that `whole_thread` checks between steps and `link_stop`/`glink_send` honour.
+
+### W11 Unbounded queue of received packets (LOW, PLAUSIBLE)
+
+In `glink_pump()` lines 2600-2616, a complete DATA message is copied into a `kalloc_data` packet and appended to `glink.first/last`, and the DSP is told DONE_REUSE at once, so it can send again at once. The consumer is the link thread, which can be held in a callback or in `glink_send()` for up to 5 s (line 2701) while the main thread's `glink_send()` also pumps and enqueues. A DSP that streams packets of up to 64 KB (`size > 0x10000` is rejected in `glink_offer`) grows the list without bound during that time. Fix: cap the list (count or bytes) and delay DONE_REUSE until the packet has been consumed.
+
+### W12 Missing load barrier on the DSP's queue (LOW, NEEDS-HARDWARE)
+
+`glink_waiting()` reads the DSP's head with `rd()` (line 2347), and `glink_peek()` then reads the payload with plain byte loads from the same mapping (line 2361). The producer side is ordered (`settle()` between payload and head in `glink_put`, lines 2399-2400), but the consumer has no `dmb ishld` or `dsb ld` between reading the head and the payload. Whether the mapping (`VM_WIMG_WCOMB`) allows the loads to be reordered is not stated in this repository: NEEDS-HARDWARE. Fix: `__asm__ volatile ("dmb ld" ::: "memory")` in `glink_waiting()` after the head read.
+
+### W13 Credentials and identifiers in the log and in boot-args (LOW, CONFIRMED)
+
+- `hakios_wifi_radio_address()` (line 4016) reads the radio's MAC from the boot-arg `wifi_mac`. The comment above `hakios_wifi_network()` (4048-4052) says boot-args "are echoed by the loader and printed with a panic", which is why the passphrase is not one; the same reasoning applies to the MAC (a device identifier). No code in this file reads `fw-wifi/mac`; if the reviewer's brief expects it, it is not here (lines 4001-4007 say the value is "nowhere in these sources"). The log prints only the length of the MAC (line 4039), which is fine.
+- `hakios_wifi_network()` prints the lengths of the name and the passphrase (line 4080) and nothing else; `join_given()` zeroes its copy after the join is asked for (4196). The passphrase itself never reaches the log from this file. `userland/build.sh:384` installs `fw/network` with mode 0600.
+- A failed join flushes the whole kept log (`say_kept()`, line 4210) into the real log and into the loader's log. That log holds what the driver and the steps said; this file's own lines contain no secrets, and the driver files were not audited for them (`lx_80211.c:24` says only lengths are said).
+
+## Checked and found fine
+
+- `smem_peek()` bound (line 504): `offset` is `uint64_t`, so `offset + size` cannot wrap; every `smem_peek` caller is safe from out-of-range reads. The unsafe parts are listed in W2.
+- `smem_partition()` (521-549): the TOC `count` is capped at 64 (3104 bytes of table, within the 4 KB), partition `offset + size` is checked against the TOC, `header.size == entry.size` is required.
+- `smem_items()` loop termination: each bottom iteration advances `at` by at least 16 and the loop ends at `free_uncached`, which is bounded by `header.size`; the top loop ends on `at <= free_cached` and on the `entry.size + step_back > at` guard (line 592), so a corrupt partition cannot make it loop. The scan cost is bounded (at most 131072 entries).
+- `smp2p_entry()` and every use of `words->valid`: capped at 16. `show_words()` uses `%.16s` and a bounded `snprintf` with a size guard. `dsp_ask_to_stop()`, `dsp_listen()` and `step_our_item()` index `entry[]` only with the capped value, and the poke offsets (at most 336 of 340 bytes) fit the item.
+- `show_crash_reason()` (710-726): `text[81]` is zeroed, the copy is `min(size, 80)`, printed with `%s` as an argument (not a format).
+- Torn reads of the 340-byte SMP2P item: `smem_peek` copies bytewise, so a snapshot can mix old and new bytes, but no state bit can appear that was not set in the old or the new value, and `memcmp` change detection is only an optimisation.
+- Every `say()`, `hakios_wifi_say()`, `hakios_wifi_tell()` and `printf` (macro for `say`) call in this file has a literal format; remote data (DSP names, crash text, SMP2P names, QRTR sizes) is only passed as `%s`, `%u` or `%.16s` arguments. Buffers are 400 bytes with `vsnprintf`, `say_kept()`'s `piece[201]` and its modulo indexing are right, the `kept[]` ring writes are under `say_lock`. The one effect left is that remote text can contain control characters or a fake log line (cosmetic).
+- `rd()`, `wr()` and `need()`: every `rd` or `wr` on a block (`ipcc`, `aoss`, `rsc`, `arb_*`, `tlmm`, `apps_smmu*`, `smem_lock`) is preceded by a `get`/`put`/`need` in the same step, and the steps run in order: `wifi_step=N` always runs 1..N, and `needed[]` for `wifi=1` includes step 2 (which maps `ipcc` and `aoss`) before any step that uses them. Offsets checked against block sizes: `RSC_TCS(7) + TCS_COMMAND(15)` fits 0x10000; `ARB_CHANNEL(511)` and `ARB_OWNER(511)` fit 0x1100 and 0x1000; the observer window for channel 511 ends at 0x10000; `GPIO_*` for pins 84-86 fit 0x3000; SMMU `SMR`/`S2CR` for 255 entries fit 0x2000.
+- `cmd_db`/RPMh readers: slave counts are capped at 512, offsets stay inside the 128 KB map for the sizes involved, `data_offset + entry->offset + length` is checked against `CMD_DB_SIZE - 0x1000`, `levels[160]` is guarded. (The command database is the boot loader's, not remote-writable at run time.)
+- MDT/ELF loading (1312-1385): the size is capped at one page, segment count is 3..16 and `52 + 32 * count <= size`; each loaded segment is checked against the reserved window in 64 bits (`paddr >= WPSS_MEMORY`, `file_size <= memory_size`, `paddr + memory_size <= window end`), so the uint32 `highest` cannot wrap; `image.segment[]` cannot overflow because `count <= MAX_SEGMENTS`; the segment file sizes are compared to the header; `52 + 32 * count + hashes == size` is required; `name[16]` fits `wpss.bNN`. `step_image()` requires 8-byte alignment of start and length, writes only inside the window, reads everything back, and `segment_word()` cannot read beyond `file_size`. Only the first few bytes of `header[0..4]` are read before the size is known to be at least 5 (the file is in the RAM disk; at most a few bytes past a tiny file).
+- SCM calls (1724-1755): all arguments are compile-time constants or validated values (`image.size`, `WPSS_MEMORY`, `kvtophys` of a page-aligned single page from `kmem_alloc(KMA_KOBJECT)`), the metadata page is cache-cleaned before the call, a preempted call is retried at most 100 times, errors are checked by every caller.
+- Wait and poll loops, with what happens at the timeout: `mailbox_wait` (1 s, link and channel taken down again on each failure), `mailbox_send_locked` (1 s, message taken back), `our_item_make_locked` (1 s, lock not owned so nothing written; the hardware lock is released on every other path), `spmi_read` (2 ms), `radio_space_on` TLB sync (100 ms, returns false before the context is switched on), `step_start` (`wifi_wait`, always bounded by `limit` or `!dsp_started`), `dsp_ask_to_stop` (`bound_ms`), `glink_send` (5000 ms), `step_link` (5 s), `link_stop` (2 s), `doorbells()` (8 iterations), the IPCC drain in `step_start` (8). The only unbounded loop reachable from remote data is W1.
+- Shutdown path (`dsp_shutdown`, `hakios_wifi_stop`, `steps_over`, `hakios_wifi_quiesce`): order is driver, wlfw, link, ask-to-stop, TrustZone shutdown, doorbell disable, AOP "off", SMMU context back (only for a DSP started by this kernel, and only after TrustZone has agreed: if the shutdown fails the SMMU is left on, which is the safe choice). The panic path takes no lock and does not rely on a thread (the `leaving` flag), and its waits are loops. A failed `PAS_SHUTDOWN` leaves `dsp_started` true.
+- Lock order: `dsp_lock` -> `hakios_aop_mailbox_lock`/`glink_lock` -> `say_lock`; `qrtr_calling` -> `qrtr_lock`/`glink_lock`; no path takes them the other way round. No spinlock is held across a sleep (there are none in this file; sleeps are `delay_for_interval` with mutexes held, which is allowed). `qrtr_close()` waits for a running callback with `qrtr_calling` unless called from the link thread.
+- Use after free: `link_thread()` reads `packet->length` while building the `kfree_data` argument, before the free; `link_stop()` frees queued packets under `glink_lock`; QRTR callbacks run under `qrtr_calling`; `our_intents[].data` buffers are never freed (so never dangling); `qrtr_out_packet()` frees after `glink_send` returns (which copies into the queue).
+- Uninitialised data: `struct smp2p` copies are fully written by `smem_peek` before use; `qrtr_control` is zeroed before the copy; `mailbox_send_locked` zero-fills its 64 bytes; `show_words`'s `line` is zeroed; `dsp_ask_to_stop()`'s `theirs.flags` printout follows a successful `dsp_words`.
+- `glink_pump()`'s other cases: the name copy is bounded (`min(param2, 32)`) and zero-terminated; DATA copies at most the intent's free space (`words[0] <= size - fill` is checked before the copy and `fill <= size` is an invariant); the intent index is checked against `our_intent_count`; `their_intents[]` insertion is bounded to 64; `glink_offer()` caps at 24 intents of at most 64 KB and rejects zero.
+- `glink_send()` and `glink_put()` sizes: the message size is bounded against the queue (`EMSGSIZE`), `glink_room()` checks the head and tail from shared memory against `ours_size` (apart from W2), the head is reduced modulo `ours_size`, and a head that is changed between the room check and the use is still reduced.
+- `qrtr_out_packet()`: length 1..8192, allocation `sizeof(header) + padded`, and `memcpy` of `length`. Tables (`qrtr_servers[64]`, `qrtr_ports[16]`, lookups[4]) are bounded; a full table drops silently. A DSP cannot make us answer HELLO more than once.
+- Boot-arg parsing: `wifi_mac` (lines 4008-4046): at most 32 characters, at most 2 digits per byte, at most 6 bytes, a multicast or all-zero address is refused, `bytes[]` is only copied when valid. `wifi_step` is clamped to `STEPS`; the other numeric args (`wifi_wait`, `wifi_listen`, `wifi_watch`, `wifi_pause`, `wifi_new`) only affect how long a step waits and use 64-bit arithmetic for the time (the one 32-bit product, `seconds * 1000` in `step_qrtr`, wraps only for a boot-arg above about 4 million seconds). `hakios_wifi_option()` returns 0 for anything unknown.
+- `hakios_wifi_network()` parsing: bounds are by `end`, an empty line gives 0, CR is trimmed only when present, lengths over the destination size are not copied, a missing second line leaves `lengths[1] = 0`, which fails the 8..63 check. The result is rejected unless the name is 1..32 and the passphrase 8..63.
+- SMMU code: `radio_space_find()` bounds `used[256]` and the context against `contexts`; `radio_enter()` indexes page tables by shifted bits, stops at `RADIO_TABLES` (32) and returns false; `radio_map()` bounds the address pool; every `put` into the SMMU is undone by `radio_space_off()` once `radio_space.on` is true.
+- DMA coherence: the header page and the radio's page tables are cleaned with `dc civac` and followed by `dsb sy`; the image is written through a write-combining map with a `dsb sy` before TrustZone starts the DSP.
+
+## Not checked
+
+- Everything outside this file: `hakios.lx.c`, `hakios.wlfw.c`, `hakios.qmi.c` (beyond the one bound read), `hakios.sta.c`, `hakios.apple80211.c`, `hakios.adsp.c` (which shares the mailbox lock and the SMEM allocation lock), `hakios_image_file()`, `loader_log_putc()` and the Wi-Fi driver under `wifi/lx/`. Whether any of them logs a key or the passphrase, takes `hakios_wifi_say` in interrupt context (it takes a mutex), or calls `qrtr_close()` from a context that deadlocks with `qrtr_calling`, is open.
+- Whether `ml_io_map`, `ml_io_map_unmappable` or `ml_io_map_wcomb` return 0 on failure or panic (W8); how `PE_parse_boot_argn` treats a non-numeric value for a 4-byte buffer (a value like `wifi_file=off` could be read as non-zero); how `thread_terminate(current_thread())` behaves on a kernel thread that is finishing itself.
+- Hardware facts: the mapping attribute behind `VM_WIMG_WCOMB` (so the alignment and ordering rules for W12 and unaligned `ldr` on item offsets), register layouts of IPCC, QMP, the PMIC arbiter, the RSC, the SMMU and TZ calling conventions, and whether a stale `STATUS_DONE` in the arbiter's observer can answer a new read early (`spmi_read`, line 1104). Timings stated in comments were not verified.
+- Whether TrustZone expects `PAS_SHUTDOWN` after a failed start (W9) and whether the DSP's SMP2P "restart" handshake in `dsp_listen()` matches Linux in every case.
+- Modem code (out of scope) and the audio loader beyond the shared-lock declarations.
+- No build, run, or runtime test was done.
diff --git a/docs/driver-review/wifi-stack.md b/docs/driver-review/wifi-stack.md
new file mode 100644
index 0000000..702e8f9
--- /dev/null
+++ b/docs/driver-review/wifi-stack.md
@@ -0,0 +1,265 @@
+# Wi-Fi stack above the bring-up: security and robustness review
+
+Read-only audit. Nothing was built, run or modified except this file.
+
+## Scope
+
+| File | Lines |
+|---|---|
+| `wifi/lx/src/lx_wpa.c` (WPA2-PSK arithmetic, 4-way and group handshake) | 523 |
+| `wifi/lx/src/lx_wpa.h` | 49 |
+| `wifi/lx/src/lx_80211.c` (frames, scan, join, 802.11 <-> Ethernet) | 2097 |
+| `wifi/lx/src/lx_base.c` (LinuxKPI stand-ins: threads, work, memory, DMA pool) | 1235 |
+| `wifi/lx/src/lx_bus.c` (bus, ring service thread, IRQ glue, driver start/stop) | 863 |
+| `wifi/lx/src/lx.h` | 20 |
+| `xnu/files/bsd/dev/hakios.lx.c` (kernel side of the driver object) | 582 |
+| `xnu/files/bsd/dev/hakios.wlfw.c` (WLFW client; also read the codec in `hakios.qmi.c` 197-575 and the rx/txn code 617-963, only as far as WLFW uses it) | 545 |
+| `xnu/files/bsd/dev/hakios.sta.c` | 371 |
+| `xnu/files/bsd/dev/hakios.apple80211.c` | 739 |
+
+Also read for evidence: `tools/wpa-test/test_wpa.c`, `xnu/files/bsd/sys/hakios.sta.h`, `hakios_wifi_network()` in `hakios.wifi.c`, the boot seed in `xnuloader/loader.c` 3050-3080, `xnu/files/osfmk/minicrypto/mc_provider.c` (PRNG part).
+
+Method: full read of every file above, tracing every length that comes from the air, firmware or userland to its use, checking `lx_wpa.c` line by line against IEEE 802.11-2020 clause 12.7 (key hierarchy, EAPOL-Key layout, supplicant rules), RFC 8018 (PBKDF2), RFC 2104 and RFC 3394. The ath11k driver sources are not in this tree (`xnu-deps/build/ath11k` is absent), so driver and firmware behaviour is inferred from comments only. The test program in `tools/wpa-test` was read but not run (no C compiler on this host).
+
+Notes on the previous review (`docs/net-review.md`): beacon parsing in `heard()` and the SSID/element copies in `apple80211.c` were not redone; I only re-confirmed in passing that `element()` and the copies are bounded.
+
+## Findings
+
+| Id | Severity | Confidence | Where | One line |
+|---|---|---|---|---|
+| W1 | Medium | CONFIRMED | lx_wpa.c:472-477, 369-384; lx_80211.c:1809-1812 | An unauthenticated message 1 re-derives and overwrites the live KCK/KEK/TK, at any time, from any spoofed sender |
+| W2 | Medium | CONFIRMED | lx_80211.c:807-813, 1795-1808 | Handshake result is last-writer-wins: one forged EAPOL frame aborts the join or hides a good message 3 |
+| W3 | High if reachable | NEEDS-HARDWARE (code gap CONFIRMED) | lx_80211.c:752-777, 817-826, 913 | 802.11-format data frames reach the IP stack without any "protected / decrypted" check (mac80211's drop-unencrypted rule is missing) |
+| W4 | Medium | CONFIRMED (absence in this layer) | lx_80211.c:16-18; lx_wpa.c:429; lx_wpa.h:31 | No packet-number (replay) check for group-addressed frames; the RSC from message 3 is stored and never used |
+| W5 | Medium | PLAUSIBLE | lx_base.c:794-834, 759 | DMA ring pool is never freed; every peer or BA session consumes it for good, and the pool is a fixed 12 MB |
+| W6 | Low-Medium | PLAUSIBLE | xnuloader/loader.c:3053-3057 -> lx_80211.c:1660 | The supplicant nonce comes from a CSPRNG whose boot seed is a function of the timer counter |
+| W7 | Low | CONFIRMED | lx_wpa.c:415-434, 480-515 | Message 3 is not checked for RSNE match, Install/Secure bits, or GTK length/index |
+| W8 | Low | CONFIRMED | lx_80211.c:1603, 1626-1628, 565-576 | A requested BSSID is ignored on the scan path, and the chosen target can be replaced by a stronger same-SSID beacon during the join |
+| W9 | Low | PLAUSIBLE | lx_80211.c:1474-1503, 850, 872, 804-806 | Teardown races: rx path can queue work or use `radio->sta`/`radio->wpa` while `station_leave()` frees or wipes them |
+| W10 | Low | CONFIRMED | lx_80211.c:1417-1428, 1380-1401 | Group rekey: a failed `set_key` is only logged and the old key is dropped anyway |
+| W11 | Low | PLAUSIBLE | lx_base.c:342-357, 278-279; lx_bus.c:410-414 | `timer_delete_sync` does not wait for a running callback; `irq_group` can loop without bound under load |
+| W12 | Info | CONFIRMED | lx_80211.c:669-672; lx_wpa.c:259-288 | The user's own AP BSSID is logged although the name is hidden; AES intermediates and failed-unwrap plaintext are not wiped |
+
+Counts: 7 CONFIRMED (W1, W2, W4, W7, W8, W10, W12), 4 PLAUSIBLE (W5, W6, W9, W11), 1 NEEDS-HARDWARE (W3). The WPA2 arithmetic itself (PBKDF2, PRF, MIC, key unwrap, replay rule, nonce check) found no defect; see the section "Checked and found fine".
+
+## Details
+
+### W1 - an unsigned message 1 overwrites the live keys (Medium, CONFIRMED)
+
+`lx_wpa.c:472-477`:
+
+```c
+if ((info & (INFO_PAIRWISE | INFO_ACK | INFO_MIC)) == (INFO_PAIRWISE | INFO_ACK)) {
+ memcpy(wpa->peer_nonce, message + AT_NONCE, 32);
+ derive(wpa);
+```
+
+`derive()` (369-384) writes `wpa->kck`, `wpa->kek`, `wpa->pairwise` and sets `have_keys`. There is no state check: the branch runs in any state, including after message 3 was accepted and after `joined`. The only filter is in `handshake_message()` (lx_80211.c:789): `radio->sta != NULL` and Ethernet source == the AP's BSSID, both of which an attacker in range can satisfy with a plaintext frame (EAPOL frames are plaintext by design; no MIC protects message 1).
+
+Failure scenarios:
+
+1. Window during join. After message 3 is accepted, `station_join()` waits (handshake loop) and then `lx_pause_ms(30)` (line 1809) before `key_set(radio, radio->wpa.pairwise, ...)` (1810). A forged message 1 arriving in that window replaces `wpa.pairwise` with a key derived from the attacker's ANonce. The firmware gets a wrong TK; the AP's frames cannot be deciphered and ours are rejected; the join reports success ("THE NETWORK IS JOINED"), the link is dead.
+2. After join. A forged message 1 replaces KCK/KEK. Every later genuine group-key message (message 1 of the group handshake) then fails the MIC (`lx_wpa_message` returns `LX_WPA_BAD`), so the group key is never updated; once the AP rotates its GTK, broadcast and multicast traffic (ARP requests for our address, IPv6 RA/NS) stops reaching us. A retransmitted genuine message 3 also fails ("nonce is not message 1's").
+3. Amplification: each forged message 1 costs one PRF (3 HMAC-SHA1) plus a transmitted 121-byte message 2, and one unconditional `printf` (lx_80211.c:800).
+
+Standard: IEEE 802.11-2020 12.7.6 treats message 1 as unauthenticated; the supplicant is expected to tolerate extra or forged message 1 frames without changing the keys in use until a message 3 passes MIC verification (the usual solution is a candidate PTK). I could not quote the exact sentence offline, so the rule is marked as my reading of 12.7.6.2-12.7.6.4.
+
+Suggested fix (candidate keys, promoted by a valid message 3):
+
+```diff
+ struct lx_wpa {
++ unsigned char cand_kck[16], cand_kek[16], cand_tk[16]; /* from the latest message 1, not yet proven */
+ unsigned char kck[16], kek[16];
+@@ derive():
+- memcpy(wpa->kck, keys, 16);
+- memcpy(wpa->kek, keys + 16, 16);
+- memcpy(wpa->pairwise, keys + 32, 16);
+- wpa->have_keys = 1;
++ memcpy(wpa->cand_kck, keys, 16); memcpy(wpa->cand_kek, keys + 16, 16); memcpy(wpa->cand_tk, keys + 32, 16);
++ wpa->have_cand = 1;
+@@ lx_wpa_message(), signed path:
++ /* message 3 (pairwise bit): verify with cand_kck; every other signed message with kck */
++ kck = (info & INFO_PAIRWISE) ? wpa->cand_kck : wpa->kck; /* mic_of takes the key as a parameter */
++ ... after MIC, nonce, replay, unwrap and GTK all pass, for a pairwise message:
++ memcpy(wpa->kck, wpa->cand_kck, 16); memcpy(wpa->kek, wpa->cand_kek, 16); memcpy(wpa->pairwise, wpa->cand_tk, 16);
++ wpa->have_keys = 1;
+```
+
+The unwrap in a pairwise message also has to use `cand_kek`. Message 2 is answered with `cand_kck` as it is now.
+
+### W2 - the handshake outcome is overwritten by whatever came last (Medium, CONFIRMED)
+
+`handshake_message()` stores every non-`NOTHING` result: lines 807-813 (`radio->handshake = said;`). `station_join()` waits with `while (radio->handshake != LX_WPA_KEYS && radio->handshake != LX_WPA_BAD && ...)` (1795-1797), then requires `radio->handshake == LX_WPA_KEYS` (1800).
+
+Two failures, both from a spoofed plaintext EAPOL frame:
+
+1. Any forged signed-looking key frame with `MIC|ACK` set and a bad MIC (or no message 1 seen yet) makes `lx_wpa_message` return `LX_WPA_BAD` (lx_wpa.c:484, 493). The loop exits at once and the join fails with `EAUTH`, which iOS shows as "wrong password" (`apple80211.c:639` maps `EAUTH` to result 21, "invalid PMK").
+2. A genuine message 3 sets `handshake = KEYS`; a forged message 1 right behind it sets `ANSWER` before the join thread has run. The loop then keeps waiting and times out after 8 s, although the handshake succeeded and message 4 was sent.
+
+Fix: make KEYS sticky, and do not end the wait on BAD (the standard says to silently discard bad frames):
+
+```diff
+- if (said != LX_WPA_NOTHING) {
++ if (said == LX_WPA_KEYS || (said != LX_WPA_NOTHING && said != LX_WPA_BAD && radio->handshake != LX_WPA_KEYS)) {
+ ...radio->handshake = said;
+@@ station_join():
+- while (radio->handshake != LX_WPA_KEYS && radio->handshake != LX_WPA_BAD && radio->answer != ANSWER_GONE && ...
++ while (radio->handshake != LX_WPA_KEYS && radio->answer != ANSWER_GONE && ...
+```
+
+Keep a separate `radio->handshake_bad` counter and `handshake_why` for the log line.
+
+### W3 - no "was it protected" check on the 802.11 data path (NEEDS-HARDWARE; code gap CONFIRMED)
+
+`linuxkpi_ieee80211_rx()` (lx_80211.c:913) sends any 802.11 data frame through `to_ethernet()` and `ethernet_received()`. `to_ethernet()` reads the Protected bit (0x4000) only to size the header (line 767); it never requires it. `ethernet_received()` (817-826) hands every non-EAPOL frame to `lx_os_net_input()` when `radio->joined`. `RX_FLAG_DECRYPTED` is not looked at anywhere in the tree (grep), and the module header lists the missing group-frame PN check (see W4) but not this.
+
+Under Linux, mac80211 supplies the rule (drop unencrypted data frames once a key is installed, except EAPOL). This layer replaces mac80211, so the rule has to be here. Failure scenario if the firmware passes a frame up in 802.11 form without having deciphered it: an attacker in range sends a From-DS data frame (TA = BSSID, RA = our MAC, Protected = 0, LLC/SNAP + ARP or IP) after the join; it is accepted and enters the IP stack (ARP poisoning, forged DNS or TCP). The RX_FLAG_8023 path (firmware decapsulates and deciphers) is not affected. Whether the ath11k firmware drops such frames itself I cannot tell from this tree; hence NEEDS-HARDWARE. A test: with a second radio, inject the frame after the join and watch `received` in the `lx_station_say()` line.
+
+Suggested fix:
+
+```diff
+-static bool to_ethernet(struct sk_buff *skb, bool cipher_header_gone)
++static bool to_ethernet(struct sk_buff *skb, bool cipher_header_gone, bool *protected)
+ ...
++ *protected = (control & 0x4000) != 0;
+@@ linuxkpi_ieee80211_rx():
+- } else if (to_ethernet(skb, (status->flag & RX_FLAG_IV_STRIPPED) != 0)) {
+- ethernet_received(radio, skb);
++ } else if (to_ethernet(skb, (status->flag & RX_FLAG_IV_STRIPPED) != 0, &prot)) {
++ ethernet_received(radio, skb, prot && (status->flag & (RX_FLAG_DECRYPTED | RX_FLAG_IV_STRIPPED)));
+@@ ethernet_received(radio, skb, bool ciphered):
+- } else if (radio->joined && skb->len >= 14) {
++ } else if (radio->joined && (ciphered || hardware_decap) && skb->len >= 14) {
+```
+
+(`hardware_decap` is true on the RX_FLAG_8023 call.)
+
+### W4 - no replay check for group-addressed frames (Medium, CONFIRMED absence)
+
+The module header (lx_80211.c:16-18) says "the check of the packet numbers of the group's frames that the driver leaves to this layer" is not done. `lx_wpa.c:429` stores the RSC from message 3 / group messages into `wpa->group_counter`; nothing reads it (grep: only lx_wpa.c:429 and lx_wpa.h:31). Unicast PN checking is in the firmware; for broadcast and multicast, ath11k's own comment says mac80211 does it.
+
+Failure: an attacker records a genuine broadcast or multicast frame (ARP request, DHCP, mDNS, IPv6 router advertisement) and replays it later; it is accepted. A replayed RA with a short lifetime or an old prefix, or a replayed ARP, is enough to disturb the host. Standard: IEEE 802.11-2020 12.5.3.4.4 (CCMP decapsulation: discard an MPDU whose PN is not greater than the replay counter of the key/TID); the initial counter comes from the RSC in the key message (12.7.6.4). The clause number is from memory, hence the rule is PLAUSIBLE; the absence of any check is CONFIRMED. Whether the firmware performs a group PN check on its own is NEEDS-HARDWARE.
+
+Fix: in the RX_FLAG_8023 path the PN is not visible, so either enable the firmware's group replay detection (driver option) or have the driver pass `status->extiv` for group frames and compare it with a per-key counter seeded from `wpa.group_counter` (reset on every group-key install):
+
+```diff
++ if (is_multicast_ether_addr(da) && !pn_greater(status->extiv, radio->group_pn)) drop();
++ memcpy(radio->group_pn, status->extiv, 6) ... (little-endian PN, 6 bytes)
+```
+
+### W5 - the ring pool is never given back (Medium, PLAUSIBLE)
+
+`linux_dma_alloc_coherent()` (lx_base.c:794-812) advances `pool.rings_used`; `kmem_free()` (814-818) and `dma_free_noncoherent()` (831-834) are empty. The pool is `POOL_RINGS` = 12 MB, of which the author notes the data path uses "about 6 MB" (759). The comment at 820-824 states that the data path takes a few KB per traffic class of every station and that "here they stay taken". `station_join()` creates a new station each attempt (lx_80211.c:1702-1708; a failed attempt included), `ba_handle()` restarts an RX BA session on every ADDBA from the AP.
+
+Failure: each (re)join, each failed join, and each ADDBA (with `wifi_ba=1`) permanently consumes pool space. A phone that re-joins often (spoofed deauth frames are accepted because PMF is not implemented, so an attacker can force a re-join as often as wifid retries) eventually reaches "no room for N more bytes of rings" (line 804): the driver cannot create peers and Wi-Fi stays down until reboot. The leak is certain from the code; the per-join size (about 17 TIDs x 1 KB if ath11k sets up every TID) and thus the number of joins to exhaustion (a few hundred) is my estimate, and which ath11k allocations go through these two functions I cannot see.
+
+Fix: replace the bump allocator with a free list of 64-byte-aligned extents (or a bitmap of 4 KB pages) and implement `kmem_free()` / `dma_free_noncoherent()`; also rate-limit RX_START per TID in `ba_handle()`.
+
+### W6 - the supplicant nonce depends on a weak boot seed (Low-Medium, PLAUSIBLE)
+
+Source of the SNonce: `get_random_bytes(radio->wpa.own_nonce, 32)` (lx_80211.c:1660) -> `arc4random_buf()` (lx_base.c:1206) -> `read_random()` (hakios.lx.c:205) -> the minicrypto HMAC-DRBG (`mc_provider.c`, seeded from the device-tree `random-seed`). That seed is built in the loader (`xnuloader/loader.c:3053-3057`):
+
+```c
+seed[i] = (uint8_t)(READ_SYSREG(CNTVCT_EL0) >> (i & 7)) ^ (uint8_t)(i * 37);
+```
+
+All 64 bytes are a function of a few consecutive reads of the virtual counter, so the entropy is that of the counter value at that moment, roughly 25-30 bits if the boot time is known to a few seconds (19.2 MHz counter assumed). Unless the kernel's entropy collector reseeds the DRBG with real entropy before the first join (`mc_prng_refresh`, not verifiable from here), the nonce, and everything else the kernel draws from `read_random`, is predictable by enumeration.
+
+Impact on WPA2 itself is limited: the SNonce is sent in the clear in message 2, and the standard needs it to be unique, not secret (IEEE 802.11-2020 12.7.5: nonces to be random with negligible chance of repeating; the section number is from memory). A repeated SNonce combined with a repeated ANonce would repeat the PTK; the AP's ANonce is random. The finding is therefore mainly about the shared kernel PRNG; it is listed here because the task asked where the nonce comes from.
+
+Fix: seed from several independent sources (CNTVCT jitter over many samples, the SoC's TRNG/PRNG registers, the DT `rng-seed` from the previous boot, UFS/timing jitter) and block the first `read_random` consumer until a reseed has happened.
+
+### W7 - message 3 is not fully validated (Low, CONFIRMED)
+
+`lx_wpa.c:480-515` accepts a message 3 on MIC, replay counter, ANonce match, Encrypted bit and a parseable GTK KDE. Not checked: (a) the RSNE in the key data against the RSNE the AP announced (the standard asks for this and for a deauthentication with reason 17 on mismatch; IEEE 802.11-2020 12.7.6.4, clause number PLAUSIBLE), so there is no downgrade protection for anybody holding the PSK; (b) Install and Secure bits; (c) GTK KDE: `e[1] - 6` may be anything from 5 to 32 (line 425-427) and the key id `e[6] & 3` may be 0, while `key_set()` always copies 16 bytes (lx_80211.c:1396) and installs with that index. `protection()` only accepts CCMP, so the right length is 16 and the right index 1-3.
+
+Failure: an AP (or a PSK holder) can make the station install a GTK that is shorter than 16 bytes (the rest is stale `wpa->group` content, zero at join) or with index 0; this breaks group traffic rather than leaking anything.
+
+Fix:
+
+```diff
+- e[1] - 6u <= sizeof(wpa->group)) {
++ e[1] - 6u == 16 && (e[6] & 3) != 0) {
+```
+
+and in `lx_wpa_message()` for a pairwise message: `if (!(info & INFO_INSTALL) || !(info & INFO_SECURE)) -> BAD`, plus compare the RSNE found in `data` with the RSNE of the beacon (pass the target's element 48 to `lx_wpa_message`).
+
+### W8 - requested BSSID ignored on the scan path; target replaced during join (Low, CONFIRMED)
+
+`station_join()` honours `what->bssid` only when choosing from the already-heard list (lx_80211.c:1612-1613). If nothing matches, `station_scan()` is called up to three times (1626-1628) and `heard()` (565-576) fills `radio->target` with the strongest beacon of that name, with no BSSID filter. So an ASSOCIATE for a given access point (Apple80211 `bssid`, copied at apple80211.c:540) joins a different one.
+
+`heard()` keeps overwriting `radio->target` as long as `radio->sta == NULL` (567), i.e. through the whole of the join up to line 1702, including the PMK derivation (1651-1665) and the channel set-up. A stronger beacon with the same SSID replaces address, capability and elements; `vif->bss_conf.bssid` is a pointer to `radio->target.address` (1668), so it changes under the driver. Also `bzero(target, ...)` at 1603 is done without `lx_os_lock()` while `heard()` writes it under the lock.
+
+Fix: store `what->bssid` in `radio->want_bssid` and have `heard()` test it; stop `heard()` from updating `target` once `joining` is set (do the selection once, under the lock); copy the address into `vif->cfg.ap_addr`-backed storage instead of pointing at `target`.
+
+### W9 - teardown races (Low, PLAUSIBLE)
+
+`station_leave()` cancels `group_work` and `ba_work` (1474-1475) and later frees `radio->sta_memory` (1502) and wipes `radio->wpa` (1480), but rx runs on another thread. In between, `management_received()` still passes its guards (`radio->sta != NULL`, `radio->reached >= ASSOC`, line 850; `reached` is reset only at 1504) and calls `queue_work(radio->work, &radio->ba_work)` (872); `ba_handle()` captures `params.sta = radio->sta` (1107) before testing it (1122) and calls `ampdu_action` on a station that the driver has already removed or that is freed. Likewise `handshake_message()` can call `ethernet_send()` (798) which passes `radio->sta` to the driver while it is freed, and queue `group_work` after `joined` was cleared by someone else, in which case `group_rekey()` (1425) installs `radio->wpa.group` after it was zeroed (an all-zero GTK). The window is the duration of the `station_state` steps (tens of ms); `wifi_ba=1` is needed for the first case.
+
+Fix: take `lx_os_lock()` around `radio->sta`/`reached` tests in the rx path and set a `radio->leaving` flag first in `station_leave()`; cancel the works after the flag is set; make `ba_handle()` read `radio->sta` once under the lock.
+
+### W10 - a failed group-key install is only logged (Low, CONFIRMED)
+
+`group_rekey()` (1417-1428): `radio->group_key = key_set(..., &error)`, then `key_drop(radio, &old, false)` whatever `error` is. `key_set()` returns the config even when `set_key` failed, or NULL on ENOMEM. After a failure the old key is removed from the firmware and the new one is not installed: group traffic is lost, `rekeys` is still incremented, only a `lx_tell` line says so. Also the replay counter was already advanced for this message, so the AP's retransmission is rejected.
+
+Fix: drop the old key only if `error == 0`; on failure free the new config, keep the old key, and return the failure to the handshake so that the group message 2 is not sent (the AP will retransmit).
+
+### W11 - timers and the IRQ thread (Low, PLAUSIBLE)
+
+- `timer_delete_sync()` (lx_base.c:343-357) returns without waiting for a callback that the ticker thread is running (`due->function_415(due)` is called after unlocking, lines 278-279); the comment at 342 says so. If the driver frees the structure that contains the timer right after, the callback runs on freed memory. Fix: record `running` under the lock and wait for it in `timer_delete_sync()`.
+- `irq_group()` (lx_bus.c:410-414) loops `do { ... } while (done >= DATA_BUDGET)` while holding `bus.service`, on the one thread that serves every vector. Sustained receive load keeps copy-engine interrupts (WMI, handshake) and the ring thread waiting. Fix: bound the loop (for example 4 rounds) and re-arm the vector so the thread yields.
+
+### W12 - minor (Info, CONFIRMED)
+
+- `say_heard()` (lx_80211.c:669-672) hides the name of "the network that is wanted" but prints its BSSID, channel and signal; the file header (24) and the code comment at 666 promise only that the name and passphrase are not said. A BSSID is a location identifier.
+- Not wiped: `t[16]` in `aes_decrypt()` (lx_wpa.c:260-286, holds the last decrypted block, that is part of the GTK) and `a[8]` in `aes_unwrap()`; in `lx_wpa_message()` the `data[]` buffer is wiped on success and on "no group key" but not when `aes_unwrap()` fails (line 503-505). Kernel stack residue only.
+
+## Checked and found fine
+
+Cryptography in `lx_wpa.c`:
+
+- PBKDF2-HMAC-SHA1 (RFC 8018 5.2 with SHA-1, 4096 iterations, 32-byte output = block 1 whole plus 12 bytes of block 2): salt is SSID || INT(block) with a big-endian 32-bit block number (149-154), `U_1 = HMAC(P, S || INT(i))`, `U_j = HMAC(P, U_{j-1})`, XOR-accumulated, 4095 further rounds (156-164). HMAC handles keys over 64 bytes by hashing. Matches the structure used by IEEE 802.11-2020 Annex J.4. `tools/wpa-test` checks the J.4.2 vectors and RFC 2202 (read, not run).
+- PRF (171-185): label || 0x00 || data || counter byte, counter from 0, 20 bytes per round, 48 bytes for CCMP (KCK 16, KEK 16, TK 16); matches 12.7.1.2 / 12.7.1.3. PTK data (369-378): min(AA,SPA) || max(AA,SPA) || min(ANonce,SNonce) || max(...), 76 bytes with exact offsets. Roles: `own` is `vif->addr`, `peer` is the BSSID (lx_80211.c:1658-1659); correct for infrastructure (AA = BSSID).
+- EAPOL-Key layout (`AT_*` offsets): 4+1+2+2+8+32+16+8+8 = 81 for the MIC, 97 for the data length, 99 for the data; matches figure 12-35.
+- MIC (355-365): HMAC-SHA1 over the EAPOL frame from the version byte through the end of the declared body, with the 16 MIC bytes replaced by zeros, truncated to 16 bytes, key = 16-byte KCK; this is the rule for key descriptor version 2 (HMAC-SHA1-128). Computed over `4 + body` (the declared length), not the received length. Comparison is constant time (488-490). Descriptor version is required to be 2 (462) and descriptor type 2 (458).
+- AES key unwrap (RFC 3394 2.2.2): six rounds j = 5..0, i = n..1, `t = n*j + i` XORed big-endian into A (307-320), integrity value A6A6A6A6A6A6A6A6 checked over all 8 bytes with an OR accumulator (321-323, 326); length must be a multiple of 8 and at least 24 (301); output buffer `data[640]` vs plaintext at most 4+body-99-8 <= 533. The `n = length/8 - 1` before the length test wraps for length 0 but is not used before the test. The `ENCRYPTED` bit is required (503). Test vectors in `tools/wpa-test` cover RFC 3394 4.1, a spoiled input and a wrong length.
+- Key data length from the air: `4 + body` is bounded by the received length and by 640 (451); `AT_DATA + data_length > length` is rejected (466); reads of fixed offsets up to 98 only after `length >= 99`. Truncated or short frames return NOTHING or BAD without reading past the buffer (also covered by the test "a key message cut short").
+- Replay counter: 8-byte big-endian comparison, strictly greater (495); updated only after MIC, nonce, unwrap and GTK parse all passed (513). Message 3 must carry message 1's ANonce (499). A retransmitted message 3 (higher counter) is answered again and does not reinstall keys: `handshake_message()` only queues work for `LX_WPA_GROUP`, and `station_join()` installs the PTK once, so there is no key-reinstallation (KRACK) exposure through message 3 retransmission. A replayed message 3 or group message 1 is rejected.
+- GTK KDE walk (415-434): both `at + 2 <= length` and `at + 2 + len <= length`; `memcpy` size at most 32 into `group[32]`; the copy ends at the element end. Group message 1 requires MIC and ACK, the same MIC and replay path.
+- Reply buffer: `handshake_message()` gives 14+256 bytes; replies are 99+22 = 121 (rsn_length is the constant 22, lx_80211.c:1662) or 99.
+- Nonce source: see W6 (CSPRNG, fresh per join; one per join, reused for message 1 retransmissions, which is allowed).
+- Wiping: PBKDF2 temporaries (166-167), HMAC pad and inner (137-138), PRF digest (184), derived `keys[48]` (382), unwrap round keys and block (324-325), `data[]` on success; `explicit_bzero(&radio->wpa)` at leave (lx_80211.c:1480); `key_drop()` wipes the key config; `what` zeroed after the join (1858); `apple80211.c:560-565` uses `memset_s`; `hakios.sta.c` zeroes the queued join request after copying it. `explicit_bzero` in `lx_base.c:1187` is a separate-TU `bzero` and is not elided.
+- Logs: no printf or `lx_tell` in `lx_80211.c`, `lx_wpa.c`, `apple80211.c` or `hakios.sta.c` prints a passphrase, PMK, PTK, GTK or nonce; the join prints lengths only; `apple80211.c` logs types, lengths and kinds only. The Apple80211 `set_join` validates passphrase length 8..63 and PMK length 32 (543-549); `hakios_wifi_network()` validates 1..32 and 8..63 (4087-4090). `station_join()` itself does not re-check `passphrase_length <= 64` (it is a `uint8_t`; `lx_wpa_pmk` would over-read the `what` struct for larger values), but every in-tree caller validates.
+
+Frame paths in `lx_80211.c`:
+
+- Management: every fixed-offset read is behind a length test (`length < 26`, `>= 30` for authentication and association response, `>= 28`/`>= 33` for the ADDBA/DELBA action frames); `answer_length` is clamped to `ELEMENTS_MOST` (847); `aid` masked to 14 bits; deauthentication/disassociation handling reads only f[24..25]. The `tid` index is masked to 0..7. The sender (TA) and receiver (RA) addresses are compared against the AP and our own address.
+- `to_ethernet()`: header size at most 24+6+2+4+8 = 44, `skb->len >= header + 8` checked before the LLC test, `skb_pull(header + 8 - 14)` is at least 18 and at most `len`; address and ethertype are copied out before the pull. (Minor: `f[0]`, `f[1]` are read before the first `skb->len` test; two bytes inside the same buffer, not exploitable.)
+- A-MSDU and fragments: the A-MSDU bit is never interpreted, so flipping it (FragAttacks CVE-2020-24588) has no effect; there is no fragment reassembly, so the mixed-key and fragment-cache attacks do not apply here; fragments are not reassembled (a first fragment would be passed as a frame, but only decrypted data reaches this path, see W3 for the caveat).
+- Association response parsing: `element()` walkers are bounded; WMM parse requires `e[1] >= 24` and reads at most `e+25`; HT (>= 26), VHT (>= 12), HT operation (>= 22) and TIM (>= 2) lengths are tested before use. A concurrent overwrite of `answer_elements` by a forged association response can change content under `station_abilities()`, but all reads stay in the 1024-byte array or at worst the next field of the same struct.
+- `request_elements()` output is at most about 131 bytes into a 300-byte buffer.
+- Rx serialization: when `wifi_irq=1`, copy-engine and data-path service run under `bus.service` (lx_bus.c:318, 397, 410), otherwise only the ring thread runs them; so `lx_wpa_message()` and `management_received()` are never run concurrently with themselves.
+- Scan: `station_scan()` request is sized from the channel counts; channel list bounded by `frequency_count <= 64` (set in `apple80211.c:484`); SSID copy bounded (32).
+
+`lx_base.c`, `lx_bus.c`, `hakios.lx.c`:
+
+- DMA: `lkpi_dma_map_phys()` refuses anything outside the pool; `pmap_kextract` answers only for pool memory; ring allocations are rounded, overflow-safe (`size_t` arithmetic) and zeroed; skb data slots are bounds-checked against `POOL_SLOT` before allocation (879). The pool is one physically contiguous allocation behind the SMMU window; nothing is sized from a hardware register except the register window offsets in `window()`/`refused()`, which are range-checked against the three windows.
+- Thread/IRQ model: the hard handler only masks the vector, ORs the pending bit and wakes; handlers run on one thread; `lx_os_irq_disable()` and `detach_all` wait for a running handler; there is no lost wakeup (`assert_wait` before the `xchg`). Sleeping lock words panic on self-recursion by design. `idr_*` and `rhashtable_*` are under the layer's lock. The transmit queue (`lx_queue`) keeps its slot reserved until `lx_queue_out++`; full-queue test is `in - out == LX_QUEUE`.
+- `hakios.sta.c`: one worker thread, one lock; `hakios_sta_attach(NULL)` waits for calls and readers; request structs are copied under the lock and zeroed after use. `standing` (the passphrase of the file network) is kept for the life of the system by design (to re-join when the radio is switched on).
+- `apple80211.c`: `give()` clamps `copyout` to the caller's `req_len`; `give_network()` clamps elements to the room the caller declared and to 1024; scan request lengths are checked against `sizeof`.
+
+QMI codec as used by `hakios.wlfw.c` (WLFW service only):
+
+- `decode_counted()` rejects a count above `elem_len` before storing it (499); arrays (numbers or structures, nested) therefore stay inside the C structure; static arrays use `elem_len`; strings need `length < elem_len` and are NUL-terminated (476-480), so the `%s` prints of `fw_build_id` and `fw_build_timestamp` (wlfw.c:449-454) are safe; each TLV's length is checked against the message and the message against the datagram (`qmi_receive`, 686-693); unknown TLVs are skipped; a TLV that does not describe a known element is ignored; the destination of a reply is decoded under the lock and the transaction is removed under the lock on timeout, so a late reply cannot write into a dead stack frame. Every `ask()` caller zeroes its reply structure first, and `send_file()` bounds the file (256 KiB) and each piece (`QMI_WLANFW_MAX_DATA_SIZE_V01`). A reply without the result TLV reads as "success" (the zeroed `result` is 0), as it does in Linux's qmi helpers.
+
+Concurrency and lock order: no cycle found among `lx_lock`, `bus.service`, `wiphy->mtx`, `sta_lock`, `apple80211_lock`; `station_leave()` cancels work items without holding `wiphy->mtx`, so `ba_handle()`/`group_rekey()` cannot deadlock against it; the deauth path in the rx thread calls the station events after dropping `lx_os_lock`.
+
+## Not checked
+
+- The ath11k driver itself and the firmware (not in the tree): whether it drops unprotected data frames (W3), checks multicast PN (W4), and how much of its DMA goes through `dma_alloc_coherent`/`dma_alloc_noncoherent` (W5, its rate).
+- `tools/wpa-test` was not run (no compiler available on the Windows host), and `reference.py` was not read line by line; the AES, PBKDF2 and unwrap checks above are by reading the code against the standards' vectors that the test cites.
+- `hakios.wifi.c` (bring-up, firmware loading, DSP), `hakios.net.c` (what `hakios_net_input` does with a frame), the QRTR transport under `hakios.qmi.c`, and the generated `hakios.wlfw_ath11k.h` tables.
+- The minicrypto DRBG internals and whether the kernel entropy collector reseeds it before the first join (W6).
+- Side channels: the AES code is table-driven and `times()` has a data-dependent ternary; it runs only for the key unwrap, so only a local cache-timing attacker would matter.
+- 40/80 MHz width selection and rate/HT/VHT handling were read for bounds only, not for correctness against the standard; power save, roaming, regulatory domain logic and the `wifi_lx=1` register-trace path were skimmed.
+- Behaviour on hardware (everything marked PLAUSIBLE or NEEDS-HARDWARE).