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

GitHub aien-dev/aienux#42 (code only)

closed derived c7ea076035ea97d4 #42

Imported from GitHub aien-dev/aienux#42 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base d0164f30d6078bcb4c90c7f853c6c524af9a5124 · Head 198b7d50048aee9e613d13128a998dccb02ad335

Apply it

git checkout -b patch-c7ea076035ea97d4 d0164f30d6078bcb4c90c7f853c6c524af9a5124
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/c7ea076035ea97d4.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aienux
42
198b7d50048aee9e613d13128a998dccb02ad335
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":42,"url":"https://github.com/aien-dev/aienux/pull/42","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:24Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/crates/aienos-boot/src/handoff.rs b/crates/aienos-boot/src/handoff.rs
index 39356f69..bc0b3571 100644
--- a/crates/aienos-boot/src/handoff.rs
+++ b/crates/aienos-boot/src/handoff.rs
@@ -24,9 +24,9 @@
 use aienos_kernel::acpi;
 use aienos_kernel::arch::aarch64::{
     counter_frequency_hz, counter_ticks, midr_el1, midr_part, mpidr_el1, psci_system_reset,
-    EarlyUart, SPARK_16550_UART_BASE,
 };
 use aienos_kernel::boot::{BootTiming, MemoryMapSummary};
+use aienos_kernel::console::EarlyConsole;
 use aienos_kernel::display::{FramebufferInfo, PixelOrder, Screen, ACCENT, FOREGROUND};
 use aienos_kernel::fatal::{self, FaultInfo};
 use aienos_kernel::report::ReportBuf;
@@ -55,7 +55,12 @@ const REPORT_VENDOR: VariableVendor = VariableVendor(guid!("a1e05b0e-7c3d-4f51-9
 /// ADR 0008 bounds on the post-handoff firmware variable.
 const MAX_VAR_WRITES: u8 = 3;
 const MAX_VAR_BYTES: usize = 3072;
-const RESTART_AFTER_SECS: u64 = 30;
+/// Countdown before reset; `AIENOS_RESTART_SECS` at build time shortens it for emulator tests.
+fn restart_after_secs() -> u64 {
+    option_env!("AIENOS_RESTART_SECS")
+        .and_then(|s| s.parse().ok())
+        .unwrap_or(30)
+}
 const ERROR: (u8, u8, u8) = (0xff, 0x6b, 0x6b);
 
 type Report = ReportBuf<MAX_VAR_BYTES>;
@@ -91,7 +96,8 @@ static STAGE: AtomicU8 = AtomicU8::new(FIRMWARE_ENTRY);
 static EXITED: AtomicBool = AtomicBool::new(false);
 static IN_FATAL: AtomicBool = AtomicBool::new(false);
 static VAR_WRITES: AtomicU8 = AtomicU8::new(0);
-static ON_SPARK: AtomicBool = AtomicBool::new(false);
+/// Serial console from the firmware SPCR table (independent of GB10 discovery).
+static CONSOLE: SpinLock<Option<acpi::UartKind>> = SpinLock::new(None);
 static FREQUENCY_HZ: AtomicU64 = AtomicU64::new(0);
 static FRAMEBUFFER: SpinLock<Option<FramebufferInfo>> = SpinLock::new(None);
 
@@ -214,32 +220,94 @@ unsafe fn table_at<'a>(addr: usize) -> Option<&'a [u8]> {
     Some(unsafe { core::slice::from_raw_parts(addr as *const u8, len) })
 }
 
-/// Core inventory from the firmware MADT (RSDP, then XSDT, then "APIC").
-fn discover_cpu_topology(boot_mpidr: u64) -> Option<acpi::CpuTopology> {
-    let rsdp = uefi::system::with_config_table(|entries| {
+/// Firmware ACPI facts read before exit: core inventory (MADT) and the serial
+/// console (SPCR), found by walking RSDP, then XSDT.
+#[derive(Default)]
+struct AcpiFacts {
+    cpu: Option<acpi::CpuTopology>,
+    spcr: Option<acpi::SpcrConsole>,
+}
+
+fn discover_acpi(boot_mpidr: u64) -> AcpiFacts {
+    let mut facts = AcpiFacts::default();
+    let Some(rsdp) = uefi::system::with_config_table(|entries| {
         entries
             .iter()
             .find(|e| e.guid == ConfigTableEntry::ACPI2_GUID)
             .map(|e| e.address as usize)
-    })?;
+    }) else {
+        return facts;
+    };
     // SAFETY: firmware published this ACPI 2.0 RSDP, which is 36 bytes long.
     let rsdp = unsafe { core::slice::from_raw_parts(rsdp as *const u8, 36) };
     if &rsdp[..8] != b"RSD PTR " {
-        return None;
+        return facts;
     }
-    let xsdt_addr = u64::from_le_bytes(rsdp[24..32].try_into().ok()?) as usize;
+    let Some(xsdt_addr) = rsdp[24..32].try_into().ok().map(u64::from_le_bytes) else {
+        return facts;
+    };
     // SAFETY: the RSDP points at the XSDT; its checksum is validated below.
-    let xsdt = acpi::checked_table(unsafe { table_at(xsdt_addr) }?, b"XSDT").ok()?;
+    let Some(xsdt) = (unsafe { table_at(xsdt_addr as usize) })
+        .and_then(|t| acpi::checked_table(t, b"XSDT").ok())
+    else {
+        return facts;
+    };
     for addr in acpi::xsdt_entries(xsdt) {
         // SAFETY: XSDT entries point at firmware ACPI tables.
         let Some(table) = (unsafe { table_at(addr as usize) }) else {
             continue;
         };
-        if &table[..4] == b"APIC" {
-            return acpi::madt_cpu_topology_for(table, Some(boot_mpidr)).ok();
+        match &table[..4] {
+            b"APIC" => facts.cpu = acpi::madt_cpu_topology_for(table, Some(boot_mpidr)).ok(),
+            b"SPCR" => facts.spcr = acpi::spcr_console(table).ok(),
+            _ => {}
         }
     }
-    None
+    facts
+}
+
+fn write_uart_line(out: &mut impl Write, spcr: Option<acpi::SpcrConsole>) {
+    let _ = match spcr {
+        None => writeln!(out, "uart: none (no SPCR)"),
+        Some(s) => match s.kind() {
+            acpi::UartKind::Ns16550Mmio32(base) => {
+                writeln!(
+                    out,
+                    "uart: 16550 mmio32 at {base:#x} (spcr type {:#04x})",
+                    s.interface_type
+                )
+            }
+            acpi::UartKind::Pl011(base) => {
+                writeln!(
+                    out,
+                    "uart: pl011 at {base:#x} (spcr type {:#04x})",
+                    s.interface_type
+                )
+            }
+            acpi::UartKind::Unsupported => writeln!(
+                out,
+                "uart: unsupported (spcr type {:#04x}, space {}, width {})",
+                s.interface_type, s.address_space, s.register_bit_width
+            ),
+        },
+    };
+}
+
+/// Send text to the SPCR console, bounded. Returns the outcome for the report.
+fn send_to_console(text: &str) -> &'static str {
+    let kind = CONSOLE.try_lock().and_then(|k| *k);
+    match kind.and_then(EarlyConsole::from_kind) {
+        Some(console) => {
+            console.write_str("\n");
+            console.write_str(text);
+            if console.is_dead() {
+                "no response"
+            } else {
+                "sent"
+            }
+        }
+        None => "no drivable console",
+    }
 }
 
 /// Geometry of the display mode the firmware already configured.
@@ -280,14 +348,9 @@ fn discover_framebuffer() -> Option<FramebufferInfo> {
 fn save_report_file(text: &str) -> uefi::Result {
     let mut fs = uefi::boot::get_image_file_system(uefi::boot::image_handle())?;
     let mut root = fs.open_volume()?;
-    root.open(
-        cstr16!("\\EFI\\AIENOS"),
-        FileMode::CreateReadWrite,
-        FileAttribute::DIRECTORY,
-    )?;
     let path = cstr16!("\\EFI\\AIENOS\\BOOTREPORT.TXT");
     if let Ok(old) = root.open(path, FileMode::ReadWrite, FileAttribute::empty()) {
-        old.delete()?;
+        let _ = old.delete();
     }
     let mut file = root
         .open(path, FileMode::CreateReadWrite, FileAttribute::empty())?
@@ -378,13 +441,13 @@ fn finish(mut screen: Option<Screen>) -> ! {
         Some(s) => {
             let _ = writeln!(s);
             s.set_color(ACCENT);
-            for remaining in (1..=RESTART_AFTER_SECS).rev() {
+            for remaining in (1..=restart_after_secs()).rev() {
                 s.clear_row();
                 let _ = write!(s, "restarting in {remaining} s");
                 wait_seconds(1);
             }
         }
-        None => wait_seconds(RESTART_AFTER_SECS),
+        None => wait_seconds(restart_after_secs()),
     }
     reset_after_exit(Status::SUCCESS)
 }
@@ -407,7 +470,7 @@ fn fatal_report(kind: &str, detail: &dyn Fn(&mut Report)) -> ! {
     if !EXITED.load(Ordering::SeqCst) {
         uefi::println!("{}", report.as_str());
         let _ = save_report_file(report.as_str());
-        wait_seconds(RESTART_AFTER_SECS);
+        wait_seconds(restart_after_secs());
         uefi::runtime::reset(ResetType::COLD, Status::ABORTED, None)
     }
 
@@ -419,13 +482,11 @@ fn fatal_report(kind: &str, detail: &dyn Fn(&mut Report)) -> ! {
         s.set_color(FOREGROUND);
         let _ = write!(s, "{}", report.as_str());
     }
+    let uart = send_to_console(report.as_str());
+    let _ = writeln!(report, "uart_report: {uart}");
     let saved = save_report_var(report.as_bytes());
-    if ON_SPARK.load(Ordering::SeqCst) {
-        let uart = EarlyUart::new(SPARK_16550_UART_BASE);
-        uart.write_str("\n");
-        uart.write_str(report.as_str());
-    }
     if let Some(s) = screen.as_mut() {
+        let _ = writeln!(s, "uart_report: {uart}");
         match saved {
             Ok(n) => {
                 let _ = writeln!(s, "nvram_report: saved (write {n} of {MAX_VAR_WRITES})");
@@ -463,12 +524,13 @@ fn main() -> Status {
 
     stage(GB10_DISCOVERY);
     let gb10 = discover_gb10();
-    ON_SPARK.store(gb10.is_some(), Ordering::SeqCst);
 
     stage(ACPI_TOPOLOGY);
     let boot_midr = midr_el1();
     let boot_mpidr = mpidr_el1();
-    let cpu = discover_cpu_topology(boot_mpidr);
+    let acpi_facts = discover_acpi(boot_mpidr);
+    let cpu = acpi_facts.cpu;
+    *CONSOLE.lock() = acpi_facts.spcr.map(|s| s.kind());
 
     stage(FRAMEBUFFER_DISCOVERY);
     let framebuffer = discover_framebuffer();
@@ -506,6 +568,7 @@ fn main() -> Status {
         }
     }
     write_cpu(&mut pre, cpu, boot_midr, boot_mpidr);
+    write_uart_line(&mut pre, acpi_facts.spcr);
     match framebuffer {
         Some(f) => {
             let _ = writeln!(
@@ -520,9 +583,10 @@ fn main() -> Status {
     }
     let _ = writeln!(pre, "exiting firmware boot services");
     uefi::println!("{}", pre.as_str());
-    match save_report_file(pre.as_str()) {
+    let pre_file = save_report_file(pre.as_str()).map_err(|e| e.status());
+    match pre_file {
         Ok(()) => uefi::println!("report file: \\EFI\\AIENOS\\BOOTREPORT.TXT saved"),
-        Err(e) => uefi::println!("report file: not saved ({:?})", e.status()),
+        Err(status) => uefi::println!("report file: not saved ({status:?})"),
     }
     stage(PRE_EXIT_SAVED);
 
@@ -580,10 +644,16 @@ fn main() -> Status {
             let _ = writeln!(report, "progress_record: not saved ({e})");
         }
     }
-    if report.truncated() {
-        let _ = writeln!(report, "truncated: yes");
+    match pre_file {
+        Ok(()) => {
+            let _ = writeln!(report, "pre_exit_file: saved");
+        }
+        Err(status) => {
+            let _ = writeln!(report, "pre_exit_file: not saved ({status:?})");
+        }
     }
 
+    // Draw and send first, then record both outcomes in the saved report.
     let mut screen = screen();
     if let Some(s) = screen.as_mut() {
         s.clear();
@@ -593,6 +663,26 @@ fn main() -> Status {
         let _ = write!(s, "{}", report.as_str());
         stage(SCREEN_DRAWN);
     }
+    let uart = send_to_console(report.as_str());
+    stage(UART_SENT);
+
+    let mut outcomes = ReportBuf::<256>::new();
+    match framebuffer.filter(|_| screen.is_some()) {
+        Some(f) => {
+            let _ = writeln!(outcomes, "screen_report: drawn {}x{}", f.width, f.height);
+        }
+        None => {
+            let _ = writeln!(outcomes, "screen_report: unavailable");
+        }
+    }
+    let _ = writeln!(outcomes, "uart_report: {uart}");
+    let _ = write!(report, "{}", outcomes.as_str());
+    if report.truncated() {
+        let _ = writeln!(report, "truncated: yes");
+    }
+    if let Some(s) = screen.as_mut() {
+        let _ = write!(s, "{}", outcomes.as_str());
+    }
 
     let saved = save_report_var(report.as_bytes());
     stage(FINAL_SAVED);
@@ -607,24 +697,6 @@ fn main() -> Status {
         }
     }
 
-    if gb10.is_some() {
-        let uart = EarlyUart::new(SPARK_16550_UART_BASE);
-        uart.write_str("\n");
-        uart.write_str(report.as_str());
-        stage(UART_SENT);
-        if let Some(s) = screen.as_mut() {
-            let _ = writeln!(
-                s,
-                "uart_report: {}",
-                if uart.is_dead() {
-                    "no response"
-                } else {
-                    "sent"
-                }
-            );
-        }
-    }
-
     if !boot_ok {
         if let Some(s) = screen.as_mut() {
             s.set_color(ERROR);
diff --git a/crates/aienos-kernel/src/acpi.rs b/crates/aienos-kernel/src/acpi.rs
index c4db0f6c..e501cff4 100644
--- a/crates/aienos-kernel/src/acpi.rs
+++ b/crates/aienos-kernel/src/acpi.rs
@@ -108,6 +108,63 @@ impl CpuTopology {
     }
 }
 
+/// Serial console described by the ACPI SPCR table.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SpcrConsole {
+    /// SPCR interface type (0x00 16550, 0x03 PL011, 0x0e SBSA, 0x12 16550 with GAS).
+    pub interface_type: u8,
+    /// Generic Address Structure: 0 = system memory.
+    pub address_space: u8,
+    pub register_bit_width: u8,
+    /// GAS access size: 1 byte, 2 word, 3 dword, 4 qword.
+    pub access_size: u8,
+    pub base: u64,
+}
+
+/// Which early UART driver fits an SPCR console.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum UartKind {
+    /// 16550-compatible with 32-bit registers (4-byte stride), as on the DGX Spark.
+    Ns16550Mmio32(u64),
+    /// ARM PL011 or SBSA generic UART (PL011 register subset).
+    Pl011(u64),
+    /// Present but not drivable by the early console.
+    Unsupported,
+}
+
+impl SpcrConsole {
+    pub fn kind(&self) -> UartKind {
+        if self.address_space != 0 || self.base == 0 {
+            return UartKind::Unsupported;
+        }
+        match self.interface_type {
+            0x00 | 0x12 if self.access_size == 3 || self.register_bit_width == 32 => {
+                UartKind::Ns16550Mmio32(self.base)
+            }
+            0x03 | 0x0d | 0x0e => UartKind::Pl011(self.base),
+            _ => UartKind::Unsupported,
+        }
+    }
+}
+
+const SPCR_INTERFACE_TYPE: usize = 36;
+const SPCR_BASE_GAS: usize = 40;
+
+/// Reads the console from a validated SPCR table.
+pub fn spcr_console(spcr: &[u8]) -> Result<SpcrConsole, AcpiError> {
+    let spcr = checked_table(spcr, b"SPCR")?;
+    let gas = spcr
+        .get(SPCR_BASE_GAS..SPCR_BASE_GAS + 12)
+        .ok_or(AcpiError::Truncated)?;
+    Ok(SpcrConsole {
+        interface_type: spcr[SPCR_INTERFACE_TYPE],
+        address_space: gas[0],
+        register_bit_width: gas[1],
+        access_size: gas[3],
+        base: u64_at(gas, 4).ok_or(AcpiError::Truncated)?,
+    })
+}
+
 /// MPIDR affinity fields (Aff3, Aff2, Aff1, Aff0); other bits are flags.
 pub const MPIDR_AFFINITY_MASK: u64 = 0xff_00ff_ffff;
 
@@ -264,6 +321,47 @@ mod tests {
         assert_eq!(madt_cpu_topology(&zero_len), Err(AcpiError::BadEntry));
     }
 
+    fn spcr(interface_type: u8, space: u8, bit_width: u8, access: u8, base: u64) -> Vec<u8> {
+        let mut t = std::vec![0u8; 80];
+        t[..4].copy_from_slice(b"SPCR");
+        t[4..8].copy_from_slice(&80u32.to_le_bytes());
+        t[SPCR_INTERFACE_TYPE] = interface_type;
+        t[SPCR_BASE_GAS] = space;
+        t[SPCR_BASE_GAS + 1] = bit_width;
+        t[SPCR_BASE_GAS + 3] = access;
+        t[SPCR_BASE_GAS + 4..SPCR_BASE_GAS + 12].copy_from_slice(&base.to_le_bytes());
+        let sum = t.iter().fold(0u8, |s, b| s.wrapping_add(*b));
+        t[9] = 0u8.wrapping_sub(sum);
+        t
+    }
+
+    #[test]
+    fn spcr_selects_the_early_uart_driver() {
+        // DGX Spark style: 16550-compatible, 32-bit registers at 0x16A00000.
+        let spark = spcr_console(&spcr(0x12, 0, 32, 3, 0x16A0_0000)).unwrap();
+        assert_eq!(spark.kind(), UartKind::Ns16550Mmio32(0x16A0_0000));
+        // QEMU virt: ARM PL011 at 0x09000000.
+        let qemu = spcr_console(&spcr(0x03, 0, 32, 3, 0x0900_0000)).unwrap();
+        assert_eq!(qemu.kind(), UartKind::Pl011(0x0900_0000));
+        // Byte-wide 16550, I/O port space and unknown types are not drivable.
+        assert_eq!(
+            spcr_console(&spcr(0x00, 0, 8, 1, 0x3f8)).unwrap().kind(),
+            UartKind::Unsupported
+        );
+        assert_eq!(
+            spcr_console(&spcr(0x12, 1, 32, 3, 0x3f8)).unwrap().kind(),
+            UartKind::Unsupported
+        );
+        assert_eq!(
+            spcr_console(&spcr(0x20, 0, 32, 3, 0x1000)).unwrap().kind(),
+            UartKind::Unsupported
+        );
+        // A corrupted table is rejected.
+        let mut bad = spcr(0x03, 0, 32, 3, 0x0900_0000);
+        bad[50] ^= 1;
+        assert_eq!(spcr_console(&bad), Err(AcpiError::BadChecksum));
+    }
+
     #[test]
     fn reads_xsdt_entry_addresses() {
         let mut xsdt = std::vec![0u8; SDT_HEADER_LEN];
diff --git a/crates/aienos-kernel/src/console.rs b/crates/aienos-kernel/src/console.rs
new file mode 100644
index 00000000..509e13d3
--- /dev/null
+++ b/crates/aienos-kernel/src/console.rs
@@ -0,0 +1,118 @@
+//! Early serial console chosen from the firmware's ACPI SPCR table.
+//!
+//! The console never depends on accelerator discovery: the firmware says where
+//! the serial port is, and AIENOS drives it if it knows the register model.
+//! Every transmit is bounded, so an absent or unclocked UART cannot hang boot.
+
+use crate::acpi::UartKind;
+use crate::arch::aarch64::{EarlyUart, MmioReg, UART_TX_SPIN_LIMIT};
+use core::cell::Cell;
+
+/// ARM PL011 / SBSA generic UART register offsets.
+pub mod pl011_regs {
+    pub const DATA: usize = 0x00;
+    pub const FLAGS: usize = 0x18;
+    pub const TX_FULL: u32 = 1 << 5;
+}
+
+/// PL011 transmitter with the same bounded behaviour as `EarlyUart`.
+pub struct Pl011Uart {
+    base: usize,
+    dead: Cell<bool>,
+}
+
+impl Pl011Uart {
+    pub const fn new(base: usize) -> Self {
+        Self {
+            base,
+            dead: Cell::new(false),
+        }
+    }
+
+    pub fn is_dead(&self) -> bool {
+        self.dead.get()
+    }
+
+    pub fn write_byte(&self, b: u8) {
+        if self.dead.get() {
+            return;
+        }
+        let flags = MmioReg::<u32>::new(self.base + pl011_regs::FLAGS);
+        let mut polls = 0u32;
+        while flags.read() & pl011_regs::TX_FULL != 0 {
+            polls += 1;
+            if polls >= UART_TX_SPIN_LIMIT {
+                self.dead.set(true);
+                return;
+            }
+            core::hint::spin_loop();
+        }
+        MmioReg::<u32>::new(self.base + pl011_regs::DATA).write(u32::from(b));
+    }
+}
+
+/// The serial console found through SPCR.
+pub enum EarlyConsole {
+    Ns16550(EarlyUart),
+    Pl011(Pl011Uart),
+}
+
+impl EarlyConsole {
+    /// `None` when SPCR described no console this driver set can use.
+    pub fn from_kind(kind: UartKind) -> Option<Self> {
+        match kind {
+            UartKind::Ns16550Mmio32(base) => Some(Self::Ns16550(EarlyUart::new(base as usize))),
+            UartKind::Pl011(base) => Some(Self::Pl011(Pl011Uart::new(base as usize))),
+            UartKind::Unsupported => None,
+        }
+    }
+
+    pub fn write_str(&self, s: &str) {
+        for b in s.bytes() {
+            if b == b'\n' {
+                self.write_byte(b'\r');
+            }
+            self.write_byte(b);
+        }
+    }
+
+    fn write_byte(&self, b: u8) {
+        match self {
+            Self::Ns16550(u) => u.write_byte(b),
+            Self::Pl011(u) => u.write_byte(b),
+        }
+    }
+
+    pub fn is_dead(&self) -> bool {
+        match self {
+            Self::Ns16550(u) => u.is_dead(),
+            Self::Pl011(u) => u.is_dead(),
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn pl011_writes_when_ready_and_gives_up_when_always_full() {
+        let mut regs = [0u32; 8]; // FLAGS (index 6) clear: ready
+        let console = EarlyConsole::from_kind(UartKind::Pl011(regs.as_mut_ptr() as u64)).unwrap();
+        console.write_str("A");
+        assert_eq!(regs[0], u32::from(b'A'));
+        assert!(!console.is_dead());
+
+        let mut full = [0u32; 8];
+        full[pl011_regs::FLAGS / 4] = pl011_regs::TX_FULL;
+        let stuck = EarlyConsole::from_kind(UartKind::Pl011(full.as_mut_ptr() as u64)).unwrap();
+        stuck.write_str("AIENOS\n");
+        assert!(stuck.is_dead());
+        assert_eq!(full[0], 0);
+    }
+
+    #[test]
+    fn unsupported_spcr_gives_no_console() {
+        assert!(EarlyConsole::from_kind(UartKind::Unsupported).is_none());
+    }
+}
diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs
index 3a71bf17..07809054 100644
--- a/crates/aienos-kernel/src/lib.rs
+++ b/crates/aienos-kernel/src/lib.rs
@@ -11,6 +11,7 @@
 pub mod acpi;
 pub mod arch;
 pub mod boot;
+pub mod console;
 pub mod crypto;
 pub mod display;
 pub mod fatal;
diff --git a/scripts/qemu_boot_test.sh b/scripts/qemu_boot_test.sh
new file mode 100755
index 00000000..3b3b6096
--- /dev/null
+++ b/scripts/qemu_boot_test.sh
@@ -0,0 +1,73 @@
+#!/usr/bin/env bash
+# Boot the AIENOS handoff image in QEMU AArch64 with UEFI (AAVMF) and check the
+# serial console for the pre-exit report, the kernel reaching `kernel: alive`,
+# and the final report. The guest starts at EL2 like Machine 1, and PSCI reset
+# ends the run (-no-reboot). No physical hardware is touched.
+#
+# Needs qemu-system-aarch64 and AAVMF (Ubuntu: qemu-system-arm qemu-efi-aarch64).
+set -euo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+cd "${repo_root}"
+
+code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}"
+vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}"
+command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not installed"; exit 2; }
+[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; exit 2; }
+
+commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
+AIENOS_COMMIT="${commit}" AIENOS_RESTART_SECS=1 cargo build --quiet --release \
+    -p aienos-boot --target aarch64-unknown-uefi --features handoff --bin aienos-handoff
+
+work="$(mktemp -d)"
+trap 'rm -rf "${work}"' EXIT
+mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS"
+touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT"
+cp target/aarch64-unknown-uefi/release/aienos-handoff.efi "${work}/esp/EFI/BOOT/BOOTAA64.EFI"
+cp "${vars_fd}" "${work}/vars.fd"
+log="${work}/serial.log"
+
+started=$(date +%s)
+set +e
+timeout "${AIENOS_QEMU_TIMEOUT:-180}" qemu-system-aarch64 \
+    -M virt,virtualization=on -cpu max -smp 4 -m 2048 \
+    -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \
+    -drive if=pflash,format=raw,file="${work}/vars.fd" \
+    -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \
+    -device virtio-blk-pci,drive=esp \
+    -device ramfb -display none -nic none \
+    -serial file:"${log}" -no-reboot
+qemu_status=$?
+set -e
+elapsed=$(( $(date +%s) - started ))
+
+tr -d '\r' <"${log}" >"${work}/serial.txt"
+failed=0
+check() { # description, pattern
+    if grep -q -- "$2" "${work}/serial.txt"; then
+        echo "PASS  $1"
+    else
+        echo "FAIL  $1"
+        failed=1
+    fi
+}
+echo "qemu exit ${qemu_status} after ${elapsed} s (commit ${commit:0:12})"
+check "pre-exit report printed" "report_kind: pre_exit"
+check "image is this commit" "aienos_commit: ${commit}"
+check "left firmware and entered the kernel" "kernel: alive"
+check "final report on the SPCR console" "report_kind: final"
+check "no panic or fault" "report_kind: final"
+if grep -qE "report_kind: (panic|fault)" "${work}/serial.txt"; then
+    echo "FAIL  panic or fault reported"
+    failed=1
+fi
+if [[ "${qemu_status}" == 124 ]]; then
+    echo "FAIL  timed out (no reset)"
+    failed=1
+fi
+
+if [[ "${failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then
+    echo "---- serial console ----"
+    cat "${work}/serial.txt"
+fi
+[[ "${failed}" == 0 ]] && echo "QEMU_BOOT: PASS" || { echo "QEMU_BOOT: FAIL"; exit 1; }