From 3e2978be0f7cba36c0d589b48effa34946992257 Mon Sep 17 00:00:00 2001 From: Christina Quast Date: Fri, 27 Nov 2026 21:21:33 +0100 Subject: [PATCH] services: Add the HW_STATUS and indirect FIFO layouts IndirectFifoStatus::space_remaining_bytes and occupancy_bytes follow the FIFO formulas of OCP Recovery 1.2, in which the FIFO keeps 1 entry free. IndirectFifoStatus::advance_indices wraps both indices at the FIFO size, as the Caliptra i3c-core does, so the write index the device reports equals the index a Recovery Agent computes when it counts modulo the FIFO size. HwStatus::default reports CompositeTemperature::Unavailable, because a temperature byte of 0 reads as 0 degrees Celsius. Signed-off-by: Christina Quast Assisted-by: Claude Fable 5.2 --- services/ocp-recovery/api/src/regs.rs | 15 +- services/ocp-recovery/api/src/regs/fifo.rs | 958 ++++++++++++++++++ .../ocp-recovery/api/src/regs/hw_status.rs | 427 ++++++++ 3 files changed, 1395 insertions(+), 5 deletions(-) create mode 100644 services/ocp-recovery/api/src/regs/fifo.rs create mode 100644 services/ocp-recovery/api/src/regs/hw_status.rs diff --git a/services/ocp-recovery/api/src/regs.rs b/services/ocp-recovery/api/src/regs.rs index a4dbe73e6..037bbe791 100644 --- a/services/ocp-recovery/api/src/regs.rs +++ b/services/ocp-recovery/api/src/regs.rs @@ -8,20 +8,25 @@ //! whose values the spec lists holds its enum, so the field holds only the //! listed values. //! -//! The spec marks the activation field of `RECOVERY_CTRL` and the reset -//! control field of `DEVICE_RESET` "Write 1, Device Clears". The Recovery -//! Agent writes the command value and the device zeroes the field once it -//! has acted, so each of these registers has an `apply_agent_write` that -//! takes the write and a `clear_*` the device calls afterwards. +//! The spec marks the activation field of `RECOVERY_CTRL`, the reset control +//! field of `DEVICE_RESET` and the reset field of `INDIRECT_FIFO_CTRL` +//! "Write 1, Device Clears". The Recovery Agent writes the command value and +//! the device zeroes the field once it has acted, so each of these registers +//! has an `apply_agent_write` that takes the write and a `clear_*` the device +//! calls afterwards. mod device_reset; mod device_status; +mod fifo; +mod hw_status; mod prot_cap; mod recovery_ctrl; mod recovery_status; pub use device_reset::*; pub use device_status::*; +pub use fifo::*; +pub use hw_status::*; pub use prot_cap::*; pub use recovery_ctrl::*; pub use recovery_status::*; diff --git a/services/ocp-recovery/api/src/regs/fifo.rs b/services/ocp-recovery/api/src/regs/fifo.rs new file mode 100644 index 000000000..da3e0a485 --- /dev/null +++ b/services/ocp-recovery/api/src/regs/fifo.rs @@ -0,0 +1,958 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +//! `INDIRECT_FIFO_CTRL` and `INDIRECT_FIFO_STATUS`, the FIFO the Recovery +//! Agent pushes an image through. +//! +//! The registers count sizes and indices in entries of [`FIFO_ENTRY_BYTES`] +//! bytes. [`FifoEntries`] holds an entry count, and byte counts are `u64`, +//! the smallest type that holds `u32::MAX` entries as a byte count. +//! +//! Both registers on the wire, with the struct field that holds each part. +//! Multi-byte fields are little endian. The `offset_of!` asserts below the +//! structs check the byte numbers. +//! +//! ```text +//! INDIRECT_FIFO_CTRL (IndirectFifoCtrl) +//! +----------------------+ +//! byte 0 | cms | ComponentMemorySpace +//! +----------------------+ +//! byte 1 | reset | FifoReset: Idle or Reset +//! +----------------------+ +//! 2 to 5 | image_size_entries | image size in entries +//! +----------------------+ +//! +//! INDIRECT_FIFO_STATUS (IndirectFifoStatus) +//! +----------------------+ +//! byte 0 | status | FifoStatusBits: bit 0 EMPTY, +//! | | bit 1 FULL, bits 2 to 7 reserved +//! +----------------------+ +//! byte 1 | region_type | FifoRegionType +//! +----------------------+ +//! 2 to 3 | reserved | +//! +----------------------+ +//! 4 to 7 | write_index | in entries +//! +----------------------+ +//! 8 to 11 | read_index | in entries +//! +----------------------+ +//! 12 to 15 | fifo_size_entries | FifoSize +//! +----------------------+ +//! 16 to 19 | max_transfer_entries | MaxTransfer +//! +----------------------+ +//! ``` + +use core::mem::offset_of; + +use zerocopy::little_endian::{U16, U32}; +use zerocopy::{Immutable, IntoBytes, KnownLayout, TryFromBytes}; + +use super::{decode_field, sized_write, struct_matches_command_table, ComponentMemorySpace}; +use crate::command::{Access, RecoveryCommand}; +use crate::error::WireError; + +// ============================================================================ +// Entry counts, shared by both registers +// ============================================================================ + +/// Bytes in 1 FIFO entry, the "4B unit" of section 9.2. +pub const FIFO_ENTRY_BYTES: u64 = 4; + +/// A count of FIFO entries. The FIFO registers count in entries, not in +/// bytes, so a separate type keeps an entry count from passing as a byte +/// count. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FifoEntries(u32); + +impl FifoEntries { + /// Builds a count from a number of entries, for the FIFO size and the + /// max transfer size the device reports in `INDIRECT_FIFO_STATUS`. + pub const fn new(entries: u32) -> Self { + Self(entries) + } + + /// Turns the length of an image in bytes into the entry count the + /// Recovery Agent writes to `INDIRECT_FIFO_CTRL`. The last entry of an + /// image whose length does not divide by [`FIFO_ENTRY_BYTES`] holds fewer + /// bytes, so the count rounds up. Returns `None` if the count does not + /// fit the 32-bit register field. + pub const fn from_bytes_rounded_up(bytes: u64) -> Option { + let entries = bytes.div_ceil(FIFO_ENTRY_BYTES); + if entries > u32::MAX as u64 { + return None; + } + Some(Self(entries as u32)) + } + + /// The entry count as a number, for writing it to a 32-bit register + /// field. + pub const fn get(self) -> u32 { + self.0 + } + + /// The count in bytes, for code that works with byte lengths, such as + /// the FIFO formulas and the size of 1 transfer. `u32::MAX` entries + /// times `FIFO_ENTRY_BYTES` fits a `u64`. + pub const fn bytes(self) -> u64 { + self.0 as u64 * FIFO_ENTRY_BYTES + } +} + +/// The FIFO size field of `INDIRECT_FIFO_STATUS`. `FifoSize` and +/// [`MaxTransfer`] are separate types, so a `code_region` call that swaps +/// the 2 arguments fails to compile. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FifoSize { + /// The FIFO size in entries. + pub entries: FifoEntries, +} + +/// The max transfer size field of `INDIRECT_FIFO_STATUS`, the largest +/// payload 1 `INDIRECT_FIFO_DATA` access may carry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MaxTransfer { + /// The max transfer size in entries. + pub entries: FifoEntries, +} + +// `FifoEntries::from_bytes_rounded_up` rounds a partial entry up, keeps a +// whole entry, accepts `u32::MAX` whole entries and refuses 1 byte more. +// `FifoEntries::bytes` turns `u32::MAX` entries back into the byte count +// without an overflow. +const _: () = { + const fn entries(bytes: u64) -> u32 { + match FifoEntries::from_bytes_rounded_up(bytes) { + Some(rounded) => rounded.get(), + None => panic!("the byte count needs more than u32::MAX entries"), + } + } + assert!(entries(0) == 0); + assert!(entries(FIFO_ENTRY_BYTES) == 1); + assert!(entries(FIFO_ENTRY_BYTES + 1) == 2); + let largest = u32::MAX as u64 * FIFO_ENTRY_BYTES; + assert!(entries(largest) == u32::MAX); + assert!(FifoEntries::from_bytes_rounded_up(largest + 1).is_none()); + assert!(FifoEntries::new(u32::MAX).bytes() == 0x3_ffff_fffc); +}; + +// ============================================================================ +// INDIRECT_FIFO_CTRL +// ============================================================================ + +/// The values of the `INDIRECT_FIFO_CTRL` reset byte. +#[derive( + Debug, Clone, Copy, PartialEq, Eq, Default, TryFromBytes, IntoBytes, Immutable, KnownLayout, +)] +#[repr(u8)] +pub enum FifoReset { + /// No reset is in flight. + #[default] + Idle = 0x0, + /// The Recovery Agent requests a reset of the FIFO indices. + Reset = 0x1, +} + +/// `INDIRECT_FIFO_CTRL`, which selects the FIFO region and sizes the image. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, TryFromBytes, IntoBytes, Immutable, KnownLayout)] +pub struct IndirectFifoCtrl { + cms: ComponentMemorySpace, + reset: FifoReset, + image_size_entries: U32, +} + +/// Field reads that the device and the Recovery Agent both use. +impl IndirectFifoCtrl { + /// Encoded size in bytes. + pub const SIZE: usize = core::mem::size_of::(); + + /// The component memory space the Recovery Agent selected. + pub fn cms(&self) -> ComponentMemorySpace { + self.cms + } + + /// Whether the Recovery Agent requested a reset the device has not + /// performed. + pub fn reset_requested(&self) -> bool { + self.reset == FifoReset::Reset + } + + /// The size of the image the Recovery Agent announced. + pub fn image_size(&self) -> FifoEntries { + FifoEntries(self.image_size_entries.get()) + } +} + +/// Operations only the device performs. +impl IndirectFifoCtrl { + /// Returns a write off the wire as the array + /// [`Self::apply_agent_write`] takes, or [`WireError::LengthMismatch`]. + pub fn from_wire(bytes: &[u8]) -> Result<&[u8; Self::SIZE], WireError> { + sized_write(RecoveryCommand::IndirectFifoCtrl, bytes) + } + + /// Stores a write from the Recovery Agent. + /// + /// The reset byte holds the FIFO reset the Recovery Agent requests, and + /// the device clears the reset byte with `clear_reset` when it resets the + /// FIFO. The device starts a FIFO reset only on the reset request in the + /// reset byte, because a reset the device started without the request + /// would zero the indices while the Recovery Agent pushes the next image. + /// + /// `apply_agent_write` decodes every byte before it stores any, so a + /// refused write stores no byte. + pub fn apply_agent_write(&mut self, bytes: &[u8; Self::SIZE]) -> Result<(), WireError> { + let command = RecoveryCommand::IndirectFifoCtrl; + let image_size_at = offset_of!(Self, image_size_entries); + *self = Self { + cms: ComponentMemorySpace::new(bytes[offset_of!(Self, cms)]), + reset: decode_field(command, bytes, offset_of!(Self, reset))?, + image_size_entries: U32::from_bytes(core::array::from_fn(|i| bytes[image_size_at + i])), + }; + Ok(()) + } + + /// Writes [`FifoReset::Idle`] to the reset byte after the device reset the + /// FIFO indices. + pub fn clear_reset(&mut self) { + self.reset = FifoReset::Idle; + } +} + +/// Operations only the Recovery Agent performs. +impl IndirectFifoCtrl { + /// The bytes a Recovery Agent writes to select a FIFO region, request a + /// reset and announce the image size. The caller builds `image_size` + /// from the image length with [`FifoEntries::from_bytes_rounded_up`]. + pub fn agent_write( + cms: ComponentMemorySpace, + reset: FifoReset, + image_size: FifoEntries, + ) -> [u8; Self::SIZE] { + zerocopy::transmute!(Self { + cms, + reset, + image_size_entries: U32::new(image_size.get()), + }) + } +} + +// `IndirectFifoCtrl` has the length the command table gives +// `INDIRECT_FIFO_CTRL`, and the command table lets the Recovery Agent write the +// register. +const _: () = assert!(struct_matches_command_table::( + RecoveryCommand::IndirectFifoCtrl +)); +const _: () = assert!(matches!( + RecoveryCommand::IndirectFifoCtrl.access(), + Access::ReadWrite +)); + +// The byte numbers of section 9.2 are the truth for the field order. +const _: () = { + assert!(offset_of!(IndirectFifoCtrl, reset) == 1); + assert!(offset_of!(IndirectFifoCtrl, image_size_entries) == 2); +}; + +// ============================================================================ +// INDIRECT_FIFO_STATUS +// ============================================================================ + +bitflags::bitflags! { + /// The bits of the `INDIRECT_FIFO_STATUS` status byte. + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub struct FifoStatusBits: u8 { + /// The FIFO is empty. + const EMPTY = 1 << 0; + /// The FIFO is full. + const FULL = 1 << 1; + } +} + +/// The region types of the `INDIRECT_FIFO_STATUS` region type byte. +/// +/// `INDIRECT_STATUS` gives the [`Self::VendorReadOnly`] code the meaning +/// read/write and adds a read-only code that `INDIRECT_FIFO_STATUS` does not +/// list, so `FifoRegionType` decodes only the `INDIRECT_FIFO_STATUS` region +/// type byte. +#[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromBytes, IntoBytes, Immutable, KnownLayout)] +#[repr(u8)] +pub enum FifoRegionType { + /// Code space the Recovery Agent writes the recovery image into. + Code = 0b000, + /// A log in the debug format, which the Recovery Agent reads. + Log = 0b001, + /// A vendor-defined region the Recovery Agent writes. + VendorWriteOnly = 0b100, + /// A vendor-defined region the Recovery Agent reads. + VendorReadOnly = 0b101, + /// The address space is out of range. + Unsupported = 0b111, +} + +/// `INDIRECT_FIFO_STATUS`, the FIFO indices and sizes. +/// +/// The indices count entries. For the write-only code region the Recovery +/// Agent advances the write index and the device advances the read index. +#[repr(C)] +#[derive(Debug, Clone, Copy, TryFromBytes, IntoBytes, Immutable, KnownLayout)] +pub struct IndirectFifoStatus { + status: u8, + region_type: FifoRegionType, + reserved: U16, + write_index: U32, + read_index: U32, + fifo_size_entries: U32, + max_transfer_entries: U32, +} + +/// Holds the write index and the read index, each wrapped at the FIFO size, +/// which is above 0. Each field counts entries. +struct WrappedIndices { + write: u64, + read: u64, + size: u64, +} + +/// Field reads that the device and the Recovery Agent both use. +impl IndirectFifoStatus { + /// Encoded size in bytes. + pub const SIZE: usize = core::mem::size_of::(); + + /// How many entries the FIFO keeps free, so that a full FIFO and an + /// empty FIFO show different indices (section 8.2.5). + pub const RESERVED_ENTRIES: u32 = 1; + + /// The bits of the status byte. + pub fn status(&self) -> FifoStatusBits { + FifoStatusBits::from_bits_retain(self.status) + } + + /// The region type. + pub fn region_type(&self) -> FifoRegionType { + self.region_type + } + + /// The write index in entries. + pub const fn write_index(&self) -> u32 { + self.write_index.get() + } + + /// The read index in entries. + pub const fn read_index(&self) -> u32 { + self.read_index.get() + } + + /// The FIFO size. + pub const fn fifo_size(&self) -> FifoSize { + FifoSize { + entries: FifoEntries::new(self.fifo_size_entries.get()), + } + } + + /// The max transfer size. + pub const fn max_transfer(&self) -> MaxTransfer { + MaxTransfer { + entries: FifoEntries::new(self.max_transfer_entries.get()), + } + } + + /// The usable capacity of the FIFO in bytes (section 8.2.5): the FIFO + /// size minus [`Self::RESERVED_ENTRIES`]. + pub const fn usable_capacity_bytes(&self) -> u64 { + let usable = self + .fifo_size_entries + .get() + .saturating_sub(Self::RESERVED_ENTRIES); + FifoEntries(usable).bytes() + } + + /// FIFO Space Remaining of section 8.2.5, in bytes: + /// (Read Index - (Write Index + 1) + FIFO Size) % FIFO Size entries, where + /// the 1 is [`Self::RESERVED_ENTRIES`]. + /// `space_remaining_bytes` returns 0 for a FIFO size of 0. + pub const fn space_remaining_bytes(&self) -> u64 { + let Some(WrappedIndices { write, read, size }) = self.wrapped_indices() else { + return 0; + }; + (read + size - (write + Self::RESERVED_ENTRIES as u64) % size) % size * FIFO_ENTRY_BYTES + } + + /// FIFO Occupancy of section 8.2.5, in bytes: + /// (Write Index - Read Index + FIFO Size) % FIFO Size entries. + /// `occupancy_bytes` returns 0 for a FIFO size of 0. + pub const fn occupancy_bytes(&self) -> u64 { + let Some(WrappedIndices { write, read, size }) = self.wrapped_indices() else { + return 0; + }; + (write + size - read) % size * FIFO_ENTRY_BYTES + } + + /// Both indices wrapped at the FIFO size, or `None` for a FIFO size of + /// 0. The wrap keeps each subtraction in the formulas of section + /// 8.2.5 at 0 or above. + const fn wrapped_indices(&self) -> Option { + let size = self.fifo_size_entries.get() as u64; + if size == 0 { + return None; + } + Some(WrappedIndices { + write: self.write_index.get() as u64 % size, + read: self.read_index.get() as u64 % size, + size, + }) + } +} + +/// Operations only the device performs. +impl IndirectFifoStatus { + /// Describes the code region the Recovery Agent pushes an image into, or + /// returns `None` for sizes `code_region` refuses. A caller with constant + /// sizes can unwrap the result in a `const` item, so a refused pair fails + /// the build. + /// + /// Section 9.2 recommends a FIFO size bigger than the max transfer size, + /// and `code_region` requires a max transfer size of at most + /// [`Self::usable_capacity_bytes`], because the device NACKs a transfer + /// that does not fit in the FIFO (section 8.2.5). A max transfer size of + /// 0 lets the Recovery Agent push no byte, so `code_region` refuses it + /// too. + pub const fn code_region(fifo_size: FifoSize, max_transfer: MaxTransfer) -> Option { + let mut region = Self { + status: FifoStatusBits::empty().bits(), + region_type: FifoRegionType::Code, + reserved: U16::ZERO, + write_index: U32::ZERO, + read_index: U32::ZERO, + fifo_size_entries: U32::new(fifo_size.entries.get()), + max_transfer_entries: U32::new(max_transfer.entries.get()), + }; + let max_transfer = max_transfer.entries.bytes(); + if max_transfer == 0 || max_transfer > region.usable_capacity_bytes() { + return None; + } + region.update_status(); + Some(region) + } + + /// The status the device serves while the CMS index in + /// `INDIRECT_FIFO_CTRL` does not support the access type. Section 8.2.5 + /// requires [`FifoRegionType::Unsupported`] for that CMS index. + /// + /// Both sizes are 0, so the status byte reads `EMPTY` and `FULL`, and a + /// Recovery Agent that checks `FULL` before a write does not write. + pub const fn unsupported_region() -> Self { + let mut region = Self { + status: FifoStatusBits::empty().bits(), + region_type: FifoRegionType::Unsupported, + reserved: U16::ZERO, + write_index: U32::ZERO, + read_index: U32::ZERO, + fifo_size_entries: U32::ZERO, + max_transfer_entries: U32::ZERO, + }; + region.update_status(); + region + } + + /// The device calls `reset_indices` after the Recovery Agent requests a + /// reset in the `INDIRECT_FIFO_CTRL` reset byte. + pub fn reset_indices(&mut self) { + self.write_index = U32::ZERO; + self.read_index = U32::ZERO; + self.update_status(); + } + + /// Advances the write index by 1 `INDIRECT_FIFO_DATA` transfer of + /// `transfer_bytes` bytes and sets the read index to the new write index. + /// + /// The device drains each transfer before it answers, so both indices + /// advance together and the FIFO reports empty again. The indices count + /// entries and the device rounds a shorter transfer up to the next entry, + /// which covers the last chunk of an image whose size does not divide by + /// [`FIFO_ENTRY_BYTES`]. Both indices wrap at the FIFO size, as the + /// indices of the Caliptra i3c-core do. A Recovery Agent that counts the + /// write index modulo the FIFO size reads the same value in + /// `INDIRECT_FIFO_STATUS`. + /// + /// `advance_indices` accepts any `transfer_bytes` and wraps the new index + /// at the FIFO size. After a transfer of exactly the FIFO size, both + /// indices hold the values they held before. With a FIFO size of 0, + /// `advance_indices` sets both indices to 0. + pub fn advance_indices(&mut self, transfer_bytes: u64) { + let entries = transfer_bytes.div_ceil(FIFO_ENTRY_BYTES); + let next = match self.wrapped_indices() { + Some(WrappedIndices { write, size, .. }) => (write + entries % size) % size, + None => 0, + }; + // `next` is 0 or below the FIFO size, so `next` fits a `u32`. + let next = U32::new(next as u32); + self.write_index = next; + self.read_index = next; + self.update_status(); + } + + /// Sets the status byte from the indices: `EMPTY` when the FIFO + /// Occupancy is 0 and `FULL` when the FIFO Space Remaining is 0 (section + /// 9.2). + const fn update_status(&mut self) { + let mut bits = FifoStatusBits::empty(); + if self.occupancy_bytes() == 0 { + bits = bits.union(FifoStatusBits::EMPTY); + } + if self.space_remaining_bytes() == 0 { + bits = bits.union(FifoStatusBits::FULL); + } + self.status = bits.bits(); + } +} + +// `IndirectFifoStatus` has the length the command table gives +// `INDIRECT_FIFO_STATUS`, and the command table makes the register read-only to +// the Recovery Agent, so `IndirectFifoStatus` has no `apply_agent_write`. +const _: () = assert!(struct_matches_command_table::( + RecoveryCommand::IndirectFifoStatus +)); +const _: () = assert!(matches!( + RecoveryCommand::IndirectFifoStatus.access(), + Access::ReadOnly +)); + +// The byte numbers of section 9.2 are the truth for the field order. +const _: () = { + assert!(offset_of!(IndirectFifoStatus, region_type) == 1); + assert!(offset_of!(IndirectFifoStatus, write_index) == 4); + assert!(offset_of!(IndirectFifoStatus, read_index) == 8); + assert!(offset_of!(IndirectFifoStatus, fifo_size_entries) == 12); + assert!(offset_of!(IndirectFifoStatus, max_transfer_entries) == 16); +}; + +// The size pairs `code_region` refuses, and the nearest pairs it accepts. +const _: () = { + const fn region(fifo_size: u32, max_transfer: u32) -> Option { + IndirectFifoStatus::code_region( + FifoSize { + entries: FifoEntries::new(fifo_size), + }, + MaxTransfer { + entries: FifoEntries::new(max_transfer), + }, + ) + } + // The FIFO size of the pairs that check the max transfer size. Any size + // with more than `RESERVED_ENTRIES` entries works. + const CHECKED_FIFO: u32 = 64; + let reserved = IndirectFifoStatus::RESERVED_ENTRIES; + // A max transfer size above the usable capacity, which is + // `RESERVED_ENTRIES` below the FIFO size. + assert!(region(CHECKED_FIFO, CHECKED_FIFO).is_none()); + assert!(region(CHECKED_FIFO, CHECKED_FIFO - reserved).is_some()); + // A FIFO that takes no transfer. A FIFO of `RESERVED_ENTRIES` entries + // reserves each entry it has, so its usable capacity is 0. The smallest + // FIFO `code_region` accepts has 1 entry more. + assert!(region(0, 0).is_none()); + assert!(region(CHECKED_FIFO, 0).is_none()); + assert!(region(reserved, 0).is_none()); + assert!(region(reserved, reserved).is_none()); + assert!(region(reserved + 1, 1).is_some()); +}; + +#[cfg(test)] +mod tests { + use core::mem::size_of; + + use super::*; + use crate::regs::assert_write_refused; + + /// A CMS index other than the default, so a test can tell a stored CMS + /// byte from the default. + const IMAGE_CMS: ComponentMemorySpace = ComponentMemorySpace::new(0x5a); + + /// A second CMS index, different from both the default and + /// [`IMAGE_CMS`]. + const OTHER_CMS: ComponentMemorySpace = ComponentMemorySpace::new(0x11); + + /// An image size whose 4 bytes all differ, so a swapped byte order shows. + const IMAGE_SIZE: FifoEntries = FifoEntries::new(0x0102_0304); + + /// A second image size, different from [`IMAGE_SIZE`]. + const OTHER_IMAGE_SIZE: FifoEntries = FifoEntries::new(0x200); + + /// The value above [`FifoReset::Reset`], which the spec does not define + /// for the reset byte. + const UNDEFINED_FIFO_RESET: u8 = FifoReset::Reset as u8 + 1; + + /// `SMBUS_MAX_DATA_PAYLOAD` bytes in entries, the most data 1 SMBus + /// write carries. + const SMBUS_MAX_TRANSFER: FifoEntries = + FifoEntries::new((crate::SMBUS_MAX_DATA_PAYLOAD as u64 / FIFO_ENTRY_BYTES) as u32); + + // The division drops the remainder of a payload that does not divide by + // `FIFO_ENTRY_BYTES`, so the assert checks that no byte goes missing. + const _: () = assert!(SMBUS_MAX_TRANSFER.bytes() == crate::SMBUS_MAX_DATA_PAYLOAD as u64); + + /// The FIFO size whose usable capacity holds exactly + /// [`SMBUS_MAX_TRANSFER`]. + const FIFO_SIZE: FifoEntries = + FifoEntries::new(SMBUS_MAX_TRANSFER.get() + IndirectFifoStatus::RESERVED_ENTRIES); + + /// The FIFO size of the rows in + /// `the_fifo_formulas_give_occupancy_and_space_remaining`, small enough to + /// compute each row by hand. + const FORMULA_FIFO: u32 = 8; + + /// A FIFO size small enough that the transfers of + /// `a_transfer_wraps_both_indices_at_the_fifo_size` wrap the indices. + const WRAP_FIFO: u32 = 4; + + /// `INDIRECT_FIFO_STATUS` bytes with the given indices and FIFO size, in + /// entries, read back through `try_read_from_bytes`. + fn parsed(write: u32, read: u32, size: u32) -> IndirectFifoStatus { + let mut bytes = [0u8; IndirectFifoStatus::SIZE]; + for (offset, value) in [ + (offset_of!(IndirectFifoStatus, write_index), write), + (offset_of!(IndirectFifoStatus, read_index), read), + (offset_of!(IndirectFifoStatus, fifo_size_entries), size), + ] { + bytes[offset..][..size_of::()].copy_from_slice(&value.to_le_bytes()); + } + IndirectFifoStatus::try_read_from_bytes(&bytes).unwrap() + } + + /// The little-endian `u32` at `offset` of `bytes`. + fn le_u32_at(bytes: &[u8], offset: usize) -> u32 { + u32::from_le_bytes(bytes[offset..][..size_of::()].try_into().unwrap()) + } + + fn indices(region: &IndirectFifoStatus) -> (u32, u32) { + (region.write_index(), region.read_index()) + } + + fn code_region_of(fifo_size: FifoEntries, max_transfer: FifoEntries) -> IndirectFifoStatus { + IndirectFifoStatus::code_region( + FifoSize { entries: fifo_size }, + MaxTransfer { + entries: max_transfer, + }, + ) + .unwrap() + } + + #[test] + fn fifo_ctrl_bytes_match_the_fields_both_ways() { + let mut wire = [0u8; IndirectFifoCtrl::SIZE]; + wire[offset_of!(IndirectFifoCtrl, cms)] = IMAGE_CMS.get(); + wire[offset_of!(IndirectFifoCtrl, reset)] = FifoReset::Reset as u8; + wire[offset_of!(IndirectFifoCtrl, image_size_entries)..] + .copy_from_slice(&IMAGE_SIZE.get().to_le_bytes()); + + let mut ctrl = IndirectFifoCtrl::default(); + ctrl.apply_agent_write(IndirectFifoCtrl::from_wire(&wire).unwrap()) + .unwrap(); + assert_eq!(ctrl.cms(), IMAGE_CMS); + assert!(ctrl.reset_requested()); + assert_eq!(ctrl.image_size(), IMAGE_SIZE); + assert_eq!(ctrl.as_bytes(), wire); + let written = IndirectFifoCtrl::agent_write(IMAGE_CMS, FifoReset::Reset, IMAGE_SIZE); + assert_eq!(written, wire); + + ctrl.clear_reset(); + wire[offset_of!(IndirectFifoCtrl, reset)] = FifoReset::Idle as u8; + assert_eq!(ctrl.as_bytes(), wire); + } + + #[test] + fn fifo_ctrl_from_wire_refuses_1_byte_short_and_1_byte_long() { + for len in [IndirectFifoCtrl::SIZE - 1, IndirectFifoCtrl::SIZE + 1] { + let wire = [0u8; IndirectFifoCtrl::SIZE + 1]; + assert_eq!( + IndirectFifoCtrl::from_wire(&wire[..len]), + Err(WireError::LengthMismatch { + command: RecoveryCommand::IndirectFifoCtrl, + got: len, + }) + ); + } + } + + #[test] + fn a_refused_fifo_ctrl_write_keeps_the_earlier_fields() { + let mut ctrl = IndirectFifoCtrl::default(); + let earlier = IndirectFifoCtrl::agent_write(IMAGE_CMS, FifoReset::Reset, IMAGE_SIZE); + ctrl.apply_agent_write(&earlier).unwrap(); + + // `OTHER_CMS` and `OTHER_IMAGE_SIZE` differ from the stored fields, so + // `assert_write_refused` panics on a partial store. + assert_write_refused( + &mut ctrl, + IndirectFifoCtrl::apply_agent_write, + RecoveryCommand::IndirectFifoCtrl, + IndirectFifoCtrl::agent_write(OTHER_CMS, FifoReset::Idle, OTHER_IMAGE_SIZE), + offset_of!(IndirectFifoCtrl, reset), + UNDEFINED_FIFO_RESET, + ); + } + + #[test] + fn a_later_write_replaces_a_pending_fifo_reset_request() { + let mut ctrl = IndirectFifoCtrl::default(); + ctrl.apply_agent_write(&IndirectFifoCtrl::agent_write( + ComponentMemorySpace::default(), + FifoReset::Reset, + IMAGE_SIZE, + )) + .unwrap(); + + // The Recovery Agent writes again before the device resets the FIFO. + let later = IndirectFifoCtrl::agent_write(IMAGE_CMS, FifoReset::Idle, OTHER_IMAGE_SIZE); + ctrl.apply_agent_write(&later).unwrap(); + assert_eq!(ctrl.as_bytes(), later); + } + + #[test] + fn fifo_ctrl_reset_byte_accepts_only_idle_and_reset() { + let mut ctrl = IndirectFifoCtrl::default(); + let mut write = [0u8; IndirectFifoCtrl::SIZE]; + for value in 0..=u8::MAX { + write[offset_of!(IndirectFifoCtrl, reset)] = value; + let accepted = ctrl.apply_agent_write(&write).is_ok(); + // Section 9.2 values, stated again to pin `FifoReset`: idle and + // reset. + assert_eq!(accepted, value <= 0x1, "reset byte = {value:#x}"); + if accepted { + assert_eq!( + ctrl.reset_requested(), + value == 0x1, + "reset byte = {value:#x}" + ); + } + } + } + + #[test] + fn fifo_status_fields_hold_entries() { + let region = code_region_of(FIFO_SIZE, SMBUS_MAX_TRANSFER); + let bytes = region.as_bytes(); + assert_eq!( + bytes[offset_of!(IndirectFifoStatus, status)], + // Section 9.2 value, stated again to pin `FifoStatusBits::EMPTY`. + 0b01 + ); + assert_eq!( + bytes[offset_of!(IndirectFifoStatus, region_type)], + FifoRegionType::Code as u8 + ); + let reserved = + offset_of!(IndirectFifoStatus, reserved)..offset_of!(IndirectFifoStatus, write_index); + assert!(bytes[reserved].iter().all(|byte| *byte == 0)); + assert_eq!( + le_u32_at(bytes, offset_of!(IndirectFifoStatus, write_index)), + 0 + ); + assert_eq!( + le_u32_at(bytes, offset_of!(IndirectFifoStatus, read_index)), + 0 + ); + assert_eq!( + le_u32_at(bytes, offset_of!(IndirectFifoStatus, fifo_size_entries)), + FIFO_SIZE.get() + ); + assert_eq!( + le_u32_at(bytes, offset_of!(IndirectFifoStatus, max_transfer_entries)), + SMBUS_MAX_TRANSFER.get() + ); + } + + #[test] + fn fifo_status_getters_read_the_index_and_size_fields() { + // 3 different values, so a getter that reads the wrong field shows. + let (write, read, size) = (3, 5, 8); + let region = parsed(write, read, size); + assert_eq!(region.write_index(), write); + assert_eq!(region.read_index(), read); + assert_eq!(region.fifo_size().entries.get(), size); + } + + #[test] + fn an_unsupported_region_reads_empty_and_full() { + let region = IndirectFifoStatus::unsupported_region(); + assert_eq!( + region.status(), + FifoStatusBits::EMPTY | FifoStatusBits::FULL + ); + // Section 9.2 values, stated again to pin `FifoStatusBits::EMPTY` and + // `FifoStatusBits::FULL`: bits 0 and 1. + assert_eq!(region.status().bits(), 0b11); + assert_eq!(region.region_type(), FifoRegionType::Unsupported); + let after_region_type = offset_of!(IndirectFifoStatus, reserved); + assert!(region.as_bytes()[after_region_type..] + .iter() + .all(|byte| *byte == 0)); + } + + #[test] + fn fifo_status_region_type_byte_accepts_only_the_region_types() { + // Section 9.2 values, stated again to pin `FifoRegionType`. + let defined = [ + (0b000, FifoRegionType::Code), + (0b001, FifoRegionType::Log), + (0b100, FifoRegionType::VendorWriteOnly), + (0b101, FifoRegionType::VendorReadOnly), + (0b111, FifoRegionType::Unsupported), + ]; + let mut bytes = [0u8; IndirectFifoStatus::SIZE]; + for value in 0..=u8::MAX { + bytes[offset_of!(IndirectFifoStatus, region_type)] = value; + let region = IndirectFifoStatus::try_read_from_bytes(&bytes).ok(); + let expected = defined + .iter() + .find(|(byte, _)| *byte == value) + .map(|(_, region_type)| *region_type); + assert_eq!( + region.map(|region| region.region_type()), + expected, + "region type byte = {value:#x}" + ); + } + } + + #[test] + fn fifo_status_keeps_status_bits_the_spec_does_not_define() { + let mut bytes = [0u8; IndirectFifoStatus::SIZE]; + bytes[offset_of!(IndirectFifoStatus, status)] = u8::MAX; + let region = IndirectFifoStatus::try_read_from_bytes(&bytes).unwrap(); + assert_eq!(region.status().bits(), u8::MAX); + } + + #[test] + fn the_fifo_formulas_give_occupancy_and_space_remaining() { + // Each row: write index, read index, then occupancy and space + // remaining in entries, for a FIFO of `FORMULA_FIFO` entries. + let rows = [ + (5, 5, 0, 7), // empty + (3, 1, 2, 5), // part full + (1, 2, 7, 0), // full: 1 more entry would make write equal read + (7, 0, 7, 0), // full without a wrap + (0, 7, 1, 6), // the write index wrapped, 1 entry held + (0, 5, 3, 4), // the write index wrapped, the read index did not + (11, 1, 2, 5), // 11 % 8 is 3, the part-full row again + (0, 9, 7, 0), // 9 % 8 is 1, so the FIFO is full + ]; + for (write, read, occupancy, space) in rows { + let region = parsed(write, read, FORMULA_FIFO); + assert_eq!( + region.occupancy_bytes(), + occupancy * FIFO_ENTRY_BYTES, + "{write}, {read}" + ); + assert_eq!( + region.space_remaining_bytes(), + space * FIFO_ENTRY_BYTES, + "{write}, {read}" + ); + assert_eq!( + region.occupancy_bytes() + region.space_remaining_bytes(), + region.usable_capacity_bytes(), + "{write}, {read}" + ); + } + } + + #[test] + fn the_fifo_formulas_hold_at_the_largest_fifo_size() { + let region = parsed(u32::MAX - 1, 0, u32::MAX); + assert_eq!(region.space_remaining_bytes(), 0); + assert_eq!( + region.occupancy_bytes(), + u64::from(u32::MAX - 1) * FIFO_ENTRY_BYTES + ); + } + + #[test] + fn a_drained_fifo_stays_empty() { + let mut region = code_region_of(FIFO_SIZE, SMBUS_MAX_TRANSFER); + // `FIFO_SIZE` is `SMBUS_MAX_TRANSFER` plus the reserved entries. + let usable = SMBUS_MAX_TRANSFER.bytes(); + assert_eq!(region.usable_capacity_bytes(), usable); + assert_eq!(region.occupancy_bytes(), 0); + assert_eq!(region.space_remaining_bytes(), usable); + + // The device drains each transfer, so the FIFO stays empty, also after + // the indices wrap at the FIFO size: `FIFO_SIZE` transfers of + // `SMBUS_MAX_TRANSFER` entries wrap the indices `SMBUS_MAX_TRANSFER` + // times. + for _ in 0..FIFO_SIZE.get() { + region.advance_indices(SMBUS_MAX_TRANSFER.bytes()); + assert_eq!(region.occupancy_bytes(), 0); + assert_eq!(region.space_remaining_bytes(), usable); + } + } + + #[test] + fn a_transfer_wraps_both_indices_at_the_fifo_size() { + let max_transfer = WRAP_FIFO - IndirectFifoStatus::RESERVED_ENTRIES; + let mut region = + code_region_of(FifoEntries::new(WRAP_FIFO), FifoEntries::new(max_transfer)); + region.advance_indices(FifoEntries::new(max_transfer).bytes()); + assert_eq!(indices(®ion), (max_transfer, max_transfer)); + + // 1 byte past a whole entry rounds up to the next entry. + let bytes = FIFO_ENTRY_BYTES + 1; + region.advance_indices(bytes); + let rounded = FifoEntries::from_bytes_rounded_up(bytes).unwrap().get(); + let wrapped = (max_transfer + rounded) % WRAP_FIFO; + assert_eq!(indices(®ion), (wrapped, wrapped)); + assert_eq!(region.occupancy_bytes(), 0); + // A transfer of exactly the FIFO size keeps both indices. + region.advance_indices(FifoEntries::new(WRAP_FIFO).bytes()); + assert_eq!(indices(®ion), (wrapped, wrapped)); + // A transfer of 0 bytes keeps both indices. + region.advance_indices(0); + assert_eq!(indices(®ion), (wrapped, wrapped)); + } + + #[test] + fn a_transfer_wraps_at_the_largest_fifo_size() { + // With a FIFO size of u32::MAX, (u32::MAX - 1) + 2 entries is + // u32::MAX + 1, which is 1 modulo u32::MAX. + let mut region = parsed(u32::MAX - 1, u32::MAX - 1, u32::MAX); + region.advance_indices(2 * FIFO_ENTRY_BYTES); + assert_eq!(indices(®ion), (1, 1)); + } + + #[test] + fn a_transfer_into_a_fifo_of_0_entries_sets_both_indices_to_0() { + // `code_region` refuses a FIFO size of 0, so the test parses bytes + // with a nonzero write index and FIFO size 0. + let mut region = parsed(3, 0, 0); + assert_eq!(region.usable_capacity_bytes(), 0); + assert_eq!(region.space_remaining_bytes(), 0); + assert_eq!(region.occupancy_bytes(), 0); + region.advance_indices(FIFO_ENTRY_BYTES); + assert_eq!(indices(®ion), (0, 0)); + } + + #[test] + fn a_transfer_into_a_fifo_of_1_entry_reports_empty_and_full() { + // `code_region` refuses a FIFO of 1 entry, so the test parses bytes + // with FIFO size 1. + let mut region = parsed(0, 0, 1); + region.advance_indices(FIFO_ENTRY_BYTES); + assert_eq!( + region.status(), + FifoStatusBits::EMPTY | FifoStatusBits::FULL + ); + } + + #[test] + fn resetting_the_fifo_zeroes_both_indices_and_keeps_the_sizes() { + let mut region = code_region_of(FIFO_SIZE, SMBUS_MAX_TRANSFER); + region.advance_indices(SMBUS_MAX_TRANSFER.bytes()); + assert_ne!(indices(®ion), (0, 0)); + region.reset_indices(); + assert_eq!(indices(®ion), (0, 0)); + assert_eq!(region.status(), FifoStatusBits::EMPTY); + assert_eq!(region.region_type(), FifoRegionType::Code); + assert_eq!(region.fifo_size().entries, FIFO_SIZE); + assert_eq!(region.max_transfer().entries, SMBUS_MAX_TRANSFER); + } +} diff --git a/services/ocp-recovery/api/src/regs/hw_status.rs b/services/ocp-recovery/api/src/regs/hw_status.rs new file mode 100644 index 000000000..79d6716ae --- /dev/null +++ b/services/ocp-recovery/api/src/regs/hw_status.rs @@ -0,0 +1,427 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +//! `HW_STATUS`, the hardware status bits, the vendor HW status byte, the +//! composite temperature and the length of the vendor-specific hardware +//! status. +//! +//! The register on the wire, with the struct field that holds each part. +//! The `offset_of!` asserts below [`HwStatus`] check the byte numbers. +//! +//! ```text +//! HW_STATUS (HwStatus) +//! +----------------------+ +//! byte 0 | hw_status | HwStatusBits: bit 0 TEMPERATURE_CRITICAL, +//! | | bit 1 SOFT_ERROR, bit 2 FATAL_ERROR, +//! | | bits 3 to 7 reserved +//! +----------------------+ +//! byte 1 | vendor_hw_status | vendor HW status, vendor-defined bits +//! +----------------------+ +//! byte 2 | composite_temp | CompositeTemperature +//! +----------------------+ +//! byte 3 | vendor_status_len | HwVendorStatusLen +//! +----------------------+ +//! byte 4 | (not in HwStatus) | vendor-specific hardware status: +//! onward | | vendor_status_len bytes, at most +//! | | HwVendorStatusLen::MAX +//! +----------------------+ +//! ``` + +use core::mem::offset_of; + +use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; + +use super::struct_matches_command_table; +use crate::command::{Access, Length, RecoveryCommand}; + +// ============================================================================ +// Field types of HW_STATUS +// ============================================================================ + +bitflags::bitflags! { + /// The bits of the `HW_STATUS` status byte. + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub struct HwStatusBits: u8 { + /// The device temperature is critical, and a reset may clear the bit. + const TEMPERATURE_CRITICAL = 1 << 0; + /// A hardware soft error, which a reset may clear. + const SOFT_ERROR = 1 << 1; + /// A hardware fatal error. + const FATAL_ERROR = 1 << 2; + } +} + +/// The composite temperature of `HW_STATUS`, which section 9.2 encodes in 1 +/// byte, in the encoding of the NVMe-MI composite temperature. +/// +/// [`CompositeTemperature::to_byte`] and +/// [`CompositeTemperature::from_byte`] convert between +/// `CompositeTemperature` and the byte. A reading in degrees Celsius is the +/// byte as an `i8`, saturated to [`CompositeTemperature::MIN_CELSIUS`] and +/// [`CompositeTemperature::MAX_CELSIUS`]. The 2 bytes above `MAX_CELSIUS` +/// encode [`CompositeTemperature::Unavailable`] and +/// [`CompositeTemperature::SensorFailure`]. Section 9.2 assigns no +/// temperature to the bytes between the `SensorFailure` byte and the +/// `MIN_CELSIUS` byte, so no `CompositeTemperature` encodes to them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CompositeTemperature { + /// A reading in degrees Celsius. [`CompositeTemperature::MAX_CELSIUS`] + /// means that temperature or higher, and + /// [`CompositeTemperature::MIN_CELSIUS`] that temperature or lower, so a + /// reading below `MIN_CELSIUS` decodes back as `MIN_CELSIUS`. A caller + /// with a wider reading saturates it to `i8` first, because `130 as i8` + /// is -126. + Celsius(i8), + /// No temperature reading, or a reading older than 5 seconds. + Unavailable, + /// The temperature sensor failed. + SensorFailure, +} + +impl CompositeTemperature { + /// Highest reading the byte holds, for 127 degrees Celsius or higher. + pub const MAX_CELSIUS: i8 = 127; + /// Lowest reading the byte holds, for -60 degrees Celsius or lower. + pub const MIN_CELSIUS: i8 = -60; + + const UNAVAILABLE_BYTE: u8 = 0x80; + const SENSOR_FAILURE_BYTE: u8 = 0x81; + + /// The byte the device writes to the temperature field. A reading + /// outside [`Self::MIN_CELSIUS`] to [`Self::MAX_CELSIUS`] saturates. + pub const fn to_byte(self) -> u8 { + match self { + Self::Celsius(celsius) => { + let clamped = if celsius < Self::MIN_CELSIUS { + Self::MIN_CELSIUS + } else { + celsius + }; + // A reading below 0 encodes as the signed byte. + clamped as u8 + } + Self::Unavailable => Self::UNAVAILABLE_BYTE, + Self::SensorFailure => Self::SENSOR_FAILURE_BYTE, + } + } + + /// The temperature a byte of the temperature field reports, or `None` + /// for a byte between the `SensorFailure` byte and the `MIN_CELSIUS` + /// byte. + pub const fn from_byte(byte: u8) -> Option { + match byte { + Self::UNAVAILABLE_BYTE => Some(Self::Unavailable), + Self::SENSOR_FAILURE_BYTE => Some(Self::SensorFailure), + // Every reading is an `i8` from `MIN_CELSIUS` up. The bytes + // without a temperature read as `i8` values below `MIN_CELSIUS`. + _ if byte as i8 >= Self::MIN_CELSIUS => Some(Self::Celsius(byte as i8)), + _ => None, + } + } +} + +// `MAX_CELSIUS` is `i8::MAX`, so `to_byte` needs no upper clamp, and the +// `Unavailable` and `SensorFailure` bytes follow the `MAX_CELSIUS` byte. +const _: () = assert!(CompositeTemperature::MAX_CELSIUS == i8::MAX); +const _: () = + assert!(CompositeTemperature::UNAVAILABLE_BYTE == CompositeTemperature::MAX_CELSIUS as u8 + 1); +const _: () = assert!( + CompositeTemperature::SENSOR_FAILURE_BYTE == CompositeTemperature::UNAVAILABLE_BYTE + 1 +); + +// Section 9.2 values, stated again to pin the encoding in both directions. +// A reading below `MIN_CELSIUS` saturates to the `MIN_CELSIUS` byte. The +// `is_none` lines pin the first and the last byte without a temperature. +const _: () = { + use CompositeTemperature as T; + assert!(T::Celsius(0).to_byte() == 0x00); + assert!(T::Celsius(-1).to_byte() == 0xff); + assert!(T::Celsius(T::MIN_CELSIUS).to_byte() == 0xc4); + assert!(T::Celsius(T::MIN_CELSIUS - 1).to_byte() == 0xc4); + assert!(T::Celsius(i8::MIN).to_byte() == 0xc4); + assert!(T::Celsius(T::MAX_CELSIUS).to_byte() == 0x7f); + assert!(T::Unavailable.to_byte() == 0x80); + assert!(T::SensorFailure.to_byte() == 0x81); + assert!(matches!(T::from_byte(0x00), Some(T::Celsius(0)))); + assert!(matches!(T::from_byte(0xff), Some(T::Celsius(-1)))); + assert!(matches!(T::from_byte(0xc4), Some(T::Celsius(-60)))); + assert!(matches!(T::from_byte(0x7f), Some(T::Celsius(127)))); + assert!(matches!(T::from_byte(0x80), Some(T::Unavailable))); + assert!(matches!(T::from_byte(0x81), Some(T::SensorFailure))); + assert!(T::from_byte(0x82).is_none()); + assert!(T::from_byte(0xc3).is_none()); +}; + +/// The length of the vendor-specific hardware status that follows +/// [`HwStatus`], bounded to the bytes the command table leaves after the +/// fixed fields. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct HwVendorStatusLen(u8); + +impl HwVendorStatusLen { + /// Longest vendor-specific hardware status: the largest minus the + /// smallest `HW_STATUS` length in the command table. The smallest length + /// equals [`HwStatus::SIZE`]. + pub const MAX: u8 = match RecoveryCommand::HwStatus.length() { + Length::Range { min, max } if max - min <= u8::MAX as usize => (max - min) as u8, + _ => panic!("HW_STATUS needs a vendor length range that fits a u8"), + }; + + /// No vendor-specific hardware status follows the fixed fields. + pub const NONE: Self = Self(0); + + /// Names a vendor-specific hardware status length, or `None` if `len` is + /// above [`Self::MAX`]. + pub const fn new(len: u8) -> Option { + if len > Self::MAX { + return None; + } + Some(Self(len)) + } + + /// The length in bytes. + pub const fn get(self) -> u8 { + self.0 + } +} + +// The asserts catch a `>=` in `HwVendorStatusLen::new`, which would refuse +// `HwVendorStatusLen::MAX`, and a missing bound, which would accept +// `HwVendorStatusLen::MAX + 1`. +const _: () = assert!(HwVendorStatusLen::new(HwVendorStatusLen::MAX + 1).is_none()); +const _: () = assert!(matches!( + HwVendorStatusLen::new(HwVendorStatusLen::MAX), + Some(len) if len.get() == HwVendorStatusLen::MAX +)); + +// ============================================================================ +// HW_STATUS +// ============================================================================ + +/// The fixed fields of `HW_STATUS`, before the vendor-specific hardware +/// status. +#[repr(C)] +#[derive(Debug, Clone, Copy, FromBytes, IntoBytes, Immutable, KnownLayout)] +pub struct HwStatus { + hw_status: u8, + vendor_hw_status: u8, + composite_temp: u8, + vendor_status_len: u8, +} + +impl Default for HwStatus { + /// No status bits, a vendor HW status byte of 0, no vendor-specific + /// hardware status and [`CompositeTemperature::Unavailable`], because a + /// temperature byte of 0 reads as 0 degrees Celsius. + fn default() -> Self { + Self { + hw_status: HwStatusBits::empty().bits(), + vendor_hw_status: 0, + composite_temp: CompositeTemperature::Unavailable.to_byte(), + vendor_status_len: HwVendorStatusLen::NONE.get(), + } + } +} + +/// Field reads that the device and the Recovery Agent both use. +impl HwStatus { + /// Encoded size in bytes. The vendor-specific hardware status follows, + /// with the length the vendor status length byte gives. + pub const SIZE: usize = core::mem::size_of::(); + + /// The bits of the status byte. `status` also returns the bits above + /// [`HwStatusBits::FATAL_ERROR`], which section 9.2 marks "Reserved", so + /// a Recovery Agent sees every bit the device sends. + pub fn status(&self) -> HwStatusBits { + HwStatusBits::from_bits_retain(self.hw_status) + } + + /// The vendor HW status byte. The vendor defines the bits. + pub fn vendor_hw_status(&self) -> u8 { + self.vendor_hw_status + } + + /// The composite temperature, or `Err` with the temperature byte when no + /// [`CompositeTemperature`] encodes to the temperature byte. + pub fn composite_temperature(&self) -> Result { + CompositeTemperature::from_byte(self.composite_temp).ok_or(self.composite_temp) + } + + /// How many bytes of vendor-specific hardware status follow the fixed + /// fields, or `Err` with the length byte when the length byte is above + /// [`HwVendorStatusLen::MAX`]. + pub fn vendor_status_len(&self) -> Result { + HwVendorStatusLen::new(self.vendor_status_len).ok_or(self.vendor_status_len) + } +} + +/// Operations only the device performs. +impl HwStatus { + /// Reports `bits` in the status byte. + pub fn set_status(&mut self, bits: HwStatusBits) { + self.hw_status = bits.bits(); + } + + /// Reports `vendor_hw_status` in the vendor HW status byte. + pub fn set_vendor_hw_status(&mut self, vendor_hw_status: u8) { + self.vendor_hw_status = vendor_hw_status; + } + + /// Reports `temperature` in the temperature byte. No + /// [`CompositeTemperature`] encodes to the bytes between the + /// `SensorFailure` byte and the `MIN_CELSIUS` byte, so the device cannot + /// write one of those bytes. + pub fn set_composite_temperature(&mut self, temperature: CompositeTemperature) { + self.composite_temp = temperature.to_byte(); + } + + /// Reports `len` in the vendor status length byte. `HwStatus` holds only + /// the fixed fields, so the device sends exactly `len` bytes of + /// vendor-specific hardware status after them. + pub fn set_vendor_status_len(&mut self, len: HwVendorStatusLen) { + self.vendor_status_len = len.get(); + } +} + +// `HwStatus` has the smallest length the command table gives `HW_STATUS`, +// because the vendor-specific hardware status follows the vendor status +// length byte. The command table makes the register read-only to the +// Recovery Agent, so `HwStatus` has no `apply_agent_write`. +const _: () = assert!(struct_matches_command_table::( + RecoveryCommand::HwStatus +)); +const _: () = assert!(matches!( + RecoveryCommand::HwStatus.access(), + Access::ReadOnly +)); + +// The byte numbers of section 9.2 are the truth for the field order. +const _: () = { + assert!(offset_of!(HwStatus, vendor_hw_status) == 1); + assert!(offset_of!(HwStatus, composite_temp) == 2); + assert!(offset_of!(HwStatus, vendor_status_len) == 3); +}; + +#[cfg(test)] +mod tests { + use super::*; + + /// A vendor HW status byte other than the default 0, so the test sees + /// `set_vendor_hw_status` change the byte. + const VENDOR_HW_STATUS: u8 = u8::MAX; + + #[test] + fn a_new_hw_status_reports_no_temperature_reading() { + let status = HwStatus::default(); + assert_eq!(status.status(), HwStatusBits::empty()); + assert_eq!(status.vendor_hw_status(), 0); + assert_eq!( + status.composite_temperature(), + Ok(CompositeTemperature::Unavailable) + ); + assert_eq!(status.vendor_status_len(), Ok(HwVendorStatusLen::NONE)); + } + + #[test] + fn hw_status_reads_keep_reserved_bits_and_decode_the_temperature() { + let mut bytes = [0u8; HwStatus::SIZE]; + bytes[offset_of!(HwStatus, hw_status)] = u8::MAX; + bytes[offset_of!(HwStatus, composite_temp)] = CompositeTemperature::SensorFailure.to_byte(); + let status = HwStatus::read_from_bytes(&bytes).unwrap(); + assert_eq!(status.status().bits(), u8::MAX); + assert!(status.status().contains(HwStatusBits::FATAL_ERROR)); + assert_eq!( + status.composite_temperature(), + Ok(CompositeTemperature::SensorFailure) + ); + } + + #[test] + fn a_vendor_status_len_above_max_reads_as_err_with_the_byte() { + let byte = HwVendorStatusLen::MAX + 1; + let mut bytes = [0u8; HwStatus::SIZE]; + bytes[offset_of!(HwStatus, vendor_status_len)] = byte; + let status = HwStatus::read_from_bytes(&bytes).unwrap(); + assert_eq!(status.vendor_status_len(), Err(byte)); + } + + #[test] + fn each_hw_status_setter_writes_only_its_byte() { + let len = HwVendorStatusLen::new(HwVendorStatusLen::MAX).unwrap(); + let bits = HwStatusBits::all(); + // 1 case per byte, so a new field without a setter case fails the + // build. + let setters: [(usize, u8, fn(&mut HwStatus)); HwStatus::SIZE] = [ + (offset_of!(HwStatus, hw_status), bits.bits(), |s| { + s.set_status(HwStatusBits::all()) + }), + ( + offset_of!(HwStatus, vendor_hw_status), + VENDOR_HW_STATUS, + |s| s.set_vendor_hw_status(VENDOR_HW_STATUS), + ), + ( + offset_of!(HwStatus, composite_temp), + CompositeTemperature::SensorFailure.to_byte(), + |s| s.set_composite_temperature(CompositeTemperature::SensorFailure), + ), + ( + offset_of!(HwStatus, vendor_status_len), + HwVendorStatusLen::MAX, + |s| { + s.set_vendor_status_len(HwVendorStatusLen::new(HwVendorStatusLen::MAX).unwrap()) + }, + ), + ]; + for (offset, value, set) in setters { + let mut status = HwStatus::default(); + let mut expected = [0u8; HwStatus::SIZE]; + expected.copy_from_slice(status.as_bytes()); + expected[offset] = value; + set(&mut status); + assert_eq!(status.as_bytes(), expected, "offset {offset}"); + } + + let mut status = HwStatus::default(); + status.set_status(bits); + status.set_vendor_hw_status(VENDOR_HW_STATUS); + status.set_composite_temperature(CompositeTemperature::SensorFailure); + status.set_vendor_status_len(len); + assert_eq!(status.status(), bits); + assert_eq!(status.vendor_hw_status(), VENDOR_HW_STATUS); + assert_eq!( + status.composite_temperature(), + Ok(CompositeTemperature::SensorFailure) + ); + assert_eq!(status.vendor_status_len(), Ok(len)); + } + + #[test] + fn every_temperature_byte_decodes_and_encodes_back_or_reads_as_none() { + // The bytes without a `CompositeTemperature` run from the byte after + // `SensorFailure` to the byte before `MIN_CELSIUS`. + let unassigned = CompositeTemperature::SensorFailure.to_byte() + 1 + ..CompositeTemperature::Celsius(CompositeTemperature::MIN_CELSIUS).to_byte(); + for byte in 0..=u8::MAX { + let decoded = CompositeTemperature::from_byte(byte); + if unassigned.contains(&byte) { + assert_eq!(decoded, None, "temperature byte = {byte:#x}"); + } else { + assert_eq!( + decoded.map(CompositeTemperature::to_byte), + Some(byte), + "temperature byte = {byte:#x}" + ); + } + } + } + + #[test] + fn a_temperature_byte_without_a_temperature_reads_as_err_with_the_byte() { + let byte = CompositeTemperature::SensorFailure.to_byte() + 1; + let mut bytes = [0u8; HwStatus::SIZE]; + bytes[offset_of!(HwStatus, composite_temp)] = byte; + let status = HwStatus::read_from_bytes(&bytes).unwrap(); + assert_eq!(status.composite_temperature(), Err(byte)); + } +}