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 / crates / aienos-kernel / src / fatal.rs

478 lines · 16344 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//! Fatal-path capture for early boot: CPU exceptions and panics.
17//!
18//! After firmware exit the firmware's exception vectors are still installed,
19//! and on a fault they typically print to a serial port and hang, leaving no
20//! evidence. `install_exception_vectors` replaces them with AIENOS vectors
21//! that switch to a dedicated stack, read the syndrome registers, and call a
22//! registered hook (which reports the fault and resets). The decoding is pure
23//! and host-tested; the vectors and register reads exist only on AArch64.
24
25use core::fmt;
26use core::sync::atomic::{AtomicUsize, Ordering};
27
28/// Registers captured when an exception is taken.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct FaultInfo {
31 /// Vector slot 0..=15 (origin * 4 + kind).
32 pub vector: u64,
33 pub exception_level: u8,
34 pub esr: u64,
35 pub elr: u64,
36 pub far: u64,
37 pub spsr: u64,
38}
39
40/// Purely decoded ESR_EL1/ESR_EL2 fields used by reports and host tests.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub struct EsrInfo {
43 pub exception_class: u8,
44 pub iss: u32,
45 pub abort: Option<AbortSyndrome>,
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub struct AbortSyndrome {
50 pub instruction: bool,
51 pub fault_status: u8,
52 pub stage1_page_table_walk: bool,
53 pub cache_maintenance: bool,
54 pub external_abort: bool,
55 pub not_valid: bool,
56 pub write: bool,
57 /// Load/store detail, present only for data aborts with ISV (ISS bit 24) set.
58 pub access: Option<AccessSyndrome>,
59}
60
61/// SRT/SAS/SSE from a data-abort ISS; architecturally valid only when ISV = 1.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct AccessSyndrome {
64 pub register: u8,
65 pub access_size: u8,
66 pub sign_extend: bool,
67}
68
69/// Decode the common ESR layout without reading any system registers.
70pub const fn decode_esr(esr: u64) -> EsrInfo {
71 let ec = ((esr >> 26) & 0x3f) as u8;
72 let iss = (esr & 0x1ff_ffff) as u32;
73 let instruction = ec == 0x20 || ec == 0x21;
74 let data = ec == 0x24 || ec == 0x25;
75 let abort = if instruction || data {
76 Some(AbortSyndrome {
77 instruction,
78 fault_status: (iss & 0x3f) as u8,
79 stage1_page_table_walk: iss & (1 << 7) != 0,
80 cache_maintenance: iss & (1 << 8) != 0,
81 external_abort: iss & (1 << 9) != 0,
82 not_valid: iss & (1 << 10) != 0,
83 write: !instruction && iss & (1 << 6) != 0,
84 access: if data && iss & (1 << 24) != 0 {
85 Some(AccessSyndrome {
86 register: ((iss >> 16) & 0x1f) as u8,
87 access_size: ((iss >> 22) & 0x3) as u8,
88 sign_extend: iss & (1 << 21) != 0,
89 })
90 } else {
91 None
92 },
93 })
94 } else {
95 None
96 };
97 EsrInfo {
98 exception_class: ec,
99 iss,
100 abort,
101 }
102}
103
104impl FaultInfo {
105 pub fn kind(&self) -> &'static str {
106 ["sync", "irq", "fiq", "serror"][(self.vector % 4) as usize]
107 }
108
109 pub fn origin(&self) -> &'static str {
110 [
111 "current_el_sp0",
112 "current_el_spx",
113 "lower_el_a64",
114 "lower_el_a32",
115 ][((self.vector / 4) % 4) as usize]
116 }
117
118 /// Exception class, ESR bits 31:26.
119 pub fn exception_class(&self) -> u8 {
120 ((self.esr >> 26) & 0x3f) as u8
121 }
122}
123
124/// Human-readable name for an ESR exception class.
125pub fn describe_exception_class(ec: u8) -> &'static str {
126 match ec {
127 0x00 => "unknown reason",
128 0x01 => "trapped WFI/WFE",
129 0x0e => "illegal execution state",
130 0x15 => "SVC (AArch64)",
131 0x16 => "HVC (AArch64)",
132 0x17 => "SMC (AArch64)",
133 0x18 => "trapped system register access",
134 0x20 => "instruction abort from lower EL",
135 0x21 => "instruction abort at current EL",
136 0x22 => "PC alignment fault",
137 0x24 => "data abort from lower EL",
138 0x25 => "data abort at current EL",
139 0x26 => "SP alignment fault",
140 0x2f => "SError",
141 0x3c => "BRK instruction",
142 _ => "other",
143 }
144}
145
146impl fmt::Display for FaultInfo {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 writeln!(f, "fault_kind: {} from {}", self.kind(), self.origin())?;
149 writeln!(f, "fault_el: EL{}", self.exception_level)?;
150 writeln!(
151 f,
152 "fault_class: {:#04x} ({})",
153 self.exception_class(),
154 describe_exception_class(self.exception_class())
155 )?;
156 writeln!(f, "fault_esr: {:#x}", self.esr)?;
157 let decoded = decode_esr(self.esr);
158 writeln!(f, "fault_iss: {:#x}", decoded.iss)?;
159 if let Some(abort) = decoded.abort {
160 writeln!(
161 f,
162 "fault_type: {}",
163 if abort.instruction {
164 "instruction_abort"
165 } else {
166 "data_abort"
167 }
168 )?;
169 writeln!(f, "fault_status: {:#x}", abort.fault_status)?;
170 if !abort.instruction {
171 writeln!(f, "fault_write: {}", if abort.write { "yes" } else { "no" })?;
172 }
173 }
174 writeln!(f, "fault_elr: {:#x}", self.elr)?;
175 writeln!(f, "fault_far: {:#x}", self.far)?;
176 writeln!(f, "fault_spsr: {:#x}", self.spsr)
177 }
178}
179
180/// Called for a fault once vectors are installed. Must not return.
181pub type FaultHook = fn(&FaultInfo) -> !;
182
183#[cfg_attr(not(target_arch = "aarch64"), allow(dead_code))]
184static HOOK: AtomicUsize = AtomicUsize::new(0);
185static IRQ_HOOK: AtomicUsize = AtomicUsize::new(0);
186
187pub fn set_irq_hook(hook: extern "C" fn()) {
188 IRQ_HOOK.store(hook as usize, Ordering::SeqCst);
189}
190
191#[cfg_attr(not(target_arch = "aarch64"), allow(dead_code))]
192pub fn call_irq_hook() {
193 let raw = IRQ_HOOK.load(Ordering::SeqCst);
194 if raw != 0 {
195 let hook: extern "C" fn() = unsafe { core::mem::transmute(raw) };
196 hook();
197 }
198}
199
200pub fn set_fault_hook(hook: FaultHook) {
201 HOOK.store(hook as usize, Ordering::SeqCst);
202}
203
204#[cfg_attr(not(target_arch = "aarch64"), allow(dead_code))]
205fn call_hook(info: &FaultInfo) -> ! {
206 let raw = HOOK.load(Ordering::SeqCst);
207 if raw != 0 {
208 // SAFETY: only `set_fault_hook` stores into HOOK, always a FaultHook.
209 let hook: FaultHook = unsafe { core::mem::transmute::<usize, FaultHook>(raw) };
210 hook(info);
211 }
212 crate::arch::aarch64::halt()
213}
214
215#[cfg(target_arch = "aarch64")]
216mod vectors {
217 use super::{call_hook, FaultInfo};
218 use crate::arch::aarch64::current_el;
219
220 const STACK_BYTES: usize = 16 * 1024;
221
222 #[repr(C, align(16))]
223 struct ExceptionStack([u8; STACK_BYTES]);
224
225 static mut EXCEPTION_STACK: ExceptionStack = ExceptionStack([0; STACK_BYTES]);
226
227 macro_rules! read_sysreg {
228 ($name:literal) => {{
229 let v: u64;
230 // SAFETY: reading a syndrome register of the current EL has no side effects.
231 unsafe {
232 core::arch::asm!(concat!("mrs {0}, ", $name), out(reg) v, options(nomem, nostack));
233 }
234 v
235 }};
236 }
237
238 #[no_mangle]
239 extern "C" fn aienos_exception_handler(vector: u64) -> ! {
240 let el = current_el();
241 let info = if el == 2 {
242 FaultInfo {
243 vector,
244 exception_level: el,
245 esr: read_sysreg!("esr_el2"),
246 elr: read_sysreg!("elr_el2"),
247 far: read_sysreg!("far_el2"),
248 spsr: read_sysreg!("spsr_el2"),
249 }
250 } else {
251 FaultInfo {
252 vector,
253 exception_level: el,
254 esr: read_sysreg!("esr_el1"),
255 elr: read_sysreg!("elr_el1"),
256 far: read_sysreg!("far_el1"),
257 spsr: read_sysreg!("spsr_el1"),
258 }
259 };
260 call_hook(&info)
261 }
262
263 // Sixteen 128-byte entries on a 2 KiB boundary. Each loads its slot number
264 // and jumps to a common trampoline that moves onto a dedicated stack, so a
265 // fault caused by a bad stack still reaches the handler.
266 core::arch::global_asm!(
267 ".balign 2048",
268 ".global aienos_exception_vectors",
269 "aienos_exception_vectors:",
270 ".irp slot, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15",
271 ".balign 128",
272 // Slot 5: IRQ at EL1h. Slot 9: IRQ from lower-EL AArch64 (EL0 tasks),
273 // which saves and restores the EL0 context through the same frame.
274 ".if \\slot == 5",
275 "b aienos_irq_trampoline",
276 ".elseif \\slot == 9",
277 "b aienos_irq_trampoline",
278 ".elseif \\slot == 8",
279 "b aienos_lower_el_sync_trampoline",
280 ".else",
281 "mov x0, #\\slot",
282 "b aienos_exception_trampoline",
283 ".endif",
284 ".endr",
285 // IRQ entry: save complete interrupted context into TrapFrame on the current stack:
286 // x0-x30, pad, ELR/SPSR_EL1, FPCR/FPSR, and SIMD/FP q0-q31. Frame: 800 bytes, 16-byte aligned.
287 "aienos_irq_trampoline:",
288 "sub sp, sp, #800",
289 "stp x0, x1, [sp, #0]",
290 "stp x2, x3, [sp, #16]",
291 "stp x4, x5, [sp, #32]",
292 "stp x6, x7, [sp, #48]",
293 "stp x8, x9, [sp, #64]",
294 "stp x10, x11, [sp, #80]",
295 "stp x12, x13, [sp, #96]",
296 "stp x14, x15, [sp, #112]",
297 "stp x16, x17, [sp, #128]",
298 "stp x18, x19, [sp, #144]",
299 "stp x20, x21, [sp, #160]",
300 "stp x22, x23, [sp, #176]",
301 "stp x24, x25, [sp, #192]",
302 "stp x26, x27, [sp, #208]",
303 "stp x28, x29, [sp, #224]",
304 "str x30, [sp, #240]",
305 "str xzr, [sp, #248]",
306 "mrs x0, elr_el1",
307 "mrs x1, spsr_el1",
308 "stp x0, x1, [sp, #256]",
309 "mrs x0, fpcr",
310 "mrs x1, fpsr",
311 "stp x0, x1, [sp, #272]",
312 "stp q0, q1, [sp, #288]",
313 "stp q2, q3, [sp, #320]",
314 "stp q4, q5, [sp, #352]",
315 "stp q6, q7, [sp, #384]",
316 "stp q8, q9, [sp, #416]",
317 "stp q10, q11, [sp, #448]",
318 "stp q12, q13, [sp, #480]",
319 "stp q14, q15, [sp, #512]",
320 "stp q16, q17, [sp, #544]",
321 "stp q18, q19, [sp, #576]",
322 "stp q20, q21, [sp, #608]",
323 "stp q22, q23, [sp, #640]",
324 "stp q24, q25, [sp, #672]",
325 "stp q26, q27, [sp, #704]",
326 "stp q28, q29, [sp, #736]",
327 "stp q30, q31, [sp, #768]",
328 "mov x0, sp",
329 "bl {irq_dispatcher}",
330 "mov sp, x0",
331 "ldp q0, q1, [sp, #288]",
332 "ldp q2, q3, [sp, #320]",
333 "ldp q4, q5, [sp, #352]",
334 "ldp q6, q7, [sp, #384]",
335 "ldp q8, q9, [sp, #416]",
336 "ldp q10, q11, [sp, #448]",
337 "ldp q12, q13, [sp, #480]",
338 "ldp q14, q15, [sp, #512]",
339 "ldp q16, q17, [sp, #544]",
340 "ldp q18, q19, [sp, #576]",
341 "ldp q20, q21, [sp, #608]",
342 "ldp q22, q23, [sp, #640]",
343 "ldp q24, q25, [sp, #672]",
344 "ldp q26, q27, [sp, #704]",
345 "ldp q28, q29, [sp, #736]",
346 "ldp q30, q31, [sp, #768]",
347 "ldp x0, x1, [sp, #272]",
348 "msr fpcr, x0",
349 "msr fpsr, x1",
350 "ldp x0, x1, [sp, #256]",
351 "msr elr_el1, x0",
352 "msr spsr_el1, x1",
353 "ldp x2, x3, [sp, #16]",
354 "ldp x4, x5, [sp, #32]",
355 "ldp x6, x7, [sp, #48]",
356 "ldp x8, x9, [sp, #64]",
357 "ldp x10, x11, [sp, #80]",
358 "ldp x12, x13, [sp, #96]",
359 "ldp x14, x15, [sp, #112]",
360 "ldp x16, x17, [sp, #128]",
361 "ldp x18, x19, [sp, #144]",
362 "ldp x20, x21, [sp, #160]",
363 "ldp x22, x23, [sp, #176]",
364 "ldp x24, x25, [sp, #192]",
365 "ldp x26, x27, [sp, #208]",
366 "ldp x28, x29, [sp, #224]",
367 "ldr x30, [sp, #240]",
368 "ldp x0, x1, [sp, #0]",
369 "add sp, sp, #800",
370 "eret",
371 "aienos_exception_trampoline:",
372 "adrp x1, {stack}",
373 "add x1, x1, :lo12:{stack}",
374 "add x1, x1, #{stack_bytes_hi}, lsl #12",
375 "mov sp, x1",
376 "bl {handler}",
377 "1: wfi",
378 "b 1b",
379 stack = sym EXCEPTION_STACK,
380 stack_bytes_hi = const STACK_BYTES >> 12,
381 handler = sym aienos_exception_handler,
382 irq_dispatcher = sym crate::thread::aienos_irq_dispatcher,
383 );
384
385 extern "C" {
386 static aienos_exception_vectors: u8;
387 }
388
389 pub fn install() {
390 let base = core::ptr::addr_of!(aienos_exception_vectors) as u64;
391 // SAFETY: VBAR of the current EL points at a valid, 2 KiB aligned table.
392 unsafe {
393 if current_el() == 2 {
394 core::arch::asm!("msr vbar_el2, {0}", "isb", in(reg) base, options(nostack));
395 } else {
396 core::arch::asm!("msr vbar_el1, {0}", "isb", in(reg) base, options(nostack));
397 }
398 }
399 }
400}
401
402/// Replace the firmware's exception vectors with AIENOS ones. Call only after
403/// firmware boot services have exited; firmware may rely on its own vectors
404/// until then.
405pub fn install_exception_vectors() {
406 #[cfg(target_arch = "aarch64")]
407 vectors::install();
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413 use std::string::ToString;
414
415 #[test]
416 fn decodes_vector_slot_and_exception_class() {
417 let data_abort = FaultInfo {
418 vector: 4,
419 exception_level: 2,
420 esr: 0x9600_0045, // EC 0x25, data abort at current EL
421 elr: 0x8000_1000,
422 far: 0xdead_0000,
423 spsr: 0x3c9,
424 };
425 assert_eq!(data_abort.kind(), "sync");
426 assert_eq!(data_abort.origin(), "current_el_spx");
427 assert_eq!(data_abort.exception_class(), 0x25);
428 let text = data_abort.to_string();
429 assert!(
430 text.contains("fault_class: 0x25 (data abort at current EL)"),
431 "{text}"
432 );
433 assert!(text.contains("fault_far: 0xdead0000"), "{text}");
434
435 let serror = FaultInfo {
436 vector: 7,
437 esr: 0xbe00_0000,
438 ..data_abort
439 };
440 assert_eq!(serror.kind(), "serror");
441 assert_eq!(describe_exception_class(serror.exception_class()), "SError");
442 }
443
444 #[test]
445 fn decodes_abort_iss_fields_without_register_access() {
446 let decoded = decode_esr(0x9600_0045);
447 assert_eq!(decoded.exception_class, 0x25);
448 assert_eq!(decoded.iss, 0x45);
449 assert_eq!(decoded.abort.unwrap().fault_status, 5);
450 assert!(decoded.abort.unwrap().write);
451
452 let instruction = decode_esr((0x21u64 << 26) | 0x15);
453 assert!(instruction.abort.unwrap().instruction);
454 assert!(!instruction.abort.unwrap().write);
455 assert_eq!(decode_esr(0).abort, None);
456 }
457
458 #[test]
459 fn access_syndrome_only_when_isv_set() {
460 // Data abort, same EL, ISV=0: SRT/SAS/SSE bits are not meaningful.
461 let no_isv = decode_esr((0x25u64 << 26) | (7 << 16) | 0x04);
462 assert_eq!(no_isv.abort.unwrap().access, None);
463 // ISV=1, SAS=0b11 (64-bit), SSE=1, SRT=x7, WnR=0, DFSC=0x07.
464 let isv =
465 decode_esr((0x25u64 << 26) | (1 << 24) | (0b11 << 22) | (1 << 21) | (7 << 16) | 0x07);
466 let access = isv.abort.unwrap().access.unwrap();
467 assert_eq!(
468 (access.register, access.access_size, access.sign_extend),
469 (7, 3, true)
470 );
471 assert!(!isv.abort.unwrap().write);
472 // Instruction aborts never carry an access syndrome, even with bit 24 set.
473 let inst = decode_esr((0x21u64 << 26) | (1 << 24) | 0x0f);
474 assert_eq!(inst.abort.unwrap().access, None);
475 // Non-abort classes (e.g. SVC, EC 0x15) decode no abort detail.
476 assert_eq!(decode_esr(0x15u64 << 26).abort, None);
477 }
478}