/*
 * kido-topo.h — Kido CPU-topology registry: which PE lives in which slot.
 *
 * Session 33 brought secondary CPUs up and assigned each a slot
 * by bring_up order (kido-smp). Session 38 decoded the PE's own
 * identity (kido-mpidr). Nothing since has recorded the binding
 * between the two: given a slot, which Aff tuple is it? Given an
 * Aff tuple, which slot answers for it? The tree's answers so
 * far are unsatisfying in exactly the ways earlier sessions
 * refused to be: re-read firmware per slot (kido_smp_query
 * answers state, not identity), or assume Aff0 == slot (the
 * QEMU-virt accident mpidr's no-linear-index law forbids as
 * arithmetic — on a multi-cluster system Aff0 repeats and
 * two PEs alias into one slot). This leaf is the table that
 * makes the binding explicit, recorded, and looked up —
 * instead of recomputed or assumed.
 *
 * TABLE LAW (deliberation C1): one module-global table of
 * KIDO_TOPO_MAX_CPUS entries, each {aff, slot, occupied}.
 * The table is system-wide by nature — topology is not a
 * per-caller object — so the ipi/call module-global
 * precedent applies, and the sync/barrier caller-embedded
 * shape is distinguished, not followed. Entries are
 * written once per slot and never rewritten: a slot's PE
 * does not change under a running kernel, and a table
 * that allowed rewrites would let a later arrival steal
 * a live CPU's identity.
 *
 * SLOT LAW (deliberation C2): the slot is an smp-assigned
 * label, passed explicitly to register(), never computed
 * from the Aff tuple. No arithmetic maps Aff -> slot
 * anywhere in this leaf; that is the mpidr C2 refusal
 * carried forward. KIDO_TOPO_MAX_CPUS is deliberately its
 * own constant with the same value as KIDO_SMP_MAX_CPUS
 * and KIDO_IPI_MAX_CPUS (the ipi precedent: one census,
 * stated per module). If the census ever grows, the
 * three constants move together — a Gate reconciliation
 * item, not a silent drift.
 *
 * IDENTITY LAW (deliberation C3): comparison is
 * kido_mpidr_same_cpu() — all four Aff levels, MT and U
 * ignored. The table stores the decoded struct whole
 * (raw carried, the mpidr reserved-bit law), so a lookup
 * result answers "which PE" with the same fidelity the
 * decoder gave. There is deliberately no raw-affinity
 * API: a caller holding smp's raw uint64_t affinity
 * decodes it first with the pure kido_mpidr_decode()
 * (one call, no register read), so comparison lives in
 * exactly one place and can never drift between a raw
 * path and a decoded path.
 *
 * CONFLICT LAW (deliberation C4): registration is
 * append-only with two loud refusals, both EARLY_ENV
 * with the table untouched. Same Aff, different slot:
 * one PE cannot live in two slots (aliasing). Different
 * Aff, same slot: one slot cannot hold two PEs (theft).
 * The exact same pair re-registered returns KIDO_OK with
 * the count unmoved — idempotent, so an arrival retry
 * (secondary_arrived called twice, a Gate wiring
 * re-running its registration) is safe, not a second
 * invention. A full table refuses through the
 * slot-conflict arm: every slot is occupied, so any new
 * Aff collides with an occupied slot. No separate FULL
 * code is needed, and none is invented (sched-D1
 * precedent).
 *
 * ABSENCE LAW (deliberation C5): lookup of an
 * unregistered Aff, or of an unoccupied slot, is NOT an
 * error. It returns KIDO_OK with *found = 0 and the
 * out-pointer untouched — the try_lock / resonate-defer
 * precedent: absence is a fact the caller acts on, not a
 * failure. Only malformed calls refuse: NULL pointers,
 * slot >= MAX, or any call before init().
 *
 * PRIMARY LAW (deliberation C6): init() registers
 * NOTHING. The boot CPU's Aff is unknown to this leaf
 * until a caller reads it (mpidr_read) and registers
 * it, and the slot it belongs in is the smp table's
 * assignment, not this leaf's guess. Topo records what
 * it is told; it does not crown slot 0. The Gate wiring
 * that brings the primary into the table (read, then
 * register at the smp slot) is a Gate item, as with
 * every leaf since session 33. The zero Aff tuple is
 * registrable: it is the uniprocessor-shaped value
 * (mpidr §2), and refusing it would refuse the UP
 * machine's only CPU.
 *
 * LOCK LAW (deliberation C7): the table is guarded by
 * one module-global kido_sync spinlock, initialized by
 * topo_init() and held across each whole operation —
 * register, both lookups, count. No operation calls out
 * while holding it except the pure same_cpu() comparison,
 * so no lock-order question exists. The sync IRQ law
 * applies unchanged: never call from IRQ context that
 * preempted a holder of this lock. The lock's owner on
 * ARM64 is the MPIDR raw (sync's law); lock and unlock
 * pair inside a single call on one CPU, so the owner
 * always matches.
 *
 * INIT LAW (deliberation C8): init() succeeds exactly
 * once, from the uninitialized state. A second init()
 * refuses EARLY_ENV even over an empty table: re-init
 * would need a policy for existing entries, and
 * refusing keeps the topology append-only and honest.
 * There is no destroy API: this leaf owns no resource
 * a destroy would free (the table is static BSS, the
 * lock is static), unlike sched's stacks — the
 * session-37 D1 distinction, applied here.
 *
 * HONESTY LAW:
 *  - No new header code (sched-D1 precedent): every
 *    refusal is EARLY_ENV; absence is found = 0, never
 *    an error code.
 *  - Zero existing files touched. smp, mpidr, sync,
 *    ipi, and call keep their contracts; this leaf only
 *    reads mpidr's decoded struct and sync's public
 *    lock API. No wiring into smp arrival, ipi masks,
 *    or call slots — consumers are Gate items.
 *  - WRITTEN, NOT ASSEMBLED, NEVER EXECUTED on bare
 *    metal (toolchain absent, 23rd data point). The
 *    leaf has no asm of its own — its ARM64 content is
 *    sync's already-carried exclusive pair — so what
 *    awaits a tooled VM is a QEMU virt -smp 2 run
 *    showing two distinct Aff tuples registered at two
 *    distinct slots, plus the Gate wiring that puts
 *    them there. The hosted proof pins the table
 *    discipline, not delivery across silicon.
 *  - No bootable kernel is finalized without N8toriousAi;
 *    first boot is his to witness.
 *
 * FUTURES (named, not built): Gate consumers — the smp
 * arrival path registering each secondary (read +
 * register at its context_id slot), the primary's own
 * registration at boot, an ipi mask translator
 * (Aff -> slot mask, or slot mask validation against
 * registered entries rather than the bare census), a
 * CALL handler that resolves its own slot from its
 * Aff; a QEMU virt -smp 2 registration proof.
 *
 * Draft status: DRAFT (2026-10-31, session 40).
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror -pthread
 *        -DKIDO_HOSTED_TEST -DKIDO_TOPO_SELFTEST
 *        kido-topo.c kido-sync.c kido-mpidr.c -o topo-selftest
 *        (plain -c needs no -pthread: threads live in the
 *        test only, the barrier precedent).
 */
#ifndef KIDO_TOPO_H
#define KIDO_TOPO_H

#include "kido-boot.h"
#include "kido-mpidr.h"
#include "kido-sync.h"

#if !defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
#error "kido-topo: refusing to compile for unknown arch. The registry lock lives in per-arch code; define KIDO_HOSTED_TEST for the hosted draft harness."
#endif

/* CPU census: the smp table's count (the ipi precedent).
 * Must move with KIDO_SMP_MAX_CPUS / KIDO_IPI_MAX_CPUS
 * if the census ever grows — a Gate reconciliation item. */
#define KIDO_TOPO_MAX_CPUS 8u

/* Initialize the registry: lock to free, table empty,
 * count zero. Succeeds exactly once; a second call
 * refuses EARLY_ENV even over an empty table (init
 * law). Registers nothing — the primary's entry is a
 * Gate wiring's register() call, not an init side
 * effect. */
kido_status_t kido_topo_init(void);

/* Record that the PE with identity *aff lives in smp
 * slot `slot`. Refuses EARLY_ENV before init, on a NULL
 * aff, on slot >= KIDO_TOPO_MAX_CPUS, on an Aff already
 * registered at a different slot, or on a slot already
 * holding a different Aff — in every refusal case the
 * table is untouched. Re-registering the exact same
 * pair returns KIDO_OK with the count unmoved. */
kido_status_t kido_topo_register(const kido_mpidr_t *aff,
                                  uint32_t slot);

/* Look up the slot for *aff. Returns KIDO_OK always on
 * a valid call; *found = 1 with *slot_out set when the
 * Aff is registered, 0 with *slot_out untouched when
 * it is not (absence law). Refuses EARLY_ENV before
 * init or on any NULL pointer. */
kido_status_t kido_topo_slot_for(const kido_mpidr_t *aff,
                                  uint32_t *slot_out,
                                  uint32_t *found);

/* Look up the identity registered at `slot`. Returns
 * KIDO_OK always on a valid call; *found = 1 with
 * *aff_out holding the stored decoded struct when the
 * slot is occupied, 0 with *aff_out untouched when it
 * is not. Refuses EARLY_ENV before init, on any NULL
 * pointer, or on slot >= KIDO_TOPO_MAX_CPUS. */
kido_status_t kido_topo_aff_for(uint32_t slot,
                                 kido_mpidr_t *aff_out,
                                 uint32_t *found);

/* Number of registered PEs. Refuses EARLY_ENV before
 * init or on a NULL out-pointer. */
kido_status_t kido_topo_count(uint32_t *count_out);

#ifdef KIDO_TOPO_SELFTEST
#ifndef KIDO_HOSTED_TEST
#error "KIDO_TOPO_SELFTEST needs KIDO_HOSTED_TEST."
#endif
int kido_topo_selftest_main(void);
#endif /* KIDO_TOPO_SELFTEST */

#endif /* KIDO_TOPO_H */
