/*
 * kido-sync.h — Kido SMP synchronization: the spinlock.
 *
 * Session 33 brought secondary CPUs up (kido-smp). Nothing yet
 * stopped two of them writing the same word at once. This module
 * is that primitive: one lock, caller-embedded, no allocator,
 * no scheduler coupling, no module-global table. A lock must
 * exist before any allocator policy, and a global lock registry
 * would be a second invention.
 *
 * THE PRIMITIVE (deliberation C5/C6):
 *   ARM64: LDAXR (acquire) / STLXR (release) exclusive pair,
 *   WFE sleep after observing the lock held, SEV wake on
 *   unlock. The WFE sits ONLY on the observed-held branch:
 *   a failed STLXR retries the LDAXR immediately, never
 *   through WFE — otherwise a spurious exclusive failure
 *   with a free lock and no future SEV could sleep forever.
 *   SEVL primes the first iteration.
 *   Hosted: GCC __atomic builtins
 *   (__atomic_compare_exchange_n for take, __atomic_store_n
 *   release for give) — real atomics on the host, proving
 *   the lock's STATE MACHINE exactly. The hosted path does
 *   NOT prove the ARM64 instruction sequence (see PROOF
 *   STATUS).
 *   Guarantee, plainly: writes before unlock() are visible
 *   to the CPU that later takes the lock. Nothing stronger
 *   is claimed. No DMB is needed for the lock itself: the
 *   acquire/release pair IS the ordering.
 *
 * OWNER LAW (deliberation C4):
 *   The lock records its owner's CPU id — MPIDR_EL1 raw on
 *   ARM64 (readable at EL1, never parsed: the smp/psci
 *   opaque-affinity law), the hosted injector's value on
 *   hosted. unlock() by a non-owner refuses EARLY_ENV and
 *   the lock stays held. unlock() of a free lock refuses
 *   the same way. The owner word is written while the lock
 *   word is held (only the holder writes it) and cleared
 *   before the release store; STLR's release semantics
 *   order the clear before the unlock visibly lands.
 *   UINT64_MAX means "free" and is never a valid CPU id.
 *
 * IRQ LAW (deliberation C3): the lock does NOT disable
 * interrupts. Taking the same lock in an IRQ handler that
 * interrupted its holder deadlocks the CPU (the handler
 * spins for a holder that cannot run). Locks are CPU-to-CPU
 * exclusion, not IRQ exclusion. IRQ handlers use try_lock
 * or a separate discipline; the scheduler/Gate wiring owns
 * that policy, not this module.
 *
 * DEAD-HOLDER LAW (deliberation C2): lock() spins until it
 * holds — that is the primitive's definition, and a lock
 * held by a LIVE holder always progresses. If the holder
 * CPU dies holding the lock, lock() never returns, and no
 * timeout would make that safe: a timeout would let two
 * CPUs into the critical section together, the exact
 * corruption the lock exists to prevent. Callers that
 * cannot wait use try_lock().
 *
 * CONTENTION IS NOT FAILURE (deliberation C1): the status
 * enum has no BUSY code, and inventing one is N8toriousAi's call
 * (sched-D1 precedent). try_lock() returns KIDO_OK with
 * *acquired = 0 on contention — the resonate-defer
 * precedent. NULL lock, NULL out-pointer, and a bad magic
 * (uninitialized lock) are real errors: EARLY_ENV loud.
 *
 * SNAPSHOT LAW (deliberation C8): is_locked() reads the
 * word once and reports it. On a live system another CPU
 * may take or release the lock in the next instant; the
 * value is a diagnostic snapshot, never a
 * synchronization point. Callers that need certainty use
 * try_lock().
 *
 * INIT LAW (deliberation C7): init() refuses EARLY_ENV on
 * a lock whose word is nonzero — re-initializing a held
 * lock would silently free it under its holder. Init on
 * a free lock (including a previously used, properly
 * unlocked one) succeeds and resets owner to free.
 *
 * PROOF STATUS: WRITTEN, NOT ASSEMBLED, NEVER EXECUTED on
 * bare metal (toolchain absent, 17th data point). The
 * hosted proof drives the real __atomic builtins and pins
 * every refusal path, including stranger-unlock via the
 * hosted CPU-id injector. The ARM64 LDAXR/STLXR/WFE/SEV
 * sequence 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): ticket lock / FIFO fairness
 * (deliberation D3 — starvation under heavy contention is
 * documented, not hidden); a barrier primitive built on
 * this lock for secondary rendezvous; the first consumer
 * (scheduler/Gate wiring or an smp shared-state guard).
 *
 * Draft status: DRAFT (2026-10-28, session 34).
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST
 *        -DKIDO_SYNC_SELFTEST kido-sync.c -o sync-selftest
 */
#ifndef KIDO_SYNC_H
#define KIDO_SYNC_H

#include "kido-boot.h"

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

/* Magic: init() stamps it; every API refuses a lock without
 * it before touching the word. Uninitialized locks fail
 * loud, never silently. */
#define KIDO_SYNC_MAGIC 0x4B594E43u /* arbitrary stamp, never zero */
#define KIDO_SYNC_OWNER_FREE ((uint64_t)~0u)

/* One lock, caller-embedded. 16 bytes, 8-aligned. The word
 * is the ONLY field the exclusive pair touches; magic and
 * owner are plain words guarded by the word itself. */
typedef struct kido_spinlock {
    volatile uint32_t word;   /* 0 = free, 1 = held */
    uint32_t          magic;  /* KIDO_SYNC_MAGIC once init() has run */
    uint64_t          owner;  /* holder's CPU id, or KIDO_SYNC_OWNER_FREE */
} kido_spinlock_t;

/* Initialize a lock to free. Refuses EARLY_ENV on a NULL
 * lock, or on a lock whose word is nonzero (a held lock
 * must never be silently freed under its holder). On a
 * free lock, succeeds and resets owner to free. */
kido_status_t kido_spin_init(kido_spinlock_t *lock);

/* Take the lock, spinning (WFE/SEV on ARM64) until held.
 * On success the caller owns the lock and owner records
 * its CPU id. Refuses EARLY_ENV on a NULL or
 * uninitialized lock. Never returns while another live
 * CPU holds the lock (dead-holder law: see header). */
kido_status_t kido_spin_lock(kido_spinlock_t *lock);

/* One attempt at the lock. Returns KIDO_OK always on a
 * valid lock; *acquired = 1 if this call took the lock
 * (owner recorded), 0 if another CPU holds it (lock
 * untouched). Refuses EARLY_ENV on a NULL lock, NULL
 * out-pointer, or uninitialized lock. */
kido_status_t kido_spin_try_lock(kido_spinlock_t *lock,
                                  uint32_t *acquired);

/* Release a lock this CPU holds. Refuses EARLY_ENV on a
 * NULL or uninitialized lock, on a free lock, or when
 * the caller is not the recorded owner — in every refusal
 * case the lock's state is untouched. On success the
 * lock is free, owner is free, and waiters are woken
 * (SEV on ARM64). */
kido_status_t kido_spin_unlock(kido_spinlock_t *lock);

/* Diagnostic snapshot: *locked = 1 if the word reads
 * held, 0 if free, at the instant of the read. Not a
 * synchronization point (snapshot law). Refuses EARLY_ENV
 * on a NULL lock, NULL out-pointer, or uninitialized
 * lock. */
kido_status_t kido_spin_is_locked(kido_spinlock_t *lock,
                                   uint32_t *locked);

#ifdef KIDO_HOSTED_TEST
/* Hosted-only CPU-id injector (the kido-image / kido-mem
 * injector precedent): lets the self-test play a second
 * CPU, so stranger-unlock refusal is proven, not
 * code-reviewed. Refuses EARLY_ENV on the free sentinel.
 * No-op on bare metal (MPIDR_EL1 is the id there). */
kido_status_t kido_sync_test_set_cpu_id(uint64_t cpu_id);
#endif /* KIDO_HOSTED_TEST */

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

#endif /* KIDO_SYNC_H */
