Skip to content

Latest commit

 

History

History
1113 lines (1009 loc) · 217 KB

re-log.md

File metadata and controls

1113 lines (1009 loc) · 217 KB

Reverse-engineering log

Every analysis step, with the command and what it showed, so anyone can re-run it against their own IPSW. Newest entries go at the end.

Inputs: iPod2,1_4.2.1_8C148_Restore.ipsw (363,553,480 bytes, sha1 b9efddc7bb4350c237a8d3846af61bbfc8a2f647, same as the ipsw.me listing for Apple's secure-appldnld.apple.com/iPhone4/061-9855.20101122.Lrft6/... URL). Keys: https://api.ipsw.me/v4/keys/ipsw/iPod2,1/8C148. The Apple Wiki puts a CAPTCHA in front of automated clients, so the tooling doesn't scrape it.

2026-11-16: M0

1. IPSW contents

python3 -c "import zipfile; ..." lists:

  • kernelcache.release.n72 (IMG3, 4.37 MB)
  • Firmware/all_flash/all_flash.n72ap.production/DeviceTree.n72ap.img3
  • root filesystem 038-0014-002.dmg (311 MiB)
  • restore ramdisk 038-0049-002.dmg and update ramdisk 038-0050-002.dmg
  • iBoot, LLB, iBEC and iBSS, plus the boot logos

2. IMG3 decryption gotcha

The kernelcache IMG3 has the tags TYPE, DATA, SEPO, KBAG, SHSH and CERT. Decrypting only dataLength & ~15 bytes of DATA (as some docs describe) leaves a 15-byte encrypted tail, and LZSS then comes up 64 bytes short with an adler32 mismatch. The ciphertext is padded to 16 bytes inside the tag's slack space. Decrypting roundup(dataLength, 16) bytes and truncating fixes it, and the adler32 then matches (1c4f9e86). Fixed in scripts/fwlib/img3.py.

3. Kernel identity and layout (make kscan)

  • Darwin Kernel Version 10.4.0: Wed Oct 20 20:06:26 PDT 2010; root:xnu-1504.58.28~3/RELEASE_ARM_S5L8720X
  • Mach-O: cputype 12 (ARM), cpusubtype 6 (CPU_SUBTYPE_ARM_V6), MH_EXECUTE.
  • __TEXT vmaddr 0x80001000; entry (LC_UNIXTHREAD pc) 0x80067050. The kernel lives at 0x80000000 and up, not 0xC0000000.
  • Segments: __TEXT, __DATA, __KLD, __LAST, __PRELINK_TEXT (0x802cf000, 5 MB of kexts), __PRELINK_INFO (XML), __CTF, __LINKEDIT.
  • LC_SYMTAB holds 4391 symbols. These are the exported KPI that kexts link against, e.g. _ml_io_map, _PE_cpu_start, _ml_processor_register, _IOFlushProcessorCache, _kprintf, _panic, _PE_parse_boot_argn, _PE_i_can_has_debugger. Internal symbols such as _arm_init and _PE_init_platform are stripped.
  • 99 distinct prelinked kext bundle IDs (see build/staging/kernelcache.txt).
  • Panic strings include source paths. The ARM-specific files are osfmk/arm/{cpu,locks_arm,loose_ends,machine_routines,pcb,pmap,rtclock,status,trap}.c, osfmk/console/arm/serial_console.c, osfmk/console/video_console.c, bsd/dev/arm/{systemcalls,unix_signal}.c and osfmk/kdp/ml/arm/kdp_machdep.c.

4. Entry stub disassembly (0x80067050)

I wrapped __TEXT in an ELF and disassembled it: llvm-objcopy -I binary -O elf32-littlearm then llvm-objdump -D --triple=armv6k-none-eabi --adjust-vma=0x80001000. The stub runs in ARM mode with the MMU off:

mov r1,#0 ; ldr lr,=<virt continuation> ; cpsid if
ldr r8,[r0,#8]    ; boot_args->physBase
ldr r9,[r0,#4]    ; boot_args->virtBase
ldr r10,[r0,#0xc] ; boot_args->memSize
ldr r4,[r0,#0x10] ; boot_args->topOfKernelData  -> L1 table goes HERE
TTBR0 = TTBR1 = r4 | 0x18 ; TTBCR = 2
zero 9*1024 words at r4 (16 KB L1 + 20 KB of L2 tables)
identity-map the 1 MB section containing PC (V=P, so the MMU-on switch survives)
map [virtBase, virtBase+memSize) -> physBase as SUPERSECTIONS (bit18), C+B, AP=01
L2 page table at r4+0x8000 for 0xFFF00000; maps the vector page at 0xFFFF0000
clean+invalidate D-cache by set/way: 128 sets x 4 ways x 32 B  (16 KB geometry hard-coded)
SCTLR |= M|C|W|Z|I|V|U|XP (0x00C0380D), high vectors, ARMv6 extended page tables
r0 = r0 - physBase + virtBase ; jump to virtual continuation

What this means for the loader:

  • r0 = physical pointer to boot_args, IRQ/FIQ masked, MMU off.
  • topOfKernelData must be 16 KB aligned (it becomes TTBR) and is followed by 36 KB that the kernel zeroes.
  • physBase must be 16 MB aligned, because supersections are used. FCRAM at 0x20000000 qualifies.
  • boot_args and the device tree must sit inside [physBase, physBase+memSize) so their virtual addresses are valid after the switch.
  • Vectors are high (0xFFFF0000, SCTLR.V), mapped by the kernel's own page table. VBAR is never used.

5. CP15 / secure-instruction scan (scripts/kscan.py)

This is a word scan of ARM-mode code. ARMv6 Thumb cannot issue coprocessor instructions, so the scan is complete apart from literal-pool false positives.

Results:

  • No SMC, no MCRR block cache ops, no c12 (VBAR) access in the kernel or the kexts.
  • MRC/MCR p15,0,c15,c2,4 at 0x80060274 (read) and 0x80064208 (write, in the reset/resume path of the vector page). This is the ARM1176 Peripheral Port Memory Remap register, so it needs patching.
  • MCR p15,0,c1,c0,1 (ACTLR write) at 0x80067bf0 is a setter function. It needs review because the MPCore ACTLR has the SMP/AMP bit.
  • MRC p15,0,c6,c0,2 (IFAR) at 0x800662e0 and 0x8006632c, in the prefetch-abort path.
  • PMU c15,c12,0..3 in the kernel (0x8006f1xx–0x8006f28c) and in a kext (AppleARM11xxProfile, 0x805810d4+).
  • Everything else is standard ARMv6: c7 cache and barrier ops by MVA and set/way, c7,c0,4 WFI, c8 TLB ops, c13,c0,1..4 (CONTEXTIDR and the thread ID registers; c13,c0,4 = TPIDRPRW is read 106 times, it holds the current-thread pointer), TTBR0/1, TTBCR, DACR, DFSR, IFSR, FAR, CPACR.

6. SoC layer inside the kernel (strings plus pointer xrefs)

pe_identify_machine matches /arm-io device_type against a table at 0x801dc0e4–0x801dc4ac. The table has entries for: s5l8900x-io, s5l8720x-io, s5l8722x-io, s3c2410-io, integratorcp-io, olocreek-io, omap3430sdp-io and s5i3000-io. Each entry carries clock/timebase constants (for example 200/100/50 MHz for Integrator/CP, and 19.2 MHz next to OMAP3430). The panic string is pe_identify_machine: Epoch Mismatch.

Built-in serial drivers are selected by uart,16550, uart,s5i3000 and uart,s5l89x0x (8900/8720/8920/8930/8940/8950). boot-console, -progress and BootCLUT are also present, along with the 32 bpp CLUT format string BBBBBBBBGGGGGGGGRRRRRRRR used by the video console. Implication: early timer, serial and framebuffer console support live in the kernel proper (pexpert, mostly Thumb code). Everything else is a kext matched through the device tree.

7. Device tree template (build/staging/devicetree.txt)

77 nodes. Root compatible = N72AP|iPod2,1|AppleARM. /cpus/cpu0 compatible = ARM,1176jzf-s|ARM,v6. /arm-io device_type = s5l8720x-io with ranges = (0x00000000 → 0x38000000, size 0x08000000) and (0x10000000 → 0x18000000, size 0x10000000). Children include: vic (vic,pl192), edgeic, gpio, power, clkrstgen, dmac0/1, sha1, usb-complex, amc, clcd, flash-controller0, aes, sdio, h264decoder, scaler, tv-out, mbx, mpvd, prng, spi0/1/4 (multi-touch on spi4), otgphyctrl, i2c0 (accelerometer, pmu, audio0, spkr-amp), i2c1 (als, mikey), timer (timer,s5l8720x|timer,s5l8900x), wdt, i2s0, uart0/1 (bluetooth on uart1), pke, mipi-dsim/lcd, swi and xmc. The template's /chosen/memory-map, /memory reg and the frequencies are all zero, because iBoot fills them in. Wi-Fi is Broadcom (AppleBCMWLAN).

8. Root filesystem

The VFDecrypt key works. The decrypted UDIF has 7 blkx partitions; the disk image (Apple_HFSX : 5) one is 1,287,512 sectors (629 MiB) and carries the HFSX signature HX. 7z l lists sbin/launchd, usr/lib/dyld, System/Library/CoreServices/SpringBoard.app/SpringBoard, and System/Library/Caches/com.apple.dyld/dyld_shared_cache_armv6 (167 MB, larger than RAM!). GL lives in OpenGLES.framework/MBXGLEngine.bundle (the only GL engine) and PrivateFrameworks/MBX2D.framework. IOMobileFramebuffer, IOSurface and CoreSurface are present.

2026-11-16: M1/M2 (emulator)

9. QEMU development machine

  • Upstream QEMU has no 3DS machine, and none was found online.
  • I wrote emu/qemu/hw/arm/nintendo3ds.c (docs/emulator.md), built against QEMU v10.2.4.
  • The two different CPU types need separate cpu-cluster objects.
  • Unmapped physical addresses raise external aborts, which is how the S5L8720 accesses below were found.

10. M1 payload in the emulator

make emu gives:

  • SD mounts (QEMU SD card, SDHC, 2 GiB);
  • the ARM11 handshake works;
  • CP15 ID registers are reported (QEMU arm11mpcore: MIDR 410fb022 r0p2, CTR 1d192992, FPSID 410120b4, MVFR0 11111111);
  • the kernel loads and the jump happens.

Probing c15,c2,4 and c6,c0,2 does not trap in QEMU (they read 0). The real console must answer that.

11. "pe_identify_machine: Epoch Mismatch"

  • After the jump, the ARM11 PC was at 0x80015dd0, just past _panic.
  • Return addresses on the stack (x/48wx 0x80251ef0) were 0x801dc137 (pe_identify_machine), 0x801dc743 and 0x80248960.
  • Disassembly at 0x801dc124: ldrh r3,[r0,#2]; cmp r3,#5; beq ok; ldr r0,="pe_identify_machine: Epoch Mismatch"; bl _panic.
  • boot_args.Version must be 5 for iOS 4.2.1. It's now ba_version=5 in boot.cfg.

12. Serial console = S5L UART ops table

  • The kernel was spinning at 0x801dcef4 (ldr r0,[base,#0x10]; and r0,#4): the UTRSTAT TX-empty poll.
  • The ops table at 0x80266e48: init 0x801dcdd0, baud 0x801dce5c, tx-ready 0x801dcee8, tx-data 0x801dcf00 (strb r0,[base,#0x20] = UTXH), rx-ready 0x801dcf18, rx-data 0x801dcf30.
  • A DCC (cp14) variant exists at 0x80266e30.
  • All six were patched. tx-data jumps into kernel/shim/shim.S, which writes to the ring that the ARM9 drains.
  • Result: the kernel's own panic text appears on the 3DS screen and in log.txt.

13. /pram must be filled

  • Translation-fault data abort at VA 0xC0001000, at PC ~0x801dcb8a.
  • The kernel reads the DT reg of the /pram node, ml_io_maps it, and compares the first word with 0x4F4F5053 ('OOPS', the persistent panic log).
  • The template's reg is (0,0), so nothing was mapped.
  • Fixed in kernel/dtgen.py: /pram = AXI WRAM 0x1FFA0000 (64 KiB), /vram = VRAM 0x18000000 (3 MiB). Both lie outside XNU's RAM, as iBoot's carve-outs do.

14. First real panic: the S5L timer

sleh_abort at interrupt context (trap.c:484):

  • external abort, write to VA 0xC0013088;
  • the store at 0x801dbf94 writes the timer-4 config register in the s5l8720x branch of pe_identify_machine (its literals: "interrupt-controller", "master", "timer", "cpu-debug-interface", _gPEClockFrequencyInfo).

The timer primitives in osfmk/arm are:

  • 0x80068038: 64-bit counter at +0x80/+0x84
  • 0x80068064: time left
  • 0x80068078: set deadline (+0xA8 count, +0xA4 = 3)

The FIQ handler is near 0x80068024 and uses FIQ-banked r8, r10 and r11. Analysis and plan: docs/m2-first-panic.md.

2026-11-16: from the first panic to SpringBoard drawing (emulator)

15. Timer and interrupts

  • XNU-1504's timer is pluggable through per-CPU hooks:
    • cpu_data+0x6C: the FIQ handler, loaded into r9_fiq
    • +0x74: the timer register base
    • +0x70 / +0x64 / +0x68: get-abstime / get-decrementer / set-decrementer, implemented at 0x80068038 / 0x80068064 / 0x80068078
  • The three hooks are patched into the shim:
    • time base = MPCore watchdog in timer mode (free-running, extended to 64 bits)
    • deadlines = MPCore private timer (GIC 29)
    • both at PERIPHCLK/128 = 1,047,311 Hz, which is also timebase-frequency
  • The IRQ entry (0x8006648C) is patched into a trampoline. For IRQ 29 it re-enters the kernel's FIQ handler (mov pc, r9 in FIQ mode).
  • Gotcha: the SWI fast path for mach_absolute_time (~0x80066290) calls get-abstime with no usable stack (sp just under the vector page), so that hook is stackless.
  • /arm-io/timer and the VIC, edge IC, GPIO, power, clkrstgen, watchdog and uart0 nodes point at fake register pages in AXI WRAM (0x1FFB0000+).
  • pexpert translates child addresses as ranges[0].parent + child and ignores the other ranges, while IOKit checks every range. So ranges[0] = child 0 → fake pages, and ranges[1] = identity map of the 3DS IO window.
  • AppleARMPL192VIC needs its PrimeCell ID registers (0xFE0–0xFFC) filled in (fakeio.bin).

16. IOKit and the root device

  • RTC wait: 30 s timeout patched to 0 (0x802E78B4).
  • IOPMU waits only block side threads.
  • secure-root-prefix=md made the md root wait for a SecureRoot callback, so the property is removed.
  • Root = md0 via memory-map RAMDisk + rd=md0. mdevstrategy (0x80072BF8, Thumb) is patched into kernel/shim/blk.c, which hands I/O to the ARM9 block server reading sd:/ios3ds/rootfs.hfs with FatFs fast seek.
  • Bugs found on the way:
    • preemption race on the single mailbox → interrupts off per transfer;
    • lazily mapped UPL pages → pre-fault them before masking interrupts.

17. Prefetch-abort fault address

The IFAR replacement was lr-4, but the handler had already done sub lr,lr,#4 (0x800662AC). The result was 2 million prefetch aborts at the same address; the fix is mov r1/r5, lr.

18. Userland

  • launchd starts.
  • Root filesystem changes (rootfs/recipe.json, applied with xpwn hfsplus):
    • fstab /dev/md0 / hfs rw
    • grown to 1 GiB (after removing CoreLocation's consolidated.db, since Apple's image has 0 free blocks)
    • 28 daemons disabled (keybagd: FATAL KEYBAG ERROR → restore reboot)
    • SpringBoard stderr routed to /dev/console
  • SpringBoard fixes:
    • "No window server display found" → keep arm-io/clcd on 2 fake pages with iBoot's CLCD state, and drop function-lcd_enable.
    • The kernel beq at 0x807A9B68 is NOP'd, so swap-done is synchronous.
    • liblockdown is stubbed in the dyld cache (no lockdownd).
    • AppleKeyStoreGetDeviceLockState is stubbed (it blocks without a system keybag).
  • QuartzCore uses its software compositor (no AppleMBXDevice).
  • Rendering is vsync-driven: the shim turns the 3DS PDC0 VBlank (GIC 42) into the S5L CLCD frame IRQ through the fake VIC.
  • tools/ios3ds-sample prints every process's thread state to the console.
  • Result: SpringBoard draws the "Connect to iTunes" screen, mirrored onto the 3DS top screen by the ARM9.

19. Input reaches SpringBoard (2026-11-16)

  • Wired: ARM9 input_poll (pad + TSC) → ring at shim+0x6200 → sysctl kern.ios3ds_input (registered from the first mdevstrategy call) → /usr/libexec/ios3ds-input.
  • QEMU: the daemon connects ("connected to SpringBoard's HID event system", "mailbox up: touch absent"; no TSC model yet) and logs key 40 down/up for START.
  • Keyboard IOHIDEvents dispatched with IOHIDEventSystemClientDispatchEvent are ignored by SpringBoard: no visible effect for Home (0x40) or volume (0xE9).
  • Buttons now go as GSEventRecords (52 bytes; infoSize at +0x30, checked in _GSSendEvent 0x352632c4) through GSSendSystemEvent (0x352635a4, resolved with dlsym) to PurpleSystemEventPort. Delivered: SELECT (lock 1010/1011) brings up "slide to power off" and an "Edit Home Screen" hint.
  • Open: both are hold reactions. The down is honoured, but the up (sent 0.3 s later) is not, or not in time. Suspects: SpringBoard measures hold time against "now" while its run loop lags in the emulator; or the up needs extra record fields. Touch (GSHandInfo to the frontmost app) is still IOHID-only and untested (no TSC model).

20. Button timing in SpringBoard (2026-11-16)

  • -[SpringBoard lockButtonDown:] (0x8a48) arms lockButtonWasHeld with a 2.5 s NSTimer (0x4004000000000000). lockButtonUp: (0x9a2c) does nothing more once the power-down sheet isOrderedFront.
  • menuButtonUp: (0x8db8) returns at 0x918e when no menu timer was set by the down. A tap then goes through the double-tap delay (performSelector:_handleMenuButtonEvent afterDelay:).
  • Reproducible: a down sent immediately and an up 0.3 s later → "slide to power off" plus the "Edit Home Screen" hint (a hold).
  • Daemon now defers: a tap sends down+up back to back on release; the down of a hold goes out after ~0.8 s (counted in poll ticks, because mach_timebase_info gave no usable value).
  • With deferral, neither a lock tap nor a 5 s lock hold (tick-stamped: down @22836, up @22969) changes the screen. A Home tap on page 1 doesn't open Spotlight either. Unresolved.
  • Debug aids tried:
    • SBLogging default: no output.
    • Setting SpringBoard's trace byte (0x18c264 → file 0x18b264): runs, but NSLog goes to ASL, and syslogd persists nothing (/var/log/syslog 0 bytes).
    • CFLOG_FORCE_STDERR=1: no visible output.
    • mkrootfs file patches now take an optional mode; they used to force 0644, which broke the patched SpringBoard executable.
  • Next: get syslogd writing (or patch NSLog's ASL path to stderr), then trace which button handlers run.

21. Buttons work; the "holds" were the test harness (2026-11-16)

  • emu/run.py turned every key_down into sendkey <key> 3000 and ignored key_up. Every test press was therefore a 3 s hold, which explains the power-off sheet and the hint in entries 19/20.
  • run.py now uses the down→up interval as the sendkey hold time.
  • Results:
    • Home tap on page 1 → Spotlight ("Search iPod" with keyboard);
    • 4 s lock hold → "slide to power off";
    • lock tap → no visible change (screen-off isn't mirrored).
  • The daemon's deferred-down for taps stays: a slow SpringBoard run loop can still lose a separate up to the 2.5 s hold timer on real hardware.
  • The SpringBoard trace patch and syslog-to-console line were removed. NSLog never reached the console in any configuration we tried (open).

22. Touch works (2026-11-16)

  • QEMU: CTR CODEC/TSC on NSPI bus 2 plus I2C/MCU, and an absolute pointer, all in nintendo3ds.c (from the QEMU agent's draft). The ARM9 driver reports tsc_ok, and pen samples land in the input ring with correct ADC values.
  • Ignored path: digitizer IOHIDEvents dispatched by our daemon reach SpringBoard's event system but are ignored, as keyboard events were (entry 19).
  • Working path: kGSEventHand (3001) GSEvents, layout from 8C148:
    • _GSEventGetHandInfo copies 0x24 bytes at record+0x34;
    • _GSEventGetPathInfoAtIndex = record+0x58+24*i;
    • _UIApplicationHandleEvent reads pathInfosCount at hand+0x21, treats type 8 as cancel, and treats a path as touching while proximity bit 1 is set.
    • Target: the frontmost app's purple port (SBFrontmostApplicationDisplayIdentifier → GSCopyPurpleNamedPort), else GSSendSystemEvent (SpringBoard).
  • Daemon: needs flipx since the display blit rotates (ix = rr*4/3).
  • Result: tapping Settings at iOS (47,320) opens Settings (emu/tap.py).

23. OpenGL ES 1.1: a software engine in MBXGLEngine's slot (2026-11-16)

  • Engine discovery (OpenGLES _eagl_init, 0x34ff870c):
    1. GLEngine.bundle is tried first and is absent.
    2. IOServiceGetMatchingServices(IOServiceMatching("AppleMBXDevice")) must return ≥1 service.
    3. CFBundleGetDataPointerForName(MBXGLEngine.bundle, "GLESGetEGLInterface") is called and its result goes into _mbx_dispatch.
    • The MBX engine serves ES1 only (initWithAPI: checks api == 1).
  • Getting past the check: one file patch on OpenGLES's own copy of the string (cache file 0x4ff9458) makes it read "IOResources". The copies in MBX2D (0x30770c68) and MBXGLEngine (0x32ee0fac) are left alone.
  • Loading our engine: enable-dylibs-to-override-cache makes dyld load our on-disk MBXGLEngine in place of the cache copy. The only .dylib files the rootfs keeps on disk are 12 symlinks into cache-only frameworks.
  • Engine table and call shapes: read from every _mbx_dispatch call site in 8C148's OpenGLES. The table has 11 entries; 4.2.1 adds Set/GetProperty at +0x24/+0x28.
    • CreateGC(sg, X+0x10, X+0xD34, X+0xC) passes two 841-slot dispatch tables.
    • attachImage:toCoreSurface:invertedRender: calls BindCoreSurface(gc, target, surface). It accepts GL_RENDERBUFFER only together with invertedRender=YES, and target 0x84F5 only with NO.
    • swapNotification: calls SwapNotification(gc, IOMobileFramebufferGetID(fb), transaction, layer). The non-MBX path calls IOMobileFramebufferSwapSignal(fb, transaction, layer) instead.
  • CA drawable protocol: read from the stock _GLESBindView (0x32eb4ba4), _ViewTextureBeginIfNeeded (0x32eb4a64), _GLESPresentView (0x32eb4628) and _GLESCreateBuffer/_GLESDestroyBuffer. The drawable is called through:
    • +4 bind(d, 'BGRA'|'L565', {ctx, create, destroy})
    • +8 unbind
    • +0xC dequeue → IOSurface
    • +0x10 present(d, 1)
  • The engine: tools/ios3ds-gl is the CPU rasterizer behind a swappable Backend. The design is in docs/gpu.md. All 44 gl* imports of QuartzCore are among the 177 implemented entry points.
  • QEMU, run 1:
    • The engine loads in ios3ds-gltest and in SpringBoard ([gl] context created, pid 8 and pid 16). SpringBoard creates an EAGL context even with CA_ENABLE_OGL=0. No unimplemented slot was hit.
    • Offscreen: all 10 pixel probes and glGetError pass (gltest: PASS).
    • On screen: drawing into the display's IOSurface through attachImage:toCoreSurface: runs at ~13.6 fps, including a 50 ms sleep per frame. The top LCD shows the scene: triangle, textures, blend, scissor bar and lit cube.
  • Regression: with the demo off, the home screen stayed black (400/449 s). SpringBoard's context came from -[CAWindowServer _detectDisplays] → M2CLCDDisplay::open → M2Display::M2Display (0x346de5b8) → Display::eagl_context(1).
    • The constructor probes ES2 and then ES1, and on success stores the API at +0x17c. API 1 picks 'L565' at +0x180.
    • Once a context exists, the display is GL-backed and the software compositor stops. Even with CA_ENABLE_OGL=0, no engine call followed, so nothing was drawn.
  • Fix: a cache patch at file 0x46de620 (bl eagl_context → mov r0,#0) skips the ES1 probe.
  • Run 4:
    • the home screen is back at 415 s;
    • the GL scene is drawn from ~425 s (449 s shot);
    • gltest: PASS;
    • SpringBoard creates no context.
  • Open: CA's GL compositor needs L565 render targets plus the BindView/SwapNotification path, which RE covers but no run has exercised yet.

24. Audio: Apple's kexts on emulated PL080/I2S/I2C (2026-11-16)

  • Kept dmac0/i2c0/i2s0 on fake pages; see docs/audio.md for the design and addresses.
  • AppleARMIICDevice transfer (0x802e4d1e, vtable 0x35c) takes (this, op, sublen, sub*, len, buf*); op 1 = read, 2 = write (the CS42L58 driver's read-modify-write pairs in the boot log confirm it). Patched to a shim register file.
  • AppleARMPL080DMAC filter (0x807d115c) reads the TC status once and writes IntTCClear once, so the shim can apply write-1-to-clear at its next service.
  • QEMU boot (450 s): AppleARMPL080DMAC::start, AppleS5L8900XI2SController::start, three _initDMAChannels, AppleCS42L58Audio::start and 78 I2C register accesses; SpringBoard home screen renders as before; mediaserverd idles with 19 threads.
  • Volume-up (R) and lock (SELECT) presses reach SpringBoard ([input] key e9/30), but no HUD appeared and no output stream started, so the DMA/CSND path is covered only by the host test (tests/test_audio.py) so far.
  • The ARM9 CODEC init reports "id 00" in QEMU (SPI stub) and carries on.

25. Real-hardware hang after "iBoot version": the clock base was 0 (2026-11-17)

  • Symptom (hardware runs 3–6): silent stop right after iBoot version: ios3ds-loader; probes showed 34 clock reads (last one with CPSR 0x93), one 10 ms deadline (caller 0x800695d3), zero IRQ entries. Plain QEMU never hung.
  • Reproduction: -icount shift=2,sleep=off (QEMU time = instruction count, ~250 MHz, roughly the Old 3DS ARM11) gives exactly the hardware probe values: abs 34 cpsr 80000093 | dec 1 last 10473 caller 800695d3. Without icount, QEMU's wall-clock timer runs far ahead of the slow TCG CPU: in a plain run clock reads 2–7 already come from IRQ mode (CPSR 0x192), i.e. the first tick fires before read 2. emu/run.py --icount 2 now does this.
  • Where it hangs (emu/gdb/postmortem.py, attach after the hang): ARM11 at 0x80069186–0x80069198, SVC, IRQs masked, in a loop do { base = rtclock[+0x30..+0x34]; … } while (base == 0 || base changed) (function 0x8006916c, abstime → seconds/microseconds; rtclock = 0x80255128). It is called from the calendar path at 0x80014eec, between a lock/unlock pair (0x80063420 / 0x800634c0) that masks IRQs.
  • Who writes rtclock+0x30:
    • rtclock_init at 0x8006993e/0x80069998: the result of mach_absolute_time() (bl 0x800694d4 at 0x80069936);
    • the clock tick handler at 0x800696e4: "now".
  • Cause: rtclock_init runs before the first set_decrementer, and the shim was only initialised there. Until then shim_get_abstime returned 0, so the base was 0. The spin then needed the first tick, which cannot arrive with IRQs masked. On Apple hardware the timer always runs; on QEMU the tick happened to come first.
  • Fix: shim_get_abstime calls shim_init itself on the first read (stackless: r3/lr/CPSR parked in pc-relative words, IRQ/FIQ masked). In the icount run the kernel now goes on through IOKit, launchd and SpringBoard (build/hwlogs/qemu-icount-fixed.txt).
  • Not the cause (checked on the way): the vector page and page tables. The new probe snapshot reads TTBR0/1, TTBCR, DACR, MPIDR, L1[0xFFF], L2[0xF0], the 8 vector words, the IRQ literal and the first two handler words from the ARM11 view; after a stall the ARM9 walks the same tables in FCRAM and compares. In the icount reproduction both views match (e59ff018…, IRQ literal 8006648c, handler e51ff004 8084001c).
  • Tooling: emu/gdb/rsp.py is a minimal GDB remote-protocol client. The Arm gdb 14.2 has no Python and the host gdb has no ARM target, so scripted traces go through this client: reads.py logs every clock read, panic.py breaks at _panic, postmortem.py attaches after a hang. The monitor writes all probe values to log.txt ([probe] lines) after ~5 s without a clock read or console output, so photos are no longer needed.

26. Real-hardware boot to SpringBoard, and boot-time performance (2026-11-17)

  • run8 (9867d28): first hardware boot to SpringBoard. Touch, volume and Mail work (docs/hwlogs/run8.txt). It is slow: ~19 md0 requests/s, launchd at ~115 s, input at ~320 s.
  • Why md0 latency is the whole story: shim_mdevstrategy (kernel/shim/blk.c) waits for each ≤32 KiB request with IRQs off. The ARM9 only answers between its other jobs. Those jobs were:
    • console output written one byte per f_write + f_sync;
    • a ~330k-pixel screen copy every 16 loop passes;
    • touch over SPI.
  • ARM9 PC samples (emu/pcsample9.py, QEMU with --icount 2): 49% send_command (SD), 26% display_blit.
  • run9 (763f374): chunked log with a 0.5 s sync; the block mailbox is polled inside the blit; one word read per VRAM pixel; screen copies paced (≤15 fps, 2/s while md0 is busy). SpringBoard and input come up in under 83 s (docs/hwlogs/run9.txt).
  • The 30 s boot wait was IOKitInitializeTime() (0x801a8004, called from bsd_init at 0x8024a53e): waitForService(resourceMatching("IORTC"), {30, 0}). Nothing publishes IORTC. Found with a SELECT+START thread dump in QEMU during the wait: the bootstrap thread 0x80284664 was blocked under 0x801a8021. The earlier rtc-wait-0s patch only covered the later getGMTTimeOfDay wait. New patch iortc-wait-0s (movs r3,#30 → #0 at 0x801a800a). BSD root now follows immediately.
  • md0 linger: after serving a request, the ARM9 polls the mailbox for up to 2 ms (at most 100 ms in total) before running the rest of its loop, so streamed reads go back to back. In QEMU with icount the emulated SD controller dominates, so this needs a hardware run to measure.
  • IORTC timeout 0 was too aggressive (hardware run10 and one QEMU run): gltest measured 0 ms per frame, so early userland gettimeofday deltas were frozen. With timeout 0, clock_initialize_calendar() can run before AppleARMPE (gIOPlatform) has registered. The "RTC did not show up" line is missing in those runs, which shows the platform expert's getGMTTimeOfDay was never called. The result looks like a race: a clean --icount 2 run with timeout 0 measured 2486 ms. Patch changed to 2 s (iortc-wait-2s, movs r3,#2). AppleARMPE is up within 1 s even in plain QEMU, so the original order is kept, while 28 of the 30 s are still saved. Clean --icount 2 run: the RTC line is back, gltest takes 2531 ms, md0 starts at ~2 s, and boot reaches SpringBoard and input.
  • Lesson: build releases from a clean worktree (ios3ds-wt/rel). Other agents' uncommitted edits in the main checkout (shim, input daemon) leaked into a test build and produced a broken boot (FS errors, launch_msg(): Socket is not connected) unrelated to the change under test.

27. PICA200 back end for the GL engine (2026-11-16)

Design and sources are in docs/pica200.md. This entry records what was checked and how.

  • Kernel facts for the GPU service (scripts/ksym_lib.py over the kernelcache symbol table; the n_desc & 8 bit says Thumb):
    • copyin 0x80067c84 and copyout 0x80067d04 are ARM. Disassembly shows copyin(r0 = user address, r1 = kernel address, r2 = length), i.e. a 32-bit user_addr_t.
    • IOMallocContiguous 0x801a70e0, ml_io_map 0x80067780, IODelay 0x801a6c2c, IOSleep 0x801a6c40, printf 0x8001c4c4, proc_selfpid 0x8014f1be, proc_find 0x8014f94c, proc_rele 0x8014f862 are Thumb.
    • _sysctl__children (top-level OID list) is at 0x8027f7a8.
  • ABI: iOS lets callees clobber r9; our shim C code is EABI and assumed r9 is preserved across calls into the kernel. The shim is now built with -ffixed-r9 (scripts/mkboot.py). This also covers blk.c and the input service.
  • References fetched for semantics: Azahar src/video_core (renderer_software/sw_rasterizer.cpp, sw_clipper.cpp, sw_framebuffer.cpp, sw_blitter.cpp, sw_texturing.cpp, pica/pica_core.cpp, pica/regs_*.h) from raw.githubusercontent.com/azahar-emu/azahar/master, and the local libn3ds copy (gfx.c, gx.h, pdn.h). Read, not copied.
  • Earlier draft reviewed (tools/ios3ds-pica from the interrupted session): encoders, tiling, texenv mapping and the shader assembler were kept. Three things were wrong or missing and are fixed: the unit test expected a truncated f31 mantissa (the encoder was right); colour-buffer and PPF formats number RGB565/RGB5A1 differently (one enum was used for both); GL_COMBINE was not mapped. Its user-mapped register design was replaced by the shim service.
  • Host:
    • make -C tools/ios3ds-pica test → 328 checks, 0 failures. The last group renders one triangle through driver core + model and checks pixel positions with and without the transfer's flip flag.
    • make -C tools/ios3ds-gl host-test → 10 probes ok on both back ends; scene 1, pica vs software: 27584 of 153600 pixels differ at all, 10 by more than 24; scene 2 … 39319 … 320 by more than 24. Scene 2 (off-target viewport, NPOT texture, two units, alpha test, GL_COMBINE, masks, render-to-texture) found one back-end bug: with a viewport that does not fit, the stale GL scissor box was applied although the scissor test was off.
  • QEMU run 1 (node registered as kern.ios3ds_gpu): [gl] pica: GPU not available: no kern.ios3ds_gpu service, then GPU pass skipped; the software pass and the boot were unaffected. The errno was not logged in that run. The node was moved to the top level (ios3ds_gpu) and the transport now logs the failing step and errno.
  • QEMU run 2 (python3 emu/run.py --time 160 --shots 150,159, gltest arguments 45 300):
    [pica] bring-up: PDN_GPU_CNT 0x0001007f, GPUPROT 0x00000000, GX clock 0x00000000, GX stat 0x00000000
    [pica] arena 8192 KiB at VA 0xcb114000 = PA 0x24684000; driver ready (state 0)
    [gl] pica: GPU up: arena 8192 KiB at PA 0x24684000 (8064 KiB free), PDN_GPU_CNT 0x1007f, PICA200
    [gl] context 0x904c00 uses the ios3ds PICA200
    gltest: GL_VERSION "OpenGL ES-CM 1.1 ios3ds", GL_RENDERER "ios3ds PICA200"
    (10 probes ok)
    gltest: pica vs software: 27584 of 153600 pixels differ at all, 10 by more than 24 (max 229) ok
    gltest: PICA200 PASS (0 failed)
    gltest: drawing into the display surface 320x480, status 0x8cd5
    
    The 150 s screenshot shows the animated scene on the top LCD, drawn through the emulated GPU into the display IOSurface. QEMU printed no picasim: diagnostic. (GX clock 0 is the model; hardware should show 0x70100.)
  • QEMU run 3 (full boot, --time 450 --shots 400,449, gltest arguments 340 60): the same [pica] / PICA200 PASS lines; the 400 s screenshot is the SpringBoard home screen as before, the 449 s one the GL scene drawn through the emulated GPU (10-11 fps including the 50 ms sleep per frame). No picasim: diagnostics, no [pica] TIMEOUT.
  • QEMU run 4 (committed configuration, gltest arguments 0 0, with scene 2): scene 1 … 27584 … 10 by more than 24 … ok, scene 2 … 39319 … 320 by more than 24 … ok, gltest: PICA200 PASS (0 failed): the same numbers as on the build host.
  • Not verified: anything on a real PICA200. docs/pica200.md §5 says what the model can and cannot show, §8 lists what to look at on the first hardware run.

28. GPU display mirror; the PICA200 path reviewed for real hardware (2026-11-17)

Branch agent/gpu = agent/pica + main. Design: docs/pica200.md §9-11.

  • Why: entry 26 measured 26% of the ARM9's time in display_blit, and the ARM11 kernel waits for md0 with IRQs off while the ARM9 is busy. The screen copy is the one big ARM9 job that a GPU can take.
  • The copy is a scaling. In the LCD framebuffers' own layout (row j = screen column j, 240 pixels from the bottom up) display.c's rotation disappears: top = iOS (⌊4i/3⌋, ⌊4(j−20)/3⌋) for j 20..379, bottom = iOS (⌊(3i−40)/2⌋, ⌊3j/2⌋) for i 14..226. Written down once as gm_map() (boot/common/gpu_mirror.h).
  • Exact nearest sampling: texcoord iOS x = 4/3·q − 1/2 at render-target column q puts every pixel centre 1/6, 1/2 or 5/6 into a texel, never near a boundary; same for the other three axes (3/2·q − 41/2, …). With truncating sampling (Citra, our model) that reproduces the integer maths exactly.
  • Colour without a BGRA texture format: iOS bytes B,G,R,A read as RGBA8 (A,B,G,R) give sample.g = R, .b = G, .a = B; three TEV stages with constant colours (1,0,0), (0,1,0), (0,0,1) and MODULATE / MULT_ADD rebuild (R,G,B) exactly.
  • Host test (make -C tools/ios3ds-pica test, test_mirror): boot/arm9/display.c compiled for the host (VRAM mapped at 0x18000000 with MAP_FIXED so its 32-bit addresses work) against the engine + model: mode top/both/bottom: GPU mirror vs ARM9 CPU copy (display.c): 0 of 1566976 bytes differ, also with a GPU that finishes operations only several polls later (3 frames needed 72 busy steps). The self-test catches a deliberately wrong list (249666 bad bytes … caught) and an unreachable list times out at the P3D stage.
  • First QEMU boot (plain, --time 450): self-test variant 0 exact, mirror on, home screen on both LCDs. But the model ran each operation inside the MMIO write, so the 52 ms model draw ran inside the VBlank handler: ARM11 IRQ time 55055 us/frame — a QEMU artefact, and the multi-interrupt stepping was never exercised. Fix: the QEMU GX model now holds back the starting write in virtual time (PSC 100 µs, PPF 400 µs, P3D 1 ms) and runs it from a timer.
  • QEMU, plain, async model (--time 450, X at 405/420/435 s): [gpu] mirror self-test variant 0 (as modelled): 0 of 518400 bytes differ, guard intact, ~10 fps (frame avg ~75000 us, 6 interrupt steps per frame, ARM11 IRQ time 129-529 us/frame), spot check (GPU copy): 0 of 512 sampled LCD pixels differ every 30 s, gltest: PICA200 PASS (0 failed) while the mirror runs (3 busy skips), all three screen modes correct with the console redrawn on the screen given back (build/emu-plain2/screen_415/430/449).
  • QEMU, --icount 2 (--time 300): CPU copy before the mirror starts: 44 copies in 30 s, 161.5 ms each, later 103 copies, 56.0 ms each (ARM9, emulated timing); once the mirror is on (after the GL test), 671 frames in 30 s (22.3 fps), spot checks 0/512, gltest: PICA200 offscreen frame took 1088 ms vs 2098 ms software. The GPU stage times in QEMU are the model's delays plus interrupt latency, not hardware figures.
  • Real-hardware review of the existing GPU service (docs/pica200.md §10): the arena came from IOMallocContiguous with whatever dirty lines its previous owner left: a write-back of one of them could land on GPU output at any later time. Now the whole D-cache is cleaned and invalidated once after allocation. boot.cfg gpu=0 stops bring-up before any register access. The GL engine checks a PPF round trip and a PSC fill through the service before pica/auto use the GPU, and logs what came back if not. No GIC line was added: completion stays polled, the mirror is stepped from the existing VBlank (42) and timer (29) interrupts.
  • Shim size: with the mirror the shim ended at +0x741C, past the +0x5F00 limit (probe snapshot). The GPU code (pica.c, pica_drv.c, pica_mirror.c, 16 KiB incl. bss) is now linked at 0x808B0000 and loaded from gpu.bin (with the command lists at 0x208B8000); the main shim shrank to 0x3414 and calls the part only through gpu_glue.c when its magic is present. The ARM9 clears that magic before the load= entries so a stale copy from a previous boot in FCRAM is never called.
  • CPU copy change: a screen that starts showing iOS is cleared first. Before, the top screen's 20-column side margins kept console text in "both"/"top" mode; the GPU writes them black, and so does the CPU copy now.
  • Not verified on hardware: everything in this entry. docs/pica200.md §11 lists the log lines that settle each assumption.
  • GPU vs CPU screenshots: the same build with gpu_mirror=0 ([gpu] display mirror disabled (boot.cfg), CPU screen copy: 109 copies in 30 s, 36.7 ms each): its 400 s and 449 s screenshots are pixel-identical to the GPU-mirror run's (0 of 192000 pixels differ, both screens, "both" mode). Touch is unaffected: the input daemon's panel → iOS mapping (flipx, 2/3 scale) was never touched and the picture under the finger is the same.
  • Fallback, injected: the final build with gpu.bin's list 0 replaced by list 1 (wrong sampling for the model): all 8 variants logged with their first difference, then [gpu] display mirror FAILED (self-test mismatch): 249666 bytes differed, first at 14403: 01 expected, 00 seen; the ARM9 keeps copying the screen; CPU copy continues (spot check (CPU copy): 0 of 512), gltest still PICA200 PASS, and the 399 s screenshot equals the CPU-only run's. The unmodified final build again: variant 0 exact, mirror on, 449 s screenshot identical to the CPU-only run's.

29. Swipes never ended: the shim starved vsync (2026-11-17)

  • Symptom (QEMU, viewer and emu/tap.py --drag): after a fast swipe the home-screen page froze half-dragged. Every later touch moved it again and froze again; a tap left the Spotlight "W" key popup up.
  • Not the touch path: the daemon logs a down and an up for every gesture. GraphicsServices backlogs full-queue sends and re-sends them with a blocking mach_msg (_GSSendEvent 0x352632c4, thread 0x352638a8). UIKit ends a touch on hand type 6 with proximity bit 1 clear (_UIApplicationHandleEvent 0x3381ecf4). Pacing and coalescing the daemon's events changed nothing.
  • Cause: UIScrollView pages and bounces through UIViewHeartbeat → GSHeartbeat. GSHeartbeatCreate (0x35264a6c) ticks on IOMobileFramebufferGetVSyncRunLoopSource, i.e. CLCD frame interrupts. AppleM2CLCD keeps its frame-IRQ enable (+0x08 bit 0, shadow ivar 0x254) set while anyone wants frames, and clears it itself when idle (interrupt action 0x807a9df8). The shim cleared it after every injected VBlank ("one-shot"), and the driver, trusting its shadow, never set it again until the next swap. Once the finger lifted nothing swapped, so the heartbeat never ticked.
  • Fix: the shim leaves the enable alone and injects on every VBlank while it is set.
  • Result (emu/tap.py --drag 450:280,240:40,240 --drag 462:40,240:280,240 --tap 475:47,320): the page snaps back after the swipe and the tap opens Settings. A 240 pt right swipe in 0.4 s did not page to Spotlight (open).
  • emu/viewer.py: a mouse release outside the views used to be dropped (pen stuck down); drags now stay in the view they started in and always end. emu/tap.py gained --drag.

29b. Hardware run 12: the PICA200 does not fill or draw; GX clock was never set (2026-11-17)

  • run12 (m1-21f26fc, docs/hwlogs/run12.txt): mirror self-test wrong in every variant (first byte 0x80, 0x40 with the read-out flip; ~451k of 518k bytes), GL self-check: memory fill left 4096 of 4096 words wrong (word 0: 0x5a5aa5a5). Fallbacks fine. ARM9 CPU copy: 313-433 ms per frame.
  • Reading the failure: the GL self-check's transfer round trip passed first, so PPF, addresses (PA>>3) and the cache maintenance work. The fill left the old data, yet its done bit came on. The mirror's read-out produced correct black margins (first 14400 bytes), so its last stage ran; the render targets held wrong data.
  • GX clock: GX clock 0x00000000. Compared the register sequences with libn3ds (source/arm11/drivers/gfx.c hardwareReset, include/arm11/drivers/gx.h) and Luma (arm11/source/main.c initScreens): libn3ds writes gpu_clk = 0x70100, clears the VRAM bank-disable bits (+0x030 bits 8-11), sets psc_dma_prio0/1 (+0x050/+0x054); Luma writes none of them, only PDN_GPU_CNT and the PDC registers. Our bring-up skipped them because "Luma leaves the GPU running" was only checked through PDN_GPU_CNT.
  • Also from libn3ds gx.h: GX +0x70..+0xBC are memory-traffic counters (PSC external/VRAM reads and writes, P3D vertex/texture/depth/colour, PPF, fills). They show whether an engine touched memory at all, independent of done bits.
  • Changes: bring-up applies the clock/VRAM/priority setup (boot.cfg gpu_clk, default 1). pica_diag.c runs staged tests before and after it (fills to VRAM and FCRAM; PPF; P3D constant quad into VRAM and FCRAM; 64x64 and 48x40 textures drawn 1:1) with counter deltas (boot.cfg gpu_diag, default 1); docs/pica200.md §12 says how to read them. A failed mirror self-test also dumps a texture tile and a render-target tile with their expected values. The diagnostic lists are built by genmirror (blob version 2).
  • Host: the diagnostics pass on the model (diagnostics on the model: 0x7f); the dump's expectations equal what a passing self-test leaves (16 of 16). The model has no traffic counters (they read 0) and does not need the clock register.
  • QEMU (this build, --time 450 and --icount 2 --time 300): [pica] GX setup as libn3ds hardwareReset: clock 0x00000000 -> 0x00070100 …, [gpu-diag] summary: fill VRAM ok->ok, fill FCRAM ok->ok …; PPF ok; P3D solid VRAM ok, FCRAM ok; texture POT ok, NPOT ok (the model fills and draws without the clock, so "as found" passes there), mirror self-test variant 0, gltest: PICA200 PASS, home screen; screenshots identical to the CPU-copy run in both modes; icount mirror 23.9 fps, spot checks 0/512.

30. Run 13's answer: no FCRAM fills, no NPOT textures; the model now agrees; fixes (2026-11-18)

  • run13 (eab9618, docs/hwlogs/run13.txt): [gpu-diag] summary: fill VRAM ok->ok, fill FCRAM FAIL->FAIL; PPF ok; P3D solid VRAM ok, FCRAM ok; texture POT ok, NPOT FAIL. Counters for the FCRAM fill: fill0 +256 ext-wr +0 (the engine ran, nothing reached external memory); NPOT 48x40: 0/1920 texels, tex +256. The GX clock setup changed nothing (VRAM fills worked before it).
  • Texture tile dump explained (run13 lines 288-291): decoding the words with the self-test pattern gives iOS pixels (0,479) (1,479) (0,478) (1,478) (2,479) …: a correct linear→tiled upload done with the flip flag, i.e. the last variant tried (7). The target tile holds (128..130, 300) throughout: NPOT sampling. The dump now re-runs variant 0 first.
  • Model = hardware: picasim writes nothing for fills outside VRAM and samples noise from NPOT textures. Proof that it reproduces the hardware: the previous build (c0ee62e) on the new QEMU gives the run13 summary line verbatim, [gpu] display mirror FAILED (self-test mismatch) and [gl] pica: GPU self-check: memory fill left 4096 of 4096 words wrong (word 0: 0x5a5aa5a5), the exact hardware message (build/emu-hwmodel); the host tests failed the same way before the fixes.
  • Fixes: mirror texture 512x512 in the FCRAM arena, filled by a PPF texture copy (60 tile rows of 10240 bytes, output gap 6144) from the 320-wide upload in VRAM; GL clears as P3D quads, depth initialised by CPU write, self-check draws a quad. docs/pica200.md §13.
  • CPU copy (docs/pica200.md §14): row reads and column writes as 16-byte LDM/STM bursts, 4 pixels packed into 3 words, only the framebuffer set the PDC shows (the shim publishes PDC0/1 +0x78; QEMU: LCDs show framebuffer set 0 on top, 0 on the bottom). Host test: byte-identical to the GPU model and to the old copy's mapping.
  • QEMU --icount 2, CPU copy only (gpu_mirror=0), same boot phases, old (c0ee62e) → new: 126.4 → 48.1 ms, 181.0 → 54.6 ms, 194.3 → 65.3 ms, 51.5 → 14.4 ms per copy (instruction-clocked: fewer instructions; the hardware gain from bursts and from writing one set instead of two plus a read-back is not visible in QEMU). Screenshots of the three icount runs differ only in the status-bar clock.
  • QEMU with the fixes: plain 450 s and --icount 2 300 s: diagnostics summary as on hardware, [gpu] display mirror: self-test passed (variant 0), screen copy: PICA200, [gl] pica: GPU up (self-check passed), gltest: PICA200 PASS (0 failed), spot checks 0/512; icount mirror ~20 fps. Plain 449 s screenshot identical to the CPU-copy run's.
  • Open on hardware: the PPF texture copy with an output gap and texture fetches from FCRAM. Both are covered by the mirror self-test (failure → CPU copy, logged with a dump).

31. Stability soak; md0 no longer freezes the kernel (2026-11-18)

  • emu/soak.py: boots QEMU, waits for [input] connected to SpringBoard, then cycles through the page-1 icon grid and the dock:

    • per cycle: tap, settle, Home, page swipes every 4th cycle, lock/wake/slide-to-unlock every 5th, a screenshot per step;
    • recovery when a cycle doesn't end on the home screen (second Home, then Dismiss), recorded per cycle;
    • afterwards the log is scanned for panics, [probe] stalls, md0/log errors, crashes, jetsam and SpringBoard restarts.

    Output: build/emu/soak*/report.md.

  • Soak 1 (main 15f2a30, plain QEMU, 40 cycles, ~19 min): no panic, stall, I/O error, crash or memory warning, and SpringBoard never restarted.

    • Cycles 13 and 33 "failed" only because the tap missed an icon and Home on page 1 opens Spotlight (correct iOS behaviour). Hence the recovery step.

    • Real bug, cycle 0: the first app launch after boot (Game Center). The input daemon sent Home as down+up in the same poll (key 40 down @1644 / up @1644), yet SpringBoard showed the "Edit Home Screen" alert, its reaction to a Home hold. The alert then blocked every tap for ~5 minutes.

      It did not reproduce in 8 quiet Game Center cycles (--targets 47,50 --settles 2,20). It needs the busy first launch.

  • Cause (by design reading): shim_mdevstrategy waited for each md0 request with IRQs off:

    • ~20 ms per request on hardware, thousands of requests for a cold app launch;
    • meanwhile no timer, scheduler or VBlank ran anywhere in the kernel.

    If SpringBoard handled the Home down, then page-faulted its own code from md0 before handling the up, its hold timer (menuButtonDown: → menuButtonUp:, re-log 20) could expire during the freeze.

  • Fix (kernel/shim/blk.c):

    • md0 requests are serialized by a kernel mutex. The XNU KPIs come from the kernelcache symbol table:
      • lck_grp_attr_alloc_init 0x8001ae22, lck_grp_alloc_init 0x8001ae00, lck_attr_alloc_init 0x8001ade8, lck_mtx_alloc_init 0x80062008 (Thumb);
      • lck_mtx_lock 0x80063000 and lck_mtx_unlock 0x800631a0 (ARM);
      • assert_wait_timeout 0x8001f02a and thread_block 0x8001edcc (Thumb).
    • The wait for the ARM9 runs with interrupts on: it spins ~200 polls, then sleeps in 250 µs steps (assert_wait_timeout + thread_block).
    • The whole buffer is faulted in before taking the lock, so no fault ever waits on md0 behind its own request.
    • If the lock can't be allocated, the old IRQs-off path is used.
  • QEMU --icount 2: by the first heartbeat (t=36 s) md0 had served 3687 requests (78 MB), with launchd, gltest and the input daemon already up. Before: ~1100 requests and 32 MB by t≈120 s.

    • Much of that gain is an emulation effect. Single-threaded icount TCG shares one virtual clock between the CPUs, so the spinning ARM11 used to burn the time the ARM9 needed.
    • On hardware the gain is responsiveness: other threads, timers, VBlank and input keep running during disk reads.
  • Soak 2 (this change, 40 cycles):

    • PASS: no panic, stall, md0/log error, crash or jetsam; ~9,400 md0 requests served through the new lock/sleep path.
    • Spotlight cases (13, 14, 33, 34) recovered with a second Home.
    • The "Edit Home Screen" alert came back once, again on cycle 0, the first app launch after boot. So the IRQs-off freeze was not the cause.
  • Correction (soak 4, §39): the alert is not a hold. It is SpringBoard's one-time REORDER_INFO tip, remembered in the default SBDidShowReorderText, which a fresh rootfs (every QEMU soak) doesn't have. The timer analysis below is still accurate, but it wasn't what happened here.

  • Why a Home tap can become a hold (SpringBoard -[SpringBoard menuButtonDown:] 0x8bc0, _menuButtonWasHeld 0x8874, found through the objc method lists):

    • The down schedules scheduledTimerWithTimeInterval:… _menuButtonWasHeld with one of three intervals:
      • 2.0 s normally;
      • 1.0 s when a SpringBoard flag is set and allowAllInBackground (0x3ff00000);
      • 5.0 s while a sheet isOrderedFront (0x40140000).
    • menuButtonUp: cancels it. The daemon queues down and up together, so a hold only happens when SpringBoard needs more than 1–2 s between handling the two GSEvents. That happens on the busy first app launch after boot.
    • The remedy is a faster SpringBoard (GPU compositing, re-log 30 / agent/gpu), not the input path.
    • emu/soak.py allows one such "Dismiss + Home" recovery per run and fails on more, or on any "stuck" cycle.

32. Audio: "could not start DMA: device is not ready", fixed; PCM reaches CSND (2026-11-18)

  • Symptom (hardware runs 8-11): each UI sound (a tap, the Home key) logged AppleEmbeddedAudioDevice: could not start DMA: device is not ready and no stream ever started. Reproduced in QEMU: two Home presses, two errors (agent/audio2 build/evidence/run1-before.txt).
  • Where the message comes from:
    • The format string %s: could not start DMA: %s is in AppleARMIISAudio (0x80612e0c), printed by startDMA (0x80611b48) when 0x80611584 fails. The text "device is not ready" is IOKit's string for kIOReturnNotReady (0xE00002D8).
    • The call chain is 0x80611474 → 0x806113c8 → I2S controller vtable 0x358.
  • The PL080 is not the culprit:
    • startDMACommand (vtable 0x354, 0x807d00e4) does return NotReady for channel state ≤ 1.
    • But _initDMAChannel leaves channels at state 2, and the boot log shows channels 3, 4 and 5 initialised.
    • State map: 1 = allocated, 2 = ready, 3 = running.
  • The I2S controller's DMA start (AppleS5L8900X kext, 0x8066d448):
    • For i2s-version 0 (the DT has no such property, so the boot log reads "i2sVersion: 0") with frame sync requested, it sets state 1 (0x8066d490), enables its interrupt and arms a timeout.
    • It then sleeps on the state.
    • The interrupt action (0x8066caf0) moves the state 1 → 2 on one edge and 2 → 3 on the next. The timeout (0x8066cb84) sets 4.
    • Anything but 3 returns NotReady; a timeout returns 0xE00002EB.
  • That interrupt is GPIO pin 44:
    • i2s0's interrupts is the string ',' = 0x2c, and its interrupt-parent 0x0090c9a0 is /arm-io/gpio, not the VIC.
    • So the driver waits for two edges of a pin (presumably the word clock) to start DMA on a frame boundary.
    • The 3DS has no such pin, and the GPIO block is a fake page.
  • Fix: kernel patch i2s-start-no-lrck-sync (kernel/patches-audio.json): mov r3,#1 → mov r3,#3 at 0x8066d490.
    • The wait loop falls through as if synced. The interrupt is disabled and the timeout cancelled as on success.
    • A DT i2s-version ≥ 3 would also skip the wait, but it changes register and clock programming. Not taken.
  • QEMU CSND model (emu/qemu/hw/arm/ctr_csnd.c): plays channels from FCRAM on the virtual clock, ST_ADDR reads the play position, and a stereo mix sink logs [csnd] statistics and writes a WAV with IOS3DS_CSND_WAV.
  • Test client: ios3ds-tone (AudioQueue via dlopen; left = tone, right = half amplitude).
  • Run 2 (plain TCG): no more NotReady. The tone stream started (tx start ch5) and CSND played L/R at the exact amplitudes, but only 1,914 of 17,640 frames were tone.
    • The fragments are whole 1,024-frame AudioQueue buffers: underruns.
    • QEMU's guest runs about 3x slower than the 3DS (home screen at ~200 s vs ~70 s) while the audio clock is real time.
  • Run 3 (--icount 2): after the first seconds of boot, every 1 s tone is 44,099 frames, gap-free, 999 Hz, peak 5999 L / 2999 R: bit-exact.
  • Volume is not applied in the PCM:
    • Volume keys change neither the samples nor the codec level.
    • Each press writes one byte to the LM48821 speaker amp: ab a3 9b 8b 83 down, 8b … c3 up.
    • AppleLM48821Amp setGain (0x807b8108) maps whole dB to a 5-bit step (19 = 0 dB, 31 = +18 dB) and writes step << 3 | 3.
    • Its mute (0x807b8048) writes 0x04; its range is −38..+18 dB (0x807b800c).
    • Run 4: volume-up stops at step 31, volume-down goes 31 … 11 and then mute (0x04, plus CS42L58 regs 6 = 0, 0x1a = 0x80).
  • Shim volume mapping: a step becomes the CSND channel volume 10^((dB − 18)/20) (step 31 = unity) and 0x04 becomes 0.
    • It is applied to the running channels at the next service.
    • Run 4's recording follows it exactly: step 16 → peak 3007 = 6000 × 16422/32768; step 11 → 239.
  • Headphones:
    • iOS stays on its speaker route (no function-hp_detect), so its volume always arrives as amp steps.
    • The CSND volume is digital, so it applies to either 3DS output.
    • The ARM9 now polls the jack (GPIO2 bit 0, debounced) and repeats the init's HEADSET_SEL routing on a change.
  • Run 5 (final code, --icount 2, 85 tones):
    • Home pressed twice: 0 NotReady errors.
    • Volume swept up to step 31, down to mute and back up. Every recorded tone plays at exactly dB(step) − 18: step 22 → −12.0 dB, step 31 → 0.0 dB, step 11 → −34.0 dB.
    • While muted, 28.2 s of digital silence although tones kept playing; the level returned on the next step.
    • The ARM9 logs [audio] iOS volume: amp step N -> CSND volume V/32768.
  • Hardware safety: the patch only skips a wait for a pin the 3DS does not have. The volume path only writes CSND channel VOL. The tone client logs and exits on any AudioToolbox error. Jack polling only runs when the CODEC answered at boot.

33. RTC: the calendar from the 3DS MCU (2026-11-18)

Tools: the flat kernel image as an ELF (llvm-objcopy -I binary -O elf32-littlearm --change-addresses 0x80001000), llvm-objdump-18 --triple=thumbv6k-none-eabi, the LC_SYMTAB dump (scripts/ksym.py).

  • Who asks for the time. IOKitInitializeTime (0x801a8004, from bsd_init) = waitForService(resourceMatching("IORTC"), {t, 0}) (literals 0x801a8028 resourceMatching 0x801ae02d, 0x801a8030 waitForService 0x801b18f1), then clock_initialize_calendar (0x80014ba0, literal 0x801a8034).
  • clock_initialize_calendar (0x80014ba0): secs = PEGetGMTTimeOfDay() (bl 0x801c84d8), commpage_set_timestamp(0, …) (0x8006ade0, see §31), boot time at 0x80283e40 set once, clock_get_system_microtime (0x80069818), epoch at 0x80283dc8 = secs − uptime, offset via nanoseconds_to_absolutetime, adjustments cleared (0x80283de8), then host_notify_calendar_change (0x80016dcc).
  • PEGetGMTTimeOfDay (0x801c84d8, Thumb): gIOPlatform (0x8029d490) ? vtable +0x390 : 0. PESetGMTTimeOfDay (0x801c84f4): vtable +0x394. AppleARMPE's vtable (pointer to it + 8 = 0x802f483c): +0x390 = getGMTTimeOfDay 0x802e78ad (found by searching the image for that word: one hit, 0x802f4bcc), +0x394 = setGMTTimeOfDay 0x802e7835, +0x388 = haltRestart 0x801c8645 (IOPlatformExpert's).
  • AppleARMPE::getGMTTimeOfDay (0x802e78ac): waitForService(resourceMatching("IORTC"), {30 s}) (the rtc-wait-0s patch), getProperty("IORTC") (vtable +0x9c), OSDynamicCast(IOService), then callPlatformFunction("getGMTTimeOfDay", false, &t, 0, 0, 0) (vtable +0x1f8). So iOS expects a PMU driver to publish an IORTC resource whose value answers that platform function. setGMTTimeOfDay (0x802e7834) has the same 30 s wait and was never patched: a settimeofday() would have blocked for 30 s.
  • Chosen design: not a fake IORTC provider (a C++ object with a hand-made vtable in the shim), but the two C entry points: PEGetGMTTimeOfDay → shim_mcu_get_gmt and PESetGMTTimeOfDay → shim_mcu_set_gmt (Thumb ldr r3,[pc,#0]; bx r3; .word, as for mdevstrategy). The time comes from the ARM9's MCU mailbox (docs/mcu.md), filled before XNU starts. Without a valid RTC the shim runs the original body, so the fallback is unchanged.
  • The IORTC wait: the literal 0x801a8030 now points at shim_mcu_wait_rtc. With an RTC it releases the matching dictionary (vtable +0x14) and returns at once; else it calls waitForService with the 2 s of iortc-wait-2s. The reason for the 2 s (§26: calendar before AppleARMPE) is gone: the calendar no longer goes through the platform expert. The "0 ms" symptom it was blamed for was something else (§31).
  • QEMU (plain, build/emu-r2): [mcu] version 13/38: RTC 2026-11-17 23:21:31 Tue (offset 0 s) = Unix 1794957691, then ios3ds-mcu: 3DS RTC present: not waiting for IORTC, ios3ds-mcu: calendar from the 3DS RTC: 1794957691; no "RTC did not show up" line any more. SpringBoard shows 3:26 PM and the calendar icon "Tuesday 17" (host clock 23:26 UTC, iOS time zone US/Pacific).

34. gettimeofday() froze for up to a second: the commpage reciprocal (2026-11-18)

  • Symptom: gltest's first QEMU run with the RTC: gettimeofday … tv 1794957716.452931 -> 1794957716.452931; mach_absolute_time 221564 ticks = 212 ms, i.e. "frame took 0 ms" again although the calendar was now initialised early with a real time. So neither the IORTC wait nor secs = 0 was the cause (§26).
  • Userland: gettimeofday (libSystem, dyld cache 0x32ca92c4) calls __commpage_gettimeofday (0x32d4b748) first and only falls back to the syscall when it returns non-zero. That reads the commpage at 0x40000040: base abstime (+0), seconds (+8), microseconds (+0xc), limit (+0x10), divisor (+0x14), reciprocal M (+0x18), "add" flag (+0x20), shift (+0x24). Base 0 or now - base >= limit → syscall; else usec += q(now - base) with q = umulhi(d, M), add ? ((d - q) >> 1 + q) >> (shift - 1) : q >> shift.
  • Kernel: commpage_set_timestamp (0x8006ade0) recomputes M/add/shift (Hacker's Delight "magicu") whenever the divisor changes. Its caller clock_gettimeofday_set_commpage (0x8006948c) passes rtclock+0 (ticks per second) as the limit and rtclock+4 (ticks per µs) as the divisor. Read from QEMU (xp /16wx 0x20255128): 0x000ffb0f 0x00000001 0x3b9aca00 0x000ffb0f = 1047311 ticks/s, divisor 1, timebase 10^9/1047311.
  • Divisor 1: the algorithm overflows: M = 0, add = 1, shift = 0 (Python transcription; for 2 or 24 it is fine). Confirmed in QEMU (emu/tap.py --hmp "245:x /12wx 0x40000040"): 0x0f012b4f 0x00000000 0x6afce4c6 0x0002ba6f | 0x000ffb0f 0x00000001 0 0 | 0x00000001 0. Userland then shifts by −1, i.e. by 255: elapsed time is always 0. gettimeofday returns the value of the last syscall refresh until a second of ticks has passed. Every earlier symptom fits: "0 ms" frames, hardware run12/13 1063 ms vs mach_absolute_time 412 ms (the first sample was ~650 ms stale), and the QEMU differences between the 2 s and 0 s IORTC waits (just where the frame fell relative to a refresh).
  • Fix (commpage-gtod-off, kernel/patches-mcu.json): the beq at 0x8006adfc that skips the update when there is no commpage becomes b, so the timestamp is never published, the base stays 0 and userland always uses the (exact) syscall. Cost: one syscall per gettimeofday.
  • After the fix: plain QEMU gltest: timing: … tv 1794958858.470788 -> 1794958858.651883; mach_absolute_time 190712 ticks = 182 ms (181 vs 182 ms); --icount 2: 2254 ms both. ios3ds-mcud's cross-check: RTC +118 s, gettimeofday +117610 ms, mach_absolute_time +117613 ms (plain), RTC +153 s, gettimeofday +154086 ms, mach_absolute_time +154084 ms (icount, -rtc clock=vm).
  • mach_absolute_time is right: the timebase is consistent (10^9 / 1047311), and the shim's clock follows the MPCore watchdog.
  • Still inexact, but bounded: the kernel's own microtime path (0x8006916c) also adds raw ticks as microseconds inside a one-second window (rtclock+0x30 base): up to 4.7 % fast for under a second, corrected at the next full conversion.

35. Battery: an IOPMPowerSource from the shim (2026-11-18)

  • What SpringBoard reads: strings on SpringBoard (from the rootfs with build/tools/hfsplus … cat) shows IOPMPowerSource, CurrentCapacity, MaxCapacity, ExternalConnected, FullyCharged, IsCharging, ExternalChargeCapable, AppleRawBatteryVoltage, kIOPMPSAtCriticalLevelKey ("Shutting down immediately …"); its imports (arm-apple-darwin10-nm -u) include IOServiceGetMatchingService, IOServiceMatching, IORegistryEntryCreateCFProperty. The kernelcache has no battery driver the 3DS could use (the n72 PMU is a D1759 on I2C, deleted from our device tree).
  • Kernel KPI (LC_SYMTAB): IOPMPowerSource::powerSource() 0x801bb624 (new 0xa8 bytes + init() via vtable +0x44), setters setCurrentCapacity 0x801bb3fc, setMaxCapacity 0x801bb3d0, setIsCharging 0x801bb1f8, setExternalConnected 0x801bb288, setExternalChargeCapable 0x801bb258, setBatteryInstalled 0x801bb228, setVoltage 0x801bb348, setPSProperty 0x801bb0dc, updateStatus 0x801bb428 (copies the PS dictionary at +0x54 into the registry with setProperty (vtable +0x6c) when +0x50 is set, then messageClients(0xe0024100) = kIOPMMessageBatteryStatusHasChanged, vtable +0x238); IOService::attach 0x801adc54, registerService 0x801b0844, getPlatform 0x801ac744; OSSymbol::withCStringNoCopy 0x8019a5d0, OSNumber::withNumber(u64, bits) 0x80197684; release = vtable +0x14.
  • Gotcha: kOSBooleanTrue / kOSBooleanFalse (0x80232e4c / 0x80232e50) are C++ references: the words hold &gOSBooleanTrue (0x8029d168). Passing the word itself made OSDictionary::setObject call through a vtable at 0: sleh_abort: prefetch abort in kernel mode: fault_addr=0x0, lr 0x8018e521 (= OSDictionary::setObject+0x68), r0 0x8029d168 (QEMU run 1). Fixed by dereferencing twice.
  • QEMU (build/emu-r2, build/emu-r3): ios3ds-mcu: battery 100%, charger, 4200 mV: IOPMPowerSource registered; the status bar shows a full battery with the charging bolt; after qom-set /machine mcu-charging off + mcu-battery 50 a half-full battery without the bolt; with mcu-battery 15 SpringBoard's own "Low Battery — 20% of battery remaining" alert.

36. HOME, POWER, shell and shutdown (2026-11-18)

  • Input path: input_proto.h already reserved INBTN_HOME / INBTN_POWER, and ios3ds-input maps them to the Menu (0x40) and Power (0x30) usages. The ARM9 now ORs the MCU state into each input sample (mcu_buttons() in input_poll).
  • MCU IRQs (regs 0x10–0x13, clear on read; mask 0x18–0x1B, 1 = masked; libn3ds mcu.h): bit 0 POWER press, 1 POWER held, 2/3 HOME press/release, 5/6 shell close/open. POWER has no release IRQ, hence the tap/long-hold scheme (docs/mcu.md §3).
  • Halt: PEHaltRestart (0x801c98b0) waits (30 s deadline, 0x801c98d2) for the shutdown handlers for types 0/1/3, then gIOPlatform->haltRestart(type) (vtable +0x388 → IOPlatformExpert's 0x801c8645). The call site at 0x801c98f6 becomes adds r1,r5,#0; ldr r3,[pc,#0]; b +2; .word shim+0x38, keeping the original blx r3 at 0x801c9900; the shim forwards every other type to the platform.
  • Shutdown hang: sliding "slide to power off" logged launchd: System: About to call: reboot(RB_HALT)., then the CPU idled forever (heartbeat PCs all 0x80067b34, the idle WFI). SELECT+START dump, launchd's thread (annotated with scripts/btmap.py): _boot+0x7a → PEHaltRestart+0x3e (the blx at 0x801c98ec to 0x801db12b, IOPMrootDomain's halt/restart broadcast) → messageClient → IOMobileGraphicsFamily+0x2738 → AppleM2DisplayDrivers+0x4c40 (AppleM2CLCD disable_backlight) → AppleARMPlatform+0x4895/+0x6019 → AppleS5L8720X+0x17f0 → IOCommandGate::runAction → AppleS5L8720X+0x37cc → commandSleep. The S5L SWI backlight function waits for an interrupt that never comes. Patch pe-halt-skip-pm (0x801c98ec blx r3 → nop). Then: [mcu] iOS shut down: log synced, powering off through the MCU, and QEMU exits.
  • QEMU (build/emu-r3): h → [input] key 40 down/up and SpringBoard opens Spotlight (Home on page 1); c → [mcu] shell closed: locking iOS (POWER tap) → [input] key 30 down/up; c again → [mcu] shell opened. The lock press does not blank the screen in this build (SBDontLockEver; re-log §21 saw the same with SELECT), so the shell now also switches the LCD backlights off/on through MCU reg 0x22 (0x14 / 0x28, libn3ds MCU_LCD_PWR_*).

37. Volume, brightness, accelerometer (2026-11-18)

  • Volume: Celestial's AVSystemController (SpringBoard imports its notifications); selectors present in the dyld cache: sharedAVSystemController, setActiveCategoryVolumeTo:, getActiveCategoryVolume:andName:.
  • Brightness: SpringBoard's strings DisplayBrightness, DisplayBrightnessFactor, …FactorWithFade, …Auto; imports IOHIDEventSystemSetProperty. The keys occur once more in the dyld cache (IOKit's HID event system), so SpringBoard keeps its backlight state as HID event system properties; IOHIDEventSystemClientCopyProperty (0x337fce40) exists for clients. Kernel side: AppleARMPWMBacklight / AppleARMBacklight drive the n72 PMU through function-backlight_*, which our device tree does not have.
  • Accelerometer: the kernelcache has AppleEmbeddedAccelerometer (LIS302DL / LIS331DLH on I2C, IOHID event service); SpringBoard has SBAccelerometerInterface and com.apple.springboard.rawOrientation. IOHIDEventCreateAccelerometerEvent (0x337faca4): (alloc, timestamp r1:r2, x r3, y [sp], z [sp+4], options [sp+8]) → the common 3-axis creator with type 13.
  • QEMU (build/emu-r2/3): [mcud] volume slider 40/63 -> iOS volume 0.63; [mcud] iOS brightness 0.50 x factor 1.00 -> LCD backlight 500/1000 → qom-get lcd-backlight 79 (0x4F) and the dimmed screenshots; accelerometer raw -16384 0 0 -> iOS 0 -1 0 g (portrait) and 16384 0 0 -> iOS 0 1 0 after ] ].
  • Accelerometer events are ignored by SpringBoard. Its HID callback's type switch (0x51b1c: IOHIDEventGetType − 3, jump table; type 3 → 0x5028c keyboard, type 13 → 0x4fb44) and the accelerometer handler 0x4fb44 (reads fields 0xd0000–0xd0003; flag 0x18d3d1 = CFPreferencesGetAppBooleanValue("SBIgnoreAccelerometerEvents"), set at 0x50bf8; posts com.apple.springboard.rawOrientation at 0x4fef8, the name resolved from the literal at 0x4fed4) were never hit in 30 s of events: hardware breakpoints through QEMU's gdbstub (-gdb tcp::12347, emu/gdb/rsp.py). Same as keyboard/digitizer events in §19/§22. The handler is also reached from 0x50054, which polls accelerometer services with IOHIDServiceCopyEvent(service, 13, …); the way in is therefore a kernel service (Apple's LIS331DLH driver on an emulated I2C device), not a client. The daemon keeps the accelerometer off unless started with acc.

38. iOS shows the 3DS clock's time (2026-11-18)

  • The 3DS RTC keeps local time (it's set in the 3DS System Settings). The MCU driver (§33) hands it to XNU as UTC, and iOS then displayed it in its default zone, /private/var/db/timezone/localtime → US Pacific: RTC 00:27 Wednesday showed as 4:29 PM Tuesday.
  • rootfs/recipe.json now replaces that symlink with rootfs/files/localtime-UTC, a 54-byte TZif v1 file generated for this project (one ttinfo: offset 0, "UTC"; no Apple data). §50 replaced it with a symlink to /usr/share/zoneinfo/UTC: as a regular file it made CoreFoundation scan all of zoneinfo in every process.
  • iOS now shows exactly the 3DS clock: QEMU RTC 00:38 → status bar "12:38 AM", calendar "Wednesday".
  • To get a true UTC epoch plus a real zone instead, set rtc_offset= in boot.cfg and pick a zone in Settings (docs/mcu.md).

39. The "Edit Home Screen" alert was iOS's one-time tip (2026-11-18)

  • Soak 4 (main e9ddbba, all drivers merged, 40 cycles):
    • no panic, stall, md0/log error (19,008 md0 requests), crash or jetsam;
    • again only cycle 0 showed "Edit Home Screen" after leaving the first app.
  • Cause: the alert's strings are REORDER_INFO_TITLE / REORDER_INFO_BODY (SpringBoard.app English.lproj), and SpringBoard keeps the default SBDidShowReorderText next to them.
    • iOS shows the tip once, on the first Home out of an app on a fresh device, then sets the key.
    • QEMU soaks always start with a fresh rootfs, hence cycle 0 every time. On a real card it shows once and is remembered.
    • The §31 "Home seen as a hold" explanation was wrong.
  • Fix: rootfs/recipe.json's com.apple.springboard.plist now sets SBDidShowReorderText = true.
  • Soak recovery is now second Home, then Dismiss alone, then Dismiss + Home. Pressing Home after Dismiss on page 1 opens Spotlight, which soak 4 recorded as "stuck".
  • The same soak showed a GPU problem: mirror self-test: GPU operation 4 of 4 (PPF transfer) did not finish, register 0x00000000 in plain (MTTCG) QEMU. It was later reported as "self-test mismatch: 0 bytes differed". The CPU copy carried on correctly. Handed to the GPU work (agent/gpu).

40. Accelerometer: Apple's LIS302DL driver on an emulated sensor (2026-11-18)

  • Node: /arm-io/i2c0/accelerometer (compatible 'accelerometer,lis331dl|accelerometer,lis302dl', reg 0x1d, interrupts 0x63 on /arm-io/gpio, orientation 4). dt_audio deleted it with the PMU. The personality AppleLIS302DL (provider AppleARMIICDevice, match accelerometer,lis302dl) lives in com.apple.driver.AppleEmbeddedAccelerometer at 0x8061a000 (scripts/kexts.py Accel). The kext is ARM code: disassembled with --triple=armv6k, and literal loads annotated with LC_SYMTAB names and kext strings.
  • Base class AppleEmbeddedI2CAccelerometer (start at ~0x8061c5xx): an IOTimerEventSource (+0x8c, action 0x8061c314), a provider-less IOInterruptEventSource (+0x80, action 0x8061bf98) and one on the I2C nub's interrupt 0 (+0x78, action 0x8061c418). The interrupt one must exist or start fails. /arm-io/gpio already has AppleS5L8900XGPIOIC running on its fake page (AppleS5L8900XGPIOIC::start: gpioBaseAddress … in every boot log), so registration works; the interrupt itself never fires.
  • Polling: setProperties → ReportInterval (0x8061b988): values 1..9999 become 10000 (µs); then the timer is armed (vtable +0x8c) or cancelled (+0xb4). The timer action reads a sample through vtable +0x3f8 (0x8061b1b8), dispatches it (+0x3c0) and re-arms with the interval minus the time spent. So no interrupt is needed while SpringBoard wants data.
  • LIS302DL methods (vtable at 0x8061f7c4: +0x3f4 enable 0x8061b2e4, +0x3f8 read 0x8061b1b8, +0x3fc serviceInterrupts 0x8061b428). I2C helpers: read 0x8061be38, write 0x8061bed8, and a write with sub-address bit 7 (auto-increment) at 0x8061be80, all through the nub's transfer (vtable +0x35c).
    • Probe: read WHO_AM_I (0x0F); only the transfer result is checked.
    • Enable: CTRL_REG1 (0x20) |= 0x40; CTRL_REG2 (0x21) = 0x40 (BOOT), then poll 0x21 every 500 µs until bit 6 clears, panic after 1000 tries ("Boot bit did not return to zero"); CTRL_REG3 (0x22) |= 0xC0.
    • Read: OUT_X/Y/Z 0x29/0x2B/0x2D, one byte each, signed. Value × 1187 = 16.16 fixed g (≈ 55.2 counts per g). Then the DT orientation flags: bit 3 swaps x/y, bits 0/1/2 negate x/y/z.
    • serviceInterrupts: FF_WU_SRC_1 (0x31) bit 6.
  • Emulation (shim_mcu_iic, tools/ios3ds-mcu/shim/mcu.c): shim_iic_transfer (kernel/shim/audio.c) asks it first.
    • The nub is recognised by its reg property (getProperty("reg"), vtable +0x9c; OSData::getBytesNoCopy 0x8018d534), cached per nub.
    • BOOT reads back cleared, WHO_AM_I = 0x3B, STATUS (0x27) = 0x0F, FF_WU_SRC = 0, outputs from the MCU mailbox as in docs/mcu.md §6.2. CTRL_REG1 bit 6 switches the ARM9's sampling.
    • The shim has no divide instruction and no libgcc, so it has its own shift-subtract divide and integer square root.
  • QEMU (build/emu-a1: home screen only): probe at boot, sensor powered on once SpringBoard is up, but no samples. On an iPod touch the home screen does not rotate, so nobody sets ReportInterval. build/emu-a2 (Safari opened by a tap): samples start at Safari's launch; SpringBoard's com.apple.springboard.rawOrientation goes 0 → 1, → 4 for model pose 1, → 3 for pose 3, → 1 for pose 0. Safari's bookmarks view rotates both ways and back.

41. Lock turns the screen off: SBDontLockEver removed, clock-controller wait patched (2026-11-18)

  • SpringBoard reads SBDontLockEver with CFPreferencesGetAppBooleanValue at 0xb42c (Thumb; CFString at 0x15848c, found by resolving ldr/add pc pairs against the string's address) into a global flag, next to SBDontLockAfterCrash and others. With it set, a lock press (key 30) leaves DisplayBrightnessFactor at 1 (§21, §36).
  • Without it, first try (QEMU build/emu-l1…l5): key 30 → factor 0 → LCD backlight 0; HOME → factor 1. But the screens kept showing the frame from before the lock (clock frozen), and iOS blanked again after ~10 s unless touched. That was its lock screen, which never reached the display. The fake CLCD page (xp /4wx 0x1ffba000) read 00000003 00000010 … before the lock and 00000002 00000000 00000000 00000001 after the wake: AppleM2CLCD had not re-enabled the controller.
  • Cause: the same wait as the shutdown hang (§36): AppleS5L8720X+0x37cc, in AppleS5L8720XClockController, is a loop while (byte +0x38c) commandGate->commandSleep(+0x38c) after starting a performance-state change (flags from vtable +0x39c). The clear comes from a completion interrupt the fake clock/power page never raises. Display sleep lowers the performance state, so the CLCD's power path blocked there.
  • Patch s5l-perf-nowait (0x807517cc): ldrb r3,[r5,#0x38c]; cmp r3,#0; bne → mov r3,#0; strb r3,[r5,#0x38c]; nop.
  • Result (build/emu-l6): CLCD 00000003 00000010 after the wake. The lock screen shows "1:32 Wednesday, November 18", the charging battery and "slide to unlock". The slide returns to the home screen, and the clock advances (1:33, 1:34). The rootfs drops SBDontLockEver; SBDontLockAfterCrash and SBDisableAutoDim stay.

42. "Where is my backlight?" flood after lock/wake (2026-11-18)

  • Soak 6 (main + accelerometer + lock, 40 cycles): PASS, but the last [hb] line was at t=150 s, because the console was never quiet. After the first lock/unlock, AppleM2CLCD::safe_enable_backlight(), Where is my backlight? appeared 3,504 times, about 3 per second.

  • Three AppleM2CLCD functions share the format string %s, Where is my backlight? (VA 0x807b0b58, literal refs 0x807a9564/95c4/965c):

    • the level setter (0x807a9514);
    • disable_backlight (0x807a9570);
    • safe_enable_backlight (0x807a95d0).

    Each looks up the backlight service (bl 0x807a9490). When there is none, which is always on the 3DS, each only IOLogs (0x801a6be9) and returns. The flow is otherwise harmless; the cost was console/SD traffic. The 3DS backlight is driven by ios3ds-mcud through the MCU (§36, §41).

  • Patches clcd-backlight-log-set / -disable / -enable: the blx r3 (IOLog) at 0x807a9558, 0x807a95b0 and 0x807a9648 becomes nop.

  • The heartbeat stopped after ~100 s in every soak.

    • In QEMU, 70% of console lines are empty: 1,603 of them after t=111 s in soak 7, arriving in triples, starting right after iBoot version. Hardware logs (run9, run13) have none, so it is a QEMU-side artefact.
    • On top of that, the daemons now print real text every few seconds.
    • Fix: the monitor counts only non-whitespace console bytes as activity, and adds a heartbeat every 30 s regardless. QEMU: heartbeats at t=10, 20, 33, 61, 76, then every 30 s to the end.

43. Screen-off power saving; no system sleep; the CLCD backlight retry (2026-11-18)

  • System sleep with no way back: after a lock without SBDontLockEver, iOS slept the whole system after ~60 s (System Sleep, then AppleARMPL192VIC's vic[0] ena 00010000); the HOME press later reached nobody (QEMU build/emu-p1). The iPod wakes from the PMU interrupt, which the 3DS does not have. IOPMAssertionCreateWithName("NoIdleSleepAssertion", 255, …) (IOKit 0x337f0d78; the type string occurs 6 times in the dyld cache) held by ios3ds-mcud prevents it ([mcud] NoIdleSleepAssertion held; 94 s locked, then wake fine).
  • Where the screen-off cost was: the ARM9 monitor loop ran ~1700 iterations/s with the screen on and ~4400/s with it off (no copies to do, so it spun faster), reading the touch ADC over SPI each time. The ARM11 still took the VBlank (GIC 42) at full rate, although nothing was injected with the CLCD off. Changes and numbers: docs/mcu.md §9.
  • ARM9 WFI: the monitor runs with CPSR I/F masked (cpsr=600001d3 in every log). ARM9 timer 1 (prescaler 64, 2 ms) with IE bit 9 asserts the IRQ line; CP15 c7,c0,4 returns without taking the exception; IF is cleared by hand. QEMU's arm946 halts in WFI and arm_cpu_has_work wakes it on the pending line. Result: the ARM9 vCPU thread goes from 39 % to 2 % host CPU.
  • safe_enable_backlight (AppleM2CLCD, ARM, 0x807a95d0): bl 0x807a9490 (find the backlight) → NULL → IOLog("%s, Where is my backlight?", "void AppleM2CLCD::safe_enable_backlight()") and return, leaving byte +0xea0 (enable pending) set; the success path clears it (0x807a9634). Called per frame while pending, i.e. ~3/s for the rest of the wake (soak 6). Patch clcd-backlight-retry-off at 0x807a963c: the three IOLog argument loads become mov r3,#0; strb r3,[r4,#0xea0]; b epilogue (the IOLog call at 0x807a9648 is skipped, so main's nop of that call can coexist).

44. Notification LED (2026-11-18)

  • MCU register 0x2D takes a 100-byte pattern stream (3dbrew "MCU Services"; libn3ds McuInfoLedPattern, MCU_REG_INFO_LED): step time, smoothing, loop delay, unknown, red[32], green[32], blue[32]. The QEMU model already treated 0x2D as a stream register; it now records the pattern (mcu-led-rgb0, mcu-led-steps).
  • ARM9: boot.cfg notify_led=1 → red blink at ≤ 10 % battery without charging, off otherwise and before a power-off. QEMU: [mcu] notification LED blinking red: battery low (16 of 32 steps lit, 0xA00000), [mcu] notification LED off once the charger is back. The timing bytes are unverified, so the default is off.

45. Wi-Fi end to end in QEMU: an AR6014 + access point model (2026-11-18)

  • Goal: prove the whole chain (ARM9 driver → network mailbox → kern.ios3ds_net → ios3ds-wifid → iOS networking) without a console. Before this, Wi-Fi had only host unit tests.
  • Model (emu/qemu/hw/arm/ctr_wifi.c, docs/wifi.md §7): TMIO controller 2 at 0x10122000, an SDIO card (CCCR/FBR/CIS, function 1), the AR6014 BMI ROM and HTC/WMI firmware behaviour, and an access point with its own WPA2-PSK authenticator, bridged to -nic user (slirp). Power from CFG11_WIFICNT (mapped over the board's CFG11 page) and GPIO 2_2/3_12 (a small GPIO block at 0x10147000).
  • Written from the references, not from our driver:
    • ath6kl target.h: function-1 addresses (HOST_INT_STATUS 0x400, RX_LOOKAHEAD_VALID 0x405, lookahead 0x408, COUNT 0x420, COUNT_DEC 0x440, window 0x474/0x478/0x47C). htc.h: ENDPOINT1 = 0, so the BMI credit is COUNT_DEC + 4·4 = 0x450, the same register GBATEK calls COUNT4. sdio.c: one credit read before each BMI command, lookahead-valid wait before BMI reads, window address LSB written last.
    • dsiwifi (runs on real DSi/3DS hardware): 2-byte WMI command header, enumerated auth/crypto values (WPA2-PSK = 5, AES = 4), BSSINFO/CONNECT/DISCONNECT layouts, 00 1C data header, 0x4000 - len mailbox addresses, HTC_MSG_READY handshake.
    • IEEE 802.11i (PRF-384, EAPOL-Key, message checks), RFC 3394 key wrap, hostapd's RSN IE comparison.
  • First boot against the model: the unchanged driver went SDIO → BMI → upload → HTC → WMI → scan → associate → 4-way → keys → link up in 1.6 s of virtual time. Both installed keys were equal to the AP's (WMI_ADD_CIPHER_KEY pairwise ... equals the AP's TK, group ... equals the AP's GTK).
  • Driver changes (the model exposed some; the references require the others):
    • WMI and data use the endpoints from the CONNECT_SERVICE responses (status checked), not fixed 1/2.
    • The RX trailer is stripped only with HTC_FLG_RX_TRAILER (bit 1). Before, any flag counted.
    • Time-outs on the monitor clock: firmware start 3 s, HTC_READY and WMI_READY 5 s, scan 10 s. A missing HTC_READY used to wait forever in state htc.
    • A disconnect takes the link down and reconnects after 5 s. Before, it reconnected at once (a tight loop with a wrong PSK). Three failed handshakes log a psk hint.
    • FIFO self-test: after "SDIO up" the driver writes a pattern into the function-1 scratch registers with CMD52 and reads it back with one CMD53. If that fails, the mailbox falls back to CMD52 per byte. Reason: dsiwifi's 3DS ARM11 build reads TMIO2's data FIFO at +0x200000, not +0x10C, and nobody has tried +0x10C from the ARM9.
  • iOS side, seen in QEMU:
    • IOEthernetControllerGetIONetworkInterfaceObject + "BSD Name" gave nothing ([wifid] interface ? up). IONetworkStack names the interface 20+ s later (still no BSD interface with our MAC after 20 s, then interface is en0). The daemon now finds it by MAC in getifaddrs AF_LINK.
    • configd configures en0 by itself. The default network set does DHCP, IPMonitor adds the default route and mDNSResponder gets the DHCP DNS server. In the first run the daemon never ran ipconfig (no name yet), yet en0 had 10.0.2.15. ipconfig set is now only a fallback after 15 s without an address.
    • ios3ds-nettest (new; nettest= in wifi.cfg, passed through the mailbox, protocol version 2):
      [nettest] en0 address 10.0.2.15 netmask 255.255.255.0 (after 11 s)
      [nettest] default route via 10.0.2.2 (interface index 2)
      [nettest] dns example.com -> 172.66.147.243
      [nettest] http 10.0.2.2:8080/ios3ds-nettest -> HTTP/1.0 200 OK | ios3ds-wifi-test-aa4ee772 path=/ios3ds-nettest (185 bytes, 0 s)
      [nettest] all steps passed
      
      The host's HTTP server logged GET /ios3ds-nettest.
  • Status-bar Wi-Fi icon: not reachable. SpringBoard's Wi-Fi state comes from configd's WiFiManager.bundle. Its strings show it only drives an IO80211Interface/IO80211Controller through Apple80211 ("Could not obtain IO80211Interface bsd name"), so an IOUserEthernet en0 stays invisible to it.
  • Unverified on hardware (docs/wifi.md §6 lists the log line that settles each):
    • the ARM9 powering the chip and driving TMIO2;
    • the ARM9 FIFO at 0x1012210C;
    • the stub setting hi_board_data_initialized;
    • Type4 firmware answering HTC/WMI as modelled;
    • BSSINFO from an all-channel scan with BSS filter 1;
    • capability bits 0 in the firmware's association RSN IE;
    • dsiwifi's post-REG_DOMAIN host-interest write, which we skip.

46. CoreAnimation's compositor on the PICA200 (2026-11-18)

Design and RE notes: docs/gpu.md §7.

  • RE (QuartzCore in the user's dyld cache, 8C148): helper scripts resolved __picsymbolstub4 stubs through the indirect symbol table and disassembled all of __text (ARM). M2Display::M2Display (0x346de5b8) probes eagl_context(2), then (1), storing the API at +0x17c and the surface format at +0x180 from a literal pool: 'BGRA' (0x346de6a4) for API 2, 'L565' (0x346de6a8) for API 1. GLESContext::make_buffer_current (0x3470d274) binds the display IOSurface as a 0x84F5 texture via attachImage:toCoreSurface:invertedRender:NO, NEAREST/CLAMP, and attaches it to an FBO. glGetString is called with GL_EXTENSIONS and 0x8A1E (0x3470dd18/dd24).
  • Runs (QEMU, plain): (1) glBindTexture(0x84F5) and glGetIntegerv(0x84F8) errors, CoreAnimation: rendering error 500, black screen with one icon; (2) after accepting 0x84F5: GL error in GetString (traced with the new IOS3DS_GL_TRACE: engine+0x49bc → _api_GetString); (3) no errors, still black but one icon; (4) cause: glFlush was a no-op and glFinish synced only the bound framebuffer while CA flushes with FBO 0 bound — the GPU frames never reached the IOSurface; the one icon came from a draw that fell back to the CPU rasterizer. With flush_all the home screen appears.
  • Pixels: home screen GPU compositor vs software compositor, same moment: 2181 of 192000 screenshot pixels differ, by at most 1. Spotlight, keyboard, page swipes render the same way (later frames differ only where the two runs are at different animation times or the status-bar clock differs). --icount 2: same.
  • Gate: [gl] CA scene check: GPU vs CPU rasterizer: 6 of 9216 pixels differ by more than 24 (max 102), [gl] CA compositor: OpenGL ES on the PICA200 (GPU self-check and scene check passed); with boot.cfg ca_gpu=0: [gl] CA compositor: software (boot.cfg ca_gpu=0 or gpu=0) and the software compositor runs as before.
  • Cost (QEMU): per CA frame on the GPU path, render thread CPU 9.7–15.2 ms (plain), 19–27 ms (--icount 2), with one read-back of the whole display surface (~616 KiB) per frame. SpringBoard CPU in 60 s sampler windows during page swipes: GPU 4.97 / 7.05 s, software 4.16 / 5.40 s, i.e. ~25 % more in QEMU. QEMU runs CA's software compositor at host speed and models GPU operations with fixed delays, so this says little about hardware; the per-frame read-back (PPF + copy-out + per-pixel byte rotation) is the known overhead and the next thing to remove (docs/gpu.md §7). The [gl] CA: lines measure it on hardware.
  • App launch / exit: my own scripted taps right after the home screen came up opened nothing in either compositor (identical behaviour, not a rendering issue). emu/soak.py --cycles 6 on the GPU compositor (merged main): PASS, apps open (Game Center, Photos "Updating Library", Contacts, …; app-vs-home difference 39–99) and Home returns to an identical home screen (difference 0.0) every cycle; no panic, crash, stall or mirror failure; [gl] CA: 600 frames; per frame … render thread CPU 8933 us, 1.0 command lists, 1.0 read-backs (604 KiB).

47. Mirror self-test "mismatch" that was a timeout (soak 4) (2026-11-18)

  • Report (soak 4, plain MTTCG, main e9ddbba): [gpu] mirror self-test: GPU operation 4 of 4 (PPF transfer) did not finish, register 0x00000000, then self-test FAILED (0 bytes differ) and FAILED (self-test mismatch). The failure dump right after shows upload, texture and target exactly as expected: the read-out was late, not wrong. "4 of 4": the self-test mirrors one framebuffer set (upload, texture copy, draw, one read-out); live frames have 5 operations with two sets.
  • Why late: the QEMU GX model completes an operation from a virtual-time timer that needs the BQL; the shim's self-test polled GX registers in a tight loop (each MMIO read takes the BQL). On a busy host (several QEMUs) the timer can wait a long time. Measured with the merged (rel) QEMU on a loaded host: upload 44871 ticks, read-out 75494 ticks (~45/75 ms) for operations modelled at 0.4 ms — the 200 ms limit had a margin of ~3. Not reproduced as a failure in this worktree.
  • Fixes: 1 s per operation; thread-context waits poll in ~1 ms slices with a 10 µs IODelay between; the QEMU model runs due operations when a GX register is read; pm_selftest returns PM_SELFTEST_TIMEOUT with the operation and register, logged as self-test aborted, GPU operation N did not finish and reported as GM_WHY_TIMEOUT (ARM9: display mirror FAILED (GPU timeout: operation N of a frame did not finish, register …)). Host test: a hung GPU gives PM_SELFTEST_TIMEOUT, operation 3.
  • After the fix (plain QEMU, this worktree, merged main): self-test read-out ~55 ms → passes with margin; mirror active in plain and --icount 2 boots.

48. Timer interrupts while the screen is off (2026-11-18)

  • Shim counters (xp /24wx 0x20840040: +0x4C timer IRQs, +0x58 deferred FIQ retries, +0x78 VBlanks, +0x80 clock reads, +0x8C set_decrementer calls, +0x98 IRQs): with the screen on, 87 timer IRQs/s, 296 decrementer sets/s, 1363 clock reads/s. With it off, 140, 415 and 2055. No deferred retries in either.
  • Sampling (set_decrementer = shim+0x18, hardware breakpoint through QEMU's gdbstub, frame-pointer backtraces 18 deep):
    • User frames end in usleep (dyld cache 0x32c9f117), called from ios3ds-input 0x70bc and ios3ds-mcud 0x7008 (both ARM bl, read with llvm-objdump --macho), or in sleep (0x32ce31ef, ios3ds-wifid).
    • Kernel-only chains go through thread_call_allocate+0x2bc (0x80025019, the thread_call worker's block), through assert_wait_deadline+0x212, and through STRDUP+0x764 (0x8005c52d).
    • 0x8005c4f0 is XNU's serial_keyboard_poll: a loop calling the UART rx hook (0x8006b004 with 0,1,0,1), then clock_interval_to_deadline(16, …), assert_wait_deadline, thread_block, i.e. 62.5 wakeups/s forever, with nothing to read (our rx-ready patch always says no). The boot-arg serial=3 (bit 1 = keyboard) started it; serial=1 keeps the serial console without it. After the change the chain is gone from the samples, and console output is unchanged.
    • The thread_call worker's function call (blx r8 at 0x80024fa6) is mostly BSD networking callouts: ip_output+0x86f4, net_del_domain+0x5c and +0xb8, in6addr_local+…, sodisconnect+0xb9a, netboot_root+0x4 (nearest exported symbols). The mix is the same with the screen on and off; only their share of all timer arms doubles when off.
  • No CoreAnimation: no SpringBoard or QuartzCore user frames among the timer arms, so the guess in §43 was wrong.
  • Changes:
    • serial=1;
    • ios3ds-input at 10 Hz while screen_off (read from the MCU mailbox; samples queue in the ring, and hold timing now counts real sleep);
    • ios3ds-mcud at 4 Hz while off.
  • Result (QEMU): off 146 IRQs/s (143 timer) instead of 245; on 127 instead of 144; ARM11 vCPU thread 10 % instead of 14 % host CPU while off. Table in docs/mcu.md §9.

49. Microphone: iOS records the 3DS mic (2026-11-18)

  • No input at first: AudioSession reported input available 0, route "", and AudioSessionSetActive(PlayAndRecord)/AudioQueueNewInput failed with 'nopi'. An iPod2,1 records only from a wired headset.
  • Codec side: AppleCS42L58Audio's input data sources come from audio0 properties (0x80660294): line always, imic with ain2b-intmic, emic with ain2a-extmic. AppleEmbeddedAudio names them (0x80655a04). Adding ain2b-intmic alone changed nothing.
  • Routing: the decision is made by mediaserverd's HAL plug-in /Library/Audio/Plug-Ins/HAL/VirtualAudio.plugin (found through the HFS catalog; stripped).
    • It picks RoutingSettings_<product> by matching hw.model against a 4-byte table at file offset 0x287210 (K48 K93 K94 K95 K66 N18 N72 N81 N82 N88 N90 N92 N94).
    • N72 has no built-in mic port.
    • Patch (rootfs/recipe.json): the N81 slot (iPod touch 4G) reads N72, the N72 slot X72. Result: input available 1, route SpeakerAndMicrophone, speaker output and amp volume unchanged.
  • Data path:
    • The 3DS MIC block (0x10162000, GBATEK's DSi layout) runs at I2S2 / 4 = 11,901 Hz.
    • First version: drained by the ARM9 monitor loop. In QEMU it overran the 16-word FIFO constantly. It now runs in the shim (ARM11), which services every 1 ms while the mic is on; the 3DS's own mic service also runs on the ARM11.
    • The ARM9 powers the CODEC ADC while the shim says iOS records. boot.cfg mic=0 keeps everything off.
    • Safety: no data for 250 ms, a FIFO that never empties, or the block switching itself off each lead to one log line, mic off, and silence.
  • Findings on the way (QEMU):
    • iOS's input chain high-passes the input and adds a fixed +23.65 dB (×15.23; an 8000 sine clipped). The shim takes it off again (AUD_MIC_GAIN_Q15).
    • The 1 ms service deadline also has to hold while the RX channel is idle between two queued commands.
    • The mic must stay on across such gaps (1 s hold); switching it off there punched 50 ms holes.
    • With main's older md0 code (interrupts off while waiting), services stalled and samples were lost. Fixed by rebasing onto the md0-with-interrupts change.
    • Some recordings were corrupted, always bit-identically, by isolated spikes while the shim's own output was clean. Cause: the L/R word phase was carried over from the previous input stream; after an odd-length stream every frame straddled two. The phase now comes from the buffer address.
    • A 10 ms write-ahead of the input ring, tried first, made no difference and was removed.
  • Result (IOS3DS_MIC=sine:440:1000, real FIFO, icount 2): five of five recordings in RecordAudio (run 16) and five of five in PlayAndRecord with the speaker output running (run 17) fit 440.03 Hz at amplitude 1003.0, residual 41 dB. 0 overruns, 0 underruns, 0 resyncs.
  • Bit-exactness: iOS's own filtering makes app-level bit-exactness impossible. The host test shows it below iOS: a counter through the shim's FIFO drain and RX emulation arrives as an exact scaled, interpolated ramp, L = R in every frame, including after an odd-length stream.

50. Boot time and cold app launches under --icount 2 (2026-11-18)

  • Instrumentation (docs/boot-perf.md §1):
    • ARM9 ioprof=1/2 ([io] and [blk] lines; the shim passes xnu_bytes and buf_flags in blkmbox line 1) and log_ts=1;
    • [boot] phase stamps (the ARM9 clock now starts at a9_main, not at the monitor);
    • QEMU N3DS_PROF, which samples CPU(cpu)->halted and blkmbox seq/done_seq (PA 0x20846020/0x20846040) every 1 ms of virtual time;
    • emu/bootprof.py and emu/hfsmap.py. The latter is a small HFS+ parser: volume header forks, catalog leaf records (data and resource forks), extents overflow, journal.
  • Timestamp pitfall: the first stamp version put the stamp before a line's first character. The console sends \r and blank lines long before the text, so an [input] down was stamped 1.6 s early. The stamp now goes before the first visible character.
  • 5 s with nothing running after /dev/md0 on / (10.7–15.7 s): no md0, ARM11 0 %. launchctl imports _IOKitWaitQuiet (strings of /bin/launchctl, extracted with hfsplus) and calls it with a 5 s timeout.
    • ios3ds-diag -iobusy walks the IOService plane: IORegistryEntryCreateIterator(root, "IOService", recursive), then IOServiceGetBusyState and IOServiceGetState, all through dlsym because the stub SDK lacks them. It found clkrstgen and wdt (AppleARMIODevice, state 0xa: matched, not registered) busy 1, and AppleS5L8720XIO busy 2.
    • SELECT+START dump at 13 s, annotated with scripts/btmap.py: two matching threads in IORecursiveLockSleep ← IOService::waitForMatchingService+0xc0 ← waitForService+0x2e:
      • ← AppleARMPlatform+0x26f3/+0x2831 ← AppleS5L8720X+0x2f68 (AppleS5L8720XClockController::start);
      • ← AppleARMPlatform+0xa017 ← AppleS5L8900X+0x9d6c (AppleARMWatchDogTimer start via super::start).
    • Clock controller: 0x80750f38 formats "function-core_voltage_%ld" (literal 0x8075109c) and calls the lookup (literal 0x807510a4 = 0x802e4815). The lookup reads that property of the provider (vtable +0x94 getProperty), takes the phandle, builds a matching dictionary and waits with no timeout. A NULL result goes to panic("…Bad DPSM Tables in Device Tree") (0x807510a8, _panic 0x80015c7c).
    • Watchdog: 0x802ec006–0x802ec014: waitForService(serviceMatching("IOPMU") [0x802f089c], 0). On NULL it skips to 0x802ec02e: it only reads IOPMUBootDebug and then parses -s.
    • Patches (kernel/patches-boot.json):
      • wdt-no-pmu-wait: 0x802ec014 blx r3 → movs r0,#0;
      • clkctl-voltage-quiet: the literal → shim +0x28 shim_quiet_clk_function (kernel/shim/quiet.c). It calls IOService::adjustBusy(-1) (0x801aef24) on IORegistryEntry::fromPath("IODeviceTree:/arm-io/clkrstgen") (0x801aae60), calls the original lookup (still endless), and adds +1 if it returns.
    • Result: [iobusy] 0s: 0 of 80 services busy; wifid starts at 10.9 s instead of 16.8 s.
  • zoneinfo scans (hfsmap): 339 reads of /usr/share/zoneinfo/* at 19, 32 and 57 s; Settings' cold launch had 454 of its 571 chunks there. Apple's /private/var/db/timezone/localtime is a 30-byte symlink (staging rootfs). The re-log 38 regular file makes CoreFoundation look for a zone file with the same contents. Now a symlink to /usr/share/zoneinfo/UTC (recipe symlink, xpwn hfsplus symlink).
  • Mail at boot: [smp] showed MobileMail with 1.7 s of CPU after boot. Its Info.plist has UIBackgroundModes = (audio, continuous). SpringBoard's strings include autoLaunchIfNecessaryOnBootOrInstall: and Not autolaunching Mail since the SBDisableMailAutoLaunch default is set, so the recipe sets that default.
  • md0 sizes:
    • mdevioctl (0x80072a14) answers MAXBLOCKCOUNT/MAXSEGMENTCOUNT read/write with 32 (0x80072a9e). MAXBYTECOUNT gets ENOTTY, so vfs_init_io_attributes (literal pool 0x80087920–0x8008797c, mount fields 0x8b8–0x8d8) fails and the mount keeps MAXPHYS = 128 KiB.
    • Page-in runs from the VM pre-heat reach 1.7 MiB. The 800 KiB read at launchd start is the shared cache's code signature (cache offset 0x9ee4000, after LINKEDIT 0x8646000+0x189e000).
  • Numbers: docs/boot-perf.md §2. Rebased on 13ee8ec (microphone): settled at 26.5 s. soak.py with 20 cycles in plain QEMU, including the 130 s lock: PASS.

51. CoreAnimation frames without the CPU read-back (2026-11-18)

Design: docs/gpu.md §7 ("Presenting without the read-back"), docs/pica200.md §15.

  • Before: each GPU-composited CA frame was copied back by the CPU: PPF tiled→linear into arena scratch, READ into the IOSurface, per-pixel A,B,G,R → B,G,R,A rotation; ~616 KiB per frame (§46).

  • Now: a swizzle pass on the GPU (one quad, three TEV stages: tex.a·(1,0,0) + tex.r·(0,1,0) + tex.g·(0,0,1), alpha tex.b) writes iOS BGRA byte order into an arena buffer, and the new shim op PICA_OP_PRESENT (protocol 3) PPF-transfers it straight into the caller's IOSurface. Surface render targets get a power-of-two colour buffer (run 13: NPOT textures sample garbage on hardware) so the swizzle pass can sample it.

  • Page-table walk in the shim: the request carries a user VA; the shim reads TTBR0/TTBCR, walks L1 (section or coarse) and L2 (small or large page) for every page, and accepts only user read/write pages (AP = 3, APX = 0) that are physically contiguous and inside FCRAM or VRAM; then cleans+invalidates the range by VA (c7,c14,1) and runs the transfer.

  • First run (plain QEMU): refused: [pica] present: destination 0x00325000 (+614400) not usable: not user-writable (… L1 257ca001 L2 18000823 … TTBCR 2 DACR 00000001 …). L1 0x257ca001 = coarse table at PA 0x257ca000, domain 0; L2 0x18000823 = small page, PA 0x18000000, AP = 2 (user read-only), APX = 0; TTBCR.N = 2 (TTBR0 covers 0–1 GiB), DACR = client for domain 0. XNU's ARM pmap emulates the modified bit: writable pages stay AP = 2 until the first write faults. CA had never written the surface since mapping it (the GPU had). The engine now writes one word per destination page right before PRESENT. The read-back fallback kept the screen right meanwhile.

  • Second run: [pica] present: GPU writes the caller's surface directly: user VA 0x00325000 = PA 0x18000000 (VRAM, 600 KiB): CA's display IOSurface is AppleM2CLCD's scan-out framebuffer at the start of /vram, contiguous. [gl] CA: … 1.0 GPU presents, 0.0 CPU read-backs (0 KiB) from then on. Same lines in --icount 2.

  • Pixels: screenshots GPU vs software compositor at the same moments: home screen 1528 (plain) / 1582 (icount) of 192000 pixels differ, 43/49 by more than 24, all inside the status-bar clock (the runs show different times); the rest by ≤ 8. Spotlight with keyboard after 22/50 swipes: same, plus the text cursor. Mid-swipe frames differ where the runs are at different animation positions.

  • Cost, render thread per CA frame ([gl] CA: line): --icount 2: 6.3–7.2 ms over 1200 frames (four 300-frame windows), was 19–27 ms with the read-back (§46). Of that, ~2.7 ms is the shim polling for the QEMU GX model, which delays every P3D list by 1 ms and every PPF by 0.4 ms of virtual time (guesses, not hardware numbers); a CA frame is ~1.3 lists + the swizzle list + one PPF. Plain QEMU: 23 ms (the picasim rasterizer runs on the host while the vCPU polls; meaningless for hardware).

  • Cost, SpringBoard CPU in 60 s sampler windows during page swipes (same method as §46, plain QEMU, same build, ca_gpu=1 vs ca_gpu=0; 10 and 5 swipes in the two windows):

    • GPU: 6.00 / 6.48 s (user 2.10 / 1.89, system 3.90 / 4.59)
    • software: 4.39 / 5.30 s (user 2.62 / 3.50, system 1.77 / 1.80)

    User time is 20–46 % lower on the GPU path; the extra system time is the shim waiting for the GPU model (above). In QEMU the GPU path therefore still costs more in total; on hardware the waits are real GPU time (well under the modelled 1 ms for a 320x480 quad) and could become sleeps.

  • --icount 2, 50 swipes: SpringBoard 7.24 s for 24 swipes on the GPU path (0.30 s/swipe, user 0.17) vs software 17.86 s / 20 swipes and 17.21 s / 21 swipes (0.89 / 0.82 s/swipe, user ~0.8). Not a like-for-like number: the bench paces swipes in wall time, and with sleep=off guest time advances differently in the two runs (the GPU run's 50 swipes fell into 40 s of guest time, the software run's into 150 s), so the software run animated more frames per swipe. Per-frame numbers above are the reliable ones.

  • Fallbacks: a refused or failed PRESENT logs once and returns the process to the read-back; IOS3DS_GL_NO_PRESENT=1 forces it; boot.cfg ca_gpu=0 still selects CA's software compositor. Host test runs gltest twice (normal, and with every eligible target presented through IOS3DS_GL_PRESENT_ALL=1): PASS.

  • Unverified on hardware: the PPF writing VRAM the LCD path reads (the GPU mirror's own read-out works this way in QEMU only), the swizzle TEV stages, the walk's descriptor reading (ARM ARM v6 layout), and that no outer cache sits between the CPU's cleaned lines and the GPU. Each fails into the read-back, not into a wrong screen: a refused walk or GPU error directly, a wrong swizzle or row order through the present check (until one non-uniform frame matches, each present is compared with the CPU read-back of the same frame; a mismatch logs GPU present check FAILED and switches the process to the read-back; host test with R/B-swapped presents: caught, gltest PASS).

52. Wi-Fi in iOS Settings and the status bar: an Apple80211 bridge in configd, a keychain for securityd (2026-11-18)

  • Goal: Settings > Wi-Fi lists networks and joins one with a password typed on the on-screen keyboard; the status bar shows bars. Before, en0 (IOUserEthernet, §45) worked but iOS did not know it was Wi-Fi ("No Wi-Fi" in Settings, no bars), and the network had to be preset in wifi.cfg.
  • Who decides: configd's WiFiManager.bundle (MobileWiFi's server; Settings and SpringBoard are its clients). It only drives an IO80211Interface whose parent conforms to IO80211Controller, through Apple80211 ioctls SIOCGA80211/SIOCSA80211 and a PF_SYSTEM 802.11 event socket. Apple80211 is linked statically into WiFiManager (and a copy into IPConfiguration).
  • Design (agent/wifi3, docs/wifi.md §10): the ARM9 driver keeps the chip idle without wifi.cfg and executes scan/join(ssid, PMK)/leave from a control area wlanmbox_t (NET_PA+0xC200, sysctl kern.ios3ds_wlan); ios3ds-a80211.dylib, inserted into configd with DYLD_INSERT_LIBRARIES, interposes the IOKit lookups, SIOCGIFMEDIA, the Apple80211 ioctls (~25 request types, layouts from WiFiManager's code) and the event socket. The QEMU access point adds two decoys, NeighborNet (WPA2) and CoffeeShop (open).
  • Seen in QEMU, step by step:
    • WiFiManager's logging switched on from the dylib (LoggingEnabled/LoggingFile = /dev/console, now IOS3DS_WIFI_LOG=1): Could not obtain IO80211Interface bsd name. WiFiDeviceCreate reads "BSD Name" 31 times 10 ms apart and gives up; configd's InterfaceNamer names the IOUserEthernet interface 20+ s after ios3ds-wifid publishes it. The first-match notification is now deferred (it gets a class that never matches) and, once en0 exists, a timer on the run loop of the client's notification port hands the callback an IOBSDNameMatching(en0) iterator.
    • Some boots: Settings still "No Wi-Fi", no WiFiManager ioctl at all. Two configd clients register for IO80211Interface, in either order; the dylib only remembered the last one. Every registration is served now; run loops come from CFRunLoopAddSource of the port's source. Then: Device power state = ON, Device RSSI bounds (-95, -30), ~20 GET types, Settings: "Wi-Fi: Not Connected".
    • Settings was killed while launching: CrashReporter (read from the md0 image after the run) 0x8badf00d, "Settings failed to launch in time", main thread in UIKit layout, 10 s CPU. SpringBoard's SBNoWatchdogs (string in SpringBoard) is now set in com.apple.springboard.plist. Taps right after the home screen appears are sometimes ignored; Home first, then tap, works (wifi_ui_test.py retries).
    • Wi-Fi page: Async scan requested by "Preferences" → [a80211] scan requested → [wifi] iOS: scan → [a80211] scan done: 3 networks → Completed Apple80211ScanAsync (0); list: CoffeeShop (open), ios3ds-qemu and NeighborNet (lock icons).
    • Join: No password for ios3ds-qemu, Failed to join(-100), Settings: "Incorrect password". WiFiManager reads the password from the keychain (SecItemCopyMatching, service AirPort): -25300, and the keychain database had no rows. A probe SecItemAdd from configd returned -25308 (errSecInteractionNotAllowed): no keychain write ever worked on ios3ds.
    • securityd (8C148): items are CCCrypt'ed with a random key that AppleKeyStore wraps (selector 10, 32 → 40 bytes; 11 unwraps) with the class key from the system keybag; keybagd is disabled (§18: FATAL KEYBAG ERROR) and there is no IOAESAccelerator ("unable to access hwaes key", the 0x835 key, request layout at securityd 0xaacc: 76 bytes). New ios3ds-hwaes.dylib in securityd: AppleKeyStore open/KeyWrap/KeyUnwrap (RFC 3394 with a software key; host check against the RFC test vector) and IOAESAccelerator selector 1 in software. Probe: SecItemAdd -> 0.
    • Join again: SecItemCopyMatching -> 0, Attempting to join WPA network, [a80211] associate "ios3ds-qemu" (WPA2-PSK, PMK from WiFiManager, auth 1/8), [wifi] EAPOL event 1/2, [wifi] link up, Joined: ios3ds-qemu, Added ios3ds-qemu to list of known networks, ~30 s later Address: 10.0.2.15. Settings shows the check mark, the status bar the Wi-Fi bars (also on the home screen).
  • Association result race (found by the test's second run): WiFiManager disassociates (SET 22) right before associating (SET 20); the watcher saw state idle before the ARM9 had taken the join and reported "failed" (GET 21 = 9) while the join went on. The result is now judged only after ack_seq reaches the join's command number.
  • Display state: WiFiManager logs Device display is OFF at every boot and keeps auto-join off (and would run its 30-minute disassociation timer on battery): it reads notify state com.apple.iokit.hid.displayStatus, which IOKit's HID session code (IOHIDSessionCreate) handles on an iPod and nobody posts on ios3ds. The dylib mirrors SpringBoard's com.apple.springboard.hasBlankedScreen into it.
  • Keyboard: iOS 4's keyboard rows are at y 291/347/400/457 (measured on a Spotlight screenshot); after - the 123 page stays up. emu/session.py remembers the page between calls.
  • Test: emu/wifi_ui_test.py does it all through the touch screen: 8/8 PASS in 358 s (docs/wifi.md §10.5). A second boot of the same image, nothing touched, joins the known network by WiFiManager's auto-join (password from the keychain) and shows the bars. emu/wifi_test.py --case ok (HTTP fetch, preset network) and --case nocfg (no firmware, no wifi.cfg) still PASS; make test passes; emu/soak.py --cycles 10 PASS (no panic, stall, md0 error, crash or jetsam; Home always back; boot to SpringBoard + input 60 s).
  • Security: the keychain key is a constant in the dylib, so the keychain on the SD card is not bound to the console (docs/wifi.md §10.3).
  • Unverified on hardware: docs/wifi.md §10.6 (open scan without probed SSID, RSSI units, link-loss events, timing on a slow console).

53. New 2DS XL (issue #1): the shim's .bss was never zeroed (2026-11-19)

  • Log from the issue (docs/hwlogs/n3ds-issue1-run1.txt, build fe45ac4): ARM11 MPCore r0p5, SCU/SMP on, XNU up to BSD root: md0.
  • The fault: kernel abort type 4: fault_type=0x1, fault_addr=0xa5ff7918 at pc 0x80063000 (lck_mtx_lock), r0 = 0xa5ff7910, lr 0x80840bac (shim_mdevstrategy). The md0 mutex pointer was garbage.
  • Cause:
    • blk_lock / blk_lock_tried are zero-initialised statics in the shim's .bss.
    • kernel/shim/link.ld had .bss as its own NOBITS output section, so objcopy -O binary (scripts/mkboot.py) left it out of shim.bin. The ARM9 loads shim.bin and nothing more.
    • .bss therefore held whatever RAM had: zero on the Old 3DS and in QEMU by luck, not on the New 2DS XL.
  • Fix: .bss input sections now go into the .data output section, so shim.bin carries them as zeros (23088 → 23300 bytes). The GPU part already did this. QEMU boot unchanged.
  • Next on the New 3DS, if it boots further:
    • the [hb] clock: … ratio line shows whether the MPCore timers run at the assumed 134 MHz PERIPHCLK (the New 3DS can run the ARM11 at 804 MHz);
    • the New 3DS has an L2 cache (L2C-310).

54. Volume "does not change" on hardware (run14): output was 18 dB too low (2026-11-19)

  • run14: the slider changed iOS's volume ([mcud] volume slider ... -> iOS volume) and the HUD showed, but the shim saw no I2C traffic between stream starts, only amp step 13/19 at start and amp off at stop. The user heard only keyboard clicks.
  • QEMU (repeating 6000-amplitude tone, keys and qom-set /machine mcu-volume): the CSND recording's level follows both, e.g. peak 936 → 353 after five volume-downs, 2650 at slider 63. Since the VirtualAudio N81 patch (§49), iOS applies media volume in software and leaves the amp at a fixed step 19 (0 dB).
  • The bug: the shim's amp mapping still took step 31 (+18 dB) as CSND unity, so all media played 18 dB too quietly. Full volume gave a peak of 2650 for a 6000 tone: barely audible on the 3DS speaker, while UI clicks remain short and percussive.
  • Fix: AUD_AMP_REF_STEP 31 → 19: step 19 = unity, louder steps clamp, step 13 (UI sounds) = −12 dB.

55. Hardware run 15: depth tests drew nothing, the arena filled up, NPOT textures repeated their padding (2026-11-19)

Design: docs/pica200.md §16, docs/gpu.md §7.

  • Run 15 (f45dc07, ca_gpu=1): gltest's cube was drawn only with GL_DEPTH_TEST off (all 9 variants: drawn iff depth off), scene 1 GPU vs CPU 12070 pixels off by > 24 (max 230), scene 2 24900. CA ran on the GPU and passed its scene check (0 of 9216), but after ~2 min of use [pica] arena full: 1048576 bytes wanted, 828928 free in 78 blocks → [gl] pica: GPU arena full (texture): sampled as opaque black, then a 128 KiB request failing on every frame. The user's photos (Settings): black rectangles behind cells, light stripe garbage in the grouped table background.
  • Depth, cause: the back end stored GL depth as is (DEPTHMAP scale = far − near, offset = far; glClear = quad at z/w = 0 → depth exactly 1.0) with GL_LESS. Hypothesis: the PICA200's conversion of depth 1.0 to 24-bit wraps to 0, so every clear writes "nearest" and nothing passes. Modelled in picasim (fragment: depth ≥ 1.0 → 0, one quirk line); with the old convention the host gltest then fails with scene 1 12070 / max 229 and the cube missing, i.e. run 15 to the pixel. Everything homebrew does on hardware avoids 1.0: citro3d's C3D_DepthMap(true, -1, 0) + GPU_GREATER (far = 0).
  • Depth, fix: pica_raster_t.depth_conv: reversed by default (stored = K(1 − d), K = 1 − 2⁻¹⁰; scale −K(far − near), offset K(1 − far − bias); LESS↔GREATER, LEQUAL↔GEQUAL; new buffers start at 0). A depth probe at bring-up draws a depth scene (clear, LESS with a hidden and a visible quad, GREATER) under each convention against the CPU rasterizer and logs which match; reversed is used if it matches, else scaled standard, else depth-tested drawing goes to the CPU. Host: reversed 0 ok, standard 0 ok, unscaled (run 15) 4608 FAIL.
  • Arena, cause: not a leak (deletes free, exited clients are reaped when full). CA keeps one texture per visible layer image, many padded to 512×512 = 1 MiB; each render target also held a full-size linear staging buffer used only during transfers (1 MiB for the display); the mirror holds 1 MiB. 8 MiB does not hold it all, and nothing ever gave memory back.
  • Arena, fix: LRU eviction of texture copies on a failed allocation (re-uploaded from the engine's image on next use; the current draw's textures stay), staging buffers only for the duration of a transfer, and if memory still cannot be had the process writes back its GPU images, frees its arena memory and draws on the CPU from then on (one line). Black is no longer drawn for lack of memory. Shim's arena full line rate-limited. [gl] CA: line: GPU memory: N KiB held (T textures, K KiB), arena F KiB free, E evictions. Host gltest: 24 × 1 MiB textures through the 16 MiB model arena, each drawn twice: 0 of 48 wrong, 39 evictions, GPU on.
  • NPOT + GL_REPEAT: GPU textures were already power-of-two in memory, but a padded NPOT texture with REPEAT repeated at the padded size (coordinates scaled by w/pw). Such an axis is now stretched to the power of two on upload. CA scene check gained a 20×12 repeated 2D layer and a 20×12 rectangle layer, limit 1 %: old code 750 pixels (fails), new 6.
  • QEMU (rel's QEMU binary, i.e. the old depth model), --icount 2, 300 s, ca_gpu=1: depth probe … reversed (citro3d) 0 ok, standard 0 ok, unscaled (run 15) 0 ok: using reversed (citro3d) (the old model cannot tell them apart — the new picasim does; QEMU picks it up at its next rebuild), CA scene check: 6 of 9216, CA compositor: OpenGL ES on the PICA200, present check passed, home screen up, no panic.
  • QEMU soak, emu/soak.py --cycles 10 (plain, ca_gpu=1): PASS (no panic/crash/stall, apps open and Home returns). The model's arena filled too ([pica] arena full 4 lines, then one every 256th failure): [gl] CA: 300 frames … GPU memory: 3444 KiB held (62 textures, 1508 KiB), arena 3595 KiB free, 210 evictions, at 600 frames 2415 KiB held (60 textures, 1503 KiB), 4624 KiB free, 313 evictions — bounded, no black, no CPU fallback. Seen on the way (old behaviour, not changed here): one app surface was not physically contiguous (present: … not usable: not physically contiguous), and P.no_present then switched the whole process to CPU read-backs (0.0 presents, ~1 read-back/frame afterwards); per-surface refusal would keep the display on PRESENT.
  • Next hardware log should show: the depth probe line (expected unscaled (run 15) … FAIL, the others ok — confirms the wrap; if reversed fails too, depth goes to the CPU and the line says so), gltest cube centre is drawn … ok and all cube variants drawn, the CA scene check with the NPOT layers, and every 300 CA frames the GPU-memory figures with evictions instead of sampled as opaque black; at worst one this process draws on the CPU from now on line.

56. Wi-Fi firmware from the console in one GodMode9 step; [wifi-diag] bring-up log for the first hardware run (2026-11-19)

Design: docs/wifi.md §3 (firmware), §6/§6.1 (diag lines, model guesses). Run 14 had [wifi] 0:/ios3ds/wifi-fw.bin: not found (-4): Wi-Fi off.

  • Firmware, user side: tools/ios3ds-wifi/ios3ds-wifi-fw.gm9 (shipped by mksd.py as sd:/gm9/scripts/): find 1:/title/00040130/00002d02/content/*.app → ask → extrcode → 0:/ios3ds/nwm.code. Read-only on NAND (no allow, no SysNAND write permission asked); commands checked against GodMode9's scripting.c/HelloScript.gm9 (extrcode decrypts the NCCH and decompresses .code). GBATEK: 00002d02 is the normal-mode NWM on all 3DS models.
  • Firmware, loader side (nwmcode.c): without wifi-fw.bin, the ARM9 reads nwm.code into the top 4 MiB of FCRAM (before XNU runs), undoes BLZ in place if needed, finds GBATEK's literal pools (newer large pool; older large pool with type1/4 from its tail or the small pool), accepts text base 100000h or 10000h only when stub data/stub code/database are exactly 38h/316h/1E8h, builds the 'I3WF' container and zeroes the FCRAM copy. GBATEK's pool tables re-read for this entry: offsets match field by field (also nwmfw.py, which gained the older-pool tail). Host tests: the C loader and nwmfw.py produce byte-identical containers for newer/older/older-tail pools, type1/4/5, plain and BLZ; non-NWM input and wrong sizes rejected by both.
  • Direct NAND read rejected: needs an eMMC driver, CTRNAND AES with the console-unique keyslot (state depends on the boot chain), NCCH keyslot 2Ch and FAT; nothing of it testable in QEMU, and GodMode9 does it once already.
  • [wifi-diag] (wifi.cfg diag=1, default): one line per step with ms since power-up — CFG11/GPIO before→after, CFG9_SDMMCCTL, SD_OPTION, CMD5 tries + both R4 values, RCA/CCCR/bus width, function-ready polls, CIS MANFID, BMI version + register values, per-part upload time, BMI_EXECUTE result, time to hi_board_data_initialized, raw HTC_READY, per-service status/endpoint, raw WMI_READY, REG_DOMAIN, GET_CHANNEL_LIST as a channel mask, scan request, one line per network (SSID, BSSID, MHz/channel, RSSI, SNR, frame type, security) for the first 3 scans, SCAN_COMPLETE time/status/counts, unhandled events (≤ 24), WMI command … rejected always, longest driver step ≥ 20 ms, a summary line. A failure logs the stage, dumps the host interest area (after the upload), holds the chip in reset; iOS/md0 unaffected.
  • Timeouts added: warm-reset wait no longer blocks (100 ms on the clock), 30 s watchdog over the bring-up, iOS scan without SCAN_COMPLETE published after 10 s, HTC service failure now goes through fail().
  • QEMU (own QEMU build: rel's build/qemu has no slirp, -nic user fails): emu/wifi_test.py --case nwm PASS (BLZ nwm.code → firmware from 0:/ios3ds/nwm.code: 58774 bytes (BLZ-compressed), main type4, 31 ms, bring-up OK in 1836 ms, scan lists the 3 model networks, link up, DHCP, HTTP fetch); badnwm (one red line, card never powered), nofw, nocfg, ok PASS; make test passes. Not run this time: wifi_ui_test.py --nwm and the 10-cycle soak (cut for time).
  • Next hardware log should show (with nwm.code on the card): the fw: pool line (type4 size vs GBATEK's three), power: readbacks, sdio: CMD5 xN — the first unverified step; wherever it stops, the FAILED in stage … line plus the lines above it name the register or step (table in docs/wifi.md §6). If it gets through, the scan: lines are the network list Settings should show.

57. Hardware run 17: the console could not be woken after many locks (2026-11-19)

  • Run 17 (main 427680e, ca_gpu=1, powersave=0): many POWER and shell close/open locks. Every screen-off logged [gpu] screen copy: ARM9 CPU again (GPU frames stopped …) and every wake screen copy: PICA200 again a moment later: the mirror did resume each time. The shim skips frames while AppleM2CLCD's CLCD is disabled (display off), so "frames stopped" was only the display being off. The busy skips (207 → 225) are VBlanks that found a GL request on the GPU; busy = 1 is only held around one synchronous request (bounded by the driver's 1 s timeouts), so it does not leak.
  • What did break: the ARM9 monitor loop rate. 57-59 passes/s until [monitor] screen mode: bottom (X: log on the top LCD), then 34, 1 (during a wake) and 15. With the log console visible, every scrolled line repainted the whole console inside the log call: 30 × 50 glyphs, 64 pixels each, into both framebuffer sets, one function call and three byte writes into VRAM per pixel. The log is busy (touches, audio, [smp] dumps), so the loop, and with it input_poll/mcu_poll, ran about once per second. The last presses were not seen (no [input] key after the final lock).
  • Fixes:
    • (console.c) once the monitor loop runs, log text only goes into the buffers; the loop paints 2 changed rows per pass. draw_char writes glyph columns directly, with no call per pixel. Boot-time output is still drawn immediately.
    • (display.c, main.c) the CPU screen copy also polls the pad, touch screen and MCU (every 8 columns, at most every 10 ms) alongside md0.
    • (gpumirror.c) gm_live(now, display_on): a display that is off is not "frames stopped" (no log, no CPU copy), and after a wake the GPU gets 1 s to resume. Before, one 150-350 ms CPU copy ran on every wake.
    • (kernel/shim/pica.c) a VBlank that finds GL busy marks the mirror frame pending. New GL requests wait until the next interrupt that finds the GPU free has started that frame; the flag is cleared whenever the mirror is not active. In QEMU the first lockburst run showed 7 one-second CPU fallbacks with the display on while CA kept the GPU busy; with this change there were none.
  • QEMU, emu/lockburst.py --rounds 12 (new: X for the log console, then rounds of POWER lock/wake, shell close/open and four rapid POWER taps; powersave=0 as on run 17): PASS. 17 screen-offs, 16 wakes, 8 of 8 shell events seen, no ARM9 CPU again, the GPU copy never dropped, and iOS on screen at the end. Plain QEMU draws the console at host speed, so the loop rate there (≥ 544/s) cannot show the hardware cost; run 18's [power] … loops/s lines will.
  • Settings > Wallpaper shows an empty grey page in QEMU with ca_gpu=1 and with ca_gpu=0 (software compositor), so it is not a GPU or arena problem. Not investigated further here.
  • Run 17's depth probe: reversed 0 ok, standard 4608 FAIL, unscaled 4608 FAIL. Reversed depth works on hardware: gltest's cube is drawn now. The scaled standard convention also fails on hardware, which the depth-1.0-wraps model in picasim does not reproduce, so the model is still incomplete there. 4608 = half of the 96×96 probe.

58. Headphone jack: iOS switches its route (2026-11-19)

Design: docs/audio.md §3, §4, §6, §8 item 3.

  • Path: ARM9 polls GPIO2 bit 0 (debounced, as before) → aud_mic_t.jack → shim hp_service → pin 0x0d00 of the fake GPIO page (word +0x1a4 bit 0) + VIC0 source 12 injected like the DMA interrupt → AppleEmbeddedAudio's rebuilt function-hp_detect / audio0 interrupt (dt_audio.py). Started from the parked WIP 99f3a33; its QEMU GPIO hook moved out of ctr_wifi.c into a 4-byte window in ctr_csnd.c (machine property headphones).
  • QEMU run 1 (--icount 2, diag image, ios3ds-tone 12 × 12 s, toggles at 150/200/240/270 s): ios3ds-audio: headphones in, jack interrupt → tone: route change, reason 1 (new device available): "Speaker" -> "Headphone"; unplug → reason 2 (old device unavailable): "Headphone" -> "Speaker" (the iPod app's pause trigger; tone now pauses on it: tone: paused after 3240 ms). Volume HUD reads "headphones" (screenshots).
  • Found: on the headphone route iOS shuts the speaker amp down (0x04) — the shim turned that into CSND volume 0, i.e. silent headphones — plays the PCM unscaled (tone peak 5999 = 6000) and sets the volume on CS42L58 reg 0x1a: 7-bit two's-complement dB, bit 7 = mute. Slider → value: 0.51 → 0x64 (-28 dB), 0.63 → 0x6c (-20), 0.76 → 0x74 (-12), 0.89 → 0x7b (-5), 1.00 → 0x02 (+2); idle/stopped 0x44 (-60); 0x80 around route changes. Matches the driver's -60 dB / 1 dB range table (0x8065fb38) and clamp (0x8065f3a4).
  • Fix: shim CSND volume = 10^((dB - 2) / 20) from reg 0x1a while iOS is on headphones (hp_gain, +2 dB = unity, so full volume = full scale as amp step 19 on the speaker), the amp's otherwise; the switch re-evaluates it. Host test covers both routes, mute, clamp, re-plug.
  • QEMU run 2 (same image): headphones 63/63 → CS42L58 02 (2 dB) -> CSND volume 32768/32768, 40/63 → 6c (-20 dB) -> 3277; unplug, speaker slider to 20/63, re-plug → 6c (-20 dB) again (separate volume memory), 48/63 → 74 (-12 dB) -> 8231; speaker streams back at amp step 19 = unity. HUD screenshots: headphones 63/63, speaker 20/63, headphones 48/63.
  • QEMU run 3 (default image, final code, --time 300 --icount 2): plug/unplug/plug → [audio] iOS route -> headphones|speaker (jack change #1..3 passed to iOS), HUD "headphones" at 56/63, speaker HUD at 16/63; no panic. make test OK; emu/soak.py --cycles 10: PASS (no panic/hang/jetsam; the one "SpringBoard restart" is the boot connection, as in earlier soaks).
  • Fail-safe (unverified on hardware): GPIO2 bit 0 = jack, 1 = plugged (libn3ds; hardware boots log "speaker" with nothing plugged, so 0 = unplugged is consistent). Reads "plugged" at boot → iOS stays on speaker until it reads "unplugged" once ([audio] jack: GPIO2 bit 0 reads 'plugged' at boot ...); > 8 changes in 10 s → iOS on speaker until reboot ([audio] jack: GPIO2 bit 0 changed N times ...). boot.cfg hp_route=0 turns the iOS side off (CODEC still follows the jack).
  • Next hardware log should show (plug, play, unplug): [audio] headphones plugged in: CODEC output -> headphones, iOS route -> headphones (CODEC headset detect XX) and unplugged ... (CODEC headset detect YY) — settles the bit and its polarity (XX ≠ YY would mean the CODEC's own detection agrees; QEMU's CODEC stub reads 91 both ways); [audio] iOS headphone volume: CS42L58 .. -> CSND volume .. while playing; sound only from the headphones while plugged. If the polarity were inverted the boot line would already say "headphones" and the speaker would be silent (it is not, runs 14-16).

59. Wi-Fi firmware without GodMode9: the launcher reads NWM's .code through Horizon's FS (2026-11-19)

Design: docs/wifi.md §3.1 (launcher), §3.2 (GodMode9 fallback, unchanged).

  • What: tools/ios3ds-launcher/main.c fetch_nwm_code() (launcher version 2). On the normal start screen, when neither sd:/ios3ds/nwm.code nor wifi-fw.bin exists, it opens NWM's exefs:/.code (title 0004013000002D02, MEDIATYPE_NAND) read-only, reads it in 64 KiB chunks with an on-screen KiB counter, checks 64 KiB ≤ size ≤ 4 MiB and bytes read = size, writes nwm.code.tmp and renames it to nwm.code, zeroes and frees the buffer. Any failure: one red line, nothing left on the card, the launch goes on with Wi-Fi off. Skipped once the file exists.
  • Lowpaths: archive 0x2345678A with {tid_lo, tid_hi, mediatype, 0} (libctru romfsMountFromTitle, FBI listtitles.c/extractsmdh.c, Checkpoint smdh.cpp); file {0 high-level NCCH, 0 content index, 1 exefs:/.code, ".code" as 8 bytes} (3dbrew "Filesystem services" title-access tables; FBI/Checkpoint use the same 20-byte form with type 2 + "icon"; Luma3DS loader.c codeContentPath = type 1 + ".code" in 0x2345678E).
  • fs:USER vs FSPXI: 3dbrew's "FS Limitations" for title access: fs:USER allows only RomFS, System Menu Data and the seed checks, not exefs:/.code; FSPXI allows all. The launcher still tries FSUSER_OpenFileDirectly first, then (only under Luma3DS, checked with svcGetSystemInfo(0x10000)) borrows a PxiFS0 client session with Luma's svcControlService(SERVICEOP_STEAL_CLIENT_SESSION) (SVC 0xB0, inline asm; same call as Checkpoint archive.cpp) and uses FSPXI_OpenArchive/OpenFile/GetFileSize/ReadFile. Disassembly checked: r0 = 0, r1 = &handle, r2 = "PxiFS0" at the svc 0xB0; the two lowpaths in .rodata as above.
  • BLZ: FS hands out the ExeFS file as stored (Luma's loader decompresses .code itself when compress_exefs_code is set), so the written file is normally BLZ-compressed; nwmcode.c already accepts that (emu/wifi_test.py --case nwm uses a BLZ file).
  • Verified: make launcher builds without warnings (local devkitARM/libctru; CI job firm builds the same target). Not verified: any of it on a console (no hardware run yet); whether Process9 accepts the FSPXI .code open from a .3dsx session; the actual NWM .code size.
  • Next hardware run should show on the launcher's top screen: <k> / <k> KiB via FSPXI (or via FS) then Wrote /ios3ds/nwm.code (<n> bytes), and in the ios3ds log [wifi] firmware from 0:/ios3ds/nwm.code: <n> bytes (BLZ-compressed), main type4. A red cannot open NWM .code (FS …, FSPXI …) line gives both result codes; then use the GodMode9 script (§3.2).

60. Cydia pre-installed: Telesphoreo base system unpacked into the rootfs at build time (2026-11-19)

Design and user docs: docs/cydia.md. Code signing was already off, so "pre-jailbroken" only needed the packages.

  • Repository state (2026-11): http://apt.saurik.com/dists/tangelo-3.7 (= dists/ios, 364 packages) still serves the iphoneos-arm pool; debs/*.deb 302-redirects to cache.saurik.com. Old 2011 bootstrap versions are mostly gone; the newest ones still run on armv6: Cydia 1.1.30 is fat armv6+arm64 with LC_VERSION_MIN_IPHONEOS 2.0 and links only libraries 4.2.1 has (libstdc++, WebCore/WebKit, SpringBoardServices, libapt-pkg 4.6). Every Mach-O in the 32-package set has an armv6 or CPU_SUBTYPE_ARM_ALL slice (audit script over the debs, none armv7-only). Set = closure of Cydia's Depends/Pre-Depends + all Essential: yes; download sizes and MD5s match the index; pinned with sha256 in rootfs/cydia.json.
  • Maintainer scripts read one by one: Cydia's postinst is an arm Mach-O (strings: makes /var/mobile/Library/{Cydia,Caches/com.saurik.Cydia} as mobile, migrates /var/db/stash); firmware.sh writes the firmware/cy+*/gsc.* virtual packages from sw_vers, sysctl, gssc, cfversion; firmware-sbin ships empty /sbin/fsck, mount, ... and its pre/extrainst restore Apple's files (we keep the stock ones); pam/pam-modules preinst stash /usr/lib/pam; uikittools extrainst rebuilds the installation cache; ncurses preinst handles an old /usr/lib/_ncurses. Only the effects that matter are reproduced; /.cydia_no_stash (checked by the Cydia binary) skips stashing, which only helps a two-partition iPod.
  • hfsplus: xpwn follows symlinks in path components (add /var/x lands in /private/var/x), new files/folders inherit the parent's owner (root under /usr, 501 under /var/mobile as dpkg would give), chmod keeps setuid (cydo 06755). addall can't be used (it follows symlinks and would write into a symlink record), so scripts/cydia.py walks each tar: 978 entries, ~1460 hfsplus calls, 4-8 s.
  • QEMU (wifi4's QEMU, has slirp): boots to SpringBoard (page 2: Cydia icon); Cydia launches in ~10 s into its UI, no "Preparing Filesystem"; Installed lists the packages. First launch wrote Cydia's own defaults (ios/550.52, BigBoss, ModMyi, ZodTTD, repo666.ultrasn0w.com) to Caches/com.saurik.Cydia/sources.list and symlinked cydia.list to it, so the build writes no source lists (an earlier saurik.list duplicated it). The boot-time firmware.sh ran in the guest: status gained 24 gsc.* packages. With ctr-wifi + slirp: refresh fetched apt.saurik.com_dists_ios_550.52_main_binary-iphoneos-arm_Packages (174237 B) and BigBoss's (8.2 MB); Sources > Cydia/Telesphoreo shows its sections; installing cpio from Cydia gave cpio 2.9-2p "install ok installed", /usr/bin/cpio, info/cpio.list. HTTPS pages (home, depictions) fail: "certificate for this server is invalid" (4.2.1's root store). emu/soak.py --cycles 10 after that: PASS (0 panics/stalls/crashes). Screenshots: build/emu-cydia/ (not committed).
  • Not done: Cydia Substrate (would add DYLD_INSERT_LIBRARIES everywhere next to our configd/SpringBoard environment; left for a separate test).

61. Current root certificates: user anchors in securityd's TrustStore.sqlite3 (2026-11-20)

Design and user docs: docs/certificates.md.

  • Where 4.2.1 keeps roots (8C148 /usr/libexec/securityd, ARM, disassembled with capstone): 174 system anchors are compiled in (__DATA,__const 0x496e4 = {len, ptr, flags}; normalized-subject hash table 0x49f1c, lookup 0x7f80..0x8360); no anchor file exists in Security.framework. User anchors: /Library/Keychains/TrustStore.sqlite3 (literal path, 0x17b8c; /Library/Keychains -> ../private/var/Keychains, owner _securityd), opened at 0xa204, schema tsettings(sha1,subj,tset,data). Contains (0x9a44) = row exists for the SHA-1 (tset unused); CopyParents (0x9aec) = rows whose subj equals SecCertificateGetNormalizedIssuerContent(child). SecPathBuilderInit (0x8e40) appends system (0x8364/0x8430) and user (0x67c8/0x67a0, SecTrustStoreForDomain(2)) anchor sources to the parent and anchor sources unless anchorsOnly; evaluation runs in securityd for every client, so a row there is a root for Safari, Cydia and all apps.
  • Normalized subject: RDN SET contents with PrintableString values upper-cased, trimmed, space runs collapsed, other string types kept, lengths re-encoded. scripts/certs.py reproduces all 174 compiled-in normalized subjects byte for byte (146 differ from the raw subject).
  • Algorithms: Security.framework (dyld cache) has md5/sha1/sha256/sha384/sha512-with-RSA OIDs, imports CC_SHA224..512, but only ecdsa-with-SHA1 and no P-256/P-384 OID: EC roots skipped (40 of Mozilla's 121). 18 of the compiled anchors are RSA-4096, and RSA-4096 roots verify (ISRG Root X1).
  • Build: recipe trust_store -> scripts/certs.py writes the DB (SQLite format 4, rollback journal; iOS has SQLite 3.6.23.2) from rootfs/certs/roots.pem (81 RSA roots: Mozilla via Ubuntu ca-certificates 20260816, plus GTS Root R2 from an older certifi). ios3ds-nettest fetches https:// URLs (wifi.cfg, or body lines of the test server's answer) through CFNetwork, looked up with dlsym (the stub SDK has no CFNetwork); emu/wifi_test.py --https.
  • QEMU (wifi4's QEMU, ctr-wifi + slirp, --icount 2), stock store vs new store: cydia.saurik.com -9807 -> 200; tls-v1-0.badssl.com (Let's Encrypt, ISRG Root X1) -9807 -> 200; Cydia's home page now loads; Safari shows tls-v1-0.badssl.com and https://www.google.com with the lock icon. Still failing: moreinfo.thebigboss.org (all-SHA-384 Sectigo chain, -9807 with both roots present; cause in the signature check not pinned down), letsencrypt.org and other TLS-1.2-only servers (-9836 errSSLPeerProtocolVersion). Controls untrusted-root/expired.badssl.com stay -9807. nettest's bare CFNetwork GET to www.google.com gets -9806 while Safari loads it (not a certificate issue). No opt-in bypass was needed.

62. Settings > Wallpaper empty: no DeviceClass from the lockdown stub, and 'L555' album surfaces; app NSLog on the console (2026-11-20)

  • App logs. SpringBoard gives apps a stderr only for a debug launch. -[SBApplication _addInternalDebugVariablesToEnvironment] (SpringBoard 0x26fd0, called from the launch path at 0x2ba04) reads SpringBoard defaults: SBMallocStackLogging, SBMallocGuardEdges, SBMallocCheckHeap*, SBZombieEnabled, SBDeallocateZombies and SBGuardMalloc[Always]; the last adds DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib to every app's environment (the non-Always keys are one-shot: removed after use). The device has no libgmalloc, so the rootfs now links that name to ios3ds-applog.dylib (tools/ios3ds-diag/applog.c) and sets SBGuardMallocAlways; SpringBoard gets the library from its plist. Active only with boot-arg ios3ds_diag=1 or ios3ds_applog=1 (boot-perf.md §3): CFLOG_FORCE_STDERR=1, stdout/stderr → /dev/console (0622 in devfs, so mobile can open it), [applog] lines for alert titles/texts (UIModalView/UIAlertView setters + popup, objc runtime via dlsym) and the view tree on each viewDidAppear:.
  • Bug: Settings > Wallpaper shows an empty page (QEMU, both ca_gpu=1 and ca_gpu=0). With no photos, Wallpaper.bundle's -[WallpaperController specifiers] points the preview straight at WallpaperAlbumController; the view tree showed WallpaperAlbumPane > PLAlbumView > PLHighlightingTableView with no cells. -[WallpaperAlbum init] (0x3713a0a4) builds /Library/Wallpaper/<model>, model = -[UIDevice model], which was "Unknown": UIKit 0x338831a8 asks lockdown_copy_value(conn, NULL, kLockdownDeviceClassKey), and our liblockdown stub (re-log 18) knew only ActivationState and BrickState. So the album looked in /Library/Wallpaper/Unknown.
    • Fix 1: lockdown_copy_value (cache 0x684b8e0) is now a table lookup: {key variable, value} pairs in the dead body of lockdown_copy_buid_identity (0x684b9b4, stubbed to return 0), compared by pointer to *kLockdown…Key (the callers use liblockdown's exported constants), plus new constant CFStrings (the recipe checks that 208-byte region by orig_sha256, new in mkrootfs, so no Apple code goes into the recipe; isa __CFConstantStringClassReference 0x3e925550, flags 0x7c8) for "iPod2,1", "4.2.1", "8C148", "N72AP". Values: ActivationState "Activated", BrickState false, DeviceClass/DeviceName "iPod" (UIKit's CFSTR), ProductType, ProductVersion, BuildVersion, HardwareModel. Keys referenced in the cache (non-lazy pointers to the key variables): DeviceClass (UIKit, MobileSync), DeviceName, ProductType (GameKit, ManagedConfiguration), ProductVersion/BuildVersion (UIKit, GameKit), HardwareModel (GameKitServices), UniqueDeviceID (left NULL). UIDevice.model is now "iPod touch"; the album finds 31 wallpapers (/Library/Wallpaper/iPhone and iPod; the name regex is ^(\d+)(_\w+)*[^thumbnail]<scale>\.png$, scale "" since PLScreenScale() = 1).
    • Then, ca_gpu=1 only: the grid stayed white; [gl] IOSurface pixel format 'L555' not supported + GL error 0x501 from BindCoreSurface. PLAlbumViewCell setCGImageRef: puts one CGImage per row into contentView.layer.contents; the thumbnails are baked by MLPhotoBakedThumbnails in MusicLibrary's formats, which come from lockdown_copy_value(Checkpoint domain, "ImageSpecifications"), else /System/Library/Lockdown/Checkpoint.xml (format 3011 = 79×79, PixelFormat 'L555'). The rows are IOSurface-backed, and CA binds the surface as a texture. CA's software compositor reads them (ca_gpu=0 showed the grid).
    • Fix 2: tools/ios3ds-gl/iface.c converts 'L555' (and 'L565') surfaces bound to a texture target into a 32 bpp copy ([gl] IOSurface pixel format 'L555' texture: converted to 32 bpp at bind, once).
    • QEMU (ca_gpu=1): the grid shows all thumbnails; tapping one opens "Wallpaper Preview" (PLWallpaperImageViewController), Set returns to the grid, and after lock (charger off, so the big battery does not cover it) the lock screen shows the chosen wallpaper.
  • Status bar "Searching…" comes from -[SBStatusBarDataManager _updateServiceItem] whenever +[SBTelephonyManager sharedTelephonyManagerCreatingIfNecessary:] returns a manager; unrelated to the lockdown values and not changed here.
  • "Invisible alert after boot" (dimmed home, taps ignored until (160,333)): not reproduced. 9 QEMU boots (ca_gpu 1/0, diag 0/1, plain and --icount 2, before and after the lockdown fix): no [applog] … alert line and the first icon tap opened its app each time; the dimming in screenshots is the emulated LCD backlight (lcd-backlight 500/1000 scales the mirror), not an alert. A real alert does render on the PICA200: qom-set mcu-battery 15 → [applog] SpringBoard alert shown, title "Low Battery", drawn with its Dismiss button at y≈283. SpringBoard's single-button "Dismiss" alerts (sb strings DISMISS_ALERT, LOW_DISK_SPACE_DISMISS): SBLowPowerAlertItem, SBDiskSpaceAlertItem (kqueue VQ_LOWDISK; the 1 GiB rootfs has 378 MiB free, HFS warns below 10 %), SBDismissOnlyAlertItem from SBLockdownManager (only with telephony), the thermal check, and the unusable-FireWire-charger check (AdapterInfo = 0xe00002c7). Next time it shows: boot with ios3ds_applog=1 (or diag=1) and read the [applog] SpringBoard alert … lines.

63. 30-cycle soak at hardware timing: a half-copied home screen after a long lock (2026-11-20)

  • Run: emu/soak.py --cycles 30 --icount 2. No panics, stalls, crashes or md0 errors. The soak counted "SpringBoard restart" once, but that entry is the first [input] connected line, not a restart. Flagged:
    • cycles 9 / 19 / 29 (after a 130 s lock):
      • cycles 9 and 29: a full home screen. Its difference to the reference (15.5 / 16.8, threshold 12) is the dimmed fade-in after unlock plus the clock. The backlight is back at 500/1000, as before the lock.
      • cycle 19 (35.0): a black screen with a sliver of the first icon row.
    • cycle 13: HOME on page 1 opened Spotlight (known soak behaviour).
  • Cause of cycle 19:
    • At wake, [gpu] screen copy: ARM9 CPU again (GPU frames stopped: state ACTIVE, 305 busy skips, 0 timeouts).
    • gm_live allows 1 s after the display comes on for mirror frames to resume.
    • After a long lock, CoreAnimation redraws everything with GL and holds the GPU, so the shim skips mirror frames as busy.
    • The ARM9 took that for a stall and switched to its CPU copy. Under --icount 2 that copy is slow, so the screenshot caught a half-copied frame.
  • Fix: boot/arm9/gpumirror.c counts a changing busy_skips as progress, for at most 3 s per busy stretch.
  • Re-run (10 cycles, long lock at cycle 9):
    • The unlock screenshot is the full home screen (diff 12.8: fade-in and clock).
    • The CPU fallback still fired once, briefly, and switched straight back to PICA200.

64. Gyroscope: how 4.2.1's CoreMotion finds a gyro, and a gyro service from Apple's accelerometer kext (2026-11-20)

Design and user docs: docs/mcu.md section 11. Disassembly from the dyld cache (build/toolchain/cache/dyld_shared_cache_armv6, CoreMotion at 0x3320d000, ARM code) and the kernelcache (kexts have no symbols; vtables and IOHIDFamily strings).

  • Where the data comes from: CoreMotion reads the sensors in the app's own process (CLSensorInterfaceIoHid over CLIoHidManager); locationd is not involved (it is disabled in our rootfs anyway). CLIoHidManager::initializeHid (0x3323c37c) makes an IOHIDEventSystemClient (SpringBoard's event system, as for ios3ds-mcud), fills a map event type -> HID usage (page 0xff00: accelerometer 13 -> usage 3, gyro 20 -> 9, compass 21 -> 10), matches with IOHIDEventSystemClientSetMatchingMultiple, and refreshHidServiceRefs (0x3323cba8) picks the service whose PrimaryUsage equals the entry's usage. Rates go to the service as its ReportInterval property (µs).
  • Sample format: onGyroIohidEvent (0x33244b74): event type 20, IOHIDEventGetFloatValue fields 0x140000/1/2 = x/y/z, integer field 0x140004, time stamp in mach ticks. The values stay in CoreMotion's internal units until CLMotionTypeRotationRateToCMRotationRate (0x33231db8) multiplies by pi/180 for CMGyroData.rotationRate: the HID event carries deg/s (16.16 in the kernel event). The first QEMU run sent rad/s and CoreMotion reported 1/57.3 of the set rate, which is how this was noticed.
  • gyro dt: CLSensorInterfaceIoHid::getGyroDt (0x33245220) looks up the service matching IOPropertyMatch {name = gyro} and reads gyro-interrupt-calibration: 8 bytes, u16 version (must be 1), u16 at +4 = sample period in µs; dt = interval / 0.005 × period (default period 0.00476 s, and CLDeviceMotion::startSensorFusion logs "Could not get gyro dt"). Our node sets 1, 0, 5000, 0: dt = the requested interval.
  • The gate: -[CMMotionManager isGyroAvailable] returns an ivar; behind it CLSensorInterfaceIoHid::isGyroAvailable (0x332451f0) = CLIoHidManager::isEventTypeAvailable(20) (0x3323bf50) = bit 6 of CLPlatformInfo::getProviders() (0x33224b18; compass: bit 5; accelerometer: always). getProviders switches on getSystemHardware(), which matches the model string against M68/N45/N82/N72/N18/N88/N90/N81/K48. Masks: N72 0x2012 (no gyro, no compass), N88 (3GS) 0x323f, N90 (iPhone 4) 0x337f, N81 (iPod touch 4) 0x2052 = N72 | gyro. No MobileGestalt / plist involved. The N72 literal is at 0x33224dd4 (shared with N45 and N18): one word in the rootfs recipe, 0x2012 -> 0x2052.
  • No gyro driver for the n72: the iPod2,1 kernelcache has no gyro kext. But com.apple.iokit.IOHIDFamily's AppleEmbeddedHIDEventService has the embedded dispatchers in its vtable: +0x3c0 dispatchAccelerometerEvent (0x80546771 -> IOHIDEvent factory 0x805455f9, type 13: ts, x, y, z, type, subtype, options), +0x3c4 dispatchGyroEvent (0x80546719 -> 0x805455b5, type 20: ts, x, y, z, type, subtype, 4 more fields, options), +0x3c8 compass (type 21). Each builds the event and calls dispatchEvent (+0x3ac).
  • AppleEmbeddedAccelerometer has three vtables: AppleLIS302DL 0x8061f7c4 (our accelerometer, re-log 40), the abstract base 0x8061fc30, AppleLIS331DLH 0x806200d0. Shared base methods: +0x3b0 getPrimaryUsagePage (0x8061b970, 0xff00), +0x3b4 getPrimaryUsage (0x8061b978, 3). The ReportInterval timer (0x8061c314) calls 0x8061c294, which reads a sample through +0x3f8 and calls this->vtable[0x3c0](this, ts, x, y, z, 0, 0, 0).
  • AppleLIS331DLH (unused on the n72): enable (0x8061cc50) sets CTRL_REG1 (0x20) bit 5 (PM normal) / clears bits 7:5 to disable, writes CTRL_REG2 (0x21) = 0x80 (BOOT) and polls it until bit 7 clears (panics after 1000 x 500 µs), CTRL_REG3, CTRL_REG4 = 0x80. Read (0x8061d594): 16-bit OUT_X/Y/Z at 0x28/0x2A/0x2C through a 3x3 calibration matrix (DT factoryCalibration, accel-sensitivity-calibration, low-temp-accel-offset, all optional). WHO_AM_I 0x32.
  • Bridge: a DT node /arm-io/i2c0/gyro (accelerometer,lis331dlh, I2C 0x6b, GPIO 0x62) gives a second instance of that kext on its own class, so its vtable can be patched without touching the accelerometer: +0x3b4 -> 0x8034433c (an existing ARM mov r0,#9; bx lr), +0x3c0 -> shim +0x2C shim_gyro_dispatch, which calls +0x3c4 with the ARM9's sample. The emulated LIS331DLH register file answers WHO_AM_I and clears BOOT; CTRL_REG1's PM bits become req_gyro for the ARM9. Everything else (IOHIDEventService registration, user client, ReportInterval timer, power on/off as clients come and go) is Apple's code.
  • 3DS side: libn3ds' I2C table (source/arm11/drivers/i2c.c): bus 3 devices 9/10/11 at 0xD6 / 0xD0 / 0xD2, 10 = "Old 3DS only? InvenSense ITG-3270". Horizon's HID reports 14.375 LSB per deg/s for the Old 3DS gyro (Citra's hwtest value), which is ITG-3200 FS_SEL 3. The ARM9 drives bus 3 like bus 2 (GodMode9's table covers all three buses from the ARM9; unverified for bus 3 on our side).
  • QEMU (--icount 2, ITG model at (10, 30, −45) °/s then changed by qom-set): CoreMotion's gyroData.rotationRate = (−0.523, 0.175, −0.786) rad/s, exactly the model's rates in iOS axes; then 1.571 / 0 / 3.142 as the model changed; deviceMotion rate and attitude follow; the chip sleeps before the first and after the last client. Log in docs/mcu.md 11.1.

65. Cameras: Celestial's virtual-camera slot, the CAM FIFO from the ARM11, Camera.app in QEMU (2026-11-20)

Design: docs/camera.md. All addresses: the 8C148 iPod2,1 shared cache.

  • Gating: Camera.app (in the rootfs) has SBAppTags = (still-camera); capabilities come from SpringBoard.app/N72AP.plist. Adding still-camera + front-facing-camera (recipe plist_merge, new nested merge in mkrootfs.py) puts the Camera icon on the home screen. Reference: the iPod touch 4G 4.2.1 rootfs (N81, public firmware; only plists read, nothing copied): N81AP.plist still-camera, video-camera, front-facing-camera, hd-video-capture; Celestial.framework/N81/AVCapture.plist mode schema.
  • Where capture runs: mediaserverd (FigRecorderRemote server, com.apple.coremedia.recorder, user mobile); Camera.app only talks to it.
  • Device discovery: figCreateVideoCaptureDevice 0x32e01520: CFPreferencesGetAppBooleanValue("vcd", "com.apple.coremedia") → FigLoadAspenCaptureDevice("/System/Library/MediaCapture/vcd.mediacapture", "FigVirtualCameraDeviceCreate") (0x32e0133c: dlopen + dlsym) before IOServiceMatching("AppleH4CamIn"/"H3"/"H2"/"H1") → H4ISP..H1ISP.mediacapture. Our plug-in goes into that slot; no patch anywhere.
  • Interface, from Apple's H3ISP.mediacapture (still in the cache): vtable {0, base, derived} at 0x3e07e5b8 (device) / 0x3e07e5c4 (stream); base class {1, storage 0xa4/0x4c, 0, invalidate, finalize, 0, copyProperty, setProperty}; stream class {1, start 0x30387804, stop 0x3038c774}; FigDerivedObjectCreate(alloc, vtable, classID, &obj). Device copy: StreamArray, Clock (FigClockGetHostTimeClock), SupportedPropertiesDictionary, else -12784. Stream: the plug-in creates BufferQueue and StillImageBufferQueue (CMBufferQueueCreate with the unsorted-sample-buffer callbacks) and returns them retained; supported formats = dicts {FormatDescription, VideoMaxFrameRate, VideoScaleFactor, VideoIsBinned}; frames = CMSampleBufferCreateForImageBuffer of IOSurface CVPixelBuffers, PTS host ns; start/stop post StreamStarted/StreamStopped with the stream as object.
  • Private constants: kFigCaptureStreamProperty_PortType, kFigCapturePortType_Camera/FrontFacingCamera, ..._FrameDroppedFromQueue, ..._ScaledPreviewPixelBuffer are bound into Apple's plug-ins by the cache but not exported to dlsym (first run: [cam] missing symbol ..., the device was retried ~25 times). Their CFStrings are PortType, PortTypeBack, PortTypeFront, FrameDroppedFromQueue, ScaledPreviewPixelBuffer; Celestial compares with CFEqual, so equal strings work.
  • QEMU run 1 (plug-in in pattern mode, no kernel path): Camera.app opens with the front/back switch; the preview stays black, console full of AppleM2CLCD, swap_queue error: e00002c8 / failed: contiguousLength: 0x1d000: CoreAnimation puts a 4:2:0 video layer into a CLCD overlay window (needs contiguous memory, and ios3ds only mirrors window 1). With BGRA frames the preview shows (CA composites them; screenshots in this run). Preview format BGRA in AVCapture.plist with 420f sensor frames did not help: the preview layer gets the sensor format.
  • Photos, debugged with a temporary DYLD_INSERT_LIBRARIES interposer in mediaserverd (logs CMNotificationCenterPostNotification names and VT/ImageIO results; not committed): WillCapturePhoto → DidCapturePhoto → VTPixelTransferSessionTransferImage -12905 from figrecorder_createPreviewImageSurfaceFromSbuf 0x32e2f7ec → JPEG fine (FigAspenCreateJPEGFromSbuf → no AppleJPEG service → softwareJPEGEncode → CGImageDestinationFinalize 1) → Recorder_PhotoTaken, but no Recorder_PhotoPreviewImageReady, and Camera.app saved nothing ("No Photos"). The review image is always 512x384 BGRA; VT on this device refuses to scale 320x240 up (same with 420f sources). figrecorder_serviceStillImageQueue (0x32e30a58) uses the sample's ScaledPreviewPixelBuffer attachment (sample attachments array, 0x32e31710) directly when present, so the plug-in attaches the frame's own pixel buffer.
  • Photo saved: with the attachment the review image needs no scaling, Recorder_PhotoTaken reaches Camera.app, the thumbnail shows the photo and Photos lists "Camera Roll (1)" (pattern mode, QEMU). The still itself goes to the still queue at 640x480 (2x interpolated; 320x240 gave the same -12905 when Celestial scaled it).
  • Front/back switch (gdb on QEMU's stub, emu/session.py start --extra=-s, hardware breakpoints in mediaserverd's Celestial): the device is created with the mode's stream plus its FastSwitchCompanion (FigCreateCaptureDevicesAndStreamsForPreset 0x32e01c70, outputs livesource +0x18c/+0x190); the switch stops stream 0, livesource_swapVideoStreams (0x32e252a8) swaps them, then livesource_startSource returned -12914 from livesource_setupVideoScalerForPreview (0x32e22c70) → PreviewFailed, stream 1 never started. The front mode had PreviewVideoMirror; a mirroring preview scaler cannot be made without the M2 scaler. Without the key the switch works (stream 1 starts, preview from the inner camera). Without FastSwitchCompanion the switch button does nothing. Also: StreamStopped is now only posted by a stream that ran (Celestial stops both).
  • Kernel path in QEMU (ctr_cam.c): the ARM9 finds all three MT9V113 (chip id 2280), brings the outer left one up in ~5-10 ms, the shim streams. Plain QEMU timing: every frame overruns (0 frames, ~60 overruns / 10 s: the guest runs ~3x slower than the virtual clock). --icount 2: 0 overruns, live preview of the model's pattern in Camera.app, photo saved.
  • Final QEMU run (rebased on main with the gyroscope, default image with Cydia, --icount 2): outer preview → photo → switch → inner preview → photo → Photos "Camera Roll (2)"; [cam] inner camera: 144 frames, 0 FIFO overruns in the last 10 s; cameras off (frames 611, FIFO overruns 0, CAM restarts 0). make test OK; emu/soak.py --cycles 5: PASS (0 panics/hangs; the one "SpringBoard restart" is the boot connection).
  • Unverified on hardware: everything 3DS-side (docs/camera.md section 7): CFG11_CAMERA_CNT, the I2C bus/address map, the DSi code list on the 3DS sensors, CAM_CNT = 0x8010 without DRQ, the FIFO window semantics, whether a 1 ms CPU drain keeps up on the console.

66. WPA2 + WPA3 mixed networks: detect them and join with WPA2-PSK (2026-11-20)

  • The report: the user's "Adlerhorst 2" is a FRITZ!Box in "WPA2 + WPA3" mode. In hardware run 22 the AR6014 answered every WMI_CONNECT with NO_NETWORK_AVAIL, although our scans saw the AP at -76 dBm.
  • The mixed RSN IE: AKMs PSK (2) and SAE (8), RSN capabilities MFPC, often a PMKID count and the BIP group management cipher. The 2010-era firmware's own profile match most likely rejects that IE.
  • wpa2_rsn_parse (boot/arm9/wifi/wpa2.c, host-tested) classifies an AP's IE as WPA2, MIXED, WPA3_ONLY or OTHER:
    • WPA3_ONLY: SAE without PSK, or MFPR set;
    • OTHER: no PSK at all (802.1X), or a malformed IE.
  • The ARM9 driver:
    • MIXED: it always connects to the scanned BSSID and channel with CONNECT_ASSOC_POLICY_USER | CONNECT_PROFILE_MATCH_DONE. The firmware builds a WPA2-PSK/CCMP association IE, and message 2 carries that IE.
    • WPA3_ONLY: one log line saying so and what to set on the router, then idle. No retry loop.
    • The target's RSN IE is logged in hex.
    • Scan-complete path: it now re-reads the scan results before connecting. Before, a join that had to scan first connected "not seen in scan" with the BSSID unknown (run 22).
  • QEMU:
    • ctr-wifi.security=wpa2-wpa3 and =wpa3 announce those IEs.
    • In mixed mode the model refuses a connect without PROFILE_MATCH_DONE, which is the suspected firmware behaviour.
    • New emu/wifi_test.py cases:
      • mixed: detected, 4-way OK, link up;
      • wpa3: refused with the log line;
      • ok still 20/20.
  • Also: emu/build-qemu.sh treated #undef CONFIG_SLIRP as "slirp present", so a QEMU built without the user-mode network backend was never reconfigured. It now looks for #define.

67. New 3DS: 804 MHz before XNU, timers at /192 with a halved count, L2C-310 write-through, the C-stick chip (2026-11-20)

Design and tester checklist: docs/n3ds.md.

  • Sources for the clock switch: libn3ds source/arm11/drivers/pdn.c (PDN_core123Init, PDN_setSocmode) and include/arm11/drivers/{pdn,cfg11}.h: PDN_LGR_SOCMODE 0x10141300 (0 CTR 268, 1 LGR2 268, 2 LGR1 268, 3 LGR1 536, 5 LGR2 804; bit 15 ack), PDN_LGR_CNT 0x10141304 (bit 0 extension RAM, bit 8 L2C), CFG11_SOCINFO 0x10140FFC (bit 0 CTR, 1 LGR1, 2 LGR2), CFG11_GPU_N3DS_CNT 0x10140400 (bit 0 N3DS mode, 1 texture fix); GIC 88 for core 0, prio 0, a ~400-cycle wait after LGR_CNT, WFI until the ack, write back, clear pending 88. linux-3ds firm_linux_loader/arm11/source/smp.c does the same (set_socmode/upclock). libn3ds keeps CTR mode unless built for extra cores/QTM RAM and switches a non-CTR mode back to 0; our n3ds_clock=0 does that too.
  • Who sets the clock on the way to us: boot9strap leaves 268 MHz (issue #1's New 2DS XL log behaved like an Old 3DS). Neither Luma's chainloader nor the launcher's reboot path touch PDN_LGR_SOCMODE, hence the stale-ack write-back first.
  • MPCore timers: PERIPHCLK = CPU/2, so 402 MHz at 804. The 8-bit prescaler can't reach /384 (= 1,047,311 Hz). Options weighed: a new timebase-frequency (touches the device tree and every 1,047,311 Hz constant in audio/camera/GPU/ARM9 code), 536 MHz (/256 exact, but mode 3 is an LGR1 mode, unknown on LGR2), or /192 with every count shifted by one in the shim. Took the shift: get_abstime (stackless, movs r1,r1,lsr #1; mov r0,r0,rrx), get/set_decrementer, and shim_now32() for the C users (audio.c, cam.c, pica.c), which keeps 32-bit wraps right. The stub measures PERIPHCLK against the ARM9's 65,457 Hz timer (watchdog at prescaler 0 over 1309 ARM9 ticks) instead of assuming it.
  • Kernelcache facts used for the L2 decision: the boot code at file offset 0x66000 maps RAM with 16 MiB supersections, descriptor bits 2 | 0xC | AP 1 (offsets 0x660a0..0x660e4): TEX=000 C=1 B=1, outer and inner write-back, no write-allocate, not shared. Every TTBR write (0x6602c, 0x66070, 0x66bc0, 0x66bcc) ORs 0x18: RGN = 11, so table walks are outer-cacheable and go through the L2. XNU's own cache ops are ARM1176 L1 c7 operations only.
  • L2C-310 shared override: per the Linux arm,shared-override binding text, without aux bit 22 the controller turns normal non-cacheable shared accesses into "cacheable no-allocate" reads and write-through writes, which can hit stale lines. We set the bit.
  • Why write-through: with debug control DWB the L2 never holds dirty lines, so only the inbound direction (ARM9/GPU wrote RAM, the ARM11 reads it) needs new work. That direction already had an L1 invalidate in every shim helper, and those now call shim_l2_inv (invalidate by PA + sync). A spurious invalidate of a clean line is harmless, so non-linear VAs fall back to a best guess. The full audit is the table in docs/n3ds.md section 2. st_panic_req is read without any invalidate (it relies on L1 eviction), which is one reason the L2 stays off by default.
  • C-stick chip: 3dbrew "I2C Registers" device 17 (no register index; byte 0 = 0x80, byte 1 buttons ZL 0x4, ZR 0x2), GBATEK "3DS I2C New3DS C-Stick and ZL/ZR-Buttons" (bytes 2/3 coarse X/Y, 4 = 0xFF, 5/6 fine X/Y signed; >0x1A bytes can hang the chip; needs CNTEX clock stretching), libn3ds I2C_DEV_EXTHID = {bus 3, 0x2A << 1}. 3dbrew "IRRST Shared Memory": Horizon's range ±0x9C after its own conversion.
  • QEMU: -M nintendo3ds,new3ds=on. QEMU patch 0001 only re-read PERIPHCLK when the prescaler field changed, so the first New-model run measured 134 MHz after the switch. It now re-reads it on every control write. Results: section 67.1.
  • Two bugs the New-model QEMU runs found:
    1. rtclock_init's tick base was 0. The first clock read comes one raw tick after shim_init starts the watchdog, and 1 >> 1 = 0, so the calendar conversion spun forever with IRQs masked (PC 0x8006918e, the hang described in entry.S). The shifted clock now adds 1.
    2. With the three new lines, the generated boot.cfg grew to 4249 bytes. The ARM9 read only 4095 (cfgbuf[4096]), so the cmdline= line at the end was lost: no rd=md0, and the kernel waited for a root device until the watchdog panic. The buffer is now 16 KiB, and the ARM9 logs an error if a boot.cfg ever fills it.

67.1 QEMU evidence (--icount 2)

  • New model, defaults (emu/run.py --new3ds --icount 2): [a11] New 3DS: SOCINFO 7, SOCMODE 5, LGR_CNT 101, PERIPHCLK 402236315 Hz, timer /192 >>1 (the model's 402,167,784 Hz measured to 0.02 %). [n3ds] … prescaler /192, tick shift 1 -> 1047490 Hz. The heartbeat compares the ARM11 clock with the ARM9 timer: [hb] clock: arm11 watchdog +589026 ms vs arm9 timer +589021 ms (ratio 1000/1000). mcud: gettimeofday +70546 ms, mach_absolute_time +70546 ms. The kernel reaches SpringBoard, and the GPU mirror runs with 0 of 512 sampled LCD pixels differ.
  • Old model: [a11] Old 3DS: SOCINFO 1, SOCMODE 0, LGR_CNT 0, PERIPHCLK 133893818 Hz, timer /128 >>0. Nothing else changes; 0x17E10000 stays unmapped.
  • C-stick and buttons (keypad 6, Z, N; emu/tap.py in Settings):
    • keypad 6 on the home screen → [input] cpad down 272,240 / up 47,240: page 2.
    • keypad 2 twice in Settings scrolls about a page each time without a fling.
    • Z (ZL) → the list animates back to Airplane Mode at the top.
    • N (ZR) → the white screenshot flash ([exthid] 80 02 … ZR, [input] ZR: screenshot).
    • First mapping tried for ZL: a double HOME press for the app switcher. In QEMU it only scrolled page 2 back to page 1: no multitasking on the iPod touch 2G.
  • n3ds_l2=1 (boot.cfg edited in the image): [n3ds] L2 cache: on, write-through (L2C-310 id 410000c9 aux 02490000 ctrl 1). After 190 s: l2c-ctrl 1, l2c-debug 2 (DWB), l2c-inv-ways 1, l2c-inv-lines 6810479, l2c-syncs 868416 (the shim's invalidates reach the controller), clock ratio 999/1000, SpringBoard up. That the maintenance is enough can only be shown on hardware.
  • Soak: python3 emu/soak.py --cycles 5 PASS on the Old model and with --new3ds (0 panics, 0 hangs, 0 watchdogs). make test OK (test_n3ds: 35 checks).

68. Cameras, hardware run 23: sensors answer, no data reaches the CAM FIFO (2026-11-20)

Log: build/hwlogs/run23.txt (main + agent/camera, camera=1 diag=1), lines 689-902 and 2387-2399. Design: docs/camera.md section 7.

  • Seen: first device creation cameras present 0x0 (the ARM9 probes the sensors only at the first start; the plug-in does not reject on it, the second creation says 0x3); all three sensors answer chip id 2280 on GBATEK's map (outer left 0x10144000/0x78, inner 0x10161000/0x7A, outer right 0x10161000/0x78); outer left camera streaming 320x240 YUV422 into CAM1 (init 136 ms) (QEMU: 5 ms, so the waits really waited on the sensor); then 0 frames, 0 FIFO overruns every 10 s until stop. A third start later: init failed (step 5) = the sequencer refresh did not finish within 100 ms.
  • Reading: with no overruns the CAM1 FIFO never filled: either the block never saw a frame (no sync/data from the sensor, or the block not enabled/clocked), or the data went to the other block, or the shim's drain never enabled CAM_CNT (no counter told). 3dbrew has no CAM register page ("Camera Registers" redirects to Y2R); GBATEK's 3DS CAM section is the only register reference; Citra/Azahar emulate the cam service at HLE level (no register sequence); no open bare-metal 3DS camera driver was found.
  • Ranking: (1) the CAM block needs more than CAM_CNT 0x8010: +6 (bits 0-5, GBATEK suspects the DSi's CAM_MCNT, 0x22 = on) and/or the DRQ bit the official driver (CDMA) uses; (2) the outer left sensor feeds CAM0, not CAM1; (3) the DSi code list leaves the 3DS sensor in standby or with parallel output off; (4) CFG11_CAMERA_CNT bit 1 (GBATEK: "reportedly turn on/off cameras") is needed; (5) the shim never started the drain (mailbox/IRQ path; ran in QEMU).
  • Changes: shim watches both blocks until data appears and moves to the one that gets it; set-up variants 0 (0x8010), 1 (+6 = 0x22), 2 (+ bit 14 DRQ, bit 9 IRQ) cycled every 2 s while nothing arrives; restart at a frame start once data is seen; diagnostics in a new mailbox line (services, services with data, CAM_STAT of both blocks, max fill, CAM_CNT readback, variant, port). ARM9: CFG11_CAMERA_CNT |= 3 with readback; [cam-diag] dumps of both CAM blocks at boot, before the set-up and 0.2/1/5 s after a start, a 50 ms sampler counting CAM_CNT bit 0/1 changes and FIFO fill changes per block, sensor registers (PLL, CLOCKS, STANDBY, RESET_MISC, 0x301A, SEQ_CMD, SEQ_STATE, SEQ_CAP_MODE, output size/format, read mode); sensor waits 500 ms; sensors probed at boot (present known before the first start, then standby and clock off). Host test: no data for 5 s → variant 2 still probing, then frames whole and in order.
  • Next hardware log must show (open Camera.app, wait 15 s): the [cam-diag] toggle lines (does CAM_CNT bit 0/1 change on CAM0 or CAM1?), the sensor dump (STANDBY bit 14 clear, RESET_MISC bit 9 set, SEQ_STATE), and the 10 s stats line with services > 0 and the variant/port. Frames > 0 with some variant/port = that is the fix to make default.

69. Launcher: NWM .code path rejected on hardware (issue #5) (2026-11-20)

  • Report: first hardware report of the launcher's firmware copy, on a New 2DS XL with Luma3DS: cannot open NWM .code (FS E0E046BE, FSPXI E0E046BE).
  • Decoding E0E046BE: level Usage, summary InvalidArgument, module FS (17), description 702 = FS InvalidPath. FS and FSPXI both rejected our path layout: archive 0x2345678A with a 20-byte file path {0, 0, 1, ".code"}.
  • What Luma3DS's own loader uses (sysmodules/loader/source/loader.c): archive 0x2345678E (SaveDataAndContent2), FS_ProgramInfo {u64 programId, u8 mediaType, pad} as the archive path, and the 12-byte file path {u32 1, ".code"}.
  • The launcher now tries, in order, each through FS and then FSPXI:
    1. Luma's layout 678E/1 (only under Luma3DS: Azahar 2126.2 crashes on that archive ID instead of returning an error);
    2. 678A/1;
    3. 678A/2 (FBI's type for ExeFS files such as icon).
  • Reporting: every attempt's result goes on screen and into sd:/ios3ds/wififw-status.txt, which the ARM9 copies into log.txt when Wi-Fi has no firmware.
  • Azahar check: 678A/1 FS C8804478; 678A/2 FS C8804478 (no NWM title there).

70. Cameras, hardware run 25: the sensor streams, neither CAM block sees anything (2026-11-20)

Log: build/hwlogs/run25.txt lines 67-962 (agent/camera-hw diagnostics, re-log 68).

  • Seen: CFG11_CAMERA_CNT 00 -> 01 (bit 1 does not stick: GBATEK's "unused" is right). At boot CAM0 cnt 0010, CAM1 0000: someone before us (boot ROM, Luma) wrote CAM0's bit 4. After our start CAM0 reads 8010, CAM1 8000: bit 4 does not stick on CAM1 (GBATEK lists it R/W, "must be 1, else data transfer hangs, maybe reset"). Variant 2 reads back c210/c200, +6 0022 on both. CAM_STAT always 0000; the 50 ms samplers (15k reads per block) never saw CNT bit 0/1 or the fill change, in all three variants, for 2 min; shim services up to 62103, 0 with data, so the drain ran (hypothesis 5 of re-log 68 is out).
  • Sensor (outer left), identical before and 5 s after the start: PLL b04a (locked, bypass off), CLOCKS 42ff, STANDBY 0028 (bit 14 clear = awake), RESET_MISC 0210 (bit 9 parallel output on; the Linux MT9V113 driver writes the same 0x0210), CORE_301A 121c (bit 2 streaming), SEQ_STATE 3 (preview), output 320x240 YUV. The sensor says it streams; no block sees sync or data. The board (GBATEK pinout P9) wires the DSi pair (I2C bus 0x10161000) and the extra camera (I2C bus 0x10144000) to separate 8-bit buses with their own HSYNC/VSYNC/PCLK, as our map assumes.
  • Remaining hypotheses: (1) the CAM block needs set-up bits we never set: the DSi's CAM_CNT init sets bits 8-9 = 2 and bit 10 = 1 before enabling the transfer (GBATEK DSi "Camera Init"; the 3DS register is "alike DSi", and GBATEK's "no effect?" for bits 8/10/11 was observed with the cam module's set-up already in place); (2) CAM1 is held in reset/unclocked (bit 4 not sticking) while CAM0 is not: the inner camera on CAM0 may work where the outer left one does not (run 25 never tried it); (3) the sensor's outputs are gated by its OE pin (RESET_MISC bit 4 set = "OE_N" control; not documented for the MT9V113); (4) pad drive (DSi PAD_SLEW 0x0201 vs Linux 0x0777).
  • Changes: set-up variants now 0x8010, 0x8610 (DSi bits 8-10), 0x8E10 (+ bit 11), 0x8610 with +6 = 0x22, 0xC610 + DRQ with +6 = 0x22, the configuration bits written before the transfer bit. Boot self-test with diag=1 (ARM9, before XNU): every sensor (outer left, inner, outer right) is brought up alone and all five variants are tried on both blocks for 200 ms each, then RESET_MISC = 0x0200 (bit 4 clear) with 0x8010/0x8610 and PAD_SLEW 0x0777; a [cam-test] line per set-up with both blocks' CNT readback, stat and maximum fill, <-- DATA when anything arrived, and the sensor registers. QEMU: data on CAM1 for the outer left camera and on CAM0 for the inner/outer right ones in every variant.
  • Next hardware log must show (diag=1, before XNU starts): the [cam-test] matrix and [cam-test] done: N set-ups saw data. Any <-- DATA line names the working sensor/block/set-up, which then becomes the default. If none: compare which CNT bits stick on each block (CAM1's bit 4) and try the front camera in Camera.app too.

71. Cydia Substrate and TLSFix: TLS 1.2/1.3 for iOS's own networking (2026-11-20)

Design: docs/cydia.md (Substrate), docs/certificates.md section 4 (TLSFix). Packages: mobilesubstrate 0.9.6301 + com.saurik.substrate.safemode 0.9.6001 (apt.saurik.com, newest; armv6 slices, min iOS 2.0), com.skyglow.tlsfix 1.3 (github.com/ObscureMosquito/TLSFix release, sha256 ca2f6bb4...cb94; OpenSSL 1.1.1w statically, armv6/armv7/arm64), pinned in rootfs/cydia.json.

  • Substrate's own boot hook: extrainst_ (Mach-O; strings) writes bsexec .. /usr/bin/cynject 1 .../SubstrateLauncher.dylib to /etc/launchd.conf (or /etc/rc.d/substrate). 4.2.1's /bin/launchctl reads /etc/launchd.conf during bootstrap and waits for each bsexec (a test script logged before/after). cynject exits 0 (task_for_pid(1) works with amfi_unrestrict_task_for_pid=1), but afterwards every process launchd forks (38 pids in a kill -0 scan) stays blocked forever and nothing execs; QEMU -d int shows no faults, the children's last syscalls are kill/waitpid (SubstrateLauncher's posix_spawn hook, 0x11ae: kill(pid, 9) + waitpid on a helper child; it also forks/execs /usr/libexec/MSUnrestrictProcess). setenv DYLD_INSERT_LIBRARIES /Library/MobileSubstrate/MobileSubstrate.dylib in launchd.conf (the pre-2011 way) hangs the boot the same way. A bash child with DYLD_INSERT_LIBRARIES = libsubstrate / SubstrateLoader / MobileSubstrate.dylib runs fine (DYLD_PRINT_LIBRARIES); SubstrateInjection loads SubstrateLoader only if CoreFoundation is loaded (imports: getenv, dlopen, _exit; strings MSExitZero, AppIndexer, Security, CoreFoundation).
  • What ships: Substrate only where needed: appended to the recipe's own DYLD_INSERT_LIBRARIES jobs (SpringBoard, configd, securityd; boots, Wi-Fi and the a80211/hwaes interposers unaffected), apps via ios3ds-applog (SBGuardMallocAlways → /usr/lib/libgmalloc.dylib, which replaces any other insert for apps) dlopening MobileSubstrate.dylib, ios3ds-nettest after it loads CFNetwork. cydia.substrate_setup(); _NSGetExecutablePath added to scripts/ios-sdk-symbols.json.
  • Sandbox: MobileSafari runs under launchd's Builtin profile: MobileSafari. A debug build of applog that writes to /private/var/tmp from inside Safari: open() → EPERM for everything under /Library (/Library/MobileSubstrate/..., /Library/Frameworks/CydiaSubstrate.framework/..., /Library/Ringtones) and for /var/mobile/Library/ConfigurationProfiles, /usr/lib/* allowed (symlinks into /Library are not). So dlopen(MobileSubstrate.dylib) fails and Safari keeps the stock TLS 1.0 ("could not establish a secure connection" for github.com and www.apple.com). Cydia is not sandboxed: Substrate and TLSFix load (loader and tlsfix handles non-NULL) and the home page loads. SpringBoard has SBEnableDebugSandboxProfiles / /usr/share/sandbox/%@.sb and libsandbox has the SBPL compiler (sandbox_compile_file), but that would replace Apple's built-in profile with our own; not done. Fix later: a Sandbox kext patch (com.apple.security.sandbox at 0x803cd000) as iOS 4 jailbreaks had.
  • TLSFix 1.1 (nfzerox) first: hooks applied (SSLHandshake starts 04f01fe5 = ldr pc,[pc,#-4] after loading), ensure_ready = 1, raw OpenSSL SSL_connect to github.com from the guest: TLSv1.3. Failures were (a) EC chains (letsencrypt, wikipedia, github's ECDSA certificate) that 4.2.1's SecTrustEvaluate cannot verify, (b) a stale per-context state: CFNetwork disposes a failed context without SSLClose, the next context at the same malloc address inherited TLSFix's "failed" state and went to the stock TLS 1.0 stack (found by swapping TLSFix's o_Handshake pointer for a logging wrapper). TLSFix 1.3 fixes both: SSLNewContext hook resets the state, and EC chains are checked with OpenSSL against the CA payloads of /var/mobile/Library/ConfigurationProfiles/* (not .stub) — so the build writes ios3ds-roots.plist there with the RSA roots + the 40 EC roots of Mozilla's bundle (rootfs/certs/roots-ec.pem).
  • BigBoss: moreinfo.thebigboss.org / apt.thebigboss.org serve a certificate that expired 2026-06-15 (and is for moreinfo only). github.com's RSA certificate is on the same SHA-384 Sectigo R36/R46 hierarchy and verifies through SecTrustEvaluate (TLSFix 1.1 with RSA-only signature algorithms), so the "SHA-384" explanation in certificates.md section 3 was wrong; corrected.
  • Results (TLSFix 1.3, nettest): github.com, en.wikipedia.org (EC), www.apple.com, www.google.com, cydia.saurik.com, ecc256.badssl.com 200; expired / untrusted-root / wrong.host.badssl.com -9807; letsencrypt.org TLS ok but CFNetwork HTTP error -4. --icount 2, TLSFix vs TLSFIX=0: cydia.saurik.com 2 s / 2 s, google 3 s / 2 s, apple.com 4 s / -9836, wikipedia 9 s / -9836. Boot to SpringBoard 80 s (plain QEMU, within the usual 50-100 s); emu/soak.py --cycles 5 PASS (0 panics, hangs, crashes). Cydia: home page loads with Substrate + TLSFix loaded in it. Safe mode not exercised.
  • Unclear, not chased: with the ios3ds_applog=1 boot-arg no [applog] line appeared on the console in any run (also with the unmodified library), and in two runs with Substrate in SpringBoard Safari did not come up after a tap; without the boot-arg apps launch normally (soak).

72. Reaching sandboxed apps: the Seatbelt sb_evaluate patch, and Safari's memory wall (2026-11-20)

Design: docs/cydia.md "Reaching sandboxed apps". Goal: get TLSFix into MobileSafari (sandboxed), which re-log 71 left on TLS 1.0.

  • Why Safari was excluded: a debug ios3ds-applog in MobileSafari (writing to /private/var/tmp, which the profile allows) open()s the candidate dylibs: every path under /Library (/Library/MobileSubstrate/*, /Library/Frameworks/CydiaSubstrate.framework/*) and /var/mobile/Library/ConfigurationProfiles returns EPERM; /usr/lib/* is allowed. launchd logs Builtin profile: MobileSafari (sandbox). So Substrate's dlopen fails and Safari keeps the stock TLS stack.
  • The Sandbox kext is com.apple.security.sandbox (prelinked at 0x803cd000, size 0xff000; Sandbox-58.12 from the SourceCache strings). Its MAC policy is registered via a mac_policy_conf at 0x803d46fc (mpc_name "Sandbox" 0x803d3740, mpc_ops 0x803d4728). Walking the 135 non-null function pointers in mpc_ops and histogramming their BL targets, the function 75 of them call is sb_evaluate at 0x803ced98 (builds a 0xe0-byte eval context; r2 = operation index). The bytecode interpreter it calls (references "bad opcode") is a separate function at 0x803d1b9c.
  • Operation indices come from the operation_names char* array at 0x803d4320: file* 1, file-chroot 2 ... file-read* 6, file-read-data 7, file-read-metadata 8, file-read-xattr 9, file-revoke 10, file-search 11, ... MobileSafari 84, etc.
  • Patch (kernel/patches-sandbox.json, opt-in SANDBOX=1): sb_evaluate's first instruction (push {r4,r5,r6,r7,lr} = e92d40f0) -> b shim_sb_evaluate (kernel/shim/entry.S; the branch word is computed from the shim ELF symbol by the patcher's new branch key, as the New-3DS work took the +0x0C jump-table slot this first used). shim_sb_evaluate: cmp r2 against {1,6,7,8,9,11} -> mov r0,#0; bx lr (allow); otherwise replay the push and ldr pc,=0x803ced9c into sb_evaluate's body. Write/exec/network/iokit/mach checks stay enforced; only file reads of the dylib paths (and, incidentally, any file read by a sandboxed app) are allowed.
  • Result: with the patch, MobileSafari's sandbox probe shows open() of the /Library paths now returns 0, and Safari gets past the TLS stage — github.com and example.com change from "could not establish a secure connection" to "Cannot allocate memory". QEMU models the real 128 MB (MEM_SIZE 0x08000000); TLSFix's static OpenSSL 1.1.1w (1.9 MB armv6 text + 144 KB __DATA + the handshake heap) does not fit in the WebKit content process, so every HTTPS load OOMs, even a 1 KB page. The patch therefore turns a TLS failure into an OOM failure for Safari.
  • Decision: off by default (SANDBOX=1 opt-in). It is stable at the kernel level — boot, Wi-Fi, Cydia HTTPS and emu/wifi_test all PASS with it applied, and Mail / App Store launch (MobileMe account screen) without regression — but it makes Safari worse on 128 MB, so "default on only if stable" keeps it out. Cydia and other unsandboxed apps get TLSFix regardless.
  • Memory thrift: Cydia Substrate is no longer appended to configd/securityd (nothing targets them; substrate.daemons = SpringBoard only), saving the SubstrateInjection/Loader + CoreFoundation scan in two daemons. At the home screen, before any app that uses CFNetwork is launched, only SpringBoard has loaded MobileSubstrate.dylib (TLSFix's deny-list excludes SpringBoard, so tlsfix.dylib itself loads nowhere until an app opens an HTTPS connection); so free memory at boot is essentially the same with TLSFix and TLSFIX=0. iOS 4.2.1 does not expose vm.page_free_count via sysctl, so the per-process cost is the dylib accounting above, paid only when an unsandboxed app (or, with SANDBOX=1, Safari) makes an HTTPS connection.

73. Installing Substrate tweaks without the launchd hang: hold, pin, cynject diversion, boot guard (2026-11-20)

Design: docs/cydia.md "Installing tweaks". Hardware report (main without pre-installed Substrate): installing anything that depends on mobilesubstrate hard-locks the install. That matches re-log 71: Cydia installs mobilesubstrate and runs its extrainst_, which calls cynject 1 ...SubstrateLauncher.dylib at once and writes the same into /etc/launchd.conf.

  • extrainst_ (0.9.6301, armv6 slice): imports system, fork, waitpid, vm_protect, Foundation (NSPropertyListSerialization, NSFileManager), no task_for_pid: the injection goes only through system("/usr/bin/cynject 1 ..."). Strings: /etc/launchd.conf, bsexec .. /usr/bin/cynject 1 ..., /etc/rc.d/substrate, /boot/untether, /System/Library/LaunchDaemons + %@/%s.plist, DYLD_INSERT_LIBRARIES, /usr/libexec/cydia/move.sh /Library/MobileSubstrate/DynamicLibraries (a no-op with /.cydia_no_stash), finish:%s (asks Cydia for a respring).
  • Build changes: mobilesubstrate + com.saurik.substrate.safemode get Status: hold ok installed and a version pin (priority 1001) in /etc/apt/preferences. Commands/cynject becomes a local dpkg diversion to cynject.real, with /usr/libexec/ios3ds-cynject in its place (refuses pid 1, execs the real one otherwise). com.ios3ds.substrate-guard (bash, once per boot) drops cynject lines from /etc/launchd.conf, removes /etc/rc.d/substrate, and re-installs the guard if a cynject binary ever shows up un-diverted.
  • QEMU, real APT (ctr-wifi + slirp; a one-shot root job, not committed, ran apt-get against http://apt.saurik.com/ ios/550.52 main and http://apt.thebigboss.org/repofiles/cydia/ stable main):
    • apt-cache policy mobilesubstrate: installed 0.9.6301, candidate 0.9.6301, Package pin: 0.9.6301 (nine older versions listed in the repo).
    • apt-get -s upgrade: 0 upgraded.
    • apt-get install com.saurik.iphone.nlnf com.abart97.nosbscreen: Inst/Conf only for those two. nlnf is "Net.-Local Number Format" from saurik, Depends: mobilesubstrate (>= 0.9.3997), UIKit filter. NoSBScreen is from BigBoss, armv6, SpringBoard filter. rc 0; dpkg -l shows hi mobilesubstrate 0.9.6301 and hi com.saurik.substrate.safemode 0.9.6001, still held.
    • Ran mobilesubstrate's own extrainst_ install, as Cydia does after a (re)install: rc 0. It wrote bsexec .. /usr/bin/cynject 1 ... into /etc/launchd.conf, and new processes still spawned (/bin/date ran): the guard refused pid 1.
    • It also rewrote com.apple.SpringBoard.plist (now binary) and removed MobileSubstrate.dylib from SpringBoard's DYLD_INSERT_LIBRARIES, leaving /usr/lib/ios3ds-applog.dylib. configd and securityd were unchanged.
    • Respring (launchctl stop com.apple.SpringBoard; SpringBoard ran with DYLD_PRINT_LIBRARIES=1): SubstrateLoader.dylib, DynamicLibraries/NoSBScreen.dylib, DynamicLibraries/PhoneNumberFormatting.dylib and tlsfix.dylib loaded. Both tweaks load.
  • Consequence: no launchd plist names Substrate any more (substrate.daemons = []). SpringBoard gets it the way apps do, from ios3ds-applog's constructor (SpringBoard.app is a .app executable), so extrainst_'s plist cleanup has nothing to remove.

74. Cameras: how the 3DS CAMERA sysmodule brings up a CAM block (2026-11-20)

Source: the user's own CAMERA sysmodule code (title 0004013000001602, BLZ-decompressed .code copied read-only by the launcher since commit 5ec8986), disassembled in a scratch directory outside the repository; nothing of it is in the tree. Load base 0x00100000, Thumb. Below are only the facts derived from it.

  • Services: the module gets handles for pdn:c, i2c::CAM, mcu::CAM (plus y2r, cfg, ptm, fs). It never touches CFG11/PDN registers itself; the CAM blocks it maps at VA 0x1EC20000/0x1EC21000 (PA 0x10120000/0x10121000), the FIFOs at 0x1EE20000/0x1EE21000 (PA 0x10320000/0x10321000), read by inter-process DMA.
  • pdn:c: two commands. 0x00010040 with one byte (0/1): camera power/clock off/on. 0x00020000: returns a byte (whether it is already on). "Power on" = query, then on, then (only if it was off) a short busy wait. "Power off" = short wait, then off. Which register pdn:c drives is not visible from the module; the ARM9 uses CFG11_CAMERA_CNT bit 0 (0x10141224, PDN_CAMERA_CNT on 3dbrew), the only bit that sticks there (run 25).
  • mcu::CAM: one command, 0x00010040 with one byte, called with 0 or 2: the camera LED state. Not part of the data path; ios3ds leaves the LED alone.
  • Block reset (driver initialisation and shutdown): CAM0 CAM_CNT bit 4 cleared; two short waits; pdn:c on; short wait; CAM0 bit 4 set; wait (~1 ms); pdn:c off; both CAM_CNTs read and written back. Bit 4 exists only on CAM0 (matches run 25: it does not stick on CAM1): it is the reset of both blocks, released while the camera clock runs. All waits are busy loops of n x 48 iterations (n = 100, 500, 15, 4100), well under a millisecond each except the last.
  • Driver initialisation, both blocks (port mask 3), in this order: reset as above; CAM_CNT bit 15 cleared (transfer off); +6 bit 15 set (overrun clear, read-modify-write of the 32-bit word at +4); transfer unit 256 bytes (+6 bits 0-5 = bytes/256 - 1, at most 10240 bytes); CAM_CNT bit 13 cleared (trimming off); +0x10 = 0x00010000, +0x14 = 0x00010000; CAM_CNT bits 8-9 = 2; bit 10 set; bit 11 cleared; then bit 14 set on CAM0 and CAM1. All CAM_CNT accesses are 16-bit.
  • Activate (per sensor, through i2c::CAM): power on (pdn:c as above), the sensor scripts (below), then standby off (0x0018 bit 0 clear), wait 0x0018 bit 14 clear (10 ms steps, 100 ms), wait 0x301A bit 2 set, then RESET_MISC 0x001A bit 9 set (parallel output on). Same as ios3ds' apt_activate.
  • Sensor scripts (a table of named scripts in the data section: register writes, MCU-variable writes and bursts, delays, waits): "Base" = reset 0x001A 3 then 0 with 1 ms after each, wakeup 0x0018 = 0x4028, PAD_SLEW 0x001E = 0x0201, CLOCKS 0x0016 = 0x42DF, the two wakeup waits, the I/O current MCU writes, SEQ_CAP_MODE 0xA115 bit 1, 10 ms, output formats 0x2755/0x2757 = 2 (YUV), MCU 0xA111 = 0x0A. "Image Setting ExtClk=16.76MHz Op_Pix=17.8MHz" = the DSi PLL values (0x0014 = 0x2145, 0x0010 = 0x0111, 0x0012 = 0, 0x0014 = 0x244B, 1 ms, 0x0014 = 0x304B, wait lock, bypass off), flicker detection MCU values (0x222D, 0xA402-0xA410, 0x2411-0x2417), output size A 256x192 and B 640x480, the DSi sensor timing, crop B full frame. Then lens correction, AE, AWB, noise reduction, gamma, and per camera read mode (0x25 outer, 0x24 inner, as GBATEK's DSi list) and AE window, then the sequencer refresh (0xA103 = 6, wait, = 5, wait). The 3DS sequence is the DSi list plus the waits and those MCU values: the sensor side of ios3ds was already right (run 25 saw it streaming).
  • StartCapture: transfer unit = lines x width x 2 bytes (+6 bits 0-5), overrun clear, then CAM_CNT bit 15 set; the inter-process DMA reads the FIFO window in transfer-unit blocks. StopCapture: clears bit 15 only.
  • Ports: camera select bits 1 = outer right, 2 = inner, 4 = outer left; port bits 1 = CAM0, 2 = CAM1 (outer right and inner on CAM0, outer left on CAM1, as GBATEK says).
  • Status reads: CAM_CNT bit 1 (per port, a busy flag), +4 bit 15 (both ports), +4 bits 0-10 (fill), bit 13 (trimming on), +0x10/+0x14.
  • What ios3ds did differently (run 25): (1) the clock was switched on with CAM0 bit 4 already set (left by whatever ran before), so the blocks' reset was never released with the clock running; (2) bit 14 only on the drained block, and only in one variant; (3) the shim wrote CAM_CNT = 0 to stop or to leave a block, which clears CAM0 bit 4 and so holds both blocks in reset; (4) transfer unit 0x22 (9216 bytes, not whole lines). The CNT bits themselves (0xC610) had been tried.
  • Changes: ARM9 power(true) now runs the module's block reset and initialisation before the sensor set-up (cam_reset, cam_block_init, logged as [cam-diag] after the cam module's block reset/init), power(false) its shutdown; the sensor set-up gets the module's waits and extra MCU writes. Set-up variant 0 is the module's (0xC610, transfer unit 2560 bytes = 4 lines of 320); the earlier five follow. The shim stops a block by clearing bit 15 only. QEMU: CAM1 bit 4 reads 0, data only flows while CAM0 bit 4 is set.
  • Next hardware log must show: after the cam module's block reset/init with CAM0 cnt 4610 and CAM1 4600 (bits 8-10 and 14 stuck, CAM0 bit 4 released), then data in variant 0 (variant 0 in the stats line, <-- DATA in the diag=1 self-test). If still nothing: pdn:c drives more than CFG11_CAMERA_CNT bit 0 (another PDN bit, to be found from the pdn module), the next thing to reverse.

75. Memory: Safari's "Cannot allocate memory", a [mem] report, the GPU arena, 256 MiB on the New 3DS (2026-11-20)

  • Report (Old 3DS and New 2DS XL): Safari's first page load often fails with "The operation couldn't be completed. Cannot allocate memory" (NSPOSIXErrorDomain 12); a retry works. The hardware logs (run23/24, issue 1, issue 5) carry no Safari error and no memory figures. They show the GPU arena trouble: [pica] arena full: 262144 bytes wanted, 1082368 free in 140 blocks, … 858112 free in 160 blocks (160 = the whole block table), and after [gl] pica: writing a surface back on the GPU failed a 1 MiB CPU read-back on every frame (render thread 20 → 65 ms per frame, arena full: 1048576 bytes wanted 256 times).
  • Tools added:
    • [mem] report: ios3ds-sample -mem 20, a launchd job behind boot-arg ios3ds_mem=1 (ios3ds-diag -g name runs a job when boot-arg name=1); with diag=1 the [smp] sampler prints it after every round. vm_stat (host_statistics; free includes the speculative pages), jetsam's kern.memorystatus_level, kern.ipc.mbstat, resident/virtual size per process (kernel zones need the host-priv port, which host_get_host_priv_port does not give the job: no zone line).
    • [applog] MobileSafari load error (provisional|load): domain code userInfo: TabDocument's WebFrameLoadDelegate failures with _kCFStreamErrorDomainKey/CodeKey, i.e. which layer produced an error (with ios3ds_applog=1 or diag=1).
    • emu/safari_test.py (docs/emulator.md): Safari page loads over the Wi-Fi model, URLs opened by ios3ds-diag -urlpoll through SBSOpenSensitiveURLAndUnlock (SpringBoard 8C148 wants the com.apple.springboard.opensensitiveurl entitlement: without it the call returns 0).
  • Memory, Old 3DS, QEMU --icount 2: after boot (Wi-Fi up, 60 s settled): free 51.6 MiB of which 50.6 MiB speculative (file pages, reclaimable), active 23.3, inactive 8.4, wired 33.4 MiB (12 MiB of it the GPU arena; 17.7 MiB before SpringBoard), memorystatus_level 63. 20 processes resident 32.5 MiB: SpringBoard 11.2, mediaserverd 4.0, configd 2.8, profiled 2.4, lsd 1.8, installd 1.3, mDNSResponder 1.3, ios3ds-mcud 1.2, everything else < 0.7. MobileSafari: 14 MiB after the first page, 29 MiB after six (level 48).
  • Trying to reproduce: no Safari alert, no jetsam kill in any of: 6/6 generated pages (images + JS) by IP; 6/6 by name through slirp DNS (10.0.2.2.nip.io); 8/8 with only 96 MiB for XNU (free down to 2 MiB, level 39; the 12/8/4/2 MiB GPU arena could not be had, so CA ran in software); 3/3 saved Wikipedia articles (4-5.5 MiB each, 147-390 s per page at hardware timing).
  • Ruled out by RE: the network path cannot produce errno 12. IOUserEthernetController::outputPacket (0x80514110) always returns 0; a failed enqueue to the daemon's kernel-control socket is only logged (failed to enqueue mbuf, never seen in a hardware log). The shim's sysctls return only EINVAL/EFAULT/EBUSY. mbuf shortage is ENOBUFS in XNU 1504, not ENOMEM.
  • What the logs do show, and what was fixed:
    • GPU arena (pica_drv.c, pica_be.c): blocks of 256 KiB and more go first-fit from the top of the arena, textures from the bottom; the block table grew from 160 to 224 entries (issue 1 hit 160, and a full table fails every allocation whatever is free); when a big block does not fit, the GL engine evicts the textures highest in the arena first instead of in LRU order. test_pica's alloc test (150 target allocations in a 3/4 full 12 MiB arena with texture churn) evicts 9.8 MiB of textures that way against 42 MiB at random.
    • Read-back mode (after a refused PICA_OP_PRESENT): one staging buffer is kept instead of taking 1 MiB from the arena (and evicting textures for it) every frame. Making the fallback per surface (the VRAM display keeps its GPU present while a scattered 600 KiB snapshot surface is read back) was tried: QEMU reproduces the refusal (present: destination … not physically contiguous after an app returns to the home screen) and with that change the soak's tap after a page swipe did nothing in 2 of 2 runs (stale home screen); the old process-wide fallback passes, so it stays.
    • ios3ds-wifid polled the mailbox every 4 ms when idle (three syscalls and a 4 KiB copy, 250 times a second: 28.7 s of system time in 630 s in run 24, ~4.5 % of the CPU); after ~0.25 s without a frame it now polls every 20 ms. A frame from iOS still wakes it at once.
  • New 3DS: 256 MiB (docs/n3ds.md section 6): the stub sets PDN_LGR_CNT bit 0 and probes 0x28000000-0x2FFFFFFF for RAM of its own (N3RES_RAM); the ARM9 patches boot_args.memSize and the device tree's /memory reg; the GPU arena is given back and retried if IOMallocContiguous places it above 0x28000000 (GPU reach unverified). QEMU's new3ds=on machine now has 256 MiB (its GPU model reaches the first 128). XNU needed no patch: the entry stub maps memSize with supersections and the VM takes the rest.
  • Results (QEMU, --icount 2): New 3DS model, free memory after boot 180.7 MiB (Old: 51.6), memorystatus_level 81 (63); after six Safari pages 141 MiB free, level 70 (Old: 23 MiB, 48); the GPU arena landed at PA 0x26206000 and CA stayed on the GPU. Safari 6/6 pages on both models with the changes; emu/soak.py --cycles 5 PASS on Old and New (one Old run failed only the lock round's unlock screenshot, as rel's soak on main did; the rerun on a fresh image passed). make test green.
  • Root cause, as far as QEMU shows: not physical memory (96 MiB with 2 MiB free still loads), not jetsam, not our network path (above). Re-log 72 gets the same text deterministically for HTTPS in Safari once TLSFix is in it (SANDBOX=1), which points at an allocation inside Safari's own process rather than system RAM; the stock hardware reports (runs 23/24 predate TLSFix) could not be reproduced. MobileSafari now always logs the failing NSError with _kCFStreamErrorDomainKey/CodeKey ([applog] MobileSafari load error …), so the next hardware log names the layer.

76. Cameras, run 30: the 1-2 s preview loop was the GPU's texture cache; frame alignment at the vertical blank; stills (2026-11-21)

Log: build/hwlogs/run30.txt (build 44), frame dumps reviewed by the coordinator (private, not in the tree).

  • Loop: the kernel delivered fresh frames (words = frames x 38400, 0 overruns; consecutive dumped frames differ), the plug-in converts every frame into a pool CVPixelBuffer and enqueues it, yet the user saw 1-2 s of frames repeating. Run 30's [gl] CA lines: 0.0 texture uploads per frame while the camera ran at ~15 fps. CA binds each IOSurface of the plug-in's pool to a texture once; on Apple's GPU that texture is the surface memory, but ios3ds' PICA200 back end keeps a tiled copy and re-uploaded only when GL said the image changed. So the preview cycled through the pool's first frames. Fix (tools/ios3ds-gl/pica_be.c): a surface-backed texture is re-uploaded when the surface's seed (IOSurfaceGetSeed, if present) or a 64-texel sample of it changed. vcd itself was right (a fresh pool buffer per frame, written before enqueueing).
  • QEMU check: the camera pattern now carries a frame counter (a grey 64x48 patch in the middle, Y = 40 + frame mod 160) and tools/ios3ds-camera/tests/preview_counter.py reads it off screenshots of a running session. Same session recipe, image without the GL fix: FAIL (steps back by -5: the preview repeats old frames); with it: PASS for the outer and the inner camera (QEMU delivers 2-3 fps under load, the counter climbs and never steps back).
  • Alignment: a dumped frame was shifted by 16 pixels (8 words) with its right edge wrapped: words lost (or doubled) without the overrun bit; run 30's fill maximum sits at exactly 560 units in every window, likely the FIFO's real cap. The shim cannot see VSYNC, but the vertical blank shows as two or more 1 ms services in a row with an empty FIFO. A frame is now published only if its 38400th word is the last before such a blank; a partial frame at a blank or words after a complete one drop that frame (resyncs, "blank drops" in the 10 s line) and the next frame starts aligned. A pause counts as the blank only within 256 words of a frame boundary (QEMU pauses mid-frame under load). Host tests: a lossy FIFO model (8 words vanish every 3rd frame, 4 come twice every 5th) delivers only whole frames; mid-frame pauses cost under 10 % of the frames.
  • Stills: run 30 has no StillImageCaptureNow at all (0 stills; one tap near the shutter at 149,437 while the outer camera ran): the request never reached the plug-in. In QEMU the same build takes photos upright and with the console face down (emu/session.py set mcu-orient 5, run 30's accelerometer read as face down, SpringBoard orientation 6), and Camera Roll gets them. The plug-in now logs every still request (still requested (frame N)) and any failure on the still path, so the next log says whether Camera.app asked.
  • Next hardware log must show: [gl] CA lines with texture uploads per frame > 0 while the camera runs, a preview that moves; 0 blank drops or a small count in the 10 s line (a large one means the FIFO keeps losing words: CDMA drain next); after a shutter tap still requested and still image #1, or nothing (then Camera.app never asked: look at the shutter's state on the screen).

77. Cydia on the first home page, and a warm SpringBoard folder (2026-11-21)

  • Home screen layout: a freshly built rootfs had no /private/var/mobile/Library/SpringBoard/IconState.plist, so SpringBoard created its own on first boot and put Cydia alone on page 2 (re-log 60). The build now writes Apple's 4.2.1 iPod2,1 layout into the image: the 4 dock icons, the 15 stock page-1 icons in their original order including the Utilities folder (Clock, Calculator, Voice Memos), and com.saurik.Cydia in the first free slot of page 1. It lives in a cydia_plist_write group in rootfs/recipe.json; scripts/mkrootfs.py applies it only when Cydia is actually installed (creating the parent directory with its inherited owner, 501 under /var/mobile), so --no-cydia keeps the stock first-boot behaviour. tests/test_cydia.py checks the plist is serialisable, has 21 unique icons, only the one Utilities folder and at most 16 icons per page.
  • Folder warm-up: the first folder open on a fresh image stalls ~2 s of guest time (QEMU --icount 2; several seconds on the console) while lsd renders every icon's ghostly image (getIconImage:4), +[SBLinenView _generateLinenStripsIfNeeded] draws the folder linen and +[SBIcon homeScreenIconOverlayImage] builds the overlay. The caches survive reboots. tools/ios3ds-diag/applog.c (inserted into SpringBoard) now does that work in the background: a CFRunLoopTimer starts 30 s after SpringBoard loads, runs one item per 0.5 s tick in the default runloop mode (so not during a touch drag) and logs [sbwarm] linen, icon overlay and N of N ghostly icons ready (X ms on the main thread, done Y s after the first step). Boot-arg ios3ds_sbwarm=0 disables it. sb_responds() now masks the BOOL in r0's low byte instead of testing the whole register.
  • QEMU check (emu/session.py start --icount 2, fresh image): [input] connected to SpringBoard at ~80 s; the warm-up reported 28/28 icons, 2050 ms of main-thread work done 15 s after its first step. page1.png (t=139 s) shows Cydia on the first page (row 4, column 3, right of Camera and below iTunes) and the Utilities folder still in row 3, column 2, with the stock dock at the bottom. Tapping Utilities at iOS point (120,237) left the home screen unchanged at 1 s and 2 s, was mid-slide at 4 s (dark linen panel rising, chevron, dimmed home icons behind) and fully open (Utilities: Clock, Calculator, Voice Memos) at ~10 s of QEMU wall time; a clean re-run matched the fully-open screenshot pixel-for-pixel at 10 s and stayed open through 15 s. emu/soak.py --cycles 5 --icount 2 on a fresh image: PASS (boot 80 s, 5 cycles, 0 panics/stalls/crashes/md0 errors, no recoveries). make test green; make userland and make sdimg clean.
  • Also: rootfs/files/com.ios3ds.sample.plist now samples every 10 s instead of 60 s, so short QEMU runs have [smp] data early.

78. New 2DS XL run 1: scattered CA surfaces through an arena copy, SELECT+START's lost write (2026-11-21)

  • Log (docs/hwlogs/n2dsxl-run1.txt, build 0.4.0 m1-0.3.0-62-g6d963b6): the New 3DS work runs on hardware: 804 MHz, timers /192 >>1 at 402.15 MHz, clock ratio 1000/1000 over 33 min, FCRAM extension: iOS gets 256 MiB, C-stick/ZL/ZR, no panic.
  • The read-back mode: line 814, [pica] present: destination 0x04d94000 (+614400) not usable: not physically contiguous (PA 0x271fa000 at +0x1000 …) after an app went back to the home screen, then reading surfaces back through the CPU from now on. CA's render thread went from 13.5-16 ms per frame (GPU presents) to 31-37 ms (1.0 CPU read-back of 600 KiB per frame) for the remaining 30 minutes. The same fallback is in run 21, 25, 29 and issues 1 and 5 on Old consoles.
  • Fix (tools/ios3ds-gl/pica_be.c): a target whose present is refused with PICA_ERR_NOT_CONTIG keeps its swizzle pass and runs the same PPF transfer (format, flip) into a linear 600 KiB arena buffer; the shim's READ then copies it out with copyout through the caller's own mapping, so the scattered pages are handled by XNU and no pixel passes through the CPU in userland. All other surfaces keep the direct present; other refusals still switch the process to the read-back. CA's 300-frame line counts these as "via an arena copy". Host test: every destination refused (IOS3DS_HOST_PRESENT=0) and the present check still passes against the CPU read-back. The QEMU soak reproduces the refusal: CA's 320x480 surfaces at 0x4a74000 / 0x4882000 after the 3rd and 4th app.
  • The "stale home screen" of re-log 75 was the soak's timing, not the display. Screenshots every 2 s of the soak's steps (emu/soak.py cycle 4): 4 s after the swipe back the page is still scrolling (offset, page 2's edge in view); the tap then only stops the scroll and YouTube does not open; the page settles on page 1 correctly. With the frames presented on the GPU each one costs QEMU's software PICA200 a full swizzle draw, which takes host time but no guest time, so a scroll lasts longer in wall-clock seconds than with the CPU read-back; with a longer wait the same tap opens YouTube. emu/soak.py now waits for the screen to stop changing after the swipes (and holds a touch 0.15 s before moving, since --icount's idle time warp made a 0.4 s swipe start 50 points late: [input] down 88,240).
  • QEMU, --icount 2, after the fix: two scattered surfaces in the soak steps (0x4882000, 0x4904000), CA keeps 1.0 GPU presents and 0.0 read-backs per frame, render thread 7.5-8.6 ms per frame over 600 frames of page swipes (before: from the first scattered surface on, every frame was a read-back; re-log 51 measured 19-27 ms per frame for that under --icount 2). Hardware before (this log): 13.5-16 ms with presents, 31-37 ms after the fallback.
  • SELECT+START never panicked on hardware (two presses, line 3515 and later). The request word was shim+0x6C, in the cache line of irq_save0-2 and st_vblanks, which the ARM11 writes on every interrupt: the line stayed dirty in the L1, the shim read its own stale 0, and each write-back put the 0 over the ARM9's 1 in RAM. QEMU has no caches, so it always worked there. The word is now shim+0x6500, a line only the ARM9 writes (zeroed at boot, it is outside shim.bin); shim_set_decrementer invalidates it in the L2 (New 3DS, n3ds_l2=1) and the L1 before reading, and shim_user_panic cleans its 0 back. QEMU, Old and --new3ds: panic(cpu 0 …): ios3ds: panic requested from the 3DS (SELECT+START).
  • Volume slider: not a bug. MCU register 0x09 reads the same on the New 2DS XL (the log has the slider moving 0 → 56 → 2 → 44 → 0/63); iOS's volume follows it only when the slider moves, so L/R (HID volume up/down) still change iOS's volume with the slider at 0. Whether the CODEC also applies the slider in hardware is not checked.

79. PICA_OP_SCATTER: per-page copy into a scattered CA surface (2026-11-21)

  • Entry 78's implementation was only an intermediate step. Copying the frame out of the arena with PICA_OP_READ+copyout works on the host (the host "physical" memory is one flat allocation), but the shim's READ needs one contiguous physical range to validate; the very destination that PRESENT refused cannot be named that way. Protocol version 4 adds PICA_OP_SCATTER instead: the engine still runs the swizzle pass and the same PPF transfer into a linear arena block; then the shim walks the caller's page tables again for every 4 KiB page (user read/write, AP=3/APX=0, FCRAM only — VRAM has no kernel linear map), maps that page at pa + 0x60000000, cleans+invalidates the caller's own lines for it, copies the 4 KiB through the kernel mapping, writes those lines back and invalidates the New 3DS L2 line. Any page that fails the walk, or a GPU error, is the ordinary process-wide read-back fallback; only a non-contiguous destination takes the detour.
  • Host tests (make test): 6678 pica checks + 39 input checks, 0 failures; ios3ds-gl host-test passes five runs, including every destination forced non-contiguous (IOS3DS_HOST_PRESENT=0), the new PRESENT test flag (IOS3DS_GL_SCATTER=1) and the wrong-swizzle run. test_pica's test_scatter copies a source block into three scattered pages (0x30000000, 0x30004000, 0x30011000), checks three caller-line invalidations and three write-backs, checks a partial last page and refuses unmapped, unaligned, zero-length and non-arena requests. Both forced runs log "through an arena copy" and "GPU present check passed" with no CPU read-back. ca_frame() also no longer underflows its CPU-time average when SpringBoard's render thread restarts (the short-interval hook made that visible).
  • Shim size: the GPU part was 32144 of 32768 bytes — 624 bytes of headroom, less than CI's devkitARM overhead (~600). scripts/mkboot.py now compiles only pica.c and pica_mirror.c (the hot request/IRQ paths) at -O2; pica_drv.c, cam.c and the already -Os pica_diag.c are cold-ish and compile at -Os: GPU part 31216 bytes with the test flag (1552 free, ~950 left after CI's compiler). mkboot prints both sizes on every make sdimg.
  • Soak harness: a first 5-cycle --icount 2 soak reached the scattered surface and kept it on the arena copy (no "reading surfaces back through the CPU" line), but cycle 4's unlock screenshot was black: settled() accepted two identical black frames while the backlight was fading in. It now requires brightness > 10 as well as two equal frames (the home-screen reference loop already did); the rerun on a fresh image is in the bullet below.
  • QEMU proof, Old and New 3DS, fresh images, --icount 2: emu/soak.py --cycles 5 printed Result: PASS on both models (0 panics, stalls, I/O errors, crashes; home-screen diff 0.0-2.4 per cycle, after-unlock diff 0.00-0.02). Both logs contain a real refusal from CA's second surface — [pica] present: destination 0x04af6000 (+614400) … not physically contiguous (Old; 0x04a74000 on New) — followed by [gl] pica: surface … through an arena copy for two surfaces, and no "reading surfaces back through the CPU" line. The screen is not stale: every Home tap restores the reference screenshot and the lock round ends on the home screen. A separate 5-cycle run with IOS3DS_CA_LOG_FRAMES=10 and IOS3DS_GL_SCATTER=1 (test hooks in SpringBoard's environment of that image only) makes the detour deterministic — [pica] present: destination 0x04800000 … not physically contiguous, [gl] pica: surface 0x4800000 … through an arena copy — and brackets it in [gl] CA: lines: frame 77 render thread CPU 26999 us, 1.4 GPU presents (0.0 via an arena copy); frame 88 CPU 28999 us, 1.6 GPU presents (0.1 via an arena copy); frame 143 CPU 25999 us, 1.6 GPU presents (0.1 via an arena copy). The 10-frame windows include app launches (and texture uploads), so they are not a clean per-frame benchmark: the steady-state 300-frame averages are in entry 78 (7.5-8.6 ms on the GPU, 19-27 ms in QEMU's CPU read-back, 31-37 ms on hardware). What these lines show is that the bounce adds one copy with no process-wide "reading surfaces back through the CPU from now on" line. The VRAM display keeps its direct present throughout.
  • SELECT+START (7a0d4ac, re-verified here): QEMU, Old and --new3ds, both pressed after SpringBoard came up: [monitor] SELECT+START: asking XNU to panic (thread dump), then panic(cpu 0 caller 0x80840710): ios3ds: panic requested from the 3DS (SELECT+START) - thread dump follows, with 101 (Old) and 44 (New) backtrace: lines. The dedicated cache line at shim+0x6500 is what the hardware fix needs; QEMU has no caches, so this re-run only checks the wiring, not the hardware failure mode.

80. Voice Memos playback, silent headphones, songs in the Music app (2026-11-21)

Design: docs/audio.md §4 (headphones), §9 (Voice Memos), §10 (Music). Hardware input: run 32 (0.4.0-era build).

  • Voice Memos, cause: run 32 and QEMU both log Remaking completed with status: AVRemakerNotification_Failure ... OSStatus error -50. The .mov pulled from the QEMU image is iLBC 8 kHz mono (stsd ilbc), its mdhd at 44,100: not a rate problem (the 3DS mic's 11,901 Hz is resampled to the I2S frame rate in the shim). VoiceMemos -[RCAudioInputDevice _createCaptureController] (0x1e5b4, disassembled with capstone): VMDebugLosslessRecording ? 'lpcm' : GSSystemHasCapability(kGSEncodeAACCapability) ? 'aac ' : 'alac'. The only AAC encoder in the dyld cache is ACAACEncoder_IOA2 (AudioCodecHWCodecLookup, S5L8720 hardware; software encoders: ALAC, IMA4, AMR, iLBC), so Celestial records iLBC and the pass-through remake into .m4a fails.
  • Voice Memos, fix: encode-aac = false in N72AP.plist (recipe plist_merge) -> 'alac'. QEMU (IOS3DS_MIC=sine:440:3000, --icount 2): Remaking completed with status: AVRemakerNotification_Complete; the .m4a is ALAC 44,100 Hz mono, decodes on the host to the sine at peak 3024 (source 3000); playing it from the list gives [csnd] non-silent frames.
  • Headphones, cause (static, no hardware access): run 32 shows the whole iOS side working (headphones plugged in, iOS route -> headphones, CS42L58 6a (-22 dB) -> CSND volume 2068/32768, stream peak 8583) and silence. The logged "CODEC headset detect 91" is page 100 reg 0x43, the detection control we write, so it says nothing. Against libn3ds CODEC_init/soundInit (open_agb_firm's sequence; GBATEK "3DS TSC, Register Summary") 0.4.0 skipped the headphone filter coefficients (page 11), never drove the Old 3DS de-pop line (GPIO3 bit 0; GBATEK's post-bootrom GPIO3 value 0x0DFB has it high) and powered the headphone driver only at boot, while the output select pointed at the speaker.
  • Headphones, change: boot.cfg hp_codec=1 (default): page 11 filters (pass-through + 10 Hz high-pass, hw_cal.c defaults) before the DACs power up; de-pop output low once the MCU reports system model 0 (reg 0x7F byte 9; New 3DS untouched, the pin is the C-stick IRQ there); on each plug-in page 101 reg 0x0b 0 -> 0x3c/0x1c, 0x0c unmute, 0x16/0x17 analog volume, 38 ms. hp_codec=0 = 0.4.0. Diagnostics: [audio] CODEC at boot|headphones|speaker: ... read back page 100 0x2c (the CODEC's own jack status) 0x43 0x45 0x25 0x26 0x76, page 101 0x0a 0x0b 0x0c 0x16 0x17 0x11, page 0 0x3f-0x42, page 1 (TSC2117) 0x1f 0x24 0x25 0x28 0x29, GPIO2/GPIO3; the jack line now prints 100:2c. QEMU (CODEC stub reads 0): [audio] de-pop (Old 3DS): GPIO3 bit 0 was input 0 -> output 0, dump lines present, boot unchanged.
  • Music, format (dyld cache strings + disassembly, MusicLibrary-720.20): 4.2.1 reads iTunes_Control/iTunes/iTunes Library.itlp/{Library,Locations,Dynamic,Extras,Genius}.itdb (no MediaLibrary.sqlitedb, that is iOS 5). With no library _MLSDBLoadAndInitSharedInstances only runs /usr/local/bin/ddbtosql (not on retail builds) on an iTunesDB; the rootfs has no template; writers are only com.apple.mobileipod, iPodOut and itdbprepserver (MLProcessHasDatabaseWritePermissions 0x30094488). A first QEMU boot with the Music app created nothing. SQLMusicLibraryPostProcessCommands.plist carries command set "8" = the user_version libgpod's iTunes 9 schema declares (db_schema_upgrade_info 8, 19).
  • Music, cbk: MLSSqliteVFSOpen (0x3000a4f4) asks _AOU243378_7_1 (0x3008530c) for <file>.cbk when the process may write and the file is in the managed list, then verifies SHA-1 blocks plus iTunes' device-keyed signature (libgpod mk_Locations_cbk). Patched to mov r0,#0; bx lr (cache file offset 0x8530c).
  • Music, build: scripts/music.py: libgpod-style rows (items, albums, artists, genre_map, location_kind_map, hidden master playlist "iPod", location relative to base 1 iTunes_Control/Music, item_stats, container_ui), files as Music/F00/XXXX0000.ext; test song = own melody, additive synthesis, ALAC .m4a with escape frames (host test decodes it back bit-exact; ffmpeg/ffprobe read it as alac 44.1 kHz stereo). --music DIR in install.py (default SD/ios3ds/music/), mksd.py, mkrootfs.py.
  • Validation (this branch): make test (55 tests incl. test_music.py), make userland and a fresh make sdimg (1 song in the library) pass. python3 emu/soak.py --cycles 5 --icount 2 on a fresh image: Result: PASS (0 panics, hangs, md0 errors or crashes; home screen recovered in all 5 cycles). Several fresh-image soak runs failed only the cycle-4 lock round's unlock screenshot: the slide-after-wake gesture was swallowed while the input daemon still polled at 10 Hz (re-log 75). emu/soak.py now retries a missed unlock slide (recorded as unlock_attempts in report.json); the final run above passed.

81. Slide to power off over an app: SBAlertWindow is modal too (2026-11-21)

  • Report (hardware run 27): with Camera open, holding POWER and dragging the power-off slider did nothing. The daemon's debug log showed [input] touch target com.apple.camera for the drag: the touch still went to the app's purple port because SpringBoard's frontmost app stays Camera while its slider covers it. The modal-state publisher in tools/ios3ds-diag/applog.c checked SBAwayController isLocked, SBAlertItemsController hasVisibleAlert and UIApplication topMostAlert, but the slider is an SBAlert in an SBAlertWindow, which topMostAlert does not report.
  • Fix: in modal_tick(), when bit 2 is not already set, walk UIApplication sharedApplication's windows, look for a visible (isHidden NO) window whose object_getClassName() is SBAlertWindow, and set bit 2 of *com.ios3ds.sb.modal. object_getClassName is resolved once in modal_start() next to objc_msgSend; the window access uses the existing respondsToSelector: guards and reads the BOOL from r0's low byte. The daemon's diagnostic now logs a touch target on every touch while modal (QEMU's frontmost-app id can stay empty while an app loads) and names an alert (bits 1/2 of the state) before the lock screen, so the log says touch target SpringBoard (alert) for the slider.
  • QEMU check (emu/session.py start --icount 2, fresh image): [input] connected at 110 s; tapping Settings (51,323) logged touch target com.apple.Preferences; lock-button holds brought up the slider (screenshot slider.png); drag 30 60 300 60 1.2 logged touch target SpringBoard (alert) and iOS shut down (ios3ds-mcu: halt: asking the ARM9 to power off through the MCU, launchd's shutdown line, QEMU exited). Repeated after rebasing this entry onto the current main: connected at 140 s, the same touch target SpringBoard (alert) and shutdown. An instrumented run first confirmed the causal chain: [applog] sb.modal 5 (locked + alert) and [input] modal 5 on the drag's touch-down. make userland and make sdimg clean.
  • Soak: python3 emu/soak.py --cycles 5 --icount 2 on a fresh image: PASS (boot 93 s, 5 cycles, 0 panics/stalls/crashes/md0 errors). After the rebase, a first soak hit the known Spotlight-after-Home recovery flake (cycles 1 and 2, no panics or I/O errors); the rerun on a fresh image passed (boot 162 s, 5 cycles, 0 panics/stalls/crashes/md0 errors, one recovered "Dismiss" cycle). make test green before and after the rebase.

82. User data carry-over on update (revised) (2026-11-21)

  • Problem: every install/update rebuilt sd:/ios3ds/rootfs.hfs (the iOS disk), wiping saved Wi-Fi networks, settings, photos, voice memos and any other user data.
  • Fix: scripts/carryover.py copies the user-data subtrees from the old image into the new one with xpwn's hfsplus (extract/add/mkdir/rm/chmod), preserving mode and the inherited owner: /private/var/mobile (Media, Library/Preferences, Library/SpringBoard, Library/Keyboard, ...), /private/var/preferences/SystemConfiguration (saved Wi-Fi networks) and /private/var/Keychains (Wi-Fi passwords and the keychain). /private/var/lib/dpkg and installed Cydia package files are deliberately not carried: an update can change Cydia/Substrate/the base system, so carrying dpkg state plus package files would desync from the new image and leave broken packages; reinstall packages from Cydia after updating.
  • Exclusions: Library/Caches and Library/Logs under /private/var/mobile are skipped (MobileInstallation's app list cache would be stale after an update), plus any *.sqlite-journal / *.lock leftovers. /private/var/mobile/Media/iTunes_Control is skipped too: re-log 80's Music library is rebuilt from SD/ios3ds/music and the test song on every install, so the new library must win over one carried from the old card.
  • Safety: before copying, the old data's total size is compared with the new image's free space (parsed from hfsplus ls); if it does not fit, or any entry fails to copy or verify, the old image is kept on the card as sd:/ios3ds/rootfs.hfs.bak and a warning with that path is printed. carry_over() returns a string-like result "carried" / "partial" / "nothing" with a reason and the backup path for callers.
  • Opt-in for developer builds: make sd/make sdimg no longer carry from the previous build output (stale SpringBoard defaults would move from build to build and soak images would stop being reproducible); pass CARRY_FROM=/path/to/old/rootfs.hfs (or IOS3DS_CARRY_FROM) to carry from an explicit image. install.py (the user's card) still carries by default, with --fresh to skip, and ignores those env vars.
  • Ownership: xpwn's hfsplus has no chown command (its usage lists ls|cat|mv|mkdir|add|rm|chmod|extract|extractall|rmall|addall|debug; its source is in the shared build/xpwn symlink, not this repo). Like scripts/mkrootfs.py, add/mkdir inherit owner and group from the parent directory, so carried files keep 501:501 under /private/var/mobile and root under Keychains/SystemConfiguration. A post-copy pass compares mode/uid/gid/size against the old image for every entry, so a wrong owner becomes a partial result instead of silent data loss; a host test builds images with 501-owned parents to check it.
  • Speed: one ls per directory in the old image is cached and reused for the size check, the copy and the verification; directories are created once (no exists check per file). tests/bench_carryover.py (1000 small files plus 50 x 300 KiB in Media/DCIM): carried in 32.4 s, well under the two-minute budget, so no further process batching was needed.
  • Validation: make test green after the rebase onto main (63 Python tests, incl. the carry-over cases and the make sd opt-in check, plus the pica/gl/wifi/input host tests). End-to-end install.py --staging build/staging --no-cydia --no-tlsfix into a temporary folder used as a card: an old 16 MiB rootfs.hfs with a 501:501 plist, a 64:0 keychain file, a root-owned SystemConfiguration plist, a photo, a stale cache and an old iTunes_Control/old.itdb produced carry-over result: carried; the new card has the four user files with their old contents, modes and owners, no stale cache/old library, and a freshly built 1-song Music library. No .bak was created. With a deliberately root-owned keychain file (a parent owner change the hfsplus CLI cannot repair) the same path returned partial, kept sd:/ios3ds/rootfs.hfs.bak and printed the warning — no silent loss. A fresh rm -f build/sd.img && make sdimg (no CARRY_FROM) has no carried IconState and python3 emu/soak.py --cycles 5 --icount 2 printed Result: PASS (boot 140 s, 5 cycles, 0 panics/stalls/md0 errors/crashes).