diff --git a/services/ocp-recovery/agent/BUILD.bazel b/services/ocp-recovery/agent/BUILD.bazel new file mode 100644 index 000000000..4175905bb --- /dev/null +++ b/services/ocp-recovery/agent/BUILD.bazel @@ -0,0 +1,23 @@ +# Licensed under the Apache-2.0 license +# SPDX-License-Identifier: Apache-2.0 + +load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test") + +rust_library( + name = "ocp_recovery_agent", + srcs = glob(["src/**/*.rs"]), + crate_name = "openprot_ocp_recovery_agent", + edition = "2024", + visibility = ["//visibility:public"], + deps = [ + "//services/ocp-recovery/api:ocp_recovery_api", + "@rust_crates//:zerocopy", + ], +) + +# Host tests against a scripted device: build on the host platform, no +# kernel/QEMU. +rust_test( + name = "ocp_recovery_agent_test", + crate = ":ocp_recovery_agent", +) diff --git a/services/ocp-recovery/agent/src/lib.rs b/services/ocp-recovery/agent/src/lib.rs new file mode 100644 index 000000000..46c2a7cb4 --- /dev/null +++ b/services/ocp-recovery/agent/src/lib.rs @@ -0,0 +1,280 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +//! The Recovery Agent side of OCP Secure Firmware Recovery, version 1.2. +//! +//! The Recovery Agent reads the recovery registers of the device through +//! [`RegisterAccess`], which the transport implements. The crate decodes +//! each response with the register layouts of `openprot_ocp_recovery_api`, +//! so a read returns the decoded register or an [`AgentError`] that names +//! the command. + +#![cfg_attr(not(test), no_std)] +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +use openprot_ocp_recovery_api::regs::{ + DeviceStatus, ImageIndex, ProtCap, RecoveryState, RecoveryStatus, +}; +use openprot_ocp_recovery_api::RecoveryCommand; +use zerocopy::FromBytes; + +#[cfg(test)] +mod script; + +/// The register accesses the Recovery Agent makes to the device. +/// +/// The transport implements `RegisterAccess` and adds its framing, such as +/// the SMBus PEC. +pub trait RegisterAccess { + /// Why an access did not complete, for example a bus fault. + type Error; + + /// Reads `command`. When the access completes, `read` calls `parse` + /// once with the register bytes of the response, without the framing + /// of the transport, such as the SMBus byte count or the PEC. When the + /// access fails, `read` returns the error of the transport. + /// + /// The response stays in the receive buffer of the transport, so the + /// Recovery Agent needs no buffer for the longest response the command + /// table allows. + fn read( + &mut self, + command: RecoveryCommand, + parse: impl FnOnce(&[u8]) -> T, + ) -> Result; +} + +/// Why a register access of the Recovery Agent failed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AgentError { + /// The access to `command` did not complete. + Access { + /// The command of the access, so a caller can tell which access + /// failed without a record of the step. + command: RecoveryCommand, + /// The error of the transport, which the Recovery Agent passes on + /// unchanged. + error: E, + }, + /// The device returned a response the register layout refuses: the + /// wrong length, a value the spec marks "Reserved" or does not define, + /// or for `PROT_CAP` a magic string or major version that + /// [`ProtCap::parse`] refuses. + Malformed(RecoveryCommand), +} + +impl core::fmt::Display for AgentError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Access { command, error } => write!(f, "{command:?} access failed: {error}"), + Self::Malformed(command) => write!(f, "{command:?} response is malformed"), + } + } +} + +impl core::error::Error for AgentError {} + +/// Reads `PROT_CAP`. `read_prot_cap` returns [`AgentError::Malformed`] +/// for each response that [`ProtCap::parse`] refuses. A response with +/// another minor version parses. +pub fn read_prot_cap(regs: &mut R) -> Result> { + read(regs, RecoveryCommand::ProtCap, ProtCap::parse) +} + +/// Reads `DEVICE_STATUS` bytes 0 to 6. +/// +/// The read clears the protocol error in byte 1 on the device, so the +/// returned `DeviceStatus` holds the only copy of the error. The device +/// also clears byte 1 for a response that `read_device_status` refuses +/// with [`AgentError::Malformed`], so the caller then holds no copy of +/// the protocol error. +pub fn read_device_status( + regs: &mut R, +) -> Result> { + read(regs, RecoveryCommand::DeviceStatus, DeviceStatus::parse) +} + +/// Reads `RECOVERY_STATUS` and returns the state and the image the state +/// refers to. `read_recovery_status` drops the vendor status byte, and +/// returns [`AgentError::Malformed`] for a response of a length other than +/// [`RecoveryStatus::SIZE`] or a state the spec does not define. +pub fn read_recovery_status( + regs: &mut R, +) -> Result<(RecoveryState, ImageIndex), AgentError> { + read(regs, RecoveryCommand::RecoveryStatus, |bytes| { + let status = RecoveryStatus::read_from_bytes(bytes).ok()?; + Some((status.state()?, status.image())) + }) +} + +/// Reads `command` and decodes the response with `parse`, which returns +/// `None` for a response the register layout refuses. +fn read( + regs: &mut R, + command: RecoveryCommand, + parse: impl FnOnce(&[u8]) -> Option, +) -> Result> { + regs.read(command, parse) + .map_err(|error| AgentError::Access { command, error })? + .ok_or(AgentError::Malformed(command)) +} + +#[cfg(test)] +mod tests { + use openprot_ocp_recovery_api::regs::{ + HeartbeatPeriod, MaxResponseTime, ReasonCode, RecoveryReason, ReportedState, + }; + use openprot_ocp_recovery_api::Capabilities; + use zerocopy::IntoBytes; + + use super::*; + use crate::script::{BusFault, Expect, ScriptedDevice}; + + /// The CMS count of the test `PROT_CAP`. No test reads a CMS, so any + /// count works. + const TEST_CMS_COUNT: u8 = 1; + + /// A `PROT_CAP` that advertises `capabilities`. + fn prot_cap(capabilities: Capabilities) -> ProtCap { + ProtCap::new( + capabilities, + TEST_CMS_COUNT, + MaxResponseTime { exponent: 0 }, + HeartbeatPeriod::NOT_SUPPORTED, + ) + } + + /// Runs `read_fn` against a device that returns `response` to a read of + /// `command`. + fn read_response( + command: RecoveryCommand, + response: &[u8], + read_fn: impl FnOnce(&mut ScriptedDevice) -> T, + ) -> T { + let mut device = ScriptedDevice::new([Expect::Read(command, response.to_vec())]); + let result = read_fn(&mut device); + device.assert_done(); + result + } + + #[test] + fn read_prot_cap_returns_the_capabilities_the_device_advertises() { + let capabilities = Capabilities::DEVICE_STATUS | Capabilities::PUSH_C_IMAGE; + let cap = prot_cap(capabilities); + let read = read_response(RecoveryCommand::ProtCap, cap.as_bytes(), read_prot_cap); + assert_eq!(read.unwrap().capabilities(), capabilities); + } + + #[test] + fn read_prot_cap_refuses_another_magic_string() { + let cap = prot_cap(Capabilities::PUSH_C_IMAGE); + let mut response = cap.as_bytes().to_vec(); + response[0] = b'X'; + let read = read_response(RecoveryCommand::ProtCap, &response, read_prot_cap); + assert_eq!( + read.unwrap_err(), + AgentError::Malformed(RecoveryCommand::ProtCap) + ); + } + + #[test] + fn read_device_status_decodes_bytes_0_to_6_and_skips_the_vendor_status() { + // RecoveryModeReady with reason code 0x12 (FlashlessStreamingBoot), + // and byte 6 announces the 2 bytes of vendor status that follow. + let response = [0x03, 0x00, 0x12, 0x00, 0x00, 0x00, 0x02, 0xaa, 0xbb]; + let read = read_response(RecoveryCommand::DeviceStatus, &response, read_device_status); + assert_eq!( + read.unwrap().reported(), + ReportedState::RecoveryModeReady(ReasonCode::spec( + RecoveryReason::FlashlessStreamingBoot + )) + ); + } + + #[test] + fn read_device_status_refuses_a_reserved_state() { + // Device state 0x06, which section 9.2 marks "Reserved" and gives no + // meaning. + let response = [0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + let read = read_response(RecoveryCommand::DeviceStatus, &response, read_device_status); + assert_eq!( + read.unwrap_err(), + AgentError::Malformed(RecoveryCommand::DeviceStatus) + ); + } + + #[test] + fn read_recovery_status_splits_the_state_and_the_image_index() { + // Awaiting recovery image (0x1) in bits 0 to 3, image index 2 in bits + // 4 to 7. + let read = read_response( + RecoveryCommand::RecoveryStatus, + &[0x21, 0x00], + read_recovery_status, + ); + assert_eq!( + read.unwrap(), + (RecoveryState::AwaitingImage, ImageIndex::new(2).unwrap()) + ); + } + + #[test] + fn read_recovery_status_refuses_a_state_the_spec_does_not_define() { + // State 0x4, for which section 9.2 gives no meaning. + let read = read_response( + RecoveryCommand::RecoveryStatus, + &[0x04, 0x00], + read_recovery_status, + ); + assert_eq!( + read.unwrap_err(), + AgentError::Malformed(RecoveryCommand::RecoveryStatus) + ); + } + + #[test] + fn read_recovery_status_refuses_a_short_or_long_response() { + // State 0x1 (awaiting recovery image) is valid, so only the length + // makes the response malformed. + let short = [0x01; RecoveryStatus::SIZE - 1]; + let long = [0x01; RecoveryStatus::SIZE + 1]; + for response in [&short[..], &long[..]] { + let read = read_response( + RecoveryCommand::RecoveryStatus, + response, + read_recovery_status, + ); + assert_eq!( + read.unwrap_err(), + AgentError::Malformed(RecoveryCommand::RecoveryStatus), + "response of {} bytes", + response.len() + ); + } + } + + #[test] + fn a_bus_fault_names_the_command_of_the_access() { + let mut device = ScriptedDevice::new([Expect::Fault(RecoveryCommand::DeviceStatus)]); + assert_eq!( + read_device_status(&mut device).unwrap_err(), + AgentError::Access { + command: RecoveryCommand::DeviceStatus, + error: BusFault, + } + ); + device.assert_done(); + } + + #[test] + fn agent_error_display_names_the_command() { + let access = AgentError::Access { + command: RecoveryCommand::DeviceStatus, + error: BusFault, + }; + assert_eq!(access.to_string(), "DeviceStatus access failed: bus fault"); + let malformed = AgentError::::Malformed(RecoveryCommand::ProtCap); + assert_eq!(malformed.to_string(), "ProtCap response is malformed"); + } +} diff --git a/services/ocp-recovery/agent/src/script.rs b/services/ocp-recovery/agent/src/script.rs new file mode 100644 index 000000000..06eeac252 --- /dev/null +++ b/services/ocp-recovery/agent/src/script.rs @@ -0,0 +1,86 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +//! A scripted device for the unit tests. A test lists the accesses it +//! expects from the Recovery Agent, in order, with the response of each read. + +use std::collections::VecDeque; + +use openprot_ocp_recovery_api::RecoveryCommand; + +use crate::RegisterAccess; + +/// The transport lost the device during the access. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BusFault; + +impl core::fmt::Display for BusFault { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("bus fault") + } +} + +/// An access the test expects from the Recovery Agent. +#[derive(Debug)] +pub enum Expect { + /// A read of the command, and the bytes of the response the device + /// returns. + Read(RecoveryCommand, Vec), + /// An access to the command that fails with [`BusFault`]. + Fault(RecoveryCommand), +} + +/// Serves the accesses of a test in the order the test lists them. +/// +/// An access the test did not list next fails the test. +pub struct ScriptedDevice { + expected: VecDeque, +} + +impl ScriptedDevice { + pub fn new(expected: impl IntoIterator) -> Self { + Self { + expected: expected.into_iter().collect(), + } + } + + /// Fails the test if the Recovery Agent skipped an access the test + /// listed. + pub fn assert_done(&self) { + assert!( + self.expected.is_empty(), + "accesses left: {:?}", + self.expected + ); + } + + fn next(&mut self, command: RecoveryCommand) -> Expect { + let expected = self + .expected + .pop_front() + .expect("the test lists no further access"); + let listed = match &expected { + Expect::Read(listed, _) | Expect::Fault(listed) => *listed, + }; + assert_eq!( + command, listed, + "the Recovery Agent accessed another command" + ); + expected + } +} + +impl RegisterAccess for ScriptedDevice { + type Error = BusFault; + + fn read( + &mut self, + command: RecoveryCommand, + parse: impl FnOnce(&[u8]) -> T, + ) -> Result { + match self.next(command) { + Expect::Read(_, response) => Ok(parse(&response)), + Expect::Fault(_) => Err(BusFault), + } + } +} diff --git a/services/ocp-recovery/api/src/regs/device_status.rs b/services/ocp-recovery/api/src/regs/device_status.rs index 8db08977a..2852909c8 100644 --- a/services/ocp-recovery/api/src/regs/device_status.rs +++ b/services/ocp-recovery/api/src/regs/device_status.rs @@ -343,6 +343,21 @@ impl DeviceStatus { } } +/// Operations only the Recovery Agent performs. +impl DeviceStatus { + /// Reads bytes 0 to 6 of `DEVICE_STATUS` as a Recovery Agent receives + /// them. + /// + /// `parse` returns `None` if `bytes` is shorter than [`Self::SIZE`], or + /// if byte 0 or byte 1 holds a value that section 9.2 marks "Reserved". + /// `parse` skips the vendor status after byte 6 and does not compare its + /// length with byte 6. + pub fn parse(bytes: &[u8]) -> Option { + let (status, _vendor_status) = Self::try_read_from_prefix(bytes).ok()?; + Some(status) + } +} + const _: () = assert!(struct_matches_command_table::( RecoveryCommand::DeviceStatus )); @@ -529,4 +544,25 @@ mod tests { assert_eq!(decode(0xff), DecodedReason::Vendor(0xff)); assert_eq!(decode(0x100), DecodedReason::Reserved(0x100)); } + + #[test] + fn parse_skips_the_vendor_status() { + // RecoveryModeReady with reason code 0x12 (FlashlessStreamingBoot), + // and byte 6 announces the 2 bytes of vendor status that follow. + let bytes = [0x03, 0x00, 0x12, 0x00, 0x00, 0x00, 0x02, 0xaa, 0xbb]; + let status = DeviceStatus::parse(&bytes).unwrap(); + assert_eq!( + status.reported(), + ReportedState::RecoveryModeReady(ReasonCode::spec( + RecoveryReason::FlashlessStreamingBoot + )) + ); + } + + #[test] + fn parse_refuses_a_response_without_byte_6() { + let bytes = [0u8; DeviceStatus::SIZE]; + assert!(DeviceStatus::parse(&bytes).is_some()); + assert!(DeviceStatus::parse(&bytes[..DeviceStatus::SIZE - 1]).is_none()); + } }