/*
 * kido-barrier.h — Kido SMP barrier: N CPUs arrive, all proceed together.
 *
 * Session 33 brought secondary CPUs up (kido-smp) and session 34
 * gave them a lock (kido-sync). Nothing yet lets N CPUs agree on
 * a shared "starting line." This module is that primitive: one
 * barrier, caller-embedded, no allocator, no scheduler coupling,
 * no module-global table. A barrier must exist before any
 * allocator policy, and a global barrier registry would be a
 * second invention.
 *
 * THE PRIMITIVE (deliberation C1/C2):
 *   A generation counter plus an arrival counter, guarded by
 *   one spinlock. wait(): take the lock, note the current
 *   generation, increment arrived; if arrived == participants,
 *   the caller is the last arriver — reset arrived to 0,
 *   bump generation, unlock, return. Otherwise unlock and
 *   spin on an acquire load of generation until it differs
 *   from the noted value.
 *   The order inside the lock (reset, then bump) is
 *   load-bearing: a waiter spins on generation, never on
 *   arrived, so the reset can never release a waiter early,
 *   and a waiter that starts spinning after the release
 *   sees the new generation on its first load.
 *
 * ORDERING CHAIN (deliberation P2 — stated exactly so a reader
 * can audit it):
 *   Last arriver writes generation under the spinlock, then
 *   unlocks (STLR release). Waiters spin on an acquire load
 *   of generation (LDAR on ARM64, __atomic acquire on
 *   hosted). A waiter that observes the new generation
 *   therefore observes everything every arriver wrote before
 *   its arrival. No DMB is claimed or needed: the lock's
 *   release plus the acquire load IS the ordering.
 *
 * CALLER CONTRACT (deliberation C5): one wait() call per
 * participant per round. Arrival counts, it does not
 * identify — a participant that calls twice in one round
 * counts twice and releases the barrier early. That is the
 * contract, stated, not a detected error: detection would
 * need per-CPU arrival slots, a second invention on a leaf.
 *
 * DEADLOCK LAW (deliberation C3): a barrier whose
 * participant count is wrong, or whose participant never
 * arrives, spins forever — by definition. No timeout: a
 * timeout would release a partial group past the starting
 * line, silent corruption (half the CPUs proceed on shared
 * state the other half never finished writing), not a
 * recovery. Callers that cannot wait do not use a barrier.
 * There is no try_wait: arrival without waiting is just a
 * counter.
 *
 * IRQ LAW (deliberation C4): wait() spins, so calling it
 * from an IRQ handler that preempted a participant deadlocks
 * that CPU (the handler spins for an arrival that cannot
 * happen until the handler returns). Barriers are CPU-to-CPU
 * rendezvous, not IRQ discipline.
 *
 * INIT LAW (deliberation C6): init() refuses EARLY_ENV on a
 * barrier with a round in flight (arrived != 0) — re-
 * initializing under arriving CPUs would silently free the
 * round — and on a NULL barrier, or 0 / >8 participants.
 * Init on an idle barrier succeeds and PRESERVES the
 * generation counter (monotonic, never reset): a stale
 * waiter from a previous life spinning on an old generation
 * must never be released by a reset to 0. Init is a
 * construction-time call, not a concurrent one: the caller
 * initializes before sharing the barrier.
 *
 * PARTICIPANT CAP (deliberation C7): 8, matching
 * KIDO_SMP_MAX_CPUS — the only CPU census the tree has.
 * A rendezvous larger than the machine's CPU table is a
 * guess, not a design.
 *
 * SNAPSHOT LAW: arrived() reads the counter once and
 * reports it. On a live system another CPU may arrive or
 * release in the next instant; the value is a diagnostic
 * snapshot, never a synchronization point. Callers that
 * need certainty wait.
 *
 * PROOF STATUS: WRITTEN, NOT ASSEMBLED, NEVER EXECUTED on
 * bare metal (toolchain absent, 18th data point). The
 * hosted proof drives real pthreads through two rendezvous
 * rounds and pins every refusal path, including re-init
 * refusal during a live round. The ARM64 LDAR spinner
 * awaits assemble + disassembly + a QEMU virt -smp 2 run
 * (which also needs the Gate secondary stub). No bootable
 * kernel is finalized without N8toriousAi; first boot is his to
 * witness.
 *
 * FUTURES (named, not built): sense-reversing local sense
 * (deliberation D2 — no behavioral payoff over the
 * generation counter); per-CPU arrival slots / double-
 * arrive detection (D3); the first consumer (scheduler-
 * tick rendezvous, smp shared-state guard, or a Gate
 * wiring — D4).
 *
 * Draft status: DRAFT (2026-10-29, session 35).
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror -pthread
 *        -DKIDO_HOSTED_TEST -DKIDO_BARRIER_SELFTEST
 *        kido-barrier.c kido-sync.c -o barrier-selftest
 *        (pthreads live in the TEST TU ONLY, never in the
 *        module: plain hosted -c of kido-barrier.c needs no
 *        -pthread.)
 */
#ifndef KIDO_BARRIER_H
#define KIDO_BARRIER_H

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

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

/* Magic: init() stamps it; every API refuses a barrier
 * without it before touching the counters. Uninitialized
 * barriers fail loud, never silently. */
#define KIDO_BARRIER_MAGIC 0x42415252u /* arbitrary stamp, never zero */

/* Participant cap: the smp table's CPU census (deliberation C7). */
#define KIDO_BARRIER_MAX_PARTICIPANTS 8u

/* One barrier, caller-embedded. The lock is the ONLY
 * synchronization field; arrived/generation are plain
 * counters guarded by it on the write side (the spinner
 * reads generation through an acquire load). */
typedef struct kido_barrier {
    kido_spinlock_t lock;         /* guards arrived + generation writes */
    volatile uint32_t arrived;    /* arrivals in the current round */
    volatile uint32_t generation; /* increments once per released round */
    uint32_t participants;        /* fixed at init, 1..8 */
    uint32_t magic;               /* KIDO_BARRIER_MAGIC once init() ran */
} kido_barrier_t;

/* Initialize a barrier for `participants` CPUs. Refuses
 * EARLY_ENV on a NULL barrier, 0 or >8 participants, or a
 * round in flight (arrived != 0). On an idle barrier,
 * succeeds, resets arrived to 0, and PRESERVES generation
 * (monotonic, never reset — deliberation C6). */
kido_status_t kido_barrier_init(kido_barrier_t *bar,
                                uint32_t participants);

/* Arrive and wait for release. Returns KIDO_OK when the
 * barrier releases (this caller was or was not the last
 * arriver — the return does not distinguish; callers that
 * need to know use arrived() before the round, not after).
 * Refuses EARLY_ENV on a NULL or uninitialized barrier.
 * Spins until the generation changes: a missing
 * participant spins forever by definition (deadlock law).
 * Never call from IRQ context that preempted a
 * participant (IRQ law). One call per participant per
 * round (caller contract). */
kido_status_t kido_barrier_wait(kido_barrier_t *bar);

/* Diagnostic snapshot: *count = arrivals in the current
 * round at the instant of the read. Not a synchronization
 * point (snapshot law). Refuses EARLY_ENV on a NULL
 * barrier, NULL out-pointer, or uninitialized barrier. */
kido_status_t kido_barrier_arrived(kido_barrier_t *bar,
                                   uint32_t *count);

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

#endif /* KIDO_BARRIER_H */
