/*
 * kido-sched-arm64.S — Kido ARM64 context switch.
 *
 * Why a separate .S file (P4): inline asm inside a compiled function
 * cannot reliably capture the CALLER's callee-saved registers — the
 * compiler may spill/reuse them in the prologue before our asm runs.
 * Here, on entry, x19-x30 hold exactly what kido_sched_yield()'s frame
 * had in them (per AAPCS64 the callee must preserve them, and this
 * function is entered normally via bl). We save them directly.
 *
 * kido_ctx_switch(old, new):
 *   x0 = old kido_task_ctx_t *, x1 = new kido_task_ctx_t *.
 *   Saves x19-x28, x29, x30, SP into old; restores from new; ret.
 *   The ret lands in the NEW task: for a yielded task, just after its
 *   bl kido_ctx_switch; for a first-run task, in kido_task_trampoline
 *   (its crafted LR) with x19 = entry, x20 = arg.
 *
 * Layout contract with kido-sched.h (kido_task_ctx_t):
 *   x[0..9] -> offsets 0..72, fp -> 80, lr -> 88, sp -> 96.
 */

    .text
    .align 2

    .global kido_ctx_switch
    .type kido_ctx_switch, %function
kido_ctx_switch:
    /* Save caller (yielding task) callee-saved state into old. */
    stp x19, x20, [x0, #0]
    stp x21, x22, [x0, #16]
    stp x23, x24, [x0, #32]
    stp x25, x26, [x0, #48]
    stp x27, x28, [x0, #64]
    stp x29, x30, [x0, #80]
    mov x2, sp
    str x2, [x0, #96]

    /* Restore the next task. */
    ldp x19, x20, [x1, #0]
    ldp x21, x22, [x1, #16]
    ldp x23, x24, [x1, #32]
    ldp x25, x26, [x1, #48]
    ldp x27, x28, [x1, #64]
    ldp x29, x30, [x1, #80]
    ldr x2, [x1, #96]
    mov sp, x2
    ret
    .size kido_ctx_switch, .-kido_ctx_switch

    .global kido_task_trampoline
    .type kido_task_trampoline, %function
/* First-run entry: crafted LR points here, x19 = entry fn, x20 = arg.
 * Moves them into the C calling convention and jumps to kido_task_start,
 * which never returns. */
kido_task_trampoline:
    mov x0, x19
    mov x1, x20
    bl kido_task_start
    /* Unreachable by contract. If we ever get here, halt LOUD rather
     * than falling off into whatever bytes follow. */
    mov w0, #6                  /* KIDO_ERR_STUB_REACHED */
    bl kido_halt
    .size kido_task_trampoline, .-kido_task_trampoline
