/*
 * kido-pl011.c — Kido PL011 UART driver (PrimeCell UART, DDI 0183).
 *
 * Init (baud divisor from a caller-supplied clock), polled TX,
 * polled RX. Stateless: base is passed per call, no per-port state
 * is kept. See kido-pl011.h for the register map, the honesty law,
 * and the declared HAL seam.
 *
 * WHAT IS REAL vs DOUBLE: the driver logic below is the real logic
 * — the hosted build runs the SAME functions against a scripted
 * UART double (scratch registers + TX capture + RX FIFO) instead
 * of MMIO. The bare-metal path is WRITTEN, NOT EXECUTED (no cross
 * toolchain this session, 9th data point; no QEMU/Pi4 run —
 * N8toriousAi's witness).
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST
 *        -DKIDO_PL011_SELFTEST kido-pl011.c -o pl011-selftest
 */

#include "kido-pl011.h"

/* ------------------------------------------------------------------ */
/* Registers (PL011 TRM, DDI 0183).                                   */
/* ------------------------------------------------------------------ */
#define KIDO_PL011_DR_OFF    0x00u
#define KIDO_PL011_RSR_OFF   0x04u /* read: status; write: error clear */
#define KIDO_PL011_FR_OFF    0x18u
#define KIDO_PL011_IBRD_OFF  0x24u
#define KIDO_PL011_FBRD_OFF  0x28u
#define KIDO_PL011_LCRH_OFF  0x2Cu
#define KIDO_PL011_CR_OFF    0x30u
#define KIDO_PL011_IMSC_OFF  0x38u
#define KIDO_PL011_DMACR_OFF 0x48u

/* FR bits. */
#define KIDO_PL011_FR_BUSY (1u << 3)
#define KIDO_PL011_FR_RXFE (1u << 4)
#define KIDO_PL011_FR_TXFF (1u << 5)
#define KIDO_PL011_FR_TXFE (1u << 7)

/* LCR_H bits: 8 data bits (WLEN 0b11) + FIFO enable = 8N1. */
#define KIDO_PL011_LCRH_FEN   (1u << 4)
#define KIDO_PL011_LCRH_WLEN8 (3u << 5)
#define KIDO_PL011_LCRH_8N1   (KIDO_PL011_LCRH_WLEN8 | KIDO_PL011_LCRH_FEN)

/* CR bits. */
#define KIDO_PL011_CR_UARTEN (1u << 0)
#define KIDO_PL011_CR_TXE    (1u << 8)
#define KIDO_PL011_CR_RXE    (1u << 9)
#define KIDO_PL011_CR_ENABLE (KIDO_PL011_CR_UARTEN | KIDO_PL011_CR_TXE | \
                              KIDO_PL011_CR_RXE)

/* DR error bits (OE/BE/PE/FE, bits 11:8). */
#define KIDO_PL011_DR_ERR_MASK 0xF00u

/* One spin budget for every poll (init BUSY, TX TXFF, RX RXFE).
 * A loop count, not time — no timer dependency by design. */
#define KIDO_PL011_POLL_MAX (1u << 20)

#if defined(KIDO_HOSTED_TEST)

/* ------------------------------------------------------------------ */
/* Hosted UART double. Scratch registers + TX capture + RX FIFO.     */
/* The double models ONE port; base is ignored except for the 0      */
/* check the driver itself performs before touching registers. The   */
/* scripted UART answers instantly (TX drains, BUSY never set)      */
/* except where a scenario says otherwise.                           */
/* ------------------------------------------------------------------ */
#include <stdio.h>

static uint32_t kido_dbl_ibrd = 0u;
static uint32_t kido_dbl_fbrd = 0u;
static uint32_t kido_dbl_lcrh = 0u;
static uint32_t kido_dbl_cr = 0u;
static uint32_t kido_dbl_imsc = 0u;
static uint32_t kido_dbl_dmacr = 0u;
static int      kido_dbl_ecr_cleared = 0;
static int      kido_dbl_tx_stuck = 0;

static char     kido_dbl_tx[256];
static unsigned kido_dbl_tx_len = 0u;

static uint8_t  kido_dbl_rx[16];
static uint32_t kido_dbl_rx_err[16];
static unsigned kido_dbl_rx_head = 0u;
static unsigned kido_dbl_rx_count = 0u;

#ifdef KIDO_PL011_SELFTEST
static void kido_pl011_test_reset(void)
{
    kido_dbl_ibrd = 0u;
    kido_dbl_fbrd = 0u;
    kido_dbl_lcrh = 0u;
    kido_dbl_cr = 0u;
    kido_dbl_imsc = 0u;
    kido_dbl_dmacr = 0u;
    kido_dbl_ecr_cleared = 0;
    kido_dbl_tx_stuck = 0;
    kido_dbl_tx_len = 0u;
    kido_dbl_rx_head = 0u;
    kido_dbl_rx_count = 0u;
}
#endif /* KIDO_PL011_SELFTEST */

#ifdef KIDO_PL011_SELFTEST
static void kido_pl011_test_feed(uint8_t byte, uint32_t errbits)
{
    unsigned slot;
    if (kido_dbl_rx_count >= 16u)
        return; /* FIFO full: the double drops, the test never does */
    slot = (kido_dbl_rx_head + kido_dbl_rx_count) % 16u;
    kido_dbl_rx[slot] = byte;
    kido_dbl_rx_err[slot] = errbits;
    kido_dbl_rx_count++;
}
#endif /* KIDO_PL011_SELFTEST */

static uint32_t kido_pl011_rd(uint64_t base, uint32_t off)
{
    uint32_t v;
    (void)base; /* one modeled port; the driver checks base != 0 */
    if (off == KIDO_PL011_FR_OFF) {
        v = KIDO_PL011_FR_TXFE; /* TX drains instantly in the double */
        if (kido_dbl_rx_count == 0u)
            v |= KIDO_PL011_FR_RXFE;
        if (kido_dbl_tx_stuck)
            v |= KIDO_PL011_FR_TXFF;
        return v; /* BUSY never set in the double */
    }
    if (off == KIDO_PL011_DR_OFF) {
        uint8_t byte;
        uint32_t err;
        if (kido_dbl_rx_count == 0u)
            return 0u; /* driver guards with RXFE; never reached */
        byte = kido_dbl_rx[kido_dbl_rx_head];
        err = kido_dbl_rx_err[kido_dbl_rx_head];
        kido_dbl_rx_head = (kido_dbl_rx_head + 1u) % 16u;
        kido_dbl_rx_count--;
        return ((uint32_t)byte) | err;
    }
    if (off == KIDO_PL011_IBRD_OFF)
        return kido_dbl_ibrd;
    if (off == KIDO_PL011_FBRD_OFF)
        return kido_dbl_fbrd;
    if (off == KIDO_PL011_LCRH_OFF)
        return kido_dbl_lcrh;
    if (off == KIDO_PL011_CR_OFF)
        return kido_dbl_cr;
    if (off == KIDO_PL011_IMSC_OFF)
        return kido_dbl_imsc;
    if (off == KIDO_PL011_DMACR_OFF)
        return kido_dbl_dmacr;
    return 0u;
}

static void kido_pl011_wr(uint64_t base, uint32_t off, uint32_t val)
{
    (void)base; /* one modeled port */
    if (off == KIDO_PL011_DR_OFF) {
        if (kido_dbl_tx_len < 256u)
            kido_dbl_tx[kido_dbl_tx_len++] = (char)(val & 0xFFu);
        return;
    }
    if (off == KIDO_PL011_IBRD_OFF) {
        kido_dbl_ibrd = val;
        return;
    }
    if (off == KIDO_PL011_FBRD_OFF) {
        kido_dbl_fbrd = val;
        return;
    }
    if (off == KIDO_PL011_LCRH_OFF) {
        kido_dbl_lcrh = val;
        return;
    }
    if (off == KIDO_PL011_CR_OFF) {
        kido_dbl_cr = val;
        return;
    }
    if (off == KIDO_PL011_IMSC_OFF) {
        kido_dbl_imsc = val;
        return;
    }
    if (off == KIDO_PL011_DMACR_OFF) {
        kido_dbl_dmacr = val;
        return;
    }
    if (off == KIDO_PL011_RSR_OFF)
        kido_dbl_ecr_cleared = 1; /* any ECR write clears errors */
}

#else /* bare metal */

/* Real MMIO. Volatile: the compiler must not reorder or elide the
 * status polls. */
static uint32_t kido_pl011_rd(uint64_t base, uint32_t off)
{
    return *(volatile uint32_t *)(uintptr_t)(base + off);
}

static void kido_pl011_wr(uint64_t base, uint32_t off, uint32_t val)
{
    *(volatile uint32_t *)(uintptr_t)(base + off) = val;
}

#endif /* KIDO_HOSTED_TEST */

/* ------------------------------------------------------------------ */
/* The driver.                                                         */
/* ------------------------------------------------------------------ */
kido_status_t kido_pl011_init(uint64_t base, uint32_t uartclk_hz,
                              uint32_t baud)
{
    uint64_t total; /* divisor x 64, rounded (TRM "+0.5" rule) */
    uint32_t ibrd;
    uint32_t fbrd;
    uint32_t polls;

    if (base == 0u || uartclk_hz == 0u || baud == 0u)
        return KIDO_ERR_EARLY_ENV;

    /* divisor = clk / (16 x baud); x64 both sides gives
     * total = clk x 4 / baud, rounded to nearest. IBRD =
     * total / 64, FBRD = total % 64, so a fractional round-up
     * past 63 carries into IBRD by construction. */
    total = ((uint64_t)uartclk_hz * 4u + baud / 2u) / baud;
    ibrd = (uint32_t)(total / 64u);
    fbrd = (uint32_t)(total % 64u);
    if (ibrd == 0u || ibrd > 0xFFFFu)
        return KIDO_ERR_EARLY_ENV; /* unrepresentable divisor: loud */

    /* Disable, wait out any in-flight byte, flush the FIFOs. */
    kido_pl011_wr(base, KIDO_PL011_CR_OFF, 0u);
    polls = 0u;
    while ((kido_pl011_rd(base, KIDO_PL011_FR_OFF) &
            KIDO_PL011_FR_BUSY) != 0u) {
        if (++polls >= KIDO_PL011_POLL_MAX)
            return KIDO_ERR_EARLY_ENV; /* transmitter wedged: loud */
    }
    kido_pl011_wr(base, KIDO_PL011_LCRH_OFF, 0u); /* FEN = 0: flush */

    /* Divisors, then the line format, then silence the IRQ/DMA
     * paths this polled driver does not use. */
    kido_pl011_wr(base, KIDO_PL011_IBRD_OFF, ibrd);
    kido_pl011_wr(base, KIDO_PL011_FBRD_OFF, fbrd);
    kido_pl011_wr(base, KIDO_PL011_LCRH_OFF, KIDO_PL011_LCRH_8N1);
    kido_pl011_wr(base, KIDO_PL011_IMSC_OFF, 0u); /* all masked */
    kido_pl011_wr(base, KIDO_PL011_DMACR_OFF, 0u); /* no DMA */
    kido_pl011_wr(base, KIDO_PL011_RSR_OFF, 0xFFu); /* clear errors */

    /* Enable: UART + TX + RX. No flow control, no loopback. */
    kido_pl011_wr(base, KIDO_PL011_CR_OFF, KIDO_PL011_CR_ENABLE);
    return KIDO_OK;
}

kido_status_t kido_pl011_putc(uint64_t base, char c)
{
    uint32_t polls;

    if (base == 0u)
        return KIDO_ERR_EARLY_ENV;
    polls = 0u;
    while ((kido_pl011_rd(base, KIDO_PL011_FR_OFF) &
            KIDO_PL011_FR_TXFF) != 0u) {
        if (++polls >= KIDO_PL011_POLL_MAX)
            return KIDO_ERR_EARLY_ENV; /* TX FIFO never drains */
    }
    kido_pl011_wr(base, KIDO_PL011_DR_OFF, (uint32_t)(uint8_t)c);
    return KIDO_OK;
}

kido_status_t kido_pl011_puts(uint64_t base, const char *s)
{
    kido_status_t st;
    if (s == NULL)
        return KIDO_ERR_EARLY_ENV;
    while (*s != '\0') {
        st = kido_pl011_putc(base, *s);
        if (st != KIDO_OK)
            return st;
        s++;
    }
    return KIDO_OK;
}

kido_status_t kido_pl011_poll(uint64_t base, uint8_t *ready)
{
    if (base == 0u || ready == NULL)
        return KIDO_ERR_EARLY_ENV;
    *ready = ((kido_pl011_rd(base, KIDO_PL011_FR_OFF) &
               KIDO_PL011_FR_RXFE) == 0u) ? 1u : 0u;
    return KIDO_OK;
}

kido_status_t kido_pl011_getc(uint64_t base, char *out)
{
    uint32_t polls;
    uint32_t v;

    if (base == 0u || out == NULL)
        return KIDO_ERR_EARLY_ENV;
    polls = 0u;
    while ((kido_pl011_rd(base, KIDO_PL011_FR_OFF) &
            KIDO_PL011_FR_RXFE) != 0u) {
        if (++polls >= KIDO_PL011_POLL_MAX)
            return KIDO_ERR_EARLY_ENV; /* RX FIFO never fills */
    }
    v = kido_pl011_rd(base, KIDO_PL011_DR_OFF);
    if ((v & KIDO_PL011_DR_ERR_MASK) != 0u) {
        /* Corrupt byte: clear the error, deliver nothing, loud. */
        kido_pl011_wr(base, KIDO_PL011_RSR_OFF, 0xFFu);
        return KIDO_ERR_EARLY_ENV;
    }
    *out = (char)(v & 0xFFu);
    return KIDO_OK;
}

/* ------------------------------------------------------------------ */
/* Self-test: pins the divisor table, the init register image, TX,    */
/* RX, error-bit rejection, and every loud failure against the      */
/* scripted UART double.                                             */
/* ------------------------------------------------------------------ */
#ifdef KIDO_PL011_SELFTEST
#ifndef KIDO_HOSTED_TEST
#error "KIDO_PL011_SELFTEST needs KIDO_HOSTED_TEST (it runs the hosted double)."
#endif

#define KIDO_PL011_BASE 0x09000000u /* the modeled port's address */

int main(void)
{
    int failures = 0;
    int checks = 0;
    uint8_t ready = 0u;
    char c = '\0';

#define KIDO_PL011_CHECK(cond, msg) do { \
    checks++; \
    if (!(cond)) { printf("[FAIL] " msg "\n"); failures++; } \
} while (0)

    /* A. Argument guards: nothing touched, all loud. */
    kido_pl011_test_reset();
    KIDO_PL011_CHECK(kido_pl011_init(0u, 24000000u, 115200u) ==
                     KIDO_ERR_EARLY_ENV, "init base 0 not refused");
    KIDO_PL011_CHECK(kido_pl011_init(KIDO_PL011_BASE, 0u, 115200u) ==
                     KIDO_ERR_EARLY_ENV, "init clock 0 not refused");
    KIDO_PL011_CHECK(kido_pl011_init(KIDO_PL011_BASE, 24000000u, 0u) ==
                     KIDO_ERR_EARLY_ENV, "init baud 0 not refused");

    /* B. Divisor table (TRM law: divisor = clk / (16 x baud)). */
    kido_pl011_test_reset();
    KIDO_PL011_CHECK(kido_pl011_init(KIDO_PL011_BASE, 24000000u,
                                     115200u) == KIDO_OK,
                     "init 24M/115200 failed");
    KIDO_PL011_CHECK(kido_dbl_ibrd == 13u, "24M/115200 IBRD not 13");
    KIDO_PL011_CHECK(kido_dbl_fbrd == 1u, "24M/115200 FBRD not 1");
    /* Init register image: 8N1 + FIFOs, TX+RX enabled, IRQ/DMA off. */
    KIDO_PL011_CHECK(kido_dbl_lcrh == 0x70u, "LCR_H not 8N1+FEN (0x70)");
    KIDO_PL011_CHECK(kido_dbl_cr == 0x301u, "CR not UARTEN|TXE|RXE");
    KIDO_PL011_CHECK(kido_dbl_imsc == 0u, "IMSC not 0 (IRQs masked)");
    KIDO_PL011_CHECK(kido_dbl_dmacr == 0u, "DMACR not 0 (no DMA)");

    kido_pl011_test_reset();
    KIDO_PL011_CHECK(kido_pl011_init(KIDO_PL011_BASE, 24000000u,
                                     9600u) == KIDO_OK,
                     "init 24M/9600 failed");
    KIDO_PL011_CHECK(kido_dbl_ibrd == 156u, "24M/9600 IBRD not 156");
    KIDO_PL011_CHECK(kido_dbl_fbrd == 16u, "24M/9600 FBRD not 16");

    kido_pl011_test_reset();
    KIDO_PL011_CHECK(kido_pl011_init(KIDO_PL011_BASE, 48000000u,
                                     115200u) == KIDO_OK,
                     "init 48M/115200 failed");
    KIDO_PL011_CHECK(kido_dbl_ibrd == 26u, "48M/115200 IBRD not 26");
    KIDO_PL011_CHECK(kido_dbl_fbrd == 3u, "48M/115200 FBRD not 3");

    /* Unrepresentable divisors: all loud, before any register write
     * after the guard (IBRD is checked before CR is touched). */
    kido_pl011_test_reset();
    KIDO_PL011_CHECK(kido_pl011_init(KIDO_PL011_BASE, 1000000u,
                                     115200u) == KIDO_ERR_EARLY_ENV,
                     "1M/115200 (IBRD 0) not refused");
    KIDO_PL011_CHECK(kido_pl011_init(KIDO_PL011_BASE, 24000000u,
                                     100000000u) == KIDO_ERR_EARLY_ENV,
                     "24M/100Mbaud (IBRD 0) not refused");
    KIDO_PL011_CHECK(kido_pl011_init(KIDO_PL011_BASE, 4294967295u,
                                     1200u) == KIDO_ERR_EARLY_ENV,
                     "huge clock (IBRD > 0xFFFF) not refused");

    /* C. TX: putc, puts, stuck transmitter, stateless putc. */
    kido_pl011_test_reset();
    KIDO_PL011_CHECK(kido_pl011_putc(KIDO_PL011_BASE, 'A') == KIDO_OK,
                     "putc A failed");
    KIDO_PL011_CHECK(kido_dbl_tx_len == 1u, "TX len not 1 after putc");
    KIDO_PL011_CHECK(kido_dbl_tx[0] == 'A', "TX byte not A");
    KIDO_PL011_CHECK(kido_pl011_puts(KIDO_PL011_BASE, "BC") == KIDO_OK,
                     "puts BC failed");
    KIDO_PL011_CHECK(kido_dbl_tx_len == 3u, "TX len not 3 after puts");
    KIDO_PL011_CHECK(kido_dbl_tx[1] == 'B' && kido_dbl_tx[2] == 'C',
                     "TX capture not ABC");
    kido_dbl_tx_stuck = 1; /* TXFF never clears */
    KIDO_PL011_CHECK(kido_pl011_putc(KIDO_PL011_BASE, 'D') ==
                     KIDO_ERR_EARLY_ENV, "TXFF-stuck putc not loud");
    KIDO_PL011_CHECK(kido_dbl_tx_len == 3u,
                     "TXFF-stuck putc wrote a byte");
    kido_pl011_test_reset(); /* fresh double, no init call */
    KIDO_PL011_CHECK(kido_pl011_putc(KIDO_PL011_BASE, 'Z') == KIDO_OK,
                     "stateless putc (firmware-owned UART) failed");

    /* D. RX: poll flag, ordered bytes, empty FIFO, error bits. */
    kido_pl011_test_reset();
    kido_pl011_test_feed((uint8_t)'H', 0u);
    kido_pl011_test_feed((uint8_t)'i', 0u);
    KIDO_PL011_CHECK(kido_pl011_poll(KIDO_PL011_BASE, &ready) == KIDO_OK,
                     "poll failed");
    KIDO_PL011_CHECK(ready == 1u, "poll ready not 1 with bytes queued");
    KIDO_PL011_CHECK(kido_pl011_getc(KIDO_PL011_BASE, &c) == KIDO_OK,
                     "getc H failed");
    KIDO_PL011_CHECK(c == 'H', "getc byte not H");
    KIDO_PL011_CHECK(kido_pl011_getc(KIDO_PL011_BASE, &c) == KIDO_OK,
                     "getc i failed");
    KIDO_PL011_CHECK(c == 'i', "getc byte not i");
    KIDO_PL011_CHECK(kido_pl011_poll(KIDO_PL011_BASE, &ready) == KIDO_OK,
                     "poll after drain failed");
    KIDO_PL011_CHECK(ready == 0u, "poll ready not 0 after drain");
    KIDO_PL011_CHECK(kido_pl011_getc(KIDO_PL011_BASE, &c) ==
                     KIDO_ERR_EARLY_ENV, "getc on empty FIFO not loud");
    /* Error byte: OE set -> rejected, ECR cleared, nothing delivered. */
    kido_pl011_test_feed((uint8_t)'X', 0x800u); /* OE, bit 11 */
    c = '\0';
    KIDO_PL011_CHECK(kido_pl011_getc(KIDO_PL011_BASE, &c) ==
                     KIDO_ERR_EARLY_ENV, "OE byte not rejected");
    KIDO_PL011_CHECK(kido_dbl_ecr_cleared == 1, "ECR not cleared on OE");
    KIDO_PL011_CHECK(c == '\0', "OE byte leaked into *out");
    kido_pl011_test_feed((uint8_t)'Y', 0u);
    KIDO_PL011_CHECK(kido_pl011_getc(KIDO_PL011_BASE, &c) == KIDO_OK,
                     "getc after OE failed");
    KIDO_PL011_CHECK(c == 'Y', "byte after OE not Y");

    /* E. Re-init is idempotent; remaining guards. */
    kido_pl011_test_reset();
    KIDO_PL011_CHECK(kido_pl011_init(KIDO_PL011_BASE, 24000000u,
                                     115200u) == KIDO_OK,
                     "first init failed");
    KIDO_PL011_CHECK(kido_pl011_init(KIDO_PL011_BASE, 24000000u,
                                     115200u) == KIDO_OK,
                     "second init failed");
    KIDO_PL011_CHECK(kido_dbl_ibrd == 13u && kido_dbl_fbrd == 1u,
                     "re-init divisors changed");
    KIDO_PL011_CHECK(kido_pl011_puts(KIDO_PL011_BASE, NULL) ==
                     KIDO_ERR_EARLY_ENV, "puts NULL not refused");
    KIDO_PL011_CHECK(kido_pl011_poll(KIDO_PL011_BASE, NULL) ==
                     KIDO_ERR_EARLY_ENV, "poll NULL not refused");
    KIDO_PL011_CHECK(kido_pl011_getc(KIDO_PL011_BASE, NULL) ==
                     KIDO_ERR_EARLY_ENV, "getc NULL not refused");
    KIDO_PL011_CHECK(kido_pl011_putc(0u, 'A') == KIDO_ERR_EARLY_ENV,
                     "putc base 0 not refused");

    if (failures == 0)
        printf("kido-pl011 self-test: ALL PASS (%d checks)\n", checks);
    else
        printf("kido-pl011 self-test: %d FAILURES (%d checks)\n",
               failures, checks);
    return failures != 0;
#undef KIDO_PL011_CHECK
}
#endif /* KIDO_PL011_SELFTEST */
