Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions services/ocp-recovery/agent/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -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",
)
280 changes: 280 additions & 0 deletions services/ocp-recovery/agent/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<T>(
&mut self,
command: RecoveryCommand,
parse: impl FnOnce(&[u8]) -> T,
) -> Result<T, Self::Error>;
}

/// Why a register access of the Recovery Agent failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentError<E> {
/// 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<E: core::fmt::Display> core::fmt::Display for AgentError<E> {
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<E: core::fmt::Debug + core::fmt::Display> core::error::Error for AgentError<E> {}

/// 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<R: RegisterAccess>(regs: &mut R) -> Result<ProtCap, AgentError<R::Error>> {
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<R: RegisterAccess>(
regs: &mut R,
) -> Result<DeviceStatus, AgentError<R::Error>> {
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<R: RegisterAccess>(
regs: &mut R,
) -> Result<(RecoveryState, ImageIndex), AgentError<R::Error>> {
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<R: RegisterAccess, T>(
regs: &mut R,
command: RecoveryCommand,
parse: impl FnOnce(&[u8]) -> Option<T>,
) -> Result<T, AgentError<R::Error>> {
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<T>(
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::<BusFault>::Malformed(RecoveryCommand::ProtCap);
assert_eq!(malformed.to_string(), "ProtCap response is malformed");
}
}
86 changes: 86 additions & 0 deletions services/ocp-recovery/agent/src/script.rs
Original file line number Diff line number Diff line change
@@ -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<u8>),
/// 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<Expect>,
}

impl ScriptedDevice {
pub fn new(expected: impl IntoIterator<Item = Expect>) -> 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<T>(
&mut self,
command: RecoveryCommand,
parse: impl FnOnce(&[u8]) -> T,
) -> Result<T, BusFault> {
match self.next(command) {
Expect::Read(_, response) => Ok(parse(&response)),
Expect::Fault(_) => Err(BusFault),
}
}
}
Loading