interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / native / kernel / include / ck.h

343 lines · 18575 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* ck.h -- AIENOS C kernel core: the services the core gives to device,
18 * Store and security code. Freestanding; no libc.
19 *
20 * Owner split (Lane 18):
21 * core (native/boot, native/kernel/{arch,mm,core}) implements everything
22 * declared under "core services".
23 * stage (native/kernel/{dev,svc}) implements the "boot stages" at the end;
24 * core calls them from kmain in order, after MMU, heap, GIC and timer
25 * are up. A stage that is not linked is reported as "not linked".
26 *
27 * Memory model: the core runs with the MMU on and an identity map (VA == PA)
28 * for RAM and for every MMIO region handed out by ck_mmio_map. QEMU is not
29 * hardware: nothing built on these services is physically qualified.
30 */
31#ifndef AIENOS_CK_H
32#define AIENOS_CK_H
33
34#include <stdarg.h>
35#include <stddef.h>
36#include <stdint.h>
37
38/* ---- core services ------------------------------------------------------ */
39
40/* Console (SPCR / PL011). Format: %s %c %d %u %x %ld %lu %lx %lld %llu %llx
41 * %zu %zx %p %%, optional '0' pad and width (e.g. %016llx). */
42void ck_puts(const char *s);
43void ck_printf(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
44void ck_vprintf(const char *fmt, va_list ap);
45
46/* Prints "report_kind: panic" plus the message, then halts via PSCI reset
47 * (or WFI loop if PSCI is missing). Never returns. */
48__attribute__((noreturn, format(printf, 1, 2))) void ck_panic(const char *fmt, ...);
49
50/* Kernel heap. Zeroed memory, 16-byte aligned. NULL on exhaustion. */
51void *ck_alloc(size_t bytes);
52void ck_free(void *p);
53
54/* Physically contiguous, zeroed, `align`-aligned (power of two >= 4096)
55 * memory that a device may DMA to. Mapped Normal Non-cacheable, so no cache
56 * maintenance is needed by callers. *phys receives the bus address (identity
57 * map: equals the pointer value). NULL on exhaustion. Never freed. */
58void *ck_dma_alloc(size_t bytes, size_t align, uint64_t *phys);
59
60/* Map [phys, phys+len) as Device-nGnRE (identity) and return the pointer.
61 * Panics if the range overlaps RAM. */
62volatile void *ck_mmio_map(uint64_t phys, size_t len);
63/* Same mapping, but NULL instead of a panic when the range overlaps RAM or
64 * cannot be mapped (for addresses read from firmware tables; added for the
65 * platform xHCI path, NEXT-PHASE-3 cut 2). */
66volatile void *ck_mmio_try_map(uint64_t phys, size_t len);
67/* Exclusive variant of ck_mmio_try_map for a caller that must later take the
68 * pages away again (aienos#286, cut B3b). Maps [phys, phys+len) Device-nGnRE
69 * only if EVERY page in the range is currently unmapped; NULL (and nothing
70 * mapped) when any page is already mapped by someone else, overlaps RAM, or
71 * cannot be mapped. ck_mmio_try_map reuses pages that are already mapped, so
72 * it must never be paired with an unmap. */
73volatile void *ck_mmio_map_exclusive(uint64_t phys, size_t len);
74/* Unmaps pages mapped by ck_mmio_map_exclusive and invalidates the TLB. 0 on
75 * success; -1 (nothing changed) if any page of the range is not a Device
76 * identity mapping of itself or the unmap cannot be done on live tables.
77 * After it returns 0 a raw access to the range faults. */
78int ck_mmio_unmap_exclusive(uint64_t phys, size_t len);
79/* 1 if any page of [phys, phys+len) is currently mapped in the kernel's
80 * tables (a table lookup, never an access, so it cannot fault), else 0. */
81int ck_mmio_is_mapped(uint64_t phys, size_t len);
82
83/* Full system barrier (dsb sy). */
84void ck_mb(void);
85
86/* ACPI: the first table with this 4-byte signature ("MCFG", "MADT" is
87 * "APIC", "SPCR", "IORT"), checksum already verified; NULL if absent. */
88const void *ck_acpi_find(const char sig[4]);
89
90/* Monotonic time from the generic timer. */
91uint64_t ck_time_us(void);
92void ck_udelay(uint32_t us);
93
94/* Boot facts. */
95const char *ck_commit(void); /* git commit the image was built from */
96uint32_t ck_boot_count_hint(void); /* 0; Store keeps the real count */
97/* Operator shell facts (added for the keyboard cut, NEXT-PHASE-3): the
98 * exception level the kernel runs at now, and the UEFI conventional memory
99 * (type 7) the firmware memory map reported at entry, in KiB (Rust shell
100 * "mem" / "el"). */
101unsigned ck_exception_level(void);
102uint64_t ck_conventional_memory_kb(void);
103
104/* Interrupts (added by core, Lane 18). GICv3, group 1, routed to the boot
105 * CPU. Handlers run in IRQ context with interrupts masked; the core
106 * acknowledges and EOIs around the call. INTID 30 (timer) is reserved.
107 * ck_irq_register: 0 ok, -1 bad/reserved intid, -2 already registered.
108 * ck_irq_enable: 0 ok, -1 before the GIC is up or bad intid.
109 * ck_irq_cpu_enable(1) unmasks IRQs on this CPU, (0) masks them. */
110int ck_irq_register(uint32_t intid, void (*fn)(void *arg), void *arg);
111int ck_irq_enable(uint32_t intid);
112void ck_irq_cpu_enable(int on);
113
114/* DMA isolation (IORT + SMMUv3, core/smmu_svc.c; added by Lane 25). The
115 * first call brings the SMMU up with GBPA.ABORT set and every stream in
116 * abort, then gives PCI requester `rid` (bus<<8 | dev<<3 | fn, segment 0)
117 * a stage-1 table that maps only [phys, phys+len) at the same bus address
118 * (identity IOVA, Normal Non-cacheable, read/write). Any DMA outside the
119 * window faults and is aborted. phys and len must be 4 KiB aligned. At most
120 * CK_DMA_MAX_STREAMS confinements, one per stream.
121 * Returns 0 and fills *out, or:
122 * CK_SMMU_ABSENT no SMMUv3 in the IORT (or no IORT): no confinement
123 * CK_SMMU_FAILED SMMU present but bring-up or this stream failed;
124 * the SMMU stays off behind ABORT or the stream aborts
125 * CK_SMMU_NOSTREAM the IORT maps no stream for this requester
126 * CK_SMMU_EARG bad window, stream already confined, or table full
127 * Device DMA may be enabled only after a 0 return. */
128#define CK_SMMU_ABSENT (-1)
129#define CK_SMMU_FAILED (-2)
130#define CK_SMMU_NOSTREAM (-3)
131#define CK_SMMU_EARG (-4)
132#define CK_SMMU_OTHER (-5) /* the stream belongs to an SMMUv3 node the IORT parser did not keep (beyond CK_IORT_MAX_SMMUS) */
133#define CK_SMMU_AMBIGUOUS (-6) /* ck_dma_unconfine: the stream id is confined on two SMMUs; nothing is aborted (#480) */
134#define CK_DMA_MAX_STREAMS 8
135struct ck_dma_confinement {
136 uint64_t smmu_base;
137 uint32_t stream_id;
138 uint64_t iova, len;
139};
140/* `segment` is the PCI segment of the device and `rid` its requester id
141 * (bus<<8 | dev<<3 | fn) inside that segment: the IORT resolves the stream
142 * id within that segment's root complex only, and names the SMMUv3 node
143 * it sits behind; that node is brought up on its first confined stream
144 * (cut B7a: several SMMUs, the Spark GB10 is stream 0x100 of the second).
145 * Firmware-reserved ranges the IORT (RMR) names for the stream are
146 * identity-mapped beside the window; an RMR attribute other than Normal
147 * memory refuses the confinement (CK_SMMU_FAILED). Never grants unconfined. */
148int ck_dma_confine(uint32_t segment, uint32_t rid, uint64_t phys, uint64_t len, struct ck_dma_confinement *out);
149/* Same window for an ACPI platform device (no PCI requester id), added for
150 * the platform xHCI path (NEXT-PHASE-3 cut 2): the stream comes from the
151 * IORT named component whose object name has the same final segment as
152 * acpi_name ("USB0" for "\\_SB_.USB0"), through its single mapping. Returns
153 * as ck_dma_confine, plus CK_SMMU_NOSTREAM when no named component or no
154 * stream mapping exists, CK_SMMU_EARG when two named components carry that
155 * name, and CK_SMMU_OTHER when the stream belongs to an SMMUv3 node the
156 * parser did not keep (*out then names that SMMU and the stream, with len
157 * 0, for the report). Never grants unconfined. */
158int ck_dma_confine_named(const char *acpi_name, uint64_t phys, uint64_t len, struct ck_dma_confinement *out);
159
160/* ACPI platform devices (core/acpi_platform.c, NEXT-PHASE-3 cut 2): a
161 * static scan of the DSDT (from the FADT) and every SSDT the XSDT lists for
162 * Device objects whose _HID or _CID is one of ids[0..nids). Nothing is
163 * executed: _STA is not evaluated, _CRS is read only when it is a constant
164 * resource template (see core/acpi_dev.h). Each table must pass signature,
165 * length and checksum checks; a refused table is counted and skipped.
166 * Returns the number of matches (only max are stored), or -1 when no DSDT is
167 * reachable. info (may be NULL) gets the scan counters. */
168struct ck_platform_dev {
169 char name[48]; /* name at the DeviceOp, usually relative ("USB0") */
170 char hid[16], cid[16];
171 uint64_t mmio_base, mmio_len; /* first memory range of _CRS; 0 if none */
172 char table[5]; /* "DSDT" or "SSDT" */
173};
174struct ck_acpi_scan_info {
175 unsigned tables; /* definition blocks scanned (DSDT + SSDTs) */
176 unsigned refused; /* blocks refused: signature, length or checksum */
177 unsigned devices; /* Device objects parsed in the accepted blocks */
178 int first_refusal; /* CK_AML_E_* of the first refused block, 0 if none */
179};
180int ck_acpi_platform_devices(const char *const *ids, unsigned nids, struct ck_platform_dev *out, unsigned max,
181 struct ck_acpi_scan_info *info);
182/* Return a confined stream to abort (after the device's bus mastering is
183 * off). 0 ok, CK_SMMU_EARG if not confined, CK_SMMU_AMBIGUOUS if (stream ids
184 * being per SMMU) it is confined on two SMMUs at once (fail closed: both stay
185 * confined), CK_SMMU_FAILED on a command timeout. */
186int ck_dma_unconfine(uint32_t stream_id);
187/* Console text for a non-zero ck_dma_unconfine result, so a caller's message
188 * tells "nothing to release" apart from an inconsistent SMMU state (#480). */
189static inline const char *ck_dma_unconfine_why(int rc)
190{
191 return rc == CK_SMMU_EARG ? "not confined in the SMMU service"
192 : rc == CK_SMMU_AMBIGUOUS ? "AMBIGUOUS: stream id confined on two SMMUs"
193 : rc == CK_SMMU_FAILED ? "abort command failed"
194 : "unexpected result";
195}
196/* Drain the event queue of every SMMU brought up. Returns how many records
197 * named `stream_id` (others are dropped); *first gets the first of them.
198 * -1 if no SMMU is up. */
199#define CK_DMA_FAULT_TRANSLATION 0x10u /* SMMUv3 F_TRANSLATION event */
200struct ck_dma_fault {
201 uint32_t type, stream_id;
202 uint64_t addr;
203 int overflow;
204};
205int ck_dma_faults(uint32_t stream_id, struct ck_dma_fault *first);
206/* Release-failed evidence (#479): when a stream cannot be returned to abort,
207 * drain its SMMU fault events once and log what they hold. Read-only: no DMA
208 * buffer is freed or reused, and the stream stays confined. */
209static inline void ck_dma_fault_report(const char *who, uint32_t stream_id)
210{
211 struct ck_dma_fault f;
212 f.type = 0;
213 f.stream_id = stream_id;
214 f.addr = 0;
215 f.overflow = 0;
216 int n = ck_dma_faults(stream_id, &f);
217 if (n < 0)
218 ck_printf("smmu: %s stream 0x%x faults: no SMMU event queue to drain\n", who, stream_id);
219 else if (n == 0)
220 ck_printf("smmu: %s stream 0x%x faults=0%s\n", who, stream_id, f.overflow ? " (event queue overflowed)" : "");
221 else
222 ck_printf("smmu: %s stream 0x%x faults=%d first type=0x%x addr=0x%llx%s\n", who, stream_id, n, f.type,
223 (unsigned long long)f.addr, f.overflow ? " (event queue overflowed)" : "");
224}
225
226/* Entropy (arch/rndr.c over core/entropy.c): the Arm RNDR instruction or a
227 * refusal; there is no fallback source. ck_entropy_fill returns 0 with len
228 * bytes of RNDR output, or a negative CK_RNG_* refusal (absent, failed,
229 * stuck) with buf zeroed; a refusal is latched for the rest of the boot.
230 * Every security consumer must fail closed on a refusal. ck_entropy_reason
231 * names the current state ("rndr" when usable). */
232int ck_entropy_fill(void *buf, size_t len);
233int ck_entropy_status(void);
234const char *ck_entropy_reason(void);
235
236/* ---- boot stages (implemented by the stage worker, all optional) -------- */
237/* Each returns 0 on success, negative on failure; core prints the result.
238 * Declared weak so the core links and boots without them. */
239__attribute__((weak)) int ck_stage_devices(void); /* PCI, NVMe, virtio-net */
240__attribute__((weak)) int ck_stage_security(void); /* capability + ARGUS */
241__attribute__((weak)) int ck_stage_store(void); /* sealed Store on NVMe */
242/* Optional devices-stage hook: ck_reset calls it once, before PSCI reset or
243 * off (final report, panic, fault), so no device keeps DMA across a reset. */
244__attribute__((weak)) void ck_stage_quiesce(void);
245/* Optional final boot stage (dev/devices.c, only in a TEST-ONLY image built with
246 * CK_CONSOLE_SESSION=1): the operator console session. kmain calls it after every
247 * other boot step and before the final report; absent in every default image. */
248__attribute__((weak)) int ck_stage_console_session(void);
249/* Optional slot hook (svc/slot_service.c, only in a CK_SERVICE=1 image):
250 * ck_kernel_entry calls it right after ck_handoff_check, while the firmware
251 * identity map is still live, to copy SLOTLDR.EFI's boot record (P11 cut 2b).
252 * It only reads; absent (weak) in every diagnostic image. */
253struct ck_handoff;
254__attribute__((weak)) void ck_slot_boot_capture(const struct ck_handoff *h);
255/* Resident production lifecycle (core/lifecycle.c, only in a CK_SERVICE=1 image):
256 * serves bounded operator requests after every boot stage until its stop order,
257 * then returns 0 so kmain prints the final report and resets. Absent (weak) in
258 * every diagnostic image. */
259__attribute__((weak)) int ck_lifecycle_run(void);
260/* Raspberry Pi 5 board glue (core/pi5.c, CK_PI5 build only): watchdog arm and
261 * SD bring-up, the watchdog pet at every stage, and the console log written
262 * to the card before the reset. Absent (weak) in every other image. */
263__attribute__((weak)) void ck_pi5_start(void);
264__attribute__((weak)) void ck_pi5_stage(const char *name);
265__attribute__((weak)) void ck_pi5_before_reset(void);
266
267/* Console serial receive (core/console.c + core/uart_rx.h), POLLED, no
268 * interrupts. It uses the UART the transmit side chose from the ACPI SPCR:
269 * PL011/SBSA (QEMU virt) or 16550 (types 0x00/0x01/0x12; the DGX Spark's
270 * console is type 0x01 at 0x16A00000). ck_console_rx_ready: 1 when that UART
271 * can deliver bytes (PL011: UARTCR UARTEN and RXE; 16550: LCR.DLAB clear and
272 * LSR not all ones), *cr gets the proving register (PL011 UARTCR, 16550
273 * LCR << 8 | LSR); 0 for no console UART or a receiver that is off: then no
274 * byte is ever read. ck_console_rx_poll: -1 nothing waiting, -2 a byte lost or
275 * damaged (overrun, parity, framing, break; dropped and counted, more may be
276 * waiting), else the byte. The kernel never writes a UART control register. */
277const char *ck_console_uart_name(void);
278uint64_t ck_console_uart_base(void);
279int ck_console_rx_ready(uint32_t *cr);
280int ck_console_rx_poll(void);
281unsigned ck_console_rx_errors(void);
282unsigned ck_console_rx_overruns(void);
283
284/* Resident inference (core/infer.c, native v1 P06): a CK_SERVICE image built
285 * with CK_INFER_LIB keeps the ingested model and one bounded session open
286 * from boot to the lifecycle stop order. ck_infer_resident: 1 when a session
287 * is open. ck_infer_prompt: chat-templates `text`, steps to the reply's end
288 * (EOT or max_new) calling cancel_poll() between steps (1 = abandon the
289 * request); 0 on a completed or cancelled request (r filled), negative on a
290 * refusal (session codes: -12 no session, -16 prompt over max_prompt_bytes,
291 * -8 longer than the cache, -15 heap reserve). ck_infer_resident_close:
292 * closes the session and returns every frame (prints the unloaded line).
293 * Images without the unit: resident 0, prompt -12, close a no-op. */
294/* Resident session limits (N3, aienos#329; frozen for a useful task, see
295 * core/context.h): KV positions, generated tokens per prompt, prompt bytes
296 * (= CK_CTX_PROMPT_MAX), heap reserve. 1024 positions x 64 KiB of f32 K+V
297 * (16 layers x 512 kv dims x 2 x 4 B, Llama 3.2 1B) = 64 MiB of the 256 MiB
298 * session heap (the model needed 22.9 MiB at 64 positions). */
299#define CK_INFER_RES_KV 1024u
300#define CK_INFER_RES_MAX_NEW 256u
301#define CK_INFER_RES_PROMPT_BYTES 752u
302#define CK_INFER_RES_RESERVE (64u << 10)
303#define CK_INFER_REPLY_IDS 256 /* = CK_INFER_RES_MAX_NEW */
304#define CK_INFER_REPLY_TEXT 1536 /* = CK_LC_REPLY_MAX */
305struct ck_infer_reply {
306 uint32_t ids[CK_INFER_REPLY_IDS];
307 uint32_t prompt_ids, produced, steps;
308 int cancelled;
309 int32_t rc;
310 uint64_t us;
311 uint8_t text[CK_INFER_REPLY_TEXT];
312 uint32_t text_len;
313 uint32_t prompt_head[4]; /* first four prompt token ids (the chat template), filled when the prompt was accepted */
314};
315int ck_infer_resident(void);
316int ck_infer_prompt(const char *text, size_t len, int (*cancel_poll)(void), struct ck_infer_reply *r);
317void ck_infer_resident_close(void);
318/* SHA-256 of the resident model bytes (32 bytes) after a successful ck_infer_run ingest of a boot-disk model,
319 * else NULL (no resident session, or an image without the unit). */
320const uint8_t *ck_infer_model_sha256(void);
321
322/* Optional Store-stage hook: signed P2 artifact candidates read from the boot
323 * disk Store (svc/artifact_store.c) during ck_stage_store, before the NVMe
324 * release. The bytes are UNTRUSTED: the core loader verifies them exactly as
325 * any other candidate. Returns 0 and fills *out once the store stage ran. */
326enum { CK_DISK_ART_OK = 0, CK_DISK_ART_MISSING = 1, CK_DISK_ART_TOO_LARGE = 2 };
327struct ck_disk_artifact {
328 const char *name; /* 1..32 printable bytes */
329 const uint8_t *bytes; /* len bytes when state == CK_DISK_ART_OK, else NULL */
330 uint64_t len;
331 int state; /* CK_DISK_ART_* */
332};
333struct ck_disk_artifacts {
334 int available; /* an artifact index was read from the Store */
335 const char *why; /* reason when not available */
336 uint64_t generation; /* Store generation of the index */
337 unsigned count;
338 const struct ck_disk_artifact *a;
339};
340__attribute__((weak)) int ck_stage_disk_artifacts(struct ck_disk_artifacts *out);
341__attribute__((weak)) void ck_stage_disk_artifacts_free(void);
342
343#endif