/*
 * kido-timer.c — Kido ARM Generic Timer driver (EL1 physical timer).
 *
 * See kido-timer.h for the register map, the honesty law, and the
 * declared futures. This file is the real logic: the hosted build
 * runs the SAME functions against a scripted timer double
 * (frequency, advancing count, CTL, CVAL) instead of system
 * registers. The bare-metal path is WRITTEN, NOT ASSEMBLED,
 * NEVER EXECUTED (toolchain absent, 12th data point — see the
 * deliberation record); the QEMU PPI-30 proof is queued.
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST
 *        -DKIDO_TIMER_SELFTEST kido-timer.c -o timer-selftest
 */

#include "kido-timer.h"

#ifdef KIDO_TIMER_SELFTEST
#ifndef KIDO_HOSTED_TEST
#error "KIDO_TIMER_SELFTEST needs KIDO_HOSTED_TEST."
#endif
#endif

/* CTL bits (CNTP_CTL_EL0): ENABLE 0, IMASK 1, ISTATUS 2 (RO). */
#define KIDO_TIMER_CTL_ENABLE  0x1u
#define KIDO_TIMER_CTL_IMASK   0x2u
#define KIDO_TIMER_CTL_ISTATUS 0x4u

/* Driver state. Static BSS: exists before any allocator. */
static uint32_t kido_timer_hz_state = 0u;
static int      kido_timer_ready = 0;

#if defined(KIDO_HOSTED_TEST)

/* ------------------------------------------------------------------ */
/* Hosted timer double. The registers as scripted state: frequency, */
/* a count the test advances by hand, CTL writable bits, and CVAL. */
/* ISTATUS is COMPUTED on read (count >= CVAL), never stored — */
/* the double cannot be wedged into reporting a stale condition. */
/* CTL writes keep ENABLE/IMASK only; an ISTATUS write is */
/* ignored, as on hardware (read-only bit). */
/* ------------------------------------------------------------------ */
#include <stdio.h>

static uint32_t kido_dbl_freq = 0u;
static uint64_t kido_dbl_count = 0u;
static uint32_t kido_dbl_ctl_w = 0u;
static uint64_t kido_dbl_cval = 0u;

static uint32_t kido_rd_freq(void)
{
    return kido_dbl_freq;
}

static uint64_t kido_rd_count(void)
{
    return kido_dbl_count;
}

static uint32_t kido_rd_ctl(void)
{
    uint32_t ctl = kido_dbl_ctl_w;
    if (kido_dbl_count >= kido_dbl_cval)
        ctl |= KIDO_TIMER_CTL_ISTATUS;
    return ctl;
}

static void kido_wr_ctl(uint32_t v)
{
    kido_dbl_ctl_w = v & (KIDO_TIMER_CTL_ENABLE | KIDO_TIMER_CTL_IMASK);
}

static uint64_t kido_rd_cval(void)
{
    return kido_dbl_cval;
}

static void kido_wr_cval(uint64_t v)
{
    kido_dbl_cval = v;
}

#else /* bare metal: real system registers, EL1 physical timer. */

static inline uint32_t kido_rd_freq(void)
{
    uint32_t v;
    __asm__ volatile("mrs %0, cntfrq_el0" : "=r" (v));
    return v;
}

static inline uint64_t kido_rd_count(void)
{
    uint64_t v;
    __asm__ volatile("mrs %0, cntpct_el0" : "=r" (v));
    return v;
}

static inline uint32_t kido_rd_ctl(void)
{
    uint32_t v;
    __asm__ volatile("mrs %0, cntp_ctl_el0" : "=r" (v));
    return v;
}

static inline void kido_wr_ctl(uint32_t v)
{
    __asm__ volatile("msr cntp_ctl_el0, %0" :: "r" (v));
}

static inline uint64_t kido_rd_cval(void)
{
    uint64_t v;
    __asm__ volatile("mrs %0, cntp_cval_el0" : "=r" (v));
    return v;
}

static inline void kido_wr_cval(uint64_t v)
{
    __asm__ volatile("msr cntp_cval_el0, %0" :: "r" (v));
}

#endif /* KIDO_HOSTED_TEST */

kido_status_t kido_timer_init(void)
{
    uint32_t freq;

    /* Disarm first: no surprise IRQ from a stale compare, even
     * on the failure path below (a zero frequency leaves the
     * driver unready AND the timer silent). */
    kido_wr_ctl(0u);
    freq = kido_rd_freq();
    if (freq == 0u) {
        kido_timer_ready = 0;
        kido_timer_hz_state = 0u;
        return KIDO_ERR_NO_TIMER;
    }
    kido_timer_hz_state = freq;
    kido_timer_ready = 1;
    return KIDO_OK;
}

kido_status_t kido_timer_hz(uint32_t *out)
{
    if (out == NULL)
        return KIDO_ERR_EARLY_ENV;
    if (!kido_timer_ready)
        return KIDO_ERR_EARLY_ENV;
    *out = kido_timer_hz_state;
    return KIDO_OK;
}

kido_status_t kido_timer_now(uint64_t *out)
{
    if (out == NULL)
        return KIDO_ERR_EARLY_ENV;
    if (!kido_timer_ready)
        return KIDO_ERR_EARLY_ENV;
    *out = kido_rd_count();
    return KIDO_OK;
}

kido_status_t kido_timer_arm_ticks(uint64_t ticks)
{
    uint64_t now, target;

    if (!kido_timer_ready)
        return KIDO_ERR_EARLY_ENV;
    if (ticks == 0u)
        return KIDO_ERR_EARLY_ENV;
    now = kido_rd_count();
    target = now + ticks;
    if (target < now)
        return KIDO_ERR_EARLY_ENV;
    /* CVAL first, then ENABLE: enabling against a stale CVAL
     * could fire immediately on a compare that is already met. */
    kido_wr_cval(target);
    kido_wr_ctl(KIDO_TIMER_CTL_ENABLE);
    return KIDO_OK;
}

kido_status_t kido_timer_arm_us(uint64_t us)
{
    uint64_t ticks;

    if (!kido_timer_ready)
        return KIDO_ERR_EARLY_ENV;
    if (us > UINT64_MAX / kido_timer_hz_state)
        return KIDO_ERR_EARLY_ENV;
    ticks = (us * kido_timer_hz_state) / 1000000u;
    if (ticks == 0u)
        return KIDO_ERR_EARLY_ENV;
    return kido_timer_arm_ticks(ticks);
}

kido_status_t kido_timer_disarm(void)
{
    if (!kido_timer_ready)
        return KIDO_ERR_EARLY_ENV;
    kido_wr_ctl(0u);
    return KIDO_OK;
}

kido_status_t kido_timer_mask(void)
{
    if (!kido_timer_ready)
        return KIDO_ERR_EARLY_ENV;
    kido_wr_ctl(kido_rd_ctl() | KIDO_TIMER_CTL_IMASK);
    return KIDO_OK;
}

kido_status_t kido_timer_unmask(void)
{
    if (!kido_timer_ready)
        return KIDO_ERR_EARLY_ENV;
    kido_wr_ctl(kido_rd_ctl() & ~KIDO_TIMER_CTL_IMASK);
    return KIDO_OK;
}

kido_status_t kido_timer_pending(uint8_t *out)
{
    uint32_t ctl;

    if (out == NULL)
        return KIDO_ERR_EARLY_ENV;
    if (!kido_timer_ready)
        return KIDO_ERR_EARLY_ENV;
    /* The SIGNAL, not the raw bit: condition AND enabled AND
     * not masked. kido_rd_ctl() carries ISTATUS on the hosted
     * double and reads it from hardware on bare metal; the
     * three-term AND is identical on both. */
    ctl = kido_rd_ctl();
    *out = ((ctl & KIDO_TIMER_CTL_ENABLE) != 0u &&
            (ctl & KIDO_TIMER_CTL_IMASK) == 0u &&
            (ctl & KIDO_TIMER_CTL_ISTATUS) != 0u) ? 1u : 0u;
    return KIDO_OK;
}

#ifdef KIDO_TIMER_SELFTEST

/* Hosted-double setters (test only). */
void kido_timer_test_set_freq(uint32_t hz)
{
    kido_dbl_freq = hz;
}

void kido_timer_test_set_count(uint64_t count)
{
    kido_dbl_count = count;
}

void kido_timer_test_get_regs(uint32_t *ctl, uint64_t *cval)
{
    if (ctl != NULL)
        *ctl = kido_rd_ctl();
    if (cval != NULL)
        *cval = kido_rd_cval();
}

static unsigned kido_timer_checks = 0u;
static unsigned kido_timer_failures = 0u;

#define TIMER_CHECK(cond) do { \
    kido_timer_checks++; \
    if (!(cond)) { \
        kido_timer_failures++; \
        printf("[FAIL] line %d: %s\n", __LINE__, #cond); \
    } \
} while (0)

int kido_timer_selftest_main(void)
{
    uint32_t hz = 0u, ctl = 0u;
    uint64_t now = 0u, cval = 0u;
    uint8_t pend = 0u;

    /* §1: pre-init guards — every call refuses. */
    TIMER_CHECK(kido_timer_hz(&hz) == KIDO_ERR_EARLY_ENV);
    TIMER_CHECK(kido_timer_now(&now) == KIDO_ERR_EARLY_ENV);
    TIMER_CHECK(kido_timer_arm_ticks(100u) == KIDO_ERR_EARLY_ENV);
    TIMER_CHECK(kido_timer_arm_us(100u) == KIDO_ERR_EARLY_ENV);
    TIMER_CHECK(kido_timer_disarm() == KIDO_ERR_EARLY_ENV);
    TIMER_CHECK(kido_timer_mask() == KIDO_ERR_EARLY_ENV);
    TIMER_CHECK(kido_timer_unmask() == KIDO_ERR_EARLY_ENV);
    TIMER_CHECK(kido_timer_pending(&pend) == KIDO_ERR_EARLY_ENV);

    /* §2: zero frequency is NO_TIMER, not a default. */
    kido_timer_test_set_freq(0u);
    TIMER_CHECK(kido_timer_init() == KIDO_ERR_NO_TIMER);
    TIMER_CHECK(kido_timer_hz(&hz) == KIDO_ERR_EARLY_ENV);

    /* §3: init at the QEMU virt frequency; disarmed, silent. */
    kido_timer_test_set_freq(62500000u);
    TIMER_CHECK(kido_timer_init() == KIDO_OK);
    TIMER_CHECK(kido_timer_hz(&hz) == KIDO_OK && hz == 62500000u);
    kido_timer_test_get_regs(&ctl, NULL);
    /* ISTATUS is masked out: with CVAL still 0 the condition
     * bit reads set, but no ENABLE/IMASK bit may be set. */
    TIMER_CHECK((ctl & (KIDO_TIMER_CTL_ENABLE | KIDO_TIMER_CTL_IMASK)) == 0u);

    /* §4: the count is what the double says it is. */
    kido_timer_test_set_count(1000u);
    TIMER_CHECK(kido_timer_now(&now) == KIDO_OK && now == 1000u);

    /* §5: arm_ticks — exact CVAL, ENABLE set, pending edges. */
    TIMER_CHECK(kido_timer_arm_ticks(500u) == KIDO_OK);
    kido_timer_test_get_regs(&ctl, &cval);
    TIMER_CHECK(cval == 1500u);
    TIMER_CHECK((ctl & KIDO_TIMER_CTL_ENABLE) != 0u);
    TIMER_CHECK((ctl & KIDO_TIMER_CTL_IMASK) == 0u);
    TIMER_CHECK(kido_timer_pending(&pend) == KIDO_OK && pend == 0u);
    kido_timer_test_set_count(1499u);
    TIMER_CHECK(kido_timer_pending(&pend) == KIDO_OK && pend == 0u);
    kido_timer_test_set_count(1500u);
    TIMER_CHECK(kido_timer_pending(&pend) == KIDO_OK && pend == 1u);
    kido_timer_test_set_count(2000u);
    TIMER_CHECK(kido_timer_pending(&pend) == KIDO_OK && pend == 1u);

    /* §6: zero and wrap arms refuse; CVAL untouched. */
    TIMER_CHECK(kido_timer_arm_ticks(0u) == KIDO_ERR_EARLY_ENV);
    kido_timer_test_get_regs(NULL, &cval);
    TIMER_CHECK(cval == 1500u);
    kido_timer_test_set_count(UINT64_MAX - 10u);
    TIMER_CHECK(kido_timer_arm_ticks(20u) == KIDO_ERR_EARLY_ENV);
    kido_timer_test_get_regs(NULL, &cval);
    TIMER_CHECK(cval == 1500u);

    /* §7: mask suppresses, unmask releases, CVAL survives. */
    kido_timer_test_set_count(2000u);
    TIMER_CHECK(kido_timer_mask() == KIDO_OK);
    kido_timer_test_get_regs(&ctl, NULL);
    TIMER_CHECK((ctl & KIDO_TIMER_CTL_IMASK) != 0u);
    TIMER_CHECK((ctl & KIDO_TIMER_CTL_ENABLE) != 0u);
    TIMER_CHECK(kido_timer_pending(&pend) == KIDO_OK && pend == 0u);
    TIMER_CHECK(kido_timer_unmask() == KIDO_OK);
    TIMER_CHECK(kido_timer_pending(&pend) == KIDO_OK && pend == 1u);

    /* §8: disarm silences; disarm again is fine. */
    TIMER_CHECK(kido_timer_disarm() == KIDO_OK);
    kido_timer_test_get_regs(&ctl, NULL);
    TIMER_CHECK((ctl & (KIDO_TIMER_CTL_ENABLE | KIDO_TIMER_CTL_IMASK)) == 0u);
    TIMER_CHECK(kido_timer_pending(&pend) == KIDO_OK && pend == 0u);
    TIMER_CHECK(kido_timer_disarm() == KIDO_OK);

    /* §9: arm_us conversions at 62.5 MHz, plus refusals. */
    kido_timer_test_set_count(0u);
    TIMER_CHECK(kido_timer_arm_us(1000u) == KIDO_OK);
    kido_timer_test_get_regs(NULL, &cval);
    TIMER_CHECK(cval == 62500u);
    kido_timer_test_set_count(0u);
    TIMER_CHECK(kido_timer_arm_us(1u) == KIDO_OK);
    kido_timer_test_get_regs(NULL, &cval);
    TIMER_CHECK(cval == 62u);
    TIMER_CHECK(kido_timer_arm_us(0u) == KIDO_ERR_EARLY_ENV);
    TIMER_CHECK(kido_timer_arm_us(UINT64_MAX) == KIDO_ERR_EARLY_ENV);
    /* Sub-tick at 1 kHz: 1 us is 0 ticks — refused, not rounded. */
    kido_timer_test_set_freq(1000u);
    TIMER_CHECK(kido_timer_init() == KIDO_OK);
    TIMER_CHECK(kido_timer_arm_us(1u) == KIDO_ERR_EARLY_ENV);
    kido_timer_test_set_freq(62500000u);
    TIMER_CHECK(kido_timer_init() == KIDO_OK);

    /* §10: re-arm replaces, never queues. */
    kido_timer_test_set_count(0u);
    TIMER_CHECK(kido_timer_arm_ticks(100u) == KIDO_OK);
    TIMER_CHECK(kido_timer_arm_ticks(200u) == KIDO_OK);
    kido_timer_test_get_regs(NULL, &cval);
    TIMER_CHECK(cval == 200u);

    /* §11: re-init disarms and keeps the frequency. */
    TIMER_CHECK(kido_timer_init() == KIDO_OK);
    kido_timer_test_get_regs(&ctl, NULL);
    TIMER_CHECK((ctl & (KIDO_TIMER_CTL_ENABLE | KIDO_TIMER_CTL_IMASK)) == 0u);
    TIMER_CHECK(kido_timer_hz(&hz) == KIDO_OK && hz == 62500000u);

    /* §12: NULL guards after init. */
    TIMER_CHECK(kido_timer_hz(NULL) == KIDO_ERR_EARLY_ENV);
    TIMER_CHECK(kido_timer_now(NULL) == KIDO_ERR_EARLY_ENV);
    TIMER_CHECK(kido_timer_pending(NULL) == KIDO_ERR_EARLY_ENV);

    printf("[kido-timer] %u checks, %u failures\n",
           kido_timer_checks, kido_timer_failures);
    return (int)kido_timer_failures;
}

int main(void)
{
    return kido_timer_selftest_main() != 0;
}

#endif /* KIDO_TIMER_SELFTEST */
