/*
 * kido-mbox.c — Kido VideoCore mailbox driver (BCM2711, Pi 4).
 *
 * Property-tags channel 8 only. One exchange shape, validated five
 * ways: mail echo, response-code success bit, tag echo, response
 * length, clock echo + nonzero rate. See kido-mbox.h for the
 * protocol sources, the honesty law, and the declared HAL seam.
 *
 * WHAT IS REAL vs DOUBLE: the exchange logic below is the real
 * logic — the hosted build runs the SAME function against a
 * scripted VideoCore double (scratch registers + a scenario table)
 * instead of MMIO. The double fabricates the firmware's in-place
 * buffer write, exactly as the firmware does on hardware. The bare-
 * metal path is WRITTEN, NOT EXECUTED (no cross toolchain this
 * session, 8th data point; no Pi4 hardware run — N8toriousAi's witness).
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST
 *        -DKIDO_MBOX_SELFTEST kido-mbox.c -o mbox-selftest
 */

#include "kido-mbox.h"

/* ------------------------------------------------------------------ */
/* Registers (ARM-physical, Low Peripheral Mode).                     */
/* ------------------------------------------------------------------ */
#define KIDO_MBOX_BASE        0xFE00B880u
#define KIDO_MBOX_READ_OFF    0x00u
#define KIDO_MBOX_STATUS0_OFF 0x18u
#define KIDO_MBOX_WRITE1_OFF  0x20u
#define KIDO_MBOX_STATUS1_OFF 0x38u
#define KIDO_MBOX_EMPTY       (1u << 30)
#define KIDO_MBOX_FULL        (1u << 31)
#define KIDO_MBOX_CH_PROP     8u

/* Property-tags message: get clock rate. */
#define KIDO_MBOX_TAG_GET_CLOCK_RATE 0x00030002u
#define KIDO_MBOX_RESP_SUCCESS      0x80000000u

/* One spin budget for every poll (write-side FULL, read-side EMPTY,
 * stale-mail discards share it on the read side). A loop count, not
 * time — no timer dependency by design (deliberation P2/P5). */
#define KIDO_MBOX_POLL_MAX (1u << 20)

/* The single-flight buffer: 8 words, 16-byte aligned (load-bearing:
 * the mail carries only the upper 28 address bits). Static BSS, so
 * it exists before any allocator and survives MMU-off boot. */
static uint32_t kido_mbox_buf[8] __attribute__((aligned(16)));

#if defined(KIDO_HOSTED_TEST)

/* ------------------------------------------------------------------ */
/* Hosted VideoCore double. Scratch registers + a scripted scenario.  */
/* On WRITE1 the double decodes the caller's buffer, fabricates the   */
/* firmware's in-place response, and arms the READ echo — the        */
/* firmware's real behavior, scripted. Scenarios let the self-test    */
/* pin every loud failure path without hardware.                      */
/* ------------------------------------------------------------------ */
#include <stdio.h>

enum kido_mbox_scenario {
    KIDO_MBOX_SCEN_OK = 0,      /* answer with the scripted rate      */
    KIDO_MBOX_SCEN_STALE_FIRST, /* one stale mail, then the answer    */
    KIDO_MBOX_SCEN_WRONG_ECHO,  /* READ value != written mail         */
    KIDO_MBOX_SCEN_NO_REPLY,    /* EMPTY never clears (timeout)       */
    KIDO_MBOX_SCEN_BAD_CODE,    /* response code without success bit  */
    KIDO_MBOX_SCEN_ZERO_RATE,   /* firmware answers rate 0            */
    KIDO_MBOX_SCEN_WRONG_TAG,   /* tag echo corrupted                 */
    KIDO_MBOX_SCEN_WRONG_CLOCK, /* clock echo corrupted               */
    KIDO_MBOX_SCEN_SHORT_LEN,   /* response length 4, not 8           */
    KIDO_MBOX_SCEN_FULL_STUCK   /* STATUS1 FULL never clears         */
};

static uint32_t kido_dbl_status0 = KIDO_MBOX_EMPTY; /* VC->ARM empty  */
static uint32_t kido_dbl_status1 = 0u;             /* ARM->VC not full */
static uint32_t kido_dbl_read = 0u;
static uint32_t kido_dbl_last_write = 0u;
static unsigned kido_dbl_scenario = KIDO_MBOX_SCEN_OK;
static uint32_t kido_dbl_script_rate = 500000000u;
static int      kido_dbl_stale_pending = 0;

static void kido_mbox_test_set_scenario(unsigned scen, uint32_t rate)
{
    kido_dbl_scenario = scen;
    kido_dbl_script_rate = rate;
    kido_dbl_stale_pending = (scen == KIDO_MBOX_SCEN_STALE_FIRST) ? 1 : 0;
    kido_dbl_status0 = KIDO_MBOX_EMPTY;
    kido_dbl_status1 = (scen == KIDO_MBOX_SCEN_FULL_STUCK)
        ? KIDO_MBOX_FULL : 0u;
    kido_dbl_read = 0u;
    kido_dbl_last_write = 0u;
}

static uint32_t kido_mbox_rd(uint32_t off)
{
    if (off == KIDO_MBOX_READ_OFF)
        return kido_dbl_read;
    if (off == KIDO_MBOX_STATUS0_OFF)
        return kido_dbl_status0;
    if (off == KIDO_MBOX_STATUS1_OFF)
        return kido_dbl_status1;
    return 0u;
}

/* The scripted firmware: runs at WRITE1 time, like the real thing.
 * The double writes the KNOWN single-flight buffer directly: a hosted
 * (PIE) address is not a firmware bus address, so decoding the mail's
 * truncated 28 address bits back into a pointer would be fiction.
 * On hardware the firmware does the decode; here the double knows the
 * one buffer that exists. The mail value itself is still echoed and
 * still checked by the caller. */
static void kido_mbox_dbl_answer(uint32_t mail)
{
    uint32_t *buf = kido_mbox_buf;
    uint32_t clock_id;

    kido_dbl_last_write = mail;
    if (kido_dbl_scenario == KIDO_MBOX_SCEN_NO_REPLY ||
        kido_dbl_scenario == KIDO_MBOX_SCEN_FULL_STUCK) {
        return; /* EMPTY stays set: the caller must time out, loud. */
    }
    clock_id = buf[5];
    if (kido_dbl_scenario == KIDO_MBOX_SCEN_STALE_FIRST &&
        kido_dbl_stale_pending) {
        /* First read delivers stale mail; the real answer arms after
         * the caller discards it. Model that by arming the stale word
         * now and deferring the true answer to the next read. */
        kido_dbl_read = 0xDEADBEE0u; /* wrong channel/value: stale */
        kido_dbl_status0 = 0u;       /* not empty: a word waits */
        kido_dbl_stale_pending = 0;
        return;
    }
    buf[1] = (kido_dbl_scenario == KIDO_MBOX_SCEN_BAD_CODE)
        ? 0u : KIDO_MBOX_RESP_SUCCESS;
    buf[2] = (kido_dbl_scenario == KIDO_MBOX_SCEN_WRONG_TAG)
        ? 0x00030006u : KIDO_MBOX_TAG_GET_CLOCK_RATE;
    buf[4] = (kido_dbl_scenario == KIDO_MBOX_SCEN_SHORT_LEN)
        ? 4u : 8u;
    buf[5] = (kido_dbl_scenario == KIDO_MBOX_SCEN_WRONG_CLOCK)
        ? (clock_id + 1u) : clock_id;
    buf[6] = (kido_dbl_scenario == KIDO_MBOX_SCEN_ZERO_RATE)
        ? 0u : kido_dbl_script_rate;
    kido_dbl_read = (kido_dbl_scenario == KIDO_MBOX_SCEN_WRONG_ECHO)
        ? (mail ^ 0x10u) : mail;
    kido_dbl_status0 = 0u; /* a word waits */
}

/* Hosted read: after a stale discard, arm the true answer. */
static uint32_t kido_mbox_rd_consume(uint32_t off)
{
    uint32_t v = kido_mbox_rd(off);
    if (off == KIDO_MBOX_READ_OFF && kido_dbl_status0 == 0u) {
        if (kido_dbl_scenario == KIDO_MBOX_SCEN_STALE_FIRST &&
            v == 0xDEADBEE0u) {
            /* Caller discarded the stale word; now arm the answer. */
            uint32_t mail = kido_dbl_last_write;
            uint32_t *buf = kido_mbox_buf; /* single-flight buffer */
            buf[1] = KIDO_MBOX_RESP_SUCCESS;
            buf[2] = KIDO_MBOX_TAG_GET_CLOCK_RATE;
            buf[4] = 8u;
            buf[6] = kido_dbl_script_rate;
            kido_dbl_read = mail;
            kido_dbl_status0 = 0u;
        } else {
            kido_dbl_status0 = KIDO_MBOX_EMPTY; /* word consumed */
        }
    }
    return v;
}

static void kido_mbox_wr(uint32_t off, uint32_t val)
{
    if (off == KIDO_MBOX_WRITE1_OFF)
        kido_mbox_dbl_answer(val);
}

#else /* bare metal */

/* Real MMIO. Volatile: the compiler must not reorder or elide the
 * status polls. */
static uint32_t kido_mbox_rd(uint32_t off)
{
    return *(volatile uint32_t *)(uintptr_t)(KIDO_MBOX_BASE + off);
}

static uint32_t kido_mbox_rd_consume(uint32_t off)
{
    return kido_mbox_rd(off); /* a READ consumes the word in hardware */
}

static void kido_mbox_wr(uint32_t off, uint32_t val)
{
    *(volatile uint32_t *)(uintptr_t)(KIDO_MBOX_BASE + off) = val;
}

#endif /* KIDO_HOSTED_TEST */

/* ------------------------------------------------------------------ */
/* The exchange. Returns KIDO_OK only when all five validations pass; */
/* *hz is written last, so a failure never leaks a partial rate.       */
/* ------------------------------------------------------------------ */
kido_status_t kido_mbox_clock_rate(uint32_t clock_id, uint32_t *hz)
{
    uint32_t mail;
    uint32_t polls;
    uint32_t word;
    uintptr_t addr;

    if (hz == NULL)
        return KIDO_ERR_EARLY_ENV;

    addr = (uintptr_t)&kido_mbox_buf[0];
    /* The mail carries only 28 address bits + the channel nibble:
     * the buffer must be 16-byte aligned and below 4 GiB. Hosted
     * addresses are not bus addresses (PIE binaries live high), so
     * this guard is bare-metal-only; the hosted double writes the
     * known buffer directly (see kido_mbox_dbl_answer). */
#if !defined(KIDO_HOSTED_TEST)
    if ((addr & 0xFu) != 0u || addr > 0xFFFFFFF0u)
        return KIDO_ERR_EARLY_ENV;
#endif

    /* Build the tag buffer: size, request code, tag, value-buffer
     * size, request length, clock id, rate slot, end tag. */
    kido_mbox_buf[0] = 32u;
    kido_mbox_buf[1] = 0u; /* request */
    kido_mbox_buf[2] = KIDO_MBOX_TAG_GET_CLOCK_RATE;
    kido_mbox_buf[3] = 8u; /* value buffer: id + rate */
    kido_mbox_buf[4] = 4u; /* request length: id only */
    kido_mbox_buf[5] = clock_id;
    kido_mbox_buf[6] = 0u;
    kido_mbox_buf[7] = 0u; /* end tag */

    mail = (uint32_t)(addr & ~0xFu) | KIDO_MBOX_CH_PROP;

    /* Wait until the ARM->VC box is not full, then write the mail. */
    polls = 0u;
    while ((kido_mbox_rd(KIDO_MBOX_STATUS1_OFF) & KIDO_MBOX_FULL) != 0u) {
        if (++polls >= KIDO_MBOX_POLL_MAX)
            return KIDO_ERR_EARLY_ENV; /* firmware wedged: loud */
        /* spin: bounded by polls, never infinite (deliberation P2) */
    }
    kido_mbox_wr(KIDO_MBOX_WRITE1_OFF, mail);

    /* Read until OUR mail echoes back; discard stale words. */
    polls = 0u;
    for (;;) {
        if ((kido_mbox_rd(KIDO_MBOX_STATUS0_OFF) & KIDO_MBOX_EMPTY) == 0u) {
            word = kido_mbox_rd_consume(KIDO_MBOX_READ_OFF);
            if (word == mail)
                break; /* our reply is in the buffer */
            /* stale mail from another exchange: discard, keep polling */
        }
        if (++polls >= KIDO_MBOX_POLL_MAX)
            return KIDO_ERR_EARLY_ENV; /* no reply: loud, not a hang */
    }

    /* Five validations, in the order the firmware's contract implies. */
    if ((kido_mbox_buf[1] & KIDO_MBOX_RESP_SUCCESS) == 0u)
        return KIDO_ERR_EARLY_ENV; /* firmware refused the request */
    if (kido_mbox_buf[2] != KIDO_MBOX_TAG_GET_CLOCK_RATE)
        return KIDO_ERR_EARLY_ENV; /* wrong tag echoed */
    if (kido_mbox_buf[4] != 8u)
        return KIDO_ERR_EARLY_ENV; /* malformed response length */
    if (kido_mbox_buf[5] != clock_id)
        return KIDO_ERR_EARLY_ENV; /* wrong clock echoed */
    if (kido_mbox_buf[6] == 0u)
        return KIDO_ERR_EARLY_ENV; /* unknown clock (or off): loud */

    *hz = kido_mbox_buf[6];
    return KIDO_OK;
}

kido_status_t kido_mbox_vpu_hz(uint32_t *hz)
{
    return kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, hz);
}

/* ------------------------------------------------------------------ */
/* Self-test: pins the exchange against the scripted VideoCore.       */
/* ------------------------------------------------------------------ */
#ifdef KIDO_MBOX_SELFTEST
#ifndef KIDO_HOSTED_TEST
#error "KIDO_MBOX_SELFTEST needs KIDO_HOSTED_TEST (it runs the hosted double)."
#endif

int main(void)
{
    int failures = 0;
    uint32_t hz = 0xDEADBEEFu;
    uint32_t mail_seen;

#define KIDO_MBOX_CHECK(cond, msg) do { \
    if (!(cond)) { printf("[FAIL] " msg "\n"); failures++; } \
} while (0)

    /* 1. NULL guard: loud, no write. */
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, NULL) ==
                    KIDO_ERR_EARLY_ENV, "NULL hz not refused");

    /* 2. Happy path, VPU: scripted 500 MHz comes back exact. */
    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_OK, 500000000u);
    hz = 0u;
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, &hz) ==
                    KIDO_OK, "VPU query failed");
    KIDO_MBOX_CHECK(hz == 500000000u, "VPU rate not 500000000");

    /* 3. Generic path: any clock id works, not just VPU. */
    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_OK, 1500000000u);
    hz = 0u;
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_ARM, &hz) ==
                    KIDO_OK, "ARM query failed");
    KIDO_MBOX_CHECK(hz == 1500000000u, "ARM rate not 1500000000");

    /* 4. Mail encoding: (buffer & ~0xF) | channel 8. */
    mail_seen = kido_dbl_last_write;
    KIDO_MBOX_CHECK((mail_seen & 0xFu) == KIDO_MBOX_CH_PROP,
                    "mail channel nibble not 8");
    KIDO_MBOX_CHECK((mail_seen & ~0xFu) ==
                    (uint32_t)((uintptr_t)&kido_mbox_buf[0] & ~0xFu),
                    "mail address not the buffer address");

    /* 5. Buffer shape after a good call: size, tag, length. */
    KIDO_MBOX_CHECK(kido_mbox_buf[0] == 32u, "buffer size word wrong");
    KIDO_MBOX_CHECK(kido_mbox_buf[2] == KIDO_MBOX_TAG_GET_CLOCK_RATE,
                    "buffer tag word wrong");
    KIDO_MBOX_CHECK(kido_mbox_buf[4] == 8u, "buffer length word wrong");

    /* 6. Buffer alignment: the load-bearing invariant. */
    KIDO_MBOX_CHECK(((uintptr_t)&kido_mbox_buf[0] & 0xFu) == 0u,
                    "mbox buffer not 16-byte aligned");

    /* 7. VPU convenience wrapper: same query, same answer. */
    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_OK, 500000000u);
    hz = 0u;
    KIDO_MBOX_CHECK(kido_mbox_vpu_hz(&hz) == KIDO_OK,
                    "vpu_hz wrapper failed");
    KIDO_MBOX_CHECK(hz == 500000000u, "vpu_hz rate wrong");

    /* 8. Stale mail first: discarded, then the true answer lands. */
    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_STALE_FIRST, 500000000u);
    hz = 0u;
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, &hz) ==
                    KIDO_OK, "stale-first exchange failed");
    KIDO_MBOX_CHECK(hz == 500000000u, "stale-first rate wrong");

    /* 9-15. Every loud failure: *hz untouched, status EARLY_ENV. */
    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_WRONG_ECHO, 500000000u);
    hz = 0xDEADBEEFu;
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, &hz) ==
                    KIDO_ERR_EARLY_ENV, "wrong echo not refused");
    KIDO_MBOX_CHECK(hz == 0xDEADBEEFu, "wrong echo leaked a rate");

    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_NO_REPLY, 500000000u);
    hz = 0xDEADBEEFu;
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, &hz) ==
                    KIDO_ERR_EARLY_ENV, "no-reply timeout not loud");
    KIDO_MBOX_CHECK(hz == 0xDEADBEEFu, "timeout leaked a rate");

    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_BAD_CODE, 500000000u);
    hz = 0xDEADBEEFu;
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, &hz) ==
                    KIDO_ERR_EARLY_ENV, "bad response code not refused");
    KIDO_MBOX_CHECK(hz == 0xDEADBEEFu, "bad code leaked a rate");

    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_ZERO_RATE, 0u);
    hz = 0xDEADBEEFu;
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, &hz) ==
                    KIDO_ERR_EARLY_ENV, "zero rate not refused");
    KIDO_MBOX_CHECK(hz == 0xDEADBEEFu, "zero rate leaked");

    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_WRONG_TAG, 500000000u);
    hz = 0xDEADBEEFu;
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, &hz) ==
                    KIDO_ERR_EARLY_ENV, "wrong tag not refused");
    KIDO_MBOX_CHECK(hz == 0xDEADBEEFu, "wrong tag leaked a rate");

    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_WRONG_CLOCK, 500000000u);
    hz = 0xDEADBEEFu;
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, &hz) ==
                    KIDO_ERR_EARLY_ENV, "wrong clock not refused");
    KIDO_MBOX_CHECK(hz == 0xDEADBEEFu, "wrong clock leaked a rate");

    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_SHORT_LEN, 500000000u);
    hz = 0xDEADBEEFu;
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, &hz) ==
                    KIDO_ERR_EARLY_ENV, "short length not refused");
    KIDO_MBOX_CHECK(hz == 0xDEADBEEFu, "short length leaked a rate");

    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_FULL_STUCK, 500000000u);
    hz = 0xDEADBEEFu;
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, &hz) ==
                    KIDO_ERR_EARLY_ENV, "FULL-stuck write not loud");
    KIDO_MBOX_CHECK(hz == 0xDEADBEEFu, "FULL-stuck leaked a rate");

    /* 16. Recovery: a good call after failures works (no stuck state). */
    kido_mbox_test_set_scenario(KIDO_MBOX_SCEN_OK, 500000000u);
    hz = 0u;
    KIDO_MBOX_CHECK(kido_mbox_clock_rate(KIDO_MBOX_CLOCK_VPU, &hz) ==
                    KIDO_OK, "recovery call failed");
    KIDO_MBOX_CHECK(hz == 500000000u, "recovery rate wrong");

    if (failures == 0)
        printf("kido-mbox self-test: ALL PASS\n");
    else
        printf("kido-mbox self-test: %d FAILURES\n", failures);
    return failures != 0;
#undef KIDO_MBOX_CHECK
}
#endif /* KIDO_MBOX_SELFTEST */
