From 3e5730bb523affff698bd2d07b701d8ec0ffa181 Mon Sep 17 00:00:00 2001 From: Drake Date: Wed, 23 Sep 2026 19:37:50 -0500 Subject: [PATCH] Make the native boot report visible without serial and self-returning bash scripts/verify_all.sh: exit 0. aienos-kernel: 27 passed (7 new). Both UEFI images build and pass aienos-evidence verify-efi. The handoff image previously reported only to the UART at 0x16A00000 and then halted. If that UART is not externally reachable, a successful boot would have been invisible and the machine stuck until a power cycle. - Pre-exit: record the firmware GOP mode, print a pre-exit report, and save it to \EFI\AIENOS\BOOTREPORT.TXT on the boot volume. - Post-exit: the kernel builds one report (aienos_kernel::report, no heap) and the image draws it on the firmware framebuffer with a built-in 5x7 font (aienos_kernel::display), stores it in the AienosBootReport firmware variable, and sends it to the UART only when the GB10 was found. - EarlyUart transmit is bounded: a UART that never reports ready is marked dead instead of hanging the boot. - After a 30 s countdown the image requests a firmware cold reset. - scripts/stage_one_time_boot.sh: dry run by default; refuses while Secure Boot is on; with --apply sets BootNext without changing BootOrder. - scripts/collect_boot_report.sh reads both reports from Linux. - docs/NATIVE_BOOT_ONE_TIME.md: the attended procedure and recovery. Not booted on hardware. Secure Boot is currently enabled on Machine 1. Co-authored-by: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- crates/aienos-boot/src/handoff.rs | 216 +++++++++++++- crates/aienos-kernel/src/arch/aarch64.rs | 47 ++- crates/aienos-kernel/src/boot.rs | 222 +++++++++----- crates/aienos-kernel/src/display/font.rs | 350 +++++++++++++++++++++++ crates/aienos-kernel/src/display/mod.rs | 243 ++++++++++++++++ crates/aienos-kernel/src/lib.rs | 2 + crates/aienos-kernel/src/report.rs | 75 +++++ docs/NATIVE_BOOT_ONE_TIME.md | 73 +++++ scripts/collect_boot_report.sh | 30 ++ scripts/stage_one_time_boot.sh | 67 +++++ 10 files changed, 1238 insertions(+), 87 deletions(-) create mode 100644 crates/aienos-kernel/src/display/font.rs create mode 100644 crates/aienos-kernel/src/display/mod.rs create mode 100644 crates/aienos-kernel/src/report.rs create mode 100644 docs/NATIVE_BOOT_ONE_TIME.md create mode 100755 scripts/collect_boot_report.sh create mode 100755 scripts/stage_one_time_boot.sh diff --git a/crates/aienos-boot/src/handoff.rs b/crates/aienos-boot/src/handoff.rs index a3c2b395..b39b769b 100644 --- a/crates/aienos-boot/src/handoff.rs +++ b/crates/aienos-boot/src/handoff.rs @@ -1,10 +1,37 @@ #![no_std] #![no_main] +//! Native handoff image with a boot report that does not depend on a serial +//! cable being attached. +//! +//! 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: +//! /boot/efi/EFI/AIENOS/BOOTREPORT.TXT +//! /sys/firmware/efi/efivars/AienosBootReport-a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a37 + +use aienos_kernel::arch::aarch64::{ + counter_frequency_hz, counter_ticks, EarlyUart, SPARK_16550_UART_BASE, +}; +use aienos_kernel::display::{FramebufferInfo, PixelOrder, Screen, ACCENT, FOREGROUND}; +use aienos_kernel::report::ReportBuf; +use core::fmt::Write; +use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams}; use uefi::mem::memory_map::{MemoryMap, MemoryType}; use uefi::prelude::*; +use uefi::proto::console::gop::{GraphicsOutput, PixelFormat}; +use uefi::proto::media::file::{File, FileAttribute, FileMode}; use uefi::proto::pci::root_bridge::PciRootBridgeIo; use uefi::proto::pci::PciIoAddress; +use uefi::runtime::{ResetType, VariableAttributes, VariableVendor}; +use uefi::{cstr16, guid}; + +const REPORT_VENDOR: VariableVendor = VariableVendor(guid!("a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a37")); +const RESTART_AFTER_SECS: u64 = 30; fn probe_gb10( root: &mut PciRootBridgeIo, @@ -70,21 +97,119 @@ fn discover_gb10() -> Option { None } +/// Geometry of the display mode the firmware already configured. +fn discover_framebuffer() -> Option { + let handle = uefi::boot::get_handle_for_protocol::().ok()?; + // Shared open: an exclusive open would disconnect the firmware console. + let mut gop = unsafe { + uefi::boot::open_protocol::( + OpenProtocolParams { + handle, + agent: uefi::boot::image_handle(), + controller: None, + }, + OpenProtocolAttributes::GetProtocol, + ) + } + .ok()?; + let mode = gop.current_mode_info(); + let order = match mode.pixel_format() { + PixelFormat::Rgb => PixelOrder::Rgb, + PixelFormat::Bgr => PixelOrder::Bgr, + _ => return None, + }; + let (width, height) = mode.resolution(); + let mut fb = gop.frame_buffer(); + FramebufferInfo { + base: fb.as_mut_ptr() as u64, + size_bytes: fb.size() as u64, + width, + height, + stride: mode.stride(), + order, + } + .validated() +} + +/// Replace `\EFI\AIENOS\BOOTREPORT.TXT` on the volume this image was loaded from. +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 mut file = root + .open(path, FileMode::CreateReadWrite, FileAttribute::empty())? + .into_regular_file() + .ok_or_else(|| uefi::Error::from(Status::UNSUPPORTED))?; + file.write(text.as_bytes()) + .map_err(|e| uefi::Error::from(e.status()))?; + file.flush() +} + +fn wait_seconds(seconds: u64, frequency_hz: u64) { + let start = counter_ticks(); + let ticks = seconds.saturating_mul(frequency_hz); + while counter_ticks().wrapping_sub(start) < ticks { + core::hint::spin_loop(); + } +} + /// Explicit native handoff image. Building it does not install or boot it. #[entry] fn main() -> Status { - let uefi_entry_ticks = aienos_kernel::arch::aarch64::counter_ticks(); - let counter_frequency_hz = aienos_kernel::arch::aarch64::counter_frequency_hz(); - uefi::println!("AIENOS: exiting firmware boot services"); + let uefi_entry_ticks = counter_ticks(); + let frequency_hz = counter_frequency_hz(); let gb10 = discover_gb10(); - uefi::println!( - "GB10 BAR0 register discovery: {}", - if gb10.is_some() { "ok" } else { "unavailable" } + let framebuffer = discover_framebuffer(); + + let mut pre = ReportBuf::<1024>::new(); + let _ = writeln!(pre, "AIENOS pre-exit report"); + 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}"); + match gb10 { + Some(g) => { + 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); + } + None => { + let _ = writeln!(pre, "gb10: unavailable"); + } + } + match framebuffer { + Some(f) => { + let _ = writeln!( + pre, + "framebuffer: {}x{} stride {} {:?} base {:#x} size {}", + f.width, f.height, f.stride, f.order, f.base, f.size_bytes + ); + } + None => { + let _ = writeln!(pre, "framebuffer: unavailable"); + } + } + let _ = writeln!(pre, "exiting firmware boot services"); + uefi::println!("{}", pre.as_str()); + match save_report_file(pre.as_str()) { + Ok(()) => uefi::println!("report file: \\EFI\\AIENOS\\BOOTREPORT.TXT saved"), + Err(e) => uefi::println!("report file: not saved ({:?})", e.status()), + } // No UEFI protocol, allocator, console, or boot-service reference is used - // after this point. The returned map owns its backing allocation and stays - // live while the early kernel path executes. + // after this point; only runtime services (variables, reset) remain. The + // returned map owns its backing allocation and stays live below. let memory_map = unsafe { uefi::boot::exit_boot_services(None) }; let mut conventional_pages = 0u64; let mut largest_region = None; @@ -103,16 +228,81 @@ fn main() -> Status { } } } - let timing = aienos_kernel::boot::BootTiming { uefi_entry_ticks, - kernel_handoff_ticks: aienos_kernel::arch::aarch64::counter_ticks(), - counter_frequency_hz, + kernel_handoff_ticks: counter_ticks(), + counter_frequency_hz: frequency_hz, }; - aienos_kernel::boot::early_kernel_init_with_gpu( + let (report, boot_ok) = aienos_kernel::boot::early_kernel_enter( conventional_pages.saturating_mul(4), largest_region, Some(timing), gb10, - ) + ); + + // 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) }); + 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()); + } + + // 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(), + ); + if let Some(s) = screen.as_mut() { + match &nvram { + Ok(()) => { + let _ = writeln!(s, "nvram_report: saved"); + } + Err(e) => { + let _ = writeln!(s, "nvram_report: failed ({:?})", e.status()); + } + } + } + + // 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()); + if let Some(s) = screen.as_mut() { + let _ = writeln!( + s, + "uart_report: {}", + if uart.is_dead() { + "no response" + } else { + "sent" + } + ); + } + } + + if let Some(s) = screen.as_mut() { + if !boot_ok { + 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) } diff --git a/crates/aienos-kernel/src/arch/aarch64.rs b/crates/aienos-kernel/src/arch/aarch64.rs index 82df9b45..34427e2d 100644 --- a/crates/aienos-kernel/src/arch/aarch64.rs +++ b/crates/aienos-kernel/src/arch/aarch64.rs @@ -208,15 +208,27 @@ pub mod uart16550_regs { pub const TX_HOLDING_EMPTY: u32 = 1 << 5; } +/// Status polls allowed per byte before the UART is treated as absent. At +/// 921600 baud one byte takes about 11 us, far below this many MMIO reads. +pub const UART_TX_SPIN_LIMIT: u32 = 1_000_000; + /// Early 8250-compatible UART with 32-bit MMIO registers. +/// +/// Transmission is bounded: if the transmitter never reports ready (no cable, +/// unclocked or absent device), the UART marks itself dead and drops further +/// output instead of hanging the boot before other outputs have run. pub struct EarlyUart { base_addr: usize, + dead: core::cell::Cell, } impl EarlyUart { /// Create a new EarlyUart driver instance at the specified MMIO base address. pub const fn new(base_addr: usize) -> Self { - Self { base_addr } + Self { + base_addr, + dead: core::cell::Cell::new(false), + } } /// Read raw register. @@ -224,12 +236,27 @@ impl EarlyUart { MmioReg::new(self.base_addr + offset) } - /// Send a single byte through UART transmit FIFO. + /// True once a transmit timed out; later writes are skipped. + pub fn is_dead(&self) -> bool { + self.dead.get() + } + + /// Send a single byte through UART transmit FIFO, giving up after + /// `UART_TX_SPIN_LIMIT` status polls. pub fn write_byte(&self, b: u8) { + if self.dead.get() { + return; + } let status = self.reg(uart16550_regs::LINE_STATUS); let data = self.reg(uart16550_regs::DATA); + let mut polls = 0u32; while (status.read() & uart16550_regs::TX_HOLDING_EMPTY) == 0 { + polls += 1; + if polls >= UART_TX_SPIN_LIMIT { + self.dead.set(true); + return; + } core::hint::spin_loop(); } data.write(b as u32); @@ -283,6 +310,13 @@ impl EarlyUart { } } +impl core::fmt::Write for EarlyUart { + fn write_str(&mut self, s: &str) -> core::fmt::Result { + EarlyUart::write_str(self, s); + Ok(()) + } +} + #[cfg(test)] mod tests { use super::*; @@ -299,4 +333,13 @@ mod tests { .write(uart16550_regs::TX_HOLDING_EMPTY | uart16550_regs::DATA_READY); assert_eq!(uart.try_read_byte(), Some(b'A')); } + + #[test] + fn a_uart_that_never_becomes_ready_is_abandoned_instead_of_hanging() { + let mut registers = [0u32; 8]; // TX_HOLDING_EMPTY never set + let uart = EarlyUart::new(registers.as_mut_ptr() as usize); + uart.write_str("AIENOS\n"); + assert!(uart.is_dead()); + assert_eq!(registers[0], 0); + } } diff --git a/crates/aienos-kernel/src/boot.rs b/crates/aienos-kernel/src/boot.rs index b9694efd..864a7386 100644 --- a/crates/aienos-kernel/src/boot.rs +++ b/crates/aienos-kernel/src/boot.rs @@ -6,7 +6,9 @@ use crate::arch::aarch64::{ counter_ticks, current_el, disable_interrupts, dsb, halt, isb, EarlyUart, SPARK_16550_UART_BASE, }; use crate::mem::{BitmapFrameAllocator, PhysAddr, PAGE_SIZE}; +use crate::report::ReportBuf; use crate::sync::spinlock::SpinLock; +use core::fmt::Write; const EARLY_BITMAP_WORDS: usize = 64; const MAX_EARLY_FRAMES: usize = EARLY_BITMAP_WORDS * 64; @@ -125,90 +127,107 @@ pub fn early_kernel_init_with_memory( early_kernel_init_with_gpu(conventional_memory_kb, memory_region, boot_timing, None) } -/// Native entry carrying read-only GB10 BAR0 identity sampled before firmware exit. -pub fn early_kernel_init_with_gpu( +/// Capacity of the native boot report shared by every output. +pub const REPORT_CAPACITY: usize = 2048; +pub type BootReport = ReportBuf; + +/// Facts the kernel reports after taking control from firmware. +pub struct BootFacts { + pub conventional_memory_kb: u64, + /// `(managed_frames, reserved_frame)` or `None` if no usable region. + pub allocator: Option<(usize, PhysAddr)>, + pub timing: Option, + pub kernel_entry_ticks: u64, + pub gb10: Option, + pub exception_level: u8, +} + +/// Formats the report. Returns false if boot cannot continue (no allocator). +pub fn write_boot_report(out: &mut impl Write, facts: &BootFacts) -> bool { + let _ = writeln!(out, "AIENOS"); + let _ = writeln!(out, "arch: aarch64"); + let _ = writeln!(out, "boot: native"); + let _ = writeln!( + out, + "conventional_memory_kb: {}", + facts.conventional_memory_kb + ); + match facts.gb10 { + Some(g) => { + let _ = writeln!(out, "gb10_segment: {}", g.bar.location.segment); + let _ = writeln!(out, "gb10_bar0_phys: {:#x}", g.bar.physical_base); + let _ = writeln!(out, "gb10_pmc_boot_0: {:#010x}", g.pmc_boot_0); + let _ = writeln!(out, "gb10_pmc_boot_42: {:#010x}", g.pmc_boot_42); + } + None => { + let _ = writeln!(out, "gb10: unavailable"); + } + } + let Some((managed_frames, first_frame)) = facts.allocator else { + let _ = writeln!(out, "allocator: unavailable; boot halted"); + return false; + }; + let _ = writeln!(out, "allocator_managed_frames: {managed_frames}"); + let _ = writeln!(out, "allocator_reserved_frame_phys: {:#x}", first_frame.0); + if let Some(t) = facts.timing { + let hz = t.counter_frequency_hz; + if let Some(ms) = BootTiming::elapsed_ms(t.uefi_entry_ticks, t.kernel_handoff_ticks, hz) { + let _ = writeln!(out, "uefi_entry_to_handoff_ms: {ms}"); + } + if let Some(ms) = + BootTiming::elapsed_ms(t.kernel_handoff_ticks, facts.kernel_entry_ticks, hz) + { + let _ = writeln!(out, "handoff_to_kernel_entry_ms: {ms}"); + } + } + let _ = writeln!(out, "exception_level: EL{}", facts.exception_level); + let _ = writeln!(out, "kernel: alive"); + true +} + +/// Kernel entry after firmware exit: interrupts off, barriers, early +/// allocator, then the report. Returns the report and whether boot may +/// continue; the caller chooses where to send it. +pub fn early_kernel_enter( conventional_memory_kb: u64, memory_region: Option, boot_timing: Option, gb10: Option, -) -> ! { +) -> (BootReport, bool) { let kernel_entry_ticks = counter_ticks(); - // 1. Disable maskable interrupts disable_interrupts(); - - // 2. Memory and instruction synchronization barriers dsb(); isb(); - - // 3. Early console UART output on DGX Spark MMIO (0x16A00000) - // Strictly unadorned console telemetry per Gate 2 specification - let uart = EarlyUart::new(SPARK_16550_UART_BASE); - uart.write_str("\nAIENOS\n"); - uart.write_str("arch: aarch64\n"); - uart.write_str("boot: native\n"); - uart.write_str("conventional_memory_kb: "); - uart.write_u64(conventional_memory_kb); - uart.write_str("\n"); - if let Some(identity) = gb10 { - uart.write_str("gb10_segment: "); - uart.write_u64(u64::from(identity.bar.location.segment)); - uart.write_str("\ngb10_bar0_phys: "); - uart.write_u64(identity.bar.physical_base); - uart.write_str("\ngb10_pmc_boot_0: "); - uart.write_u64(u64::from(identity.pmc_boot_0)); - uart.write_str("\ngb10_pmc_boot_42: "); - uart.write_u64(u64::from(identity.pmc_boot_42)); - uart.write_str("\n"); - } else { - uart.write_str("gb10: unavailable\n"); - } - // Retain the initial bitmap in kernel state and manage at most 16 MiB. // This reserves an address in bookkeeping only; it does not dereference RAM. - match memory_region.and_then(initialize_early_allocator) { - Some((managed_frames, first_frame)) => { - uart.write_str("allocator_managed_frames: "); - uart.write_u64(managed_frames as u64); - uart.write_str("\nallocator_reserved_frame_phys: "); - uart.write_u64(first_frame.0 as u64); - uart.write_str("\n"); - } - None => { - uart.write_str("allocator: unavailable; boot halted\n"); - halt(); - } - } - - if let Some(timing) = boot_timing { - if let Some(milliseconds) = BootTiming::elapsed_ms( - timing.uefi_entry_ticks, - timing.kernel_handoff_ticks, - timing.counter_frequency_hz, - ) { - uart.write_str("uefi_entry_to_handoff_ms: "); - uart.write_u64(milliseconds); - uart.write_str("\n"); - } - if let Some(milliseconds) = BootTiming::elapsed_ms( - timing.kernel_handoff_ticks, - kernel_entry_ticks, - timing.counter_frequency_hz, - ) { - uart.write_str("handoff_to_kernel_entry_ms: "); - uart.write_u64(milliseconds); - uart.write_str("\n"); - } - } + let facts = BootFacts { + conventional_memory_kb, + allocator: memory_region.and_then(initialize_early_allocator), + timing: boot_timing, + kernel_entry_ticks, + gb10, + exception_level: current_el(), + }; + let mut report = BootReport::new(); + let ok = write_boot_report(&mut report, &facts); + (report, ok) +} - let el = current_el(); - uart.write_str("exception_level: EL"); - uart.write_byte(b'0' + el); +/// Native entry carrying read-only GB10 BAR0 identity sampled before firmware exit. +/// Sends the report to the Spark UART only, then halts. +pub fn early_kernel_init_with_gpu( + conventional_memory_kb: u64, + memory_region: Option, + boot_timing: Option, + gb10: Option, +) -> ! { + let (report, ok) = early_kernel_enter(conventional_memory_kb, memory_region, boot_timing, gb10); + let uart = EarlyUart::new(SPARK_16550_UART_BASE); uart.write_str("\n"); - - uart.write_str("kernel: alive\n"); - uart.write_str("halt: clean\n"); - - // 4. Deterministic non-model halt loop + uart.write_str(report.as_str()); + if ok { + uart.write_str("halt: clean\n"); + } halt(); } @@ -234,6 +253,65 @@ mod tests { assert!(BootMemoryRegion::new(u64::MAX - 4095, 2).is_none()); } + #[test] + fn report_lists_gpu_allocator_timing_and_liveness() { + use super::{write_boot_report, BootFacts, BootReport}; + use crate::mem::PhysAddr; + let gb10 = aienos_accel::Gb10Identity { + bar: aienos_accel::Gb10Bar { + location: aienos_accel::PciLocation { + segment: 15, + bus: 1, + device: 0, + function: 0, + }, + physical_base: 0x6_5000_0000, + }, + pmc_boot_0: 0x1b00_00a1, + pmc_boot_42: 0x1b0a_0000, + }; + let facts = BootFacts { + conventional_memory_kb: 4096, + allocator: Some((128, PhysAddr(0x1000_0000))), + timing: Some(BootTiming { + uefi_entry_ticks: 0, + kernel_handoff_ticks: 1_000, + counter_frequency_hz: 1_000_000, + }), + kernel_entry_ticks: 3_000, + gb10: Some(gb10), + exception_level: 2, + }; + let mut report = BootReport::new(); + assert!(write_boot_report(&mut report, &facts)); + let text = report.as_str(); + for line in [ + "gb10_segment: 15", + "gb10_bar0_phys: 0x650000000", + "gb10_pmc_boot_0: 0x1b0000a1", + "allocator_reserved_frame_phys: 0x10000000", + "uefi_entry_to_handoff_ms: 1", + "handoff_to_kernel_entry_ms: 2", + "exception_level: EL2", + "kernel: alive", + ] { + assert!( + text.lines().any(|l| l == line), + "missing {line:?} in:\n{text}" + ); + } + + let halted = BootFacts { + allocator: None, + ..facts + }; + let mut report = BootReport::new(); + assert!(!write_boot_report(&mut report, &halted)); + assert!(report + .as_str() + .ends_with("allocator: unavailable; boot halted\n")); + } + #[test] fn early_allocator_retains_region_after_initialization() { let region = BootMemoryRegion::new(0x1000_0000, 128).unwrap(); diff --git a/crates/aienos-kernel/src/display/font.rs b/crates/aienos-kernel/src/display/font.rs new file mode 100644 index 00000000..1e8ba2df --- /dev/null +++ b/crates/aienos-kernel/src/display/font.rs @@ -0,0 +1,350 @@ +//! Built-in 5x7 bitmap font for the early boot screen. +//! +//! Glyphs are drawn as text so a reviewer can check them by eye. Lowercase +//! letters render as uppercase; anything without a glyph renders as `?`. + +pub const GLYPH_WIDTH: usize = 5; +pub const GLYPH_HEIGHT: usize = 7; + +type Art = [&'static str; GLYPH_HEIGHT]; + +const GLYPHS: &[(char, Art)] = &[ + ( + ' ', + [ + " ", " ", " ", " ", " ", " ", " ", + ], + ), + ( + '0', + [ + " ### ", "# #", "# ##", "# # #", "## #", "# #", " ### ", + ], + ), + ( + '1', + [ + " # ", " ## ", " # ", " # ", " # ", " # ", " ### ", + ], + ), + ( + '2', + [ + " ### ", "# #", " #", " # ", " # ", " # ", "#####", + ], + ), + ( + '3', + [ + "#####", " # ", " # ", " # ", " #", "# #", " ### ", + ], + ), + ( + '4', + [ + " # ", " ## ", " # # ", "# # ", "#####", " # ", " # ", + ], + ), + ( + '5', + [ + "#####", "# ", "#### ", " #", " #", "# #", " ### ", + ], + ), + ( + '6', + [ + " ## ", " # ", "# ", "#### ", "# #", "# #", " ### ", + ], + ), + ( + '7', + [ + "#####", " #", " # ", " # ", " # ", " # ", " # ", + ], + ), + ( + '8', + [ + " ### ", "# #", "# #", " ### ", "# #", "# #", " ### ", + ], + ), + ( + '9', + [ + " ### ", "# #", "# #", " ####", " #", " # ", " ## ", + ], + ), + ( + 'A', + [ + " ### ", "# #", "# #", "#####", "# #", "# #", "# #", + ], + ), + ( + 'B', + [ + "#### ", "# #", "# #", "#### ", "# #", "# #", "#### ", + ], + ), + ( + 'C', + [ + " ### ", "# #", "# ", "# ", "# ", "# #", " ### ", + ], + ), + ( + 'D', + [ + "#### ", "# #", "# #", "# #", "# #", "# #", "#### ", + ], + ), + ( + 'E', + [ + "#####", "# ", "# ", "#### ", "# ", "# ", "#####", + ], + ), + ( + 'F', + [ + "#####", "# ", "# ", "#### ", "# ", "# ", "# ", + ], + ), + ( + 'G', + [ + " ### ", "# #", "# ", "# ###", "# #", "# #", " ####", + ], + ), + ( + 'H', + [ + "# #", "# #", "# #", "#####", "# #", "# #", "# #", + ], + ), + ( + 'I', + [ + " ### ", " # ", " # ", " # ", " # ", " # ", " ### ", + ], + ), + ( + 'J', + [ + " ###", " # ", " # ", " # ", " # ", "# # ", " ## ", + ], + ), + ( + 'K', + [ + "# #", "# # ", "# # ", "## ", "# # ", "# # ", "# #", + ], + ), + ( + 'L', + [ + "# ", "# ", "# ", "# ", "# ", "# ", "#####", + ], + ), + ( + 'M', + [ + "# #", "## ##", "# # #", "# # #", "# #", "# #", "# #", + ], + ), + ( + 'N', + [ + "# #", "# #", "## #", "# # #", "# ##", "# #", "# #", + ], + ), + ( + 'O', + [ + " ### ", "# #", "# #", "# #", "# #", "# #", " ### ", + ], + ), + ( + 'P', + [ + "#### ", "# #", "# #", "#### ", "# ", "# ", "# ", + ], + ), + ( + 'Q', + [ + " ### ", "# #", "# #", "# #", "# # #", "# # ", " ## #", + ], + ), + ( + 'R', + [ + "#### ", "# #", "# #", "#### ", "# # ", "# # ", "# #", + ], + ), + ( + 'S', + [ + " ####", "# ", "# ", " ### ", " #", " #", "#### ", + ], + ), + ( + 'T', + [ + "#####", " # ", " # ", " # ", " # ", " # ", " # ", + ], + ), + ( + 'U', + [ + "# #", "# #", "# #", "# #", "# #", "# #", " ### ", + ], + ), + ( + 'V', + [ + "# #", "# #", "# #", "# #", "# #", " # # ", " # ", + ], + ), + ( + 'W', + [ + "# #", "# #", "# #", "# # #", "# # #", "# # #", " # # ", + ], + ), + ( + 'X', + [ + "# #", "# #", " # # ", " # ", " # # ", "# #", "# #", + ], + ), + ( + 'Y', + [ + "# #", "# #", " # # ", " # ", " # ", " # ", " # ", + ], + ), + ( + 'Z', + [ + "#####", " #", " # ", " # ", " # ", "# ", "#####", + ], + ), + ( + ':', + [ + " ", " # ", " # ", " ", " # ", " # ", " ", + ], + ), + ( + '_', + [ + " ", " ", " ", " ", " ", " ", "#####", + ], + ), + ( + '.', + [ + " ", " ", " ", " ", " ", " ## ", " ## ", + ], + ), + ( + ',', + [ + " ", " ", " ", " ", " ## ", " # ", " # ", + ], + ), + ( + '-', + [ + " ", " ", " ", "#####", " ", " ", " ", + ], + ), + ( + '/', + [ + " #", " #", " # ", " # ", " # ", "# ", "# ", + ], + ), + ( + '=', + [ + " ", " ", "#####", " ", "#####", " ", " ", + ], + ), + ( + '(', + [ + " # ", " # ", " # ", " # ", " # ", " # ", " # ", + ], + ), + ( + ')', + [ + " # ", " # ", " # ", " # ", " # ", " # ", " # ", + ], + ), + ( + '#', + [ + " # # ", "#####", " # # ", " # # ", " # # ", "#####", " # # ", + ], + ), + ( + '?', + [ + " ### ", "# #", " #", " # ", " # ", " ", " # ", + ], + ), +]; + +fn art(c: char) -> &'static Art { + let c = c.to_ascii_uppercase(); + GLYPHS + .iter() + .find(|(g, _)| *g == c) + .or_else(|| GLYPHS.iter().find(|(g, _)| *g == '?')) + .map(|(_, a)| a) + .expect("font contains '?'") +} + +/// Whether the pixel at column `x`, row `y` of `c`'s glyph is lit. +pub fn lit(c: char, x: usize, y: usize) -> bool { + art(c) + .get(y) + .and_then(|row| row.as_bytes().get(x)) + .is_some_and(|b| *b == b'#') +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_glyph_is_five_by_seven_hashes_and_spaces() { + for (c, rows) in GLYPHS { + for row in rows { + assert_eq!(row.len(), GLYPH_WIDTH, "glyph {c:?}"); + assert!(row.bytes().all(|b| b == b' ' || b == b'#'), "glyph {c:?}"); + } + } + } + + #[test] + fn digits_and_letters_are_distinct() { + let chars: std::vec::Vec = ('0'..='9').chain('A'..='Z').collect(); + for (i, a) in chars.iter().enumerate() { + for b in &chars[i + 1..] { + assert_ne!(art(*a), art(*b), "{a} and {b} share a glyph"); + } + } + } + + #[test] + fn lowercase_maps_to_uppercase_and_unknown_to_question_mark() { + assert_eq!(art('k'), art('K')); + assert_eq!(art('~'), art('?')); + assert!(lit('L', 0, 6) && lit('L', 4, 6) && !lit('L', 4, 0)); + } +} diff --git a/crates/aienos-kernel/src/display/mod.rs b/crates/aienos-kernel/src/display/mod.rs new file mode 100644 index 00000000..0f2715d1 --- /dev/null +++ b/crates/aienos-kernel/src/display/mod.rs @@ -0,0 +1,243 @@ +//! Early boot screen: text drawn straight into the firmware-provided +//! framebuffer (UEFI GOP) after boot services exit. No GPU driver is involved; +//! the firmware has already set the display mode. + +pub mod font; + +use core::fmt; +use core::ptr::write_volatile; +use font::{lit, GLYPH_HEIGHT, GLYPH_WIDTH}; + +/// Byte order of a 32-bit framebuffer pixel, as reported by GOP. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PixelOrder { + /// Bytes are red, green, blue, reserved. + Rgb, + /// Bytes are blue, green, red, reserved. + Bgr, +} + +/// Framebuffer geometry recorded before firmware exit. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FramebufferInfo { + pub base: u64, + pub size_bytes: u64, + pub width: usize, + pub height: usize, + /// Pixels per scanline (may exceed `width`). + pub stride: usize, + pub order: PixelOrder, +} + +impl FramebufferInfo { + /// Rejects geometry that would write outside the reported buffer. + pub fn validated(self) -> Option { + let needed = (self.stride as u64) + .checked_mul(self.height as u64)? + .checked_mul(4)?; + (self.width > 0 + && self.height > 0 + && self.stride >= self.width + && needed <= self.size_bytes) + .then_some(self) + } +} + +const CELL_W: usize = GLYPH_WIDTH + 1; +const CELL_H: usize = GLYPH_HEIGHT + 3; +/// Columns the text grid aims for; the scale grows until 80 cells fill the width. +const TARGET_COLUMNS: usize = 80; +const MARGIN_CELLS: usize = 1; + +pub const BACKGROUND: (u8, u8, u8) = (0x10, 0x14, 0x1c); +pub const FOREGROUND: (u8, u8, u8) = (0xe8, 0xec, 0xf2); +pub const ACCENT: (u8, u8, u8) = (0x5c, 0xd6, 0x8a); + +/// Text console over a linear 32-bit framebuffer. +pub struct Screen { + base: *mut u32, + info: FramebufferInfo, + scale: usize, + col: usize, + row: usize, + color: (u8, u8, u8), +} + +impl Screen { + /// # Safety + /// `info` must describe memory that is mapped, writable and not used by + /// anything else for the lifetime of the screen. + pub unsafe fn new(info: FramebufferInfo) -> Option { + let info = info.validated()?; + Some(Self { + base: info.base as usize as *mut u32, + info, + scale: (info.width / (TARGET_COLUMNS * CELL_W)).max(1), + col: MARGIN_CELLS, + row: MARGIN_CELLS, + color: FOREGROUND, + }) + } + + fn pixel(&self, (r, g, b): (u8, u8, u8)) -> u32 { + match self.info.order { + PixelOrder::Bgr => u32::from(r) << 16 | u32::from(g) << 8 | u32::from(b), + PixelOrder::Rgb => u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r), + } + } + + fn fill(&mut self, x0: usize, y0: usize, w: usize, h: usize, color: (u8, u8, u8)) { + let value = self.pixel(color); + for y in y0..(y0 + h).min(self.info.height) { + for x in x0..(x0 + w).min(self.info.width) { + // SAFETY: x < width <= stride and y < height, so the offset is + // inside the buffer checked by `FramebufferInfo::validated`. + unsafe { write_volatile(self.base.add(y * self.info.stride + x), value) }; + } + } + } + + pub fn clear(&mut self) { + let (w, h) = (self.info.width, self.info.height); + self.fill(0, 0, w, h, BACKGROUND); + self.col = MARGIN_CELLS; + self.row = MARGIN_CELLS; + } + + pub fn set_color(&mut self, color: (u8, u8, u8)) { + self.color = color; + } + + pub fn columns(&self) -> usize { + self.info.width / (CELL_W * self.scale) + } + + pub fn rows(&self) -> usize { + self.info.height / (CELL_H * self.scale) + } + + fn newline(&mut self) { + self.col = MARGIN_CELLS; + self.row += 1; + } + + pub fn put_char(&mut self, c: char) { + if c == '\n' { + self.newline(); + return; + } + if self.col + MARGIN_CELLS >= self.columns() { + self.newline(); + } + if self.row + MARGIN_CELLS >= self.rows() { + return; // Screen full: drop rather than scroll over earlier lines. + } + let s = self.scale; + let (x0, y0) = (self.col * CELL_W * s, self.row * CELL_H * s); + let color = self.color; + for gy in 0..GLYPH_HEIGHT { + for gx in 0..GLYPH_WIDTH { + if lit(c, gx, gy) { + self.fill(x0 + gx * s, y0 + gy * s, s, s, color); + } + } + } + self.col += 1; + } + + /// Paint a blank line at the current row (used for in-place countdowns). + pub fn clear_row(&mut self) { + let s = self.scale; + let y = self.row * CELL_H * s; + let w = self.info.width; + self.fill(0, y, w, CELL_H * s, BACKGROUND); + self.col = MARGIN_CELLS; + } +} + +impl fmt::Write for Screen { + fn write_str(&mut self, s: &str) -> fmt::Result { + s.chars().for_each(|c| self.put_char(c)); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use core::fmt::Write; + + fn screen(buf: &mut std::vec::Vec, width: usize, height: usize, stride: usize) -> Screen { + let info = FramebufferInfo { + base: buf.as_mut_ptr() as u64, + size_bytes: (buf.len() * 4) as u64, + width, + height, + stride, + order: PixelOrder::Bgr, + }; + unsafe { Screen::new(info) }.unwrap() + } + + #[test] + fn rejects_geometry_larger_than_the_buffer() { + let info = FramebufferInfo { + base: 0x1000, + size_bytes: 100 * 100 * 4, + width: 100, + height: 101, + stride: 100, + order: PixelOrder::Rgb, + }; + assert!(info.validated().is_none()); + assert!(FramebufferInfo { + height: 100, + ..info + } + .validated() + .is_some()); + assert!(FramebufferInfo { + stride: 99, + height: 10, + ..info + } + .validated() + .is_none()); + } + + #[test] + fn draws_glyph_pixels_and_respects_stride_padding() { + // 480 px wide gives scale 1; stride 500 leaves 20 px of padding per line. + let (w, h, stride) = (480, 120, 500); + let mut buf = std::vec![0u32; stride * h]; + let mut s = screen(&mut buf, w, h, stride); + s.clear(); + write!(s, "L").unwrap(); + let fg = + u32::from(FOREGROUND.0) << 16 | u32::from(FOREGROUND.1) << 8 | u32::from(FOREGROUND.2); + let (x0, y0) = (MARGIN_CELLS * CELL_W, MARGIN_CELLS * CELL_H); + let at = |x: usize, y: usize| buf[(y0 + y) * stride + x0 + x]; + // The L glyph: left column lit, bottom row lit, top-right dark. + assert_eq!(at(0, 0), fg); + assert_eq!(at(4, 6), fg); + assert_ne!(at(4, 0), fg); + // Padding beyond `width` is never touched. + assert!((0..h).all(|y| buf[y * stride + w..(y + 1) * stride] + .iter() + .all(|p| *p == 0))); + } + + #[test] + fn scales_up_on_wide_screens_and_drops_text_past_the_last_row() { + let (w, h) = (1920, 40); + let mut buf = std::vec![0u32; w * h]; + let mut s = screen(&mut buf, w, h, w); + assert_eq!(s.columns(), 80); + assert_eq!(s.rows(), 1); + s.clear(); + write!(s, "HELLO").unwrap(); // Row 1 is past the last row at this height. + let bg = + u32::from(BACKGROUND.0) << 16 | u32::from(BACKGROUND.1) << 8 | u32::from(BACKGROUND.2); + assert!(buf.iter().all(|p| *p == bg)); + } +} diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs index 89bdfa9b..d3efa865 100644 --- a/crates/aienos-kernel/src/lib.rs +++ b/crates/aienos-kernel/src/lib.rs @@ -11,8 +11,10 @@ pub mod arch; pub mod boot; pub mod crypto; +pub mod display; pub mod mem; pub mod recovery; +pub mod report; pub mod store; pub mod sync; diff --git a/crates/aienos-kernel/src/report.rs b/crates/aienos-kernel/src/report.rs new file mode 100644 index 00000000..35155468 --- /dev/null +++ b/crates/aienos-kernel/src/report.rs @@ -0,0 +1,75 @@ +//! Fixed-capacity text buffer for boot reports, usable without a heap. +//! +//! The same report text is sent to every output (screen, firmware variable, +//! serial), so all of them carry identical evidence. + +use core::fmt; + +pub struct ReportBuf { + bytes: [u8; N], + len: usize, + truncated: bool, +} + +impl Default for ReportBuf { + fn default() -> Self { + Self::new() + } +} + +impl ReportBuf { + pub const fn new() -> Self { + Self { + bytes: [0; N], + len: 0, + truncated: false, + } + } + + pub fn as_bytes(&self) -> &[u8] { + &self.bytes[..self.len] + } + + pub fn as_str(&self) -> &str { + // Only whole UTF-8 characters are ever appended. + core::str::from_utf8(self.as_bytes()).unwrap_or("") + } + + /// True if some text did not fit. + pub fn truncated(&self) -> bool { + self.truncated + } +} + +impl fmt::Write for ReportBuf { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + let mut tmp = [0u8; 4]; + let encoded = c.encode_utf8(&mut tmp).as_bytes(); + if self.len + encoded.len() > N { + self.truncated = true; + return Ok(()); + } + self.bytes[self.len..self.len + encoded.len()].copy_from_slice(encoded); + self.len += encoded.len(); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use core::fmt::Write; + + #[test] + fn formats_and_truncates_on_character_boundaries() { + let mut r = ReportBuf::<8>::new(); + write!(r, "ab{}", 12).unwrap(); + assert_eq!(r.as_str(), "ab12"); + write!(r, "é€xyz").unwrap(); + assert!(r.truncated()); + assert_eq!(r.as_str(), "ab12é"); + assert!(r.as_bytes().len() <= 8); + } +} diff --git a/docs/NATIVE_BOOT_ONE_TIME.md b/docs/NATIVE_BOOT_ONE_TIME.md new file mode 100644 index 00000000..f7a550d2 --- /dev/null +++ b/docs/NATIVE_BOOT_ONE_TIME.md @@ -0,0 +1,73 @@ +# 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. + +## 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. + +The image does not touch the Linux installation, its partitions, or BootOrder. + +## Before you start + +- **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. + +## Steps + +```bash +bash scripts/stage_one_time_boot.sh # dry run: prints the plan +bash scripts/stage_one_time_boot.sh --apply # needs sudo; sets BootNext only +sudo reboot +``` + +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: + +```bash +bash scripts/collect_boot_report.sh +``` + +`NATIVE_BOOT_OK` means the kernel ran and its report survived the reset. + +## 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. +- **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. diff --git a/scripts/collect_boot_report.sh b/scripts/collect_boot_report.sh new file mode 100755 index 00000000..924c8f28 --- /dev/null +++ b/scripts/collect_boot_report.sh @@ -0,0 +1,30 @@ +#!/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 + +report_file="/boot/efi/EFI/AIENOS/BOOTREPORT.TXT" +report_var="/sys/firmware/efi/efivars/AienosBootReport-a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a37" + +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 + +echo "== native kernel report (${report_var})" +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 +else + echo "missing: the kernel did not run, or the firmware refused runtime variable writes" + echo "NATIVE_BOOT_UNPROVEN" +fi diff --git a/scripts/stage_one_time_boot.sh b/scripts/stage_one_time_boot.sh new file mode 100755 index 00000000..894a24c0 --- /dev/null +++ b/scripts/stage_one_time_boot.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Stage the AIENOS handoff image for exactly one boot on this machine. +# +# 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. +# 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. +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" + +apply=0 +[[ "${1:-}" == "--apply" ]] && apply=1 + +image="target/aarch64-unknown-uefi/release/aienos-handoff.efi" +esp="/boot/efi" +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 +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." + exit 1 +fi + +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')" +digest="$(sha256sum "${image}" | cut -d' ' -f1)" + +echo "image: ${image} (sha256 ${digest})" +echo "copy to: ${esp}/EFI/AIENOS/aienos-handoff.efi" +echo "boot entry: '${label}' on ${disk} partition ${part}, loader ${loader}" +echo "BootOrder: ${order_before} (left unchanged)" +echo "BootNext: set to the AIENOS entry for one boot only" + +if [[ "${apply}" -ne 1 ]]; then + echo "Dry run. Rerun with --apply to stage." + exit 0 +fi + +sudo install -D -m 0644 "${image}" "${esp}/EFI/AIENOS/aienos-handoff.efi" +entry="$(efibootmgr | sed -n "s/^Boot\([0-9A-F]\{4\}\)\*\{0,1\} ${label}.*/\1/p" | head -1)" +if [[ -z "${entry}" ]]; then + sudo efibootmgr --quiet --create-only --disk "${disk}" --part "${part}" \ + --label "${label}" --loader "${loader}" + entry="$(efibootmgr | sed -n "s/^Boot\([0-9A-F]\{4\}\)\*\{0,1\} ${label}.*/\1/p" | head -1)" +fi +[[ -n "${entry}" ]] || { echo "boot entry was not created"; exit 1; } + +order_after="$(efibootmgr | sed -n 's/^BootOrder: //p')" +if [[ "${order_after}" != "${order_before}" ]]; then + sudo efibootmgr --quiet --bootorder "${order_before}" +fi +sudo efibootmgr --quiet --bootnext "${entry}" + +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."