Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-kernel/src/boot.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-kernel / src / boot.rs` 558 lines · 19902 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! AIENOS Bare-Metal Boot Spine (§Step 2 of Systems Integration Sequence). 17 //! 18 //! Provides the bare-metal entry path, early serial banner, and BootReceipt. 19 20 use crate::acpi::CpuTopology; 21 use crate::arch::aarch64::{ 22 counter_ticks, current_el, disable_interrupts, dsb, halt, isb, midr_el1, midr_part, EarlyUart, 23 SPARK_16550_UART_BASE, 24 }; 25 use crate::mem::{BitmapFrameAllocator, FrameBatch, PhysAddr, PAGE_SIZE}; 26 use crate::report::ReportBuf; 27 use crate::sync::spinlock::SpinLock; 28 use core::fmt::Write; 29 30 const EARLY_BITMAP_WORDS: usize = 64; 31 const MAX_EARLY_FRAMES: usize = EARLY_BITMAP_WORDS * 64; 32 static EARLY_ALLOCATOR: SpinLock>> = 33 SpinLock::new(None); 34 35 /// Allocate a frame from the first conventional-memory region after handoff. 36 pub fn allocate_early_frame() -> Option { 37 EARLY_ALLOCATOR.lock().as_mut()?.allocate_frame() 38 } 39 40 /// Atomically reserve every frame required by a candidate while holding the 41 /// early allocator lock once. The loader computes and checks the count before 42 /// calling; an allocation failure leaves the allocator unchanged. 43 pub fn reserve_early_frames(count: usize) -> Option { 44 EARLY_ALLOCATOR.lock().as_mut()?.allocate_batch(count) 45 } 46 47 /// Release a prior candidate reservation after teardown or construction 48 /// failure. Capability revocation is the caller's responsibility and must 49 /// happen before this function is called. 50 pub fn release_early_frames(batch: FrameBatch) -> bool { 51 EARLY_ALLOCATOR 52 .lock() 53 .as_mut() 54 .is_some_and(|allocator| allocator.release_batch(batch)) 55 } 56 57 /// Reserve a physically contiguous run of early frames (artifact staging). 58 pub fn reserve_early_contiguous(count: usize) -> Option { 59 EARLY_ALLOCATOR.lock().as_mut()?.allocate_contiguous(count) 60 } 61 62 /// Release a run obtained from [`reserve_early_contiguous`]. 63 pub fn release_early_contiguous(start: PhysAddr, count: usize) -> bool { 64 let mut guard = EARLY_ALLOCATOR.lock(); 65 let Some(allocator) = guard.as_mut() else { 66 return false; 67 }; 68 let mut complete = true; 69 for index in 0..count { 70 complete &= allocator.deallocate_frame(start.offset(index * PAGE_SIZE)); 71 } 72 complete 73 } 74 75 /// Free frames remaining in the early allocator (0 before initialisation). 76 pub fn early_free_frames() -> usize { 77 EARLY_ALLOCATOR 78 .lock() 79 .as_ref() 80 .map_or(0, |allocator| allocator.free_count()) 81 } 82 83 fn initialize_early_allocator(region: BootMemoryRegion) -> Option<(usize, PhysAddr)> { 84 let mut allocator = EARLY_ALLOCATOR.lock(); 85 if allocator.is_some() { 86 return None; 87 } 88 let managed_frames = region.page_count.min(MAX_EARLY_FRAMES); 89 *allocator = Some(BitmapFrameAllocator::new(region.start, managed_frames)); 90 let first_frame = allocator.as_mut()?.allocate_frame()?; 91 Some((managed_frames, first_frame)) 92 } 93 94 /// A page-aligned conventional-memory region supplied by the firmware map. 95 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 96 pub struct BootMemoryRegion { 97 start: PhysAddr, 98 page_count: usize, 99 } 100 101 impl BootMemoryRegion { 102 /// Validate descriptor arithmetic before the kernel constructs an allocator. 103 pub fn new(physical_start: u64, page_count: u64) -> Option { 104 let start = PhysAddr(usize::try_from(physical_start).ok()?); 105 let page_count = usize::try_from(page_count).ok()?; 106 if !start.is_page_aligned() 107 || page_count == 0 108 || page_count > (usize::MAX - start.0) / PAGE_SIZE 109 { 110 return None; 111 } 112 Some(Self { start, page_count }) 113 } 114 115 /// Number of 4 KiB pages in this validated region. 116 pub const fn page_count(self) -> usize { 117 self.page_count 118 } 119 120 /// Physical start address of the region. 121 pub const fn start(self) -> u64 { 122 self.start.0 as u64 123 } 124 } 125 126 /// What the firmware memory map contained and what the kernel accepted. 127 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] 128 pub struct MemoryMapSummary { 129 pub descriptors: u64, 130 pub conventional_regions: u64, 131 pub conventional_pages: u64, 132 /// Conventional regions that failed `BootMemoryRegion::new` validation. 133 pub rejected_regions: u64, 134 pub largest: Option, 135 } 136 137 impl MemoryMapSummary { 138 /// Account for one firmware memory descriptor. 139 pub fn add(&mut self, conventional: bool, physical_start: u64, page_count: u64) { 140 self.descriptors += 1; 141 if !conventional { 142 return; 143 } 144 self.conventional_regions += 1; 145 self.conventional_pages = self.conventional_pages.saturating_add(page_count); 146 match BootMemoryRegion::new(physical_start, page_count) { 147 Some(region) => { 148 if self 149 .largest 150 .is_none_or(|l| region.page_count() > l.page_count()) 151 { 152 self.largest = Some(region); 153 } 154 } 155 None => self.rejected_regions += 1, 156 } 157 } 158 159 pub fn conventional_kb(&self) -> u64 { 160 self.conventional_pages.saturating_mul(4) 161 } 162 } 163 164 /// Counter samples taken by the Rust UEFI entry and passed to the kernel. 165 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 166 pub struct BootTiming { 167 pub uefi_entry_ticks: u64, 168 pub kernel_handoff_ticks: u64, 169 pub counter_frequency_hz: u64, 170 } 171 172 impl BootTiming { 173 /// Convert elapsed architectural counter ticks to milliseconds. 174 pub fn elapsed_ms(start: u64, end: u64, frequency_hz: u64) -> Option { 175 if frequency_hz == 0 || end < start { 176 return None; 177 } 178 let elapsed = (u128::from(end - start) * 1000) / u128::from(frequency_hz); 179 u64::try_from(elapsed).ok() 180 } 181 } 182 183 /// Deterministic, immutable boot receipt emitted by the native boot spine. 184 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 185 pub struct BootReceipt { 186 pub boot_epoch: u64, 187 pub arch_magic: u32, // 0xAA64_0001 188 pub exception_level: u8, 189 pub entry_status: u8, // 0 = Clean Entry 190 pub exit_status: u8, // 0 = Clean Halt 191 pub memory_detected_kb: u64, 192 pub kernel_sha256_prefix: [u8; 8], 193 } 194 195 impl BootReceipt { 196 pub const ARCH_AARCH64: u32 = 0xAA64_0001; 197 198 pub const fn new(epoch: u64, el: u8, mem_kb: u64, hash_prefix: [u8; 8]) -> Self { 199 Self { 200 boot_epoch: epoch, 201 arch_magic: Self::ARCH_AARCH64, 202 exception_level: el, 203 entry_status: 0, 204 exit_status: 0, 205 memory_detected_kb: mem_kb, 206 kernel_sha256_prefix: hash_prefix, 207 } 208 } 209 } 210 211 /// Early kernel boot initialization executed directly from UEFI or reset vector. 212 pub fn early_kernel_init(conventional_memory_kb: u64) -> ! { 213 early_kernel_init_with_timing(conventional_memory_kb, None) 214 } 215 216 /// Early kernel entry with firmware-entry and handoff timing samples. 217 pub fn early_kernel_init_with_timing( 218 conventional_memory_kb: u64, 219 boot_timing: Option, 220 ) -> ! { 221 early_kernel_init_with_memory(conventional_memory_kb, None, boot_timing) 222 } 223 224 /// Early kernel entry with a validated conventional-memory region. 225 pub fn early_kernel_init_with_memory( 226 conventional_memory_kb: u64, 227 memory_region: Option, 228 boot_timing: Option, 229 ) -> ! { 230 early_kernel_init_with_gpu(conventional_memory_kb, memory_region, boot_timing, None) 231 } 232 233 /// Capacity of the native boot report shared by every output. 234 pub const REPORT_CAPACITY: usize = 2048; 235 pub type BootReport = ReportBuf; 236 237 /// Facts the kernel reports after taking control from firmware. 238 pub struct BootFacts { 239 pub conventional_memory_kb: u64, 240 /// Firmware memory map validation, when the caller walked the map. 241 pub memory_map: Option, 242 /// `(managed_frames, reserved_frame)` or `None` if no usable region. 243 pub allocator: Option<(usize, PhysAddr)>, 244 pub timing: Option, 245 pub kernel_entry_ticks: u64, 246 pub gb10: Option, 247 /// Core inventory from the firmware MADT, if it was found and valid. 248 pub cpu: Option, 249 /// MIDR of the core running the boot path. 250 pub boot_midr: u64, 251 pub exception_level: u8, 252 } 253 254 /// Formats the report. Returns false if boot cannot continue (no allocator). 255 pub fn write_boot_report(out: &mut impl Write, facts: &BootFacts) -> bool { 256 let _ = writeln!(out, "AIENOS"); 257 let _ = writeln!(out, "arch: aarch64"); 258 let _ = writeln!(out, "boot: native"); 259 #[cfg(feature = "seed0b-test-anchor")] 260 let _ = writeln!( 261 out, 262 "artifact_trust: SEED-0B QUALIFICATION BUILD — TEST ONLY TRUST ANCHOR" 263 ); 264 #[cfg(not(feature = "seed0b-test-anchor"))] 265 let _ = writeln!(out, "artifact_trust: no production anchors enrolled"); 266 let _ = writeln!( 267 out, 268 "conventional_memory_kb: {}", 269 facts.conventional_memory_kb 270 ); 271 if let Some(m) = facts.memory_map { 272 let _ = writeln!(out, "memory_map_descriptors: {}", m.descriptors); 273 let _ = writeln!( 274 out, 275 "memory_map_conventional_regions: {}", 276 m.conventional_regions 277 ); 278 let _ = writeln!(out, "memory_map_rejected_regions: {}", m.rejected_regions); 279 match m.largest { 280 Some(r) => { 281 let _ = writeln!( 282 out, 283 "memory_map_largest_region: {:#x} pages {}", 284 r.start(), 285 r.page_count() 286 ); 287 } 288 None => { 289 let _ = writeln!(out, "memory_map_largest_region: none"); 290 } 291 } 292 } 293 match facts.gb10 { 294 Some(g) => { 295 let _ = writeln!(out, "gb10_segment: {}", g.bar.location.segment); 296 let _ = writeln!(out, "gb10_bar0_phys: {:#x}", g.bar.physical_base); 297 let _ = writeln!(out, "gb10_pmc_boot_0: {:#010x}", g.pmc_boot_0); 298 let _ = writeln!(out, "gb10_pmc_boot_42: {:#010x}", g.pmc_boot_42); 299 } 300 None => { 301 let _ = writeln!(out, "gb10: unavailable"); 302 } 303 } 304 match facts.cpu { 305 Some(t) => { 306 let _ = writeln!(out, "cpu_cores: {}", t.cores); 307 for (class, count) in t.classes() { 308 let _ = writeln!(out, "cpu_efficiency_class_{class}: {count}"); 309 } 310 if t.unknown_class > 0 { 311 let _ = writeln!(out, "cpu_efficiency_class_unknown: {}", t.unknown_class); 312 } 313 let _ = writeln!( 314 out, 315 "cpu_boot_core_listed: {}", 316 if t.boot_core_listed { "yes" } else { "no" } 317 ); 318 match t.boot_class { 319 Some(class) => { 320 let _ = writeln!(out, "cpu_boot_core_class: {class}"); 321 } 322 None => { 323 let _ = writeln!(out, "cpu_boot_core_class: unknown"); 324 } 325 } 326 } 327 None => { 328 let _ = writeln!(out, "cpu_topology: unavailable"); 329 } 330 } 331 let _ = writeln!( 332 out, 333 "boot_cpu_midr: {:#x} (part {:#05x})", 334 facts.boot_midr, 335 midr_part(facts.boot_midr) 336 ); 337 let Some((managed_frames, first_frame)) = facts.allocator else { 338 let _ = writeln!(out, "allocator: unavailable; boot halted"); 339 return false; 340 }; 341 let _ = writeln!(out, "allocator_managed_frames: {managed_frames}"); 342 let _ = writeln!(out, "allocator_reserved_frame_phys: {:#x}", first_frame.0); 343 if let Some(t) = facts.timing { 344 let hz = t.counter_frequency_hz; 345 if let Some(ms) = BootTiming::elapsed_ms(t.uefi_entry_ticks, t.kernel_handoff_ticks, hz) { 346 let _ = writeln!(out, "uefi_entry_to_handoff_ms: {ms}"); 347 } 348 if let Some(ms) = 349 BootTiming::elapsed_ms(t.kernel_handoff_ticks, facts.kernel_entry_ticks, hz) 350 { 351 let _ = writeln!(out, "handoff_to_kernel_entry_ms: {ms}"); 352 } 353 } 354 let _ = writeln!(out, "exception_level: EL{}", facts.exception_level); 355 let _ = writeln!(out, "kernel: alive"); 356 true 357 } 358 359 /// Kernel entry after firmware exit: interrupts off, barriers, early 360 /// allocator, then the report. Returns the report and whether boot may 361 /// continue; the caller chooses where to send it. 362 pub fn early_kernel_enter( 363 conventional_memory_kb: u64, 364 memory_region: Option, 365 memory_map: Option, 366 boot_timing: Option, 367 gb10: Option, 368 cpu: Option, 369 ) -> (BootReport, bool) { 370 let kernel_entry_ticks = counter_ticks(); 371 disable_interrupts(); 372 dsb(); 373 isb(); 374 // Retain the initial bitmap in kernel state and manage at most 16 MiB. 375 // This reserves an address in bookkeeping only; it does not dereference RAM. 376 let facts = BootFacts { 377 conventional_memory_kb, 378 memory_map, 379 allocator: memory_region.and_then(initialize_early_allocator), 380 timing: boot_timing, 381 kernel_entry_ticks, 382 gb10, 383 cpu, 384 boot_midr: midr_el1(), 385 exception_level: current_el(), 386 }; 387 let mut report = BootReport::new(); 388 let ok = write_boot_report(&mut report, &facts); 389 (report, ok) 390 } 391 392 /// Native entry carrying read-only GB10 BAR0 identity sampled before firmware exit. 393 /// Sends the report to the Spark UART only, then halts. 394 pub fn early_kernel_init_with_gpu( 395 conventional_memory_kb: u64, 396 memory_region: Option, 397 boot_timing: Option, 398 gb10: Option, 399 ) -> ! { 400 let (report, ok) = early_kernel_enter( 401 conventional_memory_kb, 402 memory_region, 403 None, 404 boot_timing, 405 gb10, 406 None, 407 ); 408 let uart = EarlyUart::new(SPARK_16550_UART_BASE); 409 uart.write_str("\n"); 410 uart.write_str(report.as_str()); 411 if ok { 412 uart.write_str("halt: clean\n"); 413 } 414 halt(); 415 } 416 417 #[cfg(test)] 418 mod tests { 419 use super::{allocate_early_frame, initialize_early_allocator, BootMemoryRegion, BootTiming}; 420 421 #[test] 422 fn boot_counter_conversion_rejects_invalid_samples() { 423 assert_eq!(BootTiming::elapsed_ms(100, 150, 1000), Some(50)); 424 assert_eq!(BootTiming::elapsed_ms(150, 100, 1000), None); 425 assert_eq!(BootTiming::elapsed_ms(100, 150, 0), None); 426 } 427 428 #[test] 429 fn firmware_region_requires_aligned_nonoverflowing_pages() { 430 assert_eq!( 431 BootMemoryRegion::new(0x1000_0000, 4096).unwrap().page_count, 432 4096 433 ); 434 assert!(BootMemoryRegion::new(0x1000_0001, 1).is_none()); 435 assert!(BootMemoryRegion::new(0x1000_0000, 0).is_none()); 436 assert!(BootMemoryRegion::new(u64::MAX - 4095, 2).is_none()); 437 } 438 439 #[test] 440 fn report_lists_gpu_allocator_timing_and_liveness() { 441 use super::{write_boot_report, BootFacts, BootReport}; 442 use crate::mem::PhysAddr; 443 let gb10 = aienos_accel::Gb10Identity { 444 bar: aienos_accel::Gb10Bar { 445 location: aienos_accel::PciLocation { 446 segment: 15, 447 bus: 1, 448 device: 0, 449 function: 0, 450 }, 451 physical_base: 0x6_5000_0000, 452 }, 453 pmc_boot_0: 0x1b00_00a1, 454 pmc_boot_42: 0x1b0a_0000, 455 }; 456 let mut memory_map = super::MemoryMapSummary::default(); 457 memory_map.add(false, 0x0, 16); 458 memory_map.add(true, 0x1000_0000, 128); 459 memory_map.add(true, 0x2000_0001, 64); 460 let facts = BootFacts { 461 conventional_memory_kb: 4096, 462 memory_map: Some(memory_map), 463 allocator: Some((128, PhysAddr(0x1000_0000))), 464 timing: Some(BootTiming { 465 uefi_entry_ticks: 0, 466 kernel_handoff_ticks: 1_000, 467 counter_frequency_hz: 1_000_000, 468 }), 469 kernel_entry_ticks: 3_000, 470 gb10: Some(gb10), 471 cpu: Some(crate::acpi::CpuTopology { 472 cores: 20, 473 classes: [ 474 (0, 10), 475 (1, 10), 476 (0, 0), 477 (0, 0), 478 (0, 0), 479 (0, 0), 480 (0, 0), 481 (0, 0), 482 ], 483 distinct_classes: 2, 484 unknown_class: 0, 485 first_mpidr: Some(0x8100_0000), 486 boot_core_listed: true, 487 boot_class: Some(0), 488 }), 489 boot_midr: 0x410f_d870, 490 exception_level: 2, 491 }; 492 let mut report = BootReport::new(); 493 assert!(write_boot_report(&mut report, &facts)); 494 let text = report.as_str(); 495 #[cfg(feature = "seed0b-test-anchor")] 496 assert!( 497 text.contains("artifact_trust: SEED-0B QUALIFICATION BUILD — TEST ONLY TRUST ANCHOR") 498 ); 499 #[cfg(not(feature = "seed0b-test-anchor"))] 500 assert!(text.contains("artifact_trust: no production anchors enrolled")); 501 for line in [ 502 "gb10_segment: 15", 503 "gb10_bar0_phys: 0x650000000", 504 "gb10_pmc_boot_0: 0x1b0000a1", 505 "cpu_cores: 20", 506 "cpu_efficiency_class_0: 10", 507 "cpu_efficiency_class_1: 10", 508 "cpu_boot_core_listed: yes", 509 "cpu_boot_core_class: 0", 510 "boot_cpu_midr: 0x410fd870 (part 0xd87)", 511 "memory_map_descriptors: 3", 512 "memory_map_conventional_regions: 2", 513 "memory_map_rejected_regions: 1", 514 "memory_map_largest_region: 0x10000000 pages 128", 515 "allocator_reserved_frame_phys: 0x10000000", 516 "uefi_entry_to_handoff_ms: 1", 517 "handoff_to_kernel_entry_ms: 2", 518 "exception_level: EL2", 519 "kernel: alive", 520 ] { 521 assert!( 522 text.lines().any(|l| l == line), 523 "missing {line:?} in:\n{text}" 524 ); 525 } 526 527 let halted = BootFacts { 528 allocator: None, 529 ..facts 530 }; 531 let mut report = BootReport::new(); 532 assert!(!write_boot_report(&mut report, &halted)); 533 assert!(report 534 .as_str() 535 .ends_with("allocator: unavailable; boot halted\n")); 536 } 537 538 #[test] 539 fn early_allocator_retains_region_after_initialization() { 540 let region = BootMemoryRegion::new(0x1000_0000, 128).unwrap(); 541 let (managed, reserved) = initialize_early_allocator(region).unwrap(); 542 assert_eq!(managed, 128); 543 assert_eq!(reserved.0, 0x1000_0000); 544 assert_eq!(allocate_early_frame().unwrap().0, 0x1000_1000); 545 assert!(initialize_early_allocator(region).is_none()); 546 } 547 } 548 549 /// Canonical bare-metal entry point when compiling for `#![no_std]` targets. 550 /// 551 /// # Safety 552 /// Only the boot loader may call this, once, on the boot CPU at EL1 with a 553 /// valid stack; it never returns. 554 #[cfg(all(target_os = "none", not(feature = "std"), not(test)))] 555 #[no_mangle] 556 pub unsafe extern "C" fn _start() -> ! { 557 early_kernel_init(0); 558 }