diff --git a/crates/aienos-accel/src/lib.rs b/crates/aienos-accel/src/lib.rs index c112d7a5..e9df2492 100644 --- a/crates/aienos-accel/src/lib.rs +++ b/crates/aienos-accel/src/lib.rs @@ -163,7 +163,10 @@ mod tests { "gb10_pci_root[1]: segment 15 devices 4 bridges 1 windows 1", "gb10_pci_candidate[1]: command_status 0x00100004 bar0 0x00000000:0x00000000", ] { - assert!(text.lines().any(|l| l == line), "missing {line:?} in:\n{text}"); + assert!( + text.lines().any(|l| l == line), + "missing {line:?} in:\n{text}" + ); } let mut text = String::new(); diff --git a/crates/aienos-boot/Cargo.toml b/crates/aienos-boot/Cargo.toml index 1fd60880..624baa4e 100644 --- a/crates/aienos-boot/Cargo.toml +++ b/crates/aienos-boot/Cargo.toml @@ -14,7 +14,7 @@ uefi-base = ["dep:uefi"] # defines its own, which reports through the screen, firmware variable and # UART after boot services exit, so the two features must not be combined. firmware = ["uefi-base", "uefi/panic_handler"] -handoff = ["uefi-base", "dep:aienos-kernel", "dep:aienos-accel", "uefi/alloc", "uefi/global_allocator"] +handoff = ["uefi-base", "dep:aienos-kernel", "dep:aienos-accel", "uefi/alloc"] # SEED-0A candidate: polled USB keyboard after firmware exit (ADR 0012). # Only the QEMU keyboard test enables it; hardware staging never does. usb-keyboard = ["handoff"] diff --git a/crates/aienos-boot/src/handoff.rs b/crates/aienos-boot/src/handoff.rs index 72b08f5e..f353cd95 100644 --- a/crates/aienos-boot/src/handoff.rs +++ b/crates/aienos-boot/src/handoff.rs @@ -21,6 +21,8 @@ //! /boot/efi/EFI/AIENOS/BOOTREPORT.TXT //! /sys/firmware/efi/efivars/AienosBootReportV1-a1e05b0e-7c3d-4f51-9b6a-2d8e4c1f0a37 +extern crate alloc; + use aienos_kernel::acpi; use aienos_kernel::arch::aarch64::{ counter_frequency_hz, counter_ticks, midr_el1, midr_part, mpidr_el1, psci_system_reset, @@ -29,14 +31,19 @@ use aienos_kernel::boot::{BootTiming, MemoryMapSummary}; use aienos_kernel::console::EarlyConsole; use aienos_kernel::display::{FramebufferInfo, PixelOrder, Screen, ACCENT, FOREGROUND}; use aienos_kernel::fatal::{self, FaultInfo}; +use aienos_kernel::mem::frame_allocator::PhysAddr; +use aienos_kernel::mem::map_plan::{self, AddressRange, EfiMemoryDescriptor}; +use aienos_kernel::mem::pagetable::{FixedFramePool, PageTableBuilder, TableMemory}; use aienos_kernel::report::ReportBuf; use aienos_kernel::sync::spinlock::SpinLock; +use core::alloc::{GlobalAlloc, Layout}; use core::fmt::Write; use core::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams}; use uefi::mem::memory_map::{MemoryMap, MemoryType}; use uefi::prelude::*; use uefi::proto::console::gop::{GraphicsOutput, PixelFormat}; +use uefi::proto::loaded_image::LoadedImage; use uefi::proto::media::file::{File, FileAttribute, FileMode}; use uefi::proto::pci::configuration::ResourceRangeType; use uefi::proto::pci::root_bridge::PciRootBridgeIo; @@ -45,6 +52,201 @@ use uefi::runtime::{ResetType, VariableAttributes, VariableVendor}; use uefi::table::cfg::ConfigTableEntry; use uefi::{cstr16, guid, CStr16}; +const PT_POOL_PAGES: usize = 256; +const POST_EXIT_HEAP_PAGES: usize = 1024; +static POST_EXIT_HEAP: AtomicU64 = AtomicU64::new(0); +static POST_EXIT_HEAP_USED: AtomicU64 = AtomicU64::new(0); +static BOOT_SERVICES_LIVE: AtomicBool = AtomicBool::new(true); + +struct BootHeap; +unsafe impl GlobalAlloc for BootHeap { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + if BOOT_SERVICES_LIVE.load(Ordering::Acquire) { + return unsafe { GlobalAlloc::alloc(&uefi::allocator::Allocator, layout) }; + } + let base = POST_EXIT_HEAP.load(Ordering::Acquire) as usize; + if base == 0 { + return core::ptr::null_mut(); + } + let mut old = POST_EXIT_HEAP_USED.load(Ordering::Relaxed) as usize; + loop { + let aligned = match (base + old).checked_add(layout.align() - 1) { + Some(v) => v & !(layout.align() - 1), + None => return core::ptr::null_mut(), + }; + let next = match aligned.checked_add(layout.size()) { + Some(v) => v - base, + None => return core::ptr::null_mut(), + }; + if next > POST_EXIT_HEAP_PAGES * 4096 { + return core::ptr::null_mut(); + } + match POST_EXIT_HEAP_USED.compare_exchange_weak( + old as u64, + next as u64, + Ordering::AcqRel, + Ordering::Relaxed, + ) { + Ok(_) => return aligned as *mut u8, + Err(v) => old = v as usize, + } + } + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + if BOOT_SERVICES_LIVE.load(Ordering::Acquire) { + unsafe { GlobalAlloc::dealloc(&uefi::allocator::Allocator, ptr, layout) }; + } + } +} +#[global_allocator] +static ALLOCATOR: BootHeap = BootHeap; + +struct PhysicalTableMemory; +impl TableMemory for PhysicalTableMemory { + fn read_entry(&self, table: PhysAddr, index: usize) -> Option { + if index >= 512 { + return None; + } + Some(unsafe { core::ptr::read_volatile((table.0 as *const u64).add(index)) }) + } + fn write_entry(&mut self, table: PhysAddr, index: usize, value: u64) -> bool { + if index >= 512 { + return false; + } + unsafe { core::ptr::write_volatile((table.0 as *mut u64).add(index), value) }; + true + } +} + +fn runtime_attributes() -> Option> +{ + let mut table = None; + uefi::system::with_config_table(|entries| { + if let Some(entry) = entries + .iter() + .find(|e| e.guid == ConfigTableEntry::MEMORY_ATTRIBUTES_GUID) + { + table = Some(entry.address.cast::()); + } + }); + let ptr = table?; + let header = unsafe { core::slice::from_raw_parts(ptr, 16) }; + let count = u32::from_le_bytes(header[4..8].try_into().ok()?) as usize; + let stride = u32::from_le_bytes(header[8..12].try_into().ok()?) as usize; + let length = 16usize.checked_add(count.checked_mul(stride)?)?; + if length > 1 << 20 { + return None; + } + let bytes = unsafe { core::slice::from_raw_parts(ptr, length) }; + aienos_kernel::uefi::parse_memory_attributes_table(bytes).ok() +} + +fn clean_table_pool(base: usize, bytes: usize) { + #[cfg(target_arch = "aarch64")] + unsafe { + let ctr: u64; + core::arch::asm!("mrs {0}, ctr_el0", out(reg) ctr, options(nomem, nostack)); + let line = 4usize << ((ctr >> 16) & 0xf); + for address in (base..base + bytes).step_by(line) { + core::arch::asm!("dc cvac, {0}", in(reg) address, options(nostack)); + } + core::arch::asm!("dsb ish", options(nostack)); + } + #[cfg(not(target_arch = "aarch64"))] + let _ = (base, bytes); +} + +fn enter_kernel_mmu( + memory_map: &impl MemoryMap, + pool_base: usize, + image: AddressRange, + sections: &[aienos_kernel::mem::map_plan::PeSection], + attrs: Option<&[aienos_kernel::mem::map_plan::RuntimeAttributes]>, + framebuffer: Option, + uart: Option, + xhci_mmio: Option, + ecam: Option, +) -> (usize, usize, bool) { + let descriptors: alloc::vec::Vec<_> = memory_map + .entries() + .map(|d| EfiMemoryDescriptor { + memory_type: d.ty.0, + phys_start: d.phys_start, + page_count: d.page_count, + attribute: d.att.bits(), + }) + .collect(); + let mut mmio = alloc::vec::Vec::new(); + if let Some(fb) = framebuffer { + mmio.push(AddressRange { + start: fb.base & !4095, + length: (fb.size_bytes + (fb.base & 4095) + 4095) & !4095, + }); + } + if let Some(console) = uart { + mmio.push(AddressRange { + start: console.base & !4095, + length: 4096, + }); + } + if let Some(base) = xhci_mmio { + mmio.push(AddressRange { + start: base & !4095, + length: 0x10000, + }); + } + if let Some(range) = ecam { + mmio.push(range); + } + let (plan, decision) = + map_plan::build_map_plan(&descriptors, image.start, image, sections, attrs, &mmio) + .expect("identity map plan rejected firmware layout"); + let pool = + FixedFramePool::new(PhysAddr(pool_base), PT_POOL_PAGES).expect("invalid page table pool"); + let mut tables = PageTableBuilder::new(pool, PhysicalTableMemory) + .expect("page table root allocation failed"); + for mapping in plan { + tables + .map( + mapping.range.start as usize, + PhysAddr(mapping.range.start as usize), + mapping.range.length as usize, + mapping.flags, + ) + .expect("identity mapping failed"); + } + let root = tables.root().0; + let used = tables.frames_used().unwrap_or(0); + clean_table_pool(pool_base, PT_POOL_PAGES * 4096); + let parange: u64; + #[cfg(target_arch = "aarch64")] + unsafe { + core::arch::asm!("mrs {0}, id_aa64mmfr0_el1", out(reg) parange, options(nomem, nostack)); + } + #[cfg(not(target_arch = "aarch64"))] + { + parange = 5; + } + let entered = unsafe { + aienos_kernel::arch::aarch64::enter_el1h_mmu( + root, + map_plan::mair_el1(), + map_plan::tcr_el1((parange & 0xf) as u8), + map_plan::sctlr_el1(), + ) + }; + if !entered { + // Not at EL2: the kernel must not continue on firmware's translation. + aienos_kernel::arch::aarch64::halt(); + } + fatal::install_exception_vectors(); + ( + used, + root, + decision == Some(map_plan::RuntimeDecision::RuntimeCodeRxUnsplit), + ) +} + #[cfg(feature = "usb-keyboard")] mod usb_keyboard; @@ -247,7 +449,11 @@ fn probe_gb10( /// Walk every function on one bus of this root bridge. /// Returns the GB10 identity when the GB10 is found here. -fn scan_bus(root: &mut PciRootBridgeIo, bus: u8, scan: &mut BridgeScan) -> Option { +fn scan_bus( + root: &mut PciRootBridgeIo, + bus: u8, + scan: &mut BridgeScan, +) -> Option { for dev in 0..32u8 { for fun in 0..8u8 { let address = PciIoAddress::new(bus, dev, fun); @@ -713,6 +919,31 @@ fn main() -> Status { stage(FRAMEBUFFER_DISCOVERY); let framebuffer = discover_framebuffer(); *FRAMEBUFFER.lock() = framebuffer; + let (loaded_base, loaded_size) = + uefi::boot::open_protocol_exclusive::(uefi::boot::image_handle()) + .expect("LoadedImage protocol unavailable") + .info(); + let loaded_base = loaded_base as usize; + let loaded_size = usize::try_from(loaded_size).expect("loaded image too large"); + let image_bytes = unsafe { core::slice::from_raw_parts(loaded_base as *const u8, loaded_size) }; + let sections = aienos_kernel::pe::parse_pe_sections(image_bytes, loaded_base as u64) + .expect("loaded PE section table invalid"); + let runtime_attrs = runtime_attributes(); + let pt_pool = uefi::boot::allocate_pages( + uefi::boot::AllocateType::AnyPages, + MemoryType::LOADER_DATA, + PT_POOL_PAGES, + ) + .expect("page table pool allocation failed") + .as_ptr() as usize; + let post_exit_heap = uefi::boot::allocate_pages( + uefi::boot::AllocateType::AnyPages, + MemoryType::LOADER_DATA, + POST_EXIT_HEAP_PAGES, + ) + .expect("post-exit heap allocation failed") + .as_ptr() as usize; + POST_EXIT_HEAP.store(post_exit_heap as u64, Ordering::Release); #[cfg(feature = "usb-keyboard")] let xhci = usb_keyboard::find_xhci(); @@ -771,12 +1002,44 @@ fn main() -> Status { } stage(PRE_EXIT_SAVED); - // After this point only runtime services (variables, reset) are used. The - // returned map owns its backing allocation and stays live below. + // The firmware map and every buffer used below remain identity-mapped. stage(EXIT_BOOT_SERVICES); let memory_map = unsafe { uefi::boot::exit_boot_services(None) }; + BOOT_SERVICES_LIVE.store(false, Ordering::Release); EXITED.store(true, Ordering::SeqCst); + let (pt_frames_used, _, runtime_rx_unsplit) = enter_kernel_mmu( + &memory_map, + pt_pool, + AddressRange { + start: loaded_base as u64, + length: loaded_size as u64, + }, + §ions, + runtime_attrs.as_deref(), + framebuffer, + acpi_facts.spcr, + #[cfg(feature = "usb-keyboard")] + xhci.map(|x| x.mmio_base()), + #[cfg(not(feature = "usb-keyboard"))] + None, + #[cfg(feature = "usb-keyboard")] + xhci.and_then(|x| { + let (segment, bus) = x.ecam_location(); + acpi_facts.mcfg.and_then(|t| { + acpi::mcfg_window(t, segment, bus) + .ok() + .flatten() + .map(|w| AddressRange { + start: w.base, + length: (u64::from(w.end_bus) - u64::from(w.start_bus) + 1) << 20, + }) + }) + }), + #[cfg(not(feature = "usb-keyboard"))] + None, + ); + fatal::set_fault_hook(on_fault); fatal::install_exception_vectors(); stage(VECTORS_INSTALLED); @@ -816,6 +1079,29 @@ fn main() -> Status { let mut report = Report::new(); header(&mut report, "final"); write_index_line(&mut report); + // Measured, not asserted: read the live exception level and SCTLR_EL1.M. + let el = aienos_kernel::arch::aarch64::current_el(); + if el == 1 { + let _ = writeln!(report, "kernel_el: EL1h"); + } else { + let _ = writeln!(report, "kernel_el: unexpected EL{el}"); + } + let mmu_on = aienos_kernel::arch::aarch64::el1_mmu_enabled(); + let _ = writeln!( + report, + "mmu: {}", + if mmu_on { "enabled" } else { "disabled" } + ); + let _ = writeln!(report, "pt_frames_used: {pt_frames_used}"); + let _ = writeln!( + report, + "runtime_code: {}", + if runtime_rx_unsplit { + "rx-unsplit" + } else { + "mat-split" + } + ); let _ = write!(report, "{}", kernel_report.as_str()); if gb10.is_none() { gb10_discovery.write_diagnostics(&mut report); diff --git a/crates/aienos-boot/src/usb_keyboard.rs b/crates/aienos-boot/src/usb_keyboard.rs index d5a94870..3487c5db 100644 --- a/crates/aienos-boot/src/usb_keyboard.rs +++ b/crates/aienos-boot/src/usb_keyboard.rs @@ -38,6 +38,15 @@ pub struct XhciLocation { mmio: u64, } +impl XhciLocation { + pub fn mmio_base(self) -> u64 { + self.mmio + } + pub fn ecam_location(self) -> (u16, u8) { + (self.segment, self.bus) + } +} + /// Walk every root bridge for the first xHCI controller (pre-exit only). pub fn find_xhci() -> Option { for handle in uefi::boot::find_handles::().ok()? { diff --git a/crates/aienos-kernel/src/arch/aarch64.rs b/crates/aienos-kernel/src/arch/aarch64.rs index a294f891..d2dcdb94 100644 --- a/crates/aienos-kernel/src/arch/aarch64.rs +++ b/crates/aienos-kernel/src/arch/aarch64.rs @@ -52,6 +52,81 @@ pub fn current_el() -> u8 { } } +/// True when running at EL1 with stage-1 translation on (SCTLR_EL1.M set). +pub fn el1_mmu_enabled() -> bool { + #[cfg(target_arch = "aarch64")] + { + if current_el() != 1 { + return false; + } + let sctlr: u64; + unsafe { + core::arch::asm!("mrs {0}, sctlr_el1", out(reg) sctlr, options(nomem, nostack)); + } + sctlr & 1 != 0 + } + #[cfg(not(target_arch = "aarch64"))] + { + false + } +} + +/// Configure stage-1 translation and enter EL1h using an identity-mapped root. +/// The caller must ensure the current PC, stack, code, and data are mapped. +/// +/// # Safety +/// `root` must reference a valid 4 KiB-granule EL1 table tree whose identity +/// mappings cover this function, its caller, the active stack, and all live data. +pub unsafe fn enter_el1h_mmu(root: usize, mair: u64, tcr: u64, sctlr: u64) -> bool { + #[cfg(target_arch = "aarch64")] + { + if current_el() != 2 { + return false; + } + core::arch::asm!( + "msr daifset, #0xf", + "mov x9, sp", + "msr sp_el1, x9", + "mov x9, #0x80000000", + "msr hcr_el2, x9", + "mov x9, #0x33ff", + "msr cptr_el2, x9", + "mov x9, #3", + "msr cnthctl_el2, x9", + "msr cntvoff_el2, xzr", + "mov x9, #0x300000", + "msr cpacr_el1, x9", + "msr mair_el1, x1", + "msr tcr_el1, x2", + "msr ttbr0_el1, x0", + "tlbi vmalle1", + "dsb ish", + "isb", + "msr sctlr_el1, x3", + "isb", + "mov x9, #0x3c5", + "msr spsr_el2, x9", + "adr x9, 2f", + "msr elr_el2, x9", + "isb", + "eret", + "2:", + in("x0") root as u64, + in("x1") mair, + in("x2") tcr, + in("x3") sctlr, + lateout("x9") _, + options(nostack) + ); + true + } + #[cfg(not(target_arch = "aarch64"))] + { + let _ = (root, mair, tcr, sctlr); + false + } +} + /// Read the architectural virtual counter. Its frequency is reported by `counter_frequency_hz`. #[inline(always)] pub fn counter_ticks() -> u64 { diff --git a/crates/aienos-kernel/src/mem/map_plan.rs b/crates/aienos-kernel/src/mem/map_plan.rs index 9ede3cad..c5ea9d5b 100644 --- a/crates/aienos-kernel/src/mem/map_plan.rs +++ b/crates/aienos-kernel/src/mem/map_plan.rs @@ -37,7 +37,7 @@ pub struct PlannedMapping { } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RuntimeDecision { - AttributesTableUnavailableCallBeforeTransition, + RuntimeCodeRxUnsplit, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PlanError { @@ -52,6 +52,7 @@ pub enum PlanError { const EFI_LOADER_CODE: u32 = 1; const EFI_RUNTIME_CODE: u32 = 5; const EFI_RUNTIME_DATA: u32 = 6; +const EFI_MMIO: u32 = 11; const IMAGE_SCN_MEM_EXECUTE: u32 = 0x2000_0000; const IMAGE_SCN_MEM_WRITE: u32 = 0x8000_0000; @@ -83,6 +84,7 @@ pub fn build_map_plan( mmio: &[AddressRange], ) -> Result<(Vec, Option), PlanError> { let mut out = Vec::new(); + let mut decision = None; for d in memory { let length = d.page_count.checked_mul(4096).ok_or(PlanError::Overflow)?; if length == 0 { @@ -134,14 +136,21 @@ pub fn build_map_plan( flags: MapFlags::KERNEL_DATA, }); } + } else if d.memory_type == EFI_MMIO { + out.push(PlannedMapping { + range: region, + flags: flags(true, false, MemoryAttribute::DeviceNgnre), + }); } else if d.memory_type == EFI_RUNTIME_CODE || (d.attribute & EFI_MEMORY_RUNTIME != 0 && d.memory_type != EFI_RUNTIME_DATA) { let Some(attrs) = runtime_attributes else { - return Ok(( - out, - Some(RuntimeDecision::AttributesTableUnavailableCallBeforeTransition), - )); + out.push(PlannedMapping { + range: region, + flags: flags(false, true, MemoryAttribute::NormalWriteBack), + }); + decision = Some(RuntimeDecision::RuntimeCodeRxUnsplit); + continue; }; let mut cursor = region.start; while cursor < end(region)? { @@ -152,7 +161,9 @@ pub fn build_map_plan( let stop = end(attr.range)?.min(end(region)?); let executable = !attr.execute_protect; if executable && !attr.read_only { - return Err(PlanError::RuntimeCodeCannotSplit); + // Some firmware MATs describe a writable executable + // runtime range. Preserve execution while enforcing W^X. + decision = Some(RuntimeDecision::RuntimeCodeRxUnsplit); } out.push(PlannedMapping { range: AddressRange { @@ -167,18 +178,25 @@ pub fn build_map_plan( }); cursor = stop; } - } else if d.memory_type == EFI_RUNTIME_DATA { + } else if matches!(d.memory_type, 2 | 3 | 4 | 7 | 9 | 10 | EFI_RUNTIME_DATA) { out.push(PlannedMapping { range: region, flags: MapFlags::KERNEL_DATA, }); } } + let descriptor_mappings = out.len(); for r in mmio { - out.push(PlannedMapping { - range: *r, - flags: flags(true, false, MemoryAttribute::DeviceNgnre), - }); + if !out[..descriptor_mappings].iter().any(|m| { + m.flags.attribute == MemoryAttribute::DeviceNgnre + && m.range.start <= r.start + && end(m.range).is_ok_and(|e| e >= end(*r).unwrap_or(u64::MAX)) + }) { + out.push(PlannedMapping { + range: *r, + flags: flags(true, false, MemoryAttribute::DeviceNgnre), + }); + } } for i in 0..out.len() { for j in i + 1..out.len() { @@ -187,7 +205,7 @@ pub fn build_map_plan( } } } - Ok((out, None)) + Ok((out, decision)) } pub const fn mair_el1() -> u64 { @@ -286,7 +304,7 @@ mod tests { assert!(p[1].flags.writable && !p[1].flags.executable); } #[test] - fn missing_mat_has_explicit_runtime_call_decision() { + fn missing_mat_maps_runtime_code_rx_without_wx() { let (p, d) = build_map_plan( &[d(EFI_RUNTIME_CODE, 0x400000, 1, EFI_MEMORY_RUNTIME)], 0, @@ -299,11 +317,9 @@ mod tests { &[], ) .unwrap(); - assert!(p.is_empty()); - assert_eq!( - d, - Some(RuntimeDecision::AttributesTableUnavailableCallBeforeTransition) - ); + assert_eq!(p.len(), 1); + assert!(p[0].flags.executable && !p[0].flags.writable); + assert_eq!(d, Some(RuntimeDecision::RuntimeCodeRxUnsplit)); } #[test] fn runtime_code_needs_ro_xp_split() { @@ -343,7 +359,7 @@ mod tests { assert!(p[1].flags.writable && !p[1].flags.executable); } #[test] - fn unsplittable_runtime_code_is_rejected() { + fn writable_executable_runtime_code_is_mapped_rx() { let m = [d(EFI_RUNTIME_CODE, 0x400000, 1, EFI_MEMORY_RUNTIME)]; let a = [RuntimeAttributes { range: AddressRange { @@ -353,20 +369,20 @@ mod tests { read_only: false, execute_protect: false, }]; - assert_eq!( - build_map_plan( - &m, - 0, - AddressRange { - start: 0, - length: 1 - }, - &[], - Some(&a), - &[] - ), - Err(PlanError::RuntimeCodeCannotSplit) - ); + let (plan, decision) = build_map_plan( + &m, + 0, + AddressRange { + start: 0, + length: 1, + }, + &[], + Some(&a), + &[], + ) + .unwrap(); + assert_eq!(decision, Some(RuntimeDecision::RuntimeCodeRxUnsplit)); + assert!(plan[0].flags.executable && !plan[0].flags.writable); } #[test] fn mmio_is_device_nx_and_overlap_rejected() { diff --git a/crates/aienos-kernel/src/mem/pagetable.rs b/crates/aienos-kernel/src/mem/pagetable.rs index f46db343..cc571378 100644 --- a/crates/aienos-kernel/src/mem/pagetable.rs +++ b/crates/aienos-kernel/src/mem/pagetable.rs @@ -19,6 +19,54 @@ const PAGE_SIZE_U64: u64 = 1 << PAGE_SHIFT; pub trait FrameSource { fn allocate_frame(&mut self) -> Option; fn deallocate_frame(&mut self, frame: PhysAddr) -> bool; + fn frames_used(&self) -> Option { + None + } +} + +/// Monotonic allocator over a firmware-reserved contiguous page pool. +/// Frames are never returned to the pool after allocation. +#[derive(Clone, Copy, Debug)] +pub struct FixedFramePool { + base: PhysAddr, + capacity: usize, + used: usize, +} + +impl FixedFramePool { + pub fn new(base: PhysAddr, capacity: usize) -> Option { + if !base.is_page_aligned() || capacity == 0 || capacity > (usize::MAX - base.0) / PAGE_SIZE + { + return None; + } + Some(Self { + base, + capacity, + used: 0, + }) + } + + pub const fn used(&self) -> usize { + self.used + } +} + +impl FrameSource for FixedFramePool { + fn allocate_frame(&mut self) -> Option { + if self.used == self.capacity { + return None; + } + let frame = PhysAddr(self.base.0 + self.used * PAGE_SIZE); + self.used += 1; + Some(frame) + } + + fn deallocate_frame(&mut self, _frame: PhysAddr) -> bool { + false + } + fn frames_used(&self) -> Option { + Some(self.used) + } } impl FrameSource for super::frame_allocator::BitmapFrameAllocator { @@ -118,6 +166,10 @@ impl PageTableBuilder { self.root } + pub fn frames_used(&self) -> Option { + self.frames.frames_used() + } + /// Maps a page-aligned range, using 1 GiB or 2 MiB blocks where possible. pub fn map( &mut self, @@ -429,6 +481,17 @@ mod tests { PageTableBuilder::new(Frames { next: 0x1000 }, Memory::default()).unwrap() } + #[test] + fn fixed_pool_is_bounded_and_never_reuses_released_frames() { + let mut pool = FixedFramePool::new(PhysAddr(0x8000), 2).unwrap(); + assert_eq!(pool.allocate_frame(), Some(PhysAddr(0x8000))); + assert_eq!(pool.allocate_frame(), Some(PhysAddr(0x9000))); + assert_eq!(pool.allocate_frame(), None); + assert!(!pool.deallocate_frame(PhysAddr(0x8000))); + assert_eq!(pool.used(), 2); + assert!(FixedFramePool::new(PhysAddr(0x8001), 2).is_none()); + } + #[test] fn descriptor_encodes_attributes_exactly() { let d = (0x1234_5000u64 & ADDRESS_MASK) | leaf_attributes(MapFlags::KERNEL_DATA) | TABLE; diff --git a/scripts/qemu_boot_test.sh b/scripts/qemu_boot_test.sh index 3b3b6096..9f0d4efb 100755 --- a/scripts/qemu_boot_test.sh +++ b/scripts/qemu_boot_test.sh @@ -55,6 +55,8 @@ echo "qemu exit ${qemu_status} after ${elapsed} s (commit ${commit:0:12})" check "pre-exit report printed" "report_kind: pre_exit" check "image is this commit" "aienos_commit: ${commit}" check "left firmware and entered the kernel" "kernel: alive" +check "kernel entered EL1h" "kernel_el: EL1h" +check "EL1 page tables and caches enabled" "mmu: enabled" check "final report on the SPCR console" "report_kind: final" check "no panic or fault" "report_kind: final" if grep -qE "report_kind: (panic|fault)" "${work}/serial.txt"; then