/*
 * kido-hal-arm64.c — Kido ARM64 bare-metal HAL.
 *
 * The per-arch shim. ARM64 specifics live HERE and nowhere else.
 * Fills kido-boot's HAL table (console_putc/puts, timer_ticks/hz) and
 * probes ARM64 capabilities for the boot stage.
 *
 * WHAT IS REAL vs STUB (deliberated 2026-10-14, RPi4 closed 2026-10-23):
 *  REAL: generic timer (CNTPCT_EL0/CNTFRQ_EL0 — EL0-safe by design),
 *        FPU presence (ID_AA64PFR0_EL1), MMU presence
 *        (ID_AA64MMFR0_EL1; bring-up stays a STUB), MIDR_EL1 identity,
 *        QEMU 'virt' PL011 TX console (polled, TXFF-checked),
 *        RPi4 AUX mini-UART: init sequence (AUX enable, IER/LCR/MCR/
 *        BAUD, GPIO14/15 -> ALT5, CNTL) + polled TX (LSR bit 5).
 *  STUB (loud): memory map without firmware bootinfo (needs DTB/UEFI
 *        parse — kido-mem's job), MMU bring-up.
 *
 * RPi4 PROOF STATUS: WRITTEN, NOT EXECUTED ON HARDWARE. Register
 * addresses verified this session against the BCM2835 ARM Peripherals
 * doc (AUX block bus 0x7E215000), the OSDev Pi4 /proc/iomem dump
 * (ARM-physical base 0xFE000000), Ultibo BCM2711 (UART1 = GPIO14/15
 * ALT5), and the rpi4os bare-metal reference (PERIPHERAL_BASE
 * 0xFE000000, AUX_UART_CLOCK 500 MHz paired with core_freq_min=500).
 * The init sequence is pinned by the hosted scratch-register double;
 * a real Pi4 run is N8toriousAi's to witness.
 *
 * ENTRY-SHIM CONTRACT: run probe() at EL1+ (ID_AA64* traps at EL0) and
 * fill kido_bootinfo_t from the firmware handoff first.
 *
 * TESTING: KIDO_HOSTED_TEST builds a test double exercising the table-
 * fill/probe contract on the dev machine (+KIDO_HAL_ARM64_SELFTEST for
 * a runnable self-test). KIDO_HAL_ARM64_SYNTAX_TEST (test-only) lets
 * the ARM64 asm paths parse under -fsyntax-only on a non-ARM64 host;
 * execution under it is meaningless and it must never ship in a build.
 */

#include "kido-hal-arm64.h"

/* Shared constant: the RPi4 mini-UART baud register value is a pure
 * function of the (named, firmware-pinned) VPU clock, so both the
 * ARM64 driver and the hosted double read it from here. */
#define KIDO_RPI4_VPU_HZ       500000000u /* config.txt: core_freq_min=500 */
#define KIDO_RPI4_BAUD_115200  541u       /* 5e8/(8*115200)-1 -> 115315   */

#if defined(__aarch64__) || defined(KIDO_HAL_ARM64_SYNTAX_TEST)

/* ------------------------------------------------------------------ */
/* ARM64 register primitives. MRS strings are checked by the assembler */
/* on a real target; on the dev host only C parsing is verified.       */
/* ------------------------------------------------------------------ */

static inline uint64_t kido_mrs_cntpct_el0(void)
{
    uint64_t v;
    __asm__ volatile("mrs %0, cntpct_el0" : "=r" (v));
    return v;
}

static inline uint32_t kido_mrs_cntfrq_el0(void)
{
    uint64_t v;
    __asm__ volatile("mrs %0, cntfrq_el0" : "=r" (v));
    return (uint32_t)v; /* 0 => firmware never programmed it */
}

static inline uint64_t kido_mrs_id_aa64pfr0_el1(void)
{
    uint64_t v;
    __asm__ volatile("mrs %0, id_aa64pfr0_el1" : "=r" (v)); /* EL1+ only */
    return v;
}

static inline uint64_t kido_mrs_id_aa64mmfr0_el1(void)
{
    uint64_t v;
    __asm__ volatile("mrs %0, id_aa64mmfr0_el1" : "=r" (v)); /* EL1+ only */
    return v;
}

static inline uint64_t kido_mrs_midr_el1(void)
{
    uint64_t v;
    __asm__ volatile("mrs %0, midr_el1" : "=r" (v)); /* EL1+ only */
    return v;
}

/* ------------------------------------------------------------------ */
/* PL011 UART, minimal polled TX. Assumes firmware already configured  */
/* baud/clocks (true on QEMU virt; bare-metal-without-firmware is the  */
/* documented STUB case). TX wedged => spin: without a console there  */
/* is nowhere to report, and kido_halt() spins by the same philosophy. */
/* ------------------------------------------------------------------ */

#define KIDO_PL011_DR_OFFSET 0x00u
#define KIDO_PL011_FR_OFFSET 0x18u
#define KIDO_PL011_FR_TXFF   (1u << 5)

static void kido_pl011_putc(uint64_t base, char c)
{
    volatile uint32_t *dr =
        (volatile uint32_t *)(uintptr_t)(base + KIDO_PL011_DR_OFFSET);
    volatile uint32_t *fr =
        (volatile uint32_t *)(uintptr_t)(base + KIDO_PL011_FR_OFFSET);
    while ((*fr & KIDO_PL011_FR_TXFF) != 0u) {
        /* spin: TX FIFO full */
    }
    *dr = (uint32_t)(uint8_t)c;
}

/* ------------------------------------------------------------------ */
/* RPi4 AUX mini-UART (uart1). On the Pi 4 the mini UART is the        */
/* PRIMARY header UART (GPIO14/15) and the PL011 goes to Bluetooth —   */
/* verified this session, so this is the header UART, not the         */
/* consolation prize. TX-only: the HAL console contract is putc/puts. */
/*                                                                     */
/* Addresses: ARM-physical, Low Peripheral Mode (base 0xFE000000).     */
/*   GPIO: GPFSEL1 +0x04 — GPIO14 bits [14:12], GPIO15 bits [17:15],   */
/*         ALT5 = 0b010 (Ultibo BCM2711: UART1 = GPIO14/15 ALT5).      */
/*   AUX:  ENABLES +0x04 (bit 0 = mini-UART enable);                  */
/*         MU_IO +0x40; MU_IER +0x44; MU_LCR +0x4C; MU_MCR +0x58;      */
/*         MU_LSR +0x54 (bit 5 = transmitter empty, 16550 canon);    */
/*         MU_CNTL +0x60; MU_BAUD +0x68                               */
/*         (BCM2835 ARM Peripherals §2.2.2, bus 0x7E215000).          */
/*                                                                     */
/* Baud law (BCM2835 §2.2.1): baud = vpu_hz / (8 * (baud_reg + 1)).   */
/* THE ONE FIRMWARE BET: KIDO_RPI4_VPU_HZ = 500 MHz — the rpi4os      */
/* canonical pairing (AUX_UART_CLOCK 500000000 with core_freq_min=500  */
/* in config.txt pins the VPU clock). 541 -> 115315 baud (+0.1%).     */
/* If the firmware clocked the VPU differently the console skews —    */
/* silent, so the bet is named here, never buried. A mailbox clock    */
/* query is the named future that removes it (deliberation D2).       */
/*                                                                     */
/* GPIO pulls deliberately untouched: pulls cannot affect a driven    */
/* TX pin, and a TX-only console never reads. Firmware owns them      */
/* (deliberation C3).                                                  */
/*                                                                     */
/* Sequence: enable AUX -> CNTL=0 -> IER=0 -> LCR=3 (8-bit) -> MCR=0  */
/* -> BAUD -> GPIO14/15 ALT5 (read-modify-write: other pins in        */
/* GPFSEL1 are not ours) -> CNTL=3 (TX+RX on). All writes absolute    */
/* except AUX_ENABLES |= 1, so re-init is idempotent by construction. */
/* ------------------------------------------------------------------ */

#define KIDO_RPI4_GPIO_BASE    0xFE200000u
#define KIDO_RPI4_GPFSEL1      (KIDO_RPI4_GPIO_BASE + 0x04u)
#define KIDO_RPI4_AUX_BASE     0xFE215000u
#define KIDO_RPI4_AUX_ENABLES  (KIDO_RPI4_AUX_BASE + 0x04u)
#define KIDO_RPI4_MU_IO        (KIDO_RPI4_AUX_BASE + 0x40u)
#define KIDO_RPI4_MU_IER       (KIDO_RPI4_AUX_BASE + 0x44u)
#define KIDO_RPI4_MU_LCR       (KIDO_RPI4_AUX_BASE + 0x4Cu)
#define KIDO_RPI4_MU_MCR       (KIDO_RPI4_AUX_BASE + 0x58u)
#define KIDO_RPI4_MU_LSR       (KIDO_RPI4_AUX_BASE + 0x54u)
#define KIDO_RPI4_MU_LSR_TXE   (1u << 5)
#define KIDO_RPI4_MU_CNTL      (KIDO_RPI4_AUX_BASE + 0x60u)
#define KIDO_RPI4_MU_BAUD      (KIDO_RPI4_AUX_BASE + 0x68u)

static void kido_rpi4_uart_init(void)
{
    volatile uint32_t *enables =
        (volatile uint32_t *)(uintptr_t)KIDO_RPI4_AUX_ENABLES;
    volatile uint32_t *ier =
        (volatile uint32_t *)(uintptr_t)KIDO_RPI4_MU_IER;
    volatile uint32_t *lcr =
        (volatile uint32_t *)(uintptr_t)KIDO_RPI4_MU_LCR;
    volatile uint32_t *mcr =
        (volatile uint32_t *)(uintptr_t)KIDO_RPI4_MU_MCR;
    volatile uint32_t *cntl =
        (volatile uint32_t *)(uintptr_t)KIDO_RPI4_MU_CNTL;
    volatile uint32_t *baud =
        (volatile uint32_t *)(uintptr_t)KIDO_RPI4_MU_BAUD;
    volatile uint32_t *gpfsel1 =
        (volatile uint32_t *)(uintptr_t)KIDO_RPI4_GPFSEL1;
    uint32_t v;

    *enables |= 1u;                 /* AUX: mini-UART on                 */
    *cntl     = 0u;                 /* TX/RX off during setup            */
    *ier      = 0u;                 /* no interrupts                     */
    *lcr      = 3u;                 /* 8-bit mode                        */
    *mcr      = 0u;
    *baud     = KIDO_RPI4_BAUD_115200;

    v  = *gpfsel1;                  /* GPIO14/15 -> ALT5 (mini-UART)     */
    v &= ~((7u << 12) | (7u << 15));
    v |= (2u << 12) | (2u << 15);   /* ALT5 = 0b010                      */
    *gpfsel1 = v;

    *cntl = 3u;                     /* TX+RX on                          */
}

static void kido_rpi4_putc(uint64_t base, char c)
{
    volatile uint32_t *io =
        (volatile uint32_t *)(uintptr_t)(base + 0x40u); /* MU_IO  */
    volatile uint32_t *lsr =
        (volatile uint32_t *)(uintptr_t)(base + 0x54u); /* MU_LSR */
    while ((*lsr & KIDO_RPI4_MU_LSR_TXE) == 0u) {
        /* spin: transmitter not empty — same philosophy as PL011 */
    }
    *io = (uint32_t)(uint8_t)c;
}

/* ------------------------------------------------------------------ */
/* Board table. Runtime selection (probe-then-adapt), never a          */
/* compile-time guess. Every row is a REAL board now: init == NULL    */
/* means "firmware owns this UART" (qemu-virt PL011); a non-NULL init */
/* runs the board's bring-up from fill(). Unknown board = loud        */
/* NO_CONSOLE, never a scribble at a guessed address.                 */
/* ------------------------------------------------------------------ */

typedef struct kido_board_uart {
    uint32_t board_id;
    const char *board_name;
    uint64_t uart_base;
    void (*uart_init)(void);
    void (*uart_putc)(uint64_t base, char c);
} kido_board_uart_t;

static const kido_board_uart_t kido_board_uarts[] = {
    { KIDO_BOARD_QEMU_VIRT, "qemu-virt", 0x09000000u,
      NULL, kido_pl011_putc },
    { KIDO_BOARD_RPI4, "rpi4", KIDO_RPI4_AUX_BASE,
      kido_rpi4_uart_init, kido_rpi4_putc },
};

static uint64_t kido_arm64_uart_base = 0u; /* set by fill() */
static void (*kido_arm64_board_putc)(uint64_t, char) = NULL; /* fill() */

static void kido_arm64_putc(char c)
{
    kido_arm64_board_putc(kido_arm64_uart_base, c);
}

static void kido_arm64_puts(const char *s)
{
    while (*s != '\0') {
        if (*s == '\n')
            kido_arm64_putc('\r');
        kido_arm64_putc(*s);
        s++;
    }
}

static uint64_t kido_arm64_ticks(void)
{
    return kido_mrs_cntpct_el0();
}

static uint32_t kido_arm64_hz(void)
{
    return kido_mrs_cntfrq_el0();
}

kido_status_t kido_hal_arm64_probe(const kido_bootinfo_t *bi,
                                   kido_caps_t *caps)
{
    uint64_t pfr0, mmfr0;

    if (bi == NULL || caps == NULL)
        return KIDO_ERR_EARLY_ENV;

    caps->arch_name = KIDO_ARCH_NAME;
    caps->timer_hz  = kido_mrs_cntfrq_el0();
    /* NOTE: 0 here is honest ("firmware didn't program CNTFRQ"); the
     * boot adapt stage turns it into KIDO_ERR_NO_TIMER, loud. */

    /* FPU: ID_AA64PFR0_EL1 FP field [19:16]; 0b0000 = implemented. */
    pfr0 = kido_mrs_id_aa64pfr0_el1();
    caps->has_fpu = (((pfr0 >> 16) & 0xFu) == 0u) ? 1u : 0u;

    /* MMU presence: ID_AA64MMFR0_EL1 PARange [3:0]; 0xF = absent.
     * Presence only — bring-up remains a STUB per the boot header. */
    mmfr0 = kido_mrs_id_aa64mmfr0_el1();
    caps->has_mmu = ((mmfr0 & 0xFu) != 0xFu) ? 1u : 0u;

    /* Identity read kept for the lineage record (unused yet). */
    (void)kido_mrs_midr_el1();

    if (bi->mem_valid == 0u)
        return KIDO_ERR_STUB_REACHED;
    /* STUB: DTB/UEFI memory-map parse not written — kido-mem's job.
     * The entry shim must supply the map; we refuse to invent one. */

    caps->mem_base = bi->mem_base;
    caps->mem_size = bi->mem_size;
    return KIDO_OK;
}

kido_status_t kido_hal_arm64_fill(kido_hal_t *hal, uint32_t board_id)
{
    size_t i;

    if (hal == NULL)
        return KIDO_ERR_EARLY_ENV;

    for (i = 0; i < sizeof(kido_board_uarts) /
                    sizeof(kido_board_uarts[0]); i++) {
        if (kido_board_uarts[i].board_id != board_id)
            continue;
        if (kido_board_uarts[i].uart_init != NULL)
            kido_board_uarts[i].uart_init();
        /* NULL init = firmware owns the UART (qemu-virt PL011). */
        kido_arm64_uart_base  = kido_board_uarts[i].uart_base;
        kido_arm64_board_putc = kido_board_uarts[i].uart_putc;
        hal->console_putc = kido_arm64_putc;
        hal->console_puts = kido_arm64_puts;
        hal->timer_ticks  = kido_arm64_ticks;
        hal->timer_hz     = kido_arm64_hz;
        return KIDO_OK;
    }
    return KIDO_ERR_NO_CONSOLE;
    /* Unknown board: loud refusal. Never scribble at a guessed address. */
}

#elif defined(KIDO_HOSTED_TEST)

/* ------------------------------------------------------------------ */
/* Hosted test double. Exercises the table-fill/probe CONTRACT on the */
/* dev machine: same discipline (all-four-pointers-or-loud-failure,    */
/* loud stubs, no invented memory map), different backends. The timer */
/* is a monotonic counter, NOT wall time — stated, not hidden.         */
/* ------------------------------------------------------------------ */

#include <stdio.h>

/* ------------------------------------------------------------------ */
/* RPi4 scratch-register double. The double's "hardware": init writes */
/* land here in order, and every write is appended to the log so the  */
/* self-test pins the sequence's order+values (the session-22 MMU     */
/* precedent). LSR is never written by init — the test arms it to     */
/* model "transmitter ready".                                          */
/* ------------------------------------------------------------------ */
enum {
    KIDO_DBL_GPFSEL1 = 0,
    KIDO_DBL_ENABLES,
    KIDO_DBL_IO,
    KIDO_DBL_IER,
    KIDO_DBL_LCR,
    KIDO_DBL_MCR,
    KIDO_DBL_LSR,
    KIDO_DBL_CNTL,
    KIDO_DBL_BAUD,
    KIDO_DBL_NREGS
};

typedef struct kido_dbl_write {
    uint8_t  reg;
    uint32_t val;
} kido_dbl_write_t;

static uint32_t        kido_dbl_regs[KIDO_DBL_NREGS];
static kido_dbl_write_t kido_dbl_log[64];
static unsigned        kido_dbl_log_n = 0;

static void kido_dbl_wr(unsigned reg, uint32_t val)
{
    kido_dbl_regs[reg] = val;
    if (kido_dbl_log_n < 64u) {
        kido_dbl_log[kido_dbl_log_n].reg = (uint8_t)reg;
        kido_dbl_log[kido_dbl_log_n].val = val;
        kido_dbl_log_n++;
    }
}

static void kido_dbl_rpi4_init(void)
{
    uint32_t v;

    /* The same 8-write sequence as the real init, in the same order. */
    kido_dbl_wr(KIDO_DBL_ENABLES, kido_dbl_regs[KIDO_DBL_ENABLES] | 1u);
    kido_dbl_wr(KIDO_DBL_CNTL, 0u);
    kido_dbl_wr(KIDO_DBL_IER, 0u);
    kido_dbl_wr(KIDO_DBL_LCR, 3u);
    kido_dbl_wr(KIDO_DBL_MCR, 0u);
    kido_dbl_wr(KIDO_DBL_BAUD, KIDO_RPI4_BAUD_115200);
    v  = kido_dbl_regs[KIDO_DBL_GPFSEL1];
    v &= ~((7u << 12) | (7u << 15));
    v |= (2u << 12) | (2u << 15);
    kido_dbl_wr(KIDO_DBL_GPFSEL1, v);
    kido_dbl_wr(KIDO_DBL_CNTL, 3u);
}

static void kido_dbl_rpi4_putc(char c)
{
    while ((kido_dbl_regs[KIDO_DBL_LSR] & (1u << 5)) == 0u) {
        /* spin like the real thing; the test arms LSR first */
    }
    kido_dbl_regs[KIDO_DBL_IO] = (uint32_t)(uint8_t)c;
}

static void kido_hosted_putc(char c)
{
    putchar((int)c);
}

static void kido_hosted_puts(const char *s)
{
    fputs(s, stdout);
}

static uint64_t kido_hosted_tick_counter = 0u;

static uint64_t kido_hosted_ticks(void)
{
    return ++kido_hosted_tick_counter; /* test double, not wall time */
}

static uint32_t kido_hosted_hz(void)
{
    return 1000u;
}

kido_status_t kido_hal_arm64_probe(const kido_bootinfo_t *bi,
                                   kido_caps_t *caps)
{
    if (bi == NULL || caps == NULL)
        return KIDO_ERR_EARLY_ENV;
    caps->arch_name = "hosted(arm64-shim-test-double)";
    caps->timer_hz  = 1000u;
    caps->has_fpu   = 1u;
    caps->has_mmu   = 0u;
    if (bi->mem_valid == 0u)
        return KIDO_ERR_STUB_REACHED;
    caps->mem_base = bi->mem_base;
    caps->mem_size = bi->mem_size;
    return KIDO_OK;
}

kido_status_t kido_hal_arm64_fill(kido_hal_t *hal, uint32_t board_id)
{
    if (hal == NULL)
        return KIDO_ERR_EARLY_ENV;
    if (board_id == KIDO_BOARD_RPI4) {
        kido_dbl_rpi4_init();
        hal->console_putc = kido_dbl_rpi4_putc;
        hal->console_puts = kido_hosted_puts; /* \r\n shared, board-agnostic */
        hal->timer_ticks  = kido_hosted_ticks;
        hal->timer_hz     = kido_hosted_hz;
        return KIDO_OK;
    }
    if (board_id != KIDO_BOARD_QEMU_VIRT)
        return KIDO_ERR_NO_CONSOLE;
    hal->console_putc = kido_hosted_putc;
    hal->console_puts = kido_hosted_puts;
    hal->timer_ticks  = kido_hosted_ticks;
    hal->timer_hz     = kido_hosted_hz;
    return KIDO_OK;
}

#else
#error "kido-hal-arm64: unreachable — the header enforces arch discipline."
#endif

/* ------------------------------------------------------------------ */
/* Self-test: proves the table-fill/probe contract on the dev machine.*/
/* Build: gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST        */
/*        -DKIDO_HAL_ARM64_SELFTEST kido-hal-arm64.c -o hal-selftest   */
/* ------------------------------------------------------------------ */
#ifdef KIDO_HAL_ARM64_SELFTEST
#ifndef KIDO_HOSTED_TEST
#error "KIDO_HAL_ARM64_SELFTEST needs KIDO_HOSTED_TEST (it runs the hosted test double)."
#endif
#include <stdio.h>

int main(void)
{
    int failures = 0;
    unsigned log_before = 0;
    unsigned i;
    kido_hal_t hal;
    kido_caps_t caps;
    kido_bootinfo_t bi = {
        0x40000000u, 512u * 1024u * 1024u, 1u, KIDO_BOARD_QEMU_VIRT
    };
    kido_bootinfo_t bi_empty = { 0u, 0u, 0u, KIDO_BOARD_QEMU_VIRT };

    /* 1. Known board wires all four pointers. */
    if (kido_hal_arm64_fill(&hal, KIDO_BOARD_QEMU_VIRT) != KIDO_OK) {
        printf("[FAIL] fill(qemu-virt) did not return OK\n");
        failures++;
    }
    if (hal.console_putc == NULL || hal.console_puts == NULL ||
        hal.timer_ticks == NULL || hal.timer_hz == NULL) {
        printf("[FAIL] NULL pointer in filled table\n");
        failures++;
    }

    /* 2. Unknown board -> NO_CONSOLE, never a guessed address. */
    if (kido_hal_arm64_fill(&hal, 99u) != KIDO_ERR_NO_CONSOLE) {
        printf("[FAIL] unknown-board discipline broken\n");
        failures++;
    }

    /* 3. RPi4 board -> OK. The session-2 STUB is now real hardware init;
     * the flip from STUB_REACHED to OK is the point of this session. */
    kido_dbl_regs[KIDO_DBL_GPFSEL1] = 0xE0000000u; /* junk: RMW must keep */
    kido_dbl_regs[KIDO_DBL_LSR] = 1u << 5;        /* TX ready             */
    log_before = kido_dbl_log_n;
    if (kido_hal_arm64_fill(&hal, KIDO_BOARD_RPI4) != KIDO_OK) {
        printf("[FAIL] fill(rpi4) did not return OK\n");
        failures++;
    }

    /* 4. Probe with a firmware map -> OK, sane caps. */
    if (kido_hal_arm64_probe(&bi, &caps) != KIDO_OK) {
        printf("[FAIL] probe with bootinfo did not return OK\n");
        failures++;
    }
    if (caps.mem_size == 0u || caps.timer_hz == 0u) {
        printf("[FAIL] probe returned empty caps\n");
        failures++;
    }

    /* 5. Probe without a firmware map -> STUB_REACHED, never faked. */
    if (kido_hal_arm64_probe(&bi_empty, &caps) !=
        KIDO_ERR_STUB_REACHED) {
        printf("[FAIL] no-bootinfo discipline broken\n");
        failures++;
    }

    /* 6. NULL guards. */
    if (kido_hal_arm64_probe(NULL, &caps) != KIDO_ERR_EARLY_ENV ||
        kido_hal_arm64_fill(NULL, KIDO_BOARD_QEMU_VIRT) !=
        KIDO_ERR_EARLY_ENV) {
        printf("[FAIL] NULL guard broken\n");
        failures++;
    }

    /* 7. The wired console actually emits. */
    if (kido_hal_arm64_fill(&hal, KIDO_BOARD_QEMU_VIRT) != KIDO_OK) {
        printf("[FAIL] re-fill before console check\n");
        failures++;
    } else {
        hal.console_puts("[test] hal console live\n");
        if (hal.timer_hz() == 0u) {
            printf("[FAIL] timer_hz is zero\n");
            failures++;
        }
    }

    /* 8. The RPi4 init is exactly 8 register writes. */
    if (kido_dbl_log_n - log_before != 8u) {
        printf("[FAIL] rpi4 init wrote %u regs, want 8\n",
               kido_dbl_log_n - log_before);
        failures++;
    } else {
        /* 9-16. Order + values, pinned. */
        static const uint8_t exp_reg[8] = {
            KIDO_DBL_ENABLES, KIDO_DBL_CNTL, KIDO_DBL_IER, KIDO_DBL_LCR,
            KIDO_DBL_MCR, KIDO_DBL_BAUD, KIDO_DBL_GPFSEL1, KIDO_DBL_CNTL
        };
        static const uint32_t exp_val[8] = {
            1u, 0u, 0u, 3u, 0u, 541u, 0xE0012000u, 3u
        };
        for (i = 0; i < 8u; i++) {
            if (kido_dbl_log[log_before + i].reg != exp_reg[i] ||
                kido_dbl_log[log_before + i].val != exp_val[i]) {
                printf("[FAIL] rpi4 init step %u: got (reg %u, 0x%x), "
                       "want (reg %u, 0x%x)\n", i,
                       kido_dbl_log[log_before + i].reg,
                       kido_dbl_log[log_before + i].val,
                       exp_reg[i], exp_val[i]);
                failures++;
            }
        }
    }

    /* 17. The RPi4 putc emits the byte to the IO register. */
    if (kido_hal_arm64_fill(&hal, KIDO_BOARD_RPI4) != KIDO_OK) {
        printf("[FAIL] rpi4 fill before putc check\n");
        failures++;
    }
    hal.console_putc('Z');
    if (kido_dbl_regs[KIDO_DBL_IO] != (uint32_t)'Z') {
        printf("[FAIL] rpi4 putc did not reach the IO register\n");
        failures++;
    }

    /* 18. Re-fill replays the sequence (idempotent re-init). */
    if (kido_hal_arm64_fill(&hal, KIDO_BOARD_RPI4) != KIDO_OK) {
        printf("[FAIL] rpi4 re-fill did not return OK\n");
        failures++;
    }
    if (kido_dbl_log_n - log_before != 24u) {
        printf("[FAIL] rpi4 re-init did not replay 8 writes "
               "(log delta %u, want 24)\n", kido_dbl_log_n - log_before);
        failures++;
    }

    /* 19. All four pointers wired for the RPi4 board too. */
    if (hal.console_putc == NULL || hal.console_puts == NULL ||
        hal.timer_ticks == NULL || hal.timer_hz == NULL) {
        printf("[FAIL] NULL pointer in rpi4-filled table\n");
        failures++;
    }

    printf("[test] hal-arm64 self-test: %s (%d failures)\n",
           failures == 0 ? "PASS" : "FAIL", failures);
    return failures == 0 ? 0 : 1;
}
#endif
