interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-boot / src / handoff.rs

2163 lines · 77635 bytes Raw Blame History
1#![no_std]
2// SPDX-License-Identifier: Apache-2.0
3// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16#![no_main]
17
18//! First-boot evidence image for Machine 1.
19//!
20//! Before firmware exit it discovers the GB10, the CPU topology (ACPI MADT),
21//! and the firmware display mode, prints a pre-exit report on the firmware
22//! console, and saves it to `\EFI\AIENOS\BOOTREPORT.TXT`.
23//!
24//! After `ExitBootServices` it installs AIENOS exception vectors, writes an
25//! early progress record, enters the kernel, and reports the result on the
26//! screen, in the `AienosBootReportV1` firmware variable and on the Spark UART
27//! (bounded). A panic or CPU fault takes the same reporting path with the last
28//! boot stage and fault registers. It then counts down and cold-resets, so a
29//! one-time boot entry returns to the normal boot order.
30//!
31//! The post-handoff firmware variable write is a temporary bootstrap exception
32//! (ADR 0008): versioned name, at most `MAX_VAR_WRITES` writes of at most
33//! `MAX_VAR_BYTES` each, diagnostics only, and a failed write never stops boot.
34//! Linux reads the evidence after reboot:
35//! /boot/efi/EFI/AIENOS/BOOTREPORT.TXT
36//! /sys/firmware/efi/efivars/AienosBootReportV1-a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a37
37
38// Links the `wcslen` definition (see wcslen.rs); rustc 1.99 emits calls to it.
39extern crate aienos_boot as _;
40extern crate alloc;
41
42use aienos_kernel::acpi;
43use aienos_kernel::arch::aarch64::{
44 counter_frequency_hz, counter_ticks, midr_el1, midr_part, mpidr_el1, psci_system_reset,
45};
46use aienos_kernel::boot::{BootTiming, MemoryMapSummary};
47use aienos_kernel::console::EarlyConsole;
48use aienos_kernel::display::{FramebufferInfo, PixelOrder, Screen, ACCENT, FOREGROUND};
49use aienos_kernel::fatal::{self, FaultInfo};
50use aienos_kernel::mem::frame_allocator::PhysAddr;
51use aienos_kernel::mem::map_plan::{self, AddressRange, EfiMemoryDescriptor};
52use aienos_kernel::mem::pagetable::{FixedFramePool, PageTableBuilder, TableMemory};
53use aienos_kernel::report::ReportBuf;
54use aienos_kernel::sync::spinlock::SpinLock;
55use core::alloc::{GlobalAlloc, Layout};
56use core::fmt::Write;
57#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
58use core::sync::atomic::AtomicUsize;
59use core::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering};
60use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams};
61use uefi::mem::memory_map::{MemoryMap, MemoryType};
62use uefi::prelude::*;
63use uefi::proto::console::gop::{GraphicsOutput, PixelFormat};
64use uefi::proto::loaded_image::LoadedImage;
65use uefi::proto::media::file::{File, FileAttribute, FileMode};
66use uefi::proto::pci::configuration::ResourceRangeType;
67use uefi::proto::pci::root_bridge::PciRootBridgeIo;
68use uefi::proto::pci::PciIoAddress;
69use uefi::runtime::{ResetType, VariableAttributes, VariableVendor};
70use uefi::table::cfg::ConfigTableEntry;
71use uefi::{cstr16, guid, CStr16};
72
73const PT_POOL_PAGES: usize = 256;
74const POST_EXIT_HEAP_PAGES: usize = 1024;
75static POST_EXIT_HEAP: AtomicU64 = AtomicU64::new(0);
76static POST_EXIT_HEAP_USED: AtomicU64 = AtomicU64::new(0);
77static BOOT_SERVICES_LIVE: AtomicBool = AtomicBool::new(true);
78
79#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
80#[repr(C)]
81// Field order keeps every queue aligned to its own size (the SMMU ignores
82// low base address bits below the queue size): stream table at 0 (256 KiB),
83// event queue at 256 KiB (512 bytes), command queue after it (256 bytes),
84// then the 64-byte context descriptor.
85struct SmmuTables {
86 stream_table: [[u64; 8]; 4096],
87 event_queue: [[u64; 4]; SMMU_QUEUE_ENTRIES as usize],
88 command_queue: [[u64; 2]; SMMU_QUEUE_ENTRIES as usize],
89 context: [u64; 8],
90}
91
92#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
93const STREAM_ENTRIES: u32 = 4096;
94
95#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
96const SMMU_QUEUE_ENTRIES: u32 = 16;
97
98// The linear stream table base must be aligned to its size (4096 * 64 bytes =
99// 256 KiB) or QEMU truncates it before fetching the STE. COFF/PE cannot encode
100// section alignment above 8192, so a 256 KiB-aligned static is unbuildable for
101// aarch64-unknown-uefi; allocate the tables at runtime with an over-aligned
102// Layout and hand out one shared pointer to every user instead.
103#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
104const SMMU_TABLES_ALIGN: usize = 262144;
105
106#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
107static SMMU_TABLES_PTR: AtomicUsize = AtomicUsize::new(0);
108
109#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
110fn smmu_tables() -> *mut SmmuTables {
111 let existing = SMMU_TABLES_PTR.load(Ordering::Acquire);
112 if existing != 0 {
113 return existing as *mut SmmuTables;
114 }
115 let layout = Layout::from_size_align(core::mem::size_of::<SmmuTables>(), SMMU_TABLES_ALIGN)
116 .expect("smmu tables layout");
117 let raw = unsafe { ALLOCATOR.alloc(layout) };
118 assert!(!raw.is_null(), "smmu tables allocation failed");
119 unsafe { core::ptr::write_bytes(raw, 0, layout.size()) };
120 SMMU_TABLES_PTR.store(raw as usize, Ordering::Release);
121 raw.cast::<SmmuTables>()
122}
123
124/// Pointer to the shared event queue ring, reached by byte offset so no typed
125/// pointer dereference is needed.
126#[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
127fn smmu_event_queue_ptr() -> *const [[u64; 4]; SMMU_QUEUE_ENTRIES as usize] {
128 let base = smmu_tables() as *mut u8;
129 base.wrapping_add(core::mem::offset_of!(SmmuTables, event_queue))
130 .cast()
131}
132
133struct BootHeap;
134unsafe impl GlobalAlloc for BootHeap {
135 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
136 if BOOT_SERVICES_LIVE.load(Ordering::Acquire) {
137 return unsafe { GlobalAlloc::alloc(&uefi::allocator::Allocator, layout) };
138 }
139 let base = POST_EXIT_HEAP.load(Ordering::Acquire) as usize;
140 if base == 0 {
141 return core::ptr::null_mut();
142 }
143 let mut old = POST_EXIT_HEAP_USED.load(Ordering::Relaxed) as usize;
144 loop {
145 let aligned = match (base + old).checked_add(layout.align() - 1) {
146 Some(v) => v & !(layout.align() - 1),
147 None => return core::ptr::null_mut(),
148 };
149 let next = match aligned.checked_add(layout.size()) {
150 Some(v) => v - base,
151 None => return core::ptr::null_mut(),
152 };
153 if next > POST_EXIT_HEAP_PAGES * 4096 {
154 return core::ptr::null_mut();
155 }
156 match POST_EXIT_HEAP_USED.compare_exchange_weak(
157 old as u64,
158 next as u64,
159 Ordering::AcqRel,
160 Ordering::Relaxed,
161 ) {
162 Ok(_) => return aligned as *mut u8,
163 Err(v) => old = v as usize,
164 }
165 }
166 }
167 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
168 if BOOT_SERVICES_LIVE.load(Ordering::Acquire) {
169 unsafe { GlobalAlloc::dealloc(&uefi::allocator::Allocator, ptr, layout) };
170 }
171 }
172}
173#[global_allocator]
174static ALLOCATOR: BootHeap = BootHeap;
175
176struct PhysicalTableMemory;
177impl TableMemory for PhysicalTableMemory {
178 fn read_entry(&self, table: PhysAddr, index: usize) -> Option<u64> {
179 if index >= 512 {
180 return None;
181 }
182 Some(unsafe { core::ptr::read_volatile((table.0 as *const u64).add(index)) })
183 }
184 fn write_entry(&mut self, table: PhysAddr, index: usize, value: u64) -> bool {
185 if index >= 512 {
186 return false;
187 }
188 unsafe { core::ptr::write_volatile((table.0 as *mut u64).add(index), value) };
189 true
190 }
191}
192
193fn runtime_attributes() -> Option<alloc::vec::Vec<aienos_kernel::mem::map_plan::RuntimeAttributes>>
194{
195 let mut table = None;
196 uefi::system::with_config_table(|entries| {
197 if let Some(entry) = entries
198 .iter()
199 .find(|e| e.guid == ConfigTableEntry::MEMORY_ATTRIBUTES_GUID)
200 {
201 table = Some(entry.address.cast::<u8>());
202 }
203 });
204 let ptr = table?;
205 let header = unsafe { core::slice::from_raw_parts(ptr, 16) };
206 let count = u32::from_le_bytes(header[4..8].try_into().ok()?) as usize;
207 let stride = u32::from_le_bytes(header[8..12].try_into().ok()?) as usize;
208 let length = 16usize.checked_add(count.checked_mul(stride)?)?;
209 if length > 1 << 20 {
210 return None;
211 }
212 let bytes = unsafe { core::slice::from_raw_parts(ptr, length) };
213 aienos_kernel::uefi::parse_memory_attributes_table(bytes).ok()
214}
215
216fn clean_table_pool(base: usize, bytes: usize) {
217 #[cfg(target_arch = "aarch64")]
218 unsafe {
219 let ctr: u64;
220 core::arch::asm!("mrs {0}, ctr_el0", out(reg) ctr, options(nomem, nostack));
221 let line = 4usize << ((ctr >> 16) & 0xf);
222 for address in (base..base + bytes).step_by(line) {
223 core::arch::asm!("dc cvac, {0}", in(reg) address, options(nostack));
224 }
225 core::arch::asm!("dsb ish", options(nostack));
226 }
227 #[cfg(not(target_arch = "aarch64"))]
228 let _ = (base, bytes);
229}
230
231#[cfg(feature = "usb-keyboard")]
232fn configure_smmu_for_xhci(
233 iort: Option<&acpi::IortSmmu>,
234 xhci: Option<usb_keyboard::XhciLocation>,
235 pool_base: usize,
236 frames_used: usize,
237) -> Result<u32, aienos_kernel::smmu::Error> {
238 let iort = iort.ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
239 let xhci = xhci.ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
240 let stream_id = xhci
241 .stream_id(iort)
242 .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
243 let (dma_base, dma_length) = xhci.dma_window();
244 let remaining = PT_POOL_PAGES.saturating_sub(frames_used);
245 let next = pool_base
246 .checked_add(
247 frames_used
248 .checked_mul(4096)
249 .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?,
250 )
251 .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
252 let frames = FixedFramePool::new(PhysAddr(next), remaining)
253 .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
254 // Stage-1 table that maps only the xHCI DMA window (identity).
255 let policy = aienos_kernel::smmu::build_dma_policy(
256 stream_id,
257 1,
258 &[aienos_kernel::smmu::DmaWindow {
259 iova: dma_base as usize,
260 pa: PhysAddr(dma_base as usize),
261 length: dma_length,
262 }],
263 frames,
264 PhysicalTableMemory,
265 )?;
266 let table_frames = policy.page_table.frames_used().unwrap_or(0);
267 clean_table_pool(next, table_frames * 4096);
268
269 let tables = smmu_tables();
270 assert_eq!(
271 core::mem::size_of::<[[u64; 8]; STREAM_ENTRIES as usize]>(),
272 SMMU_TABLES_ALIGN,
273 "stream table must be exactly 256 KiB"
274 );
275 assert_eq!(STREAM_ENTRIES.trailing_zeros(), 12, "LOG2SIZE must be 12");
276 assert!(stream_id < STREAM_ENTRIES, "SID outside the stream table");
277 assert_eq!(
278 tables as usize % SMMU_TABLES_ALIGN,
279 0,
280 "SMMU stream table is not 256 KiB aligned"
281 );
282 // Safety: the tables are one live, identity-mapped, 256 KiB-aligned
283 // allocation owned by the SMMU from here on; the register aperture is
284 // identity mapped (128 KiB) by enter_kernel_mmu. configure_linear_stream
285 // writes the tables and cleans them to the SMMU itself before it
286 // programs STRTAB_BASE or enables anything.
287 let linear = unsafe {
288 aienos_kernel::smmu::LinearTables::new(
289 core::ptr::addr_of_mut!((*tables).stream_table).cast(),
290 STREAM_ENTRIES,
291 core::ptr::addr_of_mut!((*tables).command_queue).cast(),
292 SMMU_QUEUE_ENTRIES,
293 core::ptr::addr_of_mut!((*tables).event_queue).cast(),
294 SMMU_QUEUE_ENTRIES,
295 core::ptr::addr_of_mut!((*tables).context),
296 )?
297 };
298 let mut regs = unsafe { aienos_kernel::smmu::MmioRegisters::new(iort.base as usize) };
299 aienos_kernel::smmu::configure_linear_stream(
300 &mut regs,
301 &linear,
302 policy.stream_id,
303 &policy.cd,
304 aienos_kernel::smmu::DEFAULT_SPINS,
305 )?;
306 Ok(stream_id)
307}
308
309#[cfg(feature = "nvme-read")]
310fn configure_smmu_for_nvme(
311 iort: Option<&acpi::IortSmmu>,
312 nvme: Option<nvme_read::NvmeLocation>,
313 pool_base: usize,
314 frames_used: usize,
315) -> Result<u32, aienos_kernel::smmu::Error> {
316 let iort = iort.ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
317 let nvme = nvme.ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
318 let stream_id = nvme
319 .stream_id(iort)
320 .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
321 let (dma_base, dma_length) = nvme.dma_window();
322 let remaining = PT_POOL_PAGES.saturating_sub(frames_used);
323 let next = pool_base
324 .checked_add(
325 frames_used
326 .checked_mul(4096)
327 .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?,
328 )
329 .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
330 let frames = FixedFramePool::new(PhysAddr(next), remaining)
331 .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?;
332 // Stage-1 table that maps only the NVMe DMA arena (identity).
333 let policy = aienos_kernel::smmu::build_dma_policy(
334 stream_id,
335 1,
336 &[aienos_kernel::smmu::DmaWindow {
337 iova: dma_base as usize,
338 pa: PhysAddr(dma_base as usize),
339 length: dma_length,
340 }],
341 frames,
342 PhysicalTableMemory,
343 )?;
344 let table_frames = policy.page_table.frames_used().unwrap_or(0);
345 clean_table_pool(next, table_frames * 4096);
346
347 let base = smmu_tables() as *mut u8;
348 assert!(stream_id < STREAM_ENTRIES, "SID outside the stream table");
349 // Field addresses are reached by byte offset from the allocation base, so
350 // no typed pointer dereference happens here.
351 let field = |offset: usize| base.wrapping_add(offset);
352 // Safety: as in configure_smmu_for_xhci, the tables are one live,
353 // identity-mapped, 256 KiB-aligned allocation owned by the SMMU; the
354 // register aperture is identity mapped by enter_kernel_mmu.
355 let linear = unsafe {
356 aienos_kernel::smmu::LinearTables::new(
357 field(core::mem::offset_of!(SmmuTables, stream_table)).cast::<[u64; 8]>(),
358 STREAM_ENTRIES,
359 field(core::mem::offset_of!(SmmuTables, command_queue)).cast::<[u64; 2]>(),
360 SMMU_QUEUE_ENTRIES,
361 field(core::mem::offset_of!(SmmuTables, event_queue)).cast::<[u64; 4]>(),
362 SMMU_QUEUE_ENTRIES,
363 field(core::mem::offset_of!(SmmuTables, context)).cast::<[u64; 8]>(),
364 )?
365 };
366 let mut regs = unsafe { aienos_kernel::smmu::MmioRegisters::new(iort.base as usize) };
367 aienos_kernel::smmu::configure_linear_stream(
368 &mut regs,
369 &linear,
370 policy.stream_id,
371 &policy.cd,
372 aienos_kernel::smmu::DEFAULT_SPINS,
373 )?;
374 Ok(stream_id)
375}
376
377#[allow(clippy::too_many_arguments)]
378fn enter_kernel_mmu(
379 memory_map: &impl MemoryMap,
380 pool_base: usize,
381 image: AddressRange,
382 sections: &[aienos_kernel::mem::map_plan::PeSection],
383 attrs: Option<&[aienos_kernel::mem::map_plan::RuntimeAttributes]>,
384 framebuffer: Option<FramebufferInfo>,
385 uart: Option<acpi::SpcrConsole>,
386 xhci_mmio: Option<u64>,
387 ecam: Option<AddressRange>,
388 gic: Option<acpi::GicBases>,
389 smmu_mmio: Option<u64>,
390 nvme_mmio: Option<u64>,
391 nvme_ecam: Option<AddressRange>,
392) -> KernelMmu {
393 let descriptors: alloc::vec::Vec<_> = memory_map
394 .entries()
395 .map(|d| EfiMemoryDescriptor {
396 memory_type: d.ty.0,
397 phys_start: d.phys_start,
398 page_count: d.page_count,
399 attribute: d.att.bits(),
400 })
401 .collect();
402 let mut mmio = alloc::vec::Vec::new();
403 if let Some(fb) = framebuffer {
404 mmio.push(AddressRange {
405 start: fb.base & !4095,
406 length: (fb.size_bytes + (fb.base & 4095) + 4095) & !4095,
407 });
408 }
409 if let Some(console) = uart {
410 mmio.push(AddressRange {
411 start: console.base & !4095,
412 length: 4096,
413 });
414 }
415 if let Some(base) = xhci_mmio {
416 mmio.push(AddressRange {
417 start: base & !4095,
418 length: 0x10000,
419 });
420 }
421 if let Some(range) = ecam {
422 mmio.push(range);
423 }
424 if let Some(base) = nvme_mmio {
425 mmio.push(AddressRange {
426 start: base & !4095,
427 length: 0x10000,
428 });
429 }
430 if let Some(range) = nvme_ecam {
431 mmio.push(range);
432 }
433 if let Some(gic) = gic {
434 if let Some(base) = gic.distributor {
435 mmio.push(AddressRange {
436 start: base,
437 length: 0x10000,
438 });
439 }
440 if let Some((base, size)) = gic.redistributor {
441 mmio.push(AddressRange {
442 start: base,
443 length: u64::from(size).max(0x20000),
444 });
445 }
446 }
447 if let Some(base) = smmu_mmio {
448 mmio.push(AddressRange {
449 start: base & !4095,
450 length: 0x20000,
451 });
452 }
453 let (plan, decision) =
454 map_plan::build_map_plan(&descriptors, image.start, image, sections, attrs, &mmio)
455 .expect("identity map plan rejected firmware layout");
456 let pool =
457 FixedFramePool::new(PhysAddr(pool_base), PT_POOL_PAGES).expect("invalid page table pool");
458 let mut tables = PageTableBuilder::new(pool, PhysicalTableMemory)
459 .expect("page table root allocation failed");
460 for mapping in plan {
461 tables
462 .map(
463 mapping.range.start as usize,
464 PhysAddr(mapping.range.start as usize),
465 mapping.range.length as usize,
466 mapping.flags,
467 )
468 .expect("identity mapping failed");
469 }
470 let root = tables.root().0;
471 let used = tables.frames_used().unwrap_or(0);
472 clean_table_pool(pool_base, PT_POOL_PAGES * 4096);
473 let parange: u64;
474 #[cfg(target_arch = "aarch64")]
475 unsafe {
476 core::arch::asm!("mrs {0}, id_aa64mmfr0_el1", out(reg) parange, options(nomem, nostack));
477 }
478 #[cfg(not(target_arch = "aarch64"))]
479 {
480 parange = 5;
481 }
482 // Record the translation firmware left us on, so the report can show the
483 // switch (issue #27). Firmware runs at EL2 here; the switch refuses
484 // anything else and halts below.
485 let firmware = firmware_translation();
486 let entered = unsafe {
487 aienos_kernel::arch::aarch64::enter_el1h_mmu(
488 root,
489 map_plan::mair_el1(),
490 map_plan::tcr_el1((parange & 0xf) as u8),
491 map_plan::sctlr_el1(),
492 )
493 };
494 if !entered {
495 // Fail closed with evidence: the kernel must not continue on
496 // firmware's translation, and the reason must survive the halt.
497 let mut halt_report = Report::new();
498 header(&mut halt_report, "halt");
499 write_index_line(&mut halt_report);
500 let el = aienos_kernel::arch::aarch64::current_el();
501 let _ = writeln!(
502 halt_report,
503 "el1_switch: refused (current EL{el}, expected EL2)"
504 );
505 let _ = writeln!(halt_report, "boot: halted before kernel entry");
506 let _ = send_to_console(halt_report.as_str());
507 let _ = save_report_var(halt_report.as_bytes());
508 aienos_kernel::arch::aarch64::halt();
509 }
510 fatal::install_exception_vectors();
511 KernelMmu {
512 pt_frames_used: used,
513 root,
514 runtime_rx_unsplit: decision == Some(map_plan::RuntimeDecision::RuntimeCodeRxUnsplit),
515 firmware,
516 }
517}
518
519/// Result of `enter_kernel_mmu`: the AIENOS table root and what firmware
520/// was using before the switch.
521struct KernelMmu {
522 pt_frames_used: usize,
523 root: usize,
524 runtime_rx_unsplit: bool,
525 firmware: FirmwareTranslation,
526}
527
528/// Translation state firmware handed over, read before the EL1 switch.
529#[derive(Clone, Copy)]
530struct FirmwareTranslation {
531 el: u8,
532 /// TTBR0 of the firmware's regime (TTBR0_EL2 when `el` is 2).
533 ttbr0: u64,
534 /// SCTLR.M of the firmware's regime.
535 mmu_on: bool,
536}
537
538/// Translation table base address bits of a TTBR value (ASID and CnP removed).
539const TTBR_BADDR_MASK: u64 = 0x0000_ffff_ffff_fffe;
540
541fn firmware_translation() -> FirmwareTranslation {
542 let el = aienos_kernel::arch::aarch64::current_el();
543 #[cfg_attr(not(target_arch = "aarch64"), allow(unused_mut))]
544 let (mut ttbr0, mut sctlr) = (0u64, 0u64);
545 #[cfg(target_arch = "aarch64")]
546 if el == 2 {
547 unsafe {
548 core::arch::asm!("mrs {0}, ttbr0_el2", out(reg) ttbr0, options(nomem, nostack));
549 core::arch::asm!("mrs {0}, sctlr_el2", out(reg) sctlr, options(nomem, nostack));
550 }
551 }
552 FirmwareTranslation {
553 el,
554 ttbr0,
555 mmu_on: sctlr & 1 != 0,
556 }
557}
558
559/// Live TTBR0_EL1, read at EL1 after the switch.
560fn current_ttbr0_el1() -> u64 {
561 let value: u64;
562 #[cfg(target_arch = "aarch64")]
563 unsafe {
564 core::arch::asm!("mrs {0}, ttbr0_el1", out(reg) value, options(nomem, nostack));
565 }
566 #[cfg(not(target_arch = "aarch64"))]
567 {
568 value = 0;
569 }
570 value
571}
572
573#[cfg(feature = "usb-keyboard")]
574mod usb_keyboard;
575
576#[cfg(feature = "nvme-read")]
577mod nvme_read;
578
579#[cfg(feature = "store-qual")]
580mod store_qual;
581
582/// Commit this image was built from; `scripts/stage_one_time_boot.sh` sets it.
583const COMMIT: &str = match option_env!("AIENOS_COMMIT") {
584 Some(commit) => commit,
585 None => "unknown",
586};
587const REPORT_VERSION: u32 = 1;
588const REPORT_VAR: &CStr16 = cstr16!("AienosBootReportV1");
589const REPORT_VENDOR: VariableVendor = VariableVendor(guid!("a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a37"));
590/// ADR 0008 bounds on the post-handoff firmware variable.
591const MAX_VAR_WRITES: u8 = 3;
592const MAX_VAR_BYTES: usize = 3072;
593/// Countdown before reset; `AIENOS_RESTART_SECS` at build time shortens it for emulator tests.
594fn restart_after_secs() -> u64 {
595 option_env!("AIENOS_RESTART_SECS")
596 .and_then(|s| s.parse().ok())
597 .unwrap_or(30)
598}
599const ERROR: (u8, u8, u8) = (0xff, 0x6b, 0x6b);
600
601type Report = ReportBuf<MAX_VAR_BYTES>;
602
603const STAGES: [&str; 12] = [
604 "firmware_entry",
605 "gb10_discovery",
606 "acpi_topology",
607 "framebuffer_discovery",
608 "pre_exit_report_saved",
609 "exit_boot_services",
610 "exception_vectors_installed",
611 "kernel_entered",
612 "screen_report_drawn",
613 "final_report_saved",
614 "uart_report_sent",
615 "countdown",
616];
617const FIRMWARE_ENTRY: u8 = 0;
618const GB10_DISCOVERY: u8 = 1;
619const ACPI_TOPOLOGY: u8 = 2;
620const FRAMEBUFFER_DISCOVERY: u8 = 3;
621const PRE_EXIT_SAVED: u8 = 4;
622const EXIT_BOOT_SERVICES: u8 = 5;
623const VECTORS_INSTALLED: u8 = 6;
624const KERNEL_ENTERED: u8 = 7;
625const SCREEN_DRAWN: u8 = 8;
626const FINAL_SAVED: u8 = 9;
627const UART_SENT: u8 = 10;
628const COUNTDOWN: u8 = 11;
629
630static STAGE: AtomicU8 = AtomicU8::new(FIRMWARE_ENTRY);
631static EXITED: AtomicBool = AtomicBool::new(false);
632static IN_FATAL: AtomicBool = AtomicBool::new(false);
633static VAR_WRITES: AtomicU8 = AtomicU8::new(0);
634/// Serial console from the firmware SPCR table (independent of GB10 discovery).
635static CONSOLE: SpinLock<Option<acpi::UartKind>> = SpinLock::new(None);
636static FREQUENCY_HZ: AtomicU64 = AtomicU64::new(0);
637static FRAMEBUFFER: SpinLock<Option<FramebufferInfo>> = SpinLock::new(None);
638static IRQ_TICKS: AtomicU64 = AtomicU64::new(0);
639
640/// Counter value at the previous tick (or when the window armed the timer).
641static TICK_LAST: AtomicU64 = AtomicU64::new(0);
642/// Smallest and largest counter distance between consecutive ticks.
643static TICK_MIN: AtomicU64 = AtomicU64::new(u64::MAX);
644static TICK_MAX: AtomicU64 = AtomicU64::new(0);
645
646/// Called by the IRQ dispatcher only after it acknowledged INTID 30 and
647/// re-armed the timer, and before it ends the interrupt.
648extern "C" fn timer_irq() {
649 IRQ_TICKS.fetch_add(1, Ordering::Relaxed);
650 let now =
651 aienos_kernel::timer::TimerRegisters::counter(&aienos_kernel::timer::Aarch64TimerRegisters);
652 let interval = now.wrapping_sub(TICK_LAST.swap(now, Ordering::Relaxed));
653 TICK_MIN.fetch_min(interval, Ordering::Relaxed);
654 TICK_MAX.fetch_max(interval, Ordering::Relaxed);
655}
656
657/// What the timer window measured, snapshotted when the window closed.
658#[derive(Clone, Copy)]
659struct TimerWindow {
660 ticks: u64,
661 ms: u64,
662 frequency_hz: u64,
663 /// Counter distance between ticks: smallest, largest, and from arming
664 /// the timer to the last tick (`span / ticks` is the average interval).
665 min_interval: u64,
666 max_interval: u64,
667 span: u64,
668 distributor: u64,
669 redistributor: u64,
670 /// GICD_PIDR2.ArchRev, 3 for GICv3.
671 arch_rev: u32,
672 /// ICC_SRE_EL1.SRE read back: 1 when the system register interface is live.
673 icc_sre: u64,
674}
675
676impl TimerWindow {
677 fn us(&self, counter: u64) -> u64 {
678 if self.frequency_hz == 0 {
679 return 0;
680 }
681 (u128::from(counter) * 1_000_000 / u128::from(self.frequency_hz)) as u64
682 }
683}
684
685fn run_timer_window(gic: Option<acpi::GicBases>) -> Option<TimerWindow> {
686 let bases = gic?;
687 let distributor = bases.distributor? as usize;
688 let (redistributor, _) = bases.redistributor?;
689 let mut rd = aienos_kernel::gic::GicRedistributor(aienos_kernel::gic::MmioGicRegisters {
690 base: redistributor as usize,
691 });
692 if !rd.wake(1_000_000) {
693 return None;
694 }
695 rd.configure_ppi(30, 0x80);
696 let mut dist = aienos_kernel::gic::GicDistributor(aienos_kernel::gic::MmioGicRegisters {
697 base: distributor,
698 });
699 dist.enable_group1();
700 let mut cpu = aienos_kernel::gic::Aarch64GicCpuInterface;
701 aienos_kernel::gic::GicCpuInterface::set_priority_mask(&mut cpu, 0xff);
702 aienos_kernel::gic::GicCpuInterface::enable_group1(&mut cpu);
703 let arch_rev = {
704 let mut regs = aienos_kernel::gic::MmioGicRegisters { base: distributor };
705 (aienos_kernel::gic::GicRegisters::read32(&mut regs, GICD_PIDR2) >> 4) & 0xf
706 };
707 let icc_sre: u64;
708 #[cfg(target_arch = "aarch64")]
709 unsafe {
710 core::arch::asm!("mrs {0}, ICC_SRE_EL1", out(reg) icc_sre, options(nomem, nostack));
711 }
712 #[cfg(not(target_arch = "aarch64"))]
713 {
714 icc_sre = 0;
715 }
716 let mut timer = aienos_kernel::timer::Aarch64TimerRegisters;
717 let hz = aienos_kernel::timer::TimerRegisters::frequency(&timer);
718 let start = aienos_kernel::timer::TimerRegisters::counter(&timer);
719 TICK_LAST.store(start, Ordering::Relaxed);
720 TICK_MIN.store(u64::MAX, Ordering::Relaxed);
721 TICK_MAX.store(0, Ordering::Relaxed);
722 let deadline = start.wrapping_add(hz / 100);
723 aienos_kernel::timer::TimerRegisters::set_compare(&mut timer, deadline);
724 aienos_kernel::timer::TimerRegisters::enable_timer(&mut timer, true);
725 aienos_kernel::fatal::set_irq_hook(timer_irq);
726 unsafe {
727 core::arch::asm!("msr daifclr, #2", "isb", options(nostack));
728 }
729 while aienos_kernel::timer::TimerRegisters::counter(&timer).wrapping_sub(start) < hz / 5 {
730 core::hint::spin_loop();
731 }
732 unsafe {
733 core::arch::asm!("msr daifset, #2", "isb", options(nostack));
734 }
735 aienos_kernel::timer::TimerRegisters::enable_timer(&mut timer, false);
736 let ticks = IRQ_TICKS.load(Ordering::Relaxed);
737 let min_interval = TICK_MIN.load(Ordering::Relaxed);
738 Some(TimerWindow {
739 ticks,
740 ms: 200,
741 frequency_hz: hz,
742 min_interval: if ticks == 0 { 0 } else { min_interval },
743 max_interval: TICK_MAX.load(Ordering::Relaxed),
744 span: if ticks == 0 {
745 0
746 } else {
747 TICK_LAST.load(Ordering::Relaxed).wrapping_sub(start)
748 },
749 distributor: distributor as u64,
750 redistributor,
751 arch_rev,
752 icc_sre: icc_sre & 1,
753 })
754}
755
756/// Peripheral ID2 register of the distributor; bits [7:4] are ArchRev.
757const GICD_PIDR2: usize = 0xffe8;
758
759fn stage(s: u8) {
760 STAGE.store(s, Ordering::SeqCst);
761}
762
763fn stage_name() -> &'static str {
764 STAGES
765 .get(STAGE.load(Ordering::SeqCst) as usize)
766 .copied()
767 .unwrap_or("unknown")
768}
769
770fn header(out: &mut impl Write, kind: &str) {
771 let _ = writeln!(out, "report_version: {REPORT_VERSION}");
772 let _ = writeln!(out, "aienos_commit: {COMMIT}");
773 let _ = writeln!(out, "report_kind: {kind}");
774 let _ = writeln!(out, "last_stage: {}", stage_name());
775}
776
777/// Bounded report write (ADR 0008). Failure is reported, never fatal.
778fn save_report_var(bytes: &[u8]) -> Result<u8, &'static str> {
779 if bytes.len() > MAX_VAR_BYTES {
780 return Err("report larger than the bound");
781 }
782 let n = VAR_WRITES.fetch_add(1, Ordering::SeqCst);
783 if n >= MAX_VAR_WRITES {
784 return Err("write budget for this boot spent");
785 }
786 uefi::runtime::set_variable(
787 REPORT_VAR,
788 &REPORT_VENDOR,
789 VariableAttributes::NON_VOLATILE
790 | VariableAttributes::BOOTSERVICE_ACCESS
791 | VariableAttributes::RUNTIME_ACCESS,
792 bytes,
793 )
794 .map(|()| n + 1)
795 .map_err(|_| "firmware refused the write")
796}
797
798type BridgeScan = aienos_accel::RootBridgeScan;
799type RootOutcome = aienos_accel::RootBridgeOutcome;
800
801/// Outcome of pre-exit GB10 discovery: the identity when found, plus a
802/// bounded record of why it was not (bridges seen, opens refused, segments,
803/// BAR state) so the pre-exit and final reports can say what happened.
804struct Gb10Discovery {
805 identity: Option<aienos_accel::Gb10Identity>,
806 /// Number of handles carrying the `PciRootBridgeIo` protocol, when the
807 /// handle database answered.
808 handles: Option<u16>,
809 roots: [Option<RootOutcome>; MAX_ROOT_BRIDGES],
810}
811
812/// At most this many root bridges are recorded; extras are still searched.
813const MAX_ROOT_BRIDGES: usize = 4;
814
815/// Compact status names for the report (no `Debug` tables in the image).
816fn status_name(status: Status) -> &'static str {
817 match status {
818 Status::ACCESS_DENIED => "ACCESS_DENIED",
819 Status::NOT_FOUND => "NOT_FOUND",
820 Status::INVALID_PARAMETER => "INVALID_PARAMETER",
821 Status::OUT_OF_RESOURCES => "OUT_OF_RESOURCES",
822 Status::UNSUPPORTED => "UNSUPPORTED",
823 _ => "OTHER",
824 }
825}
826
827impl Gb10Discovery {
828 /// Record the outcome of one root bridge, bounded by `MAX_ROOT_BRIDGES`.
829 fn record(&mut self, outcome: RootOutcome) {
830 if let Some(slot) = self.roots.iter_mut().find(|s| s.is_none()) {
831 *slot = Some(outcome);
832 }
833 }
834
835 /// Report lines explaining why no GB10 identity was produced.
836 fn write_diagnostics(&self, out: &mut Report) {
837 aienos_accel::write_discovery_diagnostics(out, self.handles, &self.roots);
838 }
839}
840
841/// Read the config registers needed for the BAR check. `None` when the
842/// vendor/device pair does not match the GB10 or a config read failed.
843fn read_candidate(
844 root: &mut PciRootBridgeIo,
845 address: PciIoAddress,
846) -> Option<(u32, u32, u32, u32)> {
847 let config = |offset| address.with_register(offset);
848 let vendor_device = root.pci().read_one::<u32>(config(0)).ok()?;
849 if vendor_device != 0x2e12_10de {
850 return None;
851 }
852 let command_status = root.pci().read_one::<u32>(config(4)).ok()?;
853 let bar0_low = root.pci().read_one::<u32>(config(0x10)).ok()?;
854 let bar0_high = root.pci().read_one::<u32>(config(0x14)).ok()?;
855 Some((vendor_device, command_status, bar0_low, bar0_high))
856}
857
858fn probe_gb10(
859 root: &mut PciRootBridgeIo,
860 address: PciIoAddress,
861 scan: &mut BridgeScan,
862) -> Option<aienos_accel::Gb10Identity> {
863 let (vendor_device, command_status, bar0_low, bar0_high) = read_candidate(root, address)?;
864 let bar = match aienos_accel::Gb10Bar::from_config(
865 aienos_accel::PciLocation {
866 segment: root.segment_nr(),
867 bus: address.bus,
868 device: address.dev,
869 function: address.fun,
870 },
871 vendor_device,
872 command_status,
873 bar0_low,
874 bar0_high,
875 ) {
876 Some(bar) => bar,
877 None => {
878 // The GB10 was found but its BAR or command register was not
879 // usable; keep the raw values so the report shows the BAR state.
880 scan.rejected_candidate = Some((command_status, bar0_low, bar0_high));
881 return None;
882 }
883 };
884 let pmc_boot_0 = root
885 .memory()
886 .read_one::<u32>(bar.physical_base + aienos_accel::PMC_BOOT_0)
887 .ok()?;
888 let pmc_boot_42 = root
889 .memory()
890 .read_one::<u32>(bar.physical_base + aienos_accel::PMC_BOOT_42)
891 .ok()?;
892 Some(aienos_accel::Gb10Identity {
893 bar,
894 pmc_boot_0,
895 pmc_boot_42,
896 })
897}
898
899/// Walk every function on one bus of this root bridge.
900/// Returns the GB10 identity when the GB10 is found here.
901fn scan_bus(
902 root: &mut PciRootBridgeIo,
903 bus: u8,
904 scan: &mut BridgeScan,
905) -> Option<aienos_accel::Gb10Identity> {
906 for dev in 0..32u8 {
907 for fun in 0..8u8 {
908 let address = PciIoAddress::new(bus, dev, fun);
909 let config = |offset| address.with_register(offset);
910 let Ok(vendor_device) = root.pci().read_one::<u32>(config(0)) else {
911 continue;
912 };
913 if vendor_device & 0xffff == 0xffff {
914 if fun == 0 {
915 break; // no function 0: no further functions on this device
916 }
917 continue;
918 }
919 scan.devices += 1;
920 if vendor_device == 0x2e12_10de {
921 if let Some(identity) = probe_gb10(root, address, scan) {
922 return Some(identity);
923 }
924 }
925 let header_type = root
926 .pci()
927 .read_one::<u32>(config(0x0c))
928 .map(|v| ((v >> 16) & 0xff) as u8)
929 .unwrap_or(0);
930 if header_type & 0x7f == 0x01 {
931 scan.bridges += 1;
932 let window = root
933 .pci()
934 .read_one::<u32>(config(0x18))
935 .map(|v| (((v >> 8) & 0xff) as u8, ((v >> 16) & 0xff) as u8))
936 .unwrap_or((0, 0));
937 if window.0 != 0 && window.1 >= window.0 {
938 scan.windows += 1;
939 }
940 }
941 if fun == 0 && header_type & 0x80 == 0 {
942 break; // single-function device: skip functions 1..8
943 }
944 }
945 }
946 None
947}
948
949/// Read the bus-range resource descriptors of this root bridge, or `None`.
950fn bus_ranges(root: &mut PciRootBridgeIo) -> Option<(u8, u8)> {
951 let mut range: Option<(u8, u8)> = None;
952 for descriptor in root.configuration().ok()? {
953 if descriptor.resource_range_type == ResourceRangeType::Bus {
954 let min = u8::try_from(descriptor.address_min).unwrap_or(u8::MAX);
955 let max = u8::try_from(descriptor.address_max).unwrap_or(u8::MAX);
956 range = Some(match range {
957 Some((lo, hi)) => (lo.min(min), hi.max(max)),
958 None => (min, max),
959 });
960 }
961 }
962 range
963}
964
965/// Scan one root bridge. Returns the GB10 identity and the outcome to record.
966fn scan_root(root: &mut PciRootBridgeIo) -> (Option<aienos_accel::Gb10Identity>, RootOutcome) {
967 let mut scan = BridgeScan {
968 segment: root.segment_nr(),
969 devices: 0,
970 bridges: 0,
971 windows: 0,
972 rejected_candidate: None,
973 };
974 // Config A puts GB10 at segment 15, bus 1, device 0, function 0.
975 // Try that first so the common boot path does not walk every bus.
976 if scan.segment == 15 {
977 if let Some(identity) = probe_gb10(root, PciIoAddress::new(1, 0, 0), &mut scan) {
978 return (Some(identity), RootOutcome::Scanned(scan));
979 }
980 }
981 // No firmware bus descriptors: fall back to the root bus so the scan
982 // still sees devices whose bus numbers firmware never published.
983 let (bus_min, bus_max) = bus_ranges(root).unwrap_or((0, 0));
984 for bus in bus_min..=bus_max {
985 if let Some(identity) = scan_bus(root, bus, &mut scan) {
986 return (Some(identity), RootOutcome::Scanned(scan));
987 }
988 }
989 (None, RootOutcome::Scanned(scan))
990}
991
992fn discover_gb10() -> Gb10Discovery {
993 let mut discovery = Gb10Discovery {
994 identity: None,
995 handles: None,
996 roots: [const { None }; MAX_ROOT_BRIDGES],
997 };
998 let handles = match uefi::boot::find_handles::<PciRootBridgeIo>() {
999 Ok(handles) => handles,
1000 Err(_) => return discovery,
1001 };
1002 discovery.handles = Some(u16::try_from(handles.len()).unwrap_or(u16::MAX));
1003 for handle in handles {
1004 // Shared (GetProtocol) open: the firmware PCI bus driver holds this
1005 // protocol open ByDriver, so an exclusive open is refused with
1006 // ACCESS_DENIED. Shared reads are safe here: this boot code only
1007 // reads through the protocol, and firmware keeps the protocol
1008 // installed until boot services are exited.
1009 let mut root = match unsafe {
1010 uefi::boot::open_protocol::<PciRootBridgeIo>(
1011 OpenProtocolParams {
1012 handle,
1013 agent: uefi::boot::image_handle(),
1014 controller: None,
1015 },
1016 OpenProtocolAttributes::GetProtocol,
1017 )
1018 } {
1019 Ok(root) => root,
1020 Err(e) => {
1021 discovery.record(RootOutcome::OpenRefused(status_name(e.status())));
1022 continue;
1023 }
1024 };
1025 let (found, outcome) = scan_root(&mut root);
1026 discovery.record(outcome);
1027 if let Some(identity) = found {
1028 discovery.identity = Some(identity);
1029 return discovery;
1030 }
1031 }
1032 discovery
1033}
1034
1035/// Reads a firmware ACPI table whose header is at `addr`.
1036///
1037/// # Safety
1038/// `addr` must be zero or point to a mapped ACPI table left by firmware.
1039unsafe fn table_at<'a>(addr: usize) -> Option<&'a [u8]> {
1040 if addr == 0 {
1041 return None;
1042 }
1043 let header = unsafe { core::slice::from_raw_parts(addr as *const u8, acpi::SDT_HEADER_LEN) };
1044 let len = acpi::sdt_length(header)?;
1045 if !(acpi::SDT_HEADER_LEN..=1 << 20).contains(&len) {
1046 return None;
1047 }
1048 Some(unsafe { core::slice::from_raw_parts(addr as *const u8, len) })
1049}
1050
1051/// Firmware ACPI facts read before exit: core inventory (MADT) and the serial
1052/// console (SPCR), found by walking RSDP, then XSDT.
1053#[derive(Default)]
1054struct AcpiFacts {
1055 cpu: Option<acpi::CpuTopology>,
1056 spcr: Option<acpi::SpcrConsole>,
1057 gic: Option<acpi::GicBases>,
1058 #[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
1059 mcfg: Option<&'static [u8]>,
1060 #[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
1061 iort: Option<acpi::IortSmmu>,
1062}
1063
1064fn discover_acpi(boot_mpidr: u64) -> AcpiFacts {
1065 let mut facts = AcpiFacts::default();
1066 let Some(rsdp) = uefi::system::with_config_table(|entries| {
1067 entries
1068 .iter()
1069 .find(|e| e.guid == ConfigTableEntry::ACPI2_GUID)
1070 .map(|e| e.address as usize)
1071 }) else {
1072 return facts;
1073 };
1074 // SAFETY: firmware published this ACPI 2.0 RSDP, which is 36 bytes long.
1075 let rsdp = unsafe { core::slice::from_raw_parts(rsdp as *const u8, 36) };
1076 if &rsdp[..8] != b"RSD PTR " {
1077 return facts;
1078 }
1079 let Some(xsdt_addr) = rsdp[24..32].try_into().ok().map(u64::from_le_bytes) else {
1080 return facts;
1081 };
1082 // SAFETY: the RSDP points at the XSDT; its checksum is validated below.
1083 let Some(xsdt) = (unsafe { table_at(xsdt_addr as usize) })
1084 .and_then(|t| acpi::checked_table(t, b"XSDT").ok())
1085 else {
1086 return facts;
1087 };
1088 for addr in acpi::xsdt_entries(xsdt) {
1089 // SAFETY: XSDT entries point at firmware ACPI tables.
1090 let Some(table) = (unsafe { table_at(addr as usize) }) else {
1091 continue;
1092 };
1093 match &table[..4] {
1094 b"APIC" => {
1095 facts.cpu = acpi::madt_cpu_topology_for(table, Some(boot_mpidr)).ok();
1096 facts.gic = acpi::madt_gic_bases(table).ok();
1097 }
1098 b"SPCR" => facts.spcr = acpi::spcr_console(table).ok(),
1099 #[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
1100 b"MCFG" => facts.mcfg = Some(table),
1101 #[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
1102 b"IORT" => facts.iort = acpi::iort_smmuv3(table).ok().flatten(),
1103 _ => {}
1104 }
1105 }
1106 facts
1107}
1108
1109fn write_uart_line(out: &mut impl Write, spcr: Option<acpi::SpcrConsole>) {
1110 let _ = match spcr {
1111 None => writeln!(out, "uart: none (no SPCR)"),
1112 Some(s) => match s.kind() {
1113 acpi::UartKind::Ns16550Mmio32(base) => {
1114 writeln!(
1115 out,
1116 "uart: 16550 mmio32 at {base:#x} (spcr type {:#04x})",
1117 s.interface_type
1118 )
1119 }
1120 acpi::UartKind::Pl011(base) => {
1121 writeln!(
1122 out,
1123 "uart: pl011 at {base:#x} (spcr type {:#04x})",
1124 s.interface_type
1125 )
1126 }
1127 acpi::UartKind::Unsupported => writeln!(
1128 out,
1129 "uart: unsupported (spcr type {:#04x}, space {}, width {})",
1130 s.interface_type, s.address_space, s.register_bit_width
1131 ),
1132 },
1133 };
1134}
1135
1136/// Send text to the SPCR console, bounded. Returns the outcome for the report.
1137fn send_to_console(text: &str) -> &'static str {
1138 let kind = CONSOLE.try_lock().and_then(|k| *k);
1139 match kind.and_then(EarlyConsole::from_kind) {
1140 Some(console) => {
1141 console.write_str("\n");
1142 console.write_str(text);
1143 if console.is_dead() {
1144 "no response"
1145 } else {
1146 "sent"
1147 }
1148 }
1149 None => "no drivable console",
1150 }
1151}
1152
1153fn el0_console_write(bytes: &[u8]) {
1154 let Some(text) = core::str::from_utf8(bytes).ok() else {
1155 return;
1156 };
1157 let kind = CONSOLE.try_lock().and_then(|k| *k);
1158 if let Some(console) = kind.and_then(EarlyConsole::from_kind) {
1159 console.write_str(text);
1160 }
1161}
1162
1163/// Geometry of the display mode the firmware already configured.
1164fn discover_framebuffer() -> Option<FramebufferInfo> {
1165 let handle = uefi::boot::get_handle_for_protocol::<GraphicsOutput>().ok()?;
1166 // Shared open: an exclusive open would disconnect the firmware console.
1167 let mut gop = unsafe {
1168 uefi::boot::open_protocol::<GraphicsOutput>(
1169 OpenProtocolParams {
1170 handle,
1171 agent: uefi::boot::image_handle(),
1172 controller: None,
1173 },
1174 OpenProtocolAttributes::GetProtocol,
1175 )
1176 }
1177 .ok()?;
1178 let mode = gop.current_mode_info();
1179 let order = match mode.pixel_format() {
1180 PixelFormat::Rgb => PixelOrder::Rgb,
1181 PixelFormat::Bgr => PixelOrder::Bgr,
1182 _ => return None,
1183 };
1184 let (width, height) = mode.resolution();
1185 let mut fb = gop.frame_buffer();
1186 FramebufferInfo {
1187 base: fb.as_mut_ptr() as u64,
1188 size_bytes: fb.size() as u64,
1189 width,
1190 height,
1191 stride: mode.stride(),
1192 order,
1193 }
1194 .validated()
1195}
1196
1197/// Replace `\EFI\AIENOS\BOOTREPORT.TXT` on the volume this image was loaded from.
1198fn save_report_file(text: &str) -> uefi::Result {
1199 let mut fs = uefi::boot::get_image_file_system(uefi::boot::image_handle())?;
1200 let mut root = fs.open_volume()?;
1201 let path = cstr16!("\\EFI\\AIENOS\\BOOTREPORT.TXT");
1202 if let Ok(old) = root.open(path, FileMode::ReadWrite, FileAttribute::empty()) {
1203 let _ = old.delete();
1204 }
1205 let mut file = root
1206 .open(path, FileMode::CreateReadWrite, FileAttribute::empty())?
1207 .into_regular_file()
1208 .ok_or_else(|| uefi::Error::from(Status::UNSUPPORTED))?;
1209 file.write(text.as_bytes())
1210 .map_err(|e| uefi::Error::from(e.status()))?;
1211 file.flush()
1212}
1213
1214/// Most signed-artifact candidates firmware reads from `\EFI\AIENOS\ARTIFACTS`.
1215const MAX_ARTIFACT_CANDIDATES: usize = 48;
1216/// Largest candidate firmware will read. Bigger files are refused unread.
1217const MAX_ARTIFACT_FILE_BYTES: u64 = 640 * 1024;
1218const ARTIFACT_NAME_BYTES: usize = 32;
1219
1220/// One candidate file: a name plus the firmware-allocated bytes holding it.
1221/// Firmware is only a byte provider (ADR 0014 §1); it never parses or judges
1222/// the contents. The kernel copies these bytes to staging before parsing.
1223#[derive(Clone, Copy)]
1224struct ArtifactCandidate {
1225 name: [u8; ARTIFACT_NAME_BYTES],
1226 name_len: usize,
1227 size: u64,
1228 /// Physical (identity) address of the LOADER_DATA copy; 0 when unread.
1229 base: usize,
1230 len: usize,
1231}
1232
1233impl ArtifactCandidate {
1234 const EMPTY: Self = Self {
1235 name: [0; ARTIFACT_NAME_BYTES],
1236 name_len: 0,
1237 size: 0,
1238 base: 0,
1239 len: 0,
1240 };
1241
1242 fn name(&self) -> &str {
1243 core::str::from_utf8(&self.name[..self.name_len]).unwrap_or("?")
1244 }
1245
1246 fn oversize(&self) -> bool {
1247 self.size > MAX_ARTIFACT_FILE_BYTES
1248 }
1249
1250 /// The bytes firmware read, or `None` if the file was refused or failed.
1251 fn bytes(&self) -> Option<&'static [u8]> {
1252 (self.base != 0 && self.len as u64 == self.size)
1253 .then(|| unsafe { core::slice::from_raw_parts(self.base as *const u8, self.len) })
1254 }
1255}
1256
1257struct ArtifactCandidates {
1258 entries: [ArtifactCandidate; MAX_ARTIFACT_CANDIDATES],
1259 count: usize,
1260 /// `.AIEN` files beyond the bound, not read.
1261 ignored: usize,
1262}
1263
1264/// ASCII name of a directory entry, if printable and within the bound.
1265fn artifact_name(name: &CStr16) -> Option<([u8; ARTIFACT_NAME_BYTES], usize)> {
1266 let mut out = [0u8; ARTIFACT_NAME_BYTES];
1267 let mut len = 0;
1268 for c in name.iter() {
1269 let unit = u16::from(*c);
1270 if !(0x21..=0x7e).contains(&unit) || len == ARTIFACT_NAME_BYTES {
1271 return None;
1272 }
1273 out[len] = unit as u8;
1274 len += 1;
1275 }
1276 let suffix = b".aien";
1277 (len > suffix.len() && out[len - suffix.len()..len].eq_ignore_ascii_case(suffix))
1278 .then_some((out, len))
1279}
1280
1281/// Read every `.AIEN` file in `\EFI\AIENOS\ARTIFACTS` (at most eight, sorted
1282/// by name bytes) into its own LOADER_DATA pages before firmware exit. A
1283/// missing directory means no candidates. Must run while boot services live.
1284fn read_artifact_candidates() -> ArtifactCandidates {
1285 let mut out = ArtifactCandidates {
1286 entries: [ArtifactCandidate::EMPTY; MAX_ARTIFACT_CANDIDATES],
1287 count: 0,
1288 ignored: 0,
1289 };
1290 let Ok(mut fs) = uefi::boot::get_image_file_system(uefi::boot::image_handle()) else {
1291 return out;
1292 };
1293 let Ok(mut root) = fs.open_volume() else {
1294 return out;
1295 };
1296 let Some(mut dir) = root
1297 .open(
1298 cstr16!("\\EFI\\AIENOS\\ARTIFACTS"),
1299 FileMode::Read,
1300 FileAttribute::empty(),
1301 )
1302 .ok()
1303 .and_then(|handle| handle.into_directory())
1304 else {
1305 return out;
1306 };
1307 while let Ok(Some(info)) = dir.read_entry_boxed() {
1308 if info.is_directory() {
1309 continue;
1310 }
1311 let Some((name, name_len)) = artifact_name(info.file_name()) else {
1312 continue;
1313 };
1314 let entry = ArtifactCandidate {
1315 name,
1316 name_len,
1317 size: info.file_size(),
1318 ..ArtifactCandidate::EMPTY
1319 };
1320 // Keep the eight smallest names in sorted order.
1321 let key = &entry.name[..entry.name_len];
1322 let at = out.entries[..out.count]
1323 .iter()
1324 .position(|e| key < &e.name[..e.name_len])
1325 .unwrap_or(out.count);
1326 if at == MAX_ARTIFACT_CANDIDATES {
1327 out.ignored += 1;
1328 continue;
1329 }
1330 if out.count == MAX_ARTIFACT_CANDIDATES {
1331 out.ignored += 1;
1332 } else {
1333 out.count += 1;
1334 }
1335 for index in (at + 1..out.count).rev() {
1336 out.entries[index] = out.entries[index - 1];
1337 }
1338 out.entries[at] = entry;
1339 }
1340 for entry in out.entries[..out.count].iter_mut() {
1341 if entry.oversize() || entry.size == 0 {
1342 continue;
1343 }
1344 let Ok(name) = core::str::from_utf8(&entry.name[..entry.name_len]) else {
1345 continue;
1346 };
1347 let mut wide = [0u16; ARTIFACT_NAME_BYTES + 1];
1348 let Ok(path) = CStr16::from_str_with_buf(name, &mut wide) else {
1349 continue;
1350 };
1351 let Some(mut file) = dir
1352 .open(path, FileMode::Read, FileAttribute::empty())
1353 .ok()
1354 .and_then(|handle| handle.into_regular_file())
1355 else {
1356 continue;
1357 };
1358 let size = entry.size as usize;
1359 let Ok(pages) = uefi::boot::allocate_pages(
1360 uefi::boot::AllocateType::AnyPages,
1361 MemoryType::LOADER_DATA,
1362 size.div_ceil(4096),
1363 ) else {
1364 continue;
1365 };
1366 let buffer = unsafe { core::slice::from_raw_parts_mut(pages.as_ptr(), size) };
1367 let mut read = 0;
1368 while read < size {
1369 match file.read(&mut buffer[read..]) {
1370 Ok(0) | Err(_) => break,
1371 Ok(n) => read += n,
1372 }
1373 }
1374 entry.base = pages.as_ptr() as usize;
1375 entry.len = read;
1376 }
1377 out
1378}
1379
1380/// Hand each candidate to the kernel loader. One `artifacts` header record
1381/// goes to the console first; then each candidate's result line and its
1382/// unsigned Admission Receipt v0 stream to the console on their own (they do
1383/// not fit, and do not belong, in the bounded NVRAM report). Returns the
1384/// number of admitted and rejected candidates.
1385fn run_artifact_candidates(candidates: &ArtifactCandidates, kernel_root: usize) -> (usize, usize) {
1386 use aienos_kernel::artifact_loader as loader;
1387 let context = loader::ReceiptContext {
1388 verifier_identity: loader::boot_verifier_identity(COMMIT),
1389 tier: if cfg!(feature = "hardware-staging") {
1390 aienos_kernel::artifact_loader::QualificationTier::Seed0bMachine1
1391 } else {
1392 aienos_kernel::artifact_loader::QualificationTier::Seed0bQemu
1393 },
1394 };
1395 let mut record = Report::new();
1396 header(&mut record, "artifacts");
1397 #[cfg(feature = "seed0b-qualification")]
1398 let _ = writeln!(
1399 record,
1400 "artifact_trust: seed0b-test qualification build — TEST ONLY"
1401 );
1402 let _ = writeln!(record, "artifact_candidates: {}", candidates.count);
1403 let _ = write!(
1404 record,
1405 "artifact_receipt_tier: {}\nartifact_verifier_identity: ",
1406 context.tier.label()
1407 );
1408 for byte in context.verifier_identity {
1409 let _ = write!(record, "{byte:02x}");
1410 }
1411 let _ = write!(record, "\nartifact_policy_digest: ");
1412 for byte in loader::boot_policy_digest() {
1413 let _ = write!(record, "{byte:02x}");
1414 }
1415 let _ = writeln!(record);
1416 let _ = writeln!(
1417 record,
1418 "artifact_frames_free_before: {}",
1419 aienos_kernel::boot::early_free_frames()
1420 );
1421 send_to_console(record.as_str());
1422
1423 let (mut admitted, mut rejected) = (0, 0);
1424 for candidate in &candidates.entries[..candidates.count] {
1425 let name = candidate.name();
1426 let report = if candidate.oversize() {
1427 loader::firmware_rejection(loader::LoadError::StagingTooLarge)
1428 } else if let Some(bytes) = candidate.bytes() {
1429 unsafe { loader::run_boot_candidate(bytes, kernel_root) }
1430 } else {
1431 loader::firmware_rejection(loader::LoadError::FirmwareRead)
1432 };
1433 match report.decision {
1434 loader::Decision::Admitted => admitted += 1,
1435 loader::Decision::Rejected => rejected += 1,
1436 }
1437 // Each part gets its own buffer (16 grant lines alone can exceed
1438 // 2 KiB), and a part that still overflows is reported, never dropped
1439 // silently: the host fails any run that shows `report-truncated:`.
1440 let emit = |part: &str, out: &ReportBuf<4096>| {
1441 send_to_console(out.as_str());
1442 if out.truncated() {
1443 let mut note = ReportBuf::<192>::new();
1444 let _ = writeln!(note, "report-truncated: {name} part={part}");
1445 send_to_console(note.as_str());
1446 }
1447 };
1448 {
1449 let mut out = ReportBuf::<4096>::new();
1450 loader::write_candidate_line(&mut out, name, &report);
1451 emit("candidate", &out);
1452 }
1453 {
1454 let mut out = ReportBuf::<4096>::new();
1455 loader::write_grant_lines(&mut out, name, &report);
1456 emit("grants", &out);
1457 }
1458 {
1459 let mut out = ReportBuf::<4096>::new();
1460 match loader::boot_receipt(&report, &context) {
1461 (sequence, Some(bytes)) => {
1462 loader::write_receipt_line(&mut out, name, sequence, &bytes)
1463 }
1464 (sequence, None) => {
1465 let _ = writeln!(out, "receipt: {name} seq={sequence} invalid");
1466 }
1467 }
1468 emit("receipt", &out);
1469 }
1470 }
1471 let mut tail = ReportBuf::<128>::new();
1472 let _ = writeln!(
1473 tail,
1474 "artifact_frames_free_after: {}",
1475 aienos_kernel::boot::early_free_frames()
1476 );
1477 send_to_console(tail.as_str());
1478 (admitted, rejected)
1479}
1480
1481fn wait_seconds(seconds: u64) {
1482 let frequency_hz = FREQUENCY_HZ.load(Ordering::SeqCst);
1483 let start = counter_ticks();
1484 let ticks = seconds.saturating_mul(frequency_hz);
1485 while counter_ticks().wrapping_sub(start) < ticks {
1486 core::hint::spin_loop();
1487 }
1488}
1489
1490fn screen() -> Option<Screen> {
1491 let info = (*FRAMEBUFFER.try_lock()?)?;
1492 // SAFETY: firmware reported this buffer for the active mode, and nothing
1493 // else draws to it after boot services have exited.
1494 unsafe { Screen::new(info) }
1495}
1496
1497fn write_cpu(
1498 out: &mut impl Write,
1499 cpu: Option<acpi::CpuTopology>,
1500 boot_midr: u64,
1501 boot_mpidr: u64,
1502) {
1503 match cpu {
1504 Some(t) => {
1505 let _ = writeln!(out, "cpu_cores: {}", t.cores);
1506 for (class, count) in t.classes() {
1507 let _ = writeln!(out, "cpu_efficiency_class_{class}: {count}");
1508 }
1509 if t.unknown_class > 0 {
1510 let _ = writeln!(out, "cpu_efficiency_class_unknown: {}", t.unknown_class);
1511 }
1512 match t.boot_class {
1513 Some(class) => {
1514 let _ = writeln!(out, "cpu_boot_core_class: {class}");
1515 }
1516 None => {
1517 let _ = writeln!(
1518 out,
1519 "cpu_boot_core_class: unknown (listed: {})",
1520 if t.boot_core_listed { "yes" } else { "no" }
1521 );
1522 }
1523 }
1524 }
1525 None => {
1526 let _ = writeln!(out, "cpu_topology: unavailable");
1527 }
1528 }
1529 let _ = writeln!(
1530 out,
1531 "boot_cpu_midr: {:#x} (part {:#05x})",
1532 boot_midr,
1533 midr_part(boot_midr)
1534 );
1535 let _ = writeln!(out, "boot_cpu_mpidr: {boot_mpidr:#x}");
1536}
1537
1538/// Reset after firmware exit: PSCI first (not a UEFI runtime service). UEFI
1539/// ResetSystem is used only if PSCI returns without resetting (ADR 0008).
1540fn reset_after_exit(status: Status) -> ! {
1541 psci_system_reset();
1542 uefi::runtime::reset(ResetType::COLD, status, None)
1543}
1544
1545/// Line recording which bounded firmware-variable write this report will be.
1546fn write_index_line(out: &mut impl Write) {
1547 let _ = writeln!(
1548 out,
1549 "nvram_write_index: {} of {MAX_VAR_WRITES}",
1550 VAR_WRITES.load(Ordering::SeqCst) + 1
1551 );
1552}
1553
1554/// Count down on screen, then reset.
1555fn finish(mut screen: Option<Screen>) -> ! {
1556 stage(COUNTDOWN);
1557 match screen.as_mut() {
1558 Some(s) => {
1559 let _ = writeln!(s);
1560 s.set_color(ACCENT);
1561 for remaining in (1..=restart_after_secs()).rev() {
1562 s.clear_row();
1563 let _ = write!(s, "restarting in {remaining} s");
1564 wait_seconds(1);
1565 }
1566 }
1567 None => wait_seconds(restart_after_secs()),
1568 }
1569 reset_after_exit(Status::SUCCESS)
1570}
1571
1572/// Shared path for panics and CPU faults.
1573fn fatal_report(kind: &str, detail: &dyn Fn(&mut Report)) -> ! {
1574 if IN_FATAL.swap(true, Ordering::SeqCst) {
1575 // A fault while reporting a fault: firmware services are suspect, so
1576 // only the architected PSCI reset is tried before parking the core.
1577 psci_system_reset();
1578 aienos_kernel::arch::aarch64::halt();
1579 }
1580 let mut report = Report::new();
1581 header(&mut report, kind);
1582 if EXITED.load(Ordering::SeqCst) {
1583 write_index_line(&mut report);
1584 }
1585 detail(&mut report);
1586
1587 if !EXITED.load(Ordering::SeqCst) {
1588 uefi::println!("{}", report.as_str());
1589 let _ = save_report_file(report.as_str());
1590 wait_seconds(restart_after_secs());
1591 uefi::runtime::reset(ResetType::COLD, Status::ABORTED, None)
1592 }
1593
1594 let mut screen = screen();
1595 if let Some(s) = screen.as_mut() {
1596 s.clear();
1597 s.set_color(ERROR);
1598 let _ = writeln!(s, "AIENOS BOOT STOPPED: {kind}");
1599 s.set_color(FOREGROUND);
1600 let _ = write!(s, "{}", report.as_str());
1601 }
1602 let uart = send_to_console(report.as_str());
1603 let _ = writeln!(report, "uart_report: {uart}");
1604 let saved = save_report_var(report.as_bytes());
1605 if let Some(s) = screen.as_mut() {
1606 let _ = writeln!(s, "uart_report: {uart}");
1607 match saved {
1608 Ok(n) => {
1609 let _ = writeln!(s, "nvram_report: saved (write {n} of {MAX_VAR_WRITES})");
1610 }
1611 Err(e) => {
1612 let _ = writeln!(s, "nvram_report: not saved ({e})");
1613 }
1614 }
1615 }
1616 finish(screen)
1617}
1618
1619#[panic_handler]
1620fn panic(info: &core::panic::PanicInfo) -> ! {
1621 fatal_report("panic", &|r| {
1622 let _ = writeln!(r, "panic: {}", info.message());
1623 if let Some(loc) = info.location() {
1624 let _ = writeln!(r, "panic_location: {}:{}", loc.file(), loc.line());
1625 }
1626 })
1627}
1628
1629fn on_fault(info: &FaultInfo) -> ! {
1630 fatal_report("fault", &|r| {
1631 let _ = write!(r, "{info}");
1632 })
1633}
1634
1635/// First-boot evidence image. Building it does not install or boot it.
1636#[entry]
1637fn main() -> Status {
1638 let uefi_entry_ticks = counter_ticks();
1639 FREQUENCY_HZ.store(counter_frequency_hz(), Ordering::SeqCst);
1640 stage(FIRMWARE_ENTRY);
1641
1642 stage(GB10_DISCOVERY);
1643 let gb10_discovery = discover_gb10();
1644 let gb10 = gb10_discovery.identity;
1645
1646 stage(ACPI_TOPOLOGY);
1647 let boot_midr = midr_el1();
1648 let boot_mpidr = mpidr_el1();
1649 let acpi_facts = discover_acpi(boot_mpidr);
1650 let cpu = acpi_facts.cpu;
1651 *CONSOLE.lock() = acpi_facts.spcr.map(|s| s.kind());
1652
1653 stage(FRAMEBUFFER_DISCOVERY);
1654 let framebuffer = discover_framebuffer();
1655 *FRAMEBUFFER.lock() = framebuffer;
1656 let (loaded_base, loaded_size) =
1657 uefi::boot::open_protocol_exclusive::<LoadedImage>(uefi::boot::image_handle())
1658 .expect("LoadedImage protocol unavailable")
1659 .info();
1660 let loaded_base = loaded_base as usize;
1661 let loaded_size = usize::try_from(loaded_size).expect("loaded image too large");
1662 let image_bytes = unsafe { core::slice::from_raw_parts(loaded_base as *const u8, loaded_size) };
1663 let sections = aienos_kernel::pe::parse_pe_sections(image_bytes, loaded_base as u64)
1664 .expect("loaded PE section table invalid");
1665 let runtime_attrs = runtime_attributes();
1666 let pt_pool = uefi::boot::allocate_pages(
1667 uefi::boot::AllocateType::AnyPages,
1668 MemoryType::LOADER_DATA,
1669 PT_POOL_PAGES,
1670 )
1671 .expect("page table pool allocation failed")
1672 .as_ptr() as usize;
1673 let post_exit_heap = uefi::boot::allocate_pages(
1674 uefi::boot::AllocateType::AnyPages,
1675 MemoryType::LOADER_DATA,
1676 POST_EXIT_HEAP_PAGES,
1677 )
1678 .expect("post-exit heap allocation failed")
1679 .as_ptr() as usize;
1680 POST_EXIT_HEAP.store(post_exit_heap as u64, Ordering::Release);
1681 // Candidate artifact bytes must be read while boot services still live;
1682 // they are judged only by the kernel after firmware exit.
1683 let artifact_candidates = read_artifact_candidates();
1684 #[cfg(feature = "usb-keyboard")]
1685 let xhci = usb_keyboard::find_xhci();
1686 #[cfg(feature = "nvme-read")]
1687 let nvme = nvme_read::find_nvme();
1688
1689 let mut pre = Report::new();
1690 header(&mut pre, "pre_exit");
1691 let _ = writeln!(pre, "firmware_vendor: {}", uefi::system::firmware_vendor());
1692 let _ = writeln!(
1693 pre,
1694 "firmware_revision: {:#x}",
1695 uefi::system::firmware_revision()
1696 );
1697 let _ = writeln!(
1698 pre,
1699 "counter_frequency_hz: {}",
1700 FREQUENCY_HZ.load(Ordering::SeqCst)
1701 );
1702 match gb10 {
1703 Some(g) => {
1704 let _ = writeln!(
1705 pre,
1706 "gb10_pci: {:04x}:{:02x}:{:02x}.{}",
1707 g.bar.location.segment,
1708 g.bar.location.bus,
1709 g.bar.location.device,
1710 g.bar.location.function
1711 );
1712 let _ = writeln!(pre, "gb10_bar0_phys: {:#x}", g.bar.physical_base);
1713 let _ = writeln!(pre, "gb10_pmc_boot_0: {:#010x}", g.pmc_boot_0);
1714 let _ = writeln!(pre, "gb10_pmc_boot_42: {:#010x}", g.pmc_boot_42);
1715 }
1716 None => {
1717 let _ = writeln!(pre, "gb10: unavailable");
1718 gb10_discovery.write_diagnostics(&mut pre);
1719 }
1720 }
1721 write_cpu(&mut pre, cpu, boot_midr, boot_mpidr);
1722 write_uart_line(&mut pre, acpi_facts.spcr);
1723 match framebuffer {
1724 Some(f) => {
1725 let _ = writeln!(
1726 pre,
1727 "framebuffer: {}x{} stride {} {:?} base {:#x} size {}",
1728 f.width, f.height, f.stride, f.order, f.base, f.size_bytes
1729 );
1730 }
1731 None => {
1732 let _ = writeln!(pre, "framebuffer: unavailable");
1733 }
1734 }
1735 let _ = writeln!(
1736 pre,
1737 "artifact_candidates: {}{}",
1738 artifact_candidates.count,
1739 if artifact_candidates.ignored == 0 {
1740 ""
1741 } else {
1742 " (more ignored)"
1743 }
1744 );
1745 let _ = writeln!(pre, "exiting firmware boot services");
1746 uefi::println!("{}", pre.as_str());
1747 let pre_file = save_report_file(pre.as_str()).map_err(|e| e.status());
1748 match pre_file {
1749 Ok(()) => uefi::println!("report file: \\EFI\\AIENOS\\BOOTREPORT.TXT saved"),
1750 Err(status) => uefi::println!("report file: not saved ({status:?})"),
1751 }
1752 stage(PRE_EXIT_SAVED);
1753
1754 // The firmware map and every buffer used below remain identity-mapped.
1755 stage(EXIT_BOOT_SERVICES);
1756 let memory_map = unsafe { uefi::boot::exit_boot_services(None) };
1757 BOOT_SERVICES_LIVE.store(false, Ordering::Release);
1758 EXITED.store(true, Ordering::SeqCst);
1759
1760 let kernel_mmu = enter_kernel_mmu(
1761 &memory_map,
1762 pt_pool,
1763 AddressRange {
1764 start: loaded_base as u64,
1765 length: loaded_size as u64,
1766 },
1767 &sections,
1768 runtime_attrs.as_deref(),
1769 framebuffer,
1770 acpi_facts.spcr,
1771 #[cfg(feature = "usb-keyboard")]
1772 xhci.map(|x| x.mmio_base()),
1773 #[cfg(not(feature = "usb-keyboard"))]
1774 None,
1775 #[cfg(feature = "usb-keyboard")]
1776 xhci.and_then(|x| {
1777 let (segment, bus) = x.ecam_location();
1778 acpi_facts.mcfg.and_then(|t| {
1779 acpi::mcfg_window(t, segment, bus)
1780 .ok()
1781 .flatten()
1782 .map(|w| AddressRange {
1783 start: w.base,
1784 length: (u64::from(w.end_bus) - u64::from(w.start_bus) + 1) << 20,
1785 })
1786 })
1787 }),
1788 #[cfg(not(feature = "usb-keyboard"))]
1789 None,
1790 acpi_facts.gic,
1791 #[cfg(any(feature = "usb-keyboard", feature = "nvme-read"))]
1792 acpi_facts.iort.as_ref().map(|i| i.base),
1793 #[cfg(not(any(feature = "usb-keyboard", feature = "nvme-read")))]
1794 None,
1795 #[cfg(feature = "nvme-read")]
1796 nvme.map(|n| n.mmio_base()),
1797 #[cfg(not(feature = "nvme-read"))]
1798 None,
1799 #[cfg(feature = "nvme-read")]
1800 nvme.and_then(|n| {
1801 let (segment, bus) = n.ecam_location();
1802 acpi_facts.mcfg.and_then(|t| {
1803 acpi::mcfg_window(t, segment, bus)
1804 .ok()
1805 .flatten()
1806 .map(|w| AddressRange {
1807 start: w.base,
1808 length: (u64::from(w.end_bus) - u64::from(w.start_bus) + 1) << 20,
1809 })
1810 })
1811 }),
1812 #[cfg(not(feature = "nvme-read"))]
1813 None,
1814 );
1815 let pt_frames_used = kernel_mmu.pt_frames_used;
1816 let kernel_root = kernel_mmu.root;
1817 let runtime_rx_unsplit = kernel_mmu.runtime_rx_unsplit;
1818
1819 // Devices start with DMA off: clear Bus Master Enable on the xHCI's PCI
1820 // segment before any SMMU stream or driver is set up (M3 1C.3).
1821 #[cfg(feature = "usb-keyboard")]
1822 let dma_takeover = usb_keyboard::take_over_dma(xhci, acpi_facts.mcfg);
1823
1824 #[cfg(feature = "usb-keyboard")]
1825 let smmu_result =
1826 configure_smmu_for_xhci(acpi_facts.iort.as_ref(), xhci, pt_pool, pt_frames_used);
1827
1828 // NVMe read candidate: same fail-closed DMA discipline. Enabling both
1829 // `usb-keyboard` and `nvme-read` in one image is not a supported build;
1830 // each QEMU harness enables exactly one.
1831 #[cfg(feature = "nvme-read")]
1832 let nvme_takeover = nvme_read::take_over_dma(nvme, acpi_facts.mcfg);
1833
1834 #[cfg(feature = "nvme-read")]
1835 let nvme_smmu_result =
1836 configure_smmu_for_nvme(acpi_facts.iort.as_ref(), nvme, pt_pool, pt_frames_used);
1837
1838 fatal::set_fault_hook(on_fault);
1839 fatal::install_exception_vectors();
1840 stage(VECTORS_INSTALLED);
1841
1842 // Early progress record: proves native AIENOS code ran after firmware exit
1843 // even if a later step hangs.
1844 let mut progress = Report::new();
1845 header(&mut progress, "progress");
1846 write_index_line(&mut progress);
1847 let _ = writeln!(progress, "firmware_exit: ok");
1848 let progress_saved = save_report_var(progress.as_bytes());
1849
1850 let mut summary = MemoryMapSummary::default();
1851 for descriptor in memory_map.entries() {
1852 summary.add(
1853 descriptor.ty == MemoryType::CONVENTIONAL,
1854 descriptor.phys_start,
1855 descriptor.page_count,
1856 );
1857 }
1858 let timing = BootTiming {
1859 uefi_entry_ticks,
1860 kernel_handoff_ticks: counter_ticks(),
1861 counter_frequency_hz: FREQUENCY_HZ.load(Ordering::SeqCst),
1862 };
1863
1864 stage(KERNEL_ENTERED);
1865 let (kernel_report, boot_ok) = aienos_kernel::boot::early_kernel_enter(
1866 summary.conventional_kb(),
1867 summary.largest,
1868 Some(summary),
1869 Some(timing),
1870 gb10,
1871 cpu,
1872 );
1873 let irq_result = run_timer_window(acpi_facts.gic);
1874
1875 let mut report = Report::new();
1876 header(&mut report, "final");
1877 write_index_line(&mut report);
1878 // Measured, not asserted: read the live exception level and SCTLR_EL1.M.
1879 let el = aienos_kernel::arch::aarch64::current_el();
1880 if el == 1 {
1881 let _ = writeln!(report, "kernel_el: EL1h");
1882 } else {
1883 let _ = writeln!(report, "kernel_el: unexpected EL{el}");
1884 }
1885 let mmu_on = aienos_kernel::arch::aarch64::el1_mmu_enabled();
1886 let _ = writeln!(
1887 report,
1888 "mmu: {}",
1889 if mmu_on { "enabled" } else { "disabled" }
1890 );
1891 let _ = writeln!(report, "pt_frames_used: {pt_frames_used}");
1892 // Issue #27: prove the kernel runs on AIENOS tables, not firmware's. Every
1893 // field is read from live registers; switched=yes needs EL1 with SCTLR_EL1.M
1894 // set, TTBR0_EL1 pointing at the root AIENOS built, and that root differing
1895 // from the table firmware was translating with.
1896 let firmware = kernel_mmu.firmware;
1897 let el1_base = current_ttbr0_el1() & TTBR_BADDR_MASK;
1898 let firmware_base = firmware.ttbr0 & TTBR_BADDR_MASK;
1899 let switched = el == 1 && mmu_on && el1_base == kernel_root as u64 && el1_base != firmware_base;
1900 let _ = writeln!(
1901 report,
1902 "mmu_switch: firmware=EL{} firmware_mmu={} firmware_ttbr0={firmware_base:#x} aienos_root={kernel_root:#x} ttbr0_el1={el1_base:#x} switched={}",
1903 firmware.el,
1904 if firmware.mmu_on { "on" } else { "off" },
1905 if switched { "yes" } else { "no" }
1906 );
1907 #[cfg(feature = "usb-keyboard")]
1908 match smmu_result {
1909 Ok(stream_id) => {
1910 let _ = writeln!(
1911 report,
1912 "smmu: enabled base={:#x} stream_id={stream_id:#x}",
1913 acpi_facts.iort.as_ref().map_or(0, |i| i.base)
1914 );
1915 let _ = writeln!(report, "smmu_dma_window: xhci only, translation active");
1916 }
1917 Err(error) => {
1918 let _ = writeln!(report, "smmu: unavailable ({error:?})");
1919 }
1920 }
1921 // Cooperative threads at EL1 (issue #29): two workers each record a tag and
1922 // yield five times; the line reports the order actually observed.
1923 let (trace, trace_len) = unsafe { aienos_kernel::thread::run_demo() };
1924 let observed = core::str::from_utf8(&trace[..trace_len]).unwrap_or("?");
1925 let _ = writeln!(
1926 report,
1927 "threads: {} interleave={observed}",
1928 if observed == "ABABABABAB" {
1929 "ok"
1930 } else {
1931 "unexpected"
1932 }
1933 );
1934 aienos_kernel::user::set_write_hook(el0_console_write);
1935 let el0 = unsafe { aienos_kernel::user::run_demo(kernel_root) };
1936 let el0_ok =
1937 el0.write_granted && el0.forged_denied && el0.fault_contained && el0.exit_code == 0;
1938 let _ = writeln!(
1939 report,
1940 "el0: {} write={} forged={} fault={} exit={}",
1941 if el0_ok { "ok" } else { "failed" },
1942 if el0.write_granted {
1943 "granted"
1944 } else {
1945 "denied"
1946 },
1947 if el0.forged_denied {
1948 "denied"
1949 } else {
1950 "accepted"
1951 },
1952 if el0.fault_contained {
1953 "contained"
1954 } else {
1955 "uncontained"
1956 },
1957 el0.exit_code,
1958 );
1959 let (preempt_a, preempt_b, preempt_switches) =
1960 unsafe { aienos_kernel::thread::run_preemption_demo() };
1961 let preempt_ok = preempt_a > 0 && preempt_b > 0 && preempt_switches >= 4;
1962 let _ = writeln!(
1963 report,
1964 "preempt: {} a={preempt_a} b={preempt_b} switches={preempt_switches}",
1965 if preempt_ok { "ok" } else { "failed" }
1966 );
1967 match acpi_facts.cpu.as_ref() {
1968 Some(topology) => {
1969 let mut placement = ReportBuf::<128>::new();
1970 let _ = write!(placement, "placement:");
1971 for (index, name) in [(0u32, "worker0"), (1u32, "worker1")] {
1972 match aienos_kernel::thread::place_task(topology, index) {
1973 Some((class, core)) => {
1974 let _ = write!(placement, " {name}=class{class}/core{core}");
1975 }
1976 None => {
1977 let _ = write!(placement, " {name}=unplaced");
1978 }
1979 }
1980 }
1981 let _ = writeln!(report, "{}", placement.as_str());
1982 }
1983 None => {
1984 let _ = writeln!(report, "placement: unavailable");
1985 }
1986 }
1987 let ipc = unsafe { aienos_kernel::user::run_ipc_demo(kernel_root) };
1988 let _ = writeln!(
1989 report,
1990 "ipc: {} message={} cap={} rights={} forged={} revoked={}",
1991 if ipc.ok { "ok" } else { "failed" },
1992 if ipc.message_delivered {
1993 "delivered"
1994 } else {
1995 "missed"
1996 },
1997 if ipc.cap_delegated {
1998 "delegated"
1999 } else {
2000 "failed"
2001 },
2002 if ipc.rights_attenuated {
2003 "attenuated"
2004 } else {
2005 "escalated"
2006 },
2007 if ipc.forged_denied {
2008 "denied"
2009 } else {
2010 "accepted"
2011 },
2012 if ipc.revoked_denied {
2013 "denied"
2014 } else {
2015 "accepted"
2016 },
2017 );
2018 // P2-5: every firmware-provided candidate goes through the kernel's one
2019 // admission path. The per-candidate lines are their own record so they
2020 // never push the bounded final report past its NVRAM size.
2021 let (admitted, rejected) = run_artifact_candidates(&artifact_candidates, kernel_root);
2022 #[cfg(feature = "seed0b-qualification")]
2023 let _ = writeln!(
2024 report,
2025 "artifact_trust: seed0b-test qualification build — TEST ONLY"
2026 );
2027 let _ = writeln!(
2028 report,
2029 "artifacts: candidates={} admitted={admitted} rejected={rejected}",
2030 artifact_candidates.count
2031 );
2032 let _ = writeln!(
2033 report,
2034 "runtime_code: {}",
2035 if runtime_rx_unsplit {
2036 "rx-unsplit"
2037 } else {
2038 "mat-split"
2039 }
2040 );
2041 let _ = write!(report, "{}", kernel_report.as_str());
2042 if let Some(w) = irq_result {
2043 let _ = writeln!(
2044 report,
2045 "gic: v3\ntimer_irq: {} ticks in {} ms",
2046 w.ticks, w.ms
2047 );
2048 // Issue #28: where the GIC came from and tick statistics. Intervals
2049 // are counter distances between consecutive acknowledged INTID 30
2050 // ticks, the first measured from the moment the timer was armed.
2051 let _ = writeln!(
2052 report,
2053 "gic_madt: gicd={:#x} gicr={:#x} arch_rev={} icc_sre={}",
2054 w.distributor, w.redistributor, w.arch_rev, w.icc_sre
2055 );
2056 let avg = w.span.checked_div(w.ticks).unwrap_or(0);
2057 let _ = writeln!(
2058 report,
2059 "timer_stats: intid=30 freq_hz={} period_us={} min_us={} avg_us={} max_us={}",
2060 w.frequency_hz,
2061 w.us(w.frequency_hz / 100),
2062 w.us(w.min_interval),
2063 w.us(avg),
2064 w.us(w.max_interval)
2065 );
2066 } else {
2067 let _ = writeln!(report, "gic: unavailable\ntimer_irq: unavailable");
2068 }
2069 if gb10.is_none() {
2070 gb10_discovery.write_diagnostics(&mut report);
2071 }
2072 match progress_saved {
2073 Ok(_) => {
2074 let _ = writeln!(report, "progress_record: saved");
2075 }
2076 Err(e) => {
2077 let _ = writeln!(report, "progress_record: not saved ({e})");
2078 }
2079 }
2080 match pre_file {
2081 Ok(()) => {
2082 let _ = writeln!(report, "pre_exit_file: saved");
2083 }
2084 Err(status) => {
2085 let _ = writeln!(report, "pre_exit_file: not saved ({status:?})");
2086 }
2087 }
2088
2089 // Draw and send first, then record both outcomes in the saved report.
2090 let mut screen = screen();
2091 if let Some(s) = screen.as_mut() {
2092 s.clear();
2093 s.set_color(ACCENT);
2094 let _ = writeln!(s, "AIENOS NATIVE BOOT REPORT");
2095 s.set_color(FOREGROUND);
2096 let _ = write!(s, "{}", report.as_str());
2097 stage(SCREEN_DRAWN);
2098 }
2099 let uart = send_to_console(report.as_str());
2100 stage(UART_SENT);
2101
2102 let mut outcomes = ReportBuf::<256>::new();
2103 match framebuffer.filter(|_| screen.is_some()) {
2104 Some(f) => {
2105 let _ = writeln!(outcomes, "screen_report: drawn {}x{}", f.width, f.height);
2106 }
2107 None => {
2108 let _ = writeln!(outcomes, "screen_report: unavailable");
2109 }
2110 }
2111 let _ = writeln!(outcomes, "uart_report: {uart}");
2112 let _ = write!(report, "{}", outcomes.as_str());
2113 if report.truncated() {
2114 let _ = writeln!(report, "truncated: yes");
2115 }
2116 if let Some(s) = screen.as_mut() {
2117 let _ = write!(s, "{}", outcomes.as_str());
2118 }
2119
2120 let saved = save_report_var(report.as_bytes());
2121 stage(FINAL_SAVED);
2122 if let Some(s) = screen.as_mut() {
2123 match saved {
2124 Ok(n) => {
2125 let _ = writeln!(s, "nvram_report: saved (write {n} of {MAX_VAR_WRITES})");
2126 }
2127 Err(e) => {
2128 let _ = writeln!(s, "nvram_report: not saved ({e})");
2129 }
2130 }
2131 }
2132
2133 if !boot_ok {
2134 if let Some(s) = screen.as_mut() {
2135 s.set_color(ERROR);
2136 let _ = writeln!(s, "boot halted: no usable memory region");
2137 }
2138 }
2139 #[cfg(feature = "usb-keyboard")]
2140 usb_keyboard::run(
2141 xhci,
2142 dma_takeover,
2143 &mut screen,
2144 summary.conventional_kb(),
2145 el,
2146 report.as_str(),
2147 smmu_result.is_ok(),
2148 acpi_facts.iort.as_ref().map(|s| s.base),
2149 smmu_result.ok(),
2150 smmu_event_queue_ptr(),
2151 );
2152 #[cfg(feature = "nvme-read")]
2153 nvme_read::run(
2154 nvme,
2155 nvme_takeover,
2156 &mut screen,
2157 nvme_smmu_result.is_ok(),
2158 acpi_facts.iort.as_ref().map(|s| s.base),
2159 nvme_smmu_result.ok(),
2160 smmu_event_queue_ptr(),
2161 );
2162 finish(screen)
2163}