/*
 * kido-cache.h — Kido cache maintenance leaf.
 *
 * Session 22's kido-mmu turns caches on (SCTLR M|C|I).
 * Session 33's kido-smp writes a BSS mailbox one CPU
 * reads from another. Nothing in the tree maintained a
 * cache between those two facts. This module is that
 * primitive: VA-based cache maintenance, barrier-closed,
 * no allocator, no scheduler coupling, no coupling at
 * all beyond kido-boot.h's status codes.
 *
 * POINT LAW (deliberation C1): every function names its
 * point. PoC (point of coherency) is where another CPU
 * or a DMA observer sees the write — the inter-CPU job.
 * PoU (point of unification) is where the instruction
 * cache sees the write — the code-writing job only. A
 * PoU clean is NEVER a substitute for PoC work: a
 * CVAU-cleaned mailbox is still invisible to another
 * CPU's D-cache.
 *
 * TWO LINE SIZES (deliberation C2 — the decision this
 * module turns on): CTR_EL0 carries DminLine [19:16]
 * for the D-cache and IminLine [3:0] for the I-cache.
 * Line bytes = 4 << field in each case. DC ops step by
 * the D size; IC IVAU steps by the I size. There is
 * deliberately no single line_size(): on a core whose
 * I and D lines differ, one size would skip lines on
 * one side — silent stale data or stale instructions,
 * with no fault to announce it. A field value of 0
 * yields a 4-byte line: over-maintenance, the safe
 * direction, never refused.
 *
 * ALIGNMENT LAW (deliberation C3): clean-family ops
 * (CVAC, CIVAC, CVAU) align the base down and the end
 * up and maintain whole lines — cleaning a line writes
 * a neighbor's dirty bytes back, which is harmless.
 * invalidate_range() is different: invalidating a line
 * DISCARDS its dirty bytes, so an unaligned invalidate
 * would discard a neighbor's data the caller never
 * named. It refuses EARLY_ENV unless addr and len are
 * both line multiples. One destructive op, one refusal.
 *
 * ZERO LENGTH (deliberation C4): refused EARLY_ENV on
 * every range op. A caller asking to maintain nothing
 * has a bug, and rounding a zero range up to one line
 * would maintain a line nobody asked about — the C3
 * hazard wearing a no-op's clothes.
 *
 * BARRIER LAW (deliberation C5, P2): every op ends in
 * its barrier, inside the op. Range D-cache ops end in
 * DSB SY (full system, not ISH — PoC visibility is
 * owed to every observer, not just the inner shareable
 * domain). I-cache ops end in DSB SY + ISB (the ISB is
 * what makes the executing CPU fetch fresh
 * instructions). No bare dsb()/isb() API is offered
 * (deliberation D1): a barrier the caller must remember
 * is a barrier that will be forgotten once.
 *
 * NO SET/WAY OPS (deliberation C6/D2): DC CISW and kin
 * address cache geometry, not memory, and would discard
 * lines belonging to other agents' data. This leaf is
 * VA-based only. IC IALLU is the exception that proves
 * the rule: invalidating the whole I-cache discards no
 * data (instructions re-fetch from memory), so
 * icache_invalidate_all() is offered.
 *
 * EL LAW: cache maintenance by VA traps from EL0
 * unless SCTLR_EL1.UCI is set (it is not, anywhere in
 * this tree). Call at EL1 or above. Stated, not
 * enforced — the mpidr precedent. CTR_EL0 itself is
 * readable at any EL and needs no law.
 *
 * DESTRUCTIVE-OP WARNING, stated plainly: invalidate
 * of a dirty line loses the data. The caller must
 * never invalidate a range it has written without
 * cleaning first (clean_invalidate_range exists for
 * exactly that shape). The module cannot detect dirty
 * lines, so it documents the duty instead of pretending
 * to enforce it. Only the preventable case — an
 * unaligned range spilling onto a neighbor's line —
 * is refused (alignment law above).
 *
 * PROOF STATUS: WRITTEN, NOT ASSEMBLED, NEVER EXECUTED
 * on bare metal (toolchain absent, 22nd data point).
 * The hosted proof drives the recording double and pins
 * alignment arithmetic, guard refusals, walk counts,
 * and barrier order. The ARM64 spellings (MRS CTR_EL0,
 * DC CVAC/CIVAC/IVAC/CVAU, IC IVAU/IALLU, DSB SY, ISB)
 * await assemble + disassembly + a QEMU virt -smp 2
 * run with caches enabled. No bootable kernel is
 * finalized without N8toriousAi; first boot is his to
 * witness.
 *
 * FUTURES (named, not built): the first consumer — a
 * Gate wiring cleaning the smp mailbox at the writer
 * side, or a post-mmu-enable I-cache invalidate
 * (deliberation C7); a QEMU virt -smp 2 cache-coherency
 * proof (writer cleans, reader sees the write, with
 * caches on).
 *
 * Draft status: DRAFT (2026-10-31, session 39).
 *
 * TESTING: gcc -std=c11 -Wall -Wextra -Werror -DKIDO_HOSTED_TEST
 *        -DKIDO_CACHE_SELFTEST kido-cache.c -o cache-selftest
 */
#ifndef KIDO_CACHE_H
#define KIDO_CACHE_H

#include "kido-boot.h"

#if !defined(__aarch64__) && !defined(KIDO_HOSTED_TEST)
#error "kido-cache: refusing to compile for unknown arch. Cache maintenance lives in per-arch code; define KIDO_HOSTED_TEST for the hosted draft harness."
#endif

#include <stdint.h>
#include <stddef.h>

/* D-cache line size in bytes, from CTR_EL0 DminLine
 * [19:16]: 4 << field. Hosted: the injector's value
 * (default 64). NULL out refuses EARLY_ENV. Never
 * fails otherwise: a register field always yields a
 * size, and 0 fields yield the safe 4-byte size. */
kido_status_t kido_cache_dline_size(uint64_t *out);

/* I-cache line size in bytes, from CTR_EL0 IminLine
 * [3:0]: 4 << field. Same contract as dline_size.
 * Kept separate by the two-line-sizes law (C2). */
kido_status_t kido_cache_iline_size(uint64_t *out);

/* Clean [addr, addr+len) to the point of coherency:
 * DC CVAC per D-line, then DSB SY. Unaligned ranges
 * are rounded out to whole lines (alignment law).
 * Guards: addr == 0, len == 0, or addr+len wrapping
 * refuse EARLY_ENV. */
kido_status_t kido_cache_clean_range(uintptr_t addr, uint64_t len);

/* Invalidate [addr, addr+len) to the point of
 * coherency: DC IVAC per D-line, then DSB SY.
 * DESTRUCTIVE: a dirty line's data is lost — never
 * invalidate a range written without cleaning first
 * (use clean_invalidate_range for that shape).
 * Guards as clean_range, PLUS: addr and len must
 * both be D-line multiples, else EARLY_ENV (an
 * unaligned invalidate would discard a neighbor's
 * dirty line the caller never named). */
kido_status_t kido_cache_invalidate_range(uintptr_t addr, uint64_t len);

/* Clean then invalidate [addr, addr+len) to PoC:
 * DC CIVAC per D-line, then DSB SY. The safe shape
 * for a buffer being handed to another observer:
 * no data is lost (it is written back first).
 * Guards as clean_range (rounding allowed). */
kido_status_t kido_cache_clean_invalidate_range(uintptr_t addr,
                                                 uint64_t len);

/* The self-modifying-code sequence, as one function
 * so its order cannot be reordered (P4): DC CVAU per
 * D-line (clean to PoU), DSB SY, IC IVAU per I-line
 * (invalidate the stale instructions), DSB SY, ISB.
 * Guards as clean_range (rounding allowed; I-cache
 * invalidation discards no data, so no C3 refusal).
 * Use after writing code a CPU will execute. */
kido_status_t kido_cache_sync_icache_range(uintptr_t addr, uint64_t len);

/* Invalidate the entire I-cache: IC IALLU, DSB SY,
 * ISB. Discards no data (instructions re-fetch).
 * No range form is needed: the whole I-cache is the
 * unit. Cannot fail: there are no arguments to guard. */
kido_status_t kido_cache_icache_invalidate_all(void);

#ifdef KIDO_HOSTED_TEST
/* Hosted-only injectors (the sync/mpidr precedent):
 * the CTR_EL0 field values the line-size queries
 * decode on the host, where no CTR_EL0 exists.
 * Defaults: DminLine 4 (64 bytes), IminLine 4
 * (64 bytes). Never refuse: a field value is input,
 * not a claim to validate (two-line-sizes law). */
kido_status_t kido_cache_test_set_dminline(uint32_t field);
kido_status_t kido_cache_test_set_iminline(uint32_t field);

/* Hosted-only trace log, so the self-test pins what
 * the double recorded: the op kind (0 clean, 1
 * invalidate, 2 clean+invalidate, 3 sync-icache CVAU
 * walk, 4 sync-icache IVAU walk, 5 icache-all), the
 * first line address, the line count, and whether a
 * DSB / ISB followed. A log, not a single slot:
 * sync_icache_range records TWO entries (its CVAU
 * walk, then its IVAU walk) and the test must pin
 * both. Capacity 16 entries; the test resets before
 * each op, so overflow cannot trigger in the suite
 * (entries past capacity are dropped, never wrapped
 * — a wrapped log would lie about order). */
typedef struct kido_cache_trace {
    uint32_t  kind;
    uintptr_t first;
    uint64_t  lines;
    uint32_t  dsb_after;
    uint32_t  isb_after;
} kido_cache_trace_t;
kido_status_t kido_cache_test_trace_reset(void);
kido_status_t kido_cache_test_trace_count(uint64_t *out);
kido_status_t kido_cache_test_trace_at(uint64_t idx,
                                        kido_cache_trace_t *out);
#endif /* KIDO_HOSTED_TEST */

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

#endif /* KIDO_CACHE_H */
