aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / allen-reflex-kernel / src / kernel.rs
| 1 | //! Kernel side (`target_os = "none"` only): global allocator, panic handler and the C entry points |
| 2 | //! called by `native/kernel/core/allen.c`. Single core, interrupts and FP exceptions masked by the |
| 3 | //! caller for the whole time Rust code runs (as for the inference unit, `core/fpu.c`). |
| 4 | //! |
| 5 | //! Stop rule: any Rust panic, including an allocation the bounded heap cannot satisfy (Rust's |
| 6 | //! allocation-error path panics), calls `aienos_allen_panic`, which prints the reason and halts |
| 7 | //! through the kernel's panic path. It never returns, so the decision in progress is never |
| 8 | //! printed, never reaches the gate, and nothing is written (the pi5-allen image has no Store stage). |
| 9 | |
| 10 | use alloc::string::String; |
| 11 | use alloc::vec::Vec; |
| 12 | use core::alloc::{GlobalAlloc, Layout}; |
| 13 | use core::arch::asm; |
| 14 | use core::cell::UnsafeCell; |
| 15 | use core::fmt::Write; |
| 16 | |
| 17 | use crate::card::{self, CaseRef, Kind, RouteRef}; |
| 18 | use crate::heap::{Bump, Mark, Stats}; |
| 19 | use crate::runner::{self, Session}; |
| 20 | |
| 21 | extern "C" { |
| 22 | /// `native/kernel/core/allen.c`: prints `msg[..len]` and halts through `ck_panic`. Never returns. |
| 23 | fn aienos_allen_panic(msg: *const u8, len: usize) -> !; |
| 24 | } |
| 25 | |
| 26 | struct KHeap(Bump); |
| 27 | // SAFETY: one core, interrupts masked while Rust runs (module doc). |
| 28 | unsafe impl Sync for KHeap {} |
| 29 | |
| 30 | #[global_allocator] |
| 31 | static HEAP: KHeap = KHeap(Bump::new()); |
| 32 | |
| 33 | unsafe impl GlobalAlloc for KHeap { |
| 34 | unsafe fn alloc(&self, l: Layout) -> *mut u8 { |
| 35 | self.0.alloc(l.size(), l.align()) as *mut u8 |
| 36 | } |
| 37 | |
| 38 | unsafe fn dealloc(&self, p: *mut u8, l: Layout) { |
| 39 | self.0.dealloc(p as usize, l.size()) |
| 40 | } |
| 41 | |
| 42 | unsafe fn realloc(&self, p: *mut u8, l: Layout, new_size: usize) -> *mut u8 { |
| 43 | let q = self.0.resize_in_place(p as usize, l.size(), new_size); |
| 44 | if q != 0 { |
| 45 | return q as *mut u8; |
| 46 | } |
| 47 | let n = self.0.alloc(new_size, l.align()); |
| 48 | if n == 0 { |
| 49 | return core::ptr::null_mut(); |
| 50 | } |
| 51 | // SAFETY: both blocks are valid for the smaller size and do not overlap (n is new). |
| 52 | core::ptr::copy_nonoverlapping(p, n as *mut u8, core::cmp::min(l.size(), new_size)); |
| 53 | self.0.dealloc(p as usize, l.size()); |
| 54 | n as *mut u8 |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | struct Msg { |
| 59 | buf: [u8; 192], |
| 60 | len: usize, |
| 61 | } |
| 62 | |
| 63 | impl Write for Msg { |
| 64 | fn write_str(&mut self, s: &str) -> core::fmt::Result { |
| 65 | for &b in s.as_bytes() { |
| 66 | if self.len < self.buf.len() { |
| 67 | self.buf[self.len] = if (0x20..=0x7e).contains(&b) { b } else { b'?' }; |
| 68 | self.len += 1; |
| 69 | } |
| 70 | } |
| 71 | Ok(()) |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | struct PanicBuf(UnsafeCell<Msg>); |
| 76 | // SAFETY: written once, on the single core, right before halting. |
| 77 | unsafe impl Sync for PanicBuf {} |
| 78 | static PANIC_MSG: PanicBuf = PanicBuf(UnsafeCell::new(Msg { |
| 79 | buf: [0; 192], |
| 80 | len: 0, |
| 81 | })); |
| 82 | |
| 83 | #[panic_handler] |
| 84 | fn panic(info: &core::panic::PanicInfo) -> ! { |
| 85 | // SAFETY: single core; the kernel halts right after, so no one else touches the buffer. |
| 86 | let m = unsafe { &mut *PANIC_MSG.0.get() }; |
| 87 | m.len = 0; |
| 88 | let _ = write!(m, "{}", info.message()); |
| 89 | if let Some(loc) = info.location() { |
| 90 | let _ = write!(m, " at {}:{}", loc.file(), loc.line()); |
| 91 | } |
| 92 | // SAFETY: plain C function, defined by the kernel; the buffer outlives the call. |
| 93 | unsafe { aienos_allen_panic(m.buf.as_ptr(), m.len) } |
| 94 | } |
| 95 | |
| 96 | struct State { |
| 97 | card: *const u8, |
| 98 | card_len: usize, |
| 99 | cases: Option<Vec<CaseRef>>, |
| 100 | routes: Option<Vec<RouteRef>>, |
| 101 | after_cases: Option<Mark>, |
| 102 | session: Option<Session>, |
| 103 | line: String, |
| 104 | } |
| 105 | |
| 106 | struct Global(UnsafeCell<State>); |
| 107 | // SAFETY: one core, calls from the kernel never overlap (module doc). |
| 108 | unsafe impl Sync for Global {} |
| 109 | static G: Global = Global(UnsafeCell::new(State { |
| 110 | card: core::ptr::null(), |
| 111 | card_len: 0, |
| 112 | cases: None, |
| 113 | routes: None, |
| 114 | after_cases: None, |
| 115 | session: None, |
| 116 | line: String::new(), |
| 117 | })); |
| 118 | |
| 119 | fn st() -> &'static mut State { |
| 120 | // SAFETY: see `Global`. |
| 121 | unsafe { &mut *G.0.get() } |
| 122 | } |
| 123 | |
| 124 | fn ticks() -> u64 { |
| 125 | let v: u64; |
| 126 | // SAFETY: reads the virtual counter (always readable at EL1). |
| 127 | unsafe { asm!("isb", "mrs {}, cntvct_el0", out(reg) v, options(nomem, nostack)) }; |
| 128 | v |
| 129 | } |
| 130 | |
| 131 | /// Counter frequency in Hz (CNTFRQ_EL0): ticks of [`DecideInfo::ticks`] and [`TrainInfo::ticks`]. |
| 132 | #[no_mangle] |
| 133 | pub extern "C" fn aienos_allen_tick_hz() -> u64 { |
| 134 | let v: u64; |
| 135 | // SAFETY: reads a read-only system register. |
| 136 | unsafe { asm!("mrs {}, cntfrq_el0", out(reg) v, options(nomem, nostack)) }; |
| 137 | v |
| 138 | } |
| 139 | |
| 140 | /// Hand the heap region over (`len == 0` closes it: every allocation fails from then on). |
| 141 | /// Drops nothing: call [`aienos_allen_close`] first. |
| 142 | /// |
| 143 | /// # Safety |
| 144 | /// `[base, base + len)` must be writable memory owned by this unit until the next call. |
| 145 | #[no_mangle] |
| 146 | pub unsafe extern "C" fn aienos_allen_heap_init(base: usize, len: usize) { |
| 147 | HEAP.0.init(base, len); |
| 148 | } |
| 149 | |
| 150 | /// Heap counters now. |
| 151 | /// |
| 152 | /// # Safety |
| 153 | /// `out` must point to a writable `Stats`. |
| 154 | #[no_mangle] |
| 155 | pub unsafe extern "C" fn aienos_allen_heap_stats(out: *mut Stats) { |
| 156 | if !out.is_null() { |
| 157 | *out = HEAP.0.stats(); |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | /// Check the card exam file and keep its case index. Returns the case count, or -1 with |
| 162 | /// `*why` set to a NUL-terminated reason. The buffer must stay unchanged until close. |
| 163 | /// |
| 164 | /// # Safety |
| 165 | /// `buf[..len]` readable for the lifetime of the run; `why` null or writable. |
| 166 | #[no_mangle] |
| 167 | pub unsafe extern "C" fn aienos_allen_card_open( |
| 168 | buf: *const u8, |
| 169 | len: usize, |
| 170 | why: *mut *const u8, |
| 171 | ) -> i32 { |
| 172 | let s = st(); |
| 173 | s.session = None; |
| 174 | s.cases = None; |
| 175 | s.routes = None; |
| 176 | let b = core::slice::from_raw_parts(buf, len); |
| 177 | let parsed = match card::kind(b) { |
| 178 | Some(Kind::Route) => card::parse_route(b).map(|r| { |
| 179 | let n = r.len(); |
| 180 | s.routes = Some(r); |
| 181 | n |
| 182 | }), |
| 183 | _ => card::parse(b).map(|c| { |
| 184 | let n = c.len(); |
| 185 | s.cases = Some(c); |
| 186 | n |
| 187 | }), |
| 188 | }; |
| 189 | match parsed { |
| 190 | Ok(n) => { |
| 191 | s.card = buf; |
| 192 | s.card_len = len; |
| 193 | s.line = String::with_capacity(8192); |
| 194 | s.after_cases = Some(HEAP.0.mark()); |
| 195 | n as i32 |
| 196 | } |
| 197 | Err(e) => { |
| 198 | if !why.is_null() { |
| 199 | *why = reason_cstr(e); |
| 200 | } |
| 201 | -1 |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | fn reason_cstr(e: &'static str) -> *const u8 { |
| 207 | // Static, NUL-terminated copies of every reason card::parse can give. |
| 208 | const R: [&[u8]; 16] = [ |
| 209 | b"no case line\0", |
| 210 | b"route line needs id|speaker:session|flags|turns\0", |
| 211 | b"speaker must be owner:<n> or guest:<n>\0", |
| 212 | b"session must be 1..999999999\0", |
| 213 | b"flags must be - or letters from CP\0", |
| 214 | b"file size must be 1..131072 bytes\0", |
| 215 | b"only printable ASCII and LF line ends are allowed\0", |
| 216 | b"file does not end with a line feed\0", |
| 217 | b"bad header line\0", |
| 218 | b"empty line\0", |
| 219 | b"more than 512 cases\0", |
| 220 | b"case line has no '|' after the id\0", |
| 221 | b"id must be 1..16 bytes\0", |
| 222 | b"id may hold only A-Z a-z 0-9 _ -\0", |
| 223 | b"turns must be 1..4096 bytes\0", |
| 224 | b"duplicate case id\0", |
| 225 | ]; |
| 226 | for r in R { |
| 227 | if &r[..r.len() - 1] == e.as_bytes() { |
| 228 | return r.as_ptr(); |
| 229 | } |
| 230 | } |
| 231 | c"malformed".as_ptr().cast() |
| 232 | } |
| 233 | |
| 234 | /// What training reports. `#[repr(C)]`, mirrored in `core/allen.c`. |
| 235 | #[repr(C)] |
| 236 | pub struct TrainInfo { |
| 237 | /// counter ticks spent training (pool parse + train + finish), at [`aienos_allen_tick_hz`] |
| 238 | pub ticks: u64, |
| 239 | /// training examples |
| 240 | pub examples: u64, |
| 241 | /// exemplars kept |
| 242 | pub exemplars: u64, |
| 243 | /// learned-state bytes (capacity based, the core's own count) |
| 244 | pub memory_bytes: u64, |
| 245 | } |
| 246 | |
| 247 | /// Train a fresh core for `mode` (0 reflex, 1 nearest, 2 perceptron), dropping the previous one |
| 248 | /// and returning the heap to the state right after the case index. 0 ok; -1 bad mode or no card; |
| 249 | /// -2 training refused. |
| 250 | /// |
| 251 | /// # Safety |
| 252 | /// `out` null or writable. |
| 253 | #[no_mangle] |
| 254 | pub unsafe extern "C" fn aienos_allen_train(mode: u32, out: *mut TrainInfo) -> i32 { |
| 255 | let s = st(); |
| 256 | s.session = None; |
| 257 | let (Some(m), Some(mark)) = (runner::mode_of(mode), s.after_cases) else { |
| 258 | return -1; |
| 259 | }; |
| 260 | HEAP.0.reset_to(mark); |
| 261 | HEAP.0.reset_peaks(); |
| 262 | let t0 = ticks(); |
| 263 | let r = Session::train(m); |
| 264 | let dt = ticks().wrapping_sub(t0); |
| 265 | match r { |
| 266 | Ok(sess) => { |
| 267 | if !out.is_null() { |
| 268 | *out = TrainInfo { |
| 269 | ticks: dt, |
| 270 | examples: sess.examples() as u64, |
| 271 | exemplars: sess.exemplars() as u64, |
| 272 | memory_bytes: sess.memory_bytes() as u64, |
| 273 | }; |
| 274 | } |
| 275 | s.session = Some(sess); |
| 276 | 0 |
| 277 | } |
| 278 | Err(_) => -2, |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | /// What one decision reports. `#[repr(C)]`, mirrored in `core/allen.c`. |
| 283 | #[repr(C)] |
| 284 | pub struct DecideInfo { |
| 285 | /// bytes of the line written (no NUL) |
| 286 | pub len: u64, |
| 287 | /// offset of the decision JSON in the line |
| 288 | pub json_off: u64, |
| 289 | /// counter ticks of the decision itself (turn split + core.decide + JSON), not the line copy |
| 290 | pub ticks: u64, |
| 291 | /// 1 when the heap went back to its pre-decision mark |
| 292 | pub heap_reset: u64, |
| 293 | } |
| 294 | |
| 295 | /// Decide case `i` with the trained core and write `ALLEN_D <mode> <id> <json>` into `line` |
| 296 | /// (`cap` bytes, NUL-terminated). 0 ok; -1 no core/case; -2 line buffer too small. |
| 297 | /// |
| 298 | /// # Safety |
| 299 | /// `line[..cap]` writable; `out` null or writable. |
| 300 | #[no_mangle] |
| 301 | pub unsafe extern "C" fn aienos_allen_decide( |
| 302 | i: u32, |
| 303 | line: *mut u8, |
| 304 | cap: usize, |
| 305 | out: *mut DecideInfo, |
| 306 | ) -> i32 { |
| 307 | let s = st(); |
| 308 | let (Some(sess), Some(cases)) = (s.session.as_ref(), s.cases.as_ref()) else { |
| 309 | return -1; |
| 310 | }; |
| 311 | let Some(c) = cases.get(i as usize).copied() else { |
| 312 | return -1; |
| 313 | }; |
| 314 | let card = core::slice::from_raw_parts(s.card, s.card_len); |
| 315 | // card::parse admitted printable ASCII only: both ranges are valid UTF-8. |
| 316 | let (Ok(id), Ok(turns)) = ( |
| 317 | core::str::from_utf8(&card[c.id.0..c.id.1]), |
| 318 | core::str::from_utf8(&card[c.turns.0..c.turns.1]), |
| 319 | ) else { |
| 320 | return -1; |
| 321 | }; |
| 322 | let mark = HEAP.0.mark(); |
| 323 | let (json_off, dt, len) = { |
| 324 | let t0 = ticks(); |
| 325 | let json = sess.decide_json(turns); |
| 326 | let dt = ticks().wrapping_sub(t0); |
| 327 | let off = runner::line(&mut s.line, sess.mode(), id, &json); |
| 328 | (off, dt, s.line.len()) |
| 329 | }; |
| 330 | if len + 1 > cap { |
| 331 | return -2; |
| 332 | } |
| 333 | core::ptr::copy_nonoverlapping(s.line.as_ptr(), line, len); |
| 334 | *line.add(len) = 0; |
| 335 | let reset = HEAP.0.reset_to(mark); |
| 336 | if !out.is_null() { |
| 337 | *out = DecideInfo { |
| 338 | len: len as u64, |
| 339 | json_off: json_off as u64, |
| 340 | ticks: dt, |
| 341 | heap_reset: reset as u64, |
| 342 | }; |
| 343 | } |
| 344 | 0 |
| 345 | } |
| 346 | |
| 347 | /// Kind of the open card: 0 exam (`ALLEN_D` lines through [`aienos_allen_decide`]), 1 route |
| 348 | /// (`ALLEN_P` lines through [`aienos_allen_route`]), -1 no card open. |
| 349 | #[no_mangle] |
| 350 | pub extern "C" fn aienos_allen_card_kind() -> i32 { |
| 351 | let s = st(); |
| 352 | match (s.cases.is_some(), s.routes.is_some()) { |
| 353 | (true, _) => 0, |
| 354 | (_, true) => 1, |
| 355 | _ => -1, |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | /// What one route proposal reports. `#[repr(C)]`, mirrored in `core/allen.c`. |
| 360 | #[repr(C)] |
| 361 | pub struct RouteInfo { |
| 362 | /// bytes of the line written (no NUL) |
| 363 | pub len: u64, |
| 364 | /// offset of the proposal JSON in the line |
| 365 | pub json_off: u64, |
| 366 | /// counter ticks of the proposal itself (escape decode + turn split + core.decide + route |
| 367 | /// policy + PST1 digest when a Spark route + JSON), not the line copy |
| 368 | pub ticks: u64, |
| 369 | /// 1 when the heap went back to its pre-proposal mark |
| 370 | pub heap_reset: u64, |
| 371 | /// `allen_reflex::route::Route` index |
| 372 | pub route: u32, |
| 373 | /// the core's `Action` index |
| 374 | pub label: u32, |
| 375 | /// 1 owner, 0 guest (from the card line) |
| 376 | pub owner: u32, |
| 377 | /// 1 ready, 0 not ready (fallback named in the JSON) |
| 378 | pub ready: u32, |
| 379 | } |
| 380 | |
| 381 | /// Propose a route for request `i` of a route card with the trained core and write |
| 382 | /// `ALLEN_P <mode> <id> <json>` into `line` (`cap` bytes, NUL-terminated). `caps` are the image's |
| 383 | /// real capabilities (bit 1 store, 2 desk, 4 local model, 8 Spark link): the card cannot claim |
| 384 | /// any. Request id is `i + 1`. 0 ok; -1 no core/route card/request; -2 line buffer too small. |
| 385 | /// |
| 386 | /// # Safety |
| 387 | /// `line[..cap]` writable; `out` null or writable. |
| 388 | #[no_mangle] |
| 389 | pub unsafe extern "C" fn aienos_allen_route( |
| 390 | i: u32, |
| 391 | caps: u32, |
| 392 | line: *mut u8, |
| 393 | cap: usize, |
| 394 | out: *mut RouteInfo, |
| 395 | ) -> i32 { |
| 396 | let s = st(); |
| 397 | let (Some(sess), Some(routes)) = (s.session.as_ref(), s.routes.as_ref()) else { |
| 398 | return -1; |
| 399 | }; |
| 400 | let Some(r) = routes.get(i as usize).copied() else { |
| 401 | return -1; |
| 402 | }; |
| 403 | let card = core::slice::from_raw_parts(s.card, s.card_len); |
| 404 | // card::parse_route admitted printable ASCII only: both ranges are valid UTF-8. |
| 405 | let (Ok(id), Ok(turns)) = ( |
| 406 | core::str::from_utf8(&card[r.id.0..r.id.1]), |
| 407 | core::str::from_utf8(&card[r.turns.0..r.turns.1]), |
| 408 | ) else { |
| 409 | return -1; |
| 410 | }; |
| 411 | let mark = HEAP.0.mark(); |
| 412 | let (json_off, dt, len, facts) = { |
| 413 | let t0 = ticks(); |
| 414 | let (json, facts) = sess.propose_json(&r, turns, i as u64 + 1, caps); |
| 415 | let dt = ticks().wrapping_sub(t0); |
| 416 | let off = runner::route_line(&mut s.line, sess.mode(), id, &json); |
| 417 | (off, dt, s.line.len(), facts) |
| 418 | }; |
| 419 | if len + 1 > cap { |
| 420 | return -2; |
| 421 | } |
| 422 | core::ptr::copy_nonoverlapping(s.line.as_ptr(), line, len); |
| 423 | *line.add(len) = 0; |
| 424 | let reset = HEAP.0.reset_to(mark); |
| 425 | if !out.is_null() { |
| 426 | *out = RouteInfo { |
| 427 | len: len as u64, |
| 428 | json_off: json_off as u64, |
| 429 | ticks: dt, |
| 430 | heap_reset: reset as u64, |
| 431 | route: facts.route, |
| 432 | label: facts.label, |
| 433 | owner: facts.owner, |
| 434 | ready: facts.ready, |
| 435 | }; |
| 436 | } |
| 437 | 0 |
| 438 | } |
| 439 | |
| 440 | /// Drop the trained core and the case index; the heap is back at its start (if all was freed). |
| 441 | #[no_mangle] |
| 442 | pub extern "C" fn aienos_allen_close() { |
| 443 | let s = st(); |
| 444 | s.session = None; |
| 445 | s.cases = None; |
| 446 | s.routes = None; |
| 447 | s.line = String::new(); |
| 448 | s.after_cases = None; |
| 449 | s.card = core::ptr::null(); |
| 450 | s.card_len = 0; |
| 451 | } |