/*
 * kido-time.h — Kido monotonic clock: Generic Timer ticks to
 * nanoseconds, over an injected source.
 *
 * Session 29 gave the tree a timer that can arm a compare
 * and report a count. Nothing since has turned that count
 * into time: ticks are not a unit (62,500,000 ticks is one
 * second on QEMU virt and something else wherever CNTFRQ
 * differs). This leaf is the conversion, owned once, with
 * a monotonicity law the raw counter does not itself
 * promise to every future source.
 *
 * CONVERSION LAW (deliberation C6/P2): the equation is the
 * module, in pure uint64 C11, no __int128, no float:
 *   ns = (ticks / hz) * 1e9 + (ticks % hz) * 1e9 / hz
 * Truncation toward zero at both divisions; error under
 * one tick period, never rounded up (reporting time not
 * yet elapsed would be a lie). Every intermediate is
 * inside uint64 by construction: rem < hz <= 2^32 - 1,
 * so rem * 1e9 < 4.3e18 < 2^64. Two overflow guards,
 * both EARLY_ENV with *out untouched:
 *   (1) seconds > UINT64_MAX / 1e9 (the ~584.9-year cap);
 *   (2) seconds * 1e9 + remainder-ns crossing UINT64_MAX
 *       (pinned by test: hz = 4, ticks = 73786976295
 *       refuses, while ticks = 73786976292 returns
 *       exactly 18446744073000000000).
 *
 * SOURCE LAW (deliberation C1): the counter is injected
 * as a table, never coupled to kido-timer.c directly.
 * The concrete reason: timer's hosted setters live
 * behind KIDO_TIMER_SELFTEST, which also defines
 * timer's main — linking timer.c into this leaf's test
 * would collide mains. The ipi precedent applies:
 * transport (here, time) injected via an ops table, the
 * binding a one-line Gate item. The Gate binding is
 * named, not taken: { kido_timer_now, kido_timer_hz },
 * whose signatures match the source slots exactly. The
 * leaf propagates a source failure unchanged: a source
 * that is not initialized reports its own EARLY_ENV,
 * never a time invention. The caller owns the table's
 * lifetime; it must outlive every clock call (the Gate
 * binding is a static table, so this is structural).
 *
 * HZ LAW (deliberation C2): hz == 0 means two different
 * things at two layers, kept apart. In the pure
 * converter it is an argument error (EARLY_ENV:
 * division by zero has no honest answer). In init it
 * is a missing time base (NO_TIMER, the timer's own
 * code for CNTFRQ == 0).
 *
 * MONOTONICITY LAW (deliberation C3): now_ns never goes
 * backwards. If the source steps back, the clock returns
 * the last value it gave and increments the regression
 * counter in stats — the answer stays usable and the
 * audit trail shows the step. The first read cannot
 * regress (last starts at 0, and a count is unsigned).
 *
 * INIT LAW (deliberation C4): init succeeds exactly
 * once. A second init refuses EARLY_ENV even with the
 * same source: re-init would need an epoch policy, and
 * resetting the floor would let the clock jump
 * backwards through its own clamp. There is no destroy
 * API: this leaf owns no resource a destroy would free
 * (static BSS state, an injected table it does not
 * own) — the session-37 D1 distinction, applied here.
 * A failed init leaves the state untouched, so a
 * corrected init can still succeed (pinned by test).
 *
 * ELAPSED LAW (deliberation C5): elapsed_ns(since) is
 * now_ns - since in unsigned arithmetic, correct
 * modulo 2^64 for any interval shorter than the
 * ~584.9-year wrap. A `since` in the future of the
 * monotonic clock (since > now) refuses EARLY_ENV:
 * it is a caller bug or a foreign timestamp, and the
 * wrap complement would be a lie dressed as a
 * duration. The read still counts in stats — the read
 * succeeded; the refusal is the caller's.
 *
 * STATS LAW (deliberation C7): reads counts every
 * successful now_ns, including the reads now_us and
 * elapsed_ns make internally — one counter, one
 * meaning. Regressions counts clamped reads. last_ns
 * is deliberately not exposed: a caller reading it
 * would reimplement the clamp, a second monotonicity
 * path that could drift.
 *
 * HONESTY LAW:
 *  - No new header code (sched-D1 precedent): every
 *    refusal is EARLY_ENV except the missing time
 *    base, which is NO_TIMER.
 *  - Zero existing files touched. Timer keeps its
 *    contract; this leaf only names its two public
 *    signatures as slots. No wiring into the
 *    scheduler, no tick policy — consumers are Gate
 *    items.
 *  - WRITTEN, NOT ASSEMBLED, NEVER EXECUTED on bare
 *    metal (toolchain absent, 24th data point). The
 *    leaf has no asm of its own — its ARM64 content
 *    is the timer's already-carried register reads —
 *    so what awaits a tooled VM is the Gate binding
 *    plus a QEMU virt run showing now_ns advancing
 *    at the real 62.5 MHz CNTFRQ.
 *  - No bootable kernel is finalized without N8toriousAi;
 *    first boot is his to witness.
 *
 * FUTURES (named, not built): the Gate binding
 * ({ kido_timer_now, kido_timer_hz }) and its
 * timer-init ordering; a QEMU virt advancing-clock
 * proof; scheduler-quantum and timeout consumers;
 * a virtual-timer source binding when timer's
 * virtual driver exists.
 *
 * Draft status: DRAFT (2026-11-01, session 41).
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror
 *        -DKIDO_HOSTED_TEST -DKIDO_TIME_SELFTEST
 *        kido-time.c -o time-selftest
 *        (plain -c needs no extra libraries: the
 *        scripted source lives in the test TU only,
 *        the barrier precedent).
 */
#ifndef KIDO_TIME_H
#define KIDO_TIME_H

#include "kido-boot.h"

#if !defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
#error "kido-time: refusing to compile for unknown arch. The clock's counter lives in per-arch code; define KIDO_HOSTED_TEST for the hosted draft harness."
#endif

/* A time source: the two timer signatures, as slots.
 * now_fn fills *ticks with the current count;
 * hz_fn fills *hz with the counter frequency.
 * Either slot returning non-OK propagates unchanged
 * through every clock call. */
typedef struct kido_time_source {
    kido_status_t (*now_fn)(uint64_t *ticks_out);
    kido_status_t (*hz_fn)(uint32_t *hz_out);
} kido_time_source_t;

/* Clock audit counters. */
typedef struct kido_time_stats {
    uint64_t reads;       /* successful now_ns reads, all paths */
    uint64_t regressions; /* reads clamped to the last value */
} kido_time_stats_t;

/* Bind the source and read its frequency once. Refuses
 * EARLY_ENV before a valid table (NULL table or NULL
 * slot), on a source failure (propagated unchanged), or
 * on a second init; NO_TIMER when the source reports
 * hz == 0. A failed init leaves the state untouched. */
kido_status_t kido_time_init(const kido_time_source_t *src);

/* Nanoseconds since the clock's epoch (the source
 * counter's zero). Monotonic by the clamp law; a
 * backwards source step returns the last value and
 * counts a regression. Refuses EARLY_ENV before init,
 * on a NULL out-pointer, on a source failure, or on
 * conversion overflow — in every refusal case *out is
 * untouched and no read is counted. */
kido_status_t kido_time_now_ns(uint64_t *out);

/* now_ns / 1000, truncated toward zero. Same refusals
 * as now_ns; the internal read counts in stats. */
kido_status_t kido_time_now_us(uint64_t *out);

/* now_ns - since in unsigned arithmetic. Refuses
 * EARLY_ENV before init, on a NULL out-pointer, on a
 * source/conversion failure, or when since > now (a
 * future timestamp). The read counts in stats even
 * when the since-check refuses. */
kido_status_t kido_time_elapsed_ns(uint64_t since,
                                    uint64_t *out);

/* Pure converter, no source, no state: the conversion
 * law as a function. Refuses EARLY_ENV on hz == 0, on
 * a NULL out-pointer, or on either overflow guard —
 * *out untouched in every refusal case. */
kido_status_t kido_time_ticks_to_ns(uint64_t ticks,
                                     uint32_t hz,
                                     uint64_t *out);

/* Audit counters. Refuses EARLY_ENV before init or on
 * a NULL out-pointer. */
kido_status_t kido_time_stats(kido_time_stats_t *out);

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

#endif /* KIDO_TIME_H */
