/*
 * kido-mem.h — Kido memory discovery, public interface.
 *
 * The module the HAL builder deferred DTB parsing to: flattened device
 * tree parsing that produces the memory map filling kido_bootinfo_t
 * (the entry shim -> HAL firmware-handoff contract, defined in
 * kido-hal-arm64.h). A sibling builder is drafting the entry shim in
 * parallel against the same contract — this interface matches it exactly.
 *
 * PORTABILITY LAW: DTB parsing is portable-by-construction. The device
 * tree format is big-endian by specification, and this module reads it
 * with manual byte loads — zero arch assumptions, no per-arch shim
 * needed. The parser genuinely runs on the dev host, so unlike the
 * ARM64 asm paths it is testable for real, not just parseable.
 *
 * CALL ORDER (bare metal): entry shim obtains the DTB pointer from the
 * firmware handoff (x0 per the ARM64 boot protocol) -> kido_mem_discover
 * fills kido_bootinfo_t -> shim passes it to kido_hal_arm64_probe().
 *
 * Draft status: DTB discovery is REAL (header validation, memory-node
 * walk, /memreserve/ handling, DTB-extent trim). UEFI discovery is REAL
 * (2026-10-23): the no-DTB path parses the GetMemoryMap descriptor array
 * (descriptor v1, little-endian) into the same seed list through the same
 * pipeline shape. The region list seeds a future allocator; the allocator
 * itself is NOT written here.
 */
#ifndef KIDO_MEM_H
#define KIDO_MEM_H

#include "kido-boot.h"
#include "kido-hal-arm64.h" /* kido_bootinfo_t lives here */

/* Bounded region table: discovery never allocates. Sized for the walk
 * (session 3) plus the DTB-extent trim's worst case (2026-10-21): one
 * firmware blob straddling all 8 walk regions yields 16 survivors.
 * A trim needing more fails LOUD — pathological firmware, not a
 * silent squeeze. Every bound is a bet; this one is documented. */
#define KIDO_MEM_MAX_REGIONS 16u

typedef struct kido_mem_region {
    uint64_t base;  /* first byte of the region (firmware view) */
    uint64_t size;  /* region bytes                              */
} kido_mem_region_t;

/* ------------------------------------------------------------------ */
/* kido_mem_discover: parse a DTB, fill the bootinfo memory map.       */
/*  dtb / dtb_len : the firmware DTB blob.                             */
/*  bi            : filled on success — mem_base/mem_size = the        */
/*                  largest usable region (see below), mem_valid = 1.  */
/*  Returns KIDO_OK, or KIDO_ERR_NO_MEMORY for every failure mode:     */
/*   - NULL dtb or bi,                                                */
/*   - bad magic / insane totalsize / truncated structure,            */
/*   - no usable memory region (none found, all disabled, all         */
/*     reserved, region arithmetic overflow, DTB extent covering all   */
/*     regions, trim output exceeding the bounded table).              */
/*  Every failure leaves bi->mem_valid == 0, so the HAL probe fails    */
/*  LOUD downstream. Nothing is ever invented: no DTB, no regions.     */
/*                                                                     */
/*  DTB-EXTENT TRIM (2026-10-21): the firmware DTB blob lives in RAM   */
/*  at [dtb, dtb+totalsize) — inside the /memory regions on real       */
/*  firmware (QEMU virt loads it at the top of RAM). The trim removes  */
/*  that extent from every region BEFORE primary selection and seed    */
/*  publication, so the allocator never sees the DTB's own pages.      */
/*  The extent is exactly what discover vouches for: the re-validated  */
/*  totalsize, never the dtb_len slack. A region the extent splits    */
/*  yields up to two survivors; a region it covers whole is dropped;   */
/*  no overlap is a no-op (absence is a fact, not an error).           */
/*                                                                     */
/*  Primary-region rule: the LARGEST usable region wins (ties: lowest   */
/*  base) — selected AFTER the trim, so the primary never names the    */
/*  DTB's pages. /memreserve/ entries are honored on the trimmed       */
/*  primary: a leading reservation trims the region's base upward; a   */
/*  reservation strictly interior to the chosen region fails LOUD —    */
/*  a single-region bootinfo cannot represent a hole, and silently      */
/*  handing one to the allocator would be worse than failing. Fine-    */
/*  grained carving is the future allocator's job, not discovery's.    */
/* ------------------------------------------------------------------ */
kido_status_t kido_mem_discover(const uint8_t *dtb, size_t dtb_len,
                                kido_bootinfo_t *bi);

/* ------------------------------------------------------------------ */
/* Region list from the last successful discover — the allocator's     */
/* seed. Usable regions: firmware regions with the DTB extent trimmed  */
/* out (2026-10-21; previously raw/untrimmed). The bootinfo primary    */
/* is the trimmed largest. Count first, then read.                     */
/* ------------------------------------------------------------------ */
size_t kido_mem_region_count(void);
const kido_mem_region_t *kido_mem_regions(void);

#ifdef KIDO_HOSTED_TEST
/* Hosted-only test injector: the firmware DTB load extent the trimmer
 * uses. Bare metal computes [dtb, dtb+totalsize) from the real
 * firmware pointer; the dev host has no firmware DTB, so hosted
 * defaults to the vacuous (0,0) — the trim no-ops, exactly like
 * kido-image's hosted vacuity. The injector substitutes ONLY the
 * extent source; the parser and the trimmer run the real code. */
void kido_mem_test_set_dtb_extent(uint64_t base, uint64_t size);
#endif

/* ------------------------------------------------------------------ */
/* kido_mem_discover_uefi: parse a UEFI memory map (the no-DTB path).   */
/*  mmap / mmap_len : the GetMemoryMap descriptor buffer, captured     */
/*                   AFTER ExitBootServices.                          */
/*  desc_size       : the map's descriptor stride (GetMemoryMap's       */
/*                   DescriptorSize); must hold the v1 fields (>= 40). */
/*  desc_version    : the map's descriptor version (GetMemoryMap's      */
/*                   DescriptorVersion); must be 1 — Kido implements   */
/*                   descriptor v1 (the version UEFI ships).            */
/*  bi              : filled on success, same contract as               */
/*                   kido_mem_discover.                                 */
/*  Returns KIDO_OK, or KIDO_ERR_NO_MEMORY for every failure mode:      */
/*   - NULL bi, NULL/empty map, wrong version, stride too small for    */
/*     the v1 fields, ragged map (mmap_len % desc_size != 0),          */
/*   - page-count or address overflow, overlapping descriptors         */
/*     (contradictory firmware — never merged, never guessed),         */
/*   - more than 64 raw entries (pathological firmware),               */
/*   - no seedable region (all excluded, all zero-length, the map's    */
/*     own buffer covering everything, trim output exceeding the       */
/*     bounded table).                                                 */
/*  Every failure leaves bi->mem_valid == 0. Nothing is ever invented. */
/*                                                                     */
/*  CALLER CONTRACT: ExitBootServices has completed. BootServices      */
/*  code/data are therefore reclaimable and are seeded as usable —     */
/*  calling this path before EBS would hand live firmware pages to     */
/*  the allocator. The future entry-shim UEFI path owns this call      */
/*  order.                                                             */
/*                                                                     */
/*  TYPE LAW (UEFI memory types). Seeded: EfiConventionalMemory (7),   */
/*  EfiBootServicesCode (3), EfiBootServicesData (4). Excluded, each   */
/*  declared: loader code/data (1, 2 — loader-owned; kido-image's       */
/*  carve-out protects Kido's own image downstream), ACPI reclaim (9 — */
/*  reclaimable only after ACPI parse; no ACPI parser exists, named    */
/*  future), persistent memory (14 — no PM driver; claiming it as DRAM  */
/*  would be fiction), reserved (0), runtime code/data (5, 6),         */
/*  unusable (8), ACPI NVS (10), MMIO (11), MMIO port space (12), PAL   */
/*  code (13), and unknown types (skipped, never loud — absence is a   */
/*  fact, matching the DTB path's disabled-node handling).             */
/*  VirtualStart is ignored (Kido never calls SetVirtualAddressMap);   */
/*  Attribute is unread (declared).                                    */
/*                                                                     */
/*  PIPELINE (same shape as the DTB path — one discovery law, not      */
/*  two): parse+classify -> sort by base (insertion sort; no           */
/*  documented bet on firmware ordering) -> coalesce adjacent          */
/*  contiguous usable -> trim the map buffer's own [mmap, mmap+len)    */
/*  extent with the shared trimmer (the DTB-extent-trim precedent;     */
/*  vacuous when disjoint) -> largest-wins primary (ties: lowest base) */
/*  -> publish. The seed list is usable-by-construction.               */
/*                                                                     */
/*  PORTABILITY LAW: UEFI descriptors are little-endian by             */
/*  specification on AArch64; every field is read with manual          */
/*  little-endian loads — no struct casts, so a misaligned loader      */
/*  buffer can never fault the parse. Portable C, host-testable.       */
/* ------------------------------------------------------------------ */
kido_status_t kido_mem_discover_uefi(const void *mmap, size_t mmap_len,
                                     uint32_t desc_size, uint32_t desc_version,
                                     kido_bootinfo_t *bi);

#endif /* KIDO_MEM_H */
