fix(boot): save the NVRAM bank a boot consumed from and clear a carried failure record with Stela's own drivers after the firmware has exited, as pending work read as done until then, and never through the firmware's block I/O

This commit is contained in:
Tyler Smith committed 2026-11-14 01:33:59 -05:00
1 parent e1c92ebeb0
commit 4bb6ebdc71
9 files changed
+342 -211

No files matched your search

+26 -10
View File
@@ -31,7 +31,7 @@ use stela_contracts::refuse;
use stela_loader::mount_interface::{
CHOICES_FILE, CHOSEN_DISK, ChoiceKind, Choices, DISK_FILE, Opening, opening, with_disk,
};
use stela_runtime::pc::disk_plan::Plan;
use stela_runtime::pc::{disk_plan::Plan, disk_writes::Pending};
use uefi::{
CString16,
boot::{self, EventType, TimerTrigger, Tpl},
@@ -221,8 +221,18 @@ struct Menu<'a> {
impl<'a> Menu<'a> {
/// The menu of `choices`: those that can start now, then the firmware's
/// entries. `held` is why the machine can only be set up.
fn new(choices: &'a Choices, held: Option<&'a str>, disk: Option<String>) -> Self {
/// entries. An entry is checked on its disk as choosing it leaves the
/// `pending` work: the updates done and no plan, which a choice
/// replaces. `held` is why the machine can only be set up.
fn new(
choices: &'a Choices,
held: Option<&'a str>,
disk: Option<String>,
pending: &Pending,
) -> Self {
let mut pending = pending.clone();
pending.replace_plan(None);
let pending = &pending;
// A choice on a disk not chosen yet waits for Install macOS.
let resolved: Vec<Option<String>> = choices
.entries
@@ -234,7 +244,7 @@ impl<'a> Menu<'a> {
.iter()
.zip(&resolved)
.map(|(entry, options)| match options {
Some(options) => selection::ready(options, entry.kind()),
Some(options) => selection::ready(options, entry.kind(), pending),
None => Readiness::Unprepared,
})
.collect();
@@ -523,10 +533,16 @@ fn menu(volume: &mut FileSystem, choices: &Choices, mut menu: Menu<'_>) -> Optio
/// What to boot: the chosen entry's options, or `options` (`stela.cfg`).
/// `held` is why the default boot can only wait for the setup restore, when
/// it can.
pub fn choose(volume: &mut FileSystem, options: Vec<u8>, held: Option<&str>) -> Chosen {
/// it can. `pending` is the disk work decided so far, which the entries'
/// disks are read with (`selection::ready`).
pub fn choose(
volume: &mut FileSystem,
options: Vec<u8>,
held: Option<&str>,
pending: &Pending,
) -> Chosen {
if let Some(reason) = held {
return hold(volume, reason).unwrap_or(options.into());
return hold(volume, reason, pending).unwrap_or(options.into());
}
let Some(choices) = read(volume) else {
return options.into();
@@ -535,7 +551,7 @@ pub fn choose(volume: &mut FileSystem, options: Vec<u8>, held: Option<&str>) ->
if choices.timeout_seconds == 0 && pressed().is_none() {
return chosen(&choices, 0, chosen_disk(volume).as_deref()).into();
}
let opened = Menu::new(&choices, None, chosen_disk(volume));
let opened = Menu::new(&choices, None, chosen_disk(volume), pending);
if opened.glance
&& !asked()
&& let Some(Item::Choice(n, _)) = opened.items.first()
@@ -551,9 +567,9 @@ pub fn choose(volume: &mut FileSystem, options: Vec<u8>, held: Option<&str>) ->
/// setup entry starts highlighted; any entry may be chosen, and one that
/// cannot boot either returns here. Returns what the chosen entry boots;
/// `None` when the volume has no choices or no console input to choose with.
pub fn hold(volume: &mut FileSystem, reason: &str) -> Option<Chosen> {
pub fn hold(volume: &mut FileSystem, reason: &str, pending: &Pending) -> Option<Chosen> {
let choices = read(volume)?;
output::arguments(format_args!("HOLD {reason}\n"));
let held = Menu::new(&choices, Some(reason), chosen_disk(volume));
let held = Menu::new(&choices, Some(reason), chosen_disk(volume), pending);
menu(volume, &choices, held)
}
+19 -20
View File
@@ -2626,31 +2626,30 @@ fn wifi_network(
})
}
/// The change Install macOS's disk picker planned for the `--storage`
/// partition's disk (`Handoff::disk_plan`), when the picker ran this boot.
/// The host disks' start applies it, once, before it looks the partition up
/// (`storage::prepare`).
fn disk_plan(handoff: &Handoff) -> Option<stela_runtime::pc::disk_plan::Plan> {
let bytes = handoff.disk_plan.bytes as usize;
/// The disk work the loader decided before the firmware exited
/// (`Handoff::disk_writes`): the change Install macOS's disk picker planned
/// for the `--storage` partition's disk, when the picker ran this boot, and
/// the updates of the boot's partitions. The host disks' start does it,
/// once (`storage::prepare`, `storage::update`).
fn disk_writes(handoff: &Handoff) -> stela_runtime::pc::disk_writes::Pending {
let bytes = handoff.disk_writes.bytes as usize;
if bytes == 0 {
return None;
return Default::default();
}
// SAFETY: the loader left the plan's bytes allocated, and nothing
// writes them.
// SAFETY: the loader left the pending work's bytes allocated, and
// nothing writes them.
let encoded = unsafe {
core::slice::from_raw_parts(
layout::physical(handoff.disk_plan.physical) as *const u8,
layout::physical(handoff.disk_writes.physical) as *const u8,
bytes,
)
};
Some(
stela_runtime::pc::disk_plan::Plan::decode(encoded).unwrap_or_else(|| {
output::fatal(
"the plan for the disk chosen for macOS did not reach Stela's drivers whole; \
nothing was written to the disk. Start again and choose Install macOS",
)
}),
)
stela_runtime::pc::disk_writes::Pending::decode(encoded).unwrap_or_else(|| {
output::fatal(
"what this start was to write to the PC's disks did not reach Stela's drivers \
whole; nothing was written. Start again",
)
})
}
/// The whole disk and USB start's bound, which only a stall outside every
@@ -2774,7 +2773,7 @@ fn start_devices(
let owned_preboot = options.preboot.clone();
let owned_usb = options.usb_storage.clone();
let owned_wifi = wifi_network(handoff, options);
let owned_plan = disk_plan(handoff);
let owned_writes = disk_writes(handoff);
let external = options.external_disks.then(|| {
stela_soc::machine::UsbCables::disk_ports(options.guest_network, options.input)
.saturating_sub(owned_usb.len())
@@ -2821,7 +2820,7 @@ fn start_devices(
.map(|native| native as &dyn stela_drivers::probe::NativeServices),
&storage::Selection {
targets: &targets,
plan: owned_plan.as_ref(),
pending: &owned_writes,
medium: medium_partition,
preboot: owned_preboot.as_ref(),
store: translation_store,
+73 -8
View File
@@ -41,6 +41,7 @@ use stela_drivers::{
use stela_runtime::pc::{
device_starts,
disk_plan::{LocateError, Plan},
disk_writes::{Pending, Purpose, Update},
failure_record,
gpt::{Guid, PartitionDevice},
machine_state,
@@ -1424,9 +1425,11 @@ impl HostDisks {
pub struct Selection<'a> {
/// The guest's disks, in order: one service each.
pub targets: &'a [&'a Target],
/// The change Install macOS's disk picker planned for one target's
/// disk, made before the targets are looked up ([`prepare`]).
pub plan: Option<&'a Plan>,
/// The disk work decided before the firmware exited: the change Install
/// macOS's disk picker planned for one target's disk, made before the
/// targets are looked up ([`prepare`]), and the updates of the targets'
/// partitions, made once they are found ([`update`]).
pub pending: &'a Pending,
/// The install medium, by its GUID.
pub medium: Option<Guid>,
/// The installed system `--preboot` names.
@@ -1461,7 +1464,7 @@ pub struct Selection<'a> {
/// Open the explicitly selected partitions in the loader's identity root
/// `root` ([`RestoreRoot`]), and bring up every host input device and
/// network adapter. No guessed disk/partition, and no writes at open but
/// the selection's disk plan ([`prepare`]). Ownership lasts
/// the selection's pending disk work ([`prepare`], [`update`]). Ownership lasts
/// with the returned services. Probe once for all consumers;
/// do not reset a controller or reuse its DMA pages for a second probe.
///
@@ -1481,7 +1484,7 @@ pub unsafe fn open(
) -> Result<Opened, Refused> {
let Selection {
targets,
plan,
pending,
medium,
preboot,
store,
@@ -1649,7 +1652,7 @@ pub unsafe fn open(
let mut pause = |us| clock.delay(us);
// The picker's plan first: the partition it makes is one the
// search below looks for.
let prepared = match plan {
let prepared = match &pending.plan {
Some(plan) => {
// Still the device start: its steps' lines are stored
// between two drivers' calls, as each device's are.
@@ -1669,14 +1672,24 @@ pub unsafe fn open(
None => Ok(()),
};
let waited = prepared.map(|()| {
storage::wait_for_named(
let waited = storage::wait_for_named(
&mut devices.disks,
&required,
storage::PATIENCE,
&mut now_us,
&mut look,
&mut pause,
)
);
// The updates next, before any partition is opened for the
// engine to read: their partitions are found by now, or are
// missing, as the open below reports.
if !pending.updates.is_empty() {
STARTING_GS.store(this_gs(), Ordering::Release);
update(&pending.updates, targets, &mut devices.disks);
observer.store();
STARTING_GS.store(0, Ordering::Release);
}
waited
});
for found in late {
devices.absorb_usb(None, found, firmware);
@@ -2115,6 +2128,58 @@ fn prepare(
}
}
/// Make the partition updates decided before the firmware exited
/// (`pc::disk_writes`), in their order, with each disk's driver: the NVRAM
/// bank without the one-shot variables this boot consumed, and the clearing
/// of a failure record the loader copied into the log. Called once a boot,
/// after the plan's change and the wait for the boot's partitions, before
/// any of them is opened; every wait in it is the driver's own bounded one
/// for a single command.
///
/// An update that cannot be made is reported once and the boot goes on, as
/// it does when the disk keeps none of the machine state's writes
/// (`nor`): the disk then holds what it held. For the NVRAM bank that is
/// the one-shot variables, which this boot has acted on and the next start
/// acts on again; for the failure record, the record, which the next start
/// copies into the log again. An update for a partition this boot does not
/// use is not made: only the boot's targets are written.
fn update(updates: &[Update], targets: &[&Target], disks: &mut [Box<dyn BlockDevice>]) {
for update in updates {
let Update {
target, purpose, ..
} = update;
let result = if targets.contains(&target) {
update.apply(disks).map_err(|error| format!("{error}"))
} else {
Err(String::from("this boot does not use the partition"))
};
let (serial, partition) = (target.serial.as_str(), target.partition);
match (purpose, result) {
(Purpose::NvramBank, Ok(())) => output::arguments(format_args!(
"NVRAM saved the bank without the consumed variables on {serial}:{partition}, \
{} sectors\n",
update.pieces.len()
)),
(Purpose::NvramBank, Err(why)) => {
output::arguments(format_args!(
"NVRAM bank not saved on {serial}:{partition}: {why}. The variables this \
boot consumed stay, and the next start acts on them again\n"
));
crate::status::info(
"NVRAM's startup request could not be cleared: the next start repeats it",
);
}
(Purpose::FailureRecord, Ok(())) => output::arguments(format_args!(
"PREVIOUS BOOT record cleared on {serial}:{partition}\n"
)),
(Purpose::FailureRecord, Err(why)) => output::arguments(format_args!(
"PREVIOUS BOOT record not cleared on {serial}:{partition}: {why}. The next \
start copies it again\n"
)),
}
}
}
/// What the required partition at `at` of `open`'s list is for.
fn role_of(at: usize, targets: usize, medium: bool, preboot: bool) -> &'static str {
let medium_at = targets;
+7 -5
View File
@@ -16,11 +16,13 @@ pub struct Handoff {
pub magic: u64,
/// `stela.cfg`.
pub options: Region,
/// The change Install macOS's disk picker planned for the `--storage`
/// partition's disk (`pc::disk_plan`, encoded), which the engine's
/// drivers make once, before that partition is looked up. Empty when
/// the picker did not run this boot. It lives only in this memory.
pub disk_plan: Region,
/// The disk work decided before the firmware exited (`pc::disk_writes`,
/// encoded), which the engine's drivers do once: the change Install
/// macOS's disk picker planned for the `--storage` partition's disk,
/// before that partition is looked up, and then the updates of the
/// boot's partitions, before anything reads them. Empty when nothing
/// is pending. It lives only in this memory.
pub disk_writes: Region,
/// Exclusive 256-bit pre-EBS seed, erased by the engine on consumption.
/// An empty region means no checked entropy source was available.
pub random_seed: Region,
+18 -6
View File
@@ -281,22 +281,34 @@ fn main() -> Status {
drop(firmware_root);
let options = firmware::options(&mut volume).unwrap_or_else(|e| output::fatal(e));
let options = choice::resolve(&mut volume, options);
// What this start changes on a PC disk is pending until Stela's own
// drivers run: before the firmware exits, a PC disk is only read.
let mut pending = stela_runtime::pc::disk_writes::Pending::default();
// A stop the USB's log could not keep last time reaches it now.
selection::carry_failure_record(&options);
pending
.updates
.extend(selection::carry_failure_record(&options));
status::done("");
let held = system::held_at_start(&options);
let choice::Chosen { options, plan } = choice::choose(&mut volume, options, held);
let held = system::held_at_start(&options, &pending);
let choice::Chosen { options, plan } = choice::choose(&mut volume, options, held, &pending);
pending.replace_plan(plan);
status::take_screen(console::Framebuffer::from_firmware());
if options.starts_with(b"--system") {
system::boot(options, plan, volume, log, host_firmware, snapshot);
system::boot(options, pending, volume, log, host_firmware, snapshot);
}
// Only the system engine starts Stela's disk drivers, which apply it.
if plan.is_some() {
// Only the system engine does the pending work on the boot's disks.
if pending.plan.is_some() {
output::fatal(
"the chosen startup option is not a system-mode boot, so the disk chosen for macOS \
cannot be prepared; nothing was written to it",
);
}
if !pending.updates.is_empty() {
output::arguments(format_args!(
"PREVIOUS BOOT record not cleared: the chosen startup option is not a system-mode \
boot\n"
));
}
drop(snapshot);
if options.starts_with(stela_boot_core::options::HOST_CHECK.as_bytes()) {
drop(volume);
+159 -134
View File
@@ -2,8 +2,9 @@
//! `stela.efi` reads the persistent NOR's current NVRAM bank (`--nor
//! SERIAL:GUID`) through the firmware's block I/O, chooses macOS or
//! recoveryOS as `stela_loader::boot_selection` does, removes the one-shot
//! variables that boot consumes (saving the next bank, as LLB saves NVRAM
//! before it boots) and hands the engine the options for that boot. A macOS
//! variables that boot consumes (the next bank is saved before the engine
//! reads the NOR, as LLB saves NVRAM before it boots) and hands the engine
//! the options for that boot. A macOS
//! boot whose Preboot disk holds no installed system boots System Recovery
//! instead (missing boot media), as a Mac with an erased disk does. A
//! recoveryOS boot takes the disk's own copy, the paired recoveryOS of the
@@ -22,12 +23,16 @@
//! (`pc::machine_state`), and the Preboot disk is the rest, as the engine
//! splits it.
//!
//! A partition Install macOS's disk picker has just planned
//! (`pc::disk_plan`) is not on its disk yet, or not blank yet: Stela's
//! drivers make it after the firmware has exited. Every search here takes
//! the pending plan ([`Pending`]) and finds that partition as the plan
//! leaves it: where the plan puts it, the blocks the plan zeroes reading as
//! zero, and no write taken.
//! Nothing here writes a disk: the firmware's block I/O only reads. What a
//! boot changes on a PC disk before the firmware exits is pending work
//! (`pc::disk_writes`), which Stela's drivers do after it: the partition
//! Install macOS's disk picker has just planned, which is not on its disk
//! yet, or not blank yet; the NVRAM bank saved without the consumed
//! variables; a failure record cleared. Every search here takes the pending
//! work and reads a partition as that work leaves it: where the plan puts
//! it, the blocks the plan zeroes reading as zero, and the bytes of the
//! pending updates in place. So a boot routed again after a refusal finds
//! the variables it consumed gone, as it would on the disk.
use crate::Result;
use crate::{
output,
@@ -54,14 +59,17 @@ use {
stela_formats::payload::ReadAt, stela_formats::payload::gpt, stela_formats::payload::gpt::Disk,
stela_formats::payload::gpt::Role, stela_formats::preboot,
stela_formats::preboot::PrebootError, stela_runtime::pc::disk_plan::Plan,
stela_runtime::pc::disk_writes::Pending, stela_runtime::pc::disk_writes::Piece,
stela_runtime::pc::disk_writes::Purpose, stela_runtime::pc::disk_writes::Update,
stela_runtime::pc::failure_record, stela_runtime::pc::machine_state,
stela_runtime::pc::storage::Target, stela_soc_data::nor::CAPACITY, stela_soc_data::nor::Image,
stela_soc_data::nor::SECTOR_SIZE, stela_soc_data::nor::nvram::Variables,
stela_soc_data::nor::nvram::empty_bank,
};
/// One GPT partition, through its whole disk's block I/O.
struct Partition {
/// One GPT partition, or a part of it, read through its whole disk's block
/// I/O.
struct Partition<'a> {
io: ScopedProtocol<BlockIO>,
media: u32,
block_bytes: u64,
@@ -70,11 +78,18 @@ struct Partition {
/// The disk's blocks a pending plan zeroes, which read as zero already;
/// empty for a partition found on its disk.
zeroed: Vec<Extent>,
/// The partition this is, or is a part of, and the pending work whose
/// updates of it read as applied; `None` for a whole disk.
named: Option<Named<'a>>,
}
/// The change Install macOS's disk picker planned for this boot, which is
/// not on the disk yet.
pub type Pending<'a> = Option<&'a Plan>;
/// A partition `stela.cfg` names, as a search found it.
struct Named<'a> {
target: Target,
/// The whole partition's first block on its disk.
first_lba: u64,
pending: &'a Pending,
}
/// Which part of a partition that also holds the machine state in its tail.
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -86,7 +101,7 @@ enum Part {
State,
}
impl Partition {
impl Partition<'_> {
/// Confine the partition to `part`, as the engine splits it.
fn confine(&mut self, part: Part) -> Result<()> {
if part == Part::Whole {
@@ -124,34 +139,26 @@ impl Partition {
buffer[bytes(from)..to].fill(0);
}
}
if let Some(named) = &self.named {
let offset = (first - named.first_lba) * self.block_bytes;
named.pending.lay(&named.target, offset, buffer);
}
Ok(())
}
/// Whether the partition is on its disk, not only in a pending plan.
fn on_disk(&self) -> bool {
self.zeroed.is_empty()
}
fn write_sector(&mut self, offset: usize, sector: &[u8]) -> Result<()> {
if !self.on_disk() {
return Err(refuse!(
"the partition is not made yet: nothing is written to it before Stela's drivers \
make it"
));
}
let mut buffer = Aligned::new(SECTOR_SIZE);
buffer.bytes().copy_from_slice(sector);
let lba = self.first_lba + offset as u64 / self.block_bytes;
self.io
.write_blocks(self.media, lba, buffer.bytes())
.map_err(|_| refuse!("cannot write the NOR partition"))
/// Where this part starts, in bytes from the start of the partition
/// `stela.cfg` names.
fn offset(&self) -> u64 {
self.named.as_ref().map_or(0, |named| {
(self.first_lba - named.first_lba) * self.block_bytes
})
}
}
/// The largest firmware read, so a large APFS read needs no huge buffer.
const TRANSFER_BYTES: u64 = 1 << 20;
impl ReadAt for Partition {
impl ReadAt for Partition<'_> {
type Error = stela_contracts::Refusal;
fn len(&self) -> u64 {
@@ -180,11 +187,11 @@ impl ReadAt for Partition {
}
}
/// Open `handle`'s block I/O for reading and, on the NOR partition only,
/// writing. Not exclusive: the disk's other partitions, such as the ESP
/// this image was loaded from, stay connected.
/// Open `handle`'s block I/O for reading. Not exclusive: the disk's other
/// partitions, such as the ESP this image was loaded from, stay connected.
fn block_io(handle: Handle) -> Option<ScopedProtocol<BlockIO>> {
// SAFETY: Stela reads the named partitions and writes only the NOR's.
// SAFETY: Stela only reads through the protocol, and no driver's use of
// the disk is disturbed by a read.
unsafe {
boot::open_protocol::<BlockIO>(
OpenProtocolParams {
@@ -247,7 +254,7 @@ pub(crate) fn disk_controllers(serials: &[&str]) -> Vec<stela_drivers::bus::pci:
}
/// The whole disk behind `io` and its GPT.
fn table(io: ScopedProtocol<BlockIO>) -> Result<(Partition, gpt::Table)> {
fn table<'a>(io: ScopedProtocol<BlockIO>) -> Result<(Partition<'a>, gpt::Table)> {
let media = io.media();
let disk = Disk {
block_bytes: media.block_size() as u64,
@@ -261,10 +268,10 @@ fn table(io: ScopedProtocol<BlockIO>) -> Result<(Partition, gpt::Table)> {
first_lba: 0,
bytes: disk.blocks * disk.block_bytes,
zeroed: Vec::new(),
named: None,
};
// The backup table stands in for a primary an interrupted write left
// damaged (`gpt::read`); selecting a boot only reads, so the repair is
// left to the next staging run.
// damaged (`gpt::read`); selecting a boot only reads.
let found = gpt::read(disk, |lba, blocks| {
let mut bytes = vec![0u8; (blocks * disk.block_bytes) as usize];
whole
@@ -282,7 +289,7 @@ fn table(io: ScopedProtocol<BlockIO>) -> Result<(Partition, gpt::Table)> {
/// The partition the pending `plan` makes, on the disk behind `io`: where
/// the plan puts it, with the blocks the plan zeroes reading as zero. The
/// disk must be as the picker saw it.
fn planned(io: ScopedProtocol<BlockIO>, plan: &Plan) -> Result<Partition> {
fn planned<'a>(io: ScopedProtocol<BlockIO>, plan: &Plan) -> Result<Partition<'a>> {
let media = io.media();
let disk = Disk {
block_bytes: media.block_size() as u64,
@@ -301,17 +308,27 @@ fn planned(io: ScopedProtocol<BlockIO>, plan: &Plan) -> Result<Partition> {
first_lba: plan.partition.first_lba,
bytes: plan.partition.blocks * disk.block_bytes,
zeroed: plan.zero.clone(),
named: None,
})
}
/// The partition `target` names, as the engine finds it, or what was found
/// instead (`chosen_disk::Search`); the partition a `pending` plan is for,
/// as the engine finds it once the plan is applied ([`planned`]). Fails
/// only when the disks cannot be listed or the plan's disk has changed.
fn search(
/// instead (`chosen_disk::Search`); the partition the `pending` plan is
/// for, as the engine finds it once the plan is applied ([`planned`]).
/// Either reads with its pending updates applied. Fails only when the disks
/// cannot be listed or the plan's disk has changed.
fn search<'a>(
target: &Target,
pending: Pending<'_>,
) -> Result<core::result::Result<Partition, Search>> {
pending: &'a Pending,
) -> Result<core::result::Result<Partition<'a>, Search>> {
let named = |mut partition: Partition<'a>| {
partition.named = Some(Named {
target: target.clone(),
first_lba: partition.first_lba,
pending,
});
partition
};
let mut disks: Vec<_> = whole_disks()?
.into_iter()
.filter(|(serial, _)| serial.as_deref() == Some(target.serial.as_str()))
@@ -321,8 +338,8 @@ fn search(
1 => disks.remove(0).1,
_ => return Ok(Err(Search::SeveralDisks)),
};
if let Some(plan) = pending.filter(|plan| plan.is_for(target)) {
return planned(io, plan).map(Ok);
if let Some(plan) = pending.plan.as_ref().filter(|plan| plan.is_for(target)) {
return planned(io, plan).map(named).map(Ok);
}
// A table that cannot be read is a blank or wiped disk to a boot.
let Ok((mut whole, table)) = table(io) else {
@@ -343,10 +360,10 @@ fn search(
}
whole.first_lba = partition.first_lba;
whole.bytes = partition.blocks() * whole.block_bytes;
Ok(Ok(whole))
Ok(Ok(named(whole)))
}
fn find(target: &Target, pending: Pending<'_>) -> Result<Partition> {
fn find<'a>(target: &Target, pending: &'a Pending) -> Result<Partition<'a>> {
search(target, pending)?.map_err(|found| match found {
Search::NoDisk | Search::SeveralDisks => refuse!("not exactly one disk has the serial"),
Search::NoTable => refuse!("the disk has no valid GPT"),
@@ -358,39 +375,31 @@ fn find(target: &Target, pending: Pending<'_>) -> Result<Partition> {
})
}
/// Copy into the log, once, the record a previous start left in the machine
/// state of the partition `options` name for it (`--storage` and `--nor`
/// alike) when the USB's own log was out of reach of Stela's drivers
/// (`failure_record`), then clear it.
pub fn carry_failure_record(options: &[u8]) {
let Ok(text) = core::str::from_utf8(options) else {
return;
};
/// The bytes zeroed to clear a failure record: its header, in whole blocks
/// of any disk (`failure_record::OFFSET`).
const RECORD_CLEAR_BYTES: usize = 4096;
/// Copy into the log the record a previous start left in the machine state
/// of the partition `options` name for it (`--storage` and `--nor` alike)
/// when the USB's own log was out of reach of Stela's drivers
/// (`failure_record`). Returns the update that clears it, which Stela's
/// drivers make when this boot starts them on that partition; a boot that
/// does not leaves the record, and the next start copies it again.
pub fn carry_failure_record(options: &[u8]) -> Option<Update> {
let text = core::str::from_utf8(options).ok()?;
let storage = option(text, "--storage");
let Some(target) = storage
let target = storage
.filter(|_| option(text, "--nor") == storage)
.and_then(|name| name.parse::<Target>().ok())
else {
return;
};
// Before the startup menu: no plan is pending, and the partition is
// written only as it is on the disk.
let Ok(Ok(mut partition)) = search(&target, None) else {
return;
};
if partition.confine(Part::State).is_err() {
return;
}
.and_then(|name| name.parse::<Target>().ok())?;
// Before the startup menu: nothing is pending yet.
let pending = Pending::default();
let mut partition = search(&target, &pending).ok()?.ok()?;
partition.confine(Part::State).ok()?;
let mut region = vec![0u8; failure_record::BYTES as usize];
if partition
partition
.read_at(failure_record::OFFSET, &mut region)
.is_err()
{
return;
}
let Some(record) = failure_record::decode(&region) else {
return;
};
.ok()?;
let record = failure_record::decode(&region)?;
output::arguments(format_args!(
"PREVIOUS BOOT failed where the USB's log was out of reach; the chosen disk kept:\n"
));
@@ -398,35 +407,28 @@ pub fn carry_failure_record(options: &[u8]) {
output::arguments(format_args!("PREVIOUS BOOT {line}\n"));
}
// A zero header clears the record.
let block = partition.block_bytes;
let mut zeros = Aligned::new(block as usize);
let cleared = partition
.io
.write_blocks(
partition.media,
partition.first_lba + failure_record::OFFSET / block,
zeros.bytes(),
)
.and_then(|()| partition.io.flush_blocks());
if cleared.is_err() {
output::arguments(format_args!(
"PREVIOUS BOOT record not cleared: the chosen disk refused the write\n"
));
}
Some(Update {
target,
purpose: Purpose::FailureRecord,
pieces: vec![Piece {
offset: partition.offset() + failure_record::OFFSET,
bytes: vec![0; RECORD_CLEAR_BYTES],
}],
})
}
/// Whether the partition Install macOS chose before (`SERIAL:GUID`) is on
/// this PC: exactly one disk with its serial, and exactly one partition
/// with its GUID that is no EFI system partition. The menu asks before any
/// plan is made.
/// with its GUID that is no EFI system partition. The menu asks about the
/// disk as it is, whatever is pending.
pub fn chosen_present(disk: &str) -> bool {
disk.parse::<Target>()
.is_ok_and(|target| matches!(search(&target, None), Ok(Ok(_))))
.is_ok_and(|target| matches!(search(&target, &Pending::default()), Ok(Ok(_))))
}
/// Why the partition `target` names is no longer there to boot, when it is
/// not (`chosen_disk::Stale::of`).
fn stale(target: &Target, pending: Pending<'_>) -> Result<Option<Stale>> {
fn stale(target: &Target, pending: &Pending) -> Result<Option<Stale>> {
Ok(search(target, pending)?.err().and_then(Stale::of))
}
@@ -469,11 +471,11 @@ fn external(volume: &BootVolume) -> Result<Option<Target>> {
fn select_or_unprepared(
target: &Target,
part: Part,
consume: bool,
save: Option<&mut Option<Update>>,
(preboot, preboot_part): &(Target, Part),
pending: Pending<'_>,
pending: &Pending,
) -> Result<Selection, Refusal> {
let error = match select(target, part, consume, pending) {
let error = match select(target, part, save, pending) {
Ok(selection) => return Ok(selection),
Err(error) => error,
};
@@ -484,9 +486,15 @@ fn select_or_unprepared(
}
}
/// The boot NVRAM chooses, with its one-shot variables consumed and saved
/// when `consume` holds.
fn select(target: &Target, part: Part, consume: bool, pending: Pending<'_>) -> Result<Selection> {
/// The boot NVRAM chooses. With `save`, its one-shot variables are consumed
/// and the bank without them is left there: the update of the NOR's next
/// bank, which Stela's drivers write before the engine reads the NOR.
fn select(
target: &Target,
part: Part,
save: Option<&mut Option<Update>>,
pending: &Pending,
) -> Result<Selection> {
let mut nor = find(target, pending).within(|| refuse!("NOR partition"))?;
nor.confine(part).within(|| refuse!("NOR partition"))?;
if nor.io.media().is_read_only()
@@ -507,18 +515,26 @@ fn select(target: &Target, part: Part, consume: bool, pending: Pending<'_>) -> R
let (_, proxy) = image.boot_bank()?;
let mut variables = Variables::parse(&proxy)?;
let selection = select(&variables)?;
if consume && boot_selection::consume(&mut variables, &selection)? {
if let Some(save) = save
&& boot_selection::consume(&mut variables, &selection)?
{
let bank = variables.encode()?;
let (written, sectors) = image.save_bank(&bank)?;
for offset in sectors {
let sector = image.bytes()[offset..offset + SECTOR_SIZE].to_vec();
nor.write_sector(offset, &sector)?;
}
nor.io
.flush_blocks()
.map_err(|_| refuse!("cannot flush the NOR partition"))?;
let base = nor.offset();
*save = Some(Update {
target: target.clone(),
purpose: Purpose::NvramBank,
pieces: sectors
.into_iter()
.map(|offset| Piece {
offset: base + offset as u64,
bytes: image.bytes()[offset..offset + SECTOR_SIZE].to_vec(),
})
.collect(),
});
output::arguments(format_args!(
"NVRAM consumed {} into bank {written}\n",
"NVRAM consumed {} for bank {written}, which Stela's drivers save after the \
firmware has exited\n",
selection
.consumed
.iter()
@@ -538,7 +554,7 @@ fn installed(
target: &Target,
part: Part,
volume: Option<&BootVolume>,
pending: Pending<'_>,
pending: &Pending,
) -> Result<bool> {
let mut disk = find(target, pending).within(|| refuse!("Preboot disk"))?;
disk.confine(part).within(|| refuse!("Preboot disk"))?;
@@ -574,7 +590,7 @@ fn holds_recovery(
part: Part,
kind: recovery::Kind,
volume: Option<&BootVolume>,
pending: Pending<'_>,
pending: &Pending,
) -> bool {
let probe = || -> Result<bool> {
let mut disk = find(target, pending).within(|| refuse!("Preboot disk"))?;
@@ -597,7 +613,7 @@ fn holds_recovery(
/// Whether the internal SSD lacks the iBootSystemContainer every boot of a
/// Mac reads (`apfs::require_system_container`), as a blank one does.
fn blank(target: &Target, part: Part, pending: Pending<'_>) -> Result<bool> {
fn blank(target: &Target, part: Part, pending: &Pending) -> Result<bool> {
let mut disk = find(target, pending).within(|| refuse!("internal SSD"))?;
disk.confine(part).within(|| refuse!("internal SSD"))?;
match apfs::require_system_container(&mut disk) {
@@ -646,11 +662,12 @@ pub enum Readiness {
Unknown,
}
/// Whether the startup choice `options` of `kind` can start now. Install
/// and other choices are not checked ([`Readiness::Unknown`]).
pub fn ready(options: &str, kind: ChoiceKind) -> Readiness {
/// Whether the startup choice `options` of `kind` can start now, with the
/// `pending` work done. Install and other choices are not checked
/// ([`Readiness::Unknown`]).
pub fn ready(options: &str, kind: ChoiceKind, pending: &Pending) -> Readiness {
match kind {
ChoiceKind::Mac => match route_checked(options.as_bytes().into(), false, None) {
ChoiceKind::Mac => match route_checked(options.as_bytes().into(), None, pending) {
Ok((_, true)) => Readiness::Ready,
Ok((_, false)) | Err(Refusal::NoRecovery { installed: false }) => {
Readiness::NotInstalled
@@ -689,26 +706,34 @@ pub enum Refusal {
}
/// The engine's options for this boot (`boot_selection::route`), with
/// NVRAM's one-shot choices consumed. `pending` is the plan the disk picker
/// made for these options, when it made one.
pub fn route(options: Vec<u8>, pending: Pending<'_>) -> Result<Vec<u8>, Refusal> {
route_checked(options, true, pending).map(|(routed, _)| routed)
/// NVRAM's one-shot choices consumed. `pending` is the disk work decided so
/// far, the disk picker's plan for these options with it; the save of the
/// bank without the consumed variables joins it, whether or not the boot is
/// then refused: the variables are consumed once they have been acted on.
pub fn route(options: Vec<u8>, pending: &mut Pending) -> Result<Vec<u8>, Refusal> {
let mut save = None;
let routed = route_checked(options, Some(&mut save), pending);
pending.updates.extend(save);
routed.map(|(routed, _)| routed)
}
/// Where [`route`] would send `options`, leaving NVRAM unchanged: the
/// check before the startup menu, which a chosen boot routes again. No plan
/// is pending before the menu.
pub fn peek(options: Vec<u8>) -> Result<Vec<u8>, Refusal> {
route_checked(options, false, None).map(|(routed, _)| routed)
/// check before the startup menu, which a chosen boot routes again.
pub fn peek(options: Vec<u8>, pending: &Pending) -> Result<Vec<u8>, Refusal> {
route_checked(options, None, pending).map(|(routed, _)| routed)
}
/// [`route`] or [`peek`], and whether the boot disk holds an installed
/// system: false when a Mac boot falls back to recoveryOS for want of one.
/// [`route`] with a place for the NVRAM `save`, or [`peek`] without one,
/// and whether the boot disk holds an installed system: false when a Mac
/// boot falls back to recoveryOS for want of one. Nothing reads the NOR
/// after its choice is made, so the save need not be pending yet for the
/// rest of the routing.
fn route_checked(
options: Vec<u8>,
consume: bool,
pending: Pending<'_>,
save: Option<&mut Option<Update>>,
pending: &Pending,
) -> Result<(Vec<u8>, bool), Refusal> {
let consume = save.is_some();
let mut installed_system = true;
let text =
core::str::from_utf8(&options).map_err(|_| Refusal::Other("stela.cfg is not UTF-8"))?;
@@ -749,7 +774,7 @@ fn route_checked(
Part::Whole
};
let preboot = (parse(preboot)?, preboot_part);
select_or_unprepared(&parse(nor)?, part, consume, &preboot, pending)?
select_or_unprepared(&parse(nor)?, part, save, &preboot, pending)?
}
None => boot_selection::select(&Variables::parse(&empty_bank()).map_err(refuse)?)
.map_err(|error| refuse(error.into()))?,
+29 -19
View File
@@ -24,7 +24,7 @@ use stela_boot_core::options::{DEFAULT_WIFI_KEY, System};
use stela_contracts::refuse;
use stela_engine::machine::mmu::placement::Placement;
use stela_runtime::pc;
use stela_runtime::pc::disk_plan::Plan;
use stela_runtime::pc::disk_writes::Pending;
use stela_runtime::pc::gpt::Guid;
use uefi::{
boot::{self, AllocateType, MemoryType},
@@ -560,8 +560,9 @@ fn log_stale(stale: stela_boot_core::chosen_disk::Stale) {
}
/// Why the default boot, `options`, can only wait for a restore, checked
/// before the startup menu opens so that the menu starts there.
pub fn held_at_start(options: &[u8]) -> Option<&'static str> {
/// before the startup menu opens so that the menu starts there. `pending`
/// is the disk work decided so far.
pub fn held_at_start(options: &[u8], pending: &Pending) -> Option<&'static str> {
if !options.starts_with(b"--system") {
return None;
}
@@ -569,7 +570,7 @@ pub fn held_at_start(options: &[u8]) -> Option<&'static str> {
return Some("No disk is chosen for macOS yet: choose Install macOS first.");
}
crate::status::begin("Checking the internal SSD and NVRAM");
let (held, found) = match crate::selection::peek(options.to_vec()) {
let (held, found) = match crate::selection::peek(options.to_vec(), pending) {
Err(refusal @ Refusal::BlankDisk) => (Some(held(refusal)), "no macOS installed yet"),
Err(refusal @ Refusal::RecoveryMode) => (Some(held(refusal)), "an install did not finish"),
Err(refusal @ Refusal::NoRecovery { .. }) => (Some(held(refusal)), "no recoveryOS to boot"),
@@ -584,13 +585,14 @@ pub fn held_at_start(options: &[u8]) -> Option<&'static str> {
}
/// Run the engine; never returns.
/// `plan` is the change the disk picker planned for the disk `options`
/// name, which the engine's drivers make (`pc::disk_plan`). `log` is the
/// partition holding the USB's boot log, when the loader keeps one there
/// `pending` is the disk work decided so far, which the engine's drivers
/// do (`pc::disk_writes`): the change the disk picker planned for the disk
/// `options` name, and the partition updates. `log` is the partition
/// holding the USB's boot log, when the loader keeps one there
/// (`log_file`).
pub(crate) fn boot(
mut options: Vec<u8>,
mut plan: Option<Plan>,
mut pending: Pending,
mut volume: FileSystem,
log: Option<Guid>,
host_firmware: crate::host_firmware::Resources,
@@ -601,7 +603,7 @@ pub(crate) fn boot(
// waits for a restore host, until one that boots is chosen.
let options = loop {
crate::status::begin("Reading the startup request in NVRAM");
let routed = crate::selection::route(options, plan.as_ref());
let routed = crate::selection::route(options, &mut pending);
crate::status::done("");
match routed {
Ok(routed) => break routed,
@@ -611,14 +613,18 @@ pub(crate) fn boot(
log_stale(*stale);
}
// The new choice replaces the options and their plan: a
// plan dropped here wrote nothing.
crate::choice::Chosen { options, plan } =
crate::choice::hold(&mut volume, held(refusal)).unwrap_or_else(|| {
// plan dropped here wrote nothing. The NVRAM consumed for
// the refused boot stays consumed, unless the new plan
// makes its partition afresh.
let chosen = crate::choice::hold(&mut volume, held(refusal), &pending)
.unwrap_or_else(|| {
output::fatal(
"the machine can only be restored and this volume has no startup \
choices to restore it from",
)
});
options = chosen.options;
pending.replace_plan(chosen.plan);
if !options.starts_with(b"--system") {
output::fatal("the chosen startup option is not a system-mode boot");
}
@@ -632,7 +638,7 @@ pub(crate) fn boot(
let result = inputs.and_then(|inputs| {
load(
options,
plan,
pending,
inputs,
log,
host_firmware,
@@ -706,7 +712,7 @@ fn translation_store(
fn load(
options: Vec<u8>,
plan: Option<Plan>,
pending: Pending,
inputs: Inputs,
log: Option<Guid>,
host_firmware: crate::host_firmware::Resources,
@@ -723,7 +729,7 @@ fn load(
let system = System::parse(text).map_err(stela_boot_core::options::Error::message)?;
// The engine's drivers apply the plan to the `--storage` partition's
// disk and no other.
if let Some(plan) = &plan
if let Some(plan) = &pending.plan
&& !system
.storage
.as_ref()
@@ -734,7 +740,11 @@ fn load(
nothing was written to it"
));
}
let disk_plan = plan.map(|plan| plan.encode()).unwrap_or_default();
let disk_writes = if pending.is_empty() {
Vec::new()
} else {
pending.encode()
};
let (native_processors, available_cores) = crate::native_smp::firmware::capture_inventory()
.map_err(crate::native_smp::firmware::Error::message)?;
let cores = system.assigned_native_cores(available_cores, bundle_pes)?;
@@ -813,8 +823,8 @@ fn load(
source: source_region,
files,
file_count,
disk_plan,
} = handoff_phase::retain_files(options, source, bundle, disk_plan)?;
disk_writes,
} = handoff_phase::retain_files(options, source, bundle, disk_writes)?;
let handoff = handoff_page.physical as *mut Handoff;
let engine_entry =
layout::image() + (crate::engine::entry as *const () as u64 - image.start as u64);
@@ -954,7 +964,7 @@ fn load(
handoff.write(Handoff {
magic: MAGIC,
options: options_region,
disk_plan,
disk_writes,
random_seed,
source: source_region,
files,
@@ -5,8 +5,8 @@ use stela_contracts::refuse;
pub(super) struct RetainedFiles {
pub options: Region,
/// The encoded disk plan; empty without one.
pub disk_plan: Region,
/// The encoded pending disk work; empty without any.
pub disk_writes: Region,
pub source: Region,
pub files: [File; MAX_FILES],
pub file_count: usize,
@@ -17,7 +17,7 @@ pub(super) fn retain_files(
options: Vec<u8>,
source: Vec<u8>,
bundle: BundleFiles,
disk_plan: Vec<u8>,
disk_writes: Vec<u8>,
) -> Result<RetainedFiles> {
let options_region = Region {
physical: options.as_ptr() as u64,
@@ -27,9 +27,9 @@ pub(super) fn retain_files(
physical: source.as_ptr() as u64,
bytes: source.len() as u64,
};
let disk_plan_region = Region {
physical: disk_plan.as_ptr() as u64,
bytes: disk_plan.len() as u64,
let disk_writes_region = Region {
physical: disk_writes.as_ptr() as u64,
bytes: disk_writes.len() as u64,
};
let mut files = [File::default(); MAX_FILES];
for (slot, (name, contents)) in files.iter_mut().zip(&bundle) {
@@ -45,10 +45,10 @@ pub(super) fn retain_files(
core::mem::forget(options);
core::mem::forget(source);
core::mem::forget(bundle);
core::mem::forget(disk_plan);
core::mem::forget(disk_writes);
Ok(RetainedFiles {
options: options_region,
disk_plan: disk_plan_region,
disk_writes: disk_writes_region,
source: source_region,
files,
file_count,
@@ -5,7 +5,9 @@
//! partition is often found then, as it is on another bus, so the engine
//! writes the step, its message and the disk account here, and the next
//! boot's firmware-side code, which reads the stick through the firmware,
//! copies it into the USB's log and clears it.
//! copies it into the USB's log. That code only reads the partition:
//! Stela's drivers clear the record once that boot has started them
//! (`disk_writes`), and until one does, each start copies it again.
//!
//! The region starts at [`OFFSET`] of the machine state, after the RTC
//! anchor, and is [`BYTES`] long. The installer zeroes the whole tail, so a