/*
 * kido-sched.h — Kido task scheduler, public interface.
 *
 * The first module where Kido becomes multi-tasking: task control
 * blocks, a run queue, task creation with explicit stack carving,
 * voluntary yield, and a loud halt when the queue empties.
 *
 * HONESTY LAW (P1): this scheduler is COOPERATIVE round-robin.
 * Preemptive scheduling needs timer interrupts + a GIC driver; both
 * are loud stubs in the HAL. There is no fake preemption here — tasks
 * run until they call kido_sched_yield(). A task that never yields
 * starves the kernel; that is stated, not hidden.
 *
 * ALLOCATION LAW (P2/P3, integrated 2026-10-14; D2 closed 2026-10-16;
 * phase 2 2026-10-17): the
 * scheduler never allocates directly — TCBs are a static table (16 slots);
 * stacks come from kido-alloc, the Gate-approved first-fit allocator.
 * kido_sched_init initializes the allocator from kido-mem's region list
 * (hosted: the static arena as a synthetic region) before any task can be
 * created, carving the kernel-image ACTUAL bounds (kido-image: _image_start /
 * _image_end + relocation delta, boot stack included) out of the regions
 * first — no stack can ever overlap the image, wherever it really runs. Effective init order, established here in one
 * place: image bounds -> alloc init -> sched init -> task creation. DONE
 * slots keep their stacks on recycle (provably idle, never scheduled
 * again) — the reuse is accounted by the allocator, not hidden from it.
 * (History: this file was FENCED from kido-alloc by Gate order until the
 * first multitasking QEMU proof landed; the fence is fulfilled and the
 * integration below is the sequenced follow-through.)
 *
 * SMP LAW (C4): uniprocessor only. No locking exists because no second
 * CPU exists on the QEMU virt boot path. SMP is a future module.
 *
 * ARCH DISCIPLINE: ARM64 or hosted test-double only. The context
 * switch is ARM64 assembly (kido-sched-arm64.S); on hosted, a test
 * double records switches so the portable core is genuinely testable.
 *
 * Draft status: cooperative round-robin is REAL (policy, states,
 * allocator-backed stacks, accounting). Register-level switching is REAL
 * ARM64 asm, cross-assembled and EXECUTED under QEMU (multitasking proof
 * 2026-10-14: ABCABCABCABC interleaved, zero exceptions; re-proof
 * 2026-10-15 on the allocator-integrated tree). Image-bounds reservation
 * is REAL (kido-image, D2 closed 2026-10-16); its bare-metal execution is
 * queued for the next QEMU session. Preemption is a loud non-goal.
 * kido_sched_destroy (2026-10-21) is the teardown at rest — free of
 * every scheduler-owned stack, table back to EMPTY, allocator and its
 * image carve-out untouched.
 */
#ifndef KIDO_SCHED_H
#define KIDO_SCHED_H

#include "kido-boot.h"  /* kido_status_t, kido_hal_t, kido_halt */
#include "kido-alloc.h" /* task stacks are allocator clients (P2/P3) */

#if !defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
#error "kido-sched: ARM64 or hosted only. Define KIDO_HOSTED_TEST for the hosted draft harness."
#endif

/* Bounded table: the scheduler never allocates. */
#define KIDO_SCHED_MAX_TASKS 16u
/* Fixed per-task stack. 16 KiB keeps 16-byte AAPCS64 alignment trivial. */
#define KIDO_SCHED_STACK_SIZE (16u * 1024u)
#define KIDO_SCHED_NAME_LEN 16u

typedef enum kido_task_state {
    KIDO_TASK_EMPTY   = 0,  /* TCB slot free                         */
    KIDO_TASK_READY   = 1,  /* runnable, eligible for pick-next      */
    KIDO_TASK_RUNNING = 2,  /* currently executing                   */
    KIDO_TASK_DONE    = 3   /* entry returned; slot recyclable       */
} kido_task_state_t;

typedef void (*kido_task_fn)(void *arg);

/* Saved register context. ARM64: exactly what kido_ctx_switch in the
 * .S file saves/restores — x19-x28, FP(x29), LR(x30), SP. Caller-saved
 * regs are the compiler's problem across the yield call (AAPCS64). */
#if defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
typedef struct kido_task_ctx {
    uint64_t x[10];  /* x19..x28 */
    uint64_t fp;     /* x29 */
    uint64_t lr;     /* x30 */
    uint64_t sp;
} kido_task_ctx_t;
#else
/* Hosted: register switching is ARM64-only; the double keeps the slot
 * so TCB layout and offsets stay identical across builds. */
typedef struct kido_task_ctx {
    uint64_t opaque[13];
} kido_task_ctx_t;
#endif

typedef struct kido_task {
    uint32_t          id;
    char              name[KIDO_SCHED_NAME_LEN];
    kido_task_state_t state;
    kido_task_fn      entry;
    void             *arg;
    uint64_t          stack_base;  /* low address of the allocated stack */
    uint64_t          stack_size;  /* == KIDO_SCHED_STACK_SIZE        */
    kido_task_ctx_t   ctx;         /* crafted at create, switched at yield */
    uint64_t          ticks_run;   /* HAL-timer accounting (P5)       */
    uint64_t          switches;    /* times this task was switched to */
} kido_task_t;

/* ------------------------------------------------------------------ */
/* kido_sched_init: reset the table, initialize the allocator, set the
 * timer source. Allocator init comes first and is part of this call:
 * bare metal feeds kido-mem's region list to kido_alloc_init, hosted
 * feeds the static arena as a synthetic region; both reserve the
 * kernel-image bounds (kido-image, D2 closed 2026-10-16 — hosted
 * uninjected is a declared-vacuous 0,0, see kido-image.h). No usable
 * backing -> KIDO_ERR_NO_MEMORY (loud — stacks cannot exist without
 * a memory map). A failed image-bounds query on bare metal (mislinked
 * image) -> KIDO_ERR_EARLY_ENV, loud, allocator never initialized.
 * Allocator failure propagates unchanged. Re-init resets both the
 * table and the allocator; coherent because every TCB returns to
 * EMPTY (no live stack pointer survives the reset — see
 * deliberation C1). Image-bound injections are test-harness state and
 * survive re-init, like the arena itself.
 *  hal: timer_ticks() sampled at every switch for accounting; NULL
 *       hal -> KIDO_ERR_EARLY_ENV. NULL timer_ticks -> tolerated,
 *       accounting stays 0 (documented, not faked).
 * ------------------------------------------------------------------ */
kido_status_t kido_sched_init(const kido_hal_t *hal);

/* ------------------------------------------------------------------ */
/* kido_sched_create: allocate a 16 KiB stack from kido-alloc (16-     */
/* aligned payload), craft the first-run context, mark READY. Returns */
/* KIDO_OK + id, KIDO_ERR_NO_MEMORY when the table is full or the     */
/* allocator is exhausted (the slot is left EMPTY — never a half-     */
/* created task), KIDO_ERR_EARLY_ENV on NULL entry/id_out or when     */
/* sched_init was not called. DONE slots are recycled WITH their      */
/* stacks (a DONE task's stack is provably idle — never scheduled     */
/* again — so churn cannot grow the allocator without bound; the      */
/* reuse is visible in kido_alloc_stats).                             */
/* ------------------------------------------------------------------ */
kido_status_t kido_sched_create(kido_task_fn entry, void *arg,
                                const char *name, uint32_t *id_out);

/* ------------------------------------------------------------------ */
/* kido_sched_yield: voluntary yield. Saves the current task's        */
/* context, credits its timer accounting, picks the next READY task   */
/* round-robin, and switches. Returns in the yielding task when it is  */
/* re-scheduled. Calling with no current task is a no-op.             */
/* ------------------------------------------------------------------ */
void kido_sched_yield(void);

/* ------------------------------------------------------------------ */
/* kido_sched_run: enter the round-robin loop. NEVER RETURNS. When no */
/* READY task remains (zero tasks, or all DONE), halts LOUD. The halt */
/* code is KIDO_ERR_STUB_REACHED by documented mapping (D1) until the */
/* Gate approves a dedicated KIDO_ERR_NO_TASKS code.                  */
/* ------------------------------------------------------------------ */
void kido_sched_run(void);

/* ------------------------------------------------------------------ */
/* kido_sched_destroy: teardown at rest — the destroy API queued since */
/* session 6 (D1, specified 2026-10-21). Frees every scheduler-owned   */
/* task stack via kido_free (the first production caller of free),    */
/* returns all TCBs to EMPTY, and drops the scheduler back to          */
/* never-initialized (create fails loud until kido_sched_init runs     */
/* again; existing re-init law unchanged).                             */
/* REFUSAL LAW (P2): returns KIDO_ERR_EARLY_ENV — with the table and    */
/* the allocator untouched — when init was never called, when destroy  */
/* already ran, or when any task is READY or RUNNING. Teardown over a  */
/* live task would strand the cursor, the current-task pointer, and —  */
/* worst — the stack the running task is standing on; there is no      */
/* safe default, so refusal is the only honest posture. No new header  */
/* code: D1's KIDO_ERR_NO_TASKS stays N8toriousAi's call.                    */
/* OWNERSHIP LAW (P3): the allocator and its image carve-out are NOT   */
/* sched's property and are left alone — post-destroy kido_alloc_stats */
/* must show allocs == frees with allocated_bytes == 0 and the         */
/* carve-out intact. A failed kido_free aborts the teardown mid-table  */
/* (fail-stop, C2): the failing slot is kept and the allocator's       */
/* status propagates unchanged — partial teardown is caller-visible,   */
/* never misreported OK.                                               */
/* ------------------------------------------------------------------ */
kido_status_t kido_sched_destroy(void);

/* Observers (for tests, the future kido_main, and the task_start path). */
size_t kido_sched_task_count(void);          /* READY + RUNNING tasks */
const kido_task_t *kido_sched_task(uint32_t id);
kido_task_t *kido_sched_current_task(void);

/* Round-robin pick: the portable policy core, tested directly.       */
kido_task_t *kido_sched_pick_next(void);

/* Context switch. ARM64: real asm in kido-sched-arm64.S. Hosted: test
 * double that records the switch (register switching is ARM64-only). */
void kido_ctx_switch(kido_task_ctx_t *old_ctx, kido_task_ctx_t *new_ctx);

/* First-run trampoline target (ARM64 .S) / direct call (hosted test).
 * Runs entry(arg), marks the task DONE, then yields forever. NEVER
 * RETURNS to its caller. */
void kido_task_start(kido_task_fn entry, void *arg);

#endif /* KIDO_SCHED_H */
