/*
 * kido-smp.h — Kido secondary-CPU bring-up policy, on top of PSCI.
 *
 * The tree has a PSCI conduit (session 32) and a UP scheduler by
 * law. This module is the policy between them: which secondary
 * CPU to start, with which stack, and what state it is in. It
 * issues no `smc` itself — every firmware word goes through
 * kido-psci.h, and every psci status propagates unchanged.
 *
 * TWO PHASES, TWO FACTS (deliberation C1):
 *   STARTED = the firmware reports the CPU ON after bring_up's
 *             bounded AFFINITY_INFO poll. The CPU started.
 *   ARRIVED = the secondary's entry stub called
 *             kido_smp_secondary_arrived(ctx) from real Kido
 *             code. The CPU reached us. The scheduler/Gate
 *             wiring consumes ARRIVED, never STARTED.
 *
 * SECONDARY STUB CONTRACT (declared, not built — the stub is
 * a scheduler/Gate item, deliberation D3):
 *   - The stub's address is the `entry` argument to bring_up.
 *   - The stub receives the slot index as its PSCI context_id
 *     (DEN0022: the entry point receives context_id).
 *   - Before cpu_on, bring_up writes the secondary's stack top
 *     into kido_smp_secondary_stack_top[slot] (BSS, plain
 *     uint64). The stub loads SP from that word with a
 *     PC-relative read (the entry .S pattern) — no C call
 *     before SP exists.
 *   - Once it has a stack, the stub calls
 *     kido_smp_secondary_arrived(slot) and then waits on
 *     kido_smp_secondary_wait_release(slot, bound) until the
 *     primary releases it into real work.
 *
 * HONESTY LAW:
 *  - No new header code (sched-D1 precedent): every failure is
 *    KIDO_ERR_EARLY_ENV or a propagated psci status.
 *  - Affinities are opaque (psci law): smp never parses MPIDR.
 *  - No "power down another CPU" API exists, because PSCI has
 *    none: CPU_OFF powers down the CALLER. A secondary powers
 *    itself down with kido_smp_secondary_off(); the primary
 *    learns of it through kido_smp_query(), which re-reads
 *    AFFINITY_INFO. secondary_off marks nothing — on bare
 *    metal a successful CPU_OFF never returns, so marking
 *    code after the call would run only on the error path.
 *  - Stacks are caller-supplied carves (deliberation D2): smp
 *    never allocates and never frees a secondary stack. Who
 *    frees a stack — and when, if the CPU never arrives — is
 *    the scheduler/Gate wiring's question, not this module's.
 *  - WRITTEN, NOT ASSEMBLED, NEVER EXECUTED on bare metal
 *    (toolchain absent, 16th data point). The hosted proof
 *    drives the real psci API against psci.c's scripted
 *    firmware double; the double reports ON immediately after
 *    cpu_on, so the ON_PENDING-transient and poll-timeout
 *    paths are code-reviewed, not hosted-proven (see the
 *    deliberation C5). QEMU proof waits on the future stub
 *    as well as the toolchain.
 *  - No bootable kernel is finalized without N8toriousAi;
 *    first boot is his to witness.
 *
 * FUTURES (named, not built): the secondary entry stub (Gate
 * item, contract above); scheduler/Gate wiring that consumes
 * ARRIVED slots; an audited retry policy for FAILED slots
 * (deliberation D1); QEMU virt -smp proof.
 *
 * Draft status: DRAFT (2026-10-28, session 33).
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST
 *        -DKIDO_SMP_SELFTEST kido-smp.c kido-psci.c -o smp-selftest
 *        (psci.c WITHOUT KIDO_PSCI_SELFTEST, so no main
 *        collision; the double's setters stay out of this TU)
 */
#ifndef KIDO_SMP_H
#define KIDO_SMP_H

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

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

/* Bounded static table: exists before any allocator. */
#define KIDO_SMP_MAX_CPUS 8u

/* Minimum secondary stack: 16 KiB, the scheduler's stack size,
 * 16-byte aligned base and size (AAPCS64). */
#define KIDO_SMP_MIN_STACK_SIZE (16u * 1024u)

/* Bounded firmware poll after cpu_on (loop count, not time:
 * smp has no timer dependency by design). */
#define KIDO_SMP_AFFINITY_POLLS (1u << 20)

typedef enum kido_smp_state {
    KIDO_SMP_EMPTY = 0,   /* slot free */
    KIDO_SMP_STARTED,     /* firmware reports ON; stub not yet heard from */
    KIDO_SMP_ARRIVED,     /* stub called secondary_arrived */
    KIDO_SMP_FAILED,      /* cpu_on succeeded but ON never reported; terminal */
    KIDO_SMP_OFF          /* firmware reports OFF after ARRIVED/STARTED */
} kido_smp_state_t;

typedef struct kido_smp_stats {
    uint32_t brought;   /* successful bring_ups (STARTED or beyond) */
    uint32_t arrived;   /* slots that reached ARRIVED */
    uint32_t failed;    /* slots that went FAILED */
    uint32_t live;      /* slots currently STARTED or ARRIVED */
} kido_smp_stats_t;

/* Per-slot stack-top mailbox (deliberation C3). Written by
 * bring_up before cpu_on; read by the future secondary stub
 * with a PC-relative load. Plain BSS words, never a C call. */
extern uint64_t kido_smp_secondary_stack_top[KIDO_SMP_MAX_CPUS];

/* Initialize the table. Requires the PSCI conduit ready
 * (kido_psci_version() must succeed — psci init itself is
 * caller-gated, Gate policy, not this module's call).
 * Refuses EARLY_ENV while any secondary is live (STARTED or
 * ARRIVED); OFF/FAILED/EMPTY slots allow re-init. Re-init
 * clears the table and the mailbox. */
kido_status_t kido_smp_init(void);

/* Bring up one secondary: guards -> duplicate scan -> reserve
 * slot + write mailbox -> cpu_on(slot index as context_id)
 * -> bounded AFFINITY_INFO poll -> STARTED. Guards (NULL
 * slot_out, zero/unaligned stack, stack below minimum) refuse
 * BEFORE reservation, leaving the table empty. A refused
 * cpu_on returns the slot to EMPTY (refusal changes no
 * firmware state — retry with corrected arguments is
 * allowed). A poll timeout or poll error after a successful
 * cpu_on marks the slot FAILED, terminal for its affinity.
 * *slot_out receives the slot index on success. */
kido_status_t kido_smp_bring_up(uint64_t affinity, uint64_t entry,
                                 uint64_t stack_base,
                                 uint64_t stack_size,
                                 uint32_t *slot_out);

/* Secondary-side arrival: called by the entry stub with its
 * context_id (= slot index). STARTED -> ARRIVED. Any other
 * state, or an out-of-range context_id, is EARLY_ENV. */
kido_status_t kido_smp_secondary_arrived(uint32_t context_id);

/* Primary-side release: ARRIVED -> released. The secondary's
 * wait_release then returns OK. Refuses EARLY_ENV on any
 * other state or a bad slot. */
kido_status_t kido_smp_release(uint32_t slot);

/* Secondary-side wait: returns OK once the primary has
 * released this slot, EARLY_ENV if the bound expires first
 * or the slot is not ARRIVED. The bound is a loop count,
 * not a time (no timer dependency). */
kido_status_t kido_smp_secondary_wait_release(uint32_t context_id,
                                               uint32_t max_spins);

/* Secondary-side power-down: calls psci_cpu_off for the
 * CALLING cpu and propagates its status. Marks nothing:
 * on bare metal success never returns (see honesty law).
 * Refuses EARLY_ENV on a bad context_id or a slot that is
 * not STARTED/ARRIVED. */
kido_status_t kido_smp_secondary_off(uint32_t context_id);

/* Read one slot's recorded state (no firmware call).
 * EARLY_ENV on a bad slot or NULL out-pointer. */
kido_status_t kido_smp_slot_state(uint32_t slot,
                                   kido_smp_state_t *out);

/* Re-read firmware truth for one slot (AFFINITY_INFO) and
 * update the record: ARRIVED/STARTED -> OFF only on a
 * firmware OFF report. A firmware ON report leaves smp
 * state alone (arrival is smp-level, not firmware-level).
 * EARLY_ENV on a bad slot, an EMPTY/FAILED slot (nothing to
 * refresh), a NULL out-pointer, or a firmware error. */
kido_status_t kido_smp_query(uint32_t slot, kido_smp_state_t *out);

/* Table counts. EARLY_ENV before init or on a NULL out. */
kido_status_t kido_smp_stats(kido_smp_stats_t *out);

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

#endif /* KIDO_SMP_H */
