/*
 * kido-call.h — Kido cross-CPU function mailbox.
 *
 * Session 33 brought secondary CPUs up (kido-smp), 34 gave
 * them a lock (kido-sync), 35 gave them a rendezvous
 * (kido-barrier), 36 gave them a signal (kido-ipi). Nothing
 * yet lets one CPU ask another CPU to DO something. A signal
 * carries no work. This module is the work carrier: one slot
 * per CPU, one call per slot, a function pointer and an
 * argument. Session 36's ipi deliberation D2 named exactly
 * this as the blocker for a future CALL type; this module
 * closes that blocker. The CALL type itself stays a named
 * future in ipi until the Gate wiring binds transport +
 * handler + wakeup policy together.
 *
 * SHAPE (deliberation C1): module-global table, not a
 * caller-embedded struct. A mailbox slot belongs to its
 * TARGET CPU, which never "holds" it — the slot is an
 * address in a system-wide address book, like the ipi
 * registry's SGI namespace and the GIC's handler table.
 * Two mailbox tables would double-deliver calls. One
 * table, eight slots, indexed by target CPU. The
 * sync/barrier caller-embedded precedent was argued and
 * distinguished: a lock or a barrier is owned by its
 * users, who hold it; a mailbox slot is owned by its
 * target, which only services it.
 *
 * STATE MACHINE (deliberation P1): EMPTY -> POSTED ->
 * RUNNING -> DONE -> EMPTY. No other transitions exist.
 * post() moves EMPTY -> POSTED. poll() moves POSTED ->
 * RUNNING (the claim), then RUNNING -> DONE (the store).
 * reap() moves DONE -> EMPTY. A busy slot is a door, not
 * an error: post() returns KIDO_OK with *accepted = 0
 * (the resonate-defer door, the sync try_lock precedent).
 * A not-yet-done reap returns KIDO_OK with *done = 0.
 *
 * CLAIM, NOT CUSTODY (deliberation C3 — the decision the
 * module turns on): poll() claims the slot under the lock,
 * UNLOCKS, runs the function, relocks, and stores the
 * result. Running under the lock would serialize every
 * reap against an arbitrary function body, and would
 * deadlock the day a function posts a call of its own:
 * the poster would spin for a lock held by the CPU
 * running its own function. The claim is the critical
 * section, not the work. A second poll() during RUNNING
 * is a no-op by the state check, so the claim is also
 * the re-entrancy guard.
 *
 * POSTER LAW (deliberation C4): the slot records the
 * posting CPU; reap() by any other CPU refuses EARLY_ENV
 * with the slot untouched — the sync stranger-unlock
 * precedent, applied to results. The check applies
 * whenever the slot is non-EMPTY, not only at DONE.
 *
 * ARGUMENT LAW (deliberation C5): the argument is void*,
 * its lifetime is the caller's, and the mailbox never
 * copies, frees, or extends it. A function that needs to
 * return data writes it through its argument before
 * returning; the slot stores only the function's
 * kido_status_t return.
 *
 * POLL-FIRST, NO WAKEUP (deliberation C6): the target's
 * idle loop calls kido_call_poll() for its own slot, and
 * that loop is the execution engine. No ipi include, no
 * transport injection, no GIC base — the leaf stays
 * host-testable with zero MMIO. The Gate wiring that
 * binds a wakeup (ipi PING, ipi RESCHED, or the future
 * CALL type whose handler calls poll) is one line plus a
 * policy decision, and is named as the first-consumer
 * Gate item below. Polling without wakeup is slower, not
 * wrong: the call still executes, exactly once.
 *
 * CPU IDENTITY (deliberation C8): the caller passes both
 * indices explicitly. ipi deliberation C6 settled this:
 * the caller knows its smp slot, and MPIDR parsing is a
 * named future, not a guess. Both indices are validated
 * against the 8-CPU census; indices >= 8 are EARLY_ENV,
 * never truncated. No hosted injector is needed: the
 * self-test plays two CPUs by passing two indices.
 *
 * IDLE-LOOP CONTRACT (deliberation C9): the idle loop
 * services its OWN slot. The module cannot enforce this
 * without a current-CPU query it refuses to invent, so
 * it is stated, not detected — the barrier
 * one-call-per-round precedent. Servicing another CPU's
 * slot would execute the function on the wrong CPU,
 * defeating the module; the Gate wiring (which knows
 * its own slot) is the enforcement point.
 *
 * IRQ LAW (deliberation D3): a function pointer is
 * arbitrary code, and arbitrary code never runs in
 * interrupt context. poll() is a task-context call. An
 * IPI handler's job, when the Gate wiring gives it one,
 * is to arrange for poll() to be called at a safe point
 * — never to BE the execution.
 *
 * INIT LAW (deliberation C7): init() rebuilds the world
 * only when every slot is EMPTY; a POSTED, RUNNING, or
 * DONE slot refuses EARLY_ENV with the table untouched
 * (the barrier in-flight precedent). Re-init on an empty
 * table clears slots and stats.
 *
 * SNAPSHOT LAW (deliberation, sync precedent):
 * kido_call_state() reads the slot state once and
 * reports it. On a live system another CPU may post or
 * reap in the next instant; the value is a diagnostic
 * snapshot, never a synchronization point.
 *
 * NO NEW HEADER CODES (sched-D1 precedent): every
 * failure is KIDO_ERR_EARLY_ENV. Busy is KIDO_OK +
 * accepted 0; not-done is KIDO_OK + done 0.
 *
 * PROOF STATUS: WRITTEN, NOT ASSEMBLED, NEVER EXECUTED
 * on bare metal (toolchain absent, 20th data point). The
 * module has no asm at all — unlike sessions 33-35 there
 * is no ARM64 spelling awaiting disassembly — only the
 * cross-CPU execution itself, which awaits the Gate
 * secondary stub + a QEMU virt -smp 2 run. The hosted
 * proof drives the real spinlock discipline and a real
 * pthread poller thread, and pins every refusal. No
 * bootable kernel is finalized without N8toriousAi; first
 * boot is his to witness.
 *
 * FUTURES (named, not built): a queue of N calls per CPU
 * (deliberation D2 — needs a queue policy no caller has
 * asked for); blocking post/wait with a timeout (D1 —
 * overruled, the caller loops the try-shaped doors);
 * the ipi CALL type binding (transport + handler +
 * wakeup policy, Gate item); the first consumer
 * (scheduler-tick work half, or a Gate wiring).
 *
 * Draft status: DRAFT (2026-10-30, session 37).
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror -pthread
 *        -DKIDO_HOSTED_TEST -DKIDO_CALL_SELFTEST
 *        kido-call.c kido-sync.c -o call-selftest
 *        (pthreads live in the TEST TU ONLY, never in the
 *        module: plain hosted -c of kido-call.c needs no
 *        -pthread, proven below.)
 */
#ifndef KIDO_CALL_H
#define KIDO_CALL_H

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

#if !defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
#error "kido-call: refusing to compile for unknown arch. Slots live in per-CPU tables; define KIDO_HOSTED_TEST for the hosted draft harness."
#endif

/* Magic: init() stamps it; every API refuses an
 * uninitialized table before touching a slot. Zeroed BSS
 * reads magic 0, which refuses — an unbound table fails
 * loud, never silently. */
#define KIDO_CALL_MAGIC 0x43414C4Cu /* "CALL" stamp, never zero */

/* CPU census: the smp table's count (deliberation P4).
 * This module does not include kido-smp.h for one
 * constant — the barrier/ipi precedent (own cap, same
 * value, same comment) — so the leaf stays leaf. A
 * mailbox larger than the machine's CPU table is a
 * guess, not a design. */
#define KIDO_CALL_MAX_CPUS 8u

/* The work itself: a function returning a status, taking
 * the caller's argument. Runs in task context on the
 * TARGET CPU (poll's caller), never in IRQ context. */
typedef kido_status_t (*kido_call_fn_t)(void *arg);

/* Slot states. Order is the lifecycle; DONE is the only
 * state reap() accepts, EMPTY the only state post()
 * accepts, POSTED the only state poll() claims. */
typedef enum kido_call_state {
    KIDO_CALL_EMPTY   = 0, /* slot free */
    KIDO_CALL_POSTED  = 1, /* work waiting for the target's poll */
    KIDO_CALL_RUNNING = 2, /* claimed; the function is executing */
    KIDO_CALL_DONE    = 3  /* result stored; awaiting its poster */
} kido_call_state_t;

/* Counters. posted counts accepted posts; busy counts
 * post() doors closed on a non-EMPTY slot; completed
 * counts functions run to a stored result; reaped counts
 * DONE slots returned to EMPTY; stranger counts reap()
 * refusals by a non-poster. */
typedef struct kido_call_stats {
    uint32_t posted;
    uint32_t busy;
    uint32_t completed;
    uint32_t reaped;
    uint32_t stranger;
} kido_call_stats_t;

/* Build (or rebuild) the table. Refuses EARLY_ENV when
 * any slot is non-EMPTY (deliberation C7) — rebuilding
 * over a call in flight would silently lose work. On an
 * empty table, succeeds and clears slots and stats. Init
 * is a construction-time call, not a concurrent one. */
kido_status_t kido_call_init(void);

/* Post a call from source_cpu to target_cpu. Refuses
 * EARLY_ENV before init, on a NULL function, on a NULL
 * accepted pointer, or on either CPU index >=
 * KIDO_CALL_MAX_CPUS. On a non-EMPTY target slot,
 * returns KIDO_OK with *accepted = 0 and counts busy —
 * the door, not an error. On an EMPTY slot, stores fn,
 * arg, and poster, moves EMPTY -> POSTED, returns
 * KIDO_OK with *accepted = 1, and counts posted. */
kido_status_t kido_call_post(uint32_t source_cpu, uint32_t target_cpu,
                             kido_call_fn_t fn, void *arg,
                             uint32_t *accepted);

/* Service one CPU's slot: the target's idle-loop call.
 * Refuses EARLY_ENV before init or on a CPU index >=
 * KIDO_CALL_MAX_CPUS. On an EMPTY, RUNNING, or DONE
 * slot, a no-op returning KIDO_OK. On a POSTED slot,
 * claims it (POSTED -> RUNNING under the lock), runs
 * the function OUTSIDE the lock, stores the result
 * (RUNNING -> DONE under the lock), and counts
 * completed. The caller services its OWN slot
 * (deliberation C9 — stated, not detected). */
kido_status_t kido_call_poll(uint32_t cpu);

/* Reap a call's result. Refuses EARLY_ENV before init,
 * on a NULL done or result pointer, on either CPU index
 * >= KIDO_CALL_MAX_CPUS, or when the slot is non-EMPTY
 * and the caller is not the recorded poster (stranger
 * refusal — the slot is untouched, stranger counted).
 * On a DONE slot owned by the caller, copies the stored
 * result, moves DONE -> EMPTY, returns KIDO_OK with
 * *done = 1, and counts reaped. On a POSTED or RUNNING
 * slot owned by the caller, or on an EMPTY slot, returns
 * KIDO_OK with *done = 0 and touches nothing. */
kido_status_t kido_call_reap(uint32_t source_cpu, uint32_t target_cpu,
                             uint32_t *done, kido_status_t *result);

/* Diagnostic snapshot: *state reads the target slot's
 * state once. Not a synchronization point (snapshot
 * law). Refuses EARLY_ENV before init, on a NULL
 * out-pointer, or on a CPU index >= KIDO_CALL_MAX_CPUS. */
kido_status_t kido_call_state(uint32_t target_cpu,
                              kido_call_state_t *state);

/* Copy the counters out. Refuses EARLY_ENV before init
 * or on a NULL out-pointer. */
kido_status_t kido_call_stats(kido_call_stats_t *out);

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

#endif /* KIDO_CALL_H */
