From 08100f18ba700ba7f2b3648ac1f55bc536695d15 Mon Sep 17 00:00:00 2001 From: Otavio Salvador Date: Thu, 19 Nov 2026 17:37:31 -0300 Subject: [PATCH 1/5] refactor(firmware): run every reboot through one function The Reboot state and the rollback on a failed validation each ran the `reboot` command themselves. With a single `firmware::reboot` there is one place that decides how the device reboots, which the next commit needs to keep test builds from ever rebooting the machine running them. --- updatehub/src/firmware/mod.rs | 4 ++++ updatehub/src/states/mod.rs | 2 +- updatehub/src/states/reboot.rs | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/updatehub/src/firmware/mod.rs b/updatehub/src/firmware/mod.rs index 86e1d256..1a44fff4 100644 --- a/updatehub/src/firmware/mod.rs +++ b/updatehub/src/firmware/mod.rs @@ -133,6 +133,10 @@ pub(crate) fn state_change_callback(path: &Path, state: &str) -> Result Result { + Ok(easy_process::run("reboot")?) +} + pub(crate) fn validate_callback(path: &Path) -> Result { let callback = path.join(VALIDATE_CALLBACK); if !callback.exists() { diff --git a/updatehub/src/states/mod.rs b/updatehub/src/states/mod.rs index 80c06538..2bfa91fc 100644 --- a/updatehub/src/states/mod.rs +++ b/updatehub/src/states/mod.rs @@ -240,7 +240,7 @@ fn handle_startup_callbacks( #[cfg(feature = "v1-parsing")] runtime_settings.restore_v1_content()?; - easy_process::run("reboot")?; + firmware::reboot()?; // Ensure we detect the rollback in next boot. return Ok(()); diff --git a/updatehub/src/states/reboot.rs b/updatehub/src/states/reboot.rs index c35f3df1..5bb06c1b 100644 --- a/updatehub/src/states/reboot.rs +++ b/updatehub/src/states/reboot.rs @@ -37,7 +37,7 @@ impl StateChangeImpl for Reboot { async fn handle(self, _: &mut Context) -> Result<(State, machine::StepTransition)> { info!("triggering reboot"); - let output = easy_process::run("reboot").log_error_msg("failed to run reboot command")?; + let output = crate::firmware::reboot().log_error_msg("failed to run reboot command")?; if !output.stdout.is_empty() || !output.stderr.is_empty() { warn!(" reboot output: stdout: {}, stderr: {}", output.stdout, output.stderr); } From e272781b0a3fdbd4c53d07cbbcd474088b921429 Mon Sep 17 00:00:00 2001 From: Otavio Salvador Date: Thu, 19 Nov 2026 17:38:36 -0300 Subject: [PATCH 2/5] fix(firmware): never run the machine's reboot from a test build Tests run the real agent on the developer's machine with a fake `reboot` first in `PATH`. An agent that outlived its test, whose temporary directory and fake were gone, ran the system's `reboot` and rebooted the machine running the tests. Test builds (unit tests and the `test-env` feature) now only run an executable `reboot` found under the temporary directory, by its absolute path, and refuse anything else with an error. Release builds still run `reboot` as before. --- updatehub/src/firmware/mod.rs | 112 +++++++++++++++++++++++++++++++++- 1 file changed, 111 insertions(+), 1 deletion(-) diff --git a/updatehub/src/firmware/mod.rs b/updatehub/src/firmware/mod.rs index 1a44fff4..54c36620 100644 --- a/updatehub/src/firmware/mod.rs +++ b/updatehub/src/firmware/mod.rs @@ -40,6 +40,13 @@ pub enum Error { #[display("invalid installation set, the only know ones are 0 or 1")] InvalidInstallSet, + #[display( + "refusing to run {_0:?} from a test build: tests reboot through a fake `reboot` in the \ + temporary directory, so this one would reboot the machine running them" + )] + #[from(ignore)] + RealRebootInTestBuild(#[error(not(source))] Option), + Walkdir(walkdir::Error), Io(std::io::Error), @@ -134,7 +141,47 @@ pub(crate) fn state_change_callback(path: &Path, state: &str) -> Result Result { - Ok(easy_process::run("reboot")?) + #[cfg(any(test, feature = "test-env"))] + let reboot = &fake_reboot()?.display().to_string(); + #[cfg(not(any(test, feature = "test-env")))] + let reboot = "reboot"; + + Ok(easy_process::run(reboot)?) +} + +/// Test builds (unit tests and the `test-env` feature the integration tests +/// use) run the real agent on the developer's machine, with a fake `reboot` +/// first in `PATH`. If that fake is ever gone, e.g. an agent outliving the +/// test that created it, `PATH` would find the real one and reboot the +/// machine. So these builds only run a `reboot` living in the temporary +/// directory, where every test creates its fakes, and run it by its path so +/// no other lookup can pick another. +#[cfg(any(test, feature = "test-env"))] +fn fake_reboot() -> Result { + use std::os::unix::fs::PermissionsExt; + + let found = std::env::var_os("PATH") + .map(|path| std::env::split_paths(&path).map(|dir| dir.join("reboot")).collect::>()) + .unwrap_or_default() + .into_iter() + .find(|candidate| { + std::fs::metadata(candidate) + .is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) + }) + .map(|reboot| std::fs::canonicalize(&reboot).ok()); + let temp = std::fs::canonicalize(std::env::temp_dir()).ok(); + // The path is run as a command line, which must not split it + let plain = |p: &std::path::Path| { + !p.to_string_lossy().contains(|c: char| c.is_whitespace() || "'\"\\".contains(c)) + }; + + match (found.flatten(), temp) { + (Some(reboot), Some(temp)) if reboot.starts_with(&temp) && plain(&reboot) => Ok(reboot), + (other, _) => { + error!("refusing to run {:?}, which is not a fake reboot from a test", other); + Err(Error::RealRebootInTestBuild(other)) + } + } } pub(crate) fn validate_callback(path: &Path) -> Result { @@ -196,3 +243,66 @@ fn run_command_for_state(name: &str, cmd: &str) -> Result } } } + +#[cfg(test)] +mod reboot_guard { + use super::*; + use crate::utils::test_env::PathEnvGuard; + use std::{fs, os::unix::fs::PermissionsExt}; + + /// A `reboot` that only leaves a mark, so a broken guard fails the test + /// instead of rebooting anything + fn fake_reboot(dir: &Path) -> std::path::PathBuf { + let mark = dir.join("rebooted"); + let reboot = dir.join("reboot"); + fs::write(&reboot, format!("#!/bin/sh\n: > {}\n", mark.display())).unwrap(); + fs::set_permissions(&reboot, fs::Permissions::from_mode(0o755)).unwrap(); + mark + } + + #[test] + fn runs_a_fake_reboot_from_the_temporary_directory() { + let dir = tempfile::tempdir().unwrap(); + let mark = fake_reboot(dir.path()); + let _path = PathEnvGuard::set(dir.path()); + + reboot().unwrap(); + assert!(mark.exists()); + } + + #[test] + fn refuses_a_reboot_outside_the_temporary_directory() { + // Stands for the system's reboot, which also lives outside it + let outside = Path::new(env!("CARGO_MANIFEST_DIR")); + if outside.canonicalize().unwrap().starts_with(std::env::temp_dir().canonicalize().unwrap()) + { + eprintln!("skipped: the source tree is inside the temporary directory"); + return; + } + let dir = tempfile::tempdir_in(outside).unwrap(); + let mark = fake_reboot(dir.path()); + let _path = PathEnvGuard::set(dir.path()); + + assert!(matches!(reboot(), Err(Error::RealRebootInTestBuild(Some(_))))); + assert!(!mark.exists()); + } + + #[test] + fn ignores_a_reboot_that_is_not_executable() { + let dir = tempfile::tempdir().unwrap(); + let mark = fake_reboot(dir.path()); + fs::set_permissions(dir.path().join("reboot"), fs::Permissions::from_mode(0o644)).unwrap(); + let _path = PathEnvGuard::set(dir.path()); + + assert!(matches!(reboot(), Err(Error::RealRebootInTestBuild(None)))); + assert!(!mark.exists()); + } + + #[test] + fn refuses_when_there_is_no_fake_reboot() { + let dir = tempfile::tempdir().unwrap(); + let _path = PathEnvGuard::set(dir.path()); + + assert!(matches!(reboot(), Err(Error::RealRebootInTestBuild(None)))); + } +} From 2bed8f9bb63d25796d222b66e890089f9de205a9 Mon Sep 17 00:00:00 2001 From: Otavio Salvador Date: Thu, 19 Nov 2026 17:38:56 -0300 Subject: [PATCH 3/5] fix(runtime_settings): save the runtime settings atomically The runtime settings were rewritten in place and never synced. A power cut while saving could leave the file empty or torn, and the record of a pending update, which the next boot validates or rolls back, was lost with it: the agent starts over from the defaults and the update is never validated. Write a temporary file next to it, sync it, rename it over the old one and sync the directory. When the configured path is a symlink, e.g. to storage shared by both installation sets, the file it points to is replaced and the link kept, even before that file exists. --- updatehub/src/runtime_settings.rs | 47 +++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/updatehub/src/runtime_settings.rs b/updatehub/src/runtime_settings.rs index 2297f261..86481df6 100644 --- a/updatehub/src/runtime_settings.rs +++ b/updatehub/src/runtime_settings.rs @@ -135,7 +135,7 @@ impl RuntimeSettings { fs::create_dir_all(parent)?; } - fs::write(&self.path, self.serialize()?)?; + write_atomically(&self.path, self.serialize()?.as_bytes())?; debug!("saved runtime settings to {:?}", &self.path); Ok(()) @@ -243,13 +243,41 @@ impl RuntimeSettings { // procedure when rebooting. if let Some(content) = &self.v1_content { warn!("restoring previous content of runtime settings for v1 compatibility"); - fs::write(&self.path, content)?; + write_atomically(&self.path, content.as_bytes())?; } Ok(()) } } +/// Replaces `path` with `content` so a power cut leaves either the old or +/// the new content, never a torn or empty file. +fn write_atomically(path: &Path, content: &[u8]) -> Result<()> { + // A symlink stays one, the file it points to, which may not exist yet, + // is the one replaced + let mut path = path.to_owned(); + for hops in 0.. { + let Ok(target) = fs::read_link(&path) else { + break; + }; + if hops == 40 { + return Err(io::Error::from_raw_os_error(nix::libc::ELOOP).into()); + } + path = path.parent().unwrap_or(Path::new("")).join(target); + } + let path = &path; + let dir = match path.parent().ok_or(Error::InvalidDestination)? { + dir if dir.as_os_str().is_empty() => Path::new("."), + dir => dir, + }; + let mut temp = tempfile::NamedTempFile::new_in(dir)?; + std::io::Write::write_all(&mut temp, content)?; + temp.as_file().sync_all()?; + temp.persist(path).map_err(|e| e.error)?; + fs::File::open(dir)?.sync_all()?; + Ok(()) +} + #[cfg(feature = "v1-parsing")] fn v1_parse(content: &str, json_err: serde_json::Error) -> Result { use crate::utils::deserialize; @@ -309,6 +337,21 @@ mod tests { use super::*; use pretty_assertions::assert_eq; + #[test] + fn saving_through_a_symlink_keeps_it() { + let dir = tempfile::tempdir().unwrap(); + let shared = dir.path().join("shared"); + fs::create_dir(&shared).unwrap(); + let link = dir.path().join("runtime.json"); + std::os::unix::fs::symlink(shared.join("runtime.json"), &link).unwrap(); + + write_atomically(&link, b"first").unwrap(); + write_atomically(&link, b"second").unwrap(); + + assert!(fs::symlink_metadata(&link).unwrap().file_type().is_symlink()); + assert_eq!(fs::read_to_string(shared.join("runtime.json")).unwrap(), "second"); + } + #[test] fn default() { let settings = RuntimeSettings::default(); From ec5ff6f47559b3563b8e74174f02b750c6f06ae3 Mon Sep 17 00:00:00 2001 From: Otavio Salvador Date: Thu, 19 Nov 2026 17:39:14 -0300 Subject: [PATCH 4/5] feat(package-schema): add the boot-emmc target type A raw object can now name an eMMC by its base device (e.g. `/dev/mmcblk1`) with the `boot-emmc` target type, meaning the hardware boot partition of the installation set being installed rather than a fixed device. This is the type RAUC uses for the same purpose, and the one the JSON schema and uhu accept. Handlers other than raw cannot write a boot partition and reject it, and resolving it to a device without knowing the installation set fails. --- updatehub-package-schema/src/definitions/target_type.rs | 6 ++++++ updatehub/src/object/installer/flash.rs | 2 +- updatehub/src/object/installer/tarball.rs | 5 ++++- updatehub/src/utils/definitions.rs | 3 +++ updatehub/src/utils/mod.rs | 4 ++++ 5 files changed, 18 insertions(+), 2 deletions(-) diff --git a/updatehub-package-schema/src/definitions/target_type.rs b/updatehub-package-schema/src/definitions/target_type.rs index 041fb0c9..f22424ee 100644 --- a/updatehub-package-schema/src/definitions/target_type.rs +++ b/updatehub-package-schema/src/definitions/target_type.rs @@ -12,6 +12,12 @@ pub enum TargetType { Device(PathBuf), UBIVolume(String), MTDName(String), + /// The base device of an eMMC (e.g. `/dev/mmcblk1`) whose hardware boot + /// partitions hold one firmware per installation set: the agent writes + /// the boot partition of the set being installed (`boot0` for set 0, + /// `boot1` for set 1). Only valid for raw objects. + #[serde(rename = "boot-emmc")] + BootEmmc(PathBuf), } #[cfg(test)] diff --git a/updatehub/src/object/installer/flash.rs b/updatehub/src/object/installer/flash.rs index 8377abb2..dd8a8bba 100644 --- a/updatehub/src/object/installer/flash.rs +++ b/updatehub/src/object/installer/flash.rs @@ -30,7 +30,7 @@ impl Installer for objects::Flash { )?; Ok(()) } - definitions::TargetType::UBIVolume(_) => { + definitions::TargetType::UBIVolume(_) | definitions::TargetType::BootEmmc(_) => { Err(Error::InvalidTargetType(self.target.clone())) } } diff --git a/updatehub/src/object/installer/tarball.rs b/updatehub/src/object/installer/tarball.rs index 22b749c0..dcd01b81 100644 --- a/updatehub/src/object/installer/tarball.rs +++ b/updatehub/src/object/installer/tarball.rs @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: Apache-2.0 -use super::{Context, Result}; +use super::{Context, Error, Result}; use crate::{ object::{Info, Installer}, utils::{ @@ -32,6 +32,9 @@ impl Installer for objects::Tarball { .log_error_msg("device failed validation")?; Ok(()) } + definitions::TargetType::BootEmmc(_) => { + Err(Error::InvalidTargetType(self.target.clone())) + } } } diff --git a/updatehub/src/utils/definitions.rs b/updatehub/src/utils/definitions.rs index e1686518..c4905c29 100644 --- a/updatehub/src/utils/definitions.rs +++ b/updatehub/src/utils/definitions.rs @@ -84,6 +84,9 @@ impl TargetTypeExt for TargetType { } TargetType::UBIVolume(s) => mtd::target_device_from_ubi_volume_name(s), TargetType::MTDName(s) => mtd::target_device_from_mtd_name(s), + // Which boot partition depends on the installation set, which + // only the raw handler knows + TargetType::BootEmmc(device) => Err(Error::UnresolvedBootEmmc(device.clone())), } } } diff --git a/updatehub/src/utils/mod.rs b/updatehub/src/utils/mod.rs index 7a1146ce..710eff73 100644 --- a/updatehub/src/utils/mod.rs +++ b/updatehub/src/utils/mod.rs @@ -33,6 +33,10 @@ pub enum Error { #[from(ignore)] DeviceDoesNotExist(#[error(not(source))] std::path::PathBuf), + #[display("{_0:?} is a boot-emmc target, which only raw objects support")] + #[from(ignore)] + UnresolvedBootEmmc(#[error(not(source))] std::path::PathBuf), + #[display("user doesn't have write permission on target device: {_0:?}")] #[from(ignore)] MissingWritePermission(#[error(not(source))] std::path::PathBuf), From f8698d4f728cb71637f604213eb4e95fcaa73b0d Mon Sep 17 00:00:00 2001 From: Otavio Salvador Date: Thu, 19 Nov 2026 17:40:14 -0300 Subject: [PATCH 5/5] feat: keep A/B firmware in the eMMC boot partitions Boards such as the STM32MP135 boot TF-A and the FIP from an eMMC hardware boot partition, picked by PARTITION_CONFIG. Updating that firmware took scripts to unlock the partitions (force_ro), write the right one and switch PARTITION_CONFIG, all of it outside the agent's view of the update. With `[firmware.boot-emmc] device = "/dev/mmcblkN"`, installation set N boots from boot partition N, and the agent keeps the eMMC in step: - An update first copies the running firmware to the boot partition of the set it installs, then writes its `boot-emmc` raw objects over it, so a package without firmware, or with part of it, still yields complete firmware. Only that partition is unlocked, and it is synced before the update is activated. - When the set is swapped, PARTITION_CONFIG follows it through the MMC_IOC_CMD ioctl, keeping the boot acknowledge, and is read back. If it cannot, the set is swapped back. - A device booting from the partition an update is about to write, e.g. one provisioned before this, is repaired first with a warning: its firmware is copied to the other boot partition, which it then boots. - A pending update records that it wrote the eMMC, and in which boot. On start, the eMMC follows the set again, which covers a bootloader rolling the update back and a power cut between the set and the eMMC switching. In that case the agent reboots once, so the update is validated running its own firmware, and rolls it back if the eMMC still does not follow. An agent restarting before the device rebooted does not validate it. - Kernels that keep a cached PARTITION_CONFIG write it back on the next boot partition access. Each partition is read uncached before it is written and checked again afterwards; if the eMMC moved, the update fails and the eMMC goes back to the running firmware. boot-emmc needs persistent runtime settings, since they are what brings the eMMC back after a rollback, and it refuses updates while one waits for a reboot. The integration test runs the agent binary against a simulated eMMC (test builds only) and plays the ROM, U-Boot, power cuts and the server through an update history: updates, failed validation, bootloader rollback, power cuts while writing and between the switches, packages for another eMMC or without firmware, the repair, and a kernel with a stale PARTITION_CONFIG. --- .../src/api/info/runtime_settings.rs | 17 + updatehub-sdk/src/api/info/settings.rs | 12 + updatehub/Cargo.toml | 6 + updatehub/src/firmware/boot_emmc.rs | 164 ++++ updatehub/src/firmware/installation_set.rs | 11 + updatehub/src/firmware/mod.rs | 50 ++ updatehub/src/object/installer/mod.rs | 8 + updatehub/src/object/installer/raw.rs | 100 ++- updatehub/src/object/mod.rs | 13 + updatehub/src/runtime_settings.rs | 39 +- updatehub/src/settings.rs | 10 +- updatehub/src/states/install.rs | 62 +- updatehub/src/states/mod.rs | 56 +- updatehub/src/states/tests.rs | 6 +- updatehub/src/states/validation.rs | 15 +- updatehub/src/tests.rs | 2 +- updatehub/src/utils/emmc.rs | 463 ++++++++++++ updatehub/src/utils/mod.rs | 29 + updatehub/tests/boot_emmc.rs | 715 ++++++++++++++++++ 19 files changed, 1745 insertions(+), 33 deletions(-) create mode 100644 updatehub/src/firmware/boot_emmc.rs create mode 100644 updatehub/src/utils/emmc.rs create mode 100644 updatehub/tests/boot_emmc.rs diff --git a/updatehub-sdk/src/api/info/runtime_settings.rs b/updatehub-sdk/src/api/info/runtime_settings.rs index 56883894..a115acbc 100644 --- a/updatehub-sdk/src/api/info/runtime_settings.rs +++ b/updatehub-sdk/src/api/info/runtime_settings.rs @@ -38,6 +38,23 @@ pub struct RuntimeUpdate { pub upgrade_to_installation: Option, #[serde(skip_serializing_if = "Option::is_none")] pub applied_package_uid: Option, + /// Present when the pending update wrote the eMMC boot partition of its + /// installation set, which only then may the eMMC be switched to + #[serde(default, skip_serializing_if = "Option::is_none")] + pub boot_emmc: Option, +} + +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct RuntimeBootEmmc { + /// Kernel boot ID of the boot that installed the pending update, or + /// rebooted for it, which is only validated from another boot + #[serde(default, skip_serializing_if = "Option::is_none")] + pub boot_id: Option, + /// The agent rebooted for the eMMC to boot the firmware of the pending + /// update, which it only does once + #[serde(default)] + pub rebooted: bool, } #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)] diff --git a/updatehub-sdk/src/api/info/settings.rs b/updatehub-sdk/src/api/info/settings.rs index a3aac063..0ea79e10 100644 --- a/updatehub-sdk/src/api/info/settings.rs +++ b/updatehub-sdk/src/api/info/settings.rs @@ -21,6 +21,18 @@ pub struct Settings { #[serde(deny_unknown_fields)] pub struct Firmware { pub metadata: PathBuf, + #[serde(default, rename = "boot-emmc", skip_serializing_if = "Option::is_none")] + pub boot_emmc: Option, +} + +/// Installation set N boots from boot partition N of `device`: updates +/// write the boot partition of the inactive set, and the eMMC boots from the +/// boot partition of the active one. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct BootEmmc { + /// The eMMC base device, e.g. `/dev/mmcblk1` + pub device: PathBuf, } #[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)] diff --git a/updatehub/Cargo.toml b/updatehub/Cargo.toml index ea32b1a2..f8827964 100644 --- a/updatehub/Cargo.toml +++ b/updatehub/Cargo.toml @@ -49,6 +49,10 @@ required-features = ["test-env"] name = "failed_integration_test" required-features = ["test-env"] +[[test]] +name = "boot_emmc" +required-features = ["test-env"] + [dependencies] argh = "0.1.3" async-ctrlc = { version = "1", optional = true } @@ -113,6 +117,8 @@ git-version = "0.3" [dev-dependencies] expectrl = "0.9" +# The boot_emmc test ties the agent's life to its own (PR_SET_PDEATHSIG) +nix = { version = "0.32", features = ["process"] } flate2 = "1" insta = "1" loopdev-3 = "0.5.1" diff --git a/updatehub/src/firmware/boot_emmc.rs b/updatehub/src/firmware/boot_emmc.rs new file mode 100644 index 00000000..dd17583c --- /dev/null +++ b/updatehub/src/firmware/boot_emmc.rs @@ -0,0 +1,164 @@ +// Copyright (C) 2026 O.S. Systems Sofware LTDA +// +// SPDX-License-Identifier: Apache-2.0 + +//! A/B firmware in the eMMC hardware boot partitions. +//! +//! With `[firmware.boot-emmc]` set, installation set N boots from boot +//! partition N: updates copy the running firmware to the boot partition of +//! the inactive set and write their raw objects with the `boot-emmc` target +//! type over it, and the eMMC boots from the boot partition of the active +//! set. +//! +//! The eMMC only switches to a boot partition after the update wrote and +//! synced it, so a power cut while writing leaves the device booting the +//! firmware it had. The installation set and PARTITION_CONFIG are two +//! separate writes, though: a power cut between them boots the previous +//! firmware with the new set once, and the agent then switches the eMMC and +//! reboots before validating, so the new firmware gets its trial boot. It +//! reboots for that only once per update: when the eMMC still does not boot +//! the update's firmware after it, the update is rolled back. + +use super::{Error, Result, installation_set}; +use crate::{settings::Settings, utils::emmc::Emmc}; +use slog_scope::{error, info, warn}; + +pub(crate) fn emmc(settings: &Settings) -> Option { + settings.firmware.boot_emmc.as_ref().map(|c| Emmc::new(&c.device)) +} + +/// Makes the eMMC boot from the boot partition of the active installation +/// set, returning whether it had to switch. `reason` tells why the set +/// changed, for the log. +pub(crate) fn follow_active_set(settings: &Settings, reason: &str) -> Result { + let Some(emmc) = emmc(settings) else { + return Ok(false); + }; + let set = installation_set::active()?.index(); + + match enabled(&emmc)? { + partition if partition == set => Ok(false), + partition => { + info!( + "{reason}: installation set {set} is active while {:?} boots from {:?}", + emmc.device(), + emmc.boot_partition(partition) + ); + emmc.boot_from(set)?; + Ok(true) + } + } +} + +/// Whether the eMMC boots from the boot partition of the active +/// installation set, or no boot-emmc device is set. +pub(crate) fn follows_active_set(settings: &Settings) -> Result { + match emmc(settings) { + Some(emmc) => Ok(enabled(&emmc)? == installation_set::active()?.index()), + None => Ok(true), + } +} + +/// Before an update writes installation set `target`, which `pending` must +/// not be waiting on a reboot to boot. +/// +/// The eMMC must not be booting from the boot partition of `target`. A +/// device that is, such as one set up before the boot partitions followed +/// the installation sets, is repaired by copying that firmware to the other +/// boot partition and booting from there. +/// +/// The running firmware is then copied to `target`'s boot partition, so +/// what the update does not write, if anything, is the firmware running +/// now rather than whatever an older or interrupted update left there. +/// +/// The update's state must be persistent: without it, nothing would bring +/// the eMMC back after a rollback. +pub(crate) fn prepare_install( + settings: &Settings, + persistent: bool, + pending: Option, + target: u8, +) -> Result<()> { + let Some(emmc) = emmc(settings) else { + return Ok(()); + }; + if !persistent { + return Err(Error::EmmcStateNotPersistent); + } + if let Some(pending) = pending { + return Err(Error::EmmcRebootPending(pending.index())); + } + if installation_set::active()?.index() == target { + return Err(Error::EmmcTargetActive(target)); + } + + let mut running = enabled(&emmc)?; + if running == target { + let other = 1 - target; + warn!( + "{:?} boots from {:?}, which belongs to installation set {target} and is about to \ + be overwritten by this update: copying its firmware to {:?}, the boot partition \ + of installation set {other}, and booting from there instead", + emmc.device(), + emmc.boot_partition(target), + emmc.boot_partition(other), + ); + emmc.probe(other)?; + ensure_not_booting(&emmc, other)?; + emmc.copy_boot_partition(target, other)?; + emmc.boot_from(other)?; + warn!("{:?} now boots from {:?}", emmc.device(), emmc.boot_partition(other)); + running = other; + } + + // A kernel restoring its cached PARTITION_CONFIG does so on the next + // access to a boot partition. Before writing one, that access must be a + // read, which leaves it as it is if the eMMC then boots from it. + emmc.probe(target)?; + ensure_not_booting(&emmc, target)?; + + if emmc.copy_boot_partition(running, target)? { + info!( + "copied the running firmware from {:?} to {:?}", + emmc.boot_partition(running), + emmc.boot_partition(target) + ); + } + + Ok(()) +} + +/// After an update wrote the boot partition of installation set `target`: +/// the eMMC must still boot from the other one. +pub(crate) fn check_installed(settings: &Settings, target: u8) -> Result<()> { + match emmc(settings) { + Some(emmc) => ensure_not_booting(&emmc, target), + None => Ok(()), + } +} + +/// A kernel restoring its cached PARTITION_CONFIG on an access to the boot +/// partition of `target` makes the eMMC boot from it, so it is switched +/// back before failing. +fn ensure_not_booting(emmc: &Emmc, target: u8) -> Result<()> { + if enabled(emmc)? == target { + if let Err(e) = emmc.boot_from(1 - target) { + error!("unable to switch {:?} back to the running firmware: {}", emmc.device(), e); + } + return Err(Error::EmmcSwitchReverted { + device: emmc.device().to_owned(), + partition: emmc.boot_partition(target), + }); + } + Ok(()) +} + +fn enabled(emmc: &Emmc) -> Result { + match emmc.enabled_boot_partition()? { + Some(partition) => Ok(partition), + None => Err(Error::EmmcNotBooting { + device: emmc.device().to_owned(), + part_config: emmc.part_config()?, + }), + } +} diff --git a/updatehub/src/firmware/installation_set.rs b/updatehub/src/firmware/installation_set.rs index d4140ca6..f4891228 100644 --- a/updatehub/src/firmware/installation_set.rs +++ b/updatehub/src/firmware/installation_set.rs @@ -38,6 +38,17 @@ impl fmt::Display for Set { } } +impl Set { + /// 0 or 1, as the installation set scripts and the eMMC boot partitions + /// number them + pub(crate) fn index(self) -> u8 { + match self.0 { + InstallationSet::A => 0, + InstallationSet::B => 1, + } + } +} + pub fn active() -> super::Result { run_script(GET_SCRIPT)?.parse() } diff --git a/updatehub/src/firmware/mod.rs b/updatehub/src/firmware/mod.rs index 54c36620..d4d02e2b 100644 --- a/updatehub/src/firmware/mod.rs +++ b/updatehub/src/firmware/mod.rs @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: Apache-2.0 +pub(crate) mod boot_emmc; mod hook; pub mod installation_set; @@ -40,6 +41,53 @@ pub enum Error { #[display("invalid installation set, the only know ones are 0 or 1")] InvalidInstallSet, + #[display( + "{device:?} does not boot from a boot partition (PARTITION_CONFIG 0x{part_config:02x}), \ + so it cannot follow the installation set" + )] + #[from(ignore)] + EmmcNotBooting { + device: std::path::PathBuf, + part_config: u8, + }, + + #[display( + "the eMMC boot partitions are not updated while installation set {_0} waits for a \ + reboot to boot" + )] + #[from(ignore)] + EmmcRebootPending(#[error(not(source))] u8), + + #[display( + "the package was validated for the eMMC boot partition of installation set \ + {validated}, but installation set {installing} is the one inactive now" + )] + #[from(ignore)] + EmmcTargetChanged { + validated: u8, + installing: u8, + }, + + #[display( + "the eMMC boot partitions are not updated with storage.read_only set: the update's \ + state must survive a reboot for the eMMC to follow a rollback" + )] + EmmcStateNotPersistent, + + #[display("installation set {_0} is the active one, so its eMMC boot partition is not updated")] + #[from(ignore)] + EmmcTargetActive(#[error(not(source))] u8), + + #[display( + "{device:?} boots from {partition:?} again after an access to it: the kernel restored \ + its cached PARTITION_CONFIG, so it cannot switch eMMC boot partitions safely" + )] + #[from(ignore)] + EmmcSwitchReverted { + device: std::path::PathBuf, + partition: std::path::PathBuf, + }, + #[display( "refusing to run {_0:?} from a test build: tests reboot through a fake `reboot` in the \ temporary directory, so this one would reboot the machine running them" @@ -49,6 +97,8 @@ pub enum Error { Walkdir(walkdir::Error), + Utils(crate::utils::Error), + Io(std::io::Error), Process(easy_process::Error), diff --git a/updatehub/src/object/installer/mod.rs b/updatehub/src/object/installer/mod.rs index ee8bfa87..d613f4ae 100644 --- a/updatehub/src/object/installer/mod.rs +++ b/updatehub/src/object/installer/mod.rs @@ -27,6 +27,14 @@ pub(crate) struct Context { pub(crate) download_dir: PathBuf, pub(crate) offline_update: bool, pub(crate) base_url: String, + pub(crate) boot_emmc: Option, +} + +#[derive(Clone, Debug)] +pub(crate) struct BootEmmcTarget { + pub(crate) emmc: utils::emmc::Emmc, + /// Boot partition of the installation set being installed + pub(crate) partition: u8, } pub(crate) trait Installer { diff --git a/updatehub/src/object/installer/raw.rs b/updatehub/src/object/installer/raw.rs index 608192f3..99337b43 100644 --- a/updatehub/src/object/installer/raw.rs +++ b/updatehub/src/object/installer/raw.rs @@ -16,18 +16,37 @@ use slog_scope::info; use std::{io::SeekFrom, path::Path}; use tokio::{ fs, - io::{AsyncRead, AsyncReadExt, AsyncSeekExt}, + io::{AsyncRead, AsyncReadExt, AsyncSeekExt, AsyncWriteExt}, }; use tokio_take_seek::AsyncTakeSeekExt; +/// The target the object writes: a `boot-emmc` target names the eMMC, and +/// the context tells which of its boot partitions this installation set +/// owns. +fn resolve_target(obj: &objects::Raw, context: &Context) -> Result { + let definitions::TargetType::BootEmmc(ref device) = obj.target_type else { + return Ok(obj.target_type.clone()); + }; + let target = + context.boot_emmc.as_ref().ok_or_else(|| Error::BootEmmcNotConfigured(device.clone()))?; + if !target.emmc.is(device) { + return Err(Error::BootEmmcDeviceMismatch { + package: device.clone(), + configured: target.emmc.device().to_owned(), + }); + } + Ok(definitions::TargetType::Device(target.emmc.boot_partition(target.partition))) +} + impl Installer for objects::Raw { - async fn check_requirements(&self, _: &Context) -> Result<()> { + async fn check_requirements(&self, context: &Context) -> Result<()> { info!("'raw' handle checking requirements"); + let target = resolve_target(self, context)?; let access = checked_region(self) .map_or(Access::Exclusive, |(offset, len)| Access::Region { offset, len }); if let definitions::TargetType::Device(dev) = - self.target_type.valid(access).log_error_msg("device failed vaidation")? + target.valid(access).log_error_msg("device failed vaidation")? { utils::fs::ensure_disk_space(dev, self.required_install_size()) .log_error_msg("not enough disk space")?; @@ -40,9 +59,13 @@ impl Installer for objects::Raw { async fn install(&self, context: &Context) -> Result<()> { info!("'raw' handler Install {} ({})", self.filename, self.sha256sum); - let definitions::TargetType::Device(ref device) = self.target_type else { + let boot_emmc = matches!(self.target_type, definitions::TargetType::BootEmmc(_)); + let definitions::TargetType::Device(ref device) = resolve_target(self, context)? else { unreachable!("device should be secured by check_requirements") }; + if boot_emmc { + info!("writing to {:?}", device); + } let source = context.download_dir.join(self.sha256sum()); let chunk_size = self.chunk_size.0; let truncate = self.truncate.0; @@ -62,6 +85,15 @@ impl Installer for objects::Raw { ) .await?; if should_skip_install { + // What matched may be in the page cache only, left by an earlier + // try that stopped before syncing + if boot_emmc { + fs::File::open(device) + .await? + .sync_all() + .await + .log_error_msg("failed to sync target file")?; + } return Ok(()); } @@ -77,21 +109,31 @@ impl Installer for objects::Raw { _ => None, }; + // Only a boot partition checked to be the inactive set's is unlocked + let unlocked = if boot_emmc { utils::emmc::ForceRoGuard::unlock(device)? } else { None }; + utils::emmc::ensure_writable(device)?; + let mut input = open_source(self, &source).await?; + let file = fs::OpenOptions::new() + .write(true) + .truncate(truncate) + .open(device) + .await + .log_error_msg("failed to open target file")?; + // Synced through the same open file, which is the one a writeback + // error is reported to + let synced = if boot_emmc { Some(file.try_clone().await?) } else { None }; let mut target = { - let mut target = utils::io::timed_buf_writer( - chunk_size, - fs::OpenOptions::new() - .write(true) - .truncate(truncate) - .open(device) - .await - .log_error_msg("failed to open target file")?, - ); + let mut target = utils::io::timed_buf_writer(chunk_size, file); target.seek(SeekFrom::Start(seek)).await.log_error_msg("failed to seek target file")?; utils::io::BoundedWriter::new(target, limit.unwrap_or(u64::MAX)) }; + #[cfg(feature = "test-env")] + if boot_emmc { + power_cut_for_tests(&mut input, &mut target, device).await?; + } + if self.compressed { compress_tools::tokio_support::uncompress_data(&mut input, &mut target) .await @@ -101,11 +143,43 @@ impl Installer for objects::Raw { .await .log_error_msg("failed copy from source into target")?; } + target.flush().await.log_error_msg("failed to flush target file")?; + drop(target); + + // The eMMC may boot from a boot partition as soon as the update ends, + // so it must be on the device by then, not in the page cache + if let Some(synced) = synced { + synced.sync_all().await.log_error_msg("failed to sync target file")?; + } + if let Some(unlocked) = unlocked { + unlocked.lock().log_error_msg("failed to make the target read-only again")?; + } Ok(()) } } +/// Lets tests cut the power in the middle of writing a boot partition: with +/// `UPDATEHUB_TEST_POWER_CUT_AFTER` set to a byte count, only that much is +/// written and synced before the agent dies on the spot. +#[cfg(feature = "test-env")] +async fn power_cut_for_tests(input: &mut R, target: &mut W, device: &Path) -> Result<()> +where + R: AsyncRead + Unpin, + W: tokio::io::AsyncWrite + Unpin, +{ + let Some(bytes) = + std::env::var("UPDATEHUB_TEST_POWER_CUT_AFTER").ok().and_then(|v| v.parse().ok()) + else { + return Ok(()); + }; + tokio::io::copy(&mut input.take(bytes), target).await?; + target.flush().await?; + fs::File::open(device).await?.sync_all().await?; + slog_scope::warn!("power cut after writing {} bytes to {:?}", bytes, device); + std::process::abort(); +} + async fn open_source(obj: &objects::Raw, source: &Path) -> Result> { let mut input = utils::io::timed_buf_reader( obj.chunk_size.0, diff --git a/updatehub/src/object/mod.rs b/updatehub/src/object/mod.rs index 6bf6e887..49d18f93 100644 --- a/updatehub/src/object/mod.rs +++ b/updatehub/src/object/mod.rs @@ -27,6 +27,19 @@ pub enum Error { Utils(crate::utils::Error), Firmware(crate::firmware::Error), + #[display( + "the package writes the boot partitions of {_0:?}, but the settings have no \ + [firmware.boot-emmc] section" + )] + BootEmmcNotConfigured(#[error(not(source))] std::path::PathBuf), + #[display( + "the package writes the boot partitions of {package:?}, the device uses {configured:?}" + )] + BootEmmcDeviceMismatch { + package: std::path::PathBuf, + configured: std::path::PathBuf, + }, + #[display("invalid target type {_0:?}")] InvalidTargetType(#[error(not(source))] pkg_schema::definitions::TargetType), Io(std::io::Error), diff --git a/updatehub/src/runtime_settings.rs b/updatehub/src/runtime_settings.rs index 86481df6..cbbc6d76 100644 --- a/updatehub/src/runtime_settings.rs +++ b/updatehub/src/runtime_settings.rs @@ -51,6 +51,7 @@ impl Default for RuntimeSettings { update: api::RuntimeUpdate { upgrade_to_installation: None, applied_package_uid: None, + boot_emmc: None, }, path: std::path::PathBuf::new(), persistent: false, @@ -201,9 +202,30 @@ impl RuntimeSettings { self.save() } - pub(crate) fn set_upgrading_to(&mut self, new_install_set: Set) -> Result<()> { + /// Records the update installed to `new_install_set`, by this boot. With + /// `boot_emmc`, the update wrote the set's eMMC boot partition. + pub(crate) fn set_upgrading_to(&mut self, new_install_set: Set, boot_emmc: bool) -> Result<()> { debug!("setting upgrading to {}", new_install_set); self.update.upgrade_to_installation = Some(new_install_set.0); + self.update.boot_emmc = boot_emmc + .then(|| api::RuntimeBootEmmc { boot_id: crate::utils::boot_id(), rebooted: false }); + self.save() + } + + /// Whether this is still the boot that installed the pending update, or + /// rebooted for it, which is only recorded for boot-emmc updates + pub(crate) fn is_upgrade_boot(&self) -> bool { + self.update + .boot_emmc + .as_ref() + .and_then(|b| b.boot_id.as_ref()) + .is_some_and(|id| Some(id) == crate::utils::boot_id().as_ref()) + } + + /// Records the reboot for the eMMC to boot the pending update's firmware + pub(crate) fn set_boot_emmc_rebooted(&mut self) -> Result<()> { + self.update.boot_emmc = + Some(api::RuntimeBootEmmc { boot_id: crate::utils::boot_id(), rebooted: true }); self.save() } @@ -225,10 +247,22 @@ impl RuntimeSettings { self.polling.server_address = api::ServerAddress::Default; } + /// Forgets an install that failed before it was activated. Unlike + /// `reset_installation_settings`, it does not force a probe, so while + /// whatever made it fail lasts the package is retried at the polling + /// interval or on request, not again right away. + pub(crate) fn clear_upgrading(&mut self) -> Result<()> { + self.update.upgrade_to_installation = None; + self.update.applied_package_uid = None; + self.update.boot_emmc = None; + self.save() + } + pub(crate) fn reset_installation_settings(&mut self) -> Result<()> { debug!("reseting installation settings"); self.update.upgrade_to_installation = None; self.update.applied_package_uid = None; + self.update.boot_emmc = None; // Ensure we do a probe as soon as possible so full update // cycle can be finished. @@ -326,6 +360,7 @@ fn v1_parse(content: &str, json_err: serde_json::Error) -> Result None, }, applied_package_uid: None, + boot_emmc: None, }, path: std::path::PathBuf::new(), persistent: false, @@ -366,6 +401,7 @@ mod tests { update: api::RuntimeUpdate { upgrade_to_installation: None, applied_package_uid: None, + boot_emmc: None, }, path: std::path::PathBuf::new(), persistent: false, @@ -463,6 +499,7 @@ UpgradeToInstallation=1 update: api::RuntimeUpdate { upgrade_to_installation: Some(api::InstallationSet::B), applied_package_uid: None, + boot_emmc: None, }, path: std::path::PathBuf::new(), persistent: false, diff --git a/updatehub/src/settings.rs b/updatehub/src/settings.rs index 82f1816a..39a5406b 100644 --- a/updatehub/src/settings.rs +++ b/updatehub/src/settings.rs @@ -50,7 +50,7 @@ impl Default for Settings { server_address: "https://api.updatehub.io".to_string(), listen_socket: "localhost:8080".to_string(), }, - firmware: api::Firmware { metadata: "/usr/share/updatehub".into() }, + firmware: api::Firmware { metadata: "/usr/share/updatehub".into(), boot_emmc: None }, }) } } @@ -202,7 +202,7 @@ fn v1_parse(content: &str, toml_err: toml::de::Error) -> Result { .map_err(|ini_err| Error::V1Parsing(Box::new(toml_err), ini_err))?; Ok(api::Settings { - firmware: api::Firmware { metadata: old_settings.firmware.metadata_path }, + firmware: api::Firmware { metadata: old_settings.firmware.metadata_path, boot_emmc: None }, network: api::Network { server_address: old_settings.network.server_address, listen_socket: old_settings.network.listen_socket, @@ -272,7 +272,7 @@ metadata="/usr/share/updatehub" server_address: "https://api.updatehub.io".to_string(), listen_socket: "localhost:8080".to_string(), }, - firmware: api::Firmware { metadata: "/usr/share/updatehub".into() }, + firmware: api::Firmware { metadata: "/usr/share/updatehub".into(), boot_emmc: None }, }); assert_eq!(Settings::parse(sample).unwrap(), expected); } @@ -352,7 +352,7 @@ metadata="/usr/share/updatehub" server_address: "https://api.updatehub.io".to_string(), listen_socket: "localhost:8080".to_string(), }, - firmware: api::Firmware { metadata: "/usr/share/updatehub".into() }, + firmware: api::Firmware { metadata: "/usr/share/updatehub".into(), boot_emmc: None }, }); assert_eq!(Some(settings), Some(expected)); @@ -395,7 +395,7 @@ ListenSocket=localhost:8313 server_address: "http://localhost".to_string(), listen_socket: "localhost:8313".to_string(), }, - firmware: api::Firmware { metadata: "/usr/share/updatehub".into() }, + firmware: api::Firmware { metadata: "/usr/share/updatehub".into(), boot_emmc: None }, }); assert_eq!(Settings::parse(sample).unwrap(), expected); diff --git a/updatehub/src/states/install.rs b/updatehub/src/states/install.rs index b6cfbec7..9287ba93 100644 --- a/updatehub/src/states/install.rs +++ b/updatehub/src/states/install.rs @@ -7,12 +7,12 @@ use super::{ machine::{self, Context}, }; use crate::{ - firmware::installation_set, + firmware::{boot_emmc, installation_set}, object::{self, Info, Installer}, update_package::{UpdatePackage, UpdatePackageExt}, utils::log::LogContent, }; -use slog_scope::info; +use slog_scope::{error, info, warn}; #[derive(Debug)] pub(super) struct Install { @@ -52,6 +52,17 @@ impl StateChangeImpl for Install { info!("using installation set as target {}", installation_set); let obj_context = self.object_context; + // The objects write the boot partition picked when the package was + // validated, which must still be the one prepared here + if let Some(target) = &obj_context.boot_emmc { + if target.partition != installation_set.index() { + return Err(crate::firmware::Error::EmmcTargetChanged { + validated: target.partition, + installing: installation_set.index(), + } + .into()); + } + } let objs = self.update_package.objects_mut(installation_set); // Objects are sorted in reverse order so the smaller objects are installed @@ -59,11 +70,22 @@ impl StateChangeImpl for Install { // changes towards the end of the update. objs.sort_by(|a, b| a.len().partial_cmp(&b.len()).unwrap().reverse()); + boot_emmc::prepare_install( + &context.settings, + !context.settings.storage.read_only, + context.runtime_settings.update.upgrade_to_installation.map(installation_set::Set), + installation_set.index(), + ) + .log_error_msg("unable to prepare the eMMC boot partitions")?; + // Run the install routine for every object. for obj in objs.iter_mut() { obj.install(&obj_context).await?; } + boot_emmc::check_installed(&context.settings, installation_set.index()) + .log_error_msg("unable to install the eMMC boot partition")?; + // Avoid installing same package twice. context .runtime_settings @@ -73,13 +95,43 @@ impl StateChangeImpl for Install { // Set upgrading to the new installation set. context .runtime_settings - .set_upgrading_to(installation_set) + .set_upgrading_to(installation_set, boot_emmc::emmc(&context.settings).is_some()) .log_error_msg("failed to upgrade installation set to runtime settings ")?; // Swap installation set so it is used next device boot. info!("swapping active installation set"); - installation_set::swap_active() - .log_error_msg("unable to update active installation set")?; + // A swap that fails without changing the set leaves no update to + // wait for + if let Err(e) = installation_set::swap_active() { + error!("unable to update active installation set: {}", e); + if installation_set::active()? != installation_set { + context + .runtime_settings + .clear_upgrading() + .log_error_msg("failed to reset the installation settings")?; + return Err(e.into()); + } + warn!("the active installation set changed nonetheless"); + } + + // When the eMMC cannot follow the new set, the set goes back, so + // firmware and system stay a pair. Should the eMMC not follow back + // either, the update stays pending, and the next start makes it. + if let Err(e) = boot_emmc::follow_active_set(&context.settings, "update installed") { + error!("unable to boot the eMMC from the new installation set: {}", e); + installation_set::swap_active() + .log_error_msg("unable to restore the active installation set")?; + match boot_emmc::follow_active_set(&context.settings, "update aborted") { + Ok(_) => context + .runtime_settings + .clear_upgrading() + .log_error_msg("failed to reset the installation settings")?, + Err(e) => { + error!("unable to boot the eMMC from the previous installation set: {}", e) + } + } + return Err(e.into()); + } info!("update installed successfully"); Ok(( diff --git a/updatehub/src/states/mod.rs b/updatehub/src/states/mod.rs index 2bfa91fc..226cb602 100644 --- a/updatehub/src/states/mod.rs +++ b/updatehub/src/states/mod.rs @@ -224,12 +224,63 @@ fn handle_startup_callbacks( runtime_settings: &mut RuntimeSettings, ) -> crate::Result<()> { if let Some(expected_set) = runtime_settings.update.upgrade_to_installation { + // The agent restarted without the device rebooting, e.g. after the + // reboot failed: the update has not run yet + if runtime_settings.is_upgrade_boot() { + // Unless the agent stopped while rebooting for the update's + // firmware, which it then resumes + if runtime_settings.update.boot_emmc.as_ref().is_some_and(|b| b.rebooted) + && expected_set == firmware::installation_set::active()?.0 + { + firmware::boot_emmc::follow_active_set(settings, "agent start")?; + warn!("rebooting so the update is validated running its own firmware"); + firmware::reboot()?; + } else { + warn!("the installed update waits for the device to reboot"); + } + return Ok(()); + } + info!("booting from a recent installation"); + // A power cut may have come between the installation set and the + // eMMC switching, or a bootloader may have rolled the set back on + // its own after too many failed boots. Until the eMMC follows, the + // update stays pending. Only an update that wrote the eMMC boot + // partition of its set may switch it there. + let boot_emmc = runtime_settings.update.boot_emmc.clone(); + let follows = match boot_emmc { + Some(_) => firmware::boot_emmc::follows_active_set(settings)?, + None => true, + }; if expected_set == firmware::installation_set::active()?.0 { - match firmware::validate_callback(&settings.firmware.metadata)? { + let transition = if follows { + firmware::validate_callback(&settings.firmware.metadata)? + } else if boot_emmc.is_some_and(|b| b.rebooted) { + error!("the eMMC did not keep booting the firmware of the update"); + Transition::Cancel + } else { + // Recorded before switching, so an agent restarting in this + // boot does not take the switched eMMC for a booted update + runtime_settings.set_boot_emmc_rebooted()?; + firmware::boot_emmc::follow_active_set(settings, "agent start")?; + warn!("rebooting so the update is validated running its own firmware"); + firmware::reboot()?; + return Ok(()); + }; + match transition { Transition::Cancel => { warn!("validate callback has failed"); firmware::installation_set::swap_active()?; + if runtime_settings.update.boot_emmc.is_some() { + if let Err(e) = + firmware::boot_emmc::follow_active_set(settings, "update rolled back") + { + error!( + "unable to boot the eMMC from the previous installation set: {}", + e + ); + } + } warn!("swapped active installation set and running rollback"); firmware::rollback_callback(&settings.firmware.metadata)?; @@ -248,6 +299,9 @@ fn handle_startup_callbacks( Transition::Continue => firmware::installation_set::validate()?, } } else { + if !follows { + firmware::boot_emmc::follow_active_set(settings, "agent start")?; + } warn!("confirming active installation as update has been rollback"); firmware::installation_set::validate()?; } diff --git a/updatehub/src/states/tests.rs b/updatehub/src/states/tests.rs index ba111e94..38d220bd 100644 --- a/updatehub/src/states/tests.rs +++ b/updatehub/src/states/tests.rs @@ -24,7 +24,7 @@ fn startup_without_upgrade() { fn startup_with_normal_upgrade() { let mut setup = crate::tests::TestEnvironment::build().finish(); let output_file_path = &setup.binaries.data; - setup.runtime_settings.data.set_upgrading_to(Set(InstallationSet::A)).unwrap(); + setup.runtime_settings.data.set_upgrading_to(Set(InstallationSet::A), false).unwrap(); handle_startup_callbacks(&setup.settings.data, &mut setup.runtime_settings.data).unwrap(); @@ -48,7 +48,7 @@ fn startup_on_faulty_upgrade() { format!("#!/bin/sh\necho $0 >> {}\nexit 1", output_file_path.to_string_lossy()), ) .unwrap(); - setup.runtime_settings.data.set_upgrading_to(Set(InstallationSet::A)).unwrap(); + setup.runtime_settings.data.set_upgrading_to(Set(InstallationSet::A), false).unwrap(); handle_startup_callbacks(&setup.settings.data, &mut setup.runtime_settings.data).unwrap(); @@ -69,7 +69,7 @@ fn startup_on_faulty_upgrade() { #[test] fn startup_on_wrong_install_set() { let mut setup = crate::tests::TestEnvironment::build().finish(); - setup.runtime_settings.data.set_upgrading_to(Set(InstallationSet::B)).unwrap(); + setup.runtime_settings.data.set_upgrading_to(Set(InstallationSet::B), false).unwrap(); handle_startup_callbacks(&setup.settings.data, &mut setup.runtime_settings.data).unwrap(); diff --git a/updatehub/src/states/validation.rs b/updatehub/src/states/validation.rs index 924dd61a..dbf0aa9a 100644 --- a/updatehub/src/states/validation.rs +++ b/updatehub/src/states/validation.rs @@ -45,7 +45,18 @@ impl StateChangeImpl for Validation { info!("no signature key available on device, ignoring signature validation"); } + let inactive_installation_set = context + .runtime_settings + .get_inactive_installation_set() + .log_error_msg("unable to get inactive installation set")?; + let object_context = object::installer::Context { + boot_emmc: crate::firmware::boot_emmc::emmc(&context.settings).map(|emmc| { + object::installer::BootEmmcTarget { + emmc, + partition: inactive_installation_set.index(), + } + }), download_dir: context.settings.update.download_dir.clone(), offline_update: !self.require_download, base_url: format!( @@ -57,10 +68,6 @@ impl StateChangeImpl for Validation { }; // Ensure the package is compatible - let inactive_installation_set = context - .runtime_settings - .get_inactive_installation_set() - .log_error_msg("unable to get inactive installation set")?; self.package .compatible_with(&context.firmware) .log_error_msg("uhupkg is not compatible with this device")?; diff --git a/updatehub/src/tests.rs b/updatehub/src/tests.rs index 6fcd286e..f63bb1ee 100644 --- a/updatehub/src/tests.rs +++ b/updatehub/src/tests.rs @@ -192,7 +192,7 @@ impl TestEnvironmentBuilder { runtime_settings.path.clone_from(&file_path); if self.booting_from_update { runtime_settings.enable_persistency(); - runtime_settings.set_upgrading_to(Set(InstallationSet::A)).unwrap(); + runtime_settings.set_upgrading_to(Set(InstallationSet::A), false).unwrap(); } Data { data: runtime_settings, stored_path: file_path, guard: vec![Box::new(file)] } diff --git a/updatehub/src/utils/emmc.rs b/updatehub/src/utils/emmc.rs new file mode 100644 index 00000000..b8743444 --- /dev/null +++ b/updatehub/src/utils/emmc.rs @@ -0,0 +1,463 @@ +// Copyright (C) 2026 O.S. Systems Sofware LTDA +// +// SPDX-License-Identifier: Apache-2.0 + +//! eMMC hardware boot partitions. +//! +//! An eMMC has two boot partitions, `/dev/mmcblkNboot0` and `boot1`, which +//! the kernel keeps read-only (`force_ro`) and one of which the SoC ROM +//! boots from, picked by the BOOT_PARTITION_ENABLE bits of the +//! PARTITION_CONFIG register (EXT_CSD[179]). The register is read and +//! written with the `MMC_IOC_CMD` ioctl. +//! +//! Builds for tests can point this module at a directory instead of the +//! hardware, see [`simulator`]. + +use super::{Error, Result}; +use slog_scope::{info, warn}; +use std::{ + fs, io, + os::unix::fs::OpenOptionsExt, + path::{Path, PathBuf}, +}; + +const EXT_CSD_PART_CONFIG: usize = 179; +const EXT_CSD_SIZE: usize = 512; +/// Some ROMs need the boot acknowledge, so it is never touched +const BOOT_ACK: u8 = 1 << 6; +/// Set by the kernel to the partition it accesses, so not part of the switch +const PARTITION_ACCESS: u8 = 0b111; + +/// The boot partition (0 or 1) a PARTITION_CONFIG value boots from, `None` +/// for the user area or when booting is not enabled. +pub(crate) fn enabled_boot_partition(part_config: u8) -> Option { + match (part_config >> 3) & 0b111 { + 1 => Some(0), + 2 => Some(1), + _ => None, + } +} + +/// PARTITION_CONFIG booting from `partition`, keeping the boot acknowledge +/// of `current`. PARTITION_ACCESS belongs to the kernel, which sets it on +/// every access, so it is left cleared as RAUC and mmc-utils do. +pub(crate) fn part_config_booting(current: u8, partition: u8) -> u8 { + (current & BOOT_ACK) | ((partition + 1) << 3) +} + +/// An eMMC, named by its base device (e.g. `/dev/mmcblk1`) +#[derive(Clone, Debug)] +pub(crate) struct Emmc { + device: PathBuf, +} + +impl Emmc { + pub(crate) fn new(device: &Path) -> Self { + Emmc { device: device.to_owned() } + } + + pub(crate) fn device(&self) -> &Path { + &self.device + } + + /// Boot partition `partition` (0 or 1), named after the base device the + /// configured one resolves to, which may be a symlink such as + /// `/dev/disk/by-path/...` + pub(crate) fn boot_partition(&self, partition: u8) -> PathBuf { + let base = fs::canonicalize(&self.device).unwrap_or_else(|_| self.device.clone()); + let mut path = base.into_os_string(); + path.push(format!("boot{partition}")); + path.into() + } + + /// Whether `other` names this eMMC, through a symlink or not + pub(crate) fn is(&self, other: &Path) -> bool { + let canonical = |p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_owned()); + canonical(&self.device) == canonical(other) + } + + pub(crate) fn part_config(&self) -> Result { + Ok(backend::read_ext_csd(&self.device)?[EXT_CSD_PART_CONFIG]) + } + + pub(crate) fn enabled_boot_partition(&self) -> Result> { + Ok(enabled_boot_partition(self.part_config()?)) + } + + /// Makes the eMMC boot from `partition`, then reads PARTITION_CONFIG + /// back, as a switch that did not happen must not pass. A kernel that + /// keeps a cached PARTITION_CONFIG may still write the old value back on + /// its next boot partition access (see RAUC's documentation on the + /// ext_csd ioctl bug), so callers check it again after such accesses. + pub(crate) fn boot_from(&self, partition: u8) -> Result<()> { + let current = self.part_config()?; + let wanted = part_config_booting(current, partition); + if enabled_boot_partition(current) == Some(partition) { + return Ok(()); + } + + info!( + "switching {:?} to boot from {:?} (PARTITION_CONFIG 0x{current:02x} -> 0x{wanted:02x})", + self.device, + self.boot_partition(partition) + ); + backend::write_ext_csd(&self.device, EXT_CSD_PART_CONFIG, wanted)?; + + let found = self.part_config()?; + if found & !PARTITION_ACCESS != wanted { + return Err(Error::EmmcSwitchFailed { + device: self.device.clone(), + expected: wanted, + found, + }); + } + + Ok(()) + } + + /// Reads the start of boot partition `partition` from the device, an + /// access that leaves it as it is. + pub(crate) fn probe(&self, partition: u8) -> Result<()> { + read_from_media(&self.boot_partition(partition), 4096)?; + Ok(()) + } + + /// Copies boot partition `from` over `to`, unless they already hold the + /// same content. Returns whether it copied. + pub(crate) fn copy_boot_partition(&self, from: u8, to: u8) -> Result { + let source = self.boot_partition(from); + let target = self.boot_partition(to); + let data = read_from_media(&source, usize::MAX)?; + if read_from_media(&target, data.len())? == data { + return Ok(false); + } + + let unlocked = ForceRoGuard::unlock(&target)?; + ensure_writable(&target)?; + let mut file = fs::OpenOptions::new().write(true).open(&target)?; + io::Write::write_all(&mut file, &data)?; + file.sync_all()?; + drop(file); + if let Some(unlocked) = unlocked { + unlocked.lock()?; + } + + if read_from_media(&target, data.len())? != data { + return Err(Error::EmmcCopyMismatch { from: source, to: target }); + } + + Ok(true) + } +} + +/// Reads up to `limit` bytes of `path` past the page cache (`O_DIRECT`), +/// which would otherwise answer with what was just written instead of what +/// reached the device. +fn read_from_media(path: &Path, limit: usize) -> Result> { + const ALIGN: usize = 4096; + const CHUNK: usize = 1024 * 1024; + + simulator::boot_partition_access(path)?; + if simulator::active() { + // Simulated boot partitions are regular files, which do not all + // support O_DIRECT + let mut data = fs::read(path)?; + data.truncate(limit); + return Ok(data); + } + + let mut file = + fs::OpenOptions::new().read(true).custom_flags(nix::libc::O_DIRECT).open(path)?; + let mut buffer = vec![0u8; CHUNK + ALIGN]; + let start = buffer.as_ptr().align_offset(ALIGN); + let chunk = &mut buffer[start..start + CHUNK]; + let mut data = Vec::new(); + while data.len() < limit { + let read = io::Read::read(&mut file, chunk)?; + if read == 0 { + break; + } + data.extend_from_slice(&chunk[..read]); + } + data.truncate(limit); + Ok(data) +} + +/// Clears `force_ro` of a block device for as long as it lives, restoring +/// the previous value when dropped. +pub(crate) struct ForceRoGuard { + path: PathBuf, + previous: String, + restored: bool, +} + +impl ForceRoGuard { + /// `None` when the device has no `force_ro` attribute, or it is clear + /// already: nothing to restore then. + pub(crate) fn unlock(device: &Path) -> Result> { + let path = force_ro_path(device); + let Ok(previous) = fs::read_to_string(&path) else { + return Ok(None); + }; + let previous = previous.trim().to_owned(); + if previous == "0" { + return Ok(None); + } + + info!("unlocking {:?} for writing", device); + fs::write(&path, "0")?; + Ok(Some(ForceRoGuard { path, previous, restored: false })) + } + + /// Restores `force_ro`, failing when it cannot: the device must not be + /// left writable once the update goes on. + pub(crate) fn lock(mut self) -> Result<()> { + fs::write(&self.path, &self.previous)?; + self.restored = true; + Ok(()) + } +} + +impl Drop for ForceRoGuard { + fn drop(&mut self) { + if self.restored { + return; + } + if let Err(e) = fs::write(&self.path, &self.previous) { + warn!("failed to restore {:?} to {}: {}", self.path, self.previous, e); + } + } +} + +fn force_ro_path(device: &Path) -> PathBuf { + let device = fs::canonicalize(device).unwrap_or_else(|_| device.to_owned()); + let name = device.file_name().map(PathBuf::from).unwrap_or_default(); + simulator::sysfs_root().join(name).join("force_ro") +} + +/// Fails as the kernel would when opening a `force_ro` device for writing. +/// Only the simulator needs this, the kernel enforces it on the hardware. +pub(crate) fn ensure_writable(device: &Path) -> Result<()> { + if simulator::active() + && fs::read_to_string(force_ro_path(device)).is_ok_and(|v| v.trim() == "1") + { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("{} is read-only (force_ro)", device.display()), + ) + .into()); + } + simulator::boot_partition_access(device) +} + +/// Lets tests run the agent against a simulated eMMC. +/// +/// With `UPDATEHUB_EMMC_SIMULATOR` naming a directory, which only test +/// builds honour: +/// - the base device is a regular file holding the 512 bytes of EXT_CSD; +/// - the boot partitions are regular files next to it; +/// - `force_ro` lives in `//force_ro`, and writes to a boot +/// partition fail while it is set; +/// - with `UPDATEHUB_EMMC_SIMULATOR_STALE_KERNEL` set too, it behaves as a +/// kernel that keeps the PARTITION_CONFIG it read first and writes it back on +/// every boot partition access. +mod simulator { + use std::path::{Path, PathBuf}; + + #[cfg(any(test, feature = "test-env"))] + pub(super) fn root() -> Option { + std::env::var_os("UPDATEHUB_EMMC_SIMULATOR").map(PathBuf::from) + } + + #[cfg(not(any(test, feature = "test-env")))] + pub(super) fn root() -> Option { + None + } + + pub(super) fn active() -> bool { + root().is_some() + } + + pub(super) fn sysfs_root() -> PathBuf { + root().unwrap_or_else(|| PathBuf::from("/sys/class/block")) + } + + #[cfg(any(test, feature = "test-env"))] + static CACHED_PART_CONFIG: std::sync::OnceLock = std::sync::OnceLock::new(); + + #[cfg(any(test, feature = "test-env"))] + fn stale_kernel() -> bool { + active() && std::env::var_os("UPDATEHUB_EMMC_SIMULATOR_STALE_KERNEL").is_some() + } + + #[cfg(any(test, feature = "test-env"))] + pub(super) fn part_config_read(value: u8) { + if stale_kernel() { + CACHED_PART_CONFIG.get_or_init(|| value); + } + } + + #[cfg(not(any(test, feature = "test-env")))] + pub(super) fn part_config_read(_: u8) {} + + #[cfg(any(test, feature = "test-env"))] + pub(super) fn boot_partition_access(device: &Path) -> crate::utils::Result<()> { + let Some(&cached) = CACHED_PART_CONFIG.get().filter(|_| stale_kernel()) else { + return Ok(()); + }; + let name = device.to_string_lossy(); + let Some(base) = name.strip_suffix("boot0").or_else(|| name.strip_suffix("boot1")) else { + return Ok(()); + }; + let mut ext_csd = std::fs::read(base)?; + ext_csd[super::EXT_CSD_PART_CONFIG] = cached; + std::fs::write(base, ext_csd)?; + Ok(()) + } + + #[cfg(not(any(test, feature = "test-env")))] + pub(super) fn boot_partition_access(_: &Path) -> crate::utils::Result<()> { + Ok(()) + } +} + +mod backend { + use super::{EXT_CSD_SIZE, simulator}; + use crate::utils::Result; + use std::{fs, path::Path}; + + pub(super) fn read_ext_csd(device: &Path) -> Result<[u8; EXT_CSD_SIZE]> { + if simulator::active() { + let mut ext_csd = [0; EXT_CSD_SIZE]; + let data = fs::read(device)?; + let len = data.len().min(EXT_CSD_SIZE); + ext_csd[..len].copy_from_slice(&data[..len]); + simulator::part_config_read(ext_csd[super::EXT_CSD_PART_CONFIG]); + return Ok(ext_csd); + } + ioctl::read_ext_csd(device) + } + + pub(super) fn write_ext_csd(device: &Path, index: usize, value: u8) -> Result<()> { + if simulator::active() { + let mut ext_csd = read_ext_csd(device)?; + ext_csd[index] = value; + fs::write(device, ext_csd)?; + return Ok(()); + } + ioctl::write_ext_csd(device, index, value) + } + + /// `MMC_IOC_CMD`, as in `linux/mmc/ioctl.h` and mmc-utils + mod ioctl { + use super::EXT_CSD_SIZE; + use crate::utils::Result; + use std::{fs, os::fd::AsRawFd, path::Path}; + + const MMC_BLOCK_MAJOR: u8 = 179; + + const MMC_RSP_PRESENT: u32 = 1 << 0; + const MMC_RSP_CRC: u32 = 1 << 2; + const MMC_RSP_BUSY: u32 = 1 << 3; + const MMC_RSP_OPCODE: u32 = 1 << 4; + const MMC_CMD_AC: u32 = 0 << 5; + const MMC_CMD_ADTC: u32 = 1 << 5; + const MMC_RSP_SPI_S1: u32 = 1 << 7; + const MMC_RSP_SPI_BUSY: u32 = 1 << 10; + + const MMC_RSP_R1: u32 = MMC_RSP_PRESENT | MMC_RSP_CRC | MMC_RSP_OPCODE; + const MMC_RSP_R1B: u32 = MMC_RSP_R1 | MMC_RSP_BUSY; + const MMC_RSP_SPI_R1: u32 = MMC_RSP_SPI_S1; + const MMC_RSP_SPI_R1B: u32 = MMC_RSP_SPI_S1 | MMC_RSP_SPI_BUSY; + + const MMC_SWITCH: u32 = 6; + const MMC_SEND_EXT_CSD: u32 = 8; + const MMC_SWITCH_MODE_WRITE_BYTE: u32 = 0x03; + const EXT_CSD_CMD_SET_NORMAL: u32 = 1; + + #[repr(C)] + #[derive(Default)] + pub(super) struct MmcIocCmd { + write_flag: i32, + is_acmd: i32, + opcode: u32, + arg: u32, + response: [u32; 4], + flags: u32, + blksz: u32, + blocks: u32, + postsleep_min_us: u32, + postsleep_max_us: u32, + data_timeout_ns: u32, + cmd_timeout_ms: u32, + pad: u32, + data_ptr: u64, + } + + const _: () = assert!(std::mem::size_of::() == 72); + + nix::ioctl_readwrite!(mmc_ioc_cmd, MMC_BLOCK_MAJOR, 0, MmcIocCmd); + + fn run(device: &Path, cmd: &mut MmcIocCmd) -> Result<()> { + let file = fs::OpenOptions::new().read(true).write(true).open(device)?; + // SAFETY: `cmd` matches the kernel's `struct mmc_ioc_cmd`, and its + // data pointer, when set, points at a buffer of `blksz * blocks` + // bytes the caller keeps alive across the call. + unsafe { mmc_ioc_cmd(file.as_raw_fd(), cmd) }?; + Ok(()) + } + + pub(super) fn read_ext_csd(device: &Path) -> Result<[u8; EXT_CSD_SIZE]> { + let mut ext_csd = [0; EXT_CSD_SIZE]; + let mut cmd = MmcIocCmd { + opcode: MMC_SEND_EXT_CSD, + flags: MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC, + blksz: EXT_CSD_SIZE as u32, + blocks: 1, + data_ptr: ext_csd.as_mut_ptr() as u64, + ..Default::default() + }; + run(device, &mut cmd)?; + Ok(ext_csd) + } + + pub(super) fn write_ext_csd(device: &Path, index: usize, value: u8) -> Result<()> { + let mut cmd = MmcIocCmd { + write_flag: 1, + opcode: MMC_SWITCH, + arg: (MMC_SWITCH_MODE_WRITE_BYTE << 24) + | ((index as u32) << 16) + | (u32::from(value) << 8) + | EXT_CSD_CMD_SET_NORMAL, + flags: MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC, + ..Default::default() + }; + run(device, &mut cmd) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + #[test] + fn enabled_partition() { + assert_eq!(enabled_boot_partition(0x00), None); + assert_eq!(enabled_boot_partition(0x08), Some(0)); + assert_eq!(enabled_boot_partition(0x48), Some(0)); + assert_eq!(enabled_boot_partition(0x50), Some(1)); + assert_eq!(enabled_boot_partition(0x38), None, "user area"); + assert_eq!(enabled_boot_partition(0x51), Some(1), "PARTITION_ACCESS is ignored"); + } + + #[test] + fn switching_keeps_only_the_boot_ack() { + assert_eq!(part_config_booting(0x48, 1), 0x50); + assert_eq!(part_config_booting(0x50, 0), 0x48); + assert_eq!(part_config_booting(0x08, 1), 0x10); + // PARTITION_ACCESS (bits 0-2) and reserved bit 7 are not carried over + assert_eq!(part_config_booting(0xc9, 1), 0x50); + } +} diff --git a/updatehub/src/utils/mod.rs b/updatehub/src/utils/mod.rs index 710eff73..a6bc51b0 100644 --- a/updatehub/src/utils/mod.rs +++ b/updatehub/src/utils/mod.rs @@ -4,6 +4,7 @@ pub(crate) mod definitions; pub(crate) mod delta; +pub(crate) mod emmc; pub(crate) mod fs; pub(crate) mod io; pub(crate) mod log; @@ -21,6 +22,17 @@ use std::fmt::Write; pub type Result = std::result::Result; +/// The kernel's ID of the running boot. Test builds take it from +/// `UPDATEHUB_TEST_BOOT_ID`, as their reboots only restart the agent, and +/// have none without it. +pub(crate) fn boot_id() -> Option { + #[cfg(any(test, feature = "test-env"))] + return std::env::var("UPDATEHUB_TEST_BOOT_ID").ok(); + + #[cfg(not(any(test, feature = "test-env")))] + std::fs::read_to_string("/proc/sys/kernel/random/boot_id").ok().map(|id| id.trim().to_owned()) +} + #[derive(Debug, Display, Error, From)] pub enum Error { Io(std::io::Error), @@ -33,6 +45,23 @@ pub enum Error { #[from(ignore)] DeviceDoesNotExist(#[error(not(source))] std::path::PathBuf), + #[display( + "switching {device:?} failed: PARTITION_CONFIG is 0x{found:02x} instead of 0x{expected:02x}" + )] + #[from(ignore)] + EmmcSwitchFailed { + device: std::path::PathBuf, + expected: u8, + found: u8, + }, + + #[display("copying {from:?} to {to:?} did not write the same content")] + #[from(ignore)] + EmmcCopyMismatch { + from: std::path::PathBuf, + to: std::path::PathBuf, + }, + #[display("{_0:?} is a boot-emmc target, which only raw objects support")] #[from(ignore)] UnresolvedBootEmmc(#[error(not(source))] std::path::PathBuf), diff --git a/updatehub/tests/boot_emmc.rs b/updatehub/tests/boot_emmc.rs new file mode 100644 index 00000000..86f3af09 --- /dev/null +++ b/updatehub/tests/boot_emmc.rs @@ -0,0 +1,715 @@ +// Copyright (C) 2026 O.S. Systems Sofware LTDA +// +// SPDX-License-Identifier: Apache-2.0 + +//! A/B firmware in the eMMC boot partitions, end to end, without hardware. +//! +//! The agent binary runs against a simulated eMMC (`UPDATEHUB_EMMC_SIMULATOR`): +//! the boot partitions are files, EXT_CSD is a file, and `force_ro` is +//! enforced. The test plays everything around the agent: the SoC ROM +//! booting the boot partition PARTITION_CONFIG enables, U-Boot keeping the +//! installation set (and rolling it back on its own), power cycles, and the +//! update server. +//! +//! The scenarios run in order on one device, as its history: each starts +//! from the state the previous one left. + +use mockito::{Mock, ServerGuard}; +use serde_json::json; +use std::{ + fs, + io::Write, + net::TcpListener, + os::unix::{ + fs::PermissionsExt, + process::{CommandExt, ExitStatusExt}, + }, + path::{Path, PathBuf}, + process::{Child, Command, ExitStatus, Stdio}, + thread, + time::{Duration, Instant}, +}; + +const BOOT_SIZE: usize = 1024 * 1024; +const FIP_OFFSET: usize = 256 * 1024; +const CHUNK_SIZE: usize = 128 * 1024; +const FSBL_PAYLOAD: usize = 96 * 1024; +const FIP_PAYLOAD: usize = 320 * 1024; +const PART_CONFIG: usize = 179; +const HEADER: usize = 32; + +// ---- firmware, as TF-A + FIP on the STM32MP135 ----------------------------- + +/// A firmware image: magic, kind, version, length, checksum, payload. The +/// ROM refuses an image whose checksum does not match, as the STM32 one does. +fn image(kind: &[u8; 4], version: &str, len: usize) -> Vec { + let seed = version.bytes().chain(kind.iter().copied()).fold(7u8, |a, b| a.wrapping_mul(31) ^ b); + let payload: Vec = + (0..len).map(|i| (i as u8).wrapping_mul(13).wrapping_add(seed) ^ (i >> 8) as u8).collect(); + let mut data = b"UHFW".to_vec(); + data.extend_from_slice(kind); + let mut v = version.as_bytes().to_vec(); + v.resize(16, 0); + data.extend_from_slice(&v); + data.extend_from_slice(&(len as u32).to_le_bytes()); + data.extend_from_slice(&checksum(&payload).to_le_bytes()); + data.extend_from_slice(&payload); + data +} + +fn checksum(data: &[u8]) -> u32 { + data.iter().fold(0u32, |sum, b| sum.wrapping_add(u32::from(*b))) +} + +/// (kind, version) of a complete image at the start of `data` +fn parse(data: &[u8]) -> Option<([u8; 4], String)> { + if data.len() < HEADER || &data[..4] != b"UHFW" { + return None; + } + let kind = data[4..8].try_into().unwrap(); + let version = String::from_utf8_lossy(&data[8..24]).trim_end_matches('\0').to_owned(); + let len = u32::from_le_bytes(data[24..28].try_into().unwrap()) as usize; + let sum = u32::from_le_bytes(data[28..32].try_into().unwrap()); + let payload = data.get(HEADER..HEADER + len)?; + (checksum(payload) == sum).then_some((kind, version)) +} + +struct Firmware { + fsbl: Vec, + fip: Vec, +} + +impl Firmware { + fn new(version: &str) -> Self { + Firmware { + fsbl: image(b"FSBL", version, FSBL_PAYLOAD), + fip: image(b"FIP\0", version, FIP_PAYLOAD), + } + } +} + +// ---- the device: eMMC, ROM and bootloader --------------------------------- + +struct Device { + _dir: tempfile::TempDir, + /// The eMMC base device; in the simulator, its EXT_CSD + emmc: PathBuf, + /// Simulated sysfs, `force_ro` of each boot partition + sysfs: PathBuf, + /// The bootloader environment: the active installation set + active: PathBuf, + /// Makes the next validation of an update fail + fail_validation: PathBuf, + /// Where the system half of an update goes + rootfs: PathBuf, +} + +impl Device { + /// A device as the installer leaves it: both boot partitions hold the + /// same firmware, boot0 is enabled, installation set 0 is active. + fn factory(firmware: &Firmware) -> Self { + let dir = tempfile::tempdir().unwrap(); + let emmc = dir.path().join("mmcblk0"); + let sysfs = dir.path().join("sys"); + + let mut ext_csd = vec![0u8; 512]; + ext_csd[PART_CONFIG] = 0x48; // boot0, boot acknowledge + fs::write(&emmc, ext_csd).unwrap(); + + let device = Device { + emmc, + sysfs, + active: dir.path().join("active"), + fail_validation: dir.path().join("fail-validation"), + rootfs: dir.path().join("rootfs"), + _dir: dir, + }; + fs::write(&device.rootfs, vec![0u8; CHUNK_SIZE]).unwrap(); + for n in 0..2 { + let mut data = vec![0u8; BOOT_SIZE]; + data[..firmware.fsbl.len()].copy_from_slice(&firmware.fsbl); + data[FIP_OFFSET..FIP_OFFSET + firmware.fip.len()].copy_from_slice(&firmware.fip); + fs::write(device.boot_partition(n), data).unwrap(); + let sys = device.sysfs.join(format!("mmcblk0boot{n}")); + fs::create_dir_all(&sys).unwrap(); + fs::write(sys.join("force_ro"), "1\n").unwrap(); + } + device.set_active(0); + device + } + + fn lock(&self) { + for n in 0..2 { + fs::write(self.sysfs.join(format!("mmcblk0boot{n}/force_ro")), "1\n").unwrap(); + } + } + + fn boot_partition(&self, n: u8) -> PathBuf { + PathBuf::from(format!("{}boot{n}", self.emmc.display())) + } + + fn part_config(&self) -> u8 { + fs::read(&self.emmc).unwrap()[PART_CONFIG] + } + + fn set_part_config(&self, value: u8) { + let mut ext_csd = fs::read(&self.emmc).unwrap(); + ext_csd[PART_CONFIG] = value; + fs::write(&self.emmc, ext_csd).unwrap(); + } + + fn enabled(&self) -> Option { + match (self.part_config() >> 3) & 7 { + 1 => Some(0), + 2 => Some(1), + _ => None, + } + } + + fn force_ro(&self, n: u8) -> String { + fs::read_to_string(self.sysfs.join(format!("mmcblk0boot{n}/force_ro"))) + .unwrap() + .trim() + .to_owned() + } + + /// Version of the complete firmware in boot partition `n` + fn firmware(&self, n: u8) -> Option { + let data = fs::read(self.boot_partition(n)).unwrap(); + let (fsbl_kind, fsbl) = parse(&data)?; + let (fip_kind, fip) = parse(&data[FIP_OFFSET..])?; + (&fsbl_kind == b"FSBL" && &fip_kind == b"FIP\0" && fsbl == fip).then_some(fsbl) + } + + fn active(&self) -> u8 { + fs::read_to_string(&self.active).unwrap().trim().parse().unwrap() + } + + /// What U-Boot does when it rolls back, without the agent knowing + fn set_active(&self, set: u8) { + fs::write(&self.active, format!("{set}\n")).unwrap(); + } + + /// What the ROM boots: (boot partition, firmware version). A device + /// whose enabled boot partition holds no complete firmware is bricked. + fn rom(&self) -> (u8, String) { + let part = self.enabled().unwrap_or_else(|| { + panic!("ROM: PARTITION_CONFIG 0x{:02x} enables no boot partition", self.part_config()) + }); + let version = self + .firmware(part) + .unwrap_or_else(|| panic!("ROM: boot{part} has no complete firmware, bricked")); + (part, version) + } +} + +// ---- the agent -------------------------------------------------------------- + +struct Agent { + child: Child, +} + +struct Harness { + setup: updatehub::tests::TestEnvironment, + device: Device, + server: ServerGuard, + mocks: Vec, + listen: String, + log: PathBuf, + agent: Option, + /// Power-ons so far, which name the kernel's boot ID + boots: usize, + runtime: tokio::runtime::Runtime, +} + +impl Harness { + fn new() -> Self { + let device = Device::factory(&Firmware::new("1.0")); + let server = mockito::Server::new(); + // The agent listens on IPv4 whatever `localhost` resolves to + let port = (8080..65535).find(|p| TcpListener::bind(("127.0.0.1", *p)).is_ok()).unwrap(); + let listen = format!("127.0.0.1:{port}"); + + let setup = updatehub::tests::TestEnvironment::build() + .listen_socket(listen.clone()) + .server_address(server.url()) + .disable_polling() + .supported_install_modes(vec!["raw"]) + .add_echo_binary("reboot") + .finish(); + + // The bootloader environment holds the installation set + let bin = &setup.binaries.stored_path; + script(&bin.join("updatehub-active-get"), &format!("cat {}", device.active.display())); + script( + &bin.join("updatehub-active-set"), + &format!("echo $1 > {}", device.active.display()), + ); + script( + &setup.firmware.stored_path.join("validate-callback"), + &format!("test ! -e {}", device.fail_validation.display()), + ); + + let mut settings = + fs::OpenOptions::new().append(true).open(&setup.settings.stored_path).unwrap(); + write!(settings, "\n\n[firmware.boot-emmc]\ndevice=\"{}\"\n", device.emmc.display()) + .unwrap(); + + let log = setup.binaries.stored_path.join("agent.log"); + let mut harness = Harness { + setup, + device, + server, + mocks: Vec::new(), + listen, + log, + agent: None, + boots: 0, + runtime: tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(), + }; + harness.no_update(); + harness + } + + /// Powers the device on: the ROM picks the firmware, then the system + /// starts the agent. Returns what the ROM booted. + fn power_on(&mut self) -> (u8, String) { + self.power_on_with(&[]) + } + + fn power_on_with(&mut self, env: &[(&str, &str)]) -> (u8, String) { + assert!(self.agent.is_none(), "already powered on"); + let booted = self.device.rom(); + // The kernel makes boot partitions read-only at every boot + self.device.lock(); + self.boots += 1; + self.start_agent(env); + booted + } + + /// Starts the agent again without the device rebooting + fn restart_agent(&mut self) { + assert!(self.agent.is_none(), "already running"); + self.start_agent(&[]); + } + + fn start_agent(&mut self, env: &[(&str, &str)]) { + let log = fs::File::create(&self.log).unwrap(); + + let mut cmd = Command::new(env!("CARGO_BIN_EXE_updatehub")); + cmd.args(["daemon", "-v", "trace", "-c"]) + .arg(&self.setup.settings.stored_path) + .env("UPDATEHUB_EMMC_SIMULATOR", &self.device.sysfs) + .env("UPDATEHUB_TEST_BOOT_ID", format!("boot-{}", self.boots)) + .stdout(Stdio::from(log.try_clone().unwrap())) + .stderr(Stdio::from(log)); + for (k, v) in env { + cmd.env(k, v); + } + // The agent must never outlive the test: once the test is gone, so + // is the fake `reboot` it relies on, and the next reboot it asks for + // would be the real one, rebooting the machine running the tests. + // SAFETY: prctl is async-signal-safe and touches no shared state. + unsafe { + cmd.pre_exec(|| { + nix::sys::prctl::set_pdeathsig(nix::sys::signal::Signal::SIGKILL)?; + Ok(()) + }); + } + self.agent = Some(Agent { child: cmd.spawn().unwrap() }); + + // A start may reboot right away (a failed validation), or serve + let deadline = Instant::now() + Duration::from_secs(30); + while Instant::now() < deadline { + let agent = &mut self.agent.as_mut().unwrap().child; + if let Some(status) = agent.try_wait().unwrap() { + panic!("the agent exited with {status}:\n{}", self.agent_log()); + } + if self.reboots() > 0 || self.serving() { + return; + } + thread::sleep(Duration::from_millis(100)); + } + panic!("the agent did not start:\n{}", self.agent_log()); + } + + /// Whether this test's agent answers, not another one on the same port + fn serving(&self) -> bool { + let client = sdk::Client::new(&self.listen); + self.runtime + .block_on(client.info()) + .is_ok_and(|info| info.runtime_settings.path == self.setup.runtime_settings.stored_path) + } + + /// The update the device waits to validate, if any + fn pending(&self) -> Option { + let runtime: serde_json::Value = serde_json::from_str( + &fs::read_to_string(&self.setup.runtime_settings.stored_path).ok()?, + ) + .unwrap(); + runtime["update"]["upgrade_to_installation"].as_str().map(str::to_owned) + } + + /// The agent rebooted (the `reboot` binary records itself), or the + /// power was cut: the device is off. + fn power_off(&mut self) { + if let Some(mut agent) = self.agent.take() { + let _ = agent.child.kill(); + let _ = agent.child.wait(); + } + let output = &self.setup.binaries.data; + fs::write(output, "").unwrap(); + } + + fn reboots(&self) -> usize { + fs::read_to_string(&self.setup.binaries.data) + .unwrap_or_default() + .lines() + .filter(|l| l.starts_with("reboot")) + .count() + } + + /// Waits for the reboot that installing an update ends with + fn wait_for_reboot(&mut self) { + self.wait_for_reboot_after("triggering reboot"); + } + + /// Waits for a reboot, and for the agent to have logged `last` before + /// it: the log is written asynchronously, and what is still queued when + /// the power goes off is lost. + fn wait_for_reboot_after(&mut self, last: &str) { + let deadline = Instant::now() + Duration::from_secs(60); + while self.reboots() == 0 { + assert!(Instant::now() < deadline, "no reboot, agent log:\n{}", self.agent_log()); + thread::sleep(Duration::from_millis(100)); + } + self.wait_for_log(last); + self.power_off(); + self.no_update(); + } + + /// The server has nothing for the device, as once it reported the + /// update installed + fn no_update(&mut self) { + for mock in self.mocks.drain(..) { + mock.remove(); + } + self.mocks.push(self.server.mock("POST", "/upgrades").with_status(404).create()); + } + + fn wait_for_exit(&mut self) -> ExitStatus { + let agent = self.agent.as_mut().expect("powered off"); + let deadline = Instant::now() + Duration::from_secs(60); + let status = loop { + if let Some(status) = agent.child.try_wait().unwrap() { + break status; + } + assert!(Instant::now() < deadline, "the agent kept running"); + thread::sleep(Duration::from_millis(100)); + }; + self.power_off(); + status + } + + fn wait_for_log(&self, text: &str) { + let deadline = Instant::now() + Duration::from_secs(60); + while !self.agent_log().contains(text) { + assert!(Instant::now() < deadline, "no {text:?} in agent log:\n{}", self.agent_log()); + thread::sleep(Duration::from_millis(100)); + } + } + + fn agent_log(&self) -> String { + fs::read_to_string(&self.log).unwrap_or_default() + } + + /// Publishes `version`, carrying `firmware`'s images for `target`, and + /// asks the agent to probe for it. + fn update(&mut self, version: &str, firmware: &str, target: &Path) { + let fw = Firmware::new(firmware); + let object = |name: &str, data: &[u8], seek: usize| { + json!({ + "mode": "raw", + "filename": format!("{name}-{firmware}.bin"), + "size": data.len(), + "sha256sum": sha256(data), + "install-if-different": "sha256sum", + "target-type": "boot-emmc", + "target": target, + "chunk-size": CHUNK_SIZE, + "seek": seek / CHUNK_SIZE, + "count": -1, + "truncate": false, + }) + }; + let set = json!([object("fsbl", &fw.fsbl, 0), object("fip", &fw.fip, FIP_OFFSET)]); + self.publish(version, set, vec![fw.fsbl.clone(), fw.fip.clone()]); + } + + /// Publishes `version`, carrying only a system image, and asks the agent + /// to probe for it. + fn update_system(&mut self, version: &str) { + let rootfs = version.as_bytes().repeat(CHUNK_SIZE / version.len()); + let set = json!([{ + "mode": "raw", + "filename": format!("rootfs-{version}.bin"), + "size": rootfs.len(), + "sha256sum": sha256(&rootfs), + "target-type": "device", + "target": self.device.rootfs, + "chunk-size": CHUNK_SIZE, + "count": -1, + }]); + self.publish(version, set, vec![rootfs]); + } + + fn publish(&mut self, version: &str, set: serde_json::Value, objects: Vec>) { + for mock in self.mocks.drain(..) { + mock.remove(); + } + + let metadata = json!({ + "product": self.setup.firmware.data.product_uid, + "version": version, + "supported-hardware": ["board"], + "objects": [set, set], + }) + .to_string(); + let package_uid = sha256(metadata.as_bytes()); + + self.mocks.push( + self.server.mock("POST", "/upgrades").with_status(200).with_body(&metadata).create(), + ); + for data in &objects { + self.mocks.push( + self.server + .mock( + "GET", + format!( + "/products/{}/packages/{package_uid}/objects/{}", + self.setup.firmware.data.product_uid, + sha256(data) + ) + .as_str(), + ) + .with_status(200) + .with_body(data) + .create(), + ); + } + + let client = sdk::Client::new(&self.listen); + self.runtime.block_on(client.probe(None)).expect("probe failed"); + } +} + +impl Drop for Harness { + fn drop(&mut self) { + self.power_off(); + } +} + +fn script(path: &Path, body: &str) { + fs::write(path, format!("#!/bin/sh\n{body}\n")).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap(); +} + +fn sha256(data: &[u8]) -> String { + openssl::sha::sha256(data).iter().map(|b| format!("{b:02x}")).collect() +} + +#[track_caller] +fn assert_booted(h: &Harness, booted: (u8, String), part: u8, version: &str, set: u8) { + let log = h.agent_log(); + assert_eq!(booted, (part, version.to_owned()), "ROM booted the wrong firmware\n{log}"); + assert_eq!(h.device.active(), set, "wrong installation set\n{log}"); + assert_eq!(h.device.enabled(), Some(part), "PARTITION_CONFIG moved\n{log}"); +} + +#[track_caller] +fn assert_locked(h: &Harness) { + assert_eq!(h.device.force_ro(0), "1", "boot0 left writable"); + assert_eq!(h.device.force_ro(1), "1", "boot1 left writable"); +} + +#[test] +fn boot_partitions_follow_the_installation_set() { + let mut h = Harness::new(); + let emmc = h.device.emmc.clone(); + + // Factory state: both boot partitions hold 1.0, boot0 enabled, set 0 + let booted = h.power_on(); + assert_booted(&h, booted, 0, "1.0", 0); + + // An update writes the inactive set's boot partition and boots it + h.update("2.0", "2.0", &emmc); + h.wait_for_reboot(); + assert_eq!(h.device.firmware(0).as_deref(), Some("1.0"), "the running firmware was touched"); + assert_locked(&h); + // An agent restarting before the reboot does not validate the update + h.restart_agent(); + h.wait_for_log("the installed update waits for the device to reboot"); + h.power_off(); + assert_eq!(h.pending().as_deref(), Some("b"), "the update was validated without booting"); + let booted = h.power_on(); + assert_booted(&h, booted, 1, "2.0", 1); + h.wait_for_log("booting from a recent installation"); + assert_eq!(h.pending(), None); + h.power_off(); + + // A failed validation rolls the firmware back with the system + fs::write(&h.device.fail_validation, "").unwrap(); + let booted = h.power_on(); + assert_booted(&h, booted, 1, "2.0", 1); + h.update("3.0", "3.0", &emmc); + h.wait_for_reboot(); + let booted = h.power_on(); + assert_eq!(booted, (0, "3.0".to_owned()), "the new firmware boots first"); + h.wait_for_reboot_after("swapped active installation set and running rollback"); + fs::remove_file(&h.device.fail_validation).unwrap(); + let booted = h.power_on(); + assert_booted(&h, booted, 1, "2.0", 1); + h.power_off(); + + // A bootloader rollback (boot counter) brings the firmware back + let _ = h.power_on(); + h.update("4.0", "4.0", &emmc); + h.wait_for_reboot(); + h.device.set_active(1); + let booted = h.power_on(); + assert_eq!(booted, (0, "4.0".to_owned())); + h.wait_for_log("agent start: installation set 1 is active"); + assert_eq!(h.device.enabled(), Some(1), "PARTITION_CONFIG did not follow the set"); + assert_eq!(h.reboots(), 0, "a rolled back update needs no reboot"); + h.power_off(); + let booted = h.power_on(); + assert_booted(&h, booted, 1, "2.0", 1); + + // An update starts from the running firmware: boot0 gets 2.0 over the + // 4.0 it held, and the same firmware is not written again + h.update("2.0-r1", "2.0", &emmc); + h.wait_for_reboot(); + let skipped = h.agent_log().matches("has been skipped (install if different)").count(); + assert_eq!(skipped, 2, "agent log:\n{}", h.agent_log()); + let booted = h.power_on(); + assert_booted(&h, booted, 0, "2.0", 0); + h.power_off(); + + // A power cut while writing the firmware keeps the device booting + let _ = h.power_on_with(&[("UPDATEHUB_TEST_POWER_CUT_AFTER", "65536")]); + h.update("5.0", "5.0", &emmc); + assert_eq!(h.wait_for_exit().signal(), Some(nix::libc::SIGABRT)); + let (old, new) = (Firmware::new("2.0"), Firmware::new("5.0")); + let boot1 = fs::read(h.device.boot_partition(1)).unwrap(); + let fip = &boot1[FIP_OFFSET..FIP_OFFSET + new.fip.len()]; + assert_eq!(&boot1[..old.fsbl.len()], &old.fsbl[..], "the FSBL was not written yet"); + assert!(fip[..65536] == new.fip[..65536], "the FIP was written up to the power cut"); + assert!(fip[65536..] == old.fip[65536..], "the FIP was written past the power cut"); + let booted = h.power_on(); + assert_booted(&h, booted, 0, "2.0", 0); + // and the update goes through on the next try + h.update("5.0", "5.0", &emmc); + h.wait_for_reboot(); + assert_locked(&h); + let booted = h.power_on(); + assert_booted(&h, booted, 1, "5.0", 1); + + // A package for another eMMC is refused before anything is written + h.update("6.0", "6.0", Path::new("/dev/mmcblk7")); + h.wait_for_log("the device uses"); + assert_eq!(h.reboots(), 0); + assert_eq!(h.device.firmware(0).as_deref(), Some("2.0")); + assert_eq!(h.device.enabled(), Some(1)); + h.power_off(); + + // A device booting from the boot partition the update writes is left + // alone on start, and repaired first by the update, with a warning: its + // firmware moves to the other boot partition, which the eMMC then boots + // from + h.device.set_part_config(0x48); // boot0, the inactive set's + let booted = h.power_on(); + assert_eq!(booted, (0, "2.0".to_owned())); + assert_eq!(h.device.enabled(), Some(0), "the agent switched without an update pending"); + h.update("6.0", "6.0", &emmc); + h.wait_for_reboot(); + let log = h.agent_log(); + assert!(log.contains("is about to be overwritten by this update"), "agent log:\n{log}"); + assert_eq!(h.device.firmware(1).as_deref(), Some("2.0"), "the booted firmware was not kept"); + assert_locked(&h); + let booted = h.power_on(); + assert_booted(&h, booted, 0, "6.0", 0); + + // An update without firmware keeps the running one: boot1 held 2.0 + h.update_system("7.0"); + h.wait_for_reboot(); + assert_locked(&h); + let booted = h.power_on(); + assert_booted(&h, booted, 1, "6.0", 1); + h.wait_for_log("booting from a recent installation"); + h.power_off(); + + // A power cut between switching the installation set and the eMMC + // boots the previous firmware once: the agent then switches the eMMC + // and reboots, so the update is validated with its own firmware + let _ = h.power_on(); + h.update("8.0", "8.0", &emmc); + h.wait_for_reboot(); + h.device.set_part_config(0x50); // boot1, as before the update + let booted = h.power_on(); + assert_eq!(booted, (1, "6.0".to_owned())); + h.wait_for_reboot_after("rebooting so the update is validated running its own firmware"); + let booted = h.power_on(); + assert_booted(&h, booted, 0, "8.0", 0); + h.wait_for_log("booting from a recent installation"); + + // When the eMMC does not keep booting the update's firmware, the agent + // reboots for it only once, then rolls the update back + h.update("9.0", "9.0", &emmc); + h.wait_for_reboot(); + h.device.set_part_config(0x48); // reset to boot0 on every boot + let booted = h.power_on(); + assert_eq!(booted, (0, "8.0".to_owned())); + h.wait_for_reboot_after("rebooting so the update is validated running its own firmware"); + h.device.set_part_config(0x48); + let booted = h.power_on(); + assert_eq!(booted, (0, "8.0".to_owned())); + h.wait_for_reboot_after("swapped active installation set and running rollback"); + let booted = h.power_on(); + assert_booted(&h, booted, 0, "8.0", 0); + h.power_off(); + + // A kernel writing its cached PARTITION_CONFIG back once the update + // writes the boot partition fails the update, and the eMMC goes back to + // the firmware it was running + h.device.set_part_config(0x50); // boot1, the inactive set's + let booted = h.power_on_with(&[("UPDATEHUB_EMMC_SIMULATOR_STALE_KERNEL", "1")]); + assert_eq!(booted, (1, "9.0".to_owned())); + h.update("10.0", "10.0", &emmc); + h.wait_for_log("restored its cached PARTITION_CONFIG"); + assert_eq!(h.reboots(), 0); + assert_eq!(h.device.enabled(), Some(0), "the eMMC boots the partition just written"); + assert_eq!(h.device.firmware(0).as_deref(), Some("9.0"), "the booted firmware was not kept"); + h.power_off(); + + // An update pending from an agent without boot-emmc support never + // wrote the boot partition of its set, so the eMMC stays where it is + let _ = h.power_on(); + h.update("11.0", "11.0", &emmc); + h.wait_for_reboot(); + let path = &h.setup.runtime_settings.stored_path; + let mut runtime: serde_json::Value = + serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap(); + runtime["update"].as_object_mut().unwrap().remove("boot_emmc").unwrap(); + fs::write(path, runtime.to_string()).unwrap(); + h.device.set_part_config(0x48); + let booted = h.power_on(); + assert_eq!(booted, (0, "9.0".to_owned())); + h.wait_for_log("booting from a recent installation"); + assert_eq!( + h.device.enabled(), + Some(0), + "the eMMC switched for an update that did not write it" + ); + assert_eq!(h.pending(), None); + h.power_off(); +}