Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/patches/f7e41eca1961135c # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aienux#15 (code only) closed derived `f7e41eca1961135c` #15 Imported from GitHub aien-dev/aienux#15 (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 `44fcba74bbd900167d171ee744762c4c8cb6bff6` · Head `64f5c4a43915ccb3184856a65d0cfd66be8d3df3` ### Apply it ``` git checkout -b patch-f7e41eca1961135c 44fcba74bbd900167d171ee744762c4c8cb6bff6 curl -fsSL https://interplane.io/drakestapleton/aienux/patches/f7e41eca1961135c.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 15 64f5c4a43915ccb3184856a65d0cfd66be8d3df3 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aienux","number":15,"url":"https://github.com/aien-dev/aienux/pull/15","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:50Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/crates/aienos-boot/Cargo.toml b/crates/aienos-boot/Cargo.toml index cc5cde6b..379592f3 100644 --- a/crates/aienos-boot/Cargo.toml +++ b/crates/aienos-boot/Cargo.toml @@ -9,11 +9,15 @@ description = "AArch64 UEFI entry diagnostic for AIENOS native boot bring-up" [features] default = [] -firmware = ["dep:uefi"] -handoff = ["firmware", "dep:aienos-kernel", "dep:aienos-accel", "uefi/alloc", "uefi/global_allocator"] +uefi-base = ["dep:uefi"] +# The diagnostic image uses the uefi crate's panic handler. The handoff image +# defines its own, which reports through the screen, firmware variable and +# UART after boot services exit, so the two features must not be combined. +firmware = ["uefi-base", "uefi/panic_handler"] +handoff = ["uefi-base", "dep:aienos-kernel", "dep:aienos-accel", "uefi/alloc", "uefi/global_allocator"] [dependencies] -uefi = { version = "0.41", default-features = false, features = ["panic_handler"], optional = true } +uefi = { version = "0.41", default-features = false, optional = true } aienos-kernel = { path = "../aienos-kernel", default-features = false, optional = true } aienos-accel = { path = "../aienos-accel", optional = true } diff --git a/crates/aienos-boot/src/handoff.rs b/crates/aienos-boot/src/handoff.rs index b278a382..39356f69 100644 --- a/crates/aienos-boot/src/handoff.rs +++ b/crates/aienos-boot/src/handoff.rs @@ -1,26 +1,38 @@ #![no_std] #![no_main] -//! Native handoff image with a boot report that does not depend on a serial -//! cable being attached. +//! First-boot evidence image for Machine 1. //! -//! Before firmware exit it prints a pre-exit report on the firmware console and -//! saves it to `\EFI\AIENOS\BOOTREPORT.TXT` on the boot volume. After exit the -//! kernel's report is drawn on the firmware-configured screen, stored in the -//! `AienosBootReport` firmware variable, and sent to the Spark UART (bounded). -//! The image then counts down and cold-resets, so a one-time boot entry -//! returns the machine to its normal boot order without a power cycle. -//! Linux reads both reports after reboot: +//! Before firmware exit it discovers the GB10, the CPU topology (ACPI MADT), +//! and the firmware display mode, prints a pre-exit report on the firmware +//! console, and saves it to `\EFI\AIENOS\BOOTREPORT.TXT`. +//! +//! After `ExitBootServices` it installs AIENOS exception vectors, writes an +//! early progress record, enters the kernel, and reports the result on the +//! screen, in the `AienosBootReportV1` firmware variable and on the Spark UART +//! (bounded). A panic or CPU fault takes the same reporting path with the last +//! boot stage and fault registers. It then counts down and cold-resets, so a +//! one-time boot entry returns to the normal boot order. +//! +//! The post-handoff firmware variable write is a temporary bootstrap exception +//! (ADR 0008): versioned name, at most `MAX_VAR_WRITES` writes of at most +//! `MAX_VAR_BYTES` each, diagnostics only, and a failed write never stops boot. +//! Linux reads the evidence after reboot: //! /boot/efi/EFI/AIENOS/BOOTREPORT.TXT -//! /sys/firmware/efi/efivars/AienosBootReport-a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a37 +//! /sys/firmware/efi/efivars/AienosBootReportV1-a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a37 use aienos_kernel::acpi; use aienos_kernel::arch::aarch64::{ - counter_frequency_hz, counter_ticks, EarlyUart, SPARK_16550_UART_BASE, + 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::display::{FramebufferInfo, PixelOrder, Screen, ACCENT, FOREGROUND}; +use aienos_kernel::fatal::{self, FaultInfo}; use aienos_kernel::report::ReportBuf; +use aienos_kernel::sync::spinlock::SpinLock; use core::fmt::Write; +use core::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams}; use uefi::mem::memory_map::{MemoryMap, MemoryType}; use uefi::prelude::*; @@ -30,10 +42,97 @@ use uefi::proto::pci::root_bridge::PciRootBridgeIo; use uefi::proto::pci::PciIoAddress; use uefi::runtime::{ResetType, VariableAttributes, VariableVendor}; use uefi::table::cfg::ConfigTableEntry; -use uefi::{cstr16, guid}; +use uefi::{cstr16, guid, CStr16}; +/// Commit this image was built from; `scripts/stage_one_time_boot.sh` sets it. +const COMMIT: &str = match option_env!("AIENOS_COMMIT") { + Some(commit) => commit, + None => "unknown", +}; +const REPORT_VERSION: u32 = 1; +const REPORT_VAR: &CStr16 = cstr16!("AienosBootReportV1"); const REPORT_VENDOR: VariableVendor = VariableVendor(guid!("a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a37")); +/// 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; +const ERROR: (u8, u8, u8) = (0xff, 0x6b, 0x6b); + +type Report = ReportBuf; + +const STAGES: [&str; 12] = [ + "firmware_entry", + "gb10_discovery", + "acpi_topology", + "framebuffer_discovery", + "pre_exit_report_saved", + "exit_boot_services", + "exception_vectors_installed", + "kernel_entered", + "screen_report_drawn", + "final_report_saved", + "uart_report_sent", + "countdown", +]; +const FIRMWARE_ENTRY: u8 = 0; +const GB10_DISCOVERY: u8 = 1; +const ACPI_TOPOLOGY: u8 = 2; +const FRAMEBUFFER_DISCOVERY: u8 = 3; +const PRE_EXIT_SAVED: u8 = 4; +const EXIT_BOOT_SERVICES: u8 = 5; +const VECTORS_INSTALLED: u8 = 6; +const KERNEL_ENTERED: u8 = 7; +const SCREEN_DRAWN: u8 = 8; +const FINAL_SAVED: u8 = 9; +const UART_SENT: u8 = 10; +const COUNTDOWN: u8 = 11; + +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); +static FREQUENCY_HZ: AtomicU64 = AtomicU64::new(0); +static FRAMEBUFFER: SpinLock> = SpinLock::new(None); + +fn stage(s: u8) { + STAGE.store(s, Ordering::SeqCst); +} + +fn stage_name() -> &'static str { + STAGES + .get(STAGE.load(Ordering::SeqCst) as usize) + .copied() + .unwrap_or("unknown") +} + +fn header(out: &mut impl Write, kind: &str) { + let _ = writeln!(out, "report_version: {REPORT_VERSION}"); + let _ = writeln!(out, "aienos_commit: {COMMIT}"); + let _ = writeln!(out, "report_kind: {kind}"); + let _ = writeln!(out, "last_stage: {}", stage_name()); +} + +/// Bounded report write (ADR 0008). Failure is reported, never fatal. +fn save_report_var(bytes: &[u8]) -> Result { + if bytes.len() > MAX_VAR_BYTES { + return Err("report larger than the bound"); + } + let n = VAR_WRITES.fetch_add(1, Ordering::SeqCst); + if n >= MAX_VAR_WRITES { + return Err("write budget for this boot spent"); + } + uefi::runtime::set_variable( + REPORT_VAR, + &REPORT_VENDOR, + VariableAttributes::NON_VOLATILE + | VariableAttributes::BOOTSERVICE_ACCESS + | VariableAttributes::RUNTIME_ACCESS, + bytes, + ) + .map(|()| n + 1) + .map_err(|_| "firmware refused the write") +} fn probe_gb10( root: &mut PciRootBridgeIo, @@ -116,7 +215,7 @@ unsafe fn table_at<'a>(addr: usize) -> Option<&'a [u8]> { } /// Core inventory from the firmware MADT (RSDP, then XSDT, then "APIC"). -fn discover_cpu_topology() -> Option { +fn discover_cpu_topology(boot_mpidr: u64) -> Option { let rsdp = uefi::system::with_config_table(|entries| { entries .iter() @@ -137,7 +236,7 @@ fn discover_cpu_topology() -> Option { continue; }; if &table[..4] == b"APIC" { - return acpi::madt_cpu_topology(table).ok(); + return acpi::madt_cpu_topology_for(table, Some(boot_mpidr)).ok(); } } None @@ -199,7 +298,8 @@ fn save_report_file(text: &str) -> uefi::Result { file.flush() } -fn wait_seconds(seconds: u64, frequency_hz: u64) { +fn wait_seconds(seconds: u64) { + let frequency_hz = FREQUENCY_HZ.load(Ordering::SeqCst); let start = counter_ticks(); let ticks = seconds.saturating_mul(frequency_hz); while counter_ticks().wrapping_sub(start) < ticks { @@ -207,27 +307,196 @@ fn wait_seconds(seconds: u64, frequency_hz: u64) { } } -/// Explicit native handoff image. Building it does not install or boot it. +fn screen() -> Option { + let info = (*FRAMEBUFFER.try_lock()?)?; + // SAFETY: firmware reported this buffer for the active mode, and nothing + // else draws to it after boot services have exited. + unsafe { Screen::new(info) } +} + +fn write_cpu( + out: &mut impl Write, + cpu: Option, + boot_midr: u64, + boot_mpidr: u64, +) { + match cpu { + Some(t) => { + let _ = writeln!(out, "cpu_cores: {}", t.cores); + for (class, count) in t.classes() { + let _ = writeln!(out, "cpu_efficiency_class_{class}: {count}"); + } + if t.unknown_class > 0 { + let _ = writeln!(out, "cpu_efficiency_class_unknown: {}", t.unknown_class); + } + match t.boot_class { + Some(class) => { + let _ = writeln!(out, "cpu_boot_core_class: {class}"); + } + None => { + let _ = writeln!( + out, + "cpu_boot_core_class: unknown (listed: {})", + if t.boot_core_listed { "yes" } else { "no" } + ); + } + } + } + None => { + let _ = writeln!(out, "cpu_topology: unavailable"); + } + } + let _ = writeln!( + out, + "boot_cpu_midr: {:#x} (part {:#05x})", + boot_midr, + midr_part(boot_midr) + ); + let _ = writeln!(out, "boot_cpu_mpidr: {boot_mpidr:#x}"); +} + +/// Reset after firmware exit: PSCI first (not a UEFI runtime service). UEFI +/// ResetSystem is used only if PSCI returns without resetting (ADR 0008). +fn reset_after_exit(status: Status) -> ! { + psci_system_reset(); + uefi::runtime::reset(ResetType::COLD, status, None) +} + +/// Line recording which bounded firmware-variable write this report will be. +fn write_index_line(out: &mut impl Write) { + let _ = writeln!( + out, + "nvram_write_index: {} of {MAX_VAR_WRITES}", + VAR_WRITES.load(Ordering::SeqCst) + 1 + ); +} + +/// Count down on screen, then reset. +fn finish(mut screen: Option) -> ! { + stage(COUNTDOWN); + match screen.as_mut() { + Some(s) => { + let _ = writeln!(s); + s.set_color(ACCENT); + 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), + } + reset_after_exit(Status::SUCCESS) +} + +/// Shared path for panics and CPU faults. +fn fatal_report(kind: &str, detail: &dyn Fn(&mut Report)) -> ! { + if IN_FATAL.swap(true, Ordering::SeqCst) { + // A fault while reporting a fault: firmware services are suspect, so + // only the architected PSCI reset is tried before parking the core. + psci_system_reset(); + aienos_kernel::arch::aarch64::halt(); + } + let mut report = Report::new(); + header(&mut report, kind); + if EXITED.load(Ordering::SeqCst) { + write_index_line(&mut report); + } + detail(&mut report); + + if !EXITED.load(Ordering::SeqCst) { + uefi::println!("{}", report.as_str()); + let _ = save_report_file(report.as_str()); + wait_seconds(RESTART_AFTER_SECS); + uefi::runtime::reset(ResetType::COLD, Status::ABORTED, None) + } + + let mut screen = screen(); + if let Some(s) = screen.as_mut() { + s.clear(); + s.set_color(ERROR); + let _ = writeln!(s, "AIENOS BOOT STOPPED: {kind}"); + s.set_color(FOREGROUND); + let _ = write!(s, "{}", report.as_str()); + } + 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() { + match saved { + Ok(n) => { + let _ = writeln!(s, "nvram_report: saved (write {n} of {MAX_VAR_WRITES})"); + } + Err(e) => { + let _ = writeln!(s, "nvram_report: not saved ({e})"); + } + } + } + finish(screen) +} + +#[panic_handler] +fn panic(info: &core::panic::PanicInfo) -> ! { + fatal_report("panic", &|r| { + let _ = writeln!(r, "panic: {}", info.message()); + if let Some(loc) = info.location() { + let _ = writeln!(r, "panic_location: {}:{}", loc.file(), loc.line()); + } + }) +} + +fn on_fault(info: &FaultInfo) -> ! { + fatal_report("fault", &|r| { + let _ = write!(r, "{info}"); + }) +} + +/// First-boot evidence image. Building it does not install or boot it. #[entry] fn main() -> Status { let uefi_entry_ticks = counter_ticks(); - let frequency_hz = counter_frequency_hz(); + FREQUENCY_HZ.store(counter_frequency_hz(), Ordering::SeqCst); + stage(FIRMWARE_ENTRY); + + 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); + + stage(FRAMEBUFFER_DISCOVERY); let framebuffer = discover_framebuffer(); - let cpu = discover_cpu_topology(); - let boot_midr = aienos_kernel::arch::aarch64::midr_el1(); + *FRAMEBUFFER.lock() = framebuffer; - let mut pre = ReportBuf::<1024>::new(); - let _ = writeln!(pre, "AIENOS pre-exit report"); + let mut pre = Report::new(); + header(&mut pre, "pre_exit"); let _ = writeln!(pre, "firmware_vendor: {}", uefi::system::firmware_vendor()); let _ = writeln!( pre, "firmware_revision: {:#x}", uefi::system::firmware_revision() ); - let _ = writeln!(pre, "counter_frequency_hz: {frequency_hz}"); + let _ = writeln!( + pre, + "counter_frequency_hz: {}", + FREQUENCY_HZ.load(Ordering::SeqCst) + ); match gb10 { Some(g) => { + let _ = writeln!( + pre, + "gb10_pci: {:04x}:{:02x}:{:02x}.{}", + g.bar.location.segment, + g.bar.location.bus, + g.bar.location.device, + g.bar.location.function + ); let _ = writeln!(pre, "gb10_bar0_phys: {:#x}", g.bar.physical_base); let _ = writeln!(pre, "gb10_pmc_boot_0: {:#010x}", g.pmc_boot_0); let _ = writeln!(pre, "gb10_pmc_boot_42: {:#010x}", g.pmc_boot_42); @@ -236,26 +505,7 @@ fn main() -> Status { let _ = writeln!(pre, "gb10: unavailable"); } } - match cpu { - Some(t) => { - let _ = writeln!(pre, "cpu_cores: {}", t.cores); - for (class, count) in t.classes() { - let _ = writeln!(pre, "cpu_efficiency_class_{class}: {count}"); - } - if t.unknown_class > 0 { - let _ = writeln!(pre, "cpu_efficiency_class_unknown: {}", t.unknown_class); - } - } - None => { - let _ = writeln!(pre, "cpu_topology: unavailable"); - } - } - let _ = writeln!( - pre, - "boot_cpu_midr: {:#x} (part {:#05x})", - boot_midr, - aienos_kernel::arch::aarch64::midr_part(boot_midr) - ); + write_cpu(&mut pre, cpu, boot_midr, boot_mpidr); match framebuffer { Some(f) => { let _ = writeln!( @@ -274,78 +524,94 @@ fn main() -> Status { Ok(()) => uefi::println!("report file: \\EFI\\AIENOS\\BOOTREPORT.TXT saved"), Err(e) => uefi::println!("report file: not saved ({:?})", e.status()), } + stage(PRE_EXIT_SAVED); - // No UEFI protocol, allocator, console, or boot-service reference is used - // after this point; only runtime services (variables, reset) remain. The + // After this point only runtime services (variables, reset) are used. The // returned map owns its backing allocation and stays live below. + stage(EXIT_BOOT_SERVICES); let memory_map = unsafe { uefi::boot::exit_boot_services(None) }; - let mut conventional_pages = 0u64; - let mut largest_region = None; + EXITED.store(true, Ordering::SeqCst); + + fatal::set_fault_hook(on_fault); + fatal::install_exception_vectors(); + stage(VECTORS_INSTALLED); + + // Early progress record: proves native AIENOS code ran after firmware exit + // even if a later step hangs. + let mut progress = Report::new(); + header(&mut progress, "progress"); + write_index_line(&mut progress); + let _ = writeln!(progress, "firmware_exit: ok"); + let progress_saved = save_report_var(progress.as_bytes()); + + let mut summary = MemoryMapSummary::default(); for descriptor in memory_map.entries() { - if descriptor.ty != MemoryType::CONVENTIONAL { - continue; - } - conventional_pages = conventional_pages.saturating_add(descriptor.page_count); - if let Some(region) = - aienos_kernel::boot::BootMemoryRegion::new(descriptor.phys_start, descriptor.page_count) - { - if largest_region.is_none_or(|largest: aienos_kernel::boot::BootMemoryRegion| { - region.page_count() > largest.page_count() - }) { - largest_region = Some(region); - } - } + summary.add( + descriptor.ty == MemoryType::CONVENTIONAL, + descriptor.phys_start, + descriptor.page_count, + ); } - let timing = aienos_kernel::boot::BootTiming { + let timing = BootTiming { uefi_entry_ticks, kernel_handoff_ticks: counter_ticks(), - counter_frequency_hz: frequency_hz, + counter_frequency_hz: FREQUENCY_HZ.load(Ordering::SeqCst), }; - let (report, boot_ok) = aienos_kernel::boot::early_kernel_enter( - conventional_pages.saturating_mul(4), - largest_region, + + stage(KERNEL_ENTERED); + let (kernel_report, boot_ok) = aienos_kernel::boot::early_kernel_enter( + summary.conventional_kb(), + summary.largest, + Some(summary), Some(timing), gb10, cpu, ); - // 1. Screen: the display mode firmware set up, written directly. - // SAFETY: firmware reported this buffer for the active mode, and nothing - // else draws to it after boot services have exited. - let mut screen = framebuffer.and_then(|info| unsafe { Screen::new(info) }); + let mut report = Report::new(); + header(&mut report, "final"); + write_index_line(&mut report); + let _ = write!(report, "{}", kernel_report.as_str()); + match progress_saved { + Ok(_) => { + let _ = writeln!(report, "progress_record: saved"); + } + Err(e) => { + let _ = writeln!(report, "progress_record: not saved ({e})"); + } + } + if report.truncated() { + let _ = writeln!(report, "truncated: yes"); + } + + let mut screen = screen(); if let Some(s) = screen.as_mut() { s.clear(); s.set_color(ACCENT); let _ = writeln!(s, "AIENOS NATIVE BOOT REPORT"); s.set_color(FOREGROUND); let _ = write!(s, "{}", report.as_str()); + stage(SCREEN_DRAWN); } - // 2. Firmware variable, readable from Linux after the reset below. - let nvram = uefi::runtime::set_variable( - cstr16!("AienosBootReport"), - &REPORT_VENDOR, - VariableAttributes::NON_VOLATILE - | VariableAttributes::BOOTSERVICE_ACCESS - | VariableAttributes::RUNTIME_ACCESS, - report.as_bytes(), - ); + let saved = save_report_var(report.as_bytes()); + stage(FINAL_SAVED); if let Some(s) = screen.as_mut() { - match &nvram { - Ok(()) => { - let _ = writeln!(s, "nvram_report: saved"); + match saved { + Ok(n) => { + let _ = writeln!(s, "nvram_report: saved (write {n} of {MAX_VAR_WRITES})"); } Err(e) => { - let _ = writeln!(s, "nvram_report: failed ({:?})", e.status()); + let _ = writeln!(s, "nvram_report: not saved ({e})"); } } } - // 3. Serial, only where the Spark's UART is known to exist, and bounded. 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, @@ -359,19 +625,11 @@ fn main() -> Status { } } - if let Some(s) = screen.as_mut() { - if !boot_ok { + if !boot_ok { + if let Some(s) = screen.as_mut() { + s.set_color(ERROR); let _ = writeln!(s, "boot halted: no usable memory region"); } - let _ = writeln!(s); - s.set_color(ACCENT); - for remaining in (1..=RESTART_AFTER_SECS).rev() { - s.clear_row(); - let _ = write!(s, "restarting in {remaining} s"); - wait_seconds(1, frequency_hz); - } - } else { - wait_seconds(RESTART_AFTER_SECS, frequency_hz); } - uefi::runtime::reset(ResetType::COLD, Status::SUCCESS, None) + finish(screen) } diff --git a/crates/aienos-kernel/src/acpi.rs b/crates/aienos-kernel/src/acpi.rs index 286f8f9b..c4db0f6c 100644 --- a/crates/aienos-kernel/src/acpi.rs +++ b/crates/aienos-kernel/src/acpi.rs @@ -81,6 +81,10 @@ pub struct CpuTopology { pub unknown_class: u32, /// Affinity (MPIDR) of the first listed core, for cross-checking the boot core. pub first_mpidr: Option, + /// The boot core (matched by MPIDR affinity) appears in the MADT. + pub boot_core_listed: bool, + /// Efficiency class of the boot core, if its entry carries one. + pub boot_class: Option, } impl CpuTopology { @@ -104,8 +108,19 @@ impl CpuTopology { } } +/// MPIDR affinity fields (Aff3, Aff2, Aff1, Aff0); other bits are flags. +pub const MPIDR_AFFINITY_MASK: u64 = 0xff_00ff_ffff; + /// Summarises the cores in a validated MADT ("APIC") table. pub fn madt_cpu_topology(madt: &[u8]) -> Result { + madt_cpu_topology_for(madt, None) +} + +/// Like `madt_cpu_topology`, also locating the core whose MPIDR is `boot_mpidr`. +pub fn madt_cpu_topology_for( + madt: &[u8], + boot_mpidr: Option, +) -> Result { let madt = checked_table(madt, b"APIC")?; let mut topo = CpuTopology::default(); let mut at = MADT_ENTRIES_OFFSET; @@ -123,6 +138,14 @@ pub fn madt_cpu_topology(madt: &[u8]) -> Result { if topo.first_mpidr.is_none() { topo.first_mpidr = u64_at(entry, GICC_MPIDR); } + let mpidr = u64_at(entry, GICC_MPIDR).unwrap_or(u64::MAX); + if boot_mpidr + .is_some_and(|b| b & MPIDR_AFFINITY_MASK == mpidr & MPIDR_AFFINITY_MASK) + { + topo.boot_core_listed = true; + topo.boot_class = + (len >= GICC_LEN_WITH_CLASS).then(|| entry[GICC_EFFICIENCY_CLASS]); + } if len >= GICC_LEN_WITH_CLASS { topo.add(entry[GICC_EFFICIENCY_CLASS]); } else { @@ -183,6 +206,23 @@ mod tests { assert_eq!(topo.first_mpidr, Some(0x8100_0000)); } + #[test] + fn finds_the_boot_core_class_ignoring_mpidr_flag_bits() { + let entries: Vec> = (0..20u64) + .map(|i| gicc(0x8100_0000 + (i << 8), GICC_ENABLED, u8::from(i >= 10), 82)) + .collect(); + let table = madt(&entries); + // MPIDR_EL1 bit 31 is RES1 and absent from the MADT copy. + let boot = (1 << 31) | 0x8100_0000 | (15 << 8); + let topo = madt_cpu_topology_for(&table, Some(boot)).unwrap(); + assert!(topo.boot_core_listed); + assert_eq!(topo.boot_class, Some(1)); + + let missing = madt_cpu_topology_for(&table, Some(0x42)).unwrap(); + assert!(!missing.boot_core_listed); + assert_eq!(missing.boot_class, None); + } + #[test] fn skips_disabled_cores_and_counts_old_entries_as_unknown() { let entries = [ diff --git a/crates/aienos-kernel/src/arch/aarch64.rs b/crates/aienos-kernel/src/arch/aarch64.rs index f66104aa..bef08b2d 100644 --- a/crates/aienos-kernel/src/arch/aarch64.rs +++ b/crates/aienos-kernel/src/arch/aarch64.rs @@ -92,6 +92,33 @@ pub fn midr_el1() -> u64 { } } +/// Multiprocessor affinity of the executing core (matches MADT GICC MPIDR). +#[inline(always)] +pub fn mpidr_el1() -> u64 { + #[cfg(target_arch = "aarch64")] + { + let mpidr: u64; + unsafe { + core::arch::asm!("mrs {0}, mpidr_el1", out(reg) mpidr, options(nomem, nostack, preserves_flags)); + } + mpidr + } + #[cfg(not(target_arch = "aarch64"))] + { + 0 + } +} + +/// PSCI SYSTEM_RESET (function 0x8400_0009) through the secure monitor: the +/// architected Arm reset path, not a UEFI runtime service. Does not return if +/// the platform implements it; returns if the monitor refused the call. +pub fn psci_system_reset() { + #[cfg(target_arch = "aarch64")] + unsafe { + core::arch::asm!("smc #0", inout("x0") 0x8400_0009u64 => _, options(nostack)); + } +} + /// Part number field of a MIDR value. pub const fn midr_part(midr: u64) -> u16 { ((midr >> 4) & 0xfff) as u16 diff --git a/crates/aienos-kernel/src/boot.rs b/crates/aienos-kernel/src/boot.rs index 91a60fd8..a5d8cc7b 100644 --- a/crates/aienos-kernel/src/boot.rs +++ b/crates/aienos-kernel/src/boot.rs @@ -58,6 +58,49 @@ impl BootMemoryRegion { pub const fn page_count(self) -> usize { self.page_count } + + /// Physical start address of the region. + pub const fn start(self) -> u64 { + self.start.0 as u64 + } +} + +/// What the firmware memory map contained and what the kernel accepted. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct MemoryMapSummary { + pub descriptors: u64, + pub conventional_regions: u64, + pub conventional_pages: u64, + /// Conventional regions that failed `BootMemoryRegion::new` validation. + pub rejected_regions: u64, + pub largest: Option, +} + +impl MemoryMapSummary { + /// Account for one firmware memory descriptor. + pub fn add(&mut self, conventional: bool, physical_start: u64, page_count: u64) { + self.descriptors += 1; + if !conventional { + return; + } + self.conventional_regions += 1; + self.conventional_pages = self.conventional_pages.saturating_add(page_count); + match BootMemoryRegion::new(physical_start, page_count) { + Some(region) => { + if self + .largest + .is_none_or(|l| region.page_count() > l.page_count()) + { + self.largest = Some(region); + } + } + None => self.rejected_regions += 1, + } + } + + pub fn conventional_kb(&self) -> u64 { + self.conventional_pages.saturating_mul(4) + } } /// Counter samples taken by the Rust UEFI entry and passed to the kernel. @@ -136,6 +179,8 @@ pub type BootReport = ReportBuf; /// Facts the kernel reports after taking control from firmware. pub struct BootFacts { pub conventional_memory_kb: u64, + /// Firmware memory map validation, when the caller walked the map. + pub memory_map: Option, /// `(managed_frames, reserved_frame)` or `None` if no usable region. pub allocator: Option<(usize, PhysAddr)>, pub timing: Option, @@ -158,6 +203,28 @@ pub fn write_boot_report(out: &mut impl Write, facts: &BootFacts) -> bool { "conventional_memory_kb: {}", facts.conventional_memory_kb ); + if let Some(m) = facts.memory_map { + let _ = writeln!(out, "memory_map_descriptors: {}", m.descriptors); + let _ = writeln!( + out, + "memory_map_conventional_regions: {}", + m.conventional_regions + ); + let _ = writeln!(out, "memory_map_rejected_regions: {}", m.rejected_regions); + match m.largest { + Some(r) => { + let _ = writeln!( + out, + "memory_map_largest_region: {:#x} pages {}", + r.start(), + r.page_count() + ); + } + None => { + let _ = writeln!(out, "memory_map_largest_region: none"); + } + } + } match facts.gb10 { Some(g) => { let _ = writeln!(out, "gb10_segment: {}", g.bar.location.segment); @@ -178,6 +245,19 @@ pub fn write_boot_report(out: &mut impl Write, facts: &BootFacts) -> bool { if t.unknown_class > 0 { let _ = writeln!(out, "cpu_efficiency_class_unknown: {}", t.unknown_class); } + let _ = writeln!( + out, + "cpu_boot_core_listed: {}", + if t.boot_core_listed { "yes" } else { "no" } + ); + match t.boot_class { + Some(class) => { + let _ = writeln!(out, "cpu_boot_core_class: {class}"); + } + None => { + let _ = writeln!(out, "cpu_boot_core_class: unknown"); + } + } } None => { let _ = writeln!(out, "cpu_topology: unavailable"); @@ -217,6 +297,7 @@ pub fn write_boot_report(out: &mut impl Write, facts: &BootFacts) -> bool { pub fn early_kernel_enter( conventional_memory_kb: u64, memory_region: Option, + memory_map: Option, boot_timing: Option, gb10: Option, cpu: Option, @@ -229,6 +310,7 @@ pub fn early_kernel_enter( // This reserves an address in bookkeeping only; it does not dereference RAM. let facts = BootFacts { conventional_memory_kb, + memory_map, allocator: memory_region.and_then(initialize_early_allocator), timing: boot_timing, kernel_entry_ticks, @@ -253,6 +335,7 @@ pub fn early_kernel_init_with_gpu( let (report, ok) = early_kernel_enter( conventional_memory_kb, memory_region, + None, boot_timing, gb10, None, @@ -305,8 +388,13 @@ mod tests { pmc_boot_0: 0x1b00_00a1, pmc_boot_42: 0x1b0a_0000, }; + let mut memory_map = super::MemoryMapSummary::default(); + memory_map.add(false, 0x0, 16); + memory_map.add(true, 0x1000_0000, 128); + memory_map.add(true, 0x2000_0001, 64); let facts = BootFacts { conventional_memory_kb: 4096, + memory_map: Some(memory_map), allocator: Some((128, PhysAddr(0x1000_0000))), timing: Some(BootTiming { uefi_entry_ticks: 0, @@ -330,6 +418,8 @@ mod tests { distinct_classes: 2, unknown_class: 0, first_mpidr: Some(0x8100_0000), + boot_core_listed: true, + boot_class: Some(0), }), boot_midr: 0x410f_d870, exception_level: 2, @@ -344,7 +434,13 @@ mod tests { "cpu_cores: 20", "cpu_efficiency_class_0: 10", "cpu_efficiency_class_1: 10", + "cpu_boot_core_listed: yes", + "cpu_boot_core_class: 0", "boot_cpu_midr: 0x410fd870 (part 0xd87)", + "memory_map_descriptors: 3", + "memory_map_conventional_regions: 2", + "memory_map_rejected_regions: 1", + "memory_map_largest_region: 0x10000000 pages 128", "allocator_reserved_frame_phys: 0x10000000", "uefi_entry_to_handoff_ms: 1", "handoff_to_kernel_entry_ms: 2", diff --git a/crates/aienos-kernel/src/fatal.rs b/crates/aienos-kernel/src/fatal.rs new file mode 100644 index 00000000..0f4471b3 --- /dev/null +++ b/crates/aienos-kernel/src/fatal.rs @@ -0,0 +1,235 @@ +//! Fatal-path capture for early boot: CPU exceptions and panics. +//! +//! After firmware exit the firmware's exception vectors are still installed, +//! and on a fault they typically print to a serial port and hang, leaving no +//! evidence. `install_exception_vectors` replaces them with AIENOS vectors +//! that switch to a dedicated stack, read the syndrome registers, and call a +//! registered hook (which reports the fault and resets). The decoding is pure +//! and host-tested; the vectors and register reads exist only on AArch64. + +use core::fmt; +use core::sync::atomic::{AtomicUsize, Ordering}; + +/// Registers captured when an exception is taken. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FaultInfo { + /// Vector slot 0..=15 (origin * 4 + kind). + pub vector: u64, + pub exception_level: u8, + pub esr: u64, + pub elr: u64, + pub far: u64, + pub spsr: u64, +} + +impl FaultInfo { + pub fn kind(&self) -> &'static str { + ["sync", "irq", "fiq", "serror"][(self.vector % 4) as usize] + } + + pub fn origin(&self) -> &'static str { + [ + "current_el_sp0", + "current_el_spx", + "lower_el_a64", + "lower_el_a32", + ][((self.vector / 4) % 4) as usize] + } + + /// Exception class, ESR bits 31:26. + pub fn exception_class(&self) -> u8 { + ((self.esr >> 26) & 0x3f) as u8 + } +} + +/// Human-readable name for an ESR exception class. +pub fn describe_exception_class(ec: u8) -> &'static str { + match ec { + 0x00 => "unknown reason", + 0x01 => "trapped WFI/WFE", + 0x0e => "illegal execution state", + 0x15 => "SVC (AArch64)", + 0x16 => "HVC (AArch64)", + 0x17 => "SMC (AArch64)", + 0x18 => "trapped system register access", + 0x20 => "instruction abort from lower EL", + 0x21 => "instruction abort at current EL", + 0x22 => "PC alignment fault", + 0x24 => "data abort from lower EL", + 0x25 => "data abort at current EL", + 0x26 => "SP alignment fault", + 0x2f => "SError", + 0x3c => "BRK instruction", + _ => "other", + } +} + +impl fmt::Display for FaultInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + writeln!(f, "fault_kind: {} from {}", self.kind(), self.origin())?; + writeln!(f, "fault_el: EL{}", self.exception_level)?; + writeln!( + f, + "fault_class: {:#04x} ({})", + self.exception_class(), + describe_exception_class(self.exception_class()) + )?; + writeln!(f, "fault_esr: {:#x}", self.esr)?; + writeln!(f, "fault_elr: {:#x}", self.elr)?; + writeln!(f, "fault_far: {:#x}", self.far)?; + writeln!(f, "fault_spsr: {:#x}", self.spsr) + } +} + +/// Called for a fault once vectors are installed. Must not return. +pub type FaultHook = fn(&FaultInfo) -> !; + +static HOOK: AtomicUsize = AtomicUsize::new(0); + +pub fn set_fault_hook(hook: FaultHook) { + HOOK.store(hook as usize, Ordering::SeqCst); +} + +fn call_hook(info: &FaultInfo) -> ! { + let raw = HOOK.load(Ordering::SeqCst); + if raw != 0 { + // SAFETY: only `set_fault_hook` stores into HOOK, always a FaultHook. + let hook: FaultHook = unsafe { core::mem::transmute::(raw) }; + hook(info); + } + crate::arch::aarch64::halt() +} + +#[cfg(target_arch = "aarch64")] +mod vectors { + use super::{call_hook, FaultInfo}; + use crate::arch::aarch64::current_el; + + const STACK_BYTES: usize = 16 * 1024; + + #[repr(C, align(16))] + struct ExceptionStack([u8; STACK_BYTES]); + + static mut EXCEPTION_STACK: ExceptionStack = ExceptionStack([0; STACK_BYTES]); + + macro_rules! read_sysreg { + ($name:literal) => {{ + let v: u64; + // SAFETY: reading a syndrome register of the current EL has no side effects. + unsafe { + core::arch::asm!(concat!("mrs {0}, ", $name), out(reg) v, options(nomem, nostack, preserves_flags)); + } + v + }}; + } + + /// Entered from the vector table on the exception stack. + #[no_mangle] + extern "C" fn aienos_exception_handler(vector: u64) -> ! { + let el = current_el(); + let info = if el == 2 { + FaultInfo { + vector, + exception_level: el, + esr: read_sysreg!("esr_el2"), + elr: read_sysreg!("elr_el2"), + far: read_sysreg!("far_el2"), + spsr: read_sysreg!("spsr_el2"), + } + } else { + FaultInfo { + vector, + exception_level: el, + esr: read_sysreg!("esr_el1"), + elr: read_sysreg!("elr_el1"), + far: read_sysreg!("far_el1"), + spsr: read_sysreg!("spsr_el1"), + } + }; + call_hook(&info) + } + + // Sixteen 128-byte entries on a 2 KiB boundary. Each loads its slot number + // and jumps to a common trampoline that moves onto a dedicated stack, so a + // fault caused by a bad stack still reaches the handler. + core::arch::global_asm!( + ".balign 2048", + ".global aienos_exception_vectors", + "aienos_exception_vectors:", + ".irp slot, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15", + ".balign 128", + "mov x0, #\\slot", + "b aienos_exception_trampoline", + ".endr", + "aienos_exception_trampoline:", + "adrp x1, {stack}", + "add x1, x1, :lo12:{stack}", + "add x1, x1, #{stack_bytes_hi}, lsl #12", + "mov sp, x1", + "bl {handler}", + "1: wfi", + "b 1b", + stack = sym EXCEPTION_STACK, + stack_bytes_hi = const STACK_BYTES >> 12, + handler = sym aienos_exception_handler, + ); + + extern "C" { + static aienos_exception_vectors: u8; + } + + pub fn install() { + let base = core::ptr::addr_of!(aienos_exception_vectors) as u64; + // SAFETY: VBAR of the current EL points at a valid, 2 KiB aligned table. + unsafe { + if current_el() == 2 { + core::arch::asm!("msr vbar_el2, {0}", "isb", in(reg) base, options(nostack)); + } else { + core::arch::asm!("msr vbar_el1, {0}", "isb", in(reg) base, options(nostack)); + } + } + } +} + +/// Replace the firmware's exception vectors with AIENOS ones. Call only after +/// firmware boot services have exited; firmware may rely on its own vectors +/// until then. +pub fn install_exception_vectors() { + #[cfg(target_arch = "aarch64")] + vectors::install(); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::string::ToString; + + #[test] + fn decodes_vector_slot_and_exception_class() { + let data_abort = FaultInfo { + vector: 4, + exception_level: 2, + esr: 0x9600_0045, // EC 0x25, data abort at current EL + elr: 0x8000_1000, + far: 0xdead_0000, + spsr: 0x3c9, + }; + assert_eq!(data_abort.kind(), "sync"); + assert_eq!(data_abort.origin(), "current_el_spx"); + assert_eq!(data_abort.exception_class(), 0x25); + let text = data_abort.to_string(); + assert!( + text.contains("fault_class: 0x25 (data abort at current EL)"), + "{text}" + ); + assert!(text.contains("fault_far: 0xdead0000"), "{text}"); + + let serror = FaultInfo { + vector: 7, + esr: 0xbe00_0000, + ..data_abort + }; + assert_eq!(serror.kind(), "serror"); + assert_eq!(describe_exception_class(serror.exception_class()), "SError"); + } +} diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs index 3baac6ab..3a71bf17 100644 --- a/crates/aienos-kernel/src/lib.rs +++ b/crates/aienos-kernel/src/lib.rs @@ -13,6 +13,7 @@ pub mod arch; pub mod boot; pub mod crypto; pub mod display; +pub mod fatal; pub mod mem; pub mod recovery; pub mod report; diff --git a/docs/MILESTONES.md b/docs/MILESTONES.md index a99c89c1..a1b85882 100644 --- a/docs/MILESTONES.md +++ b/docs/MILESTONES.md @@ -52,23 +52,32 @@ only at M8. Status words: **done** = verified on this repository's evidence; | **M7** AIEN runtime and native CPU inference | | pending | Compare against the M0 CPU baseline | | **M8** Cortex and persistent agent | | pending | Host crates exist (`cortex`, `agent-state`) | -**Current blocker for M2 on hardware:** Secure Boot is enabled on Machine 1 -(observed 2026-09-24), so firmware refuses the unsigned handoff image. Changing -it is escalation trigger 1 and is the operator's decision. +**Secure Boot (operator decision 2026-09-24, escalation trigger 1):** disabled +for early development only, so unsigned experimental images can be tested. No +other security mechanism is relaxed. Before daily use: operator-owned key, +signed loader, signed kernel and system manifest, offline recovery key, and a +known-good rollback image. Observed enabled on 2026-09-24; switching it off is +a physical step in firmware setup. **Accelerator lane:** device characterization (PCI identity, BAR layout, firmware interfaces, register discovery) is allowed now. Command submission, GSP interaction, GPU memory management and GPU inference stay a separate, non-blocking program (see [GB10_NATIVE_STATUS.md](GB10_NATIVE_STATUS.md)). -**Open operator decisions on the M2 bring-up path:** -- The handoff image writes its report to the `AienosBootReport` firmware - variable after `ExitBootServices`, as a one-time bring-up diagnostic. - AIENOS does not depend on it, but it uses a firmware runtime storage service - after handoff (escalation trigger 11) and needs operator sign-off. +**Operator decisions on the M2 bring-up path (2026-09-24):** +- The post-handoff `AienosBootReportV1` firmware report is a temporary + bootstrap exception to escalation trigger 11 under the conditions in + [ADR 0008](adr/0008-temporary-bring-up-firmware-report-exception.md). It is + removed once a native evidence path exists. - `scripts/stage_one_time_boot.sh --apply` sets `BootNext` and adds a boot - entry outside BootOrder. It runs only when the operator invokes it - (Phase 2 escalation trigger on NVRAM boot variables). + entry outside BootOrder. It runs only when the operator invokes it, under + `aien-proof hold --resource machine-1`. + +**M2 gate (first native boot):** Machine 1 leaves firmware, enters native +AIENOS code with no Linux underneath, produces independently recoverable +evidence that it did so, and returns to the existing system without damaging +it. `scripts/collect_boot_report.sh` prints `M2_GATE: PASS` only when all of +those checks hold. --- diff --git a/docs/NATIVE_BOOT_ONE_TIME.md b/docs/NATIVE_BOOT_ONE_TIME.md index 9e0de1e2..63254eb8 100644 --- a/docs/NATIVE_BOOT_ONE_TIME.md +++ b/docs/NATIVE_BOOT_ONE_TIME.md @@ -1,82 +1,103 @@ # First native boot on Machine 1: attended, one time -This procedure boots the `aienos-handoff` image on the DGX Spark exactly once -and brings the machine back to Linux on its own. It is the M2 hardware gate and -the rollback test that closes M0. +This procedure boots the `aienos-handoff` first-boot evidence image on the DGX +Spark exactly once and brings the machine back to Linux on its own. It is the +M2 hardware gate and the rollback test that closes M0. + +**Gate:** Machine 1 leaves firmware, enters native AIENOS code with no Linux +underneath, produces independently recoverable evidence that it did so, and +returns to the existing system without damaging it. ## What the image does -1. **Before firmware exit:** finds the GB10 and the display mode the firmware - set up, prints a pre-exit report on screen, and saves it to - `\EFI\AIENOS\BOOTREPORT.TXT` on the EFI system partition. -2. **After firmware exit:** the AIENOS kernel takes over, sets up its early - allocator, and writes its report three ways: - - drawn directly on the screen with a built-in font (no GPU driver), - - stored in the `AienosBootReport` firmware variable, - - sent to the Spark UART at `0x16A00000`, with a time limit so a missing - serial path cannot hang the boot. -3. Counts down 30 seconds on screen, then asks the firmware for a cold reset. +1. **Before firmware exit:** discovers the GB10 (PCI identity, BAR0, PMC boot + registers), the CPU topology from the ACPI MADT (cores per efficiency class + and the boot core's class), and the firmware display mode. It prints this + pre-exit report on screen and saves it to `\EFI\AIENOS\BOOTREPORT.TXT`. +2. **After firmware exit:** installs AIENOS exception vectors, writes an early + progress record, validates the firmware memory map, and enters the kernel. + The final report goes to the screen, the `AienosBootReportV1` firmware + variable ([ADR 0008](adr/0008-temporary-bring-up-firmware-report-exception.md)) + and the Spark UART (bounded). +3. **On a panic or CPU fault:** reports the last boot stage, the panic message + or the fault registers (ESR, ELR, FAR, SPSR) the same three ways. +4. Counts down 30 seconds, then resets (PSCI first). BootNext is used up, so + the machine returns to Linux. The image does not touch the Linux installation, its partitions, or BootOrder. -## Before you start +## Before you start (at the machine) + +1. **Recovery media:** plug in a bootable Linux USB stick. As of 2026-09-24 no + removable media was attached. The internal fallbacks are present: the + `ubuntu` boot entry (shim + GRUB), the firmware fallback loader + `\EFI\BOOT\BOOTAA64.EFI`, and three installed kernels. +2. **Monitor and keyboard** attached to the Spark. +3. **Everything on this Linux install stops** for each reboot: agents, model + servers, the aienos.com waitlist API, and remote access. + +## Step 1: turn Secure Boot off (operator decision 2026-09-24) + +```bash +sudo systemctl reboot --firmware-setup # reboots straight into firmware setup +``` -- **Secure Boot must be off.** On 2026-09-24 it was on (Ubuntu boots through - `shimaa64.efi`). The firmware refuses an unsigned image while it is on. The - staging script checks this and stops. Alternative: sign the image with your - own key and enroll it (the later owner-signed boot milestone). -- **Be at the machine** with a monitor and keyboard attached. -- **Have recovery media** (a Linux USB stick) in case the firmware misbehaves. -- **Everything running on this Linux install stops** for the reboot: agents, - model servers, the website waitlist API, and remote access. +In the setup screen, disable **Secure Boot** only. Change nothing else. Save, +exit, and let Linux boot. -## Steps +## Step 2: stage one boot ```bash -bash scripts/stage_one_time_boot.sh # dry run: prints the plan -sudo -v # cache sudo; hold gives the command no stdin +cd ~/workspace/hive-worktrees/aienos-main && git pull --ff-only +bash scripts/stage_one_time_boot.sh # dry run: commit, digest, plan +sudo -v # hold gives the command no stdin aien-proof hold --resource machine-1 --job stage-native-boot -- \ - bash scripts/stage_one_time_boot.sh --apply # sets BootNext only + bash scripts/stage_one_time_boot.sh --apply sudo reboot ``` -`aien-proof hold` (aien-sovereign-core) lets only one agent own Machine 1 at a -time and records each attempt, with its full output, as an `audit` event in the -shared ledger. +The script refuses a dirty checkout (the boot must map to one commit) and +refuses while Secure Boot is on. It records `\EFI\AIENOS\STAGED.TXT`: commit, +image sha256, who staged it, and the boot state before. -Expect: the firmware logo, the AIENOS pre-exit report, then a dark screen with -`AIENOS NATIVE BOOT REPORT` and a countdown. After the reset, Linux boots -normally. Then: +Expect: the firmware logo, the pre-exit report, then a dark screen headed +`AIENOS NATIVE BOOT REPORT` (or `AIENOS BOOT STOPPED` in red), and a countdown. +**Photograph the screen** before the countdown ends; it is the only record of +the post-exit screen. + +## Step 3: collect after Linux returns ```bash aien-proof hold --resource machine-1 --job collect-native-boot -- \ bash scripts/collect_boot_report.sh ``` -The ledger entry then carries the booted image digest and both reports. +The full output becomes an `audit` event in the hardware-test ledger. +`M2_GATE: PASS` requires every check below to pass. -`NATIVE_BOOT_OK` means the kernel ran and its report survived the reset. +| Evidence asked for | Where it comes from | +| --- | --- | +| Exact AIENOS commit | `aienos_commit` in STAGED.TXT, the pre-exit report and the native report, all compared | +| Exact boot image digest | `image_sha256` in STAGED.TXT, compared with the image on the ESP | +| Machine 1 lease holder | `aien-proof hold` records the agent in both ledger events; `staged_by` in STAGED.TXT | +| Firmware handoff data | Pre-exit report: firmware vendor/revision, counter frequency; kernel report: handoff timing | +| Heterogeneous CPU counts, boot-core class | `cpu_efficiency_class_*`, `cpu_boot_core_class`, `boot_cpu_midr` | +| Memory-map validation | `memory_map_descriptors`, `_conventional_regions`, `_rejected_regions`, `_largest_region` | +| GB10 PCI identity and BAR | `gb10_pci`, `gb10_bar0_phys`, `gb10_pmc_boot_0`, `gb10_pmc_boot_42` | +| Framebuffer/GOP observations | `framebuffer:` line pre-exit; the screen photo shows whether post-exit drawing worked | +| Console/UART observations | `uart_report: sent / no response` on screen | +| Last successful boot stage | `last_stage` in every report | +| Panic/fault data | `report_kind: panic` or `fault` with message or ESR/ELR/FAR/SPSR | +| Firmware-variable report contents | Printed in full; `nvram_write_index` shows which bounded write it was | +| Complete test output | The ledger payload of both `hold` events | +| Linux/recovery intact | BootNext consumed, BootOrder unchanged, same boot entry and kernel, root writable | ## If something goes wrong - **Screen stays black or frozen:** hold the power button until the machine - turns off, then power on. BootNext was used up by the failed attempt, so the - machine boots Linux. Anything already saved (the pre-exit file) is still - readable afterwards. + turns off, then power on. BootNext was used up, so Linux boots. The pre-exit + file and any saved variable report remain readable; collect as in step 3. - **Firmware says the image is not allowed:** Secure Boot is still on. -- **Linux does not come back:** boot the recovery media, or choose `ubuntu` in - the firmware boot menu. The AIENOS entry is not in BootOrder, so it never runs - unless BootNext is set again. - -## What each outcome proves - -| Evidence | Proves | -| --- | --- | -| Pre-exit file present | Firmware accepted and ran the image; GB10 and display were discovered through firmware services | -| Report on screen after exit | The firmware framebuffer stays writable after `ExitBootServices` | -| `NATIVE_BOOT_OK` from the firmware variable | The AIENOS kernel ran on Machine 1 and runtime variable writes work | -| `uart_report: sent` on screen | The UART at `0x16A00000` accepts output (whether a cable can reach it is separate) | -| Machine returned to Linux by itself | Firmware reset works, and the one-time path rolls back cleanly | - -Record the collected output in the evidence bundle before claiming the M2 gate -or marking the M0 recovery procedure verified. +- **Linux does not come back:** choose `ubuntu` in the firmware boot menu, or + boot the recovery USB stick. The AIENOS entry is not in BootOrder, so it + never runs unless BootNext is set again. diff --git a/docs/adr/0008-temporary-bring-up-firmware-report-exception.md b/docs/adr/0008-temporary-bring-up-firmware-report-exception.md new file mode 100644 index 00000000..ac8dd301 --- /dev/null +++ b/docs/adr/0008-temporary-bring-up-firmware-report-exception.md @@ -0,0 +1,56 @@ +# ADR 0008: Temporary Bring-Up Exception for a Post-Handoff Firmware Report + +Status: accepted by the operator, 2026-09-24, as a **temporary bootstrap +exception to escalation trigger 11**. It does not change the architecture. +Governing: [ADR 0003](0003-bootstrap-firmware-handoff-and-minimal-object-store.md), [MILESTONES.md section 0 and section 3](../MILESTONES.md), [NATIVE_BOOT_ONE_TIME.md](../NATIVE_BOOT_ONE_TIME.md). + +## Context + +ADR 0003 makes firmware handoff one-way: after `ExitBootServices`, firmware +runtime storage is not part of AIENOS operation. The first native boot on +Machine 1 has no proven native console, external capture or native persistent +storage. If that boot fails, a small report that survives the reset is the +only reliable evidence of how far the kernel got. + +## Decision + +The explicit bring-up and test image (`aienos-handoff`) may write a small +diagnostic report into UEFI variable storage after handoff, under these +conditions set by the operator: + +1. Only the bring-up/test image may do it. +2. Only diagnostic and evidence data may be written. Never credentials, + personal data, model state, Cortex state, or agent identity state. +3. The variable is namespaced and versioned: `AienosBootReportV1` under vendor + GUID `a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a37`, so it cannot overwrite + unrelated firmware state. +4. Writes are bounded: at most 3 per boot (progress, final or fault) and at + most 3072 bytes each. +5. A failed write never prevents boot; the result is reported and boot + continues. +6. Normal AIENOS operation does not depend on UEFI runtime variable services. +7. Every write is in the hardware-test ledger. Each report states its own + `nvram_write_index`, and `scripts/collect_boot_report.sh` runs under + `aien-proof hold --resource machine-1`, which records the collected report + as an `audit` event. +8. The exception is removed once a reliable native console, external capture + or native persistent evidence path exists. + +**Reset after handoff.** The image resets through PSCI `SYSTEM_RESET`, the +architected Arm interface, which is not a UEFI runtime service. UEFI +`ResetSystem` is called only if PSCI returns without resetting. That fallback +is part of this bring-up exception and is removed with it. + +## Target boundary (unchanged) + +UEFI performs boot handoff, then `ExitBootServices`, then AIENOS owns the +machine. Firmware runtime storage is no longer part of normal OS operation. + +## Consequences + +- A failed first boot still leaves the last boot stage, fault registers, or + panic message in a place Linux can read after the reset. +- Removing the exception means deleting `save_report_var`, the + `AienosBootReportV1` variable, and the UEFI reset fallback from + `crates/aienos-boot/src/handoff.rs`, and replacing the collector's variable + check with the native evidence path. diff --git a/docs/adr/README.md b/docs/adr/README.md index 4b48c284..f78e89b6 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -13,6 +13,7 @@ This directory documents the key architectural decisions and formal technical sp | [ADR 0005](0005-unified-memory-c1-cow-and-reservation-accounting.md) | Unified Memory C1 Copy-On-Write and Reservation Accounting | Accepted | 2026-09-23 | [`ARCHITECTURE.md` §2, §7](../ARCHITECTURE.md); [`BLUEPRINT.md` §9, §10, §28](../BLUEPRINT.md); [`MILESTONES.md` Phase 4, 5](../MILESTONES.md); [`PHASE_3_TO_5_SPECIFICATION.md` §4](../PHASE_3_TO_5_SPECIFICATION.md#4-phase-5-native-hardware-acceleration--hardware-bound-c1-compute) | | [ADR 0006](0006-deterministic-recovery-core-and-offline-operator-authority.md) | Deterministic Recovery Core and Offline Operator Authority | Accepted | 2026-09-23 | [`ARCHITECTURE.md` §1, §4, §6](../ARCHITECTURE.md); [`BLUEPRINT.md` §5, §6, §33](../BLUEPRINT.md); [`MILESTONES.md` Phase 2, 6](../MILESTONES.md); [`SYSTEMS_INTEGRATION_SEQUENCE.md` §2.5](../SYSTEMS_INTEGRATION_SEQUENCE.md#step-5-prove-recovery-core-before-the-model-adr-0006) | | [ADR 0007](0007-continuous-existence-provisioning-once.md) | Continuous Existence and Provisioning-Once | Accepted | 2026-09-23 | [`CONTINUOUS_EXISTENCE_AMENDMENT.md`](../CONTINUOUS_EXISTENCE_AMENDMENT.md); [`ARCHITECTURE.md` §1, §10](../ARCHITECTURE.md); [`SYSTEMS_INTEGRATION_SEQUENCE.md` Steps 1–10](../SYSTEMS_INTEGRATION_SEQUENCE.md); [`MILESTONES.md` Phase 3, 6, 8](../MILESTONES.md); [ADR 0005](0005-unified-memory-c1-cow-and-reservation-accounting.md); [ADR 0006](0006-deterministic-recovery-core-and-offline-operator-authority.md) | +| [ADR 0008](0008-temporary-bring-up-firmware-report-exception.md) | Temporary bring-up exception: post-handoff firmware report (trigger 11) | Accepted (temporary) | 2026-09-24 | [ADR 0003](0003-bootstrap-firmware-handoff-and-minimal-object-store.md); [`MILESTONES.md` section 0](../MILESTONES.md); [`NATIVE_BOOT_ONE_TIME.md`](../NATIVE_BOOT_ONE_TIME.md) | --- diff --git a/scripts/collect_boot_report.sh b/scripts/collect_boot_report.sh index 873fbea5..dfb7edc0 100755 --- a/scripts/collect_boot_report.sh +++ b/scripts/collect_boot_report.sh @@ -1,38 +1,79 @@ #!/usr/bin/env bash -# Read the reports left by an AIENOS handoff boot, from Linux. Read-only. -# pre-exit report: written to the EFI system partition before firmware exit -# native report: written to a firmware variable by the AIENOS kernel -set -euo pipefail +# Collect and judge the evidence from an AIENOS first-boot attempt. Read-only. +# Run under `aien-proof hold --resource machine-1` so the full output becomes +# an audit event in the hardware-test ledger. +# +# Gate (M2 first native boot): Machine 1 left firmware, entered native AIENOS +# code with no Linux underneath, left independently recoverable evidence, and +# returned to the existing system without damaging it. +set -uo pipefail -report_file="/boot/efi/EFI/AIENOS/BOOTREPORT.TXT" -report_var="/sys/firmware/efi/efivars/AienosBootReport-a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a37" -image="/boot/efi/EFI/AIENOS/aienos-handoff.efi" +esp="${AIENOS_ESP_DIR:-/boot/efi/EFI/AIENOS}" +staged_file="${esp}/STAGED.TXT" +report_file="${esp}/BOOTREPORT.TXT" +image="${esp}/aienos-handoff.efi" +report_var="${AIENOS_REPORT_VAR:-/sys/firmware/efi/efivars/AienosBootReportV1-a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a37}" -echo "== staged image" -if [[ -r "${image}" ]]; then - echo "sha256: $(sha256sum "${image}" | cut -d" " -f1)" -else - echo "missing: ${image}" +field() { sed -n "s/^$1: //p" <<<"$2" | head -1; } +check() { # name, pass(0/1), detail + if [[ "$2" == 1 ]]; then echo "PASS $1: $3"; else echo "FAIL $1: $3"; failed=1; fi +} +failed=0 + +echo "== staging record (${staged_file})" +staged="$(cat "${staged_file}" 2>/dev/null)" +if [[ -z "${staged}" ]]; then + echo "missing: nothing was staged, or the file is unreadable" + echo "M2_GATE: UNPROVEN" + exit 1 fi +printf '%s\n' "${staged}" +commit="$(field aienos_commit "${staged}")" + +echo "== staged image" +digest_now="$(sha256sum "${image}" 2>/dev/null | cut -d' ' -f1)" +echo "sha256: ${digest_now:-missing}" echo "== pre-exit report (${report_file})" -if [[ -r "${report_file}" ]]; then - cat "${report_file}" -else - echo "missing: the image did not reach the pre-exit save, or the file was not readable" -fi +pre="$(cat "${report_file}" 2>/dev/null)" +printf '%s\n' "${pre:-missing}" -echo "== native kernel report (${report_var})" +echo "== native firmware-variable report" +native="" if [[ -r "${report_var}" ]]; then # efivarfs prefixes the value with 4 bytes of attributes. native="$(tail -c +5 "${report_var}")" - printf '%s\n' "${native}" - if grep -qx "kernel: alive" <<<"${native}"; then - echo "NATIVE_BOOT_OK" - else - echo "NATIVE_BOOT_INCOMPLETE" - fi +fi +printf '%s\n' "${native:-missing}" + +echo "== current boot state" +boot_state="$(efibootmgr)" +printf '%s\n' "${boot_state}" | sed -n '1,4p' +echo "kernel: $(uname -r)" +echo "root: $(findmnt -no OPTIONS / | cut -d, -f1)" + +echo "== verdict" +check "image_unchanged" "$([[ -n "${digest_now}" && "${digest_now}" == "$(field image_sha256 "${staged}")" ]] && echo 1 || echo 0)" \ + "staged ${commit:0:12}, image ${digest_now:0:16}" +check "left_firmware_into_aienos" "$([[ "$(field aienos_commit "${pre}")" == "${commit}" ]] && echo 1 || echo 0)" \ + "pre-exit report from this commit, last stage $(field last_stage "${pre}")" +check "native_code_after_firmware_exit" "$([[ -n "${native}" && "$(field aienos_commit "${native}")" == "${commit}" ]] && echo 1 || echo 0)" \ + "firmware variable written by AIENOS after ExitBootServices (kind $(field report_kind "${native}"))" +check "kernel_alive" "$(grep -qx "kernel: alive" <<<"${native}" && echo 1 || echo 0)" \ + "last stage $(field last_stage "${native}")" +check "boot_next_consumed" "$(grep -q "^BootNext:" <<<"${boot_state}" && echo 0 || echo 1)" \ + "no pending one-time boot" +check "boot_order_unchanged" "$([[ "$(field BootOrder "${boot_state}")" == "$(field boot_order_before "${staged}")" ]] && echo 1 || echo 0)" \ + "$(field BootOrder "${boot_state}")" +check "linux_entry_booted" "$([[ "$(field BootCurrent "${boot_state}")" == "$(field boot_current_before "${staged}")" ]] && echo 1 || echo 0)" \ + "BootCurrent $(field BootCurrent "${boot_state}")" +check "linux_kernel_unchanged" "$([[ "$(uname -r)" == "$(field linux_kernel_before "${staged}")" ]] && echo 1 || echo 0)" \ + "$(uname -r)" +check "root_filesystem_writable" "$([[ "$(findmnt -no OPTIONS / | cut -d, -f1)" == "rw" ]] && echo 1 || echo 0)" "/" + +if [[ "${failed}" == 0 ]]; then + echo "M2_GATE: PASS" else - echo "missing: the kernel did not run, or the firmware refused runtime variable writes" - echo "NATIVE_BOOT_UNPROVEN" + echo "M2_GATE: FAIL" + exit 1 fi diff --git a/scripts/stage_one_time_boot.sh b/scripts/stage_one_time_boot.sh index 894a24c0..72e75c15 100755 --- a/scripts/stage_one_time_boot.sh +++ b/scripts/stage_one_time_boot.sh @@ -1,11 +1,13 @@ #!/usr/bin/env bash -# Stage the AIENOS handoff image for exactly one boot on this machine. +# Stage the AIENOS first-boot evidence image for exactly one boot. # # Dry run by default: prints what it would do and changes nothing. # With --apply (needs sudo) it copies the image to the EFI system partition, -# creates a boot entry WITHOUT adding it to BootOrder, and sets BootNext to it. +# writes \EFI\AIENOS\STAGED.TXT (commit, image digest, prior boot state), +# creates a boot entry WITHOUT adding it to BootOrder, and sets BootNext. # The firmware consumes BootNext on that boot, so the following boot returns to # the normal BootOrder (Linux) whether AIENOS succeeds, hangs, or is powered off. +# Run it under `aien-proof hold --resource machine-1` so the attempt is recorded. set -euo pipefail repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -20,13 +22,19 @@ loader='\EFI\AIENOS\aienos-handoff.efi' label="AIENOS handoff (one-time)" secure_boot_var="/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c" -cargo build --quiet --release -p aienos-boot --target aarch64-unknown-uefi \ - --features handoff --bin aienos-handoff +if [[ -n "$(git status --porcelain)" ]]; then + echo "STOP: the checkout has uncommitted changes; the boot must map to one exact commit." + exit 1 +fi +commit="$(git rev-parse HEAD)" + +AIENOS_COMMIT="${commit}" cargo build --quiet --release -p aienos-boot \ + --target aarch64-unknown-uefi --features handoff --bin aienos-handoff cargo run --quiet --release -p aienos-evidence -- verify-efi "${image}" if [[ -r "${secure_boot_var}" ]] && [[ "$(od -An -t u1 -j 4 -N 1 "${secure_boot_var}" | tr -d ' ')" == "1" ]]; then echo "STOP: Secure Boot is enabled. Firmware will refuse the unsigned AIENOS image." - echo "Turn Secure Boot off in the firmware setup screen, or sign the image and enroll the key, then rerun." + echo "Turn Secure Boot off in the firmware setup screen, then rerun." exit 1 fi @@ -34,10 +42,25 @@ source_dev="$(findmnt -no SOURCE "${esp}")" disk="/dev/$(lsblk -no PKNAME "${source_dev}")" part="$(cat "/sys/class/block/$(basename "${source_dev}")/partition")" order_before="$(efibootmgr | sed -n 's/^BootOrder: //p')" +current_before="$(efibootmgr | sed -n 's/^BootCurrent: //p')" digest="$(sha256sum "${image}" | cut -d' ' -f1)" +staged_by="${AIEN_AGENT_ID:-${USER:-unknown}}" + +record="$(mktemp)" +trap 'rm -f "${record}"' EXIT +cat >"${record}" <>"${record}" +sudo install -m 0644 "${record}" "${esp}/EFI/AIENOS/STAGED.TXT" sudo efibootmgr --quiet --bootnext "${entry}" +cat "${record}" efibootmgr | sed -n '1,4p' echo "Staged: the next boot runs Boot${entry} once. Reboot when you are at the machine." -echo "After it returns to Linux, run scripts/collect_boot_report.sh." +echo "After it returns to Linux, collect under the same key (docs/NATIVE_BOOT_ONE_TIME.md)." ```