/*
 * kido-serial-irq.h — Kido interrupt-driven PL011 RX.
 *
 * The RX side of the interrupt chain, and the first consumer of
 * the session-27 GIC + session-28 vector modules: a GIC handler
 * that drains the PL011 RX FIFO into a static ring the kernel
 * reads without polling. TX stays polled (kido_pl011_putc).
 *
 * REGISTER WINDOW (ARM PrimeCell UART PL011 TRM, DDI 0183 —
 * the same source as kido-pl011.h; see the window rule below):
 *   DR 0x000, RSR/ECR 0x004, FR 0x018, IFLS 0x034, IMSC 0x038,
 *   MIS 0x040, ICR 0x044. FR RXFE bit 4. DR error bits OE/BE/PE/FE
 *   bits 11:8. IMSC RXIM bit 4. ICR RXIC bit 4. IFLS RXIFLSEL
 *   bits 2:0 (001 = interrupt at 1/4 full, 4 bytes of 16).
 *   QEMU virt PL011 IRQ: SPI 33 (DTB, same source as the GIC
 *   bases). No Pi4 UART0 IRQ is named here: unverified this
 *   session — a Pi4 caller supplies the IRQ, same discipline as
 *   the PL011 clock and the GIC bases.
 *
 * IRQ WINDOW RULE (read this before calling it a fork): this
 * module owns exactly the IRQ side of the UART — unmask, trigger
 * level, drain, error clear. kido-pl011 owns init, baud, TX, and
 * polled RX. The window exists because the pl011 hosted double's
 * feed setter is static inside pl011.c's self-test TU and cannot
 * be reached from another TU's test without breaking the fence
 * or colliding mains; a module that cannot be tested end to end
 * is worse than a declared 5-register window. If the TRM
 * reading ever changes, both files change together.
 *
 * INIT ORDER LAW (handler before enable before unmask):
 *   1. register handler at the GIC
 *   2. GIC trigger config = level, GIC enable
 *   3. UART: IFLS RX trigger 1/4, IMSC RXIM unmask, ICR RXIC clear
 * An interrupt can therefore never arrive without a handler or
 * without a drain path. stop() reverses it: mask UART, disable
 * GIC, unregister. The vec install + DAIF unmask that would fire
 * this handler on hardware are Gate items, not this module's —
 * the hosted proof drives the chain through kido_gic_dispatch(),
 * which is exactly what the vec stub calls.
 *
 * HONESTY LAW:
 *  - Static 256-byte ring, never allocates, never blocks. IRQ
 *    context cannot wait: the handler drains at most the 16-deep
 *    hardware FIFO per invocation and counts what it cannot keep.
 *    A full ring drops bytes with the drop counter incremented —
 *    never overwrites unread bytes.
 *  - Error bytes (OE/BE/PE/FE) are discarded, ECR cleared, and
 *    counted — the polled RX law, inherited. Nothing corrupt
 *    reaches the ring.
 *  - Consumer API is non-blocking, unlike the polled driver:
 *    available() is the flag, getc() is the drain; an empty ring
 *    is EARLY_ENV immediately, never a wait. The caller checks
 *    available() first.
 *  - Priority is untouched (GIC reset value stands); assigning
 *    one is caller policy via kido_gic_set_priority.
 *  - One port, module-global state (UP, one console UART).
 *    Multi-port is a named future, not a flag.
 *  - stop() stops NEW delivery only; bytes already in the ring
 *    are facts and remain drainable.
 *  - No new header code (N8toriousAi's call, sched-D1 precedent):
 *    every failure maps to KIDO_ERR_EARLY_ENV.
 *  - HOSTED-PROVEN AND SPI-PROVEN ON QEMU 2026-10-27
 *    (session 31): UART RX IRQ 33 delivered through the
 *    committed vec table — 4 injected bytes ("KIDO")
 *    arrived in the ring byte-identical and in order
 *    (ST:4), via the real dispatch chain, with clean
 *    exception returns and zero fault entries
 *    (deliberations/2026-10-27-qemu-irq-proof.log).
 *    Still queued: wiring init into the boot path (after
 *    GIC init, before DAIF unmask), Pi4 UART0 IRQ identity.
 *  - NOT wired into the HAL or the boot path this session.
 *    The seam is declared: a future Gate item calls
 *    kido_serial_irq_init() after GIC init and before DAIF
 *    unmask, with the vec table installed.
 *
 * FUTURES (named, not built): TX-empty interrupt + TX queue,
 * multi-port instances, RX-timeout interrupt handling as a
 * distinct source, Pi4 UART0 IRQ identity.
 *
 * Draft status: DRAFT (2026-10-26, session 30). No bootable kernel
 * is finalized without N8toriousAi; first boot is his to witness.
 */
#ifndef KIDO_SERIAL_IRQ_H
#define KIDO_SERIAL_IRQ_H

#include "kido-boot.h"
#include "kido-gic.h"

#if !defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
#error "kido-serial-irq: refusing to compile for unknown arch. UART MMIO lives in per-arch files; define KIDO_HOSTED_TEST for the hosted draft harness."
#endif

/* QEMU virt PL011 interrupt (SPI, DTB). No Pi4 IRQ named. */
#define KIDO_SERIAL_IRQ_QEMU_VIRT_IRQ 33u

/* Static ring depth: 16x the hardware FIFO, a power of two. */
#define KIDO_SERIAL_IRQ_RING_DEPTH 256u

/* Delivery counters. All counts are exact, never sampled. */
typedef struct {
    uint32_t received;      /* bytes placed in the ring */
    uint32_t dropped;       /* bytes lost to a full ring */
    uint32_t errors;        /* error-bit bytes discarded */
    uint32_t handler_runs;  /* handler invocations */
    uint32_t spurious_runs; /* invocations that drained nothing */
} kido_serial_irq_stats_t;

/* Initialize interrupt-driven RX on the UART at base for the
 * given SPI IRQ. Requires kido_gic_init() already done (the GIC
 * calls below fail loud otherwise, before any UART register is
 * touched). Registers the handler, sets level trigger, enables
 * the IRQ, then unmasks RXIM with a 1/4-full trigger level.
 * Double init is EARLY_ENV; stop() then init() is the restart
 * path. Returns EARLY_ENV on base 0, a non-SPI IRQ (the GIC's
 * set_config accepts SPI only), an out-of-range IRQ, or any GIC
 * failure (state left uninitialized on failure). */
kido_status_t kido_serial_irq_init(uint64_t base, uint32_t irq);

/* Stop new delivery: mask RXIM, disable the IRQ, unregister the
 * handler. Bytes already in the ring remain drainable.
 * EARLY_ENV when not initialized (including a second stop). */
kido_status_t kido_serial_irq_stop(void);

/* Bytes currently waiting in the ring. EARLY_ENV when not
 * initialized or on a NULL out-pointer. */
kido_status_t kido_serial_irq_available(uint32_t *out);

/* Drain one byte from the ring. Non-blocking: an empty ring is
 * EARLY_ENV immediately. Check available() first. */
kido_status_t kido_serial_irq_getc(char *out);

/* Copy the delivery counters. EARLY_ENV when not initialized
 * or on a NULL out-pointer. */
kido_status_t kido_serial_irq_stats(kido_serial_irq_stats_t *out);

#endif /* KIDO_SERIAL_IRQ_H */
