/*
 * kido-ipi.h — Kido inter-processor interrupts: the signaling
 * discipline on top of the GIC's software interrupts.
 *
 * Session 33 brought secondary CPUs up (kido-smp), session 34
 * gave them exclusion (kido-sync), session 35 gave them a
 * rendezvous (kido-barrier). Nothing yet lets one CPU SIGNAL
 * another. The GIC driver can send a software interrupt
 * (kido_gic_send_sgi), but an SGI number means nothing without
 * a discipline: which SGI ids are IPIs, what each one asks
 * for, who handles it, what gets counted. This module is that
 * discipline — not another transport.
 *
 * SHAPE (deliberation C1): module-global registry, not a
 * caller-embedded struct. SGI ids are a single system-wide
 * namespace — one GIC, sixteen ids — so two IPI registries
 * would double-claim ids. The GIC's own static handler table
 * is the precedent: system-wide resources get module-global
 * registries, CPU-local primitives get caller-embedded
 * structs.
 *
 * TRANSPORT (deliberation P2/D3): injected, never included.
 * The ops table's send slot matches kido_gic_send_sgi's
 * signature (cpu_mask, sgi_id) -> status exactly, so the
 * future Gate wiring binds it in one line. This module never
 * includes kido-gic.h and never touches MMIO — the fence
 * pattern holds, and the hosted proof needs no GIC bases.
 *
 * TYPES (deliberation P5): exactly two ship. RESCHED asks a
 * CPU to reschedule (the scheduler-tick vocabulary the Gate
 * wiring wants); PING asks nothing but proves presence (a
 * future proof can distinguish a live CPU from a silent one
 * by whether PINGs arrive). CALL, STOP, and TLB shootdown
 * are named futures with stated blockers (D1/D2), not bare
 * enum values claiming capabilities with no contract behind
 * them.
 *
 * IRQ LAW (deliberation P3): an IPI handler runs in interrupt
 * context, called from the future vector stub through
 * kido_gic_dispatch. It must be short, non-blocking, and
 * allocator-free. dispatch() owns counting even when no
 * handler is registered: a delivery with nobody listening is
 * a counted fact, not an error.
 *
 * MASK LAW (deliberation P4): the mask is uint32_t and is
 * validated against the 8-CPU census (KIDO_SMP_MAX_CPUS).
 * A zero mask routes nowhere and is EARLY_ENV; bits at or
 * above 8 are EARLY_ENV, never silently truncated. The mask
 * narrows to the transport's uint8_t only after validation.
 * (The GIC's uint8_t mask cannot even express the bit-8
 * refusal case; this layer validates first.)
 *
 * SEND CLAIMS HANDOFF, NEVER DELIVERY (deliberation C8): an
 * SGI is fire-and-forget by architecture — it pends on the
 * target, and the target's IRQ handler runs dispatch() later
 * or never. stats.sent counts handoffs to the transport;
 * stats.received counts dispatch() calls. The two counters
 * are kept separate so no caller can mistake one for the
 * other.
 *
 * DISPATCH LAW (deliberation C4): dispatch() maps sgi_id to
 * a type by subtracting the init-time base. An SGI outside
 * base..base+1 counts in stats.unknown and refuses
 * EARLY_ENV — the Gate wiring registers this dispatch as
 * the GIC handler for exactly the owned ids, so an
 * out-of-range arrival is a wiring bug made loud.
 *
 * NO NEW HEADER CODES (sched-D1 precedent): every failure is
 * KIDO_ERR_EARLY_ENV or a transport status propagated
 * unchanged.
 *
 * PROOF STATUS: WRITTEN, NOT ASSEMBLED, NEVER EXECUTED on
 * bare metal (toolchain absent, 19th data point). The hosted
 * proof drives the layer through a scripted transport and
 * direct dispatch() calls and pins every refusal. The SGI
 * actually arriving on another CPU awaits the Gate wiring
 * (bind transport, register dispatch for the owned ids with
 * the GIC, unmask) plus a QEMU virt -smp 2 run. No bootable
 * kernel is finalized without N8toriousAi; first boot is his to
 * witness.
 *
 * FUTURES (named, not built): STOP type (deliberation D1 —
 * parking is scheduler policy at a safe point, not an IRQ
 * handler action, since a spinning handler blocks its own
 * EOIR); CALL type (D2 — needs a cross-CPU function
 * mailbox/queue, a second invention behind the scheduler);
 * TLB shootdown (needs the MMU call-site wiring first);
 * acknowledged send (D4 — a reverse IPI plus a timeout
 * policy; rendezvous is the barrier's job, already built);
 * the first consumer (scheduler-tick RESCHED broadcast, or
 * a Gate wiring).
 *
 * Draft status: DRAFT (2026-10-29, session 36).
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror
 *        -DKIDO_HOSTED_TEST -DKIDO_IPI_SELFTEST
 *        kido-ipi.c -o ipi-selftest
 */
#ifndef KIDO_IPI_H
#define KIDO_IPI_H

#include "kido-boot.h"

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

/* Magic: init() stamps it; every API refuses an
 * uninitialized layer before touching handlers or stats.
 * Zeroed BSS reads magic 0, which refuses — an unbound
 * layer fails loud, never silently. */
#define KIDO_IPI_MAGIC 0x49504921u /* "IPI!" 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 precedent (its own cap, same value, same comment)
 * — so the leaf stays leaf. A rendezvous larger than the
 * machine's CPU table is a guess, not a design. */
#define KIDO_IPI_MAX_CPUS 8u

/* IPI types. Order is load-bearing: type N rides SGI
 * base + N, and dispatch() recovers the type by subtraction.
 * Adding a type widens the owned range; it never reorders. */
typedef enum kido_ipi_type {
    KIDO_IPI_RESCHED = 0, /* please reschedule (scheduler tick) */
    KIDO_IPI_PING   = 1, /* diagnostic presence, asks nothing */
    KIDO_IPI_TYPE_COUNT  /* = 2: the owned range is base..base+1 */
} kido_ipi_type_t;

/* Handler signature: called by dispatch() with the IPI type,
 * the source CPU index (the GIC IAR source-CPUID bits, as
 * passed by the wiring — NOT parsed here, see below), and
 * the caller's arg. Runs in interrupt context: keep it short,
 * no blocking, no allocator. The wiring passes source_cpu
 * through from the IAR value; this module never parses
 * MPIDR and never invents a source. */
typedef void (*kido_ipi_handler_t)(kido_ipi_type_t type,
                                   uint32_t source_cpu, void *arg);

/* Transport table: one slot, matching kido_gic_send_sgi's
 * signature exactly so the Gate wiring binds it directly.
 * send_sgi's cpu_mask is uint8_t (GIC SGI target list);
 * this layer validates the wider uint32_t mask first and
 * narrows only on success. A transport failure propagates
 * unchanged and counts nothing. */
typedef struct kido_ipi_ops {
    kido_status_t (*send_sgi)(uint8_t cpu_mask, uint8_t sgi_id);
} kido_ipi_ops_t;

/* Counters. sent[] counts handoffs to the transport;
 * received[] counts dispatch() calls; unknown counts
 * dispatch() calls for SGIs outside the owned range. Sent
 * and received are separate by law (C8): send() claims
 * handoff, never delivery. */
typedef struct kido_ipi_stats {
    uint32_t sent[KIDO_IPI_TYPE_COUNT];
    uint32_t received[KIDO_IPI_TYPE_COUNT];
    uint32_t unknown; /* out-of-range dispatch attempts */
} kido_ipi_stats_t;

/* Bind the transport and claim SGI ids base..base+1.
 * Refuses EARLY_ENV on NULL ops, a NULL send slot, or a
 * base that would push an owned id past SGI 15
 * (base > 14). Re-init is allowed and rebuilds the world:
 * handlers, args, and stats are cleared, the ops table is
 * rebound (deliberation C6). Init is a construction-time
 * call, not a concurrent one. */
kido_status_t kido_ipi_init(const kido_ipi_ops_t *ops,
                            uint8_t sgi_base);

/* The SGI id carrying a type (base + type). The Gate wiring
 * registers dispatch() with the GIC for exactly these ids —
 * it never recomputes the mapping. Refuses EARLY_ENV before
 * init, on a bad type, or on a NULL out-pointer. */
kido_status_t kido_ipi_sgi_id(kido_ipi_type_t type, uint8_t *out);

/* Register (or unregister, fn = NULL) a handler for one
 * type. Refuses EARLY_ENV before init or on a bad type.
 * Registering replaces any previous handler for the type. */
kido_status_t kido_ipi_register_handler(kido_ipi_type_t type,
                                        kido_ipi_handler_t fn,
                                        void *arg);

/* Signal the CPUs in cpu_mask (bit n = CPU n) with a type.
 * Refuses EARLY_ENV before init, on a bad type, on a zero
 * mask, or on mask bits at or above KIDO_IPI_MAX_CPUS.
 * On transport success, sent[type]++ and OK is returned;
 * on transport failure, the status propagates unchanged and
 * nothing is counted. Returns handoff, never delivery. */
kido_status_t kido_ipi_send(kido_ipi_type_t type, uint32_t cpu_mask);

/* Deliver one SGI: called by the wiring's GIC handler with
 * the SGI id and the source CPU index from the IAR value.
 * In-range: received[type]++, handler called if one is
 * registered, OK returned. Out-of-range: unknown++,
 * EARLY_ENV returned. Refuses EARLY_ENV before init. */
kido_status_t kido_ipi_dispatch(uint8_t sgi_id, uint32_t source_cpu);

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

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

#endif /* KIDO_IPI_H */
