diff --git a/crates/stela-boot/src/engine.rs b/crates/stela-boot/src/engine.rs index 30e441b12d..673d12a722 100644 --- a/crates/stela-boot/src/engine.rs +++ b/crates/stela-boot/src/engine.rs @@ -1722,6 +1722,7 @@ fn install_host(handoff: &'static Handoff, options: &Options, ram: &[RamRange]) pool_physical: handoff.pool.physical, pool_bytes: partition.pool_bytes, window_root: handoff.root, + loader_tables: &handoff.native_loader_tables, code_virtual: layout::code(), code_physical: handoff.code.physical, code_bytes: partition.code_bytes, diff --git a/crates/stela-boot/src/engine/host.rs b/crates/stela-boot/src/engine/host.rs index abc01ce3f9..30520b214f 100644 --- a/crates/stela-boot/src/engine/host.rs +++ b/crates/stela-boot/src/engine/host.rs @@ -262,6 +262,7 @@ pub struct State { host_root: u64, /// Original actual loader root retained from install, never caller metadata. window_root: u64, + _loader_tables: &'static crate::paging::loader::LoaderTables, roots: [u64; ROOTS], /// The roots of other SPRR_PERM_EL0 and SPRR_PERM_EL1 pairs. banks: [Bank; BANKS], @@ -368,6 +369,7 @@ pub struct Config { pub pool_bytes: u64, /// The loader's root, whose window entries every root shares. pub window_root: u64, + pub(crate) loader_tables: &'static crate::paging::loader::LoaderTables, /// Processor-private executable alias; arena writes use the physmap. pub code_virtual: u64, pub code_physical: u64, @@ -408,16 +410,21 @@ pub unsafe fn install(config: Config) -> Result { pool.reset_half(half); } let (first, last) = layout::window_entries(); - let window = layout::physical(config.window_root) as *const u64; + if config.loader_tables.root() != config.window_root { + return Err("loader root descriptor differs from its original owner"); + } let mut root = || -> Result { let frame = pool.permanent().ok_or("page-table pool too small")?; for entry in first..=last { - // SAFETY: a fresh permanent frame and the loader's root, both - // through the physmap. + let value = config + .loader_tables + .boot_entry(entry) + .map_err(|_| "original loader table context changed before host installation")?; + // SAFETY: this actual processor's fresh permanent pool allocation. unsafe { (layout::physical(frame) as *mut u64) .add(entry) - .write(window.add(entry).read()) + .write(value) }; } Ok(frame) @@ -448,6 +455,7 @@ pub unsafe fn install(config: Config) -> Result { pool, host_root, window_root: config.window_root, + _loader_tables: config.loader_tables, roots, banks, bank_switches: 0, diff --git a/crates/stela-boot/src/handoff.rs b/crates/stela-boot/src/handoff.rs index a12d567594..82df380343 100644 --- a/crates/stela-boot/src/handoff.rs +++ b/crates/stela-boot/src/handoff.rs @@ -199,6 +199,8 @@ pub struct Handoff { /// Firmware-created task allocation owners; the preceding wire fields keep /// their offsets. The engine can claim each owner once, after mapping checks. pub(crate) native_task_allocations: crate::native_smp::resources::TaskAllocations, + /// Original loader table allocations; root is only their copied descriptor. + pub(crate) native_loader_tables: crate::paging::loader::LoaderTables, } #[cfg(test)] diff --git a/crates/stela-boot/src/native_smp/executor.rs b/crates/stela-boot/src/native_smp/executor.rs index 1491772574..034b665ac7 100644 --- a/crates/stela-boot/src/native_smp/executor.rs +++ b/crates/stela-boot/src/native_smp/executor.rs @@ -449,6 +449,7 @@ pub(crate) unsafe fn start( pool_physical: handoff.pool.physical + part.pool_offset, pool_bytes: part.pool_bytes, window_root: handoff.root, + loader_tables: &handoff.native_loader_tables, code_virtual: layout::code() + part.code_offset, code_physical: handoff.code.physical + part.code_offset, code_bytes: part.code_bytes, diff --git a/crates/stela-boot/src/paging.rs b/crates/stela-boot/src/paging.rs index ee843c2211..bfc9c9af67 100644 --- a/crates/stela-boot/src/paging.rs +++ b/crates/stela-boot/src/paging.rs @@ -5,6 +5,7 @@ use alloc::vec::Vec; mod active; #[cfg(feature = "diagnostics")] pub(crate) mod config; +pub(crate) mod loader; pub(crate) use active::{ActivatedTables, RootError}; use core::{ arch::{asm, naked_asm}, @@ -58,12 +59,12 @@ struct AllocatedTablePage { } fn new_table() -> Result { - let page = uefi::boot::allocate_pages( - uefi::boot::AllocateType::AnyPages, - uefi::boot::MemoryType::LOADER_DATA, - 1, - ) - .map_err(|_| "no memory for a page table")?; + allocate_table(uefi::boot::AllocateType::AnyPages) +} + +fn allocate_table(policy: uefi::boot::AllocateType) -> Result { + let page = uefi::boot::allocate_pages(policy, uefi::boot::MemoryType::LOADER_DATA, 1) + .map_err(|_| "no memory for a page table")?; let table = page.as_ptr().cast::(); // SAFETY: a fresh page owned by Stela for the rest of the boot. unsafe { table.write_bytes(0, 1) }; diff --git a/crates/stela-boot/src/paging/active.rs b/crates/stela-boot/src/paging/active.rs index e78764f22c..3ca30c0120 100644 --- a/crates/stela-boot/src/paging/active.rs +++ b/crates/stela-boot/src/paging/active.rs @@ -21,6 +21,8 @@ pub(crate) enum RootError { ControlsChanged, NotActivated, Closed, + CatalogSize, + CatalogAllocation(uefi::Status), Traversal(mappings::Error), AliasMissing { physical: u64 }, AliasMismatch { physical: u64 }, @@ -39,6 +41,10 @@ impl fmt::Display for RootError { Self::ControlsChanged => f.write_str("native root controls or PAT changed"), Self::NotActivated => f.write_str("new table root was not actually activated"), Self::Closed => f.write_str("native root ownership was closed after a context change"), + Self::CatalogSize => f.write_str("loader catalog size overflows or is empty"), + Self::CatalogAllocation(status) => { + write!(f, "loader catalog allocation failed: {status:?}") + } Self::Traversal(error) => write!(f, "owned page-table traversal refused: {error:?}"), Self::AliasMissing { physical } => { write!(f, "native tables omit their frame mapping at {physical:#x}") diff --git a/crates/stela-boot/src/paging/loader.rs b/crates/stela-boot/src/paging/loader.rs new file mode 100644 index 0000000000..c42267c8e2 --- /dev/null +++ b/crates/stela-boot/src/paging/loader.rs @@ -0,0 +1,205 @@ +//! Original Engine loader allocations, including their real catalog storage. +//! Allocation ownership supplies no controller, firmware-service or CPU grant. +use super::{AllocatedTablePage, RootError, allocate_table}; +use alloc::vec::Vec; +use core::arch::asm; +use stela_boot_core::guarded_stacks::mappings; + +pub(crate) struct Builder { + root: u64, + pages: Vec, + levels: u32, +} +impl Builder { + pub(crate) fn new() -> Result { + let mut pages = Vec::new(); + pages + .try_reserve_exact(1) + .map_err(|_| "loader table catalog allocation failed")?; + // The real-mode/AP trampoline loads this original root below 4 GiB. + let allocation = allocate_table(uefi::boot::AllocateType::MaxAddress(u32::MAX as u64))?; + let root = allocation.physical; + pages.push(allocation); + Ok(Self { + root, + pages, + levels: crate::layout::top_level() + 1, + }) + } + pub(crate) fn root(&self) -> u64 { + self.root + } + pub(crate) fn retain(self) -> Result { + let mut catalog = CatalogBacking::reserve(self.pages.len())?; + for (index, owner) in self.pages.into_iter().enumerate() { + catalog.place(index, owner); + } + let owner = LoaderTables { + root: self.root, + levels: self.levels, + catalog, + }; + owner.validate_aliases()?; + Ok(owner) + } +} +impl crate::tables::Frames for Builder { + fn frame(&mut self) -> Option { + self.pages.try_reserve(1).ok()?; + let allocation = allocate_table(uefi::boot::AllocateType::AnyPages).ok()?; + let physical = allocation.physical; + self.pages.push(allocation); + Some(physical) + } + fn table(&self, physical: u64) -> *mut u64 { + assert!( + self.pages.iter().any(|page| page.physical == physical), + "foreign loader table frame" + ); + physical as *mut u64 + } +} + +/// A genuine separate LOADER_DATA allocation contains the MOVED original +/// non-Clone page owners. No firmware-heap Vec or Arc pointer crosses roots. +struct CatalogBacking { + physical: u64, + bytes: u64, + count: usize, +} +impl CatalogBacking { + fn reserve(count: usize) -> Result { + let bytes = count + .checked_mul(size_of::()) + .filter(|bytes| *bytes != 0) + .ok_or(RootError::CatalogSize)?; + let pages = bytes.div_ceil(super::PAGE); + let bytes = pages + .checked_mul(super::PAGE) + .ok_or(RootError::CatalogSize)?; + let allocation = uefi::boot::allocate_pages( + uefi::boot::AllocateType::AnyPages, + uefi::boot::MemoryType::LOADER_DATA, + pages, + ) + .map_err(|error| RootError::CatalogAllocation(error.status()))?; + // SAFETY: this fresh, exclusive actual allocation has exactly bytes + // writable bytes. It is not a table, DMA buffer or published catalog. + unsafe { + allocation.as_ptr().write_bytes(0, bytes); + } + Ok(Self { + physical: allocation.as_ptr() as u64, + bytes: bytes as u64, + count, + }) + } + fn place(&mut self, index: usize, owner: AllocatedTablePage) { + assert!(index < self.count); + // SAFETY: actual original catalog allocation, checked slot geometry; + // each owner is moved once before publication, with no active readers. + unsafe { + (self.physical as *mut AllocatedTablePage) + .add(index) + .write(owner); + } + } + fn physical(&self, index: usize) -> Option { + if index >= self.count { + return None; + } + // SAFETY: retained original metadata allocation; construction or actual + // original-loader context supplies its checked identity alias. Read only + // the observation field, without cloning the original allocation owner. + Some(unsafe { + core::ptr::addr_of!((*(self.physical as *const AllocatedTablePage).add(index)).physical) + .read_volatile() + }) + } +} + +/// Inline Handoff owner of ORIGINAL table pages and catalog allocation. None +/// are freed to firmware, guest RAM or DMA for the complete shared-root boot. +/// Native consumers still need their real CPU/root/controller exclusion grants. +pub(crate) struct LoaderTables { + root: u64, + levels: u32, + catalog: CatalogBacking, +} +impl LoaderTables { + pub(crate) fn root(&self) -> u64 { + self.root + } + fn read_owned(&self, table: u64, index: usize) -> Option { + if index >= super::ENTRIES + || !(0..self.catalog.count).any(|slot| self.catalog.physical(slot) == Some(table)) + { + return None; + } + // SAFETY: original allocated page owner is retained in the actual + // catalog; construction or checked loader context supplies its alias. + Some(unsafe { (table as *const u64).add(index).read_volatile() }) + } + fn observe(&self, address: u64) -> Result, mappings::Error> { + mappings::observe(address, self.root, self.levels, |table, index| { + self.read_owned(table, index) + }) + } + fn validate_page(&self, physical: u64) -> Result<(), RootError> { + for alias in [physical, crate::layout::physical(physical)] { + let leaf = self + .observe(alias) + .map_err(RootError::Traversal)? + .ok_or(RootError::AliasMissing { physical })?; + if leaf.physical != physical || !leaf.writable || leaf.user { + return Err(RootError::AliasMismatch { physical }); + } + } + Ok(()) + } + fn validate_aliases(&self) -> Result<(), RootError> { + for index in 0..self.catalog.count { + self.validate_page(self.catalog.physical(index).ok_or(RootError::CatalogSize)?)?; + } + for offset in (0..self.catalog.bytes).step_by(super::PAGE) { + self.validate_page( + self.catalog + .physical + .checked_add(offset) + .ok_or(RootError::CatalogSize)?, + )?; + } + Ok(()) + } + pub(crate) fn boot_entry(&self, index: usize) -> Result { + let selector: u16; + // SAFETY: read-only CPL observation precedes privileged operations. + unsafe { + asm!("mov {0:x}, cs", out(reg) selector, options(nomem, nostack, preserves_flags)); + } + if selector & 3 != 0 { + return Err(RootError::Privilege); + } + let (flags, root, cr4): (u64, u64, u64); + // SAFETY: actual CPL0; controlled boot installation runs without + // migration, callbacks or another table builder using these pages. + unsafe { + asm!("pushfq", "pop {}", "mov {}, cr3", "mov {}, cr4", out(reg) flags, out(reg) root, out(reg) cr4, options(nomem, preserves_flags)); + } + if flags & (1 << 9) != 0 { + return Err(RootError::InterruptsEnabled); + } + if root != self.root { + return Err(RootError::RootChanged); + } + if self.levels != if cr4 & (1 << 12) != 0 { 5 } else { 4 } { + return Err(RootError::ControlsChanged); + } + // Sealing checked all original identity and high-window aliases. The + // sole builder was consumed; later native mappings must preserve them. + self.read_owned(self.root, index) + .ok_or(RootError::Transition( + "loader root entry is outside its owned table", + )) + } +} diff --git a/crates/stela-boot/src/system.rs b/crates/stela-boot/src/system.rs index e2835155e3..fa818df2ba 100644 --- a/crates/stela-boot/src/system.rs +++ b/crates/stela-boot/src/system.rs @@ -102,21 +102,6 @@ pub fn take_snapshot() { } } -/// Firmware pages reached by identity. -struct FirmwareFrames; - -impl Frames for FirmwareFrames { - fn frame(&mut self) -> Option { - let page = firmware::pages(1).ok()? as u64; - // SAFETY: a fresh page owned by Stela. - unsafe { (page as *mut u8).write_bytes(0, PAGE as usize) }; - Some(page) - } - fn table(&self, physical: u64) -> *mut u64 { - physical as *mut u64 - } -} - fn low_page(kind: MemoryType) -> Result { let page = boot::allocate_pages(AllocateType::MaxAddress(BELOW_4G), kind, 1) .map_err(|_| "no page below 4 GiB for the page-table root")?; @@ -708,7 +693,11 @@ fn load( handoff_page, trampoline, root, + loader_tables, } = memory; + let loader_tables = loader_tables + .retain() + .map_err(|_| "loader table ownership validation failed")?; let bounce = native_resources.bounce[0]; let handoff_phase::RetainedFiles { options: options_region, @@ -811,6 +800,7 @@ fn load( bytes: wifi_key.len() as u64, }, native_task_allocations, + native_loader_tables: loader_tables, }); } // SAFETY: boot services ended; the completed root maps this code and diff --git a/crates/stela-boot/src/system/memory.rs b/crates/stela-boot/src/system/memory.rs index 3ec4d0cc65..c6092b1999 100644 --- a/crates/stela-boot/src/system/memory.rs +++ b/crates/stela-boot/src/system/memory.rs @@ -24,6 +24,7 @@ pub(super) struct EngineMemory { pub handoff_page: Region, pub trampoline: u64, pub root: u64, + pub loader_tables: crate::paging::loader::Builder, } /// Copy and relocate the pristine image into the selected host window. @@ -163,7 +164,8 @@ pub(super) fn reserve( crate::native_smp::resources::partition(cores, cores - 1, code.bytes, pool.bytes, false)?; let handoff_page = allocate(size_of::() as u64)?; let trampoline = low_page(MemoryType::LOADER_CODE)?; - let root = low_page(MemoryType::LOADER_DATA)?; + let loader_tables = crate::paging::loader::Builder::new()?; + let root = loader_tables.root(); Ok(EngineMemory { heap, native_resources, @@ -174,6 +176,7 @@ pub(super) fn reserve( handoff_page, trampoline, root, + loader_tables, }) } @@ -200,11 +203,12 @@ pub(super) fn map( code, trampoline, root, + loader_tables, .. } = memory; let (root, trampoline, apic) = (*root, *trampoline, *apic); let cores = native_resources.cores as usize; - let mut frames = FirmwareFrames; + let frames = loader_tables; let mut image_rights: Vec<(u64, u64, u64)> = image .sections .iter() @@ -215,14 +219,14 @@ pub(super) fn map( if native_resources.sipi != 0 { image_rights.push((native_resources.sipi, native_resources.sipi + PAGE, PRESENT)); } - identity(&mut frames, root, ram, &image_rights)?; + identity(frames, root, ram, &image_rights)?; if let Some(storage) = storage { - map_devices(&mut frames, root, ram, &storage.mapped)?; + map_devices(frames, root, ram, &storage.mapped)?; } let mapped = storage .as_ref() .map_or(&[][..], |storage| &storage.mapped[..]); - runtime.map(&mut frames, root, ram, mapped)?; + runtime.map(frames, root, ram, mapped)?; let mut storage = match storage { Some(storage) => Storage::new(storage)?, None => Storage::absent(), @@ -234,7 +238,7 @@ pub(super) fn map( let start = screen.base as u64 & !(PAGE - 1); let end = (screen.base + screen.bytes) as u64; tables::map_range( - &mut frames, + frames, root, start, start, @@ -246,7 +250,7 @@ pub(super) fn map( for page in (0..snapshot.bytes as u64).step_by(PAGE as usize) { let rights = image.rights(image.start + page as usize); tables::map_page( - &mut frames, + frames, root, layout::image() + page, engine.physical + page, @@ -256,7 +260,7 @@ pub(super) fn map( let data = PRESENT | WRITABLE | NX; for slot in 0..cores { tables::map_range( - &mut frames, + frames, root, layout::stack() + slot as u64 * STACK_STRIDE + PAGE, native_resources.stacks.physical + slot as u64 * STACK_BYTES, @@ -285,7 +289,7 @@ pub(super) fn map( .slot(base, index) .map_err(|_| "guarded stack virtual range overflow")?; tables::map_range( - &mut frames, + frames, root, slot.usable.start, region.physical @@ -317,7 +321,7 @@ pub(super) fn map( .backing(raw.physical..end, index) .map_err(|_| "mixed32 backing alignment overflow")?; tables::map_range( - &mut frames, + frames, root, slot.usable.start, backing.start, @@ -327,7 +331,7 @@ pub(super) fn map( } } tables::map_range( - &mut frames, + frames, root, layout::code(), code.physical, @@ -338,7 +342,7 @@ pub(super) fn map( for &(start, end) in ram { let (start, end) = (start as u64, end as u64); tables::map_range( - &mut frames, + frames, root, layout::physical(start), start, @@ -351,7 +355,7 @@ pub(super) fn map( let end = ((screen.base + screen.bytes) as u64).next_multiple_of(PAGE); if !ram.iter().any(|r| r.0 as u64 <= start && end <= r.1 as u64) { tables::map_range( - &mut frames, + frames, root, layout::physical(start), start, @@ -363,13 +367,7 @@ pub(super) fn map( // The xAPIC page must be strong uncacheable (Intel SDM Vol. 3A 11.4.1); // the entry says so rather than relying on the firmware's MTRRs. if !ram.iter().any(|r| r.0 as u64 <= apic && apic < r.1 as u64) { - tables::map_page( - &mut frames, - root, - layout::physical(apic), - apic, - data | UNCACHED, - )?; + tables::map_page(frames, root, layout::physical(apic), apic, data | UNCACHED)?; } // The bounce slot's leaf entries, which the translation helper points // at guest frames; until then they map a scratch page. @@ -377,14 +375,14 @@ pub(super) fn map( for index in 0..2 { let scratch = allocate(PAGE)?.physical; let address = layout::bounce() + (slot * 2 + index) as u64 * PAGE; - tables::map_page(&mut frames, root, address, scratch, data)?; - let entry = tables::entry(&mut frames, root, address, 0, false)?; + tables::map_page(frames, root, address, scratch, data)?; + let entry = tables::entry(frames, root, address, 0, false)?; native_resources.bounce[slot][index] = entry.ok_or("bounce slot unmapped")? as u64; } } if let Some(prepared) = native_mmio { - prepared.aperture(&mut frames, root, cores)?; + prepared.aperture(frames, root, cores)?; } Ok(storage)