/*
 * kido-mmu.h — Kido ARM64 stage-1 MMU, public interface.
 *
 * The memory-management unit, drafted 2026-10-22 (session 22). The last
 * named item in the scaffold's standing remains ("UEFI/RPi4/MMU") that
 * is draftable without hardware: page-table construction is pure
 * computation, fully host-testable. (RPi4 UART init is register pokes
 * with no observable effect on a dev host; a UEFI memory-map parser is
 * half a module without the boot-services call.)
 *
 * DESIGN (deliberation 2026-10-22-kido-session22-mmu-design.md):
 * - 4 KiB granule, 39-bit VA (T0SZ=25), walk starts at L1. 512 GiB of
 *   VA — every real map fits with room for ten lifetimes; 2 table
 *   levels instead of 3, auditable by eye (D1: 48-bit overruled).
 * - IDENTITY MAP (VA == PA). The MMU's real job here is turning on the
 *   caches (M+C+I) and giving memory attributes (device vs normal) —
 *   not virtual-memory theater. Every existing address stays valid
 *   across the enable (C1).
 * - Largest-fitting blocks: L1 1 GiB blocks where a whole GiB is
 *   mapped, else L1 table -> L2 2 MiB blocks, else L2 table -> L3
 *   4 KiB pages. Exact coverage — no 896 MiB of phantom-mapped RAM
 *   around the real region (C2).
 * - Static bounded tables (P2): KIDO_MMU_MAX_TABLE_PAGES pages in BSS,
 *   never the allocator (the MMU's input IS the allocator's regions).
 *   The map is caller-supplied — no kido-mem coupling, no HAL coupling
 *   (the one-query pattern).
 * - Enable order (P4): TLBI -> TTBR0 -> TCR -> MAIR -> DSB/ISB ->
 *   SCTLR |= M|C|I -> ISB. Controls fully programmed before the M bit
 *   flips. TCR/MAIR from pure C functions, bit-pinned by test.
 * - Call-site seam DECLARED, NOT WIRED (P5, D3): after
 *   kido_reloc_verify() OK in the entry chain, before kido_boot().
 *   The phase-3 relocator runs with the MMU OFF (it fixes physical
 *   addresses; enabling first would be circular). Wiring waits for the
 *   Gate — this draft touches no approved file.
 *
 * PROOF STATUS (honest, session-16 style):
 * - Table construction: REAL. Portable C, host-tested (the self-test
 *   walks the built tables with an independent walker).
 * - Register sequence: WRITTEN, NOT ASSEMBLED, NEVER EXECUTED. The
 *   ARM64 writes are real inline asm; the cross toolchain is absent
 *   this session (5th data point, see ledger). A hosted double records
 *   the sequence + values; the encoding waits for the toolchain.
 * - Call site: DECLARED, NOT WIRED (future Gate item).
 * - No bootable kernel is finalized without N8toriousAi; first boot is his
 *   to witness.
 *
 * ARCH DISCIPLINE: ARM64 or hosted test-double only.
 */
#ifndef KIDO_MMU_H
#define KIDO_MMU_H

#include "kido-boot.h"  /* kido_status_t */
#include <stddef.h>
#include <stdint.h>

#if !defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
#error "kido-mmu: ARM64 or hosted only. Define KIDO_HOSTED_TEST for the hosted draft harness."
#endif

/* Bounded static tables: L1 root + on-demand L2/L3 pages. 16 pages =
 * 64 KiB of BSS. Worst honest map (RAM + UART + a spare device window
 * + fragments) needs 4; the bound is headroom with a loud failure,
 * not a guess that silently fits. */
#define KIDO_MMU_MAX_TABLE_PAGES 16u
#define KIDO_MMU_PAGE_SHIFT      12u
#define KIDO_MMU_PAGE_SIZE       (1u << KIDO_MMU_PAGE_SHIFT)
/* 39-bit VA: the walk must stay inside 512 GiB. */
#define KIDO_MMU_VA_LIMIT        (1ull << 39)

/* Memory attributes. Two MAIR entries only (P3): device-nGnRnE for
 * MMIO, Normal WBWA for RAM. Every bit below is stated with reason
 * in kido-mmu.c; nothing copied without asking why. */
typedef enum kido_mmu_attr {
    KIDO_MMU_ATTR_NORMAL = 0,  /* DRAM: WBWA, inner-shareable        */
    KIDO_MMU_ATTR_DEVICE = 1   /* MMIO: nGnRnE, outer-shareable      */
} kido_mmu_attr_t;

/* One mapped region. base+size must be 4 KiB multiples (the smallest
 * mapping unit); regions must not overlap; the whole map must sit
 * under KIDO_MMU_VA_LIMIT. Violations fail LOUD, never silently
 * clipped. */
typedef struct kido_mmu_map_entry {
    uint64_t         base;
    uint64_t         size;
    kido_mmu_attr_t  attr;
} kido_mmu_map_entry_t;

/* ------------------------------------------------------------------ */
/* kido_mmu_tcr_el1 / kido_mmu_mair_el1: pure functions returning the  */
/* exact register values the enable sequence programs. Bit-pinned by */
/* the self-test (TCR == 0x200993519, MAIR == 0xFF00).                 */
/*   TCR: T0SZ=25 (39-bit), TG0=4KiB, SH0=ISH, ORGN0/IRGN0=WBWA,      */
/*        EPD0=0, EPD1=1 (TTBR1 walks disabled, explicit — C6),        */
/*        T1SZ=25 (don't-care-but-sane), IPS=40-bit (QEMU virt PA).    */
/*   MAIR: Attr0 = 0x00 Device-nGnRnE, Attr1 = 0xFF Normal WBWA.       */
/* ------------------------------------------------------------------ */
uint64_t kido_mmu_tcr_el1(void);
uint64_t kido_mmu_mair_el1(void);

/* SCTLR_EL1 bits the enable sequence sets (M | C | I). Pure constant,
 * test-pinned. Everything else in SCTLR is preserved (read-modify-
 * write) — the kernel sets three bits, not a whole register. */
#define KIDO_MMU_SCTLR_ENABLE_BITS (0x1005u)

/* ------------------------------------------------------------------ */
/* kido_mmu_build: construct the static tables for `map` (identity    */
/* mapping, VA == PA). Zeroes the tables first — rebuild is           */
/* idempotent. Returns KIDO_OK, KIDO_ERR_EARLY_ENV (NULL/empty map,   */
/* zero size, misaligned base/size, base+size overflow, VA-limit      */
/* breach, bad attr, overlapping regions, descriptor conflict), or    */
/* KIDO_ERR_NO_MEMORY (table-page exhaustion — loud, never silent     */
/* truncation).                                                       */
/* ------------------------------------------------------------------ */
kido_status_t kido_mmu_build(const kido_mmu_map_entry_t *map, size_t n);

/* ------------------------------------------------------------------ */
/* kido_mmu_enable: program TTBR0_EL1/TCR_EL1/MAIR_EL1 and set        */
/* SCTLR_EL1.M+C+I (sequence P4). ARM64: real inline asm. Hosted:     */
/* records the sequence into the trace below (the HAL's test-double   */
/* precedent). Must be called after kido_mmu_build; calling before    */
/* build is KIDO_ERR_EARLY_ENV, loud.                                 */
/* PROOF STATUS: written, not assembled, never executed (no toolchain */
/* this session). The hosted double proves the sequence logic and the  */
/* values; the encoding waits for PENDING #1's toolchain.             */
/* ------------------------------------------------------------------ */
kido_status_t kido_mmu_enable(void);

/* Observers (tests and the future wiring). */
const uint64_t *kido_mmu_l1(void);      /* TTBR0 value: the L1 root   */
size_t          kido_mmu_pages_used(void); /* 1 + on-demand pages     */
int             kido_mmu_built(void);     /* build() has succeeded    */

#ifdef KIDO_HOSTED_TEST
/* Enable-sequence trace (hosted double only). Steps recorded in order;
 * the test asserts both the order and the values. */
typedef enum kido_mmu_hosted_step {
    KIDO_MMU_STEP_TLBI  = 0,
    KIDO_MMU_STEP_TTBR0 = 1,
    KIDO_MMU_STEP_TCR   = 2,
    KIDO_MMU_STEP_MAIR  = 3,
    KIDO_MMU_STEP_SCTLR = 4
} kido_mmu_hosted_step_t;
typedef struct kido_mmu_hosted_trace {
    uint64_t ttbr0;
    uint64_t tcr;
    uint64_t mair;
    uint64_t sctlr_old;
    uint64_t sctlr_new;
    unsigned char order[8];  /* step codes, in program order */
    unsigned nsteps;
} kido_mmu_hosted_trace_t;
void kido_mmu_hosted_trace_reset(void);
const kido_mmu_hosted_trace_t *kido_mmu_hosted_trace(void);
#endif

#endif /* KIDO_MMU_H */
