//
//  ksafe.h
//  Cyanide
//
//  Mapped-address safety gate for KRW reads.
//
//  A KRW read of an unmapped kernel address faults the kernel and panics the
//  device. ksafe answers "is this kernel address mapped?" BEFORE a pointer is
//  dereferenced. It used to be a software page-table walk; on SPTM devices
//  (T8140/A18) page-table pages are unreadable by the kernel (instant panic),
//  so the check is now a snapshot of kernel_map's vm_map_entry list, which is
//  ordinary zone memory. Everything here is READ-ONLY.
//

#ifndef ksafe_h
#define ksafe_h

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

// True once the kernel_map entry snapshot has been built and kaddr_is_mapped
// can answer mapped-checks.
bool ksafe_available(void);

// Builds the kernel_map entry snapshot (pid0 proc -> task -> kernel_map, all
// known struct offsets; no kernelcache, no symbols). Safe to call again;
// later calls are no-ops once available.
void ksafe_bringup(void);

// Re-takes the kernel_map snapshot (the bringup snapshot is never updated, so
// kernel memory mapped after it -- e.g. the struct of a thread created later --
// reads as "not mapped"). Callers about to SKIP something that must happen
// (un-arming a thread we armed) refresh and re-check instead of trusting a
// stale "no". Readers never see a half-built snapshot (double buffer, atomic
// switch); refreshes are serialised and at most one per 500 ms (a call inside
// that window does not refresh). Returns true when a fresh snapshot is now
// active: taken by this call, or a successful one taken inside the window
// (ksafe_refresh_status() != KSAFE_REFRESH_FAILED).
bool ksafe_refresh(void);

// Tri-state variant of ksafe_refresh. DONE: this call took a fresh snapshot.
// RECENT: rate-limited, but a SUCCESSFUL snapshot completed within the last
// 500 ms and is active (as authoritative as DONE). FAILED: no snapshot could
// be taken and none succeeded within the window (unavailable, KRW down,
// snapshot failed, or a reader pinned the spare buffer).
typedef enum {
    KSAFE_REFRESH_FAILED = 0,
    KSAFE_REFRESH_DONE,
    KSAFE_REFRESH_RECENT,
} ksafe_refresh_status_t;
ksafe_refresh_status_t ksafe_refresh_status(void);

// Diagnostics: logs the snapshot range nearest to kvaddr (why a check failed).
void ksafe_describe(uint64_t kvaddr, size_t len);

// True iff [kvaddr, kvaddr+len) lies inside the kernel_map snapshot (adjacent
// entries are merged, so a range across a seam between them counts)
// (i.e. the range is covered by kernel VA mappings). Use this to gate any
// dereference of a kernel pointer that is not known-good.
bool kaddr_is_mapped(uint64_t kvaddr, size_t len);

#endif /* ksafe_h */
